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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
e69c5fdb1fb30c25070fa375eee77a5677c8b9e9 | C++ | s-kramer/cpp_tests | /boost_training/examples/examples/module06_7.cpp | UTF-8 | 289 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <functional>
#include <algorithm>
int main(int argc, char* argv[]) {
int numerki[] = {1,2,3,4,5,6,7,8,9};
int ilosc;
ilosc = std::count_if(numerki, numerki+9,
std::bind2nd(std::greater_equal<int>(),4));
std::cout << "Jest " << ilosc << " liczb >=4\n";
}
| true |
a0f3bdec4d39e7b809fd4cc45c2caeba918aadd9 | C++ | willproj/willToys | /vendor/RenderX/RenderX/include/utils/Mouse.h | UTF-8 | 1,486 | 2.5625 | 3 | [] | no_license | #pragma once
#include "..//..//Common.h"
#include "..//event/MouseEvent.h"
namespace renderx::utils
{
enum REN_API MouseButton
{
RX_LEFT_BUTTON,
RX_RIGHT_BUTTON,
RX_MIDDLE_BUTTON
};
class REN_API Mouse
{
private:
bool m_LeftButton = false;
bool m_RightButton = false;
bool m_MiddleButton = true;
glm::vec2 m_CurrentPosition = glm::vec2(0.0f);
glm::vec2 m_LastPosition = glm::vec2(0.0f);
glm::vec2 m_ScrollOffset = glm::vec2(0.1f);
float m_ScrollSensitivity = 0.45f;
float m_MouseSensitivity = 0.1;
static std::shared_ptr<Mouse> ms_Mouse;
Mouse();
public:
~Mouse();
static std::shared_ptr<Mouse> Create();
static std::shared_ptr<Mouse> GetMouseInstance() { return ms_Mouse; }
glm::vec2& GetMouseLastPosition() { return m_LastPosition; }
glm::vec2& GetMouseCurrentPosition() { return m_CurrentPosition; }
glm::vec2& GetMouseScrollOffset() { return m_ScrollOffset; }
float GetMouseSensitivity()const { return m_MouseSensitivity; }
float GetScrollSensitivity()const { return m_ScrollSensitivity; }
bool IsLeftMousebuttonPressed()const { return m_LeftButton; }
bool IsRightMousebuttonPressed()const { return m_RightButton; }
bool IsMiddleMousebuttonMoved()const { return m_MiddleButton; }
void OnEvent(events::MouseMovedEvent& event);
void OnEvent(events::MousePressedEvent& event);
void OnEvent(events::MouseRelasedEvent& event);
void OnEvent(events::MouseScrollEvent& event);
void UpdateMouse();
};
} | true |
6dcf52be4793846c632c9b70032c795d1bd092c5 | C++ | Zomega/VoroniExample | /transform.h | UTF-8 | 2,142 | 3.53125 | 4 | [] | no_license | #ifndef TRANSFORM_H
#define TRANSFORM_H
#include "vector.h"
#include <cmath>
class Rotation {
private:
float angle;
public:
Rotation() {
this->angle = 0;
}
Rotation( float angle ) {
this->angle = angle;
}
Rotation( const Rotation& rotation ) {
this->angle = rotation.getAngle();
}
Rotation operator=( Rotation rhs ) {
this->angle = rhs.getAngle();
}
Vector operator*( Vector vector ) {
return Vector(
cos( this->angle ) * vector.x - sin( this->angle ) * vector.y,
cos( this->angle ) * vector.y + sin( this->angle ) * vector.x
);
}
Rotation operator*( Rotation rhs ) {
return Rotation( this->getAngle() + rhs.getAngle() );
}
float getAngle() const {
return this->angle;
}
};
class Transform {
private:
Rotation rotation;
Vector translation;
public:
Transform() {
this->rotation = Rotation();
this->translation = Vector();
}
Transform( float rotation, Vector translation ) {
this->rotation = rotation;
this->translation = translation;
}
Transform( Rotation rotation, Vector translation ) {
this->rotation = rotation;
this->translation = translation;
}
Transform(const Transform& transform) {
this->rotation = transform.rotation;
this->translation = transform.translation;
}
Transform operator=( Transform rhs ) {
this->rotation = rhs.getRotation();
this->translation = rhs.getTranslation();
}
Vector operator*( Vector rhs ) {
return rotation * rhs + this->translation;
}
Transform operator*( Transform rhs ) {
Rotation rotation = this->getRotation() * rhs.getRotation();
Vector translation = this->getTranslation() + this->getRotation() * rhs.getTranslation();
return Transform( rotation, translation );
}
Rotation getRotation() {
return this->rotation;
}
Vector getTranslation() {
return this->translation;
}
};
Rotation inverse( Rotation rotation ) {
return Rotation( rotation.getAngle() );
};
Transform inverse( Transform transform ) {
Rotation invRotation = inverse( transform.getRotation() );
Vector invTranslation = invRotation * ( transform.getTranslation() * -1 );
return Transform( invRotation, invTranslation );
};
#endif
| true |
8428c1e442537e9b4086d5dafb91ed2738c2bc43 | C++ | kshitij86/code-examples | /prac/01_knap.cpp | UTF-8 | 1,432 | 3.46875 | 3 | [] | no_license | // Program to implement 0-1 knapsack using DP
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
typedef vector<int> vec;
typedef vector<vector<int>> vecv;
void print_vec(vec x)
{
for (int i : x)
cout << i << " ";
cout << endl;
}
int dp(vec weights, vec values, int w, int n, vec mem)
{
if (n == 0)
{
return 0;
}
if (weights[n - 1] > w)
{
return dp(weights, values, w, n - 1, mem);
}
else
{
if (mem[n - 1] == -1)
{
mem[n - 1] = max(values[n - 1] + dp(weights, values, w - weights[n - 1], n - 1, mem), dp(weights, values, w, n - 1, mem));
return max(values[n - 1] + dp(weights, values, w - weights[n - 1], n - 1, mem), dp(weights, values, w, n - 1, mem));
}
else
{
return mem[n - 1];
}
}
}
int main()
{
// Values of items
int n, w, x;
vec mem, values, weights;
cout << "No. of items:\n";
cin >> n;
cout << "Weights capacity\n";
cin >> w;
cout << "Weights \n";
for (int i = 0; i < n; i++)
{
cin >> x;
weights.pb(x);
}
cout << "Values: \n";
for (int i = 0; i < n; i++)
{
cin >> x;
values.pb(x);
}
// Set mem to -1
for (int i = 0; i < n; i++)
{
mem.pb(-1);
}
int max_val = dp(weights, values, w, n, mem);
cout << max_val << endl;
}
| true |
c37819202d1998a1b946b2ca44d0e18311d0295d | C++ | elvircrn/ccppcodes | /pritnerqueue.cpp | UTF-8 | 1,282 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <queue>
using namespace std;
struct Job
{
int priority, location;
bool myJob;
Job () { }
Job (int _priority, int _location, bool _myJob) { priority = _priority; location = _location; myJob =_myJob; }
bool operator < (const Job &B) const
{
if (priority != B.priority)
return priority < B.priority;
else
return location < B.location;
}
};
priority_queue <Job> jobs;
int t, A, n, m;
void clear_case()
{
}
int main ()
{
scanf ("%d", &t);
while (t--)
{
scanf ("%d %d", &n, &m);
bool found = false;
for (int i = 0; i < n; i++)
{
scanf ("%d", &A);
if (found == true)
continue;
jobs.push (Job (A, i, (i == m)));
}
for (int i = 0; i < n; i++)
{
Job J = jobs.top();
jobs.pop();
printf ("%d\n", J.priority);
if (J.myJob == true)
{
printf ("%d %d\n", J.priority, i);
break;
}
}
}
return 0;
}
/*
3
6 0
1 1 9 1 1 1
4 2
1 2 3 4
*/
| true |
0df3a858aedc240bc07865df9fc37592dcc9a5e4 | C++ | slimek/Caramel | /include/Caramel/Android/JniClass.h | UTF-8 | 1,756 | 2.65625 | 3 | [] | no_license | // Caramel C++ Library - Android Facility - JNI Class Header
#ifndef __CARAMEL_ANDROID_JNI_CLASS_H
#define __CARAMEL_ANDROID_JNI_CLASS_H
#pragma once
#include <Caramel/Setup/CaramelDefs.h>
#include <Caramel/Android/Detail/JniConstructor.h>
#include <Caramel/Android/Detail/JniGlobals.h>
#include <Caramel/Android/Detail/JniStaticMethod.h>
#include <Caramel/Android/JniObject.h>
namespace Caramel
{
namespace Android
{
///////////////////////////////////////////////////////////////////////////////
//
// JNI Class
//
class JniClass
{
public:
explicit JniClass( std::string classPath );
std::string Path() const { return m_classPath; }
// Lazy initializing
jclass Jni() const;
// Make a static method to be called.
template< typename Result >
Detail::JniStaticMethod< Result > Method( std::string methodName ) const;
// Create a new instance of this class
template< typename... Args >
JniObject NewObject( const Args&... args ) const;
private:
std::string m_classPath;
// Lazy initialized
mutable std::shared_ptr< Detail::JniClassGlobal > m_class;
};
///////////////////////////////////////////////////////////////////////////////
//
// Implementation
//
template< typename Result >
inline Detail::JniStaticMethod< Result > JniClass::Method( std::string methodName ) const
{
return Detail::JniStaticMethod< Result >( this->Jni(), m_classPath, std::move( methodName ));
}
template< typename... Args >
inline JniObject JniClass::NewObject( const Args&... args ) const
{
return Detail::JniConstructor( this->Jni(), m_classPath ).Call( args... );
}
///////////////////////////////////////////////////////////////////////////////
} // namespace Android
} // namespace Caramel
#endif // __CARAMEL_ANDROID_JNI_CLASS_H
| true |
8277ebb45fed9631e50a46ebf270131a23e3eaea | C++ | tychen5/NTU_ANTS-lab | /networkTA_project/submission/DemoI/b05705055.cpp | UTF-8 | 5,392 | 2.90625 | 3 | [] | no_license | #pragma comment(lib, "Ws2_32.lib")
#include <WinSock2.h>
#include <iostream>
#include <string>
using namespace std;
//Server IP: 140.112.107.194 port=33120
int main(){
const int MSG_SIZE = 100;
const int CMD_SIZE = 100;
WSAData wsa;
WORD version = MAKEWORD(2, 2);
int Result = WSAStartup(version, &wsa);
SOCKET server = socket(AF_INET, SOCK_STREAM, NULL);
char IP[CMD_SIZE];
int portNum;
char pNum[CMD_SIZE] = "#";
cout << "Please enter the IP address you want to connect: ";
cin >> IP;
cout << "Please enter the port number: ";
cin >> portNum;
char tempNum[CMD_SIZE];
sprintf(tempNum, "%d", portNum);
strcat(pNum, tempNum);
SOCKADDR_IN targetAddress;
targetAddress.sin_addr.s_addr = inet_addr(IP);
targetAddress.sin_family = AF_INET;
targetAddress.sin_port = htons(portNum);
connect(server, (SOCKADDR*) &targetAddress, sizeof(targetAddress));
char message[MSG_SIZE];
ZeroMemory(message, MSG_SIZE);
Result = recv(server, message, sizeof(message), 0);
if (server != SOCKET_ERROR){
cout << "-------------------------------" << endl;
cout << "Connection succeeded!" << endl;
cout << "-------------------------------" << endl;
}
bool whetherSignIn = false;
while(true){
char command[CMD_SIZE];
cout << endl << "Now enter the command that you want to communicate with the server:" << endl;
cout << "(Type 'help' can make you know what command you can request.)" << endl;
cin >> command;
for (int i = 0; command[i]; i++){
if (command[i] >= 'A' && command[i] <= 'Z')
command[i] += 32;
}
string command_type;
// Help
command_type = command;
command_type = command_type.substr(0,5);
if (command_type == "help"){
cout << endl << "All commands follow the following descriptions:" << endl << endl;
cout << "'register': Register an account on the server." << endl;
cout << "'signin': Sign in to an existing account on the server." << endl;
cout << "The commands after signing in:" << endl;
cout << "'list': Request the latest online list from the server." << endl;
cout << "'exit': End the entire program." << endl;
continue;
}
// Register
command_type = command;
command_type = command_type.substr(0, 9);
if (command_type == "register"){
if (whetherSignIn == true){
cout << endl << "You have already signed in an account." << endl;
cout << "You cannot register an account now!" << endl;
continue;
}
char userAccountName[CMD_SIZE];
cout << endl << "Enter the user account name that you wnat to register: ";
cin >> userAccountName;
char message[MSG_SIZE] = "REGISTER#";
strcat(message, userAccountName);
Result = send(server, message, (int)strlen(message), 0);
ZeroMemory(message, MSG_SIZE);
Result = recv(server, message, sizeof(message), 0);
string registerResult = message;
if (registerResult.substr(0,3) == "100")
cout << endl << "Register succeeded!" << endl;
else
cout << endl << "Register failed!" << endl;
continue;
}
// Signin
command_type = command;
command_type = command_type.substr(0, 7);
if (command_type == "signin"){
if (whetherSignIn == true){
cout << endl << "You have already signed in an account." << endl;
continue;
}
char message[CMD_SIZE];
cout << endl << "Enter the user account name: ";
cin >> message;
strcat(message, pNum);
Result = send(server, message, (int)strlen(message), 0);
ZeroMemory(message, MSG_SIZE);
Result = recv(server, message, sizeof(message), 0);
string signinResult = message;
if (signinResult.substr(0,13) == "220 AUTH_FAIL")
cout << endl << "Sign in failed! The user name is not existed!" << endl;
else{
whetherSignIn = true;
cout << endl << "Account balance: " << message;
ZeroMemory(message, MSG_SIZE);
Result = recv(server, message, sizeof(message), 0);
cout << message;
}
continue;
}
// List
command_type = command;
command_type = command_type.substr(0, 5);
if (command_type == "list"){
if (whetherSignIn == false){
cout << endl << "You have not yet signed in any account." << endl;
continue;
}
char message[MSG_SIZE] = "List\n";
Result = send(server, message, (int)strlen(message), 0);
ZeroMemory(message, MSG_SIZE);
Result = recv(server, message, sizeof(message), 0);
cout << endl << "Account balance: " << message;
ZeroMemory(message, MSG_SIZE);
Result = recv(server, message, sizeof(message), 0);
cout << message;
continue;
}
// Exit
command_type = command;
command_type = command_type.substr(0, 5);
if (command_type == "exit"){
if (whetherSignIn == false){
cout << endl << "You have not yet signed in any account." << endl;
continue;
}
char message[CMD_SIZE] = "Exit\n";
Result = send(server, message, (int)strlen(message), 0);
ZeroMemory(message, MSG_SIZE);
Result = recv(server, message, sizeof(message), 0);
cout << endl << message;
cout << endl << "Thank you for your using!" << endl;
break;
}
//Illegal input
cout << endl << "This command is not existed!" << endl;
}
closesocket(server);
return 0;
}
| true |
48d208253151194ed0637ca1474631c8f93c7e55 | C++ | jolilj/suntracker | /arduino/servo_test/servo_test.ino | UTF-8 | 523 | 2.609375 | 3 | [] | no_license | #include <Servo.h>
#define SERVO_PIN 3
//hservo working range 10-160
//vservo working range 40-120
#define HSERVO_MIN 10
#define HSERVO_MAX 160
#define VSERVO_MIN 40
#define VSERVO_MAX 120
#define uToVPos(u) (VSERVO_MAX-VSERVO_MIN)/100.0*u + VSERVO_MIN
#define uToHPos(u) (HSERVO_MAX-HSERVO_MIN)/100.0*u + HSERVO_MIN
Servo hServo;
void setup() {
Serial.begin(9600);
//hServo.attach(3);
}
void loop() {
for(int u=0; u<=100; u+=10) {
Serial.println(u);
Serial.println(uToVPos(u));
delay(1000);
}
}
| true |
327f15bc0e8d4b9cba88f08f1773423bbd81680a | C++ | 1998factorial/Codeforces | /contests/educationalRound92/D2.cpp | UTF-8 | 1,676 | 2.59375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int t; scanf("%d" , &t);
while(t--){
ll N , K , l1 , r1 , l2 , r2 , a , b , c , i;
scanf("%lld %lld" , &N , &K);
scanf("%lld %lld %lld %lld" , &l1 , &r1 , &l2 , &r2);
// assume l1 <= l2
if(l1 > l2){
swap(l1 , l2);
swap(r1 , r2);
}
// a = already intersected part
// b = bridge between two intervals
// c = the 1 unit per step part
if(r2 <= r1){
// embeded
a = r2 - l2;
b = 0;
c = l2 - l1 + r1 - r2;
}
else if(l2 <= r1){
// partial intersect
a = r1 - l2;
b = 0;
c = l2 - l1 + r2 - r1;
}
else{
// no intersect
a = 0;
b = l2 - r1;
c = r2 - l1;
}
K -= N * a;
if(K <= 0){
printf("0\n");
continue;
}
// need to fix up the first interval in order to have chance for 1 : 2
ll ret = b + min(K , c);
K -= min(K , c);
// try to use as many as 1 unit per step ones
// at the end , we need 2 * K extra steps to fix up
for(i = 2; i <= N; ++i){
ll steps = b + min(c , K); // connect 2 intervals first , then we can extend all 1:1 until the end or up to K
ll val = min(K , c); // increments we get from this pair
if(steps >= K * 2)break; // we might just extend 1 : 2 instead
ret += steps;
K -= val;
}
printf("%lld\n" , ret + K * 2);
}
} | true |
0423a1b217cb2b2985e3f0be1a30d5fe8fca7ac3 | C++ | afeng0007/cpp11feature | /features/std_declval.cpp | UTF-8 | 332 | 3.703125 | 4 | [] | no_license | #include <utility>
#include <iostream>
struct Default {int foo()const{return 1;}};
struct NoDefault
{
NoDefault(const NoDefault&){}
int foo()const{return 1;}
};
int main()
{
decltype(Default().foo()) n1 = 1;
decltype(std::declval<NoDefault>().foo()) n2 = n1;
std::cout << "n1 = " << n1 << '\n'
<< "n2 = " << n2 << '\n';
} | true |
60a2e28e3050a07c9fc817b8542cff0c1ea6be75 | C++ | tatsy/tatsy-pppm | /sources/bbox.cc | UTF-8 | 2,999 | 2.890625 | 3 | [
"MIT"
] | permissive | #define BBOX_EXPORT
#include "bbox.h"
#include <algorithm>
#include "common.h"
BBox::BBox()
: _posMin(INFTY, INFTY, INFTY)
, _posMax(-INFTY, -INFTY, -INFTY)
{
}
BBox::BBox(double minX, double minY, double minZ, double maxX, double maxY, double maxZ)
: _posMin(minX, minY, minZ)
, _posMax(maxX, maxY, maxZ)
{
}
BBox::BBox(const Vector3D& posMin, const Vector3D& posMax)
: _posMin(posMin)
, _posMax(posMax)
{
}
BBox::BBox(const BBox& box)
: _posMin(box._posMin)
, _posMax(box._posMax)
{
}
BBox::~BBox()
{
}
BBox& BBox::operator=(const BBox& box) {
this->_posMin = box._posMin;
this->_posMax = box._posMax;
return *this;
}
BBox BBox::fromTriangle(const Triangle& t) {
BBox retval;
retval.merge(t.p(0));
retval.merge(t.p(1));
retval.merge(t.p(2));
return retval;
}
void BBox::merge(const Vector3D& v) {
_posMin = Vector3D::minimum(_posMin, v);
_posMax = Vector3D::maximum(_posMax, v);
}
void BBox::merge(const BBox& box) {
_posMin = Vector3D::minimum(_posMin, box._posMin);
_posMax = Vector3D::maximum(_posMax, box._posMax);
}
void BBox::merge(const Triangle& t) {
for (int k = 0; k < 3; k++) {
this->merge(t.p(k));
}
}
BBox BBox::merge(const BBox& b1, const BBox& b2) {
BBox retval = b1;
retval.merge(b2);
return retval;
}
int BBox::maximumExtent() const {
Vector3D b = _posMax - _posMax;
double bx = std::abs(b.x());
double by = std::abs(b.y());
double bz = std::abs(b.z());
if (bx >= by && bx >= bz) return 0;
if (by >= bx && by >= bz) return 1;
return 2;
}
bool BBox::inside(const Vector3D& v) const {
return (_posMin.x() <= v.x() && v.x() <= _posMax.x()) &&
(_posMin.y() <= v.y() && v.y() <= _posMax.y()) &&
(_posMin.z() <= v.z() && v.z() <= _posMax.z());
}
double BBox::area() const {
Vector3D b = _posMax - _posMin;
double bx = std::abs(b.x());
double by = std::abs(b.y());
double bz = std::abs(b.z());
return 2.0 * (bx * by + by * bz + bz * bx);
}
bool BBox::intersect(const Ray& ray, double* tMin, double* tMax) const {
double xMin = (_posMin.x() - ray.origin().x()) * ray.invdir().x();
double xMax = (_posMax.x() - ray.origin().x()) * ray.invdir().x();
double yMin = (_posMin.y() - ray.origin().y()) * ray.invdir().y();
double yMax = (_posMax.y() - ray.origin().y()) * ray.invdir().y();
double zMin = (_posMin.z() - ray.origin().z()) * ray.invdir().z();
double zMax = (_posMax.z() - ray.origin().z()) * ray.invdir().z();
if (xMin > xMax) std::swap(xMin, xMax);
if (yMin > yMax) std::swap(yMin, yMax);
if (zMin > zMax) std::swap(zMin, zMax);
*tMin = std::max(xMin, std::max(yMin, zMin));
*tMax = std::min(xMax, std::min(yMax, zMax));
if (*tMin > *tMax || (*tMin < 0.0 && *tMax < 0.0)) {
return false;
}
if (*tMin < 0.0 && *tMax >= 0.0) {
*tMin = *tMax;
*tMax = INFTY;
}
return true;
}
| true |
7cd4e38523c923e42200dc31d5779b9b0c04ee8f | C++ | krzysiek1105/_chess | /src/piece_legal_moves.cpp | UTF-8 | 6,661 | 2.953125 | 3 | [] | no_license | #include "chessboard.h"
std::vector<Chessboard::Move> Chessboard::getLegalMovesPawn(Position position, Position axis, Side side)
{
std::vector<Chessboard::Move> result;
bool guardian = axis.x || axis.y ? true : false;
int direction = (side == WHITE ? 1 : -1);
int current_x = position.x;
int current_y = position.y + direction;
if (!(current_x < 0 || current_x > 7 || current_y < 0 || current_y > 7))
{
if (pieces[current_x][current_y].pieceType == EMPTY)
{
// Pawn promotion
if ((current_y == 7 && side == WHITE) || (current_y == 0 && side == BLACK) && !guardian)
result.push_back(Move(PAWN_PROMOTION, position, Position(current_x, current_y), getPieceAt(position).pieceType));
else if (!guardian || (!axis.x && axis.y))
result.push_back(Move(position, Position(current_x, current_y), getPieceAt(position).pieceType));
}
}
current_x = position.x;
current_y = position.y + 2 * direction;
if (!pieces[position.x][position.y].firstMoveDone)
if (pieces[current_x][current_y].pieceType == EMPTY && pieces[current_x][current_y - direction].pieceType == EMPTY)
if (!guardian || (!axis.x && axis.y))
result.push_back(Move(position, Position(current_x, current_y), getPieceAt(position).pieceType));
for (int horizontal = -1; horizontal <= 1; horizontal += 2)
{
current_x = position.x + horizontal;
current_y = position.y + direction;
if (!(current_x < 0 || current_x > 7 || current_y < 0 || current_y > 7))
{
if (pieces[current_x][current_y].side == side * -1)
{
// Pawn promotion
if (!guardian || axis.x * axis.y == horizontal * direction)
{
if ((current_y == 7 && side == WHITE) || (current_y == 0 && side == BLACK))
result.push_back(Move(PAWN_PROMOTION_WITH_BEATING, position, Position(current_x, current_y), getPieceAt(position).pieceType));
else
result.push_back(Move(BEATING, position, Position(current_x, current_y), getPieceAt(position).pieceType));
}
}
//en passant
else if (pieces[current_x][current_y].pieceType == EMPTY && pieces[current_x][current_y - direction].pieceType == PAWN && lastMove.x == current_x && lastMove.y == current_y - direction && pieces[lastMove.x][lastMove.y].twoSquares)
if (!guardian || axis.x * axis.y == horizontal * direction)
result.push_back(Move(EN_PASSANT, position, Position(current_x, current_y), getPieceAt(position).pieceType));
}
}
return result;
}
std::vector<Chessboard::Move> Chessboard::getLegalMovesKnight(Position position, Position axis, Side side)
{
std::vector<Chessboard::Move> result;
bool guardian = axis.x || axis.y ? true : false;
for (int horizontal = -1; horizontal <= 1; horizontal += 2)
{
if (guardian)
break;
for (int vertical = -1; vertical <= 1; vertical += 2)
{
for (int x = -2; x <= -1; x++)
{
int current_x = position.x + horizontal * x;
int current_y = position.y + vertical * (x == -2 ? 1 : 2);
if (current_x < 0 || current_x > 7 || current_y < 0 || current_y > 7)
continue;
if (pieces[current_x][current_y].pieceType == EMPTY)
result.push_back(Move(position, Position(current_x, current_y), getPieceAt(position).pieceType));
else if (pieces[current_x][current_y].side == side * -1)
result.push_back(Move(BEATING, position, Position(current_x, current_y), getPieceAt(position).pieceType));
}
}
}
return result;
}
std::vector<Chessboard::Move> Chessboard::getLegalMovesBishop(Position position, Position axis, Side side)
{
std::vector<Chessboard::Move> result;
bool guardian = axis.x || axis.y ? true : false;
for (int horizontal = -1; horizontal <= 1; horizontal += 2)
{
if (guardian && !(axis.x * axis.y))
break;
for (int vertical = -1; vertical <= 1; vertical += 2)
{
if (guardian && axis.x * axis.y != horizontal * vertical)
continue;
for (int i = 1; i <= 7; i++)
{
int current_x = position.x + horizontal * i;
int current_y = position.y + vertical * i;
if (current_x < 0 || current_x > 7 || current_y < 0 || current_y > 7)
break;
if (!pieces[current_x][current_y].pieceType)
{
result.push_back(Move(position, Position(current_x, current_y), getPieceAt(position).pieceType));
continue;
}
if (pieces[current_x][current_y].side == side * -1)
result.push_back(Move(BEATING, position, Position(current_x, current_y), getPieceAt(position).pieceType));
break;
}
}
}
return result;
}
std::vector<Chessboard::Move> Chessboard::getLegalMovesRook(Position position, Position axis, Side side)
{
std::vector<Chessboard::Move> result;
bool guardian = axis.x || axis.y ? true : false;
std::vector<Position> dirs;
dirs.push_back(Position(-1, 0));
dirs.push_back(Position(1, 0));
dirs.push_back(Position(0, 1));
dirs.push_back(Position(0, -1));
for (Position dir : dirs)
{
if (guardian)
{
if (axis.x * axis.y)
break;
if (!(axis.x * dir.x) && !(axis.y * dir.y))
continue;
}
for (int i = 1; i <= 7; i++)
{
int current_x = position.x + dir.x * i;
int current_y = position.y + dir.y * i;
if (current_x < 0 || current_x > 7 || current_y < 0 || current_y > 7)
break;
if (!pieces[current_x][current_y].pieceType)
{
result.push_back(Move(position, Position(current_x, current_y), getPieceAt(position).pieceType));
continue;
}
else if (pieces[current_x][current_y].side == side * -1)
result.push_back(Move(BEATING, position, Position(current_x, current_y), getPieceAt(position).pieceType));
break;
}
}
return result;
}
std::vector<Chessboard::Move> Chessboard::getLegalMovesQueen(Position position, Position axis, Side side)
{
std::vector<Chessboard::Move> result;
result = getLegalMovesBishop(position, axis, side);
std::vector<Chessboard::Move> result2;
result2 = getLegalMovesRook(position, axis, side);
result.insert(result.end(), result2.begin(), result2.end());
return result;
}
std::vector<Chessboard::Move> Chessboard::getLegalMovesKing(Position position, Side side)
{
std::vector<Chessboard::Move> result;
for (int horizontal = -1; horizontal <= 1; horizontal++)
{
for (int vertical = -1; vertical <= 1; vertical++)
{
int current_x = position.x + horizontal;
int current_y = position.y + vertical;
if (current_x < 0 || current_x > 7 || current_y < 0 || current_y > 7)
continue;
if (pieces[current_x][current_y].pieceType == EMPTY)
result.push_back(Move(position, Position(current_x, current_y), getPieceAt(position).pieceType));
else if (pieces[current_x][current_y].side == side * -1)
result.push_back(Move(BEATING, position, Position(current_x, current_y), getPieceAt(position).pieceType));
}
}
return result;
} | true |
b38b4da2059b220f3d9fa9f3e712a042c14b7edf | C++ | ganapathi7869/compilergenerateopcode | /compilergenerateopcode.cpp | UTF-8 | 11,401 | 2.625 | 3 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct symbol{
char name[20];
unsigned int address;
unsigned int size;
char constval;
};
struct block{
char name[20];
unsigned int address;
};
struct targetline{
unsigned int lineno;
unsigned int opcode;
unsigned int arg1;
unsigned int arg2;
unsigned int arg3;
unsigned int arg4;
};
void buildsymboltable(char *command,char * arg1,struct symbol *symboltable,unsigned int symboltablelen){
unsigned int address;
if (symboltablelen == 0) address = 0;
else address = symboltable[symboltablelen - 1].address + symboltable[symboltablelen - 1].size;
unsigned int size=1;
if (!strcmp(command, "DATA")){
if (strchr(arg1, '[')){
char *sub = strchr(arg1, '[');
sscanf(sub, "[%d]", &size);
*sub = '\0';
strcpy(symboltable[symboltablelen].name, arg1);
symboltable[symboltablelen].address = address;
symboltable[symboltablelen].size = size;
}
else{
strcpy(symboltable[symboltablelen].name, arg1);
symboltable[symboltablelen].address = address;
symboltable[symboltablelen].size = size;
}
}
else if (!strcmp(command, "CONST")){
char name[20]; char val;
sscanf(arg1, "%s = %d", name, &val);
strcpy(symboltable[symboltablelen].name, name);
symboltable[symboltablelen].address = address;
symboltable[symboltablelen].size = size;
symboltable[symboltablelen].constval = val;
}
}
void buildlabeltable(char *name,unsigned int address,struct block *labeltable,unsigned int labeltablelen){
strcpy(labeltable[labeltablelen].name, name);
labeltable[labeltablelen].address = address;
}
unsigned int getaddressofsymbol(char *name ,struct symbol *symboltable, unsigned int symboltablelen){
if (strchr(name, '[')){
char *arg = strchr(name, '[');
unsigned int offset;
sscanf(arg, "[%d]", &offset);
*arg = '\0';
for (unsigned int i = 0; i < symboltablelen; i++){
if (!strcmp(name, symboltable[i].name)){
return symboltable[i].address + offset;
}
}
}
for (unsigned int i = 0; i < symboltablelen; i++){
if (!strcmp(name, symboltable[i].name)){
return symboltable[i].address;
}
}
printf("symbol not found\n");
exit(1);
}
unsigned int getaddressofblock(char *name, struct block *labeltable, unsigned int labeltablelen){
for (unsigned int i = 0; i < labeltablelen; i++){
if (!strcmp(name, labeltable[i].name)){
return labeltable[i].address;
}
}
printf("block not found\n");
exit(1);
}
//void deleteelselabel(struct block *labeltable, unsigned int *labeltablelen){ ///////////////////////
// for (unsigned int i = *labeltablelen - 1; i >-1; i--){
// if (!strcmp("ELSE", labeltable[i].name)){
// strcpy(labeltable[i].name, labeltable[*labeltablelen - 1].name);
// labeltable[i].address = labeltable[*labeltablelen - 1].address;
// *labeltablelen = *labeltablelen - 1;
// break;
// }
// }
//}
void processmov(char *arg1, char * arg2, struct targetline *targetlanguage, unsigned int targetlanguagelen, struct symbol *symboltable, unsigned int symboltablelen){
int isregister = 0,i;
char registercodes[][3] = { "AX", "BX", "CX", "DX", "EX", "FX", "GX", "HX" };
for ( i = 0; i < 8; i++){
if (!strcmp(arg1, registercodes[i])){
isregister = 1; break;
}
}
if (isregister){
targetlanguage[targetlanguagelen].opcode = 2;
targetlanguage[targetlanguagelen ].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen ].arg1 = i;
targetlanguage[targetlanguagelen ].arg2 = getaddressofsymbol(arg2, symboltable, symboltablelen);
}
else{
targetlanguage[targetlanguagelen ].opcode = 1;
targetlanguage[targetlanguagelen ].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen ].arg1 = getaddressofsymbol(arg1, symboltable, symboltablelen);
for (i = 0; i < 8; i++){
if (!strcmp(arg2, registercodes[i])){
break;
}
}
targetlanguage[targetlanguagelen ].arg2 = i;
}
}
void processarith(char opcode, char *arg1, char * arg2, char *arg3, struct targetline *targetlanguage, unsigned int targetlanguagelen){
targetlanguage[targetlanguagelen ].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen ].opcode = opcode;
targetlanguage[targetlanguagelen ].arg1 = arg1[0] - 'A';
targetlanguage[targetlanguagelen ].arg2 = arg2[0] - 'A';
targetlanguage[targetlanguagelen ].arg3 = arg3[0] - 'A';
}
void processjump(char *arg1, struct targetline *targetlanguage, unsigned int targetlanguagelen, struct block *labeltable, unsigned int labeltablelength){
if (!arg1){
targetlanguage[targetlanguagelen].opcode = 6;
targetlanguage[targetlanguagelen].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen].arg1 = 0;
return;
}
targetlanguage[targetlanguagelen].opcode = 6;
targetlanguage[targetlanguagelen].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen].arg1 = getaddressofblock(arg1, labeltable, labeltablelength);
}
void processif(char *arg1, char *arg2, char *arg3, struct targetline *targetlanguage, unsigned int targetlanguagelen,unsigned int *stack, unsigned int stacklen){
targetlanguage[targetlanguagelen].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen].opcode = 7;
targetlanguage[targetlanguagelen].arg1 = arg1[0] - 'A';
targetlanguage[targetlanguagelen].arg2 = arg3[0] - 'A';
char operators[][5] = { "EQ", "LT", "GT", "LTEQ", "GTEQ" };
for (unsigned int i = 0; i < 5; i++){
if (!strcmp(arg2, operators[i])){
targetlanguage[targetlanguagelen].arg3 = 8 + i;
break;
}
}
targetlanguage[targetlanguagelen].arg4 = 0;
stack[stacklen] = targetlanguagelen + 1;
}
void processelse(struct targetline *targetlanguage, unsigned int targetlanguagelen, struct block *labeltable, unsigned int labeltablelen, unsigned int *stack, unsigned int stacklen){
processjump(NULL, targetlanguage, targetlanguagelen, labeltable, labeltablelen);
stack[stacklen] = targetlanguagelen + 1;
buildlabeltable("ELSE", targetlanguagelen + 2,labeltable,labeltablelen);
}
void processendif(struct targetline *targetlanguage, unsigned int targetlanguagelen, struct block *labeltable, unsigned int labeltablelen, unsigned int *stack, unsigned int *stacklen){
buildlabeltable("ENDIF", targetlanguagelen + 1, labeltable, labeltablelen);
unsigned int linehold = targetlanguagelen + 1;
if (targetlanguage[stack[*stacklen - 1]].opcode == 6 ){
targetlanguage[stack[*stacklen - 1]].arg2 = linehold ;
linehold = stack[*stacklen - 1] + 1;
*stacklen -= 1;
}
targetlanguage[stack[*stacklen - 1]].arg4 = linehold;
*stacklen -= 1;
}
void processprint(char *arg1, struct targetline *targetlanguage, unsigned int targetlanguagelen, struct symbol *symboltable, unsigned int symboltablelen){
targetlanguage[targetlanguagelen].opcode = 13;
targetlanguage[targetlanguagelen].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen].arg1 = getaddressofsymbol(arg1, symboltable, symboltablelen);
}
void processread(char *arg1, struct targetline *targetlanguage, unsigned int targetlanguagelen){
targetlanguage[targetlanguagelen].opcode = 14;
targetlanguage[targetlanguagelen].lineno = targetlanguagelen + 1;
targetlanguage[targetlanguagelen].arg1 = arg1[0] - 'A';
}
int main(){
FILE *inp = fopen("input.txt", "r");
char command[50],buf[20],arg1[20],arg2[20],arg3[20],arg4[20];
unsigned int stack[100];
struct symbol symboltable[100];
struct block labeltable[100];
struct targetline targetlanguage[100];
unsigned int stacklen = 0, symboltablelen = 0, labeltablelen = 0, targetlanguagelen = 0;
//char registercodes[][3] = { "AX", "BX", "CX", "DX", "EX", "FX","GX","HX" };
while (!feof(inp)){
//fgets(command, sizeof(char) * 50, inp);
fscanf(inp, "%[^\n]s%*c", command);
//fflush(inp);
sscanf(command, "%s", buf);
if (!strcmp(buf, "DATA")){
sscanf(command, "%*s %s", arg1);
buildsymboltable(buf, arg1,symboltable,symboltablelen);
symboltablelen += 1;
}
else if (!strcmp(buf, "CONST")){
strcpy(arg1, &strchr(buf, ' ')[1]);
buildsymboltable(buf, arg1, symboltable, symboltablelen);
symboltablelen += 1;
}
else if (!strcmp(buf, "MOV")){
sscanf(command, "%*s %s %s", arg1, arg2);
char *arg = strchr(arg1, ',');
*arg = '\0';
processmov(arg1,arg2,targetlanguage,targetlanguagelen,symboltable,symboltablelen);
targetlanguagelen += 1;
}
else if (!strcmp(buf, "START:")){
continue;
}
else if (!strcmp(buf, "ADD")){
sscanf(command, "%*s %s %s %s", arg1, arg2,arg3);
char *arg = strchr(arg1, ',');
*arg = '\0';
arg = strchr(arg2, ',');
*arg = '\0';
processarith(3,arg1, arg2, arg3, targetlanguage, targetlanguagelen);
targetlanguagelen += 1;
}
else if (!strcmp(buf, "SUB")){
sscanf(command, "%*s %s %s %s", arg1, arg2, arg3);
char *arg = strchr(arg1, ',');
*arg = '\0';
arg = strchr(arg2, ',');
*arg = '\0';
processarith(4, arg1, arg2, arg3, targetlanguage, targetlanguagelen);
targetlanguagelen += 1;
}
else if (!strcmp(buf, "MUL")){
sscanf(command, "%*s %s %s %s", arg1, arg2, arg3);
char *arg = strchr(arg1, ',');
*arg = '\0';
arg = strchr(arg2, ',');
*arg = '\0';
processarith(5, arg1, arg2, arg3, targetlanguage, targetlanguagelen);
targetlanguagelen += 1;
}
else if (!strcmp(buf, "JUMP")){
sscanf(command, "%*s %s", arg1);
processjump(arg1, targetlanguage, targetlanguagelen,labeltable,labeltablelen);
targetlanguagelen += 1;
}
else if (!strcmp(buf, "IF")){
sscanf(command, "%*s %s %s %s", arg1, arg2, arg3);
processif(arg1, arg2, arg3, targetlanguage, targetlanguagelen, stack, stacklen);
stacklen += 1;
targetlanguagelen += 1;
}
else if (!strcmp(buf, "ELSE")){
processelse(targetlanguage, targetlanguagelen, labeltable, labeltablelen, stack, stacklen);
targetlanguagelen += 1;
stacklen += 1;
labeltablelen += 1;
}
else if (!strcmp(buf, "ENDIF")){
processendif(targetlanguage, targetlanguagelen, labeltable, labeltablelen, stack, &stacklen);
labeltablelen += 1;
}
else if (!strcmp(buf, "PRINT")){
sscanf(command, "%*s %s", arg1);
processprint(arg1,targetlanguage, targetlanguagelen, symboltable, symboltablelen);
targetlanguagelen += 1;
}
else if (!strcmp(buf, "READ")){
sscanf(command, "%*s %s", arg1);
processread(arg1, targetlanguage, targetlanguagelen);
targetlanguagelen += 1;
}
else if(strchr(buf,':')){
char *arg = strchr(buf, ':');
arg[0] = '\0';
buildlabeltable(buf, targetlanguagelen + 2, labeltable, labeltablelen);
labeltablelen += 1;
}
else{
printf("invalid command found\n");
}
}
fclose(inp);
FILE *out = fopen("output.txt", "w");
for (unsigned int i = 0; i < targetlanguagelen; i++){
if (targetlanguage[i].opcode == 1 || targetlanguage[i].opcode == 2){
fprintf(out, "%d %d %d\n", targetlanguage[i].opcode, targetlanguage[i].arg1, targetlanguage[i].arg2);
}
else if (targetlanguage[i].opcode >= 3 && targetlanguage[i].opcode <= 5){
fprintf(out, "%d %d %d %d\n", targetlanguage[i].opcode, targetlanguage[i].arg1, targetlanguage[i].arg2,targetlanguage[i].arg3);
}
else if (targetlanguage[i].opcode == 6 || targetlanguage[i].opcode == 13 || targetlanguage[i].opcode == 14){
fprintf(out, "%d %d\n", targetlanguage[i].opcode, targetlanguage[i].arg1);
}
else {
fprintf(out, "%d %d %d %d %d\n", targetlanguage[i].opcode, targetlanguage[i].arg1, targetlanguage[i].arg2, targetlanguage[i].arg3, targetlanguage[i].arg4);
}
}
fclose(out);
return 0;
} | true |
8c95339a4f3f8dbd736b6ec5d505199fa631b6fc | C++ | wuggy-ianw/AoC2017 | /day12/testday12.cpp | UTF-8 | 1,587 | 3.21875 | 3 | [
"Unlicense"
] | permissive | //
// Created by wuggy on 21/12/2017.
//
#include "gtest/gtest.h"
#include "day12.h"
TEST(DAY12, TestParse)
{
std::string example = "0 <-> 2\n"
"1 <-> 1\n"
"2 <-> 0, 3, 4\n"
"3 <-> 2, 4\n"
"4 <-> 2, 3, 6\n"
"5 <-> 6\n"
"6 <-> 4, 5\n";
std::istringstream iss(example);
std::map<int, Day12::program> parsed = Day12::parse_input(iss);
std::map<int, Day12::program> expected =
{
std::make_pair(0, Day12::program{0, {2}}),
std::make_pair(1, Day12::program{1, {1}}),
std::make_pair(2, Day12::program{2, {0, 3, 4}}),
std::make_pair(3, Day12::program{3, {2, 4}}),
std::make_pair(4, Day12::program{4, {2, 3, 6}}),
std::make_pair(5, Day12::program{5, {6}}),
std::make_pair(6, Day12::program{6, {4, 5}})
};
ASSERT_EQ(expected, parsed);
}
TEST(DAY12, TestSolvePart1)
{
std::string example = "0 <-> 2\n"
"1 <-> 1\n"
"2 <-> 0, 3, 4\n"
"3 <-> 2, 4\n"
"4 <-> 2, 3, 6\n"
"5 <-> 6\n"
"6 <-> 4, 5\n";
std::istringstream iss(example);
std::map<int, Day12::program> programs = Day12::parse_input(iss);
int actual = Day12::solve_part1(programs);
ASSERT_EQ(6, actual);
}
TEST(DAY12, TestSolvePart2)
{
std::string example = "0 <-> 2\n"
"1 <-> 1\n"
"2 <-> 0, 3, 4\n"
"3 <-> 2, 4\n"
"4 <-> 2, 3, 6\n"
"5 <-> 6\n"
"6 <-> 4, 5\n";
std::istringstream iss(example);
std::map<int, Day12::program> programs = Day12::parse_input(iss);
int actual = Day12::solve_part2(programs);
ASSERT_EQ(2, actual);
}
| true |
672cc34a538b147197bb7fe324b1af1c1819e968 | C++ | bonorose/adspecto | /Specto-Light/Specto-Light.ino | UTF-8 | 3,824 | 2.796875 | 3 | [] | no_license | /*
Name: Specto_Light.ino
Created: 14-Sep-19 11:12:20 AM
Author: Simeon Marlokov
Brief: This project contains the source code for the Specto Light prototype testing module.
Hardware Components:
Solar Panel;
BME280 Temperature Sensor,
5V Relay JQC-3FF-S-Z,
TSL 2591 Dynamic Light Sensor
Microcontroller: Arduino Nano 328p + NodeMCU ESP 8266
*/
// Library Initialization
#include <math.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Adafruit_TSL2591_Library/Adafruit_TSL2591.h>
// Parameter & Variable Declaration/Initialization
// A3 and A4 for SCL + SDA
LiquidCrystal_I2C lcd(0x27, 20, 4); // Initialize a LCD with I2C address set to 0x27 for a 16 chars and 2 line display
Adafruit_BME280 BME; // Initializing BME sensor as I2C device
Adafruit_TSL2591 TSL = Adafruit_TSL2591(2591); // Initializing TSL 2591 dynamic light sensor as I2C device.
int Relay = 3;
int Solar = A2;
/** @brief Read analog solar panel callback funciton.
* @param Pin int
* @return float Read Solar voltage.
*/
float SolarMeasure() {
}
/** @brief Initialize the LCD and write a test message.
* @return Initialized LCD ready for writing.
*/
void DisplayInit() {
// Initialize the lcd.
lcd.init();
lcd.init();
// Test Print LCD.
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("AdSpecto Inc.");
}
/** @brief Control the relay and turn on/off the lightbulb based on time.
* @param Time from RTC.
* @return bool Bulb Status.
*/
void RelaySwitch() {
}
/** @brief Set TSL 2591 working parameters.
* @param void
* @return Configured Lux Sensor :).
*/
void LuxSetup(void)
{
// You can change the gain on the fly, to adapt to brighter/dimmer light situations
TSL.setGain(TSL2591_GAIN_LOW); // 1x gain (bright light)
//TSL.setGain(TSL2591_GAIN_MED); // 25x gain
// Changing the integration time gives you a longer time over which to sense light
// longer timelines are slower, but are good in very low light situtations!
TSL.setTiming(TSL2591_INTEGRATIONTIME_100MS); // shortest integration time (bright light)
//TSL.setTiming(TSL2591_INTEGRATIONTIME_200MS);
}
/** @brief Read analog solar panel callback funciton.
* @param .
* @return uint16_t Calculated lux.
*/
int LuxRead(void)
{
// More advanced data read example. Read 32 bits with top 16 bits IR, bottom 16 bits full spectrum.
// That way you can do whatever math and comparisons you want!
uint32_t lum = TSL.getFullLuminosity();
uint16_t ir, full;
ir = lum >> 16;
full = lum & 0xFFFF;
uint16_t lux = TSL.calculateLux(full, ir); //Calculates total lux summing both IR and FS.
return lux;
}
/*
TO-DO: Can seperate parameters and variables in a seperate file
*/
/** @brief Initializes all of the nessecary pins for the project
*/
void PinMeBaby() {
pinMode(Relay, OUTPUT); // sets the relay pin to output
}
/** @brief Check if all the sensors have initialized correctly. If not, flag which sensor and stop program.
* @param Actual hardware.
* @return bool check if working.
*/
void StatusCheck() {
bool status;
Serial.print("Checking BME sensor.");
status = BME.begin();
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
Serial.print("Checking Lux sensor.");
status = lux.begin();
if (!status) {
Serial.println("Could not find a valid TSL 2591 sensor, check wiring!");
while (1);
}
}
// the setup function runs once when you press reset or power the board
void setup() {
//Serial.begin(9600); //Initializes USB serial communication with host computer at a baud of 9600
DisplayInit();
LuxSetup();
PinMeBaby();
//StatusCheck();
}
// the loop function runs over and over again until power down or reset
void loop() {
SolarMeasure();
BME.readTemperature();
} | true |
6c79c00b6394970785a9c1971b590fbe1d3cb9e5 | C++ | lyl2000/CSP | /201709-1 打酱油.cpp | UTF-8 | 266 | 2.5625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int N,p=10,c1=5,d1=2,c2=3,d2=1,res=0;
cin>>N;
N/=p;
while(N/c1){
res+=(c1+d1)*(N/c1);
N%=c1;
}
while(N/c2){
res+=(c2+d2)*(N/c2);
N%=c2;
}
res+=N;
cout<<res<<endl;
return 0;
}
| true |
c4f372620742fd290a5720ce6cddde8a54f7c216 | C++ | siamcodes/c | /while1.cpp | UTF-8 | 145 | 2.671875 | 3 | [] | no_license | #include <stdio.h>
main(){
int i;
printf("Enter Number:");
scanf("%d", &i);
while(i > 0){
printf("Hello World %d \n", i);
i--;
}
}
| true |
5c35a2d7daf5697315dab9583eb007290a0c97d4 | C++ | Frankie-2000-F/PAT_Advanced-Level | /1031/1031/源.cpp | UTF-8 | 525 | 2.671875 | 3 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
string s;
int N,k,n;
int main(){
cin >> s;
N = s.size();
switch ((N+2) % 3){
case 0:
k = n = (N + 2) / 3;
break;
case 1:
k = (N + 2) / 3;
n = (N + 2) / 3 + 1;
break;
case 2:
k = (N + 2) / 3;
n = (N + 2) / 3 + 2;
break;
}
for (int i = 0; i < k - 1; i++){
cout << s[i];
for (int j = 0; j < n - 2; j++)
cout << " ";
cout << s[N - i - 1] << endl;
}
for (int i = k - 1; i <= N - k; i++){
cout << s[i];
}
system("pause");
return 0;
} | true |
bab0ae7d4638bcf3f689744fa11ad0683c4640d9 | C++ | sbaskar1997/PurdueTracSat | /src/LaserCom/Lasercom Library/receiver/receiver.ino | UTF-8 | 1,268 | 2.890625 | 3 | [] | no_license | #define SOLARPIN A0
#define THRESHOLD 30
int ascii = 0;
int ambientReading;
int k = 1;
void setup() {
// Setup Code.
pinMode(SOLARPIN, INPUT);
Serial.begin(9600);
ambientReading = analogRead(SOLARPIN);
Serial.println(ambientReading);//Set the ambient reading of the receiver.
}
void loop() {
int reading = analogRead(SOLARPIN);
int bits[8];
//When a start flash is read, an 8 bit loop begins.
if (reading > ambientReading + THRESHOLD) {
delay(1);
for (int i = 0; i < 8; i++){
if (analogRead(SOLARPIN) > ambientReading + THRESHOLD){
bits[i] = 1;
} else{
bits[i] = 0;
}
// Serial.println(analogRead(SOLARPIN));
delayMicroseconds(1000);
}
convertToText(bits);
}
}
//Convert array of bits to text. Outputted to serial monitor.
void convertToText(int bits[]){
int i = 0;
int j = 0;
int len = 8;
double sum = 0;
for(i=(len-1);i>=0;i--)
{
sum = sum + (pow(2,i) * (bits[j]));
j++;
}
char aChar = (int) lround(sum);
if (aChar == '#'){
Serial.println("");
} else {
Serial.print(aChar);
}
/*
for (int l = 0; l < 8; l++){
Serial.print(bits[l]);
}
Serial.println("");*/
}
| true |
46ba495afc38d2c8cc9dd8fc86c1eafc1709d707 | C++ | waskerdu/Mercutio-Engine | /MercutioEngine/meBarrier.h | UTF-8 | 266 | 2.515625 | 3 | [] | no_license | #pragma once
#include "meEntity.h"
class Barrier :
public Entity
{
public:
Barrier();
~Barrier();
void OnCollision(Entity* ent);
Entity* Copy()
{
Barrier* copy = new Barrier(dynamic_cast<const Barrier&>(*this));
DeepCopy(this, copy);
return copy;
}
};
| true |
0abbe505eb9ae202b911a5e4e3452afa69b03d19 | C++ | ms-darshan/Competitive-Coding | /Google CodeJam/Google_CodeJAm_2018_Round_1B_Rounding_Error.cpp | UTF-8 | 2,780 | 2.546875 | 3 | [] | no_license | /*~~~~~~~~~~~~~~~~~~*
* *
* $DollarAkshay$ *
* *
*~~~~~~~~~~~~~~~~~~*/
//https://codejam.withgoogle.com/2018/challenges/0000000000007764/dashboard
#include <algorithm>
#include <assert.h>
#include <ctype.h>
#include <deque>
#include <iostream>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <time.h>
#include <vector>
using namespace std;
#define sp system("pause")
#define FOR(i, a, b) for (int i = a; i <= b; ++i)
#define FORD(i, a, b) for (int i = a; i >= b; --i)
#define REP(i, n) FOR(i, 0, (int)n - 1)
#define pb(x) push_back(x)
#define mp(a, b) make_pair(a, b)
#define MSX(a, x) memset(a, x, sizeof(a))
#define SORT(a, n) sort(begin(a), begin(a) + n)
#define ll long long
#define pii pair<int, int>
#define MOD 1000000007
int c[100000];
bool r[100000];
int n, l;
int value() {
int res = 0;
REP(i, n) {
res += round(100.0 * c[i] / n);
}
// if (res > 100) {
// printf("Count :");
// REP(i, n) {
// printf(" %d", c[i]);
// }
// printf("\nRound :");
// REP(i, n) {
// printf(" %d", (int)round(100.0 * c[i] / n));
// }
// printf("\n");
// }
return res;
}
int recursiveDP(int rem) {
if (rem == 0) {
return value();
}
else {
int maxVal = 0;
REP(i, n) {
c[i]++;
maxVal = max(maxVal, recursiveDP(rem - 1));
c[i]--;
}
return maxVal;
}
}
int requireToRoundUp(int val, int maxVal) {
int delta = 0;
bool flag = false;
while (delta <= maxVal) {
double percent = 100.0 * (val + delta) / n;
double fraction = percent - (int)percent;
if (fraction >= 0.5000) {
flag = true;
break;
}
delta++;
}
return flag ? delta : -1;
}
int algo(int rem) {
int newLang = requireToRoundUp(0, rem);
vector<pii> delta;
REP(i, l) {
int val = requireToRoundUp(c[i], rem);
if (val != -1 && (val < newLang || newLang == -1)) {
delta.pb(mp(val, i));
}
}
SORT(delta, delta.size());
int roundUp = 0;
REP(i, delta.size()) {
if (rem >= delta[i].first) {
rem -= delta[i].first;
c[delta[i].second] += delta[i].first;
roundUp++;
}
}
printf("RU : %d\n", roundUp);
if (newLang != -1) {
roundUp += newLang / rem;
}
else {
roundUp += round(100.0 * rem / n);
}
printf("NewLang = %d\n", newLang);
REP(i, l) {
roundUp += round(100.0 * c[i] / n);
}
return roundUp;
}
int main() {
int t;
scanf("%d", &t);
REP(tc, t) {
MSX(c, 0);
MSX(r, 0);
scanf("%d %d", &n, &l);
int surveyed = 0;
REP(i, l) {
scanf("%d", &c[i]);
surveyed += c[i];
}
int res2 = algo(n - surveyed);
int res1 = recursiveDP(n - surveyed);
printf("Case #%d: %d\n", tc + 1, res1);
printf("ALGO #%d: %d\n\n", tc + 1, res2);
}
return 0;
}
// | true |
380b91802ee49987bf20afdb9827129054339f28 | C++ | olethrosdc/beliefbox | /src/statistics/SparseTransitions.h | UTF-8 | 2,704 | 2.890625 | 3 | [] | no_license | /* -*- Mode: c++; -*- */
// copyright (c) 2009 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef SPARSE_TRANSITIONS_H
#define SPARSE_TRANSITIONS_H
#include <map>
#include <vector>
#include "real.h"
/**
\ingroup StatisticsGroup
*/
/*@{*/
/** A sparse transition model for discrete observations.
*/
class SparseTransitions
{
protected:
typedef long Context;
typedef std::map<int, std::vector<real>, std::greater<int> > SourceMap;
typedef SourceMap::iterator SourceMapIterator;
typedef SourceMap::const_iterator SourceMapCIterator;
int n_sources; ///< number of source contexts
int n_destinations; ///< number of next observations
SourceMap sources; ///< a map of sources
public:
/** Constructor
@param n_sources number of contexts
@param n_destinations number of predicted values
*/
SparseTransitions(int n_sources, int n_destinations)
{
this->n_sources = n_sources;
this->n_destinations = n_destinations;
}
/// Get the raw weight of a particular src/dst pair.
real get_weight(int src, int dst) const
{
const SourceMapCIterator i = sources.find(src);
if (i==sources.end()) {
return 0.0;
} else {
return i->second[dst];
}
}
/// Get the weights of all predictions from a src context.
std::vector<real> get_weights(int src) const
{
const SourceMapCIterator i = sources.find(src);
if (i==sources.end()) {
std::vector<real> zero_vector(n_destinations);
return zero_vector;
} else {
return i->second;
}
}
/// Get the number of destinations
int nof_destinations() const
{
return n_destinations;
}
/// Get the number of sources
int nof_sources() const
{
return n_sources;
}
/// Observe a particular transition
real observe(int src, int dst)
{
const SourceMapIterator i = sources.find(src);
if (i==sources.end()) {
std::vector<real> v(n_destinations);
for (int j=0; j<n_destinations; ++j) {
v[j] = 0.0;
}
v[dst] = 1.0;
//std::pair<SourceMapIterator, bool> ret =
sources.insert(std::make_pair(src, v));
return 1.0;
} else {
i->second[dst]++;
return i->second[dst];
}
}
};
/*@}*/
#endif
| true |
6b7572f2f64bed96e39fdade3ff033c1c6dbc5e3 | C++ | senestone/ActionTimer | /src/ActionTimer.h | UTF-8 | 654 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /***********************************************************************
* Class: ActionTimer
*
* Author: Charles McKnight
*
* Description:
* This class provides a millis()-driven timer that can be used to
* control object states and actions.
***********************************************************************/
#pragma once
#ifndef ACTIONTIMER_H
#define ACTIONTIMER_H
#include <Arduino.h>
class ActionTimer {
public:
ActionTimer();
~ActionTimer();
void start(unsigned long duration);
bool isExpired();
private:
bool expirationState;
unsigned long startTime;
unsigned long duration;
};
#endif | true |
ae10c9f1fd355fdb7b87d5745d6925ece73ee559 | C++ | sergiobravo-git/IPC202101 | /While5.cpp | ISO-8859-1 | 477 | 3.5 | 4 | [] | no_license | #include<iostream>
using namespace std;
int main()
{
// while (<CONDICION>) for (<INICIALES>;<CONDICION>;<INCREMENTOS>)
// 1,2,3,4,5
int i;
cout<<"Usando el ciclo for"<<endl;
for(i=7;i<=5;i++)
cout<<i<<endl;
cout<<"****la variable i termino en, despus del ciclo for. "<<
i<<endl<<"Usando el ciclo do...while"<<endl;
i=7;
do
{
cout<<i<<endl;
i++;
} while (i<=5);
cout<<"****la variable i termino en, despus del ciclo do...while. "<<
i<<endl;
}
| true |
036aa5a8c8a585c1cdb5e796a6dfe8100e6dabdb | C++ | koochin/course-scheduler | /src/course_graph.cpp | UTF-8 | 535 | 3.171875 | 3 | [] | no_license | #include "../include/course_graph.h"
CourseGraph::CourseGraph(const std::vector<std::vector<int>>& graph, const std::vector<CourseNode>& nodes) {
this->graph = graph;
this->nodes = nodes;
this->V = nodes.size();
int edges{};
for (const auto& node : graph) {
edges += node.size();
}
this->E = edges;
}
const std::vector<int>& CourseGraph::get_neighbours(const int& node) {
return this->graph[node];
}
const CourseNode& CourseGraph::get_course(const int& node) {
return this->nodes[node];
} | true |
55bb6a27b7c64dc0e40603e7d4a44932adf7b294 | C++ | jwarton/N-Technium-Libs | /NT-Template/ntechnium/libNtechnium/FEM/archive/ntNode_arm.h | UTF-8 | 3,796 | 2.578125 | 3 | [] | no_license | ///////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////// ntNode_arm.h
// openGl scratch libs ///////////////////
// Element Class ///////////////////
// created by James Warton on 11/04/2014 ///////////////////
///////////////////////////////////////////////////////////////////
#ifndef FEM_NODE_JPW_NTECHNIUM_ARM
#define FEM_NODE_JPW_NTECHNIUM_ARM
#include <iostream>
#include <sstream>
#include <vector>
#include <array>
#include "ntVec3.h"
#include "ntVertex.h"
#include "ntEdge.h"
using namespace jpw;
class ntTruss;///////////////////////////////// FORWARD DECLARE
class ntElement;
enum BC_type { FIX, X, Y, Z, U, V, W, PIN, FREE };
class ntNode : public ntVertex{
private:
protected:
std::string id = "node_";
std::string id_i; //identification
Vec3 posI; //position initial
Vec3 posD; //position after displacement
Vec3 Q; //nodal displacement: (x,y,z)
Vec3 R; //nodal rotation: (u,v,w)
Vec3 F; //force applied at node
Vec3 M; //moment applied at node
int maxDOF; //set value from element init()
int dof = 3; //degrees of freedom
int bc = 0; //bc = dof - fixed conditions
void def_BC();
/////////////////////////// MEMBERS ACCESSED BY FRIEND CLASS
bool free = true;
bool fixed = false;
bool fixed_X = false;
bool fixed_Y = false;
bool fixed_Z = false;
bool fixed_U = true;
bool fixed_V = true;
bool fixed_W = true;
public:
friend class ntTruss;
friend class ntElement;
ntNode(ntVec3* pos);
ntNode(ntVec3* pos, int dof); ///TEMPORARY SOLUTION FOR FRAME ELEMENTS
ntNode(ntVec3* pos, ntCol4 col);
void set_BC(BC_type n);
void set_FC(ntVec3 f);
void set_MC(ntVec3 m);
void reset();
int get_DOF();
int get_BC();
bool is_Free();
};
inline ntNode::ntNode(ntVec3* pos) :
ntVertex(pos){
posI.x = pos->x;
posI.y = pos->y;
posI.z = pos->z;
maxDOF = 3;
}
inline ntNode::ntNode(ntVec3* pos, int dof) :
ntVertex(pos){
posI.x = pos->x;
posI.y = pos->y;
posI.z = pos->z;
maxDOF = dof;
}
inline ntNode::ntNode(ntVec3* pos, ntCol4 col):
ntVertex(pos, col){
posI.x = pos->x;
posI.y = pos->y;
posI.z = pos->z;
maxDOF = 3;
}
inline void ntNode::set_BC(BC_type n){
if (n == FREE){
free = true;
fixed = false;
fixed_X = false;
fixed_Y = false;
fixed_Z = false;
if (maxDOF == 6){
fixed_U = false;
fixed_V = false;
fixed_W = false;
}
} else {
free = false;
if (n == FIX){
fixed = true;
fixed_X = true;
fixed_Y = true;
fixed_Z = true;
fixed_U = true;
fixed_V = true;
fixed_W = true;
}
if (n == PIN){
fixed = false;
fixed_X = true;
fixed_Y = true;
fixed_Z = true;
fixed_U = false;
fixed_V = false;
fixed_W = false;
}
if (n == X){ fixed_X = true; }
if (n == Y){ fixed_Y = true; }
if (n == Z){ fixed_Z = true; }
if (n == U){ fixed_U = true; }
if (n == V){ fixed_V = true; }
if (n == W){ fixed_W = true; }
}
def_BC();
}
inline void ntNode::set_FC(ntVec3 F){
this->F = F;
}
inline void ntNode::set_MC(ntVec3 M){
this->M = M;
}
inline void ntNode::def_BC(){
dof = maxDOF;
if (free == false){
if (fixed == true){
dof = 0;
} else {
if (fixed_X == true){
dof -= 1;
}
if (fixed_Y == true){
dof -= 1;
}
if (fixed_Z == true){
dof -= 1;
}
if (fixed_U == true && maxDOF == 6){
dof -= 1;
}
if (fixed_V == true && maxDOF == 6){
dof -= 1;
}
if (fixed_W == true && maxDOF == 6){
dof -= 1;
}
}
}
}
inline void ntNode::reset(){
free = true;
fixed = false;
fixed_X = false;
fixed_Y = false;
fixed_Z = false;
}
inline int ntNode::get_BC(){
bc = maxDOF - dof;
return bc;
}
inline int ntNode::get_DOF(){
def_BC();
return maxDOF;
}
inline bool ntNode::is_Free(){
return free;
}
#endif
| true |
30dd68e92faca66000fc3524f6c9e60d834530e5 | C++ | radtek/RetroCode | /FoxMediaCenter/FoxMediaCenter/Blowfish/Blowfish.h | UTF-8 | 3,772 | 3.125 | 3 | [
"MIT"
] | permissive |
////////////////////////////////////////////////////////////////////////////
///
// Blowfish.h Header File
//
// BLOWFISH ENCRYPTION ALGORITHM
//
// Encryption and Decryption of Byte Strings using the Blowfish Encryption Algorithm.
// Blowfish is a block cipher that encrypts data in 8-byte blocks. The algorithm consists
// of two parts: a key-expansion part and a data-ancryption part. Key expansion converts a
// variable key of at least 1 and at most 56 bytes into several subkey arrays totaling
// 4168 bytes. Blowfish has 16 rounds. Each round consists of a key-dependent permutation,
// and a key and data-dependent substitution. All operations are XORs and additions on 32-bit words.
// The only additional operations are four indexed array data lookups per round.
// Blowfish uses a large number of subkeys. These keys must be precomputed before any data
// encryption or decryption. The P-array consists of 18 32-bit subkeys: P0, P1,...,P17.
// There are also four 32-bit S-boxes with 256 entries each: S0,0, S0,1,...,S0,255;
// S1,0, S1,1,...,S1,255; S2,0, S2,1,...,S2,255; S3,0, S3,1,...,S3,255;
//
// The Electronic Code Book (ECB), Cipher Block Chaining (CBC) and Cipher Feedback modes
// are used:
//
// In ECB mode if the same block is encrypted twice with the same key, the resulting
// ciphertext blocks are the same.
//
// In CBC Mode a ciphertext block is obtained by first xoring the
// plaintext block with the previous ciphertext block, and encrypting the resulting value.
//
// In CFB mode a ciphertext block is obtained by encrypting the previous ciphertext block
// and xoring the resulting value with the plaintext
//
// The previous ciphertext block is usually stored in an Initialization Vector (IV).
// An Initialization Vector of zero is commonly used for the first block, though other
// arrangements are also in use.
/*
http://www.counterpane.com/vectors.txt
Test vectors by Eric Young. These tests all assume Blowfish with 16
rounds.
*/
#ifndef __BLOWFISH_H__
#define __BLOWFISH_H__
//Block Structure
struct SBlock
{
//Constructors
SBlock(unsigned int l=0, unsigned int r=0) : m_uil(l), m_uir(r) {}
//Copy Constructor
SBlock(const SBlock& roBlock) : m_uil(roBlock.m_uil), m_uir(roBlock.m_uir) {}
SBlock& operator^=(SBlock& b) { m_uil ^= b.m_uil; m_uir ^= b.m_uir; return *this; }
unsigned int m_uil, m_uir;
};
class CBlowFish
{
public:
enum { ECB=0, CBC=1, CFB=2 };
//Constructor - Initialize the P and S boxes for a given Key
CBlowFish(unsigned char* ucKey, size_t n, const SBlock& roChain = SBlock(0UL,0UL));
//Resetting the chaining block
void ResetChain() { m_oChain = m_oChain0; }
// Encrypt/Decrypt Buffer in Place
void Encrypt(unsigned char* buf, size_t n, int iMode=ECB);
void Decrypt(unsigned char* buf, size_t n, int iMode=ECB);
// Encrypt/Decrypt from Input Buffer to Output Buffer
void Encrypt(const unsigned char* in, unsigned char* out, size_t n, int iMode=ECB);
void Decrypt(const unsigned char* in, unsigned char* out, size_t n, int iMode=ECB);
//Private Functions
private:
unsigned int F(unsigned int ui);
void Encrypt(SBlock&);
void Decrypt(SBlock&);
private:
//The Initialization Vector, by default {0, 0}
SBlock m_oChain0;
SBlock m_oChain;
unsigned int m_auiP[18];
unsigned int m_auiS[4][256];
static const unsigned int scm_auiInitP[18];
static const unsigned int scm_auiInitS[4][256];
};
//Extract low order byte
inline unsigned char MyByte(unsigned int ui)
{
return (unsigned char)(ui & 0xff);
}
//Function F
inline unsigned int CBlowFish::F(unsigned int ui)
{
return ((m_auiS[0][MyByte(ui>>24)] + m_auiS[1][MyByte(ui>>16)]) ^ m_auiS[2][MyByte(ui>>8)]) + m_auiS[3][MyByte(ui)];
}
#endif // __BLOWFISH_H__
| true |
ced4b630ad926bd08b055692496926e6699777b4 | C++ | ala24013/CA_SPR12 | /ASM/Converter.cpp | UTF-8 | 8,784 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
#define FILEPATH ../testASM
string binary(int n)
{
//TODO
//handle negatives
string result;
do result.push_back( '0' + (n & 1) );
while (n >>= 1);
reverse( result.begin(), result.end() );
return result;
}
int Converter::parseInput(string filepath)
{
string temp;
if((filepath == NULL) || (filepath == ""))
filepath = FILEPATH;
//exception handling for input
ifstream fin;
fin.exceptions(ifstream::failbit|ifstream::badbit);
try
{
fin.open(filepath);
//PARSE ASM FROM TXT HERE
while(getline(fin,temp))
{
asmCode.push_back(temp);
}
}
catch (ifstream::failure e)
{
cout << "error opening/reading file" << endl;
}
fin.close();
return 0;
}
int Converter::convertToMachine(void)
{
str opcode, operands, binary, func;
char type;
for(int i = 0; i < asmCode.size(); i++)
{
//CODE TO CONVERT EACH ASM LINE INTO MACHINE CODE GOES HERE
//first split into opcode and operands
opcode = strtok(asmCode[i],' ');
operands = strtok(asmCode[i],' ');
binary = "";
cout << "found opcode " << opcode << " with operands " << operands << endl;
switch (opcode)
{
case "add":
binary.append("0000"); //append opcode to binary
type = 'R';
func = "000";
break;
case "sub":
binary.append("0000"); //append opcode to binary
type = 'R';
func = "001";
break;
case "slt":
binary.append("0000"); //append opcode to binary
type = 'R';
func = "010";
break;
case "sgt":
binary.append("0000"); //append opcode to binary
type = 'R';
func = "011";
break;
case "sle":
binary.append("0000"); //append opcode to binary
type = 'R';
func = "100";
break;
case "sge":
binary.append("0000"); //append opcode to binary
type = 'R';
func = "101";
break;
case "and":
binary.append("0001"); //append opcode to binary
type = 'R';
func = "000";
break;
case "or":
binary.append("0001"); //append opcode to binary
type = 'R';
func = "001";
break;
case "nor":
binary.append("0001"); //append opcode to binary
type = 'R';
func = "010";
break;
case "xor":
binary.append("0001"); //append opcode to binary
type = 'R';
func = "011";
break;
case "sll":
binary.append("0010"); //append opcode to binary
type = 'I';
func = "";
break;
case "srl":
binary.append("0011"); //append opcode to binary
type = 'I';
func = "";
break;
case "beq":
binary.append("0100"); //append opcode to binary
type = 'I';
func = "";
break;
case "blt":
binary.append("0101"); //append opcode to binary
type = 'I';
func = "";
break;
case "bgt":
binary.append("0110"); //append opcode to binary
type = 'I';
func = "";
break;
case "ble":
binary.append("0111"); //append opcode to binary
type = 'I';
func = "";
break;
case "bge":
binary.append("1000"); //append opcode to binary
type = 'I';
func = "";
break;
case "ori":
binary.append("1001"); //append opcode to binary
type = 'I';
func = "";
break;
case "andi":
binary.append("1010"); //append opcode to binary
type = 'I';
func = "";
break;
case "lw":
binary.append("1011"); //append opcode to binary
type = 'I';
func = "";
break;
case "sw":
binary.append("1100"); //append opcode to binary
type = 'I';
func = "";
break;
case "j":
binary.append("1101"); //append opcode to binary
type = 'J';
func = "";
break;
default:
cout << "bad opcode " << opcode << endl;
return 1;
} // end switch
//now switch on type
switch(type)
{
case 'R':
string rd,rs,rt;
rd = strtok(operands,',');
rs = strtok(operands,',');
rt = strtok(operands,',');
//make sure they're registers
if (rd[0] != '$') || (rd[1] != 'r') || (rs[0] != '$') || (rs[1] != 'r') || (rt[0] != '$') || (rt[1] != 'r')
{
cout << "bad operand!" << endl;
return 1;
}
int iRd, iRs, iRt;
string bRd,bRs,bRt;
iRd = atoi(rd[2]);
iRs = atoi(rs[2]);
iRt = atoi(rt[2]);
if (iRd < 0) || (iRd > 7) || (iRs < 0) || (iRs > 7) || (iRt < 0) || (iRt > 7)
{
cout << "bad register number!" << endl;
return 1;
}
bRd = toBinary(iRd);
bRs = toBinary(iRs);
bRt = toBinary(iRt);
//TODO
//add padding zeros
binary.append(bRd);
binary.append(bRs);
binary.append(bRt);
//registers finished, so append func
binary.append(func);
//finished
break;
case 'I':
string rs, rt, imm;
rs = strtok(operands,',');
rt = strtok(operands,',');
imm = strtok(operands',');
//make sure they're registers
if (rs[0] != '$') || (rs[1] != 'r') || (rt[0] != '$') || (rt[1] != 'r')
{
cout << "bad operand!" << endl;
return 1;
}
int iRt, iRs;
string bRt,bRst;
iRs = atoi(rs[2]);
iRt = atoi(rt[2]);
if (iRs < 0) || (iRs > 7) || (iRt < 0) || (iRt > 7)
{
cout << "bad register number!" << endl;
return 1;
}
bRs = toBinary(iRs);
bRt = toBinary(iRt);
//TODO
//add padding zeros
binary.append(bRs);
binary.append(bRt);
//handle immediate
int iImm;
string bImm;
iImm = atoi(imm.c_str());
bImm = toBinary(iImm);
binary.append(bImm);
break;
case 'J':
//handle address in operands
int iAddr;
string bAddr;
iAddr = atoi(operands.c_str());
bAddr = toBinary(iAddr);
binary.append(bAddr);
break;
default:
return 1; //should never get here
} // end type switch
//binary is ready; push it back
machineCode.push_back(binary);
} // end for
return 0;
}
int Converter::createIMEM(void)
{
for(int i = 0; i < machineCode.size(); i++)
{
//Stores Machine Code in IMEM
MEMSlot MemSlot;
MemSlot.data = machineCode[i];
int memLoc = 2 * i;
MemSlot.location = intToString(memLoc);
IMEM.push_back(MemSlot);
}
}
| true |
73d567b7a158958803d38900b07d5ebcef0c5bab | C++ | leighfall/130-Projects | /lab1.cpp | UTF-8 | 3,372 | 4.03125 | 4 | [] | no_license | //Lab1
//COSC130
//Description: This program takes two values and an operation and converts values
//to integers, performs the operation and converts the value back to strings.
//Autumn Henderson
//January 18th, 2019
#include <iostream>
#include <string>
using namespace std;
int CharToInt(char v);
char IntToChar(int v);
int StringToInt(string val);
string IntToString(int val);
int main(int argc, char *argv[])
{
string sresult;
int left;
int right;
char op;
if (4 != argc) {
printf("Usage: %s <left> <op> <right>\n", argv[0]);
return -1;
}
//Notice that this calls your StringToInt. So, make sure you debug
//StringToInt() to make sure that left and right get a proper
//value.
left = StringToInt(argv[1]);
right = StringToInt(argv[3]);
op = argv[2][0];
//Calculate based on the op. Notice that this calls IntToString,
//so debug your IntToString() function to make sure that sresult
//is given the proper result.This assumes your StringToInt already
//works.
switch (op)
{
case 'x':
sresult = IntToString(left * right);
break;
case '/':
sresult = IntToString(left / right);
break;
case '+':
sresult = IntToString(left + right);
break;
case '-':
sresult = IntToString(left - right);
break;
case '%':
sresult = IntToString(left % right);
break;
default:
sresult = IntToString(left);
break;
}
//Remember, printf is the only output function you may use for this lab!
//The format string is %d %c %d = %s. This means that the first argument is %d (decimal / integer),
//%c (characer), %d (decimal/integer),
//%s (string). Notice that because printf() is a C-style function, you
//must pass strings as character arrays. We can convert a C++ string
//to a character array (C-style string) by using the c_str() member function.
printf("%d %c %d = %s\n", left, op, right, sresult.c_str());
return 0;
}
//This function converts a character to an integer
int CharToInt(char v) {
return v - 48;
}
//This function converts an integer to a character
char IntToChar(int v) {
return v + 48;
}
//This function takes a string and converts it into an integer
int StringToInt(string val) {
int i = val.size() - 1;
bool valueIsNegative = false;
int digit = 0;
int tensPower = 1;
int newValue = 0;
//Handles negative
if (val[i] == '-') {
valueIsNegative = true;
--i;
}
//Examines string at index i, multiplies by
//appropriate 10s power, then adds values together
for (i = i; i >= 0; --i) {
digit = CharToInt(val[2]);
for (int j = 0; j < i; ++j) {
tensPower *= 10;
}
newValue += (digit * tensPower);
tensPower = 1;
}
//Converts value to negative
if (valueIsNegative) {
newValue = 0 - newValue;
}
return newValue;
}
//This function takes an integer and converts it to a string
string IntToString(int val) {
string finalAnswer = "";
int digit;
char newLetter;
string tempAnswer = "";
//Converts val to positive and adds negative character
if (val < 0) {
val = val * -1;
finalAnswer += "-";
}
//Takes individual digit, converts to character, adds it to a
//temporary answer
do {
digit = val % 10;
newLetter = IntToChar(digit);
tempAnswer = newLetter + tempAnswer;
val /= 10;
}while (val > 0);
//temporary answer is added to final answer to handle the negative
//if needed
finalAnswer += tempAnswer;
return finalAnswer;
}
| true |
2602d664fd858489c888e8558f443b6b3614b897 | C++ | Yu-anan/ece551 | /068_circle/point.cpp | UTF-8 | 260 | 3.234375 | 3 | [] | no_license | #include "point.h"
#include <cmath>
Point::Point(){
x=0;
y=0;
}
void Point::move(double dx, double dy){
x=x+dx;
y=y+dy;
}
double Point::distanceFrom(const Point & p){
double distence = sqrt(((x-p.x)*(x-p.x))+((y-p.y)*(y-p.y)));
return distence;
}
| true |
3d6850b2de2da2f39c588f64ce73bcf51395e88f | C++ | Sebelino/Team18v2 | /bpt-sebelino/bpt.cpp | UTF-8 | 5,580 | 3.484375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <cstring>
#include <algorithm>
#include <iterator>
#include <queue>
using namespace std;
// Read from stdin.
vector<string> readBoard() {
vector<string> board;
for (string line; getline(cin, line);)
board.push_back(line);
return board;
}
// Prints out the input lines.
void display(vector<string>& lines) {
for(vector<string>::const_iterator i=lines.begin();i != lines.end();++i){
cout << *i << endl;
}
}
// Returns a pair (x,y) representing the position of (an) @.
// Returns (-1,-1) if no such character exists.
// Returns (-2,-2) if such a character exists on a goal.
pair<int,int> startPosition(vector<string> & board){
// Får runtime-error om jag ens använder brädstorleken i en beräkning.
int esrnt = board.size();
bool sthswrong = (esrnt >= 0);
// while(1){}
//Timelimit
if(sthswrong){
while(1){}
}
for(int i = 0;i < esrnt;i++){
//Runtime
for(int j = 0;j < board[i].length();j++){
//Runtime
if(board[i][j] == '+'){
//Runtime
return make_pair(-2,-2);
}
if(board[i][j] == '@'){
return make_pair(j,i);
}
}
}
while(1){}
return make_pair(-1,-1);
}
vector<pair<int,int> > goalPositions(vector<string> & board){
vector<pair<int,int> > goals;
for(int i = 0;i < board.size();i++){
for(int j = 0;j < board[i].length();j++){
if(board[i][j] == '.'){
goals.push_back(make_pair(j,i));
}
}
}
return goals;
}
int matrixWidth(vector<string> lines){
int max;
for(int i = 0;i < lines.size();i++){
if(lines[i].length() > max){
max = lines[i].length();
}
}
return max;
}
vector<pair<int,int> > successors(vector<string> & board,pair<int,int> node){
vector<pair<int,int> > ss;
int diffs[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};
for(int i = 0;i < 4;i++){
int x = node.first+diffs[i][0];
int y = node.second+diffs[i][1];
if(x >= 0
&& x < matrixWidth(board)
&& y >= 0
&& y < board.size()
&& (board[y][x] == ' '
|| board[y][x] == '.')){
ss.push_back(make_pair(x,y));
}
}
return ss;
}
bool contains(pair<int,int> x,vector<pair<int,int> > v){
for(int i = 0;i < v.size();i++){
if(x.first == v[i].first && x.second == v[i].second){
return true;
}
}
return false;
}
// Generic search algorithm. Returns a path to the goal, if accessible.
// Returns a path with (-1,-1) if there is no such path.
vector<pair<int,int> > pathfinding(vector<string> & board){
//Timelimit
queue<vector<pair<int,int> > > q;
vector<pair<int,int> > rootPath;
vector<pair<int,int> > goals = goalPositions(board);
//Timelimit
int w = matrixWidth(board);
int h = board.size();
int visited[w][h]; // 0 |-> Not visited, 1 |-> Fringe, 2 |-> Visited.
//Timelimit
for(int i = 0;i < h;i++){
for(int j = 0;j < w;j++){
visited[j][i] = 0;
}
}
//Timelimit
rootPath.push_back(startPosition(board));
//Runtime
if(rootPath.back().first == -1 && rootPath.back().second == -1){
vector<pair<int,int> > nopath;
nopath.push_back(pair<int,int>(-1,-1));
return nopath;
}
//Runtime
if(rootPath.back().first == -2 && rootPath.back().second == -2){
return vector<pair<int,int> >();
}
//Runtime
q.push(rootPath);
//Runtime
while(1){
if(q.empty()){
vector<pair<int,int> > nopath;
nopath.push_back(pair<int,int>(-1,-1));
return nopath;
}
vector<pair<int,int> > path = q.front();
q.pop();
visited[path.back().first][path.back().second] = 2;
if(contains(path.back(),goals)){
return path;
}
vector<pair<int,int> > succs = successors(board,path.back());
for(int i = 0;i < succs.size();i++){
int x = succs[i].first;
int y = succs[i].second;
if(visited[x][y] == 0){
visited[x][y] = 1;
vector<pair<int,int> > newPath = path;
newPath.push_back(succs[i]);
q.push(newPath);
}
}
}
}
// Returns directions, given a collection of lines that make up the board.
string answer(vector<string>& board){
vector<pair<int,int> > path = pathfinding(board);
if(path.size() == 1 && path.front().first == -1 && path.front().second == -1){
return "no path\n";
}
string directions = "";
for(int i = 0;i < (path.size()<=0 ? 0 : path.size()-1);i++){
if(path[i+1].first == path[i].first+1 && path[i+1].second == path[i].second){
directions += 'R';
}else if(path[i+1].first == path[i].first-1 && path[i+1].second == path[i].second){
directions += 'L';
}else if(path[i+1].first == path[i].first && path[i+1].second == path[i].second+1){
directions += 'D';
}else if(path[i+1].first == path[i].first && path[i+1].second == path[i].second-1){
directions += 'U';
}
}
directions += '\n';
return directions;
}
int main(int argc, char **argv) {
vector<string> board;
board = readBoard();
// Obs. blankrad för triviala fallet.
cout << answer(board);
return 0;
}
| true |
509a23468e803302435fa676dc4d4ab2d3ec542f | C++ | Sionesevaki/SinglyLinkedList | /MovieNode.cpp | UTF-8 | 938 | 3.203125 | 3 | [] | no_license | //
// MovieNode.cpp
// SinglyLinkedListHW2
//
// Created by Sione on 10/10/17.
// Copyright © 2017 FangaiuihaCode. All rights reserved.
//
#include "MovieNode.hpp"
MovieNode::MovieNode(Movie movie)
{
this->movie = movie;
next = nullptr;
}
Movie MovieNode::getMovie() const
{
return movie;
}
MovieNode* MovieNode::getNext(void) const
{
return next;
}
void MovieNode::setNext(MovieNode* newNext)
{
if(this->getNext())
{
newNext = this->next;
this->next = newNext;
}
else
{
this->next = newNext;
}
}
void MovieNode::write(ostream& outfile) const
{
movie.write(outfile);
}
ostream& operator << (ostream& outfile, const MovieNode& node)
{
node.write(outfile);
return outfile;
}
bool MovieNode::operator < ( const MovieNode& rhs ) const
{
if(movie.title < rhs.getMovie().title)
{
return true;
}
else
return false;
}
| true |
f14a92e2688f5c37de57700fa372202858eb7c51 | C++ | cbaltingok98/Programming-Questions | /Questions/Coding Ability Test/Bronze 1/firstUniqueCharacter.cpp | UTF-8 | 707 | 3.40625 | 3 | [] | no_license | class Solution
{
public:
/**
* @param str: str: the given string
* @return: char: the first unique character in a given string
*/
char firstUniqChar(string &str)
{
// Write your code here
vector<int> charSet(27, 0);
bool stop = true;
char c = ' ';
int hold = 0;
for (int i = 0; i < str.size(); i++)
{
c = str.at(i);
hold = c - 97;
charSet.at(hold)++;
}
for (int i = 0; i < charSet.size() && stop; i++)
{
if (charSet.at(i) == 1)
{
c = i + 97;
stop = false;
}
}
return c;
}
}; | true |
a58253211361e693f6d1839d43331ba739b88ac5 | C++ | btcup/sb-admin | /exams/2559/02204111/2/midterm/1_1_713_5920503351.cpp | UTF-8 | 2,166 | 2.9375 | 3 | [
"MIT"
] | permissive | //5920503351Katekanok Meeruang
#include<iostream>
using namespace std;
int main ()
{
int year,downpayment,a,b,c,j;
float Amount,Finan,;
char model;
cout<<"------- Car lease calculator -----------"<<endl;
cout<<"Enter car model : "<<model;
cin>>model;
cout<<"Enter number of years (1-6) :"<<year;
cin>>year;
cout<<"Enter percentage of down payment :"<<downpayment;
cin>>downpayment;
cout<<"----------------------------------------"<<endl;
if(model='A',year<=6){
a=1385000;{
cout<<"Financing amount : "<<a/(downpayment/100)<<endl;
Finan=a/(downpayment/100);
cout<<"Amount of interest : "<<Finan*2.09*year<<endl;
Amount=Finan*2.09*year;
cout<<"Monthly payment : "<<(Finan+Amount)/(year*12)<<endl;
}
}
else if(model='B',year<=6){
b=511500;{
cout<<"Financing amount : "<<b/(downpayment/100)<<endl;
Finan=b/(downpayment/100);
cout<<"Amount of interest : "<<Finan*1.79*year<<endl;
Amount=Finan*1.79*year;
cout<<"Monthly payment : "<<(Finan+Amount)/(year*12)<<endl;
}
}
else if(model='C',year<=6){
c=738000;{
cout<<"Financing amount : "<<c/(downpayment/100)<<endl;
Finan=c/(downpayment/100);
cout<<"Amount of interest : "<<Finan*1.99*year<<endl;
Amount=Finan*1.99*year;
cout<<"Monthly payment : "<<(Finan+Amount)/(year*12)<<endl;
}
}
else if(model='J',year<=6){
j==694000;{
cout<<"Financing amount : "<<j/(downpayment/100)<<endl;
Finan=j/(downpayment/100);
cout<<"Amount of interest : "<<Finan*1.99*year<<endl;
Amount=Finan*1.99*year;
cout<<"Monthly payment : "<<(Finan+Amount)/(year*12)<<endl;
}
}
else
cout<<"Error!, number of years is not in range";
system("pause");
return 0;
}
| true |
ca8b10c5fb093c3fc42aa02e4b6ac5c9d7604858 | C++ | brorica/Algorithm | /simulation/3048.cpp | UTF-8 | 846 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N1, N2, timer;
string antGroupA, antGroupB;
vector<char> ant, symbol;
cin >> N1 >> N2;
cin >> antGroupA >> antGroupB;
for (int i = 0; i < N1; i++)
{
ant.push_back(antGroupA[i]);
symbol.push_back('>');
}
reverse(ant.begin(), ant.end());
for (int i = 0; i < N2; i++)
{
ant.push_back(antGroupB[i]);
symbol.push_back('<');
}
cin >> timer;
for (int i = 0; i < timer;i++)
{
for (int j = 0; j < N1 + N2 - 1; j++)
{
if (symbol[j] == '>' && symbol[j + 1] == '<')
{
swap(symbol[j], symbol[j + 1]);
swap(ant[j], ant[j + 1]);
j++;
}
}
}
int size = ant.size();
for (int i = 0; i < size; i++)
cout << ant[i];
return 0;
} | true |
1c2fb45f01321587f5916ac8ae1ddb51fbc4f83c | C++ | 201524547/ACM-ICPC_Eat | /1026(sort).cpp | UHC | 892 | 3.46875 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int Multiple_Array(int* A, int* B, int N){
int Sum = 0;
for(int i = 0; i < N; i++){
Sum = Sum + A[i]*B[i];
}
return Sum;
}
int compare_inc(const void *a, const void *b)
{
return *(int *)b - *(int *)a; //
}
int compare_dec(const void *a, const void *b)
{
return *(int *)a - *(int *)b; //
}
void Sort_Array(int* A, int* B, int N){
qsort(A,N,sizeof(int),compare_inc);
qsort(B,N,sizeof(int),compare_dec);
}
int main()
{
int N, output;
int* A, *B;
cin >> N;
A = new int[N];
B = new int[N];
for(int i = 0; i < N; i++){
cin>> A[i];
}
for(int i = 0; i < N; i++){
cin>> B[i];
}
Sort_Array(A,B,N);
output = Multiple_Array(A,B,N);
cout << output;
return 0;
}
| true |
172ad1d3e8ece5e84888ef04f0a3bdebaab4b460 | C++ | pkhadilkar/compcode | /codechef/DEC14/CAPPLE/CAPPLE.cpp | UTF-8 | 566 | 2.921875 | 3 | [] | no_license | /*
* Codechef DEC14 challenge
* Chef and Apple
*/
#include <iostream>
#include <algorithm>
#include <fstream>
#define MAX 100001
using namespace std;
// we don't want to deal with changing offset here
bool apples[MAX + 1];
int main() {
ios_base::sync_with_stdio(false);
int t;
cin >> t;
int N;
int x; // tmp variable
for(int i = 0; i < t; ++i) {
fill(apples, apples + MAX + 1, false);
int count = 0;
cin >> N;
for(int j = 0; j < N; ++j) {
cin >> x;
count += (!apples[x]);
apples[x] = true;
}
cout << count << "\n";
}
return 0;
}
| true |
b01bb414c81b640c913f7d6b5ebf7518dcafc48e | C++ | vslavik/poedit | /deps/boost/libs/core/test/exchange_move_test.cpp | UTF-8 | 1,580 | 2.6875 | 3 | [
"GPL-1.0-or-later",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
Copyright 2018 Glen Joseph Fernandes
(glenjofe@gmail.com)
Distributed under the Boost Software License, Version 1.0.
(http://www.boost.org/LICENSE_1_0.txt)
*/
#include <boost/config.hpp>
#if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES)
#include <boost/core/exchange.hpp>
#include <boost/core/lightweight_test.hpp>
class C1 {
public:
explicit C1(int i)
: i_(i) { }
C1(C1&& c)
: i_(c.i_) { }
C1& operator=(C1&& c) {
i_ = c.i_;
return *this;
}
int i() const {
return i_;
}
private:
C1(const C1&);
C1& operator=(const C1&);
int i_;
};
void test1()
{
C1 x(1);
BOOST_TEST(boost::exchange(x, C1(2)).i() == 1);
BOOST_TEST(x.i() == 2);
}
class C2 {
public:
explicit C2(int i)
: i_(i) { }
operator C1() const {
return C1(i_);
}
int i() const {
return i_;
}
private:
C2(const C2&);
C2& operator=(const C2&);
int i_;
};
void test2()
{
C1 x(1);
BOOST_TEST(boost::exchange(x, C2(2)).i() == 1);
BOOST_TEST(x.i() == 2);
}
class C3 {
public:
explicit C3(int i)
: i_(i) { }
C3(C3&& c)
: i_(c.i_) { }
C3& operator=(C1&& c) {
i_ = c.i();
return *this;
}
int i() const {
return i_;
}
private:
C3(const C3&);
C3& operator=(const C3&);
int i_;
};
void test3()
{
C3 x(1);
BOOST_TEST(boost::exchange(x, C1(2)).i() == 1);
BOOST_TEST(x.i() == 2);
}
int main()
{
test1();
test2();
test3();
return boost::report_errors();
}
#else
int main()
{
return 0;
}
#endif
| true |
0fc07cd80cbc8e91fcedb938112345fd9fa2d162 | C++ | eagletmt/procon | /poj/1/1673.cc | UTF-8 | 1,089 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <complex>
#include <cstdio>
#define M_PI_2 1.570796326795
using namespace std;
const double EPS = 1e-8;
typedef complex<double> P;
struct L : public vector<P> {
L(const P& a, const P& b)
{
push_back(a);
push_back(b);
}
};
double cross(const P& a, const P& b) {
return imag(conj(a)*b);
}
P crosspoint(const L &l, const L &m) {
double A = cross(l[1] - l[0], m[1] - m[0]);
double B = cross(l[1] - l[0], l[1] - m[0]);
if (abs(A) < EPS && abs(B) < EPS) return m[0]; // same line
return m[0] + B / A * (m[1] - m[0]);
}
P solve(P a, P b, P c)
{
b -= a;
c -= a;
P d = c * P(0, -1);
P e = b * P(0, 1);
P f = b + e;
P g = b + (b-c) * P(0, -1);
P h = (d + e) * 0.5;
P i = b + ((f - b) + (g - b))*0.5;
P o = crosspoint(L(P(0,0), h), L(b, i));
return a + o;
}
int main(void)
{
int n;
cin >> n;
for (int i = 0; i < n; i++) {
double a, b, c, d, e, f;
cin >> a >> b >> c >> d >> e >> f;
P p = solve(P(a,b), P(c,d), P(e,f));
printf("%.4f %.4f\n", real(p), imag(p));
}
return 0;
}
| true |
b07812865d812dbf7690074b1415026ad39a552a | C++ | ippilikaushik/competitive-coding | /permpal.cpp | MacCentralEurope | 1,441 | 4.03125 | 4 | [] | no_license | #include<iostream>
#include<iomanip>
using namespace std;
// A function swapping values using references.
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
// A function to implement Heaps Algorithm for the permutation of N numbers.
void print(const int *v)
{
int i;
int size = sizeof(v)/sizeof(int)+1;
// Loop to print the sequence.
cout<<"\t";
for ( i = 0; i < size; i++)
cout<<setw(4)<<v[i];
cout<<"\n";
}
void HeapPermute(int v[], int n)
{
int i;
// Print the sequence if the heap top reaches to the 1.
if (n == 1)
print(v);
else
{
// Fix a number at the heap top until only two one element remaining and permute remaining.
for (i = 0; i < n; i++)
{
HeapPermute(v, n-1);
// If odd then swap the value at the start index with the n-1.
if(n%2 == 1)
swap(&v[0], &v[n-1]);
// If even then swap the value at the 'i' index with the n-1.
else
swap(&v[i], &v[n-1]);
}
}
}
int main()
{
int i, n, count = 1;
cout<<"How many numbers do you want to enter: ";
cin>>n;
int num[n];
// Take the input.
cout<<"\nEnter the numbers: ";
for (i = 0; i < n; i++)
{
cin>>num[i];
count *= (i+1);
}
// Print the permutation's count.
cout<<"\nThe number of permutations possible is: "<<count<<"\n";
// Calling Function to print all the permutation.
HeapPermute(num, n);
return 0;
}
| true |
5ff165ab80456aa10a026ebc3eaf45499ebb6612 | C++ | michal-harish/hellocpp11 | /src/func.cpp | UTF-8 | 960 | 2.515625 | 3 | [] | no_license | #include "func.h"
#include <xmmintrin.h>
#include <vector>
#include <stddef.h>
void vectorAdd(float* a, float* b, float* c, size_t n) {
__m128 A, B, C;
for (size_t i = 0; i < n; i += 4) {
A = _mm_load_ps(&a[i]);
B = _mm_load_ps(&b[i]);
C = _mm_add_ps(A, B);
_mm_store_ps(&c[i], C);
}
}
void vectorSub(float* a, float* b, float* c, size_t n) {
__m128 A, B, C;
for (size_t i = 0; i < n; i += 4) {
A = _mm_load_ps(&a[i]);
B = _mm_load_ps(&b[i]);
C = _mm_sub_ps(A, B);
_mm_store_ps(&c[i], C);
}
}
void vectorMultiply(float* a, float* b, float* c, size_t n) {
__m128 A, B, C;
for (size_t i = 0; i < n; i += 4) {
A = _mm_load_ps(&a[i]);
B = _mm_load_ps(&b[i]);
C = _mm_mul_ps(A, B);
_mm_store_ps(&c[i], C);
}
}
void vectorDiv(float* a, float* b, float* c, size_t n) {
__m128 A, B, C;
for (size_t i = 0; i < n; i += 4) {
A = _mm_load_ps(&a[i]);
B = _mm_load_ps(&b[i]);
C = _mm_div_ps(A, B);
_mm_store_ps(&c[i], C);
}
}
| true |
ae8ebaff69b3ace813b7d78727d2fb4f09701e60 | C++ | uzh-rpg/flightmare | /flightlib/include/flightlib/common/logger.hpp | UTF-8 | 2,912 | 2.890625 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | // """credit: Philipp Foehn """
#pragma once
#include <cstdio>
#include <fstream>
#include <iostream>
#include <string>
namespace flightlib {
class Logger {
public:
Logger(const std::string& name, const bool color = true);
Logger(const std::string& name, const std::string& filename);
~Logger();
inline std::streamsize precision(const std::streamsize n);
inline void scientific(const bool on = true);
template<class... Args>
void info(const std::string& message, const Args&... args) const;
void info(const std::string& message) const;
template<class... Args>
void warn(const std::string& message, const Args&... args) const;
void warn(const std::string& message) const;
template<class... Args>
void error(const std::string& message, const Args&... args) const;
void error(const std::string& message) const;
template<class... Args>
void fatal(const std::string& message, const Args&... args) const;
void fatal(const std::string& message) const;
template<typename T>
std::ostream& operator<<(const T& printable) const;
static constexpr int MAX_CHARS = 256;
private:
static constexpr int DEFAULT_PRECISION = 3;
static constexpr int NAME_PADDING = 15;
static constexpr char RESET[] = "\033[0m";
static constexpr char RED[] = "\033[31m";
static constexpr char YELLOW[] = "\033[33m";
static constexpr char INFO[] = "Info: ";
static constexpr char WARN[] = "Warning: ";
static constexpr char ERROR[] = "Error: ";
static constexpr char FATAL[] = "Fatal: ";
//
std::string name_;
mutable std::ostream sink_;
const bool colored_;
};
template<class... Args>
void Logger::info(const std::string& message, const Args&... args) const {
char buf[MAX_CHARS];
const int n = std::snprintf(buf, MAX_CHARS, message.c_str(), args...);
if (n >= 0 && n < MAX_CHARS)
info(buf);
else
error("=== Logging error ===\n");
}
template<class... Args>
void Logger::warn(const std::string& message, const Args&... args) const {
char buf[MAX_CHARS];
const int n = std::snprintf(buf, MAX_CHARS, message.c_str(), args...);
if (n >= 0 && n < MAX_CHARS)
warn(buf);
else
error("=== Logging error ===\n");
}
template<class... Args>
void Logger::error(const std::string& message, const Args&... args) const {
char buf[MAX_CHARS];
const int n = std::snprintf(buf, MAX_CHARS, message.c_str(), args...);
if (n >= 0 && n < MAX_CHARS)
error(buf);
else
error("=== Logging error ===\n");
}
template<class... Args>
void Logger::fatal(const std::string& message, const Args&... args) const {
char buf[MAX_CHARS];
const int n = std::snprintf(buf, MAX_CHARS, message.c_str(), args...);
if (n >= 0 && n < MAX_CHARS)
fatal(buf);
else
fatal("=== Logging error ===\n");
}
template<typename T>
std::ostream& Logger::operator<<(const T& printable) const {
return sink_ << name_ << printable;
}
} // namespace flightlib | true |
46e0a90b052e1c0d93f66b6cafd427539ea1ca26 | C++ | dariosena/LearningCpp | /arrays/fsra.cpp | UTF-8 | 500 | 3.65625 | 4 | [] | no_license | // A fixed size raw array matrix (that is, a 2D raw array)
#include <iostream>
#include <iomanip>
using namespace std;
auto main() -> int
{
int const n_rows = 3;
int const n_cols = 7;
int const m[n_rows][n_cols] =
{
{1,2,3,4,5,6,7},
{8,9,0,1,2,3,4},
{4,3,5,2,1,6,7}
};
for (int y = 0; y < n_rows; ++y)
{
for (int x = 0; x < n_cols; ++x)
{
cout << setw(4) << m[y][x];
}
cout << '\n';
}
}
| true |
7842678cfdee29ffd798ed34694f82ea01ca5368 | C++ | Anjalikumari15/object_oriented_programs | /OOP14.CPP | UTF-8 | 1,197 | 3.390625 | 3 | [] | no_license | #include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
class players
{
protected:
int experience;
char *type_of_sport;
public:
void getdata()
{
cout<<"Enter experience of player in years : ";
cin>>experience;
cout<<"Enter associated type of sport : ";
gets(type_of_sport);
}
};
class zone:public virtual players
{
protected:
int zrank;
public:
void getzrank()
{
cout<<"Enter rank of player in zones : ";
cin>>zrank;
}
};
class national:public virtual players
{
protected:
int nrank;
public:
void getnrank()
{
cout<<"Enter rank of players in nationals : ";
cin>>nrank;
}
};
class international:public zone,public national
{
int final_rank;
public:
void display()
{
final_rank=zrank+nrank;
cout<<"\nType of sport of player : "<<type_of_sport;
cout<<"\nExperience of player : "<<experience<<" years";
cout<<"\nRank in zones : "<<zrank;
cout<<"\nRank in nationals : "<<nrank;
cout<<"\nRank in internationals : "<<final_rank;
}
};
void main()
{
clrscr();
international p1;
p1.getdata();
p1.getzrank();
p1.getnrank();
p1.display();
getch();
}
| true |
818b37e26e6d1ad371d8b4ccc4e7816966484b4c | C++ | delivite/fractal | /FractalCreator.cpp | UTF-8 | 3,839 | 2.859375 | 3 | [] | no_license | /*
* FractalCreator.cpp
*
* Created on: 29 Jan 2020
* Author: Samuel Chinedu
*/
#include <cassert>
#include "FractalCreator.h"
void FractalCreator::run(std::string name) {
/*addZoom(Zoom(295, m_height - 202, 0.1));
addZoom(Zoom(312, m_height - 304, 0.1));*/
calculateIterations();
totalIterations();
calculateRangeTotal();
drawFractal();
writeBitmap("file.bmp");
}
FractalCreator::FractalCreator(int width, int height) :
m_width { width }, m_height { height }, m_histogram {
(new int[Mandelbrot::MAX_ITERATIONS] { 0 }) }, m_fractal {
(new int[m_width * m_height] { 0 }) }, m_bitmap { m_width,
m_height }, m_zoomList { m_width, m_height } {
// TODO Auto-generated constructor stub
m_zoomList.add(Zoom(m_width / 2, m_height / 2, 4.0 / m_width)); //4.0 / m_width
}
FractalCreator::~FractalCreator() {
// TODO Auto-generated destructor stub
}
void FractalCreator::calculateIterations() {
for (int y = 0; y < m_height; y++) {
for (int x = 0; x < m_width; x++) {
//bitmap.setPixel(x , y , 255, 0, 0);
std::pair<double, double> coords = m_zoomList.doZoom(x, y);
int iterations = Mandelbrot::getIterations(coords.first,
coords.second);
m_fractal[y * m_width + x] = iterations;
if (iterations != Mandelbrot::MAX_ITERATIONS) {
m_histogram[iterations]++;
}
}
}
}
void FractalCreator::drawFractal() {
/* RGB startColor(0, 0, 0);
RGB endColor(0, 0, 255);
RGB diff = endColor - startColor;*/
for (int y = 0; y < m_height; y++) {
for (int x = 0; x < m_width; x++) {
int iterations = m_fractal[y * m_width + x];
int range = getRange(iterations);
int rangeTotal = m_rangeTotals[range];
int rangeStart = m_ranges[range];
RGB &startColor = m_colors[range];
RGB &endColor = m_colors[range + 1];
RGB colorDiff = endColor - startColor;
std::uint8_t red = 0;
std::uint8_t green = 0;
std::uint8_t blue = 0;
if (iterations != Mandelbrot::MAX_ITERATIONS) {
int totalPixels { };
for (int i = rangeStart; i <= iterations; i++) {
totalPixels += m_histogram[i];
}
//green = std::pow(255, hue);
red = startColor.r
+ colorDiff.r * (double) totalPixels / rangeTotal;
green = startColor.g
+ colorDiff.g * (double) totalPixels / rangeTotal;
blue = startColor.b
+ colorDiff.b * (double) totalPixels / rangeTotal;
/*red = std::pow(diff.r, hue);
green = std::pow(diff.g, hue);
blue = std::pow(diff.b, hue);*/
}
m_bitmap.setPixel(x, y, red, green, blue);
}
}
}
void FractalCreator::writeBitmap(std::string name) {
m_bitmap.write(name);
}
void FractalCreator::addZoom(const Zoom &zoom) {
m_zoomList.add(zoom);
}
void FractalCreator::totalIterations() {
for (int i = 0; i < Mandelbrot::MAX_ITERATIONS; i++) {
m_total += m_histogram[i];
}
std::cout << "Overall Total2:" << m_total << std::endl;
}
void FractalCreator::addRange(double rangeEnd, const RGB &rgb) {
m_ranges.push_back(rangeEnd * Mandelbrot::MAX_ITERATIONS);
m_colors.push_back(rgb);
if (m_bGotFirstRange) {
m_rangeTotals.push_back(0);
}
m_bGotFirstRange = true;
}
void FractalCreator::calculateRangeTotal() {
int rangeIndex { 0 };
for (int i = 0; i < Mandelbrot::MAX_ITERATIONS; i++) {
int pixels = m_histogram[i];
if (i >= m_ranges[rangeIndex + 1]) {
rangeIndex++;
}
m_rangeTotals[rangeIndex] += pixels;
}
int overallTotal { 0 };
for (int value : m_rangeTotals) {
std::cout << "Range total: " << value << std::endl;
overallTotal += value;
}
std::cout << "Overall Total1:" << m_total << std::endl;
}
int FractalCreator::getRange(int iterations) const {
int range { 0 };
for (int i = 1; i < m_ranges.size(); i++) {
range = i;
if (m_ranges[i] > iterations) {
break;
}
}
range--;
assert(range > -1);
assert(range < m_ranges.size());
return range;
}
| true |
14cf50898d16f9091f69443fca4222a934ba56cc | C++ | hekl0/Sliding-Puzzle | /MainScreen.cpp | UTF-8 | 1,622 | 2.859375 | 3 | [] | no_license | #include <main.h>
#include <iostream>
void MainScreen::start(SDL_Renderer* gRenderer, bool& quit) {
bool goBack = false;
//clear screen
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear(gRenderer);
//load background
SDL_Surface* surface = IMG_Load("Picture/background.png");
SDL_Texture* background = SDL_CreateTextureFromSurface(gRenderer, surface);
SDL_FreeSurface(surface);
SDL_RenderCopy( gRenderer, background, NULL, NULL );
SDL_RenderPresent( gRenderer );
SDL_Event e;
while (!quit && !goBack) {
while (SDL_PollEvent(&e) != 0) {
if (e.type == SDL_QUIT) quit = true;
if (e.type == SDL_MOUSEBUTTONDOWN)
if( e.button.button == SDL_BUTTON_LEFT ){
int x = e.button.x;
int y = e.button.y;
//New Game
if (259 <= x && x <= 479 && 284 <= y && y <= 356) {
OptionScreen::start(gRenderer, quit);
goBack = true;
}
//Introduction
if (259 <= x && x <= 479 && 419 <= y && y <= 490) {
InstructionScreen::start(gRenderer, quit);
goBack = true;
}
//High score
if (259 <= x && x <= 479 && 563 <= y && y <= 635) {
HighscoreScreen::start(gRenderer, quit);
goBack = true;
}
}
}
}
SDL_DestroyTexture(background);
}
| true |
dc387c2a196b92fbe2b4a7dc6ebc807bc366ea36 | C++ | TannerLow/Expression-Parser | /Validator.h | UTF-8 | 901 | 2.875 | 3 | [] | no_license | #ifndef VALIDATOR_H
#define VALIDATOR_H
#include <string>
#include <vector>
//Recursive descent parser for checking validity of expressions
class Validator
{
public:
Validator(std::vector<std::string> Tokens);
Validator(std::vector<std::string> Tokens, std::vector<std::string>::iterator start);
void reset(std::vector<std::string> Tokens);
bool expression(std::string endToken);
bool expression();
bool statement();
bool function();
bool library();
private:
bool endOfExpr();
bool terminal(std::string token);
bool statement1();
bool expression1();
bool expression2();
bool expression3();
bool expression4();
//Variables
std::vector<std::string> tokens;
std::vector<std::string>::iterator it;
bool empty = true;
};
#endif // VALIDATOR_H
| true |
4a1f5030681e08e630e59804f100e4411c984f32 | C++ | Starwolf-001/CAB401 | /CAB401_MatrixMultiply_Win_Thread/main.cpp | UTF-8 | 2,667 | 3.03125 | 3 | [] | no_license | #include <stdlib.h>
// Added stdlib.h to allow for gcc to compile using Code::Blocks
#include <stdio.h>
#include <chrono>
#include <Windows.h>
#include <algorithm>
#define N 1000
#define ElementType double
#define NUM_THREADS 4
ElementType** AllocateMatrix(int n, int m, bool initialize)
{
ElementType **matrix = (ElementType**) malloc(sizeof(ElementType*) * n);
for (int i = 0; i < n; i++)
{
matrix[i] = (ElementType*)malloc(sizeof(ElementType) * m);
if (initialize)
for (int j = 0; j < m; j++)
matrix[i][j] = rand();
}
return matrix;
}
DWORD WINAPI maxtrixMultiplyThread(LPVOID param) {
int thread_id = *(int*)¶m;
int chunk_size = (N + (NUM_THREADS - 1)) / NUM_THREADS;
int start = thread_id * chunk_size;
int end = std::min(N, start + chunk_size);
printf("Hello World from thread %d\n", thread_id, chunk_size, start, end);
// Do the main matrix multiply calculation
//for (int i = 0; i < N; i++) {
//for (int j = 0; j < N; j++) {
//C[i][j] = 0;
//for (int k = 0; k < N; k++) {
//C[i][j] += A[i][k] * B[k][j];
//}
//}
//}
return 0;
}
int main(int argc, char* argv[])
{
// ToDo:
// 1) Try different ElementTypes e.g. int vs double vs float
// 2) Try Debug vs Release build
// 3) Try x86 vs x64 build
// 4) Try running on VMWare Virtual machine vs Local machine
// 5) Try different data structures for representing Matrices, e.g. 2D array of arrays vs flattened 1D array
// 6) Try different Matrix sizes e.g. 100x100, 1000x1000, 10000x10000
ElementType **A, **B, **C;
// seed the random number generator with a constant so that we get identical/repeatable results each time we run.
srand(42);
A = AllocateMatrix(N, N, true);
B = AllocateMatrix(N, N, true);
C = AllocateMatrix(N, N, false);
// time how long it takes ...
auto start_time = std::chrono::high_resolution_clock::now();
HANDLE threads[NUM_THREADS];
for(int i = 0; i < NUM_THREADS; i++) {
CreateThread(nullptr, // attributes
0, // stack size
maxtrixMultiplyThread, // start address
(LPVOID)i, //parameter
0, //creation flkags
nullptr);
}
WaitForMultipleObjects(NUM_THREADS, threads, TRUE, INFINITE);
auto finish_time = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = finish_time - start_time;
printf("Duration: %f seconds\n", duration.count());
// write the result matrix to a output file in binary format
// FILE *output_file = fopen("output.data", "wb");
// fwrite(C, sizeof(ElementType), N*N, output_file);
// fclose(output_file);
return 0;
}
| true |
c7555739f136b78894999b3b4a3ed3b3101cbb25 | C++ | rkBrunecz/projectJR | /src/Game/Battle/Ogre.cpp | UTF-8 | 1,600 | 2.859375 | 3 | [] | no_license | #include "Game\Battle\Ogre.h"
#include "Game\Game.h"
/*
constructor
Parameters:
window: The game window. Used to get the window size.
Creates the main characters sprite and sets other important information.
*/
Ogre::Ogre()
{
// Initialize the height and width of the battle sprite
battleHeight = 96;
battleWidth = 96;
// Load sprite map
battleSprite.setTexture(*Game::graphicManager->addTexture("Ogre_test.png"));
// Set up the battle sprite defualt sprite
battleSprite.setTextureRect(sf::IntRect(0, 0, 96, 96));
battleSprite.setOrigin(48, 48);
takingDamage = new Battle_Animation(3, 70, 70, 70, 1, 3, battleHeight, battleWidth, battleHeight, 0, true);
constantTakingDamage = new Battle_Animation(3, 100, 100, 100, 1, 3, battleHeight, battleWidth, battleHeight, 0, false);
standing = new Battle_Animation(3, 100, 300, 300, 1, 3, battleHeight, battleWidth, 0, 0, false);
animator.changeBattleAnimation(standing);
}
void Ogre::drawSprite(bool animate)
{
if (animate)
animator.animate(&battleSprite, &battleAniClock, isAttacking);
Game::graphicManager->addToDrawList(&battleSprite, false);
if (isTakingDamage && !animator.getCurrentAnimation()->isAnimating(&battleSprite))
{
isTakingDamage = false;
if (isAirBound)
animator.changeBattleAnimation(constantTakingDamage);
else
animator.changeBattleAnimation(standing);
}
}
short Ogre::performBattleAction(short numAttacksPerformed)
{
return 0;
}
bool Ogre::moveToPosition(float x, float y)
{
return false;
}
void Ogre::toggleCrushState()
{
if (isCrushable)
isCrushable = false;
else
isCrushable = true;
} | true |
09a0ebda5bde0697349a125900ba1ce6a558c49d | C++ | AnatolyDomrachev/aleksei_cpp | /socket/pthread.cpp | UTF-8 | 722 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <pthread.h>
void wait_thread (void);
void* thread_func (void*);
int main (int argc, char *argv[], char *envp[]) {
pthread_t thread;
if (pthread_create(&thread,NULL,thread_func,NULL)) return EXIT_FAILURE;
for (unsigned int i = 0; i < 20; i++) {
puts("a");
// wait_thread();
}
if (pthread_join(thread,NULL)) return EXIT_FAILURE;
return EXIT_SUCCESS;
}
void wait_thread (void) {
time_t start_time = time(NULL);
while(time(NULL) == start_time) {}
}
void* thread_func (void* vptr_args) {
for (unsigned int i = 0; i < 20; i++) {
fputs("b\n",stderr);
wait_thread();
}
return NULL;
}
| true |
bf468b717c9a8db8edd31ed8314323017f79a0e8 | C++ | cehughes/calvr_plugins | /calit2/CaveCADBeta/Geometry/CAVEGeodeReference.cpp | UTF-8 | 8,166 | 2.578125 | 3 | [] | no_license | /***************************************************************
* File Name: CAVEGeodeReference.cpp
*
* Description:
*
* Written by ZHANG Lelin on Nov 30, 2010
*
***************************************************************/
#include "CAVEGeodeReference.h"
using namespace std;
using namespace osg;
const int CAVEGeodeReferenceAxis::gHeadUnitSegments(2);
const float CAVEGeodeReferenceAxis::gBodyRadius(0.003f);
const float CAVEGeodeReferenceAxis::gArrowRadius(0.005f);
const float CAVEGeodeReferenceAxis::gArrowLength(0.05f);
const float CAVEGeodeReferencePlane::gSideLength(20.f);
// Constructor
CAVEGeodeReferenceAxis::CAVEGeodeReferenceAxis(): mType(POS_Z)
{
float len = (CAVEGeodeSnapWireframe::gSnappingUnitDist) * gHeadUnitSegments;
mCone = new Cone();
mConeDrawable = new ShapeDrawable(mCone);
mCone->setRadius(gArrowRadius);
mCone->setHeight(gArrowLength);
mCone->setCenter(Vec3(0, 0, len));
addDrawable(mConeDrawable);
mCylinder = new Cylinder();
mCylinderDrawable = new ShapeDrawable(mCylinder);
mCylinder->setRadius(gBodyRadius);
mCylinder->setHeight(len);
mCylinder->setCenter(Vec3(0, 0, len * 0.5));
addDrawable(mCylinderDrawable);
/* texture coordinates is associated with size of the geometry */
Material *material = new Material;
material->setDiffuse(Material::FRONT_AND_BACK, Vec4(0, 1, 0, 1));
material->setAlpha(Material::FRONT_AND_BACK, 1.0f);
StateSet *stateset = getOrCreateStateSet();
stateset->setAttributeAndModes(material, StateAttribute::OVERRIDE | StateAttribute::ON);
stateset->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON );
stateset->setRenderingHint(StateSet::TRANSPARENT_BIN);
}
/***************************************************************
* Function: setType()
***************************************************************/
void CAVEGeodeReferenceAxis::setType(const AxisType &typ, osg::MatrixTransform **matTrans)
{
if (typ == mType)
return;
mType = typ;
Quat rotation = Quat(0.f, Vec3(0, 0, 1));
switch (mType)
{
case POS_X: rotation = Quat(M_PI * 0.5, Vec3(0, 1, 0)); break;
case POS_Y: rotation = Quat(M_PI * 0.5, Vec3(-1, 0, 0)); break;
case POS_Z: rotation = Quat(0.f, Vec3(0, 0, 1)); break;
case NEG_X: rotation = Quat(M_PI * 0.5, Vec3(0, -1, 0)); break;
case NEG_Y: rotation = Quat(M_PI * 0.5, Vec3(1, 0, 0)); break;
case NEG_Z: rotation = Quat(M_PI, Vec3(0, 0, 1)); break;
default: break;
}
Matrixf rotMat;
rotMat.setRotate(rotation);
(*matTrans)->setMatrix(rotMat);
}
/***************************************************************
* Function: resize()
***************************************************************/
void CAVEGeodeReferenceAxis::resize(const float &length)
{
float len = length > 0 ? length: -length;
len += (CAVEGeodeSnapWireframe::gSnappingUnitDist) * gHeadUnitSegments;
mCone->setRadius(gArrowRadius);
mCone->setHeight(gArrowLength);
mCone->setCenter(Vec3(0, 0, len));
mCylinder->setRadius(gBodyRadius);
mCylinder->setHeight(len);
mCylinder->setCenter(Vec3(0, 0, len * 0.5));
mConeDrawable = new ShapeDrawable(mCone);
mCylinderDrawable = new ShapeDrawable(mCylinder);
setDrawable(0, mConeDrawable);
setDrawable(1, mCylinderDrawable);
}
// Constructor
CAVEGeodeReferencePlane::CAVEGeodeReferencePlane()
{
mVertexArray = new Vec3Array;
mNormalArray = new Vec3Array;
mTexcoordArray = new Vec2Array;
mGeometry = new Geometry;
/* vertex coordinates and normals */
mVertexArray->push_back(Vec3(-gSideLength, -gSideLength, 0)); mNormalArray->push_back(Vec3(0, 0, 1));
mVertexArray->push_back(Vec3( gSideLength, -gSideLength, 0)); mNormalArray->push_back(Vec3(0, 0, 1));
mVertexArray->push_back(Vec3( gSideLength, gSideLength, 0)); mNormalArray->push_back(Vec3(0, 0, 1));
mVertexArray->push_back(Vec3(-gSideLength, gSideLength, 0)); mNormalArray->push_back(Vec3(0, 0, 1));
/* texture coordinates */
float unitLength = SnapLevelController::getInitSnappingLength();
float texcoordMax = gSideLength / unitLength;
mTexcoordArray->push_back(Vec2(-texcoordMax, -texcoordMax));
mTexcoordArray->push_back(Vec2( texcoordMax, -texcoordMax));
mTexcoordArray->push_back(Vec2( texcoordMax, texcoordMax));
mTexcoordArray->push_back(Vec2(-texcoordMax, texcoordMax));
DrawElementsUInt* xyPlaneUp = new DrawElementsUInt(PrimitiveSet::POLYGON, 0);
xyPlaneUp->push_back(0);
xyPlaneUp->push_back(1);
xyPlaneUp->push_back(2);
xyPlaneUp->push_back(3);
xyPlaneUp->push_back(0);
mGeometry->addPrimitiveSet(xyPlaneUp);
mGeometry->setVertexArray(mVertexArray);
mGeometry->setNormalArray(mNormalArray);
mGeometry->setTexCoordArray(0, mTexcoordArray);
mGeometry->setNormalBinding(Geometry::BIND_PER_VERTEX);
addDrawable(mGeometry);
/* texture coordinates is associated with size of the geometry */
Material *material = new Material;
material->setDiffuse(Material::FRONT_AND_BACK, Vec4(1, 1, 1, 1));
material->setAlpha(Material::FRONT_AND_BACK, 1.f);
StateSet *stateset = getOrCreateStateSet();
stateset->setAttributeAndModes(material, StateAttribute::OVERRIDE | StateAttribute::ON);
stateset->setMode(GL_BLEND, StateAttribute::OVERRIDE | StateAttribute::ON );
stateset->setRenderingHint(StateSet::TRANSPARENT_BIN);
}
/***************************************************************
* Function: resize()
***************************************************************/
void CAVEGeodeReferencePlane::resize(const float lx, const float ly, const float unitsize)
{
if (mVertexArray->getType() == Array::Vec3ArrayType)
{
Vec3* vertexArrayDataPtr = (Vec3*) (mVertexArray->getDataPointer());
vertexArrayDataPtr[0] = Vec3(-lx, -ly, 0);
vertexArrayDataPtr[1] = Vec3( lx, -ly, 0);
vertexArrayDataPtr[2] = Vec3( lx, ly, 0);
vertexArrayDataPtr[3] = Vec3(-lx, ly, 0);
}
if (mTexcoordArray->getType() == Array::Vec2ArrayType)
{
Vec2* texcoordArrayDataPtr = (Vec2*) (mTexcoordArray->getDataPointer());
texcoordArrayDataPtr[0] = Vec2(-lx, -ly) / unitsize;
texcoordArrayDataPtr[1] = Vec2( lx, -ly) / unitsize;
texcoordArrayDataPtr[2] = Vec2( lx, ly) / unitsize;
texcoordArrayDataPtr[3] = Vec2(-lx, ly) / unitsize;
}
mGeometry->dirtyDisplayList();
mGeometry->dirtyBound();
}
/***************************************************************
* Function: setGridColor()
***************************************************************/
void CAVEGeodeReferencePlane::setGridColor(const GridColor &color)
{
StateSet *stateset = getOrCreateStateSet();
if (!stateset)
return;
Image* texImage;
if (color == RED)
texImage = osgDB::readImageFile(CAVEGeode::getDataDir() + "Textures/RedTile.PNG");
else if (color == GREEN)
texImage = osgDB::readImageFile(CAVEGeode::getDataDir() + "Textures/GreenTile.PNG");
else if (color == BLUE)
texImage = osgDB::readImageFile(CAVEGeode::getDataDir() + "Textures/BlueTile.PNG");
else
return;
Texture2D *texture = new Texture2D(texImage);
texture->setWrap(Texture::WRAP_S, Texture::REPEAT);
texture->setWrap(Texture::WRAP_T, Texture::REPEAT);
texture->setDataVariance(Object::DYNAMIC);
stateset->setTextureAttributeAndModes(0, texture, StateAttribute::ON);
}
/***************************************************************
* Function: setAlpha()
***************************************************************/
void CAVEGeodeReferencePlane::setAlpha(const float &alpha)
{
StateSet *stateset = getOrCreateStateSet();
if (!stateset)
return;
Material *material = dynamic_cast<Material*> (stateset->getAttribute(StateAttribute::MATERIAL));
if (!material)
return;
material->setAlpha(Material::FRONT_AND_BACK, alpha);
stateset->setAttributeAndModes(material, StateAttribute::ON);
}
| true |
b270fe6d96d496dfe41525340e13155fedf841df | C++ | mcarlen/libbiarc | /tools/tangent_indicatrix.cpp | UTF-8 | 1,794 | 3.109375 | 3 | [
"Apache-2.0"
] | permissive | /*!
\file tangent_indicatrix.cpp
\ingroup ToolsGroup
\brief Write the tangent indicatrix of a given (open or closed) curve to
a PKF file.
Tangents for the tangent indicatrix are interpolated, therefore strange
points like cusps would not be visible! The default is for an open curve,
for closed curves put the -closed switch.
*/
#ifndef DOXYGEN_SHOULD_SKIP_THIS
#include "../include/CurveBundle.h"
int main(int argc, char **argv) {
if (argc<3 || argc>5) {
cout << "Usage : "<<argv[0]
<< " [-closed] [-neg] <pkf in> <indicatrix pkf>\n";
exit(0);
}
int Neg = 0;
int Closed = 0;
if (argc>3)
for (int i=1;i<argc-2;i++) {
if (!strcmp(argv[i],"-closed")) Closed = 1;
if (!strcmp(argv[i],"-neg")) Neg = 1;
}
CurveBundle<Vector3> cb(argv[argc-2]);
if (Closed) cb.link();
CurveBundle<Vector3> indicatrix;
Vector3 tan_tmp, v1, v2;
cout << "Construct indicatrix " << flush;
for (int i=0;i<cb.curves();i++) {
Curve<Vector3> tmp;
vector<Biarc<Vector3> >::iterator current = cb[i].begin();
while (current!=cb[i].end()) {
tan_tmp = current->getTangent();
if (Neg) tan_tmp=-tan_tmp;
tmp.append(tan_tmp,Vector3(0,0,0));
current++;
}
tmp.computeTangents();
// Put the tangents in the sphere tangent space !
current = tmp.begin();
while (current!=tmp.end()) {
v1 = current->getPoint();
v2 = current->getTangent();
tan_tmp = v2 - v1.dot(v2)*v1;
tan_tmp.normalize();
current->setTangent(tan_tmp);
current++;
}
indicatrix.newCurve(tmp);
}
cout << "\t\t[OK]\n";
cout << "Write indicatrix to "<< argv[argc-1];
indicatrix.writePKF(argv[argc-1]);
cout << "\t[OK]\n";
return 0;
}
#endif // DOXYGEN_SHOULD_SKIP_THIS
| true |
bde448ceac2a34185287483cbc9619ff787d1f0e | C++ | Xzzzh/cpplearn | /20170425/20170425.src/templateSingleton.cc | UTF-8 | 1,570 | 3.53125 | 4 | [] | no_license | ///
/// @file templateSingleton.cc
/// @author lemon(haohb13@gmail.com)
/// @date 2017-04-25 10:52:36
///
#include <stdio.h>
#include <iostream>
using std::cout;
using std::endl;
class Point
{
public:
Point(int ix = 0, int iy = 0)
: _ix(ix)
, _iy(iy)
{
cout << "Point()" << endl;
}
~Point()
{
cout << "~Point()" << endl;
}
private:
int _ix;
int _iy;
};
template <typename T>
class Singleton
{
class AutoRelease
{
public:
AutoRelease()
{
cout << "AutoRelease()" << endl;
}
~AutoRelease()
{
if(_pInstance)
{
cout << "~AutoRelease()" << endl;
delete _pInstance;
}
}
};
public:
static T * getInstance()
{
if(_pInstance == NULL)
{
_auto;//模板生成时会根据该语句生成一个相应类型的_auto对象
_pInstance = new T;
}
return _pInstance;
}
private:
Singleton(){
cout << "Singleton()" << endl;
}
~Singleton(){
cout << "~Singleton()" << endl;
}
private:
static T * _pInstance;
static AutoRelease _auto;
};
template <typename T>
T * Singleton<T>::_pInstance = getInstance();
//1. 在类内部定义的自定义类型,如果使用模板则必须要使用typename
//告诉编译器这是一个自定义类型,而不是数据成员
//2. 模板的实例化是在实参传递时或者是在函数中要去使用某个对象
template <typename T>
typename Singleton<T>::AutoRelease Singleton<T>::_auto;
int main(void)
{
Point * pt1 = Singleton<Point>::getInstance();
Point * pt2 = Singleton<Point>::getInstance();
printf("pt1 = %p\n", pt1);
printf("pt2 = %p\n", pt2);
}
| true |
4a7ea3d5bb044be39ab5406839d1744c57ca4712 | C++ | SysuMadw/DataStructrue | /树/CreatetreeByPreandIn.cpp | UTF-8 | 1,673 | 3.296875 | 3 | [] | no_license | /*************************************************************************
> File Name: CreatetreeByPreandIn.cpp
> Author: 马定伟
> Mail: 1981409833@qq.com
> Created Time: 2019年01月26日 星期六 20时14分07秒
************************************************************************/
# include <iostream>
using namespace std;
class TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* createtree(vector<int>& pre, vector<int>& in){
return createtree(pre,0,pre.size()-1,in,0,in.size()-1);
}
TreeNode* createtree2(vector<int>& in, vector<int>& post){
return createtree2(in,0,in.size()-1,post,0,post.size()-1);
}
TreeNode* createtree2(vector<int>& in, int instart, int inend, vector<int>& post, int poststart, int postend){
if (instart > inend)
return NULL;
int rootVal = post[postend], i = 0;
for (i=instart; i<=inend; i++)
if (in[i] == rootVal)
break;
int leftnum = i - instart;
TreeNode* root = new TreeNode(rootVal);
root->left = createtree2(in,instart,i-1,post,poststart,poststart+leftnum-1);
root->right = createtree2(in,i+1,inend,post,poststart+leftnum,postend-1);
return root;
}
TreeNode* createtree(vector<int>& pre, int prestart, int preend, vector<int>& in, int instart, int inend){
if (prestart > preend)
return NULL;
int rootVal = pre[prestart], i = 0;
for (i=instart; i<=inend; i++)
if (in[i] == rootVal)
break;
int leftnum = i - instart;
TreeNode* root = new TreeNode(rootVal);
root->left = createtree(pre,prestart+1,prestart+leftnum,in,instart,i-1);
root->right = createtree(pre,prestart+leftnum+1,preend,in,i+1,inend);
return root;
}
| true |
eaf7a66d647086995682a33f9bf991016904a24e | C++ | rstratton/cs184-final-project | /BVH.h | UTF-8 | 1,164 | 2.53125 | 3 | [] | no_license | //
// BVH.h
// final
//
// Created by Kavan Sikand on 10/15/13.
// Copyright (c) 2013 Kavan Sikand. All rights reserved.
//
#ifndef __RayTracer__BVH__
#define __RayTracer__BVH__
#include "algebra3.h"
#include <iostream>
#include <vector>
class Ray;
//bounding volume hierarchy
#include "Shape.h"
class BoundingBox {
private:
vec3 minPos;
vec3 maxPos;
public:
BoundingBox() { BoundingBox(vec3(0,0,0),vec3(0,0,0));};
BoundingBox(vec3 min, vec3 max) : minPos(min), maxPos(max){
for(int i = 0; i < 3; i++) { //ensure ordering
if(minPos[i] > maxPos[i]) {
float temp = minPos[i];
minPos[i] = maxPos[i];
maxPos[i]= temp;
}
}
};
bool doesIntersect(Ray& p);
float center(int i) {
return (maxPos[i]-minPos[i])/ 2;
}
BoundingBox operator+(BoundingBox bb);
};
class BVHNode {
public:
BVHNode(std::vector <Shape*> shapes, int l);
BVHNode* leftChild;
BVHNode* rightChild;
bool isLeaf;
Shape* shape;
~BVHNode ();
bool doesIntersect(Ray& p) { return bb.doesIntersect(p); };
int level;
bool operator()(Shape* a, Shape* b);
protected:
BoundingBox bb;
};
#endif /* defined(__RayTracer__BVH__) */
| true |
f5e221097e98a2edc4ffa27982e3e4e42c1daa14 | C++ | tom1516/OpenGL-Tetris | /main.cpp | UTF-8 | 18,148 | 3.03125 | 3 | [] | no_license |
#include <GL/glut.h>
#include <math.h>
#include <sstream>
#include <stdio.h>
#include <iostream>
#include <string.h>
#include "Cube.h"
#include "Object.h"
using namespace std;
// size of grid side
#define N 20
#define M 4
// width and height of initial window
#define width 500
#define height 500
// window initial location x and y
#define locationx 50
#define locationy 50
GLfloat posx; // camera position on x
GLfloat posy; // camera position on y
GLfloat posz; // camera position on z
GLfloat lookx; // camera points on x
GLfloat looky; // camera points on y
GLfloat lookz; // camera points on z
GLfloat camerax; // camera positioned on x
GLfloat cameray; // camera positioned on y
GLfloat cameraz; // camera positioned on z
GLfloat angley; // camera angle around y axis
GLfloat anglexz; // camera angle around x and z axis
GLfloat zoom; // zoom factor
GLfloat dist; // distance from center (0, 0, 0)
bool objectFound = false; // object found to remove MxMxM where M >= 4
GLint scaleFound; // value of M
GLint x; // x location to start
GLint y; // y location to start
GLint z; // z location to start
GLint points; // user points
GLint speed; // game speed
Object *object = new Object(); // a falling object
GLint cubes[N][N][N]; // game cubes in the game for grid N = 20
// game state enum
enum GAME {
NOTHING,
START,
PAUSE,
END
};
GAME gameStatus; // initialize game state to nothing
// glut required functions
void initializeVariables();
void drawGame(void);
void grid(void);
void drawCubes();
void resizeGame(int w, int h);
void handleKeyboard(unsigned char key, int x, int y);
void handleKeyboardSpecial(int key, int x, int y);
void printPoints();
void run(int var);
void moveObjectDown();
void moveObjectLeft();
void moveObjectRight();
void moveObjectBack();
void moveObjectForward();
bool checkArrayOfCubes(GLint x, GLint y, GLint z, GLint scale);
void findLargeObject(GLint i1, GLint j1, GLint k1, GLint scale);
/**
* Start point of application.
*/
int main(int argc, char ** argv) {
initializeVariables();
// init glut
glutInit(&argc, argv);
// set window position
glutInitWindowPosition(locationx, locationy);
// set window size at 500 x 500
glutInitWindowSize(width, height);
// set display mode
// 1. Double buffer
// 2. RGB display
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
// create window with title
glutCreateWindow("Askisi 2 | 2013 - 2014");
// set black background for window
glClearColor(0.0,0.0,0.0,0.0);
// set this for correct depth projection
glEnable(GL_DEPTH_TEST);
// set callback functions
glutDisplayFunc(drawGame);
glutReshapeFunc(resizeGame);
glutKeyboardFunc(handleKeyboard);
glutSpecialFunc(handleKeyboardSpecial);
// enter glut main loop
glutMainLoop();
return 0;
}
/**
* Initialize variables.
*/
void initializeVariables() {
angley = 45; // 45 degrees on x axis
anglexz = 60; // 60 degrees on y axis
zoom = 1.0; // zoom factor
dist = 55; // distance from center
posx = sin(angley * M_PI / 180) * dist; // camera x location
posy = cos(anglexz * M_PI / 180) * dist; // camera x location
posz = cos(angley * M_PI / 180) * dist; // camera x location
lookx = 0.0; // where camera points on x
looky = 0.0; // where camera points on y
lookz = 0.0; // where camera points on y
camerax = 0.0; // how camera is positioned x
cameray = 1.0; // how camera is positioned y
cameraz = 0.0; // how camera is positioned z
points = 0; // initialize points to 0
gameStatus = NOTHING; // initialize game state to nothing
speed = 1000; // initialize game speed to 1 sec
// initialize array of cubes : arxikopoihsh tou plegmatow sintetagmenon oste na einai mideniko
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
for (int k=0; k<N; k++) {
cubes[i][j][k] = 0;
}
}
}
object->createObject(N);
}
// draw the game
// this function is set as the callback for glut glutDisplayFunc
void drawGame() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(40 * zoom, width / height, 1.0, 100.0f);
// calculate camera position
posx = sin(angley * M_PI / 180) * dist; // camera x location
posy = cos(anglexz * M_PI / 180) * dist; // camera x location
posz = cos(angley * M_PI / 180) * dist; // camera x location
// position the camera
gluLookAt(posx, posy, posz, lookx, looky, lookz, camerax, cameray, cameraz);
// create the game grid
grid();
// draw object
object->createCubes();
// draw cubes
drawCubes();
// print points
printPoints();
// swap buffers
glutSwapBuffers();
}
// what happens when window is resized
// this function is set as the callback for glut glutReshapeFunc
void resizeGame(int w, int h) { //kathe fora pou anoigo to parathiro na vlepo tin idia skini kai oxi autin pou afisa prin
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(40 * zoom, (GLfloat) w / (GLfloat) h, 1.0, 100.0f);
glMatrixMode(GL_MODELVIEW);
}
// this function creates the grid
// it draws the grid lines for each side of the grid
void grid() {
// white color
glColor3f(1.0, 1.0, 1.0);
// draw lines
glBegin(GL_LINES);
for (int i=0; i<N+1; i++) {
// x -> (0, N), y -> (i, i), z -> (0, 0)
glVertex3d(0, i, 0);
glVertex3d(N, i, 0);
// x -> (0, N), y -> (0, 0), z -> (i, i)
glVertex3d(0, 0, i);
glVertex3d(N, 0, i);
// x -> (i, i), y -> (0, N), z -> (0, 0)
glVertex3d(i, 0, 0);
glVertex3d(i, N, 0);
// x -> (0, 0), y -> (0, N), z -> (i, i)
glVertex3d(0, 0, i);
glVertex3d(0, N, i);
// x -> (i, i), y -> (0, 0), z -> (0, N)
glVertex3d(i, 0, 0);
glVertex3d(i, 0, N);
// x -> (0, 0), y -> (i, i), z -> (0, N)
glVertex3d(0, i, 0);
glVertex3d(0, i, N);
}
// stop drawing lines
glEnd();
}
// this function will draw all cubes in the game
void drawCubes() {
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
for (int k=0; k<N; k++) {
if (cubes[i][j][k] == 1) {
// set color to blue
glColor3f(0.1, 0.5, 0.9);
// push current matrix
glPushMatrix();
// translate location
glTranslatef(i+0.5, j+0.5, k+0.5);
// draw the cube
glutSolidCube(1);
// draw cube souround
glBegin(GL_LINES);
glLineWidth(5.0f);
glColor3f(1.0f, 0.0, 0.0);
if ((i-1 > 0 && cubes[i-1][j][k] != 1) && (j-1 > 0 && cubes[i][j-1][k] != 1)) {
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(-0.5, -0.5, 0.5);
}
if ((i+1 < N && cubes[i+1][j][k] != 1) && (j-1 > 0 && cubes[i][j-1][k] != 1)) {
glVertex3f(0.5, -0.5, -0.5);
glVertex3f(0.5, -0.5, 0.5);
}
if ((k-1 > 0 && cubes[i][j][k-1] != 1) && (j-1 > 0 && cubes[i][j-1][k] != 1)) {
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(0.5, -0.5, -0.5);
}
if ((k+1 < N && cubes[i][j][k+1] != 1) && (j-1 > 0 && cubes[i][j-1][k] != 1)) {
glVertex3f(-0.5, -0.5, 0.5);
glVertex3f(0.5, -0.5, 0.5);
}
if ((i-1 > 0 && cubes[i-1][j][k] != 1) && (j+1 < N && cubes[i][j+1][k] != 1)) {
glVertex3f(-0.5, 0.5, -0.5);
glVertex3f(-0.5, 0.5, 0.5);
}
if ((i+1 < N && cubes[i+1][j][k] != 1) && (j+1 < N && cubes[i][j+1][k] != 1)) {
glVertex3f(0.5, 0.5, -0.5);
glVertex3f(0.5, 0.5, 0.5);
}
if ((k-1 > 0 && cubes[i][j][k-1] != 1) && (j+1 < N && cubes[i][j+1][k] != 1)) {
glVertex3f(-0.5, 0.5, -0.5);
glVertex3f(0.5, 0.5, -0.5);
}
if ((k+1 < N && cubes[i][j][k+1] != 1) && (j+1 < N && cubes[i][j+1][k] != 1)) {
glVertex3f(-0.5, 0.5, 0.5);
glVertex3f(0.5, 0.5, 0.5);
}
if ((k-1 > 0 && cubes[i][j][k-1] != 1) && (i-1 > 0 && cubes[i-1][j][k] != 1)) {
glVertex3f(-0.5, -0.5, -0.5);
glVertex3f(-0.5, 0.5, -0.5);
}
if ((k+1 < N && cubes[i][j][k+1] != 1) && (i-1 > 0 && cubes[i-1][j][k] != 1)) {
glVertex3f(-0.5, -0.5, 0.5);
glVertex3f(-0.5, 0.5, 0.5);
}
if ((k+1 < N && cubes[i][j][k+1] != 1) && (i+1 < N && cubes[i+1][j][k] != 1)) {
glVertex3f(0.5, -0.5, 0.5);
glVertex3f(0.5, 0.5, 0.5);
}
if ((k-1 > 0 && cubes[i][j][k-1] != 1) && (i+1 < N && cubes[i+1][j][k] != 1)) {
glVertex3f(0.5, -0.5, -0.5);
glVertex3f(0.5, 0.5, -0.5);
}
glLineWidth(1.0f);
glEnd();
// pop previous matrix
glPopMatrix();
}
}
}
}
}
void handleKeyboard(unsigned char key, int x, int y) {
// zoom out
if (key == 'q') {
zoom += 0.01;
}
// zoom in
if (key == 'w') {
zoom -= 0.01;
}
// rotate camera left
if (key == 'a') {
angley--;
}
// rotate camera right
if (key == 's') {
angley++;
}
// rotate camera up
if (key == 'z') {
anglexz--;
}
// rotate camera down
if (key == 'x') {
anglexz++;
}
// start or pause the game
if (key == 'p') {
if (gameStatus == NOTHING) {
gameStatus = START;
run(0); // start game loop
} else if (gameStatus == START) {
gameStatus = PAUSE;
} else if (gameStatus == PAUSE) {
gameStatus = START;
run(0); // start game loop
}
}
// increase game speed by 2
if (key == 'c') {
speed *= 2;
}
// decrease game speed by 2
if (key == 'v') {
speed /= 2;
}
glutPostRedisplay();
}
void handleKeyboardSpecial(int key, int x, int y) {
// move object left
if (key == GLUT_KEY_LEFT) {
moveObjectLeft();
}
// move object right
if (key == GLUT_KEY_RIGHT) {
moveObjectRight();
}
// move object back
if (key == GLUT_KEY_UP) {
moveObjectBack();
}
// move object forward
if (key == GLUT_KEY_DOWN) {
moveObjectForward();
}
glutPostRedisplay();
}
// this function run a game loop
void run(int var) {
switch (gameStatus) {
case START:
glutTimerFunc(speed, run, 0);
// move object down
moveObjectDown();
break;
case PAUSE:
break;
case NOTHING:
break;
case END:
return;
}
glutPostRedisplay();
}
// will move object down
void moveObjectDown() {
bool move = true;
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
GLint x = object->cubes[i]->x;
GLint y = object->cubes[i]->y;
GLint z = object->cubes[i]->z;
if (y - 1 < 0 || cubes[x][y-1][z] != 0) {
// game over situation
if (y == N - 1) {
gameStatus = END;
return;
}
move = false;
break;
}
}
}
if (move) {
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
object->cubes[i]->y--;
}
}
} else {
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
GLint x = object->cubes[i]->x;
GLint y = object->cubes[i]->y;
GLint z = object->cubes[i]->z;
cubes[x][y][z] = 1; // otan ftasei to object katw kai enopoieithei me ta ipoloipa kivakia tote svinw tis grammes
}
}
// calculate points
points += 10 * object->cubesNumber;
// remove objects MxMxM with M >= 4
findLargeObject(0, 0, 0, M);
if (objectFound) {
for (int i=x; i<x+scaleFound; i++) {
for (int j=y; j<y+scaleFound; j++) {
for (int k=z; k<z+scaleFound; k++) {
cubes[i][j][k] = 0;
}
}
}
points += powl(scaleFound, 3);
objectFound = false;
}
// create a new object to fall
object->createObject(N);
}
}
// will move object left
void moveObjectLeft() {
bool move = true;
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
GLint x = object->cubes[i]->x;
GLint y = object->cubes[i]->y;
GLint z = object->cubes[i]->z;
if (x - 1 < 0 || cubes[x-1][y][z] != 0) {
move = false;
break;
}
}
}
if (move) {
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
object->cubes[i]->x--;
}
}
}
}
// will move object right
void moveObjectRight() {
bool move = true;
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
GLint x = object->cubes[i]->x;
GLint y = object->cubes[i]->y;
GLint z = object->cubes[i]->z;
if (x + 1 >= N || cubes[x+1][y][z] != 0) {
move = false;
break;
}
}
}
if (move) {
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
object->cubes[i]->x++;
}
}
}
}
// will move object back
void moveObjectBack() {
bool move = true;
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
GLint x = object->cubes[i]->x;
GLint y = object->cubes[i]->y;
GLint z = object->cubes[i]->z;
if (z - 1 < 0 || cubes[x][y][z-1] != 0) {
move = false;
break;
}
}
}
if (move) {
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
object->cubes[i]->z--;
}
}
}
}
// will move object forward
void moveObjectForward() {
bool move = true;
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
GLint x = object->cubes[i]->x;
GLint y = object->cubes[i]->y;
GLint z = object->cubes[i]->z;
if (z + 1 >= N || cubes[x][y][z+1] != 0) {
move = false;
break;
}
}
}
if (move) {
for (int i=0; i<4; i++) {
if (object->cubes[i] != NULL) {
object->cubes[i]->z++;
}
}
}
}
// check specific array in the cubes
// if one with MxMxM is found return true
bool checkArrayOfCubes(GLint x, GLint y, GLint z, GLint scale) {
for (int i=x; i<x+scale; i++) {
for (int j=y; j<y+scale; j++) {
for (int k=z; k<z+scale; k++) {
if (cubes[i][j][k] != 1) {
return false;
}
}
}
}
return true;
}
// find large object in the cubes 3-dimension array
void findLargeObject(GLint i1, GLint j1, GLint k1, GLint scale) {
for (int i=i1; i<N-scale; i++) {
for (int j=j1; j<N-scale; j++) {
for (int k=k1; k<N-scale; k++) {
if (checkArrayOfCubes(i, j, k, scale)) {
objectFound = true;
x = i;
y = j;
z = k;
scaleFound = scale;
findLargeObject(i, j, k, scale+1);
}
}
}
}
}
// print user points on top left of the window
void printPoints() {
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluOrtho2D(0.0, glutGet(GLUT_WINDOW_WIDTH), 0.0, glutGet(GLUT_WINDOW_HEIGHT));
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
stringstream s;
if (gameStatus == END) {
s << "Game Over - ";
}
s << points;
char message[20] = "";
char * final_message = strcat(message,s.str().c_str());
glColor3f(0.2, 0.5, 0.7);
glRasterPos2d(10, 480);
for (int i=0; i<strlen(final_message); i++) {
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18, final_message[i]);
}
glMatrixMode(GL_MODELVIEW);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
}
| true |
5d187e948ed5cf71bb01bba64bc3b8731fc3caff | C++ | Gfast2/esp32-snippets | /cpp_utils/JSON.h | UTF-8 | 1,569 | 2.625 | 3 | [
"Apache-2.0"
] | permissive | /*
* JSON.h
*
* Created on: May 23, 2017
* Author: kolban
*/
#ifndef COMPONENTS_CPP_UTILS_JSON_H_
#define COMPONENTS_CPP_UTILS_JSON_H_
#include <cJSON.h>
#include <string>
// Forward declarations
class JsonObject;
class JsonArray;
class JSON {
public:
static JsonObject createObject();
static JsonArray createArray();
static void deleteObject(JsonObject jsonObject);
static void deleteArray(JsonArray jsonArray);
static JsonObject parseObject(std::string text);
static JsonArray parseArray(std::string text);
}; // JSON
class JsonArray {
public:
JsonArray(cJSON *node);
int getInt(int item);
JsonObject getObject(int item);
std::string getString(int item);
bool getBoolean(int item);
double getDouble(int item);
void addBoolean(bool value);
void addDouble(double value);
void addInt(int value);
void addObject(JsonObject value);
void addString(std::string value);
cJSON *m_node;
}; // JsonArray
class JsonObject {
public:
JsonObject(cJSON *node);
int getInt(std::string name);
JsonObject getObject(std::string name);
std::string getString(std::string name);
bool getBoolean(std::string name);
double getDouble(std::string name);
void setArray(std::string name, JsonArray array);
void setBoolean(std::string name, bool value);
void setDouble(std::string name, double value);
void setInt(std::string name, int value);
void setObject(std::string name, JsonObject value);
void setString(std::string name, std::string value);
std::string toString();
cJSON *m_node;
}; // JsonObject
#endif /* COMPONENTS_CPP_UTILS_JSON_H_ */
| true |
0f8ca52b8787a5999e8ba6a541d79909ba4c6dce | C++ | EthanSteinberg/SuperGunBros | /src/rendering/renderlist.cpp | UTF-8 | 11,726 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "renderlist.h"
#include <glad/glad.h>
#include <cmath>
#include <iostream>
RenderList::RenderList(const char* filename): file(filename), wrapper(file) {
metadata.ParseStream(wrapper);
std::array<std::array<float, 3>, 3> mat = {{
{{1, 0, 0}},
{{0, 1, 0}},
{{0, 0, 1}}
}};
state.transform = mat;
state.z_offset = 0;
}
Rectangle RenderList::get_image_dimensions(const std::string &name) const {
if (!metadata.HasMember(name.c_str())) {
std::cerr<<"Could not find image \"" << name << "\"" << std::endl;
exit(-1);
}
auto& info = metadata[name.c_str()];
return {0, 0, info["sizex"].GetDouble(), info["sizey"].GetDouble()};
}
void RenderList::add_outline(const std::string &name, const Rectangle& rect, double line_width) {
add_line(name, rect.x - rect.width/2, rect.y - rect.height/2 + line_width / 2, rect.x + rect.width/2, rect.y - rect.height/2 + line_width/2, line_width);
add_line(name, rect.x - rect.width/2, rect.y + rect.height/2 - line_width / 2, rect.x + rect.width/2, rect.y + rect.height/2 - line_width/2, line_width);
add_line(name, rect.x - rect.width/2 + line_width / 2, rect.y - rect.height/2, rect.x - rect.width/2 + line_width / 2, rect.y + rect.height/2, line_width);
add_line(name, rect.x + rect.width/2 - line_width / 2, rect.y - rect.height/2, rect.x + rect.width/2 - line_width / 2, rect.y + rect.height/2, line_width);
}
void RenderList::add_rect(const std::string &name, const Rectangle& rect) {
add_image(name, rect.x - rect.width/2, rect.y - rect.height/2, rect.width, rect.height);
}
void RenderList::add_line(const std::string &name, float x_1, float y_1, float x_2, float y_2, double line_width) {
double dist = sqrt((x_2 - x_1) * (x_2 - x_1) + (y_2 - y_1) * (y_2 - y_1));
double angle = atan2(y_2 - y_1, x_2 - x_1);
translate(x_1, y_1);
rotate(angle);
add_image(name, 0, -line_width/2, dist, line_width);
rotate(-angle);
translate(-x_1, -y_1);
}
void RenderList::add_number(float x, float y, int num) {
std::string num_text = std::to_string(num);
for (const char c : num_text) {
std::string blah = "0";
blah[0] = c;
auto& info = metadata[blah.c_str()];
add_image(blah, x, y - info["sizey"].GetDouble());
x += (double) info["sizex"].GetDouble() + 4;
}
}
void RenderList::add_image(const std::string &name, float x, float y, float width, float height) {
if (!metadata.HasMember(name.c_str())) {
std::cerr<<"Could not find image \"" << name << "\"" << std::endl;
exit(-1);
}
auto& info = metadata[name.c_str()];
if (width == -1) {
width = info["sizex"].GetDouble();
}
if (height == -1) {
height = info["sizey"].GetDouble();
}
add_image_core(name, x, y, width, height);
}
void RenderList::add_scaled_image(const std::string &name, float x, float y, float scale, bool centered) {
if (!metadata.HasMember(name.c_str())) {
std::cerr<<"Could not find image \"" << name << "\"" << std::endl;
exit(-1);
}
auto& info = metadata[name.c_str()];
float width = info["sizex"].GetDouble();
width = width * scale;
float height = info["sizey"].GetDouble();
height = height * scale;
if(centered){
x = x - width/2;
y = y - height/2;
}
add_image_core(name, x, y, width, height);
}
void RenderList::add_text(const std::string& text, float x, float y) {
std::string lowercase = "abcdefghijklmnopqrstuvwxyz";
std::string uppercase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int advance = 11;
const int height = 20;
for (unsigned int i = 0; i < text.size(); i++) {
char current_char = text[i];
if (current_char == ' ') {
// Don't draw anything for a space
} else if (lowercase.find(current_char) != std::string::npos) {
int offset = lowercase.find(current_char);
add_image_core("lowercase", x, y, advance, height, offset * advance, 0, advance, height);
} else if (uppercase.find(current_char) != std::string::npos) {
int offset = uppercase.find(current_char);
add_image_core("uppercase", x, y, advance, height, offset * advance, 0, advance, height);
} else {
std::cout<<"Could not find image for character " << current_char << std::endl;
}
x += advance;
}
}
void RenderList::add_red_numbers(const std::string& color, int num, float center_x, float center_y) {
std::string num_text = std::to_string(num);
std::string numbers = "0123456789";
const int advance = 24;
const int height = 33;
const int visual_advance = 21;
float y = center_y - height / 2.0;
float x = center_x - visual_advance * num_text.size() / 2.0;
for (unsigned int i = 0; i < num_text.size(); i++) {
char current_char = num_text[i];
int offset = numbers.find(current_char);
// add_image("green", x, y, visual_advance, height);
add_image_core(color + "-numbers", x - 3, y, advance, height, offset * advance, 0, advance, height);
x += visual_advance;
}
}
void RenderList::add_image_core(const std::string &name, float x, float y, float width, float height) {
if (!metadata.HasMember(name.c_str())) {
std::cerr<<"Could not find image \"" << name << "\"" << std::endl;
exit(-1);
}
auto& info = metadata[name.c_str()];
add_image_core(name, x, y, width, height, 0, 0, info["sizex"].GetInt(), info["sizey"].GetInt());
}
void RenderList::add_image_core(const std::string &name, float x, float y, float width, float height, float subx, float suby, float subwidth, float subheight) {
if (!metadata.HasMember(name.c_str())) {
std::cerr<<"Could not find image \"" << name << "\"" << std::endl;
exit(-1);
}
std::vector<float>* vec = &data;
if (state.z_offset == 100) {
vec = &top_data;
}
auto& info = metadata[name.c_str()];
int px = info["x"].GetInt() + subx;
int psizex = subwidth;
int py = info["y"].GetInt() + suby;
int psizey = subheight;
add_transformed_point(*vec, x, y + height);
vec->push_back(state.z_offset);
vec->push_back(px);
vec->push_back(py + psizey);
vec->push_back(px);
vec->push_back(py);
vec->push_back(psizex);
vec->push_back(psizey);
add_transformed_point(*vec, x + width, y);
vec->push_back(state.z_offset);
vec->push_back(px + psizex);
vec->push_back(py);
vec->push_back(px);
vec->push_back(py);
vec->push_back(psizex);
vec->push_back(psizey);
add_transformed_point(*vec, x + width, y + height);
vec->push_back(state.z_offset);
vec->push_back(px + psizex);
vec->push_back(py + psizey);
vec->push_back(px);
vec->push_back(py);
vec->push_back(psizex);
vec->push_back(psizey);
add_transformed_point(*vec, x, y + height);
vec->push_back(state.z_offset);
vec->push_back(px);
vec->push_back(py + psizey);
vec->push_back(px);
vec->push_back(py);
vec->push_back(psizex);
vec->push_back(psizey);
add_transformed_point(*vec, x + width, y);
vec->push_back(state.z_offset);
vec->push_back(px + psizex);
vec->push_back(py);
vec->push_back(px);
vec->push_back(py);
vec->push_back(psizex);
vec->push_back(psizey);
add_transformed_point(*vec, x, y);
vec->push_back(state.z_offset);
vec->push_back(px);
vec->push_back(py);
vec->push_back(px);
vec->push_back(py);
vec->push_back(psizex);
vec->push_back(psizey);
}
void RenderList::add_flame(float center_x, float center_y, float r, float g, float b, float a) {
double radius = 8;
double height = 20;
double width = 20;
double x = center_x - width / 2;
double y = center_y - height / 2;
add_transformed_point(flame_data, x, y + height);
flame_data.push_back(state.z_offset);
flame_data.push_back(r);
flame_data.push_back(g);
flame_data.push_back(b);
flame_data.push_back(a);
add_transformed_point(flame_data, center_x, center_y);
flame_data.push_back(radius * state.transform[0][0]);
add_transformed_point(flame_data, x + width, y);
flame_data.push_back(state.z_offset);
flame_data.push_back(r);
flame_data.push_back(g);
flame_data.push_back(b);
flame_data.push_back(a);
add_transformed_point(flame_data, center_x, center_y);
flame_data.push_back(radius * state.transform[0][0]);
add_transformed_point(flame_data, x + width, y + height);
flame_data.push_back(state.z_offset);
flame_data.push_back(r);
flame_data.push_back(g);
flame_data.push_back(b);
flame_data.push_back(a);
add_transformed_point(flame_data, center_x, center_y);
flame_data.push_back(radius * state.transform[0][0]);
add_transformed_point(flame_data, x, y + height);
flame_data.push_back(state.z_offset);
flame_data.push_back(r);
flame_data.push_back(g);
flame_data.push_back(b);
flame_data.push_back(a);
add_transformed_point(flame_data, center_x, center_y);
flame_data.push_back(radius * state.transform[0][0]);
add_transformed_point(flame_data, x + width, y);
flame_data.push_back(state.z_offset);
flame_data.push_back(r);
flame_data.push_back(g);
flame_data.push_back(b);
flame_data.push_back(a);
add_transformed_point(flame_data, center_x, center_y);
flame_data.push_back(radius * state.transform[0][0]);
add_transformed_point(flame_data, x, y);
flame_data.push_back(state.z_offset);
flame_data.push_back(r);
flame_data.push_back(g);
flame_data.push_back(b);
flame_data.push_back(a);
add_transformed_point(flame_data, center_x, center_y);
flame_data.push_back(radius * state.transform[0][0]);
}
void RenderList::draw() {
glBufferData(GL_ARRAY_BUFFER, 4 * data.size(), data.data(), GL_STREAM_DRAW);
glDrawArrays(GL_TRIANGLES, 0, data.size() / 9);
}
void RenderList::draw_flame() {
glBufferData(GL_ARRAY_BUFFER, 4 * flame_data.size(), flame_data.data(), GL_STREAM_DRAW);
glDrawArrays(GL_TRIANGLES, 0, flame_data.size() / 10);
}
void RenderList::draw_top() {
glBufferData(GL_ARRAY_BUFFER, 4 * top_data.size(), top_data.data(), GL_STREAM_DRAW);
glDrawArrays(GL_TRIANGLES, 0, top_data.size() / 9);
}
void RenderList::add_transformed_point(std::vector<float>& vec, float x, float y) {
float finalX = state.transform[0][0] * x + state.transform[0][1] * y + state.transform[0][2];
float finalY = state.transform[1][0] * x + state.transform[1][1] * y + state.transform[1][2];
vec.push_back(finalX);
vec.push_back(finalY);
}
void RenderList::mmultiply(float other[][3]) {
std::array<std::array<float, 3>, 3> result = {};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
result[i][j] += state.transform[i][k] * other[k][j];
}
}
}
state.transform = result;
}
void RenderList::translate(float x, float y) {
float mat[3][3] = {
{1, 0, x},
{0, 1, y},
{0, 0, 1}
};
mmultiply(mat);
}
void RenderList::rotate(double radians) {
float mat[3][3] = {
{(float) cos(radians), (float) -sin(radians), 0},
{(float) sin(radians), (float) cos(radians), 0},
{0, 0, 1}
};
mmultiply(mat);
}
void RenderList::scale(float scaleX, float scaleY) {
float mat[3][3] = {
{scaleX, 0, 0},
{0, scaleY, 0},
{0, 0, 1}
};
mmultiply(mat);
}
void RenderList::push() {
prev_states.push(state);
}
void RenderList::pop() {
state = prev_states.top();
prev_states.pop();
}
void RenderList::set_z(float z) {
state.z_offset = z;
} | true |
cadca6502143d91461c3697cd741aed4be487911 | C++ | bharathajay51/mrm-2020 | /bharath/joystick-differential-drive/joystic_differetial_v3.0/joystic_differetial_v3.0.ino | UTF-8 | 2,831 | 3.03125 | 3 | [] | no_license | const byte pot_Y = A1; //Analog Jostick Y axis
const byte pot_X = A0; //Analog Jostick X axis
const byte left_forward = 3; //(left motor forward)
const byte left_reverse = 4; //(left motor reverse)
const byte right_forward = 5; //(right motor forward)
const byte right_reverse = 6; //(right motor reverse)
const byte left_enable = 9;
const byte right_enable = 10;
int throttle, steering = 0;
int left_motor, left_output = 0;
int right_motor, right_output = 0;
int deadZone = 100;
void setup()
{
Serial.begin(9600);
pinMode(left_forward, OUTPUT);
pinMode(left_reverse, OUTPUT);
pinMode(right_forward, OUTPUT);
pinMode(right_reverse, OUTPUT);
pinMode(left_enable, OUTPUT);
pinMode(right_enable, OUTPUT);
}
void loop()
{
throttle = (512 - (analogRead(pot_Y))) / 2;
steering = (512 - (analogRead(pot_X))) / 2;
left_motor = throttle + steering;
right_motor = throttle - steering;
mixer(left_motor, right_motor);
//*************** LEFT MOTOR ***************//
if (abs(left_output) > deadZone)
{
if (left_output > 0)
{
// left motor is going forward.
digitalWrite(left_reverse, 0);
digitalWrite(left_forward, 1);
analogWrite(left_enable, abs(left_output));
}
else
{
// left motor is going backwards.
digitalWrite(left_forward, 0);
digitalWrite(left_reverse, 1);
analogWrite(left_enable, abs(left_output));
}
}
else
{
//left motor is in deadzone(stop the motor)
digitalWrite(left_forward, 0);
digitalWrite(left_reverse, 0);
}
//**************** RIGHT MOTOR *****************//
if (abs(right_output) > deadZone)
{
if (right_output > 0)
{
// right motor forward
digitalWrite(right_reverse, 0);
digitalWrite(right_forward, 1);
analogWrite(right_enable, abs(right_output));
}
else
{
// right motor reverse
digitalWrite(right_forward, 0);
digitalWrite(right_reverse, 1);
analogWrite(right_enable, abs(right_output));
}
}
else
{
// right motor in dead zone (stop)
analogWrite(right_forward, 0);
analogWrite(right_reverse, 0);
}
if(abs(left_output)<deadZone) left_output = 0;
if(abs(right_output)<deadZone) right_output = 0;
Serial.println("");
Serial.println();
Serial.print("L_Final:");
Serial.print(left_output);
Serial.print(", R_Final:");
Serial.print(right_output);
delay(10);
}
void mixer (int left_init , int right_init)
{
float L_scale, R_scale, max_scale;
L_scale = left_init / 255.0;
L_scale = abs(L_scale);
R_scale = right_init / 255.0;
R_scale = abs(R_scale);
max_scale = max(L_scale, R_scale);
max_scale = max(1, max_scale);
left_output = constrain(left_init / max_scale, -255, 255);
right_output = constrain(right_init / max_scale, -255, 255);
}
| true |
5be7d62f24a875a17af09914a6bd0ccd8090aeac | C++ | KarpenkoDenis/tetris | /Field.cpp | WINDOWS-1251 | 1,254 | 3.03125 | 3 | [] | no_license | #include "Field.h"
Field::Field(unsigned size_h, unsigned size_w)
{
this->size_h = size_h;
this->size_w = size_w;
//
for (size_t i = 0; i < size_h; i++)
{
base_field.push_back(std::vector<short>());
for (size_t j = 0; j < size_w; j++)
{
base_field[i].push_back(0);
}
}
}
unsigned Field::get_size_w() const
{
return size_w;
}
unsigned Field::get_size_h() const
{
return size_h;
}
std::vector<std::vector<short>> Field::get_base_field() const
{
return base_field;
}
void Field::add_point(unsigned i, unsigned j)
{
base_field[i][j] = 1;
}
void Field::check_line()
{
bool is_collapce;
int i = 0;
for(auto iter = base_field.begin(); iter != base_field.end() ; iter++ , i++)
{
is_collapce = true;
for (size_t j = 0; j < size_w; j++)
{
if (base_field[i][j] != 1)
{
is_collapce = false;
break;
}
}
if (is_collapce)
{
base_field.erase(iter);
base_field.insert(base_field.begin(), std::vector<short>());
for (size_t j = 0; j < size_w; j++)
{
base_field[0].push_back(0);
}
return;
}
}
}
bool Field::block_exist(unsigned i, unsigned j)
{
if (i >= size_w || j >= size_h)
{
return false;
}
return true;
}
| true |
272de8e06a0bcaad37f2eed3a13d5f6f1986e77d | C++ | Rushi-710/CipherSchools_Assignment | /Assignment1/Question-5.cpp | UTF-8 | 711 | 4.09375 | 4 | [] | no_license | //Toggle the case of every character of a string
#include<bits/stdc++.h>
using namespace std;
int main() {
string str1;
cout <<"\n Please Enter any String to Toggle : ";
cin >> str1;
int len = str1.length();
for (int i = 0; i < len; i++) {
//If the character is upper-cased
if(str1[i] >= 'A' && str1[i] <= 'Z') {
str1[i] = 'a' + (str1 [i] - 'A');
}
//If the character is lower-cased
else if(str1[i] >= 'a' && str1[i] <= 'z') {
str1[i] = 'A' + (str1[i] - 'a');
}
}
//Printing the output after we toggled the string
cout << "\n The Given String after Toggling Case of all Characters = ";
cout << str1 << endl;
return 0;
} | true |
adb89db5353aeb427bc3abd825e6b6dc317793da | C++ | denis-gubar/Leetcode | /all/0071. Simplify Path.cpp | UTF-8 | 927 | 2.8125 | 3 | [] | no_license | class Solution {
public:
string simplifyPath( string path ) {
string result = "/";
path += "/";
int n = path.size();
int i = 0;
while (path.find( '/', i + 1 ) != string::npos)
{
int j = path.find( '/', i + 1 );
string s = path.substr( i + 1, j - i - 1 );
if (s == string() || s == ".")
{
}
else if (s == "..")
{
int k = result.size() - 1;
while (k >= 0 && result[k] != '/')
--k;
if (k > 0)
result = result.substr( 0, k );
else
result = "/";
}
else
{
if (result.back() != '/')
result += "/";
result += s;
}
i = j;
}
return result;
}
}; | true |
dfb605ebec9e3fd92c8940dca7250fa6ffdeb703 | C++ | ondrej008/Accelerator | /obstacles/moving.cpp | UTF-8 | 3,322 | 2.90625 | 3 | [] | no_license | #include "moving.hpp"
MovingObstacle::MovingObstacle(glm::vec3 pos, float speed, bool vertical)
: m_cuboid1(2.0, 2.0, 0.2), m_cuboid2(2.0, 2.0, 0.2), m_speed(speed), m_vertical(vertical)
{
glm::vec3 offset(1.25, 0.0, 0.0);
if(m_vertical)
{
offset = glm::vec3(0.0, 1.25, 0.0);
}
m_model1 = glm::translate(glm::mat4(1.0), pos + offset);
m_model2 = glm::translate(glm::mat4(1.0), pos - offset);
glGenBuffers(1, &m_VBO1);
glGenVertexArrays(1, &m_VAO1);
glBindVertexArray(m_VAO1);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO1);
glBufferData(GL_ARRAY_BUFFER, m_cuboid1.m_vertices.size() * sizeof(float), m_cuboid1.m_vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glGenBuffers(1, &m_VBO2);
glGenVertexArrays(1, &m_VAO2);
glBindVertexArray(m_VAO2);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO2);
glBufferData(GL_ARRAY_BUFFER, m_cuboid2.m_vertices.size() * sizeof(float), m_cuboid2.m_vertices.data(), GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
}
MovingObstacle::~MovingObstacle()
{
glDeleteBuffers(1, &m_VBO1);
glDeleteBuffers(1, &m_VBO2);
glDeleteVertexArrays(1, &m_VAO1);
glDeleteVertexArrays(1, &m_VAO2);
}
bool MovingObstacle::playerCollide(glm::vec3 pos, float radius)
{
Cuboid player(radius, radius, radius);
glm::vec3 scale;
glm::qua<float> orientation;
glm::vec3 translation;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(m_model1, scale, orientation, translation, skew, perspective);
glm::vec3 playerOffset1 = translation - pos;
glm::decompose(m_model2, scale, orientation, translation, skew, perspective);
glm::vec3 playerOffset2 = translation - pos;
return m_cuboid1.collides(player, playerOffset1) || m_cuboid2.collides(player, playerOffset2);
}
bool MovingObstacle::update(double elapsed, glm::vec3 pos)
{
glm::vec3 scale;
glm::qua<float> orientation;
glm::vec3 translation1;
glm::vec3 skew;
glm::vec4 perspective;
glm::decompose(m_model1, scale, orientation, translation1, skew, perspective);
if(translation1.z - pos.z > 1.0)
{
return true;
}
glm::vec3 translation2;
glm::decompose(m_model2, scale, orientation, translation2, skew, perspective);
if(!m_vertical)
{
if(translation1.x > 2.0 || translation2.x < -2.0)
{
m_speed *= -1.0;
}
m_model1 = glm::translate(glm::mat4(1.0), glm::vec3(m_speed * elapsed, 0.0, 0.0)) * m_model1;
m_model2 = glm::translate(glm::mat4(1.0), glm::vec3(m_speed * elapsed, 0.0, 0.0)) * m_model2;
}
else
{
if(translation1.y > 2.0 || translation2.y < -2.0)
{
m_speed *= -1.0;
}
m_model1 = glm::translate(glm::mat4(1.0), glm::vec3(0.0, m_speed * elapsed, 0.0)) * m_model1;
m_model2 = glm::translate(glm::mat4(1.0), glm::vec3(0.0, m_speed * elapsed, 0.0)) * m_model2;
}
return false;
}
void MovingObstacle::render(GLint modelL, GLint colorL)
{
glUniformMatrix4fv(modelL, 1, GL_FALSE, glm::value_ptr(m_model1));
glUniform4fv(colorL, 1, glm::value_ptr(glm::vec4(0.7, 0.0, 0.0, 1.0)));
glBindVertexArray(m_VAO1);
glDrawArrays(GL_TRIANGLES, 0, m_cuboid1.m_vertices.size());
glUniformMatrix4fv(modelL, 1, GL_FALSE, glm::value_ptr(m_model2));
glBindVertexArray(m_VAO2);
glDrawArrays(GL_TRIANGLES, 0, m_cuboid2.m_vertices.size());
} | true |
9d6aafb14ca407d9dee576ab07e69fc748e6b033 | C++ | MichalTurek/algorithms | /a-game-with-numbers-spoj.cpp | UTF-8 | 286 | 2.953125 | 3 | [] | no_license | #include <iostream>
using std::cout;
using std::cin;
#include <string>
using std::string;
int main()
{
string number;
cin >> number;
char last_digit = number[number.length() - 1];
if (last_digit != '0')
{
cout << "1\n";
cout << last_digit << "\n";
}
else cout << "2\n";
}
| true |
e564dc546bdba532eaa951421436799ffedecad5 | C++ | ingramali/hub | /unit_test/context_manager_test.hpp | UTF-8 | 1,248 | 2.703125 | 3 | [] | no_license | #ifndef __CONTEXT_MANAGER_TESTS_HPP
#define __CONTEXT_MANAGER_TESTS_HPP
#include <gtest/gtest.h>
#include "context_manager.hpp"
#include "system.hpp"
using namespace network;
class ContextManagerTest : public testing::Test
{
protected:
ContextManager * _sut = nullptr;
public:
void SetUp() override
{
_sut = new ContextManager();
}
void TearDown() override
{
delete _sut;
_sut = nullptr;
}
};
TEST_F(ContextManagerTest, Instance)
{
EXPECT_TRUE(_sut != nullptr);
}
TEST_F(ContextManagerTest, CreateContext)
{
EXPECT_EQ(0u, _sut->GetActiveCountextCount());
auto context1 = _sut->CreateContext();
EXPECT_EQ(1u, _sut->GetActiveCountextCount());
auto context2 = _sut->CreateContext();
EXPECT_EQ(2u, _sut->GetActiveCountextCount());
_sut->DeleteContext(context1);
EXPECT_EQ(1u, _sut->GetActiveCountextCount());
_sut->DeleteContext(context2);
EXPECT_EQ(0u, _sut->GetActiveCountextCount());
}
TEST_F(ContextManagerTest, ContextContent)
{
auto context = _sut->CreateContext();
EXPECT_EQ(account::AccessLevel::Level::NotLogged, context->GetUser().GetAccessLevel().GetLevel());
}
#endif
| true |
f8b76d23889656031f5a37fdc3e5ac14a23b3551 | C++ | manikmayur/BatterySim | /src/algorithms/interpolate.cpp | UTF-8 | 670 | 3.203125 | 3 | [] | no_license | /*
* interpolate.cpp
*
* Created on: 08.02.2019
* Author: Manik
*/
#include "algorithms/algorithms.h"
double interpolate(double x, std::vector<double> xList, std::vector<double> fList)
{
double c;
// Assumes that "table" is sorted by .first
// Check if x is out of bound
if (x > xList.back()) {
c = fList.back();
return c;
}
if (x < xList[0]) {
c = fList[0];
return c;
}
size_t i = std::distance(xList.begin(), std::lower_bound(xList.begin(), xList.end(), x));
c = fList[i-1] + (fList[i] - fList[i-1]) * (x - xList[i-1])/(xList[i]- xList[i-1]);
return c;
}
| true |
df7c0c93c235fc778eb22599e24b2e5ec3250e16 | C++ | Simon-Fuhaoyuan/LeetCode-100DAY-Challenge | /magicDict/main.cpp | UTF-8 | 1,506 | 3.703125 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class MagicDictionary {
private:
vector<string> dict;
public:
/** Initialize your data structure here. */
MagicDictionary() {
dict.clear();
}
/** Build a dictionary through a list of words */
void buildDict(vector<string> dict) {
this->dict = dict;
}
/** Returns if there is any word in the trie that equals to the given word after modifying exactly one character */
bool search(string word) {
int num = dict.size();
int diff = 0;
for (int i = 0; i < num; ++i)
{
if (word.length() != dict[i].length())
continue;
diff = 0;
for (int j = 0; j < word.length(); ++j)
{
if (word[j] != dict[i][j])
{
diff++;
if (diff > 1) break;
}
}
if (diff == 1) return true;
}
return false;
}
};
/**
* Your MagicDictionary object will be instantiated and called as such:
* MagicDictionary* obj = new MagicDictionary();
* obj->buildDict(dict);
* bool param_2 = obj->search(word);
*/
int main()
{
MagicDictionary *obj = new MagicDictionary();
vector<string> input;
input.push_back("hello");
input.push_back("leetcode");
obj->buildDict(input);
cout << obj->search("helll") << endl;
cout << obj->search("leetcoded") << endl;
} | true |
43fbbf0d5108ad31456b00fade332633d501db5d | C++ | xiaoquanjie/global_server_fk | /fk/slience/socket/linuxsock_init.ipp | UTF-8 | 728 | 2.515625 | 3 | [] | no_license |
class LinuxSockBase
{
protected:
struct data
{
int _init_cnt;
};
};
template<s_int32_t Version=1>
class LinuxSockInit : public LinuxSockBase
{
public:
M_SOCKET_DECL LinuxSockInit();
M_SOCKET_DECL ~LinuxSockInit();
protected:
static data _data;
};
template<s_int32_t Version>
LinuxSockBase::data LinuxSockInit<Version>::_data;
template<s_int32_t Version>
M_SOCKET_DECL LinuxSockInit<Version>::LinuxSockInit()
{
if (::__sync_add_and_fetch(&_data._init_cnt,1)==1){
signal(SIGPIPE, SIG_IGN);
}
}
template<s_int32_t Version>
M_SOCKET_DECL LinuxSockInit<Version>::~LinuxSockInit()
{
if (::__sync_sub_and_fetch(&_data._init_cnt, 1) == 0){
}
}
static const LinuxSockInit<>& gLinuxSockInstance = LinuxSockInit<>();
| true |
f4f4175e89ffaaa8ec3c6e755d242573301d2986 | C++ | nshaver/liambot | /liambot_4.ino | UTF-8 | 13,147 | 2.6875 | 3 | [] | no_license | /* This example shows how to smoothly control a single servo on a
Maestro servo controller using the PololuMaestro library. It
assumes you have an RC hobby servo connected on channel 0 of your
Maestro, and that you have already used the Maestro Control
Center software to verify that the servo is powered correctly and
moves when you command it to from the Maestro Control Center
software.
Before using this example, you should go to the Serial Settings
tab in the Maestro Control Center and apply these settings:
* Serial mode: UART, fixed baud rate
* Baud rate: 9600
* CRC disabled
Be sure to click "Apply Settings" after making any changes.
This example also assumes you have connected your Arduino to your
Maestro appropriately. If you have not done so, please see
https://github.com/pololu/maestro-arduino for more details on how
to make the connection between your Arduino and your Maestro. */
#include <PololuMaestro.h>
/* On boards with a hardware serial port available for use, use
that port to communicate with the Maestro. For other boards,
create a SoftwareSerial object using pin 10 to receive (RX) and
pin 11 to transmit (TX). */
#ifdef SERIAL_PORT_HARDWARE_OPEN
#define maestroSerial SERIAL_PORT_HARDWARE_OPEN
#else
#include <SoftwareSerial.h>
SoftwareSerial maestroSerial(10, 11);
#endif
/* Next, create a Maestro object using the serial port.
Uncomment one of MicroMaestro or MiniMaestro below depending
on which one you have. */
MicroMaestro maestro(maestroSerial);
//MiniMaestro maestro(maestroSerial);
// leg adjustments variables
int thighSpeed=0;
int thighAccel=160;
int calfSpeed=0;
int calfAccel=120;
int rightCalfOffset=1500;
int leftCalfOffset=0;
// range=4000-7800
int thighMin=4000;
int thighMax=7800;
int thighStand=800;
int calfMin=4000;
int calfMax=7800;
int calfStand=1000;
bool leftOn=true;
bool rightOn=true;
int lastLeftCalf, lastRightCalf, lastLeftThigh, lastRightThigh, standRightCalf, standLeftCalf, standRightThigh, standLeftThigh=0;
// nunchuck init
#include <Wire.h>
#include <ArduinoNunchuk.h>
ArduinoNunchuk nunchuk = ArduinoNunchuk();
int thisX, thisY, thisZ=0;
int zeroX=519;
int zeroZ=380;
float drift=0.04;
int moveSpeed=20;
bool walking=false;
char lastStep='l';
unsigned long nextStepTime=0;
int stepMillis=1000;
void setup()
{
// Set the serial baud rate.
maestroSerial.begin(9600);
// nunchuck setup
nunchuk.init();
Serial.begin(9600);
// start with legs in standing position
if (rightOn){
maestro.setSpeed(0, thighSpeed);
maestro.setAcceleration(0,thighAccel);
maestro.setSpeed(2, calfSpeed);
maestro.setAcceleration(2,calfAccel);
lastRightThigh=4000+thighStand;
maestro.setTarget(0, lastRightThigh);
lastRightCalf=4000+calfStand+rightCalfOffset;
maestro.setTarget(2, lastRightCalf);
standRightThigh=lastRightThigh;
standRightCalf=lastRightCalf;
}
if (leftOn){
maestro.setSpeed(1, thighSpeed);
maestro.setAcceleration(1,thighAccel);
maestro.setSpeed(3, calfSpeed);
maestro.setAcceleration(3,calfAccel);
lastLeftThigh=7800-thighStand;
maestro.setTarget(1, lastLeftThigh);
lastLeftCalf=4000+calfStand+leftCalfOffset;
maestro.setTarget(3, lastLeftCalf);
standLeftThigh=lastLeftThigh;
standLeftCalf=lastLeftCalf;
}
delay(2000);
}
void loop()
{
nunchuk.update();
// joystick X and Y:
// nunchuk.analogX
// nunchuk.analogY
// buttons
// nunchuk.zButton
// nunchuk.cButton
thisX=nunchuk.accelX;
thisY=nunchuk.accelY;
thisZ=nunchuk.accelZ;
if (nunchuk.cButton==1){
// turn on/off walking
if (walking){
walking=false;
} else {
walking=true;
nextStepTime=stepMillis+millis();
}
}
if (walking){
// take a quick step every two seconds
if (millis()>nextStepTime){
// time to take another step
maestro.setSpeed(1, 0);
maestro.setAcceleration(1, 0);
maestro.setSpeed(3, 0);
maestro.setAcceleration(3, 0);
maestro.setSpeed(0, 0);
maestro.setAcceleration(0, 0);
maestro.setSpeed(2, 0);
maestro.setAcceleration(2, 0);
if (lastStep=='l'){
lastStep='r';
//maestro.setTarget(0, lastRightThigh-200);
maestro.setTarget(2, lastRightCalf-300);
delay(300);
maestro.setAcceleration(2, 100);
//maestro.setTarget(0, lastRightThigh);
maestro.setTarget(2, lastRightCalf);
} else {
lastStep='l';
//maestro.setTarget(1, lastLeftThigh+200);
maestro.setTarget(3, lastLeftCalf+300);
delay(300);
maestro.setAcceleration(3, 100);
//maestro.setTarget(1, lastLeftThigh);
maestro.setTarget(3, lastLeftCalf);
}
//maestro.setTarget(3, calfMax);
//delay(300);
//maestro.setTarget(3, calfMax);
// return left thigh and calf to previous position
nextStepTime=stepMillis+millis();
}
}
if (true){
Serial.print("x=");
Serial.print(thisX);
Serial.print(" y=");
Serial.print(thisY);
Serial.print(" z=");
Serial.print(thisZ);
Serial.println("");
}
/* setSpeed takes channel number you want to limit and the
speed limit in units of (1/4 microseconds)/(10 milliseconds).
A speed of 0 makes the speed unlimited, so that setting the
target will immediately affect the position. Note that the
actual speed at which your servo moves is also limited by the
design of the servo itself, the supply voltage, and mechanical
loads. */
//maestro.setSpeed(0, 0);
/* setAcceleration takes channel number you want to limit and
the acceleration limit value from 0 to 255 in units of (1/4
microseconds)/(10 milliseconds) / (80 milliseconds).
A value of 0 corresponds to no acceleration limit. An
acceleration limit causes the speed of a servo to slowly ramp
up until it reaches the maximum speed, then to ramp down again
as the position approaches the target, resulting in relatively
smooth motion from one point to another. */
//maestro.setAcceleration(0, 0);
int mode=3;
if (mode==0){
// move thighs
// Configure channel 0 to move slowly and smoothly.
maestro.setSpeed(0, 50);
maestro.setAcceleration(0,127);
maestro.setSpeed(1, 50);
maestro.setAcceleration(1,127);
// Set the target of channel 0 to 1500 us, and wait 2 seconds.
maestro.setTarget(0, 4000);
maestro.setTarget(1, 4000);
delay(1000);
maestro.setTarget(0, 8000);
maestro.setTarget(1, 8000);
delay(1000);
//maestro.setTarget(0, 6000);
//maestro.setTarget(1, 6000);
//delay(2000);
}
if (mode==1){
// move calfs
// Configure channel 0 to move slowly and smoothly.
maestro.setSpeed(2, 50);
maestro.setAcceleration(0,127);
maestro.setSpeed(3, 50);
maestro.setAcceleration(1,127);
// Set the target of channel 0 to 1500 us, and wait 2 seconds.
maestro.setTarget(2, 4000);
maestro.setTarget(3, 4000);
delay(1000);
maestro.setTarget(2, 8000);
maestro.setTarget(3, 8000);
delay(1000);
//maestro.setTarget(0, 6000);
//maestro.setTarget(1, 6000);
//delay(2000);
}
if (mode==2){
// move thighs and calfs
if (rightOn){
maestro.setSpeed(0, thighSpeed);
maestro.setAcceleration(0,thighAccel);
maestro.setSpeed(2, calfSpeed);
maestro.setAcceleration(2,calfAccel);
maestro.setTarget(2, calfMin);
}
if (leftOn){
maestro.setSpeed(1, thighSpeed);
maestro.setAcceleration(1,thighAccel);
maestro.setSpeed(3, calfSpeed);
maestro.setAcceleration(3,calfAccel);
maestro.setTarget(3, calfMin);
}
delay(300);
if (rightOn){
maestro.setTarget(0, thighMin);
}
if (leftOn){
maestro.setTarget(1, thighMin);
}
delay(500);
if (rightOn){
maestro.setTarget(2, calfMax+rightCalfOffset);
}
if (leftOn){
maestro.setTarget(3, calfMax+leftCalfOffset);
}
//maestro.setTarget(1, 4000);
//maestro.setTarget(3, 4000);
delay(500);
if (rightOn){
maestro.setTarget(0, thighMax);
maestro.setTarget(2, calfMax+rightCalfOffset);
}
if (leftOn){
maestro.setTarget(1, thighMax);
maestro.setTarget(3, calfMax+leftCalfOffset);
}
//maestro.setTarget(1, 8000);
//maestro.setTarget(3, 8000);
delay(500);
//maestro.setTarget(0, 6000);
//maestro.setTarget(1, 6000);
//delay(2000);
}
if (mode==3){
// stand still
if (false && thisX<(zeroX*(1.0-drift))){
// lower left leg
lastLeftThigh=lastLeftThigh+50;
lastLeftCalf=lastLeftCalf+50;
if (lastLeftThigh>thighMax) lastLeftThigh=thighMax;
if (lastLeftCalf>calfMax) lastLeftCalf=calfMax;
maestro.setTarget(1, lastLeftThigh);
maestro.setTarget(3, lastLeftCalf);
// raise right leg
lastRightThigh=lastRightThigh+50;
lastRightCalf=lastRightCalf+50;
if (lastRightThigh>thighMax) lastRightThigh=thighMax;
if (lastRightCalf>calfMax) lastRightCalf=calfMax;
maestro.setTarget(0, lastRightThigh);
maestro.setTarget(2, lastRightCalf);
} else if(false && thisX>zeroX*(1.0+drift)){
// raise left leg
lastLeftThigh=lastLeftThigh-50;
lastLeftCalf=lastLeftCalf-50;
if (lastLeftThigh<thighMin) lastLeftThigh=thighMin;
if (lastLeftCalf<calfMin) lastLeftCalf=calfMin;
maestro.setTarget(1, lastLeftThigh);
maestro.setTarget(3, lastLeftCalf);
// lower right leg
lastRightThigh=lastRightThigh-50;
lastRightCalf=lastRightCalf-50;
if (lastRightThigh<thighMin) lastRightThigh=thighMin;
if (lastRightCalf<calfMin) lastRightCalf=calfMin;
maestro.setTarget(0, lastRightThigh);
maestro.setTarget(2, lastRightCalf);
} else if(thisZ>zeroZ*(1.0+drift)){
// leaning backward
int thisMoveSpeed=moveSpeed;
if (thisZ>zeroZ*(1.0+(drift*3))){
// REALLY leaning backward
//thisMoveSpeed=moveSpeed*3;
}
maestro.setSpeed(0, thighSpeed);
maestro.setSpeed(1, thighSpeed);
maestro.setAcceleration(0, thighAccel);
maestro.setAcceleration(1, thighAccel);
maestro.setSpeed(2, calfSpeed);
maestro.setSpeed(3, calfSpeed);
maestro.setAcceleration(2, calfAccel);
maestro.setAcceleration(3, calfAccel);
// lower right thigh
lastRightThigh=lastRightThigh+thisMoveSpeed;
if (lastRightThigh>thighMax) lastRightThigh=thighMax;
// lower left thigh
lastLeftThigh=lastLeftThigh-thisMoveSpeed;
if (lastLeftThigh<thighMin) lastLeftThigh=thighMin;
// raise right calf
lastRightCalf=lastRightCalf-thisMoveSpeed;
if (lastRightCalf<calfMin) lastRightCalf=calfMin;
// raise left calf
lastLeftCalf=lastLeftCalf+thisMoveSpeed;
if (lastLeftCalf>calfMax) lastLeftCalf=calfMax;
maestro.setTarget(0, lastRightThigh);
maestro.setTarget(1, lastLeftThigh);
maestro.setTarget(2, lastRightCalf);
maestro.setTarget(3, lastLeftCalf);
} else if (thisZ<(zeroZ*(1.0-drift))){
// leaning forward
int thisMoveSpeed=moveSpeed;
if (thisZ<zeroZ*(1.0+(drift*3))){
// REALLY leaning
//thisMoveSpeed=moveSpeed*3;
}
maestro.setSpeed(0, thighSpeed);
maestro.setSpeed(1, thighSpeed);
maestro.setAcceleration(0, thighAccel);
maestro.setAcceleration(1, thighAccel);
maestro.setSpeed(2, calfSpeed);
maestro.setSpeed(3, calfSpeed);
maestro.setAcceleration(2, calfAccel);
maestro.setAcceleration(3, calfAccel);
// raise right thigh
lastRightThigh=lastRightThigh-thisMoveSpeed;
if (lastRightThigh<thighMin) lastRightThigh=thighMin;
// raise left thigh
lastLeftThigh=lastLeftThigh+thisMoveSpeed;
if (lastLeftThigh>thighMax) lastLeftThigh=thighMax;
// lower right calf
lastRightCalf=lastRightCalf+thisMoveSpeed;
if (lastRightCalf>calfMax) lastRightCalf=calfMax;
// lower left calf
lastLeftCalf=lastLeftCalf-thisMoveSpeed;
if (lastLeftCalf<calfMin) lastLeftCalf=calfMin;
maestro.setTarget(0, lastRightThigh);
maestro.setTarget(1, lastLeftThigh);
maestro.setTarget(2, lastRightCalf);
maestro.setTarget(3, lastLeftCalf);
} else {
if (false) {
// level, try to return to stand position
if (lastRightThigh>standRightThigh) lastRightThigh=lastRightThigh-25;
if (lastLeftThigh>standLeftThigh) lastLeftThigh=lastLeftThigh-25;
if (lastRightCalf>standRightCalf) lastRightCalf=lastRightCalf-25;
if (lastLeftCalf>standLeftCalf) lastLeftCalf=lastLeftCalf-25;
maestro.setTarget(0, lastRightThigh);
maestro.setTarget(1, lastLeftThigh);
maestro.setTarget(2, lastRightCalf);
maestro.setTarget(3, lastRightCalf);
}
}
}
}
| true |
153c33cb2e1b583975f903b0723518005e863560 | C++ | tuananhlai/dont_touch_the_spike | /Don't Touch The Spike/src/MainControl.cpp | UTF-8 | 4,383 | 2.8125 | 3 | [] | no_license | #include "MainControl.h"
using namespace std;
int MainControl::WIDTH;
int MainControl::HEIGHT;
Bird* bird = NULL;
Background* background = NULL;
Spike* spike = NULL;
MainControl::MainControl()
{
window = NULL;
renderer = NULL;
end_loop = false;
status = 0;
hit = false;
score = 0;
}
MainControl::~MainControl()
{
background->free();
bird->free();
spike->free();
}
void MainControl::logSDLError(ostream& os, const string &msg, bool fatal)
{
os << msg << " Error: " << SDL_GetError() << endl;
if (fatal)
{
SDL_Quit();
exit(1);
}
}
void MainControl::initializeSDL(string window_title, const int&x, const int& y, const int& width, const int& height, const int& screen_option)
{
WIDTH = width;
HEIGHT = height;
if(SDL_Init(SDL_INIT_EVERYTHING) != 0)
{
logSDLError(cout, "SDL_Init", true);
}
window = SDL_CreateWindow(window_title.c_str(), x, y, width, height, SDL_WINDOW_SHOWN);
if(window == NULL)
{
logSDLError(cout, "CreateWindow", true);
}
renderer = SDL_CreateRenderer(this -> window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if(renderer == NULL)
{
logSDLError(cout, "CreateRenderer", true);
}
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
logSDLError(cout, "SDL_Init_image", true);
}
bird = new Bird();
background = new Background();
spike = new Spike();
loadFromFile();
}
void MainControl::loadFromFile()
{
background->loadFromFile("assets/sprites/background-day.png", renderer);
bird->loadFromFile("assets/sprites/yellowbird-midflap.png", renderer);
spike->loadFromFile("assets/sprites/spike.png", renderer);
}
void MainControl::handleEvent()
{
for( int i = 0; i < spike->getQuality(); i++) //detect collision
{
if( status == 0)
{
if((bird->getY()+24 >= spike->getY(i))
&&(bird->getY() <= spike->getY(i)+10)
&&(bird->getX()+34 >= spike->getX(i))
&&(bird->getX() <= spike->getX(i)+30)) //bird hit left/right spikes
end_loop = true;
}
else
{
if((bird->getY() <= spike->getY(i)+10)
&&(bird->getY()+24 >= spike->getY(i))
&&(bird->getX() <= spike->getX(i)+30)
&&(bird->getX()+30 >= spike->getX(i)))
end_loop = true;
}
}
if(bird->getY() == 0 || bird->getY() == SCREEN_HEIGHT-24) //bird hit top/bottom spikes
{
end_loop = true;
}
bird->handleEvent(event, status);
SDL_PollEvent(&event);
switch(event.type)
{
case SDL_QUIT:
{
end_loop = true;
break;
}
case SDL_KEYUP:
{
if(event.key.keysym.sym==SDLK_ESCAPE)
{
end_loop=true;
}
break;
}
default:
{
break;
}
}
}
void MainControl::update()
{
bird->update(status, hit, score);
spike->update(status, hit, score);
}
void MainControl::render()
{
if(!end_loop)
{
//set background color
SDL_SetRenderDrawColor(renderer,0,0,0,255);
SDL_RenderClear(renderer);
SDL_SetRenderDrawColor(renderer,255,0,0,255);
background->render(0,0,SCREEN_WIDTH,SCREEN_HEIGHT, renderer);
bird->render(bird->getX(),bird->getY(), bird->getWidth(), bird->getHeight(), renderer, status);
for (int i = 0; i< spike->getQuality(); i++)
{
spike->render(spike->getX(i), spike->getY(i), spike->getWidth(), spike->getHeight(), renderer, status);
}
SDL_RenderPresent(renderer);
}
}
void MainControl::close()
{
delete bird;
delete background;
delete spike;
SDL_DestroyWindow(this->window);
SDL_DestroyRenderer(this->renderer);
SDL_Quit();
}
SDL_Window* MainControl::getWindow() const
{
return this->window;
}
SDL_Renderer* MainControl::getRenderer()const
{
return this->renderer;
}
bool MainControl::isEndLoop() const
{
return this->end_loop;
}
void MainControl::setEndLoop(const bool& end_loop)
{
this->end_loop=end_loop;
}
int MainControl::getWidth()
{
return WIDTH;
}
int MainControl::getHeight()
{
return HEIGHT;
}
int MainControl::getScore()
{
return score;
}
| true |
494a3c47a03a169b9c08a6069495a87edb005c5c | C++ | issackpgit/Parallel-Processing | /Openmp Parallel Prefix/Parallel Prefix parallel/a0.hpp | UTF-8 | 1,808 | 2.640625 | 3 | [] | no_license | /* ISSAC KOSHY
* PANICKER
* issackos
*/
#ifndef A0_HPP
#define A0_HPP
template <typename T, typename Op>
void omp_scan(int n, T* in, T* out, Op op) {
int *temp;
// int *x;// = (int*) malloc ((n+1)*sizeof(int));
int numofthreads, work;
int i, tid, last;
int start ,end;
// x = const_cast<int*>(in);
#pragma omp parallel shared(in, out, temp, numofthreads, work, n) private(i, tid, start, end)
{
#pragma omp single
{
numofthreads = omp_get_num_threads();
work = n / numofthreads + 1;
}
tid = omp_get_thread_num();
start = work*tid;
end =op(start,work);
if (end>n)
end=n;
for(i=start+1;i<end;i++){
in[i] = op(in[i],in[i - 1]);
}
out[tid] = in[i-1];
// printf("Firstout[%d]=%d\n",tid,out[tid]);
// x[tid]=out[tid];
#pragma omp barrier
for(i = 1; i < numofthreads; i=2*i) {
// printf("i is %d \n",i);
// printf("Out[%d]=%d,Out[%d]=%d\n",tid,out[tid],tid-1,out[tid-1]);
if(tid >= i)
temp[tid] = op(out[tid], out[tid-i]);
// printf("temp[%d] is %d when i is %d and Out[%d]=%d,Out[%d]=%d\n",tid,temp[tid],i,tid,out[tid],tid-1,out[tid-1]);
#pragma omp barrier
// for(i=0;i<4;i++)
// {
// out[i+1]=temp[i+1];
// }
std::copy_n(temp+1, numofthreads-1, out+1);
// printf("Secondout[%d]=%d\n",tid,out[tid]);
}
if(end>n)
end=n;
for(i = start; i < end; i++)
in[i] += out[tid]-in[end-1];
}
for(i = 0; i < n; i++){
// printf("%d\n", in[i]);
out[i]=in[i];
// printf(" %d ",out[i]);
}
} // omp_scan
#endif // A0_HPP
| true |
c14dedebf2bd20a64c7494bba7e0b955edd81261 | C++ | JavongChang/aphid | /btree/Array.h | UTF-8 | 1,266 | 2.828125 | 3 | [] | no_license | #pragma once
#include "Entity.h"
#include "Sequence.h"
namespace aphid {
namespace sdb {
template<typename KeyType, typename ValueType>
class Array : public Sequence<KeyType>
{
public:
Array(Entity * parent = NULL) : Sequence<KeyType>(parent) {}
virtual ~Array() {}
void insert(const KeyType & x, ValueType * v) {
Pair<KeyType, Entity> * p = Sequence<KeyType>::insert(x);
if(!p->index) p->index = new Single<ValueType>;
Single<ValueType> * d = static_cast<Single<ValueType> *>(p->index);
d->setData(v);
}
ValueType * value() const {
Single<ValueType> * s = static_cast<Single<ValueType> *>(Sequence<KeyType>::currentIndex());
return s->data();
}
ValueType * find(const KeyType & k, MatchFunction::Condition mf = MatchFunction::mExact, KeyType * extraKey = NULL) const
{
Pair<Entity *, Entity> g = Sequence<KeyType>::findEntity(k, mf, extraKey);
if(!g.index) return NULL;
Single<ValueType> * s = static_cast<Single<ValueType> *>(g.index);
return s->data();
}
virtual void clear()
{
Sequence<KeyType>::begin();
while(!Sequence<KeyType>::end()) {
ValueType * p = value();
if(p) delete p;
Sequence<KeyType>::next();
}
Sequence<KeyType>::clear();
}
private:
};
} //end namespace sdb
}
| true |
245f76070ec943f1ed85d666d57791ff077543cd | C++ | vij-duggirala/ds_algos | /graph/min_capacity_cut.cpp | UTF-8 | 1,493 | 2.625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
bool bfs(vector<vector<int>> rg,int s,int t,int parent[]){
vector<bool> v(rg.size(),false);
queue<int> q;
v[s]=true;
q.push(s);
int k,i;
while(!q.empty()){
k=q.front();
q.pop();
for(i=0;i<rg.size();i++){
if(!v[i] && rg[k][i]>0){
v[i]=true;
parent[i]=k;
q.push(i);
}
}
}
return v[t];
}
void dfs(vector<vector<int>> rg,bool vis[],int s){
vis[s]=true;
for(int i=0;i<rg.size();i++){
if(!vis[i] && rg[s][i]>0)
dfs(rg,vis,i);
}
}
int main(){
int n,i,j,k,x,s,t;
cout<<"enter no of vertices\n";
cin>>n;
cout<<"enter source vertex\n";
cin>>s;
cout<<"enter sink vertex\n";
cin>>t;
vector<vector<int>> g,rg;
g.resize(n);
rg.resize(n);
cout<<"enter flow network in the form of adjacency matrix\n";
for(i=0;i<n;i++){
for(j=0;j<n;j++){
cin>>x;
g[i].push_back(x);
rg[i].push_back(x);
}
}
int max_flow=0;
int parent[n];
parent[s]=-1;
while(bfs(rg,s,t,parent)){
int pathflow=INT_MAX;
for(i=t;i!=s;i=parent[i]){
k=parent[i];
if(rg[k][i]<pathflow)
pathflow=rg[k][i];
}
for(i=t;i!=s;i=parent[i]){
k=parent[i];
rg[k][i] -=pathflow;
rg[i][k] +=pathflow;
}
max_flow+=pathflow;
}
bool vis[n];
for(i=0;i<n;i++)
vis[i]=false;
dfs(rg,vis,s);
cout<<"minimum capacity cut is "<<max_flow<<endl;
cout<<"cut set edges are\n";
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(vis[i] && !vis[j] && g[i][j]>0)
cout<<i<<" --- "<<j<<endl;
}
}
} | true |
b05984259c45f248307dae12b87a6b89a38b3cd3 | C++ | yoniescobar/CursoProgramacionC-4PC | /Primera Unidad/incremento.cpp | UTF-8 | 202 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <conio.h>
using namespace std;
int main(){
int a=0;
cout<<"El valor de a es: "<<a;
a--; // a = a - 1
cout<<"\nEl valor de a es: "<<a;
return 0;
getch();
}
| true |
68f66a91477dfffb9534b110e88cfd65007fb525 | C++ | PaulKrauseTeam/IntercomProject | /Communication/checkPermission.cpp | UTF-8 | 1,028 | 2.828125 | 3 | [] | no_license | #include <ctime>
#include <iostream>
#include <pqxx/pqxx>
#include <string>
#include <typeinfo>
using namespace std;
string getUserTime(string str) {
string user_time;
pqxx::connection c("dbname=intercomdb user=guilherme-fonseca");
pqxx::work txn(c);
time_t t = time(0); // get time now
struct tm * now = localtime( & t );
const string DAY[] = {"sun", "mon", "tue" , "wed", "thu", "fri", "sat"};
pqxx::result en = txn.exec(
"SELECT * "
"FROM entry_permission "
"WHERE user_id = " + str
);
pqxx::result ex = txn.exec(
"SELECT * "
"FROM exit_permission "
"WHERE user_id = " + str
);
for (pqxx::result::const_iterator c = en.begin(); c != en.end(); ++c) {
user_time += c[DAY[now->tm_wday]].as<string>();
}
for (pqxx::result::const_iterator c = ex.begin(); c != ex.end(); ++c) {
user_time += ", ";
user_time += c[DAY[now->tm_wday]].as<string>();
}
// cout << user_time << endl;
return user_time;
}
| true |
d8dc161dd5f7ff4bd508f438ab2cc9380fe751dc | C++ | maximaximal/legui | /include/legui/FontManagerAbstract.h | UTF-8 | 1,092 | 3.09375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <SFML/Graphics/Font.hpp>
#include <string>
namespace legui {
/**
* @brief This is the abstract base class of the legui font manager.
*
* It is ment to be derived from your font manager to use the same ressources
* you use.
*/
class FontManagerAbstract {
public:
/**
* @brief Gets the required font from the internal storage & loads it if
* necessary.
*
* @param filename The path to the font (origin in the working dir).
*
* @return A reference to the required font.
*/
virtual sf::Font& get(const std::string& filename) = 0;
/**
* @brief Clears (deletes) all saved fonts.
*
* Previously assigned fonts will no longer be there. If the objects using
* them aren't deleted there will be a segmentation fault!.
*/
virtual void clear() = 0;
/**
* @brief Frees the wanted font from memory.
*
* If a font was only used for a short time by only one user, it should
* be freed after using it.
*
* @param filename The path to the font (ID).
*/
virtual void free(const std::string& filename) = 0;
};
}
| true |
3083f1335ae2d2dd9471b6c8b23f8fa58eb6655f | C++ | bachsoda326/Mario | /DemoDirectX/GameObjects/Enemy/Enemy.cpp | UTF-8 | 2,668 | 2.65625 | 3 | [] | no_license | #include "Enemy.h"
#include "EnemyRunningState.h"
#include "../../GameComponents/GameCollision.h"
Enemy::Enemy(D3DXVECTOR3 position)
{
mAnimationDie = new Animation("Resources/enemy/die.png", 1, 1, 1, 0);
mAnimationRunning = new Animation("Resources/enemy/runningleft.png", 2, 1, 2, 0.4f);
this->mEnemyData = new EnemyData();
this->mEnemyData->enemy = this;
this->SetState(new EnemyRunningState(this->mEnemyData));
SetPosition(position);
}
Enemy::~Enemy()
{
}
void Enemy::Update(float dt)
{
mCurrentAnimation->Update(dt);
if (this->mEnemyData->state)
{
this->mEnemyData->state->Update(dt);
}
Entity::Update(dt);
}
void Enemy::SetReverse(bool flag)
{
mCurrentReverse = flag;
}
void Enemy::Draw(D3DXVECTOR3 position, RECT sourceRect, D3DXVECTOR2 scale, D3DXVECTOR2 transform, float angle, D3DXVECTOR2 rotationCenter, D3DXCOLOR colorKey)
{
mCurrentAnimation->FlipVertical(mCurrentReverse);
mCurrentAnimation->SetPosition(this->GetPosition());
mCurrentAnimation->Draw(position, sourceRect, scale, transform, angle, rotationCenter, colorKey);
}
void Enemy::Draw(D3DXVECTOR2 transform)
{
mCurrentAnimation->FlipVertical(mCurrentReverse);
mCurrentAnimation->SetPosition(this->GetPosition());
mCurrentAnimation->Draw(D3DXVECTOR2(transform));
}
void Enemy::SetState(EnemyState *newState)
{
delete this->mEnemyData->state;
this->mEnemyData->state = newState;
this->changeAnimation(newState->GetState());
mCurrentState = newState->GetState();
}
void Enemy::OnCollision(Entity *impactor, Entity::CollisionReturn data, Entity::SideCollisions side)
{
this->mEnemyData->state->OnCollision(impactor, side, data);
}
RECT Enemy::GetBound()
{
if (isBound)
{
bound.left = posX - width / 2;
bound.right = posX + width / 2;
bound.top = posY - height / 2;
bound.bottom = posY + height / 2;
}
return bound;
}
void Enemy::changeAnimation(EnemyState::StateName state)
{
switch (state)
{
case EnemyState::Running:
mCurrentAnimation = mAnimationRunning;
break;
case EnemyState::Die:
mCurrentAnimation = mAnimationDie;
break;
default:
break;
}
this->width = mCurrentAnimation->GetWidth();
this->height = mCurrentAnimation->GetHeight();
}
Enemy::MoveDirection Enemy::getMoveDirection()
{
if (this->vx > 0)
{
return MoveDirection::MoveToRight;
}
else if (this->vx < 0)
{
return MoveDirection::MoveToLeft;
}
return MoveDirection::None;
}
void Enemy::OnNoCollisionWithBottom()
{
/*if (mCurrentState != EnemyState::Jumping && mCurrentState != EnemyState::Falling)
{
this->SetState(new PlayerFallingState(this->mPlayerData));
}*/
}
EnemyState::StateName Enemy::getState()
{
return mCurrentState;
}
| true |
50bd34ae385eaf32716fa39bf67104aff7da0433 | C++ | zybeasy/libevent_demo | /epoll/epoll_client_001.cpp | UTF-8 | 1,891 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <fcntl.h>
using namespace std;
#define MAX_LINE (1024)
#define SERVER_PORT ((7778)
void set_noblocking(int fd) {
int opts = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, opts | O_NONBLOCK);
}
void func(const char* server_ip) {
int sockfd;
char recvline[MAX_LINE + 1] = {0};
struct sockaddr_in server_addr;
if ((sockfd=socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket error");
exit(0);
}
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
if (inet_pton(AF_INET, server_ip, &server_addr.sin_addr) <= 0) {
perror("inet_pton error for ");
fprintf(stderr, "inet_pton error for %s", server_ip);
exit(0);
}
if(connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0){
perror("connect");
exit(0);
}
set_noblocking(sockfd);
char input[100];
int n = 0;
int count = 0;
while(fgets(input, 100, stdin) != NULL) {
cout << "[send] " << input << endl;
n = send(sockfd, input, strlen(input), 0);
if(n < 0) {
perror("send");
}
while(1) {
n = read(sockfd, recvline+count, MAX_LINE);
if(n == MAX_LINE) {
count += n;
continue;
}
else if (n < 0) {
perror("recv");
break;
}
else {
count += n;
recvline[count] = '\0';
cout << "[recv]: " << recvline << endl;
break;
}
}
}
} | true |
23d9a6683b0ded0d46bba05c981a3b101d2bdc83 | C++ | xUhEngwAng/oj-problems | /leetcode/剑指 Offer 66. 构建乘积数组.cpp | UTF-8 | 536 | 3.015625 | 3 | [] | no_license | #include <vector>
using std::vector;
class Solution {
public:
vector<int> constructArr(vector<int>& a) {
if(a.empty()) return vector<int>();
int n = a.size(), prod = 1;
vector<int> ret(a.size(), 1);
for(int ix = 1; ix != n; ++ix){
prod = prod * a[ix-1];
ret[ix] = ret[ix] * prod;
}
prod = 1;
for(int ix = n-2; ix >= 0; --ix){
prod = prod * a[ix+1];
ret[ix] = ret[ix] * prod;
}
return ret;
}
};
| true |
3cf67f4c987d78a66b9d1fa724fa8c7c6a3b5e71 | C++ | ibhawna/PRACTICE-DS | /leetcode dsa bootcamp kunal kushwaha/linked list/middle element.cpp | UTF-8 | 309 | 2.8125 | 3 | [] | no_license | class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* sp = head;
ListNode* fp = head;
while(fp and fp->next){
sp = sp->next;
fp = fp->next->next;
}
head = sp;
return head;
}
}; | true |
eee9f183900cb6f54964c94f8a095546d5d88bf6 | C++ | little-czy/csp | /2017/201709-5.cpp | GB18030 | 2,323 | 3.078125 | 3 | [] | no_license | // ͨ汾
// #include <iostream>
// #include <cstdio>
// #define MAXN 100005
// using namespace std;
// int n, m;
// long long a[MAXN];
// long long count1[MAXN];
// int main()
// {
// cin >> n >> m;
// int op, l, r, v;
// long long tmp_count = 0;
// for (int i = 1; i <= n; i++)
// {
// scanf("%lld", &a[i]);
// }
// for (int j = 0; j <= n; j++)
// {
// tmp_count += a[j];
// count1[j] = tmp_count;
// }
// for (int i = 0; i < m; i++)
// {
// scanf("%d", &op);
// if (op == 1)
// {
// scanf("%d%d%d", &l, &r, &v);
// for (int j = l; j <= r; j++)
// {
// if (a[j] % v == 0)
// {
// a[j] /= v;
// }
// }
// tmp_count = 0;
// for (int j = 0; j <= n; j++)
// {
// tmp_count += a[j];
// count1[j] = tmp_count;
// }
// }
// else
// {
// scanf("%d%d", &l, &r);
// cout << count1[r] - count1[l - 1] << endl;
// }
// }
// return 0;
// }
//״汾
#include <iostream>
#define MAXN 100005
using namespace std;
int n, m;
int a[MAXN];
long long c[MAXN];
int lowbit(int x)
{
return x & -x;
}
void update(int i, int k)
{
while (i <= n)
{
c[i] += k;
i += lowbit(i);
}
}
long long sum(int i)
{
long long r = 0;
while (i > 0)
{
r += c[i];
i -= lowbit(i);
}
return r;
}
int main()
{
int op, l, r, v;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
update(i, a[i]);
}
for (int i = 0; i < m; i++)
{
scanf("%d", &op);
if (op == 1)
{
scanf("%d%d%d", &l, &r, &v);
if (v == 1)
continue;
for (int j = l; j <= r; j++)
{
if (a[j] >= v && a[j] % v == 0)
{
update(j, a[j] / v - a[j]);
a[j] /= v;
}
}
}
else
{
scanf("%d%d", &l, &r);
cout << sum(r) - sum(l - 1) << endl;
}
}
return 0;
} | true |
6f03bdccac758a9cbdee33f87102a5263606a489 | C++ | seg449/CS3113 | /HW06/sprite.cpp | UTF-8 | 2,481 | 2.75 | 3 | [] | no_license | #include "sprite.h"
#include <iostream>
using namespace std;
sprite::sprite(GLuint ID, float u, float v, float w, float h, float x, float y, float velocityX, float velocityY, float constX, float constY, float s, float rotation, bool collidedTop, bool collidedBottom, bool collidedLeft, bool collidedRight){
this->x = x;
this->y = y;
this->u = u;
this->v = v;
this->s = s;
lives = 0;
width = w;
height = h;
this->constX = constX;
this->constY = constY;
vX = velocityX;
vY = velocityY;
this->ID = ID;
r = rotation;
collidedLeft = false;
collidedRight = false;
collidedBottom = false;
collidedTop = false;
}
void sprite::Render(){
cout << width << "\t" << height << endl;
matrixTransformations();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glMultMatrixf(m.ml);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ID);
GLfloat quad[] = { -width * constX, height * constY, -width * constX, -height * constY, width * constX, -height * constY, width * constX, height * constY };
glVertexPointer(2, GL_FLOAT, 0, quad);
glEnableClientState(GL_VERTEX_ARRAY);
GLfloat quadUVs[] = { u, v, u, v + height, u + width, v + height, u + width, v};
glTexCoordPointer(2, GL_FLOAT, 0, quadUVs);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDrawArrays(GL_QUADS, 0, 4);
glDisable(GL_TEXTURE_2D);
glDisable(GL_BLEND);
glPopMatrix();
}
void sprite::matrixTransformations(){
//this function will generate the scale matrix times the rotation matrix times the translation matrix
//first reset the current matrix to the identity matrix
/*m.identity();
Matrix translation, scale, rotation;
for (int i = 0; i < 4; ++i){
for (int j = 0; j < 4; ++j){
if (i == 0){
if (j == 0){
scale.m[i][j] = constX;
rotation.m[i][j] = cos(r);
}
else if (j == 1){
rotation.m[i][j] = sin(r);
}
}
else if (i == 1){
if (j == 0) rotation.m[i][j] = -sin(r);
else if (j == 1){
scale.m[i][j] = constY;
rotation.m[i][j] = cos(r);
}
}
else if (i == 3){
if (j == 0) translation.m[i][j] == x;
else if (j == 1) translation.m[i][j] == y;
}
}
}*/
Matrix scale;
scale.m[0][0] = constX;
scale.m[1][1] = constY;
Matrix rotate;
rotate.m[0][0] = cos(r);
rotate.m[0][1] = sin(r);
rotate.m[1][0] = -sin(r);
rotate.m[1][1] = cos(r);
Matrix translate;
translate.m[3][0] = x;
translate.m[3][1] = y;
m = scale * rotate * translate;
} | true |
a79b706fb351d6fbed76f0b1c5f7abd026efe154 | C++ | xxAtrain223/EmbGenParser | /src/Variable.cpp | UTF-8 | 2,387 | 2.859375 | 3 | [
"MIT"
] | permissive | #include "EmbGen/Parser/Variable.hpp"
#include <tinyxml2.h>
#include "EmbGen/Parser/Exceptions.hpp"
namespace emb
{
namespace gen
{
namespace parser
{
Variable::Variable(const tinyxml2::XMLElement* xml) :
XmlElement(xml)
{
m_type = getAttribute("type")->Value();
m_name = getAttribute("name")->Value();
try
{
m_core = getAttribute("core")->BoolValue();
}
catch (AttributeException)
{
m_core = false;
}
for (auto parameter : getElements("parameter"))
{
m_parameters.emplace_back(parameter);
}
try
{
m_appendage = getAttribute("appendage")->Value();
}
catch (AttributeException)
{
m_appendage = "";
}
try
{
m_default = getAttribute("default")->Value();
}
catch (AttributeException)
{
m_default = "";
}
if (!isAttributesEmpty())
{
throw AttributeException("Extra attributes for Include on line " + std::to_string(getLineNum()));
}
if (!isElementsEmpty())
{
throw ElementException("Extra elements for Include on line " + std::to_string(getLineNum()));
}
}
std::string Variable::getType() const
{
return m_type;
}
std::string Variable::getName() const
{
return m_name;
}
bool Variable::isCore() const
{
return m_core;
}
std::string Variable::getAppendage() const
{
return m_appendage;
}
std::string Variable::getDefault() const
{
return m_default;
}
std::vector<Parameter> Variable::getParameters() const
{
return m_parameters;
}
}
}
} | true |
815668bca8379dd8d4b00d9e868a64b6f4c41148 | C++ | vishwaramm/Cplusplus-FlightSystem | /Phase_5.cpp | UTF-8 | 12,400 | 3.015625 | 3 | [] | no_license | // (c) s. trowbridge 2021
#include <iostream>
#include <iomanip>
#include "Flight.h"
// containers
MyArray<Airline*> airlines;
MyArray<Airport*> airports;
MyArray<Passenger*> passengers;
MyArray<Pilot*> pilots;
MyArray<Flight*> flights;
// store data into containers
void read() {
std::cout << "Airlines: " << airlines;
std::cout << "adding airlines\n";
airlines.push_back( new Airline("Rebellion Air") );
airlines.push_back( new Airline("Empire Air") );
airlines.push_back( new Airline("Jawa Air") );
std::cout << "adding airports\n";
airports.push_back( new Airport("DAN", "Dantooine") );
airports.push_back( new Airport("END", "Endor") );
airports.push_back( new Airport("HOT", "Hoth") );
airports.push_back( new Airport("KES", "Kessel") );
std::cout << "adding pilots\n";
pilots.push_back( new Pilot("Darth Sidious") );
pilots.push_back( new Pilot("Darth Plagueis") );
pilots.push_back( new Pilot("Darth Bane") );
std::cout << "adding passengers\n";
passengers.push_back( new Passenger("Boba Fett") );
passengers.push_back( new Passenger("Zam Wesell") );
passengers.push_back( new Passenger("Qui-Gon Jinn") );
passengers.push_back( new Passenger("Mace Windu") );
passengers.push_back( new Passenger("Kit Fisto") );
passengers.push_back( new Passenger("Barriss Offee") );
passengers.push_back( new Passenger("Eeth Koth") );
passengers.push_back( new Passenger("Count Dooku") );
passengers.push_back( new Passenger("Aayla Secura") );
std::cout << "adding flights\n";
flights.push_back( new Flight(111, *airlines[0], *airports[0], *airports[1], *pilots[0]) );
flights.push_back( new Flight(222, *airlines[1], *airports[2], *airports[3], *pilots[0]) );
flights.push_back( new Flight(333, *airlines[2], *airports[2], *airports[0], *pilots[0]) );
std::cout << "adding passengers to flights \n";
flights[0]->addPassenger(*passengers[0]);
flights[0]->addPassenger(*passengers[1]);
flights[0]->addPassenger(*passengers[3]);
flights[0]->addPassenger(*passengers[6]);
flights[0]->addPassenger(*passengers[7]);
flights[0]->addPassenger(*passengers[2]);
flights[1]->addPassenger(*passengers[1]);
flights[1]->addPassenger(*passengers[3]);
flights[1]->addPassenger(*passengers[4]);
flights[1]->addPassenger(*passengers[5]);
flights[1]->addPassenger(*passengers[7]);
flights[1]->addPassenger(*passengers[2]);
flights[1]->addPassenger(*passengers[0]);
std::cout << "Finished read\n";
}
void listPilots() {
std::cout << "\nPILOTS:\n";
for(int i=0; i< pilots.getSize();i++) {
std::cout << i << ": " << *(pilots[i]);
}
std::cout << "\n";
}
void listPassengers() {
std::cout << "\nPASSENGERS:\n";
for(int i=0; i< passengers.getSize();i++) {
std::cout << i << ": " << *(passengers[i]);
}
std::cout << "\n";
}
void listAirports() {
std::cout << "\nAIRPORTS:\n";
for(int i=0; i< airports.getSize();i++) {
std::cout << i << ": " << *(airports[i]);
}
std::cout << "\n";
// listMyArray(airports, "Airports");
}
void listAirlines() {
std::cout << "\nAIRLINES:\n";
for(int i=0; i< airlines.getSize();i++) {
std::cout << i << ": " << *(airlines[i]);
}
std::cout << "\n";
}
void listFlights() {
std::cout << "\nFLIGHTS:\n";
for(int i=0; i< flights.getSize();i++) {
std::cout << i << ": " << *(flights[i]);
}
std::cout << "\n";
}
void deleteFlight() {
listFlights();
int index;
std::cout << "SELECT A FLIGHT BY INDEX TO DELETE: ";
std::cin >> index;
if (index < flights.getSize() && index >= 0) {
Flight *f = flights[index];
f->cancel();
f = NULL;
delete f;
flights.erase(index);
std::cout << "Successfully deleted flight at index: " << index << "\n";
}
}
void deleteAirport() {
listAirports();
int index;
std::cout << "SELECT AN AIRPORT BY INDEX TO DELETE: ";
std::cin >> index;
if (index < airports.getSize() && index >= 0) {
Airport *a = airports[index];
a->closeAirport();
airports.erase(index);
delete a;
std::cout << "Successfully deleted airport at index: " << index << "\n";
}
}
void deletePassenger() {
listPassengers();
int index;
std::cout << "SELECT A PASSENGER BY INDEX TO DELETE: ";
std::cin >> index;
if (index < passengers.getSize() && index >= 0) {
Person *p = passengers[index];
for (int i = 0; i < flights.getSize(); i++) {
flights[i]->removePassenger(*p);
}
passengers.erase(index);
delete p;
std::cout << "Successfully deleted passenger at index: " << index << "\n";
}
}
void createPassenger() {
std::cout << "\nCreate a Passenger:\n";
std::cout << "ENTER PASSENGER NAME: ";
std::string name;
std::getline(std::cin >> std::ws, name);
passengers.push_back(new Passenger(name));
std::cout << "\nSuccessfully added new Passenger\n";
}
void createAirport() {
std::cout << "\nCreate a new Airport:\n";
std::cout << "ENTER AIRPORT NAME: ";
std::string name;
std::string symbol;
std::getline(std::cin >> std::ws, name);
std::cout << "ENTER AIPORT SYMBOL: ";
std::getline(std::cin >> std::ws, symbol);
airports.push_back(new Airport(symbol, name));
std::cout << "\nSuccessfully added new Airport\n";
}
void createFlight() {
std::cout << "\nADD NEW FLIGHT:\n";
std::cout << "ENTER FLIGHT NUMBER: ";
int number;
int airline;
int source;
int destination;
int pilot;
std::cin >> number;
listAirlines();
std::cout << "PICK AIRLINE BY INDEX: ";
std::cin >> airline;
listAirports();
std::cout << "PICK SOURCE AIRPORT BY INDEX: ";
std::cin >> source;
listAirports();
std::cout << "PICK DESTINATION AIRPORT BY INDEX: ";
std::cin >> destination;
listPilots();
std::cout << "PICK PILOT BY INDEX: ";
std::cin >> pilot;
flights.push_back(new Flight(number, *airlines[airline], *airports[source], *airports[destination], *pilots[pilot]));
std::cout << "\nSuccessfully added new Flight\n";
}
void changePilot(Flight *f) {
std::cout << "\nCHANGE PILOT:\n";
listPilots();
std::cout << "SELECT PILOT BY INDEX: ";
int pilot;
std::cin >> pilot;
f->setPilot(*(pilots[pilot]));
std::cout << "\nSuccessfully changed Pilot\n";
}
void changeSourceAirport(Flight *f) {
std::cout << "\nCHANGE SOURCE AIRPORT:\n";
listAirports();
std::cout << "SELECT SOURCE AIRPORT BY INDEX: ";
int source;
std::cin >> source;
f->setSource(*(airports[source]));
std::cout << "\nSuccessfully changed Source Airport\n";
}
void changeDestinationAirport(Flight *f) {
std::cout << "\nCHANGE DESTINATION AIRPORT:\n";
listAirports();
std::cout << "SELECT DESTINATION AIRPORT BY INDEX: ";
int destination;
std::cin >> destination;
f->setDestination(*(airports[destination]));
std::cout << "\nSuccessfully changed Destination Airport\n";
}
void addPassenger(Flight *f) {
std::cout << "\nADD PASSENGER:\n";
listPassengers();
std::cout << "SELECT PASSENGER BY INDEX: ";
int passenger;
std::cin >> passenger;
f->addPassenger(*(passengers[passenger]));
std::cout << "\nSuccessfully added Passenger with index: " << passenger << "\n";
}
void removePassenger(Flight *f) {
std::cout << "\nREMOVE PASSENGER:\n";
listPassengers();
std::cout << "SELECT PASSENGER BY INDEX: ";
int passenger;
std::cin >> passenger;
f->removePassenger(*(passengers[passenger]));
std::cout << "\nSuccessfully removed Passenger at index: " << passenger << "\n";
}
void flightSubmenu(int index) {
std::cout << "index: " << index;
if (index >= 0 && index < flights.getSize()) {
Flight *f = flights[index];
int input;
while (input != 6) {
std::cout << "\n*******************************\n";
std::cout << "FLIGHT " << f->getNumber() << " SUBMENU:";
std::cout << "\n*******************************\n";
std::cout << "1 Change Pilot\n";
std::cout << "2 Change Departure Airport\n";
std::cout << "3 Change Arrival Airport\n";
std::cout << "4 Add Passenger\n";
std::cout << "5 Remove Passenger\n";
std::cout << "6 Flights Menu\n";
std::cout << "\nSELECT AN OPTION: ";
std::cin >> input;
switch(input) {
case 1:
changePilot(f);
break;
case 2:
changeSourceAirport(f);
break;
case 3:
changeDestinationAirport(f);
break;
case 4:
addPassenger(f);
break;
case 5:
removePassenger(f);
break;
}
}
}
}
int selectFlight() {
listFlights();
int index;
std::cout << "SELECT A FLIGHT BY INDEX: ";
std::cin >> index;
return index;
}
void flightsMenu() {
int input;
while (input != 5) {
std::cout << "\n*******************************\n";
std::cout << "FLIGHTS MENU:";
std::cout << "\n*******************************\n";
std::cout << "1 List Flights\n";
std::cout << "2 Add Flight\n";
std::cout << "3 Delete Flight\n";
std::cout << "4 Select Flight\n";
std::cout << "5 Main Menu\n";
std::cout << "\nSELECT AN OPTION: ";
std::cin >> input;
switch(input) {
case 1:
listFlights();
break;
case 2:
createFlight();
break;
case 3:
deleteFlight();
break;
case 4:
flightSubmenu(selectFlight());
break;
}
}
}
void airportsMenu() {
int input;
while (input != 4) {
std::cout << "\n*******************************\n";
std::cout << "AIRPORTS MENU:";
std::cout << "\n*******************************\n";
std::cout << "1 List Airports\n";
std::cout << "2 Create Airport\n";
std::cout << "3 Delete Airport\n";
std::cout << "4 Main Menu\n";
std::cout << "\nSELECT AN OPTION: ";
std::cin >> input;
switch(input) {
case 1:
listAirports();
break;
case 2:
createAirport();
break;
case 3:
deleteAirport();
break;
}
}
}
void passengersMenu() {
int input;
while (input != 4) {
std::cout << "\n*******************************\n";
std::cout << "PASSENGERS MENU:";
std::cout << "\n*******************************\n";
std::cout << "1 List Passengers\n";
std::cout << "2 Create Passenger\n";
std::cout << "3 Delete Passenger\n";
std::cout << "4 Main Menu\n";
std::cout << "\nSELECT AN OPTION: ";
std::cin >> input;
switch(input) {
case 1:
listPassengers();
break;
case 2:
createPassenger();
break;
case 3:
deletePassenger();
break;
}
}
}
void mainMenu() {
int input;
while (input != 4) {
std::cout << "\n*******************************\n";
std::cout << "MAIN MENU:";
std::cout << "\n*******************************\n";
std::cout << "1 Airports\n";
std::cout << "2 Flights\n";
std::cout << "3 Passengers\n";
std::cout << "4 End program\n";
std::cout << "\nSELECT AN OPTION: ";
std::cin >> input;
switch(input) {
case 1:
airportsMenu();
break;
case 2:
flightsMenu();
break;
case 3:
passengersMenu();
break;
}
}
}
int main() {
std::cout << "\n";
// read data into the containers
read();
mainMenu();
std::cout << "\n";
return 0;
}
| true |
19a491230720fc3add909d6b31d3bfbff99d3ea6 | C++ | andreas-volz/stateval-creator | /src/Vector2.h | UTF-8 | 5,328 | 3.65625 | 4 | [
"MIT"
] | permissive | #ifndef VECTOR2_H
#define VECTOR2_H
#include <cmath>
#include <string>
#include <sstream>
#include <iomanip>
template <typename T>
class Vector2
{
private:
public:
T x, y;
Vector2() {}
/// copy constructor
Vector2(const Vector2<T> &v) : x(v.x), y(v.y) {}
/// construct given two values
/*!
* \param _x the x component to the Vector2
* \param _y the y component to the Vector2
*/
Vector2(const T &_x, const T &_y) : x(_x), y(_y) {}
virtual ~Vector2() {}
/// set all components to zero
void zero()
{
x = y = 0;
}
/// copy values
Vector2<T>& operator = (const Vector2<T>& v1);
/// \return inverted vector
Vector2<T> operator - ();
/// vector_2 += vector_1
Vector2<T>& operator += (const Vector2<T>& v1);
/// vector_2 -= vector_1
Vector2<T>& operator -= (const Vector2<T>& v1);
/// vector_1 *= scalar
Vector2<T>& operator *= (const T scalar);
};
template <typename T>
class Vector2decimal : public Vector2<T>
{
public:
Vector2decimal() : Vector2<T> () {}
Vector2decimal(T _x, T _y) : Vector2<T> (_x, _y) {}
Vector2decimal(const Vector2<T> &v) : Vector2<T> (v) {}
virtual ~Vector2decimal() {}
// no special functions for decimal vectors
};
template <typename T>
class Vector2real : public Vector2<T>
{
public:
Vector2real() : Vector2<T> () {}
Vector2real(T _x, T _y) : Vector2<T> (_x, _y) {}
Vector2real(const Vector2<T> &v) : Vector2<T> (v) {}
virtual ~Vector2real() {}
/// normalize it
void normalize();
/// return the magnitude
virtual T getMagnitude() const = 0;
/// vector_1 /= scalar
Vector2real<T>& operator /= (const T scalar);
};
class Vector2f : public Vector2real<float>
{
public:
Vector2f() : Vector2real<float> () {}
Vector2f(float _x, float _y) : Vector2real<float> (_x, _y) {}
Vector2f(const Vector2<float> &v) : Vector2real<float> (v) {}
virtual ~Vector2f() {}
virtual float getMagnitude() const
{
// usage of sqrtf is faster than sqrt for float!
return sqrtf(x * x + y * y);
}
};
class Vector2d : public Vector2real<double>
{
public:
Vector2d() : Vector2real<double> () {}
Vector2d(double _x, double _y) : Vector2real<double> (_x, _y) {}
Vector2d(const Vector2<double> &v) : Vector2real<double> (v) {}
virtual ~Vector2d() {}
virtual double getMagnitude() const
{
return sqrt(x * x + y * y);
}
};
typedef Vector2decimal<int> Vector2i;
/*****************************/
/* Member Template functions */
/*****************************/
template <typename T>
void Vector2real<T>::normalize()
{
T magnitude = getMagnitude();
if (magnitude > 0.0)
{
T one_mag = 1.0 / magnitude;
*this *= one_mag;
}
}
/********************/
/* Member-Operators */
/********************/
template <typename T>
Vector2<T>& Vector2<T>::operator = (const Vector2<T>& v1)
{
x = v1.x;
y = v1.y;
return *this;
}
template <typename T>
Vector2<T> Vector2<T>::operator - ()
{
Vector2<T> v;
v.x = -x;
v.y = -y;
return v;
}
template <typename T>
inline Vector2<T>& Vector2<T>::operator += (const Vector2<T>& v1)
{
x += v1.x;
y += v1.y;
return *this;
}
template <typename T>
inline Vector2<T>& Vector2<T>::operator -= (const Vector2<T>& v1)
{
x -= v1.x;
y -= v1.y;
return *this;
}
template <typename T>
inline Vector2<T>& Vector2<T>::operator *= (const T scalar)
{
x *= scalar;
y *= scalar;
return *this;
}
template <typename T>
inline Vector2real<T>& Vector2real<T>::operator /= (const T scalar)
{
Vector2<T>::x /= scalar;
Vector2<T>::y /= scalar;
return *this;
}
/**************************************/
/* Non-Member operators and functions */
/**************************************/
/// test if two Vector2 have the same values
template <typename T>
inline bool operator == (const Vector2<T>& v1, const Vector2<T>& v2)
{
if ((v1.x == v2.x) &&
(v1.y == v2.y))
{
return true;
}
return false;
}
/// vector_2 = vector_1 * scalar
template <typename T>
inline Vector2<T> operator * (const Vector2<T>& v1, const T scalar)
{
Vector2<T> v3 = v1;
return v3 *= scalar;
}
/// vector_2 = vector_1 / scalar
template <typename T>
inline Vector2real<T> operator / (const Vector2<T>& v1, const T scalar)
{
Vector2real<T> v3 = v1;
return v3 /= scalar;
}
/// vector_3 = vector_1 - vector_2
template <typename T>
inline Vector2<T> operator - (const Vector2<T>& v1, const Vector2<T>& v2)
{
Vector2<T> v3 = v1;
return v3 -= v2;
}
/// vector_3 = vector_1 + vector_2
template <typename T>
inline Vector2<T> operator + (const Vector2<T>& v1, const Vector2<T>& v2)
{
Vector2<T> v3 = v1;
return v3 += v2;
}
/// calculate the distance between two Vector2 (float)
inline float vectorDistance(const Vector2f &v1, const Vector2f &v2)
{
Vector2f dist = v1 - v2;
return dist.getMagnitude();
}
/// calculate the distance between two Vector2 (double)
inline double vectorDistance(const Vector2d &v1, const Vector2d &v2)
{
Vector2d dist = v1 - v2;
return dist.getMagnitude();
}
/// << operator for output
template <typename T>
std::ostream &operator << (std::ostream &s, const Vector2<T> &v)
{
s << "[";
s << "x: " << v.x << " y: " << v.y;
s << "]";
return s;
}
#endif // VECTOR2_H
| true |
22429cd64061648eca86bdf330abe4e18fa8dcef | C++ | Dlol/reylub | /main.cpp | UTF-8 | 1,386 | 2.953125 | 3 | [] | no_license | #include <raylib.h>
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <time.h>
void centerRect(int x, int y, int width, int height, Color color) {
DrawRectangle((x - (width / 2)), (y - (height / 2)), width, height, color);
}
void statusBar(int height, int value) {
DrawRectangle(0, height, 800, 30, RAYWHITE);
std::stringstream out;
out << "bg value: " << value;
DrawText(out.str().c_str(),5,height + 5, 20, BLACK);
}
int main() {
int screenWidth = 800;
int screenHeight = 800;
InitWindow(screenWidth, screenHeight + 30, "raylib example");
SetTargetFPS(60);
int currentX = screenWidth / 2;
int currentY = screenHeight / 2;
int alpha = 255;
int speed = 5;
srand(time(NULL));
Vector2 direction = {0.76,-0.89};
Color rectColor = {255, 0, 0, 255};
Color clearColor = {0,0,0,128};
while (!WindowShouldClose()){
BeginDrawing();
DrawRectangle(0,0,screenWidth,screenHeight,clearColor);
if(currentX - 32 < 0 || currentX + 32 > screenWidth){
srand(time(NULL));
direction.x = direction.x * -1;
}
if(currentY - 32 < 0 || currentY + 32 > screenHeight){
srand(time(NULL));
direction.y = direction.y * -1;
}
currentX += (speed * direction.x);
currentY += (speed * direction.y);
DrawCircle(currentX, currentY, 32, rectColor);
statusBar(screenHeight, clearColor.r);
EndDrawing();
}
CloseWindow();
return 0;
} | true |
936bb99b0657e9cffe48090e7ffc63d0e73860a6 | C++ | Adam-/anope | /include/extensible.h | UTF-8 | 3,458 | 2.625 | 3 | [] | no_license | /*
*
* (C) 2003-2014 Anope Team
* Contact us at team@anope.org
*
* Please read COPYING and README for further details.
*
*/
#pragma once
#include "anope.h"
#include "service.h"
#include "logger.h"
class Extensible;
class CoreExport ExtensibleBase : public Service
{
protected:
std::map<Extensible *, void *> items;
ExtensibleBase(Module *m, const Anope::string &n);
ExtensibleBase(Module *m, const Anope::string &t, const Anope::string &n);
~ExtensibleBase();
public:
virtual void Unset(Extensible *obj) anope_abstract;
};
class CoreExport Extensible
{
public:
std::vector<ExtensibleBase *> extension_items;
virtual ~Extensible();
template<typename T> T* GetExt(const Anope::string &name);
bool HasExtOK(const Anope::string &name);
template<typename T> T* Extend(const Anope::string &name, const T &what);
template<typename T> void ShrinkOK(const Anope::string &name);
};
template<typename T>
class ExtensibleItem : public ExtensibleBase
{
public:
ExtensibleItem(Module *m, const Anope::string &n) : ExtensibleBase(m, n) { }
ExtensibleItem(Module *m, const Anope::string &t, const Anope::string &n) : ExtensibleBase(m, t, n) { }
~ExtensibleItem()
{
while (!items.empty())
{
std::map<Extensible *, void *>::iterator it = items.begin();
Extensible *obj = it->first;
T *value = static_cast<T *>(it->second);
auto it2 = std::find(obj->extension_items.begin(), obj->extension_items.end(), this);
if (it2 != obj->extension_items.end())
obj->extension_items.erase(it2);
items.erase(it);
delete value;
}
}
T* Set(Extensible *obj, const T &value)
{
T* t = new T(value);
Unset(obj);
items[obj] = t;
obj->extension_items.push_back(this);
return t;
}
void Unset(Extensible *obj) override
{
T *value = Get(obj);
items.erase(obj);
auto it = std::find(obj->extension_items.begin(), obj->extension_items.end(), this);
if (it != obj->extension_items.end())
obj->extension_items.erase(it);
delete value;
}
T* Get(Extensible *obj)
{
std::map<Extensible *, void *>::const_iterator it = items.find(obj);
if (it != items.end())
return static_cast<T *>(it->second);
return nullptr;
}
bool HasExt(Extensible *obj)
{
return items.find(obj) != items.end();
}
T* Require(Extensible *obj)
{
T* t = Get(obj);
if (t)
return t;
return Set(obj, T());
}
};
template<typename T>
struct ExtensibleRef : ServiceReference<ExtensibleItem<T>>
{
ExtensibleRef(const Anope::string &n) : ServiceReference<ExtensibleItem<T>>("Extensible", n) { }
ExtensibleRef(const Anope::string &t, const Anope::string &n) : ServiceReference<ExtensibleItem<T>>(t, n) { }
};
template<typename T>
T* Extensible::GetExt(const Anope::string &name)
{
ExtensibleRef<T> ref(name);
if (ref)
return ref->Get(this);
Log(LOG_DEBUG) << "GetExt for nonexistent type " << name << " on " << static_cast<const void *>(this);
return NULL;
}
template<typename T>
T* Extensible::Extend(const Anope::string &name, const T &what)
{
ExtensibleRef<T> ref(name);
if (ref)
{
ref->Set(this, what);
return ref->Get(this);
}
Log(LOG_DEBUG) << "Extend for nonexistent type " << name << " on " << static_cast<void *>(this);
return NULL;
}
template<typename T>
//XXX
void Extensible::ShrinkOK(const Anope::string &name)
{
ExtensibleRef<T> ref(name);
if (ref)
ref->Unset(this);
else
Log(LOG_DEBUG) << "Shrink for nonexistent type " << name << " on " << static_cast<void *>(this);
}
| true |
d138b4f294239c1e359daf59f9c7db56a21ff06f | C++ | danieleRocha/VolumesFinitos | /Problemas/Problema.cpp | ISO-8859-1 | 1,810 | 2.84375 | 3 | [] | no_license | #include "Problema.h"
Problema::~Problema(void)
{
}
void Problema::DefinirArquivo()
{
arquivo = ofstream("resultado.txt");
}
void Problema::ImprimirMensagemDeErro(int numeroDoErro)
{
switch(numeroDoErro)
{
case 1:
arquivo<<"Erro: \n"
"No foi possvel calcular a varivel independente: espao.\n\n";
cout<<"Erro: \n"
"No foi possvel calcular a varivel independente: espao.\n\n";
break;
case 2:
arquivo<<"Erro: \n"
"No foi possvel calcular a soluo analtica.\n\n";
cout<<"Erro: \n"
"No foi possvel calcular a soluo analtica.\n\n";
break;
case 3:
arquivo<<"Erro: \n"
"No foi possvel calcular a soluo numrica.\n\n";
cout<<"Erro: \n"
"No foi possvel calcular a soluo numrica.\n\n";
break;
case 4:
arquivo<<"Erro: \n"
"No foi possvel calcular os desvios dos resultados numricos em relao aos analticos.\n\n";
cout<<"Erro: \n"
"No foi possvel calcular os desvios dos resultados numricos em relao aos analticos.\n\n";
break;
case 5:
arquivo<<"Erro: \n"
"No foi possvel calcular a varivel independente: espao x.\n\n";
cout<<"Erro: \n"
"No foi possvel calcular a varivel independente: espao x.\n\n";
break;
case 6:
arquivo<<"Erro: \n"
"No foi possvel calcular a varivel independente: espao y.\n\n";
cout<<"Erro: \n"
"No foi possvel calcular a varivel independente: espao y.\n\n";
break;
case 7:
arquivo<<"Erro: \n"
"No foi possvel calcular a varivel independente: tempo.\n\n";
cout<<"Erro: \n"
"No foi possvel calcular a varivel independente: tempo.\n\n";
break;
default:
arquivo<<"Erro: \n"
"Houve um erro no sistema.\n\n";
cout<<"Erro: \n"
"Houve um erro no sistema.\n\n";
break;
}
}
| true |
033fdec51b0685f65601f9cf7d2f7f205f20df0a | C++ | umbesere/num_sim_lab | /LSN_2/es02_2.cpp | UTF-8 | 3,376 | 2.9375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <numeric>
#include "random.h"
#include "random_walk.h"
using namespace std;
// error function to calculate standard deviation from mean and mean squared
double error(double ave, double av2, int n){
if (n == 0)
return 0;
else
return sqrt((av2 - pow(ave,2))/n);
}
int main (int argc, char *argv[]){
// initializing random
Random rnd;
int seed[4];
int p1, p2;
ifstream Primes("Primes");
if (Primes.is_open()){
Primes >> p1 >> p2 ;
} else cerr << "PROBLEM: Unable to open Primes" << endl;
Primes.close();
ifstream input("seed.in");
string property;
if (input.is_open()){
while ( !input.eof() ){
input >> property;
if( property == "RANDOMSEED" ){
input >> seed[0] >> seed[1] >> seed[2] >> seed[3];
rnd.SetRandom(seed,p1,p2);
}
}
input.close();
} else cerr << "PROBLEM: Unable to open seed.in" << endl;
for(int i=0; i<20; i++){
cout << rnd.Rannyu() << endl;
}
rnd.SaveSeed();
cout << endl;
//** SIMULATION OF DESCRETE AND CONTINUOUS RANDOM WALKS **//
// initializing variables
int M = 10000; // #RWs
int N = 100; // #blocks
int L = int(M/N); // block's length
int N_step = 100; // total number of steps
double sum_discr, mean_discr, mea2_discr, err_discr, sum_cont, mean_cont, mea2_cont, err_cont;
vector<double> r2_discr(N); // vectors to be filled by block's mean of |r|^2 for descrete/continuous RWs
vector<double> r22_discr(N);
vector<double> r2_cont(N);
vector<double> r22_cont(N);
// initializing M random walks
RandomWalk RW_discr[M];
RandomWalk RW_cont[M];
// setting initial points to origin
for(int i=0; i<M; i++){
RW_discr[i].SetCoord();
RW_cont[i].SetCoord();
}
// opening output file
ofstream WriteResults;
WriteResults.open("es02_2.txt");
if(!WriteResults){
cerr << "PROBLEM: Unable to open es02_2.txt!" << endl;
return -1;
}
// simulating RWs
for (int j=0; j<N_step; j++){
for(int i=0; i<N; i++){
sum_discr = 0;
sum_cont = 0;
// simulating a step for each RW of the considered block
for(int k=L*i; k<L*(i+1); k++){
RW_discr[k].DiscrStep(rnd);
RW_cont[k].ContStep(rnd);
sum_discr += pow( RW_discr[k].getR(), 2);
sum_cont += pow( RW_cont[k].getR(), 2);
}
// loading vectors with means and squared means
sum_discr /= L;
sum_cont /= L;
r2_discr[i] = sum_discr;
r22_discr[i] = sum_discr*sum_discr;
r2_cont[i] = sum_cont;
r22_cont[i] = sum_cont*sum_cont;
}
// computing progressive means and errors
mean_discr = accumulate(r2_discr.begin(), r2_discr.end(), 0.0) / N;
mea2_discr = accumulate(r22_discr.begin(), r22_discr.end(), 0.0) / N;
mean_cont = accumulate(r2_cont.begin(), r2_cont.end(), 0.0) / N;
mea2_cont = accumulate(r22_cont.begin(), r22_cont.end(), 0.0) / N;
err_discr = error(mean_discr, mea2_discr, N);
err_cont = error(mean_cont, mea2_cont, N);
// writing results
cout << j << sqrt(mean_discr) << " " << err_discr/(2*sqrt(mean_discr)) << " " << sqrt(mean_cont) << " " << err_cont/(2*sqrt(mean_cont)) << endl;
WriteResults << j << " " << sqrt(mean_discr) << " " << err_discr/(2*sqrt(mean_discr)) << " " << sqrt(mean_cont) << " " << err_cont/(2*sqrt(mean_cont)) << endl;
}
WriteResults.close();
return 0;
}
| true |
941b4a8a86f06b2910904f9776e57bfe5c2118ce | C++ | Trigger2000/Computational-mathematics | /lab7/main.cpp | UTF-8 | 2,826 | 3.34375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <functional>
#define STEP 0.001
struct point
{
double x = 0.0;
double y = 0.0;
double y1 = 0.0;
};
std::vector<point> solve(double b, std::function<double(double)> func);
std::vector<point> solve_with_rk3(double alpha, std::function<double(double)> func);
std::ostream& operator<<(std::ostream& stream, const std::vector<point>& points);
int main()
{
/* std::vector<point> result1 = solve(0.5, [](double x){return std::exp(x);});
std::vector<point> result2 = solve(1.0, [](double x){return std::exp(x);});
std::vector<point> result3 = solve(1.4, [](double x){return std::exp(x);}); */
std::vector<point> result1 = solve(0.5, [](double x){return (-1.0) * std::exp(x);});
std::vector<point> result2 = solve(1.0, [](double x){return (-1.0) * std::exp(x);});
std::vector<point> result3 = solve(1.4, [](double x){return (-1.0) * std::exp(x);});
std::ofstream file1("data1.dat");
std::ofstream file2("data2.dat");
std::ofstream file3("data3.dat");
file1 << result1;
file2 << result2;
file3 << result3;
return 0;
}
std::vector<point> solve_with_rk3(double alpha, std::function<double(double)> func)
{
std::vector<point> result;
result.reserve(static_cast<std::size_t>(1.0 / STEP) + 1);
result.resize(static_cast<std::size_t>(1.0 / STEP) + 1);
result[0].x = 0;
result[0].y = 1;
result[0].y1 = alpha;
for (int i = 1; i <= static_cast<std::size_t>(1.0 / STEP); ++i)
{
double xk = result[i - 1].x;
double yk = result[i - 1].y;
double y1k = result[i - 1].y1;
double k1 = y1k;
double m1 = func(yk);
double k2 = y1k + (STEP * m1) / 3.0;
double m2 = func(yk + (STEP * k1) / 3.0);
double k3 = y1k + (2.0 * STEP * m2);
double m3 = func(yk + (2.0 * STEP * k2) / 3.0);
result[i].x = xk + STEP;
result[i].y = yk + STEP * (k1 + 3.0 * k3) / 4.0;
result[i].y1 = y1k + STEP * (m1 + 3.0 * m3) / 4.0;
}
return result;
}
std::vector<point> solve(double b, std::function<double(double)> func)
{
double alpha = -5.0;
double h = 0.001;
std::vector<point> result = solve_with_rk3(alpha, func);
while (std::abs(result.back().y - b) >= 0.01)
{
std::vector<point> helper = solve_with_rk3(alpha + h, func);
alpha -= h * (result.back().y - b) / (helper.back().y - result.back().y);
result = solve_with_rk3(alpha, func);
}
return result;
}
std::ostream& operator<<(std::ostream& stream, const std::vector<point>& points)
{
for (const auto& item: points)
{
stream.precision(5);
stream << std::fixed;
stream << item.x << '\t' << item.y << '\n';
}
return stream;
} | true |
f96d0f0a72b6c6af74d37162400bb4fb476c5bc9 | C++ | mymichellle/Collage-Builder | /Utility.h | UTF-8 | 3,734 | 2.765625 | 3 | [] | no_license | //
// Utility.h
// Collage
//
// Created by Michelle Alexander on 10/02/11.
// Copyright 2011 ??? . All rights reserved.
//
#ifndef Utility_h
#define Utility_h
#include <GL/glut.h>
#include <string>
using namespace std;
#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 700
#define DISPLAY_FONT GLUT_BITMAP_HELVETICA_18 //GLUT_BITMAP_9_BY_15;
static void displayString(std::string s)
{
for (string::iterator i = s.begin(); i != s.end(); ++i)
{
char c = *i;
glutBitmapCharacter(DISPLAY_FONT, c);
}
}
static int displayStringWidth(string s)
{
// Calculate the width of the string to be displayed
return glutBitmapLength ( DISPLAY_FONT, (const unsigned char *)s.c_str());
}
static int displayStringHeight(string s)
{
// Return the font height
if(DISPLAY_FONT == GLUT_BITMAP_HELVETICA_18)
return 15;
else if(DISPLAY_FONT == GLUT_BITMAP_9_BY_15)
return 15;
else
return 1;
}
static int getMainTitleX(string s)
{
return WINDOW_WIDTH/2 - displayStringWidth(s)/2;
}
static int getMainTitleY(string s)
{
return WINDOW_HEIGHT - 50;
}
// Flip the y-axis
static void correctCoords(int &aX, int &aY)
{
aY=WINDOW_HEIGHT-aY;
}
/* Upscaling the image uses simple bilinear interpolation */
static int up_scale_image
(
const unsigned char* const orig,
int width, int height, int channels,
unsigned char* resampled,
int resampled_width, int resampled_height
)
{
float dx, dy;
int x, y, c;
/* error(s) check */
if ( (width < 1) || (height < 1) ||
(resampled_width < 2) || (resampled_height < 2) ||
(channels < 1) ||
(NULL == orig) || (NULL == resampled) )
{
/* signify badness */
return 0;
}
/*
for each given pixel in the new map, find the exact location
from the original map which would contribute to this guy
*/
dx = (width - 1.0f) / (resampled_width - 1.0f);
dy = (height - 1.0f) / (resampled_height - 1.0f);
for ( y = 0; y < resampled_height; ++y )
{
/* find the base y index and fractional offset from that */
float sampley = y * dy;
int inty = (int)sampley;
/* if( inty < 0 ) { inty = 0; } else */
if( inty > height - 2 ) { inty = height - 2; }
sampley -= inty;
for ( x = 0; x < resampled_width; ++x )
{
float samplex = x * dx;
int intx = (int)samplex;
int base_index;
/* find the base x index and fractional offset from that */
/* if( intx < 0 ) { intx = 0; } else */
if( intx > width - 2 ) { intx = width - 2; }
samplex -= intx;
/* base index into the original image */
base_index = (inty * width + intx) * channels;
for ( c = 0; c < channels; ++c )
{
/* do the sampling */
float value = 0.5f;
value += orig[base_index]
*(1.0f-samplex)*(1.0f-sampley);
value += orig[base_index+channels]
*(samplex)*(1.0f-sampley);
value += orig[base_index+width*channels]
*(1.0f-samplex)*(sampley);
value += orig[base_index+width*channels+channels]
*(samplex)*(sampley);
/* move to the next channel */
++base_index;
/* save the new value */
resampled[y*resampled_width*channels+x*channels+c] =
(unsigned char)(value);
}
}
}
/* done */
return 1;
}
// Define an object to define Color
class BaseColor{
private:
struct Color{
float red;
float green;
float blue;
float alpha;
};
public:
BaseColor(float r, float g, float b, float a)
{
color.red=r;color.green=g;color.blue=b;color.alpha=a;
}
Color color;
};
#endif | true |
684a6e90c5ed17cc4cf1c47227cf3dbc0be599df | C++ | yvson18/Roteiro_3 | /questao_1/Imoveis.cpp | UTF-8 | 409 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include "Imoveis.h"
Imoveis::Imoveis(std::string titulo,double valor,std::string disponibilidade){
this->titulo = titulo;
this->valor = valor;
this->disponibilidade = disponibilidade;
}
void Imoveis::exibir(){
std::cout << "Titulo: " << titulo << "\n"
<< "Valor: " << valor << "\n"
<<"Disponibilidade: " << disponibilidade << std::endl;
} | true |
542261d7c708496ca681ffa396f4a7de58d718c4 | C++ | HristoHristov95/C-- | /481-str C++/481-str C++/Source1.cpp | UTF-8 | 1,509 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<list>
#include<cstring>
using namespace std;
class Project{
public:
char name[40];
int days_to_completion;
Project(){
strcpy(name, "");
days_to_completion = 0;
}
Project(char *n, int d){
strcpy(name, n);
days_to_completion = d;
}
void add_days(int i){
days_to_completion += i;
}
void sub_days(int i){
days_to_completion -= i;
}
bool completed(){ return !days_to_completion; }
void report(){
cout << name << ": ";
cout << days_to_completion;
cout << " days left.\n";
}
};
bool operator<(const Project &a, const Project &b)
{
return a.days_to_completion < b.days_to_completion;
}
bool operator>(const Project &a, const Project &b)
{
return a.days_to_completion>b.days_to_completion;
}
bool operator==(const Project &a, const Project &b)
{
return a.days_to_completion == b.days_to_completion;
}
bool operator !=(const Project &a, const Project &b)
{
return a.days_to_completion != b.days_to_completion;
}
int main()
{
list<Project> proj, proj1;
proj.push_back(Project("Compiler", 35));
proj.push_back(Project("SpredSheet", 190));
proj.push_back(Project("STL Implementation", 1000));
proj1.push_back(Project("Data Base", 780));
proj1.push_back(Project("Mail Merge", 50));
proj1.push_back(Project("COM objects", 300));
proj.sort();
proj1.sort();
proj.merge(proj1);
list<Project>::iterator p,q;
p = proj.begin();
for (; p != proj.end();)
{
do
{
p->sub_days(5);
p->report();
} while (!p->completed());
p++;
}
return 0;
} | true |
bac441ab18f7f28753ff0c1e12354beb9b201c68 | C++ | JinyuChata/leetcode_cpp | /leetcode/editor/cn/_l_c_pf01guess-numbers.cpp | UTF-8 | 1,072 | 3.15625 | 3 | [] | no_license | //小A 和 小B 在玩猜数字。小B 每次从 1, 2, 3 中随机选择一个,小A 每次也从 1, 2, 3 中选择一个猜。他们一共进行三次这个游戏,请返回 小
//A 猜对了几次?
//
// 输入的guess数组为 小A 每次的猜测,answer数组为 小B 每次的选择。guess和answer的长度都等于3。
//
//
//
// 示例 1:
//
//
//输入:guess = [1,2,3], answer = [1,2,3]
//输出:3
//解释:小A 每次都猜对了。
//
// 示例 2:
//
//
//输入:guess = [2,2,3], answer = [3,2,1]
//输出:1
//解释:小A 只猜对了第二次。
//
//
//
// 限制:
//
//
// guess 的长度 = 3
// answer 的长度 = 3
// guess 的元素取值为 {1, 2, 3} 之一。
// answer 的元素取值为 {1, 2, 3} 之一。
//
// Related Topics 数组 👍 126 👎 0
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public:
int game(vector<int>& guess, vector<int>& answer) {
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main() {
Solution s;
} | true |
806fa3437b415aaaff7cf12f0279d7f0726cc378 | C++ | im-13/computer-vision | /02_EdgesAndLinesDetection/h4/h4.cpp | UTF-8 | 4,663 | 2.984375 | 3 | [] | no_license | /******************************************************************************************
Title : h4.cpp
Author : Ilona Michalowska
Created on : October 20, 2015
Description : The program finds lines in the image from its Hough Transform space using
a given threshold and draws the detected lines on a copy of the original
scene image.
Usage : ./h4 <arg1> <arg2> <arg3> <arg4>
where:
<arg1> is an input original gray-level image
<arg2> is an input gray-level Hough image
<arg3> is an input gray-level Hough threshold value
<arg4> is an output gray-level line image
Comments : Hough image is thrsholded and saved as a grey-level image and its binary
copy. The objects in the binary copy are labeled, and a HoughDatabase
object is used to record all "areas of brightness" weights and weighted
positions. HoughDatabase class contains the optimize member function that
further averages values of rho and theta if the values for two records
differ by less than 10 pixels and 7 degress, respectively.
Drawing the lines in the original image that do not extend beyond the
actual edges is implemented with the use of its smoothed with the Gaussian
filter and thresholded binary Sobel image. Lines are drawn only on these
pixels in the original image that have corresponding black (0) pixels in
the Sobel image.
******************************************************************************************/
#include <iomanip>
#include <cassert>
#include <string>
#include <iostream>
#include <vector>
#include "Image.h"
#include "DisjSets.h"
#include "HoughDatabase.h"
#include "Database.h"
using namespace std;
/**
* Print information on how to run the program.
*/
void showUsage(string fileName);
/******************************************************************************************
* MAIN
******************************************************************************************/
int main(int argc, char * argv[]) {
if (argc!=5) {
showUsage(argv[0]);
return 0;
}
Image *input, *inputCopy, *Hough, *Sobel, *output;
input = new Image;
assert(input != 0);
Hough = new Image;
assert(Hough != 0);
Sobel = new Image;
assert(Sobel != 0);
output = new Image;
assert(output != 0);
if (readImage(input, argv[1])) {
printf("Can't open file %s\n", argv[1]);
return 0;
}
inputCopy = new Image(*input);
assert(inputCopy != 0);
//writeImage(input, "input.pgm");
if (readAndThresholdImage(Hough, argv[2], atoi(argv[3]))) {
printf("Can't open file %s\n", argv[2]);
return 0;
}
//writeImage(Hough, "Hough_T.pgm");
setRhoShiftForHoughImage(input, Hough);
HoughDatabase db;
findLocalMaxima(Hough, db);
/* For drawing detected lines that do not extend beyond actual edges */
apply5x5GaussianFilter(input);
//writeImage(input, "input_G.pgm");
applySobelOperator(input, Sobel);
//writeImage(Sobel, "input_G_S.pgm");
apply5x5GaussianFilter(Sobel);
//writeImage(Sobel, "input_G_S_G.pgm");
thresholdAndMakeBinaryImage(Sobel, 15);
//writeImage(Sobel, "input_G_S_G_TB.pgm");
drawLines(input, db);
drawLines(inputCopy, db, Sobel);
if (writeImage(input, argv[4])) {
printf("Can't write to file %s\n", argv[3]);
return 0;
}
if (writeImage(inputCopy, "edges.pgm")) {
printf("Can't write to file %s\n", argv[3]);
return 0;
}
return 0;
}
/******************************************************************************************
* showUsage
******************************************************************************************/
void showUsage(string fileName) {
cout << "********************************************************************************\n"
<< "Usage:\t" << fileName << " <arg1> <arg2> <arg3> <arg4>\n"
<< "********************************************************************************\n"
<< "where:\n"
<< "\t<arg1> is an input original gray-level image\n"
<< "\t<arg2> is an input gray-level Hough image\n"
<< "\t<arg3> is an input gray-level Hough threshold value\n"
<< "\t<arg4> is an output gray-level line image\n"
<< "example:\n\t" << fileName << " inputImage.pgm inputHoughImage.pgm 100 output.pgm\n";
} | true |
02daa645e28d6639fdc2d82fe6b12c45f60fe745 | C++ | ShepherdQR/programming | /codes/openglstudying/openglCollections/Basic/opengl0002qr/gl002blankwindow.cpp | UTF-8 | 4,200 | 2.984375 | 3 | [] | no_license |
// https://learnopengl-cn.github.io/
// /usr/include/GL/freeglut_std.h文件查看opengl version 4.13 . but is wrong. should be 4.2
// ln -s /usr/include /usr/x/y/z/x.h (假设缺少的头文件路径 /usr/x/y/z/,根据实际情况操作)
// extern "C"{
// #include <glad/glad.h>
// #include <GLFW/glfw3.h>
// }
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
/*
To check the opengl version, in shell:
$ sudo apt-get install mesa-utils
$ glxinfo
mine is 4.2, make sure it's higher than the next two parameters.
*/
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);//we'll get access to a smaller subset of OpenGL features without backwards-compatible features we no longer need
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // uncomment this statement to fix compilation on OS X
#endif
// glfw window creation
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearningOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
//We register the callback functions after we've created the window and before the render loop is initiated.
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
//initialize GLAD before calling any OpenGL function---------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// render loop
while (!glfwWindowShouldClose(window))
{
// input function
processInput(window);
// render functon
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);// state-setting function, a dark green-blueish color
glClear(GL_COLOR_BUFFER_BIT);//state=-using function.it uses the current state to retrieve the clearing color from.
//The possible bits we can set are GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT and GL_STENCIL_BUFFER_BIT.
glfwSwapBuffers(window);//swap the color buffer (a large 2D buffer that contains color values for each pixel in GLFW's window)
glfwPollEvents();//poll IO events (keys pressed/released, mouse moved etc.)
}
//双缓冲(Double Buffer):单缓冲绘图时图像的逐步生成可能会使图像闪烁。双缓冲的前缓冲保存最终输出的图像并显示在屏幕上,后缓冲进行渲染。渲染完成后交换(Swap)前缓冲和后缓冲,立即显示图像消除不真实感。
// glfw: terminate, clearing all previously allocated GLFW resources.
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
void processInput(GLFWwindow *window)
{
// this function means pressing esc to close window
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
/*
make sure the viewport matches the new window dimensions; note that width and
height will be significantly larger than specified on retina displays.
the location of the lower left corner of the window is set to (0, 0)
The third and fourth parameter set the width and height of the rendering window in pixels
Note that processed coordinates in OpenGL are between -1 and 1 so we effectively map from the range (-1 to 1) to (0, 800) and (0, 600).
*/
}
| true |
8c25d80bb7e128dd1ece7e0a5c7373919ab162e9 | C++ | zimw/coding-challenge | /q2/find-pair-bonus.cpp | UTF-8 | 2,039 | 3.203125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(int argc, char **argv)
{
if (argc != 3)
return -1;
string fileName(argv[1]);
string nums(argv[2]);
int credits = stoi(nums);
//cout<< fileName<<" "<< credits<<endl;
ifstream infile(fileName);
std::string line;
vector< pair<int, string> > myVec;
while (std::getline(infile, line))
{
size_t pos = 0;
std::string delimiter = ", ";
pos = line.find(delimiter);
string itemName = line.substr(0, pos);
//std::cout << itemName << std::endl;
line.erase(0, pos + delimiter.length());
pos = line.find(delimiter);
string prices = line.substr(0, pos);
//std::cout << prices <<"end"<< std::endl;
int price = stoi(prices);
//cout<< price<<itemName<<endl;
myVec.push_back(make_pair(price, itemName));
}
//int left = 0, right = myVec.size() - 1;
int diff = credits + 1;
int finalLeft, finalRight;
int finalI = 0 ;
for (int i = 0; i < myVec.size() - 2; i++)
{
int left = i + 1;
int right = myVec.size()-1;
while (left < right)
{
int triSum = myVec[i].first + myVec[left].first + myVec[right].first;
if (triSum <= credits)
{
if (credits - triSum < diff)
{
diff = credits - triSum;
finalI = i;
finalLeft = left;
finalRight = right;
}
left++;
}
else
{
right--;
}
}
}
if (diff > credits)
cout << "Not possible" << endl;
else
{
cout << myVec[finalI].first << myVec[finalI].second << endl;
cout << myVec[finalLeft].first << myVec[finalLeft].second << endl;
cout << myVec[finalRight].first << myVec[finalRight].second << endl;
}
return 0;
} | true |
d3db7f16cb20b8e764e80a12297586f9186467c2 | C++ | germandiagogomez/the-cpp-abstraction-penalty | /benchmarks/skip-01-sieve/ranges_sieve.cpp | UTF-8 | 2,398 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <algorithm>
#include <string>
#include <bitset>
#include <vector>
#include <chrono>
#include <iostream>
#include <tuple>
#include "range/v3/view/iota.hpp"
#include "range/v3/view/stride.hpp"
#include "range/v3/view/filter.hpp"
#include "range/v3/view/take.hpp"
#include "range/v3/algorithm/for_each.hpp"
#include "range/v3/range_for.hpp"
#include "util/benchutil.hpp"
namespace v = ranges::view;
namespace a = ranges::action;
namespace r = ranges;
namespace c = std::chrono;
/** Sieve table for the first UpToNumber natural numbers */
template <std::size_t UpToNumber>
class sieve_table {
public:
void set(std::size_t nat_number, bool value = true) noexcept {
repr_.set((nat_number / 2) - 1, value);
}
constexpr std::size_t size() const noexcept {
return repr_.size();
}
private:
std::bitset<(UpToNumber/2) - 1> repr_;
};
constexpr std::size_t ct_sqrt(std::size_t n, std::size_t i = 1) noexcept {
return n == i ? n : (i * i < n ? ct_sqrt(n, i + 1) : i);
}
template <std::size_t NatNumber>
auto mark_sieve_for_number(int current_number) noexcept {
std::size_t sieve_start = current_number * current_number;
std::size_t step_size = 2 * current_number;
std::size_t sieve_end = NatNumber + 1;
return
v::stride(v::ints(sieve_start, sieve_end), step_size) |
v::filter([current_number](int i) {
return i % current_number == 0;
});
}
template <std::size_t NatNumber>
sieve_table<NatNumber> execute_sieve() noexcept {
sieve_table<NatNumber> table{};
r::for_each(v::stride(v::ints((std::size_t)3u, ct_sqrt(NatNumber)), 2),
[&table](auto i) {
RANGES_FOR(auto i, mark_sieve_for_number<NatNumber>(i))
table.set(i);
});
return table;
}
int main(int argc, char * argv[]) {
using namespace std;
using namespace benchmarks::util;
int times_exe = std::stoi(argv[1]);
std::vector<std::chrono::milliseconds> times;
times.reserve(times_exe);
for (int i = 0; i < times_exe; ++i) {
c::milliseconds total_time;
std::tie(total_time, std::ignore) =
time_it_milliseconds([] { return execute_sieve<100'000'000u>(); });
times.push_back(total_time);
}
sort(begin(times), end(times));
std::cout << times[times.size()/2].count() << ' ';
}
| true |
7b990fb1a06064701578aac39aac2c942bc2e869 | C++ | shubham-shinde/code_library | /Check bipartite (by coloring)/main.cpp | UTF-8 | 1,721 | 2.75 | 3 | [
"Unlicense"
] | permissive | #include <bits/stdc++.h>
#define N 2010
#define endl '\n'
using namespace std;
vector <vector <int> >G(N);
int color[N];
bool checkbipartite(int s)
{
queue <int>q;
q.push(s);
color[s]=1;
while(!q.empty())
{
int u=q.front();
//cout<<u<<" "<<color[u]<<endl;
q.pop();
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(color[v]==-1)
{
color[v]=1-color[u];
q.push(v);
}
else
{
if(color[u]==color[v])
return false;
}
}
}
return true;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t,tt=1;
cin>>t;
while(t--)
{
int n;//number of nodes
int m;//number of edges
cin>>n>>m;
int s;
for(int i=1;i<=m;i++)
{
int u,v;
s=u;
cin>>u>>v;
G[u].push_back(v);
G[v].push_back(u);
}
for(int i=1;i<=n;i++)
color[i]=-1;
bool f=1;
for(int i=1;i<=n;i++)
{
if(color[i]==-1)
{
f=f*checkbipartite(i);
}
}
// for(int i=1;i<=n;i++)
// cout<<color[i]<<" ";
// cout<<endl;
cout<<"Scenario #"<<(tt++)<<":"<<endl;
if(f)
cout<<"No suspicious bugs found!"<<endl;
else
cout<<"Suspicious bugs found!"<<endl;
//cout<<checkbipartite(s)<<endl;
for(int i=0;i<N;i++)G[i].clear();
}
return 0;
}
| true |
b93915fdf3fbf2a49048a5734f921a9ccee5e754 | C++ | Boussau/Genqual | /HDPP/SiteLikes.h | UTF-8 | 1,306 | 2.53125 | 3 | [] | no_license | #ifndef SiteLikes_H
#define SiteLikes_H
class Parm;
class SiteModels;
class SiteInfo {
public:
SiteInfo(void);
int getActiveState(void) { return activeLike; }
double getActiveLike(void) { return like[activeLike]; }
double getLike(int i) { return like[i]; }
double getLnLikeDiff(void) { return like[activeLike] - like[flip(activeLike)]; }
int flip(int x);
void flipActiveLike(void) { (activeLike == 0 ? activeLike = 1 : activeLike = 0); }
void setActiveLike(double x) { like[activeLike] = x; }
private:
int activeLike;
double like[2];
};
class SiteLikes {
public:
SiteLikes(int n);
~SiteLikes(void);
void flipActiveLikeForSites(std::vector<int>& affectedSites);
void flipActiveLikeForSitesSharingParm(Parm* p, SiteModels* sm, int parmType);
double getActiveLike(int siteIdx) { return siteInfo[siteIdx].getActiveLike(); }
double getActiveLike(void);
double getLnDiff(int siteIdx) { return siteInfo[siteIdx].getLnLikeDiff(); }
void print(void);
void setActiveLike(int siteIdx, double x) { siteInfo[siteIdx].setActiveLike(x); }
private:
int numSites;
SiteInfo* siteInfo;
};
#endif | true |