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
3c21d06d4fdf35ef9b14158dc8e7ab0b1b558c7f
C++
greenfox-zerda-sparta/katbtr
/week-02/day-1/Exercise25.cpp
UTF-8
750
3.3125
3
[]
no_license
//============================================================================ // Name : Exercise25.cpp // Author : katbtr // Version : // Copyright : Your copyright notice // Description : Week-02 Day-1 Exercise25 //============================================================================ #include <iostream> #include <string> using namespace std; int main() { // print the even numbers till 20 cout << "while" << endl; int a = 2; while (a <= 20) { cout << a << endl; a += 2; } cout << "do+while" << endl; int b = 2; do { cout << b << endl; b += 2; } while ( b <= 20 ); cout << "for" << endl; for ( int c = 2; c <= 20; (c += 2) ) { cout << c << endl; } return 0; }
true
debd0e7882aed5d7776a35ca8b7c3b0184b26c49
C++
pratikdas44/codingPratice_cpp
/greedy & dp/coin_change.cpp
UTF-8
1,621
3.28125
3
[]
no_license
//unlimited number of coins present. //find number of ways different coins chosen such that //sum equals to m. #include <bits/stdc++.h> using namespace std; #define ll long long int ll dp(int a[],int n,int m){ ll table[m+1]; memset(table,0,sizeof(table)); table[0] = 1; for(int i=0;i<n;i++) for(int j=a[i];j<=m;j++) table[j] += table[j-a[i]]; return table[m]; } int main(){ int m,n; cin >> m >> n; //m is cost and n is size. int a[n]; for(int i=0;i<n;i++){ cin >> a[i]; } cout << dp(a,n,m); } //here permutation are also taken. //hence {1,2} different from {2,1}. int res[n+1]; res[0] = 1; res[1] = 1; for (int i=2; i<=n; i++) { res[i] = 0; for (int j=1; j<=m && j<=i; j++) res[i] += res[i-j]; //all this means fibonacci series. //res = [1,1,2,3,5] } for(int i=0;i<=n;i++) cout << res[i] << " "; return res[n]; //for string given "12" - o/p is AB and L int countDecodingDP(char *digits, int n) { int count[n+1]; // A table to store results of subproblems count[0] = 1; count[1] = 1; for (int i = 2; i <= n; i++) { count[i] = 0; // If the last digit is not 0, then last digit must add to // the number of words if (digits[i-1] > '0') count[i] = count[i-1]; // If second last digit is smaller than 2 and last digit is // smaller than 7, then last two digits form a valid character if (digits[i-2] == '1' || (digits[i-2] == '2' && digits[i-1] < '7') ) count[i] += count[i-2]; } return count[n]; }
true
259d218df76c36dc5e5e20315900e4cae0565d59
C++
betarixm/CSED451
/ASSN/ASSN4/Shader.cpp
UTF-8
3,383
2.625
3
[]
no_license
#include "Shader.h" #include <glm/gtc/type_ptr.hpp> #define NUM_SHADER 2 Shader *shader; Shader *shaders[NUM_SHADER]; bool shader_index = 0; void initShader() { shaders[0] = new Shader((char *)"shader/Shader.vert", (char *)"shader/Shader.frag"); shaders[1] = new Shader((char *)"shader/Shader_g.vert", (char *)"shader/Shader_g.frag"); shader = shaders[0]; //default = Phong shading } Shader::Shader(char *vShaderPath, char *fShaderPath) { ifstream vShaderFile, fShaderFile; stringstream vShaderStream, fShaderStream; string vShaderString, fShaderString; int vShader, fShader; vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { vShaderFile.open(vShaderPath); fShaderFile.open(fShaderPath); vShaderStream << vShaderFile.rdbuf(); fShaderStream << fShaderFile.rdbuf(); vShaderFile.close(); fShaderFile.close(); vShaderString = vShaderStream.str(); fShaderString = fShaderStream.str(); } catch(const ifstream::failure& e) { cout << "[-][Shader] File Read Failed" << endl; } const char* vShaderCode = vShaderString.c_str(); const char* fShaderCode = fShaderString.c_str(); int success; char infoLog[512]; vShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vShader, 1, &vShaderCode, NULL); glCompileShader(vShader); glGetShaderiv(vShader, GL_COMPILE_STATUS, &success); if(!success){ glGetShaderInfoLog(vShader, 512, NULL, infoLog); std::cout << "[-][Shader] Vertex Shader Compilation Failed\n" << infoLog << std::endl; } fShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fShader, 1, &fShaderCode, NULL); glCompileShader(fShader); glGetShaderiv(fShader, GL_COMPILE_STATUS, &success); if(!success){ glGetShaderInfoLog(fShader, 512, NULL, infoLog); std::cout << "[-][Shader] Fragment Shader Compilation Failed!\n" << infoLog << std::endl; }; _sid = glCreateProgram(); glAttachShader(_sid, vShader); glAttachShader(_sid, fShader); glLinkProgram(_sid); glGetProgramiv(_sid, GL_LINK_STATUS, &success); if(!success){ glGetProgramInfoLog(_sid, 512, NULL, infoLog); std::cout << "[-][Shader] Linking Failed!\n" << infoLog << std::endl; } glDeleteShader(vShader); glDeleteShader(fShader); } void Shader::use() const { glUseProgram(_sid); } void Shader::uniform4v(const string &key, float x, float y, float z, float w) const { glUniform4f(GET_UNIFORM(_sid, key.c_str()), x, y, z, w); } void Shader::uniform4m(const string &key, const glm::mat4 &value) const { glUniformMatrix4fv(GET_UNIFORM(_sid, key.c_str()), 1, GL_FALSE, glm::value_ptr(value)); } void Shader::uniform3v(const string &key, float x, float y, float z) const { glUniform3f(GET_UNIFORM(_sid, key.c_str()), x, y, z); } void Shader::uniform3v(const string &key, const glm::vec3 &value) const { glUniform3fv(GET_UNIFORM(_sid, key.c_str()), 1, glm::value_ptr(value)); } void Shader::uniform1f(const string &key, float x) const { glUniform1f(GET_UNIFORM(_sid, key.c_str()), x); } void Shader::uniform1i(const string &key, int x) const { glUniform1i(glGetUniformLocation(_sid, key.c_str()), x); }
true
9eda90aea601535d6e8670868e96832539ae3feb
C++
leoleoasd/oi
/senior/124/p193.cpp
UTF-8
1,894
2.515625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> //using namespace std; using std::cin; using std::cout; using std::vector; using std::ios; using std::endl; #define MAXN 5050 vector<int> output; int data[MAXN][MAXN]={0}; int n,m,q; struct p{ p(){} p(int x,int y,int z){ a=x; b=y; c=z; } int a,b,c; } cz[MAXN]; int father[MAXN]={0}; inline void init(){ for(int i=1;i<MAXN;++i){ father[i]=i; } } inline int getfather(int pos){ if(father[pos]==pos){ return pos; }else{ father[pos]=getfather(father[pos]); return father[pos]; } } inline void merge(int a,int b){ int fa,fb; fa = getfather(a); fb= getfather(b); if(fa==fb){ return; } if(fa>fb){ father[fa]=fb; }else{ father[fb]=fa; } } void solve(int cmd,int x,int y){ if(cmd==1){ merge(x,y); return; } if(cmd==2){ output.push_back(getfather(x)==getfather(y)); return; } int out = 0; for(int i=1;i<=n;++i){ if(getfather(i)==i)++out; } output.push_back(out); } int main(){ ios::sync_with_stdio(false); cin>>n>>m>>q; int x,y; init(); for(int i=0;i<m;++i){ cin>>x>>y; data[x][y]=data[y][x]=1; } int z; for(int i=q-1;i>=0;--i){ cin>>x; if(x==1){ cin>>y>>z; cz[i]=p(x,y,z); data[y][z]=data[z][y]=0; } if(x==2){ cin>>y>>z; cz[i]=p(x,y,z); } if(x==3){ cz[i]=p(3,0,0); } } for(int i=1;i<=n;++i) for(int j=i;j<=n;++j){ if(data[i][j])merge(i,j); } for(int i=0;i<q;++i){ solve(cz[i].a,cz[i].b,cz[i].c); } for(int i=output.size()-1;i>=0;--i){ cout<<output[i]<<endl; } return 0; }
true
0c3fd371d0a6e58ac80fe19ee7ec75f21178d0b2
C++
kenuosec/MPPT-charger
/#0 Out-of-date and other files/Charger-Software_BT_IV/Charger-Software_BT_IV.ino
UTF-8
4,258
3
3
[]
no_license
/* Name: MPPT Solar Charger with Bluetooth communication | Main software file * Author: Karol Wojsław * Date: 02/04/2021 (last release) */ #include <SoftwareSerial.h> /*Define pin allocations on Arduino board */ #define BAT_VOLT_PIN A0 #define PV_VOLT_PIN A1 #define PV_CURRENT_PIN A2 #define PWM_PIN 3 #define BT_TX_PIN 5 #define BT_RX_PIN 6 #define BUZZER_PIN 8 #define LED_PIN 9 /*Fill in values below after callibration for better performance */ #define Vin_mV 5000 //Atmega328 supply voltage in mV #define R3 4700 #define R4 1000 #define R5 4700 #define R6 1000 #define R8 12000 #define R9 9000 /*Bluetooth serial port definition */ SoftwareSerial bluetooth(BT_RX_PIN, BT_TX_PIN); // RX, TX void setup() { //Input-output pin mode definition pinMode(BAT_VOLT_PIN, INPUT); pinMode(PV_VOLT_PIN, INPUT); pinMode(PV_CURRENT_PIN, INPUT); pinMode(PWM_PIN, OUTPUT); pinMode(BT_TX_PIN, OUTPUT); pinMode(BT_RX_PIN, OUTPUT); pinMode(BUZZER_PIN, OUTPUT); pinMode(LED_PIN, OUTPUT); //Software serial and bluetooth serial ports configuration (baud rate: 9600) Serial.begin(9600); bluetooth.begin(9600); } void loop() { int BAT_voltage, PV_voltage, PV_current; //Values of measured voltages and currents in mV //Measure the average of n = 20 readings from analog pins. Total execution time: 300 ms BAT_voltage = measureAverage(BAT_VOLT_PIN, 20, R5, R6); PV_voltage = measureAverage(PV_VOLT_PIN, 20, R3, R4); PV_current = (measureAverage(PV_CURRENT_PIN, 20, 1, 0) - 2500)*10; //No voltage div, hence R1=0 & R2=1, 2.5 V nominal, then 1mV = 10 mA //Generate and send a report through Bluetooth and Serial Port generateReport(BAT_voltage, PV_voltage, PV_current, 1); //Bluetooth (bt = 1) generateReport(BAT_voltage, PV_voltage, PV_current, 0); //Serial Port (bt = 0) } /* -------------------------------------------------------------------------------------------------------------- */ /* Function that measure average of n readings from the input_pin and returns value in mV. Execution time:~5*n ms */ int measureAverage(int input_pin, int n, int V_div_R1, int V_div_R2){ int readings_avr_mV, Vin_avr_mV, readings_sum = 0; for(int i = 0; i < n; i++){ //Take n measurements readings_sum += analogRead(input_pin); //Add a 10-bit (0-1024) value read to readings_sum delay(5); //Atmega328 takes ~0.1 ms to read an analog val. Wait 5 ms between readings for better performance } readings_avr_mV = map((readings_sum / n), 0, 1024, 0, Vin_mV); Vin_avr_mV = (readings_avr_mV *(V_div_R1 + V_div_R2))/(V_div_R2); return Vin_avr_mV; //Return the average of n readings in mV } /* ---------------------------------------------------------------------------------------------- */ /* Function that send a report on the current status of the charger through bluetooth/serial port */ void generateReport(int BAT_voltage, int PV_voltage, int PV_current, bool bt){ if(bt == 1){ bluetooth.print("-----------------------------------------------\n"); bluetooth.print("MPPT Solar Charger with Bt | Current status: \nBattery voltage: "); bluetooth.print(BAT_voltage); bluetooth.print(" mV \nPhotovoltaic panel voltage: "); bluetooth.print(PV_voltage); bluetooth.print(" mV \nPhotovoltaic panel current: "); bluetooth.print(PV_current); bluetooth.print(" mA \nPower delivered by PV panel: "); bluetooth.print(PV_current * PV_voltage); bluetooth.print(" mW \nBattery SOC (state of charge) "); bluetooth.print((BAT_voltage - 11820)/13); bluetooth.print(" % of full capacity \n\n"); } else if(bt == 0){ Serial.print("-----------------------------------------------\n"); Serial.print("MPPT Solar Charger with Bt | Current status: \nBattery voltage: "); Serial.print(BAT_voltage); Serial.print(" mV \nPhotovoltaic panel voltage: "); Serial.print(PV_voltage); Serial.print(" mV \nPhotovoltaic panel current: "); Serial.print(PV_current); Serial.print(" mA \nPower delivered by PV panel: "); Serial.print(PV_current * PV_voltage); Serial.print(" mW \nBattery SOC (state of charge) "); Serial.print((BAT_voltage - 11820)/13); Serial.print(" % of full capacity \n\n"); } }
true
24c623b339e0c6deccd87b677d4673fe929264c5
C++
PaulEcoffet/roborobo3
/roborobo3/include/core/Observers/WorldObserver.h
UTF-8
1,467
2.859375
3
[]
no_license
/* * WorldObserver.h * roborobo-online * * Created by Nicolas on 20/03/09. * Copyright 2009. All rights reserved. * */ #ifndef WORLDOBSERVER_H #define WORLDOBSERVER_H #include "Observers/Observer.h" class World; class WorldObserver : public Observer { //private: protected: World *_world; public: //Initializes the variables WorldObserver( World *__world ); virtual ~WorldObserver(); virtual void reset(); /* a remark on stepPre() and stepPost(): the update ordering for one step of roborobo is N_o*object.step() => worldObserver.stepPre() => N_a*agent.step() => N*a*agent.move() => worldObserver.stepPost() ie. to observe the state of the world or modify agent state before agents move, use stepPre() to observe the state of the world or modify agent state just after agents move, use stepPost() to modify objects, it might be better to do it in stepPost() (so that object can be updated afterwards) to modify objects before the simulation starts, use init() you may use init() or stepPre() to initialize agents before simulation starts init() is called once before any object is updated stepPre() is called the first time just before the first object's updating, and then at each iteration A final note on backward compatibility: from 2017-11-29, step() is renamed stepPre() */ virtual void stepPre(); virtual void stepPost(); }; #endif
true
b9041b3ce098ff55e15b8ad5fefcd21ab80280ee
C++
whing123/C-Coding
/NewCoder/97.cpp
UTF-8
741
3.125
3
[]
no_license
/* 97 滑动窗口最大值 */ class Solution { public: vector<int> maxInWindows(const vector<int>& num, unsigned int size) { vector<int> res; if (size < 1 || num.size() < size) { return res; } deque<int> qmax; for (int i = 0; i < num.size(); ++i) { while (!qmax.empty() && num[qmax.back()] <= num[i]) { qmax.pop_back(); } qmax.push_back(i); if (qmax.front() == i - size) { qmax.pop_front(); } if (i >= size - 1) { res.push_back(num[qmax.front()]); } } return res; } };
true
d87d690be4133d47f0da6c3c0036b5b3acade605
C++
Dusting0/LeetCode
/150.逆波兰表达式求值/evalRPN.cpp
UTF-8
1,077
3.609375
4
[]
no_license
#include <iostream> #include <vector> #include <string> #include <stack> using namespace std; class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> stk; for(int i=0; i<tokens.size(); i++) { try { int num = stoi(tokens[i]); stk.push(num); } catch(std::invalid_argument) { string op = tokens[i]; int a = stk.top(); stk.pop(); int b = stk.top(); stk.pop(); int c; if(op == "+") { c = a + b; } else if(op == "-") { c = b - a; } else if(op == "*") { c = a * b; } else { c = int(b / a); } stk.push(c); } } return stk.top(); } }; int main() { Solution solu; vector<string> tokens = {"4","13","5","/","+"}; int re = solu.evalRPN(tokens); cout << re << endl; }
true
28f205d636e1cff782d7f35e211f3e02dc17a46c
C++
aminnezarat/KTT
/source/api/stop_condition/tuning_duration.h
UTF-8
2,105
2.96875
3
[ "MIT" ]
permissive
/** @file tuning_duration.h * Stop condition based on total tuning duration. */ #pragma once #include <algorithm> #include <chrono> #include <api/stop_condition/stop_condition.h> namespace ktt { /** @class TuningDuration * Class which implements stop condition based on total tuning duration. */ class TuningDuration : public StopCondition { public: /** @fn explicit TuningDuration(const double duration) * Initializes tuning duration condition. * @param duration Condition will be satisfied when specified amount of time has passed. The measurement starts when kernel tuning begins. * Duration is specified in seconds. */ explicit TuningDuration(const double duration) : passedTime(0.0) { targetTime = std::max(0.0, duration); } bool isSatisfied() const override { return passedTime > targetTime; } void initialize(const size_t totalConfigurationCount) override { totalCount = totalConfigurationCount; initialTime = std::chrono::steady_clock::now(); } void updateStatus(const bool, const std::vector<ParameterPair>&, const double, const KernelProfilingData&, const std::map<KernelId, KernelProfilingData>&) override { std::chrono::steady_clock::time_point currentTime = std::chrono::steady_clock::now(); passedTime = static_cast<double>(std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - initialTime).count()) / 1000.0; } size_t getConfigurationCount() const override { return totalCount; } std::string getStatusString() const override { if (isSatisfied()) { return std::string("Target tuning time reached: " + std::to_string(targetTime) + " seconds"); } return std::string("Current tuning time: " + std::to_string(passedTime) + " / " + std::to_string(targetTime) + " seconds"); } private: size_t totalCount; std::chrono::steady_clock::time_point initialTime; double passedTime; double targetTime; }; } // namespace ktt
true
52240cbb6badbdb485aec4aafbc27c7a9d7c8a02
C++
NoCodeBugsFree/RTS
/Source/RTS/RTS_CameraPawn.cpp
UTF-8
2,134
2.546875
3
[]
no_license
// Fill out your copyright notice in the Description page of Project Settings. #include "RTS_CameraPawn.h" #include "Components/BillboardComponent.h" #include "GameFramework/SpringArmComponent.h" #include "Camera/CameraComponent.h" #include "GameFramework/FloatingPawnMovement.h" // Sets default values ARTS_CameraPawn::ARTS_CameraPawn() { /* billboard */ ROOT = CreateDefaultSubobject<UBillboardComponent>(TEXT("ROOT")); SetRootComponent(ROOT); /** camera boom */ CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 1500.f; CameraBoom->SetRelativeRotation(FRotator(-70.f, 0.f, 0.f)); CameraBoom->bDoCollisionTest = false; /* camera component */ CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent")); CameraComponent->SetupAttachment(CameraBoom); /** floating pawn movement component */ FloatingPawnMovement = CreateDefaultSubobject<UFloatingPawnMovement>(TEXT("FloatingPawnMovement")); } // Called to bind functionality to input void ARTS_CameraPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); /** zoom */ PlayerInputComponent->BindAction("ZoomIn", IE_Pressed, this, &ARTS_CameraPawn::ZoomIn); PlayerInputComponent->BindAction("ZoomOut", IE_Pressed, this, &ARTS_CameraPawn::ZoomOut); /** movement */ PlayerInputComponent->BindAxis("MoveForward", this, &ARTS_CameraPawn::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &ARTS_CameraPawn::MoveRight); } void ARTS_CameraPawn::MoveForward(float Value) { FloatingPawnMovement->AddInputVector(FVector(Value, 0.f, 0.f)); } void ARTS_CameraPawn::MoveRight(float Value) { FloatingPawnMovement->AddInputVector(FVector(0.f, Value, 0.f)); } void ARTS_CameraPawn::ZoomIn() { CameraBoom->TargetArmLength = FMath::Clamp(CameraBoom->TargetArmLength + ZoomIncrement, MinZoom, MaxZoom); } void ARTS_CameraPawn::ZoomOut() { CameraBoom->TargetArmLength = FMath::Clamp(CameraBoom->TargetArmLength - ZoomIncrement, MinZoom, MaxZoom); }
true
f8fb885db05ceb086e51f69ce269b3a5cadfaf05
C++
TamakiRinko/High_Level_Programme
/OJ/Exam5/exam5/OpSeq.h
UTF-8
744
2.5625
3
[]
no_license
// // Created by rinko on 2019/11/8. // #ifndef EXAM5_OPSEQ_H #define EXAM5_OPSEQ_H #include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; class List{ vector<int> list; int len; public: List(int* a,int len); void show(); List& operator=(List x); int getLen(); void add(int n); void reverse(); void init(); void tail(); bool isEmpty(){ return len == 0; } }; class OpSeq { vector<string> opList; int value; public: OpSeq(){ value = 0; } OpSeq(string s); OpSeq(OpSeq& opSeq); List forward_computing(List input); List backward_computing(List input); int gather_value(); }; #endif //EXAM5_OPSEQ_H
true
f4aca1a229a2a8b885b8e50db27a4869e6a7df4d
C++
himanshu-802/CP1_CIPHERSCHOOLS
/Dynamic Programming/Partial Equal Subset Sum.cpp
UTF-8
682
2.71875
3
[]
no_license
class Solution { public: bool func(vector<int>nums, int sum, int n, unordered_map<int,int>&dp) { if(sum==0){ return true; } if(n==0){ return false; } if(dp.find(sum)!=dp.end()){ return dp[sum]; } int result= func(nums,sum-nums[n-1],n-1,dp) || func(nums,sum,n-1,dp); dp[sum]=result; return dp[sum]; } bool canPartition(vector<int>& nums) { unordered_map<int,int>dp; int sum=0; int n=nums.size(); for(int i=0;i<n;i++)sum+=nums[i]; if(sum%2==1)return false; else{ return func(nums,sum/2,n,dp); } } };
true
61458822798f89bdfea429c0ecfcc1c28346945a
C++
s-kramer/cpp_tests
/t28_aggregate_sequential_initialization.cpp
UTF-8
1,306
3.625
4
[]
no_license
#include <iostream> #include <vector> #include <algorithm> #include <iterator> struct Widget { public: Widget(int num = Widget::count++) : value(num) { // std::cout << "Widget default constructor\n"; // std::cout << "Count: " << count << '\n'; } Widget(const Widget &rhs) { // std::cout << "Widget copy constructor\n"; // std::cout << "Count: " << count << '\n'; value = rhs.value; count++; } unsigned value; ~Widget(void) { count--; // std::cout << "Count: " << count-- << '\n'; } unsigned get_object_count(void) const {return count;}; private: static unsigned count; }; void print_widget(const Widget &w) { std::cout << w.get_object_count() << '\n'; } unsigned Widget::count = 0; template<typename T, std::size_t N> std::size_t arr_size(T(&)[N]) { return N; } int main() { std::vector<Widget> arr(10, Widget()); std::for_each(arr.begin(), arr.end(), print_widget); Widget widget_array[10] = {}; for (std::size_t i = 0; i < arr_size(widget_array); i++) { print_widget(i); } for(auto i : widget_array) print_widget(i); return 0; }
true
24d2b818de84568248fd0a95c17b8644e1cb2f03
C++
MLoktev/Bin_Tree
/Bin_Tree/Tests/Bin_Tree_Tests/main.cpp
UTF-8
884
2.890625
3
[]
no_license
#include <iostream> #include "bin_tree.h" #include <gtest/gtest.h> TEST(Bin_Tree_Test, addNode){ //Input BinTree<int> binTree; //Expected size_t expextedSize = binTree.getSize() + 1; //Actual binTree.add(10); size_t actualSize = binTree.getSize(); //Check ASSERT_EQ(expextedSize, actualSize); } TEST(Bin_Tree_Test, deleteNode){ //Input BinTree<int> binTree; binTree.add(20); binTree.add(30); binTree.add(10); binTree.add(5); binTree.add(8); binTree.add(1); binTree.add(7); binTree.add(9); //Expected size_t expextedSize = binTree.getSize() - 1; //Actual binTree.remote(10); size_t actualSize = binTree.getSize(); //Check ASSERT_EQ(expextedSize, actualSize); } int main(int argc, char *argv[]){ ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
true
19d78cdafa85c235f20a417a67c0c405d2a6321b
C++
tsingfun/cpp
/C++常用算法/查找(Search)/顺序查找和二分查找.cpp
UTF-8
1,151
3.328125
3
[ "Apache-2.0" ]
permissive
#include<iostream> #include<windows.h> using namespace std; class int_Arr { int *std; int maxsize; public: int_Arr(int size); ~int_Arr(); int &operator[](int i); int length(){return maxsize;} }; int_Arr::int_Arr(int size) { maxsize=size; std=new int[maxsize]; } int_Arr::~int_Arr() { delete []std; } int &int_Arr::operator[](int i) { return std[i]; } int SeqSearch(int_Arr &arr,int key) { int i; for(i=0;i<arr.length()&&arr[i]!=key;i++){} if(i==arr.length()) return 0; else return 1; } int BinSearch(int_Arr &R,int k) { int i,mid,l=1,r=R.length(); while(l<=r) { mid=(l+r)/2; if (R[mid]==k) return 1; else if (R[mid]>k) r=mid-1; else l=mid+1; } return 0;; } int F(int_Arr &R,int left,int right) { int temp; while(!(left>=right)) { if(R[left]>0&&R[right]<0) { temp=R[left]; R[left]=R[right]; R[right]=temp; left++; right--; } else { if(R[left]<0) { left++; } if(R[right]>0) right--; } } return 1; } int main() { int_Arr a(4); for(int i=0;i<10;i++) cin>>a[i]; F(a,0,9); for(int i=0;i<10;i++) cout<<a[i]<<" "; cout<<endl; system("pause"); return 0; }
true
0b6435b44431388686cf36d638ccf74e6522b772
C++
Twila27/SimplerMiner
/Engine/Code/Engine/Math/Vector3.hpp
UTF-8
5,763
3.359375
3
[]
no_license
#pragma once #include <math.h> #include "Engine/Error/ErrorWarningAssert.hpp" class Vector3 { public: inline Vector3(); inline Vector3( float initialX, float initialY, float initialZ ); inline Vector3( const Vector3& vectorToCopy ); inline void GetXYZ( float& out_x, float& out_y, float& out_z ) const; inline void SetXYZ( float newX, float newY, float newZ ); inline float CalcLength() const; inline void Normalize(); inline Vector3 operator+( const Vector3& vectorToAdd ) const; inline Vector3 operator-( const Vector3& vectorToSubtract ) const; inline Vector3 operator-( ); inline Vector3 operator*( float scalarToScaleBy ) const; inline Vector3 operator/( float scalarToScaleBy ) const; inline void operator+=( const Vector3& vectorToAdd ); inline void operator-=( const Vector3& vectorToSubtract ); inline void operator*=( const float uniformScale ); inline void operator=( const Vector3& copyFrom ); inline bool operator==( const Vector3& compareTo ) const; inline bool operator!=( const Vector3& compareTo ) const; public: //Because Vector3 is virtually a primitive. static const Vector3 ZERO; static const Vector3 ONE; float x; float y; float z; }; //-------------------------------------------------------------------------------------------------------------- // Do-nothing default ctor: because it saves time to leave trash values rather than allocate and initialize. inline Vector3::Vector3() : x() , y() , z() { } //-------------------------------------------------------------------------------------------------------------- inline Vector3::Vector3( float initialX, float initialY, float initialZ ) : x( initialX ) , y( initialY ) , z( initialZ ) { } //-------------------------------------------------------------------------------------------------------------- inline Vector3::Vector3( const Vector3& vectorToCopy ) : x( vectorToCopy.x ) , y( vectorToCopy.y ) , z( vectorToCopy.z ) { } //-------------------------------------------------------------------------------------------------------------- inline Vector3 Vector3::operator+( const Vector3& vectorToAdd ) const { return Vector3( x + vectorToAdd.x, y + vectorToAdd.y, z + vectorToAdd.z ); } //-------------------------------------------------------------------------------------------------------------- inline Vector3 Vector3::operator-( const Vector3& vectorToSubtract ) const { return Vector3( x - vectorToSubtract.x, y - vectorToSubtract.y, z - vectorToSubtract.z ); } //-------------------------------------------------------------------------------------------------------------- inline Vector3 Vector3::operator-( ) { x = -x; y = -y; z = -z; return Vector3( x, y, z ); } //-------------------------------------------------------------------------------------------------------------- inline Vector3 Vector3::operator*( float scalarToScaleBy ) const { return Vector3( x * scalarToScaleBy, y * scalarToScaleBy, z * scalarToScaleBy ); } //-------------------------------------------------------------------------------------------------------------- inline Vector3 Vector3::operator/( float scalarToScaleBy ) const { if ( scalarToScaleBy == 0.f ) ERROR_AND_DIE( "Vector3 Divided By Scalar Zero" ); return Vector3( x / scalarToScaleBy, y / scalarToScaleBy, z / scalarToScaleBy ); } //-------------------------------------------------------------------------------------------------------------- inline bool Vector3::operator==( const Vector3& compareTo ) const { return ( x == compareTo.x ) && ( y == compareTo.y ) && ( z == compareTo.z ); } //-------------------------------------------------------------------------------------------------------------- inline bool Vector3::operator!=( const Vector3& compareTo ) const { return !( *this == compareTo ); } //-------------------------------------------------------------------------------------------------------------- inline void Vector3::operator+=( const Vector3& vectorToAdd ) { x += vectorToAdd.x; y += vectorToAdd.y; z += vectorToAdd.z; } //-------------------------------------------------------------------------------------------------------------- inline void Vector3::operator-=( const Vector3& vectorToSubtract ) { x -= vectorToSubtract.x; y -= vectorToSubtract.y; z -= vectorToSubtract.z; } //-------------------------------------------------------------------------------------------------------------- inline void Vector3::operator*=( const float scalarToScaleBy ) { x *= scalarToScaleBy; y *= scalarToScaleBy; z *= scalarToScaleBy; } //-------------------------------------------------------------------------------------------------------------- inline void Vector3::operator=( const Vector3& vectorToCopy ) { x = vectorToCopy.x; y = vectorToCopy.y; z = vectorToCopy.z; } //-------------------------------------------------------------------------------------------------------------- inline float Vector3::CalcLength() const { return sqrt( ( x * x ) + ( y * y ) + ( z * z ) ); } //-------------------------------------------------------------------------------------------------------------- inline void Vector3::GetXYZ( float& out_x, float& out_y, float& out_z ) const { out_x = x; out_y = y; out_z = z; } //-------------------------------------------------------------------------------------------------------------- inline void Vector3::SetXYZ( float newX, float newY, float newZ ) { x = newX; y = newY; z = newZ; } //-------------------------------------------------------------------------------------------------------------- inline void Vector3::Normalize() { float len = CalcLength(); if ( len == 0.f ) ERROR_AND_DIE( "Normalizing Vector3 By Length Zero" ); x /= len; y /= len; z /= len; }
true
f326388f73b8850041ad1c3297823bf2b15d9322
C++
dubrousky/binomial
/include/thread_pool.h
UTF-8
7,327
3.125
3
[]
no_license
// // Created by Aliaksandr Dubrouski on 6/8/15. // #ifndef BINOMIAL_THREADPOOL_H #define BINOMIAL_THREADPOOL_H #include <thread> #include <mutex> #include <condition_variable> #include <vector> #include <future> #include <queue> #include <iostream> #include <numeric> #include <memory> class thread_pool; /** * @class worker * @brief class for picking the job from the thread pool task queue. * * This is a class for performing piece of work available from the * work queue of the thread pool. In the contrast to the std::async * it does not spawn the background thread - it uses the predefined * number of worker threads. */ class worker { public: /// @brief constructor explicit worker(thread_pool& s) : pool(s) { } /// @brief operator for executing the event loop void operator()(); private: /// @memo link to the thread pool to get the thread_pool& pool; }; /** * @class thread_pool * * @brief Class for execution of delayed tasks on the group of threads * * * This is a thread pool class that manages the task queue * and threads required to perform the work. We will use the * std::packaged_task to submit into the thread pool and the * std::future linked to the packaged task */ class thread_pool { public: /// @brief Constructor explicit thread_pool(size_t); /// @info No copy or assignment thread_pool(const thread_pool&) = delete; thread_pool& operator=(const thread_pool&) = delete; /// @brief Destructor ~thread_pool(); /// @brief Submits task of typr void->void to the thread pool for execution template <template<typename> class Task> std::future<void> async(Task<void()> f); /// @brief Submits task of typr (args...)->void to the thread pool for execution template<typename... Args, template<typename> class Task> std::future<void> async(Task<void(Args...)> f, Args... args); /// @brief Submits task of typr (void)->ret to the thread pool for execution template<typename Ret, template<typename> class Task> std::future<Ret> async(Task<Ret()> f); /// @brief Submits task of typr (args...)->ret to the thread pool for execution template<typename Ret, typename... Args, template<typename> class Task> std::future<Ret> async(Task<Ret(Args...)> f, Args... args); /// @brief Executes the parallel version of std::accumulate on the thread pool template<typename R, typename Iterator, typename BinOp > R paccumulate(Iterator first, Iterator last, R start, BinOp bop, int fork_threshold = std::thread::hardware_concurrency()); private: friend class worker; // Threads std::vector< std::thread > workers; // Task queue std::queue<std::future<void> > tasks; mutable std::mutex queue_mutex; std::condition_variable work_available; std::atomic<bool> stopping; }; /// @brief template<typename Ret, typename... Args, template<typename> class Task> std::future<Ret> thread_pool::async(Task<Ret(Args...)> f, Args... args) { typedef Task<Ret(Args...)> F; auto p = std::make_shared<std::promise<Ret> >(); // promise to be completed // packaged task to evaluate function and complete a promise auto task_wrapper = [p](F&& t,Args&&... as) { try { auto tmp = t(as...); p->set_value(std::move(tmp)); } catch (...) { p->set_exception(std::current_exception()); } }; auto task = std::async(std::launch::deferred,task_wrapper,f,args...); { std::lock_guard<std::mutex> guard(queue_mutex); tasks.push(std::move(task)); } work_available.notify_one(); return p->get_future(); } /// @brief unary function void -> Ret template<typename Ret, template<typename> class Task> std::future<Ret> thread_pool::async(Task<Ret()> f) { typedef Task<Ret()> F; auto p = std::make_shared<std::promise<Ret> >(); // promise to be completed // packaged task to evaluate function and complete a promise auto task_wrapper = [p](F&& t) { try { p->set_value(t()); } catch (...) { p->set_exception(std::current_exception()); } }; auto task = std::async(std::launch::deferred,task_wrapper,std::move(f)); { std::lock_guard<std::mutex> guard(queue_mutex); tasks.push(std::move(task)); } work_available.notify_one(); return p->get_future(); } /// @brief template<typename... Args,template<typename> class Task> std::future<void> thread_pool::async(Task<void(Args...)> f, Args... args) { typedef Task<void(Args...)> F; auto p = std::make_shared<std::promise<void> >(); // promise to be completed // packaged task to evaluate function and complete a promise auto task_wrapper = [p](F&& t,Args&&...as) { try { t(as...); p->set_value(); } catch (...) { p->set_exception(std::current_exception()); } }; auto task = std::async(std::launch::deferred,task_wrapper,f,args...); { std::lock_guard<std::mutex> guard(queue_mutex); tasks.push(std::move(task)); } work_available.notify_one(); return p->get_future(); } /// @brief void -> void template <template<typename> class Task> std::future<void> thread_pool::async(Task<void()> f) { typedef Task<void()> F; auto p = std::make_shared<std::promise<void> >(); // promise to be completed // packaged task to evaluate function and complete a promise auto task_wrapper = [p](F&& t) { try { t(); p->set_value(); } catch (...) { p->set_exception(std::current_exception()); } }; auto task = std::async(std::launch::deferred,task_wrapper,std::move(f)); { std::lock_guard<std::mutex> guard(queue_mutex); tasks.push(std::move(task)); } work_available.notify_one(); return p->get_future(); } /// @brief (coll,start,op)->decltype(start) template<typename R, typename Iterator, typename BinOp> R thread_pool::paccumulate(Iterator first,Iterator last, R start, BinOp bop, int fork_threshold) { std::vector<std::future<R> > intermediates; // fork if the task volume is large enough while(std::distance(first,last) > fork_threshold) { Iterator mid = first; std::advance(mid,fork_threshold); auto handle = this->async([first,mid,bop]() -> R { return std::accumulate(first,mid,bop.unity(),bop);}); intermediates.push_back(std::move(handle)); std::advance(first,fork_threshold); } // calculate the rest itself if any R res = (first!=last) ? res = std::accumulate(first, last, start, bop) : start; // join the results (the load may be uneven) return std::accumulate(intermediates.begin(), intermediates.end(), res,[&bop](R e,std::future<R>& f) { return bop(e,f.get()); }); } /** * @class thread_pool_of<N> * @brief convenience wrapper for creation of threads with compile time deduced number of threads */ template<unsigned short N> class thread_pool_of : public thread_pool { public: thread_pool_of() : thread_pool(N){ } }; #endif //BINOMIAL_THREADPOOL_H
true
b8c12b6f3e79abbfa237f744343c0f831e787e5f
C++
Vortez2471/Dynamic_Programming
/Wine_problem.cpp
UTF-8
913
3.0625
3
[]
no_license
//Wine problem #include<iostream> #include<bits/stdc++.h> #include<algorithm> using namespace std; int memo[1000][1000]; int wine(int arr[],int s,int e,int year) { if(s>e) return 0; if(memo[s][e]!=-1) return memo[s][e]; int q1=INT_MIN; int q2=q1; q1=arr[s]*year+wine(arr,s+1,e,year+1); q2=arr[e]*year+wine(arr,s,e-1,year+1); int ans=max(q1,q2); return memo[s][e]=ans; } int bottom_up(int arr[],int n) { int dp[1000][1000]; int year=n; for(int i=0;i<=n;i++) dp[i][i]=arr[i]*year; year--; for(int len=2;len<=n;len++) { int s=0; int e=n-len; while(s<=e) { int end=s+len-1; dp[s][end]=max(arr[s]*year+dp[s+1][end],arr[end]*year+dp[s][end-1]); s++; } year--; } return dp[0][n-1]; } int main() { memset(memo,-1,sizeof(memo)); int n; cin>>n; int arr[n]; arr[0]=INT_MAX; for(int i=0;i<n;i++) cin>>arr[i]; cout<<wine(arr,0,n-1,1)<<"\n"<<bottom_up(arr,n)<<endl; }
true
f5c3132af29f394d4b4a8ce45c8bca4c7457488e
C++
varun-sundar-rabindranath/matmul-HPC
/matmul_cpp.cpp
UTF-8
2,177
3.640625
4
[]
no_license
#include <iostream> #include <cstdlib> // malloc #include <cassert> // assert #include "utils.hpp" #include "timer.hpp" using namespace std; #define G 1000000000 #define M 1000000 void matmul(float* A, float* B, float* C, int n) { for (int i = 0; i < n; i++) { // Iterates the rows for (int j = 0; j < n; j++) { // Iterates the columns float product = 0; for (int k = 0; k < n; k++) { product += A[i * n + k] * B[k * n + j]; } C[i * n + j] = product; } } } int main(int argc, char *argv[]) { if(argc != 2) { /* Too many or too few arguments */ cerr<<" Too many or too few arguments;"<<endl; cerr<<" Right usage is : ./matmul <square-matrix-dimension>"<<endl; return 0; } int mat_dim = atoi(argv[1]); cout<<"*********** Multiply square matrix **********"<<endl; cout<<"Dimension : "<<mat_dim<<endl; cout<<"Memory required : "<<(double)(mat_dim * mat_dim * 3 * sizeof(float)) / (double)G<<" GB"<<endl; float* A = NULL; // input float* B = NULL; // input float* C = NULL; // A * B A = (float*) calloc(mat_dim * mat_dim, sizeof(float)); B = (float*) calloc(mat_dim * mat_dim, sizeof(float)); C = (float*) calloc(mat_dim * mat_dim, sizeof(float)); assert(A != NULL && "Cannot allocate memory - A"); assert(B != NULL && "Cannot allocate memory - B"); assert(C != NULL && "Cannot allocate memory - C"); /* Fill A and B */ for (int iter = 0; iter < mat_dim * mat_dim; iter++) { A[iter] = 1; B[iter] = 1; } startTimer(); matmul(A, B, C, mat_dim); // C = A * B endTimer(); /* Check C * Multiplying matrices of all 1's should leave C with all values 'mat_dim' */ bool c_matmul_pass = true; for (int iter = 0; iter < mat_dim * mat_dim; iter++) { if(C[iter] != mat_dim) { c_matmul_pass = false; break; } } /* Print result with elapsed time */ if (c_matmul_pass) { cerr<<"C matmul pass. - "<<getElapsedTime() / (double)M<<" sec."<<endl; } else { cerr<<"C matmul fail. - "<<getElapsedTime() / (double)M<<" sec."<<endl; } free(A); free(B); free(C); return 0; }
true
37e6414aba72ca0f4b9e1e2fb53e8013b616eac7
C++
festiveBean/Titan-Voyager-Custom-Game-Engine
/Game Engine - Titan Voyager - Rony Hanna/Voyager/PointLight.h
UTF-8
1,074
2.90625
3
[]
no_license
#pragma once #ifndef __POINTLIGHT_H__ #define __POINTLIGHT_H__ #include "Dependencies\glm-0.9.9-a2\glm\glm.hpp" #include "Dependencies\glm-0.9.9-a2\glm\gtx\transform.hpp" class PointLight { public: PointLight(); ~PointLight(); void Configure(glm::vec3 ambient, glm::vec3 diffuse, glm::vec3 specular, float constant, float linear, float quadratic); void SetPosition(glm::vec3 pos) { m_position = pos; } void SetLightColour(glm::vec3 col) { m_lightColour = col; } glm::vec3& GetPos() { return m_position; } glm::vec3& GetColour() { return m_lightColour; } glm::vec3& GetAmbient() { return m_ambient; } glm::vec3& GetDiffuse() { return m_diffuse; } glm::vec3& GetSpecular() { return m_specular; } float& GetConstant() { return m_constant; } float& GetLinear() { return m_linear; } float& GetQuadratic() { return m_quadratic; } private: glm::vec3 m_position; glm::vec3 m_ambient; glm::vec3 m_diffuse; glm::vec3 m_specular; glm::vec3 m_lightColour; float m_constant; float m_linear; float m_quadratic; }; #endif // !__POINTLIGHT_H__
true
bd3761a5b1dd73d7e2f2f7713247c993ccc464b4
C++
yuhsuanyang/leetcode
/integer_to_roman.cpp
BIG5
1,114
3.734375
4
[]
no_license
#include <iostream> #include <string> #include <map> using namespace std; //bC++rꪺOѦrҲզ}CAæb̫[W@Ӫš]null^r'\0' class Solution { public: map<int, string>m[4]; Solution(){ m[0][1]="M"; m[1][1]="C"; m[2][1]="X"; m[3][1]="I"; m[1][5]="D"; m[2][5]="L"; m[3][5]="V"; for(int i=0;i<4;i++){ m[i][0]=""; if(i!=0){ m[i][4]=m[i][1]+m[i][5]; m[i][9]=m[i][1]+m[i-1][1]; } } } string intToRoman(int num) { int result[4]; int tens[4]={1000,100,10,1}; string ans=""; for(int i=0;i<4;i++){ result[i]=num/tens[i]; num=num-tens[i]*result[i]; }; for(int i=0;i<4;i++){ //cout<<result[i]<<" "; if(result[i]==0 or result[i]==4 or result[i]==9){ ans=ans+m[i][result[i]]; }else{ if(result[i]>=5){ ans=ans+m[i][5]; }; for(int j=0;j<result[i]%5;j++){ ans=ans+m[i][1]; } } }; return ans; }; }; int main(){ Solution sol; //cout<<sol.m[3][5]<<endl; cout<<sol.intToRoman(1994)<<endl; return 0; }
true
5b4664f1bbb70f89c6e17c2d6d010c1820e69052
C++
ScienceIsNeato/escape_room_radio
/include/trigger.h
UTF-8
407
2.6875
3
[]
no_license
#ifndef TRIGGER_H #define TRIGGER_H #include <functional> class Trigger { // This class manages a triggered event (i.e. button press) that initiates the checks throughout the program private: bool _debug_condition = false; public: Trigger(); ~Trigger(); void Listen(std::function<void()> callback); void SetDebugCondition(bool cond); }; #endif
true
12e57a49b1d20aa471b22fbd2a698fe591f3f09e
C++
violetfeline/cppBasic
/03/25/main.cpp
UTF-8
537
2.859375
3
[]
no_license
#include <iostream> int main() { const int size = 10; const int merged = size * 2; int a[size]; int b[size]; int c[merged]; for(int i = 0; i < size; i++) std::cin >> a[i]; for(int i = 0; i < size; i++) std::cin >> b[i]; int i = 0; int j = 0; int k = 0; while(i < size && j < size) { if(a[i] <= b[j]) { c[k] = a[i]; i++; } else { c[k] = b[j]; j++; } k++; } while(i < size) c[k++] = a[i++]; while(j < size) c[k++] = b[j++]; i = 0; while(i < merged) { std::cout << c[i] << ' '; i++; } return 0; }
true
ecc1a3f4a315d4c9db65a5afab3de1e45ec63e72
C++
DaDaMrX/ACM
/Code/Dynamic Programming/Codeforces 337D Book of Evil (子树直径).cpp
UTF-8
1,332
2.640625
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int INF = 0x7f7f7f7f; const int N = 1e5 + 10; struct Edge { int to, next; } e[N * 2]; int head[N], num; int n, m, d; int p[N], dis1[N], dis2[N]; void add(int u, int v) { e[num].to = v; e[num].next = head[u]; head[u] = num++; } queue<int> q; int vis[N]; void bfs(int start, int dis[]) { memset(vis, false, sizeof(vis)); dis[start] = 0; while (!q.empty()) q.pop(); q.push(start); vis[start] = true; while (!q.empty()) { int from = q.front(); q.pop(); for (int i = head[from]; i != -1; i = e[i].next) { int to = e[i].to; if (vis[to]) continue; dis[to] = dis[from] + 1; q.push(to); vis[to] = true; } } } int main() { scanf("%d%d%d", &n, &m, &d); for (int i = 1; i <= m; i++) scanf("%d", &p[i]); memset(head, -1, sizeof(head)); num = 0; for (int i = 1; i < n; i++) { int a, b; scanf("%d%d", &a, &b); add(a, b); add(b, a); } bfs(p[1], dis1); int s = -1; for (int i = 1; i <= m; i++) if (s == -1 || dis1[p[i]] > dis1[s]) s = p[i]; bfs(s, dis1); int t = -1; for (int i = 1; i <= m; i++) if (t == -1 || dis1[p[i]] > dis1[t]) t = p[i]; bfs(t, dis2); int ans = 0; for (int i = 1; i <= n; i++) if (dis1[i] <= d && dis2[i] <= d) ans++; printf("%d\n", ans); return 0; }
true
d2e87f4d948db685a1cd4970ddea2688a537b39d
C++
mediabuff/Lumino
/Source/LuminoEngine/Include/Lumino/Scene/TextBlock.h
UTF-8
2,609
2.75
3
[ "MIT" ]
permissive
 #pragma once #include <Lumino/Graphics/Texture.h> #include "VisualNode.h" LN_NAMESPACE_BEGIN LN_NAMESPACE_SCENE_BEGIN namespace detail { class Paragraph; } class TextBlock2DComponent; using TextBlock2DComponentPtr = Ref<TextBlock2DComponent>; /** @brief */ class TextBlock2DComponent : public VisualComponent { LN_OBJECT; public: /** @brief */ static TextBlock2DComponentPtr create(); /** @brief */ static TextBlock2DComponentPtr create(const StringRef& text); public: void setFont(Font* font); /** 表示する文字列を設定します。*/ void setText(const StringRef& text); /** @brief テキストの表示の原点を設定します。 @details 値は (0,0) から (1,1) の間で指定します。 デフォルトは (0,0) で、これはテキストの左上が原点であることを意味します。 (0.5,0.5) はテキストの中央、(1,1) は右下が原点となります。 */ void setAnchorPoint(const Vector2& ratio); void setAnchorPoint(float ratioX, float ratioY); /**< @overload setAnchorPoint */ protected: TextBlock2DComponent(); virtual ~TextBlock2DComponent(); void initialize(); virtual void updateFrameHierarchy(SceneNode* parent, float deltaTime) override; virtual detail::Sphere getBoundingSphere() override; virtual void onRender2(RenderingContext* renderer) override; protected: Vector2 m_anchor; Ref<Font> m_font; String m_text; Size m_renderSize; //Ref<detail::Paragraph> m_paragraph; //Size m_renderSize; }; /** @brief */ LN_CLASS() class TextBlock2D : public VisualObject { LN_OBJECT; public: /** @brief */ static Ref<TextBlock2D> create(); /** @brief */ static Ref<TextBlock2D> create(const StringRef& text); void setFont(Font* font); void setText(const StringRef& text); /** @brief テキストの表示の原点を設定します。 @details 値は (0,0) から (1,1) の間で指定します。 デフォルトは (0,0) で、これはテキストの左上が原点であることを意味します。 (0.5,0.5) はテキストの中央、(1,1) は右下が原点となります。 */ void setAnchorPoint(const Vector2& ratio); void setAnchorPoint(float ratioX, float ratioY); /**< @overload setAnchorPoint */ protected: virtual VisualComponent* getMainVisualComponent() const override; LN_CONSTRUCT_ACCESS: TextBlock2D(); virtual ~TextBlock2D(); LN_METHOD() void initialize(); LN_METHOD() void initialize(const StringRef& text); private: Ref<TextBlock2DComponent> m_component; }; LN_NAMESPACE_SCENE_END LN_NAMESPACE_END
true
01f4f82498d8f049d26985ab58b5e1d4cab6fcb0
C++
DFLovingWM/leetcode-solving
/problems/413-arithmetic-slices/math.cpp
UTF-8
667
3.5
4
[]
no_license
/** * 数学:计算每一段等差子数组的个数(用求和公式),累加即可 * * 时间:`O(N)`, 8ms */ class Solution { public: int numberOfArithmeticSlices(vector<int>& A) { int res = 0; int acc = 0, d; // 找连续的等差子数组 for (int i = 2; i < A.size(); ++i) { // 技巧:这里从2开始 if (A[i] - A[i-1] == A[i-1] - A[i-2]) { // 可连续 ++acc; } else { res += acc * (acc + 1) / 2; // 求和公式 acc = 0; } } // 最后一次 res += acc * (acc + 1) / 2; return res; } };
true
a5b273a80e7ba94a4319fe648e1c48f2528ceaa3
C++
yzbx/surveillance-video-system
/objectTracking/src/objectTracking/yzbxLib/ObjectTrajectoryProcessing.h
UTF-8
2,121
2.625
3
[]
no_license
#ifndef OBJECTTRAJECTORYPROCESSING_H #define OBJECTTRAJECTORYPROCESSING_H #include <QtCore> #include <iostream> #include <yzbx_config.h> class ObjectTrajectoryProcessing { public: ObjectTrajectoryProcessing(QString inputFile,QString outputFile); private: float distanceThreshold=100; class object{ public: int id; std::list<std::pair<int,Rect_t>> rects; }; std::list<object> objects; void updateObjects(int id, int frameNum, Rect_t rect); void loadObjects(QString inputFile); void filterObjects(); void dumpObjects(QString outputFile); inline float calculateDistance(object &a, object &b){ auto ita=a.rects.begin(); auto itb=b.rects.begin(); //use kalman to find weather object a in object b // float frameNumDif=a.rects.size()-b.rects.size(); int frameNumSame=0; float rectsDif=0.0; while(ita!=a.rects.end()&&itb!=b.rects.end()){ int ida=ita->first; int idb=ita->first; if(ida>idb){ itb++; } else if(ida<idb){ ita++; } else{ frameNumSame++; Rect_t &ra=(ita->second); Rect_t &rb=(itb->second); Point_t dbr=ra.br()-rb.br(); Point_t dtl=ra.tl()-rb.tl(); float dx=(ra.br().x-rb.br().x)*(ra.tl().x-rb.tl().x); float dy=(ra.br().y-rb.br().y)*(ra.tl().y-rb.tl().y); if(dx<=0&&dy<=0){ //ra in rb or rb in ra } else{ float dist=(cv::norm(dbr)+cv::norm(dtl))/2; rectsDif+=dist; if(rectsDif>distanceThreshold){ return std::numeric_limits<float>::max(); } } } } if(frameNumSame==0) return std::numeric_limits<float>::max(); else return rectsDif/frameNumSame; } void calculateDistanceMat(cv::Mat &distMat); }; #endif // OBJECTTRAJECTORYPROCESSING_H
true
8efad9d8763ab330f64baf14eab605578e04f135
C++
gabrielgbs/Pel-eterno
/Jogador.cpp
UTF-8
12,326
2.671875
3
[]
no_license
#include "Jogador.hpp" Jogador::Jogador(){ posX = posZ = posY = 0; } Jogador::Jogador(double x, double y, double z){ posX = x; posY = y; posZ = z; //criaListas(); } void Jogador::setPos(double x,double y,double z){ posX = x; posY = y; posZ = z; } double Jogador::getPosX(){ return posX; } double Jogador::getPosY(){ return posY; } double Jogador::getPosZ(){ return posZ; } void Jogador::desenhaPele(){ //criar braco static GLuint braco = glGenLists(1);//gerar um indice de uma lista glNewList(braco, GL_COMPILE); glScalef(0.05, 0.18, 0.05); glColor3f(0.478f,0.2862f,0.2745f); glutSolidCube(2.0f); glEndList();//Finaliza a lista iniciada //criar ante-braco static GLuint antebraco = glGenLists(1); glNewList(antebraco, GL_COMPILE); glScalef(0.06, 0.18, 0.07); glColor3f(1.0f,1.0f,0.0f); glutSolidCube(2.0f); glEndList(); //criar mao static GLuint mao = glGenLists(1); glNewList(mao, GL_COMPILE); glScalef(0.2,0.25,0.2); glColor3f(0.478f,0.2862f,0.2745f); glutSolidSphere(0.35, 10, 10); glEndList(); //criar articulacao static GLuint articulacao = glGenLists(1); glNewList(articulacao, GL_COMPILE); glScalef(0.2,0.2,0.2); glColor3f(0.478f,0.2862f,0.2745f); glutSolidSphere(0.25, 10, 10); glEndList(); //criar ombro static GLuint ombro = glGenLists(1); glNewList(ombro, GL_COMPILE); glScalef(0.3,0.2,0.2); glColor3f(1.0f,1.0f,0.0f); glutSolidSphere(0.4, 10, 10); glEndList(); //criar busto static GLuint busto = glGenLists(1); glNewList(busto, GL_COMPILE); glScalef(0.21, 0.45, 0.14); glColor3f(1.0f,1.f,0.0f); glutSolidTorus(1, 0, 8, 8);//Definindo um solido para ser o corpo glEndList(); //criar cabeca static GLuint cabeca = glGenLists(1); glNewList(cabeca, GL_COMPILE); glScalef(0.2, 0.27, 0.2); glColor3f(0.478f,0.2862f,0.2745f); glutSolidSphere(0.6, 10, 10); glEndList(); //criar perna static GLuint perna = glGenLists(1); glNewList(perna, GL_COMPILE); glScalef(0.06, 0.22, 0.06); glColor3f(0.0f,0.0f,1.0f); glutSolidCube(2.0f); glEndList(); //criar canela static GLuint canela = glGenLists(1); glNewList(canela, GL_COMPILE); glScalef(0.05, 0.16, 0.05); //glColor3f(0.478f,0.2862f,0.2745f); glColor3f(0.9f,0.9f,0.9f); glutSolidCube(2.0f); glEndList(); //criar calcao static GLuint calcao = glGenLists(1); glNewList(calcao, GL_COMPILE); glScalef(0.15, 0.18, 0.07); glColor3f(0.0f,0.0f,1.0f); glutSolidCube(2.0f); glEndList(); //criar pe static GLuint pe = glGenLists(1); glNewList(pe, GL_COMPILE); glScalef(0.05, 0.02, 0.1); glColor3f(0.0f,0.0f,0.0f); glutSolidCube(2.0f); glEndList(); //desenhar a figura //desenhar o busto glPushMatrix(); glTranslatef(posX+30, posY+1.2, posZ+47); glCallList(busto); glPopMatrix(); //desenhar as pernas glPushMatrix();//desenha calcao glTranslatef(posX+30, posY+0.7, posZ+47); glCallList(calcao); glPopMatrix(); glPushMatrix();//perna direita glTranslatef(posX+30.1, posY+0.65, posZ+47); glPushMatrix(); glCallList(perna); glPopMatrix(); glPushMatrix();//canela direita glTranslatef(0.0, -0.424, 0.0); glCallList(canela); glPopMatrix(); glPopMatrix(); glPushMatrix();//joelho direito glTranslatef(posX+30.1, 0.4, posZ+47); glCallList(articulacao); glPopMatrix(); glPushMatrix();//perna esquerda glTranslatef(posX+29.9, posY+0.65, posZ+47); glPushMatrix(); glCallList(perna); glPopMatrix(); glPushMatrix();//canela esquerda glTranslatef(0.0, -0.424, 0.0); glCallList(canela); glPopMatrix(); glPopMatrix(); glPushMatrix();//joelho esquerdo glTranslatef(posX+29.9, 0.4, posZ+47); glCallList(articulacao); glPopMatrix(); //desenhar pes glPushMatrix();//pe direito glTranslatef(posX+30.1, posY+0.05, posZ+47.05); glCallList(pe); glPopMatrix(); glPushMatrix();//pe esquerdo glTranslatef(posX+29.9, posY+0.05, posZ+47.05); glCallList(pe); glPopMatrix(); //desenhar a cabeca glPushMatrix(); glTranslatef(posX+30, posY+1.75, posZ+47); glCallList(cabeca); glPopMatrix(); //desenhar ombros glPushMatrix();//ombro direito glTranslatef(posX+30.17, posY+1.47, posZ+47); glCallList(ombro); glPopMatrix(); glPushMatrix();//ombro esquerdo glTranslatef(posX+29.83, posY+1.47, posZ+47); glCallList(ombro); glPopMatrix(); //desenhar os bracos glPushMatrix();//Ante-braco direito glTranslatef(posX+30.23, posY+1.3, posZ+47); glPushMatrix(); glCallList(antebraco); glPopMatrix(); glPushMatrix();//braco direito glTranslatef(0.02, -0.4, 0.0); glCallList(braco); glPopMatrix(); glPopMatrix(); glPushMatrix();//cotovelo direito glTranslatef(posX+30.25, posY+1.12, posZ+47); glCallList(articulacao); glPopMatrix(); glPushMatrix();//Ante-braco esquerdo glTranslatef(posX+29.77, posY+1.3, posZ+47); glPushMatrix(); glCallList(antebraco); glPopMatrix(); glPushMatrix();//braco esquerdo glTranslatef(-0.02, -0.4, 0.0); glCallList(braco); glPopMatrix(); glPopMatrix(); glPushMatrix();//cotovelo esquerdo glTranslatef(posX+29.75, posY+1.12, posZ+47); glCallList(articulacao); glPopMatrix(); //desenhar as maos glPushMatrix();//mao direita glTranslatef(posX+30.25, posY+0.65, posZ+47); glCallList(mao); glPopMatrix(); glPushMatrix();//mao esquerda glTranslatef(posX+29.75, posY+0.65, posZ+47); glCallList(mao); glPopMatrix(); glDeleteLists(braco, 1); glDeleteLists(antebraco, 1); glDeleteLists(mao, 1); glDeleteLists(articulacao, 1); glDeleteLists(ombro, 1); glDeleteLists(busto, 1); glDeleteLists(cabeca, 1); glDeleteLists(perna, 1); glDeleteLists(canela, 1); glDeleteLists(calcao, 1); glDeleteLists(pe, 1); } void Jogador::desenhaGoleiro(){ //criar braco static GLuint braco = glGenLists(1);//gerar um indice de uma lista glNewList(braco, GL_COMPILE); glScalef(0.05, 0.18, 0.05); glColor3f(0.3098f,0.6431f,0.8352f); glutSolidCube(2.0f); glEndList();//Finaliza a lista iniciada //criar ante-braco static GLuint antebraco = glGenLists(1); glNewList(antebraco, GL_COMPILE); glScalef(0.06, 0.18, 0.07); glColor3f(0.9098f,0.8588f,0.8078f); glutSolidCube(2.0f); glEndList(); //criar mao static GLuint mao = glGenLists(1); glNewList(mao, GL_COMPILE); glScalef(0.2,0.25,0.2); glColor3f(0.9803f,0.8588f,0.7725f); glutSolidSphere(0.35, 10, 10); glEndList(); //criar articulacao static GLuint articulacao = glGenLists(1); glNewList(articulacao, GL_COMPILE); glScalef(0.2,0.2,0.2); glColor3f(0.9098f,0.8745f,0.8078f); glutSolidSphere(0.25, 10, 10); glEndList(); //criar ombro static GLuint ombro = glGenLists(1); glNewList(ombro, GL_COMPILE); glScalef(0.3,0.2,0.2); glColor3f(0.3098f,0.6431f,0.8352f); glutSolidSphere(0.4, 10, 10); glEndList(); //criar busto static GLuint busto = glGenLists(1); glNewList(busto, GL_COMPILE); glScalef(0.21, 0.45, 0.14); glColor3f(0.3098f,0.6431f,0.8352f); glutSolidTorus(1, 0, 8, 8);//Definindo um solido para ser o corpo glEndList(); //criar cabeca static GLuint cabeca = glGenLists(1); glNewList(cabeca, GL_COMPILE); glScalef(0.2, 0.27, 0.2); glColor3f(1.0f,0.2862f,0.2745f); glutSolidSphere(0.6, 10, 10); glEndList(); //criar perna static GLuint perna = glGenLists(1); glNewList(perna, GL_COMPILE); glScalef(0.06, 0.22, 0.06); glColor3f(0.0f,0.0f,0.0f); glutSolidCube(2.0f); glEndList(); //criar canela static GLuint canela = glGenLists(1); glNewList(canela, GL_COMPILE); glScalef(0.05, 0.16, 0.05); //glColor3f(0.478f,0.2862f,0.2745f); glColor3f(0.9f,0.9f,0.9f); glutSolidCube(2.0f); glEndList(); //criar calcao static GLuint calcao = glGenLists(1); glNewList(calcao, GL_COMPILE); glScalef(0.15, 0.18, 0.07); glColor3f(0.0f,0.0f,0.0f); glutSolidCube(2.0f); glEndList(); //criar pe static GLuint pe = glGenLists(1); glNewList(pe, GL_COMPILE); glScalef(0.05, 0.02, 0.1); glColor3f(0.0f,0.0f,0.0f); glutSolidCube(2.0f); glEndList(); //desenhar a figura //desenhar o busto glPushMatrix(); glTranslatef(posX+30, posY+1.2, posZ+47); glCallList(busto); glPopMatrix(); //desenhar as pernas glPushMatrix();//desenha calcao glTranslatef(posX+30, posY+0.7, posZ+47); glCallList(calcao); glPopMatrix(); glPushMatrix();//perna direita glTranslatef(posX+30.1, posY+0.65, posZ+47); glPushMatrix(); glCallList(perna); glPopMatrix(); glPushMatrix();//canela direita glTranslatef(0.0, -0.424, 0.0); glCallList(canela); glPopMatrix(); glPopMatrix(); glPushMatrix();//joelho direito glTranslatef(posX+30.1, 0.4, posZ+47); glCallList(articulacao); glPopMatrix(); glPushMatrix();//perna esquerda glTranslatef(posX+29.9, posY+0.65, posZ+47); glPushMatrix(); glCallList(perna); glPopMatrix(); glPushMatrix();//canela esquerda glTranslatef(0.0, -0.424, 0.0); glCallList(canela); glPopMatrix(); glPopMatrix(); glPushMatrix();//joelho esquerdo glTranslatef(posX+29.9, 0.4, posZ+47); glCallList(articulacao); glPopMatrix(); //desenhar pes glPushMatrix();//pe direito glTranslatef(posX+30.1, posY+0.05, posZ+46.95); glCallList(pe); glPopMatrix(); glPushMatrix();//pe esquerdo glTranslatef(posX+29.9, posY+0.05, posZ+46.95); glCallList(pe); glPopMatrix(); //desenhar a cabeca glPushMatrix(); glTranslatef(posX+30, posY+1.75, posZ+47); glCallList(cabeca); glPopMatrix(); //desenhar ombros glPushMatrix();//ombro direito glTranslatef(posX+30.17, posY+1.47, posZ+47); glCallList(ombro); glPopMatrix(); glPushMatrix();//ombro esquerdo glTranslatef(posX+29.83, posY+1.47, posZ+47); glCallList(ombro); glPopMatrix(); //desenhar os bracos glPushMatrix();//Ante-braco direito glTranslatef(posX+30.3, posY+1.4, posZ+47); glPushMatrix(); glRotatef(65, 0, 0, 1); glCallList(antebraco); glPopMatrix(); glPushMatrix();//braco direito glTranslatef(0.27, 0.1, 0.0); glRotatef(-20, 0, 0, 1); glCallList(braco); glPopMatrix(); glPopMatrix(); glPushMatrix();//cotovelo direito glTranslatef(posX+30.5, posY+1.3, posZ+47); glCallList(articulacao); glPopMatrix(); glPushMatrix();//Ante-braco esquerdo glTranslatef(posX+29.7, posY+1.4, posZ+47); glPushMatrix(); glRotatef(-65, 0, 0, 1); glCallList(antebraco); glPopMatrix(); glPushMatrix();//braco esquerdo glTranslatef(-0.27, 0.1, 0.0); glRotatef(20, 0, 0, 1); glCallList(braco); glPopMatrix(); glPopMatrix(); glPushMatrix();//cotovelo esquerdo glTranslatef(posX+29.5, posY+1.3, posZ+47); glCallList(articulacao); glPopMatrix(); //desenhar as maos glPushMatrix();//mao direita glTranslatef(posX+30.66, posY+1.75, posZ+47); glCallList(mao); glPopMatrix(); glPushMatrix();//mao esquerda glTranslatef(posX+29.34, posY+1.75, posZ+47); glCallList(mao); glPopMatrix(); glDeleteLists(braco, 1); glDeleteLists(antebraco, 1); glDeleteLists(mao, 1); glDeleteLists(articulacao, 1); glDeleteLists(ombro, 1); glDeleteLists(busto, 1); glDeleteLists(cabeca, 1); glDeleteLists(perna, 1); glDeleteLists(canela, 1); glDeleteLists(calcao, 1); glDeleteLists(pe, 1); }
true
7fa204c8b2f470eeb0bb9c61c9aad556023dd2f8
C++
mike-sherman1/parser
/parser3/lexan.cpp
UTF-8
2,660
2.9375
3
[]
no_license
#include <iostream> #include <fstream> #include <cctype> #include "token.h" #include "functions.h" using namespace std; extern ifstream ifs; // input file stream to read from extern SymTab symtab; // global symbol table static int lineno = 1; // static var to remember line no. Token lexan( ) // lexical analyzer { int t; string tokstr; while( 1 ) { t = ifs.get( ); // get next character if( t == '#' ) // beginning of a comment { while( ifs.get( ) != '\n' ) { // comment until \n } } else if( t == ' ' || t == '\t' ) { // discard white space } else if( t == '\n' ) // new line { ++lineno; } else if( isalpha( t ) ) // t is a letter { tokstr = ""; // empty tokstr while( isalnum( t ) ) // while it is an alpha numeric char { tokstr.push_back( t ); t = ifs.get( ); // get the next character } ifs.putback( t ); // went one char too far int p = symtab.lookup( tokstr ); if( p < 0 ) { // add an "undefined ID" to symtab p = symtab.insert( tokstr, UID ); } return Token( tokstr, symtab.toktype( p ), p, lineno ); } else if( t == EOF ) { return Token( "", DONE, 0, lineno ); } else { tokstr.push_back( t ); return Token( tokstr, t, NONE, lineno ); } } } void init_kws( ) // init keywords/ids in symtab { symtab.insert( "begin", KW ); symtab.insert( "end", KW ); symtab.insert( "A", ID ); symtab.insert( "B", ID ); symtab.insert( "C", ID ); } ifstream get_ifs( ) // get input file stream { string filename; // input file name cerr << "name of file to read from? "; cin >> filename; ifstream ifs( filename, ifstream::in ); if( ! ifs ) // cannot open file infilen { cerr << "cannot open input file '" << filename << "'\n"; exit( 1 ); } return ifs; // return input file stream }
true
acff69a459ad497c0a3820e575c8b5947ab8cfca
C++
CaiyuhangChina/-
/乙级/1026. 程序运行时间(15).cpp
GB18030
461
2.71875
3
[]
no_license
#include <iostream> #include <iomanip> using namespace std; int main() { unsigned c1, c2, c; cin >> c1 >> c2; unsigned h, m, s; unsigned diff = (c2 - c1); if (diff % 100 >= 50)//˳β c = 1; else c = 0; diff = diff / 100 + c; s = diff % 60; diff /= 60; m = diff % 60; diff /= 60; h = diff; cout << setfill('0')<<setw(2) << h << setw(1) << ':' << setw(2) << m << setw(1) << ':' << setw(2) << s; }
true
dd4c43c277bbb8eff9c7df3e0a8ab9f12ad7d020
C++
ftlka/data-structures
/week 3/mergingTables.cpp
UTF-8
2,964
3.75
4
[]
no_license
/* There are n tables stored in some database. The tables are numbered from 1 to n. All tables share the same set of columns. Each table contains either several rows with real data or a symbolic link to another table. Initially, all tables contain data, and i-th table has r_i rows. You need to perform m of the following operations: 1. Consider table number destination_i. Traverse the path of symbolic links to get to the data. That is, while destination_i contains a symbolic link instead of real data do destination_i ← symlink (destination_i). 2. Consider the table number source_i and traverse the path of symbolic links from it in the same manner as for destination_i. 3. Now, destination_i and source_i are the numbers of two tables with real data. If destination_i != source_i, copy all the rows from table source_i to table destination_i, then clear the table source_i and instead of real data put a symbolic link to destination_i into it. 4. Print the maximum size among all n tables (recall that size is the number of rows in the table). If the table contains only a symbolic link, its size is considered to be 0. */ #include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> #include <iostream> using namespace std; struct DisjointSetsElement { int size, parent, rank; DisjointSetsElement(int size = 0, int parent = -1, int rank = 0): size(size), parent(parent), rank(rank) {} }; struct DisjointSets { int size; int max_table_size; vector<DisjointSetsElement> sets; DisjointSets(int size): size(size), max_table_size(0), sets(size) { for (int i = 0; i < size; i++) { sets[i].parent = i; } } int getParent(int table) { if (sets[table].parent == table) { return table; } return getParent(sets[table].parent); } void unite(int rootIdx, int childIdx) { DisjointSetsElement root = sets[rootIdx]; DisjointSetsElement child = sets[childIdx]; sets[childIdx].parent = rootIdx; sets[rootIdx].rank = max(sets[rootIdx].rank, sets[childIdx].rank + 1); sets[rootIdx].size += sets[childIdx].size; if (sets[rootIdx].size > max_table_size) { max_table_size = sets[rootIdx].size; } } void merge(int destination, int source) { int realDestination = getParent(destination); int realSource = getParent(source); if (realDestination != realSource) { if (sets[realDestination].rank >= sets[realSource].rank) { unite(realDestination, realSource); } else { unite(realSource, realDestination); } } } }; int main() { int n, m; cin >> n >> m; DisjointSets tables(n); for (auto& table : tables.sets) { cin >> table.size; tables.max_table_size = max(tables.max_table_size, table.size); } for (int i = 0; i < m; i++) { int destination, source; cin >> destination >> source; --destination; --source; tables.merge(destination, source); cout << tables.max_table_size << endl; } return 0; }
true
e97ed5abe0b4c3dc30104fd1db55f89519338865
C++
rlavaee/sesc-src
/libll/HeapManager.cpp
UTF-8
4,445
2.71875
3
[]
no_license
#include "HeapManager.h" #include "ReportGen.h" HeapManager::HeapManager(Address base, size_t size) : refCount(0), begAddr(base), endAddr(base){ // The base and the size need to be non-zero multiples of MinBlockSize I(base&&!(base&MinBlockMask)); I(size&&!(size&MinBlockMask)); BlockInfo *blockInfo=new BlockInfo(base,size); freeByAddr.insert(BlockInfo(base,size)); freeBySize.insert(BlockInfo(base,size)); } HeapManager::~HeapManager(void){ Report::field("HeapManager:maxHeapSize=0x%08lx",endAddr-begAddr); } Address HeapManager::allocate(size_t size) { size_t blockSize=roundUp(size); BlocksBySize::iterator sizeIt=freeBySize.lower_bound(BlockInfo(0,blockSize)); if(sizeIt==freeBySize.end()) return 0; Address blockBase=sizeIt->addr; size_t foundSize=sizeIt->size; I(foundSize>=blockSize); BlocksByAddr::iterator addrIt=freeByAddr.find(BlockInfo(blockBase,foundSize)); freeBySize.erase(sizeIt); freeByAddr.erase(addrIt); busyByAddr.insert(BlockInfo(blockBase,size)); if(foundSize>blockSize){ freeBySize.insert(BlockInfo(blockBase+blockSize,foundSize-blockSize)); freeByAddr.insert(BlockInfo(blockBase+blockSize,foundSize-blockSize)); } if(blockBase+blockSize>(size_t)endAddr) endAddr=blockBase+blockSize; return blockBase; } Address HeapManager::allocate(Address addr, size_t size) { size_t blockSize=roundUp(size); // Find block with next strictly higher address, then go to block before that BlocksByAddr::iterator addrIt=freeByAddr.upper_bound(BlockInfo(addr,blockSize)); if(addrIt==freeByAddr.begin()){ // All available blocks are at higher addresses than what we want return allocate(size); } addrIt--; Address foundAddr=addrIt->addr; // Start of the block should be no higher than what we want I(foundAddr<=addr); size_t foundSize=addrIt->size; // End of the block should be no lower than what we want if(foundAddr+foundSize<addr+blockSize){ // Block at requested location is not long enough return allocate(size); } BlocksBySize::iterator sizeIt=freeBySize.find(*addrIt); I(sizeIt!=freeBySize.end()); I((sizeIt->addr==foundAddr)&&(sizeIt->size==foundSize)); freeByAddr.erase(addrIt); freeBySize.erase(sizeIt); if(foundAddr<addr){ size_t frontChop=addr-foundAddr; freeBySize.insert(BlockInfo(foundAddr,frontChop)); freeByAddr.insert(BlockInfo(foundAddr,frontChop)); foundSize-=frontChop; foundAddr+=frontChop; I(foundAddr==addr); } I(foundSize>=blockSize); if(foundSize>blockSize){ size_t backChop=foundSize-blockSize; freeBySize.insert(BlockInfo(foundAddr+blockSize,backChop)); freeByAddr.insert(BlockInfo(foundAddr+blockSize,backChop)); foundSize-=backChop; I(foundSize==blockSize); } busyByAddr.insert(BlockInfo(addr,blockSize)); if(addr+blockSize>(size_t)endAddr) endAddr=addr+blockSize; return addr; } size_t HeapManager::deallocate(Address addr) { // Find block in the busy set and remove it BlocksByAddr::iterator busyIt=busyByAddr.find(BlockInfo(addr,0)); I(busyIt!=busyByAddr.end()); Address blockAddr=busyIt->addr; size_t oldBlockSize=busyIt->size; size_t blockSize=roundUp(oldBlockSize); I(blockAddr==addr); busyByAddr.erase(busyIt); BlocksByAddr::iterator addrIt=freeByAddr.upper_bound(BlockInfo(blockAddr,0)); I((addrIt==freeByAddr.end())||(blockAddr+(Address)blockSize<=addrIt->addr)); // Try to merge with the next free block if((addrIt!=freeByAddr.end())&&(blockAddr+(Address)blockSize==addrIt->addr)){ blockSize+=addrIt->size; freeBySize.erase(*addrIt); freeByAddr.erase(addrIt); // Erasing from a set invalidates iterators, so reinitialize addrIt addrIt=freeByAddr.upper_bound(BlockInfo(blockAddr,0)); I((addrIt==freeByAddr.end())||(blockAddr+(Address)blockSize<addrIt->addr)); } // Try to merge with the previous free block if(addrIt!=freeByAddr.begin()){ addrIt--; I(addrIt->addr+(Address)(addrIt->size)<=blockAddr); if(addrIt->addr+(Address)(addrIt->size)==blockAddr){ blockAddr=addrIt->addr; blockSize+=addrIt->size; freeBySize.erase(*addrIt); freeByAddr.erase(addrIt); } } freeBySize.insert(BlockInfo(blockAddr,blockSize)); freeByAddr.insert(BlockInfo(blockAddr,blockSize)); return oldBlockSize; }
true
46aed592408aece16b8e63479fefea2be99f9501
C++
frontseat-astronaut/Competitive-Programming
/UVa/10443.cpp
UTF-8
1,628
2.59375
3
[]
no_license
#include<iostream> using namespace std; int main() { int t; cin>>t; while(t--) { int r,c,n; cin>>r>>c>>n; char grid[2][r][c]; for(int i=0; i<r; ++i) for(int j=0; j<c; ++j) cin>>grid[0][i][j]; int g=0, k=0; for(k=0; k<n; ++k, g=(g+1)%2) { for(int i=0; i<r; ++i) { for(int j=0; j<c; ++j) { grid[!g][i][j]=grid[g][i][j]; if(i+1<r) { if(grid[g][i][j]=='R' && grid[g][i+1][j]=='P') grid[!g][i][j]='P'; else if(grid[g][i][j]=='P' && grid[g][i+1][j]=='S') grid[!g][i][j]='S'; else if(grid[g][i][j]=='S' && grid[g][i+1][j]=='R') grid[!g][i][j]='R'; } if(j+1<c) { if(grid[g][i][j]=='R' && grid[g][i][j+1]=='P') grid[!g][i][j]='P'; else if(grid[g][i][j]=='P' && grid[g][i][j+1]=='S') grid[!g][i][j]='S'; else if(grid[g][i][j]=='S' && grid[g][i][j+1]=='R') grid[!g][i][j]='R'; } if(i-1>=0) { if(grid[g][i][j]=='R' && grid[g][i-1][j]=='P') grid[!g][i][j]='P'; else if(grid[g][i][j]=='P' && grid[g][i-1][j]=='S') grid[!g][i][j]='S'; else if(grid[g][i][j]=='S' && grid[g][i-1][j]=='R') grid[!g][i][j]='R'; } if(j-1>=0) { if(grid[g][i][j]=='R' && grid[g][i][j-1]=='P') grid[!g][i][j]='P'; else if(grid[g][i][j]=='P' && grid[g][i][j-1]=='S') grid[!g][i][j]='S'; else if(grid[g][i][j]=='S' && grid[g][i][j-1]=='R') grid[!g][i][j]='R'; } } } } for(int i=0; i<r; ++i) { for(int j=0; j<c; ++j) cout<<grid[g][i][j]; cout<<endl; } if(t) cout<<endl; } }
true
52295d294701b7ebee921b4d84a8e6e320b78b2a
C++
GABRIELMUTTI/mtecs
/include/mtecs/group/GroupManager.hpp
UTF-8
815
2.59375
3
[]
no_license
#pragma once #include "mtecs/group/Group.hpp" #include "mtecs/entity/EntityManager.hpp" #include "mtecs/component/ComponentManager.hpp" namespace mtecs::internal { class GroupManager { private: std::vector<Group*> groups; const EntityManager& entityManager; const ComponentManager& componentManager; void createGroup(const Mask& mask); public: GroupManager(const EntityManager& entityManager, const ComponentManager& componentManager); void updateGroups(); template<class ... Types> Group* getGroup() { Mask mask = componentManager.getMask<Types ...>(); for (uint i = 0; i < groups.size(); i++) { if (groups[i]->getMask() == mask) { return groups[i]; } } createGroup(mask); return groups[groups.size() - 1]; } }; }
true
fa0f0d5b25573b62cba4e9389a8abd1743dd6b2e
C++
liweiliv/DBStream
/sqlParserV2/token.cpp
UTF-8
536
2.6875
3
[]
no_license
#include "token.h" namespace SQL_PARSER { DLL_EXPORT bool token::compare(const token& t) { if (type !=t.type) return false; switch (type) { case tokenType::identifier: break; case tokenType::keyword: case tokenType::specialCharacter: case tokenType::symbol: if (value.compare(t.value) != 0) return false; break; case tokenType::literal: { if (static_cast<literal*>(this)->lType != static_cast<const literal*>(&t)->lType) return false; break; } default: break; } return true; } }
true
f83e88bb07484dbcf902991f9be671b6b724bb41
C++
cats9rule/sp-lab
/BinarnaStabla/BinarnaStabla/Stack.h
UTF-8
216
2.90625
3
[]
no_license
#pragma once #include "BSTNode.h" class Stack { public: virtual void push(BSTNode* el) = 0; virtual BSTNode* pop() = 0; virtual bool isEmpty() = 0; virtual bool isFull() = 0; virtual int numOfElements() = 0; };
true
1bc6adbdec745cd2bb5a27e3d360ef4567f032bb
C++
damansh/Arduino-Code
/Appmotor/Appmotor.ino
UTF-8
1,453
2.578125
3
[]
no_license
int ltPowerOne = 6; int ltFwdOne = 7; int ltBwdOne = 8; int ltPowerTwo = 1; int ltFwdTwo = 2; int ltBwdTwo = 3; int LEDpin = 13; int estado ; void setup() { Serial.begin(9600); pinMode(ltPowerOne, OUTPUT); pinMode(ltFwdOne, OUTPUT); pinMode(ltBwdOne, OUTPUT); pinMode(ltPowerTwo, OUTPUT); pinMode(ltFwdTwo, OUTPUT); pinMode(ltBwdTwo, OUTPUT); } void loop() { estado = Serial.read(); if(Serial.available()>0){ // lee el bluetooth y almacena en estado } else if(estado=='a'){ // Boton desplazar al Frente digitalWrite (LEDpin, HIGH); digitalWrite(ltFwdOne, HIGH); digitalWrite(ltFwdTwo, LOW); delay(100); } else if(estado=='b'){ // Boton IZQ digitalWrite (LEDpin, LOW); digitalWrite(ltFwdOne, LOW); digitalWrite(ltFwdTwo, LOW); digitalWrite(ltBwdOne, HIGH); digitalWrite(ltBwdTwo, HIGH); delay(100); } else if(estado=='c'){ // Boton Parar digitalWrite (LEDpin, HIGH); digitalWrite (ltFwdOne, HIGH); digitalWrite (ltFwdTwo, LOW); digitalWrite (ltBwdOne, LOW); digitalWrite (ltBwdTwo, LOW); delay (100); } else if(estado=='d'){ // Boton DER digitalWrite (LEDpin, LOW); digitalWrite (ltFwdOne, LOW); digitalWrite (ltFwdTwo, HIGH); digitalWrite (ltBwdOne, LOW); digitalWrite (ltBwdTwo, LOW); delay (100); } else if(estado=='e'){ // Boton Reversa digitalWrite(ltFwdOne, LOW); digitalWrite(ltFwdTwo, HIGH); delay (100); } }
true
b6e633ee9b0e8cbe0c374ce540923463de839158
C++
hvariant/LICAgent
/demo/controller/main.cc
UTF-8
2,922
2.53125
3
[]
no_license
#include "yapcontroller.h" #include "parser.h" #include <string> #include <stdlib.h> using std::string; //#define KIF_FILE "tic.kif" //#define PL_FILE "tic.pl" //#define COMPILED_GGP "tic.ggp" //#define KIF_FILE "pentago.kif" //#define PL_FILE "pentago.pl" //#define COMPILED_GGP "pentago.ggp" //#define KIF_FILE "buttons.kif" //#define PL_FILE "buttons.pl" //#define COMPILED_GGP "buttons.ggp" //#define KIF_FILE "3-puzzle.kif" //#define PL_FILE "3-puzzle.pl" //#define COMPILED_GGP "3-puzzle.ggp" #define GGP_EXTENSION "ggp.extensions.pl" int main(int argc,char** argv){ string KIF_FILE = argv[1]; KIF_FILE += ".kif"; string PL_FILE = argv[1]; PL_FILE += ".pl"; string COMPILED_GGP = argv[1]; COMPILED_GGP += ".ggp"; std::ifstream in(KIF_FILE); string input((std::istreambuf_iterator<char>(in)),std::istreambuf_iterator<char>()); //ref: the most vexing parse problem? gdl* game = parser::parse_game(input); FILE* fout = fopen(PL_FILE.c_str(),"w"); game->print(fout); //game->printS(stdout); fclose(fout); controller* con = new yapcontroller(game,GGP_EXTENSION,PL_FILE.c_str(),COMPILED_GGP.c_str()); if(!con->init()){ fprintf(stderr,"error initiating controller!\n"); delete con; delete game; return 1; } vector<string> roles = con->roles(); printf("roles:\n"); for(int i=0;i<roles.size();i++) printf("%s ",roles[i].c_str()); printf("\n\n"); srand(time(NULL)); while(!con->terminal()){ printf("===========================================\n"); printf("get_current_state:\n"); terms* cur_state = con->state(); controller::print_terms(cur_state,stdout); controller::free_terms(cur_state); printf("====================\n"); terms j_move; vector<terms*>* all_moves = con->all_moves(); vector<terms*>::iterator it = all_moves->begin(); while(it != all_moves->end()){ terms* moves = *it; int i = rand() % moves->size(); j_move.push_back((*moves)[i]); it++; } printf("====================\n"); printf("j_move:\n"); controller::print_terms(&j_move,stdout); printf("====================\n"); con->make_move(j_move); controller::free_moves(all_moves); } printf("====================\n"); printf("terminal state:\n"); terms* cur_state = con->state(); controller::print_terms(cur_state,stdout); controller::free_terms(cur_state); printf("====================\n"); for(int i=0;i<roles.size();i++){ using namespace std; int gv = con->goal(roles[i]); cout<<"(goal " << roles[i] << " " << gv << ")" << endl; } printf("deleting controller\n"); delete con; delete game; //printf("game(%x)\n",(int)(game)); return 0; }
true
34f56e49d2b403f779d2b95a811a9e744e4abe66
C++
TCC-Grupo-19/Sistema-IoT-de-Tratamento-de-gua-de-Chuva-para-Mini-hortas-Inteligentes
/TCC - GRUPO 19/Codigo_DHT11_ThingSpeak/Codigo_DHT11_ThingSpeak.ino
UTF-8
1,394
2.6875
3
[]
no_license
#include "ThingSpeak.h" #include <WiFi.h> #include <Wire.h> #include "DHT.h" #define DHTPIN 23 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); char ssid[] = "NAME"; // Nome da Rede que será usada char pass[] = "PASSWORD"; // Senha da Rede que será usada WiFiClient client; unsigned long myChannelNumber = 000000; //update const char * myWriteAPIKey = "KEY"; //Key do canal no ThingSpeak void setup() { Serial.begin(115200); //Inicializa dht.begin(); //Inicializa o sensor WiFi.mode(WIFI_STA); //Seleciona o modo STA para o WiFi ThingSpeak.begin(client); // Inicializa o ThingSpeak } void loop() { // Conectar ou reconectar ao WiFi if(WiFi.status() != WL_CONNECTED){ Serial.print("Conectando ao SSID: "); while(WiFi.status() != WL_CONNECTED){ WiFi.begin(ssid, pass); Serial.print("."); delay(5000); } Serial.println("\nConnected."); } float h = dht.readHumidity(); float t = dht.readTemperature(); Serial.print("Umidade do Ar: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperatura: "); Serial.print(t); Serial.println(" °C "); ThingSpeak.setField(1, t); ThingSpeak.setField(2, h); int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey); if(x == 200){ Serial.println("Atualização bem sucedida"); } else{ Serial.println("Problema ao atualizar. HTTP error code " + String(x)); } delay(20000); //
true
a2ed62990f85f53e160b4342fe5ad40de76f1438
C++
loohcs/LookForPlace
/LookForPlace/include/htl/htl_uninitialized.h
UTF-8
1,979
2.734375
3
[]
no_license
/* * htl-lite - a basic data structures and algorithms. * Copyright (C) 2009 leon hong. All rights reserved. * authors: * leon hong <codeblocker@gmail.com> */ #ifndef __HTL_UNINITIALIZED__ #define __HTL_UNINITIALIZED__ #include "htl_construct.h" __HTL_BEGIN_NAMESPACE template<typename ForwardIterator, typename Size, typename T> ForwardIterator uninitalized_fill_n(ForwardIterator first, Size n, const T& x) { for (; n > 0; --n, ++first) construct(&*first, x); return first; } template<typename ForwardIterator, typename T> void uninitalized_fill(ForwardIterator first, ForwardIterator last, const T& x) { for (; first != last; ++first) construct(&*first, x); } template<typename InputIterator, typename ForwardIterator> inline ForwardIterator uninitalized_copy(InputIterator first, InputIterator last, ForwardIterator result) { for (; first != last; ++first, ++result) construct(&*result, *first); return result; } template<typename InputIterator, typename OutputIterator> inline OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result) { for (; first != last; ++first, ++result) *result = *first; return result; } template<typename InputIterator, typename OutputIterator> inline OutputIterator copy_backward(InputIterator first, InputIterator last, OutputIterator result) { for (; first != last; --last, --result) { *(result-1) = *(last-1); } return result; } template<typename InputIterator, typename T> void fill(InputIterator first, InputIterator last, const T& value) { for (; first != last; ++first) *first = value; } template<typename T> T htl_max(const T& a, const T& b) { return a > b ? a : b; } __HTL_END_NAMESPACE #endif
true
e0225e95b0132c1bce8ce28e5e9e62c72fd7ca52
C++
dgg5503/Game-Graphics-Programming-Project
/LightRenderer.cpp
UTF-8
9,598
2.640625
3
[]
no_license
#include "LightRenderer.h" // -------------------------------------------------------- // Constructor // // Creates a light renderer which will use the context and // device found in the given renderer. // // renderer - Reference to renderer object in which to render // light to. // -------------------------------------------------------- LightRenderer::LightRenderer(Renderer & renderer) : renderer(renderer), lights(32), lightText(nullptr), lightRTV(nullptr), lightSRV(nullptr), pointLightMesh(nullptr), spotLightMesh(nullptr), pointLightPS(nullptr), directionalLightPS(nullptr), lightVS(nullptr), quadVS(nullptr) { pointLights.reserve(16); directionalLights.reserve(16); } // -------------------------------------------------------- // Destructor // -------------------------------------------------------- LightRenderer::~LightRenderer() { } // -------------------------------------------------------- // Initializes the light renderer. // // quadVS - The vertex shader which draws a full screen quad. // width - Width of screen. // height - Height of screen. // // returns - Result of initialization. // -------------------------------------------------------- HRESULT LightRenderer::Initialize(SimpleVertexShader* quadVS, unsigned int width, unsigned int height) { HRESULT hr; // Create texture, rtv, srv D3D11_TEXTURE2D_DESC renderTargetTextDesc = {}; renderTargetTextDesc.Width = width; renderTargetTextDesc.Height = height; renderTargetTextDesc.MipLevels = 1; renderTargetTextDesc.ArraySize = 1; renderTargetTextDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; renderTargetTextDesc.Usage = D3D11_USAGE_DEFAULT; renderTargetTextDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; renderTargetTextDesc.CPUAccessFlags = 0; renderTargetTextDesc.MiscFlags = 0; renderTargetTextDesc.SampleDesc.Count = 1; renderTargetTextDesc.SampleDesc.Quality = 0; hr = renderer.device->CreateTexture2D(&renderTargetTextDesc, nullptr, &lightText); if (FAILED(hr)) return hr; D3D11_RENDER_TARGET_VIEW_DESC renderTargetViewDesc = {}; renderTargetViewDesc.Format = renderTargetTextDesc.Format; renderTargetViewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; renderTargetViewDesc.Texture2D.MipSlice = 0; hr = renderer.device->CreateRenderTargetView(lightText, &renderTargetViewDesc, &lightRTV); if (FAILED(hr)) return hr; D3D11_SHADER_RESOURCE_VIEW_DESC renderTargetSRVDesc = {}; renderTargetSRVDesc.Format = renderTargetTextDesc.Format; renderTargetSRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; renderTargetSRVDesc.Texture2D.MipLevels = 1; renderTargetSRVDesc.Texture2D.MostDetailedMip = 0; hr = renderer.device->CreateShaderResourceView(lightText, &renderTargetSRVDesc, &lightSRV); if (FAILED(hr)) return hr; // Load point light mesg // TODO: loading a mesh in twice, not good... pointLightMesh = renderer.CreateMesh("./Assets/Models/sphere.obj"); if (!pointLightMesh) return E_FAIL; // Load shaders pointLightPS = renderer.CreateSimplePixelShader(); if (!pointLightPS->LoadShaderFile(L"./Assets/Shaders/DeferredPointLightPS.cso")) return E_FAIL; directionalLightPS = renderer.CreateSimplePixelShader(); if (!directionalLightPS->LoadShaderFile(L"./Assets/Shaders/DeferredDirectionalLightPS.cso")) return E_FAIL; lightVS = renderer.CreateSimpleVertexShader(); if (!lightVS->LoadShaderFile(L"./Assets/Shaders/DeferredLightVS.cso")) return E_FAIL; if (!(this->quadVS = quadVS)) return E_FAIL; return S_OK; } // -------------------------------------------------------- // Cleans up and shutsdown this light renderer object. // // returns - Result of shutdown. // -------------------------------------------------------- HRESULT LightRenderer::Shutdown() { // Free all lights for (auto it = lights.cbegin(); it != lights.cend(); it++) if(it->second) delete it->second; // Free text,rtv,srv if (lightText) { lightText->Release(); } if (lightRTV) { lightRTV->Release(); } if (lightSRV) { lightSRV->Release(); } // Free meshs if (pointLightMesh) { delete pointLightMesh; } // Free Shaders if (pointLightPS) { delete pointLightPS; } if (directionalLightPS) { delete directionalLightPS; } if (lightVS) { delete lightVS; } // Do not free QuadVS, that is handled by the renderer. return S_OK; } // -------------------------------------------------------- // Creates a point light object. // // NOTE: The name of the point light must not already exist // in the light renderer! // // attenuation - Attenuation type for this point light. // name - Unique name for this point light. // autostage - Whether or not the light should be staged for // rendering on creation. // // return - Pointer to point light object. // -------------------------------------------------------- PointLight * const LightRenderer::CreatePointLight(PointLightAttenuation attenuation, std::string name, bool autostage) { // Ensure name doesnt already exist assert(lights.count(name) == 0); PointLight* pointLight = new PointLight(attenuation); lights[name] = pointLight; if (autostage) pointLights.push_back(pointLight); return pointLight; } // -------------------------------------------------------- // Creates a directional light object. // // NOTE: The name of the directional light must not already exist // in the light renderer! // // name - Unique name for this directional light. // autostage - Whether or not the light should be staged for // rendering on creation. // // return - Pointer to directional light object. // -------------------------------------------------------- DirectionalLight * const LightRenderer::CreateDirectionalLight(std::string name, bool autostage) { // Ensure name doesnt already exist assert(lights.count(name) == 0); DirectionalLight* directionalLight = new DirectionalLight(); lights[name] = directionalLight; if (autostage) directionalLights.push_back(directionalLight); return directionalLight; } // -------------------------------------------------------- // Renders all stages lights to this light renderer's light // RTV according to depth found in the renderer's // depth stencil view. // // NOTE: D3D11 state values are not preserved. // // camera - Camera to use when rendering lights. // -------------------------------------------------------- void LightRenderer::Render(const Camera * const camera) { //renderer.depthStencilView // Set render target renderer.context->OMSetRenderTargets(1, &lightRTV, renderer.depthStencilView); renderer.context->OMSetDepthStencilState(renderer.lightStencilState, 0); // Mesh related information const Mesh* currMesh = nullptr; ID3D11Buffer* currVertBuff = nullptr; const UINT stride = sizeof(Vertex); const UINT offset = 0; // Set once vertex shader information lightVS->SetMatrix4x4("view", camera->GetViewMatrix()); lightVS->SetMatrix4x4("projection", camera->GetProjectionMatrix()); // Iterate through all point lights // Set SRVs and other const information once pointLightPS->SetShaderResourceView("worldPosTexture", renderer.targetSRVs[1]); pointLightPS->SetShaderResourceView("normalsTexture", renderer.targetSRVs[2]); pointLightPS->SetSamplerState("deferredSampler", renderer.targetSampler); pointLightPS->SetFloat2("screenSize", XMFLOAT2(renderer.viewport.Width, renderer.viewport.Height)); // Setup mesh information currMesh = pointLightMesh; currVertBuff = pointLightMesh->GetVertexBuffer(); renderer.context->IASetVertexBuffers(0, 1, &currVertBuff, &stride, &offset); renderer.context->IASetIndexBuffer(currMesh->GetIndexBuffer(), DXGI_FORMAT_R32_UINT, 0); for (auto it = pointLights.cbegin(); it != pointLights.cend(); it++) { PointLight* const currPL = (*it); // Update info... currPL->PrepareForShader(); // set position lightVS->SetMatrix4x4("world", currPL->transform.GetWorldMatrix()); // set light specific pointLightPS->SetStruct("diffuse", &currPL->pointLightLayout, sizeof(PointLightLayout)); // upload shader properties pointLightPS->CopyAllBufferData(); lightVS->CopyAllBufferData(); pointLightPS->SetShader(); lightVS->SetShader(); // draw renderer.context->DrawIndexed(currMesh->GetIndexCount(), 0, 0); } // Iterate through all spot lights // Ensure zbuffer off renderer.context->OMSetDepthStencilState(nullptr, 0); // Iterate through all directional lights // Setup mesh information renderer.context->IASetVertexBuffers(0, 0, nullptr, nullptr, nullptr); renderer.context->IASetIndexBuffer(nullptr, (DXGI_FORMAT)0, 0); // Set SRVs and other const information once directionalLightPS->SetShaderResourceView("worldPosTexture", renderer.targetSRVs[1]); directionalLightPS->SetShaderResourceView("normalsTexture", renderer.targetSRVs[2]); directionalLightPS->SetSamplerState("deferredSampler", renderer.targetSampler); // Set quad VS once quadVS->SetShader(); for (auto it = directionalLights.cbegin(); it != directionalLights.cend(); it++) { DirectionalLight* const currDL = (*it); // set light specific directionalLightPS->SetStruct("diffuse", &currDL->directionalLightLayout, sizeof(DirectionalLightLayout)); // upload shader properties directionalLightPS->CopyAllBufferData(); directionalLightPS->SetShader(); // draw quad renderer.context->Draw(3, 0); } } // -------------------------------------------------------- // Clears the light RTV. // -------------------------------------------------------- void LightRenderer::ClearRTV() { const float color[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; renderer.context->ClearRenderTargetView(lightRTV, color); }
true
0ce6f5701285c6fcbe42c927adf4c36c61f4864d
C++
ragrag/Competitive-Programming-Library
/Problems(UVA_CF)/Codeforces/9A.cpp
UTF-8
802
2.609375
3
[]
no_license
#include <vector> #include <iostream> #include <algorithm> #include <string> #include <set> using namespace std; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<ii> vii; int main() { int x, y; cin >> x >> y; vector <int> ar; for (int i = 0; i < 6; i++) { if (i + 1 >= max(x, y)) { ar.push_back(i + 1); } } if (ar.size() == 6) { cout << "1/1" << endl; goto end; } if (ar.size() == 0) { cout << "0/1" << endl; goto end; } if (ar.size() == 5) cout << "5/6" << endl; if (ar.size() == 3) { cout << "1/2" << endl; } if (ar.size() == 4) { cout << "2/3" << endl; } if (ar.size() == 1) { cout << "1/6" << endl; } if (ar.size() == 2) { cout << "1/3" << endl; } end: int ll; return 0; }
true
1dbdbe97c4eb4df378efb188e649a106368fac6b
C++
adityajain17/CPP-Codes
/OCTAL_TO_DECIMAL.cpp
UTF-8
409
3.75
4
[]
no_license
/*WAP to convert from octal format to decimal format using do-while loop*/ #include<iostream> #include<math.h> using namespace std; int main() { int octal,d,c=0;double dec=0; cout<<"Enter the number in octal "<<endl; cin>>octal; do { d=octal%10; dec=dec+d*pow(8,c); c++; octal=octal/10; } while(octal>0); cout<<"The number in decimal format is = "<<dec<<endl; return 0; }
true
e6a2f0e9f64a0deaef0d0331b2a6466673e2a480
C++
bhavya2026/practice-questions
/linked list/KthElement2pointer.cpp
UTF-8
1,245
3.5
4
[]
no_license
#include<iostream> using namespace std; struct node{ int data; node *next; }*head=NULL; void create(){ int tests,x; do{ node *newnode=new node; node *temp; cout<<"\t\t\t\tenter the value "; cin>>x; newnode->data=x; newnode->next=NULL; if(head==NULL){ head=newnode; temp=newnode; } else{ temp->next=newnode; temp=newnode; } cout<<"\n\t\t\t\tpress any key to continue\n\t\t\t\tpress 0 to stop"; cin>>tests; } while(tests); } int lengthsll(){ if(head==NULL) return -1; node *temp=head; int count=0; while(temp!=NULL){ count++; temp=temp->next; } return count; } void kthelement(int k){ if(head==NULL) cout<<"list unavailable"; if(k>lengthsll()) cout<<"wrong input"; else{ int i=0; node *first=head,*second=head; while(i<k){ first=first->next; i++; } while(first!=NULL){ first=first->next; second=second->next; } cout<<second->data; } } main(){ create(); kthelement(8); return 0; }
true
085573da99f603966b4e4b26c7de9301aeb84dbb
C++
elfmedy/vvdn_tofa
/mdk_release_18.08.10_general_purpose/mdk/common/components/kernelLib/MvCV/kernels/bitwiseAndMask/unittest/bitwiseAndMask_unittest.cpp
UTF-8
8,352
2.890625
3
[]
no_license
//bitwiseAndMask kernel test //Asm function prototype: // void bitwiseAndMask_asm(u8** in1, u8** in2, u8** out, u8** mask, u32 width); //Asm test function prototype: // void bitwiseAndMask_asm_test(unsigned char **input1, unsigned char **input2, unsigned char **output, unsigned char **mask, unsigned int width); //C function prototype: // void bitwiseAndMask(u8** in1, u8** in2, u8** out, u8** mask, u32 width); //width - width of input line //in1 - first image //in2 - the second image //mask - mask //out - the output line #include "gtest/gtest.h" #include "bitwiseAndMask.h" #include "bitwiseAndMask_asm_test.h" #include "RandomGenerator.h" #include "InputGenerator.h" #include "UniformGenerator.h" #include "TestEventListener.h" #include "ArrayChecker.h" #include <ctime> class bitwiseAndMaskTest : public ::testing::Test { protected: virtual void SetUp() { randGen.reset(new RandomGenerator); uniGen.reset(new UniformGenerator); inputGen.AddGenerator(std::string("random"), randGen.get()); inputGen.AddGenerator(std::string("uniform"), uniGen.get()); } unsigned char** inLine1; unsigned char** inLine2; unsigned char** mask; unsigned char** outLineC; unsigned char** outLineAsm; unsigned char** outLineExpected; unsigned int width; InputGenerator inputGen; RandomGenerator randomGen; ArrayChecker outputCheck; std::auto_ptr<RandomGenerator> randGen; std::auto_ptr<UniformGenerator> uniGen; virtual void TearDown() {} }; TEST_F(bitwiseAndMaskTest, TestUniformInput7and11eq3Mask1) { width = 240; inputGen.SelectGenerator("uniform"); inLine1 = inputGen.GetLines(width, 1, 7); inLine2 = inputGen.GetLines(width, 1, 11); mask = inputGen.GetLines(width, 1, 1); outLineExpected = inputGen.GetLines(width, 1, 3); outLineC = inputGen.GetEmptyLines(width, 1); outLineAsm = inputGen.GetEmptyLines(width, 1); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineExpected[0], outLineC[0], width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInputMinWidth8Mask1) { width = 8; inputGen.SelectGenerator("random"); inLine1 = inputGen.GetLines(width, 1, 0, 255); inLine2 = inputGen.GetLines(width, 1, 0, 255); inputGen.SelectGenerator("uniform"); mask = inputGen.GetLines(width, 1, 1); outLineC = inputGen.GetEmptyLines(width, 1); outLineAsm = inputGen.GetEmptyLines(width, 1); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInputWidth16Mask1) { width = 16; inputGen.SelectGenerator("random"); inLine1 = inputGen.GetLines(width, 1, 0, 255); inLine2 = inputGen.GetLines(width, 1, 0, 255); inputGen.SelectGenerator("uniform"); mask = inputGen.GetLines(width, 1, 1); outLineC = inputGen.GetEmptyLines(width, 1); outLineAsm = inputGen.GetEmptyLines(width, 1); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInputMaxWidth1920Mask1) { width = 1920; inputGen.SelectGenerator("random"); inLine1 = inputGen.GetLines(width, 1, 0, 255); inLine2 = inputGen.GetLines(width, 1, 0, 255); inputGen.SelectGenerator("uniform"); mask = inputGen.GetLines(width, 1, 1); outLineC = inputGen.GetEmptyLines(width, 1); outLineAsm = inputGen.GetEmptyLines(width, 1); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInputRandomWidthMask1) { width = randGen->GenerateUInt(8, 1921, 8); width = (width >> 3)<<3; //(line width have to be mutiple of 8) inputGen.SelectGenerator("random"); inLine1 = inputGen.GetLines(width, 1, 0, 255); inLine2 = inputGen.GetLines(width, 1, 0, 255); inputGen.SelectGenerator("uniform"); mask = inputGen.GetLines(width, 1, 1); outLineC = inputGen.GetEmptyLines(width, 1); outLineAsm = inputGen.GetEmptyLines(width, 1); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInputWidth16Mask0) { width = 16; inputGen.SelectGenerator("random"); inLine1 = inputGen.GetLines(width, 1, 0, 255); inLine2 = inputGen.GetLines(width, 1, 0, 255); inputGen.SelectGenerator("uniform"); mask = inputGen.GetLines(width, 1, 0); outLineC = inputGen.GetLines(width, 1, 0); outLineAsm = inputGen.GetLines(width, 1, 0); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInput1Mask01) { width = 240; inputGen.SelectGenerator("uniform"); inLine1 = inputGen.GetLines(width, 1, 255); outLineC = inputGen.GetLines(width, 1, 0); outLineAsm = inputGen.GetLines(width, 1, 0); mask = inputGen.GetLines(width, 1, 0); for(unsigned int i = 0; i < width; i=i+2) { mask[0][i] = 1; } inputGen.SelectGenerator("random"); inLine2 = inputGen.GetLines(width, 1, 0, 255); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outLineExpected = inLine2; for(unsigned int i = 1; i < width; i=i+2) { outLineExpected[0][i] = 0; } outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); outputCheck.CompareArrays(outLineC[0], outLineExpected[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInputMinWidth8MaskRandom) { width = 8; inputGen.SelectGenerator("random"); inLine1 = inputGen.GetLines(width, 1, 0, 255); inLine2 = inputGen.GetLines(width, 1, 0, 255); mask = inputGen.GetLines(width, 1, 0, 2); inputGen.SelectGenerator("uniform"); outLineC = inputGen.GetLines(width, 1, 0); outLineAsm = inputGen.GetLines(width, 1, 0); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); } TEST_F(bitwiseAndMaskTest, TestRandomInputMaxWidth1920MaskRandom) { width = 1920; inputGen.SelectGenerator("random"); inLine1 = inputGen.GetLines(width, 1, 0, 255); inLine2 = inputGen.GetLines(width, 1, 0, 255); mask = inputGen.GetLines(width, 1, 0, 50); inputGen.SelectGenerator("uniform"); outLineC = inputGen.GetLines(width, 1, 0); outLineAsm = inputGen.GetLines(width, 1, 0); mvcvBitwiseAndMask(inLine1, inLine2, outLineC, mask, width); bitwiseAndMask_asm_test(inLine1, inLine2, outLineAsm, mask, width); RecordProperty("CyclePerPixel", bitwiseAndMaskCycleCount / width); outputCheck.CompareArrays(outLineC[0], outLineAsm[0], width); //outputCheck.DumpArrays("inLine1", "inLine1.c", inLine1, width, 1); //outputCheck.DumpArrays("inLine2", "inLine2.c", inLine2, width, 1); //outputCheck.DumpArrays("mask", "mask.c", mask, width, 1); //outputCheck.DumpArrays("outLineC", "outLineC.c", outLineC, width, 1); //outputCheck.DumpArrays("outLineAsm", "outLineAsm.c", outLineAsm, width, 1); }
true
1906faae37c0adae9698fb03daabafc3804592d5
C++
siljeanf/TDT4102_OOP
/Øving 3/std_lib_facilities_mac/std_lib_facilities_mac/cannonball.cpp
UTF-8
2,978
3.109375
3
[]
no_license
// // cannonball.cpp // std_lib_facilities_mac // // Created by Silje Anfindsen on 22/01/2019. // Copyright © 2019 Lars Musaus. All rights reserved. // #include "std_lib_facilities.h" #include "cannonball.hpp" #include <math.h> /* pow */ double acclY() { double acc = -9.81; return acc; } double velY(double initVelocityY, double time) { double v_y=0; double a_y= acclY(); v_y = initVelocityY + (time * a_y); return v_y; } double posY ( double initPosition, double initVeolocity, double time) { double pos_y = 0; double a_y = acclY(); pos_y = initPosition + (initVeolocity * time ) + ( (a_y * pow(time, 2) )/2); return pos_y; } double posX (double initPosition, double initVeolocity, double time) { double pos_x = 0; double a_x = 0; // aks. i x-retning er 0. pos_x = initPosition + (initVeolocity * time ) + ( (a_x * pow(time, 2)) / 2); return pos_x; } void printTime (double sec) { int h = sec/(3600); int min = (sec/60) - (h*60); int s = sec - (h*3600) - (min*60); cout << h << "timer, " << min << "minutter," << s << "sekunder." <<'\n'; } double flightTime (double initVelocityY) { double a_y = acclY(); return (-2*initVelocityY)/ (a_y); } // Ber brukeren om to tall, en vinkel (i grader) og en fart. // Formålet er å endre verdien på argumentene. // theta og absVelocity er referanser til objektene funksjonen kalles med. void getUserInput(double& theta, double& absVelocity) { cout << "oppgi en vinkel (i grader):" ; cin >> theta; cout << "\n oppgi en fart:" ; cin >> absVelocity; } // Konverterer fra grader til radianer double degToRad(double deg) { return (deg * M_PI)/180; } // Returnerer henholdsvis farten i x-, og y-retning, gitt en vinkel // theta og en absoluttfart absVelocity. double getVelocityX(double theta, double absVelocity) { double v_x = cos(theta)*absVelocity; return v_x; } double getVelocityY(double theta, double absVelocity) { double v_y = sin(theta) * absVelocity; return v_y; } // Dekomponerer farten gitt av absVelocity, i x- og y-komponentene // gitt vinkelen theta. Komponentene oppdateres gjennom referansene. // med Vector i funksjonsnavnet tenker vi på vektor-begrepet i geometri void getVelocityVector(double theta, double absVelocity,double& velocityX, double& velocityY) { velocityX = getVelocityX(theta, absVelocity); velocityY = getVelocityY(theta, absVelocity); } //skal returnere x-posisjon når kanonkulen er på bakken double getDistanceTraveled(double velocityX, double velocityY) { double t = flightTime(velocityY); return posX(0, velocityX, t); } // skal returnere avviket mellom avstanden fra målet og der kula lander. double targetPractice(double distanceToTarget, double velocityX, double velocityY) { double total_distance = getDistanceTraveled(velocityX, velocityY); double avvik = abs(total_distance - distanceToTarget); return avvik; }
true
3424fecc0ee4d2e04f0adb3024c365dea78f6720
C++
tbaekk/cs343
/final/boundedbufferEXT.cc
UTF-8
936
2.921875
3
[]
no_license
#include <uC++.h> #include <iostream> using namespace std; _Task BoundedBuffer { int front, back, count; int Elements[20]; public: BoundedBuffer() : front(0), back(0), count(0) {} _Nomutex int query() { return count; } void insert( int elem ) { Elements[back] = elem; back = ( back + 1 ) % 20; count += 1; } int remove() { int elem = Elements[front]; front = ( front + 1 ) % 20; count -= 1; return elem; } protected: void main() { for ( ;; ) { // INFINITE LOOP!!! _When ( count != 20 ) _Accept( insert ) { // after call } or _When ( count != 0 ) _Accept( remove ) { // after call } // _Accept } } }; int main() { BoundedBuffer bf; for (int i = 0; i < 20; i++) { bf.insert(i); } for (int i = 0; i < 5; i++) { bf.remove(); } cout << bf.query() << endl; }
true
b30723c2a1430eeb99d95f3027cc6445c1906bf1
C++
kir156/projects
/wavelet_alghoritm/mathematic.cpp
UTF-8
1,242
2.546875
3
[]
no_license
#include "mainwindow.h" std::vector<float> MainWindow::pairConv(std::vector<float> &data,std::vector<float> &CL, std::vector<float> &CH, int delta) { if(CL.size() == CH.size()) { std::vector<float> out; int N = CL.size(); int M = data.size(); for(int i = 0; i != M; i += 2) { float sL = 0; float sH = 0; for(int k = 0; k < N; ++k) { sL += data[(i + k - delta) % M] * CL[k]; sH += data[(i + k - delta) % M] * CH[k]; } out.push_back(sL); out.push_back(sH); } return out; } } void MainWindow::iCoeffs(std::vector<float> &CL, std::vector<float> &CH) { if(CL.size() == CH.size()) { for(int k = 0; k < CL.size(); k += 2) { if(k == 0) { int i = CL.size() - 1; iCL.push_back(CL[i-1]); iCL.push_back(CH[i-1]); iCH.push_back(CL[i]); iCH.push_back(CH[i]); } else { iCL.push_back(CL[k-2]); iCL.push_back(CH[k-2]); iCH.push_back(CL[k-1]); iCH.push_back(CH[k-1]); } } } }
true
ab5f107affafed319e720b7c73a3d2ab2449c6bf
C++
BullynckVictor/VulkanRave
/VulkanRave/Engine/General/Window/Mouse.h
UTF-8
611
2.59375
3
[]
no_license
#pragma once #include "Engine/Utilities/Flag.h" #include "Engine/Utilities/Vector.h" namespace rv { class Mouse { public: class Button { public: bool Pressed() const; bool Flagged(); bool Peek() const; private: bool pressed = false; Flag<bool> flag; friend class Window; }; const Point& Position() const; Point Delta(); const Point& PeekDelta() const; const int& PeekScroll() const; int Scroll(); Button left; Button middle; Button right; Button x1; Button x2; private: Point pos; Flag<Point> delta; int scroll = 0; friend class Window; }; }
true
718e84675794a93d8a3f1e1c907ff98334320f6e
C++
hoangpham95/3d-tetris
/include/Tetromino.h
UTF-8
685
2.625
3
[]
no_license
#ifndef TETROMINO_H #define TETROMINO_H #include <Constants.h> #include <Cube.hpp> class Tetromino { public: Tetromino(Shape, const int&); std::vector<Cube*> getCubes(); void Move(Direction); void Rotate(Rotation); private: std::vector<Cube*> m_Cubes; Cube* m_Center; void genCubeCoords(float* cubeCoords, const int& board_h, float* color); float RED[4] = {1.0f, 0.0f, 0.0f, 1.0f}; float GREEN[4] = {0.0f, 1.0f, 0.0f, 1.0f}; float BLUE[4] = {0.0f, 0.0f, 1.0f, 1.0f}; float PURPLE[4] = {0.5f, 0.0f, 0.5f, 1.0f}; float CYAN[4] = {0.0f, 0.5f, 0.5f, 1.0f}; float ORANGE[4] = {1.0f, 0.65f, 0.0f, 1.0f}; float PINK[4] = {0.5f, 0.0f, 0.0f, 1.0f}; }; #endif
true
b24f221c0c2ce2451d36822c421a868e4fb053ce
C++
Boringmanzr/boringmanzr-git-test
/cpppointer/cpp-pointer-array.cpp
UTF-8
394
3.53125
4
[]
no_license
#include <iostream> using namespace std; const int MAX = 3 ; int main() { int var[MAX]={10,20,30}; for(int i=0; i<MAX;i++) { *(var + i ) = i ; //*操作的必须是指针 /* 使用*var[i]就是错误的, */ //var++; //常量不能使用++计算 cout << "指针所指的数组var["<<i<<"]" << var[i] << endl; } return 0; }
true
bd11718ad4dbc1816e8e7d37cdebc83e3fe86690
C++
CaptainTPS/LeetCodeRep
/LeetCode/lc394.cpp
UTF-8
798
3.25
3
[]
no_license
#include <string> using namespace std; class Solution394 { public: string dfs(string& s, int& sptr){ string re = ""; if (sptr >= s.length()) return re; if (isdigit(s[sptr])){ int n = 0; while (sptr < s.length() && isdigit(s[sptr])){ n = n * 10 + s[sptr] - '0'; sptr++; } string temp; sptr++; while (sptr < s.length() && s[sptr] != ']'){ if (isdigit(s[sptr])){ temp += dfs(s, sptr); } else { temp += s[sptr]; sptr++; } } sptr++; for (int i = 0; i < n; i++){ re += temp; } } return re; } string decodeString(string s) { int ptr = 0; string re = ""; while (ptr < s.length()){ if (isdigit(s[ptr])){ re += dfs(s, ptr); } else { re += s[ptr]; ptr++; } } return re; } };
true
2c2b5bf9f60a8bd22d9d5bca628d0e74c63d0d85
C++
kimshgood/DRAMsim3
/tests/test_config.cc
UTF-8
2,998
2.5625
3
[ "MIT" ]
permissive
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "configuration.h" TEST_CASE("Address Mapping", "[config]") { dramsim3::Config config("configs/HBM1_4Gb_x128.ini", "."); SECTION("TEST address mapping set up") { REQUIRE(config.address_mapping == "rorabgbachco"); // COL width is not necessarily the same as col bits because BL REQUIRE(config.co_pos == 0); REQUIRE(config.ch_pos == 5); REQUIRE(config.ba_pos == 8); REQUIRE(config.bg_pos == 10); REQUIRE(config.ra_pos == 12); REQUIRE(config.ro_pos == 12); } SECTION("Test address mapping column") { uint64_t hex_addr = 0x0; auto addr = config.AddressMapping(hex_addr); REQUIRE(addr.column == 0); hex_addr = 0b11111000000; addr = config.AddressMapping(hex_addr); REQUIRE(addr.column == 31); } SECTION("Test address mapping channel") { uint64_t hex_addr = 0b11111111111; auto addr = config.AddressMapping(hex_addr); REQUIRE(addr.channel == 0); hex_addr = 0b111110111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.channel == 5); hex_addr = 0b000011111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.channel == 7); } SECTION("Test address mapping bank") { uint64_t hex_addr = 0b11111111111111; auto addr = config.AddressMapping(hex_addr); REQUIRE(addr.bank == 0); hex_addr = 0b1011111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.bank == 2); hex_addr = 0b1111011111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.bank == 2); } SECTION("Test address mapping bankgroup") { uint64_t hex_addr = 0b1111111111111111; auto addr = config.AddressMapping(hex_addr); REQUIRE(addr.bankgroup == 0); hex_addr = 0b101111111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.bankgroup == 2); hex_addr = 0b111101111111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.bankgroup == 2); } SECTION("Test address mapping rank") { uint64_t hex_addr = 0xFFFFFFFFFFFF; auto addr = config.AddressMapping(hex_addr); REQUIRE(addr.rank == 0); } SECTION("Test address mapping row") { uint64_t hex_addr = 0b111111111111111111; auto addr = config.AddressMapping(hex_addr); REQUIRE(addr.row == 0); hex_addr = 0b10001111111111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.row == 17); hex_addr = 0b10000000000000111111111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.row == 0b10000000000000); hex_addr = 0b11110000000000000111111111111111111; addr = config.AddressMapping(hex_addr); REQUIRE(addr.row == 0b10000000000000); } }
true
987de8a4777738c44afc69a659f454004a2f9e7c
C++
OpenBoardView/OpenBoardView
/src/openboardview/utils.cpp
UTF-8
3,516
3.078125
3
[ "MIT" ]
permissive
#include "utils.h" #include <SDL.h> #include <algorithm> #include <cctype> #include <cstring> #include <fstream> #include <iostream> #include <iterator> #include <sstream> #include <cstdint> #ifndef _WIN32 #include <dirent.h> #endif #include <sys/stat.h> #include <sys/types.h> // Loads an entire file in to memory std::vector<char> file_as_buffer(const filesystem::path &filepath, std::string &error_msg) { std::vector<char> data; if (!filesystem::is_regular_file(filepath)) { error_msg = "Not a regular file"; SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Error opening %s: %s", filepath.string().c_str(), error_msg.c_str()); return data; } ifstream file; file.open(filepath, std::ios::in | std::ios::binary | std::ios::ate); if (!file.is_open()) { error_msg = strerror(errno); SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Error opening %s: %s", filepath.string().c_str(), error_msg.c_str()); return data; } file.seekg(0, std::ios_base::end); std::streampos sz = file.tellg(); ENSURE(sz >= 0, error_msg); data.reserve(sz); file.seekg(0, std::ios_base::beg); data.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()); ENSURE(data.size() == static_cast<unsigned int>(sz), error_msg); file.close(); return data; } // Extract extension from filename and check against given fileext // fileext must be lowercase bool check_fileext(const filesystem::path &filepath, const std::string fileext) { std::string ext{filepath.extension().string()}; // extract file ext std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower); // make ext lowercase return ext == fileext; } // Returns true if the given str was found in buf bool find_str_in_buf(const std::string str, const std::vector<char> &buf) { return std::search(buf.begin(), buf.end(), str.begin(), str.end()) != buf.end(); } // Case insensitive comparison of std::string bool compare_string_insensitive(const std::string &str1, const std::string &str2) { return str1.size() == str2.size() && std::equal(str2.begin(), str2.end(), str1.begin(), [](const char &a, const char &b) { return std::tolower(a) == std::tolower(b); }); } // Case insensitive lookup of a filename at the given path filesystem::path lookup_file_insensitive(const filesystem::path &path, const std::string &filename, std::string &error_msg) { std::error_code ec; filesystem::directory_iterator di{path, ec}; if (ec) { error_msg = "Error looking up '" + filename + "' in '" + path.string().c_str() + "': " + ec.message(); SDL_LogError(SDL_LOG_CATEGORY_ERROR, "Error looking up '%s' in '%s': %d - %s", filename.c_str(), path.string().c_str(), ec.value(), ec.message().c_str()); return {}; } for(auto& p: filesystem::directory_iterator(path)) { if (compare_string_insensitive(p.path().filename().string(), filename)) { return p.path(); } } error_msg = filename + ": file not found in '" + path.string() + "'."; return {}; } // Split a string in a vector, delimiter is a space (stringstream iterator) std::vector<std::string> split_string(const std::string str) { std::istringstream iss(str); return {std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}}; } // Split a string in a vector with given delimiter std::vector<std::string> split_string(const std::string &str, char delimeter) { std::istringstream iss(str); std::string item; std::vector<std::string> strs; while (std::getline(iss, item, delimeter)) { strs.push_back(item); } return strs; }
true
25bcb48557844fa71bc95fa8e52c3a4eaf6a026c
C++
dasmysh/OGLFrameworkLib_uulm
/OGLFramework_uulm/gfx/Material.h
UTF-8
1,416
2.9375
3
[ "MIT" ]
permissive
/** * @file Material.h * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2013.12.31 * * @brief Contains the material class */ #ifndef MATERIAL_H #define MATERIAL_H #include "main.h" namespace cgu { class GLTexture2D; /** * @brief Class describing materials. * * @author Sebastian Maisch <sebastian.maisch@googlemail.com> * @date 2013.12.31 */ class Material { public: Material(); Material(const Material&); Material& operator=(const Material&); Material(Material&&); Material& operator=(Material&&); ~Material(); /** Holds the materials ambient color. */ glm::vec3 ambient; /** Holds the materials diffuse color. */ glm::vec3 diffuse; /** Holds the materials specular color. */ glm::vec3 specular; /** Holds the materials alpha value. */ float alpha; /** Holds the materials minimum oriented alpha value. */ float minOrientedAlpha; /** Holds the materials specular exponent. */ float N_s; /** Holds the materials index of refraction. */ float N_i; /** Holds the materials diffuse texture. */ const GLTexture2D* diffuseTex; /** Holds the materials bump texture. */ const GLTexture2D* bumpTex; /** Holds the materials bump multiplier. */ float bumpMultiplier; }; } #endif /* MATERIAL_H */
true
d097519b97fd538ca8883d264d1f8adcab7b7127
C++
yh1807/data_struct
/string.h
UTF-8
939
3.296875
3
[]
no_license
#pragma once #include <string.h> #include <ostream> class string { public: string(const char *cstr = 0); string(const string &rhs); string& operator=(const string &s); ~string() { delete[] data_; } char* get_c_str() const { return data_; } private: char *data_; }; string::string(const char *cstr) { if (cstr) { data_ = new char[strlen(cstr) + 1]; strcpy(data_, cstr); } else { data_ = new char[1]; *data_ = '\0'; } } string::string(const string &rhs) { data_ = new char[strlen(rhs.data_) + 1]; strcpy(data_, rhs.data_); } string& string::operator=(const string &str) { if (this == &str) return *this; delete[] data_; data_ = new char[strlen(str.data_) + 1]; strcpy(data_, str.data_); return *this; } std::ostream& operator<<(std::ostream &os, const string &rhs) { return os << rhs.get_c_str(); }
true
1e9936900f913aa423121cc5f39840c4b55928c8
C++
Naruell/BAEKJOON
/2742.cpp
UTF-8
308
2.828125
3
[]
no_license
// 2742 기찍 N #include <iostream> int main() { std::cin.tie(NULL); std::ios_base::sync_with_stdio(false); int printNumberFrom; std::cin >> printNumberFrom; printNumberFrom++; while(printNumberFrom-- > 1) { std::cout << printNumberFrom << '\n'; } return 0; }
true
9ab7d0585f5a567a7235390281071476b6ea742d
C++
xminjie/TSOJ
/1363类斐波那契终极版(谢).cpp
GB18030
3,693
3.265625
3
[]
no_license
1363:쳲 Ѷȣ 󲬽 ʱƣ 1000MS ռƣ 64MB ύ 242 ͨ 8 ĿԴ: admin Ŀ [2017 տƼѧ ƾ] C. 쳲 (ı) Ŀ ѧУһĵƹʽΪ쳲ƹʽѧʣѧѧΪйѧڿͨ F(n) ʾһ쳲еĵ n ļ㹫ʽǣ q a * F(n - 2) + b * F(n - 1) (n > 2) F(n) = | p (n = 1) t q (n = 2) Уa, b, p, q, Ϊȷij ij쳲еĵ i Ƕ١ жݣÿռС ڵһУһոָ a, b, p, q, ȷ쳲еĵƹʽ ڵڶУһ mʾУҪ m F(n) ڵУ m ÿոָ n1, n2, n3, ... , nm, ʾҪij±ꡣ a, b, p, q 10 m 25 ÿ n 10000 ÿݣһд𰸣ÿոָ вҪκζĿո 1 1 1 1 3 5 10 98 1 2 5 10 3 5 8 10 5 55 135301852344706746049 145 2040 11890 #include <iostream>//1.ַ洢2.ģֶ 3.صÿһ 4.Ҫ #include <string> using namespace std; #define N 10001 string s[N]; string mul(string &s1,int &n) {//ֶģ˷λ int jin = 0; char c; string st = s1; for(int i = s1.size() - 1; i >= 0; i--) { st[i] = ((s1[i] - '0') * n + jin) % 10 + '0'; jin = ((s1[i] - '0') * n + jin) / 10; } c = jin + '0';//˺һλ if(jin >= 1) st = c + st; return st; } string add(string &s1, string &s2) { string st = s1; char c; int jin = 0, i, j; if(s1.size() > s2.size() ) {//ǰs1.s2λһ,(ֻs1>=s2)Ϊs1Ǻһ for(i = 0; i < s1.size() - s2.size();i++) //յλò0 ,888 66 -> 888 066; st[i] = '0'; for(i = s1.size() - s2.size(),j = 0; i < s1.size() ; i++,j++) st[i] = s2[j]; s2 = st; } for(i = s2.size() - 1; i >= 0; i--) {//ֶģ⣬λ st[i] = ((s1[i] + s2[i] - '0' - '0' + jin) % 10) + '0'; jin = (s1[i] + s2[i] - '0' - '0' + jin) / 10; } c = jin + '0';//Ӻһλ if(jin >= 1) st = c + st; return st; } string fun(string &s1, string &s2, int n1, int n2) { string s11,s22; s11 = mul(s1,n1); s22 = mul(s2,n2); return add(s11,s22); } int main() { int a, b, m, n, t, i; while(scanf("%d%d",&a,&b) != EOF) { cin >> s[1] >> s[2];//1.ַÿһ ̫int long longҲը scanf("%d",&m); int ar[m+1]; t = 0; for( i = 1; i <= m; i++) {//t壬Ҫõڼͼ㵽ڼ scanf("%d",&ar[i]); if(t < ar[i]) t = ar[i]; } for( i = 3; i <= t; i++) s[i] = fun(s[i-1],s[i-2],b,a);//ÿһ for( i = 1; i <= m-1; i++) // //ÿһո cout << s[ar[i]] << ' '; cout << s[ar[m]] << endl; } return 0; } /*һǣҪ ֮ǰ fun(s[i-1],s[i-2],b,a)ֱдһ ȻǺңڵԻĶܲ ֮ǰдһǵطѾԼ붼 ɼС*/
true
843f0cccb8ba2ba2f6254342b77b9a80b046f2da
C++
realfan-1s/LeetCodeHard
/Union-find Sets/InvertPairs.cpp
UTF-8
2,961
3.234375
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <set> #include <unordered_map> using namespace std; // 归并排序 class Solution1 { public: int reversePairs(vector<int>& nums) { if (nums.size() < 2) return 0; return RescursiveSort(nums, 0, nums.size() - 1); } private: int RescursiveSort(vector<int>& nums, int left, int right){ if (left == right) return 0; else { int mid = left + (right - left) / 2; int n1 = RescursiveSort(nums, left, mid); int n2 = RescursiveSort(nums, mid + 1, right); int res = n1 + n2; int i = left, j = mid + 1; while (i <= mid) { while (j <= right && (long)nums[i] > (long)nums[j] * 2) j++; res += (j - mid - 1); i++; } // 归并排序 int p1 = left, p2 = mid + 1; int p = 0; vector<int> sorted(right - left + 1); while (p1 <= mid || p2 <= right){ if (p1 > mid) sorted[p++] = nums[p2++]; else if(p2 > right) sorted[p++] = nums[p1++]; else { if (nums[p1] < nums[p2]) sorted[p++] = nums[p1++]; else sorted[p++] = nums[p2++]; } } for (auto k = 0; k < sorted.size(); k++) nums[left + k] = sorted[k]; return res; } } }; // 树状数组 class BIT{ private: vector<int> tree; int n; public: BIT(int n) : n(n), tree(n + 1) {} static constexpr int Lowbit(int x){ return x & (-x); } void Update(int x, int d){ while (x <= n){ tree[x] += d; x += Lowbit(x); } } int Query(int x){ int ans = 0; while (x != 0){ ans += tree[x]; x -= Lowbit(x); } return ans; } }; class Solution2 { public: int reversePairs(vector<int>& nums) { set<long> allNumbers; for (int i = 0; i < nums.size(); i++) { allNumbers.insert(nums[i]); allNumbers.insert((long)nums[i] * 2); } unordered_map<long, int> valuesDict; int index = 0; for(long item : allNumbers) valuesDict[item] = ++index; int res = 0; BIT bit(valuesDict.size()); for (int k = 0; k < nums.size(); k++){ int left = valuesDict[(long) nums[k] * 2]; int right = valuesDict.size(); res += bit.Query(right) - bit.Query(left); bit.Update(valuesDict[nums[k]], 1); } return res; } };
true
c071296a89c6e6094e6112fddf38cf66f240e5f6
C++
peter88037/LeetCode
/62. Unique Paths.cpp
UTF-8
542
2.890625
3
[]
no_license
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int>> ans(m,vector<int>(n)); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { if(i==0 || j==0) { ans[i][j]=1; } else { ans[i][j]=ans[i-1][j]+ans[i][j-1]; } } } //cout<<ans[0][0]; return ans[m-1][n-1]; } };
true
7bac5d12ae8c0cc4922b6dcf20b2a660bbbadc9c
C++
zengmmm00/DSAA
/week6/MatchingProbelm/main.cpp
UTF-8
1,352
2.5625
3
[]
no_license
#include <iostream> #include <cstring> using namespace std; char s[200001]; char t[200001]; int main() { int T; scanf("%d", &T); for (int i = 0; i < T; ++i) { int n, m; scanf("%d %d", &n, &m); scanf("%s\n%s", s, t); int location = -1; for (int j = 0; j < n; ++j) { if (s[j] == '*')location = j; } bool check = true; if (location == -1) { if (m != n)check = false; else { for (int j = 0; j < n; ++j) { if (s[j] != t[j]) { check=false; break; } } } } else { if (m < n - 1) { check=false;} else { for (int j = 0; j <= location - 1; ++j) { if (s[j] != t[j]) { check = false; break; } } for (int j = 0; j < n - location - 1; ++j) { if (s[n - 1 - j] != t[m - 1 - j]) { check = false; break; } } } } if (check)printf("YES"); else printf("NO"); if (i != T - 1) printf("\n"); } return 0; }
true
4e37894d355310944fc26f78642d663d70d294e1
C++
FungluiKoo/CodeForceSolutions
/88C.cpp
UTF-8
488
3
3
[ "MIT" ]
permissive
#include <iostream> #include <numeric> #include <queue> int main(){ long long dasha_interval, masha_interval; std::cin >> dasha_interval >> masha_interval; long long gcd = std::gcd<long long,long long>(dasha_interval, masha_interval); dasha_interval/=gcd; masha_interval/=gcd; if(std::abs(dasha_interval-masha_interval)<=1){ std::cout << "Equal"; }else{ std::cout << ((dasha_interval>masha_interval) ? "Masha" : "Dasha"); } return 0; }
true
77d4f1accf432bcffe7c7c329cc493d2e47a7183
C++
JamesCMLucas/GameMathDump
/cVector3.cpp
UTF-8
1,380
3.09375
3
[]
no_license
#include "cVector3.h" #include "nMath.h" float cVector3::Normalize( float tol /*= nMath::EPSILON */ ) { float mag2 = x*x + y*y + z*z; if ( mag2 < tol ) { return mag2; } float magInv = nMath::InverseSqrt( mag2 ); x *= magInv; y *= magInv; z *= magInv; return mag2; } float cVector3::Length() const { return sqrt( x*x + y*y + z*z ); } float cVector3::Len2() const { return ( ( x * x ) + ( y * y ) + ( z * z ) ); } float cVector3::Dot( const cVector3& vec ) const { return ( ( x * vec.x ) + ( y * vec.y ) + ( z * vec.z ) ); } cVector3 cVector3::ProjectedOn( const cVector3& vec ) const { float mult = ( ( x * vec.x ) + ( y * vec.y ) + ( z * vec.z ) ) / ( ( vec.x * vec.x ) + ( vec.y * vec.y ) + ( vec.z * vec.z ) ); return cVector3( ( vec.x * mult ), ( vec.y * mult), ( vec.z * mult) ); } cVector3 cVector3::ProjectedOn( const cVector3& v1, const cVector3& v2 ) const { float m1 = ( ( x * v1.x ) + ( y * v1.y ) + ( z * v1.z ) ) / ( ( v1.x * v1.x ) + ( v1.y * v1.y ) + ( v1.z * v1.z ) ); float m2 = ( ( x * v2.x ) + ( y * v2.y ) + ( z * v2.z ) ) / ( ( v2.x * v2.x ) + ( v2.y * v2.y ) + ( v2.z * v2.z ) ); return cVector3( (( v1.x * m1 ) + ( v2.x * m2 )), (( v1.y * m1 ) + ( v2.y * m2 )), (( v1.z * m1 ) + ( v2.z * m2 )) ); } cVector3 cVector3::Cross( const cVector3& v ) const { return cVector3( y*v.z - z*v.y, z*v.x - x*v.z, x*v.y - y*v.x ); }
true
99a0bf3c1cd40087339b8a5fffff61603bb7029e
C++
ksobtafo/Exam273
/event.h
UTF-8
780
3.109375
3
[]
no_license
#ifndef EVENT_H #define EVENT_H #include <iostream> #include <string> #include <list> #include <vector> #include "invite.h" class event: class invite { private: std::list<std::string> name; public: invite *add(std::string name) { name.push_front(name1); // an invite is added to the fron ot the line std::list<std::string> ::iterator it = name.begin(); invite*NewInvite = new invite(name.begin()); //this points to the recently added invited return NewInvite; //adds a person with name into the event and returns an invite for that person }; void list() { std::list<std::string> ::iterator it = name.begin(); for (it; it != name.end(); it++) { std::cout << *it << std::endl; //prints out all the people currently at the event } } }; #endif
true
a027a0e4bc0dfb332d9b4defafb6d1b5d0bc9b46
C++
AmanajasLG/IDJ
/src/Collider.cpp
UTF-8
2,583
2.765625
3
[]
no_license
#include "../include/Collider.h" #include "../include/Collision.h" #include "../include/Camera.h" #include "../include/Game.h" Collider::Collider(GameObject &associated, Vec2 scale, Vec2 offset) : Component(associated){ this->scale = scale; this->offset = offset; } void Collider::Update(float dt){ box = associated.box; box.w *= scale.x; box.y *= scale.y; Vec2 center( box.Center(box) ); Vec2 centerRotated = center.SubVectors(Vec2(box.x, box.y), center); centerRotated.GetRotated(associated.angleDeg/(180/M_PI)); Vec2 centerPoint = center.AddVectors(center,centerRotated); centerPoint = center.SubVectors(centerPoint,Camera::pos); } bool Collider::Is(std::string type){ return strcmp(type.c_str(),"Collider") == 0; } void Collider::SetScale(Vec2 scale){ this->scale = scale; } void Collider::SetOffset(Vec2 offset){ this->offset = offset; } void Collider::Render() { #ifdef DEBUG Vec2 center( box.Center(box) ); SDL_Point points[5]; Vec2 centerRotated = center.SubVectors(Vec2(box.x, box.y), center); centerRotated.GetRotated(associated.angleDeg/(180/M_PI)); Vec2 centerPoint = center.AddVectors(center,centerRotated); centerPoint = center.SubVectors(centerPoint,Camera::pos); Vec2 point = center; points[0] = {(int)point.x, (int)point.y}; points[4] = {(int)point.x, (int)point.y}; centerRotated = center.SubVectors(Vec2(box.x + box.w, box.y), center); centerRotated.GetRotated(associated.angleDeg/(180/M_PI)); centerPoint = center.AddVectors(center,centerRotated); centerPoint = center.SubVectors(centerPoint,Camera::pos); point = centerPoint; points[1] = {(int)point.x, (int)point.y}; centerRotated = center.SubVectors(Vec2(box.x + box.w, box.y + box.h), center); centerRotated.GetRotated(associated.angleDeg/(180/M_PI)); centerPoint = center.AddVectors(center,centerRotated); centerPoint = center.SubVectors(centerPoint,Camera::pos); point = centerPoint; points[2] = {(int)point.x, (int)point.y}; centerRotated = center.SubVectors(Vec2(box.x, box.y + box.h), center); centerRotated.GetRotated(associated.angleDeg/(180/M_PI)); centerPoint = center.AddVectors(center,centerRotated); centerPoint = center.SubVectors(centerPoint,Camera::pos); point = centerPoint; points[3] = {(int)point.x, (int)point.y}; SDL_SetRenderDrawColor(Game::GetInstance().GetRenderer(), 255, 0, 0, SDL_ALPHA_OPAQUE); SDL_RenderDrawLines(Game::GetInstance().GetRenderer(), points, 5); #endif // DEBUG }
true
344a157aca39efc0a50784fb0d1477d316868d74
C++
tolerance1/Example-Task
/include/HourlyWaged.h
UTF-8
354
2.875
3
[]
no_license
#ifndef HOURLYWAGED_H #define HOURLYWAGED_H #include "Employee.h" class HourlyWaged : public Employee { public: HourlyWaged(const string name, const string surname, const double rate); ~HourlyWaged() {} void CalculateSalary(); private: double Hours {8}; double Days {20.8}; }; #endif // HOURLYWAGED_H
true
468bed4452c44f41dc930bbd408b231a934a1ba1
C++
juso40/IPK_BlockSeminar
/Sheet7/FroggerTemplate/Frogger/Frog.h
UTF-8
596
2.5625
3
[]
no_license
#ifndef FROG_H #define FROG_H #include "Vec2D.h" #include "Terminal.h" #include "Water.h" #include <vector> class Frog{ private: std::vector<Vec2D> _body; public: Frog(); void draw_frog(Terminal& term); void move(char pressed); //retuns the hitbox of the frog Vec2D position(int n); //checks if frog crossed road bool check_win(); bool is_on_log_left(Water& log); bool is_on_log_right(Water& log); void move_with_log(Water& log); //Returns bool, if fallen in water. bool died_in_water(Water& log); bool out_of_bounds(); }; #endif
true
b5d41d68fcf0659ffd3af29a8d05e2e82e46ae99
C++
JayPOS/ProtAIGame
/Pacman/includes/astar.hpp
UTF-8
758
2.59375
3
[]
no_license
#ifndef ASTAR_HPP #define ASTAR_HPP #include "includes.hpp" typedef struct nos No; struct nos { int i, j, w; ii pai; }; bool equal(No um, No dois); auto comp = [](No &um, No &dois) { return um.w > dois.w; }; No criaInicio(int i, int j, int i_final, int j_final); No criaFim(int i, int j); No iniciaNo(int i, int j, No inicio, No dest, No pai); int manhattan(No um, No dois); // abre no e insere na fila os vizinhos void abreNo(No inicio, No dest, No atual, priority_queue<No, vector<No>, decltype(comp)> &fila, vector<No> &pilha, int id_squares[31][28]); vector<No> A_star(No inicio, No dest, int id_squares[31][28]); // retorna lista fechada; vector<No> cria_caminho(vector<No> &lst_fechada); // cria pilha de caminho pela lst_fechada. #endif
true
6af11d5e60d84e39c1e3783e7919b341b99a1f54
C++
kirvlasenkov/cpp_garbage_collector
/belts/white/week_1/euclid.cpp
UTF-8
939
3.421875
3
[ "MIT" ]
permissive
#include <iostream> using namespace std; int main() { int a, b; cin >> a >> b; // пока оба числа положительны, будем их уменьшать, не меняя их НОД while (a > 0 && b > 0) { // возьмём большее из чисел и заменим его остатком от деления на второе // действительно, если a и b делятся на x, то a - b и b делятся на x // тогда и a % b и b делятся на x, так что можно a заменить на a % b if (a > b) { a %= b; } else { b %= a; } } // если одно из чисел оказалось равно нулю, значит, на последней итерации // большее число разделилось на меньшее cout << a + b; return 0; }
true
a6d46c8cfcc54e28c4e8a132b2accd683317cb7a
C++
italankin/bezier
/main.cpp
UTF-8
12,369
2.6875
3
[]
no_license
#include <windows.h> // for ms windows #include <GL\freeglut.h> // glut #include <vector> #include "bezier.h" // bezier calculations and classes #include "files.h" // tools for reading files and converting into objects #include "utils.h" // mouse class and other tools const double FIELD_SIZE = 100.0; // grid size const double ROTATION_STEP = 2.0; // rotation step (degrees) used for rotate tool const double TRANSLATE_STEP = 20.0; // translate step used for keyboard arrows const int WINDOW_WIDTH = 800; // default windows width const int WINDOW_HEIGHT = 600; // and height enum MENU_TYPE { // items list for glut context menu MENU_AXES, MENU_FULLSCREEN, MENU_GRID, MENU_RELOAD }; GLfloat xRotation = 10; // default GLfloat yRotation = -10; // scene GLfloat zRotation = 0; // rotation GLfloat xTranslate = 0.0; // default GLfloat yTranslate = 0.0; // scene GLfloat zTranslate = -650.; // translation bool drawAxis = true; // show axis switch bool drawGrid = true; // show grid switch bool fullscreen = false; // enable fullscreen switch Mouse mouse; // mouse object used for scene manipulations with mouse vector<surface*> curves; // vector array of objects drawn in scene (read from file) char* filename; // input file name // draw a simple bezier curve void drawSurface(surface1d s) { Point *p, *l = s.anchors[0]; glColor3f(0.8f, 0.0, 0.8f); for (int i = 1; i < s.dimen_n; i++) { p = s.anchors[i]; glEnd(); glBegin(GL_LINES); glVertex3f(p->x, p->y, p->z); glVertex3f(l->x, l->y, l->z); glEnd(); l = p; } } // draw bezier surface void drawSurface(surface2d s) { Point *p1, *p2, *l1, *l2; bool nl; glColor3f(0.0f, 0.7f, 0.9f); for (int u = 0; u < s.dimen_n; u++) { nl = true; // start a new line, if point is on the edge // (means there are no other points to connect with) for (int v = 0; v < s.dimen_m; v++) { p1 = s.anchors[u][v]; // points used to draw horizontal p2 = s.anchors[v][u]; // and vertical lines glBegin(GL_LINES); glVertex3f(p1->x, p1->y, p1->z); if (!nl) { glVertex3f(l1->x, l1->y, l1->z); } glEnd(); glBegin(GL_LINES); glVertex3f(p2->x, p2->y, p2->z); if (!nl) { glVertex3f(l2->x, l2->y, l2->z); } glEnd(); l1 = p1; l2 = p2; nl = false; } // END v } // END u } // draw a string in (x;y) void renderString(string s, int x, int y) { glRasterPos2i(x, y); void * font = GLUT_BITMAP_8_BY_13; for (string::iterator i = s.begin(); i != s.end(); ++i) { char c = *i; glutBitmapCharacter(font, c); } } // main render loop void render() { glMatrixMode(GL_MODELVIEW); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(xTranslate, yTranslate, zTranslate); // translate scene glRotatef(xRotation, 1.0, 0.0, 0.0); // rotate glRotatef(yRotation, 0.0, 1.0, 0.0); // scene glRotatef(zRotation, 0.0, 0.0, 1.0); // // draw grid lines, if enabled if (drawGrid) { int lines = FIELD_SIZE; for (int i = -lines; i < lines; i++) { if (i == 0 && drawAxis) // do not draw grid lines where zero axis are continue; glColor3f(0.95f, 0.95f, 0.95f); // light grey glBegin(GL_LINES); glVertex3f(i, 0.0f, -FIELD_SIZE); glVertex3f(i, 0.0f, FIELD_SIZE); glEnd(); glBegin(GL_LINES); glVertex3f(-FIELD_SIZE, 0.0f, i); glVertex3f(FIELD_SIZE, 0.0f, i); glEnd(); } } if (drawAxis) { // y axis (green) glColor3f(0.0f, 1.0f, 0.0f); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, FIELD_SIZE, 0.0f); glEnd(); glColor3f(0.8f, 1.0f, 0.8f); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, -FIELD_SIZE, 0.0f); glEnd(); // x axis (red) glColor3f(1.0f, 0.0f, 0.0f); glBegin(GL_LINES); glVertex3f(-FIELD_SIZE, 0.0f, 0.0f); glVertex3f(FIELD_SIZE, 0.0f, 0.0f); glEnd(); // z axis (blue) glColor3f(0.0f, 0.0f, 1.0f); glBegin(GL_LINES); glVertex3f(0.0f, 0.0f, -FIELD_SIZE); glVertex3f(0.0f, 0.0f, FIELD_SIZE); glEnd(); } // draw bezier objects for (unsigned int i = 0; i < curves.size(); i++) { if (curves[i]->type == SURFACE1D) { surface1d* sd = (surface1d*) curves[i]; drawSurface(*sd); } else { surface2d* sd = (surface2d*) curves[i]; drawSurface(*sd); } } glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0.0, glutGet(GLUT_WINDOW_WIDTH), 0.0, glutGet(GLUT_WINDOW_HEIGHT)); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); // OSD info texts glColor3f(0.0f, 0.0f, 0.0f); string s = "divs=" + int_to_string(divisions); renderString(s, 10, 10); s = "pgup/pgdn"; renderString(s, 10, 30); s = "rotation=(" + int_to_string(xRotation) + "," + int_to_string(yRotation) + "," + int_to_string(zRotation) + ")"; renderString(s, 110, 10); s = "arrow keys"; renderString(s, 110, 30); s = "translation=(" + int_to_string(xTranslate) + "," + int_to_string(yTranslate) + "," + int_to_string(zTranslate) + ")"; renderString(s, 280, 10); s = "ctrl+arrow keys"; renderString(s, 280, 30); s = "fullscreen=" + (string) (fullscreen ? "1" : "0"); renderString(s, 470, 10); s = "f"; renderString(s, 470, 30); s = "grid=" + (string) (drawGrid ? "1" : "0"); renderString(s, 580, 10); s = "g"; renderString(s, 580, 30); s = "axis=" + (string) (drawAxis ? "1" : "0"); renderString(s, 650, 10); s = "a"; renderString(s, 650, 30); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glMatrixMode(GL_PROJECTION); glPopMatrix(); glFlush(); glutSwapBuffers(); } // void arrowKeyPressed(int key, int x, int y) { int mod = glutGetModifiers(); switch (key) { case GLUT_KEY_LEFT: switch (mod) { case GLUT_ACTIVE_CTRL: xTranslate += TRANSLATE_STEP / 100.0; break; default: yRotation += ROTATION_STEP; if (yRotation > 360.0f) { yRotation -= 360; } } break; // case GLUT_KEY_RIGHT: switch (mod) { case GLUT_ACTIVE_CTRL: xTranslate -= TRANSLATE_STEP / 100.0; break; default: yRotation -= ROTATION_STEP; if (yRotation > 360.0f) { yRotation -= 360; } } break; // case GLUT_KEY_UP: switch (mod) { case GLUT_ACTIVE_CTRL: yTranslate -= TRANSLATE_STEP / 100.0; break; default: xRotation += ROTATION_STEP; if (xRotation > 360.0f) { xRotation -= 360; } } break; // case GLUT_KEY_DOWN: switch (mod) { case GLUT_ACTIVE_CTRL: yTranslate += TRANSLATE_STEP / 100.0; break; default: xRotation -= ROTATION_STEP; if (xRotation > 360.0f) { xRotation -= 360; } } break; // case GLUT_KEY_PAGE_DOWN: if (divisions > 4) { divisions -= 2; } break; // case GLUT_KEY_PAGE_UP: if (divisions < (DIMEN_BUFFER - 2)) { divisions += 2; } break; // } // end switch render(); } // void mouseMove(int x, int y) { mouse.set(x, y); if (mouse.active) { switch (mouse.button) { case GLUT_MIDDLE_BUTTON: xTranslate += mouse.dx() / 75.0; yTranslate -= mouse.dy() / 75.0; break; // case GLUT_LEFT_BUTTON: xRotation += mouse.dy() / 10.0; if (xRotation > 360.0f) { xRotation -= 360; } yRotation += mouse.dx() / 10.0; if (yRotation > 360.0f) { yRotation -= 360; } break; // } // END switch render(); } // END mouse.active } // void mousePress(int button, int state, int x, int y) { switch (button) { case 3: zTranslate += TRANSLATE_STEP; render(); break; // case 4: zTranslate -= TRANSLATE_STEP; render(); break; // default: mouse.set(x, y); mouse.button = button; mouse.state = state; mouse.active = state == GLUT_DOWN; // } // END switch } // void keyPressed(unsigned char key, int x, int y) { switch (key) { case 'a': drawAxis = !drawAxis; break; // case 'g': drawGrid = !drawGrid; break; // case 'f': fullscreen = !fullscreen; if (fullscreen) { glutFullScreen(); } else { glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT); } break; // case 'd': xRotation = 10; yRotation = -10; xTranslate = 0.0; yTranslate = 0.0; zTranslate = -400.0; break; // } // END switch render(); } // void reshape(int x, int y) { if (y == 0 || x == 0) return; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(1.0, (GLdouble) x / (GLdouble) y, 1.5, 20000.0); glMatrixMode(GL_MODELVIEW); glViewport(0, 0, x, y); } // void menu(int item) { switch (item) { case MENU_AXES: drawAxis = !drawAxis; render(); break; // case MENU_GRID: drawGrid = !drawGrid; render(); break; // case MENU_FULLSCREEN: fullscreen = !fullscreen; if (fullscreen) { glutFullScreen(); } else { glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT); } break; // case MENU_RELOAD: curves = read_file(filename); render(); break; // } // END switch glutPostRedisplay(); } int main(int argc, char** argv) { if (argc > 1) { filename = argv[1]; // load bezier objects from file curves = read_file(filename); } glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH) - WINDOW_WIDTH) / 2, (glutGet(GLUT_SCREEN_HEIGHT) - WINDOW_HEIGHT) / 2); glutCreateWindow("bezier"); glutReshapeWindow(WINDOW_WIDTH, WINDOW_HEIGHT); glClearColor(255, 255, 255, 0); glutDisplayFunc(render); glutReshapeFunc(reshape); glutSpecialFunc(arrowKeyPressed); glutKeyboardFunc(keyPressed); glutMotionFunc(mouseMove); glutMouseFunc(mousePress); glutCreateMenu(menu); // add menu items glutAddMenuEntry("Toggle axis", MENU_AXES); glutAddMenuEntry("Toggle grid", MENU_GRID); glutAddMenuEntry("Toggle fullscreen", MENU_FULLSCREEN); glutAddMenuEntry("Reload file", MENU_RELOAD); // associate a mouse button with menu glutAttachMenu(GLUT_RIGHT_BUTTON); glutMainLoop(); mouse = Mouse(); return 0; }
true
e31a0f29d132453e3644cfe6adac55c428c09a04
C++
noelchalmers/occa
/include/occa/tools/properties.hpp
UTF-8
1,409
2.546875
3
[ "MIT" ]
permissive
#ifndef OCCA_TOOLS_PROPERTIES_HEADER #define OCCA_TOOLS_PROPERTIES_HEADER #include <occa/tools/json.hpp> namespace occa { class properties: public json { public: // Note: Do not use directly since we're casting between // occa::json& <--> occa::properties& mutable bool initialized; properties(); properties(const properties &other); properties(const json &j); properties(const char *c); properties(const std::string &s); ~properties(); properties& operator = (const properties &other); bool isInitialized() const; void load(const char *&c); void load(const std::string &s); static properties read(const std::string &filename); }; inline properties operator + (const properties &left, const properties &right) { properties sum = left; sum.mergeWithObject(right.value_.object); return sum; } inline properties operator + (const properties &left, const json &right) { properties sum = left; sum.mergeWithObject(right.value_.object); return sum; } inline properties& operator += (properties &left, const properties &right) { left.mergeWithObject(right.value_.object); return left; } inline properties& operator += (properties &left, const json &right) { left.mergeWithObject(right.value_.object); return left; } template <> hash_t hash(const properties &props); } #endif
true
d5755b9a6ea5293be94101cb01b2c7dc677067a3
C++
erythronelumbo/tesela
/include/cynodelic/tesela/image_types.hpp
UTF-8
17,747
2.921875
3
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright (c) 2019 Álvaro Ceballos // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt /** * @file image_types.hpp * * @brief Defines the `basic_image` container. */ #ifndef CYNODELIC_TESELA_IMAGE_TYPES_HPP #define CYNODELIC_TESELA_IMAGE_TYPES_HPP #include <cstdlib> #include <cstddef> #include <cstdint> #include <iterator> #include <utility> #include <stdexcept> #include <cynodelic/tesela/config.hpp> #include <cynodelic/tesela/color_space.hpp> #include <cynodelic/tesela/rgb_types.hpp> #include <cynodelic/tesela/rgba_types.hpp> #include <cynodelic/tesela/gray_types.hpp> #include <cynodelic/tesela/ga_types.hpp> #include <cynodelic/tesela/point.hpp> #include <cynodelic/tesela/rectangle.hpp> namespace cynodelic { namespace tesela { /** * @ingroup types * @brief Image container * * A type that contains a image, that is, a two-dimensional array of pixels. * * @param PixelType A valid @link pixeltypes pixel type @endlink. */ template <typename PixelType> class basic_image { public: /** * @brief Iterator type * * The random access iterator for @ref basic_image. */ template <typename PixelT_> class image_iterator { public: using self_type = image_iterator<PixelT_>; using value_type = PixelT_; using difference_type = std::ptrdiff_t; using pointer = PixelT_*; using reference = PixelT_&; using iterator_category = std::random_access_iterator_tag; image_iterator() : data_ptr(nullptr) {} image_iterator(pointer addr) : data_ptr(addr) {} image_iterator(const self_type& other) : data_ptr(other.data_ptr) {} self_type& operator=(const self_type& other) { data_ptr = other.data_ptr; return *this; } self_type& operator++() { ++data_ptr; return *this; } self_type& operator--() { --data_ptr; return *this; } self_type operator++(int) { data_ptr++; return *this; } self_type operator--(int) { data_ptr--; return *this; } self_type operator+(const difference_type& n) const { return self_type(data_ptr + n); } self_type& operator+=(const difference_type& n) { data_ptr += n; return *this; } self_type operator-(const difference_type& n) const { return self_type(data_ptr - n); } self_type& operator-=(const difference_type& n) { data_ptr -= n; return *this; } reference operator*() const { return *data_ptr; } pointer operator->() const { return data_ptr; } reference operator[](const difference_type& idx) const { return data_ptr[idx]; } friend bool operator==(const self_type& lhs,const self_type& rhs) { return (lhs.data_ptr == rhs.data_ptr); } friend bool operator!=(const self_type& lhs,const self_type& rhs) { return (lhs.data_ptr != rhs.data_ptr); } friend bool operator>(const self_type& lhs,const self_type& rhs) { return (lhs.data_ptr > rhs.data_ptr); } friend bool operator<(const self_type& lhs,const self_type& rhs) { return (lhs.data_ptr < rhs.data_ptr); } friend bool operator>=(const self_type& lhs,const self_type& rhs) { return (lhs.data_ptr >= rhs.data_ptr); } friend bool operator<=(const self_type& lhs,const self_type& rhs) { return (lhs.data_ptr <= rhs.data_ptr); } friend difference_type operator+(const self_type& lhs,const self_type& rhs) { return lhs.data_ptr + rhs.data_ptr; } friend difference_type operator-(const self_type& lhs,const self_type& rhs) { return lhs.data_ptr - rhs.data_ptr; } private: pointer data_ptr; }; using type = basic_image<PixelType>; /**< @brief Reference to its own type */ using value_type = PixelType; /**< @brief Type of the values contained by `basic_image` */ using size_type = std::size_t; /**< @brief Size type */ using difference_type = std::ptrdiff_t; /**< @brief Pointer difference type */ using iterator = image_iterator<value_type>; /**< @brief Iterator type */ using const_iterator = image_iterator<const value_type>; /**< @brief Const-iterator type */ using reverse_iterator = std::reverse_iterator<iterator>; /**< @brief Reverse iterator type */ using const_reverse_iterator = std::reverse_iterator<const_iterator>; /**< @brief Reverse const-iterator type */ /// @brief The type of the components of the pixel type. using component_type = typename PixelType::component_type; /// @brief The color space of the contained pixel type. static constexpr color_space contained_color_space = PixelType::pixel_color_space; /** * @brief Default constructor * * Initializes a @ref basic_image as an empty image. */ basic_image() : img_writting_colspace(contained_color_space), width_(0), height_(0), size_(0), pixels(nullptr) {} /** * @brief Initializes with width, height and color mode * * Initializes the image with width, height and color mode. * * @param width Image width. * @param height Image height. * @param col_space Color space used to write the image. */ basic_image(const std::size_t& width,const std::size_t& height,color_space col_space = contained_color_space) { width_ = width; height_ = height; size_ = width_*height_; img_writting_colspace = col_space; pixels = new value_type[width*height]; } /** * @brief Initializes with rectangle and color mode * * Initializes the image with a @ref rectangle and color mode. The `x` and `y` * members of `rec` are ignored. * * @param rec A @ref rectangle with width and height. * @param col_space Color space used to write the image. */ basic_image(const rectangle& rec,color_space col_space = contained_color_space) : basic_image(rec.width,rec.height,col_space) {} /** * @brief Copy constructor * * Initializes an image copying the contents of another one. * * @param other The instance. */ basic_image(const basic_image<PixelType>& other) { // Allocate array pixels = new value_type[other.size_]; // Copy content for (std::size_t i = 0; i < other.size_; i++) pixels[i] = other.pixels[i]; width_ = other.width_; height_ = other.height_; size_ = other.size_; img_writting_colspace = other.img_writting_colspace; } /** * @brief Move constructor * * Initializes an image _moving_ the contents of another one. * * @param other The instance. */ basic_image(basic_image<PixelType>&& other) noexcept { pixels = other.pixels; width_ = other.width_; height_ = other.height_; size_ = other.size_; img_writting_colspace = other.img_writting_colspace; // "Reset" x other.pixels = nullptr; other.size_ = 0; other.width_ = 0; other.height_ = 0; other.img_writting_colspace = contained_color_space; } /// @brief Destructor. ~basic_image() noexcept { delete [] pixels; pixels = nullptr; } /** * @brief Copy assignment operator * * Replaces the content of an image with the contents of `other`. */ basic_image<PixelType>& operator=(const basic_image<PixelType>& other) { if (this == &other) return *this; // Deallocate array of pixels delete [] pixels; // Reallocate array pixels = new value_type[other.size_]; // Copy content for (std::size_t i = 0; i < other.size_; i++) pixels[i] = other.pixels[i]; width_ = other.width_; height_ = other.height_; size_ = other.size_; img_writting_colspace = other.img_writting_colspace; return *this; } /** * @brief Move assignment operator * * Replaces the content of an image, _moving_ the contents of `other`. */ basic_image<PixelType>& operator=(basic_image<PixelType>&& other) noexcept { if (this == &other) return *this; // Deallocate array of pixels delete [] pixels; pixels = other.pixels; width_ = other.width_; height_ = other.height_; size_ = other.size_; img_writting_colspace = other.img_writting_colspace; // "Reset" x other.pixels = nullptr; other.size_ = 0; other.width_ = 0; other.height_ = 0; other.img_writting_colspace = contained_color_space; return *this; } /** * @brief Swaps the content * * Swaps (exchanges) the content of the image with those of another one. * * @param other The other instance. */ void swap(basic_image<PixelType>& other) { std::swap(width_,other.width_); std::swap(height_,other.height_); std::swap(size_,other.size_); std::swap(img_writting_colspace,other.img_writting_colspace); std::swap(pixels,other.pixels); } /** * @brief Accesses pixel from image * * Accesses a pixel from the image, given its X-Y position. * * @param xpos X position. * @param ypos Y position. */ value_type& operator()(const std::size_t& xpos,const std::size_t& ypos) { if (width_*ypos + xpos > size_) throw std::out_of_range("[cynodelic::tesela::basic_image<...>::operator()] Position outside the bounds of the image's internal array."); return pixels[width_*ypos + xpos]; } /** * @brief Accesses pixel from image * * Accesses a pixel from the image, given its X-Y position. * * @param xpos X position. * @param ypos Y position. */ const value_type& operator()(const std::size_t& xpos,const std::size_t& ypos) const { if (width_*ypos + xpos > size_) throw std::out_of_range("[cynodelic::tesela::basic_image<...>::operator()] Position outside the bounds of the image's internal array."); return pixels[width_*ypos + xpos]; } /** * @brief Accesses pixel from image * * Accesses a pixel from the image, given its position in the underlying array. * * @param idx The position in the underlying array. */ value_type& operator[](const std::size_t& idx) { return pixels[idx]; } /** * @brief Accesses pixel from image * * Accesses a pixel from the image, given its position in the underlying array. * * @param pt The position in the underlying array. */ value_type& operator[](const point& pt) { return pixels[width_*pt.y + pt.x]; } /** * @brief Accesses pixel from image * * Accesses a pixel from the image, given its position in the underlying array. * * @param idx The position in the underlying array. */ const value_type& operator[](const std::size_t& idx) const { return pixels[idx]; } /** * @brief Accesses pixel from image * * Accesses a pixel from the image, given its position in the underlying array. * * @param pt The position in the underlying array. */ const value_type& operator[](const point& pt) const { return pixels[width_*pt.y + pt.x]; } /** * @brief Sets the color space used to write the image * * Determines which color space will be the image written in. * * @param col_space The color space */ void write_with_color_space(const color_space& col_space) { img_writting_colspace = col_space; } /** * @brief Gets the color space used to write the image * * Returns the color space that will be used to write the image. */ color_space get_color_space() const { return img_writting_colspace; } /** * @brief Iterator to the beginning. * * Returns an iterator to the beginning of this container. */ iterator begin() noexcept { return iterator(pixels); } /** * @brief Iterator to the beginning. * * Returns an iterator to the beginning of this container. */ const_iterator begin() const noexcept { return iterator(pixels); } /** * @brief Iterator to the end. * * Returns an iterator to the end of this container. */ iterator end() noexcept { return iterator(pixels + size_); } /** * @brief Iterator to the end. * * Returns an iterator to the end of this container. */ const_iterator end() const noexcept { return iterator(pixels + size_); } /** * @brief Iterator to the beginning. * * Returns an iterator to the beginning of this container. */ const_iterator cbegin() const noexcept { return const_iterator(pixels); } /** * @brief Iterator to the end. * * Returns an iterator to the end of this container. */ const_iterator cend() const noexcept { return const_iterator(pixels + size_); } /** * @brief Reverse iterator to the beginning. * * Returns a reverse iterator to the beginning of this container. */ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /** * @brief Reverse iterator to the end. * * Returns a reverse iterator to the end of this container. */ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /** * @brief Reverse iterator to the beginning. * * Returns a reverse iterator to the beginning of this container. */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /** * @brief Reverse iterator to the end. * * Returns a reverse iterator to the end of this container. */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } /** * @brief Image width * * Returns the width of the image. */ std::size_t width() const { return width_; } /** * @brief Image height * * Returns the height of the image. */ std::size_t height() const { return height_; } /** * @brief Image size * * Returns the size of the image, i.e., its ammount of pixels (width*height). */ std::size_t size() const { return size_; } /** * @brief Checks if the container is empty * * Checks if the image container is empty, i.e., it has no pixels. */ bool empty() const { return (size_ == 0) || (*this->cbegin() == *this->cend()); } /** * @brief Width and height as a rectangle * * Returns the width and height of an image, as a @ref rectangle. */ rectangle dimensions() const { return rectangle(width_,height_); } /** * @brief Access to underlying array * * Returns a pointer to the container's underlying array. */ value_type* data() noexcept { return pixels; } /** * @brief Access to underlying array * * Returns a pointer to the container's underlying array. */ const value_type* data() const noexcept { return pixels; } /** * @brief Equality operator * * Checks if two images are equal, i.e., they have the same content. */ friend bool operator==(const basic_image<PixelType>& lhs,const basic_image<PixelType>& rhs) { if (!(lhs.width_ == rhs.width_ && lhs.height_ == rhs.height_)) return false; for (std::size_t iy = 0; iy < lhs.height_; iy++) { for (std::size_t ix = 0; ix < lhs.width_; ix++) { if (lhs(ix,iy) != rhs(ix,iy)) return false; } } return true; } /** * @brief Inequality operator * * Checks if two images are not equal. */ friend bool operator!=(const basic_image<PixelType>& lhs,const basic_image<PixelType>& rhs) { return !(lhs == rhs); } private: color_space img_writting_colspace; std::size_t width_; std::size_t height_; std::size_t size_; value_type* pixels; }; template <typename PixelType> constexpr color_space basic_image<PixelType>::contained_color_space; /** * @ingroup types * @brief Same as `basic_image<rgba_t>`. * * @deprecated Unnecessary alias. Use @ref rgba_image instead. */ using image = basic_image<rgba_t>; /** * @ingroup types * @brief Same as `basic_image<nrgba_t>`. * * @deprecated Unnecessary alias. Use @ref nrgba_image instead. */ using norm_image = basic_image<nrgba_t>; /** * @ingroup types * @brief Same as `basic_image<rgb_t>`. */ using rgb_image = basic_image<rgb_t>; /** * @ingroup types * @brief Same as `basic_image<rgba_t>`. */ using rgba_image = basic_image<rgba_t>; /** * @ingroup types * @brief Same as `basic_image<gray_t>`. */ using gray_image = basic_image<gray_t>; /** * @ingroup types * @brief Same as `basic_image<ga_t>`. */ using ga_image = basic_image<ga_t>; /** * @ingroup types * @brief Same as `basic_image<nrgb_t>`. */ using nrgb_image = basic_image<nrgb_t>; /** * @ingroup types * @brief Same as `basic_image<nrgba_t>`. */ using nrgba_image = basic_image<nrgba_t>; /** * @ingroup types * @brief Same as `basic_image<ngray_t>`. */ using ngray_image = basic_image<ngray_t>; /** * @ingroup types * @brief Same as `basic_image<nga_t>`. */ using nga_image = basic_image<nga_t>; }} // end of "cynodelic::tesela" namespace #endif // CYNODELIC_TESELA_IMAGE_TYPES_HPP
true
6417b6f5b1cd32f81845bef23724c1054abb0d89
C++
killian05000/IUT
/Algo/tp1/tp1.cpp
UTF-8
717
3.125
3
[]
no_license
#include <iostream> #include <fstream> #include <unordered_map> using namespace std; unordered_map<string, size_t> mymap; //unordered_map<string, size_t>::const_iterator got = mymap.find(_content); void addWord(string _content) { // if (ca y est) // j'itere le compteur de ce mot // else // j'ajoute le mot } int main() { //unordered_map<string, size_t> mymap; string fileName="Jules_Verne_Voyage_au_centre_de_la_Terre.txt"; ifstream file(fileName, ios::in); if(file) { string content; while(file.good()) { file >> content; cout << content << endl; addWord(content); } file.close(); } else cerr << "Impossible d'ouvrir le fichier !" << endl; }
true
6ba7eb159b000d46d8f05249a21f7b0967813db6
C++
yuchen0515/online-judge-practice
/summer_Week5/uva10034_2.cpp
UTF-8
1,853
3.171875
3
[]
no_license
#include <iostream> #include <queue> #include <vector> #include <cmath> using namespace std; typedef struct Pair{ int32_t v; int32_t u; double w; }s_pair; struct cmp{ bool operator()(s_pair a, s_pair b){ return a.w > b.w; } }; double dist(pair<double, double> a, pair<double, double> b){ double tp_a = a.first - b.first; double tp_b = a.second - b.second; return sqrt((tp_a * tp_a) + (tp_b * tp_b)); } int32_t dis_find(int32_t root[], int32_t a){ if (a != root[a]){ return root[a] = dis_find(root, root[a]); }else return a; } void dis_union(int32_t root[], int32_t a, int32_t b){ int32_t x = dis_find(root, a); int32_t y = dis_find(root, b); if (x != y) root[y] = x; } int main(){ int32_t t = 0; cin >> t; for (int32_t p = 0 ; p < t; p ++){ if (p != 0) cout << endl; int32_t point_num = 0; double tp_x = 0, tp_y = 0; cin >> point_num; pair<double, double> num[point_num]; int32_t root[point_num]; for (int32_t i = 0; i < point_num ; i++){ cin >> tp_x >> tp_y; num[i] = {tp_x, tp_y}; root[i] = i; } priority_queue<s_pair, vector<s_pair>, cmp> stl; for (int32_t i = 0 ; i < point_num ; i++){ for (int32_t j = i+1 ; j < point_num ; j++){ stl.push({i, j, dist(num[i], num[j])}); stl.push({j, i, dist(num[i], num[j])}); } } double ans = 0; while (!stl.empty()){ s_pair temp = stl.top(); stl.pop(); if (dis_find(root, temp.u) != dis_find(root, temp.v)){ ans += temp.w; dis_union(root, temp.u, temp.v); } } printf("%.2f\n", ans); } return 0; }
true
12d3f7f1495f627290593fba7906e600c94a7c0e
C++
Vicondrus/DMPPRactice
/DMPPractice/2018R1EngProb3/2018R1EngProb3.ino
UTF-8
279
2.828125
3
[]
no_license
#include <Wire.h> void setup() { Wire.begin(); } void loop() { for(int i=0;i<20;i++){ int y = (1.5 + 1.5*sin(i/20 * 2*PI))*10; int toSend = map(y,0,33,0,255); Wire.beginTransmission(0x65); Wire.write(toSend); Wire.endTransmission(); delay(1); } }
true
9f5686ec4197a81fc75b59b9ef5dac397e15ecc7
C++
iitalics/ml
/src/Expression.h
UTF-8
884
2.5625
3
[]
no_license
#pragma once #include "Lexer.h" #include "Value.h" #include <memory> #include <vector> #include <string> #include <iostream> namespace ml { class Context; class Expression { public: virtual ~Expression () = 0; virtual std::string type () const = 0; virtual bool eval (Value*& out, Context* ctx, Error& err); }; namespace Exp { using ptr = std::shared_ptr<Expression>; struct LambaData { inline LambaData () : body(nullptr) {} std::vector<std::string> args; ptr body; }; typedef Value* (Context::*Generator) (); ptr makeInt (int_t num); ptr makeReal (real_t real); ptr makeVariable (const std::string& var, bool global = false); ptr makeApplication (ptr base, const std::vector<ptr>& args); ptr makeLambda (const LambaData& data); ptr makeGenerator (const std::string& name, Generator gen); ptr makeIf (ptr cond, ptr then, ptr otherwise); }; };
true
07ac46f856103c1b2900aaeb64a4391b40f24d26
C++
sheshanathkumar/coding
/Bit1.cpp
UTF-8
688
2.578125
3
[]
no_license
#include <bits/stdc++.h> using namespace std; long powerOne (long long x){ long count = 0; while (x){ x = x & (x-1); count ++; } return count; } int main (){ int test; cin >>test; while (test--){ int size, k = 0; long long arr[size], b[size]; long long hash [32] = {0}; for ( int i = 0; i<size; i++){ cin >> arr[i]; countOne (arr[i]); hash [count] ++; } for (int i = 1; <32; i++){ for (int j = 0; j < size; j++){ if ( hash[j] == i) b[k++] = a[] } } } }
true
f95c9e2cdfa63185e7678a38ea87e00cf81423ec
C++
shikhak101/leetcode
/BattleshipsInABoard.cpp
UTF-8
477
2.765625
3
[]
no_license
class Solution { public: int countBattleships(vector<vector<char>>& board) { int count = 0; for(int i=0; i<board.size(); i++) { for(int j = 0; j<board[i].size(); j++) { if(board[i][j] == 'X') { if(i>0 && board[i-1][j] == 'X') continue; else if(j>0 && board[i][j-1] == 'X') continue; else count++; } } } return count; } };
true
20b4a2e9868539aaecc864541c75d2a2bc32eb33
C++
rosoareslv/SED99
/c++/ClickHouse/2017/8/CastTypeBlockInputStream.h
UTF-8
1,561
2.84375
3
[ "BSL-1.0" ]
permissive
#pragma once #include <DataStreams/IProfilingBlockInputStream.h> namespace DB { class IFunction; /// Implicitly converts string and numeric values to Enum, numeric types to other numeric types. class CastTypeBlockInputStream : public IProfilingBlockInputStream { public: CastTypeBlockInputStream(const Context & context, const BlockInputStreamPtr & input, const Block & reference_definition); String getName() const override; String getID() const override; protected: Block readImpl() override; private: const Context & context; Block ref_defenition; /// Initializes cast_description and prepares tmp_conversion_block void initialize(const Block & src_block); bool initialized = false; struct CastElement { /// Prepared function to do conversion std::shared_ptr<IFunction> function; /// Position of first function argument in tmp_conversion_block size_t tmp_col_offset; CastElement(std::shared_ptr<IFunction> && function_, size_t tmp_col_offset_); }; /// Describes required conversions on source block /// Contains column numbers in source block that should be converted std::map<size_t, CastElement> cast_description; /// Auxiliary block, stores prefilled arguments and result for each CAST function in cast_description /// 3 columns are allocated for each conversion: [blank of source column, column with res type name, blank of res column] Block tmp_conversion_block; }; }
true
3a77789e3b71b79557d5a2022e5d654d3451a736
C++
rozPierog/FuzzyProject
/FuzzyProject/SimplyFuzzy.h
UTF-8
758
2.703125
3
[]
no_license
#ifndef SIMPLYFUZZY_H #define SIMPLYFUZZY_H #include<math.h> #include<malloc.h> #include "TermTrapez.h" struct Node { float value = 0; Node* next = NULL; }; class SimplyFuzzy { public: SimplyFuzzy(); ~SimplyFuzzy(); void init(); void setInputs(int left, int mid, int right); float getOutput(bool isLeft); private: TermTrapez inputTerms[4]; TermTrapez outPutTerms[6]; float outputValues[6]; float leftValues[4]; float midValues[4]; float rightValues[4]; Node* rulesTails[6]; Node rules[6]; float maxmax(int ruleNum); float maxmax(float arr[], int arrSize); float minmin(float a, float b, float c); void addNode(int ruleNum, float value); void cleanVariables(); void rulesLeft(); void rulesRight(); }; #endif // !SIMPLYFUZZY_H
true
925aa6e353f06fffb683775c0f7acf49a5bab861
C++
UnpureRationalist/learnModernCpp
/24distingushReference.cpp
UTF-8
1,080
3.1875
3
[]
no_license
#include <iostream> #include <vector> #include <Windows.h> using namespace std; /* 区分万能引用和右值引用 T&& 有两种含义:右值引用 和 万能引用 */ // 万能引用 template <typename T> void f(T &&param) { } int getInt() { return 0; } template <typename T> void f2(vector<T> &&param) // 是右值引用,不是万能引用 { } void f3(int n) { for (int i = 0; i < n; ++i) ; } int main() { auto &&var1 = getInt(); // 万能引用 涉及型别推导则为万能引用 否则为右值引用 vector<int> v; // f2(v); // 报错 模板不匹配 // 计算函数执行时间 C++ 14 auto timeFuncInvocation = [](auto &&func, auto &&...params) { auto start = GetTickCount(); // 计时器启动 forward<decltype(func)>(func)( forward<decltype(params)>(params)...); // 函数调用 auto end = GetTickCount(); // 计时器停止并计算时间间隔 cout << "run time = " << end - start << " ms" << endl; }; timeFuncInvocation(f3, 10000000); return 0; }
true
c0a18bed04562890adb042e29442766f521c4aca
C++
timofimo/GameEngine
/GameEngine/Input.cpp
UTF-8
2,965
2.890625
3
[]
no_license
#include "Input.h" GLFWwindow* Input::m_parentWindow; Input::KeyState Input::m_ks[]; Input::KeyState Input::m_mbs[]; glm::vec2 Input::m_mousePos; glm::vec2 Input::m_mouseLastPos; bool Input::m_cursorWithinBounds; /*utility includes*/ #include <iostream> Input::Input() { } Input::~Input() { } void Input::initialize() { double x, y; glfwGetCursorPos(m_parentWindow, &x, &y); setMousePosition(glm::vec2(x, y)); reset(); } void Input::reset() { for (int keyIndex = 0; keyIndex < GLFW_KEY_LAST; keyIndex++) { if (m_ks[keyIndex] == PRESS) m_ks[keyIndex] = HOLD; else if (m_ks[keyIndex] == RELEASE) m_ks[keyIndex] = UP; } for (int buttonIndex = 0; buttonIndex < GLFW_MOUSE_BUTTON_LAST; buttonIndex++) { if (m_mbs[buttonIndex] == PRESS) m_mbs[buttonIndex] = HOLD; else if (m_mbs[buttonIndex] == RELEASE) m_mbs[buttonIndex] = UP; } m_mouseLastPos = m_mousePos; } bool Input::getKey(int key) { return m_ks[key] == PRESS || m_ks[key] == HOLD; } bool Input::getKeyDown(int key) { return m_ks[key] == PRESS; } bool Input::getKeyUp(int key) { return m_ks[key] == RELEASE; } bool Input::getMouseButton(int button) { return m_mbs[button] == PRESS || m_mbs[button] == HOLD; } bool Input::getMouseButtonDown(int button) { return m_mbs[button] == PRESS; } bool Input::getMouseButtonUp(int button) { return m_mbs[button] == RELEASE; } glm::vec2 Input::getMousePosition() { return m_mousePos; } glm::vec2 Input::getMouseTranslation() { return m_mouseLastPos - m_mousePos; } void Input::setMousePosition(glm::vec2 pos) { if (m_parentWindow) { glfwSetCursorPos(m_parentWindow, pos.x, pos.y); m_mousePos = m_mouseLastPos = pos; } } void Input::setMouseMode(int mode) { if (mode < GLFW_CURSOR_NORMAL || mode > GLFW_CURSOR_DISABLED) return; glfwSetInputMode(m_parentWindow, GLFW_CURSOR, mode); } bool Input::cursorWithinBounds() { return m_cursorWithinBounds; } void Input::setKey(int key, int action) { if (action == GLFW_REPEAT) return; if (action == GLFW_PRESS) { if (m_ks[key] == UP) m_ks[key] = PRESS; else if (m_ks[key] == PRESS) m_ks[key] = HOLD; } else if (action == GLFW_RELEASE) { if (m_ks[key] == PRESS || m_ks[key] == HOLD) m_ks[key] = RELEASE; } else { m_ks[key] = UP; } } void Input::setMouseButton(int button, int action) { if (action == GLFW_REPEAT) return; if (action == GLFW_PRESS) { if (m_mbs[button] == UP) m_mbs[button] = PRESS; else if (m_mbs[button] == PRESS) m_mbs[button] = HOLD; } else if (action == GLFW_RELEASE) { if (m_mbs[button] == PRESS || m_mbs[button] == HOLD) m_mbs[button] = RELEASE; } else { m_mbs[button] = UP; } } void Input::setMousePos(double x, double y) { m_mousePos = glm::vec2(x, y); } void Input::setCursorWithinBounds(int action) { if (action == GL_TRUE) m_cursorWithinBounds = true; else m_cursorWithinBounds = false; } void Input::setParentWindow(GLFWwindow* window) { m_parentWindow = window; }
true
02420fd6bcd137548240ea87af5cf7e801acbeb2
C++
Roy19/advanced_cplusplus
/standard_template_library/maps.cpp
UTF-8
675
3.890625
4
[]
no_license
#include <iostream> #include <map> #include <string> using namespace std; int main(){ map<string, int> ages; // create a key,value pair table // key: string, value: int ages["Mike"] = 40; ages["Raj"] = 50; ages["John"] = 60; // print all elements in the map for(map<string, int>::iterator it = ages.begin();it != ages.end();it++){ cout << it->first << ": " << it->second << endl; } // trying to check ages["Sue"] will result in creating a new key value pair // Sue: 0 //instead use this method if(ages.find("Sue") != ages.end()){ cout << "Found Sue. Sue: " << ages["Sue"] << endl; }else{ cout << "Could not find Sue." <<endl; } return 0; }
true
319aebf843b36c732dbee693b81a2e063c6d29d1
C++
Akshayy99/3D-Game-Opengl
/plane.cpp
UTF-8
5,431
2.84375
3
[]
no_license
#include "plane.h" #include "main.h" Plane::Plane(float x, float y, float z, color_t color) { this->position = glm::vec3(x, y, z); this->yaw = 0; this->roll = 0; this->pitch = 0; float n = 300; len = 10.0; float len2 = 13.0; float len_head = 2.0; speed = 3; rise = false; fall = false; speedy = 0; g1 = 0.002; g2 = 0.0005; max_fuel = 20; fuel = max_fuel; float theta = 2*3.14159/n; this->radius = 1.5; int numTriangles = 300; // cylindrical portion of the plane GLfloat vertex_buffer_data1[numTriangles*18]; for(int i=0; i<numTriangles; i++) { float angleBefore = theta * (180 + i); float angle = angleBefore + theta; vertex_buffer_data1[i*18] = this->radius * cos(angleBefore); vertex_buffer_data1[i*18+1] = this->radius * sin(angleBefore); vertex_buffer_data1[i*18+2] = len; vertex_buffer_data1[i*18+3] = this->radius * cos(angle); vertex_buffer_data1[i*18+4] = this->radius * sin(angle); vertex_buffer_data1[i*18+5] = len; vertex_buffer_data1[i*18+6] = this->radius * cos(angleBefore); vertex_buffer_data1[i*18+7] = this->radius * sin(angleBefore); vertex_buffer_data1[i*18+8] = 0.0f; vertex_buffer_data1[i*18+9] = this->radius * cos(angleBefore); vertex_buffer_data1[i*18+10] = this->radius * sin(angleBefore); vertex_buffer_data1[i*18+11] = 0.0f; vertex_buffer_data1[i*18+12] = this->radius * cos(angle); vertex_buffer_data1[i*18+13] = this->radius * sin(angle); vertex_buffer_data1[i*18+14] = len; vertex_buffer_data1[i*18+15] = this->radius * cos(angle); vertex_buffer_data1[i*18+16] = this->radius * sin(angle); vertex_buffer_data1[i*18+17] = 0.0f; } // wings of the plane static GLfloat vertex_buffer_data2[] = { 0.0f, 0.6f*this->radius, 0.3f*len, 0.0f, 0.6f*this->radius, 0.6f*len, -len2/2, -0.6f*this->radius, 0.6f*len, 0.0f, 0.6f*this->radius, 0.6f*len, -len2/2, -0.6f*this->radius, 0.6f*len, -(8/15.0f)*len2, -0.6f*this->radius, 0.7f*len, 0.0f, 0.6f*this->radius, 0.3f*len, 0.0f, 0.6f*this->radius, 0.6f*len, len2/2, -0.6f*this->radius, 0.6f*len, 0.0f, 0.6f*this->radius, 0.6f*len, len2/2, -0.6f*this->radius, 0.6f*len, (8/15.0f)*len2, -0.6f*this->radius, 0.7f*len }; // conical head of the plane GLfloat vertex_buffer_data3[numTriangles*18]; for(int i=0;i<numTriangles;i++) { float angleBefore = theta * (180 + i); float angle = angleBefore + theta; vertex_buffer_data3[i*9] = 0.0f; vertex_buffer_data3[i*9+1] = -0.2f; vertex_buffer_data3[i*9+2] = -len_head; vertex_buffer_data3[i*9+3] = this->radius * cos(angleBefore); vertex_buffer_data3[i*9+4] = this->radius * sin(angleBefore); vertex_buffer_data3[i*9+5] = 0.0f; vertex_buffer_data3[i*9+6] = this->radius * cos(angle); vertex_buffer_data3[i*9+7] = this->radius * sin(angle); vertex_buffer_data3[i*9+8] = 0.0f; } this->object1 = create3DObject(GL_TRIANGLES, numTriangles*6, vertex_buffer_data1, {22,29,116}, GL_FILL); this->object2 = create3DObject(GL_TRIANGLES, 4*3, vertex_buffer_data2, {38,54,111}, GL_FILL); this->object3 = create3DObject(GL_TRIANGLES, numTriangles*3, vertex_buffer_data3, {38,54,111}, GL_FILL); } void Plane::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate1 = glm::rotate((float) (this->yaw * M_PI / 180.0f), glm::vec3(0, -1, 0)); glm::mat4 rotate2 = glm::rotate((float) (this->roll * M_PI / 180.0f), glm::vec3(0, 0, -1)); glm::mat4 rotate3 = glm::rotate((float) (this->pitch * M_PI / 180.0f), glm::vec3(1, 0, 0)); // No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate // rotate = rotate * glm::translate(glm::vec3(0, -2, 0)); Matrices.model *= (translate*rotate1*rotate3*rotate2); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->object1); draw3DObject(this->object2); draw3DObject(this->object3); } void Plane::set_position(float x, float y, float z = 0) { this->position = glm::vec3(x, y, z); } void Plane::tick() { this->fuel -= 0.001; this->position.z -= this->speed * cos(this->yaw * M_PI / 180.0f) * cos(this->pitch * M_PI /180.0f); this->position.x += this->speed * sin(this->yaw * M_PI / 180.0f); this->position.y += this->speed * sin(this->pitch * M_PI / 180.0f); float alt_default = 0; // if(this->rise){ // this->position.y += 1; // } if(this->fall){ this->position.y -= 1; } if(this->position.y > alt_default && !this->rise && !this->fall) this->position.y -= speedy; if(this->position.y < alt_default && !this->rise && !this->fall) // this->position.y = alt_default; if(this->position.y > alt_default + 10 && !this->rise) { this->speedy -= this->g1; } else if(this->position.y >= alt_default && !this->rise) { this->speedy -= this->g2; } // this->rotation += speed; // this->position.x -= speed; // this->position.y -= speed; }
true
a4a8402b6faa9300ad7d446adabad62efb4c5325
C++
pauld4/Portfolio
/c++/clocks.cpp
UTF-8
2,853
4.25
4
[]
no_license
/* * Clocks.cpp * * Clock application that starts at 0:00:00 and can add an hour, minute, or second to the time. * By Paul Dziedzic * */ #include <iostream> #include <iomanip> using namespace std; //adds an hour to the time void addHour(int& cTime) { cTime = cTime + 3600; if(cTime >= 86400) { cTime = cTime - 86400; } } //adds a minute to the time void addMinute(int& cTime) { cTime = cTime + 60; if(cTime >= 86400) { cTime = cTime - 86400; } } //adds a second to the time void addSecond(int& cTime) { cTime = cTime + 1; if(cTime >= 86400) { cTime = cTime - 86400; } } //prints the time in 12 hour format, with PM/AM void print12Hour(int cTime) { int hour = cTime / 3600; int minute = (cTime % 3600) / 60; int second = (cTime % 3600) % 60; string ampm = (cTime >= (12 * 3600)) ? "PM" : "AM"; if(hour > 12) { hour = hour - 12; } if(hour == 0) { hour = 12; } cout << setfill('0'); cout << setw(2) << hour << ":"; cout << setfill('0'); cout << setw(2) << minute << ":"; cout << setfill('0'); cout << setw(2) << second << " " << ampm; } //prints the time in 24 hour format void print24Hour(int cTime) { int hour = cTime / 3600; int minute = (cTime % 3600) / 60; int second = (cTime % 3600) % 60; cout << setfill('0'); cout << setw(2) << hour << ":"; cout << setfill('0'); cout << setw(2) << minute << ":"; cout << setfill('0'); cout << setw(2) << second; } int main() { int clockTime = 0; int userInput = 0; while(userInput != 4) { //process user input if requesting to add an hour, minute, or second if(userInput == 1) { addHour(clockTime); } else if(userInput == 2) { addMinute(clockTime); } else if(userInput == 3) { addSecond(clockTime); } //print both clocks cout << "*************************** ***************************" << endl; cout << "* 12-Hour Clock * * 24-Hour Clock *" << endl; cout << "* "; print12Hour(clockTime); cout << " * * "; print24Hour(clockTime); cout << " *" << endl; cout << "*************************** ***************************" << endl; cout << endl; //print menu cout << "**************************" << endl; cout << "* 1 - Add One Hour *" << endl; cout << "* 2 - Add One Minute *" << endl; cout << "* 3 - Add One Second *" << endl; cout << "* 4 - Exit Program *" << endl; cout << "**************************" << endl; //get user input for next selection cin >> userInput; } cout << "Exiting program." << endl; return 0; }
true
43e858d1be0c4a9700a6f407408773c22d17fd59
C++
d34th4ck3r/Random-Codes
/deepest_root.cpp
UTF-8
552
2.828125
3
[]
no_license
#include<iostream> #include<vector> #include<string> #include<map> #include<cstdio> #include<cmath> #include<algorithm> #include<limits> #include<set> using namespace std; class Node{ public: int val; Node *next; Node(int x): val(x), next(NULL){} }; class BinaryTree{ public: int val; BinaryTree *left; BinaryTree *right; BinaryTree(int x): val(x),left(NULL),right(NULL){} BinaryTree(int x, BinaryTree *left, BinaryTree *right): val(x), left(left),right(right){} } int main() { return 0; }
true
1b4873735af784fa441f33c3f311a43b35768bfb
C++
qq834719601/KeRuiNote
/周作业/base64/review/review.cpp
GB18030
3,803
2.5625
3
[]
no_license
// review.cpp : ̨Ӧóڵ㡣 // #include "stdafx.h" #include <iostream> #include <fstream> using namespace std; #pragma warning(disable:4996) char base64[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxzy0123456789+/"; void base64_encode(const char* strI, int nLength, char* strO); void dec(const char* strI, int nLength, char* strO); void Find_Index(const char* str, char* Index); int _tmain(int argc, _TCHAR* argv[]) { ifstream fp; ofstream ofp; ofstream decyOfp; char *p = NULL; char szBuf[256] = { 0 }; char szOutBuf[256] = { 0 }; fp.open("enc.txt"); //fp.open("˺.txt"); decyOfp.open("decy.txt"); if (fp.is_open()&&decyOfp.is_open()) { fp.seekg(3,fp.beg); while (!fp.eof()) { memset(szBuf, 0, 256); fp.getline(szBuf, 256); //˺ p = (char*)malloc(sizeof(char)*strlen(szBuf)); p=strtok(szBuf, "----"); if (NULL == p) { break; } decyOfp << p; // p = strtok(NULL, "----"); dec(p, strlen(p), szOutBuf); decyOfp << "----" << szOutBuf << endl; } } fp.close(); ofp.close(); return 0; } void base64_encode(const char* strI, int nLength, char* strO) { /* 8 8 8 6 2+4 4+2 6 */ unsigned char arry3B[3] = { 0 }; unsigned char arry4B[4] = { 0 }; int nCount = 0; int n = 0; memset(strO, 0, 256); nLength % 3 ? nCount = nLength/3 : nCount = nLength/3 + 1; for (int i = 0; i < nCount; i++) { arry3B[0] = strI[3 * i]; arry3B[1] = strI[3 * i+1]; arry3B[2] = strI[3 * i + 2]; memset(arry4B, 0, 4); //arry4B[0] = base64[arry3B[0] >> 2 & 0x3F]; strO[n++] = base64[arry3B[0] >> 2 & 0x3F]; //arry4B[1] = base64[(arry3B[0] << 4 & 0x30) | (arry3B[1] >> 4 & 0x0F)]; strO[n++] = base64[(arry3B[0] << 4 & 0x30) | (arry3B[1] >> 4 & 0x0F)]; //arry4B[2] = base64[(arry3B[1] << 2 & 0x3c) | (arry3B[2] >> 6 & 0x03)]; strO[n++] = base64[(arry3B[1] << 2 & 0x3c) | (arry3B[2] >> 6 & 0x03)]; //char c = arry3B[3] & 0x3F; strO[n++] = base64[arry3B[2] & 0x3F]; } //ոĵȺŸ if (nLength % 3 == 1) { strO[n] = strO[n+1] = '='; } else if (nLength % 3 == 2) { strO[n] = '='; } } void dec( const char* strI, int nLength, char* strO) { /* 6 6 6 6 6+2 4+4 2+6 */ unsigned char arry3B[3] = { 0 }; unsigned char arry4B[4] = { 0 }; int nCount = 0; int n = 0; char nIndex[4] = { 0 }; nCount = nLength / 4; for (int j = 0; j < nCount; j++) { arry4B[0] = strI[j * 4]; arry4B[1] = strI[j * 4+1]; arry4B[2] = strI[j * 4+2]; arry4B[3] = strI[j * 4+3]; Find_Index(&strI[j * 4], nIndex); //arry3B[0] =(nIndex[0] << 2 & 0xFC) | (nIndex[1] >> 4 & 0x03); strO[n++] = (nIndex[0] << 2 & 0xFC) | (nIndex[1] >> 4 & 0x03); //arry3B[1] = (nIndex[1] << 4 & 0xF0) | (nIndex[2] >> 2 & 0x0F); strO[n++] = (nIndex[1] << 4 & 0xF0) | (nIndex[2] >> 2 & 0x0F); //arry3B[2] = (nIndex[2] << 6 & 0xC0) | nIndex[3]; strO[n++] = (nIndex[2] << 6 & 0xC0) | nIndex[3]; } } void Find_Index(const char* str,char* Index) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 64; j++) { if (str[i] == base64[j]) { Index[i] = j; break; } } } }
true
f8f9247ab782b6eb88df129ebdb5789b89eeb187
C++
Veirisa/TranslationMethods
/ManualBuilding/lexical_analyzer.cpp
UTF-8
2,707
3.359375
3
[]
no_license
#include "lexical_analyzer.h" lexical_analyzer::lexical_analyzer() : s(), cur_pos(0), cur_token(BEGIN), cur_token_length(0) {}; lexical_analyzer::lexical_analyzer(const string& in) : s(in), cur_pos(0), cur_token(BEGIN), cur_token_length(0) {}; bool lexical_analyzer::is_blank(size_t pos) { return s[pos] == ' ' || s[pos] == '\r' || s[pos] == '\n' || s[pos] == '\t'; } bool lexical_analyzer::is_letter(size_t pos) { return (s[pos] >= 'a' && s[pos] <= 'z') || (s[pos] >= 'A' && s[pos] <= 'Z'); } bool lexical_analyzer::is_number(size_t pos) { return (s[pos] >= '0' && s[pos] <= '9'); } bool lexical_analyzer::is_end_of_size(size_t pos) { return s[pos] == ']'; } bool lexical_analyzer::is_end(size_t pos) { return pos == s.size(); } void lexical_analyzer::inc_pos(size_t x) { cur_pos += x; if (cur_pos > s.size()) { throw parser_exception("Out of string range"); } } void lexical_analyzer::next_token() { inc_pos(cur_token_length); while (is_blank(cur_pos)) { inc_pos(1); } cur_token_length = 1; if (is_end(cur_pos)) { cur_token = END; return; } switch (s[cur_pos]) { case '*': cur_token = STAR; break; case ',': cur_token = COMMA; break; case ';': cur_token = SEMICOLON; break; case '[': cur_token = SIZE; while (!is_end(cur_pos + cur_token_length) && !is_end_of_size(cur_pos + cur_token_length) && is_number(cur_pos + cur_token_length)) { ++cur_token_length; } if (cur_token_length < 2 || !is_end_of_size(cur_pos + cur_token_length)) { throw parser_exception("Illegal token", cur_pos); } ++cur_token_length; break; default: if (is_letter(cur_pos)) { cur_token = NAME; while (!is_end(cur_pos + cur_token_length) && is_letter(cur_pos + cur_token_length)) { ++cur_token_length; } } else { if (is_end_of_size(cur_pos) || is_number(cur_pos)) { throw parser_exception("Illegal token", cur_pos); } throw parser_exception("Illegal character", cur_pos); } } } size_t lexical_analyzer::get_cur_pos() { return cur_pos; } token lexical_analyzer::get_cur_token() { return cur_token; } string lexical_analyzer::get_cur_token_string() { if (cur_token == END) { throw parser_exception("Impossible to get string representation of the end"); } return string(s, cur_pos, cur_token_length); }
true
4c23f648e98c55a9c03c43193a7733e3e188f7e7
C++
Firlej/SK2-hangman
/server/server.cpp
UTF-8
12,381
2.59375
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> //FD_SET, FD_ISSET, FD_ZERO macros #include <string> #include <pthread.h> #include <time.h> /* time */ #define PORT 2000 #define MAX_CLIENTS 3 #define MIN_CLIENTS 2 #define LIVES 8 #define FOR(i, n) for(int i=0; i<n; i++) #define WORDS 4 char words[WORDS][30] = { "ABC", "XYZ", "QWERTY", "WASD", }; void reset_game(); struct Client { char username[30]; // char guessed[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int lives = LIVES; int done = true; // is player done with this round -> lose, or guessed, or just joined an ongoing game char word[30]; int socket; // 0 == free socket } clients[MAX_CLIENTS]; struct Game { char word[30]; bool on = false; } game; bool wordwin(int index) { if (strcmp(clients[index].word, game.word) == 0) { clients[index].done = true; return true; } else { return false; } } int allplayers() { int cnt = 0; FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0) { cnt++; } } return cnt; } int activeplayers() { int cnt = 0; FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0 && !clients[i].done) { cnt++; } } return cnt; } void sendHeader() { char clients_conn[2 + sizeof(char)]; char clients_playing[2 + sizeof(char)]; snprintf(clients_conn, sizeof clients_conn, "%d", allplayers()); snprintf(clients_playing, sizeof clients_playing, "%d", activeplayers()); char header[100] = "header,"; strcat(header, "Connected!"); strcat(header, " | Players connected: "); strcat(header, clients_conn); strcat(header, " | PLayers playing: "); strcat(header, clients_playing); strcat(header, "."); FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0) { if((unsigned)send(clients[i].socket, header, strlen(header), 0) != strlen(header)) { perror("send"); } } } } void reset_client(int i) { clients[i].socket = 0; clients[i].done = true; strcpy(clients[i].word, ""); } void sendWord(int i) { char wordUpdate[100] = "wordUpdate,"; strcat(wordUpdate, clients[i].word); strcat(wordUpdate, "\n\nLives left:"); char str[12]; sprintf(str, "%d", clients[i].lives); strcat(wordUpdate, " "); strcat(wordUpdate, str); strcat(wordUpdate, "."); if((unsigned)send(clients[i].socket, wordUpdate, strlen(wordUpdate), 0) != strlen(wordUpdate)) { perror("send"); } } void sendClients() { char usersLives[500] = "usersLives,"; FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0) { char str[12]; if (!clients[i].done) { strcat(usersLives, "PLAYING | "); } else { if (strcmp(clients[i].word, "") == 0) { strcat(usersLives, "LOBBY | "); } else if (wordwin(i)) { strcat(usersLives, "WINNER | "); } else if (clients[i].lives <= 0) { strcat(usersLives, "HANGED | "); } else { strcat(usersLives, "LOBBY2 | "); } } sprintf(str, "%d", clients[i].lives); strcat(usersLives, clients[i].username); strcat(usersLives, ": "); strcat(usersLives, str); strcat(usersLives, "\n\n"); } } strcat(usersLives, "."); FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0) { if((unsigned)send(clients[i].socket, usersLives, strlen(usersLives), 0) != strlen(usersLives)) { perror("send"); } } } } void reset_game() { printf("All players: %d\n", activeplayers()); printf("Active players: %d\n", activeplayers()); if (activeplayers() > 0 || allplayers() == 0) { return; } if (allplayers() < MIN_CLIENTS) { FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0) { clients[i].done = true; } } sendClients(); sendHeader(); return; } srand(time(NULL)); int index = rand() % WORDS; strcpy(game.word, words[index]); printf("%s\n", game.word); game.on = true; FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0) { strcpy(clients[i].word, game.word); for (int j=0; clients[i].word[j] != '\0'; j++) { clients[i].word[j] = '_'; } clients[i].lives = LIVES; clients[i].done = false; sendWord(i); } } sendClients(); sendHeader(); } void guess(int index, char guess) { if (game.on && !clients[index].done) { bool guessed = false; for (int i=0; game.word[i] != '\0'; i++) { if (game.word[i] == guess) { guessed = true; clients[index].word[i] = guess; } } if (wordwin(index)) { clients[index].done = true; sendClients(); sendHeader(); reset_game(); } if (!guessed) { clients[index].lives--; if (clients[index].lives <= 0) { clients[index].done = true; } sendClients(); sendHeader(); reset_game(); } sendWord(index); } } int main(int argc , char *argv[]) { printf("Starting server...\n"); int opt = true; int master_socket, addrlen, new_socket, activity, valread, sd; int max_sd; struct sockaddr_in address; char buffer[1024]; //data buffer of 1K //set of socket descriptors fd_set readfds; // set all sockets to 0 FOR(i, MAX_CLIENTS) { clients[i].socket = 0; } //create a master socket if( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0) { perror("socket failed"); exit(EXIT_FAILURE); } //set master socket to allow multiple connections , if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ) { perror("setsockopt"); exit(EXIT_FAILURE); } //type of socket created address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(PORT); if (bind(master_socket, (struct sockaddr *)&address, sizeof(address))<0) { perror("bind failed"); exit(EXIT_FAILURE); } printf("Listening on port %d \n", PORT); //try to specify maximum of MAX_CLIENTS pending connections for the master socket if (listen(master_socket, MAX_CLIENTS) < 0) { perror("listen"); exit(EXIT_FAILURE); } //accept the incoming connection addrlen = sizeof(address); puts("Waiting for connections ..."); while (true) { //clear the socket set FD_ZERO(&readfds); //add master socket to set FD_SET(master_socket, &readfds); max_sd = master_socket; FOR(i, MAX_CLIENTS) { //socket descriptor sd = clients[i].socket; //if valid socket descriptor then add to read list if(sd > 0) FD_SET(sd, &readfds); //highest file descriptor number, need it for the select function if(sd > max_sd) max_sd = sd; } activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL); if ((activity < 0) && (errno!=EINTR)) { printf("select error"); } // incoming connection if (FD_ISSET(master_socket, &readfds)) { // check for errors if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) { perror("accept"); exit(EXIT_FAILURE); } valread = read(new_socket, buffer, 1024); // printf("%s\n", buffer); // todo remove if (valread <= 0) { printf("Empty username\n"); continue; } char *ptr = strtok(buffer, ","); ptr = strtok(NULL, ","); char *username = ptr; // check for player count if (allplayers() >= MAX_CLIENTS) { printf("Too many users\n"); char limit[30] = "limit."; if ((unsigned)send(new_socket, limit, strlen(limit), 0) != strlen(limit) ) { perror("send"); } continue; } // check for duplicate username bool duplicate_user_error = false; FOR(i, MAX_CLIENTS) { if (clients[i].socket != 0 && strcmp(username, clients[i].username ) == 0) { printf("User tried to log in with duplicate username\n"); char duplicate[30] = "duplicate."; if ((unsigned)send(new_socket, duplicate, strlen(duplicate), 0) != strlen(duplicate)) { perror("send"); } duplicate_user_error = true; break; } } if (duplicate_user_error) { continue; } // inform user of socket number - used in send and receive commands printf( "New connection, socket fd: %d, ip: %s, port: %d\n", new_socket, inet_ntoa(address.sin_addr), ntohs(address.sin_port) ); // save client information FOR(i, MAX_CLIENTS) { if (clients[i].socket == 0) { clients[i].socket = new_socket; strcpy(clients[i].username, username); char wordUpdate[100] = "wordUpdate,"; strcat(wordUpdate, "Succesfully connected\nPlease wait for\nthe next game to start."); if((unsigned)send(clients[i].socket, wordUpdate, strlen(wordUpdate), 0) != strlen(wordUpdate)) { perror("send"); } if (game.on) { clients[i].done = true; } reset_game(); sendHeader(); sendClients(); break; } } } // else its some IO operation on some other socket FOR(i, MAX_CLIENTS) { if (FD_ISSET(clients[i].socket, &readfds)) { //Check if it was for closing, and also read the incoming message if ((valread = read(clients[i].socket, buffer, 1024)) <= 0) { //Somebody disconnected getpeername(clients[i].socket, (struct sockaddr*)&address, (socklen_t*)&addrlen); printf("%s disconnected\n", clients[i].username); //Close the socket and mark as 0 in list for reuse close(clients[i].socket); allplayers(); reset_client(i); if (allplayers() == 0) { game.on = false; } reset_game(); sendClients(); sendHeader(); } else { //set the string terminating NULL byte on the end of the data read buffer[valread] = '\0'; printf("message received from %s: %s\n", clients[i].username, buffer); char delim[] = ","; char *ptr = strtok(buffer, delim); char *type = ptr; ptr = strtok(NULL, delim); char *message = ptr; // printf("%s\n", message); if (strcmp(type, "guess") == 0) { guess(i, message[0]); } } } } } return 0; }
true
ef27464846f89ab16d63625a3a4bc7b951aa9247
C++
kmc7468/BOJ
/P14487.cpp
UTF-8
228
2.96875
3
[]
no_license
#include <iostream> int main() { int n; std::cin >> n; int sum = 0, max = 0; for (int i = 0; i < n; ++i) { int cost; std::cin >> cost; sum += cost; if (cost > max) { max = cost; } } std::cout << sum - max; }
true
d8b1fe2496d6ffe8a240098f57f4fe9a794fdee8
C++
adamcavendish/HomeworkGitShare
/DataStructures/Homework/03/0305.cpp
UTF-8
806
3.015625
3
[]
no_license
#include "../List/List" #include <cstring> #include <iostream> using namespace adamcavendish::data_structure; int main(int argc, char * argv[]) { if(argc != 3) return 1; List<char> t1(&argv[1][0], &argv[1][strlen(argv[1])]); List<char> t2(&argv[2][0], &argv[2][strlen(argv[2])]); auto bgn1 = t1.begin(); auto bgn2 = t2.begin(); auto end1 = t1.cend(); auto end2 = t2.cend(); while(bgn1 != end1 && bgn2 != end2) { if(*bgn1 == *bgn2) { bgn1 = t1.erase(bgn1); bgn2 = t2.erase(bgn2); } else { ++bgn1; ++bgn2; break; }//if-else }//while std::cout << "testA: " << std::endl; for(auto i : t1) std::cout << i << ' '; std::cout << std::endl; std::cout << "testB: " << std::endl; for(auto i : t2) std::cout << i << ' '; std::cout << std::endl; return 0; }//main
true
9d193a182bffc7f0ad279f6bc746e1388cee9755
C++
IhorHandziuk/LagrangePolynomial
/LagrangePolynomial.h
UTF-8
798
2.921875
3
[ "MIT" ]
permissive
#ifndef LAGRANGEPOLYNOMIAL_H #define LAGRANGEPOLYNOMIAL_H #include <vector> using std::vector; using std::pair; class LagrangePolynomial { public: bool addPoint(float x, float y); bool removePoint(float x, float y); void removeAllPoints(); float getPolynomialAtPoint(float x); vector<float> getPolynomialCoefficients(); vector<pair<float, float>> getPoints(); private: vector<pair<float, float>> points; vector<float> polynomialCoefficients; vector<pair<float, float>> swapPoints; vector<float> leftSideTerms; vector<float> rightSideTerms; float eps = 0.1; double distance(pair<float, float> p1, pair<float, float> p2); void swapping(int k); void solve(int len, double mult, int shift); }; #endif //LAGRANGEPOLYNOMIAL_H
true
a3b72d325a09c15a15720fa2fe9dabfe1a6204d4
C++
marthall/TDT4102
/Oving 02/ex5.cpp
UTF-8
395
3.59375
4
[]
no_license
#include <iostream> #include <cmath> using namespace std; int callByValue(int); void callByReference(int&); int main() { int a = 10; int b = 10; int c = callByValue(a); callByReference(b); cout << a << endl << b << endl << c << endl; return 0; } int callByValue(int number) { return (pow(number, 2) + 10)*2; } void callByReference(int &number) { number = (pow(number, 2) + 10)*2; }
true
394bdfae0050a4debcd51e2df2821ac42757d56b
C++
vitorecomp/PooProject
/Exemplo/trabalho 1/poo/testes/testestipos.h
UTF-8
7,578
2.546875
3
[]
no_license
//--------------------------------------------------------------------------- #ifndef testestiposH #define testestiposH #include <iostream> #include "..\header\Dominios.h" #include "..\header\Entidades.h" //--------------------------------------------------------------------------- /** * \mainpage Testes do Sistema de Projetos de Alunos * Esse sistema realiza os testes dos tipos basicos definidos no Sistema de Projeto de Alunos. * Para cada tipo basico realiza-se um teste usando um argumento valido e um invalido. * */ /// Classe TesteUnidade /** Classe basica para realizacao dos testes*/ class TesteUnidade { public: virtual void setUp() = 0; virtual void tearDown() = 0; virtual void run() = 0; }; /// Classe TesteUnidadeCodigo_Projeto /** Realiza o teste de validez da classe Codigo_Projeto */ class TesteUnidadeCodigo_Projeto: public TesteUnidade, public Codigo_Projeto { private: Codigo_Projeto *codigo_projeto; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Codigo_Projeto */ void setUp(){ codigo_projeto = new Codigo_Projeto; } /** * \brief deleta a instancia da classe Codigo_Projeto */ void tearDown(){ delete codigo_projeto; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeCodigo_Modulo /** Realiza o teste de validez da classe Codigo_Modulo */ class TesteUnidadeCodigo_Modulo: public TesteUnidade, public Codigo_Modulo{ private: Codigo_Modulo *codigo_modulo; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Codigo_Modulo */ void setUp(){ codigo_modulo = new Codigo_Modulo; } /** * \brief deleta a instancia da classe Codigo_Modulo */ void tearDown(){ delete codigo_modulo; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeCodigo_Fase /** Realiza o teste de validez da classe Codigo_Fase */ class TesteUnidadeCodigo_Fase: public TesteUnidade, public Codigo_Fase{ private: Codigo_Fase *codigo_fase; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Codigo_Fase */ void setUp(){ codigo_fase = new Codigo_Fase; } /** * \brief deleta a instancia da classe Codigo_Fase */ void tearDown(){ delete codigo_fase; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeData_Inicio /** Realiza o teste de validez da classe Data_Inicio */ class TesteUnidadeData_Inicio: public TesteUnidade, public Data_Inicio{ private: Data_Inicio *data_inicio; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Data_Inicio */ void setUp(){ data_inicio = new Data_Inicio; } /** * \brief deleta a instancia da classe Data_Inicio */ void tearDown(){ delete data_inicio; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeData_Termino /** Realiza o teste de validez da classe Data_Termino*/ class TesteUnidadeData_Termino: public TesteUnidade, public Data_Termino{ private: Data_Termino *data_termino; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Data_Termino */ void setUp(){ data_termino = new Data_Termino; } /** * \brief deleta a instancia da classe Data_Termino */ void tearDown(){ delete data_termino; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeMatricula /** Realiza o teste de validez da classe Matricula */ class TesteUnidadeMatricula: public TesteUnidade, public Matricula { private: Matricula *matricula; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Matricula */ void setUp(){ matricula = new Matricula; } /** * \brief deleta a instancia da classe Matricula */ void tearDown(){ delete matricula; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run() { setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeNome_Arquivo /** Realiza o teste de validez da classe Nome_Arquivo*/ class TesteUnidadeNome_Arquivo: public TesteUnidade, public Nome_Arquivo { private: Nome_Arquivo *nome_arquivo; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Nome_Arquivo */ void setUp(){ nome_arquivo = new Nome_Arquivo; } /** * \brief deleta a instancia da classe Nome_Arquivo */ void tearDown(){ delete nome_arquivo; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeNota /** Realiza o teste de validez da classe Nota */ class TesteUnidadeNota: public TesteUnidade, public Nota{ private: Nota *nota; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Nota */ void setUp(){ nota = new Nota; } /** * \brief deleta a instancia da classe Nota */ void tearDown(){ delete nota; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; /// Classe TesteUnidadeTamanho /** Realiza o teste de validez da classe Tamanho*/ class TesteUnidadeTamanho: public TesteUnidade, public Tamanho{ private: Tamanho *tamanho; void testarValido(); void testarInvalido(); public: /** * \brief cria uma instancia da classe Tamanho */ void setUp(){ tamanho = new Tamanho; } /** * \brief deleta a instancia da classe Tamanho */ void tearDown(){ delete tamanho; } /** * \brief executa o setUp(), testarValido() , testarInvalido(), tearDown(). */ void run(){ setUp(); testarValido(); testarInvalido(); tearDown(); } }; #endif
true
1075ffb6a100e57baa7a5e6baf9e571bea61b519
C++
nysanier/cf
/nc/huawei/test2.cpp
UTF-8
409
2.75
3
[]
no_license
#include <iostream> #include <algorithm> const int N = 1000; int a[N]; int n; int main() { while (std::cin >> n) { for (int i = 0; i < n; ++i) { std::cin >> a[i]; } std::sort(a, a + n); auto p = std::unique(a, a + n); int n2 = p - a; for (int i = 0; i < n2; ++i) { std::cout << a[i] << std::endl; } } return 0; }
true
3449ff7310a331c8e6247e98c966abfe5e3bfe8a
C++
am11/ffcore
/src/core/util/String/String.h
UTF-8
8,307
3.21875
3
[]
no_license
#pragma once namespace ff { class String; typedef const String &StringRef; /// Sometimes a function needs to return a string reference, but needs /// something to return for failure cases. Use this. UTIL_API StringRef GetEmptyString(); /// Ref-counted string class that acts mostly like std::string (but with copy-on-write). /// /// The string can be read on multiple threads, as long as none of them modify it. /// That's not safe, even with the copy-on-write design. Getting that to work isn't worth it. class UTIL_API String { public: static const size_t npos = INVALID_SIZE; String(); String(const String &rhs); String(const String &rhs, size_t pos, size_t count = npos); String(String &&rhs); explicit String(const wchar_t *rhs, size_t count = npos); String(size_t count, wchar_t ch); String(const wchar_t *start, const wchar_t *end); ~String(); String &operator=(const String &rhs); String &operator=(String &&rhs); String &operator=(const wchar_t *rhs); String &operator=(wchar_t ch); String operator+(const String &rhs) const; String operator+(String &&rhs) const; String operator+(const wchar_t *rhs) const; String operator+(wchar_t ch) const; String &operator+=(const String &rhs); String &operator+=(String &&rhs); String &operator+=(const wchar_t *rhs); String &operator+=(wchar_t ch); bool operator==(const String &rhs) const; bool operator==(const wchar_t *rhs) const; bool operator==(wchar_t ch) const; bool operator!=(const String &rhs) const; bool operator!=(const wchar_t *rhs) const; bool operator!=(wchar_t ch) const; bool operator<(const String &rhs) const; bool operator<(const wchar_t *rhs) const; bool operator<(wchar_t ch) const; bool operator<=(const String &rhs) const; bool operator<=(const wchar_t *rhs) const; bool operator<=(wchar_t ch) const; bool operator>(const String &rhs) const; bool operator>(const wchar_t *rhs) const; bool operator>(wchar_t ch) const; bool operator>=(const String &rhs) const; bool operator>=(const wchar_t *rhs) const; bool operator>=(wchar_t ch) const; String &assign(const String &rhs, size_t pos = 0, size_t count = npos); String &assign(String &&rhs); String &assign(const wchar_t *rhs, size_t count = npos); String &assign(size_t count, wchar_t ch); String &assign(const wchar_t *start, const wchar_t *end); String &append(const String &rhs, size_t pos = 0, size_t count = npos); String &append(const wchar_t *rhs, size_t count = npos); String &append(size_t count, wchar_t ch); String &append(const wchar_t *start, const wchar_t *end); String &insert(size_t pos, const String &rhs, size_t rhs_pos = 0, size_t count = npos); String &insert(size_t pos, const wchar_t *rhs, size_t count = npos); String &insert(size_t pos, size_t count, wchar_t ch); const wchar_t *insert(const wchar_t *pos, wchar_t ch); const wchar_t *insert(const wchar_t *pos, const wchar_t *start, const wchar_t *end); const wchar_t *insert(const wchar_t *pos, size_t count, wchar_t ch); void push_back(wchar_t ch); void pop_back(); const wchar_t *erase(const wchar_t *start, const wchar_t *end); const wchar_t *erase(const wchar_t *pos); String &erase(size_t pos = 0, size_t count = npos); String &replace(size_t pos, size_t count, const wchar_t *rhs, size_t rhs_count = npos); String &replace(size_t pos, size_t count, const String &rhs, size_t rhs_pos = 0, size_t rhs_count = npos); String &replace(size_t pos, size_t count, size_t ch_count, wchar_t ch); String &replace(const wchar_t *start, const wchar_t *end, const wchar_t *rhs, size_t rhs_count = npos); String &replace(const wchar_t *start, const wchar_t *end, const String &rhs); String &replace(const wchar_t *start, const wchar_t *end, size_t ch_count, wchar_t ch); String &replace(const wchar_t *start, const wchar_t *end, const wchar_t *start2, const wchar_t *end2); typedef SharedStringVectorAllocator::StringVector::iterator iterator; typedef SharedStringVectorAllocator::StringVector::const_iterator const_iterator; typedef SharedStringVectorAllocator::StringVector::reverse_iterator reverse_iterator; typedef SharedStringVectorAllocator::StringVector::const_reverse_iterator const_reverse_iterator; iterator begin(); const_iterator begin() const; const_iterator cbegin() const; iterator end(); const_iterator end() const; const_iterator cend() const; reverse_iterator rbegin(); const_reverse_iterator rbegin() const; const_reverse_iterator crbegin() const; reverse_iterator rend(); const_reverse_iterator rend() const; const_reverse_iterator crend() const; wchar_t &front(); const wchar_t &front() const; wchar_t &back(); const wchar_t &back() const; wchar_t &at(size_t pos); const wchar_t &at(size_t pos) const; wchar_t &operator[](size_t pos); const wchar_t &operator[](size_t pos) const; const wchar_t *c_str() const; const wchar_t *data() const; size_t length() const; size_t size() const; bool empty() const; size_t max_size() const; size_t capacity() const; void clear(); void resize(size_t count); void resize(size_t count, wchar_t ch); void reserve(size_t alloc); void shrink_to_fit(); size_t copy(wchar_t * out, size_t count, size_t pos = 0); void swap(String &rhs); String substr(size_t pos = 0, size_t count = npos) const; // Custom functions that aren't part of std::string bool format(const wchar_t *format, ...); bool format_v(const wchar_t *format, va_list args); static String format_new(const wchar_t *format, ...); static String format_new_v(const wchar_t *format, va_list args); static String from_acp(const char *str); static String from_static(const wchar_t *str, size_t len = npos); BSTR bstr() const; #if METRO_APP Platform::String ^pstring() const; static String from_pstring(Platform::String ^str); #endif size_t find(const String &rhs, size_t pos = 0) const; size_t find(const wchar_t *rhs, size_t pos = 0, size_t count = npos) const; size_t find(wchar_t ch, size_t pos = 0) const; size_t rfind(const String &rhs, size_t pos = npos) const; size_t rfind(const wchar_t *rhs, size_t pos = npos, size_t count = npos) const; size_t rfind(wchar_t ch, size_t pos = npos) const; size_t find_first_of(const String &rhs, size_t pos = 0) const; size_t find_first_of(const wchar_t *rhs, size_t pos = 0, size_t count = npos) const; size_t find_first_of(wchar_t ch, size_t pos = 0) const; size_t find_last_of(const String &rhs, size_t pos = npos) const; size_t find_last_of(const wchar_t *rhs, size_t pos = npos, size_t count = npos) const; size_t find_last_of(wchar_t ch, size_t pos = npos) const; size_t find_first_not_of(const String &rhs, size_t pos = 0) const; size_t find_first_not_of(const wchar_t *rhs, size_t pos = 0, size_t count = npos) const; size_t find_first_not_of(wchar_t ch, size_t pos = 0) const; size_t find_last_not_of(const String &rhs, size_t pos = npos) const; size_t find_last_not_of(const wchar_t *rhs, size_t pos = npos, size_t count = npos) const; size_t find_last_not_of(wchar_t ch, size_t pos = npos) const; int compare(const String &rhs, size_t rhs_pos = 0, size_t rhs_count = npos) const; int compare(size_t pos, size_t count, const String &rhs, size_t rhs_pos = 0, size_t rhs_count = npos) const; int compare(const wchar_t *rhs, size_t rhs_count = npos) const; int compare(size_t pos, size_t count, const wchar_t *rhs, size_t rhs_count = npos) const; private: void make_editable(); SharedStringVectorAllocator::SharedStringVector *_str; }; class StaticString { public: UTIL_API StaticString(const wchar_t *sz, size_t len); template<size_t len> StaticString(const wchar_t (&sz)[len]) { Initialize(sz, len); } UTIL_API StringRef GetString() const; UTIL_API operator StringRef() const; private: UTIL_API void Initialize(const wchar_t *sz, size_t lenWithNull); SharedStringVectorAllocator::SharedStringVector *_str; SharedStringVectorAllocator::SharedStringVector _data; }; template<> inline hash_t HashFunc<String>(const String &val) { return HashBytes(val.c_str(), val.size() * sizeof(wchar_t)); } }
true
09003694b6782cc814bfbd11c1272165fd54125b
C++
csimstu/OI
/bzoj/p2111.cpp
UTF-8
1,067
2.703125
3
[]
no_license
#include <cstdio> typedef long long ll; int N, P; int log2[1000011]; ll powMod(ll a, ll n, ll m){ ll res = n & 1 ? a : 1; for(n >>= 1; n; n >>= 1){ a = a * a % m; if(n & 1) res = res * a % m; } return res % m; } ll bino(ll n, ll k){ ll res = 1; for(ll x = 1; x <= n; x ++) res = res * x % P; ll inv = 1; for(ll x = 1; x <= n - k; x ++) inv = inv * x % P; for(ll x = 1; x <= k; x ++) inv = inv * x % P; return res * powMod(inv, P - 2, P) % P; } ll dp(ll n){ static bool done[1000011]; static ll memo[1000011]; if(n == 0) return 1; if(done[n]) return memo[n]; done[n] = true; int k = log2[n]; ll p = n - ((1 << k) - 1); ll l, r; if(p <= (1 << (k - 1))) l = p + (1 << (k - 1)) - 1, r = (1 << (k - 1)) - 1; else l = (1 << k) - 1, r = n - l - 1; return memo[n] = dp(l) * dp(r) % P * bino(l + r, l) % P; } int main(){ freopen("t.in", "r", stdin); scanf("%d%d", &N, &P); for(int i = 0; 1 << i <= N; i ++) log2[1 << i] = i; for(int i = 2; i <= N; i ++) if(log2[i] == 0) log2[i] = log2[i - 1]; printf("%lld\n", dp(N)); }
true
2f2cc086402902bb2399c90ea8914e5897893fd9
C++
kuuala/cs253
/search_in_state_space/Solver.cpp
UTF-8
4,732
3.203125
3
[]
no_license
#include "Solver.hpp" const vector<function<int(int)>> functions { [] (int num) { return num * 2; }, [] (int num) { return num + 3; }, [] (int num) { return num - 2; } }; const vector<function<bool(int&)>> back_functions { [] (int &num) { if (num % 2) return false; num /= 2; return true; }, [] (int &num) { num -= 3; return true; }, [] (int &num) { num += 2; return true; } }; Position *task12(int start, int end) { clock_t s = clock(); set<Position *, Position::comparator> positions; queue<Position *> q; auto first = new Position(start, 0, nullptr); positions.insert(first); q.push(first); while (!q.empty()) { auto current = q.front(); q.pop(); if (current->getNum() == end) { cout << "time straight search: " << double(clock() - s) / CLOCKS_PER_SEC << endl; cout << "space straight search: " << positions.size() << endl; return current; } for (const auto& fun: functions) { auto next = new Position(fun(current->getNum()), current->getStep() + 1, current); if (positions.find(next) == positions.end()) { q.push(next); positions.insert(next); } } } return nullptr; } Position *task3(int start, int end) { clock_t s = clock(); set<Position *, Position::comparator> positions; queue<Position *> q; auto first = new Position(end, 0, nullptr); positions.insert(first); q.push(first); while (!q.empty()) { auto current = q.front(); q.pop(); if (current->getNum() == start) { cout << "time back search: " << double(clock() - s) / CLOCKS_PER_SEC << endl; cout << "space back search: " << positions.size() << endl; return current; } for (const auto &f: back_functions) { int num = current->getNum(); if (f(num)) { auto next = new Position(num, current->getStep() + 1, current); if (positions.find(next) == positions.end()) { q.push(next); positions.insert(next); } } } } return nullptr; } pair<Position*, Position*> task4(int start, int end) { clock_t s = clock(); set<Position *, Position::comparator> straight_positions; set<Position *, Position::comparator> reverse_positions; queue<pair<Position *, bool>> q; auto head = new Position(start, 0, nullptr); straight_positions.insert(head); q.emplace(head, true); auto tail = new Position(end, 0, nullptr); straight_positions.insert(tail); q.emplace(tail, false); while (!q.empty()) { bool is_straight = q.front().second; auto current = q.front().first; q.pop(); if (is_straight) { for (const auto &f: functions) { auto next = new Position(f(current->getNum()), current->getStep() + 1, current); if (straight_positions.find(next) == straight_positions.end()) { if (reverse_positions.find(next) != reverse_positions.end()) { cout << "time bidirectional search: " << double(clock() - s) / CLOCKS_PER_SEC << endl; cout << "space bidirectional search: " << reverse_positions.size() + straight_positions.size() << endl; return {next, *reverse_positions.find(next)}; } q.emplace(next, true); straight_positions.insert(next); } } } else { for (const auto &f: back_functions) { int num = current->getNum(); if (f(num)) { auto next = new Position(num, current->getStep() + 1, current); if (reverse_positions.find(next) == reverse_positions.end()) { if (straight_positions.find(next) != straight_positions.end()) { cout << "time bidirectional search: " << double(clock() - s) / CLOCKS_PER_SEC << endl; cout << "space bidirectional search: " << reverse_positions.size() + straight_positions.size() << endl; return {*straight_positions.find(next), next}; } q.emplace(next, false); reverse_positions.insert(next); } } } } } return {nullptr, nullptr}; }
true
c010e74a7a7ae047f61a43b6fb4b216523254e52
C++
brl2002/DODGameEngine
/Src/Render.cpp
UTF-8
2,019
2.875
3
[]
no_license
#include "Render.h" #include "ResourceManager.h" #include "Common.h" #include <stdio.h> #include <string> // Constructor. RenderComponent::RenderComponent( char* renderBuffer, char* mapBuffer, int mapBufferWidth, int mapBufferHeight ) : m_RenderableBufferArray(renderBuffer), m_MapBufferArray(mapBuffer), m_MapBufferWidth(mapBufferWidth), m_MapBufferHeight(mapBufferHeight), m_TotalBufferSize((m_MapBufferWidth + 1) * m_MapBufferHeight + 1) {} // Destructor. RenderComponent::~RenderComponent() { delete[] m_MapBufferArray; delete[] m_RenderableBufferArray; } void RenderComponent::Clear() { // Clear console screen. system("cls"); // Copy map buffer string to rendering buffer string. // Analogous to drawing skybox to rendering buffer in 3D rendering techniques. memcpy(m_RenderableBufferArray, m_MapBufferArray, m_TotalBufferSize); } void RenderComponent::Update( void* renderComponentInst, Entity** entities, int startIndex, int numEntities, double deltaTime ) { // Cast void pointer variable to RenderComponent pointer. RenderComponent* renderComponent = (RenderComponent*)renderComponentInst; // Update render buffer using array of entities. int endIndex = startIndex + numEntities; for (int i = startIndex; i < endIndex; ++i) { int index = renderComponent->PositionToArrayIndex(entities[i]->position.x, entities[i]->position.y); renderComponent->m_RenderableBufferArray[index] = entities[i]->GetChar(); } } void RenderComponent::Render() { // Print render buffer to screen. printf(m_RenderableBufferArray); } void RenderComponent::Debug( Entity** entities, int startIndex, int numEntities ) { //for (int i = startIndex; i < numEntities; ++i) //{ // for (auto segment : entities[i].path) // { // int segmentIndex = segment->GetIndex(); // int x = ArrayAccessHelper::GetSimpleColumnIndex(segmentIndex); // int y = ArrayAccessHelper::GetSimpleRowIndex(segmentIndex); // int index = PositionToArrayIndex(x, y); // m_RenderableBufferArray[index] = '+'; // } //} }
true
a54804dab0ea1a1849d1b2263f71c628c146105d
C++
sutuglon/Motor
/lib/Collide/font.cpp
UTF-8
4,576
3.171875
3
[]
no_license
/* * font.cpp * Noise * * Created by Chema on 11/30/09. * Copyright 2009 __MyCompanyName__. All rights reserved. * */ #include "GLInclude.h" #include <fstream> #include <string> #include <stdexcept> #include "font.h" // Helper function to read a piece of data from a stream. template<class T, class S> void readObject(T& to_read, S& in) { in.read(reinterpret_cast<char*>(&to_read), sizeof(T)); } // This is how glyphs are stored in the file. struct Glyph_Buffer { unsigned char ascii, width; unsigned short x, y; }; Font::Font(const char* filename) : _line_height(0), _texture(0), _tex_line_height(0) {;} void Font::load(const char* filename) { _line_height=(0); _texture=(0); _tex_line_height=(0); if (!filename) return; // Open the file and check whether it is any good (a font file // starts with "F0") std::ifstream input(filename, std::ios::binary); if (input.fail() || input.get() != 'F' || input.get() != '0') throw std::runtime_error("Not a valid font file."); // Get the texture size, the number of glyphs and the line height. size_t width, height, n_chars; readObject(width, input); readObject(height, input); readObject(_line_height, input); readObject(n_chars, input); _tex_line_height = static_cast<float>(_line_height) / height; // Make the glyph table. _glyphs = new Glyph[n_chars]; for (size_t i = 0; i != 256; ++i) _table[i] = NULL; // Read every glyph, store it in the glyph array and set the right // pointer in the table. Glyph_Buffer buffer; for (size_t i = 0; i < n_chars; ++i){ readObject(buffer, input); _glyphs[i].tex_x1 = static_cast<float>(buffer.x) / width; _glyphs[i].tex_x2 = static_cast<float>(buffer.x + buffer.width) / width; _glyphs[i].tex_y1 = static_cast<float>(buffer.y) / height; _glyphs[i].advance = buffer.width; _table[buffer.ascii] = _glyphs + i; } // All chars that do not have their own glyph are set to point to // the default glyph. Glyph* default_glyph = _table[(unsigned char)'\xFF']; // We must have the default character (stored under '\xFF') if (default_glyph == NULL) throw std::runtime_error("Font file contains no default glyph"); for (size_t i = 0; i != 256; ++i){ if (_table[i] == NULL) _table[i] = default_glyph; } // Store the actual texture in an array. unsigned char* tex_data = new unsigned char[width * height]; input.read(reinterpret_cast<char*>(tex_data), width * height); // Generate an alpha texture with it. glGenTextures(1, &_texture); glBindTexture(GL_TEXTURE_2D, _texture); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA8, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, tex_data); // And delete the texture memory block delete[] tex_data; } Font::~Font() { // Release texture object and glyph array. glDeleteTextures(1, &_texture); delete[] _glyphs; } size_t Font::lineHeight() const { return _line_height; } size_t Font::charWidth(unsigned char c) const { return _table[c]->advance; } size_t Font::stringWidth(const std::string& str) const { size_t total = 0; for (size_t i = 0; i != str.size(); ++i) total += charWidth(str[i]); return total; } void Font::preDrawString() const { glEnable(GL_TEXTURE_2D); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); glBindTexture(GL_TEXTURE_2D, _texture); } void Font::drawString(const std::string& str, float x, float y) const { // Simply draw quads textured with the current glyph for every // character, updating the x position as we go along. glBegin(GL_QUADS); for (size_t i = 0; i != str.size(); ++i){ Glyph* glyph = _table[str[i]]; if(!glyph) continue; glTexCoord2f(glyph->tex_x1, glyph->tex_y1+ _tex_line_height); glVertex2f(x, y); glTexCoord2f(glyph->tex_x1, glyph->tex_y1 ); glVertex2f(x, y + _line_height); glTexCoord2f(glyph->tex_x2, glyph->tex_y1 ); glVertex2f(x + glyph->advance, y + _line_height); glTexCoord2f(glyph->tex_x2, glyph->tex_y1+ _tex_line_height); glVertex2f(x + glyph->advance, y); x += glyph->advance; } glEnd(); } void Font::posDrawString() const { glDisable(GL_TEXTURE_2D); glDisable(GL_BLEND); }
true