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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c145c9452ddfffa903ccf0a9911227fc1488dc27 | C++ | fuhailin/show-me-cpp-code | /leetcode_cc/131.palindrome-partitioning.cc | UTF-8 | 1,073 | 3.03125 | 3 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
private:
vector<vector<int>> dp;
vector<vector<string>> res;
vector<string> path;
int n;
public:
void backtracking(const string& s, int i) {
if (i == n) {
res.emplace_back(path);
return;
}
for (int j = i; j < n; ++j) {
if (!dp[i][j]) continue;
path.emplace_back(s.substr(i, j - i + 1));
backtracking(s, j + 1);
path.pop_back();
}
}
vector<vector<string>> partition(string s) {
n = s.size();
dp.assign(n, vector<int>(n, true));
for (int i = n - 1; i >= 0; --i) {
for (int j = i + 1; j < n; ++j) {
dp[i][j] = (s[i] == s[j]) && dp[i + 1][j - 1];
}
}
backtracking(s, 0);
return res;
}
};
int main(int argc, char const* argv[]) {
Solution so;
string test = "aba";
bool res = so.isPalindrome(test);
cout << "res: " << res << endl;
}
| true |
9c6619c2221678506cdcf7fa789280492746d6cb | C++ | ZRobbins7/C-Projects | /Assignments/Assignment3/RobbinsAsg3/RobbinsAsg3P3.cpp | UTF-8 | 2,695 | 3.484375 | 3 | [] | no_license | /*
Zac Robbins
zrobbins@my.athens.edu
00100125
Asg3P3 - CS317
*/
// This program creates a receipt for the customer at Ying Thai Kitchen.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
int main()
{
string server, date = "7/4/2013", time = "7:28 PM";
string foodItem1 = "44 Ginger Lover";
string flavor = "[pork][2**]";
string foodItem2 = "Brown Rice";
const double TAX_RATE = 9.48;
const double GINGER_LOVER_PRICE = 9.50;
const double BROWN_RICE_PRICE = 2.00;
double total, tax, grandTotal;
double fifteenPercent = 0.15, eighteenPercent = 0.18, twentyPercent = 0.20;
int tableNumber, itemsOrdered = 2, orderNumber = rand();
cout << "Please enter the name of your server: " << endl;
cin >> server;
cout << "Please enter your table number: " << endl;
cin >> tableNumber;
total = GINGER_LOVER_PRICE + BROWN_RICE_PRICE;
tax = total * (TAX_RATE / 100);
grandTotal = total + tax;
cout << "\n\n\n";
cout << setprecision(2) << fixed << showpoint;
cout << setw(28) << "Ying Thai Kitchen" << endl << setw(30) << "2220 Queen Anne AVE N" << endl;
cout << setw(28) << "Seattle WA 98109" << endl;
cout << " Tel. (206) 285-8424 Fax. (206) 285-8427" << endl;
cout << setw(31) << "www.yingthaikitchen.com" << endl;
cout << "Welcome to Ying Thai Kitchen Restaurant." << endl << endl;
cout << "Order#: " << left << setw(20) << orderNumber << right << setw(12) << "Table " << tableNumber << endl;
cout << "Date: " << date << " " << time << endl;
cout << "Server: " << left << setw(20) << server << right << setw(13) << " (T.4)" << endl;
cout << "------------------------------------------" << endl;
cout << left << setw(20) << foodItem1 << right << setw(17) << "$" << GINGER_LOVER_PRICE << endl;
cout << flavor << endl;
cout << left << setw(20) << foodItem2 << right << setw(17) << "$" << BROWN_RICE_PRICE << endl;
cout << "------------------------------------------" << endl;
cout << "Total " << itemsOrdered << left << setw(14) << " item(s)" << right << setw(15) << "$" << total << endl;
cout << left << setw(20) << "Sales Tax" << right << setw(17) << "$" << tax << endl;
cout << "------------------------------------------" << endl;
cout << "------------------------------------------" << endl;
cout << left << setw(20) << "Grand Total" << right << setw(16) << "$" << grandTotal << endl << endl;
cout << "Tip Guide" << endl;
cout << "15% = $" << (grandTotal * fifteenPercent) << "," << setw(10) << "18% = $" << (grandTotal * eighteenPercent) << ",";
cout << setw(10) << "20% = $" << (grandTotal * twentyPercent) << endl << endl;
cout << setw(30) << "Thank you very much." << endl << setw(27) << "Come back again";
return 0;
} | true |
36353861c126d44896561b3e76dba8cdaf5f6dc4 | C++ | bigsuperfa/MPI_3DCompact | /src/PngWriter.hpp | UTF-8 | 9,479 | 2.609375 | 3 | [
"MIT"
] | permissive | #ifndef PNG_WRITER_HPP
#define PNG_WRITER_HPP
// ======================================================================
// PngWriter.hpp
//
// This class can write a png image using libpng routines (i.e. png.h).
//
// Sample usage:
//
// PngWriter png(nx,ny);
//
// // then one or more calls to...
//
// png.set(i, j, red, green, blue); // 0 <= red,green,blue <= 255
//
// png.write("myfile.png");
//
// // at this point you can change the image and write again...
//
// png.set(i, j, red, green, blue);
//
// png.write("myfile2.png");
//
//
// History:
// authors: Frank Ham & Phuc Quang - July 2013
// ======================================================================
// ======================================================================
// Copyright (c) 2013 Frank Ham and Phuc Quang
//
// License: MIT (http://opensource.org/licenses/MIT)
//
// use for any purpose, commercial or otherwise.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ======================================================================
#include <png.h>
#include "CurvilinearInterpolator.hpp"
#include "AbstractCSolver.hpp"
class PngWriter {
public:
int mpiRank;
unsigned char (*buffer)[3]; // 0 <= r,g,b < 255
int nx,ny;
int dumpInterval;
double *fieldPtr;
string varName;
int planeInd;
double fraction;
double x_min[3], x_max[3];
bool bboxFlag;
bool interpolatorFlag;
CurvilinearInterpolator *ci;
bool valFlag;
double valMax, valMin;
string timeStepString;
enum Colormap {GREYSCALE,
RAINBOW,
BWR};
Colormap cm;
//General constructor w/ floating value bounds
PngWriter(int dumpInterval, const int width, const int height, double *fieldPtr, string varName, int planeInd, double fraction, Colormap cm){
nx = width;
ny = height;
buffer = new unsigned char[nx*ny][3];
// fill buffer with a "nice" cyan [73,175,205] -- eventually a designer should choose this ;)
for (int i = 0; i < nx*ny; ++i) {
buffer[i][0] = 73;
buffer[i][1] = 175;
buffer[i][2] = 205;
}
this->cm = cm;
this->fieldPtr = fieldPtr;
this->varName = varName;
this->planeInd = planeInd;
this->fraction = fraction;
interpolatorFlag = false;
ci = NULL;
valFlag = false;
valMax = 0.0;
valMin = 0.0;
bboxFlag = false;
this->dumpInterval = dumpInterval;
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
}
//Constructor for fixed value bounds
PngWriter(int dumpInterval, const int width, const int height, double *fieldPtr, string varName, int planeInd, double fraction, double valMin, double valMax, Colormap cm){
nx = width;
ny = height;
buffer = new unsigned char[nx*ny][3];
// fill buffer with a "nice" cyan [73,175,205] -- eventually a designer should choose this ;)
for (int i = 0; i < nx*ny; ++i) {
buffer[i][0] = 73;
buffer[i][1] = 175;
buffer[i][2] = 205;
}
this->fieldPtr = fieldPtr;
this->varName = varName;
this->planeInd = planeInd;
this->fraction = fraction;
this->cm = cm;
interpolatorFlag = false;
ci = NULL;
valFlag = true;
this->valMax = valMax;
this->valMin = valMin;
bboxFlag = false;
this->dumpInterval = dumpInterval;
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
}
//Constructor for fixed value bounds and fixed bounds
PngWriter(int dumpInterval, const int width, const int height, double *fieldPtr, string varName, int planeInd, double fraction, double valMin, double valMax, double x_min[3], double x_max[3], Colormap cm){
nx = width;
ny = height;
buffer = new unsigned char[nx*ny][3];
// fill buffer with a "nice" cyan [73,175,205] -- eventually a designer should choose this ;)
for (int i = 0; i < nx*ny; ++i) {
buffer[i][0] = 73;
buffer[i][1] = 175;
buffer[i][2] = 205;
}
this->fieldPtr = fieldPtr;
this->varName = varName;
this->planeInd = planeInd;
this->fraction = fraction;
this->cm = cm;
interpolatorFlag = false;
ci = NULL;
valFlag = true;
this->valMax = valMax;
this->valMin = valMin;
this->dumpInterval = dumpInterval;
bboxFlag = true;
for(int ip = 0; ip < 3; ip++){
this->x_min[ip] = x_min[ip];
this->x_max[ip] = x_max[ip];
}
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
}
~PngWriter() {
delete[] buffer;
}
void set(const int i,const int j,const unsigned char r,const unsigned char g,const unsigned char b) {
// recall that for png files, the pixels are ordered from the top left, so modify
// this set routine's passed j so that zero is at the bottom left...
buffer[(ny-j-1)*nx+i][0] = r;
buffer[(ny-j-1)*nx+i][1] = g;
buffer[(ny-j-1)*nx+i][2] = b;
}
void write(const char * filename) {
// note: we completely skip any error handling treatment here for simplicity.
FILE * fp = fopen(filename,"wb");
if (!fp) {
std::cout << "Warning: could not open png file: " << filename << std::endl;
return;
}
png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING,
(png_voidp)NULL,NULL,NULL);
if (!png_ptr) {
fclose(fp);
std::cout << "Warning: could not create png_ptr" << std::endl;
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
png_destroy_write_struct(&png_ptr,(png_infopp)NULL);
std::cout << "Warning: could not create info_ptr" << std::endl;
return;
}
png_init_io(png_ptr, fp);
png_set_IHDR(png_ptr, info_ptr,
nx, ny, // width, height
8, // bits per pixel -- 16 does not work with blockbuster
PNG_COLOR_TYPE_RGB, // non-alpha options are PNG_COLOR_TYPE_RGB,PNG_COLOR_TYPE_GRAY,
PNG_INTERLACE_NONE,
PNG_COMPRESSION_TYPE_DEFAULT,
PNG_FILTER_TYPE_DEFAULT);
// Some bits per pixel notes: 16 does not work with blockbuster, and there are also
// issues with PNG_COLOR_TYPE_GRAY interpretation, so stick to 8 and PNG_COLOR_TYPE_RGB
// for now. Note that if you do use 16, pay attention to MSB/LSB order. Endian is
// flipped on my linux workstation...
png_write_info(png_ptr, info_ptr);
// set up row pointers to point into the raw image data in buffer...
png_byte * row_pointers[ny];
for (int i = 0; i < ny; ++i)
row_pointers[i] = (png_byte*)(buffer + i*nx);
png_write_image(png_ptr, row_pointers);
png_write_end(png_ptr, NULL);
png_destroy_write_struct(&png_ptr, &info_ptr);
fclose(fp);
// leave the image data in buffer to allow the calling process to change it and/or
// write another image. It is deleted in the destructor.
}
void getRainbowColormap(double f, int &r, int &g, int &b){
int r_map[5] = {0, 0, 0, 255, 255};
int g_map[5] = {0, 255, 255, 255, 0};
int b_map[5] = {255, 255, 0, 0, 0};
int chunk = (int) floor(f/0.2500001);
double interp = (f-0.2500001*(double)chunk)/0.2500001;
r = (int) ( (1.0-interp)*r_map[chunk] + interp*r_map[chunk+1]);
g = (int) ( (1.0-interp)*g_map[chunk] + interp*g_map[chunk+1]);
b = (int) ( (1.0-interp)*b_map[chunk] + interp*b_map[chunk+1]);
}
void getPARAVIEW_BWR(double f, int &r, int &g, int &b){
double r_mapf[33] = {0.07514311, 0.247872569, 0.339526309, 0.409505078, 0.468487184, 0.520796675, 0.568724526, 0.613686735, \
0.656658579, 0.698372844, 0.739424025, 0.780330104, 0.821573924, 0.863634967, 0.907017747, 0.936129275, \
0.943467973, 0.990146732, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.961891484, 0.916482116};
;
double g_mapf[33] = {0.468049805, 0.498782363, 0.528909511, 0.558608486, 0.588057293, 0.617435078, 0.646924167, 0.676713218, \
0.707001303, 0.738002964, 0.769954435, 0.803121429, 0.837809045, 0.874374691, 0.913245283, 0.938743558, \
0.943498599, 0.928791426, 0.88332677, 0.833985467, 0.788626485, 0.746206642, 0.70590052, 0.667019783, \
0.6289553, 0.591130233, 0.552955184, 0.513776083, 0.472800903, 0.428977855, 0.380759558, 0.313155629, 0.236630659};
double b_mapf[33] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0.983038586, 0.943398095, 0.917447482, 0.861943246, 0.803839606, \
0.750707739, 0.701389973, 0.654994046, 0.610806959, 0.568237474, 0.526775617, 0.485962266, 0.445364274, \
0.404551679, 0.363073592, 0.320428137, 0.265499262, 0.209939162};
;
int r_map[33], g_map[33], b_map[33];
for(int i = 0; i < 33; i++){
r_map[i] = (int)(255.0*r_mapf[i]);
g_map[i] = (int)(255.0*g_mapf[i]);
b_map[i] = (int)(255.0*b_mapf[i]);
}
double dd = 0.031250001;
int chunk = (int) floor(f/dd);
double interp = (f-dd*(double)chunk)/dd;
r = (int) ( (1.0-interp)*r_map[chunk] + interp*r_map[chunk+1]);
g = (int) ( (1.0-interp)*g_map[chunk] + interp*g_map[chunk+1]);
b = (int) ( (1.0-interp)*b_map[chunk] + interp*b_map[chunk+1]);
}
};
#endif
| true |
3237fc16cdfae8988497682aee2891dd9ffc6023 | C++ | ShadowBLR/OAIP-1-course | /Вариант 7/sem2laba2/sem2laba2/sem2laba2.cpp | UTF-8 | 826 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int mn(int n, ...);
void diht(double (*f)(double));
double f1(double x);
double f2(double x);
int main()
{/**/
setlocale(LC_ALL, "ru");
cout << mn(4,15,3,14,29) << endl;
cout << mn(2,13,4) << endl;
cout << mn(5,12,13,14,2,4) << endl;
/*2--------------------------------------------
x3 + 2x – 4
x2 – 1*/
diht(f1);
diht(f2);
}
void diht(double (*f)(double))
{
double a, b, c, e = 0.001;
a = 0;
cin >> b;
while (b - a > e) {
c = (a + b) / 2;
if (f(b) * f(c) < 0)
a = c;
else
b = c;
}
cout << (a + b) / 2 << endl;
return ;
}
double f1(double x)
{
return pow(x, 3) + x * x - 4;
}
double f2(double x)
{
return x * x - 1;
}
int mn(int n, ...)
{
int *p = &n;
int min = *(++p);
for (int i = 1; i <= n; i++)
if (min > p[i])
min = p[i];
return min;
}
| true |
22ee74fdaf1353d971980404bebdc43f2f830373 | C++ | whyshivam/CppCode | /CodeForces/479C.cpp | UTF-8 | 937 | 2.609375 | 3 | [] | no_license | //Cut my wings and ask me to fly,
//to your astonishment I'll be lost in the sky
#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long int
#define ll long long int
#define fast() ios_base::sync_with_stdio(false); cin.tie(NULL);
#define rep(n) for(ll i=0;i<n;i++)
#define repj(n) for(ll j=;j<n;j++)
#define MAX INT_MAX
#define MOD 1000000007
#define cint ll t;for(cin>>t;t>0;t--)
#define f first
#define s second
#define pb push_back
#define mk make_pair
#define ex "\n"
struct date{
ll a,b;
};
bool fn(date k, date j){
if(k.a==j.a)
return(k.b<j.b);
return (k.a<j.a);
}
int main(){
ios_base::sync_with_stdio(0), cin.tie(0);
ll n;
cin>>n;
vector<date> date(n);
rep(n){
cin>>date[i].a>>date[i].b;
}
sort(date.begin(),date.end(),fn);
int currdate=0;
rep(n){
if(currdate>date[i].b){
currdate=date[i].a;
}else{
currdate=date[i].b;
}
}
cout<<currdate<<"\n";
}
| true |
763b3aabbd45a40d16fb04ffa719ba8327870391 | C++ | aman-aman/Leetcode | /628. Maximum Product of Three Numbers.cpp | UTF-8 | 239 | 2.71875 | 3 | [] | no_license | class Solution {
public:
int maximumProduct(vector<int>& nums)
{
sort(nums.begin(),nums.end(),greater<int>());
return max(nums[0]*nums[nums.size()-1]*nums[nums.size()-2],nums[0]*nums[1]*nums[2]);
}
};
| true |
5b5d99b6884de034c95aa4d3634e0f0bf4614217 | C++ | 42seoul-NULL/Webserv_ | /libft_cpp/ft_memset.cpp | UTF-8 | 177 | 2.6875 | 3 | [] | no_license | #include "libft.hpp"
void *ft_memset(void *s, int c, size_t n)
{
unsigned char *temp;
temp = (unsigned char *)s;
while (n--)
*(temp++) = (unsigned char)c;
return (s);
}
| true |
1cd8986a9feaee70ca10dbd3d05202a757706551 | C++ | blackjack-nix/monix | /src/Server/MongoWrapper.cpp | UTF-8 | 2,085 | 3.125 | 3 | [] | no_license | #include "MongoWrapper.h"
Mongo& MongoWrapper::database(){
static Mongo database;
return database;
}
std::string MongoWrapper::addUser(std::vector<std::string> parameter){
std::string pseudo(parameter[0]);
float money = std::stof(parameter[1]);
database().addUser(pseudo, money);
return "";
}
std::string MongoWrapper::removeUser(std::vector<std::string> parameter){
std::string pseudo(parameter[0]);
database().removeUser(pseudo);
return "";
}
std::string MongoWrapper::renameUser(std::vector<std::string> parameter){
std::string oldPseudo(parameter[0]);
std::string newPseudo(parameter[1]);
database().renameUser(oldPseudo, newPseudo);
return "";
}
std::string MongoWrapper::setUserBalance(std::vector<std::string> parameter){
std::string pseudo(parameter[0]);
float money = std::stof(parameter[1]);
database().setUserBalance(pseudo, money);
return "";
}
std::string MongoWrapper::incUserBalance(std::vector<std::string> parameter){
std::string pseudo(parameter[0]);
float money = std::stof(parameter[1]);
database().incUserBalance(pseudo, money);
return "";
}
std::string MongoWrapper::decUserBalance(std::vector<std::string> parameter){
std::string pseudo(parameter[0]);
float money = std::stof(parameter[1]);
database().decUserBalance(pseudo, money);
return "";
}
std::string MongoWrapper::incUserBalanceByOne(std::vector<std::string> parameter){
std::string pseudo(parameter[0]);
database().incUserBalanceByOne(pseudo);
return "";
}
std::string MongoWrapper::decUserBalanceByOne(std::vector<std::string> parameter){
std::string pseudo(parameter[0]);
database().decUserBalanceByOne(pseudo);
return "";
}
std::string MongoWrapper::displayMembers(std::vector<std::string> parameter){
std::string response = database().displayMembers();
return response;
}
std::string MongoWrapper::displaySum(std::vector<std::string> parameter){
database().displaySum();
return "";
}
std::string MongoWrapper::getUserBalance(std::vector<std::string> parameter){
float money = database().getUserBalance(parameter[0]);
return std::to_string(money);
}
| true |
2d78a5ce4b25941fe15b96941e9e06c18ca35d42 | C++ | pantzerbrendan/INF34207_TP3 | /tests/main2.cpp | UTF-8 | 781 | 2.9375 | 3 | [] | no_license |
#include <vector>
#include <iostream>
#include "../include/Thread.hpp"
#include "../include/Mutex.hpp"
#include "../include/IThreadable.hpp"
Mutex *mtx;
void *function(void *args)
{
long long sig1 = reinterpret_cast<long long>(args);
int sig = static_cast<int>(sig1);
for (int index = 0; index < 10; index++)
{
mtx->lock();
std::cout << sig << " : " << index << std::endl;
mtx->unlock();
}
return (NULL);
}
int main(int ac, char **av)
{
std::vector<Thread *> threads;
mtx = new Mutex();
mtx->init();
for (int i = 0; i < 5; i++)
threads.push_back(new Thread());
for (int i = 0; i < 5; i++)
threads[i]->create(function, (void*)i);
for (int i = 0; i < 5; i++)
threads[i]->join();
threads.clear();
return (0);
}
| true |
a83a95a24bb20e6784e47da103efba31dec02419 | C++ | madeibao/PythonAlgorithm | /PartC/交换数字中的两个位置来实现数字最大化.cpp | UTF-8 | 487 | 3.296875 | 3 | [] | no_license |
class Solution {
public:
int maximumSwap(int num) {
string a = to_string(num);
int res = num;
for(int i=0; i<a.size(); i++){
for(int j=i+1; j<a.size(); j++){
swap(a[i], a[j]);
res = max(res, stoi(a));
swap(a[i], a[j]);
}
}
return res;
}
};
int main(int argc, char* argv[]) {
int num = 2732;
Solution s;
cout<<s.maximumSwap(num)<<endl;
return 0;
} | true |
bfb6c1e753fea8649f5ba52434c08e5174f71b27 | C++ | Sakery/CLK | /Machines/Oric/BD500.cpp | UTF-8 | 3,602 | 2.78125 | 3 | [
"MIT"
] | permissive | //
// BD500.cpp
// Clock Signal
//
// Created by Thomas Harte on 14/01/2020.
// Copyright © 2020 Thomas Harte. All rights reserved.
//
#include "BD500.hpp"
using namespace Oric;
BD500::BD500() : DiskController(P1793, 9000000, Storage::Disk::Drive::ReadyType::ShugartModifiedRDY) {
disable_basic_rom_ = true;
select_paged_item();
set_is_double_density(true);
}
void BD500::write(int address, uint8_t value) {
access(address);
if(address >= 0x0320 && address <= 0x0323) {
// if(address == 0x320) printf("Command %02x\n", value);
WD::WD1770::write(address, value);
}
}
uint8_t BD500::read(int address) {
access(address);
switch(address) {
default: return 0xff;
case 0x0320: case 0x0321: case 0x0322: case 0x0323:
return WD::WD1770::read(address);
case 0x312: return (get_data_request_line() ? 0x80 : 0x00) | (get_interrupt_request_line() ? 0x40 : 0x00);
}
}
void BD500::access(int address) {
// Determine whether to perform a command.
switch(address) {
case 0x0320: case 0x0321: case 0x0322: case 0x0323: case 0x0312:
return;
case 0x310: enable_overlay_ram_ = true; break;
case 0x313: enable_overlay_ram_ = false; break;
case 0x317: disable_basic_rom_ = false; break; // Could be 0x311.
default:
// printf("Switch %04x???\n", address);
break;
}
select_paged_item();
}
/*
The following was used when trying to find appropriate soft switch locations. It is preserved
as the values I have above are unlikely to be wholly correct and further research might be
desirable.
void BD500::access(int address) {
// 0,1,4,5,10,11 -> 64kb Atmos
// 2,3,9 -> 56kb Atmos.
// Broken: 6, 7, 8
int order = 5;
int commands[4];
std::vector<int> available_commands = {0, 1, 2, 3};
const int modulos[] = {6, 2, 1, 1};
for(int c = 0; c < 4; ++c) {
const int index = order / modulos[c];
commands[c] = available_commands[size_t(index)];
available_commands.erase(available_commands.begin() + index);
order %= modulos[c];
}
// Determine whether to perform a command.
int index = -1;
switch(address) {
case 0x0320: case 0x0321: case 0x0322: case 0x0323: case 0x0312:
return;
case 0x310: index = 0; break;
case 0x313: index = 1; break;
case 0x314: index = 2; break;
case 0x317: index = 3; break;
default:
printf("Switch %04x???\n", address);
break;
}
select_paged_item();
if(index >= 0) {
switch(commands[index]) {
case 0: enable_overlay_ram_ = true; break; // +RAM
case 1: disable_basic_rom_ = false; break; // -rom
case 2: disable_basic_rom_ = true; break; // +rom
case 3: enable_overlay_ram_ = false; break; // -RAM
}
select_paged_item();
}
}
*/
void BD500::set_head_load_request(bool head_load) {
// Turn all motors on or off; if off then unload the head instantly.
is_loading_head_ |= head_load;
for(auto &drive : drives_) {
if(drive) drive->set_motor_on(head_load);
}
if(!head_load) set_head_loaded(false);
}
void BD500::run_for(const Cycles cycles) {
// If a head load is in progress and the selected drive is now ready,
// declare head loaded.
if(is_loading_head_ && drives_[selected_drive_] && drives_[selected_drive_]->get_is_ready()) {
set_head_loaded(true);
is_loading_head_ = false;
}
WD::WD1770::run_for(cycles);
}
void BD500::set_activity_observer(Activity::Observer *observer) {
observer_ = observer;
if(observer) {
observer->register_led("BD-500");
observer_->set_led_status("BD-500", get_head_loaded());
}
}
void BD500::set_head_loaded(bool loaded) {
WD::WD1770::set_head_loaded(loaded);
if(observer_) {
observer_->set_led_status("BD-500", loaded);
}
}
| true |
12e0c6858201e4f10250f590410bfd1afcb9dff2 | C++ | calofmijuck/BOJ | /Data Structures/splay_tree.cpp | UTF-8 | 3,433 | 3.515625 | 4 | [] | no_license |
#include <bits/stdc++.h>
using namespace std;
template <typename T>
class node {
public:
node *left, *right, *parent;
T value;
int size;
node(void) : left(0), right(0), parent(0), size(0) {}
node(const T &value) : left(0), right(0), parent(0), value(value), size(0) {}
};
template <typename T>
class splay_tree {
node<T> *root;
public:
void update(node<T> *target) {
target->size = 1;
if (target->left) {
target->size += target->left->size;
}
if (target->right) {
target->size += target->right->size;
}
}
void rotate(node<T> *target) {
node<T> *parent = target->parent;
node<T> *subtree;
if (target == parent->left) { // zig
parent->left = subtree = target->right;
target->right = parent;
} else { // zag
parent->right = subtree = target->left;
target->left = parent;
}
if (subtree) {
subtree->parent = parent;
}
target->parent = parent->parent;
parent->parent = target;
if (target->parent) {
if (parent == target->parent->left) {
target->parent->left = target;
} else {
target->parent->right = target;
}
} else {
root = target;
}
update(parent);
update(target);
}
void splay(node<T> *target) {
while (target->parent) {
node<T> *parent = target->parent, *grandparent = parent->parent;
if (grandparent) {
if ((grandparent->left == parent) == (parent->left == target)) { // zig-zig or zag-zag
rotate(parent);
} else { // zig-zag or zag-zig
rotate(target);
}
}
rotate(target);
}
}
void splay_kth(int k) {
node<T> *target = root;
while (true) {
while (target->left && target->left->size > k) {
target = target->left;
}
if (target->left) {
k -= target->left->size;
}
if (k == 0) {
break;
}
k--;
target = target->right;
}
splay(target);
}
void splay_interval(int left, int right) {
splay_kth(left - 1);
node<T> *tmp = root;
root = root->right;
root->parent = nullptr;
splay_kth(right - left + 1);
tmp->right = root;
root->parent = tmp;
root = tmp;
}
void init(string &s) {
int n = s.size();
node<T> *new_node = new node('\0');
new_node->size = n + 2;
root = new_node;
for (int i = 0; i <= n; i++) {
new_node->right = new node(s[i]);
new_node->right->parent = new_node;
new_node = new_node->right;
new_node->size = n + 1 - i;
}
}
void query() {
// implement
}
void inorder() {
if (root) {
inorder(root);
}
cout << '\n';
}
void inorder(node<T> *target) {
if (target->left) {
inorder(target->left);
}
cout << target->value << ' ';
if (target->right) {
inorder(target->right);
}
}
};
int main() {
// implement
}
| true |
bb42bc9dd5fe30eb63fd95b88092a070c1726c41 | C++ | kymo/hmmseg | /include/trie.h | UTF-8 | 2,613 | 2.609375 | 3 | [] | no_license | // Copyright (C) 2010, 2011, 2012, 2013, 2014, 2015 Aron
// contact: kymowind@gmail.com www.idiotaron.org
//
// This file is part of hmmseg
//
// hmmseg is a segmentation module conbined hidden markov model with
// maximum match segmentation, you can redistribute it and modify it
// under the term of the GNU Genural Public License as published by
// the free software Foundation, either version of 3 of the Lisence
//
// In the project of hmmseg, we use the trie tree to store the dict
// so as to reduce the memory which speed up the search for word in
//
// trie.h: the definiton of the tree
#ifndef __TRIE_H_
#define __TRIE_H_
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>
namespace hmmseg {
namespace trie {
class Trie {
private:
Trie* _root;
std::map<std::string, Trie*> _child_trees;
// brief : build a trie tree from the dict
// param :
// trie : a trie object
// words : a vector stored the ch words
// cur : the index of current word
// return :
// None
void build_tree(Trie *&trie, const std::vector<std::string> &words, int cur);
public:
bool _is_string_node;
std::string _word;
Trie() : _is_string_node(false) {}
Trie(std::string word) : _word(word), _is_string_node(false) {}
// display trees
void display(Trie *&trie);
// brief : given the string, find out all the possible segment result
// Param :
// str string stored all the results
// results vector stored the results
// return :
// None
bool find_all_results(std::string &str,
std::vector<std::vector<std::string> > &results);
// brief : dfs seach
void dfs_search(int i, int j,
const std::vector<std::string> &words,
std::vector<std::string> &temp_results,
std::vector<std::vector<std::string> > &results) ;
// brief : set the node status
void set_string_node(bool is_string_node);
// brief : load the dict to build a tree
// note : each word in a line which's decoding as UTF-8
// param :
// file_name : the dict file name
// return :
// false : load dict failed
// true : load dict successed
bool load_dict(const char* file_name);
// brief : simple segment method just using the maximum match strategy
// param :
// str : the string gona to be segmented
// return :
// None
void simple_seg(std::string &str);
// brief : search whether the current word is a child node of the
// current node thus judging whether to end the search
bool search(Trie * &tree, const std::vector<std::string> &word, int i, int j);
};
}
}
#endif
| true |
cad21300b6b785cb785a130a2f6c0bc8d5fa5f0f | C++ | MaxDerouet/learncpp | /9.2/1/main.cpp | UTF-8 | 1,735 | 3.84375 | 4 | [] | no_license | #include <iostream>
class Fraction
{
int m_nominator=0;
int m_denominator=1;
public:
Fraction(int nominator=0, int denominator=1):m_nominator(nominator), m_denominator(denominator)
{
}
friend Fraction operator*(const Fraction &firstFraction, const Fraction &secondFraction);
friend Fraction operator*(int value, const Fraction &fraction);
friend Fraction operator*(const Fraction &fraction, int value);
void reduce();
void print();
static int gcd(int a, int b)
{
return (b == 0) ? (a > 0 ? a : -a) : gcd(b, a % b);
}
};
Fraction operator*(const Fraction &firstFraction, const Fraction &secondFraction)
{
Fraction fraction((firstFraction.m_nominator*secondFraction.m_nominator),(firstFraction.m_denominator*secondFraction.m_denominator));
fraction.reduce();
return fraction;
}
Fraction operator*(int value, const Fraction &fraction)
{
Fraction temp((value*fraction.m_nominator),fraction.m_denominator);
temp.reduce();
return temp;
}
Fraction operator*(const Fraction &fraction, int value)
{
Fraction temp(value*fraction);
temp.reduce();
return temp;
}
void Fraction::reduce()
{
int greatestCommonDivisor(Fraction::gcd(m_nominator,m_denominator));
m_nominator/=greatestCommonDivisor;
m_denominator/=greatestCommonDivisor;
}
void Fraction::print()
{
std::cout << m_nominator << "/" << m_denominator << "\n";
}
int main()
{
Fraction f1(2, 5);
f1.print();
Fraction f2(3, 8);
f2.print();
Fraction f3 = f1 * f2;
f3.print();
Fraction f4 = f1 * 2;
f4.print();
Fraction f5 = 2 * f2;
f5.print();
Fraction f6 = Fraction(1, 2) * Fraction(2, 3) * Fraction(3, 4);
f6.print();
}
| true |
e6bf0a10bdb4ff755733b02fb82b23ec581f9ae7 | C++ | AlexMaz99/WDI | /lab2/zad01.cpp | UTF-8 | 525 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int number;
int tab[10000];
int a = 1, b = 1;
bool done = false;
cin >> number;
tab[0] = 1;
if (number == 1) done = true;
for (int i = 1; a + b <= number && !done; i++) {
b = a + b;
a = b - a;
tab[i] = b;
for (int j = i; j >= 0 && !done; j--) {
if (tab[j] * tab[i] == number) {
done = true;
}
}
}
if (done) cout << "YES";
else cout << "NO";
} | true |
b2c4adb14a48ce4cff5b6a6bc0529846411dd877 | C++ | NathanBeals/Escape-Room | /EscapeRoom/Source/EscapeRoom/NewToggleGroup.cpp | UTF-8 | 757 | 2.546875 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "NewToggleGroup.h"
void ANewToggleGroup::ToggleGroupVisibility(bool visible)
{
for (auto x : ActorsToHide)
if (x != nullptr)
x->SetActorHiddenInGame(!visible);
bIsVisibleInScene = visible;
}
// Sets default values
ANewToggleGroup::ANewToggleGroup()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ANewToggleGroup::BeginPlay()
{
Super::BeginPlay();
ToggleGroupVisibility(bIsVisibleInScene);
}
// Called every frame
void ANewToggleGroup::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
| true |
bf63fe00b1213237e319fc055dc217ab6d344e66 | C++ | SantiagoMunoz/raytracer | /src/world.cpp | UTF-8 | 1,825 | 2.78125 | 3 | [] | no_license | #include "world.h"
#include "ray.h"
#include "tuple.h"
#include "matrix.h"
#include <cmath>
#include <iterator>
void camera::render(world* w)
{
color illumination{0, 0, 0};
tuple horizontal_stride = rotate_y(PI/2)*dir;
tuple vertical_stride = rotate_x(-PI/2)*dir;
tuple origin = (pos + horizontal_stride*(screen->width/2) + vertical_stride*(screen->height/2)) - dir*depth;
tuple pixel_pos = origin;
tuple collision_point = origin;
for (int j=0; j < screen->height; j++) {
for (int i=0; i < screen->width; i++) {
pixel_pos = pos + vertical_stride*j + horizontal_stride*i;
ray r{origin, (pixel_pos - origin).unary(), 1};
screen->set_pixel(j, i, w->castRay(r));
}
}
}
color world::castRay(ray &r)
{
color result{0,0,0};
bool inShadow = false;
if(r.allowed_bounces < 0)
return result;
r.allowed_bounces--;
r.collide_with(&objects);
std::optional<intersection> collision = r.get_hit();
if (collision != std::nullopt) {
tuple collision_point = r.position(collision->t);
collision_point = collision_point + collision->obj->get_unary_normal_at(collision_point).direction*0.05;
collision_point.type = POINT;
inShadow = isPointInShadow(collision_point, lightsources[0]);
result = r.get_illumination(lightsources[0], inShadow);
//Reflections!
double ref = collision->obj->mat.reflectiveness;
if (ref > 0) {
tuple collision_normal = collision->obj->get_unary_normal_at(collision_point).direction;
r.origin= collision_point;
r.direction = r.get_reflected_direction(collision_normal);
result = result*(1 - ref) + castRay(r)*ref;
}
}
return result;
}
bool world::isPointInShadow(tuple point, light lightsource)
{
ray r(point, (lightsource.position - point).unary());
r.collide_with(&objects);
if (r.get_hit() != std::nullopt)
return true;
return false;
}
| true |
9c5f4c8054c64f9e276b267a9181b5a59b85d307 | C++ | MastProgs/MyAlgorithm | /Console/AlgorithmConsole/AlgorithmConsole/Fibonacci.cpp | UTF-8 | 537 | 3.6875 | 4 | [] | no_license | #include "Fibonacci.h"
#include <iostream>
Fibonacci::Fibonacci(size_t n)
: m_number{ n }
{
m_memo.reserve(n + 1);
m_memo.emplace_back(0);
m_memo.emplace_back(1);
m_memo.emplace_back(1);
GetValue(n);
}
size_t Fibonacci::GetValue(size_t n)
{
if (n < 3) { return 1; }
if (n < m_memo.size()) { return m_memo[n]; }
m_memo.emplace_back(GetValue(n - 1) + GetValue(n - 2));
return m_memo[n];
}
void Fibonacci::Print()
{
int i{ 0 };
for (auto& n : m_memo)
{
std::cout << "index[" << i << "] : " << n << std::endl;
++i;
}
}
| true |
09476bcd62dfa3e493ab47544166495a2ea8899f | C++ | rastabaddon/saphire | /saphire-memory/src/module/CMemoryBuffer.cpp | UTF-8 | 1,539 | 2.859375 | 3 | [] | no_license | /*
* CMemoryBuffer.cpp
*
* Created on: 14 mar 2015
* Author: rast
*/
#include "CMemoryBuffer.h"
namespace Saphire {
namespace Core {
namespace Types {
CMemoryBuffer::CMemoryBuffer(Saphire::Module::IMemoryModule * mm,Saphire::Core::Types::size size) {
this->mm = mm;
Grab(this->mm);
this->size = size;
memoryPointer = this->mm->allocate(size);
//printf("Create memory %X %u \n",memoryPointer,size);
if(!memoryPointer) { this->size = 0;
throw std::bad_alloc();
}
}
CMemoryBuffer::~CMemoryBuffer() {
//printf("Free memory %p %u \n",memoryPointer,(unsigned int)size);
this->size=0;
this->mm->deallocate(memoryPointer);
memoryPointer = NULL;
Free(mm);
}
void * CMemoryBuffer::getPointer(Saphire::Core::Types::size pos) {
//printf("MEM %u [%x] [%x] \n",pos,(void *)memoryPointer,(void *)(memoryPointer+((sizeof memoryPointer) * pos)));
//Return pointer with memory shift;
if(pos<0||pos>size) return memoryPointer;
//return (void *)(memoryPointer+((sizeof memoryPointer) * pos));
return(void *)(memoryPointer + pos);
}
Saphire::Core::Types::size CMemoryBuffer::getSize()
{
return this->size;
}
/**
* Reads a byte
*/
Saphire::Core::Types::u8 CMemoryBuffer::get(Saphire::Core::Types::size pos){
if(pos<0||pos>size) return 0;
return *(memoryPointer + pos);
}
/**
* Write a byte
*/
bool CMemoryBuffer::put(Saphire::Core::Types::size pos,Saphire::Core::Types::u8 _char){
if(pos<0||pos>size) return false;
return true;
}
} /* namespace Types */
} /* namespace Core */
} /* namespace Saphire */
| true |
47f25afac76fed3171d20fef6932e8bf548a12d1 | C++ | Koo12/exp_cpp | /lab4_2.cpp | UTF-8 | 561 | 3.6875 | 4 | [] | no_license | #include<iostream>
#include<string>
using namespace std;
const int SIZE=100;
template<class T>
class Stack
{
private:
T stack[SIZE];
int tos=0;
public:
void Push(T n)
{
stack[tos]=n;
tos++;
}
T Pop()
{
stack[tos]=0;
tos--;
}
int getTos()
{
return tos;
}
T * getStack()
{
return stack;
}
};
int main()
{
Stack<int> stack;
int a,b,c;
a=1;
b=2;
c=3;
stack.Push(a);
stack.Push(b);
stack.Push(c);
int number=stack.getTos();
for(int i=0;i<number;i++)
{
cout << stack.getStack()[i] << " ";
}
cout << endl;
return 0;
}
| true |
7daa3c30fbbfb81ad80e54b2a36c8a27618da911 | C++ | dnavas77/cpp-concepts | /DesignPatterns/DesignPatterns/src/MultipleBuilders/MultipleBuilders.cpp | UTF-8 | 473 | 2.65625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <boost/algorithm/string.hpp>
#include <sstream>
#include "Person.h"
#include "PersonBuilder.h"
#include "PersonAddressBuilder.h"
#include "PersonJobBuilder.h"
int main() {
Person p = Person::create()
.lives().at("999 Some Street")
.withPostCode("9889-777")
.works().at("Merck & Co")
.asA("Accountant")
.earning(444444);
std::cout << p << '\n';
std::cin.get();
return 0;
}
| true |
20919f9c8f59ff45f57181c77395fd535536a261 | C++ | liuguoxu/learning_module | /cpp_learn/static/static.cpp | UTF-8 | 642 | 4.0625 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Girl
{
public:
static int Num;
void set_info(string new_name, int new_age);
void show_info()
{
cout << "name is "<< this->name <<", age is "<< this->age<< endl;
}
Girl()
{
cout << "This is a new girl!" << endl;
}
~Girl()
{
cout << name << " is gone" << endl;
Num--;
}
static int get_num()
{
return Num;
}
private:
string name;
int age;
};
int Girl::Num = 0;
void Girl::set_info(string new_name, int new_age)
{
name = new_name;
age = new_age;
}
int main()
{
Girl lily;
lily.set_info("Lily", 17);
lily.show_info();
}
| true |
521c6cd9b848f5e5b6ad76ada98120fb7f5f9681 | C++ | bryant1410/bayesAB | /src/closedTests.cpp | UTF-8 | 808 | 2.78125 | 3 | [] | no_license | #include <Rcpp.h>
using namespace Rcpp;
double lbeta(double a, double b) {
return lgamma(a) + lgamma(b) - lgamma(a + b);
}
// [[Rcpp::export]]
double bayesPoissonTestClosed_(double alpha_1, double beta_1, double alpha_2, double beta_2) {
double total = 0;
for(int i = 0; i < alpha_1; i++) {
total += exp(i * log(beta_1) + alpha_2 * log(beta_2) - (i + alpha_2) * log(beta_1 + beta_2) - log(i + alpha_2) - lbeta(i + 1, alpha_2));
}
return total;
}
// [[Rcpp::export]]
double bayesBernoulliTestClosed_(double alpha_1, double beta_1, double alpha_2, double beta_2) {
double total = 0;
for(int i = 0; i < alpha_2; i++) {
total += exp(lbeta(alpha_1 + i, beta_1 + beta_2) - log(beta_2 + i) - lbeta(1 + i, beta_2) - lbeta(alpha_1, beta_1));
}
return 1 - total;
}
| true |
c02dae18e869fc4cec93901e1b550aac69e75ee4 | C++ | chjesus/Estructura-de-Datos | /Parcial II/Parcial 2/Problema 1/Personal.h | UTF-8 | 1,177 | 3.609375 | 4 | [] | no_license | #ifndef PERSONAL_H
#define PERSONAL_H
#include <string.h>
using namespace std;
class Personal{
int id;
char nombre[40];
bool activo;
int precio;
public:
Personal(){}
Personal(int id,char *nom,bool act,int pre){
this->id = id;
strcpy(this->nombre,nom);
this->activo = act;
this->precio = pre;
}
friend ostream& operator<<(ostream& os, const Personal& datos){
if(datos.activo == true && datos.precio==0){
os<<"ID: "<<datos.id<<" | Nombre: "<<datos.nombre<<" | Estatus: Libre";
}else if(datos.activo == true && datos.precio>0){
os<<"ID: "<<datos.id<<" | Nombre: "<<datos.nombre<<" | Estatus: Libre"<<" | Monto Recaudado: "<<datos.precio;
}else{
os<<"ID: "<<datos.id<<" | Nombre: "<<datos.nombre<<" | Estatus: Ocupado";
}
return os;
}
bool operator<(const Personal& datos){
return this->id < datos.id;
}
bool operator==(const Personal& datos){
return this->id==datos.id;
}
int getId(){return id;}
char *getNombre(){return nombre;}
bool getActivo(){return activo;}
int getPrecio(){return precio;}
void setPrecio(int pre){ precio += pre;}
void setActivo(bool act){activo = act;}
};
#endif
| true |
cff9981bf5f1b061e6d558611123d129b4ce9c41 | C++ | mszhangjiao/GameNetwork | /GameNetwork/NetClient.h | UTF-8 | 1,473 | 2.6875 | 3 | [] | no_license | #pragma once
// defines the client networking features:
// - set up connection with server,
// - maintains client network states;
// - handles received packets;
class NetClient : public NetManager
{
public:
const float cHelloTimeout = 1.f;
static NetClient* Instance()
{
return dynamic_cast<NetClient *>(NetManager::Instance().get());
}
static bool StaticInit(const string& serverIP, const string& service, int family, const string& playerName, bool enableHeartbeat = true);
virtual bool IsServer() override
{
return false;
}
NetPlayerPtr GetLocalPlayerPtr() const
{
return m_LocalPlayerPtr;
}
virtual void ProcessPacket(InputBitStream& is, const SockAddrIn& addr) override;
virtual void HandleConnectionError(const SockAddrIn& sockAddr) override;
void SendOutgoingPackets();
void CheckForDisconnects();
void ShutdownAndClose();
virtual void ShowDroppedPacket(InputBitStream& is, const SockAddrIn& addr) override;
private:
NetClient(const string& serverIP, const string& service, int family, const string& playerName, bool enableHeartbeat = true);
bool Init();
// Packet sending functions;
void SendHelloPacket();
void SendInputPacket();
// Packets handling functions;
void HandleWelcomePacket(InputBitStream& is);
// Update functions;
void UpdateSendingHello();
void UpdateSendingInput();
string m_ServerIP;
SockAddrIn m_ServerSockAddr;
NetPlayerPtr m_LocalPlayerPtr;
float m_TimeOfLastHello;
bool m_SendHeartbeats;
}; | true |
63d0062967d1f8253e34814e0593e69d01da9236 | C++ | bunnybryna/Parkland_College_CSC125_CPP2 | /Lectures/0314/mainTogether.cpp | UTF-8 | 3,381 | 4.09375 | 4 | [] | no_license | #include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class LinkedListNode
{
public:
LinkedListNode(string str,LinkedListNode* ptr);
LinkedListNode* getNext(){return m_Next;}
void setNext(LinkedListNode* ptr){m_Next = ptr;}
void setData(string str){m_Data = str;}
string getData(){return m_Data;}
private:
string m_Data;
LinkedListNode* m_Next;
};
class LinkedList
{
friend ostream& operator<<(ostream& o, LinkedList ll);
public:
LinkedList();
bool empty();
void push_front(string str);
void push_back(string str);
void pop_front();
void clear();
private:
LinkedListNode* m_Head;
LinkedListNode* m_Tail;
};
ostream& operator<<(ostream& o, LinkedListNode node);
ostream& operator<<(ostream& o, LinkedListNode* nodePtr);
int main()
{
LinkedListNode n("string",NULL);
LinkedListNode two("another",&n);
LinkedList ll;
cout << "First list:" << ll << " is the first list" << endl;
ll.push_front("one");
ll.push_front("two");
ll.push_front("three");
cout << "Here's ll after inserting 3 items: " << ll << endl;
ll.push_back("end1");
ll.push_back("end2");
ll.push_back("end3");
cout << "Here's ll after inserting 3 items: " << ll << endl;
ll.pop_front();
ll.pop_front();
ll.pop_front();
cout << "Here's ll after popping 3 items: " << ll << endl;
cout << "Hello World!" << endl;
return 0;
}
ostream& operator<<(ostream& o,LinkedListNode node)
{
o<< node.getData();
return o;
}
ostream& operator<<(ostream& o,LinkedListNode* nodePtr)
{
o<<nodePtr->getData();
return o;
}
ostream& operator<<(ostream& o,LinkedList ll)
{
if(ll.empty())
{
o << "This list is empty";
}
LinkedListNode* ptr = ll.m_Head;
while (ptr != NULL)
{
// note when ptr is printed, a function
// ostream& operator<<(ostream& o, LinkedListNode* nodePtr) is called
// so the object this ptr is pointing to got printed out
o<< ptr << ", ";
// move pointer through the list just like i++
ptr = ptr->getNext();
}
return o;
}
LinkedListNode::LinkedListNode(string str, LinkedListNode* ptr)
{
m_Next = ptr;
m_Data = str;
}
LinkedList::LinkedList()
{
m_Head = NULL;
m_Tail = NULL;
}
bool LinkedList::empty()
{
if(m_Head == NULL)
return true;
else
return false;
}
void LinkedList::push_front(string str)
{
if (empty())
{
// = goes from the back
// return the address of a new object node
m_Head = m_Tail = new LinkedListNode(str,NULL);
}
else
{
m_Head = new LinkedListNode(str, m_Head);
}
}
void LinkedList::push_back(string str)
{
if (empty())
{
m_Head = m_Tail = new LinkedListNode(str,NULL);
}
else
{
m_Tail -> setNext(new LinkedListNode(str, NULL));
m_Tail = m_Tail->getNext();
}
}
void LinkedList::pop_front()
{
if (empty())
{
cerr << "Error: trying to remove things from an empty list" << endl;
exit(3);
}
LinkedListNode* tempPtr = m_Head;
m_Head = m_Head->getNext();
delete tempPtr;
// may go down from one to zero
if (m_Head == NULL)
{
m_Tail = NULL;
}
}
void LinkedList::clear()
{
while (!empty())
{
pop_front();
}
}
| true |
f415e6a803f052e4d39567712c74842cc5d43edc | C++ | LinMdjj/daigua | /create/create/create.cpp | UTF-8 | 1,824 | 2.84375 | 3 | [] | no_license | #include"pch.h"
#include<iostream>
#include<stdio.h>
#include<time.h>
#include <stdlib.h>
#include<sys/timeb.h>
using namespace std;
struct timeb timeSeed;
int random()//产生随机数的函数
{
ftime(&timeSeed);
srand(timeSeed.time * 1000 + timeSeed.millitm);
int a;
a = rand() % 100+1;
return a;
}
int random1()//产生随机数的函数
{
int a;
srand((unsigned int)time(NULL));
a = rand() % 101 + 1;
return a;
}
int random2()//产生随机数的函数
{
int a;
srand((unsigned int)time(NULL));
a = rand() % 99 + 1;
return a;
}
int random3()//产生随机数的函数
{
int a;
srand((unsigned int)time(NULL));
a = rand() % 98 + 1;
return a;
}
int test(int t)//产生除数的函数
{
int b,e;
srand((unsigned)time(NULL));
e = rand() % 30;
b = t * e;
return b;
}
int symbol()//产生符号
{
int t;
int x;
srand((unsigned)time(NULL));
for (int i = 0; i < 10; i++)
t = rand() % 3+1;
switch (t)
{
case 1:x = 42; break;
case 2:x = 43; break;
case 3:x = 45; break;
}
return x;
}
int symbol1()//产生符号
{
int t;
int x=42;
srand((unsigned)time(NULL));
t = rand() % 4 ;
switch (t)
{
case 1:x = 42; break;
case 2:x = 43; break;
case 3:x = 45; break;
}
return x;
}
void delay(int msec)//延时函数
{
clock_t now = clock();
while (clock() - now < msec);
}
int main()
{
char s, j;
int r,n,h,g,k,i;
cout << "请输入需要题的数目(按回车键获取题目)" << endl;
cin >> i;
for (int t = 1; t <= i; t++)
{
h = random();
n = random1();
g = random2();
k = random3();
if (h % 2 == 0)
{
r = test(n);
s = symbol();
j = 47;
cout << r << j << n << s << g << endl;
}
else
{
s = symbol();
j = symbol1();
cout << k << j << n << s << g << endl;
}
delay(1000);
}
cout << "谢谢使用";
return 0;
} | true |
705479f8458f14da040a4ef863c2ec32148b8bb8 | C++ | Svitojar/Curve2d | /main.cpp | UTF-8 | 821 | 2.984375 | 3 | [] | no_license | #pragma once
#include "Point2D.h"
#include "Curve2d.h"
#include "Line2d.h"
#include "Arc2d.h"
#include <iostream>
using namespace lesson_10;
using namespace std;
void main()
{
Point2D *CentralPoint = new Point2D(137,158);
Point2D *StartPoint = new Point2D(10, 10);
Point2D *EndPoint = new Point2D(230, 480);
Line2d* Myline = new Line2d(*StartPoint, *EndPoint);
Arc2d* MyArc = new Arc2d(*StartPoint, *EndPoint,*CentralPoint);
Curve2d *MyCurve = Myline;
MyCurve->length();
Curve2d *MyCurve2 = MyArc;
MyCurve2->length();
cout << "The length of the line "<< Myline->getLength() <<endl;
cout << "Radius "<<MyArc->radius() << endl;
cout << "The Angle Gamma "<<MyArc->angle()<< endl;
cout << "The length of the ARC " << MyArc->getLength() << endl;
cin.get();
cin.get();
} | true |
a2ed337ce96116bff116a7486c4c4c3b33eb0b35 | C++ | JonnieWayy/Own-Notes | /数字图像处理/SourceCode/chapter04/code04-01-resize/code04-01-resize/code04-01-resize.cpp | GB18030 | 1,631 | 2.9375 | 3 | [
"MIT"
] | permissive | /************************************************************
Copyright (C), 2008-2014, ӿƼѧȨ.
ļ: code04-01-resize.cpp
: λ
: 1.0
: 2014-08-11
: ʵͼıŲʾ
:
б:
1.
ļ¼:
<> <ʱ> <汾> <>
λ 2014-08-11 1.0 ļ
***********************************************************/
#include <iostream>
#include <cmath>
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
using namespace std;
int main(int argc, char* argv[])
{
/// ͼ
string srcFileName;
cout << "Enter the source image file name: ";
cin >> srcFileName;
Mat src = imread(srcFileName, 1);
if(src.empty())
{
cerr << "Failed to load image " << srcFileName << endl;
return -1;
}
///
Mat dst; //Ŀͼָ
float scale = 0.618f; //ű˴趨Ϊ0.618
Size dst_size; //Ŀͼߴ
dst_size.width = src.cols * scale; //ĿͼĿΪԴͼscale
dst_size.height = src.rows * scale; //ĿͼĸΪԴͼߵscale
resize(src, dst, dst_size); //ԴͼĿͼ
/// ʾԭͼ
namedWindow("src", CV_WINDOW_AUTOSIZE);
imshow("src", src);
/// ʾźͼ
namedWindow("dst", CV_WINDOW_AUTOSIZE);
imshow("dst", dst);
waitKey(0);
return 0;
}
| true |
7bd43608e42cb70c9cd21d3239fd6e6b9d15b804 | C++ | prostain/projetsSio | /c++/pointeur1/pointeur.cpp | UTF-8 | 519 | 3.53125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int nb1, nb2;
cout<<"entrer le premier nombre : ";
cin>>nb1;
cout<<"entrer le second nombre : ";
cin>>nb2;
int *lePlusGrand, *lePlusPetit;
if(nb1>nb2)
{
lePlusGrand = &nb1;
lePlusPetit = &nb2;
}
else
{
lePlusGrand = &nb2;
lePlusPetit = &nb1;
}
cout<<"le nombre le plus petit est : "<<*lePlusPetit<<endl<<" le plus grand est : "<<*lePlusGrand<<endl;
cout<<"l'adresse de nb1 est : "<<&nb1<<endl<<" l'adresse de nb2 est : "<<&nb2<<endl;
}
| true |
0c4c3fd8526392c759e131bda790ad32ca5ce660 | C++ | alaneos777/club | /camp 2018/contest 1/H.cpp | UTF-8 | 1,819 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
template <typename T>
struct SegmentTree{
SegmentTree *left, *right;
int start, end, half;
T value, lazy;
SegmentTree(int start, int end){
this->start = start;
this->end = end;
this->half = start + ((end - start) >> 1);
this->value = this->lazy = 0;
if(start == end){
this->left = this->right = NULL;
}else{
this->left = new SegmentTree(start, this->half);
this->right = new SegmentTree(this->half + 1, end);
}
}
void propagate(T dif){
this->value += dif;
if(this->start != this->end){
this->left->lazy += dif;
this->right->lazy += dif;
}
}
void add(T dif, int start, int end){
if(this->lazy != 0){
this->propagate(this->lazy);
this->lazy = 0;
}
if(start > end)
return;
if(start == this->start && end == this->end)
this->propagate(dif);
else{
this->left->add(dif, start, min(end, this->half));
this->right->add(dif, max(start, this->half + 1), end);
this->value = max(this->left->value, this->right->value);
}
}
T query(int start, int end){
if(this->lazy != 0){
this->propagate(this->lazy);
this->lazy = 0;
}
if(start > end)
return 0;
if(start == this->start && end == this->end)
return this->value;
return max(this->left->query(start, min(end, this->half)), this->right->query(max(start, this->half + 1), end));
}
};
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, q, l, r;
char t;
int value;
cin >> n;
SegmentTree<lli> *ST = new SegmentTree<lli>(1, n);
for(int i = 1; i <= n; i++){
cin >> value;
ST->add(value, i, i);
}
cin >> q;
for(int i = 1; i <= q; i++){
cin >> t;
cin >> l >> r;
if(t == 'm'){
cout << ST->query(l, r) << " ";
}else{
cin >> value;
ST->add(value, l, r);
}
}
return 0;
} | true |
8e1adfd70ab3fd53ee500332af7215c246978867 | C++ | siddhanta1/ticpp | /CPP/Chap2_Ticpp/casting_float_to_char_pointer.cpp | UTF-8 | 409 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void printBinary(const unsigned char val) {
for (int i = 0; i <=sizeof(val); i++)
if (val & (1 << i))
cout << "1";
else
cout << "0";
}
int main() {
float f=2.2;
unsigned char *p = reinterpret_cast<unsigned char*>(&f);
for (int i =0; i <sizeof(f); i +=2) {
printBinary(p[i - 1]);
printBinary(p[i]);
}
cout << endl;
return 0;
} | true |
1848e05260298c810d2a7a38a1e2a02807a64bb2 | C++ | hello-sources/Coding-Training | /LeetCode/433最小基因变化.cpp | UTF-8 | 679 | 2.8125 | 3 | [] | no_license | class Solution {
public:
int minMutation(string start, string end, vector<string>& bank) {
if (start == end) minNum = min(minNum, num);
for (auto str : bank) {
int diff = 0;
for (int i = 0; i < str.size(); i++) if (str[i] != start[i]) diff++;
if (diff == 1 && u_set.find(str) == u_set.end()) {
u_set.insert(str);
num += 1;
minMutation(str, end, bank);
num -= 1;
u_set.erase(str);
}
}
return minNum == INT_MAX ? -1 : minNum;
}
private :
int minNum = INT_MAX, num = 0;
unordered_set<string> u_set;
}; | true |
16896b5b70d6237448baf1fb74f2bfedc5cef8fd | C++ | shashank9aug/DSA_CB | /BackTracking/ImpProblems/unique_permutation.cpp | UTF-8 | 926 | 3.765625 | 4 | [] | no_license | /*
we have given char set :
we have to return all the possible permutation.
permutation : all the possible rearrangement .
if Given in question : unique and lexicographical
we can use set for that => stl container
ip : aba
op : aab,aba,baa,
*/
#include<iostream>
#include<set>
#include<string>
#include<cstring>
using namespace std;
//taking i -> for traversal of given char set
void permute(char ip[],int i,set<string>&s){
//Base case :
if(ip[i]=='\0'){
string t(ip);
s.insert(t);
return;
}
//Rec case :
for(int j=i;ip[j]!='\0';j++){
swap(ip[i],ip[j]);
permute(ip,i+1,s);
swap(ip[i],ip[j]);
}
}
int main(){
char ip[100];
cin>>ip;
set<string>s;
permute(ip,0,s);
//print unique and lixicographical order strings :
for(auto str : s){
cout<<str<<",";
}
return 0;
} | true |
cd58f390a5d4a1534192345093c7dcc5fed28cdb | C++ | CremboC/aktex | /aktex/Screens.cpp | UTF-8 | 1,247 | 2.671875 | 3 | [] | no_license | #include "stdafx.h"
#include "Screens.h"
#include "Game.h"
using std::pair;
using enums::GameState;
using enums::ItemSpeed;
using enums::ItemType;
Screens::Screens()
{}
Screens::~Screens()
{}
// returns the start screen
Screen *Screens::main()
{
Screen *scr = new Screen(
"menu",
"Welcome to Aktex. The adventure action text game. \n"
"To start the game type in 'start' and press enter! \n"
"Also try 'options' for options or 'exit' to exit the game.",
{ "start", "options" },
nullptr,
true
);
scr->defineMoveBehaviour("start", [this]
{
State::inst().setState(GameState::PLAYING);
State::inst().setScreen(start());
});
return scr;
}
// the first game screen
Screen *Screens::start()
{
vector<Item *> items = {
new Item("first", 10, ItemType::WEAPON, ItemSubType::WEAPON_SWORD, ItemSpeed::NORMAL)
};
EnemyProperties *eProps = new EnemyProperties;
eProps
->hpRange(pair < int, int > {80, 100})
->possibleDrops(1)
->dropLikelyhood(0.5f)
->items(items);
Screen *scr = new Screen(
"first",
"Dis da' first game screen, wassup y'all. \n"
"Youse in room, youse see door north of you. What you do?",
{},
eProps,
false
);
return scr;
}
Screen *Screens::generateRoom()
{
return nullptr;
} | true |
f43b063ee4172d91ae4493a989be3249e00773d8 | C++ | cheickmec/Todo-List-Program | /c_command.h | UTF-8 | 1,700 | 2.578125 | 3 | [] | no_license | #ifndef COMMAND_H
#define COMMAND_H
#include <fstream>
#include "c_Arglist.h"
#include <vector>
///-------------------------COMMAND------------------------------
class c_Command
{
private:
std::fstream m_File;
bool isEmpty();
bool isFormat(std::string str);
public:
c_Command();
c_Command(c_Arglist args);
virtual void process() = 0;
void set_arglist(c_Arglist aList);
virtual ~c_Command();
protected:
std::vector <c_Task> m_TaskList;
void parseFile();
void updateFile();
void displayList();
void checkGivenTask();
c_Arglist m_arglist;
};
///-------------------------LIST (COMMAND)------------------------
class c_List : public c_Command
{
private:
protected:
public:
c_List(c_Arglist args);
void process();
virtual ~c_List();
};
///---------------------ADD (COMMAND)-------------------------
class c_Add : public c_Command
{
private:
protected:
public:
c_Add(c_Arglist args);
void process();
~c_Add();
};
///------------------------DO (COMMAND)-----------------------
class c_Do : public c_Command
{
private:
protected:
public:
c_Do(c_Arglist args);
void process();
~c_Do();
};
///========================UTILIES========================
//initializes argument list
void initArguments(int argc, char* argv[], c_Arglist& args);
//Determines which command to be used
void Processor(c_Command* com, const c_Arglist& args);
//returns true if x is a digit
bool isDigit(const char x);
//returns position of last digit in str
unsigned int getpos(std::string str);
//returns true if strings match
bool doMatch(const char* st1, const char* st2);
//returns value of leading positive integer
//if there are no leading integer, returns -1
int toInt(std::string x);
#endif // COMMAND_H
| true |
814991a83d1158cf54abef6fb36578a5536d4a99 | C++ | PiggerZZM/DataStructure_cpp | /stack/Hanoi.cpp | GB18030 | 372 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <cstring>
void Hanoi(int n, String A, String B, String C)
{
// AnӽBƶC
if (n == 1)
cout << "Move top disk from peg" << A << "to peg" << C << endl;
else
{
Hanoi(n-1, A, C, B);
cout << "Move top disk form peg" << A << "to peg" << C << endl;
Hanoi(n-1, B, A, C);
}
}
| true |
78881a0ebf96a3afb829a3b9b38fe5524103c0f8 | C++ | WonJoonPark/BOJ-Algorithm | /17822.cpp | UHC | 3,644 | 2.765625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int N, M, T; // , Ǵ , T ȸŲ.
int circle[51][51]; // ° / °
bool visited[51][51]; //bfs
queue<pair<int, int>> tmpq;
int xi, di, ki;
int xdk[51][3];
bool checkexist = false;
int dx[4] = { -1,1,0,0 };
int dy[4] = { 0,0,-1,1 };
double tmpsum, tmpn;
bool neighbor = false;
//ȣ xi di(0-ð,1-ݽð) kiĭ ŭ ȸ
void inputs() {
cin >> N >> M >> T;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
cin >> circle[i][j];
}
}
for (int i = 1; i <= T; i++) {
cin >> xdk[i][0] >> xdk[i][1] >> xdk[i][2];
}
}
bool boundcheck(int x) {
return (x >= 1 && x <= N); //
}
void rotate(int r) {
for (int k = 0; k < xdk[r][2]; k++) {
for (int i = 1; i <= N; i++) {
if (i % xdk[r][0] != 0) continue; // xi Ǹ ȸ
int tmpnum;
if (xdk[r][1] == 0) { // ð
tmpnum = circle[i][M];
for (int j = M; j >= 2; j--) {
circle[i][j] = circle[i][j - 1];
}
circle[i][1] = tmpnum;
}
else { //ݽð
tmpnum = circle[i][1];
for (int j = 1; j < M; j++) {
circle[i][j] = circle[i][j + 1];
}
circle[i][M] = tmpnum;
}
}
}
}
void initvisit() {
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
visited[i][j] = false;
}
}
}
void bfs(int x, int y) {
visited[x][y] = true;
tmpq.push({x,y});
while (!tmpq.empty()) {
int qsize = tmpq.size();
while (qsize--) {
int nextx = tmpq.front().first;
int nexty = tmpq.front().second;
tmpq.pop();
for (int i = 0; i < 4; i++) {
int tx = nextx + dx[i]; int ty = nexty + dy[i];
if (ty == 0) ty = M; //circular
if (ty == M + 1) ty = 1;
if (boundcheck(tx) && !visited[tx][ty] && circle[tx][ty] == circle[x][y]) {
tmpq.push({ tx,ty });
visited[tx][ty] = true;
neighbor = true;
circle[tx][ty] = 0; //
checkexist = true;
}
}
}
}
if (neighbor == true) {
circle[x][y] = 0;
} //ϳ ϸ ()
}
void getsum() {
tmpsum = 0; tmpn = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
if (circle[i][j] != 0) {
tmpsum += circle[i][j];
tmpn++;
}
}
}
}
/*void watchcircle() {
cout << "\n";
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
cout << circle[i][j] << " ";
}
cout << "\n";
}
cout << "\n";
}*/
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
inputs(); //
for(int a=1;a<=T;a++) {
rotate(a); //ȸ
getsum(); // ü
if (tmpn == 0) { cout << 0; return 0; }
initvisit();
checkexist = false; // ϸ鼭 ϳ ϴ üũ
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
neighbor = false; //̿ ϳ ǰ ƴϸ
if (circle[i][j] != 0 && visited[i][j] == false) {
bfs(i, j);
} //
}
}
if (checkexist == false) { //
double avg = tmpsum / tmpn;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
if (circle[i][j] == 0) continue;
if (circle[i][j] > avg) {
circle[i][j]--; continue;
}
else if (circle[i][j] < avg) {
circle[i][j]++; continue;
}
}
}
}
}
int resultsum = 0;
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= M; j++) {
resultsum += circle[i][j];
}
}
cout << resultsum;
return 0;
} | true |
da749209b13ab831aab64e8b1a1fed0a81d5e81b | C++ | iridium-browser/iridium-browser | /buildtools/third_party/libc++/trunk/test/std/ranges/range.factories/range.iota.view/iterator/plus_eq.pass.cpp | UTF-8 | 2,319 | 2.703125 | 3 | [
"NCSA",
"LLVM-exception",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03, c++11, c++14, c++17
// constexpr iterator& operator+=(difference_type n)
// requires advanceable<W>;
#include <cassert>
#include <ranges>
#include <type_traits>
#include "test_macros.h"
#include "../types.h"
constexpr bool test() {
// When "_Start" is signed integer like.
{
std::ranges::iota_view<int> io(0);
auto iter1 = io.begin();
auto iter2 = io.begin();
assert(iter1 == iter2);
iter1 += 5;
assert(iter1 != iter2);
assert(iter1 == std::ranges::next(iter2, 5));
static_assert(std::is_reference_v<decltype(iter2 += 5)>);
}
// When "_Start" is not integer like.
{
std::ranges::iota_view io(SomeInt(0));
auto iter1 = io.begin();
auto iter2 = io.begin();
assert(iter1 == iter2);
iter1 += 5;
assert(iter1 != iter2);
assert(iter1 == std::ranges::next(iter2, 5));
static_assert(std::is_reference_v<decltype(iter2 += 5)>);
}
// When "_Start" is unsigned integer like and n is greater than or equal to zero.
{
std::ranges::iota_view<unsigned> io(0);
auto iter1 = io.begin();
auto iter2 = io.begin();
assert(iter1 == iter2);
iter1 += 5;
assert(iter1 != iter2);
assert(iter1 == std::ranges::next(iter2, 5));
static_assert(std::is_reference_v<decltype(iter2 += 5)>);
}
{
std::ranges::iota_view<unsigned> io(0);
auto iter1 = io.begin();
auto iter2 = io.begin();
assert(iter1 == iter2);
iter1 += 0;
assert(iter1 == iter2);
}
// When "_Start" is unsigned integer like and n is less than zero.
{
std::ranges::iota_view<unsigned> io(0);
auto iter1 = io.begin();
auto iter2 = io.begin();
assert(iter1 == iter2);
iter1 += 5;
assert(iter1 != iter2);
assert(iter1 == std::ranges::next(iter2, 5));
static_assert(std::is_reference_v<decltype(iter2 += 5)>);
}
return true;
}
int main(int, char**) {
test();
static_assert(test());
return 0;
}
| true |
93816edcaf10a5af9c88beef57ef1b745c838b4f | C++ | abiles/StudySlowly | /305_VALVUE_CATEGORY/valueCategories.cpp | UHC | 490 | 3.4375 | 3 | [] | no_license | #include <iostream>
using namespace std;
void f1 ( int a ) {}
void f2 ( int& a ) {}
void f3 ( int&& a ) {}
int main ()
{
int n= 10;
f1 ( n );
f2 ( n );
// f3 ( n ); : error
f3 ( static_cast< int&& > ( n ) ); // f3(move(n));
}
/*
1.
2. Լ Ÿ ϴ ˱
*/
int x=0;
int f4 () { return x; };
int& f5 () { return x; };
//int&& f6 () { return x; };
int&& f6 () { return move ( x ); }; | true |
35e597eecc62de06bd22b7459de377257a5fbec6 | C++ | alextzik/arduino_workshop-2019 | /Robotic_Arm/Arm.ino | UTF-8 | 2,339 | 2.75 | 3 | [] | no_license | template <typename type>
type sign(type value) {
return type((value>0)-(value<0));
}
void MoveServos(){
long xx = abs(x);
long yy = abs(y);
long zz = abs(z);
// sample comment
// Servo 1
long dxy = sqrt(sq(xx)+sq(yy));
Serial.print("dxy=");
Serial.println(dxy);
if (y == 0L){
angle1 = 90;
} else if (x == 0L){
angle1 = -(sign(y)*90 - 90);
} else {
angle1 = acos((sq(xx)+sq(dxy)-sq(yy))/((double)(2*xx*dxy)))*4068/71;
angle1 = -(sign(y)*angle1 - 90);
}
Serial.print("angle1=");
Serial.println(angle1);
Servo1.write((int)angle1);
delay(1000);
// Servo 2,3
long dxyz = sqrt(sq(dxy)+sq(zz));
Serial.print("dxyz=");
Serial.println(dxyz);
double xyz_angle;
if (dxy == 0){
if (sign(z) < 0){
xyz_angle = -90;
} else if (sign(z) > 0){
xyz_angle = 90;
} else {
Serial.println("Zero coordinates.");
Serial.println("Arm not moving.");
return;
}
} else if (z == 0L){
xyz_angle = 0;
} else {
xyz_angle = acos((sq(dxy)+sq(dxyz)-sq(zz))
/((double)(2*dxy*dxyz)))*4068/71;
xyz_angle = xyz_angle*sign(z);
}
Serial.print("xyz_angle=");
Serial.println(xyz_angle);
if (dxyz > (length1+length2)){
Serial.println("Object is too far.");
Serial.println("Arm not moving.");
return;
} else {
angle2 = acos((sq(length1)+sq(dxyz)-sq(length2))
/((double)(2*length1*dxyz)))*4068/71;
Serial.print("triangle_angle2=");
Serial.println(angle2);
angle2 = 90 - xyz_angle - angle2 - 20; // - error
Serial.print("angle2=");
Serial.println(angle2);
angle3 = acos((sq(length1)+sq(length2)-sq(dxyz))
/(double(2*length1*length2)))*4068/71;
Serial.print("triangle_angle3=");
Serial.println(angle3);
angle3 = - 90 + angle3 + (-10); // + error
Serial.print("angle3=");
Serial.println(angle3);
}
if ((angle2<0) || (angle2>180)){
Serial.println("Servo2 can not go there.");
Serial.println("Arm not moving.");
return;
} else if ((angle3<0) || (angle3>180)){
Serial.println("Servo3 can not go there.");
Serial.println("Arm not moving.");
return;
} else {
Servo2.write((int)angle2);
delay(1000);
Servo3.write((int)angle3);
delay(1000);
}
}
| true |
e91b9924e20a2db842ab37e5bba98427728dc0dc | C++ | anujinm/Game_of_life | /Game_of_life/welcome_screen.h | UTF-8 | 6,543 | 2.6875 | 3 | [] | no_license | #pragma once
#include <iostream>
namespace welcome {
static void draw_start_button(int x) {
// draw the start button
if (x==0) {
std::cout << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl;
std::cout << " ****************************************" << std::endl;
std::cout << " * ____ _____ _ ____ _____ *" << std::endl;
std::cout << " * / ___|_ _|/ \\ | _ \\_ _| *" << std::endl;
std::cout << " * \\___ \\ | | / _ \\ | |_) || | *" << std::endl;
std::cout << " * ___) || |/ ___ \\| _ < | | *" << std::endl;
std::cout << " * |____/ |_/_/ \\_\\_| \\_\\|_| *" << std::endl;
std::cout << " * *" << std::endl;
std::cout << " ****************************************" << std::endl;
}
else if (x==1) {
std::cout << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl << std::endl;
std::cout << " ~** * **** * /***** /** %*****//~" << std::endl;
std::cout << " * * **********/* ******** ******* * *" << std::endl;
std::cout << " * ____ _____ _ ____ _____ **" << std::endl;
std::cout << " / / ___|_ _|/ \\ | _ \\_ _| *" << std::endl;
std::cout << " \\* \\___ \\ | | / _ \\ | |_) || | *" << std::endl;
std::cout << " * ___) || |/ ___ \\| _ < | | *" << std::endl;
std::cout << " ** |____/ |_/_/ \\_\\_| \\_\\|_| /" << std::endl;
std::cout << " * *" << std::endl;
std::cout << " * ************* *%****** ****** /** *" << std::endl;
std::cout << " %****% ****** **** ****% * **\\" << std::endl;
}
}
static void start_screen() {
//ascii
//http://patorjk.com/software/taag/#p=display&f=Standard&t=START
//mouse click
//https://stackoverflow.com/questions/6285270/how-can-i-get-the-mouse-position-in-a-console-program
//https://stackoverflow.com/questions/11391262/the-meaning-of-enable-processed-input-in-setconsolemode-flags
//https://docs.microsoft.com/en-us/windows/console/reading-input-buffer-events
//IF NOT WORKING, TRY:
/*Opening command-prompt and right-clicking on its title-bar and then clicking 'Defaults'
A Dialog box would appear, titled 'Console Windows Properties'. There in Options tab, under Edit Options sub-heading, you would find 'Quick Edit Mode' checkbox!
The problem was being caused by this 'Quick Edit Mode' option which was enabled(checkbox is checked) by default on my Windows 10. And in this enabled status, this
'Quick Edit Mode' was consuming all the Mouse-Events and wasn't dispatching any to my '.exe' .
When this 'Quick Edit Mode' options' checkbox is unchecked (disabled), then program runs fine as intended/coded in this sample-code here, telling/printing all Mouse events.
NOTE: The change in 'Console Properties' requires relaunch of the console, to take effect.*/
draw_start_button(0);
int x = 36; int x_size = 39;
int y = 12; int y_size = 7; // location and size of this button
// GET MOUSE CLICK
HANDLE hin = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD input_record;
DWORD events;
COORD coord;
// current (default) state to restore later
DWORD fdwSaveOldMode;
GetConsoleMode(hin, &fdwSaveOldMode);
// new state
SetConsoleMode(hin, ENABLE_EXTENDED_FLAGS | ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT);
bool flag = true;
while (true) {
// infinite loop to wait for user input
ReadConsoleInput(hin, &input_record, 1, &events);
if (input_record.EventType == MOUSE_EVENT) { // if clicked
if (input_record.Event.MouseEvent.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { // if left-click
///std::cout << "sup bruh" << std::endl;
coord.X = input_record.Event.MouseEvent.dwMousePosition.X; // get positions
coord.Y = input_record.Event.MouseEvent.dwMousePosition.Y;
//std::cout << coord.X << std::endl;
//std::cout << coord.Y << std::endl;
if (coord.X>x && coord.X<(x+x_size) && coord.Y>y && coord.Y<(y+y_size)) { // if clicked inside box
flag = false;
system("cls");
draw_start_button(1);
Sleep(500);
system("cls");
break;
}
}
}
///FlushConsoleInputBuffer(hin);
}
SetConsoleMode(hin, fdwSaveOldMode);
}
static int choose_what_to_do() {
// type of simulation
std::cout << "*******************************" << std::endl;
std::cout << "*******************************" << std::endl;
std::cout << "*** ***" << std::endl;
std::cout << "*** 1. Original game ***" << std::endl;
std::cout << "*** 2. By_Generation ***" << std::endl;
std::cout << "*** 3. By_Queue ***" << std::endl;
std::cout << "*** ***" << std::endl;
std::cout << "*******************************" << std::endl;
std::cout << "*******************************" << std::endl;
std::cout << "\n\n\n\n\nEnter you choice: ";
int choice;
do {
// input validation
std::cin >> choice;
} while (choice<1 || choice>3);
return choice;
}
static int ask_wait_rate() {
// ask for by_generation wait rate
int zombie_mode_wait_rate;
std::cout << "How long do you want to keep a dead cell in a zombie mode before resurrecting it? ";
do {
//input validation
std::cin >> zombie_mode_wait_rate;
} while (zombie_mode_wait_rate<1);
return zombie_mode_wait_rate;
}
static int ask_res_rate() {
// ask for by_queue res rate
int resurrection_rate;
std::cout << "How many cells do you want to resurrect per generation? ";
do {
// input validation
std::cin >> resurrection_rate;
} while (resurrection_rate<1);
return resurrection_rate;
}
} | true |
122a1051c570a40c220e79e9a6af6ea053085d90 | C++ | andreimocian/Probleme-Pbinfo-rezolvate | /zoo.cpp | UTF-8 | 892 | 2.546875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
ifstream fin("zoo.in");
ofstream fout("zoo.out");
int n, m, a[105][105], q, i1, j1, i2, j2;
long long sum[105][105], s;
void SumePart()
{
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
sum[i][j] = sum[i-1][j] + sum [i][j-1] - sum [i-1][j-1] + a[i][j];
}
}
}
void Intrebari()
{
///i1 j1 sus , i2 j2 jos
s = sum[i2][j2] - sum [i1-1][j2] - sum[i2][j1-1] + sum[i1-1][j1-1];
fout << s;
fout << "\n";
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
fin >> a[i][j];
}
}
SumePart();
fin >> q;
while(q)
{
fin >> i1 >> j1 >> i2 >> j2;
Intrebari();
q--;
}
return 0;
}
| true |
96fed9084d179ba06c741825f9f72bb7278d34e4 | C++ | autonomobil/SDCND-P9_PID-Control | /src/PID.cpp | UTF-8 | 1,592 | 2.984375 | 3 | [
"MIT"
] | permissive | #include "PID.h"
using namespace std;
PID::PID() {}
PID::~PID() {}
void PID::Init(double Kp, double Ki, double Kd) {
p_error = 0;
i_error = 0;
d_error = 0;
steering_val_acc = 0;
d_error_acc = 0;
last_cte = 0;
Kp_ = Kp;
Ki_ = Ki;
Kd_ = Kd;
m_timeBegin = std::chrono::steady_clock::now( );
}
void PID::UpdateError(double cte) {
p_error = cte;
if(fabs(cte) < 0.01){
i_error = 0;
}
else{
i_error += cte;
if(i_error > 50.0){
i_error = 50.0;
}
else if(i_error < -50.0){
i_error = -50.0;
}
}
// smooth d_error
d_error_acc = (0.5 * (cte - last_cte)) + (1.0 - 0.5) * d_error_acc;
d_error = d_error_acc ;
last_cte = cte;
}
double PID::TotalError(double speed) {
cout << endl;
double p_val = -(Kp_ - speed/500) * p_error;
double i_val = -Ki_ * i_error;
double d_val = -(Kd_ + speed/50) * d_error;
cout << "speed:" << setw(1) << speed <<
setw(15) << "p value:" << setw(2) << p_val <<
setw(15) << "i value:" << setw(2) << i_val <<
setw(15) << "d value:" << setw(2) << d_val << '\n';
double steering_val = p_val + i_val + d_val;
if(steering_val > 0.95){
steering_val = 0.95;
}
else if(steering_val < -0.95){
steering_val = -0.95;
}
// smooth steering_val
steering_val_acc = (0.6 * steering_val) + (1.0 - 0.6) * steering_val_acc;
steering_val = steering_val_acc;
return steering_val;
}
long int PID::Time_stepper(){
auto timeNow = std::chrono::steady_clock::now();
auto msSinceCreation = std::chrono::duration_cast<std::chrono::milliseconds>(timeNow - m_timeBegin);
return msSinceCreation.count( );
}
| true |
faa3b813a5127f9eac2faffd191e32fc3ad803db | C++ | bulingma/DataStructAndAlgorithm | /bitmap/main_o1_init.cpp | GB18030 | 2,054 | 2.875 | 3 | [
"MIT"
] | permissive | /******************************************************************************************
* Data Structures and Algorithm in C++ .
* Junhui DENG(deng@tsinghua.edu.cn) is first author, Yuguang Ma learnadd and modify it .
* All rights reserved.
******************************************************************************************/
#pragma warning(disable : 4996 4800)
#include "../_share/util.h"
#include "bitmap.h"
//#include "bitmap_O1_init.h"
/* ͷļֻһ;
bitmap.h: ռ临Ӷ
bitmap_O1_init.h: ԿռΪʡʼʱ */
/******************************************************************************************
* λͼ
******************************************************************************************/
int testBitmap ( int n ) {
bool* B = new bool[n];
memset ( B, 0, n * sizeof ( bool ) ); //λͼ漴O(n)ʱʼ
Bitmap M ( n );
for ( int i = 0; i < 9 * n; i++ ) {
Rank k = dice ( n );
if ( dice ( 2 ) )
{
printf ( "set(%d) ...", k ); //set(k)
B[k] = true;
M.set ( k );
}
else
{
printf ( "clear(%d) ...", k ); //clear(k)
B[k] = false;
M.clear ( k );
}
printf ( "done\n CRC: " );
for ( int j = 0; j < n; j++ )
printf ( "%6c", B[j] == M.test ( j ) ? ' ' : '!' );
printf ( "\n B[]: " );
for ( int j = 0; j < n; j++ )
printf ( "%6c", B[j] ? 'x' : '.' );
printf ( "\n M[]: " );
for ( int j = 0; j < n; j++ )
printf ( "%6c", M.test ( j ) ? 'x' : '.' );
printf ( "\n\n\n" );
}
delete [] B;
return 0;
}
/******************************************************************************************
* λͼ
******************************************************************************************/
int main ( int argc, char* argv[] ) {
int iNumber = 10;
srand ( ( unsigned int ) time ( NULL ) ); //
return testBitmap (iNumber); //
} | true |
bfbbdecf194d54bbc28ad9d6d2fe5137f206af13 | C++ | alicezywang/cognition | /src/micros/resource_management/cognition/cognition_resource/math_model_lib/crowd_compute/crowd_evaluate/src/crowd_evaluate.cpp | UTF-8 | 12,275 | 2.578125 | 3 | [] | no_license | #include "crowd_evaluate/crowd_evaluate.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <math.h>
namespace warning_expel_model
{
//#######################################
// Implementation of functions
//#######################################
// Predict the behavior of the crowd
Behavior predictCrowdBehavior(const BattleArraySeq & scene_seq, Line frontier)
{
Behavior behavior = CROWD_MOTIONLESS; // behavior of the crowd
// Statistic energies of all scenes
int scene_number = scene_seq.size();
float crowd_kinetic[scene_number];
float crowd_muddle[scene_number];
float crowd_forward[scene_number];
float crowd_disperse[scene_number];
for(int i=0; i<scene_number; i++)
{
SoldierArraySeq scene;
scene = scene_seq[i].battle_array;
// Calculate four kinds of energies
Energy scene_energy;
scene_energy = calcuSceneEnergy(scene, frontier);
crowd_kinetic[i] = scene_energy.kinetic;
crowd_muddle[i] = scene_energy.muddle;
crowd_forward[i] = scene_energy.forward;
crowd_disperse[i] = scene_energy.disperse;
}
// Predict motionless by kinetic energy
HalfSeq stats_energy;
float average_crowd_energy = 0;
stats_energy= statsHalfSequence(crowd_kinetic);
if(stats_energy.front_average > stats_energy.end_average)
average_crowd_energy = stats_energy.end_average; // using right-half average if kinetic-energy decreases
else
average_crowd_energy = stats_energy.max_value;
if(average_crowd_energy < K_ENERGY_THRES) // predict motionless by low velocity
behavior = CROWD_MOTIONLESS;
else
{
stats_energy = statsHalfSequence(crowd_muddle);
if(stats_energy.front_average > stats_energy.end_average)
average_crowd_energy = stats_energy.end_average;
else
average_crowd_energy = stats_energy.max_value;
if(average_crowd_energy < M_ENERGY_THRES)
{
// Predict forwards and retreat by forwards energy
stats_energy = statsHalfSequence(crowd_forward);
if(stats_energy.front_average > stats_energy.end_average)
average_crowd_energy = stats_energy.end_average; // using right-half average if forward-energy decreases
else
average_crowd_energy = stats_energy.max_value;
if(average_crowd_energy < PI/2) // predict backwards by low muddleless and low cross-angle
behavior = CROWD_BACKWARDS;
else
behavior = CROWD_FORWARDS; // predict forwards by low muddleless and high cross-angle
}
else
{
behavior = CROWD_PANIC; // predict panic by high velocity and high muddleless
}
}
return behavior;
}
// Calculate the average velocity of the crowd
Velocity calcuCrowdVelocity(const BattleArraySeq & scene_seq)
{
Velocity crowd_velocity;
crowd_velocity.x_velocity = 0;
crowd_velocity.y_velocity = 0;
// Average the velocity of crowd across scenes and soldiers
int scene_number = scene_seq.size();
for(int i=0; i<scene_number; i++)
{
SoldierArraySeq scene;
scene = scene_seq[i].battle_array;
int soldier_number = scene.size();
float scene_x_velocity = 0;
float scene_y_velocity = 0;
for(int j=0; j<soldier_number; j++)
{
SoldierPose soldier;
soldier = scene[j];
scene_x_velocity += soldier.x_velocity;
scene_y_velocity += soldier.y_velocity;
}
crowd_velocity.x_velocity += scene_x_velocity / soldier_number;
crowd_velocity.y_velocity += scene_y_velocity / soldier_number;
}
crowd_velocity.x_velocity = crowd_velocity.x_velocity / scene_number;
crowd_velocity.y_velocity = crowd_velocity.y_velocity / scene_number;
return crowd_velocity;
}
// Calculate the center of the crowd
Coordinate calcuCrowdCenter(const BattleArraySeq & scene_seq)
{
Coordinate crowd_center;
crowd_center.x = 0;
crowd_center.y = 0;
// Average the velocity of corwd across scenes and soldiers
int scene_number = scene_seq.size();
for(int i=0; i<scene_number; i++)
{
SoldierArraySeq scene;
scene = scene_seq[i].battle_array;
int soldier_number = scene.size();
float scene_x_coordinate = 0;
float scene_y_coordinate = 0;
for (int j=0; j<soldier_number; j++)
{
SoldierPose soldier;
soldier = scene[j];
scene_x_coordinate += soldier.x;
scene_y_coordinate += soldier.y;
}
crowd_center.x += scene_x_coordinate / soldier_number;
crowd_center.y += scene_y_coordinate / soldier_number;
}
crowd_center.x = crowd_center.x / scene_number;
crowd_center.y = crowd_center.y / scene_number;
return crowd_center;
}
// Calculate the velocity of a scene
Velocity calcuSceneVelocity(const SoldierArraySeq & scene)
{
Velocity scene_velocity;
scene_velocity.x_velocity = 0;
scene_velocity.y_velocity = 0;
// Average the velocity of soldiers
int soldier_number = scene.size();
for(int j=0; j<soldier_number; j++)
{
SoldierPose soldier;
soldier = scene[j];
scene_velocity.x_velocity += soldier.x_velocity;
scene_velocity.y_velocity += soldier.y_velocity;
}
scene_velocity.x_velocity = scene_velocity.x_velocity / soldier_number;
scene_velocity.y_velocity = scene_velocity.y_velocity / soldier_number;
return scene_velocity;
}
// Calculate the center of a scene
Coordinate calcuSceneCenter(const SoldierArraySeq & scene)
{
Coordinate scene_center;
scene_center.x = 0;
scene_center.y = 0;
// Calculate the center coordinate of all soldiers
int soldier_number = scene.size();
for(int j=0; j<soldier_number; j++)
{
SoldierPose soldier;
soldier = scene[j];
scene_center.x += soldier.x;
scene_center.y += soldier.y;
}
scene_center.x = scene_center.x / soldier_number;
scene_center.y = scene_center.y / soldier_number;
return scene_center;
}
// Calculate four types of energies of a scene
Energy calcuSceneEnergy(const SoldierArraySeq & scene, Line frontier)
{
int soldier_number=scene.size();
// Calculate kinetic energy
float kinetic_energy = 0;
float delta = 1e-0; // TODO: parameter over the kinetic energy
for(int j=0; j<soldier_number; j++)
{
SoldierPose soldier;
soldier = scene[j];
kinetic_energy += pow(soldier.x_velocity, 2) + pow(soldier.y_velocity, 2);
}
kinetic_energy = delta * kinetic_energy / soldier_number;
// Calculate muddleless energy
float muddle_energy = 0;
float alpha = 0.6; // TODO: percentage of angle cosine in muddleless
float beta = 0.4; // TODO: percentage of differene of velocities
float gamma = 1e-0; // TODO: parameter over the muddleless energy
for(int i=0; i<soldier_number-1; i++)
{
for(int j=i+1; j<soldier_number; j++)
{
SoldierPose soldier1, soldier2;
soldier1 = scene[i];
soldier2 = scene[j];
Velocity velocity1, velocity2;
velocity1.x_velocity = soldier1.x_velocity;
velocity1.y_velocity = soldier1.y_velocity;
velocity2.x_velocity = soldier2.x_velocity;
velocity2.y_velocity = soldier2.y_velocity;
muddle_energy += alpha * calcuAngleCosine(velocity1, velocity2);
float magnitude1 = sqrt(pow(velocity1.x_velocity, 2) + pow(velocity1.y_velocity, 2));
float magnitude2 = sqrt(pow(velocity2.x_velocity, 2) + pow(velocity2.y_velocity, 2));
muddle_energy += beta * (fabs(magnitude1 - magnitude2));
}
}
int total_number = (soldier_number - 1) * (soldier_number - 2) / 2;
muddle_energy = gamma * muddle_energy / total_number;
// Calculate forward energy
float forward_energy = 0;
for(int j=0; j<soldier_number; j++)
{
SoldierPose soldier;
soldier = scene[j];
forward_energy += calcuForwardAngle(soldier, frontier);
}
forward_energy = forward_energy / soldier_number;
// Calculate disperse energy
float disperse_energy = 0;
float sigma = 1e-0; // TODO: parameter over disperse energy
Coordinate scene_center = calcuSceneCenter(scene);
for(int j=0; j<soldier_number; j++)
{
SoldierPose soldier;
soldier = scene[j];
disperse_energy += sqrt(pow(soldier.x - scene_center.x, 2) + pow(soldier.y - scene_center.y, 2));
}
disperse_energy = sigma * disperse_energy / soldier_number;
// Assemble scene energies
Energy scene_energy;
scene_energy.kinetic = kinetic_energy;
scene_energy.muddle = muddle_energy;
scene_energy.forward = forward_energy;
scene_energy.disperse = disperse_energy;
return scene_energy;
}
// Calculate the angle between the velocity and the direction to the frontier
float calcuForwardAngle(SoldierPose soldier, Line frontier)
{
Coordinate coordinate;
coordinate.x = soldier.x;
coordinate.y = soldier.y;
Velocity velocity;
velocity.x_velocity = soldier.x_velocity;
velocity.y_velocity = soldier.y_velocity;
// Calculate the foot point from the solider to the frontier
Coordinate foot_point;
float t1, t2, t;
t1 = 0;
t2 = 0;
t = 0;
t1 += (coordinate.x - frontier.start_point.x) * (frontier.start_point.x - frontier.end_point.x);
t1 += (coordinate.y - frontier.start_point.y) * (frontier.start_point.y - frontier.end_point.y);
t2 += pow(frontier.start_point.x - frontier.end_point.x, 2) + pow(frontier.start_point.y - frontier.end_point.y, 2);
t = t1 / t2;
foot_point.x = (frontier.start_point.x - frontier.end_point.x) * t + frontier.start_point.x;
foot_point.y = (frontier.start_point.y - frontier.end_point.y) * t + frontier.start_point.y;
Velocity velocity_twf;
// Calculate the direction from the crowd center to the foot point
velocity_twf.x_velocity = foot_point.x - coordinate.x;
velocity_twf.y_velocity = foot_point.y - coordinate.y;
// Calculte the angle of two velocities
float angle_cosine = calcuAngleCosine(velocity_twf, velocity);
float forward_angle = acos(angle_cosine);
return forward_angle;
}
// Calculate the cosine value of the angle between two directions
float calcuAngleCosine(Velocity velocity1, Velocity velocity2)
{
float angle_cosine = 0;
angle_cosine = (velocity1.x_velocity * velocity2.x_velocity + velocity1.y_velocity * velocity2.y_velocity);
angle_cosine /= std::max(sqrt(pow(velocity1.x_velocity, 2) + pow(velocity1.y_velocity, 2)), (double)TINY_VALUE); // To avoid numerical problem
angle_cosine /= std::max(sqrt(pow(velocity2.x_velocity, 2) + pow(velocity2.y_velocity, 2)), (double)TINY_VALUE);
return angle_cosine;
}
// Statistic front and end averages and the max and min values of a sequence
HalfSeq statsHalfSequence(const float sequence[])
{
float left_sum = 0;
float right_sum = 0;
int left_num = 0;
int right_num = 0;
float max_value = 0;
float min_value = INF_VALUE;
int scene_num = sizeof(sequence)/sizeof(sequence[0]);
for(int i=0; i<scene_num; i++)
{
if(i < ceil(scene_num/2)) // front part
{
left_sum += sequence[i];
left_num += 1;
}
else // end part
{
right_sum += sequence[i];
right_num += 1;
}
if(sequence[i] > max_value) // maximum value
max_value = sequence[i];
if(sequence[i] < min_value) // minimum value
min_value = sequence[i];
}
HalfSeq stats_seq;
stats_seq.front_average = left_sum / left_num;
stats_seq.end_average = right_sum / right_num;
stats_seq.max_value = max_value;
stats_seq.min_value = min_value;
return stats_seq;
}
}
| true |
f3ce41c4d2acfd15a00387fe0b1d3265515a84ef | C++ | luis8230/cc1-L2017-1 | /bisiesto.cpp | ISO-8859-10 | 301 | 2.75 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int anio ;
cout<<"ingrese un ao "<<endl;
cin>> anio ;
if (anio % 4 == 0){
if((anio%100)!=0 || (anio% 400) ==0)
cout<<"es bisiesto"<<endl;
}
else
cout<<"no es bisiesto"<<endl;
return 0;
}
| true |
f51b14ad0a9338b43a8638c05bc3099c7026b0f3 | C++ | AlexPandaBear/vortex | /src/SimKernel.cxx | UTF-8 | 20,789 | 2.90625 | 3 | [] | no_license | #include "SimKernel.hxx"
SimKernel::SimKernel(bool x_periodic, bool y_periodic, double x_period, double y_period, std::string method) :
m_X_periodic(x_periodic),
m_Y_periodic(y_periodic),
m_X_period(x_period),
m_Y_period(y_period),
m_method(method) {}
SimKernel::~SimKernel() {}
void SimKernel::addVortex(Vortex &v)
{
v_vtx.push_back(v);
}
void SimKernel::buildTimeSample(double t0, double tEnd, size_t steps)
{
double deltaT(tEnd - t0);
if (!(deltaT > 0.))
{
throw std::invalid_argument("t0 must be smaller than tEnd");
}
for (size_t i = 0; i <= steps; i++)
{
v_time.push_back(t0 + ((double) i/steps) * deltaT);
}
}
void SimKernel::setXPeriodicityTo(bool periodic, double period)
{
m_X_periodic = periodic;
m_X_period = period;
}
void SimKernel::setYPeriodicityTo(bool periodic, double period)
{
m_Y_periodic = periodic;
m_Y_period = period;
}
void SimKernel::setMethodTo(std::string method)
{
m_method = method;
}
bool SimKernel::readyToSim()
{
if (m_X_period)
{
double x;
for (auto &v : v_vtx)
{
x = v.getX();
if (x > m_X_period || x < 0.)
{
return false;
}
}
}
if (m_Y_period)
{
double y;
for (auto &v : v_vtx)
{
y = v.getY();
if (y > m_Y_period || y < 0.)
{
return false;
}
}
}
return true;
}
void SimKernel::integrate(DataManager &dm, size_t step)
{
double dt(v_time[step+1] - v_time[step]);
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(dm.getUAt(step, i) * dt, dm.getVAt(step, i) * dt);
dm.storeXAt(step+1, i, v_vtx[i].getX());
dm.storeYAt(step+1, i, v_vtx[i].getY());
dm.storeCirculationAt(step+1, i, v_vtx[i].getCirculation());
dm.storeRegRadiusAt(step+1, i, v_vtx[i].getRegRadius());
}
}
void SimKernel::computeEEStep(DataManager &dm, size_t step, size_t firstVtx, size_t lastVtx) const
{
double x, y, u, v;
Vortex vtx(0,0,0,0);
for (size_t i = firstVtx; i < lastVtx; i++)
{
x = v_vtx[i].getX();
y = v_vtx[i].getY();
u = 0.;
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
vtx = v_vtx[j];
if (j!=i)
{
u += vtx.computeXInducedVelocityAt(x, y);
v += vtx.computeYInducedVelocityAt(x, y);
}
}
dm.storeUAt(step, i, u);
dm.storeVAt(step, i, v);
}
}
void SimKernel::computeEEStep_multithread(DataManager &dm, size_t step, size_t nb_threads)
{
if (nb_threads < 1)
{
std::ostringstream ss;
ss << "Unable to perform computation on " << nb_threads << " threads";
throw std::invalid_argument(ss.str());
}
std::vector<std::thread> v_threads;
size_t firstVtx(0), lastVtx(m_nb_vtx/nb_threads);
for (size_t i = 0; i < nb_threads-1; i++)
{
v_threads.push_back(std::thread(&SimKernel::computeEEStep, this, std::ref(dm), step, firstVtx, lastVtx));
firstVtx = lastVtx;
lastVtx += m_nb_vtx/nb_threads;
}
lastVtx = m_nb_vtx;
computeEEStep(dm, step, firstVtx, lastVtx);
for (auto &th : v_threads) {th.join();}
integrate(dm, step);
}
void SimKernel::computeRK4Substep(std::vector<Vortex> &workingCopy, std::vector<double> &k_u, std::vector<double> &k_v, size_t step, size_t firstVtx, size_t lastVtx, size_t substep) const
{
double x, y;
Vortex vtx(0,0,0,0);
for (size_t i = firstVtx; i < lastVtx; i++)
{
x = workingCopy[i].getX();
y = workingCopy[i].getY();
k_u[i] = 0.;
k_v[i] = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
vtx = workingCopy[j];
if (j!=i)
{
k_u[i] += vtx.computeXInducedVelocityAt(x, y);
k_v[i] += vtx.computeYInducedVelocityAt(x, y);
}
}
}
}
void SimKernel::computeRK4Step_multithread(DataManager &dm, size_t step, size_t nb_threads)
{
if (nb_threads < 1)
{
std::ostringstream ss;
ss << "Unable to perform computation on " << nb_threads << " threads";
throw std::invalid_argument(ss.str());
}
//association of vortices to threads
std::vector<size_t> v_separations;
for (size_t i = 0; i < nb_threads; i++)
{
v_separations.push_back(i*m_nb_vtx/nb_threads);
}
//initialisation
std::vector<double> k1_u(m_nb_vtx, 0.), k2_u(m_nb_vtx, 0.), k3_u(m_nb_vtx, 0.), k4_u(m_nb_vtx, 0.);
std::vector<double> k1_v(m_nb_vtx, 0.), k2_v(m_nb_vtx, 0.), k3_v(m_nb_vtx, 0.), k4_v(m_nb_vtx, 0.);
double dt(v_time[step+1] - v_time[step]);
std::vector<Vortex> workingCopy;
for (auto v : v_vtx) {workingCopy.push_back(v);}
//computation of k1
std::vector<std::thread> v_threads_k1;
for (size_t i = 0; i < nb_threads-1; i++)
{
v_threads_k1.push_back(std::thread(&SimKernel::computeRK4Substep, this, std::ref(workingCopy), std::ref(k1_u), std::ref(k1_v), step, v_separations[i], v_separations[i+1], 1));
}
computeRK4Substep(workingCopy, k1_u, k1_v, step, v_separations[nb_threads-1], m_nb_vtx, 1);
for (auto &th : v_threads_k1) {th.join();}
for (size_t i = 0; i < m_nb_vtx; i++)
{
workingCopy[i].move(k1_u[i]*0.5*dt, k1_v[i]*0.5*dt);
}
//computation of k2
std::vector<std::thread> v_threads_k2;
for (size_t i = 0; i < nb_threads-1; i++)
{
v_threads_k2.push_back(std::thread(&SimKernel::computeRK4Substep, this, std::ref(workingCopy), std::ref(k2_u), std::ref(k2_v), step, v_separations[i], v_separations[i+1], 2));
}
computeRK4Substep(workingCopy, k2_u, k2_v, step, v_separations[nb_threads-1], m_nb_vtx, 2);
for (auto &th : v_threads_k2) {th.join();}
for (size_t i = 0; i < m_nb_vtx; i++)
{
workingCopy[i].setX(v_vtx[i].getX() + k2_u[i]*0.5*dt);
workingCopy[i].setY(v_vtx[i].getY() + k2_v[i]*0.5*dt);
}
//computation of k3
std::vector<std::thread> v_threads_k3;
for (size_t i = 0; i < nb_threads-1; i++)
{
v_threads_k3.push_back(std::thread(&SimKernel::computeRK4Substep, this, std::ref(workingCopy), std::ref(k3_u), std::ref(k3_v), step, v_separations[i], v_separations[i+1], 3));
}
computeRK4Substep(workingCopy, k3_u, k3_v, step, v_separations[nb_threads-1], m_nb_vtx, 3);
for (auto &th : v_threads_k3) {th.join();}
for (size_t i = 0; i < m_nb_vtx; i++)
{
workingCopy[i].setX(v_vtx[i].getX() + k3_u[i]*dt);
workingCopy[i].setY(v_vtx[i].getY() + k3_v[i]*dt);
}
//computation of k4
std::vector<std::thread> v_threads_k4;
for (size_t i = 0; i < nb_threads-1; i++)
{
v_threads_k4.push_back(std::thread(&SimKernel::computeRK4Substep, this, std::ref(workingCopy), std::ref(k4_u), std::ref(k4_v), step, v_separations[i], v_separations[i+1], 4));
}
computeRK4Substep(workingCopy, k4_u, k4_v, step, v_separations[nb_threads-1], m_nb_vtx, 4);
for (auto &th : v_threads_k4) {th.join();}
//storage
for (size_t i = 0; i < m_nb_vtx; i++)
{
dm.storeUAt(step, i, (k1_u[i] + k2_u[i]*2. + k3_u[i]*2. + k4_u[i])/6.);
dm.storeVAt(step, i, (k1_v[i] + k2_v[i]*2. + k3_v[i]*2. + k4_v[i])/6.);
}
integrate(dm, step);
}
void SimKernel::computeEAStep(DataManager &dm, size_t step)
{
double x, y, u, v;
Vortex vtx(0,0,0,0);
double dt(v_time[step+1] - v_time[step]);
std::vector<Vortex> workingCopy;
for (auto v : v_vtx) {workingCopy.push_back(v);}
for (size_t i = 0; i < m_nb_vtx; i++)
{
x = workingCopy[i].getX();
y = workingCopy[i].getY();
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
vtx = workingCopy[j];
if (j!=i)
{
u += vtx.computeXInducedVelocityAt(x, y);
}
}
dm.storeUAt(step, i, u);
}
for (size_t i = 0; i < m_nb_vtx; i++) {workingCopy[i].move(dt*dm.getUAt(step, i), 0.);}
for (size_t i = 0; i < m_nb_vtx; i++)
{
x = workingCopy[i].getX();
y = workingCopy[i].getY();
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
vtx = workingCopy[j];
if (j!=i)
{
v += vtx.computeYInducedVelocityAt(x, y);
}
}
dm.storeVAt(step, i, v);
}
integrate(dm, step);
}
void SimKernel::computeEBStep(DataManager &dm, size_t step)
{
double x, y, u, v;
Vortex vtx(0,0,0,0);
double dt(v_time[step+1] - v_time[step]);
std::vector<Vortex> workingCopy;
for (auto v : v_vtx) {workingCopy.push_back(v);}
for (size_t i = 0; i < m_nb_vtx; i++)
{
x = workingCopy[i].getX();
y = workingCopy[i].getY();
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
vtx = workingCopy[j];
if (j!=i)
{
v += vtx.computeYInducedVelocityAt(x, y);
}
}
dm.storeVAt(step, i, v);
}
for (size_t i = 0; i < m_nb_vtx; i++) {workingCopy[i].move(0., dt*dm.getVAt(step, i));}
for (size_t i = 0; i < m_nb_vtx; i++)
{
x = workingCopy[i].getX();
y = workingCopy[i].getY();
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
vtx = workingCopy[j];
if (j!=i)
{
u += vtx.computeXInducedVelocityAt(x, y);
}
}
dm.storeUAt(step, i, u);
}
integrate(dm, step);
}
void SimKernel::computeSVStep(DataManager &dm, size_t step)
{
double x, y, u, v;
Vortex vtx(0,0,0,0);
double dt(v_time[step+1] - v_time[step]);
std::vector<double> U_pt1(m_nb_vtx, 0.), U_pt2(m_nb_vtx, 0.);
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
U_pt1[i] = u;
}
for (size_t i = 0; i < m_nb_vtx; i++) {v_vtx[i].move(0.5*dt*U_pt1[i], 0.);}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeVAt(step, i, v);
}
for (size_t i = 0; i < m_nb_vtx; i++) {v_vtx[i].move(0., dt*dm.getVAt(step, i));}
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
U_pt2[i] = u;
}
for (size_t i = 0; i < m_nb_vtx; i++) {v_vtx[i].move(0.5*dt*U_pt2[i], 0.);}
for (size_t i = 0; i < m_nb_vtx; i++) //integrate() w/o double call to move()
{
dm.storeUAt(step, i, 0.5*(U_pt1[i]+U_pt2[i]));
dm.storeXAt(step+1, i, v_vtx[i].getX());
dm.storeYAt(step+1, i, v_vtx[i].getY());
dm.storeCirculationAt(step+1, i, v_vtx[i].getCirculation());
dm.storeRegRadiusAt(step+1, i, v_vtx[i].getRegRadius());
}
}
void SimKernel::computeSVIStep(DataManager &dm, size_t step)
{
double x, y, u, v;
Vortex vtx(0,0,0,0);
double dt(v_time[step+1] - v_time[step]);
std::vector<double> V_pt1(m_nb_vtx, 0.), V_pt2(m_nb_vtx, 0.);
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
V_pt1[i] = v;
}
for (size_t i = 0; i < m_nb_vtx; i++) {v_vtx[i].move(0., 0.5*dt*V_pt1[i]);}
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeUAt(step, i, u);
}
for (size_t i = 0; i < m_nb_vtx; i++) {v_vtx[i].move(dt*dm.getUAt(step, i), 0.);}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
V_pt2[i] = v;
}
for (size_t i = 0; i < m_nb_vtx; i++) {v_vtx[i].move(0., 0.5*dt*V_pt2[i]);}
for (size_t i = 0; i < m_nb_vtx; i++) //integrate() w/o double call to move()
{
dm.storeVAt(step, i, 0.5*(V_pt1[i]+V_pt2[i]));
dm.storeXAt(step+1, i, v_vtx[i].getX());
dm.storeYAt(step+1, i, v_vtx[i].getY());
dm.storeCirculationAt(step+1, i, v_vtx[i].getCirculation());
dm.storeRegRadiusAt(step+1, i, v_vtx[i].getRegRadius());
}
}
/*
void SimKernel::computeTestStep(DataManager &dm, size_t step)
{
double u, v;
Vortex vtx(0,0,0,0);
double dt(v_time[step+1] - v_time[step]);
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeUAt(step, i, u);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(dt*dm.getUAt(step,i), 0.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeVAt(step, i, v);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(0., 0.5*dt*dm.getVAt(step, i));
dm.storeYAt(step+1, i, v_vtx[i].getY());
}
for (size_t i = 0; i < m_nb_vtx; i++) //integrate() w/o double call to move()
{
dm.storeXAt(step+1, i, v_vtx[i].getX());
dm.storeCirculationAt(step+1, i, v_vtx[i].getCirculation());
dm.storeRegRadiusAt(step+1, i, v_vtx[i].getRegRadius());
v_vtx[i].move(0., 0.5*dt*dm.getVAt(step, i));
}
}
void SimKernel::computeS3Step(DataManager &dm, size_t step)
{
double u, v;
Vortex vtx(0,0,0,0);
double dt(v_time[step+1] - v_time[step]);
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeUAt(step, i, u);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(dt*dm.getUAt(step,i), 0.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeVAt(step, i, v);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(0., -dt*dm.getVAt(step,i)/24.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeUAt(step, i, u);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(-2.*dt*dm.getUAt(step,i)/3., 0.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeVAt(step, i, v);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(0., 3.*dt*dm.getVAt(step,i)/4.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeUAt(step, i, u);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(2.*dt*dm.getUAt(step,i)/3., 0.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeVAt(step, i, v);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(0., 7.*dt*dm.getVAt(step,i)/24.);
dm.storeXAt(step+1, i, v_vtx[i].getX());
dm.storeYAt(step+1, i, v_vtx[i].getY());
dm.storeCirculationAt(step+1, i, v_vtx[i].getCirculation());
dm.storeRegRadiusAt(step+1, i, v_vtx[i].getRegRadius());
}
}
void SimKernel::computeTest2Step(DataManager &dm, size_t step)
{
double u, v;
Vortex vtx(0,0,0,0);
double dt(v_time[step+1] - v_time[step]);
std::vector<double> U_tmp(m_nb_vtx, 0.), V_tmp(m_nb_vtx, 0.);
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
U_tmp[i] = u;
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(0.5*dt*U_tmp[i], 0.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
u = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
u += v_vtx[j].computeXInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeUAt(step, i, u);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(dt * (dm.getUAt(step, i) - 0.5*U_tmp[i]), 0.);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
V_tmp[i] = v;
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(0., 0.5*dt*V_tmp[i]);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v += v_vtx[j].computeYInducedVelocityAt(v_vtx[i].getX(), v_vtx[i].getY());
}
}
dm.storeVAt(step, i, v);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].move(0., 0.5*dt * (dm.getVAt(step, i) - V_tmp[i]));
dm.storeYAt(step+1, i, v_vtx[i].getY());
}
for (size_t i = 0; i < m_nb_vtx; i++) //integrate() w/o double call to move()
{
dm.storeXAt(step+1, i, v_vtx[i].getX());
dm.storeCirculationAt(step+1, i, v_vtx[i].getCirculation());
dm.storeRegRadiusAt(step+1, i, v_vtx[i].getRegRadius());
v_vtx[i].move(0., 0.5*dt*dm.getVAt(step, i));
}
}
*/
void SimKernel::printSimProgression(size_t step) const
{
std::cout << "\rComputing step " << step+1 << " out of " << m_nb_steps << " -- " << 100.*(step+1)/m_nb_steps << "% completed " << std::flush;
}
void SimKernel::sim(DataManager &dm, size_t nb_threads)
{
m_nb_vtx = v_vtx.size();
m_nb_steps = v_time.size()-1;
if (!readyToSim())
{
throw std::invalid_argument("Bad choice of vortices");
}
if (m_X_periodic)
{
for (size_t i = 0; i < m_nb_vtx; i++)
{
v_vtx[i].setXPeriodicity(m_X_periodic);
v_vtx[i].setXPeriod(m_X_period);
v_vtx[i].prepareFactors();
}
}
dm.reset(m_nb_steps, m_nb_vtx);
for (size_t t = 0; t < m_nb_steps+1; t++)
{
dm.storeTimeAt(t, v_time[t]);
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
dm.storeFluidId(i, v_vtx[i].getFluidId());
}
for (size_t i = 0; i < m_nb_vtx; i++)
{
dm.storeXAt(0, i, v_vtx[i].getX());
dm.storeYAt(0, i, v_vtx[i].getY());
dm.storeCirculationAt(0, i, v_vtx[i].getCirculation());
dm.storeRegRadiusAt(0, i, v_vtx[i].getRegRadius());
}
if (m_method == "euler")
{
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeEEStep_multithread(dm, t, nb_threads);
}
}
else if (m_method == "rk4")
{
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeRK4Step_multithread(dm, t, nb_threads);
}
}
else if (m_method == "eulerA")
{
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeEAStep(dm, t);
}
}
else if (m_method == "eulerB")
{
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeEBStep(dm, t);
}
}
else if (m_method == "sv")
{
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeSVStep(dm, t);
}
}
else if (m_method == "svi")
{
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeSVIStep(dm, t);
}
}
else if (m_method == "test")
{
double v_start;
double dt(v_time[1]-v_time[0]);
for (size_t i = 0; i < m_nb_vtx; i++) //initialization
{
v_start = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v_start += v_vtx[j].computeYInducedVelocityAt(dm.getXAt(0,i), dm.getYAt(0,i));
}
}
v_vtx[i].move(0., 0.5*dt*v_start);
}
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeTestStep(dm, t);
}
}
else if (m_method == "test2")
{
double v_start;
double dt(v_time[1]-v_time[0]);
for (size_t i = 0; i < m_nb_vtx; i++) //initialization
{
v_start = 0.;
for (size_t j = 0; j < m_nb_vtx; j++)
{
if (j!=i)
{
v_start += v_vtx[j].computeYInducedVelocityAt(dm.getXAt(0,i), dm.getYAt(0,i));
}
}
v_vtx[i].move(0., 0.5*dt*v_start);
}
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeTest2Step(dm, t);
}
}
else if (m_method == "test3")
{
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeS3Step(dm, t);
}
}
else
{
throw std::invalid_argument("Unknown numerical method " + m_method);
}
/*
switch (m_method)
{
case "euler":
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeEEStep_multithread(dm, t, nb_threads);
}
case "rk4":
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeRK4Step_multithread(dm, t, nb_threads);
}
case "eulerA":
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeEAStep(dm, t);
}
case "eulerB":
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeEBStep(dm, t);
}
case "sv":
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeSVStep(dm, t);
}
case "svi":
for (size_t t = 0; t < m_nb_steps; t++)
{
printSimProgression(t);
computeSVIStep(dm, t);
}
default:
throw std::invalid_argument("Unknown numerical method " + m_method);
}
*/
std::cout << std::endl;
} | true |
d02406a845ca7a67c5d42dbad438e1aa29ec694b | C++ | budelphine/_cpp_modules | /day03/ex04/NinjaTrap.cpp | UTF-8 | 11,086 | 3.1875 | 3 | [] | no_license | #include "NinjaTrap.hpp"
NinjaTrap::NinjaTrap() : ClapTrap("defaultNinjaTrap", 60, 60, 120, 120, 1, 60, 50, 0)
{
std::cout << "* NINJ4-TP Default constructor called *" << std::endl;
std::cout << GREEN_COLOR << this->getName() << ": " << END_COLOR;
std::cout << "Hey, best friend!" << std::endl;
}
NinjaTrap::NinjaTrap(std::string name) : ClapTrap(name, 60, 60, 120, 120, 1, 60, 50, 0)
{
std::cout << "* NINJ4-TP Default named constructor called *" << std::endl;
std::cout << GREEN_COLOR << this->getName() << ": " << END_COLOR;
std::cout << "Let me teach you the ways of magic!" << std::endl;
}
NinjaTrap::NinjaTrap(const NinjaTrap ©) : ClapTrap(copy)
{
std::cout << "* NINJ4-TP Copy constructor called *" << std::endl;
std::cout << GREEN_COLOR << this->getName() << ": " << END_COLOR;
std::cout << "Sooooo... how are things?" << std::endl;
}
NinjaTrap::~NinjaTrap()
{
std::cout << "* NINJ4-TP Destructor called *" << std::endl;
std::cout << BLUE_COLOR << this->getName() << END_COLOR << ": ";
std::cout << "Defragmenting!" << std::endl;
}
NinjaTrap& NinjaTrap::operator=(const NinjaTrap &other) {
std::cout << "* NINJ4-TP Assignation operator called *" << std::endl;
std::cout << GREEN_COLOR << this->getName() << ": " << END_COLOR;
std::cout << "You can't just program this level of excitement!" << std::endl;
this->name_ = other.getName();
this->hitPoints_ = other.getHitPoints();
this->maxHitPoints_ = other.getMaxHitPoints();
this->energyPoints_ = other.getEnergyPoints();
this->level_ = other.getLevel();
this->meleeAttackDamage_ = other.getMeleeAttackDamage();
this->rangedAttackDamage_ = other.getRangedAttackDamage();
this->armorDamageReduction_ = other.getArmorDamageReduction();
return (*this);
}
unsigned int NinjaTrap::rangedAttack(std::string const& targetName)
{
std::string randomAttackPhrase[6] = {
"I'm cloaking...",
"Roses are red and/Violets are blue/Wait... how many syllables was that?",
"Shoot him... he's the real one...",
"I'm a robot ninja...",
"I'm invisible!",
"Calm down!"
};
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
std::cout << "* NINJ4-TP " << BLUE_COLOR << this->getName() << END_COLOR;
std::cout << " attacks " << VIOLET_COLOR << targetName << END_COLOR;
std::cout << " at *range*, causing " << this->getRangedAttackDamage() << " points of damage! *" << std::endl;
std::cout << randomAttackPhrase[std::rand() % 6] << std::endl;
return ClapTrap::rangedAttack(targetName);
}
unsigned int NinjaTrap::meleeAttack(std::string const& targetName)
{
std::string randomAttackPhrase[5] = {
"Boiyoiyoiyoiyoing!",
"Zing! Bullet reflection!",
"I am rubber, and you are so dead!",
"I'm a superball!",
"Trouncy, flouncy... founcy... those aren't words."
};
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
std::cout << "* NINJ4-TP " << BLUE_COLOR << this->getName() << END_COLOR;
std::cout << " attacks " << VIOLET_COLOR << targetName << END_COLOR;
std::cout << " at *melee*, causing " << this->getMeleeAttackDamage() << " points of damage! *" << std::endl;
std::cout << randomAttackPhrase[std::rand() % 5] << std::endl;
return ClapTrap::meleeAttack(targetName);
}
unsigned int NinjaTrap::takeDamage(unsigned int damageAmount)
{
std::string randomTakeDamagePhrase[7] = {
"Why do I even feel pain?!",
"Why did they build me out of galvanized flesh?!",
"Ow hohoho, that hurts! Yipes!",
"My robotic flesh! AAHH!",
"Yikes! Ohhoho!",
"Woah! Oh! Jeez!",
"If only my chassis... weren't made of recycled human body parts! Wahahaha!"
};
std::string randomCriticalDamagePhrase[6] = {
"Pop pop!",
"Crit-i-cal!",
"That looks like it hurts!",
"WOW! I hit 'em!",
"Extra ouch!",
"Shwing!"
};
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
std::cout << "* NINJ4-TP " << RED_COLOR << this->getName() << END_COLOR;
std::cout << " has been damaged at " << damageAmount;
ClapTrap::takeDamage(damageAmount);
std::cout << " current Hit Point: " << GRAY_BACKGROND << this->getHitPoints() << " hp" << END_COLOR << " *" << std::endl;
std::cout << randomTakeDamagePhrase[std::rand() % 7] << std::endl;
if (this->hitPoints_ == 0)
{
std::cout << "* NINJ4-TP " << this->getName() << " died *" << std::endl;
std::cout << randomCriticalDamagePhrase[std::rand() % 6] << std::endl;
}
return this->getHitPoints();
}
unsigned int NinjaTrap::beRepaired(unsigned int healAmount)
{
std::string randomTakeDamagePhrase[5] = {
"Health! Eww, what flavor is red?",
"Health over here!",
"Sweet life juice!",
"I found health!",
"Healsies!"
};
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR;
std::cout << " has been healed at " << healAmount;
ClapTrap::beRepaired(healAmount);
std::cout << " current Hit Point: " << this->getHitPoints() << " hp *" << std::endl;
std::cout << randomTakeDamagePhrase[std::rand() % 5] << std::endl;
return this->getHitPoints();
}
unsigned int NinjaTrap::ninjaShoebox(NinjaTrap &enemy)
{
int randomAttackValue[10] = {7, 14, 21, 28, 35, 42, 49, 56, 63, 0};
std::string randomAttackName[10] = {
"I am a tornado of death and bullets!",
"Stop me before I kill again, except don't!",
"Hehehehe, mwaa ha ha ha, MWAA HA HA HA!",
"I'm on a roll!",
"Unts unts unts unts!",
"Ha ha ha! Fall before your robot overlord!",
"Can't touch this!",
"Ha! Keep 'em coming!",
"There is no way this ends badly!",
"This is why I was built!"
};
int randomAttackIndex = std::rand() % 10;
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
if (this->getEnergyPoints() < 25)
{
std::cout << "* NINJ4-TP has only " << this->getEnergyPoints() << " EnergyPoints - it's to low *" << std::endl;
return 0;
}
this->energyPoints_ -=25;
std::cout << "* NINJ4-TP " << BLUE_COLOR << this->getName() << END_COLOR << " use special ninjaShoebox attack";
std::cout << " on " << VIOLET_COLOR << enemy.getName() << END_COLOR << " *" << std::endl;
std::cout << randomAttackName[randomAttackIndex] << std::endl;
enemy.takeDamage(randomAttackValue[randomAttackIndex]);
return randomAttackValue[randomAttackIndex];
}
unsigned int NinjaTrap::ninjaShoebox(FragTrap &enemy)
{
int randomAttackValue[10] = {7, 14, 21, 28, 35, 42, 49, 56, 63, 0};
std::string randomAttackName[10] = {
"I am a tornado of death and bullets!",
"Stop me before I kill again, except don't!",
"Hehehehe, mwaa ha ha ha, MWAA HA HA HA!",
"I'm on a roll!",
"Unts unts unts unts!",
"Ha ha ha! Fall before your robot overlord!",
"Can't touch this!",
"Ha! Keep 'em coming!",
"There is no way this ends badly!",
"This is why I was built!"
};
int randomAttackIndex = std::rand() % 10;
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
if (this->getEnergyPoints() < 25)
{
std::cout << "* NINJ4-TP has only " << this->getEnergyPoints() << " EnergyPoints - it's to low *" << std::endl;
return 0;
}
this->energyPoints_ -=25;
std::cout << "* NINJ4-TP " << BLUE_COLOR << this->getName() << END_COLOR << " use special ninjaShoebox attack";
std::cout << " on " << VIOLET_COLOR << enemy.getName() << END_COLOR << " *" << std::endl;
std::cout << randomAttackName[randomAttackIndex] << std::endl;
enemy.takeDamage(randomAttackValue[randomAttackIndex]);
return randomAttackValue[randomAttackIndex];
}
unsigned int NinjaTrap::ninjaShoebox(ScavTrap &enemy)
{
int randomAttackValue[10] = {7, 14, 21, 28, 35, 42, 49, 56, 63, 0};
std::string randomAttackName[10] = {
"I am a tornado of death and bullets!",
"Stop me before I kill again, except don't!",
"Hehehehe, mwaa ha ha ha, MWAA HA HA HA!",
"I'm on a roll!",
"Unts unts unts unts!",
"Ha ha ha! Fall before your robot overlord!",
"Can't touch this!",
"Ha! Keep 'em coming!",
"There is no way this ends badly!",
"This is why I was built!"
};
int randomAttackIndex = std::rand() % 10;
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
if (this->getEnergyPoints() < 25)
{
std::cout << "* NINJ4-TP has only " << this->getEnergyPoints() << " EnergyPoints - it's to low *" << std::endl;
return 0;
}
this->energyPoints_ -=25;
std::cout << "* NINJ4-TP " << BLUE_COLOR << this->getName() << END_COLOR << " use special ninjaShoebox attack";
std::cout << " on " << VIOLET_COLOR << enemy.getName() << END_COLOR << " *" << std::endl;
std::cout << randomAttackName[randomAttackIndex] << std::endl;
enemy.takeDamage(randomAttackValue[randomAttackIndex]);
return randomAttackValue[randomAttackIndex];
}
unsigned int NinjaTrap::ninjaShoebox(ClapTrap &enemy)
{
int randomAttackValue[10] = {7, 14, 21, 28, 35, 42, 49, 56, 63, 0};
std::string randomAttackName[10] = {
"I am a tornado of death and bullets!",
"Stop me before I kill again, except don't!",
"Hehehehe, mwaa ha ha ha, MWAA HA HA HA!",
"I'm on a roll!",
"Unts unts unts unts!",
"Ha ha ha! Fall before your robot overlord!",
"Can't touch this!",
"Ha! Keep 'em coming!",
"There is no way this ends badly!",
"This is why I was built!"
};
int randomAttackIndex = std::rand() % 10;
if (this->getHitPoints() == 0)
{
std::cout << "* NINJ4-TP " << GREEN_COLOR << this->getName() << END_COLOR << " - is dead *" << std::endl;
std::cout << trapDeadMumbling_[std::rand() % 5] << std::endl;
return 0;
}
if (this->getEnergyPoints() < 25)
{
std::cout << "* NINJ4-TP has only " << this->getEnergyPoints() << " EnergyPoints - it's to low *" << std::endl;
return 0;
}
this->energyPoints_ -=25;
std::cout << "* NINJ4-TP " << BLUE_COLOR << this->getName() << END_COLOR << " use special ninjaShoebox attack";
std::cout << " on " << VIOLET_COLOR << enemy.getName() << END_COLOR << " *" << std::endl;
std::cout << randomAttackName[randomAttackIndex] << std::endl;
enemy.takeDamage(randomAttackValue[randomAttackIndex]);
return randomAttackValue[randomAttackIndex];
}
| true |
a289504fbd186751ae2eb37cffaa833ae2860469 | C++ | IndianShifu/Compiler-Lab | /LAB3/q9.cpp | UTF-8 | 12,718 | 3.0625 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<map>
#include<fstream>
using namespace std;
string terminals = "e", nonterminals; // e is epsilon
struct parseEntry
{
//terminal,production
string production;
string input;
};
string dupliRemove( string a )
{
string w;
for( int i=0; i<a.length();i++)
{
if ( w.find(a[i]) == string::npos)
{
w += a[i];
}
}
return w;
}
//FIRST SET
string first( string a,multimap<char,string>& map)
{
string first_ans;
for (multimap<char, string>::iterator it = map.begin();it != map.end();++it)
{
if ( it->first == a[0])
{
//rhs is non-terminal
for( int k = 0 ; k < (it->second).length(); k++) //searching rhs of production
{
// multimap<char,string> cfg;
bool repeat = false;
string rhs;
rhs += (it->second)[k];
string tmp ;
tmp = first(rhs, map);
const int length = tmp.length();
//searching tmp for epsilon
for( int i=0;i<length;i++)
{
if ( tmp[i] == 'e')
{
if ( k != (it->second).length()) //last symbol on rhs dont remove
tmp.erase(i,1);
first_ans += tmp;
repeat = true; //epsilon found go to next symbol
break;
}
}
//epsilon not found leave the loop
if ( repeat == false)
{
first_ans += tmp;
break;
}
}
}
else //terminal is part of loop not necessary but keep this way
{
for( int j=0 ; j< terminals.length();j++)
{
// cout << "terminal " << terminals[j] << endl;
if ( a[0] == terminals[j] )
{
first_ans += a[0];
// cout << first_ans << endl;
break;
}
}
}
}
//
return first_ans;
}
string rhs_cfg(string a)
{
int i=0;
while ( a[i] != '-')i++;
i+= 2;
if ( i >= a.length()) return "-1";
return a.substr(i,a.length()-i); // rhs of production
}
string firstMain( string a , multimap<char,string>& map )
{
string first_ans,temp,e = "e";
for( int i=0 ; i < a.length(); i++)
{
string in;
in = a[i];
temp = first(in , map);
if ( temp.find(e) != string::npos)
{
temp.erase(temp.find(e),1);
first_ans += temp;
if ( i == a.length()-1)
{
first_ans += e;
}
}
else
{
first_ans += temp;
break;
}
}
string ans = dupliRemove(first_ans);
return ans;
}
//FOLLOW SET
string follow( string a , multimap<char,string>& map) //enter cfg
{
string follow_ans;
for (multimap<char,string>::iterator it = map.begin();it != map.end();++it)
{
//means it is the start symbol
if ( it == map.begin() && a[0] == it->first)
{
follow_ans += "$";
}
//scanning rhs to apply 2 rule to find follow
if ( (it->second).find(a[0]) != string::npos) // we found a[0]
{
int length = (it->second).length();
int pos = (it->second).find(a[0]);
string e = "e";
if ( (pos+1) < length ) //not the last symbol
{
string p,tmp;
//p += (it->second)[pos+1]; //change this to accomaodate whole till end
p = (it->second).substr(pos+1,length-pos-1);
tmp = firstMain(p,map);
while( tmp.find(e) != string::npos)
tmp.erase((tmp.find(e)),1); //removing epsilon from first
follow_ans += tmp;
}
string tmp2;
tmp2 = (it->second).substr(pos+1,length-pos-1); //need to modify this rule
// cout << "POS " << pos+2 << " length " << length << " FOLLOW OF " << a[0] << " rhs " << it->second << endl;
//applying 3 rule
if ( (pos+1) == length )
{
string tmp1;
tmp1 += it->first;
if ( tmp1[0] == a[0])
{
continue;
}
// cout << "FOLLOW " << follow(tmp1,map) << " to be added in " << a[0] << endl;
follow_ans += follow(tmp1,map);
// cout << "Which is " << follow_ans << endl;
}
else if ( firstMain(tmp2,map).find(e) != string::npos ) //first has epsilon
{
string a1;
a1 += it->first;
if ( a1[0] == a[0]) continue;
follow_ans += follow(a1,map);
}
}
}
return follow_ans;
}
//PREDICTIVE PARSING TABLE PART
void PrediciveParsingTable(multimap<char,parseEntry>& ptable ,multimap<char,string> cfg)
{
//creating empty parsing table
for( int i=0; i < nonterminals.length(); i++)
{
char lhs = nonterminals[i];
for( int j=0; j< terminals.length(); j++)
{
parseEntry temp;
if( terminals[j] != 'e') // we are not adding e entry in the table
{
temp.input = terminals[j]; //input symbol
ptable.insert(pair<char,parseEntry>(lhs,temp));
}
}
//adding the dollar entry
parseEntry dollar;
dollar.input = "$";
ptable.insert(pair<char,parseEntry>(lhs,dollar));
}
//computations
for ( multimap<char, string>::iterator it = cfg.begin(); it != cfg.end(); ++it)
{
string lhs1,rhs1 ;
lhs1 += it->first; //lhs
rhs1 += it->second; //rhs
string first1 = firstMain(rhs1,cfg);
// cout << "\n ..............LHS............ " << it->first << endl;
// cout << "First of " << t << " is " << first1 << endl; //checked right
for( int k=0; k< first1.length(); k++)
{
if ( first1[k] == 'e')
{
// cout << "taking e" << endl;
string p1,follow1;
p1 += it->first; //lhs
follow1 = dupliRemove(follow(p1,cfg)); // to be used later
// cout << "Follow of " << p1 << " " << follow1 << endl;
//for each terminal in follow
for ( int l=0 ; l< follow1.length(); l++)
{
for (multimap<char,parseEntry>::iterator pit = ptable.begin(); pit != ptable.end(); ++pit)
{
parseEntry temp = pit->second;
// cout << "LHS: " << it->first << " INPUT: " << temp.input << " PRODUCTION: " << temp.production << endl;
if ( (pit->first == it->first) && ((temp.input)[0] == follow1[l]))
{
string pro;
pro += lhs1 + " - " + rhs1;
// cout << "CFG: " << it->first << " - " << it->second << endl;
// cout << "CFG ACTUAL: " << pro << endl;
(pit->second).production += pro;
}
}
}
}
else
{
for (multimap<char,parseEntry>::iterator pit = ptable.begin(); pit != ptable.end(); ++pit)
{
parseEntry temp = pit->second;
// cout << "LHS: " << it->first << " INPUT: " << temp.input << " PRODUCTION: " << temp.production << endl;
if ( (pit->first == it->first) && ((temp.input)[0] == first1[k]))
{
string pro;
pro += lhs1 + " - " + rhs1;
// cout << "CFG: " << it->first << " " << it->second << endl;
//cout << "CFG ACTUAL: " << pro << endl;
(pit->second).production += pro;
}
}
}
}
}
}
int main()
{
multimap<char,string> cfg;
map<string,string> firstSet;
map<string,string> followSet;
fstream in("q8.txt"); //Input File
int i;
string input,temp;
while(true)
{
getline(in,input);
//add to multimap
if ( rhs_cfg(input) != "-1")
cfg.insert(pair<char,string>(input[0],rhs_cfg(input)));
if ( in.eof()) break;
}
cout << ".................CONTEXT FREE GRAMMAR.......................\n" << endl;
for (multimap<char, string>::iterator it = cfg.begin();it != cfg.end();++it)
{
//store first set in a array
cout << (*it).first << " - " << (*it).second << endl;
}
//asking for terminals and nonterminals
cout << "Enter TERMINALS in the CFG .Press q to exit" << endl;
while(true)
{
cin >> temp;
if ( temp == "q" ) break;
terminals += temp;
}
cout << endl;
cout << "Enter NON-TERMINALS in the CFG" << endl;
while(true)
{
cin >> temp;
if ( temp == "q" ) break;
nonterminals += temp;
}
cout << "\n Terminals " << terminals << " \n Nonterminals " << nonterminals << endl;
// cout << "....................FIRST sets........................." << endl;
char duplicateChecker = NULL ;
for (multimap<char, string>::iterator it = cfg.begin(); it != cfg.end(); ++it)
{
if ( duplicateChecker != it->first)
{
string lhs;
lhs += it->first;
string ans = dupliRemove(first(lhs,cfg));
duplicateChecker = it->first;
firstSet.insert(pair<string,string>(lhs,ans)); //adding to first hashtable
// cout << "FIRSTMAIN " << dupliRemove(firstMain(lhs,cfg)) << endl;
}
}
for (multimap<string, string>::iterator it = firstSet.begin(); it != firstSet.end(); ++it)
{
// cout << "FIRST( " << it->first << " ) = " << it->second << endl;
}
// cout << "first " << first("A",cfg);
// cout << "....................FOLLOW sets........................." << endl;
duplicateChecker = NULL ;
for (multimap<char, string>::iterator it = cfg.begin(); it != cfg.end(); ++it)
{
if ( duplicateChecker != it->first)
{
string lhs;
lhs += it->first;
string ans = dupliRemove(follow(lhs,cfg));
duplicateChecker = it->first;
followSet.insert(pair<string,string>(lhs,ans)); //adding to follow hashtable
}
}
for (multimap<string, string>::iterator it = followSet.begin(); it != followSet.end(); ++it)
{
// cout << "FOLLOW( " << it->first << " ) = " << it->second << endl;
}
cout << endl;
while(true)
{
string input;
cout << "Enter the string to find the FIRST set. Press 1 to exit" << endl;
cin >> input;
if ( input == "1")break;
cout << "FIRST( " << input << " ) = " << dupliRemove(firstMain(input,cfg)) << endl;
}
multimap<char,parseEntry> parsetable;
cout << "....................Predictive Parsing Table........................." << endl;
PrediciveParsingTable(parsetable,cfg);
/* for (multimap<char,parseEntry>::iterator it = parsetable.begin(); it != parsetable.end(); ++it)
{
parseEntry temp = it->second;
cout << "NONTERMINAL: " << it->first << " INPUT SYMBOL: " << temp.input << " PRODUCTION: " << temp.production << endl;
}
*/
//cout << "NONTERMINAL\t\t\t\t" << "INPUT SYMBOL" << endl;
multimap<char,parseEntry>::iterator ptable_it = parsetable.begin();
char nonterminalptable = ptable_it->first ;
for (ptable_it ; ptable_it != parsetable.end(); ++ptable_it)
{
parseEntry temp = ptable_it->second;
if ( nonterminalptable != ptable_it->first) //new lhs comes change line
{
nonterminalptable = ptable_it->first ;
cout << endl;
}
cout << "NONTERMINAL: " << ptable_it->first << " INPUT SYMBOL: " << temp.input << " PRODUCTION: " << temp.production << endl;
}
in.close();
return 0;
}
| true |
bf4af8f20e03f4bef526cbcbae60c73c366a716d | C++ | Vetos22854/Lab_1 | /Git 1/Git 1.cpp | WINDOWS-1251 | 1,199 | 2.984375 | 3 | [] | no_license | // Git 1.cpp: .
//
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
cout << "29.06.1998";
cout << "";
cout << "";
cout << "";
cout << " 3";
cout << " 9 ";
cout << " ";
cout << " 2017";
cout << " 2017";
cout << " ";
cout << " ";
cout << " ";
cout << " ";
cout << " 3 ";
cout << " 1 ";
cout << " ";
cout << " ";
cout << " ";
cout << " 8 ";
cout << " ";
cout << " ";
cout << " ";
cout << " ";
return 0;
}
| true |
0e6336cab67b46a296dbfe5c6911c9b5693d7924 | C++ | ivanenkomaksym/designpatterns | /src/bridge/entertainmentdevice.cpp | UTF-8 | 527 | 2.96875 | 3 | [] | no_license | #include "bridge/entertainmentdevice.h"
#include <iostream>
void EntertainmentDevice::buttonSevenPressed()
{
m_volumeLevel++;
std::cout << "Volume at: " << m_volumeLevel << std::endl;
}
void EntertainmentDevice::buttonEightPressed()
{
m_volumeLevel--;
std::cout << "Volume at: " << m_volumeLevel << std::endl;
}
void EntertainmentDevice::deviceFeedback()
{
if (m_deviceState > m_maxSetting || m_deviceState < 0)
m_deviceState = 0;
std::cout << "On Channel " << m_deviceState << std::endl;
}
| true |
03de5b816c82d054c56f776395a8273bf289873d | C++ | 0000duck/travsales | /genalg.cpp | UTF-8 | 7,232 | 2.703125 | 3 | [
"MIT"
] | permissive | //
// genalg.cpp
// Traveling Salesman
//
// Created by Alexandre Soares on 1/10/2020.
// Copyright © 2020 Alexandre Soares. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <chrono>
#include <thread>
#include <mutex>
#include <GL/glut.h>
#include "GAPopulation.h"
#include "TSCity.h"
// Globals
GAIndividual best;
std::vector<TSCity> cities_list;
std::mutex mutex;
// GLUT globals
struct { int x, y; } prevMouseCoords;
struct { double x, y, z; } mapCenter = { 0.0, 0.0, 0.0 };
double angleX=0, angleY=0;
// FreeGLUT Helper functions
void computeMapCenter()
{
for (auto &city : cities_list) {
mapCenter.x += city.position().x;
mapCenter.y += city.position().y;
mapCenter.z += city.position().z;
}
mapCenter.x /= (double)cities_list.size();
mapCenter.y /= (double)cities_list.size();
mapCenter.z /= (double)cities_list.size();
}
void reshape(int w, int h)
{
glViewport(0,0,(GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(65.0, (double)w/(double)h, 10.0, 300.0);
glMatrixMode(GL_MODELVIEW);
}
void drawCities(const std::vector<TSCity> &cities_list)
{
glColor3d(0.2, 0.2, 0.2);
for (auto city : cities_list) {
glPushMatrix();
glTranslated(city.position().x, city.position().y, city.position().z);
glutSolidSphere(0.8,10,10);
glPopMatrix();
}
}
void drawCircuit(const GAIndividual &ind)
{
glColor3d(0.7, 0.0, 0.0);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBegin(GL_LINES);
ind.draw();
glEnd();
}
void init()
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(50.0,50.0,120.0,50.0,50.0,0.0,0.0,1.0,0.0);
}
void display(void)
{
glLoadIdentity();
gluLookAt(50.0,50.0,120.0+mapCenter.z,50.0,50.0,0.0,0.0,1.0,0.0);
glTranslated(mapCenter.x, 0.0, mapCenter.z);
glRotated(angleX,0.0, 1.0, 0.0);
glTranslated(-mapCenter.x, 0.0, -mapCenter.z);
glTranslated(0.0, mapCenter.y, mapCenter.z);
glRotated(angleY, 1.0, 0.0, 0.0);
glTranslated(0.0, -mapCenter.y, -mapCenter.z);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawCities(cities_list);
mutex.lock();
drawCircuit(best);
mutex.unlock();
glFlush();
}
void mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON and state == GLUT_DOWN) {
prevMouseCoords.x = x;
prevMouseCoords.y = y;
}
}
void mouseMoved(int x, int y)
{
angleX += (double)(x-prevMouseCoords.x)/3;
angleY += (double)(y-prevMouseCoords.y)/3;
prevMouseCoords.x = x;
prevMouseCoords.y = y;
}
// Function to run the Genetic Algorithm concurrently
void GA()
{
// Standard parameters
unsigned int pop_size = 1000;
double mutation_rate = 0.001;
double crossover_rate = 0.25;
unsigned elitism_count = 10;
unsigned tournament_size = 500;
unsigned max_generations = 2000;
unsigned cull_count = 10;
unsigned chromosome_size = cities_list.size();
unsigned generation;
GAPopulation pop (pop_size, chromosome_size, &cities_list);
// Start the chronometer before initializing GAPopulation
auto start_time = std::chrono::high_resolution_clock::now();
generation = 1;
while (generation < max_generations) {
std::cout << "Generation: " << generation;
GAIndividual localBest = pop.getFittest();
mutex.lock();
if (best < localBest)
best = localBest;
else
pop.insertIndividual(best);
mutex.unlock();
/*
// Print fittest individual
std::cout << "Best solution: "
<< pop.bestDescription() << " "
<< pop.bestFitness() << std::endl;
*/
std::cout << " Best fitness: " << pop.bestFitness() << std::endl;
pop.mutate(mutation_rate);
pop = GAPopulation(pop, crossover_rate, elitism_count, tournament_size, cull_count);
++generation;
}
// Stop the chronometer after we're done
auto end_time = std::chrono::high_resolution_clock::now();
// Inform end stats
std::cout << "Found solution in " << generation << " generations" << std::endl;
std::cout << "Best solution: " << pop.bestDescription() << std::endl;
std::cout << "Fitness: " << pop.bestFitness() << std::endl;
// Inform how long it took to run things
auto dur = std::chrono::duration<double>(end_time - start_time);
std::cout << "Algorithm ran for " << dur.count() << " seconds" << std::endl;
}
// Function to join each thread in the list and report results
void wrapUp (std::vector<std::thread> &threads)
{
for (auto &thread : threads)
thread.join();
std::cout << "Absolute best solution: "
<< best.chromosomeAsString()
<< " " << best.fitness() << std::endl;
}
// Initialize cities list randomly uniformly in a 100x100x100 grid
void makeRandomCities()
{
for (int i=0; i<100; ++i)
cities_list.push_back(TSCity(100u, 100u, 100u));
}
// Initialize cities from a file
void loadCities()
{
std::ifstream file("cities.txt");
if (file) {
std::string line;
while (getline(file, line)) {
std::istringstream stream(line);
double x, y, z;
stream >> x >> y >> z;
cities_list.push_back(TSCity(TSCity::Coordinates{x, y, z}));
}
}
else {
std::cout << "Could not open cities.txt, terminating" << std::endl;
}
}
int main (int argc, char **argv)
{
char option;
// Determine if user wants randomly generated cities or wants to load the cities from a file
std::cout << "Welcome to Traveling Salesman solver" << std::endl;
std::cout << "Would you like to load cities from cities.txt? (y/n): ";
std::cin >> option;
if (std::tolower(option) == 'n') {
std::cout << "Map will be randomly generated" << std::endl;
makeRandomCities();
}
else {
loadCities();
}
if (cities_list.empty()) {
std::cout << "Cannot run algorithm on an empty map!" << std::endl;
return 1;
}
// Compute center of map
computeMapCenter();
// Create and join threads
std::vector<std::thread> threads;
for (int i=0; i!=5; ++i)
threads.push_back(std::thread(GA));
std::thread wrap(wrapUp, std::ref(threads));
// Initialize and run visualization of solution
glutInit(&argc, argv);
glutInitWindowSize(700, 700);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA | GLUT_DEPTH);
glutCreateWindow("Traveling Salesman");
glEnable(GL_DEPTH_TEST);
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(mouse);
glutMotionFunc(mouseMoved);
glutIdleFunc(glutPostRedisplay);
init();
glutMainLoop();
return 0;
}
| true |
4eacd9865745844923d206e05d5f1260d38174b8 | C++ | clckwrkbdgr/miniban | /src/counter.h | UTF-8 | 225 | 2.828125 | 3 | [
"WTFPL"
] | permissive | #pragma once
struct Counter {
Counter(int counter_stop_value);
bool is_active() const;
void start();
int multiplied_value(int factor);
void tick(int increase);
private:
bool active;
int current_value, stop_value;
};
| true |
8f192f910d6a73cc6b3113a1a043b6981c1f3f09 | C++ | sbojarovski/rubic-solver | /Cell.cpp | UTF-8 | 449 | 2.71875 | 3 | [
"MIT"
] | permissive | //
// Created by stefan on 12/24/15.
//
#include <assert.h>
#include "Cell.h"
Cube::CubeFace::Cell::Cell(const CellColor &color)
:color(CellColor::UNKNOWN)
{
assert(color >= 0 && color <= 6);
this->color = color;
}
void Cube::CubeFace::Cell::setColor(const CellColor &color) {
assert(color >= 0 && color <= 6);
this->color = color;
}
const CellColor & Cube::CubeFace::Cell::getColor() const {
return this->color;
}
| true |
67671b3d749f895c15aaa5eb00d2f4a86433cbd1 | C++ | brucelevis/cherrysoda-engine | /Engine/CherrySoda/Renderers/SingleTagRenderer.h | UTF-8 | 947 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef _CHERRYSODA_RENDERERS_SINGLETAGRENDERER_H_
#define _CHERRYSODA_RENDERERS_SINGLETAGRENDERER_H_
#include <CherrySoda/Graphics/Effect.h>
#include <CherrySoda/Renderers/Renderer.h>
#include <CherrySoda/Util/BitTag.h>
#include <CherrySoda/Util/Camera.h>
namespace cherrysoda {
class Scene;
class SingleTagRenderer : public Renderer
{
public:
SingleTagRenderer(const BitTag& tag)
: m_tag(tag)
{
}
void Render(Scene* scene) override;
inline Camera* GetCamera() override { return &m_camera; }
inline Effect* GetEffect() { return &m_effect; }
inline void SetEffect(const Effect& effect) { *GetEffect() = effect; }
inline type::UInt16 RenderPass() { return m_renderPass; };
inline void RenderPass(type::UInt16 renderPass) { m_renderPass = renderPass; }
private:
BitTag m_tag;
Camera m_camera;
Effect m_effect;
type::UInt16 m_renderPass = 0;
};
} // namespace cherrysoda
#endif // _CHERRYSODA_RENDERERS_SINGLETAGRENDERER_H_
| true |
f6be99efd92e5b7ce5aa8c6f14c0e25cc3ffd305 | C++ | olethrosdc/beliefbox | /src/models/CompressSensing.cc | UTF-8 | 1,837 | 2.796875 | 3 | [] | no_license | #include <vector>
#include <map>
#include <random>
#include "CompressSensing.h"
#include "real.h"
compressor createCompressionMatrix(std::vector<std::vector<int> > &indices) {
compressor c;
std::map<int,int> indexMap;
int distinct = 0;
for(int i = 0;i<indices.size();i++) {
for(int j=0;j<indices[i].size();j++) {
if(indexMap.find(indices[i][j])==indexMap.end()) {
indexMap.insert(std::map<int,int>::value_type(indices[i][j], distinct));
distinct++;
}
}
}
int tmpSize = 0;
// find argmax_i S-sparse
for(int i = 0;i<indices.size();i++) {
if(indices[i].size() > tmpSize) {
tmpSize = indices[i].size();
}
}
// to have the RIP-property K = O(S * log(N/S) for S-sparse
double ratio = (double) distinct/ (double) tmpSize;
int resultSize = (int)(tmpSize * std::log(ratio)+0.5);
std::vector<std::vector<real> > compressionMatrix(resultSize);
std::normal_distribution<double> distribution(0.0,1.0);
std::default_random_engine gen;
for(int i = 0;i<resultSize;i++) {
compressionMatrix[i].resize(distinct);
for(int j = 0;j<distinct;j++) {
compressionMatrix[i][j] = distribution(gen);
}
}
c.compressionMatrix = compressionMatrix;
c.indexMap = indexMap;
return c;
}
std::vector<real> compressSparseArray(std::vector<int> &values, std::vector<int> &indices, compressor c) {
int resultingSize = c.compressionMatrix.size();
int distinct = c.compressionMatrix[0].size();
std::vector<int> tmpValueArray(distinct);
for(int i=0;i<values.size();i++) {
int realIndex = c.indexMap.at(indices[i]);
tmpValueArray[realIndex] = values[i];
}
std::vector<real> compressedArray(resultingSize);
for(int i=0;i<resultingSize;i++) {
real tmp = 0.0;
for(int j=0;j<distinct;j++) {
tmp+=c.compressionMatrix[i][j] * tmpValueArray[j];
}
compressedArray[i] = tmp;
}
return compressedArray;
} | true |
b01c04384a4e0403384835140dc4387e51742a4e | C++ | 123Phil/Compiler | /2 Parser/main.cpp | UTF-8 | 615 | 2.640625 | 3 | [] | no_license | // Phillip Stewart, 891499733
// OCT 2014
// compiled on OSX 10.9.5 using g++ which invokes clang, with:
// $ g++ main.cpp Parser.cpp Lexer.cpp
// can be run supplying filename as command line argument:
// ./a.out program.txt
// or run and supplied filename during runtime:
// ./a.out
// >Enter filename: program.txt
#include <iostream>
#include <string>
#include "Lexer.h"
#include "Parser.h"
int main(int argc, char** argv)
{
std::string filename;
if (argc == 2) {
filename = argv[1];
}
else {
std::cout << "Enter filename: ";
std::cin >> filename;
}
Parser P(filename);
P.run();
return 0;
}
| true |
80122bad687dfb4ea1e86a5ba064de804ac01fd4 | C++ | harshraj22/problem_solving | /solution/leetcode/76.cpp | UTF-8 | 1,247 | 2.8125 | 3 | [] | no_license | class Solution {
bool in(map<char, int> &t, map<char, int> &s) {
for (auto pi: t) {
if (pi.second > s[pi.first])
return false;
}
return true;
}
public:
string minWindow(string s, string t) {
if (t.empty() || s.empty()) return string();
map<char, int> freqt, freq;
int left = 0, right = 0, n = s.size();
// pair of: index, length
pair<int, int> ans = {0, INT_MAX};
for (auto ch: t)
freqt[ch] += 1;
while (left < n) {
if (right < n) {
freq[s[right]] += 1;
right += 1;
}
while (in(freqt, freq)) {
if (ans.second > right-left)
ans = {left, right-left};
// ans = min(ans, right-left);
freq[s[left]] -= 1;
if (freq[s[left]] == 0)
freq.erase(s[left]);
left += 1;
}
if (right == n && !in(freqt, freq))
break;
}
cout << ans.first << ' ' << ans.second << '\n';
return (ans.second != INT_MAX? s.substr(ans.first, ans.second): string());
}
}; | true |
f464a8f743573b413edce4817e3e67422ead0ea5 | C++ | alexandrakl/Crazy | /test.cpp | UTF-8 | 1,481 | 2.90625 | 3 | [] | no_license |
#include <iostream>
using std::cout; using std::endl;
int tape[1000] = {0};
int* dp = tape;
int main(){
cout << endl;
++(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
while(*dp){
++dp;
++(*dp);
++(*dp);
++(*dp);
++(*dp);
while(*dp){
++dp;
++(*dp);
++(*dp);
++dp;
++(*dp);
++(*dp);
++(*dp);
++dp;
++(*dp);
++(*dp);
++(*dp);
++dp;
++(*dp);
--dp;
--dp;
--dp;
--dp;
--(*dp);
}
++dp;
++(*dp);
++dp;
++(*dp);
++dp;
--(*dp);
++dp;
++dp;
++(*dp);
while(*dp){
--dp;
}
--dp;
--(*dp);
}
++dp;
++dp;
cout << static_cast<char>(*dp);
++dp;
--(*dp);
--(*dp);
--(*dp);
cout << static_cast<char>(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
++(*dp);
cout << static_cast<char>(*dp);
cout << static_cast<char>(*dp);
++(*dp);
++(*dp);
++(*dp);
cout << static_cast<char>(*dp);
++dp;
++dp;
cout << static_cast<char>(*dp);
--dp;
--(*dp);
cout << static_cast<char>(*dp);
--dp;
cout << static_cast<char>(*dp);
++(*dp);
++(*dp);
++(*dp);
cout << static_cast<char>(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
cout << static_cast<char>(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
--(*dp);
cout << static_cast<char>(*dp);
++dp;
++dp;
++(*dp);
cout << static_cast<char>(*dp);
++dp;
++(*dp);
++(*dp);
cout << static_cast<char>(*dp);
cout << endl;
return 0;
}
| true |
43c8075354b6232016e2c07b33df8c47aca19829 | C++ | MohamadIsmail/Online-Judges-solutions | /spoj/reverse.cpp | UTF-8 | 602 | 2.640625 | 3 | [] | no_license | //#include<iostream>
//#include<algorithm>
//#include<vector>
//#include<string>
//using namespace std;
//int main ()
//{
// int n;
// cin>>n;
// cin.ignore();
// string arr,t;
// vector<string> s;
// for(int e=0 ; e<n; e++)
// {
// getline(cin,arr);
// for(int i=arr.size()-1; i>=0; i--)
// {
// if(arr[i]!=' ')
// t+=arr[i];
// if((arr[i]==' ')||(i==0))
// {
// reverse(t.begin(),t.end());
// t+=' ';
// s.push_back(t);
// t="";
// }
// }
// cout<<"Case #"<<e+1<<": ";
// for(int i=0; i<s.size(); i++)
// cout<<s[i];
// cout<<endl;
// s.clear();
// }
// return 0;
//} | true |
8c9f3907b8d0363dee29518510a157f2ffba5834 | C++ | relision/elipp | /src/term/ISpecialForm.h | UTF-8 | 1,253 | 2.53125 | 3 | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | #ifndef ISPECIALFORM_H_
#define ISPECIALFORM_H_
/**
* @file
* Define the public interface to a special form.
*
* @author sprowell@gmail.com
*
* @verbatim
* _ _ _
* ___| (_)___(_) ___ _ __
* / _ \ | / __| |/ _ \| '_ \
* | __/ | \__ \ | (_) | | | |
* \___|_|_|___/_|\___/|_| |_|
* The Elision Term Rewriter
*
* Copyright (c) 2014 by Stacy Prowell (sprowell@gmail.com)
* All rights reserved.
* @endverbatim
*/
#include "ITerm.h"
namespace elision {
namespace term {
/**
* Specify the public interface to a special form. Special forms are really
* just pairs that are subject to some "special" treatment by the system. The
* first element of the pair is called the @b tag, and the second element is
* called the @b content, but really either can be any term you wish.
*/
class ISpecialForm : public virtual ITerm {
public:
/**
* Get the tag for this special form.
* @return The tag.
*/
virtual pTerm get_tag() const = 0;
/**
* Get the content for this special form.
* @return The content.
*/
virtual pTerm get_content() const = 0;
};
/// Shorthand for a property specification pointer.
typedef std::shared_ptr<ISpecialForm const> pSpecialForm;
} /* namespace term */
} /* namespace elision */
#endif /* ISPECIALFORM_H_ */
| true |
68548347b6249a9f4f40496de3bbbd086bcbbba9 | C++ | YhgzXxfz/leetcode | /reshape_the_matrix.cpp | UTF-8 | 388 | 2.765625 | 3 | [] | no_license | class Solution {
public:
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int m = nums.size(), n = nums[0].size();
if (m*n != r*c) return nums;
vector<vector<int>> output(r, vector<int>(c, 0));
for (int k = 0; k < m*n; ++k) {
output[k/c][k%c] = nums[k/n][k%n];
}
return output;
}
};
| true |
aaabcddf941eb9f6f289f28688e689f11cf62c1f | C++ | mdiazmeli/JUEGO-PONG-SOCKET-TCP | /servidor.cpp | UTF-8 | 5,161 | 2.546875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#define PORT 7777
using namespace std;
int p1y = 9;
int p2y = 9;
int jugadores[2];
void gotoxy(int x,int y)
{
printf("%c[%d;%df",0x1B,y,x);
}
void *movi_1(void *arg)
{
char buffer[256];
while (true){
recv(jugadores[0], buffer, sizeof(buffer), 0);
p1y = atoi(buffer);
usleep(50000);
}
}
void *movi_2(void *apg)
{
char buffer[256];
while (true){
recv(jugadores[1], buffer, sizeof(buffer), 0);
p2y = atoi(buffer);
usleep(50000);
}
}
void *write_1(void *apg)
{
while (true){
string s = to_string(p2y);
char mensaje[2];
strcpy(mensaje,s.c_str());
write(jugadores[0], mensaje, sizeof(mensaje));
usleep(50000);
}
}
void logo()
{
system("clear");
gotoxy(33,1); printf("███████████████████");
gotoxy(33,2); printf("█ █");
gotoxy(33,3); printf("█ ██████ █");
gotoxy(33,4); printf("█ ██████ █");
gotoxy(33,5); printf("█ ██████ █");
gotoxy(33,6); printf("█ █████████ █");
gotoxy(33,7); printf("█ █████████ █");
gotoxy(33,8); printf("█ ████████ █");
gotoxy(33,9); printf("██ ███████ ██");
gotoxy(33,10);printf(" ██ ██████ ██");
gotoxy(33,11);printf(" ██ ████ ██");
gotoxy(33,12);printf(" ██ ██");
gotoxy(33,13);printf(" ███████████");
gotoxy(33,14);printf(" UTEM ");
printf("\n");
}
int main(int argc, char const *argv[])
{
int server_fd, socket_client, valread;
struct sockaddr_in direccion;
struct sockaddr_in client_addr;
fd_set descriptoresLectura;
socklen_t size_addr = 0;
int opt = 1;
int addrlen = sizeof(direccion);
logo();
//:::::::::::::::::::::::::Creacion del socket::::::::::::::::::::::::::::::::::::::
// Crear descriptor de archivo de socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("fallo creacion de Socket");
exit(EXIT_FAILURE);
}
printf("Esperando jugadores..........\n");
// Conexión forzada del zócalo al puerto 7777
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
direccion.sin_family = AF_INET;
direccion.sin_addr.s_addr = INADDR_ANY;
direccion.sin_port = htons( PORT );
// Conexión forzada del zócalo al puerto 7777
if (bind(server_fd, (struct sockaddr *)&direccion, sizeof(direccion))<0)
{
perror("Fallo el enlace");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 2) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
socket_client = accept(server_fd, (struct sockaddr *)&direccion,(socklen_t*)&addrlen);
jugadores[0]= socket_client;
if (socket_client == -1)
{
perror("error");
}
printf("\nSe ha conectado el jugador 1\n");
char player1[2] = "1";
write(jugadores[0], player1,sizeof(player1));
usleep(1000);
char msg[20]="Esperando jugador 2";
write(jugadores[0],msg,sizeof(msg));
//---------------------------
socket_client = accept(server_fd, (struct sockaddr *)&direccion,(socklen_t*)&addrlen);
jugadores[1]= socket_client;
if (socket_client == -1)
{
perror("error");
}
printf("\nSe ha conectado el jugador 2\n");
char player2[2] = "2";
write(jugadores[1], player2,sizeof(player2));
usleep(1000);
char msg2[29]="Se ha conectado el jugador 2";
for (int i = 0; i < 2; ++i)
{
write(jugadores[i],msg2,sizeof(msg2));
}
usleep(3500000);
pthread_t hear1,hear2,env1;
if(pthread_create(&hear1, NULL, &movi_1, NULL)) {
fprintf(stderr, "Error creating thread\n");
}
if(pthread_create(&hear2, NULL, &movi_2, NULL)) {
fprintf(stderr, "Error creating thread\n");
}
if(pthread_create(&env1, NULL, &write_1, NULL)) {
fprintf(stderr, "Error creating thread\n");
}
while(true)
{
string s = to_string(p1y);
char mensaje[2];
strcpy(mensaje,s.c_str());
write(jugadores[1], mensaje, sizeof(mensaje));
usleep(50000);
}
close(server_fd);
close(socket_client);
if(pthread_join(hear1, NULL)) {
fprintf(stderr, "Error joining thread\n");
}
if(pthread_join(hear2, NULL)) {
fprintf(stderr, "Error joining thread\n");
}
if(pthread_join(env1, NULL)) {
fprintf(stderr, "Error joining thread\n");
}
return EXIT_SUCCESS;
}
| true |
2cb34224f77657f88dbd5383bb737aaade29a38b | C++ | korbiniak/SolverMachine | /Solver3/src/face.cpp | UTF-8 | 449 | 3.171875 | 3 | [] | no_license | #include "include/face.h"
Face::Face() {}
Face::Face(Digit setColor) {
for(int i = 0 ; i < 9 ; ++i)
tile[i] = setColor;
}
Face::Face(const Face &f) {
for(int i = 0 ; i < 9 ; ++i)
tile[i] = f.tile[i];
}
void Face::swapTiles(uint8_t tile1, uint8_t tile2) {
swap(tile[tile1], tile[tile2]);
}
bool Face::operator==(const Face &face1)const {
for(int i = 0 ; i < 9 ; ++i)
if(!(face1.tile[i] == tile[i]))
return false;
return true;
} | true |
b42de7bf05f81f5e868e90f94b4b8d39ab7a063b | C++ | HampsterEater/VoxelEngine | /Source/Generic/Helper/StringHelper.cpp | UTF-8 | 2,569 | 3.109375 | 3 | [] | no_license | // ===================================================================
// Copyright (C) 2013 Tim Leonard
// ===================================================================
#include "Generic\Helper\StringHelper.h"
#include <stdarg.h>
int StringHelper::Split(const char* v, char deliminator, std::vector<std::string>& segments)
{
std::string value = v;
if (strlen(v) == 0)
{
return 0;
}
int startIndex = 0;
while (true)
{
int offset = value.find(deliminator, startIndex);
if (offset < 0)
{
break;
}
segments.push_back(value.substr(startIndex, offset - startIndex));
startIndex = offset + 1;
}
segments.push_back(value.substr(startIndex, value.size() - startIndex));
return segments.size();
}
void StringHelper::Find_Line_And_Column(const char* text, int offset, int& line, int& column)
{
// Reset values.
line = 1;
column = 0;
// Calculate length.
//int len = strlen(text); // Assumption made that text length is inside bounds, as this function is used with strings containing multiple \0's
for (int i = 0; /*i < len &&*/ i <= offset; i++)
{
char chr = text[i];
if (chr == '\n')
{
line++;
column = 0;
}
else if (chr != '\r')
{
column++;
}
}
}
std::string StringHelper::Trim(const char* value)
{
int start_offset = 0;
int end_offset = 0;
int length = strlen(value);
for (start_offset = 0; start_offset < length; start_offset++)
{
if (!iswspace(value[start_offset]))
{
break;
}
}
for (end_offset = length - 1; end_offset >= 0; end_offset--)
{
if (!iswspace(value[end_offset]))
{
end_offset++;
break;
}
}
std::string result = std::string(value).substr(start_offset, end_offset - start_offset);
return result;
}
std::string StringHelper::Remove_Whitespace(const char* value)
{
std::string result = "";
int length = strlen(value);
for (int i = 0; i < length; i++)
{
if (!iswspace(value[i]))
{
result += value[i];
}
}
return result;
}
int StringHelper::Hash(const char* value)
{
unsigned int hash = 0;
for (; *value; ++value)
{
hash += *value;
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return hash;
}
std::string StringHelper::Format(const char* format, ...)
{
va_list va;
va_start(va, format);
char buffer[512];
int num = vsnprintf(buffer, 512, format, va);
if (num >= 511)
{
char* new_buffer = new char[num + 1];
vsnprintf(buffer, num + 1, format, va);
delete[] new_buffer;
va_end(va);
return new_buffer;
}
va_end(va);
return buffer;
}
| true |
13dd9815a8f82fe23f06b8efe0a12883f1d0026d | C++ | ayush-artist07/CipherSchools_Assignment | /src/Recursion and Backtracking/Unique Paths.cpp | UTF-8 | 1,076 | 3.5 | 4 | [] | no_license | /*
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time.
The robot is trying to reach the bottom-right corner of the grid.
*/
#include<iostream>
using namespace std;
//Since this problem is already solved using recursion i.e Count all possible paths and was getting TLE
//on platform from where the question was given so i have solved it using basic DP
int uniquePaths(int m, int n) {
int mat[m][n];
for(int i=0;i<m;i++)
for(int j=0;j<n;j++){
mat[i][j]=0;
}
for(int i=0;i<n;i++)
mat[0][i]=1;
for(int i=0;i<m;i++)
mat[i][0]=1;
for(int i=1;i<m;i++)
for(int j=1;j<n;j++){
mat[i][j]=mat[i-1][j]+mat[i][j-1];
}
return mat[m-1][n-1];
}
int main()
{
int m=3,n=7;
cout<<uniquePaths(m,n);
return 0;
}
| true |
5f711ba391bf49f66732fd1966d9c13dea816fa8 | C++ | yinchunxiang/LeetCode | /7.ReverseInteger/ReverseInterger.cc | UTF-8 | 613 | 3.671875 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*
int reverse(int x) {
int ret = 0;
int sign = 0;
if (x < 0) {
sign = 1;
x = 0 - x;
}
for(; x; x/=10) {
ret = ret*10 + x%10;
}
return sign == 1 ? 0 - ret : ret;
}
*/
int reverse(int x) {
int r = 0;
for (; x; x /= 10) {
cout << x << "%10 => " << x%10 << endl;
r = r * 10 + x % 10;
cout << x << "/10 => " << x/10 << endl;
}
return r;
}
int main() {
int x = 1;
cout << x << " => " << reverse(x) << endl;
x = -1;
cout << x << " => " << reverse(x) << endl;
}
| true |
8d5d99c4edd6dbc6157b15f2c113bc40edbb64b5 | C++ | sniper-fly/atcoder | /ABC/208/b.cpp | UTF-8 | 1,301 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
using ll=long long;
using ld=long double;
using pll=pair<ll, ll>;
#define rep(i,n) for (ll i=0; i<n; ++i)
#define all(c) begin(c),end(c)
#define PI acos(-1)
#define oo 2e18
template<typename T1, typename T2>
bool chmax(T1 &a,T2 b){if(a<b){a=b;return true;}else return false;}
template<typename T1, typename T2>
bool chmin(T1 &a,T2 b){if(a>b){a=b;return true;}else return false;}
//priority_queue<ll, vector<ll>, greater<ll>> Q;
// LLMAX = 9,223,372,036,854,775,807 (9.2 * 10^18)
// IMAX = 2147483647 (2.1*10^9)
/*
10! 3628800
9! 362880
8! 40320
7 5040
6! 720
5 120
4 24
3 6
2 2
1 1
*/
int main()
{
cin.tie(0);
ios::sync_with_stdio(0);
cout << fixed << setprecision(10);
ll P;
cin >> P;
ll ten = 3628800,
nine = 362880,
eight = 40320,
seven = 5040,
six = 720,
five = 120,
four = 24,
three = 6,
two = 2,
one = 1;
ll coins[11] = {
3628800,
362880,
40320,
5040,
720,
120,
24,
6,
2,
1
};
//まず10!硬貨で調べる。
ll ct = 0;
ll remain;
ct += P / ten;
remain = P % ten;
for (int i = 1; i < 10; ++i) {
ct += remain / coins[i];
remain = remain % coins[i];
}
cout << ct << endl;
}
| true |
714f1139bc99a4ec9f8b9a6064eb7d69be52e028 | C++ | abhishekchandra2522k/CPPrograms | /Pointers/Dangling_Pointer/dangling_pointer_2.cpp | UTF-8 | 455 | 3.671875 | 4 | [] | no_license | // Dangling Pointers using dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
int main()
{
// 4 bytes of int memory block (64bit compiler)
// allocated using malloc() during runtime
int *ptr = (int *)malloc(sizeof(int)); // normal pointer
*ptr = 10;
// memory block deallocated using free() function
free(ptr);
// here ptr acts as a dangling pointer
printf("%d", *ptr);
return 0;
} | true |
acc911ae8fff664c5f2611032344e113a3e86635 | C++ | mrmorais/tree | /examples/questao_101.cpp | UTF-8 | 2,570 | 3.6875 | 4 | [] | no_license | #include <iostream>
#include <vector>
/**
* Questão 101
*
* Montei um template de heapsort para um vetor de tipo 't_x', é necessário passar a função de comparação dele
* a funçào de comparação possibilita ordenar estruturas variadas ou também alterar a ordem de ordenação
*/
template <class t_x> std::vector<t_x> heapsort(std::vector<t_x> x_vec, bool ((*fn)(t_x,t_x))){
//make heap
// um vetor vazio ou com um elemento já está ordenado
for(unsigned int x=1;x<x_vec.size();x++){
int kid = x,dad;
while(kid>0){
dad = (kid-1+kid%2)/2;
if (fn(x_vec[dad],x_vec[kid])){
break; //the structure is a heap
}else{
//the kid should be above the dad, swap them
//uses the std op, swaps the memory from &x_vec[dad] to &x_vec[dad+1] (the content of x_vec[dad]) to &x_vec[kid] and the necessary size forward
std::swap_ranges(&x_vec[dad],&x_vec[dad+1],&x_vec[kid]);
kid = dad; //the kid resides at the former dad position
}
}
}
unsigned int size_left = x_vec.size(), replaced;
while(size_left>0){
//remove top & put last at top
std::swap_ranges(&x_vec[0],&x_vec[1],&x_vec[size_left-1]);
//decrease size
size_left--;
//reheap
unsigned int r_son,l_son,best_son;
replaced = 0;
while(replaced*2+1<size_left){
r_son = replaced*2+1;
l_son = replaced*2+2;
if(l_son<size_left){
best_son = fn(x_vec[r_son],x_vec[l_son])?r_son:l_son;
}else{
best_son = r_son;
}
if(fn(x_vec[replaced],x_vec[best_son])){
break;
}else{
//swap them and keep reordering from where the best son was
std::swap_ranges(&x_vec[replaced],&x_vec[replaced+1],&x_vec[best_son]);
replaced = best_son;
}
}
}
return x_vec;
}
int main() {
std::vector<int> v {15, 19, 3, 42, 90, 50, 21, 73}; // Vetor com valores não ordenados e aleatórios
std::vector<int> ordenado = heapsort(v,+[](int a,int b)->bool{return a>b;});
for (int c: ordenado) {
std::cout << c << " ";
}
std::cout << "\n";
srand (time(NULL));
std::vector<int> x;
//#define SEE_RESULTS
#define test_size 100
for(int i=test_size;i>0;i--) x.push_back(rand());
#ifdef SEE_RESULTS
for (int c: x) {
std::cout << c << " ";
}
std::cout << "\n";
#endif
x = heapsort(x,+[](int a,int b)->bool{return a>b;});
#ifdef SEE_RESULTS
for (int c: x) {
std::cout << c << " ";
}
std::cout << "\n";
#endif
}
| true |
7de1efcd65d6ef8791f8a43e46a5b424a5adade3 | C++ | BenQuickDeNN/LeetCodeSolutions | /分割等和子集.cpp | UTF-8 | 1,094 | 3.265625 | 3 | [] | no_license | #include <vector>
#include <algorithm>
using namespace std;
class Solution {
bool isFound;
// 深度优先搜索
bool dfs(const vector<int>& nums, const int& target, const int& idx)
{
if (isFound)
return true;
if (target == 0)
{
isFound = true;
return true;
}
for (int i = idx; i < nums.size(); ++i)
if (i > idx && nums[i] == nums[i - 1])
continue;
else if (target - nums[i] < 0)
return false;
else if (dfs(nums, target - nums[i], i + 1))
return true;
return false;
}
public:
bool canPartition(vector<int>& nums) {
// 先排序,有利于剪枝
sort(nums.begin(), nums.end());
int sum = 0;
for (int& num : nums)
sum += num;
if (sum % 2 != 0) // 如果sum不是偶数
return false;
if (sum == 0)
return true;
isFound = false;
return dfs(nums, sum / 2, 0);
}
}; | true |
94e02ea11e83b365bc83cbe6505bc986196c0420 | C++ | Alegruz/Game-AI-Track | /1_2/high_level_programming_ii_the_cpp_programming_language/cpp_primer/part_i_the_basics/07 Classes/ex02.h | UTF-8 | 560 | 3.203125 | 3 | [] | no_license | // Add the combine and isbn members to the Sales_data class
// you wrote for the exercises in § 2.6.2 (p. 76).
#if !defined(EX02_H)
#define EX02_H
#include <string>
struct Sales_data {
std::string bookNo;
double price;
unsigned int units_sold = 0;
double revenue = 0.0;
Sales_data &combine(const Sales_data &sd);
std::string isbn() const { return this->bookNo; }
};
Sales_data &Sales_data::combine(const Sales_data &sd) {
this->units_sold += sd.units_sold;
this->revenue += sd.revenue;
return *this;
}
#endif // EX02_H
| true |
252ac86c35428312034c348f4b6ffdcd1055e97c | C++ | AgelkazzWrenchsprocket/PJATK_CPP_PJC | /lab5/zad2/main.cpp | UTF-8 | 991 | 3.484375 | 3 | [] | no_license | /*
* Rozwiń definicje klasy Osoba o konstruktory:
* - pusty – wprowadzający wartości pól do dynamicznie alokowanych zasobów,
* - przyjmujący dwa parametry (char*, int) – inicjujący pola przez listę inicjacyjną.
* Oba z konstruktorów powinny wyświetlić na ekranie informacje o utworzeniu obiektu Osoba.
* Dodefiniuj destruktor, wyświetlający informacje o zniszczeniu obiektu i zwalniający dynamicznie zaalokowane zasoby.
* Przedstaw tworzenie obiektów klasy z użyciem obu typów konstruktorów.
*/
#include <iostream>
class Osoba {
char* imie;
int wiek;
public:
Osoba() { std::cout << "utworzono obiekt" << std::endl; }
Osoba(char* a, int b) {
this->imie=a;
this->wiek=b;
std::cout << "utworzono obiekt" << std::endl;
}
~Osoba() { std::cout << "skasowano obiekt" << std::endl; }
};
int main() {
Osoba *obiekt1 = new Osoba("Asia",29),
*obiekt2 = new Osoba();
delete obiekt1,
obiekt2;
} | true |
020593f58284d9778e771d5317def2f88d1ca994 | C++ | luczeng/HoughRectangle | /tests/unit_tests/test_io.cpp | UTF-8 | 4,823 | 2.921875 | 3 | [] | no_license | #define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
#include "io.hpp"
#include "string"
#ifndef STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_IMPLEMENTATION
#ifndef STB_IMAGE_WRITE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <array>
#include "stb_image.h"
#include "stb_image_write.h"
unsigned char uc_conv(int x) { return static_cast<unsigned char>(x); };
/////////////////////////////////////////////////////////////////////////////
// Raw buffer matcher
/////////////////////////////////////////////////////////////////////////////
class RawBufEq : public Catch::MatcherBase<unsigned char*> {
unsigned char* m_arr1;
int m_L;
public:
RawBufEq(unsigned char* arr1, int L) : m_arr1(arr1), m_L(L) {}
// Matcher. If elements don't match, prints them
bool match(unsigned char* const& arr2) const override {
bool out = true;
for (int i = 0; i < m_L; i++) {
if (m_arr1[i] != arr2[i]) {
std::cout << "elements " << i << ": arr1=" << (int)m_arr1[i] << ", arr2=" << (int)arr2[i] << std::endl;
out = false;
} else {
std::cout << "elements " << i << ": arr1=" << (int)m_arr1[i] << ", arr2=" << (int)arr2[i] << std::endl;
}
}
return out;
}
virtual std::string describe() const override {
std::ostringstream ss;
ss << "Arrays do not match";
return ss.str();
}
};
inline RawBufEq IsEqual(unsigned char* arr1, int L) { return RawBufEq(arr1, L); }
/////////////////////////////////////////////////////////////////////////////
// Tests
/////////////////////////////////////////////////////////////////////////////
TEST_CASE("Test Input-output functions for images") {
std::string filename = "../unit_tests/test_img.png";
SECTION("Convert raw buffer to Eigen matrix") {
// Convert some data to Eigen matrix
std::unique_ptr<unsigned char[]> data(new unsigned char[12]);
data[0] = (unsigned char)1;
data[1] = (unsigned char)2;
data[2] = (unsigned char)3;
data[3] = (unsigned char)155;
data[4] = (unsigned char)255;
data[5] = (unsigned char)3;
data[6] = (unsigned char)4;
data[7] = (unsigned char)5;
data[8] = (unsigned char)2;
data[9] = (unsigned char)5;
data[10] = (unsigned char)78;
data[11] = (unsigned char)1;
Eigen::MatrixXf gray;
eigen_io::convert_RawBuff2Mat(data, gray, 4, 3);
// Ground truth
Eigen::MatrixXf ground_truth(3, 4);
ground_truth << 1, 2, 3, 155, 255, 3, 4, 5, 2, 5, 78, 1;
REQUIRE(ground_truth == gray);
}
SECTION("Converter from Eigen matrix to unsigned char raw buffer") {
// Build input
const int x = 4;
const int y = 3;
const int L = x * y;
Eigen::Matrix<float, y, x, Eigen::RowMajor> gray;
;
gray << 1.34, 3.908, 55.201, 255.0978, 0.097, 69.698, 25.09853, 94.8975, 30.309, 50.5, 38.0985, 50;
int ground_truth_int[L] = {1, 4, 55, 255, 0, 70, 25, 95, 30, 51, 38, 50};
// Populate GT. Replace this loop later
std::unique_ptr<unsigned char[]> ground_truth(new unsigned char[L]);
for (int i = 0; i < L; i++) {
ground_truth[i] = static_cast<unsigned char>(ground_truth_int[i]);
}
// Function to test: converting matrix to raw buffer
std::unique_ptr<unsigned char[]> gray_UC(new unsigned char[L]);
eigen_io::convert_Mat2RawBuff(gray, gray_UC, 3 * 4);
// Test Raw buffers equality
REQUIRE_THAT(gray_UC.get(), IsEqual(ground_truth.get(), 12));
}
SECTION("Eigen matrix saver") {
// Dummy matrix
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> gray(3, 6);
gray << 2, 3, 1, 5, 6, 5, 5, 2, 6, 1, 9, 3, 3, 1, 5, 3, 2, 1;
auto out = eigen_io::save_image(gray, "../unit_tests/test_save_img.png", 30, 6, 3);
REQUIRE(out == 1);
}
SECTION("Image reader into Eigen matrix") {
// Load image
std::string test_img_folder_path = UNIT_TEST_FOLDER_PATH;
Eigen::MatrixXf img = eigen_io::read_image(test_img_folder_path + "/test_img.png");
// Ground truth
Eigen::MatrixXf ground_truth(3, 4);
ground_truth << 1, 2, 3, 155, 255, 3, 4, 5, 2, 5, 78, 1;
REQUIRE(ground_truth == img);
}
SECTION("Save maximums to txt file") {
std::vector<std::array<int, 2>> vec_max;
vec_max.push_back({1, 2});
vec_max.push_back({3, 4});
std::string test_img_folder_path = UNIT_TEST_FOLDER_PATH;
std::string filename = test_img_folder_path + "/test_save_maximums.txt";
eigen_io::save_maximum(filename, vec_max);
}
}
#endif
#endif
| true |
9d166f11c79558135dec36bc48fb267b7b1caa96 | C++ | bjpark0805/Problem_solvings | /examples/programmers_위장.cpp | UTF-8 | 789 | 3.46875 | 3 | [] | no_license | //8분 소요
// hash(map) 사용하는 연습문제
// iterator사용하는 법을 잘 익혀두자.
#include <string>
#include <vector>
#include <iostream>
#include <map>
using namespace std;
int solution(vector<vector<string> > clothes) {
int answer = 1;
map<string, int> m;
for(int i = 0; i < clothes.size(); ++i){
if(m.find(clothes[i][1]) != m.end()) m[clothes[i][1]] += 1;
else m[clothes[i][1]] = 1;
}
map<string, int>::iterator iter;
for(iter = m.begin(); iter != m.end(); ++iter){
answer *= iter->second + 1;
}
answer -= 1;
return answer;
}
int main(){
vector<vector<string> > clothes = {{"yellowhat", "headgear"}, {"bluesunglasses", "eyewear"}, {"green_turban", "headgear"}};
cout << solution(clothes) << endl;
return 0;
} | true |
f16668f56d78e572e7062fcdf107eee47c80fd01 | C++ | tusharc31/Temperature-Monitoring-System | /ESW.ino | UTF-8 | 5,100 | 2.671875 | 3 | [] | no_license | // Embedded Systems Workshop - Lab 2 and 3
// Tushar Choudhary
#include "DHT.h"
#include <WiFi.h>
#include <WiFiMulti.h>
#include "BluetoothSerial.h"
// Defining the max safe temperature
int safe_t=15;
// Pin numbers for LEDs and buzzer
const byte alert = 23;
const byte not_alert = 22;
// WiFi and Bluetooh details
#define WIFI_NAME "OnePlus"
#define PASSWORD "56781234"
#define TIMEOUT 5000 // Timeout for server response.
BluetoothSerial SerialBT;
WiFiClient client;
// ThingSpeak details
#define NUM_FIELDS 3 // To update more fields, increase this number and add a field label below.
#define THING_SPEAK_ADDRESS "api.thingspeak.com"
String writeAPIKey="YHZDPHX3B3S1OZB6"; // Change this to the write API key for your channel.
// For connecting to WiFi
int connectWifi()
{
while (WiFi.status() != WL_CONNECTED) {
WiFi.begin( WIFI_NAME , PASSWORD );
Serial.println( "Connecting to Wi-Fi" );
delay( 2500 );
}
Serial.println( "Connected" ); // Inform the serial monitor.
}
// For updating the data obtained on ThingSpeak
int HTTPPost( int numFields , String fieldData[] ){
if (client.connect( THING_SPEAK_ADDRESS , 80 )){
// Build the postData string.
// If you have multiple fields, make sure the sting does not exceed 1440 characters.
String postData= "api_key=" + writeAPIKey ;
for ( int fieldNumber = 1; fieldNumber < numFields+1; fieldNumber++ ){
String fieldName = "field" + String( fieldNumber );
postData += "&" + fieldName + "=" + fieldData[ fieldNumber ];
}
// Print statements for debugging
Serial.println( "Connecting to ThingSpeak for update..." );
Serial.println();
client.println( "POST /update HTTP/1.1" );
client.println( "Host: api.thingspeak.com" );
client.println( "Connection: close" );
client.println( "Content-Type: application/x-www-form-urlencoded" );
client.println( "Content-Length: " + String( postData.length() ) );
client.println();
client.println( postData );
Serial.println( postData );
String answer=getResponse();
Serial.println( answer );
}
else
{
Serial.println ( "Connection Failed" );
}
}
// Function for getting the acknowledgement from ThingSpeak after posting data
String getResponse(){
String response;
long startTime = millis();
delay( 200 );
while ( client.available() < 1 && (( millis() - startTime ) < TIMEOUT ) ){
delay( 5 );
}
if( client.available() > 0 ){ // Get response from server.
char charIn;
do {
charIn = client.read(); // Read a char from the buffer.
response += charIn; // Append the char to the string response.
} while ( client.available() > 0 );
}
client.stop();
return response;
}
// Input pin for Lm35
int lm35=13;
// Detials for DHT22 sensor
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
pinMode(lm35, INPUT);
SerialBT.begin("Tushar ESW");
connectWifi();
Serial.println(F("DHTxx test!"));
pinMode(alert, OUTPUT);
pinMode(not_alert, OUTPUT);
dht.begin();
}
void loop() {
// A short delay after every measurement
delay(30000);
// Getting the data from DHT
float h = dht.readHumidity();
float t = dht.readTemperature();
float f = dht.readTemperature(true);
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
float hif = dht.computeHeatIndex(f, h);
float hic = dht.computeHeatIndex(t, h, false);
// Getting data from Lm35
int analogValue = analogRead(lm35);
float millivolts = (analogValue/1024.0) * 3300;
float lmc = millivolts/10;
float lmf = ((lmc * 9)/5 + 32);
t = (t+lmc)/2;
f = (f+lmf)/2;
// Printing the data on serial monitor
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("째C "));
Serial.print(f);
Serial.print(F("째F Heat index: "));
Serial.print(hic);
Serial.print(F("째C "));
Serial.print(hif);
Serial.println(F("째F"));
// Printing the data to bluetooth connected mobile device
SerialBT.println("Humidity: ");
SerialBT.println(h);
SerialBT.println("Temperature (celsius): ");
SerialBT.println(t);
SerialBT.println("Heat Index: ");
SerialBT.println(hic);
SerialBT.println(" ");
// Checking if the data lies in the safe range
if (t>=safe_t)
{
SerialBT.println("Temperature is outside the safety range!");
Serial.println("Temperature is outside the safety range!");
digitalWrite(alert, HIGH);
digitalWrite(not_alert, LOW);
}
else
{
digitalWrite(alert, LOW);
digitalWrite(not_alert, HIGH);
}
// Calling the function to update data on ThingSpeak
String fieldData[ NUM_FIELDS ];
fieldData[1]=h;
fieldData[2]=t;
fieldData[3]=hif;
HTTPPost( NUM_FIELDS , fieldData );
}
| true |
ca265898ec61eaf832181d08da3a7bb51159d74a | C++ | AdamFurmanek/ProgramowanieGrafikiKomputerowej | /lab1zad1.h | UTF-8 | 1,356 | 2.71875 | 3 | [] | no_license | #pragma once
#include <stdlib.h>
#include <GL/glut.h>
using namespace std;
double cameraX = 0;
double cameraY = 0;
double cameraSpeed = 3.0;
bool figure = true;
GLUquadricObj* obj;
void Display() {
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 1.0, 1.0);
glLoadIdentity();
glRotatef(cameraX, 1.0f, 0.0f, 0.0f);
glRotatef(cameraY, 0.0f, 1.0f, 0.0f);
obj = gluNewQuadric();
gluQuadricDrawStyle(obj, GLU_FILL);
gluQuadricNormals(obj, GLU_SMOOTH);
if(figure)
gluCylinder(obj, 0.1, 0.3, 0.4, 10, 10);
else
gluSphere(obj, 0.4, 10, 10);
glutSwapBuffers();
}
void Reshape(int w, int h) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glViewport(0, 0, w, h);
glMatrixMode(GL_MODELVIEW);
}
void Keyboard(unsigned char key, int x, int y)
{
switch (key)
{
case 'w':
cameraX += cameraSpeed;
break;
case 's':
cameraX -= cameraSpeed;
break;
case 'a':
cameraY += cameraSpeed;
break;
case 'd':
cameraY -= cameraSpeed;
break;
case ' ':
figure = !figure;
cameraX = cameraY = 0;
break;
case 27:
case 'q':
exit(0);
break;
}
Display();
}
static void Launch(int argc, char* argv[]) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
glutInitWindowSize(640, 480);
glutCreateWindow(argv[0]);
glutDisplayFunc(Display);
glutReshapeFunc(Reshape);
glutKeyboardFunc(Keyboard);
glutMainLoop();
} | true |
6c0629b8f2effac487b0f041527d3e2ebe0b87f7 | C++ | tmcphillips/absflow-accelerators | /OpenCL/OpenCL_Features/NumberFilter.Tests/IntegerFilter_Native_Tests.cpp | UTF-8 | 752 | 2.875 | 3 | [] | no_license | #include "stdafx.h"
#include "CppUnitTest.h"
#include <string>
#include <vector>
#include "Utilities.h"
using std::string;
using std::vector;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace NumberFilterTests
{
template<typename T>
vector<T> lowpassFilter(vector<T> inValues, T maxValue) {
vector<T> outValues;
for (T value : inValues) {
if (value <= maxValue) outValues.push_back(value);
}
return outValues;
}
TEST_CLASS(IntegerFilter_Native_Tests)
{
public:
TEST_METHOD(TestLowpassFilter_Native_Short)
{
vector<int> inValues{ 10, 3, 5, -18, 16, 403, -19 };
auto outValues = lowpassFilter(inValues, 10);
Assert::AreEqual(string("10, 3, 5, -18, -19"), concatenate(outValues, ", "));
}
};
} | true |
280d8cf924635396fb3ac5cd18359e54449cdaf1 | C++ | KritikRawal/C-rudiments | /22. Calculator.cpp | UTF-8 | 1,315 | 3.46875 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
using namespace std;
class CALC{
public:
CALC(int i=0)
{
result=i;
}
void addnumber(int num1, int num2)
{
result=num1+num2;
}
void subnumber(int num1, int num2)
{
result=num1-num2;
}
void multnumber(int num1, int num2)
{
result=num1*num2;
}
void divnumber(int num1, int num2)
{
result=num1/num2;
}
int getresult()
{
return result;
}
private:
//hidden from outside the world
int result;
};
int main()
{
CALC cob;
int a,b,c;
char ch;
do{
system("cls");
cout<<"Enter two numbers:";
cin>>a>>b;
cout<<"Enter the operator(+,-,/,*):";
cin>>ch;
switch(ch)
{
case'+':
cob.addnumber(a,b);
cout<<"Summation ="<<cob.getresult()<<"\n";
break;
case'-':
cob.subnumber(a,b);
cout<<"Subtraction ="<<cob.getresult()<<"\n";
break;
case'*':
cob.multnumber(a,b);
cout<<"Multiplication ="<<cob.getresult()<<"\n";
break;
case'/':
cob.divnumber(a,b);
cout<<"Division ="<<cob.getresult()<<"\n";
break;
default:
cout<<"Wrong operator";
break;
}
cout<<"Do you want to continue...(1-YES/0-No):";
cin>>c;
}while(c==1);
getch();
return 0;
}
| true |
064a719ef4160ce766a98c887694c68367bc9600 | C++ | my-official/NastyMathCPP | /Matrix/BaseMatrix.h | WINDOWS-1251 | 4,998 | 2.875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "..\Utils.h"
template <typename ElementType>
using Vector = std::vector<ElementType>;
template <typename ElementType>
ElementType DotProduct(const Vector<ElementType>& a, const Vector<ElementType>& b);
enum class RankMethod
{
LeftTop,
RightTop,
RightBottom,
LeftBottom
};
typedef std::pair<uint32_t, uint32_t> ElementIndex;
//class Matrix;
//typedef Matrix Minor;
template <class T>
struct equal_to_zero {
bool operator() (const T& x) const { return x == 0; }
typedef T first_argument_type;
typedef bool result_type;
};
template <typename ElementType,
class DerivedMatrixT,
class IsEqual = equal_to<ElementType>,
class IsEqualZero = equal_to_zero<ElementType> >
class BaseMatrix : boost::operators< DerivedMatrixT >
{
public:
BaseMatrix() : m_VerticalDimensional(0),
m_HorizontalDimensional(0)
{
}
using zero_t = float;
BaseMatrix(zero_t) : BaseMatrix()
{
}
BaseMatrix(uint32_t vertical, uint32_t horizontal);//
BaseMatrix(initializer_list<ElementType> il);//
BaseMatrix(initializer_list<DerivedMatrixT> il);//
BaseMatrix(uint32_t vertical, uint32_t horizontal, initializer_list<ElementType> il);
BaseMatrix(uint32_t vertical, uint32_t horizontal, initializer_list<DerivedMatrixT> il);
virtual ~BaseMatrix() { static_assert(sizeof(DerivedMatrixT) == sizeof(BaseMatrix) && is_base_of<BaseMatrix, DerivedMatrixT>::value,"Derived Matrix type must have same data-members"); }
uint32_t m_VerticalDimensional;
uint32_t m_HorizontalDimensional;
vector<ElementType> m_Data;
virtual bool operator==(const DerivedMatrixT& rhs) const;
virtual DerivedMatrixT& operator+=(const DerivedMatrixT& rhs);
virtual DerivedMatrixT& operator-=(const DerivedMatrixT& rhs);
virtual DerivedMatrixT& operator*=(const DerivedMatrixT& rhs);
virtual DerivedMatrixT& operator/=(const DerivedMatrixT& rhs);
virtual DerivedMatrixT& Scale(const ElementType& rhs);
virtual DerivedMatrixT operator-() const;
virtual ElementType& operator[](ElementIndex idx);
virtual ElementType operator[](ElementIndex idx) const;
virtual void SetDimensionals(uint32_t vertical, uint32_t horizontal);
virtual DerivedMatrixT& GrowBottom(DerivedMatrixT m);
virtual DerivedMatrixT& GrowRight(DerivedMatrixT m);
virtual void FlipHorizontal();
virtual void FlipVertical();
virtual void ExcludeColumnsExcept(const vector<ElementIndex>& elements);
virtual bool IsZeroMatrix() const;
virtual bool IsIdentityMatrix() const;
virtual uint32_t FindColumn(const DerivedMatrixT& srcColumn, uint32_t offset_x = 0) const;
static const uint32_t npos = -1;
virtual DerivedMatrixT GetSubMatrix(uint32_t y, uint32_t x, uint32_t verticalDimensional, uint32_t horizontalDimensional) const;
virtual void SetSubMatrix(uint32_t y, int32_t x, const DerivedMatrixT& m);
virtual Vector<ElementType> GetRowAsVector(uint32_t verticalIndex) const;
virtual Vector<ElementType> GetColumnAsVector(uint32_t horizontalIndex) const;
virtual void ExtractMinor(uint32_t verticalIndex, uint32_t horizontalIndex, DerivedMatrixT& minor) const;//
virtual ElementType Det() const;
virtual uint32_t Rank(RankMethod rankMethod = RankMethod::LeftTop, vector<ElementIndex>* linearlyIndependent = nullptr) const;
virtual std::string AsStringRanked(RankMethod rankMethod = RankMethod::LeftTop) const;
virtual ElementType Trace() const;
virtual DerivedMatrixT Transpose() const;
virtual DerivedMatrixT Inverse() const;
virtual std::string AsString() const;
virtual std::string AsLatexCode() const;
virtual std::string AsLatexCodeRanked(RankMethod rankMethod = RankMethod::LeftTop) const;
//protected:
public:
virtual uint32_t RankInternal_Step1(vector<ElementIndex>* linearlyIndependent, uint32_t target_x = 0, uint32_t iteration = 0);
private:
IsEqual m_IsEqual;
IsEqualZero m_IsEqualZero;
};
//template <
// class charT, class traits,
// typename ElementType, class DerivedMatrixT, class IsEqual = equal_to<ElementType>, class IsEqualZero = equal_to_zero<ElementType>
//>
//std::basic_ostream<charT, traits>& operator<<(basic_ostream<charT, traits>& latex, const BaseMatrix<ElementType, DerivedMatrixT, IsEqual, IsEqualZero>& a);
template <class DerivedMatrixT>
DerivedMatrixT ZeroMatrix(const DerivedMatrixT& A);
template <class DerivedMatrixT>
DerivedMatrixT IdentityMatrix(const DerivedMatrixT& A);
template <class DerivedMatrixT>
DerivedMatrixT PermutationColumnsMatrix(const DerivedMatrixT& src, const DerivedMatrixT& dest);
template <class DerivedMatrixT>
string to_string(const DerivedMatrixT& val)
{
return val.AsString();
}
template <class DerivedMatrixT>
string to_latex(const DerivedMatrixT& val)
{
return val.AsLatexCode();
}
#include "BaseMatrix.inl"
| true |
86a4250ea2c80709072548536f9ba6ddda290f13 | C++ | colinw7/CQTextFile | /src/CTextFileSel.cpp | UTF-8 | 6,191 | 2.515625 | 3 | [
"MIT"
] | permissive | #include <CTextFileSel.h>
#include <CTextFile.h>
CTextFileSel::
CTextFileSel(CTextFile *file) :
file_ (file),
selected_(false),
selMode_ (RANGE_SEL_MODE),
start_ (),
end_ ()
{
notifyMgr_ = new CTextFileSelNotifierMgr(this);
}
void
CTextFileSel::
addNotifier(CTextFileSelNotifier *notifier)
{
notifyMgr_->addNotifier(notifier);
}
void
CTextFileSel::
removeNotifier(CTextFileSelNotifier *notifier)
{
notifyMgr_->removeNotifier(notifier);
}
void
CTextFileSel::
clearSelection()
{
if (selected_) {
selected_ = false;
notifySelectionChanged();
}
}
void
CTextFileSel::
setMode(SelMode mode)
{
if (mode != selMode_) {
selMode_ = mode;
notifySelectionChanged();
}
}
void
CTextFileSel::
selectBBox(const CIBBox2D & /*bbox*/, bool /*clear*/)
{
}
void
CTextFileSel::
selectInside(const CIBBox2D & /*bbox*/, bool /*clear*/)
{
}
void
CTextFileSel::
rangeSelect(const CIBBox2D & /*bbox*/, bool /*clear*/)
{
}
void
CTextFileSel::
rangeSelect(int row1, int col1, int row2, int col2, bool clear)
{
rangeSelect(CIPoint2D(col1, row1), CIPoint2D(col2, row2), clear);
}
void
CTextFileSel::
rangeSelect(const CIPoint2D &start, const CIPoint2D &end, bool clear)
{
if (end.y < start.y || (end.y == start.y && end.x < start.x)) {
rangeSelect(end, start, clear);
return;
}
bool oldSel = selected_;
CIPoint2D oldStart = start_;
CIPoint2D oldEnd = end_;
if (clear) selected_ = false;
start_ = start;
end_ = end;
selected_ = isValid();
bool changed = false;
if (selected_ != oldSel || start_ != oldStart || end_ != oldEnd)
changed = true;
if (changed)
notifySelectionChanged();
}
void
CTextFileSel::
selectChar(int row, int col)
{
CIPoint2D start(col, row);
CIPoint2D end(start_.x + 1, start.y);
rangeSelect(start, end, true);
}
void
CTextFileSel::
selectLine(int row)
{
const std::string &line = file_->getLine(row);
CIPoint2D start( 0, row);
CIPoint2D end (int(line.size()) - 1, row);
rangeSelect(start, end, true);
}
void
CTextFileSel::
setSelectionColor(const CRGBA & /*color*/)
{
}
void
CTextFileSel::
setSelectRange(const CIPoint2D &start, const CIPoint2D &end)
{
rangeSelect(start, end, true);
}
const CIPoint2D &
CTextFileSel::
getSelectStart() const
{
return start_;
}
const CIPoint2D &
CTextFileSel::
getSelectEnd() const
{
return end_;
}
std::string
CTextFileSel::
getSelectedText() const
{
std::string sel;
if (selMode_ == RANGE_SEL_MODE) {
const std::string &line1 = file_->getLine(start_.y);
int len1 = int(line1.size());
if (len1 > 0) {
int x1 = (start_.x < len1 ? start_.x : 0);
sel += line1.substr(x1);
}
for (int row = start_.y + 1; row <= end_.y - 1; ++row)
sel += "\n" + file_->getLine(row);
const std::string &line2 = file_->getLine(end_.y);
int len2 = int(line2.size());
if (len2 > 0) {
int x2 = (end_.x + 1 < len2 ? end_.x + 1 : len2);
sel += "\n" + line2.substr(0, x2);
}
}
else {
for (int row = start_.y; row <= end_.y; ++row) {
const std::string &line = file_->getLine(row);
int len = int(line.size());
if (row > start_.y) sel += "\n";
if (len <= 0) continue;
int x1 = std::min(start_.x, end_.x);
int x2 = std::max(start_.x, end_.x);
if (x1 < 0) x1 = 0;
if (x1 >= len) { x1 = len - 1; x2 = x1; }
else if (x2 >= len) x2 = len - 1;
sel += line.substr(x1, x2 - x1 + 1);
}
}
return sel;
}
bool
CTextFileSel::
isLineInside(uint row) const
{
if (! selected_) return false;
if (selMode_ == RANGE_SEL_MODE)
return (int(row) > start_.y && int(row) < end_.y);
else
return false;
}
bool
CTextFileSel::
isPartLineInside(uint row) const
{
if (! selected_) return false;
if (selMode_ == RANGE_SEL_MODE)
return (int(row) >= start_.y && int(row) <= end_.y);
else
return (int(row) >= start_.y && int(row) <= end_.y);
}
bool
CTextFileSel::
isCharInside(uint row, int col) const
{
if (! selected_) return false;
if (selMode_ == RANGE_SEL_MODE) {
if (start_.y == end_.y)
return (int(row) == start_.y &&
int(col) >= start_.x && int(col) <= end_ .x);
else
return (int(row) == start_.y && int(col) >= start_.x) ||
(int(row) == end_ .y && int(col) <= end_ .x);
}
else {
return (int(row) >= start_.y && int(row) <= end_ .y &&
int(col) >= start_.x && int(col) <= end_ .x);
}
}
bool
CTextFileSel::
insideSelection(const CIPoint2D &pos) const
{
if (! selected_) return false;
if (selMode_ == RANGE_SEL_MODE) {
if (start_.y == end_.y)
return (pos.y == start_.y && pos.x >= start_.x && pos.x <= end_.x);
else {
if (pos.y == start_.y)
return pos.x >= start_.x;
else if (pos.y == end_ .y)
return pos.x <= end_ .x;
else
return (pos.y > start_.y && pos.y < end_.y);
}
}
else {
return (pos.y >= start_.y && pos.y <= end_.y &&
pos.x >= start_.x && pos.x <= end_.x);
}
}
bool
CTextFileSel::
isValid() const
{
if (selMode_ == RANGE_SEL_MODE)
return cmp(start_, end_) < 0;
else
return true;
}
int
CTextFileSel::
cmp(const CIPoint2D &p1, const CIPoint2D &p2)
{
if (p1.y == p2.y)
return (p1.x - p2.x);
else
return (p1.y - p2.y);
}
void
CTextFileSel::
notifySelectionChanged()
{
notifyMgr_->selectionChanged(getSelectedText());
//cerr << getSelectedText() << endl;
}
//------
CTextFileSelNotifierMgr::
CTextFileSelNotifierMgr(CTextFileSel *sel) :
sel_(sel)
{
}
void
CTextFileSelNotifierMgr::
addNotifier(CTextFileSelNotifier *notifier)
{
notifierList_.push_back(notifier);
}
void
CTextFileSelNotifierMgr::
removeNotifier(CTextFileSelNotifier *notifier)
{
notifierList_.remove(notifier);
}
void
CTextFileSelNotifierMgr::
selectionChanged(const std::string &str)
{
NotifierList::const_iterator p1, p2;
for (p1 = notifierList_.begin(), p2 = notifierList_.end(); p1 != p2; ++p1)
(*p1)->selectionChanged(str);
}
//------
CTextFileSelNotifier::
CTextFileSelNotifier()
{
}
void
CTextFileSelNotifier::
selectionChanged(const std::string &)
{
}
| true |
00e52fdbeb33567a615688d0b1d92c652321d86d | C++ | yuquanF/cpp_course_code | /chapter_2/eg_2_18/quote_1.cpp | UTF-8 | 1,425 | 3.828125 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int i;
int &j = i;
i = 30;
cout<<"i = "<<i<<", j = "<<j<<endl; // i=30,j=30
j = 80;
cout<<"i = "<<i<<", j = "<<j<<endl;
cout<<"i addr: "<<&i<<endl;
cout<<"j addr: "<<&j<<endl;
return 0;
}
/**
* 引用说明:
* 1)引用名可以使用任何合法的变量名。
* 2)除了用作函数的参数或者返回类型外,在声明引用时,必须立即对它进行初始化,不能声明完成后再赋值。
* 3)为引用提供的初始值,可以是一个变量或另外一个引用。
* 4)指针是通过地址间接访问某个变量,而引用是通过别名直接访问某个变量。
* 5)引用在初始化后不能再被重新声明为另一个变量的引用。
* 6)并不是任何类型的数据都可以引用。
* 6.1 不允许建立void类型的引用: void &r = 10; // 错误
* 6.2 不能建立引用的数组: int a[4] = "abcd"; int &ra[4] = a; // 错误
* 6.3 不能建立引用的引用,不能建立指向引用的指针:
* int n = 3;
* int &&r = n; // 错误,不能建立引用的引用
* int &*p = n; // 错误,不能建立指向引用的指针
* 7)可将引用的地址赋给一个指针,此时指针指向的是原来的变量。
* 8)引用操作符&仅仅声明时代表引用的意思,其他场合使用都是地址操作符。
*/ | true |
51005fc156945c5cdf916eea4a4a16e24b4c65e5 | C++ | ShashankRampardos/Cpp | /Assignment 28 Mar 2021/Q27 ClassOfClass.cpp | UTF-8 | 234 | 3 | 3 | [] | no_license | #include<iostream>
using namespace std;
class B
{ public:
int y=0;
};
class A
{
B obj;
int x;
public:
void fun()
{
cout<<obj.y;
}
};
int main()
{
A main;
main.fun();
}
| true |
622444f6901fa4e6bf43ee4f00b6bea64a87104e | C++ | harpreethkaurj/Simulation-of-weather-conditions-using-open-gl | /main.cpp | UTF-8 | 79,493 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<GL/glut.h>
#include<windows.h>
#define PI 3.1416
GLint i;
GLfloat cx=0,str=500.0,mn=500.0;
GLfloat sr=0.0,sg=0.749,sb=1.0;
void circle(GLdouble rad) {
GLint points = 50;
GLdouble delTheta = (2.0 * PI) / (GLdouble)points;
GLdouble theta = 0.0;
glBegin(GL_POLYGON);
for( i = 0; i <=50; i++, theta += delTheta )
{
glVertex2f(rad * cos(theta),rad * sin(theta));
}
glEnd();
}
void bus()
{
glColor3f(1.0, 0.5, 0.0);
glBegin(GL_POLYGON);
glVertex3f(-0.52, 0.2, 0.0);
glVertex3f(-0.9, 0.2, 0.0);
glVertex3f(-0.87, 0.5, 0.0);
glVertex3f(-0.52, 0.5, 0.0);
glEnd();
glColor3f(1.0, 0.5, 0.0);
glBegin(GL_POLYGON);
glVertex3f(-0.43, 0.2, 0.0);
glVertex3f(-0.52, 0.2, 0.0);
glVertex3f(-0.52, 0.5, 0.0);
glVertex3f(-0.46, 0.45,0.0);
glEnd();
glColor3f(1.0, 0.5, 1.0);
glBegin(GL_POLYGON);
glVertex3f(-0.53, 0.5, 0.0);
glVertex3f(-0.83, 0.5, 0.0);
glVertex3f(-0.77, 0.8, 0.0);
glVertex3f(-0.56, 0.75, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.65, 0.2, 0.0);
glVertex3f(-0.65, 0.5, 0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.65, 0.5, 0.0);
glVertex3f(-0.68, 0.79, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.75, 0.2, 0.0);
glVertex3f(-0.75, 0.5, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.75, 0.5, 0.0);
glVertex3f(-0.77, 0.8, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.55, 0.2, 0.0);
glVertex3f(-0.55, 0.5, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.55, 0.5, 0.0);
glVertex3f(-0.58, 0.77, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.6, 0.4, 0.0);
glVertex3f(-0.62, 0.4, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glBegin(GL_LINES);
glVertex3f(-0.7, 0.4, 0.0);
glVertex3f(-0.72, 0.4, 0.0);
glEnd();
glColor3f(0.0, 0.0, 0.0);
glPushMatrix();
glTranslatef(-0.78, 0.2, 0.0);
circle(0.06);
glPopMatrix();
glColor3f(0.0, 0.0, 0.0);
glPushMatrix();
glTranslatef(-0.5, 0.2, 0.0);
circle(0.06);
glPopMatrix();
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glTranslatef(-0.5, 0.2, 0.0);
circle(0.02);
glPopMatrix();
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glTranslatef(-0.78, 0.2, 0.0);
circle(0.02);
glPopMatrix();
}
void cloudB() {
glPushMatrix();
glTranslatef(4.0,5.5,0.0);
circle(4.0);
glPopMatrix();
//right
glPushMatrix();
glTranslatef(-8.0,5.5,0.0);
circle(3.5);
glPopMatrix();
//top left
glPushMatrix();
glTranslatef(-3.5,9.0,0.0);
circle(3.5);
glPopMatrix();
//top right
glPushMatrix();
glTranslatef(1.0,9.0,0.0);
circle(3.0);
glPopMatrix();
//middle
glPushMatrix();
glColor3f(1.0, 1.0 ,1.0);
glTranslatef(-1.5,5.5,0.0);
circle(4);
glPopMatrix();
}
void a() //mini Cloud
{ //left
glPushMatrix();
glTranslatef(4.0,5.5,0.0);
circle(4);
glPopMatrix();
//right
glPushMatrix();
glTranslatef(-8.0,5.5,0.0);
circle(3.5);
glPopMatrix();
//top left
glPushMatrix();
glTranslatef(-3.5,9.0,0.0);
circle(3.5);
glPopMatrix();
//top right
glPushMatrix();
glTranslatef(1.0,9.0,0.0);
circle(3.0);
glPopMatrix();//middle
glPushMatrix(); glTranslatef(-1.5,5.5,0.0);
circle(4); glPopMatrix();
}
void c() //One Single Cloud
{
glPushMatrix();
glColor3f(1.0,1.0,1.0);
glTranslatef(35.0,10.0,0.0);
a();
glPopMatrix();
glPushMatrix();
glColor3f(1.0,1.0,1.0);
glTranslatef(28.0,16.0,0.0);
a();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(20.0,10.0,0.0);
a();
glPopMatrix();
}
void cloud() // Three Cloud
{
glPushMatrix();
glTranslatef(-15.0,25.0,0.0);
glScalef(0.7,0.7,0.0);
c();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,25.0,0.0);
glScalef(0.7,0.7,0.0);
c();
glPopMatrix();
glPushMatrix();
glTranslatef(-60.0,25.0,0.0);
glScalef(0.7,0.7,0.0);
c();
glPopMatrix();
}
void rect()
{
glRectf(-16.0, -16.0, 16.0, 16.0);
}
GLfloat ss=0.0;
void day()
{
glBegin(GL_POLYGON);
// blue sky
glColor3f(sr,sg,sb);
glVertex3f(-50,-3,0.0);
glVertex3f(-50,50,0.0);
glVertex3f(80.0,50.0,0.0);
glVertex3f(80.0,-3.0,0.0);
glEnd();
glPushMatrix();
//sun
glTranslatef(ss,0.0,0.0);
glTranslatef(-20.0,40.0,0.0);
glScalef(1.0,1.5,0.0);
glColor3f(1.0,1.0,0.0);
circle(3);
glPopMatrix();
}
void ground()
{
glColor3f(0.4,0.4,0.4);
glPushMatrix();
glTranslatef(-70.0,-42.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(-10.0, 0.0,0.0);
glVertex3f(-10.0,10.0,0.0);
glVertex3f (600.0,10.0,0.0);
glVertex3f (600.0,0.0,0.0);
glEnd();
}
void divider()
{
glColor3f(1.0,1.0,1.0);
glTranslatef(-30.0,-43.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(-10.0,4.0,0.0);
glVertex3f(-10.0,6.0,0.0);
glVertex3f(-2.0,6.0,0.0);
glVertex3f(-2.0,4.0,0.0);
glEnd();
}
void divider1()
{
glColor3f(1.0,1.0,1.0);
glTranslatef(-10.0,-43.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(-10.0,4.0,0.0);
glVertex3f(-10.0,6.0,0.0);
glVertex3f(-2.0,6.0,0.0);
glVertex3f(-2.0,4.0,0.0);
glEnd();
}
void divider2()
{
glColor3f(1.0,1.0,1.0);
glTranslatef(10.0,-43.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(-10.0,4.0,0.0);
glVertex3f(-10.0,6.0,0.0);
glVertex3f(-2.0,6.0,0.0);
glVertex3f(-2.0,4.0,0.0);
glEnd();
}
void divider3()
{
glColor3f(1.0,1.0,1.0);
glTranslatef(30.0,-43.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(-10.0,4.0,0.0);
glVertex3f(-10.0,6.0,0.0);
glVertex3f(-2.0,6.0,0.0);
glVertex3f(-2.0,4.0,0.0);
glEnd();
}
void divider4()
{
glColor3f(1.0,1.0,1.0);
glTranslatef(50.0,-43.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(-10.0,4.0,0.0);
glVertex3f(-10.0,6.0,0.0);
glVertex3f(-2.0,6.0,0.0);
glVertex3f(-2.0,4.0,0.0);
glEnd();
}
void night() //black sky
{
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
glVertex3f(-50.0,-3.0,0.0);
glVertex3f(-50.0,50.0,0.0);
glVertex3f(80.0,50.0,0.0);
glVertex3f(80.0,-3.0,0.0);
}
void moon() //moon
{
glPushMatrix();
glTranslatef(mn,0.0,0.0);
glTranslatef(20.0,35.0,0.0);
glScalef(1.0,1.5,0.0);
glColor3f(1.0,1.0,1.0);
circle(3.5);
glPopMatrix();
glutPostRedisplay();
}
void triangle(void)
{
glColor3f(0.137255,0.556863,0.137255);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(9.0, 13.0, 0.0);
glVertex3f(18.0, 0.0, 0.0);
glEnd();
}
void grass()
{
glPushMatrix();
glColor3f(0.8,0.196078,0.6);
glTranslatef(38.0,16.0,0.0);
glScalef(0.1,0.1,0.0);
cloud();
glPopMatrix();
}
void tree2() {
glPushMatrix();
glTranslatef(3.0,8.0,0.0);
triangle();
glPopMatrix();
glPushMatrix();
glTranslatef(3.5,14.0,0.0);
glScalef(0.9,0.9,0.0);
triangle();
glPopMatrix();
glPushMatrix();
glTranslatef(4.5,20.0,0.0);
glScalef(0.8,0.8,0.0);
triangle();
glPopMatrix();
glPushMatrix();
glTranslatef(7.0,26.0,0.0);
glScalef(0.5,0.5,0.0);
triangle();
glPopMatrix();
//gora
glPushMatrix();
glBegin(GL_POLYGON);
glColor3f(0.36,0.25,0.20);
glVertex3f(10.0, 4.0, 0.0);
glVertex3f(10.0, 8.0, 0.0);
glVertex3f(14.0, 8.0, 0.0);
glVertex3f(14.0, 4.0, 0.0);
glEnd();
glPopMatrix();
}
void tree() //green leaves
{
glPushMatrix();
glTranslatef(35.0,10.0,0.0);
a();
glPopMatrix();
glPushMatrix();
glTranslatef(28.0,16.0,0.0);
a();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,10.0,0.0);
a();
glPopMatrix();
}
void treebody() //tree body
{
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(0.0,0.0,0.0);
glVertex3f(2.5,2.0,0.0);
glVertex3f(4.0,-2.0,0.0);
glVertex3f(1.0,-4.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(7.0,2.0,0.0);
glVertex3f(9.0,2.0,0.0);
glVertex3f(8.0,-2.0,0.0);
glVertex3f(4.0,-2.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(1.0,-4.0,0.0);
glVertex3f(4.0,-2.0,0.0);
glVertex3f(8.0,-2.0,0.0);
glVertex3f(7.0,-7.0,0.0);
glVertex3f(1.5,-7.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(1.5,-7.0,0.0);
glVertex3f(7.0,-7.0,0.0);
glVertex3f(6.5,-10.0,0.0);
glVertex3f(2.0,-10.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(2.0,-10.0,0.0);
glVertex3f(6.5,-10.0,0.0);
glVertex3f(6.8,-13.0,0.0);
glVertex3f(1.5,-13.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(1.5,-13.0,0.0);
glVertex3f(6.8,-13.0,0.0);
glVertex3f(7.0,-18.0,0.0);
glVertex3f(0.5,-18.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(0.5,-18.0,0.0);
glVertex3f(7.0,-18.0,0.0);
glVertex3f(3.0,-27.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(0.5,-18.0,0.0);
glVertex3f(2.5,-23.0,0.0);
glVertex3f(-1.0,-25.0,0.0);
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.502, 0.000, 0.000);
glVertex3f(7.0,-18.0,0.0);
glVertex3f(8.0,-28.0,0.0);
glVertex3f(4.0,-22.0,0.0);
glEnd();
}
///////////////////// / //***HOME Start***//// / /////////////////////
void home1()
{
//1st Home / /1
glColor3ub(102,51,0);
glBegin(GL_POLYGON);
glVertex2d(3.0,14.0);
glVertex2d(3.0,11.0);
glVertex2d(10.0,8.0);
glVertex2d(10.0,12.0);
glVertex2d(6.0,18.0);
glEnd();
glColor3ub(153,153,0);
glBegin(GL_POLYGON);
glVertex2d(10.0,8.0);
glVertex2d(10.0,12.0);
glVertex2d(20.0,12.0);
glVertex2d(20.0,8.0);
glEnd();
glColor3ub(0,100,200);
glBegin(GL_POLYGON);
glVertex2d(10.0,12.0);
glVertex2d(6.0,18.0);
glVertex2d(17.0,18.0);
glVertex2d(21.0,12.0);
glEnd();
glColor3ub(255,255,0);
glBegin(GL_POLYGON);
glVertex2d(5.0,11.0);
glVertex2d(5.0,12.0);
glVertex2d(8.0,11.0);
glVertex2d(8.0,10.0);
glEnd();
glColor3ub(50,50,50);
glBegin(GL_POLYGON);
glVertex2d(14.0,8.0);
glVertex2d(14.0,10.0);
glVertex2d(17.0,10.0);
glVertex2d(17.0,8.0);
glEnd();
}
void house() {
glColor3ub(240,150,100);
glBegin(GL_POLYGON);
glVertex2d(33.0,23.0);
glVertex2d(44.0,23.0);
glVertex2d(44.0,30.0);
glVertex2d(33.0,30.0);
glEnd();
glColor3ub(0,105,105);
glBegin(GL_POLYGON);
glVertex2d(31.0,30.0);
glVertex2d(46.0,30.0);
glVertex2d(38.5,38.0);
glEnd();
}
//HOME END///
void well()
{
glBegin(GL_POLYGON);
glColor3ub(204, 51, 0);
glVertex2f(-0.9f,-0.35f);
glVertex2f(-0.9f,-0.55f);
glVertex2f(-0.85f,-0.575f);
glVertex2f(-0.8f,-0.59f);
glVertex2f(-0.7f,-0.59f);
glVertex2f(-0.65f,-0.575f);
glVertex2f(-0.6f,-0.55f);
glVertex2f(-0.6f,-0.35f);
glEnd();
glBegin(GL_POLYGON);
// glColor3ub(255, 102, 51);
glColor3ub(38, 154, 214);
glVertex2f(-0.9f,-0.35f);
glVertex2f(-0.85f,-0.375f);
glVertex2f(-0.8f,-0.38f);
glVertex2f(-0.7f,-0.38f);
glVertex2f(-0.65f,-0.375f);
glVertex2f(-0.6f,-0.35f);
glVertex2f(-0.65f,-0.33f);
glVertex2f(-0.7f,-0.325f);
glVertex2f(-0.8f,-0.325f);
glVertex2f(-0.85f,-0.33f);
glEnd();
glLineWidth(5);
glBegin(GL_LINES);
glColor3ub(204, 51, 0);
glVertex2f(-0.9f,-0.35f);
glVertex2f(-0.85f,-0.33f);//
glVertex2f(-0.85f,-0.33f);
glVertex2f(-0.8f,-0.325f);//
glVertex2f(-0.8f,-0.325f);
glVertex2f(-0.7f,-0.325f);//
glVertex2f(-0.7f,-0.325f);
glVertex2f(-0.65f,-0.33f);//
glVertex2f(-0.65f,-0.33f);
glVertex2f(-0.6f,-0.35f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(194, 194, 163);
glVertex2f(-0.59f,-0.43f);
glVertex2f(-0.57f,-0.5f);
glVertex2f(-0.52f,-0.5f);
glVertex2f(-0.5f,-0.43f);
glVertex2f(-0.52f,-0.42f);
glVertex2f(-0.57f,-0.42f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(38, 154, 214);
glVertex2f(-0.585f,-0.43f);
glVertex2f(-0.568f,-0.44f);
glVertex2f(-0.528f,-0.44f);
glVertex2f(-0.505f,-0.43f);
glVertex2f(-0.528f,-0.425f);
glVertex2f(-0.57f,-0.425f);
glEnd();
glLineWidth(3);
glBegin(GL_LINES);
glColor3ub(194, 194, 163);
glVertex2f(-0.59f,-0.43f);
glVertex2f(-0.57f,-0.39f);//
glVertex2f(-0.57f,-0.39f);
glVertex2f(-0.55f,-0.39f);//
glVertex2f(-0.55f,-0.39f);
glVertex2f(-0.52f,-0.39f);//
glVertex2f(-0.52f,-0.39f);
glVertex2f(-0.5f,-0.43f);//
glEnd();
glLineWidth(2);
glBegin(GL_LINES);
glColor3ub(230, 172, 0);
glVertex2f(-0.545f,-0.385f);
glVertex2f(-0.57f,-0.45f);//
glVertex2f(-0.57f,-0.45f);
glVertex2f(-0.575f,-0.5f);//
glVertex2f(-0.575f,-0.5f);
glVertex2f(-0.58f,-0.53f);//
glVertex2f(-0.58f,-0.53f);
glVertex2f(-0.57f,-0.55f);//
glVertex2f(-0.57f,-0.55f);
glVertex2f(-0.48f,-0.53f);//
glEnd();
}
void bird()
{
//bird1//
int i;
GLfloat a=0.175f,b=0.8f,c=0.15f,d=0.8f,e=0.14f,f1=0.84f,f2=0.1f,f3=0.11f,f4=0.79f,f5=0.12f,f6=0.78f,f7=0.16f,f8=0.77f,f9=0.19f,f10=0.201f,f11=0.83f,f12=0.144f;
GLfloat mm=0.182f; GLfloat nn=.801f; GLfloat radiusmm =.01f;
int triangleAmount = 20;
GLfloat twicePi = 2.0f * PI;
glBegin(GL_TRIANGLE_FAN);
glColor3f(0.0,0.0,0.0);
// glColor3ub(225, 225, 208);
glVertex2f(mm, nn); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
mm + (radiusmm * cos(i * twicePi / triangleAmount)),
nn + (radiusmm * sin(i * twicePi / triangleAmount))
);
}
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
//glColor3ub(225, 225, 208 );
glVertex2f(f2,b);
glVertex2f(f3,f4);
glVertex2f(f5,f6);
glVertex2f(f7,f8);
glVertex2f(f9,f4);
glVertex2f(f10,d);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
//glColor3ub(217, 217, 217);
glVertex2f(a,b);
glVertex2f(c,d);
glVertex2f(e,f1);
/* for(i=0;i<=30;i++)
{
glVertex2f(a+=0.175f,b);
glVertex2f(c+=0.15f,d);
glVertex2f(e+=0.14f,f1);
}*/
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
// glColor3ub(242, 242, 242 );
glVertex2f(a,b);
glVertex2f(f12,d);
glVertex2f(f5,f11);
/*for(i=0;i<=0;i++)
{
glVertex2f(a+=0.175f,b);
glVertex2f(f12+=0.144f,d);
glVertex2f(f5+=0.12f,f11);
}*/
glEnd();
/////2nd bird////
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
//glColor3ub(225, 225, 208 );
glVertex2f(-0.02f,0.8f);
glVertex2f(-0.01f,0.79f);
glVertex2f(0.0f,0.78f);
glVertex2f(0.04f,0.77f);
glVertex2f(0.07f,0.79f);
glVertex2f(0.081f,0.8f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
// glColor3ub(217, 217, 217);
glVertex2f(0.055f,0.8f);
glVertex2f(0.03f,0.8f);
glVertex2f(0.02f,0.84f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
//glColor3ub(242, 242, 242 );
glVertex2f(0.055f,0.8f);
glVertex2f(0.024f,0.8f);
glVertex2f(0.0f,0.83f);
glEnd();
GLfloat mmm=0.062f; GLfloat nnn=.801f; GLfloat radiusmmm =.01f;
glBegin(GL_TRIANGLE_FAN);
glColor3f(0.0,0.0,0.0);
//glColor3ub(225, 225, 208);
glVertex2f(mmm, nnn); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
mmm + (radiusmmm * cos(i * twicePi / triangleAmount)),
nnn + (radiusmmm * sin(i * twicePi / triangleAmount))
);
}
glEnd();
/////3rd bird/////
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
// glColor3ub(225, 225, 208 );
glVertex2f(-0.72f,0.8f);
glVertex2f(-0.71f,0.79f);
glVertex2f(-0.7f,0.78f);
glVertex2f(-0.66f,0.77f);
glVertex2f(-0.63f,0.79f);
glVertex2f(-0.619f,0.8f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
// glColor3ub(217, 217, 217);
glVertex2f(-0.645f,0.8f);
glVertex2f(-0.67f,0.8f);
glVertex2f(-0.68f,0.84f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
// glColor3ub(242, 242, 242 );
glVertex2f(-0.645f,0.8f);
glVertex2f(-0.676f,0.8f);
glVertex2f(-0.7f,0.83f);
glEnd();
GLfloat mmmm=-0.638f; GLfloat nnnn=.801f;
glBegin(GL_TRIANGLE_FAN);
glColor3f(0.0,0.0,0.0);
// glColor3ub(225, 225, 208);
glVertex2f(mmmm,nnnn); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
mmmm + (radiusmmm * cos(i * twicePi / triangleAmount)),
nnnn + (radiusmmm * sin(i * twicePi / triangleAmount))
);
}
glEnd();
////4th bird////
GLfloat mmmmm=-0.518f; GLfloat nnnnn=.801f;
glBegin(GL_TRIANGLE_FAN);
glColor3f(0.0,0.0,0.0);
//glColor3ub(225, 225, 208);
glVertex2f(mmmmm, nnnnn); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
mmmmm + (radiusmm * cos(i * twicePi / triangleAmount)),
nnnnn + (radiusmm * sin(i * twicePi / triangleAmount))
);
}
glEnd();
glBegin(GL_POLYGON);
glColor3f(0.0,0.0,0.0);
//glColor3ub(225, 225, 208 );
glVertex2f(-0.6f,0.8f);
glVertex2f(-0.59f,0.79f);
glVertex2f(-0.58f,0.78f);
glVertex2f(-0.54f,0.77f);
glVertex2f(-0.51f,0.79f);
glVertex2f(-0.499f,0.8f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
// glColor3ub(217, 217, 217);
glVertex2f(-0.525f,0.8f);
glVertex2f(-0.55f,0.8f);
glVertex2f(-0.56f,0.84f);
glEnd();
glBegin(GL_TRIANGLES);
glColor3f(0.0,0.0,0.0);
// glColor3ub(242, 242, 242 );
glVertex2f(-0.525f,0.8f);
glVertex2f(-0.556f,0.8f);
glVertex2f(-0.58f,0.83f);
glEnd();
// glutPostRedisplay();
}
void backgroundtree()
{
//pamtrees
glBegin(GL_POLYGON);
glColor3ub(102,51,30);
glVertex2f(-1.0f,0.45f);
glVertex2f(-0.98f, 0.5f);
glVertex2f(-0.93f, 0.56);
glVertex2f(-0.9f,0.6f);
glVertex2f(-0.82f, 0.64);
glVertex2f(-0.75f, 0.67);
glVertex2f(-0.68f, 0.64);
glVertex2f(-0.6f,0.6f);
glVertex2f(-0.57f, 0.56);
glVertex2f(-0.52f, 0.5f);
glVertex2f(-0.5f,0.45f);
glVertex2f(-1.0f,0.45f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(102,51,0);
glVertex2f(1.0f,0.45f);
glVertex2f(0.98f, 0.5f);
glVertex2f(0.93f, 0.56);
glVertex2f(0.9f,0.6f);
glVertex2f(0.82f, 0.64);
glVertex2f(0.75f, 0.67);
glVertex2f(0.68f, 0.64);
glVertex2f(0.6f,0.6f);
glVertex2f(0.57f, 0.56);
glVertex2f(0.52f, 0.5f);
glVertex2f(0.5f,0.45f);
glVertex2f(1.0f,0.45f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(102,51,0);
glVertex2f(-0.5f,0.45f);
glVertex2f(-0.48f, 0.5f);
glVertex2f(-0.45f, 0.56);
glVertex2f(-0.42f,0.6f);
glVertex2f(-0.37f, 0.62);
glVertex2f(-0.32f, 0.6);
glVertex2f(-0.29f, 0.56f);
glVertex2f(-0.27f, 0.5f);
glVertex2f(-0.25f,0.45f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(102,51,0);
glVertex2f(0.5f,0.45f);
glVertex2f(0.48f, 0.5f);
glVertex2f(0.45f, 0.56);
glVertex2f(0.42f,0.6f);
glVertex2f(0.37f, 0.62);
glVertex2f(0.32f, 0.6);
glVertex2f(0.29f, 0.56f);
glVertex2f(0.27f, 0.5f);
glVertex2f(0.25f,0.45f);
glEnd();
glBegin(GL_POLYGON);
glColor3ub(102,51,0);
glVertex2f(-.25f,0.45f);
glVertex2f(-0.23f, 0.5f);
glVertex2f(-0.18f, 0.56);
glVertex2f(-0.15f,0.6f);
glVertex2f(-0.07f, 0.64);
glVertex2f(-0.00f, 0.67);
glVertex2f(0.07f, 0.64);
glVertex2f(0.15f,0.6f);
glVertex2f(0.18f, 0.56);
glVertex2f(0.23f, 0.5f);
glVertex2f(.25f,0.45f);
glEnd();
}
void triangle1(void)
{
glColor3f(1.0,1.0,1.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(9.0, 13.0, 0.0);
glVertex3f(18.0, 0.0, 0.0);
glEnd();
}
void grass1()
{
glLineWidth(4);
glBegin(GL_LINES);
glColor3ub(0, 102, 0);
glVertex2f(-.05f, -0.35f);
glVertex2f(-0.0f, -0.4f);//
glVertex2f(0.05f, -0.35f);
glVertex2f(0.0f, -0.4f);//
glVertex2f(0.027f, -0.33f);
glVertex2f(0.0f, -0.4f);//
glVertex2f(-0.027f, -0.33f);
glVertex2f(0.0f, -0.4f);//
glVertex2f(0.0f, -0.3f);
glVertex2f(0.0f, -0.4f);//
glVertex2f(-0.075f, -0.37f);
glVertex2f(-0.0f, -0.4f);//
glVertex2f(0.0745f, -0.37f);
glVertex2f(-0.0f, -0.4f);//
glEnd();
int i;
int triangleAmount = 20;
GLfloat twicePi = 2.0f * PI;
GLfloat e=-.05f; GLfloat f=-.35f; GLfloat radius11 =.02f;
glBegin(GL_TRIANGLE_FAN);
glColor3ub(255, 51, 0);
glVertex2f(e, f); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
e + (radius11 * cos(i * twicePi / triangleAmount)),
f+ (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
GLfloat g=0.05f; GLfloat h=-0.35f;
glBegin(GL_TRIANGLE_FAN);
glColor3ub(255, 102, 0);
glVertex2f(g, h); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
g + (radius11 * cos(i * twicePi / triangleAmount)),
h+ (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
GLfloat a1=0.0f; GLfloat b1=-0.3f;
glBegin(GL_TRIANGLE_FAN);
glColor3ub(255, 255, 0);
glVertex2f(a1, b1); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
a1 + (radius11 * cos(i * twicePi / triangleAmount)),
b1 + (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
void flower()
{
int i;
int triangleAmount = 20;
GLfloat twicePi = 2.0f * PI;
GLfloat e=-.05f; GLfloat f=-.35f; GLfloat radius11 =.02f;
glBegin(GL_TRIANGLE_FAN);
glColor3ub(255, 182, 203);
glVertex2f(e, f); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
e + (radius11 * cos(i * twicePi / triangleAmount)),
f+ (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
GLfloat g=0.05f; GLfloat h=-0.35f;
glBegin(GL_TRIANGLE_FAN);
glColor3ub(255, 182, 203);
glVertex2f(g, h); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
g + (radius11 * cos(i * twicePi / triangleAmount)),
h+ (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
GLfloat a1=0.0f; GLfloat b1=-0.3f;
glBegin(GL_TRIANGLE_FAN);
glColor3ub(255, 182, 203);
glVertex2f(a1, b1); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
a1 + (radius11 * cos(i * twicePi / triangleAmount)),
b1 + (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
void flower1()
{
int i;
int triangleAmount = 20;
GLfloat twicePi = 2.0f * PI;
GLfloat e=-.05f; GLfloat f=-.35f; GLfloat radius11 =.02f;
glBegin(GL_TRIANGLE_FAN);
glColor3f(1.0,1.0,0.0);
glVertex2f(e, f); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
e + (radius11 * cos(i * twicePi / triangleAmount)),
f+ (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
GLfloat g=0.05f; GLfloat h=-0.35f;
glBegin(GL_TRIANGLE_FAN);
glColor3f(1.0,1.0,0.0);
glVertex2f(g, h); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
g + (radius11 * cos(i * twicePi / triangleAmount)),
h+ (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
GLfloat a1=0.0f; GLfloat b1=-0.3f;
glBegin(GL_TRIANGLE_FAN);
glColor3f(1.0,1.0,0.0);
glVertex2f(a1, b1); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
a1 + (radius11 * cos(i * twicePi / triangleAmount)),
b1 + (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
void apple()
{
int i;
int triangleAmount = 20;
GLfloat twicePi = 2.0f * PI;
GLfloat e=-.05f; GLfloat f=-.35f; GLfloat radius11 =.02f;
glBegin(GL_TRIANGLE_FAN);
glColor3ub(255, 51, 0);
glVertex2f(e, f); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
e + (radius11 * cos(i * twicePi / triangleAmount)),
f+ (radius11 * sin(i * twicePi / triangleAmount))
);
}
glEnd();
}
void fence()
{
glLineWidth(4);
glBegin(GL_LINES);
glColor3ub(255, 255, 102);
glVertex2f(-2.0f,-0.1f);
glVertex2f(-1.6f,-0.1f);
glColor3ub(255, 255, 102);
glVertex2f(-2.0f,-0.05f);
glVertex2f(-1.6f,-0.05f);
glColor3ub(255, 255, 102);
glVertex2f(-2.0f,0.0f);
glVertex2f(-1.6f,0.0f);
glColor3ub(255, 255, 102);
glVertex2f(-2.0f,0.05f);
glVertex2f(-1.6f,0.05f);
glColor3ub(255, 255, 102);
glVertex2f(-2.0f,0.1f);
glVertex2f(-1.6f,0.1f);
glColor3ub(255, 255, 102);
glVertex2f(-1.95f,0.13f);
glVertex2f(-1.95f,-0.12f);
glColor3ub(255, 255, 102);
glVertex2f(-1.9f,0.13f);
glVertex2f(-1.9f,-0.12f);
glColor3ub(255, 255, 102);
glVertex2f(-1.85f,0.13f);
glVertex2f(-1.85f,-0.12f);
glColor3ub(255, 255, 102);
glVertex2f(-1.8f,0.13f);
glVertex2f(-1.8f,-0.12f);
glColor3ub(255, 255, 102);
glVertex2f(-1.75f,0.13f);
glVertex2f(-1.75f,-0.12f);
glColor3ub(255, 255, 102);
glVertex2f(-1.7f,0.13f);
glVertex2f(-1.7f,-0.12f);
glColor3ub(255, 255, 102);
glVertex2f(-1.65f,0.13f);
glVertex2f(-1.65f,-0.12f);
glEnd();
}
void Display(void)
{
//std::cout<<"Display 1 called"<<std::endl;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glPushMatrix();
glTranslatef(0,0,-20);
// glScalef(30.0,30.0,0.0);
glutPostRedisplay();
//glutSwapBuffers();
glPopMatrix();
glFlush();
glutSwapBuffers();
// glutPostRedisplay();
}
GLfloat xw=-40.0;
GLfloat yw,f1,f2,f3,f4,f5,f6;
void disp()
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
day();
glPopMatrix();
///ground///
glPushMatrix();
glTranslatef(0.0,-35.0,0.0);
glScalef(3.5,3.0,0.0);
glColor3f(0.0, 0.5, 0.0);
rect();
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,-5.0,0.0);
glScalef(80.0,40.0,0.0);
// glColor3f(0.0, 0.5, 0.0);
backgroundtree();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glScalef(40.0,40.0,0.0);
glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glTranslatef(cx,17.0,0.0);
glScalef(40.0,40.0,0.0);
// glTranslatef(cx,17.0,0.0);
bird();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
// glTranslatef(cx,20.0,0.0);
// cloudB();
glPopMatrix();
//tree1
glPushMatrix();
glColor3ub(248, 188, 203);
//glColor3f(0.133, 0.545, 0.133);
glTranslatef(-49.0,9.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.4,15.4,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); // ///
glPushMatrix();
moon();
glPopMatrix(); ///
glPushMatrix();
glTranslatef(cx,0.0,0.0);
glScalef(0.8,1.0,0.0);
cloud();
glPopMatrix(); //***/// / //home 2///
glPushMatrix();
glTranslatef(-65.0,-20.0,0.0);
house();
glPopMatrix(); //***/// / //home 1///
glPushMatrix();
glTranslatef(-45.0,-10.0,0.0);
home1();
glPopMatrix();
///home 2///
glPushMatrix();
glTranslatef(20.0,-15.0,0.0);
home1();
glPopMatrix();
//***/// / //tree typeA 1///
glPushMatrix();
glTranslatef(-5.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeB 1///
glPushMatrix();
glTranslatef(35.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeC 1///
glPushMatrix();
glTranslatef(30.0,-15.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***///
///tree2///
glPushMatrix();
glColor3ub(250, 182, 203);
// glColor3f(0.133, 0.545, 0.133);
glTranslatef(-44.0,-1.0,0.0);
glScalef(0.4,0.5,0.0); tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-35.0,5.0,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix();
//***/// / //********home 4********///
glPushMatrix();
glTranslatef(-10.0,-10.0,0.0);
home1();
glPopMatrix();
glPopMatrix();
//***/// / //********road********///
glPushMatrix();
glTranslatef(-10.0,15.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
//divider ///
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider1();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider2();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider3();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider4();
glPopMatrix();
//************/// / //BUS///
glPushMatrix();
glTranslatef(cx, -18.0, 0.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
//***/// ///BUS2///
glPushMatrix();
glTranslatef(cx, -8.0, -15.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
//***/// ///tree3///
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
//***/// ///tree3///
glPushMatrix();
glColor3ub(255, 182, 203);
//glColor3f(0.133, 0.545, 0.133);
glTranslatef(22.0,-32.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(30.5,-26.5,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); //***/// ///home 3///
glPushMatrix();
glTranslatef(-5.0,-70.0,0.0);
house();
glPopMatrix(); glPopMatrix();
//***/// ///tree typeD 1///
glPushMatrix();
glTranslatef(-10.0,-50.0,0.0);
glScalef(.5,1,0);
tree2();
glPopMatrix(); ///***///
//well
glPushMatrix();
glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
well();
glPopMatrix(); ///***///
glPushMatrix();
// glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
// bird();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-15.0,10.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-18.0,8.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-23.0,6.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-29.0,1.0,0.0);
glScalef(25.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(24.0,-2.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(45.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,-1.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-9.0,5.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(4.0,1.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(12.0,5.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix(); ///flower///
glPushMatrix();
glTranslatef(-33.5,20.1,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-36.5,20.1,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-39.0,20.3,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-44.5,20.3,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-41.5,13.0,0.0); //down
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-41.5,20.0,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-42.5,14.0,0.0);//down
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
//2ndtree
glPushMatrix();
glTranslatef(-39.0,9.9,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-36.0,9.9,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-32.0,9.9,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-29.0,9.9,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
//3rd tree
glPushMatrix();
glTranslatef(29.0,-22.0,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(32.0,-22.0,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(36.0,-22.0,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(xw,yw,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
//fallflowertree1
glPushMatrix();
glTranslatef(-36.0,yw,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-39.0,f1,0.0); //2tree
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-32.0,f2,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-29.0,f1,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-36.0,f3,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-29.0,-1.0,0.0);
glScalef(15.0,15.0,0.0);
flower();//downflower 2tree
glPopMatrix();
glPushMatrix();
glTranslatef(-27.0,-1.0,0.0);
glScalef(15.0,15.0,0.0);
flower();//downflower 2tree
glPopMatrix();
glPushMatrix();
glTranslatef(-38.0,-1.0,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-38.0,0.0,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-36.0,-9.5,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(38.0,-28.0,0.0);
glScalef(15.0,15.0,0.0);
flower();//downflower 3tree
glPopMatrix();
glPushMatrix();
glTranslatef(36.0,-28.0,0.0);
glScalef(15.0,15.0,0.0);
flower();//downflower 3tree
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,-28.0,0.0);
glScalef(15.0,15.0,0.0);
flower();//downflower tree
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,-26.0,0.0);
glScalef(15.0,15.0,0.0);
flower();//downflower 2tree
glPopMatrix();
glPushMatrix();
glTranslatef(29.0,f4,0.0);
glScalef(15.0,15.0,0.0);
flower();//falling3
glPopMatrix();
glPushMatrix();
glTranslatef(36.0,f5,0.0);
glScalef(15.0,15.0,0.0);
flower();
glPopMatrix();
glPushMatrix();
glTranslatef(-3.0,f6,0.0);
glScalef(15.0,15.0,0.0);
flower1();
glPopMatrix();
glPushMatrix();
glTranslatef(1.0,-40.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflowery 3tree
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,-42.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflower 3tree
glPopMatrix();
glPushMatrix();
glTranslatef(1.0,-42.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflower tree
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,-40.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflower 2tree
glPopMatrix();
glPushMatrix();
glTranslatef(-1.0,-32.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflower 3tree
glPopMatrix();
glPushMatrix();
glTranslatef(-4.0,-35.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflower 3tree
glPopMatrix();
glPushMatrix();
glTranslatef(-3.0,-28.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflower tree
glPopMatrix();
glPushMatrix();
glTranslatef(-6.0,-30.0,0.0);
glScalef(15.0,15.0,0.0);
flower1();//downflower 2tree
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-9.5,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix(); glPushMatrix();
glTranslatef(75.0,-9.5,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0,-0.0,0.0);
glScalef(2.0,3.0,0.0);
fence();
glPopMatrix();
glFlush();
}
void bird1(){
//bird1//
int i;
GLfloat mm=0.182f; GLfloat nn=.801f; GLfloat radiusmm =.01f;
int triangleAmount = 20;
GLfloat twicePi = 2.0f * PI;
glBegin(GL_TRIANGLE_FAN);
// glColor3ub(225, 225, 208);
glVertex2f(mm, nn); // center of circle
for(i = 0; i <= triangleAmount;i++) {
glVertex2f(
mm + (radiusmm * cos(i * twicePi / triangleAmount)),
nn + (radiusmm * sin(i * twicePi / triangleAmount))
);
}
glEnd();
glBegin(GL_POLYGON);
// glColor3f(0.0,0.0,0.0);
//glColor3ub(225, 225, 208 );
glVertex2f(0.1f,0.8f);
glVertex2f(0.11f,0.79f);
glVertex2f(0.12f,0.78f);
glVertex2f(0.16f,0.77f);
glVertex2f(0.19f,0.79f);
glVertex2f(0.201f,0.8f);
glEnd();
glBegin(GL_TRIANGLES);
// glColor3f(0.0,0.0,0.0);
//glColor3ub(217, 217, 217);
glVertex2f(0.175f,0.8f);
glVertex2f(0.15f,0.8f);
glVertex2f(0.14f,0.84f);
glEnd();
glBegin(GL_TRIANGLES);
// glColor3f(0.0,0.0,0.0);
// glColor3ub(242, 242, 242 );
glVertex2f(0.175f,0.8f);
glVertex2f(0.144f,0.8f);
glVertex2f(0.12f,0.83f);
glEnd();
}
void display1()
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
day();
glPopMatrix();
///ground///
glPushMatrix();
glTranslatef(0.0,-35.0,0.0);
glScalef(3.5,3.0,0.0);
glColor3f(0.0, 0.5, 0.0);
rect();
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,-5.0,0.0);
glScalef(80.0,40.0,0.0);
// glColor3f(0.0, 0.5, 0.0);
backgroundtree();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glScalef(40.0,40.0,0.0);
glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glTranslatef(cx,17.0,0.0);
glScalef(40.0,40.0,0.0);
bird();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
// glTranslatef(cx,20.0,0.0);
// cloudB();
glPopMatrix();
//tree1
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(-49.0,9.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.4,15.4,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); // ///
glPushMatrix();
moon();
glPopMatrix(); ///
glPushMatrix();
glTranslatef(cx,0.0,0.0);
glScalef(0.8,1.0,0.0);
cloud();
glPopMatrix(); //***/// / //home 2///
glPushMatrix();
glTranslatef(-65.0,-20.0,0.0);
house();
glPopMatrix(); //***/// / //home 1///
glPushMatrix();
glTranslatef(-45.0,-10.0,0.0);
home1();
glPopMatrix();
///home 2///
glPushMatrix();
glTranslatef(20.0,-15.0,0.0);
home1();
glPopMatrix();
//***/// / //tree typeA 1///
glPushMatrix();
glTranslatef(-5.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeB 1///
glPushMatrix();
glTranslatef(35.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeC 1///
glPushMatrix();
glTranslatef(30.0,-15.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***///
///tree2///
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(-44.0,-1.0,0.0);
glScalef(0.4,0.5,0.0); tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-35.0,5.0,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix();
//***/// / //********home 4********///
glPushMatrix();
glTranslatef(-10.0,-10.0,0.0);
home1();
glPopMatrix();
glPopMatrix();
//***/// / //********road********///
glPushMatrix();
glTranslatef(-10.0,15.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
//divider ///
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider1();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider2();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider3();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider4();
glPopMatrix();
//************/// / //BUS///
glPushMatrix();
glTranslatef(cx, -19.0, 0.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
//***/// ///BUS2///
glPushMatrix();
glTranslatef(cx, -8.0, -15.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
//***/// ///tree3///
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(22.0,-32.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(30.5,-26.5,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); //***/// ///home 3///
glPushMatrix();
glTranslatef(-5.0,-70.0,0.0);
house();
glPopMatrix(); glPopMatrix();
//***/// ///tree typeD 1///
glPushMatrix();
glTranslatef(-10.0,-50.0,0.0);
glScalef(.5,1,0);
tree2();
glPopMatrix(); ///***///
//well
glPushMatrix();
glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
well();
glPopMatrix(); ///***///
glPushMatrix();
// glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
// bird();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-15.0,10.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-18.0,8.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-23.0,6.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-29.0,1.0,0.0);
glScalef(25.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(24.0,-2.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(45.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,-1.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-9.0,5.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(4.0,1.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(12.0,5.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-9.5,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(-20.4,6.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-20.4,8.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-26.0,1.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-25.0,1.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
//right grass
glPushMatrix();
glTranslatef(28.5,-3.5,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(30.0,-4.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(10.0,-40.0,0.0);
glScalef(25.0,22.0,0.0);
bird1(); //wood
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,-33.5,0.0);
glColor3f(0.0,0.0,0.0);
glScalef(20.0,25.0,0.0);
bird1(); //btree
glPopMatrix();
glPushMatrix();
glTranslatef(-30.0,-0.5,0.0);
glScalef(20.0,20.0,0.0);
bird1();
glPopMatrix();
glPushMatrix();
glColor3f(1.0,1.0,0.9);
glTranslatef(-39.0,1.0,0.0);
glScalef(20.0,20.0,0.0);
bird1();
glPopMatrix();
glPushMatrix();
glTranslatef(-30.0,5.0,0.0);
glScalef(20.0,10.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.0,27.2,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-35.5,27.2,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-39.0,32.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-42.0,27.3,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0,0.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-35.5,22.2,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-30.0,22.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-28.0,17.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-30.5,17.2,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-38.0,17.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(-35.5,17.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(30.5,-15.3,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(38.0,-15.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(35.5,-15.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(35.0,-10.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(29.5,-12.0,0.0);
glScalef(20.0,35.0,0.0);
apple();
glPopMatrix();
glFlush();
}
void day2()
{
glBegin(GL_POLYGON);
// blue sky
// glColor3f(0.0,0.0,0.9);
// glColor3ub(211,211,217);
//glColor3ub(177,156,217);
glColor3ub(177,211,217); //snowfall
glVertex3f(-50,-3,0.0);
glVertex3f(-50,50,0.0);
glVertex3f(80.0,50.0,0.0);
glVertex3f(80.0,-3.0,0.0);
glEnd();
}
void bubbles()
{
glColor3f(1.0,1.0,1.0);
glutSolidSphere(0.5,8,10);
}
GLfloat q1,q2,q3,q4,q5;
void display2()
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
day2();
glPopMatrix();
///ground///
glPushMatrix();
glTranslatef(0.0,-35.0,0.0);
glScalef(3.5,3.0,0.0);
glColor3f(1.0, 1.0, 1.0);
rect();
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,-5.0,0.0);
glScalef(80.0,40.0,0.0);
// glColor3f(0.0, 0.5, 0.0);
backgroundtree();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(-20.0,44.0,0.0);
glScalef(0.9,0.8,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(10.5,44.0,0.0);
glScalef(0.9,0.8,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(45.0,44.0,0.0);
glScalef(0.9,0.8,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(cx,17.0,0.0);
glScalef(40.0,40.0,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(cx,20.0,0.0);
// cloudB();
glPopMatrix();
//tree1
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(-49.0,9.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.4,15.4,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); // ///
glPushMatrix();
// glTranslatef(cx,0.0,0.0);
glScalef(0.8,1.0,0.0);
cloud();
glPopMatrix(); //***/// / //home 2///
glPushMatrix();
glTranslatef(-65.0,-20.0,0.0);
house();
glPopMatrix(); //***/// / //home 1///
glPushMatrix();
glTranslatef(-45.0,-10.0,0.0);
home1();
glPopMatrix();
///home 2///
glPushMatrix();
glTranslatef(20.0,-15.0,0.0);
home1();
glPopMatrix();
//***/// / //tree typeA 1///
glPushMatrix();
glTranslatef(-5.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeB 1///
glPushMatrix();
glTranslatef(35.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeC 1///
glPushMatrix();
glTranslatef(30.0,-15.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***///
///tree2///
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(-44.0,-1.0,0.0);
glScalef(0.4,0.5,0.0); tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-35.0,5.0,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix();
//***/// / //********home 4********///
glPushMatrix();
glTranslatef(-10.0,-10.0,0.0);
home1();
glPopMatrix();
glPopMatrix();
//***/// / //********road********///
glPushMatrix();
glTranslatef(-10.0,15.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
//divider ///
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider1();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider2();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider3();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider4();
glPopMatrix();
//************/// / //BUS///
glPushMatrix();
glTranslatef(cx, -19.0, 0.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
//***/// ///BUS2///
glPushMatrix();
glTranslatef(cx, -8.0, -15.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
//***/// ///tree3///
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(22.0,-32.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(30.5,-26.5,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); //***/// ///home 3///
glPushMatrix();
glTranslatef(-5.0,-70.0,0.0);
house();
glPopMatrix(); glPopMatrix();
//***/// ///tree typeD 1///
glPushMatrix();
glTranslatef(-10.0,-50.0,0.0);
glScalef(.5,1,0);
tree2();
glPopMatrix(); ///***///
//well
glPushMatrix();
glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
well();
glPopMatrix(); ///***///
glPushMatrix();
// glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
// bird();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-15.0,10.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-18.0,8.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-23.0,6.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-29.0,1.0,0.0);
glScalef(25.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(24.0,-2.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(45.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,-1.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-9.0,5.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(4.0,1.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(12.0,5.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-9.5,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(-20.4,6.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-20.4,8.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-26.0,1.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-25.0,1.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
//right grass
glPushMatrix();
glTranslatef(28.5,-3.5,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(30.0,-4.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(10.0,-40.0,0.0);
glScalef(25.0,22.0,0.0);
bird1(); //wood
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,-33.5,0.0);
glColor3f(0.0,0.0,0.0);
glScalef(20.0,25.0,0.0);
bird1(); //btree
glPopMatrix();
glPushMatrix();
glTranslatef(-30.0,-0.5,0.0);
glScalef(20.0,20.0,0.0);
bird1();
glPopMatrix();
glPushMatrix();
glColor3f(1.0,1.0,0.9);
glTranslatef(-39.0,1.0,0.0);
glScalef(20.0,20.0,0.0);
bird1();
glPopMatrix();
glPushMatrix();
glTranslatef(-30.0,5.0,0.0);
glScalef(20.0,10.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0,0.0,0.0);
glScalef(20.0,20.0,0.0);
apple();
glPopMatrix();
// 1 cloud
glPushMatrix();
glTranslatef(-25.0,q1,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-23.0,q5,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-28.0,q2,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-31.0,q3,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-33.0,q4,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-36.0,q1,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-39.0,q2,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-41.0,q3,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-15.0,q5,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-20.0,q4,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-39.0,21.0,0.0);
glScalef(1.0,1.0,0.0);
cloud();
glPopMatrix();
//2 cloud
glPushMatrix();
glTranslatef(-5.0,q1,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glPushMatrix();
glTranslatef(-0.5,q4,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,q2,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(1.0,q3,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(3.0,q1,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(6.0,q1,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(9.0,q2,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(12.0,q3,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(14.0,q5,0.0);
bubbles();
glPopMatrix();
//3 cloud
glPushMatrix();
glTranslatef(20.0,q4,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(22.0,q2,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(25.0,q3,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(28.0,q1,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,q2,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(33.0,q3,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(36.0,q1,0.0);
bubbles();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(38.0,q2,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(40.0,q3,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(45.0,q5,0.0);
bubbles();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(35.0,-26.5,0.0);
glScalef(0.5,0.3,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glTranslatef(-0.5,5.5,0.0);
glScalef(0.5,0.3,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glTranslatef(-37.0,19.5,0.0);
glScalef(0.5,0.3,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glTranslatef(-26.0,2.5,0.0);
glScalef(0.3,0.2,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glTranslatef(-1.5,21.3,0.0);
glScalef(0.25,0.55,0.0);
triangle1();
glPopMatrix();
glPushMatrix();
glTranslatef(-8.0,-30.0,0.0);
glScalef(0.1,0.1,0.0);
triangle1();
glPopMatrix();
glPushMatrix();
glTranslatef(10.0,22.0,0.0);
glScalef(4.0,4.7,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glTranslatef(10.0,16.0,0.0);
glScalef(5.0,10.0,0.0);
bubbles();
glPopMatrix();
glPushMatrix();
glColor3f(0.0,0.0,0.0);
glTranslatef(10.0,22.0,0.0);
//glScalef(0.8,0.8,0.0);
glutSolidSphere(0.5,8,11);
glPopMatrix();
glPushMatrix();
glColor3f(0.0,0.0,0.0);
glTranslatef(8.3,22.0,0.0);
//glScalef(1.0,1.0,0.0);
glutSolidSphere(0.5,8,11);
glPopMatrix();
glPushMatrix();
glTranslatef(15.0,30.0,0.0);
glScalef(100.0,30.0,0.0);
apple();
glPopMatrix();
glPushMatrix();
glTranslatef(8.3,21.0,0.0);
glScalef(0.09,0.09,0.0);
triangle();
glPopMatrix();
glFlush();
}
void rain(){
// Draw particles
glColor3f(0.5, 0.5, 1.0);
glBegin(GL_LINES);
glVertex2f(10.0,10.8);
glVertex2f(10.0,12.8);
glEnd();
}
void display3()
{
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
day2();
glPopMatrix();
///ground///
glPushMatrix();
glTranslatef(0.0,-35.0,0.0);
glScalef(3.5,3.0,0.0);
rect();
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,-5.0,0.0);
glScalef(80.0,40.0,0.0);
// glColor3f(0.0, 0.5, 0.0);
backgroundtree();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(-20.0,44.0,0.0);
glScalef(0.9,0.8,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(10.5,44.0,0.0);
glScalef(0.9,0.8,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(45.0,44.0,0.0);
glScalef(0.9,0.8,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(cx,17.0,0.0);
glScalef(40.0,40.0,0.0);
// glTranslatef(cx,17.0,0.0);
cloudB();
glPopMatrix();
glPushMatrix();
glColor3f (1.0,1.0,1.0);
glTranslatef(cx,20.0,0.0);
// cloudB();
glPopMatrix();
//tree1
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(-49.0,9.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.4,15.4,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); // ///
glPushMatrix();
// glTranslatef(cx,0.0,0.0);
glScalef(0.8,1.0,0.0);
cloud();
glPopMatrix(); //***/// / //home 2///
glPushMatrix();
glTranslatef(-65.0,-20.0,0.0);
house();
glPopMatrix(); //***/// / //home 1///
glPushMatrix();
glTranslatef(-45.0,-10.0,0.0);
home1();
glPopMatrix();
///home 2///
glPushMatrix();
glTranslatef(20.0,-15.0,0.0);
home1();
glPopMatrix();
//***/// / //tree typeA 1///
glPushMatrix();
glTranslatef(-5.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeB 1///
glPushMatrix();
glTranslatef(35.0,-5.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***/// / //tree typeC 1///
glPushMatrix();
glTranslatef(30.0,-15.0,0.0);
glScalef(0.5,1.0,0.0);
tree2();
glPopMatrix();
//***///
///tree2///
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(-44.0,-1.0,0.0);
glScalef(0.4,0.5,0.0); tree();
glPopMatrix();
glPushMatrix();
glTranslatef(-35.0,5.0,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix();
//***/// / //********home 4********///
glPushMatrix();
glTranslatef(-10.0,-10.0,0.0);
home1();
glPopMatrix();
glPopMatrix();
//***/// / //********road********///
glPushMatrix();
glTranslatef(-10.0,15.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
ground();
glPopMatrix();
glPopMatrix();
//divider ///
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider1();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider2();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider3();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,20.0,0.0);
divider4();
glPopMatrix();
//************/// / //BUS///
glPushMatrix();
glTranslatef(cx, -19.0, 0.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
//***/// ///BUS2///
glPushMatrix();
glTranslatef(cx, -8.0, -15.0);
glScalef(30.0, 8.0, 0.0);
bus();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
//***/// ///tree3///
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glColor3f(0.133, 0.545, 0.133);
glTranslatef(22.0,-32.5,0.0);
glScalef(0.4,0.5,0.0);
tree();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(30.5,-26.5,0.0);
glScalef(0.4,0.5,0.0);
treebody();
glPopMatrix(); //***/// ///home 3///
glPushMatrix();
glTranslatef(-5.0,-70.0,0.0);
house();
glPopMatrix(); glPopMatrix();
//***/// ///tree typeD 1///
glPushMatrix();
glTranslatef(-10.0,-50.0,0.0);
glScalef(.5,1,0);
tree2();
glPopMatrix(); ///***///
//well
glPushMatrix();
glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
well();
glPopMatrix(); ///***///
glPushMatrix();
// glTranslatef(-12.0,-20.0,0.0);
glScalef(40.0,40.0,0.0);
// bird();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-15.0,10.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-18.0,8.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-23.0,6.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-29.0,1.0,0.0);
glScalef(25.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-40.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(24.0,-2.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(45.0,3.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(20.0,-1.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(-9.0,5.0,0.0);
glScalef(20.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(4.0,1.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(12.0,5.0,0.0);
glScalef(15.0,15.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-9.5,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(100.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(125.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(160.0,-10.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(75.0,-25.0,0.0);
glScalef(65.0,15.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(-20.4,6.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-20.4,8.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-26.0,1.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(-25.0,1.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
//right grass
glPushMatrix();
glTranslatef(28.5,-3.5,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix(); ///***///
glPushMatrix();
glTranslatef(30.0,-4.0,0.0);
glScalef(12.0,12.0,0.0);
grass1();
glPopMatrix();
glPushMatrix();
glTranslatef(10.0,-40.0,0.0);
glScalef(25.0,22.0,0.0);
bird1(); //wood
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,-33.5,0.0);
glColor3f(0.0,0.0,0.0);
glScalef(20.0,25.0,0.0);
bird1(); //btree
glPopMatrix();
glPushMatrix();
glTranslatef(-30.0,-0.5,0.0);
glScalef(20.0,20.0,0.0);
bird1();
glPopMatrix();
glPushMatrix();
glColor3f(1.0,1.0,0.9);
glTranslatef(-39.0,1.0,0.0);
glScalef(20.0,20.0,0.0);
bird1();
glPopMatrix();
glPushMatrix();
glTranslatef(-30.0,5.0,0.0);
glScalef(20.0,10.0,0.0);
fence();
glPopMatrix();
glPushMatrix();
glTranslatef(0.0,0.0,0.0);
glScalef(20.0,20.0,0.0);
apple();
glPopMatrix();
// 1 cloud
glPushMatrix();
glTranslatef(-25.0,q1,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-23.0,q5,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-28.0,q2,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-31.0,q3,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-33.0,q4,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-36.0,q1,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-39.0,q2,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-41.0,q3,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-15.0,q5,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-20.0,q4,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-39.0,21.0,0.0);
glScalef(1.0,1.0,0.0);
cloud();
glPopMatrix();
//2 cloud
glPushMatrix();
glTranslatef(-5.0,q1,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glPushMatrix();
glTranslatef(-0.5,q4,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0,q2,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(1.0,q3,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(3.0,q1,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(6.0,q1,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(9.0,q2,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(12.0,q3,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(14.0,q5,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
//3 cloud
glPushMatrix();
glTranslatef(20.0,q4,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(22.0,q2,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(25.0,q3,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(28.0,q1,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(30.0,q2,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(33.0,q3,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(36.0,q1,0.0);
rain();
glPopMatrix();
glPopMatrix();
glPushMatrix();
glTranslatef(38.0,q2,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(40.0,q3,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(45.0,q5,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glPushMatrix();
glTranslatef(-26.0,2.5,0.0);
glScalef(-0.01,1.9,0.0);
rain();
glPopMatrix();
glFlush();
}
void init(void)
{
glClearColor (0.0, 0.749, 1.0, 0.0);
glOrtho(-50.0,50.0, -50.0, 50.0, -1.0, 1.0);
}
void spinDisplay() {
cx = cx +0.07;
if(cx>70) {
cx = -70;
}
yw=yw-0.03;
if(yw<13.0){
yw=22.0;
}
f1-=0.05;
if(f1<-1.0)
{
f1=9.9;
}
f2-=0.08;
if(f2<-1.0){
f2=9.9;
}
f3-=0.08;
if(f3<-1.0)
{
f3=9.9;
}
f4-=0.05;
if(f4<-28.0)
{
f4=-22.2;
}
f5-=0.08;
if(f5<-28.0)
{
f5=-22.2;
}
f6-=0.08;
if(f6<-40.0)
{
f6=-35.0;
}
q1-=0.1;
if(q1<0.9)
{
q1=32.4;//y
}
q2-=0.09;
if(q2<-25.0)
{
// p2=0.0;
q2=32.4;
}
q3-=0.25;
if(q3<-28.0)
{
// p3=0.0;
q3=32.4;
}
q4-=0.3;
if(q4<-30.0)
{
// p3=0.0;
q4=32.4;
}
q5-=0.09;
if(q5<13.0)
{
// p3=0.0;
q5=40.5;
}
glutPostRedisplay();
}
void mouse(int key, int state, int x, int y) {
switch(key) {
case GLUT_LEFT_BUTTON: if (state == GLUT_DOWN) {
glutIdleFunc(spinDisplay);
}
break;
case GLUT_MIDDLE_BUTTON: case GLUT_RIGHT_BUTTON: if (state == GLUT_DOWN) {
glutIdleFunc(NULL); }
break;
default: break; } }
void keyDisplayAnimationDay() {
str=500.0;
sr=0.0;
sg=0.749;
sb=1.0;
ss=0.0;
mn=500.0;
// glPushMatrix();
//disp();
//glPopMatrix();
glutPostRedisplay();
}
void keyDisplayAnimationNight() {
str = 0.0; sr=0.0;
sg=0.0; sb=0.0; ss=500.0;
mn = 0.0;
glutPostRedisplay();
}
/*void keyboard(unsigned char key, int x, int y) {
switch(key) {
case 'd': keyDisplayAnimationDay();
break;
case 'n': night();
// glutPostRedisplay();
keyDisplayAnimationNight();
break;
default: break;
} }*/
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case 's':
// glutDestroyWindow(1);
glutInitWindowSize (1350, 690);
glutInitWindowPosition (0, 0);
glutCreateWindow("village scenario");
init();
glutKeyboardFunc(handleKeypress);
glutMouseFunc(mouse);
glutDisplayFunc(display1);
glutPostRedisplay();
break;
case 'w':
glutDestroyWindow(1);
glutInitWindowSize (1350, 690);
glutInitWindowPosition (0, 0);
glutCreateWindow("village scenario");
init();
glutKeyboardFunc(handleKeypress);
glutMouseFunc(mouse);
glutDisplayFunc(display2);
glutPostRedisplay();
break;
case 'p':
glutDestroyWindow(1);
glutInitWindowSize (1350, 690);
glutInitWindowPosition (0, 0);
glutCreateWindow("village scenario");
init();
glutKeyboardFunc(handleKeypress);
glutMouseFunc(mouse);
glutDisplayFunc(disp);
glutPostRedisplay();
break;
case 'r':
glutDestroyWindow(1);
glutInitWindowSize (1350, 690);
glutInitWindowPosition (0, 0);
glutCreateWindow("village scenario");
init();
glutKeyboardFunc(handleKeypress);
glutMouseFunc(mouse);
glutDisplayFunc(display3);
glutPostRedisplay();
break;
glutPostRedisplay();
}
}
int main( int argc,char ** argv)
{
printf(">><< Press s for summer season>><< Press w for winter season >><< Press r for rainy season>><< Press p for spring season>><<\n\n");
printf("Click Mouse Left/Right Button for cloud movement\n\n");
glutInit(&argc,argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (1350, 690);
glutInitWindowPosition (0, 0);
glutCreateWindow("My House ");
init();
// glutDisplayFunc(StartingText);
glutDisplayFunc(disp);
glutMouseFunc(mouse);
glutKeyboardFunc(handleKeypress);
glutMainLoop();
return 0;
}
| true |
62d2c3c538da094305a8d8048732811fa06d95aa | C++ | DeftHaHa/ACM | /cjluoj/2853.cpp | UTF-8 | 440 | 3.28125 | 3 | [] | no_license | #include<cstdio>
#include<iostream>
using namespace std;
void hmove(int n,char a,char b,char c)
{
if(n==1) printf("%c-->%c\n",a,c);
else
{
hmove(n-1,a,c,b);
printf("%c-->%c\n",a,c);
hmove(n-1,b,a,c);
}
}
int main()
{
int n;
while(cin>>n)
{
hmove(n,'A','B','C');
cout<<endl;
}
return 0;
}
| true |
de87787cf2489b9e0352b8d8bffd08c608fe681e | C++ | paintdream/PaintsNow | /Source/Utility/MythForest/Component/Field/Types/FieldSimplygon.cpp | UTF-8 | 3,735 | 2.59375 | 3 | [
"MIT"
] | permissive | #include "FieldSimplygon.h"
using namespace PaintsNow;
FieldSimplygon::FieldSimplygon(SIMPOLYGON_TYPE t, const Float3Pair& b) : type(t), box(b) {
}
TObject<IReflect>& FieldSimplygon::operator () (IReflect& reflect) {
BaseClass::operator () (reflect);
if (reflect.IsReflectProperty()) {
ReflectProperty(type);
}
return *this;
}
Bytes FieldSimplygon::operator [] (const Float3& position) const {
bool result = false;
switch (type) {
case BOUNDING_BOX:
result = Math::Contain(box, position);
break;
case BOUNDING_SPHERE:
{
Float3 local = Math::ToLocal(box, position);
result = Math::SquareLength(local) <= 1.0f;
}
break;
case BOUNDING_CYLINDER:
{
Float3 local = Math::ToLocal(box, position);
if (local.z() < -1.0f || local.z() > 1.0f) {
result = false;
} else {
result = Math::SquareLength(Float2(local.x(), local.y())) <= 1.0f;
}
}
break;
}
Bytes encoder;
encoder.Assign((const uint8_t*)&result, sizeof(bool));
return result;
}
template <int type, class Q>
class BoxQueryer {
public:
BoxQueryer(Q& q, const Float3Pair& b) : queryer(q), box(b) {}
Q& queryer;
const Float3Pair& box;
bool operator () (TKdTree<Float3Pair, Unit>& tree) const {
if (type == FieldSimplygon::BOUNDING_BOX) {
queryer(static_cast<Entity&>(tree));
} else if (type == FieldSimplygon::BOUNDING_SPHERE) {
Float3 from = Math::ToLocal(box, tree.GetKey().first);
Float3 to = Math::ToLocal(box, tree.GetKey().second);
float dx = Math::Max(0.0f, Math::Max(from.x(), -to.x()));
float dy = Math::Max(0.0f, Math::Max(from.y(), -to.y()));
float dz = Math::Max(0.0f, Math::Max(from.z(), -to.z()));
if (dx * dx + dy * dy + dz * dz <= 1.0f) {
queryer(static_cast<Entity&>(tree));
}
} else if (type == FieldSimplygon::BOUNDING_CYLINDER) {
Float3 from = Math::ToLocal(box, tree.GetKey().first);
Float3 to = Math::ToLocal(box, tree.GetKey().second);
float dx = Math::Max(0.0f, Math::Max(from.x(), -to.x()));
float dy = Math::Max(0.0f, Math::Max(from.y(), -to.y()));
if (dx * dx + dy * dy <= 1.0f) {
queryer(static_cast<Entity&>(tree));
}
}
return true; // search all
}
};
class Poster {
public:
Poster(Event& e, Tiny::FLAG m) : event(e), mask(m) {}
Event& event;
Tiny::FLAG mask;
void operator () (Entity& entity) {
entity.PostEvent(event, mask);
}
};
void FieldSimplygon::PostEventForEntityTree(Entity* entity, Event& event, FLAG mask) const {
Poster poster(event, mask);
switch (type) {
case BOUNDING_BOX:
{
BoxQueryer<BOUNDING_BOX, Poster> q(poster, box);
entity->Query(std::true_type(), box, q);
break;
}
case BOUNDING_SPHERE:
{
BoxQueryer<BOUNDING_SPHERE, Poster> q(poster, box);
entity->Query(std::true_type(), box, q);
break;
}
case BOUNDING_CYLINDER:
{
BoxQueryer<BOUNDING_CYLINDER, Poster> q(poster, box);
entity->Query(std::true_type(), box, q);
break;
}
}
}
class Collector {
public:
Collector(std::vector<TShared<Entity> >& e) : entities(e) {}
std::vector<TShared<Entity> >& entities;
void operator () (Entity& entity) {
entities.push_back(&entity);
}
};
void FieldSimplygon::QueryEntitiesForEntityTree(Entity* entity, std::vector<TShared<Entity> >& entities) const {
Collector collector(entities);
switch (type) {
case BOUNDING_BOX:
{
BoxQueryer<BOUNDING_BOX, Collector> q(collector, box);
entity->Query(std::true_type(), box, q);
break;
}
case BOUNDING_SPHERE:
{
BoxQueryer<BOUNDING_SPHERE, Collector> q(collector, box);
entity->Query(std::true_type(), box, q);
break;
}
case BOUNDING_CYLINDER:
{
BoxQueryer<BOUNDING_CYLINDER, Collector> q(collector, box);
entity->Query(std::true_type(), box, q);
break;
}
}
}
| true |
384e58b6fd34e014cbedb420cc7ac1535230cd90 | C++ | Hengle/NarvalEngine | /src/primitives/InstancedModel.h | UTF-8 | 686 | 2.546875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "primitives/Model.h"
#include "primitives/Ray.h"
#include "primitives/Primitive.h"
#include "utils/StringID.h"
namespace narvalengine {
class InstancedModel {
public:
StringID modelID = NE_INVALID_STRING_ID;
bool isCollisionEnabled = true;
Model *model;
glm::mat4 transformToWCS;
glm::mat4 invTransformToWCS;
InstancedModel();
InstancedModel(Model* model, StringID modelID, glm::mat4 transformToWCS);
InstancedModel(Model* model, glm::mat4 transformToWCS);
/*
Receives a ray in WCS, converts it to OCS and tests intersection with this model's primitives
*/
bool intersect(Ray ray, RayIntersection& hit, float& tMin, float& tMax);
};
} | true |
3838d596e2c33e07590449e860db0d4f96a78143 | C++ | kjh107704/Algorithm | /BOJ/13460.cpp | UTF-8 | 6,910 | 3.3125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <map>
using namespace std;
int N, M;
int min_move = 11;
struct position
{
int x, y;
position(int _x, int _y) : x(_x), y(_y) {}
};
struct marble
{
position red;
position blue;
marble(int x1, int y1, int x2, int y2) : red(position(x1, y1)), blue(position(x2, y2)) {}
void setRed(int x, int y)
{
red = position(x, y);
}
void setBlue(int x, int y)
{
blue = position(x, y);
}
};
struct cmp
{
bool operator()(const marble a, const marble b) const
{
return a.red.x > a.red.y;
}
};
// 파란색 먼저: -1, 상관없음: 0, 빨간색 먼저: 1
int setMoveSequence(marble m, char direction)
{
// 파란색이나 빨간색을 먼저 움직여야 할 경우를 걸러냄
switch (direction)
{
case 'l':
if (m.red.x == m.blue.x)
{
if (m.blue.y < m.red.y)
return -1;
else
return 1;
}
break;
case 'r':
if (m.red.x == m.blue.x)
{
if (m.blue.y > m.red.y)
return -1;
else
return 1;
}
break;
case 'u':
if (m.red.y == m.blue.y)
{
if (m.blue.x < m.red.x)
return -1;
else
return 1;
}
break;
case 'd':
if (m.red.y == m.blue.y)
{
if (m.blue.x > m.red.x)
return -1;
else
return 1;
}
break;
}
return 0;
}
pair<int, marble> getNewPosition(vector<string> &board, marble m, char direction, int sequence)
{
// state = 0: 계속 진행, state = 1: 성공, state = -1: 실패
int state = 0;
int tmp = 0;
int x = 0, y = 0;
if (sequence == -1) // 파란색을 먼저 움직여야 하는 경우
{
x = m.blue.x;
y = m.blue.y;
}
else
{
x = m.red.x;
y = m.red.y;
}
if (direction == 'l' || direction == 'r')
{
if (direction == 'l')
tmp = -1;
else
tmp = 1;
for (int i = 0; i < 2; i++)
{
if (i == 1)
{
if (sequence == -1)
{
m.setBlue(x, y);
x = m.red.x;
y = m.red.y;
}
else
{
m.setRed(x, y);
x = m.blue.x;
y = m.blue.y;
}
}
for (; 0 <= y && 0 < M; y += tmp)
{
if (y + tmp < 0 || y + tmp >= M || board[x][y + tmp] == '#')
break;
if(i == 1 && sequence == -1 && y+tmp == m.blue.y)
break;
else if(i == 1 && sequence == 1 && y+tmp == m.red.y)
break;
else if (board[x][y + tmp] == 'O')
{
if ((sequence == -1 && i == 0) || (sequence == 1 && i == 1) || (sequence == 0 && i == 1))
{
state = -1;
y = 0;
break;
}
else if(state != -1)
{
state = 1;
y = 0;
break;
}
}
}
}
}
else if (direction == 'u' || direction == 'd')
{
if (direction == 'u')
tmp = -1;
else
tmp = 1;
for (int i = 0; i < 2; i++)
{
if (i == 1)
{
if (sequence == -1)
{
m.setBlue(x, y);
x = m.red.x;
y = m.red.y;
}
else
{
m.setRed(x, y);
x = m.blue.x;
y = m.blue.y;
}
}
for (; 0 <= x && 0 < N; x += tmp)
{
if (x + tmp < 0 || x + tmp >= N || board[x + tmp][y] == '#')
break;
if(i == 1 && sequence == -1 && x+tmp == m.blue.x)
break;
else if(i == 1 && sequence == 1 && x+tmp == m.red.x)
break;
else if (board[x + tmp][y] == 'O')
{
if ((sequence == -1 && i == 0) || (sequence == 1 && i == 1) || (sequence == 0 && i == 1))
{
state = -1;
x = 0;
break;
}
else if(state != -1)
{
state = 1;
x = 0;
break;
}
}
}
}
}
if(sequence == -1)
m.setRed(x,y);
else
m.setBlue(x,y);
return make_pair(state, m);
}
string getKey(marble m) {
string output = "";
output += to_string(m.red.x)+to_string(m.red.y)+to_string(m.blue.x)+to_string(m.blue.y);
return output;
}
void move(vector<string> &board, marble m, map<string, int> &history, int cnt)
{
string key = getKey(m);
if (cnt > 10 || (history.find(key) != history.end() && history[key] < cnt))
{
return;
}
history.insert(make_pair(key, cnt));
char dir[] = {'l', 'r', 'u', 'd'};
for (int i = 0; i < 4; i++)
{
pair<int, marble> result = getNewPosition(board, m, dir[i], setMoveSequence(m, dir[i]));
if (result.first == -1)
continue;
else if (result.first == 1)
{
if (min_move > cnt)
min_move = cnt;
continue;
}
else
{
move(board, result.second, history, cnt + 1);
}
}
return;
}
int solution(vector<string> &board)
{
int ans = -1;
map<string, int> history;
marble m(0, 0, 0, 0);
// 보드 재활용이 가능하도록 구슬의 위치를 기록한 뒤 .으로 바꿔 줌
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++)
{
if (board[i][j] == 'B')
{
m.setBlue(i, j);
board[i][j] = '.';
}
else if (board[i][j] == 'R')
{
m.setRed(i, j);
board[i][j] = '.';
}
}
move(board, m, history, 1);
if (min_move != 11)
ans = min_move;
return ans;
}
int main()
{
scanf("%d %d", &N, &M);
vector<string> board;
string input;
for (int i = 0; i < N; i++)
{
cin >> input;
board.push_back(input);
}
printf("%d", solution(board));
} | true |
d8b137b693aa27ec13a50bfcff3ce30afbb5ab47 | C++ | closedsum/core | /CsPlugin/Source/CsCore/Public/Containers/CsWeakObjectPtr.h | UTF-8 | 1,192 | 2.671875 | 3 | [
"MIT"
] | permissive | // Copyright 2017-2023 Closed Sum Games, LLC. All Rights Reserved.
// MIT License: https://opensource.org/license/mit/
// Free for use and distribution: https://github.com/closedsum/core
#pragma once
class UObject;
template<typename ObjectType>
struct TCsWeakObjectPtr
{
static_assert(std::is_base_of<UObject, ObjectType>(), "TCsWeakObjectPtr: ObjectType does not extend from UObject.");
private:
ObjectType* Object;
TWeakObjectPtr<ObjectType> WeakObject;
public:
TCsWeakObjectPtr() :
Object(nullptr),
WeakObject(nullptr)
{
}
FORCEINLINE TCsWeakObjectPtr<ObjectType>& operator=(ObjectType* InObject)
{
Object = InObject;
WeakObject = InObject;
return *this;
}
FORCEINLINE void Set(ObjectType* InObject)
{
Object = InObject;
WeakObject = InObject;
}
FORCEINLINE ObjectType* Get() const
{
return Object;
}
template<typename T>
FORCEINLINE T* Get() const
{
return Cast<T>(Get());
}
FORCEINLINE ObjectType* GetSafe() const
{
return WeakObject.IsValid() ? WeakObject.Get() : nullptr;
}
template<typename T>
FORCEINLINE T* GetSafe() const
{
return Cast<T>(GetSafe());
}
void Reset()
{
Object = nullptr;
WeakObject = nullptr;
}
}; | true |
74e596812b28f3b35845b3dd3f8832342104ad92 | C++ | vishalsahu5/spoj | /ARMY.cpp | UTF-8 | 649 | 2.5625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
freopen("input.txt", "r", stdin);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int t;
cin >> t;
while(t--){
int G,M;
cin >> G >> M;
priority_queue<int> A,B;
for(int i=0; i<G; i++){
int x;
cin >> x;
A.push(x);
}
for(int i=0; i<M; i++){
int x;
cin >> x;
B.push(x);
}
while(true){
int x,y;
x = A.top(); y = B.top();
if(x < y){
A.pop();
}else{
B.pop();
}
if(A.empty()){
cout << "MechaGodzilla" <<endl;
break;
}else if(B.empty()){
cout << "Godzilla" << endl;
break;
}
}
}
return 0;
} | true |
781bc6993a8bb649a6b95ef5f45ff6f8c92cfa3e | C++ | volcoma/netpp | /netpp/netpp/error_code.cpp | UTF-8 | 831 | 2.890625 | 3 | [
"BSD-2-Clause"
] | permissive | #include "error_code.h"
namespace net
{
namespace
{
const net_err_category net_category{};
}
const char* net::net_err_category::name() const noexcept
{
return "network";
}
std::string net::net_err_category::message(int ev) const
{
switch(static_cast<errc>(ev))
{
case errc::data_corruption:
return "Data corruption or unknown data format.";
case errc::user_triggered_disconnect:
return "User triggered disconnect.";
case errc::host_unreachable:
return "Host is unreachable.";
default:
return "(Unrecognized error)";
}
}
std::error_code make_error_code(errc e)
{
return {static_cast<int>(e), net_category};
}
bool is_data_corruption_error(const error_code& ec)
{
return ec == make_error_code(errc::data_corruption);
}
}
| true |
963e8c83be23827483bac3415c991206f628b0bd | C++ | ajmalsiddiqui/mouse-cli | /src/cli_ncurses.cpp | UTF-8 | 1,995 | 2.828125 | 3 | [] | no_license | #include <iostream>
#include <stack>
#include <string>
#include <string.h>
#include <ncurses.h>
#include <term.h>
//include the OS specific interrupt handler
//_WIN32 is defined for both windows 64 bit and 32 bit
#if defined(_WIN32)
// TODO: write the handlers for windows
//if not windows, then assume unix
#else
//#include "interruptHandlers/keyboard/unix/getKeyPress.h"
#endif
#include "split_delim.h"
#include "man.h"
using namespace std;
stack <string> commandStack;
stack <string> bufferStack;
string prompt = "->";
int row, col, x =0, y=0;
int continueFlag = 1;
void newLine(){
getyx(stdscr, y, x);
mvcur(x, y, 0, y+1);
move(y+1,0);
refresh();
}
void getCommand(char ** command){
int ch, i=0;
char temp[10];
while((ch = getch()) != 10){
temp[i] = (char)ch;
putchar(ch);
refresh();
i++;
}
temp[i] = '\0';
//printw(temp);
//refresh();
*command = &temp[0];
//strcpy(command, temp);
//printw(*command);
//refresh();
newLine();
return;
}
void cli() {
//initialize curses
initscr();
//raw();
cbreak();
noecho();
keypad(stdscr, TRUE);
getmaxyx(stdscr,row,col);
//initialize cli
printw("Welcome to the demonstration CLI.\nCurrently the following arithmetic commands are supported:\n1. add\n2. sub\n3. mul\n4. div\nUse man <command> to learn more about a specific command.\n\'exit\' for exiting the CLI.\n\n");
refresh();
/*while(continueFlag) {
}*/
char ** command;
command = (char **) malloc(10 * sizeof *command);
getCommand(command);
// get command
/*int ch, i=0;
char temp[10];
while((ch = getch()) != 10){
temp[i] = (char)ch;
putchar(ch);
refresh();
i++;
}
temp[i] = '\0';*/
//printw(temp);
//refresh();
//command = temp;
printw((char *)command);
refresh();
getch();
endwin();
}
int main() {
cli();
return 0;
} | true |
cb5edf2fc25dc5097b00460d13e3052c10a51fea | C++ | syalanurag1991/ImageProcessing | /C++/src/FeatureReduction.cpp | UTF-8 | 1,144 | 2.515625 | 3 | [] | no_license | #include "FeatureReduction.h"
#include "pca.h"
#define NUM_REDUCED_FEATURES 3
vector<vector<float>> ReduceFeaturesUsingPCA(vector<vector<float>> &feature_set)
{
stats::pca pca(feature_set.front().size());
vector<double> v3(feature_set.front().size(), 0);
vector<vector<double>> double_feature_set(feature_set.size(), v3);
for(int i = 0; i < feature_set.size(); ++i) {
for(int j = 0; j < feature_set.front().size(); ++j) {
double_feature_set[i][j] = (double) feature_set[i][j];
}
}
for(int i = 0; i < double_feature_set.size(); ++i) {
pca.add_record(double_feature_set[i]);
}
pca.solve();
vector<float> v1 (NUM_REDUCED_FEATURES, 0);
vector<vector<float>> princ_comp(double_feature_set.size(), v1);
vector<double> v2 (double_feature_set.size(), 0);
vector<vector<double>> transpose_princ_comp(NUM_REDUCED_FEATURES, v2);
for(int i = 0; i < NUM_REDUCED_FEATURES; ++i) {
transpose_princ_comp[i] = pca.get_principal(i);
}
for(int i = 0; i < double_feature_set.size(); ++i) {
for(int j = 0; j < NUM_REDUCED_FEATURES; ++j) {
princ_comp[i][j] = (float)transpose_princ_comp[j][i];
}
}
return princ_comp;
} | true |
048de15161b8327aad99aa87d0169e3b9712185a | C++ | omjee17/DS_Algo_Questions | /Backtracking/print_all_permutations_of_a_string.cpp | UTF-8 | 791 | 2.984375 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<string>ans;
void helper(string s,int l,int r)
{
if(l==r)
{
ans.push_back(s);
return;
}
for(int i=l;i<=r;i++)
{
swap(s[l],s[i]);
helper(s,l+1,r);
swap(s[l],s[i]);
}
}
vector<string>find_permutation(string S)
{
helper(S,0,S.size()-1);
sort(ans.begin(),ans.end());
return ans;
}
};
int main(){
int t;
cin >> t;
while(t--)
{
string S;
cin >> S;
Solution ob;
vector<string> ans = ob.find_permutation(S);
for(auto i: ans)
{
cout<<i<<" ";
}
cout<<"\n";
}
return 0;
} | true |
bafc6c5ba4fae5fcd8206ab8fecf2596a492d859 | C++ | hanjongho/baekjoon | /dijkstra/1504.cpp | UTF-8 | 1,591 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
#define INF 987654321
using namespace std;
int dist[801];
int N, E, v1, v2, v1_ans, v2_ans, v3_ans, v4_ans;
vector <pair<int, int> > v[801];
priority_queue <pair<int, int> > q;
void dijkstra(int x)
{
for (int i = 1; i <= N; i++)
dist[i] = INF;
dist[x] = 0;
q.push({dist[x], x});
while (!q.empty())
{
int cost = q.top().first * -1;
int now = q.top().second;
q.pop();
if (dist[now] < cost)
continue ;
for (int i = 0; i < v[now].size(); i++)
{
int next = v[now][i].first;
int nextCost = cost + v[now][i].second;
if (nextCost < dist[next])
{
dist[next] = nextCost;
q.push({nextCost * -1, next});
}
}
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> N >> E;
for (int i = 0; i < E; i++)
{
int a, b, c;
cin >> a >> b >> c;
v[a].push_back({b, c});
v[b].push_back({a, c});
}
cin >> v1 >> v2;
dijkstra(1);
v1_ans = dist[v1];
v3_ans = dist[v2];
dijkstra(v1);
int dist1 = dist[v2];
dijkstra(v2);
int dist2 = dist[v1];
dijkstra(v2);
v2_ans = dist[N];
dijkstra(v1);
v4_ans = dist[N];
if ((v1_ans == INF || v2_ans == INF) && (v3_ans == INF || v4_ans == INF) || (dist1 == INF && dist2 == INF))
cout << "-1\n";
else
cout << min(v1_ans + dist1 + v2_ans, v3_ans + dist2 + v4_ans) << "\n";
return (0);
} | true |
6b165614720699195f10d559489f7d68da72d644 | C++ | Ian-Parberry/Tourney | /Code/TakefujiLee.cpp | UTF-8 | 7,161 | 2.515625 | 3 | [
"MIT"
] | permissive | /// \file TakefujiLee.cpp
/// \brief Code for the neural network tourney generator CTakefujiLee.
// MIT License
//
// Copyright (c) 2019 Ian Parberry
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
#include "TakefujiLee.h"
#include "Helpers.h"
#include "Random.h"
#include "Includes.h"
#include "Defines.h"
#include "Board.h"
extern MoveDeltas g_vecDeltas; ///< Move deltas for all possible knight's moves.
extern std::atomic_bool g_bFinished; ///< Search termination flag.
/// Initialize the neural network.
/// \param w Board width.
/// \param h Board height.
/// \param seed PRNG seed.
CTakefujiLee::CTakefujiLee(int w, int h, int seed):
CNeuralNet(w*h, seed), m_nWidth(w), m_nHeight(h), m_nSize(w*h)
{
for(int srcy=0; srcy<m_nHeight; srcy++)
for(int srcx=0; srcx<m_nWidth; srcx++){
const int src = srcy*m_nWidth + srcx;
for(auto delta: g_vecDeltas){
const int destx = srcx + delta.first;
if(0 <= destx && destx < m_nWidth){
const int desty = srcy + delta.second;
if(0 <= desty && desty < m_nHeight){
const int dest = desty*m_nWidth + destx;
if(src < dest)
InsertNeuron(src, dest);
} //if
} //if
} //for
} //for
Reset();
} //constructor
/// Reset all neuron outputs to zero and all neuron states
/// to a random value.
void CTakefujiLee::Reset(){
for(CEdge* pEdge: m_vEdgeList){
CNeuron* pNeuron = (CNeuron*)pEdge;
pNeuron->SetOutput(m_cRandom.randf() < 0.5f);
pNeuron->SetState(0);
} //for
RandomizeEdgeList();
} //Reset
/// Update all neurons.
/// \return true If the network has stabilized.
bool CTakefujiLee::Update(){
for(CEdge* pEdge: m_vEdgeList){ //update neuron states
CNeuron* pNeuron = (CNeuron*)pEdge;
int newstate = pNeuron->GetState() + 4;
UINT v0, v1;
pEdge->GetVertexIndices(v0, v1);
for(UINT v: {v0, v1}){
std::vector<CEdge*>* adj = m_pVertexList[v].GetAdjacencyList();
for(CEdge* pEdge2: *adj)
if(((CNeuron*)pEdge2)->GetOutput())
newstate -= 1;
} //for
pNeuron->SetState(newstate);
if(newstate > 3)pNeuron->SetOutput(true);
else if(newstate < 0)pNeuron->SetOutput(false);
} //for
return IsStable();
} //Update
/// The network is stable if all neurons are stable.
/// \return true If all neurons are stable.
bool CTakefujiLee::IsStable(){
for(CEdge* pEdge: m_vEdgeList)
if(((CNeuron*)pEdge)->IsStable())
return false;
return true;
} //IsStable
/// The neural network may converge to a state in which not all vertices have
/// degree 2, which is a requirement for knight's tours and tourneys.
/// \return true If all vertices have degree 2.
bool CTakefujiLee::HasDegree2(){
int* degree = new int[m_nNumVerts];
for(UINT i=0; i<m_nNumVerts; i++)
degree[i] = 0;
for(CEdge* pEdge: m_vEdgeList){
CNeuron* pNeuron = (CNeuron*)pEdge;
if(pNeuron->GetOutput()){
UINT i, j;
pNeuron->GetVertexIndices(i, j);
degree[i]++;
degree[j]++;
} //if
} //for
bool bDegree2 = true;
for(UINT i=0; i<m_nNumVerts && bDegree2; i++)
bDegree2 = bDegree2 && degree[i] == 2;
delete [] degree;
return bDegree2;
} //HasDegree2
/// Generate a tourney.
/// \param b [out] Chessboard.
void CTakefujiLee::Generate(CBoard& b){
bool bFinished = false;
bool bStable = false;
while(!bFinished && !g_bFinished){
Reset();
bStable = false;
for(int j=0; j<400 && !bStable; j++)
bStable = Update();
bFinished = HasDegree2();
} //while
if(bFinished)
GraphToBoard(b);
} //Generate
/// Assuming the neural network has converged, convert the outputs
/// of its neurons to a move table.
/// \param b [out] Chessboard for the results.
void CTakefujiLee::GraphToBoard(CBoard& b){
b.Clear();
for(UINT i=0; i<m_nNumVerts; i++)
m_pVertexList[i].Mark(false);
UINT startindex = 0;
while(startindex < m_nNumVerts && m_pVertexList[startindex].Marked())
startindex++;
while(startindex < m_nNumVerts){
CVertex* start = &m_pVertexList[startindex];
CVertex* prev = start;
prev->Mark();
CEdge* pEdge = nullptr;
auto adj = prev->GetAdjacencyList();
for(auto it=(*adj).begin(); it!=(*adj).end(); it++){
CNeuron* pNeuron = (CNeuron*)*it;
if(pNeuron->GetOutput() == 1){
if(!pNeuron->GetNextVertex(prev)->Marked()){
pEdge = *it;
break;
} //if
} //if
} //for
CVertex* cur = pEdge->GetNextVertex(prev);
b.InsertUndirectedMove(prev->GetIndex(), (int)cur->GetIndex());
while(cur != start && !cur->Marked()){
cur->Mark();
CEdge* pNextEdge = nullptr;
auto adj = cur->GetAdjacencyList();
for(auto it=(*adj).begin(); it!=(*adj).end(); it++){
CNeuron* pNeuron = (CNeuron*)*it;
if(pNeuron->GetOutput() == 1 && (*it) != pEdge){
pNextEdge = *it;
break;
} //if
} //for
CVertex* next = pNextEdge->GetNextVertex(cur);
prev = cur;
cur = next;
b.InsertUndirectedMove(prev->GetIndex(), (int)cur->GetIndex());
pEdge = pNextEdge;
} //while
while(startindex < m_nNumVerts && m_pVertexList[startindex].Marked())
startindex++;
} //while
} //GraphToBoard
/// Get vector of vertices adjacent to a given vertex.
/// \param p Pointer to a vertex.
/// \param v [out] Vector of vertices adjacent to the vertex pointed to by p.
void CTakefujiLee::GetAdjacentVertices(std::vector<CVertex*>& v, CVertex* p){
v.clear();
if(p == nullptr)return;
std::vector<CEdge*>* adjacencylist = p->GetAdjacencyList();
for(CEdge* pEdge: *adjacencylist){
CVertex* pNext = pEdge->GetNextVertex(p);
if(pNext != nullptr)
v.push_back(pNext);
} //for
} //GetAdjacentVertices
/// Permute the edge list into pseudorandom order for update.
void CTakefujiLee::RandomizeEdgeList(){
const size_t n = m_vEdgeList.size();
for(size_t i=0; i<n; i++){
const int j = m_cRandom.randn((UINT)i, (UINT)n - 1);
std::swap(m_vEdgeList[i], m_vEdgeList[j]);
} //for
} //RandomizeEdgeList | true |
d232cf0667b784582d802f0e1aa6dc756c333ef3 | C++ | silviuh/first_game | /MyfirstSDLgame/main.cpp | UTF-8 | 6,625 | 2.609375 | 3 | [
"Zlib",
"FTL",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | #include "gameHandler.h"
#include "LevelManager.h"
#include "EndGameMenu.h"
#include "CharacterMenu.h"
bool restartGameFlag = false;
bool backToMainMenuFlag = false;
int totalScore = 0;
Game *game = nullptr;
Menu *endGameMenu = nullptr;
Menu* mainMenu = nullptr;
Menu* characterMenu;
LevelManager *gameLevelManager = nullptr;
Menu* endGameMenuInit(int finalScore, int levelReached);
Menu* mainMenuInit();
void displayInstructions();
void instructionsMenuManager();
void startGame();
void mainMenuQuitGame();
void restartGame();
void backToMyMenu();
void endMenuQuitGame();
int main(int argc, char* args[])
{
const int FPS = 100;
const int frameDelay = 1000 / FPS;
Uint32 frameStart = 0;
Uint32 lastUpdate = 0;
int frameTime;
game = new Game();
game->init((char*) "IN DIRE NEED FOR SOME COIN", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 800, false, LEVEL_1);
gameLevelManager = new LevelManager(game);
mainMenu = mainMenuInit();
MainMenuLabel:
while (mainMenu->menuIsActive() == true) {
frameStart = SDL_GetTicks();
mainMenu->drawMenu();
mainMenu->handleEvents();
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
if (mainMenu->returnRequestForExitingTheGame() == false) {
characterMenu = new CharacterMenu(250, 80, make_pair(270, 210), vector<menuItem>());
characterMenu->characterDataInit();
while (characterMenu->menuIsActive() == true) {
frameStart = SDL_GetTicks();
characterMenu->drawMenu();
characterMenu->handleEvents();
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
gameLevelManager->setCurrentCharacterInGame(characterMenu->getSelectedCharacter());
game->setCharacter(characterMenu->getSelectedCharacter());
game->createHeroes();
if (characterMenu->returnRequestForExitingTheGame() == false) {
GamePlayLabel:
while (true == game->gameIsRunning()) {
frameStart = SDL_GetTicks();
game->handleEvents();
if (frameStart - lastUpdate >= 300) {
game->update();
lastUpdate = SDL_GetTicks();
}
pair<int, int> playerStatus = game->render();
if (playerStatus.first == PLAYER_IS_DEAD) {
totalScore += playerStatus.second;
Menu* endGameMenu = endGameMenuInit(totalScore, game->currentLevel);
endGameMenu->showMessageWhenPlayerDies = true;
while (endGameMenu->menuIsActive() == true) {
frameStart = SDL_GetTicks();
endGameMenu->drawMenu();
endGameMenu->handleEvents();
switch (endGameMenu->optionsFlag) {
case RESTART_GAME_FLAG:
goto GamePlayLabel;
break;
case BACK_TO_MY_MENU_FLAG:
goto MainMenuLabel;
break;
case QUIT_GAME_FLAG:
cout << "\n You exited the game!";
break;
default:
break;
}
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
}
else if (playerStatus.first == PLAYER_WON_THE_LEVEL) {
gameLevelManager->getCurrentScoreOnLevelSucces(playerStatus.second);
totalScore += playerStatus.second;
game = gameLevelManager->loadNextLevel();
}
}
}
}
delete mainMenu;
delete endGameMenu;
delete characterMenu;
game->clean();
return 0;
}
void startGame() {
mainMenu->switchOffMenuLoop();
game->switchOnGameLoop();
}
void mainMenuQuitGame() {
mainMenu->switchOffMenuLoop();
mainMenu->gameExit();
game->switchOffGameLoop();
}
void instructionsMenuManager() {
mainMenu->switchOnInstructionMenu();
SDL_Event event;
int frameTime;
const int frameDelay = 1000 / 100;
while (mainMenu->checkIfinstructionsMenuIsActive() == true) {
Uint32 frameStart = SDL_GetTicks();
displayInstructions();
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_KEYDOWN: {
switch (event.key.keysym.sym) {
case SDLK_RETURN:
mainMenu->switchOffInstructionMenu();
break;
}
break;
}
case SDL_QUIT: {
mainMenu->switchOffInstructionMenu();
mainMenu->switchOffMenuLoop();
mainMenu->gameExit();
break;
}
}
}
frameTime = SDL_GetTicks() - frameStart;
if (frameDelay > frameTime) {
SDL_Delay(frameDelay - frameTime);
}
}
}
void displayInstructions() {
SDL_RenderClear(Game::renderer);
TTF_Font *font = TTF_OpenFont(TAHOMA, 20);
SDL_Rect blittingRectangle;
blittingRectangle.x = 170;
blittingRectangle.y = 160;
blittingRectangle.h = 350;
blittingRectangle.w = 450;
SDL_Surface* textSurface = TTF_RenderText_Blended_Wrapped(font, INSTRUCTIONS_TEXT, SDL_Color({ 255, 0, 0 }), 350);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(Game::renderer, textSurface);
SDL_RenderCopy(Game::renderer, textTexture, nullptr, &blittingRectangle);
SDL_RenderPresent(Game::renderer);
SDL_FreeSurface(textSurface);
}
Menu* endGameMenuInit(int finalScore, int levelReached) {
vector<menuItem> optionsForEndGameMenu;
menuItem m1 = { "< Restart Game? >", restartGame };
menuItem m2 = { "< Back to Main Menu >", backToMyMenu };
menuItem m3 = { "< Exit Game >", endMenuQuitGame };
optionsForEndGameMenu.push_back(m1);
optionsForEndGameMenu.push_back(m2);
optionsForEndGameMenu.push_back(m3);
endGameMenu = new EndGameMenu(250, 80, make_pair(270, 400), optionsForEndGameMenu, finalScore, levelReached);
return endGameMenu;
}
Menu* mainMenuInit(){
vector<menuItem> optionsForMainMenu;
menuItem m1 = { "< Start Game >", startGame };
menuItem m2 = { "< Instructions >", instructionsMenuManager };
menuItem m3 = { "< Exit Game >", mainMenuQuitGame };
optionsForMainMenu.push_back(m1);
optionsForMainMenu.push_back(m2);
optionsForMainMenu.push_back(m3);
mainMenu = new Menu(250, 80, make_pair(270, 210), optionsForMainMenu);
return mainMenu;
}
void restartGame() {
endGameMenu->switchOffMenuLoop();
game->clean();
delete game;
game = new Game();
game->init((char*) "IN DIRE NEED FOR SOME COIN", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 800, false, LEVEL_1);
game->setCharacter(gameLevelManager->getCurrentCharacterInGame());
game->createHeroes();
endGameMenu->optionsFlag = RESTART_GAME_FLAG;
}
void backToMyMenu() {
restartGame();
mainMenu->switchOnMenuLoop();
characterMenu->switchOnMenuLoop();
mainMenu->switchOnInstructionMenu();
endGameMenu->optionsFlag = BACK_TO_MY_MENU_FLAG;
}
void endMenuQuitGame() {
endGameMenu->switchOffMenuLoop();
mainMenu->switchOffMenuLoop();
characterMenu->switchOffMenuLoop();
game->switchOffGameLoop();
endGameMenu->optionsFlag = QUIT_GAME_FLAG;
} | true |
ffc5ad65d4789cc0ae92429287f7c52c595af2c9 | C++ | venkatarajasekhar/tortuga | /wrappers/core/include/EventFunctor.h | UTF-8 | 886 | 2.640625 | 3 | [] | no_license | /*
* Copyright (C) 2007 Robotics at Maryland
* Copyright (C) 2007 Joseph Lisee <jlisee@umd.edu>
* All rights reserved.
*
* Author: Joseph Lisee jlisee@umd.edu>
* File: wrappers/core/include/EventFunctor.h
*/
#ifndef RAM_CORE_WRAP_EVENTFUNCTOR_H_10_30_2007
#define RAM_CORE_WRAP_EVENTFUNCTOR_H_10_30_2007
// Library Includes
#include <boost/python.hpp>
// Project Includes
#include "core/include/Event.h"
/** Wraps a called python object, so it can handle events
*
* Then given python object is checked to make sure its calledable and has
* the proper number of arguments on functor creation.
*/
class EventFunctor
{
public:
EventFunctor(boost::python::object pyObject);
void operator()(ram::core::EventPtr event);
/** The callable python object which is called to handle the event */
boost::python::object pyFunction;
};
#endif // RAM_CORE_WRAP_EVENTFUNCTOR_H_10_30_2007
| true |
c378f1e75c56d8f24bc7b554aa26f2d7863799de | C++ | pvantonov/qnavierstokes | /src/side_heating/side_heating_solver.hpp | UTF-8 | 10,738 | 2.8125 | 3 | [] | no_license | #pragma once
#include <QtCore/QMutex>
#include <QtCore/QThread>
//! Класс, отвечающий за решение конвективной задачи бокового подогрева.
class SideHeatingSolver : public QThread
{
Q_OBJECT
public:
//! \param[in] parent Указатель на родительский виджет.
SideHeatingSolver(QObject *parent = NULL);
~SideHeatingSolver();
/*!
* \brief Функция для задания физических параметров задачи.
* \param height Высота расчетной области.
* \param Pr Число Прандтля.
* \param Gr Число Грасгофа.
* \param isLeftWallHard Флаг, показывающий является ли левая стенка жесткой.
* \param isRightWallHard Флаг, показывающий является ли правая стенка жесткой.
* \param isTopWallHard Флаг, показывающий является ли верхняя стенка жесткой.
* \param isBottomWallHard Флаг, показывающий является ли нижняя стенка жесткой.
*/
void setProblemParameters(double height, double Pr, double Gr, bool isLeftWallHard,
bool isRightWallHard, bool isTopWallHard, bool isBottomWallHard);
/*!
* \brief Функция для задания математических параметров задачи.
* \param nx Число узлов сетки по горизонтали.
* \param ny Число узлов сетки по вертикали.
* \param numOfMaxIter Максимальное число итераций.
* \param wT Коэффициент релаксации для температуры.
* \param wPsi Коэффициент релаксации для функции тока.
* \param wOmega Коэффициент релаксации для вихря.
*/
void setSolverParameters(int nx, int ny, int maxNumOfIter, double wT, double wPsi, double wOmega);
//! \return Значение по умолчанию для параметра релаксации температуры.
double getDefaultWT();
//! \return Значение по умолчанию для параметра релаксации функции тока.
double getDefaultWPsi();
//! \return Значение по умолчанию для параметра релаксации вихря.
double getDefaultWOmega();
//! \return Значение по умолчанию для максимального числа итераций.
int getDefaultMaxNumOfIter();
//! Прервать работу решателя.
void cutOffSolution();
protected:
//! Запуск решателя в отдельном потоке.
void run();
signals:
/*!
* Сигнал о завершении очередной итерации решателя.
* \param currentIteration Номер завершенной итерации.
* \param maxNumOfIterations Максимально допустимое число итераций.
* \param currentResidual Текущая невязка по нелинейности.
*/
void iterationFinished(int currentIteration, int maxNumOfIterations ,double currentResidual);
/*!
* Сигнал о том, что решение прервано из-за того, что достигнуто максимальное число итераций.
* \param currentResidual Текущая невязка по нелинейности.
*/
void maxIterNumberAttained(double currentResidual);
//! Сигнал о завершении работы решателя.
void solutionFinished();
private:
/*!
* Функция выделяет динамическую память для данных, создает конечноэлементную сетку,
* а также задает начальное приближение для искомых функций T, Psi и Omega.
*/
void prepareData();
//! Сборка СЛАУ для температуры.
void tSLAE();
//! Сборка СЛАУ для температуры.
void psiSLAE();
//! Сборка СЛАУ для температуры.
void omegaSLAE();
//! Вычисление вектора скорости.
void formV();
//! Вывод результатов.
void output();
//! Освобождение динамически выделенной памяти.
void freeMemory();
//! Расчет невязки по нелинейности с учетом коэффициента релаксации.
double residual();
//! Очистка матрицы СЛАУ и вектора правой части(заполнение их нулями).
void clearSLAE();
//********************************************************************************************************
//Физические и геометрические параметры задачи.
//********************************************************************************************************
double Pr; //!< Число Прандтля.
double Gr; //!< Число Грасгофа.
double width; //!< Ширина расчетной области.
double height; //!< Высота расчетной области.
//********************************************************************************************************
//Математические параметры задачи.
//********************************************************************************************************
double wT; //!< Коэффициент релаксации для температуры.
double wPsi; //!< Коэффициент релаксации для функции тока.
double wOmega; //!< Коэффициент релаксации для вихря.
int maxNumOfIter; //!< Максимальное число итераций решателя.
//********************************************************************************************************
//Переменные, описывающие краевые условия задачи.
//********************************************************************************************************
bool isLeftWallHard; //!< Флаг, показывающий является ли левая стенка жесткой.
bool isRightWallHard; //!< Флаг, показывающий является ли правая стенка жесткой.
bool isTopWallHard; //!< Флаг, показывающий является ли верхняя стенка жесткой.
bool isBottomWallHard; //!< Флаг, показывающий является ли нижняя стенка жесткой.
//********************************************************************************************************
//Конечноэлементная сетка. Сетка является регулярной. Расчетная область разбивается на прямоугольники с
//длинной сторон hx и hy. Число прямоугольников в вертикальном и горизонтальном напрвлениях составляе
//nx - 1 и ny - 1 соответственно.
//********************************************************************************************************
int nx; //!< Число узлов в сетке по горизоньали
int ny; //!< Число узлов в сетке по вертикали
double hx; //!< Шаг сетки по горизонтали
double hy; //!< Шаг сетки по вертикали
int **nvtr;
double **xy;
int numOfPoints;
int numOfTriangles;
//********************************************************************************************************
//Информация о краевых условиях. Для температуры - это узлы в которых задано первое КУ и значение
//температуры в этих узлах. Для функции тока и для вихря - только узлы. Для функции тока значение
//на границе всегда равно 0, а для вихря оно зависит от текущего значения функции тока.
//********************************************************************************************************
int *topT_bc1;
int *topPsiOmega_bc1;
double *T_bc1;
int numOfPointsT_bc1;
int numOfPointsPsiOmega_bc1;
//********************************************************************************************************
//СЛАУ и вектора неизвестных (в том числе их копии с предыдущей итерации по нелинейности).
//********************************************************************************************************
int *ig;
int *jg;
double *ggl;
double *di;
double *ggu;
double *f;
double *t;
double *psi;
double *omega;
double *tOld;
double *psiOld;
double *omegaOld;
//********************************************************************************************************
//Вектора компонент скорости и радиального градиента температуры.
//********************************************************************************************************
double *tx;
double *vx;
double *vy;
//********************************************************************************************************
//********************************************************************************************************
QMutex mutex; //!< Mutex обеспечивает защиту переменной от одновременного доступа из нескольких потоков.
bool isSolutionCutOff; //!< Флаг, реагирующий на сигналы извне о прерывании работы решателя.
};
| true |