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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1f743427eac4f889aaa6659b62249e5b88a413fe | C++ | Kim-dongeon/Algorithm | /Study/백준/2667_동언.cpp | UTF-8 | 1,187 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
int N;
int arr[27][27];
bool isVisited[27][27];
vector<int> apart;
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };
int main()
{
scanf("%d", &N);
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
scanf("%1d", &arr[i][j]);
}
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
queue<pair<int,int>> que;
if (arr[i][j] == 1 && isVisited[i][j] == false)
{
que.push(make_pair(i, j));
isVisited[i][j] = true;
int apart_cnt = 0;
while (!que.empty())
{
int x = que.front().first;
int y = que.front().second;
que.pop();
for (int k = 0; k < 4; k++)
{
int nx = x + dx[k];
int ny = y + dy[k];
if (nx >= 0 && nx < N&&ny >= 0 && ny < N&&arr[nx][ny] == 1 && isVisited[nx][ny] == false)
{
que.push(make_pair(nx, ny));
isVisited[nx][ny] = true;
apart_cnt++;
}
}
}
apart.push_back(apart_cnt);
}
}
}
cout << apart.size()<<endl;
sort(apart.begin(), apart.end());
for (int i = 0; i < apart.size(); i++)
{
cout << apart[i]+1 << endl;
}
} | true |
6361c6a8ab52c18650d0d1012175d14a1f0cc9c9 | C++ | Haut-Stone/ACM | /INBOX/独木舟问题(贪心).cpp | UTF-8 | 3,096 | 3.5625 | 4 | [] | no_license | /*
n个人,已知每个人体重,独木舟承重固定,每只独木舟最多坐两个人,可以坐一个人或者两个人。显然要求总重量不超过独木舟承重,假设每个人体重也不超过独木舟承重,问最少需要几只独木舟?
分析:
一个显然的策略是按照人的体重排序。
极端化贪心策略,最重的人要上船——如果最重的人和最轻的人体重总和不超过船的承重,则他们两个占用一条船。否则(因为假设最重的人的体重也不超过船的承重了),最重的人单独占一条船。转变为(n – 1)或者(n – 2)的问题了。
关键在于这种贪心策略是正确的。我们可以证明,最优解也可以变为这种策略。
(1) 假设最重的人和最轻的人的体重和超过了船的承重,那么最优解中,显然也是最重的人单独占一条船,所以这种情况下最优解和贪心策略是相同的。
(2) 假设最重的人和最轻的人的体重和没超过船的承重。
(2.1)如果最优解中,最重的人单独占用一条船,则可以把最轻的人也放上去,这样最优解用的船数不增加。如果最轻的人占用一条船,同样我们可以把最重的人放上去,最优解船数不增。
(2.2) 如果最优解中最重的人x和x’占用一只船(x, x’),而最轻的人y和y’占用一只船(y, y’)
我们换成(x, y) (x’,y’)
(x, y)显然没超过船的承重——因为我们假设就是如此。关键看(x’, y’)。
x’ + y’<= x’ + x 因为(x’, x)没超重,所以(x’,y’)也合法。所以换一下,最优解船数也不增。这样我们就证明了如果可能把最重的人和最轻的人放在一条船上,不会影响最优解。
反复应用这个策略,就可以把n降低为(n – 1)或者(n – 2)个人的规模,从而解决这个问题。
最后,我们来提供输入输出数据,由你来写一段程序,实现这个算法,只有写出了正确的程序,才能继续后面的课程。
输入
第一行包含两个正整数n (0<n<=10000)和m (0<m<=2000000000),表示人数和独木舟的承重。
接下来n行,每行一个正整数,表示每个人的体重。体重不超过1000000000,并且每个人的体重不超过m。
输出
一行一个整数表示最少需要的独木舟数。
输入示例
3 6
1
2
3
输出示例
2
*/
//
// main.c
// 独木舟问题(贪心)
//
// Created by Jack Lee on 2016/11/29.
// Copyright © 2016年 SJH. All rights reserved.
//
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
long long n,m;
long long weight[10000+11];
scanf("%lld %lld", &n, &m);
for(long long i=0;i<n;i++){
scanf("%lld", &weight[i]);
}
sort(weight, weight+n, greater<long long>());
long long b=n-1;
long long sum=0;
for(long long i=0;i<=b;i++){
if(weight[i] + weight[b] <= m){
b--;
sum++;
}else{
sum++;
}
}
printf("%lld\n", sum);
return 0;
} | true |
19d644dc2cfd77d8dd45bd25d40e62a3df676c94 | C++ | HuuPhuc25/abstract_demo_cpp | /date_field.cpp | UTF-8 | 1,780 | 2.84375 | 3 | [] | no_license | #include "date_field.h"
DateField::DateField()
{
}
DateField::~DateField()
{
}
DateField::DateField(int _index)
{
this->index = _index;
this->setDefaultData();
}
DateField::DateField(int _index,tm _data)
{
index = _index;
mData = _data;
}
int DateField::getIndex()
{
return this->index;
}
void DateField::setIndex(int index)
{
this->index = index;
}
eDataType DateField::getDataType()
{
return eDATE;
}
void*
DateField::getData(void* p)
{
if(p == NULL)
return NULL;
memcpy(p,&this->mData,sizeof(tm));
return &this->mData;
}
void
DateField::setData(void* _mData)
{
memset(&mData, 0, sizeof(tm));
memcpy(&mData, (tm*)_mData, sizeof(tm));
}
void
DateField::setDataFrom(char* field)
{
if(field != NULL)
{
memset(&mData, 0, sizeof(tm));
strptime(field, "%Y-%m-%d", &mData);
}
}
char*
DateField::buildQuery(char* columnName)
{
char* cmd;
cmd = (char*) malloc(BUFFER_SIZE_OF_DATE + strlen(columnName) + 3);
sprintf(cmd, "%s = \'%s\'", columnName, date2String(this->mData));
return cmd;
}
char*
DateField::genJson(char* columnName)
{
char* cmd;
cmd = (char*) malloc(BUFFER_SIZE_OF_DATE + strlen(columnName) + 7);
sprintf(cmd, "\"%s\" = \"%s\"", columnName, date2String(this->mData));
return cmd;
}
long
DateField::getSizeData()
{
return BUFFER_SIZE_OF_DATE;
}
long
DateField::getSizeQuery()
{
return BUFFER_SIZE_OF_DATE + MAX_SIZE_COLUMN_NAME + 5;
}
char*
DateField::data2String()
{
char* dst;
dst = (char*) malloc(BUFFER_SIZE_OF_DATE);
sprintf(dst, "\'%d-%d-%d\'", 1900 + this->mData.tm_year, this->mData.tm_mon+1, this->mData.tm_mday);
return dst;
}
void
DateField::setDefaultData()
{
memset(&this->mData, 0, sizeof(tm));
} | true |
ec9573988644fc33c63eec1c169edc52e2bf44a1 | C++ | ibnumaulana215/program-perulangan-While-dan-Do-While | /main.cpp | UTF-8 | 312 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int a=1;
while(a<10)
{
cout<<a<<endl;
a++;
}
cout<<endl<<"---------------------------------------"<<endl;
int b=0;
do
{
cout<<b<<endl;
b++;
}
while(b<10);
}
| true |
839e66393680f1090189826e61fb5b86bd8b4c3f | C++ | chemesh/Elections_v2 | /DistrictsList.cpp | UTF-8 | 2,548 | 2.875 | 3 | [] | no_license | #include "DistrictsList.h"
namespace elc
{
bool DistrictsList::setSize(const int& _size)
{
District** temp = new District*[_size];
for (int i = 0; i < size; i++)
temp[i] = list[i];
this->size = _size;
//delete[] list;
list = temp;
return true;
}
bool DistrictsList::setLength(const int& len)
{
this->length = len;
return true;
}
bool DistrictsList::setDistrict(char* _DistrictName, int numOfReps, bool div)
{
//District* temp;
if (isFull())
{
setSize(size * 2);
}
if (div)
list[length] = new Divided(_DistrictName, numOfReps);
//temp = new Divided(_DistrictName, numOfReps);
else
list[length] = new District(_DistrictName, numOfReps);
//temp = new District(_DistrictName, numOfReps);
//list[length]->setDistrict(_DistrictName, numOfReps);
//list[length] = temp;
list[length]->setDistID(length);
setLength(length + 1);
return true;
}
bool DistrictsList::setDistrict(const District& _dist)
{
if (isFull())
{
setSize(size * 2);
}
*(list[length]) = _dist;
list[length]->setDistID(length);
setLength(length + 1);
return true;
}
//added
bool DistrictsList::setCitizenInDist(const Citizen& resident, const District& dist)
{
list[dist.getDistID()]->setDistCitizenInList(resident);
return true;
}
int DistrictsList::getSize() const
{
return this->size;
}
int DistrictsList::getLength() const
{
return this->length;
}
bool DistrictsList::isFull()
{
if (length == size)
return true;
return false;
}
void DistrictsList::operator=(const DistrictsList& o)
{
setSize(o.size);
setLength(o.length);
for (int i = 0; i < o.length; i++)
{
list[i] = o.list[i];
}
}
// bool DistrictsList::isDivided(int i)
// {
// if (typeid(*list[i]) == typeid(Divided))
// return true;
// else
// return false;
// }
void DistrictsList::save(ofstream& out) const
{
bool type = false;
out.write(rcastcc(&size), sizeof(size));
out.write(rcastcc(&length), sizeof(length));
for (int i = 0; i < length; ++i)
{
type = list[i]->isDivided();
out.write(rcastcc(&type), sizeof(type));
list[i]->save(out);
}
}
void DistrictsList::load(ifstream& in)
{
bool type = false;
in.read(rcastc(&size), sizeof(size));
in.read(rcastc(&length), sizeof(length));
list = new District * [size];
for (int i = 0; i < length; ++i)
{
in.read(rcastc(&type), sizeof(type));
if (type) // ==1 meand divided
{
list[i] = new Divided();
}
else
{
list[i] = new District();
}
list[i]->load(in);
}
}
} | true |
fdcb14392bf363b53bb96a59684f998b4fc53bf4 | C++ | Tsaanstu/new_project_2 | /Game/tests/src/test_object.cpp | UTF-8 | 4,092 | 2.859375 | 3 | [] | no_license | #include "catch.hpp"
#include "mistborn.hpp"
#include "misting.hpp"
#include "soldier.hpp"
#include "metal.hpp"
TEST_CASE("mistborn, constructor with initialisation", "[mistborn]") {
SECTION("without argument") {
Mistborn mistborn(100, 10, 9, 8, 7, 600, String("test_mistborn_1"), String("test_mistborn_1"));
REQUIRE(mistborn.get_name().toAnsiString() == "test_mistborn_1");
REQUIRE(mistborn.get_hp() == 100);
REQUIRE(mistborn.get_force() == 10);
REQUIRE(mistborn.get_distant_force() == 9);
REQUIRE(mistborn.get_accuracy_of_shooting() == 8);
REQUIRE(mistborn.get_distance_of_walk() == 7);
REQUIRE(mistborn.get_cost() == 600);
}
SECTION("from file") {
Mistborn mistborn;
mistborn.read_data_from_file("test_mistborn_1");
REQUIRE(mistborn.get_name().toAnsiString() == "test_mistborn_1");
REQUIRE(mistborn.get_hp() == 80);
REQUIRE(mistborn.get_force() == 10);
REQUIRE(mistborn.get_distant_force() == 11);
REQUIRE(mistborn.get_accuracy_of_shooting() == 12);
REQUIRE(mistborn.get_distance_of_walk() == 13);
REQUIRE(mistborn.get_cost() == 100);
}
}
TEST_CASE("misting, constructor with initialisation", "[misting]") {
SECTION("without argument") {
Misting misting(100, 10, 9, 8, 7, 600, String("test_misting_1"), String("test_misting_1"));
REQUIRE(misting.get_name().toAnsiString() == "test_misting_1");
REQUIRE(misting.get_hp() == 100);
REQUIRE(misting.get_force() == 10);
REQUIRE(misting.get_distant_force() == 9);
REQUIRE(misting.get_accuracy_of_shooting() == 8);
REQUIRE(misting.get_distance_of_walk() == 7);
REQUIRE(misting.get_cost() == 600);
}
SECTION("from file") {
Misting misting;
misting.read_data_from_file("test_misting_1");
REQUIRE(misting.get_name().toAnsiString() == "test_misting_1");
REQUIRE(misting.get_hp() == 90);
REQUIRE(misting.get_force() == 10);
REQUIRE(misting.get_distant_force() == 11);
REQUIRE(misting.get_accuracy_of_shooting() == 12);
REQUIRE(misting.get_distance_of_walk() == 13);
REQUIRE(misting.get_cost() == 110);
}
}
TEST_CASE("soldier, constructor with initialisation", "[soldier]") {
SECTION("without argument") {
Soldier soldier(100, 10, 9, 8, 7, 600, String("test_soldier_1"), String("test_soldier_1"));
REQUIRE(soldier.get_name().toAnsiString() == "test_soldier_1");
REQUIRE(soldier.get_hp() == 100);
REQUIRE(soldier.get_force() == 10);
REQUIRE(soldier.get_distant_force() == 9);
REQUIRE(soldier.get_accuracy_of_shooting() == 8);
REQUIRE(soldier.get_distance_of_walk() == 7);
REQUIRE(soldier.get_cost() == 600);
}
SECTION("from file") {
Soldier soldier;
soldier.read_data_from_file("test_soldier_1");
REQUIRE(soldier.get_name().toAnsiString() == "test_soldier_1");
REQUIRE(soldier.get_hp() == 100);
REQUIRE(soldier.get_force() == 10);
REQUIRE(soldier.get_distant_force() == 11);
REQUIRE(soldier.get_accuracy_of_shooting() == 12);
REQUIRE(soldier.get_distance_of_walk() == 13);
REQUIRE(soldier.get_cost() == 90);
}
}
TEST_CASE("metal, constructor with initialisation", "[metal]") {
SECTION("without argument") {
Metal metal(100, 10, 9, 8, 7, 600, String("test_metal_1"), String("test_metal_1"));
REQUIRE(metal.get_name().toAnsiString() == "test_metal_1");
REQUIRE(metal.get_action_time() == 100);
REQUIRE(metal.get_allomantic_power().get_force() == 10);
REQUIRE(metal.get_allomantic_power().get_distant_force() == 9);
REQUIRE(metal.get_allomantic_power().get_accuracy_of_shooting() == 8);
REQUIRE(metal.get_allomantic_power().get_distance_of_walk() == 7);
REQUIRE(metal.get_cost() == 600);
}
SECTION("from file") {
Metal metal;
metal.read_data_from_file("test_metal_1");
REQUIRE(metal.get_name().toAnsiString() == "test_metal_1");
REQUIRE(metal.get_action_time() == 3);
REQUIRE(metal.get_allomantic_power().get_force() == 10);
REQUIRE(metal.get_allomantic_power().get_distant_force() == 11);
REQUIRE(metal.get_allomantic_power().get_accuracy_of_shooting() == 12);
REQUIRE(metal.get_allomantic_power().get_distance_of_walk() == 13);
REQUIRE(metal.get_cost() == 200);
}
}
| true |
e65b9e233a2feecbac1e023865770ab666baa6d7 | C++ | gcaushik/Cplusplus-School-Projects | /College Course Map/graph.cpp | UTF-8 | 8,578 | 3.828125 | 4 | [] | no_license | //Gokul Caushik
#include "graph.h"
#include <iostream>
using namespace std;
#include <cstring>
/*The constructor allocates the memory for the vertices and initializes
all their head pointers to NULL.*/
graph::graph()
{
numofvertices = 0; //Keeps track of the number of vertices in the graph
degree = new vertex[20]; //Allocate memory for 20 vertices
for (int i=0; i<20; i++)
{
degree[i].head = NULL; //Initialize head pointers to NULL
}
}
/*The addreq function takes in a course name, adds a vertex, and copies
this information to it. If the course has been added already, then it
returns 0, otherwise it returns 1.*/
int graph::addreq(char req[])
{
for(int i=0; i<numofvertices; i++)
{
if(strcmp(degree[i].requirements, req) == 0) // If vertex has already been added
return 0;
}
degree[numofvertices].requirements = new char[strlen(req)+1];
strcpy(degree[numofvertices].requirements, req);
++numofvertices;
return 1;
}
/*The addcourse function takes in a course and its prerequisite as
arguments. It adds a vertex and an edge, and copies the name of the course
to the edge node and the prerequisite name to the vertex. It returns 0 if
the prerequisite and the course are the same, returns 1-4 if the course
gets added, and returns 5 if there are any duplicates.*/
int graph::addcourse(char course[], char prereq[])
{
int compare, compare2; //Compare the prereq and course to the vertices
int reqflag = 0; //Activated if there is a match for prereq in vertex
int courseflag = 0; //Activated if there is a match for course in vertex
if(strcmp(course, prereq) == 0) //If prereq and course are the same
return 0;
for(int i=0; i<numofvertices; i++)
{
compare = strcmp(degree[i].requirements, prereq);
compare2 = strcmp(degree[i].requirements, course);
if(courseflag == 0 && compare2 == 0) //If match for course
courseflag = 1; //Activate course flag
if(reqflag == 0 && compare == 0) //If match for prereq
{
reqflag = 1; //Activate reqflag
node *current = degree[i].head; //Used to traverse the adjacency list to see if there are duplicates for course
node *temp = current;
while(temp)
{
if(strcmp(current->course, course)== 0) //If duplicate for course
return 5;
temp = temp->next;
}
degree[i].head = new node; //Add the course to the adjacency list
degree[i].head->course = new char[strlen(course)+1];
strcpy(degree[i].head->course, course);
degree[i].head->next = current;
}
if(reqflag && courseflag) //If course has been added
return 1;
}
if((reqflag && !courseflag) || (!reqflag && !courseflag)) //If no matches found or no course match
{
degree[numofvertices].requirements = new char[strlen(course)+1]; //Add vertex
strcpy(degree[numofvertices].requirements, course);
++numofvertices;
if(reqflag && !courseflag)
return 3;
}
degree[numofvertices].requirements = new char[strlen(prereq)+1]; //Add vertex and course
strcpy(degree[numofvertices].requirements, prereq);
degree[numofvertices].head = new node;
degree[numofvertices].head->course = new char[strlen(course)+1];
strcpy(degree[numofvertices].head->course, course);
degree[numofvertices].head->next = NULL;
++numofvertices;
return 2;
}
/*The removecourse function takes in a course as an argument and removes
it from the graph. This means removing a vertex and all edges containing
the course. It returns 0 if the course to be removed is not found,
otherwise it returns 1.*/
int graph::removecourse(char course[])
{
node *current; //These three node pointers are used to delete a node, whether it be in the beginning, middle, or end
node *temp;
node *previous;
int compare; //Compares course to the vertex
int deleteflag = 0; //Activated when traversing through last vertex
int counter = 0; //Counts matches
for(int i=0; i<numofvertices; i++)
{
if(i == numofvertices-1)
deleteflag = 1;
compare = strcmp(degree[i].requirements, course);
if(compare == 0 || (deleteflag == 1 && counter > 0)) //If there is a match or match has already been found but it is not the last vertex
{
counter++;
current = degree[i].head;
temp = current;
while(current) //Destroy the adjacency list
{
current = temp->next;
delete temp->course;
temp->course = NULL;
delete temp;
temp = current;
}
degree[i].head = NULL;
if(deleteflag == 0) //If match is not found in the last node
{
strcpy(degree[i].requirements, degree[numofvertices-1].requirements);
copy(degree[i].head, degree[numofvertices-1].head);
}
}
else
{
current = degree[i].head;
previous = NULL;
while(current) //Search adjacency list for node to delete
{
if(strcmp(current->course, course) == 0) //If match for node for course
{
counter++;
node *temp = current;
current = current->next;
delete temp->course; //Delete course (same as removing an edge)
delete temp;
if(previous)
{
previous->next = current;
}
else
degree[i].head = current;
}
else //Traverse
{
previous = current;
current = current->next;
}
}
}
}
if(counter == 0) //If no matches were found
return 0;
else
{
--numofvertices; //Decrement number of vertices
return 1;
}
}
/*The removepreq function takes in a course and a prerequisite and
searches the vertices for a match for prereq, and then searches its
adjacency list for a match for the course. If there is a match, it deletes
the course (deletes an edge). It returns 0 if no matches are found and
returns 1 or 2 if the edge is removed. */
int graph::removepreq(char course[], char prereq[])
{
int compare; //Compares prereq to the vertex
for(int i=0; i<numofvertices; i++)
{
compare = strcmp(degree[i].requirements, prereq);
if(compare == 0) //If there is a match
{
node *current = degree[i].head; //Used to remove the edge
node *previous = NULL;
while(current)
{
if(strcmp(current->course, course) == 0) //If match for course
{
node *temp = current;
current = current->next;
delete temp; //Remove the edge
if(previous)
{
previous->next = current;
return 1;
}
degree[i].head = current;
return 2;
}
else //Keep traversing
{
previous = current;
current = current->next;
}
}
}
}
return 0;
}
/*The copy function takes the head pointer for a vertex by reference and
the head pointer from the last vertex. It recursively copies the LLL from
the last vertex to the vertex that has been deleted. It returns 1 for
success and 0 if there is an empty LLL. */
int graph::copy(node *&newhead, node *oldhead)
{
if(!oldhead) //If adjacency list is empty
{
newhead = NULL;
return 0;
}
newhead = new node;
if(!newhead)
return 0;
strcpy(newhead->course,oldhead->course); //Copy data
copy(newhead->next, oldhead->next); //Recursive call
return 1;
}
/*The displayall function does not take any arguments and display all the
vertices and their respective adjacency lists. There is no return type for
this function.*/
void graph::displayall()
{
node *current; //Used to traverse and display
for(int i=0; i<numofvertices; i++)
{
cout << "You need ";
cout << degree[i].requirements; //List the vertices
cout << " so you can take:";
cout << endl;
current = degree[i].head;
if(!current) //If adjacency list is empty
cout << "No classes listed\n";
while(current) //List the edges
{
cout << current->course;
cout << endl;
current = current->next;
}
}
}
/*The destructor deallocates all the memory for the graph. It deletes all
the vertices and destroys all the adjacency lists.*/
graph::~graph()
{
node *current;
for(int i=0; i<numofvertices; i++)
{
delete degree[i].requirements; //Deallocate memory for vertex
current = degree[i].head;
while(current) //Destroy the adjacency list
{
degree[i].head = degree[i].head->next;
delete current->course;
delete current;
current = degree[i].head;
}
}
}
| true |
75dc73ed29712a515c8c72faf6c5ba61d99823da | C++ | sheeyen/FE2assignment- | /Q3straddle.cpp | UTF-8 | 2,223 | 2.890625 | 3 | [] | no_license | //FE2 ASSIGNMENT STRADDLE
#include <iostream>
#include <math.h>
#include <conio.h>
#include <iomanip>
#include <fstream>
#define PI 3.14159265358979323846
using namespace std;
double N (double);
double M (double);
void main ()
{
float time, K, d1, d2, nd1, nd2, n1d1, delta, vega, theta;
float S, r, q, v;
K = 100;
r = 0.07;
q = 0;
v = 0.30;
ofstream output;
output.open("Q3straddle.txt", ios :: out);
output << setw(13) << "Stock Price";
output << setw(13) << "Delta(1M)" << setw(13) << "Vega(1M)";
output << setw(13) << "Theta(1M)" << setw(13) << "Delta(1Y)";
output << setw(13) << "Vega(1Y)" << setw(13) << "Theta(1Y)";
for (S = 60; S <= 140; S += 1)
{
time = 0.083333333;
output << "\n" << setw(13) << S ;
do {
d1 = (log(S/K) + (r - q + (pow(v,2)/2))*time)/(v*pow(time,0.5));
d2 = d1 - (v*pow(time,0.5));
nd1 = N(d1);
nd2 = N(d2);
n1d1 = M(d1);
delta = nd1 + nd1 - 1 ;
vega = S*n1d1*pow(time,0.5) + S*n1d1*pow(time,0.5);;
theta = - (S*n1d1*v)/(2*pow(time,0.5)) - r*K*exp(-r*time)*nd2 - (S*n1d1*v)/(2*pow(time,0.5)) + r*K*exp(-r*time)*N(-d2);
output << setw(13) << delta << setw(13) << vega << setw(13) << theta ;
time = time*12;
} while (time <= 1);
}
output.close();
system("gnuplot -p Q3straddledelta.gnu");
system("gnuplot -p Q3straddlevega.gnu");
system("gnuplot -p Q3straddletheta.gnu");
cout << "\nCompleted\n" << endl;
_getch();
}
// To calculate N(d1) & N(d2)
double N (double x)
{
// constants
double a1 = 0.254829592;
double a2 = -0.284496736;
double a3 = 1.421413741;
double a4 = -1.453152027;
double a5 = 1.061405429;
double p = 0.3275911;
// Save the sign of x
int sign = 1;
if (x < 0)
sign = -1;
x = fabs(x)/sqrt(2.0);
// A&S formula 7.1.26
double t = 1.0/(1.0 + p*x);
double y = 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);
return 0.5*(1.0 + sign*y);
}
// To calculate N'(d1)
double M (double w)
{
double z;
z = pow(w,2)/2;
return pow(2*PI, -0.5)*exp(-z);
}
| true |
425a114009ebdfdef3d96d5d1f322189685c1099 | C++ | gabrielpastori/Competitive-Programming | /OBI/2013/soma_de_fracoes.cpp | UTF-8 | 527 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
long long int mdc(long long int a,long long int b){
return (b==0 ? a:mdc(b,a%b));
}
int main(){
long long int a,b,c,d;
cin>>a>>b>>c>>d;
long long int mmc=b*d/mdc(max(b,d),min(b,d));
long long int n=(mmc/b)*a + (mmc/d)*c;
long long int md=mdc(n,mmc);
while(mdc(max(n,mmc),min(n,mmc))!=1){
n/=md;
mmc/=md;
md=mdc(max(n,mmc),min(n,mmc));
}
cout<<n<<" "<<mmc<<endl;
}
| true |
85853f750742153cc6f0417a5160a2052bfb010b | C++ | Arryboom/LeagueAPI | /include/lol/def/LolChampSelectLegacyChampSelectChatRoomDetails.hpp | UTF-8 | 719 | 2.578125 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include "../base_def.hpp"
namespace lol {
struct LolChampSelectLegacyChampSelectChatRoomDetails {
std::string chatRoomName;
std::optional<std::string> chatRoomPassword;
};
inline void to_json(json& j, const LolChampSelectLegacyChampSelectChatRoomDetails& v) {
j["chatRoomName"] = v.chatRoomName;
if(v.chatRoomPassword)
j["chatRoomPassword"] = *v.chatRoomPassword;
}
inline void from_json(const json& j, LolChampSelectLegacyChampSelectChatRoomDetails& v) {
v.chatRoomName = j.at("chatRoomName").get<std::string>();
if(auto it = j.find("chatRoomPassword"); it != j.end() && !it->is_null())
v.chatRoomPassword = it->get<std::optional<std::string>>();
}
} | true |
ea7f7ecc0618634c94060cc0adb7d645639403c3 | C++ | JustinLiu1998/ECNU-Online-Judge | /34/main.cpp | UTF-8 | 811 | 2.71875 | 3 | [] | no_license | //
// main.cpp
// 34
//
// Created by 刘靖迪 on 2018/1/7.
// Copyright © 2018年 刘靖迪. All rights reserved.
//
#include <iostream> //有错
#include <cstring>
char *Filter(char *s, char *x) {
int len = (int)strlen(x);
for (int i=0; i<strlen(s) - len; i++) {
int flag = 1;
for (int j=0; j<len; j++) {
if (s[i+j] != x[j]) {
flag = 0;
break;
}
}
if (flag) {
for (int j = i+len; j<=strlen(s); j++) {
s[j-len] = s[j];
}
i--;
}
}
return s;
}
using namespace std;
int main(int argc, const char * argv[]) {
char s[81], x[81];
scanf("%s%s", s, x);
printf("%s\n", Filter(s, x));
return 0;
}
| true |
d4e605f7d3a2baab48fbd60b3dd3ee9abcec59dc | C++ | ccdxc/logSurvey | /data/crawl/git/hunk_285.cpp | UTF-8 | 1,040 | 3.234375 | 3 | [] | no_license | }
/*
- * Convert a partial SHA1 hex string to the corresponding partial SHA1 value.
- * - hex - Partial SHA1 segment in ASCII hex format
- * - hex_len - Length of above segment. Must be multiple of 2 between 0 and 40
- * - oid - Partial SHA1 value is written here
- * Return 0 on success or -1 on error (invalid arguments or input not
- * in hex format).
+ * Read `len` pairs of hexadecimal digits from `hex` and write the
+ * values to `binary` as `len` bytes. Return 0 on success, or -1 if
+ * the input does not consist of hex digits).
*/
-static int get_oid_hex_segment(const char *hex, unsigned int hex_len,
- unsigned char *oid)
+static int hex_to_bytes(unsigned char *binary, const char *hex, size_t len)
{
- unsigned int i, len = hex_len >> 1;
- if (hex_len % 2 != 0)
- return -1;
- for (i = 0; i < len; i++) {
+ for (; len; len--, hex += 2) {
unsigned int val = (hexval(hex[0]) << 4) | hexval(hex[1]);
+
if (val & ~0xff)
return -1;
- *oid++ = val;
- hex += 2;
+ *binary++ = val;
}
return 0;
}
| true |
24db26dc73d71ce1f54f552b6755d2dabaad2967 | C++ | chiibu21/cppGameProject | /game.cpp | UTF-8 | 16,199 | 3.34375 | 3 | [] | no_license | //============================================================================
// Name : game.cpp
// Author : Chiibu Abdul-Kudus
//============================================================================
// PLEASE COMPILE AND RUN THIS FROM A WINDOWS COMMAND PROMPT OR CODEBLOCKS. I USED FUNCTIONS RESERVED FOR WINDOWS AND THE CLEAR FUNCTION DOES NOT
// WORK ON ECLIPSE IDE. THANKS
#include <iostream> // for i/o
#include <windows.h>// for Sleep() and clear functions
#include <cstdlib> //
#include <string> // for strings
#include <fstream> // for file handling
using namespace std;
typedef struct { // struct declaration
int level[6]; // levels go from 0 to 5
}Tower; // Tower now like a new data type
Tower towers[3]; // an array of 3 instances of tower. one for each tower
string username; // STORE USERNAME
int move_counter; // COUNT MOVES
string top_names[4][5];// STORE NAMES OF PEOPLE IN LEADERBOARD
int top_scores[4][5]={0};// STORE MOVES MADE BY PEOPLE IN LEADERBOARD
// CONST CHAR ARRAY to hold names of leaderboard files for the different game levels
const char * ld[8]={"leaderboard.dat","leaderboard2.dat","leaderboard3.dat","leaderboard4.dat","leaderboard5.dat","leaderboard6.dat","leaderboard7.dat","leaderboard8.dat"};
//START OF FUNCTION PROTOTYPES...
void gameMenu();
void newGame(Tower towers[]);
void gameRules();
void leaderboard();
void printTowers(Tower towers[]);
void getLeaderBoard();
void writeToLeaderBoard();
void sort_lb();
void replace(int i);
void flip(int i);
// END of function prototypes
int main() { // MAIN FUNCTION
getLeaderBoard(); // RETRIEVE ALL DATA IN FILES AND STORE THEM IN LOCAL ARRAYS
system("cls"); // CLEAR CONSOLE
gameMenu(); // CALL MAIN MENU OF GAME
return 0; // TERMINATE PROGRAM
}
//END OF MAIN FUNCTION
void gameMenu(){
system("cls"); // CLEAR
cout <<"\n\n\n\n\n\t\t\t\t\t\t**********************************" << endl; // NAME TAG
cout <<"\n\t\t\t\t\t\tWelcome to the Tower of Hanoi Game" << endl;
cout <<"\n\t\t\t\t\t\t\tBy Chiibu Abdul-Kudus" << endl;
cout <<"\n\t\t\t\t\t\t**********************************" << endl;
int menu_choice; // user choice of menu item
cout<<"\t\t\t\t\t\t\t1. New Game\n\t\t\t\t\t\t\t2. Read Game Rules\n\t\t\t\t\t\t\t3. Leaderboard\n\t\t\t\t\t\t\t4. Exit\n\t\t\t\t\t\t\tEnter your choice: "; // print menu items
while(!(cin>>menu_choice) || menu_choice<1 || menu_choice>4){ // input and validation
cout<<"\t\t\t\t\t\tWrong input. Try again: "; // prompt
cin.clear(); // clear fail bit
while(cin.get()!='\n'){} // clear input buffer
}
switch(menu_choice){ // switch user choice
case 1:
newGame(towers); // call new game and pass the towers to it
break;
case 2:
gameRules(); // display game rules by it's function
break;
case 3:
leaderboard(); // leaderboard function to display leaderboard
break;
case 4:
system("cls");
exit(EXIT_SUCCESS);
break; // break out and exit if user chooses to
default:
cout<<"\t\t\t\t\t\tI don't understand you!"<<endl; // won't come to this because of validation but eehhh!
break;
}
system("cls"); // clear console
}
void newGame(Tower towers[]){ // new game fucntion
system("cls");
cout<<"Enter number of disks per tower(3-6): "; // ask number of disks per tower...the higher the tougher it is
int disk_per_tower;
bool fail;
move_counter=0;
while(!(cin>> disk_per_tower) || disk_per_tower <3 || disk_per_tower > 6){ // input and validation
cin.clear();
while(getchar()!='\n'){}
cout<<"Enter a number between 3 and 6: ";
}
cout<<"New Game with "<<disk_per_tower<<" disks..."<<endl; // prompt
Sleep(1000);
system("cls");
int i,j;
int premature=0; // used to check if user quits prematurely
for(i=0;i<3;i++){ // for loop to fill all levels of towers with 0s. This means no disks ...initialization
for(j=0;j<6;j++){
towers[i].level[j]=0;
}
}
for(i=0;i<disk_per_tower;i++){ // fill first tower with as many disks as the user chooses. disk radii range from 1 to 6.
towers[0].level[i]=(6-i);
}
int check[6]; // array to hold initial content of first tower to be compared with for winning
for(i=0;i<6;i++){ // for loop to assign tower[0] to check[]
check[i]=towers[0].level[i];
}
int from,to; // int variables to hold moves
bool game_on=true; // check if game play should keep running
while(game_on==true){
fail=false; // check if move is invalid
system("cls");
cout<<"\n\n"<<endl;
printTowers(towers); // print towers
cout<<"\t\t\tTotal moves made: "<<move_counter<<endl; // print number of moves made
cout<<endl;
cout<<"Move disk from ( enter 0 to quit ): "; // print output
while(!(cin>>from) || from > 3 || from < 0){ // input to from and validate it
cin.clear();
while(cin.get()!='\n'){}
cout<<"Wrong input. Enter either 0, 1, 2 or 3: ";
}
if(from==0){ // if user enters 0, quit
premature=1; // let program know it quit prematurely
break;
}
cout<<"To ( enter 0 to quit ): ";
while(!(cin>>to)||to>3||to<0||to==from){ // input to "to" variable and validate it
cin.clear();
while(cin.get()!='\n'){}
if(to==from){
cout<<"You may not move from a tower to same tower. Enter another tower: "<<endl;
}
else{
cout<<"Wrong input. Enter either 0, 1, 2 or 3: ";
}
}
if(to==0){ // quit if input is 0
premature=1; // premature quitting
break;
}
int i=5;
int j;
int disk_temp=0;
while(i>=0 && disk_temp==0){ // loop through to see where the first disk is from the tower you want to pick from
if(towers[from-1].level[i]>0){
disk_temp=towers[from-1].level[i];
j=i;
}
i--;
}
if(disk_temp==0){ // if no disk was found there
cout<<"There is no disk from your initial tower. Pick a tower with a disk already in it."<<endl;
Sleep(700);
fail=true; // set fail to false so it can go back without doing the rest of the game
}
if(fail==false){ // if the preceeding part was successful...
for(i=0;i<6;i++){ // loop through to place the disk on the first free space on the "to" tower
if(towers[to-1].level[i]==0){
if(i==0){ // successfully placed
towers[to-1].level[i]=disk_temp;
towers[from-1].level[j]=0;
move_counter++;
break;
}
else{
if(towers[to-1].level[i-1]<disk_temp){ // if you try to place on a disk smaller than the disk being moved
cout<<"You cannot place a bigger disk on a smaller one. Try again..."<<endl;
Sleep(2000);
}
else{ // successfully placed
towers[to-1].level[i]=disk_temp;
towers[from-1].level[j]=0; // always reset the point from which the disk was moved to 0 so it signifies no disk exists there anymore
move_counter++; // increment move counter
}
break;
}
}
}
}
game_on=false; // temporally set game_on to false. You will check to see if it really is in the next loop below
for(i=0;i<6;i++){ // check through to see if your last tower has disks matching how you started on the first tower
if(towers[2].level[i]!=check[i]){
game_on=true; // if any of them fails to match, the game is still on
break; // break and stop checking
}
}
}
if(premature==0){ // if you do not quit prematurely. You must win to get to this part of the program unless you quit prematurely then it will skip it.
system("cls");
cout<<"\n\n"<<endl;
printTowers(towers); // print the tower
cout<<"\t\t\tTotal moves made: "<<move_counter<<endl; // display moves made
Sleep(1000);
system("cls");
for(i=0;i<2;i++){ // nice way of saying "You win!" ;)
cout<<"\n\n\n\n\n\t\t\t\t\t\tYOU WIN !!!"<<endl;
Sleep(700);
system("cls");
Sleep(500);
}
switch(disk_per_tower){
case 3: // CHECK IF PLAYER WON WITH THE LEAST POSSIBLE MOVES
if(move_counter==7){
cout<<"You made a perfect score!"<<endl;
Sleep(600);
}
break;
case 4:
if(move_counter==15){
cout<<"You made a perfect score!"<<endl;
Sleep(600);
}
break;
case 5:
if(move_counter==31){
cout<<"You made a perfect score!"<<endl;
Sleep(600);
}
break;
case 6:
if(move_counter==63){
cout<<"You made a perfect score!"<<endl;
Sleep(600);
}
break;
}
if(move_counter<=top_scores[disk_per_tower-3][4] || top_scores[disk_per_tower-3][4]==0){ // if you used less moves than those in the leaderboard or that part is occupied by 0 ( 0 used to show empty space )
cout<<"You have made the leaderboard!"<<endl;
cout<<"Enter a nickname: ";
cin>>username;
cin.clear();
while(cin.get()!='\n'){}
replace(disk_per_tower); // place on leaderboard
writeToLeaderBoard(); // write it to the external data files
leaderboard(); // call leaderboard so they can see their stance
}
cout<<endl;
}
else{ // if they quit prematurely
system("cls");
cout<<"Sorry to see you leave!"<<endl; // prompt
Sleep(1000);
}
gameMenu(); // call game menu at the end
}
void gameRules(){ // PRINT OUT GAME RULES
system("cls");
cout<<endl;
cout<<"\t\t\t\t\t\t\tGAME RULES: \n\t\t\t\t\t\t\t-----------"<<endl;
cout<<"\t\t\t\tIn this game, you have a number of disks stacked on a pole.\n\t\t\t\tYour goal is to transfer these disks to the third pole stacked in same order as initially.\n\t\t\t\tYou cannot place a bigger disk on a smaller disk! You should try to win in as few moves a possible!\n\n";
cout<<"\t\t\t\t";
system("pause"); // WAIT FOR INPUT
system("cls");
gameMenu(); // CALL GAME MENU
}
void leaderboard(){
system("cls");
cout<<endl;
cout<<"\t\t\t\t\t\t\tLEADERBOARD:\n\t\t\t\t\t\t\t---------------"<<endl;
int i,j;
for(i=3;i<=6;i++){ // loop through arrays and print leaderboard
cout<<"\t\t\t\t\t\t\t"<<i<<" disks:\n\t\t\t\t\t\t\t-----------\n";
for(j=0;j<5;j++){
if(top_scores[i-3][j]!=0){
cout<<"\t\t\t\t\t\t\t"<<top_names[i-3][j]<<" : "<<top_scores[i-3][j]; // print name and moves
if((i==3 && top_scores[i-3][j]==7) || (i==4 && top_scores[i-3][j]==15) || (i==5 && top_scores[i-3][j]==31) || (i==6 && top_scores[i-3][j]==63)){// if least possible moves
cout<<" (Perfect score!) ";
}
}
cout<<endl;
}
cout<<endl;
}
cout<<"\n\n";
cout<<"\t\t\t\t\t\t\t";system("pause"); // wait for keyboard input
system("cls");
gameMenu();
}
void printTowers(Tower towers[]){ // FUNCTION TO PRINT TOWERS AND THE DISKS!
int i,j,temp;
for(i=0;i<=6;i++){ // loop through 6 lines. Printing is done from top to bottom
for(j=0;j<79;j++){ // I require a total of 79 columns to print the three towers
if(j<27){ //Start of tower 1
if(j==12){
if(i==6){
cout<<"1"; // if in the middle of the tower at last line, print label of tower
}
else
cout<<"|"; // else if not at the last line but in the middle, print the bar
}
else{ // anywhere else...
if(towers[0].level[5-i]>0){ // if a disk exist in that level of the bar
temp=towers[0].level[5-i]; // set temp to the radius of that disk
temp*=2; // i multiply by two so the difference between the disks is readily visible
if(j<12 && 12-(temp+j)>0){ // whilst not in the area occupied by disk on one side print spaces
cout<<" ";
}
else if(j>12 && (j-12)>temp){ // print spaces on other side of disk
cout<<" ";
}
else{
cout<<"="; // if in the location of a disk, print =. To represent a fraction of the thickness of the disk
}
}
else{
cout<<" "; // print space anywhere else
}
}
} // End of tower1
// THE ABOVE IS USED TO PRINT TOWER 2 AS WELL
else if(j>=27 && j<52){
if(j==39){
if(i==6){
cout<<"2";
}
else
cout<<"|";
}
else{
if(towers[1].level[5-i]>0){
temp=towers[1].level[5-i];
temp*=2;
if(j<39 && 39-(temp+j)>0){
cout<<" ";
}
else if(j>39 && (j-39)>temp){
cout<<" ";
}
else{
if(i==6){ // BECAUSE I USE 5-i, AT i=6, I GET A NEGATIVE INDEX. THIS MAKES IT PRINT = IN THE ROW MEANT FOR LABELS FOR DISKS EQUAL TO 6. THIS IF HERE FIXES IT
cout<<" "; // THIS PROBLEM ONLY PERSISTS IN THE 2ND TOWER
}
else{
cout<<"=";
}
}
}
else{
cout<<" ";
}
}
}
else{
// SAME TECHNIQUE USED TO PRINT TOWER 3
if(j==66){ // START OF TOWER 3
if(i==6){
cout<<"3";
}
else
cout<<"|";
}
else{
if(towers[2].level[5-i]>0){
temp=towers[2].level[5-i];
temp*=2;
if(j<66 && 66-(temp+j)>0){
cout<<" ";
}
else if(j>66 && (j-66)>temp){
cout<<" ";
}
else{
cout<<"=";
}
}
else{
cout<<" ";
}
}
}
}
temp=0; // RESET TEMP
cout<<endl; // END LINE AT END OF EACH ROW!
}
cout<<"\n"<<endl; // SPACE AFTER PRINTING ALL THE TOWERS COMPELETELY.
}
void getLeaderBoard(){ // WHEN GAME STARTS, LOAD LEADERBOARD FILES TO MULTIDIMENSIONAL ARRAYS FOR USAGE IN THE PROGRAM
int j,count;
fstream fs;
for(count=0;count<4;count++){ // reads in the names
fs.open(ld[count], fstream::in); // open for reading
for(j=0;j<5;j++)
{
fs >> top_names[count][j]; // read to location in array
}
fs.close(); // close file
}
for(count=4;count<8;count++){ // reads in the top scores. I make them correspond to each other. I don't know how to make a dictionary kind of thing where you assign a data value to a name :(
fs.open(ld[count],fstream::in);
for(j=0;j<5;j++){
fs >> top_scores[count-4][j];
}
fs.close();
}
sort_lb();
}
void writeToLeaderBoard(){ // FUNCTION TO WRITE LEADERBOARD TO EXTERNAL FILES
int j,count;
fstream fs;
for(count=0;count<4;count++){ // LOOP THROUGH FIRST 4 FILES
for(j=0;j<5;j++){
if(j==0){
fs.open(ld[count],fstream::out); // IF FIRST TIME, OPEN FOR OUT WHICH MEANS IT CLEARS EVERYTHING ALREADY THERE. I utilize
// an array of file names(ld[]) so I can loop through it.
// I don't have mastery over file handling so I use multiple files so it's easy for me.
fs<<top_names[count][j]; // WRITE FIRST NAME THERE
fs.close();
}
else{
fs.open(ld[count],fstream::app); // SUBSEQUENTLY OPEN IT FOR APPENDING SO YOU DON'T CLEAR EXISTING DATA
fs<<" "<<top_names[count][j]; // WRITE REST OF NAMES
fs.close(); // CLOSE FILE
}
}
}
for(count=4;count<8;count++){ // LOOP THROUGH LAST FOUR FILES
for(j=0;j<5;j++){
if(j==0){
fs.open(ld[count],fstream::out); // OPEN FIRST FOR OUT
fs<<top_scores[count-4][j]; // WRITE FIRST TOP SCORE
fs.close();
}
else{
fs.open(ld[count],fstream::app); // NOW OPEN FOR APPENDING
fs<<" "<<top_scores[count-4][j]; // APPEND REST OF TOP SCORES
fs.close();
}
}
}
sort_lb();
}
void replace(int i)
{ // replace a user in the leader board at the end ( one with largest moves )
top_scores[i-3][4]=move_counter;
top_names[i-3][4]=username;
flip(i); // used to place newest player in leaderboard above all those already in leaderboard with same number of moves.
sort_lb(); // call sort function
}
void sort_lb(){ // function to sort leaderboard using bubble sort algorithm.
int i,j,k,temp;
string stemp;
for(i=0;i<4;i++){
for (j=0;j<4;j++){
for(k=0;k<5-j-1;k++){
if((top_scores[i][k]>=top_scores[i][k+1] && top_scores[i][k+1]!=0) || (top_scores[i][k]==0 && top_scores[i][k+1]!=0)){ // sort using top_scores. Place 0s at the end
temp=top_scores[i][k];
top_scores[i][k]=top_scores[i][k+1];
top_scores[i][k+1]=temp;
stemp=top_names[i][k]; // if need to flip a score, go ahead and flip corresponding names too
top_names[i][k]=top_names[i][k+1];
top_names[i][k+1]=stemp;
}
}
}
}
}
void flip(int i)
{
// Used to flip new user to position of existing users with same scores. This ensures new users stay longer on leaderboard
bool flipon=true;
int j=4;
int temp;
string stemp;
do{
if(top_scores[i-3][j]==top_scores[i-3][j-1] || top_scores[i-3][j-1]==0){
// switch scores
temp=top_scores[i-3][j];
top_scores[i-3][j]=top_scores[i-3][j-1];
top_scores[i-3][j-1]=temp;
// switch names
stemp=top_names[i-3][j];
top_names[i-3][j]=top_names[i-3][j-1];
top_names[i-3][j-1]=stemp;
j--;
}
else{
flipon=false;
}
}while(flipon==true && j>=1);
}
| true |
cfab1f4c36da24e748f5191002106243873c6211 | C++ | binkesi/leetcode_easy | /cpp/n530_BSTMinus.cpp | UTF-8 | 960 | 3.40625 | 3 | [] | no_license | // https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int getMinimumDifference(TreeNode* root) {
vector<int> tree_val;
TreeList(root, tree_val);
if (tree_val.size() == 1) return 0;
int min_res = tree_val[1] - tree_val[0];
for (size_t i = 2; i < tree_val.size(); ++i)
min_res = min(min_res, tree_val[i] - tree_val[i-1]);
return min_res;
}
void TreeList(TreeNode* root, vector<int>& tree_val){
if (root == NULL) return;
TreeList(root -> left, tree_val);
tree_val.push_back(root -> val);
TreeList(root -> right, tree_val);
}
};
int main(){
return 0;
} | true |
41feef098169a6cd5407208e898847e974a5d2e1 | C++ | ddorobek/3307-Final-Project-Video-Game | /Final Project/Final/GameOver.cpp | UTF-8 | 3,983 | 3.625 | 4 | [] | no_license | /** @class GameOver
* @brief The GameOver class creates a screen for when the player fails to complete the game.
* @author
*
* The GameOver class creates a window of the screen when the player fails to complete the game (player dies). The screen informs the player that they have lost and gives them the option to exit the game.
*/
#include "GameOver.h"
using namespace sf;
/** @fn GameOver::GameOver()
* @brief This function constructs the GameWon object.
*
* This function constructs the GameOver object and renders a window to display to the user. The user will be informed they have lost the game and the game creators will be displayed. The user will have the option to exit the game.
*/
GameOver::GameOver() {
//Open window and set frame rate to 60
RenderWindow window(VideoMode(1280, 720), "R.E.M. - Game Over", Style::Default);
window.setFramerateLimit(60);
Event event;
Vector2f mousePosWindow;
//Create overlay texture and sprite for window background.
Texture bgTexture;
Sprite bgSprite;
Image bgImage;
bgImage.loadFromFile("over-1280x720.png");
bgTexture.loadFromImage(bgImage);
bgSprite.setTexture(bgTexture);
bgSprite.setTextureRect(IntRect(0, 0, 1280, 720));
bgSprite.setPosition(0.0f, 0.0f);
//Create overlay texture and sprite for Exit image.
Texture quitTexture;
Sprite quitSprite;
Image quitImage;
quitImage.loadFromFile("exit-red-480x135.png");
quitTexture.loadFromImage(quitImage);
quitSprite.setTexture(quitTexture);
quitSprite.setTextureRect(IntRect(0, 0, 480, 135));
quitSprite.setPosition(800.0f / 2.0f, 292.5f);
//Loads font to display text
Font font;
if (!font.loadFromFile("lcdsolid.ttf"))
{
//didn't load properly
std::cout << "Font did not load properly." << std::endl;
}
//Sets text and position for informing the player they have lost to display on screen
Text overText;
overText.setFont(font);
overText.setString("You have perished...");
overText.setCharacterSize(48);
overText.setFillColor(Color::White);
overText.setPosition(24, 24);
//Sets text and position for the credits to display on screen
Text creditsText;
creditsText.setFont(font);
creditsText.setString("Creators: Claudiu Cretu, Damien Dorobek, John Fischer, Brayden Horth, Jordan Nesbitt");
creditsText.setCharacterSize(24);
creditsText.setFillColor(Color::White);
creditsText.setPosition(12, 684);
while (window.isOpen()) {
while (window.pollEvent(event)) {
//If user clicks the "x" icon to close the window at the top right of the screen, window is closed which terminates game.
if (event.type == sf::Event::Closed) {
closed = true;
window.close();
}
//Set mouse coordinates to mousePosWindow
mousePosWindow = Vector2f(Mouse::getPosition(window));
}
if (Mouse::isButtonPressed(Mouse::Left)) {
//If user clicked on Exit, set closed to true and close window
if (quitSprite.getGlobalBounds().contains(mousePosWindow)) {
closed = true;
window.close();
}
}
//Clear the window.
window.clear();
//Draw all created sprites in the window.
window.draw(bgSprite);
window.draw(quitSprite);
window.draw(overText);
window.draw(creditsText);
//Display the window.
window.display();
}
}
/** @fn bool GameOver::isClosed()
* @brief This function returns true if the player has clicked Exit.
* @return
* This function returns true if the player has clicked on Exit. If the player has not clicked on Exit, function returns false.
*/
bool GameOver::isClosed() {
if (closed == true) return true;
return false;
}
/** @fn bool GameOver::isStarted()
* @brief This function returns true if the player has lost the game and the window is rendered.
* @return
* This function returns true if the player has lost the game (player died) and the window is rendered. Otherwise, it returns false.
*/
bool GameOver::isStarted() {
if (started == true) return true;
return false;
} | true |
45dcbe108d47a8b37284f518b2206e29bbea8254 | C++ | BurningS0ul/QT-Projects | /Praktikum2A4/main.cpp | UTF-8 | 593 | 3.109375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
float Zinsen, Schuld = 10000, Ann, Til, Rate = 0.07;
cout << "Tilgungsplan" << endl;
cout << "Bitte geben Sie die gewuenschte Annuitaet ein: ";
cin >> Ann;
for (int i = 0; i < Schuld; i++) {
Zinsen = Schuld * Rate;
Til = Ann - Zinsen;
Schuld = Schuld - Til;
if (Schuld < 0) {
break;
}
cout << "Jahr: " << i << "\t" << "Zinsen: " << Zinsen << "\t" << "Tilgung: " << Til << " Euro\t" << "Restschuld: " << Schuld << " Euro" << endl;
}
return 0;
}
| true |
c7fe2417f1c96f969b02dcc6ce2435ade179c7d3 | C++ | pratiksaha/practice | /geometric/minCostPolynomialTriangulation.cpp | UTF-8 | 1,381 | 3.78125 | 4 | [] | no_license | //A DP based sol to find min cost of convex polygon triangulation
#include<iostream>
#include<cmath>
#include<cfloat>
#include<algorithm>
using namespace std;
struct point{
int x, y;
};
typedef struct point Point;
double dist(Point p1, Point p2) {
return sqrt( (p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) );
}
double cost(Point points[], int i, int j, int k) {
Point p1 = points[i];
Point p2 = points[j];
Point p3 = points[k];
return dist(p1,p2)+dist(p2,p3)+dist(p3,p1);
}
double minCostPolyTriang(Point points[], int n) {
if (n<3)
return 0;
double table[n][n]; //table[i][j] = cost of triangulation of points from i to j
for (int gap=0; gap<n; gap++) {
for (int i=0, j=gap; j<n; i++, j++) {
if (j < i+2) {
table[i][j] = 0.0;
} else {
table[i][j] = DBL_MAX;
for (int k=i+1; k<j; k++) {
double val = table[i][k]+table[k][j]+cost(points,i,j,k);
if (table[i][j] > val)
table[i][j] = val;
}
}
}
}
return table[0][n-1];
}
int main() {
Point points[] = {{0, 0}, {1, 0}, {2, 1}, {1, 2}, {0, 2}};
cout<<"Minimum Cost for Polynomial Triangulation :"<<minCostPolyTriang(points, sizeof(points)/sizeof(points[0]))<<endl;;
return 0;
}
| true |
ab46d488f85731f5cc93c63054ce2d4ae3c70736 | C++ | mastereuclid/cs494project | /src/responses.cpp | UTF-8 | 1,936 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | #include "responses.hpp"
#include <sstream>
// using namespace irc::response;
const string err_NOSUCHNICK(const string arg) {
return string("401 ") + arg + string(" :No such nick/channel");
}
const string err_NOSUCHCHANNEL(const string arg) {
return string("403 ") + arg + string(" :No such nick/channel");
}
const string err_UNKNOWNCOMMAND(const string arg) {
return string("421 ") + arg + string(" :Unknown command");
}
const string err_NICKNAMEINUSE(const string arg) {
return string("433 * ") + arg + string(" :Nickname is already in use");
}
const string err_NEEDMOREPARAMS(const string arg) {
return string("461 ") + arg + string(" :Not enough parameters");
}
const string err_NOTEXTTOSEND() { return string("412 :No text to send"); }
// string rpl_WELCOME(string arg)
const string rpl_quit(const string nickname, const string message) {
std::stringstream out;
out << ":" << nickname << " QUIT :" << message;
return out.str();
}
const string rpl_privmsg(const string nickname, const string dest,
const string msg) {
std::stringstream out;
out << ":" << nickname << " " << dest << " :" << msg;
return out.str();
}
const string rpl_WHOREPLY(const string channel, const string user,
const string host, const string server,
const string nick, const string realname) {
std::stringstream out;
out << "352 " << channel << " " << user << " " << host << " " << server << " "
<< nick << " :" << realname;
return out.str();
}
const string rpl_ENDOFWHO(const string name) {
std::stringstream out;
out << "315 " << name << " :END of WHO list";
return out.str();
}
const string rpl_TOPIC(const string server, const string nick,
const string channel, const string topic) {
std::stringstream out;
out << ":" << server << " 332 " << nick << " " << channel << " :" << topic;
return out.str();
}
| true |
0dc862920a209b9e167eea2c2a92e9578b52d43e | C++ | YellowFish085/NightmareBeforeChristmas | /GLImac-Template/projet/src/Vertex.cpp | UTF-8 | 994 | 3.0625 | 3 | [] | no_license | #include "projet/Vertex.hpp"
namespace Projet
{
Vertex::Vertex() :
_position(glm::vec3(0)),
_texCoords(glm::vec2(0)),
_normal(glm::vec3(0)){
}
Vertex::Vertex(glm::vec3 position, glm::vec2 textcoord, glm::vec3 normal) :
_position(position),
_texCoords(textcoord),
_normal(normal){
}
Vertex::Vertex(float posX, float posY, float posZ, float tcX, float tcY, float normX, float normY, float normZ) :
_position(glm::vec3(posX, posY, posZ)),
_texCoords(glm::vec2(tcX, tcY)),
_normal(glm::vec3(normX, normY, normZ)){
}
Vertex::Vertex(const Vertex& vertexToCopy) :
_position(vertexToCopy._position),
_texCoords(vertexToCopy._texCoords),
_normal(vertexToCopy._normal){
}
Vertex::~Vertex()
{
}
/* OVERLOADING */
/* Operators */
/* |_Comparison operators */
bool Vertex::operator==(const Vertex& rhs) const {
return(_position == rhs._position && _texCoords == rhs._texCoords && _normal == rhs._normal);
}
} | true |
1cda4b0dc08196fd16df2557edd48ffe31115ea8 | C++ | jigar23/Entropycoding | /EntropyCoding/src/Ahuffman/TreeManipulations.cpp | UTF-8 | 4,518 | 3.703125 | 4 | [] | no_license | #include "TreeManipulations.h"
//Global values define
std::vector<Tree*> treeElements;
std::vector<Tree*> leafNodes;
/**
* This function gives birth to two new nodes
* when a new symbol occurs.
* the left child --> NYT node and
* the right right --> new Symbol
* @param:
* 1. int value - value of the symbol
*/
void giveBirth(int value) {
checkNodeForSwapping(512 - Tree::COUNT);
Tree *par = treeElements.at(512 - Tree::COUNT);
Tree *left = new Tree;
Tree *right = new Tree;
//Make it the intermediate node
par->setValue(-1);
par->setWeight(1);
left->setParent(par);
right->setParent(par);
left->setWeight(0);
right->setWeight(1);
left->setValue(-2);
right->setValue(value);
right->setOrder(--Tree::COUNT);
left->setOrder(--Tree::COUNT);
par->setLeftChild(left);
par->setRightChild(right);
treeElements.push_back(right);
treeElements.push_back(left);
leafNodes.push_back(right);
}
/**
* This function just prints all the tree params
* present in the vector.
*/
void printAllVectors() {
for (unsigned int i = 0; i < treeElements.size(); i++) {
Tree *node = treeElements.at(i);
cout << "Order : " << node->getOrder() << endl;
cout << "Weight : " << node->getWeight() << endl;
cout << "Value : " << (char) node->getValue() << endl;
if (node->getParent() != NULL) {
cout << "ParentOrder : " << node->getParent()->getOrder() << endl;
} else {
cout << "Parent : Root" << endl;
}
cout << "------------------" << endl;
}
cout << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" << endl;
}
/**
* This function is useful when swapping two
* pointers.
* In this we copy the contents of a pointer in a
* new pointer,
*/
Tree* copyContentsinObject(Tree *node) {
Tree *obj = new Tree;
obj->setParent(node->getParent());
obj->setOrder(node->getOrder());
return obj;
}
/**
* This function checks the sibling property if the symbol
* is already present in the tree or the NYT's weight.
* Note the vectors of tree elements are arranged
* in descending order of 'Order'.
* If Any of the vector having a higher weight has a lower order
* than the vector with lower weight, then those two branches
* are swapped.
* @param:
* 1. int pos - position in the vector of tree elements
*/
void checkNodeForSwapping(int pos) {
Tree *current = treeElements.at(pos);
int nextpos = -1;
//root node
if (pos == 0) {
//increment the weight before returning.
int wt = treeElements.at(pos)->getWeight();
treeElements.at(pos)->setWeight(++wt);
// printAllVectors();
return;
}
for (int i = pos - 1; i >= 0; i--) {
Tree *nextT = treeElements.at(i);
//previous weight bigger, then break.
//else get the position
if (nextT->getWeight() > current->getWeight())
break;
//dont check if parent
else if (current->getParent() == nextT)
continue;
else
nextpos = i;
}
//Swap the positions
if (nextpos != -1) {
Tree *swapTree = treeElements.at(nextpos);
//copy contents in new pointer before swapping
Tree *st = copyContentsinObject(swapTree);
//Interchange the parent
treeElements.at(nextpos)->setParent(current->getParent());
treeElements.at(pos)->setParent(st->getParent());
//Change the order
treeElements.at(nextpos)->setOrder(current->getOrder());
treeElements.at(pos)->setOrder(st->getOrder());
//Change the positions in the vector array
Tree *temp = treeElements.at(nextpos);
treeElements.at(nextpos) = treeElements.at(pos);
treeElements.at(pos) = temp;
//increment the weight
int wt = treeElements.at(nextpos)->getWeight();
treeElements.at(nextpos)->setWeight(++wt);
//Call its parent
int parentPos =
(512 - treeElements.at(nextpos)->getParent()->getOrder());
checkNodeForSwapping(parentPos);
}
//dont swap and goto the parent
else {
int wt = treeElements.at(pos)->getWeight();
treeElements.at(pos)->setWeight(++wt);
int order = ((treeElements.at(pos)->getParent())->getOrder());
int parentPos = 512 - order;
checkNodeForSwapping(parentPos);
}
}
/**
* This function checks if the sybol is present in the leaf nodes.
* If present, it returns the position of the symbol in the vector of tree
* elements else returns -1 indicating that the symbol is not present in
* the leaf node (i.e. new symbol)
*/
int findSymbol(int val) {
int pos = -1;
unsigned int i;
for (i = 0; i < leafNodes.size(); i++) {
if (val == leafNodes.at(i)->getValue())
break;
}
//Symbol found
if (i < leafNodes.size()) {
int order = leafNodes.at(i)->getOrder();
pos = 512 - order;
}
return pos;
}
| true |
c475a83dcbc4a0f2c78795519446727c84385e7a | C++ | shikharbhatia/Algorithm-and-DataStructures | /AllTopologicalSorts.cpp | UTF-8 | 1,300 | 2.921875 | 3 | [] | no_license | #include <bits/stdc++.h>
#define V 6
using namespace std;
vector<list<int> >adj(V);
vector<int>indegree(V, 0);
void addEdge(int u, int v){
adj[u].push_back(v);
indegree[v]++;
}
void alltopologicalutil(vector<bool>visited, vector<int>&res){
bool flag = 0;
for(int i = 0; i < V; i++){
if(indegree[i] == 0 && !visited[i]){
list<int>::iterator j;
for(j = adj[i].begin(); j != adj[i].end(); j++){
indegree[*j]--;
}
visited[i] = true;
res.push_back(i);
alltopologicalutil(visited, res);
visited[i] = false;
res.erase(res.end()-1);
for(j = adj[i].begin(); j != adj[i].end(); j++){
indegree[*j]++;
}
flag = true;
}
}
if(!flag){
for(int i = 0; i < res.size(); i++){
cout<<res[i]<<" ";
}
cout<<endl;
}
}
void alltopological(){
vector<bool>visited(V, false);
vector<int>res;
alltopologicalutil(visited, res);
}
int main(){
addEdge(5, 2);
addEdge(5, 0);
addEdge(4, 0);
addEdge(4, 1);
addEdge(2, 3);
addEdge(3, 1);
alltopological();
return 0;
}
| true |
9a5a652f28b680bab7243846b51ac00105eb4c20 | C++ | netikras/studies | /Strukt.Progr/_1/N.D./nd_uzd/7.uzd.cpp | UTF-8 | 382 | 2.703125 | 3 | [] | no_license | #include <cstdlib>
#include <stdio.h>
#include <time.h>
/*
7. Funkcijos, kuri generuoja atsitiktinius skaičius, pagalba aprašyti žaidimo kauliuką, kuris po metimo išveda skaičių iš intervalo 1...6.
*/
using namespace std;
int randGen();
int main(){
printf("Iškrito:\t%i",randGen());
return 0;
}
int randGen(){
srand(time(0));
return (rand() % 6)+1;
}
| true |
fed8cc8a75fc7018fa4be170969cc88626136ba1 | C++ | ccluo33/LeetCode | /src/array/56.合并区间.cpp | UTF-8 | 782 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
/*
* @lc app=leetcode.cn id=56 lang=cpp
*
* [56] 合并区间
*/
// @lc code=start
class Solution {
private:
static bool cmp(vector<int>& a, vector<int>& b) {
return a[0] < b[0];
}
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> res;
int idx = -1;
sort(intervals.begin(), intervals.end(), cmp);
for (int i = 0; i < intervals.size(); i++) {
if (idx == -1 || intervals[i][0] > res[idx][1]) {
res.push_back(intervals[i]);
idx++;
} else {
res[idx][1] = max(intervals[i][1], res[idx][1]);
}
}
return res;
}
};
// @lc code=end
| true |
e567c2a01dd077bf411743cc0151420d03e620d9 | C++ | cpbonnell/winlockr | /src/CryptUnprotectData.cpp | UTF-8 | 2,286 | 2.84375 | 3 | [] | no_license | #include <Rcpp.h>
#include <stdio.h>
// Some fixes to make the code play nicely with Windows.h ...
#undef Realloc
#undef Free
// Windows specific includes...
//#pragma comment(lib, "crypt32.lib")
#include <windows.h>
#include <wincrypt.h>
using namespace Rcpp;
//' A wrapper for the Windows DPAPI function CryptUnprotectData()
//'
//' This function is intended to be an internal helper file for the package.
//' Both parameters are currently necessary, and bust be between 1 and 256 bytes
//' in length. The salt should be the one used to encrypt pwd in the first place
//'
//' @param pwd The raw bytes of the encrypted password
//' @param salt The raw bytes of the salt used when the password was encrypted
//'
//' @export
// [[Rcpp::export]]
Rcpp::RawVector CryptUnprotectData(Rcpp::RawVector pwd, Rcpp::RawVector salt){
const int MAX_BYTES = 256;
if(pwd.size() > MAX_BYTES || salt.size() > MAX_BYTES){
//return List::create(Named("ERROR") = "Parameters too long.\n");
return Rcpp::RawVector();
}
int pwd_len = 0;
int salt_len = 0;
BYTE pwd_buffer[MAX_BYTES];
BYTE salt_buffer[MAX_BYTES];
// Copy the input data into buffers and appropriate Windows types
pwd_len = pwd.size();
salt_len = salt.size();
for(int i = 0; i < pwd.size(); i++){
pwd_buffer[i] = pwd[i];
}
for(int i = 0; i < salt.size(); i++){
salt_buffer[i] = salt[i];
}
// Point some windows structures at the buffers
DATA_BLOB pwd_blob;
DATA_BLOB salt_blob;
DATA_BLOB unencrypted_blob;
pwd_blob.cbData = pwd_len;
pwd_blob.pbData = pwd_buffer;
salt_blob.cbData = salt_len;
salt_blob.pbData = salt_buffer;
// Now call the OS function to encrypt the data
CryptUnprotectData(
&pwd_blob,
NULL,
&salt_blob,
NULL, NULL, 0,
&unencrypted_blob
);
// Move the encrypted data to a structure that can be returned
Rcpp::RawVector unprot;
for(unsigned int i = 0; i < unencrypted_blob.cbData; i++){
unprot.push_back(unencrypted_blob.pbData[i]);
}
// Clean up memory (opposite order from CryptProtectData...)
SecureZeroMemory(unencrypted_blob.pbData, unencrypted_blob.cbData);
LocalFree(unencrypted_blob.pbData);
// return List::create(
// Named("unprotected_pwd") = unprot
// );
return unprot;
}
| true |
5fab5ff740d4de4715db4d000d1d8e56381a2042 | C++ | yuyilei/LeetCode | /conTest/180-week/1379_Design-a-Stack-With-Increment-Operation.cpp | UTF-8 | 3,440 | 4.3125 | 4 | [] | no_license | /*
Design a stack which supports the following operations.
Implement the CustomStack class:
CustomStack(int maxSize) Initializes the object with maxSize which is the maximum number of elements in the stack or do nothing if the stack reached the maxSize.
void push(int x) Adds x to the top of the stack if the stack hasn't reached the maxSize.
int pop() Pops and returns the top of stack or -1 if the stack is empty.
void inc(int k, int val) Increments the bottom k elements of the stack by val. If there are less than k elements in the stack, just increment all the elements in the stack.
Example 1:
Input
["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","pop","pop"]
[[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]
Output
[null,null,null,2,null,null,null,null,null,103,202,201,-1]
Explanation
CustomStack customStack = new CustomStack(3); // Stack is Empty []
customStack.push(1); // stack becomes [1]
customStack.push(2); // stack becomes [1, 2]
customStack.pop(); // return 2 --> Return top of the stack 2, stack becomes [1]
customStack.push(2); // stack becomes [1, 2]
customStack.push(3); // stack becomes [1, 2, 3]
customStack.push(4); // stack still [1, 2, 3], Don't add another elements as size is 4
customStack.increment(5, 100); // stack becomes [101, 102, 103]
customStack.increment(2, 100); // stack becomes [201, 202, 103]
customStack.pop(); // return 103 --> Return top of the stack 103, stack becomes [201, 202]
customStack.pop(); // return 202 --> Return top of the stack 102, stack becomes [201]
customStack.pop(); // return 201 --> Return top of the stack 101, stack becomes []
customStack.pop(); // return -1 --> Stack is empty return -1.
Constraints:
1 <= maxSize <= 1000
1 <= x <= 1000
1 <= k <= 1000
0 <= val <= 100
At most 1000 calls will be made to each method of increment, push and pop each separately.
*/
/*
仅在pop进行一次累加
用vector<pair<int,int>> 存贮, pair中的first和second分别表示当前元素大小、元素增量
increment操作时,将增量加到pair的second中,
pop操作时,返回top pair的first+second,并将增量second加到下一个top的second中
*/
class CustomStack {
public:
CustomStack(int maxSize) {
size = maxSize;
v.resize(maxSize);
top = -1;
}
void push(int x) {
if ((top+1) < size) {
v[++top] = {x, 0};
}
}
int pop() {
if (top == -1) {
return -1;
}
pair<int, int> now = v[top];
int inc = now.second;
int res = now.first + now.second;
top--;
if (top != -1) {
v[top].second += inc;
}
return res;
}
void increment(int k, int val) {
if (top == -1) {
return;
}
int len = min(k-1, top);
v[len].second += val;
}
private:
int size;
vector<pair<int,int>> v;
int top;
};
/**
* Your CustomStack object will be instantiated and called as such:
* CustomStack* obj = new CustomStack(maxSize);
* obj->push(x);
* int param_2 = obj->pop();
* obj->increment(k,val);
*
| true |
19e1b08f9f98aabc9dac08ffd55a84f10799cf4b | C++ | kylemarino22/droneProject | /Testing/encoderTesting/MotorController/MotorController.cpp | UTF-8 | 997 | 3.109375 | 3 | [] | no_license |
#include "MotorController.h"
MotorController::MotorController() {}
void MotorController::setup(int id, int motorPin){
this->id = id;
motor.attach(motorPin);
char rx_byte;
Serial.println("Initialize Motors?");
while(1) {
//waiting for serial response
if (Serial.available() > 0) {
rx_byte = Serial.read();
if (rx_byte == 'y') {
Serial.println("Initializing motors");
initializeMotor();
break;
}
else {
Serial.println("Not initializing motors");
break;
}
}
}
motor.writeMicroseconds(1000);
delay(100);
}
void MotorController::initializeMotor() {
motor.writeMicroseconds(2000);
delay(2000);
motor.writeMicroseconds(1000);
delay(2000);
Serial.println("Initialized Motor");
}
void MotorController::readPair(int address) {
}
void MotorController::setSpeed(double speed) {
} | true |
6cdb2f18da1117395da0dbd6b34b70fcd62449fa | C++ | eugenyvolosenkov/compgraph | /КГ Турлапов/global illumination/PPM/src/ray.hxx | WINDOWS-1251 | 1,009 | 2.90625 | 3 | [
"MIT"
] | permissive | #ifndef __RAY_HXX__
#define __RAY_HXX__
#include <vector>
#include <cmath>
#include "math.hxx"
//////////////////////////////////////////////////////////////////////////
// Ray casting
struct Ray
{
Ray()
{}
Ray(const Vec3f& aOrg,
const Vec3f& aDir,
float aTMin
) :
org(aOrg),
dir(aDir),
tmin(aTMin)
{}
Vec3f org; //
Vec3f dir; //
float tmin; //
};
struct Isect
{
Isect()
{}
Isect(float aMaxDist):dist(aMaxDist)
{}
float dist; //
int matID; // ID
int lightID; // ID ( < 0, )
Vec3f normal; //
};
#endif //__RAY_HXX__
| true |
5e579e99ec6450830e7ce0f49bc3cf1e80b3c95a | C++ | bloomberg/bde | /groups/bal/balber/balber_berutil.h | UTF-8 | 299,915 | 2.609375 | 3 | [
"Apache-2.0"
] | permissive | // balber_berutil.h -*-C++-*-
#ifndef INCLUDED_BALBER_BERUTIL
#define INCLUDED_BALBER_BERUTIL
#include <bsls_ident.h>
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide functions to encode and decode simple types in BER format.
//
//@CLASSES:
// balber::BerUtil: namespace of utility functions for BER
//
//@SEE_ALSO: balber_berencoder, balber_berdecoder
//
//@DESCRIPTION: This component provides utility functions for encoding and
// decoding of primitive BER constructs, such as tag identifier octets, length
// octets, fundamental C++ types. The encoding and decoding of 'bsl::string'
// and BDE date/time types is also implemented.
//
// These utility functions operate on 'bsl::streambuf' for buffer management.
//
// More information about BER constructs can be found in the BER specification
// (X.690). A copy of the specification can be found at the URL:
//: o http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
//
// Note that this is a low-level component that only encodes and decodes
// primitive constructs. Clients should use the 'balber_berencoder' and
// 'balber_berdecoder' components (which use this component in the
// implementation) to encode and decode well-formed BER messages.
//
///Terminology
///-----------
// The documentation of this component occasionally uses the following
// terminology as shorthand:
//
//: *date-and-time* *type*:
//: A data type provided by BDE for the representation of a date and/or time
//: value. The date-and-time types are: 'bdlt::Date', 'bdlt::DateTz',
//: 'bdlt::Datetime', 'bdlt::DatetimeTz', 'bdlt::Time', and 'bdlt::TimeTz'.
//: Note that under this definition, the time-zone-aware types provided by
//: BDE, such as 'baltzo::LocalDatetime', are not date-and-time types.
//:
//: *date-and-time* *value*:
//: The value associated with an object of a date-and-time type.
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Reading and Writing Identifier Octets
///- - - - - - - - - - - - - - - - - - - - - - - - -
// The following snippets of code illustrate the usage of this component. Due
// to the low-level nature of this component, an extended usage example is not
// necessary.
//
// Suppose we wanted to write the identifier octets for a BER tag having the
// following properties:
//..
// Tag Class: Context-specific
// Tag Type: Primitive
// Tag Number: 31
//..
// According to the BER specification, this should generate two octets
// containing the values 0x9F and 0x1F. The following function demonstrates
// this:
//..
// bdlsb::MemOutStreamBuf osb;
//
// balber::BerConstants::TagClass tagClass =
// balber::BerConstants::e_CONTEXT_SPECIFIC;
// balber::BerConstants::TagType tagType =
// balber::BerConstants::e_PRIMITIVE;
// int tagNumber = 31;
//
// int retCode = balber::BerUtil::putIdentifierOctets(&osb,
// tagClass,
// tagType,
// tagNumber);
// assert(0 == retCode);
// assert(2 == osb.length());
// assert(0x9F == (unsigned char)osb.data()[0]);
// assert(0x1F == (unsigned char)osb.data()[1]);
//..
// The next part of the function will read the identifier octets from the
// stream and verify its contents:
//..
// bdlsb::FixedMemInStreamBuf isb(osb.data(), osb.length());
//
// balber::BerConstants::TagClass tagClassIn;
// balber::BerConstants::TagType tagTypeIn;
// int tagNumberIn;
// int numBytesConsumed = 0;
//
// retCode = balber::BerUtil::getIdentifierOctets(&isb,
// &tagClassIn,
// &tagTypeIn,
// &tagNumberIn,
// &numBytesConsumed);
// assert(0 == retCode);
// assert(2 == numBytesConsumed);
// assert(tagClass == tagClassIn);
// assert(tagType == tagTypeIn);
// assert(tagNumber == tagNumberIn);
//..
#include <balscm_version.h>
#include <balber_berconstants.h>
#include <balber_berdecoderoptions.h>
#include <balber_berencoderoptions.h>
#include <bdldfp_decimal.h>
#include <bdlt_date.h>
#include <bdlt_datetime.h>
#include <bdlt_datetimetz.h>
#include <bdlt_datetz.h>
#include <bdlt_iso8601util.h>
#include <bdlt_prolepticdateimputil.h>
#include <bdlt_time.h>
#include <bdlt_timetz.h>
#include <bdlb_float.h>
#include <bdlb_variant.h>
#include <bslmf_assert.h>
#include <bsla_nodiscard.h>
#include <bsla_unreachable.h>
#include <bsls_assert.h>
#include <bsls_platform.h>
#include <bsls_review.h>
#include <bsl_streambuf.h>
#include <bsl_string.h>
#include <bsl_vector.h>
namespace BloombergLP {
namespace balber {
// ==============
// struct BerUtil
// ==============
struct BerUtil {
// This utility contains functions to encode and decode primitive BER
// constructs and simple value semantic types. By convention, all
// functions return 0 on success, and a non-zero value otherwise. Also by
// convention, all the "get" functions take an 'accumNumBytesConsumed';
// each of the functions will add to this variable the number of bytes
// consumed within the scope of the function.
enum {
k_INDEFINITE_LENGTH = -1 // used to indicate that the length is
// indefinite
#ifndef BDE_OMIT_INTERNAL_DEPRECATED
,
BDEM_INDEFINITE_LENGTH = k_INDEFINITE_LENGTH,
INDEFINITE_LENGTH = k_INDEFINITE_LENGTH
#endif // BDE_OMIT_INTERNAL_DEPRECATED
};
// CLASS METHODS
static int getEndOfContentOctets(bsl::streambuf *streamBuf,
int *accumNumBytesConsumed);
// Decode the "end-of-content" octets (two consecutive zero-octets)
// from the specified 'streamBuf' and add the number of bytes consumed
// (which is always 2) to the specified 'accumNumBytesConsumed'.
// Return 0 on success, and a non-zero value otherwise.
static int getIdentifierOctets(
bsl::streambuf *streamBuf,
BerConstants::TagClass *tagClass,
BerConstants::TagType *tagType,
int *tagNumber,
int *accumNumBytesConsumed);
// Decode the identifier octets from the specified 'streamBuf' and load
// the tag class, tag type, and tag number to the specified 'tagClass',
// 'tagType', and 'tagNumber' respectively. Add the number of bytes
// consumed to the specified 'accumNumBytesConsumed'. Return
// 0 on success, and a non-zero value otherwise.
static int getLength(bsl::streambuf *streamBuf,
int *result,
int *accumNumBytesConsumed);
// Decode the length octets from the specified 'streamBuf' and load the
// result to the specified 'result'. If the length is indefinite
// (i.e., contents will be terminated by "end-of-content" octets) then
// 'result' will be set to 'k_INDEFINITE_LENGTH'. Add the number of
// bytes consumed to the specified 'accumNumBytesConsumed'. Return 0
// on success, and a non-zero value otherwise.
template <typename TYPE>
static int getValue(
bsl::streambuf *streamBuf,
TYPE *value,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
// Decode the specified 'value' from the specified 'streamBuf',
// consuming exactly the specified 'length' bytes. Return 0 on
// success, and a non-zero value otherwise. Optionally specify
// decoding 'options' to control aspects of the decoding. Note that
// the value consists of the contents bytes only (no length prefix).
// Also note that only fundamental C++ types, 'bsl::string', and BDE
// date/time types are supported.
template <typename TYPE>
static int getValue(
bsl::streambuf *streamBuf,
TYPE *value,
int *accumNumBytesConsumed,
const BerDecoderOptions& options = BerDecoderOptions());
// Decode the specified 'value' from the specified 'streamBuf' and add
// the number of bytes consumed to the specified
// 'accumNumBytesConsumed'. Return 0 on success, and a non-zero value
// otherwise. Optionally specify decoding 'options' to control aspects
// of the decoding. Note that the value consists of the length and
// contents primitives. Also note that only fundamental C++ types,
// 'bsl::string', and BDE date/time types are supported.
static int putEndOfContentOctets(bsl::streambuf *streamBuf);
// Encode the "end-of-content" octets (two consecutive zero-octets) to
// the specified 'streamBuf'. The "end-of-content" octets act as the
// termination bytes for objects that have indefinite length. Return 0
// on success, and a non-zero value otherwise.
static int putIdentifierOctets(bsl::streambuf *streamBuf,
BerConstants::TagClass tagClass,
BerConstants::TagType tagType,
int tagNumber);
// Encode the identifier octets for the specified 'tagClass', 'tagType'
// and 'tagNumber' to the specified 'streamBuf'. Return 0 on success,
// and a non-zero value otherwise.
static int putIndefiniteLengthOctet(bsl::streambuf *streamBuf);
// Encode the "indefinite-length" octet onto the specified 'streamBuf'.
// This octet signifies that the length of the contents is indefinite
// (i.e., contents will be terminated by end of content octets).
// Return 0 on success, and a non-zero value otherwise.
static int putLength(bsl::streambuf *streamBuf, int length);
// Encode the specified 'length' to the specified 'streamBuf'. Return
// 0 on success, and a non-zero value otherwise. The behavior is
// undefined unless '0 <= length'.
template <typename TYPE>
static int putValue(bsl::streambuf *streamBuf,
const TYPE& value,
const BerEncoderOptions *options = 0);
// Encode the specified 'value' to the specified 'streamBuf'. Return 0
// on success, and a non-zero value otherwise. Note that the value
// consists of the length and contents primitives. Also note that only
// fundamental C++ types, 'bsl::string', 'bslstl::StringRef' and BDE
// date/time types are supported.
};
///Implementation Note
///-------------------
// The following utility structs used in the implementation of 'BerUtil' are
// provided in reverse dependency order. This means that low-level utilities
// appear first, and higher-level utilities later. No utility uses another
// that appears later.
//
// Each utility provides type aliases for the lower-level utilities used in its
// implementation. This set of type aliases also serves as a manifest of the
// utility's dependencies.
// ========================
// struct BerUtil_Constants
// ========================
struct BerUtil_Constants {
// This component-private utility 'struct' provides a namespace for a set
// of constants used to calculate quantities needed by BER encoders and
// decoders. For example, this struct provides a named constant for the
// number of bits in a byte, which is used in downstream calculations.
// TYPES
enum { k_NUM_BITS_PER_OCTET = 8 };
};
// ============================
// struct BerUtil_StreambufUtil
// ============================
struct BerUtil_StreambufUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to perform input and output operations on
// 'bsl::streambuf' objects. Note that these functions are intended to
// adapt the standard stream-buffer operations to a BDE-style interface.
// CLASS METHODS
static int peekChar(char *value, bsl::streambuf *streamBuf);
// Read the next byte from the specified 'streamBuf' without advancing
// the read position and load that byte into the specified 'value'.
// Return 0 on success, and a non-zero value otherwise. If this
// operation is not successful, the value of '*value' is unchanged.
// This operation fails if the input sequence of 'streamBuf' is at its
// end.
static int getChars(char *buffer,
bsl::streambuf *streamBuf,
int bufferLength);
// Read the specified 'bufferLength' number of bytes from the input
// sequence of the specified 'streamBuf', as if by a call to
// 'streamBuf->sgetn(buffer, bufferLength)', and load the bytes into
// successive elements of the specified 'buffer', starting at the first
// element. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if 'length' bytes are successfully read from the
// input sequence of the 'streamBuf' without the read position becoming
// unavailable. If less than 'bufferLength' bytes are read, the number
// of bytes loaded into 'buffer' is not specified. The behavior is
// undefined unless '0 <= bufferLength' and 'buffer' is the address of
// a sequence of at least 'bufferLength' bytes.
static int putChars(bsl::streambuf *streamBuf,
const char *buffer,
int bufferLength);
// Write the first specified 'bufferLength' number of bytes from the
// specified 'buffer' to the specified 'streamBuf', as if by a call to
// 'streamBuf->sputn(buffer, bufferLength)'. Return 0 on success, and
// a non-zero value otherwise.
};
// ================================
// struct BerUtil_IdentifierImpUtil
// ================================
struct BerUtil_IdentifierImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER identifier octet
// encoding and decoding.
// TYPES
typedef BerUtil_Constants Constants;
// 'Constants' is an alias to a namespace for a suite of
// general-purpose constants that occur when encoding or decoding BER
// data.
private:
// PRIVATE TYPES
enum {
k_TAG_CLASS_MASK = 0xC0, // 0xC0 = 0b1100'0000
k_TAG_TYPE_MASK = 0x20, // 0x20 = 0b0010'0000
k_TAG_NUMBER_MASK = 0x1F, // 0x1F = 0b0001'1111
// The first octet in a sequence of one or more BER identifier
// octets encodes 3 quantities: the tag class, the tag type, and
// the leading bits of the tag number. These quantities are
// encoded according to the packing suggested by the above 3 masks.
k_MAX_TAG_NUMBER_IN_ONE_OCTET = 30,
// The last 5 bits of the first octet in a sequence of one or more
// BER identifier octets encodes one of 32 different values.
// Values 0 through 30 indicate the tag number of the contents is
// the corresponding value. The value 31 indicates that the next
// octet is the first byte in a possibly multi-byte encoding of an
// 8-bit VLQ.
k_NUM_VALUE_BITS_IN_TAG_OCTET = 7,
// BER identifier octets (after the first octet) encode an 8-bit
// VLQ unsigned integer value that indicates the tag number of the
// contents. The most significant bit of this octet indicates
// whether or not the octet is the last one in the VLQ sequence, or
// if another VLQ octet follows.
k_MAX_TAG_NUMBER_OCTETS =
(sizeof(int) * Constants::k_NUM_BITS_PER_OCTET) /
k_NUM_VALUE_BITS_IN_TAG_OCTET +
1,
// This component restricts the maximum supported number of octets
// used to represent the tag number to 4. This means that there
// are at most '4 * 7 = 28' bits used to encode such a tag number.
k_CHAR_MSB_MASK = 0x80, // 0x80 = 0b1000'0000
// An 8-bit mask for the most significant bit of an octet.
k_SEVEN_BITS_MASK = 0x7F // 0x7F = 0b0111'1111
// An 8-bit mask for all but the most significant bit of an octet.
};
public:
// CLASS METHODS
static int getIdentifierOctets(
BerConstants::TagClass *tagClass,
BerConstants::TagType *tagType,
int *tagNumber,
int *accumNumBytesConsumed,
bsl::streambuf *streamBuf);
// Decode the identifier octets from the specified 'streamBuf' and load
// the tag class, tag type, and tag number to the specified 'tagClass',
// 'tagType', and 'tagNumber', respectively. Add the number of bytes
// consumed to the specified 'accumNumBytesConsumed'. Return 0 on
// success, and a non-zero value otherwise.
static int putIdentifierOctets(bsl::streambuf *streamBuf,
BerConstants::TagClass tagClass,
BerConstants::TagType tagType,
int tagNumber);
// Encode the identifier octets for the specified 'tagClass', 'tagType'
// and 'tagNumber', in that order, to the specified 'streamBuf'.
// Return 0 on success, and a non-zero value otherwise.
};
// ================================
// struct BerUtil_RawIntegerImpUtil
// ================================
struct BerUtil_RawIntegerImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER integer encoding. This
// 'struct' is separate from 'BerUtil_IntegerImpUtil' to break a dependency
// cycle between 'BerUtil_IntegerImpUtil' and 'BerUtil_LengthImpUtil'.
// TYPES
typedef BerUtil_Constants Constants;
// 'Constants' is an alias to a namespace for a suite of
// general-purpose constants that occur when encoding or decoding BER
// data.
// CLASS METHODS
template <class INTEGRAL_TYPE>
static int putIntegerGivenLength(bsl::streambuf *streamBuf,
INTEGRAL_TYPE value,
int length);
// Encode the octets used in the BER encoding of the specified 'value'
// of the specified 'INTEGRAL_TYPE' to the specified 'streamBuf', using
// exactly the specified 'length' number of octets. Return 0 on
// success, and a non-zero value otherwise. The behavior is undefined
// unless 'INTEGRAL_TYPE' is fundamental integral type and exactly
// 'length' number of octets is used in the BER encoding of the
// specified 'value'.
};
// ============================
// struct BerUtil_LengthImpUtil
// ============================
struct BerUtil_LengthImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER length quantity encoding
// and decoding.
// TYPES
typedef BerUtil_Constants Constants;
// 'Constants' is an alias to a namespace for a suite of
// general-purpose constants that occur when encoding or decoding BER
// data.
typedef BerUtil_RawIntegerImpUtil RawIntegerUtil;
// 'RawIntegerUtil' is an alias to a namespace for a suite of functions
// used to implement integer encoding.
private:
// PRIVATE TYPES
enum {
k_INDEFINITE_LENGTH = -1,
// constant used to indicate that a calculated length quantity is
// indefinite
k_INDEFINITE_LENGTH_OCTET = 0x80, // 0x80 = 0b1000'0000
// value of the (singular) length octet used to indicate that
// the length of a sequence of BER octets will be determined by
// seeking forward until and end-of-contents pair of octets is
// encountered
k_LONG_FORM_LENGTH_FLAG_MASK = 0x80, // 0x80 = 0b1000'0000
// mask used to determine if the higher-order bit of a length
// octet indicates that the next octet in the sequence is part of
// the VLQ-encoding of the length or if the current octet is the
// final octet of the length octets
k_LONG_FORM_LENGTH_VALUE_MASK = 0x7F // 0x7F = 0b0111'1111
// mask used to retrieve the bits of a non-final length octet
// that contribute to the BLQ-encoding of the length
};
public:
// CLASS METHODS
// Length Decoding Functions
static int getLength(int *result,
int *accumNumBytesConsumed,
bsl::streambuf *streamBuf);
// Decode the length octets from the specified 'streamBuf' and load the
// result to the specified 'result'. If the length is indefinite
// (i.e., contents will be terminated by "end-of-content" octets) then
// 'result' will be set to 'k_INDEFINITE_LENGTH'. Add the number of
// bytes consumed to the specified 'accumNumBytesConsumed'. Return 0
// on success, and a non-zero value otherwise.
static int getEndOfContentOctets(int *accumNumBytesConsumed,
bsl::streambuf *streamBuf);
// Decode the "end-of-content" octets (two consecutive zero-octets)
// from the specified 'streamBuf' and add the number of bytes consumed
// (which is always 2) to the specified 'accumNumBytesConsumed'.
// Return 0 on success, and a non-zero value otherwise.
// Length Encoding Functions
static int putLength(bsl::streambuf *streamBuf, int length);
// Encode the specified 'length' length octets to the specified
// 'streamBuf'. Return 0 on success, and a non-zero value otherwise.
// The behavior is undefined unless '0 <= length'.
static int putIndefiniteLengthOctet(bsl::streambuf *streamBuf);
// Encode the "indefinite-length" octet onto the specified 'streamBuf'.
// This octet signifies that the length of the contents is indefinite
// (i.e., contents will be terminated by end of content octets).
// Return 0 on success, and a non-zero value otherwise.
static int putEndOfContentOctets(bsl::streambuf *streamBuf);
// Encode the identifier octets for the specified 'tagClass', 'tagType'
// and 'tagNumber' to the specified 'streamBuf'. Return 0 on success,
// and a non-zero value otherwise.
};
// =============================
// struct BerUtil_BooleanImpUtil
// =============================
struct BerUtil_BooleanImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER encoding and decoding
// operations for boolean values. Within the definition of this 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690.
// TYPES
typedef BerUtil_LengthImpUtil LengthUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
// CLASS METHODS
// Decoding
static int getBoolValue(bool *value,
bsl::streambuf *streamBuf,
int length);
// Decode to the specified 'value' from the specified 'streamBuf',
// consuming exactly the specified 'length' bytes. Return 0 on
// success, and a non-zero value otherwise. This operations succeeds
// if 'length' bytes are successfully read from the 'streamBuf' and
// they contain a valid representation of the contents octets for a
// BER-encoded boolean value according to the specification.
// Encoding
static int putBoolValue(bsl::streambuf *streamBuf, bool value);
// Encode the specified 'value' to the specified 'streamBuf'. Return 0
// on success and a non-zero value otherwise. The 'value' is encoded
// as the sequence of contents octets for a BER-encoded boolean value
// according to the specification. This operation succeeds if all of
// the contents octets are successfully written to the 'streamBuf'.
};
// =============================
// struct BerUtil_IntegerImpUtil
// =============================
struct BerUtil_IntegerImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER encoding and decoding
// operations for integer values. Within the definition of this 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690.
// TYPES
typedef BerUtil_Constants Constants;
// 'Constants' is an alias to a namespace for a suite of
// general-purpose constants that occur when encoding or decoding BER
// data.
typedef BerUtil_LengthImpUtil LengthImpUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
typedef BerUtil_RawIntegerImpUtil RawIntegerUtil;
// 'RawIntegerUtil' is an alias to a namespace for a suite of low-level
// functions used to implement BER encoding operations for integer
// values.
typedef BerUtil_StreambufUtil StreambufUtil;
// 'StreambufUtil' is an alias to a namespace for a suite of functions
// used to implement input and output operations on 'bsl::streambuf'
// objects.
// CLASS DATA
static const int k_40_BIT_INTEGER_LENGTH = 5;
// Number of octets used to encode a signed integer value in 40 bits.
// CLASS METHODS
static int getNumOctetsToStream(short value);
static int getNumOctetsToStream(int value);
static int getNumOctetsToStream(long long value);
// Return the number of octets required to provide a BER encoding of
// the specified 'value' according to the specification.
template <class INTEGRAL_TYPE>
static int getNumOctetsToStream(INTEGRAL_TYPE value);
// Return the number of octets required to provide a BER encoding of
// the specified 'value' according to the specification. The program
// is ill-formed unless the specified 'INTEGRAL_TYPE' is a fundamental
// integral type.
static int getIntegerValue(long long *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the contents octets of a
// BER-encoded integer value according to the specification. Return 0
// if successful, and a non-zero value otherwise.
template <class INTEGRAL_TYPE>
static int getIntegerValue(INTEGRAL_TYPE *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the contents octets of BER-encoded
// integer value according to the specification. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes read contain a valid representation of the contents octets
// of an integer value according to the specification. The program is
// ill-formed unless the specified 'INTEGRAL_TYPE' is a fundamental
// integral type.
static int get40BitIntegerValue(bsls::Types::Int64 *value,
bsl::streambuf *streamBuf);
// Read 5 bytes from the input sequence of the specified 'streamBuf'
// and load to the specified 'value' the interpretation of those bytes
// as a 40-bit, signed, 2's-complement, big-endian integer. Return 0
// if successful, and a non-zero value otherwise. The operation
// succeeds if all 5 bytes are successfully read from the input
// sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes read contain a valid representation of a
// 40-bit, signed, 2's-complement, big-endian integer.
template <class INTEGRAL_TYPE>
static int putIntegerValue(bsl::streambuf *streamBuf, INTEGRAL_TYPE value);
// Write the length and contents octets of the BER encoding of the
// specified integer 'value' (as defined in the specification) to the
// output sequence of the specified 'streamBuf'. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if all bytes corresponding to the length and contents octets are
// written to the 'streamBuf' without the write position becoming
// unavailable. The program is ill-formed unless the specified
// 'INTEGRAL_TYPE' is a fundamental integral type.
static int put40BitIntegerValue(bsl::streambuf *streamBuf,
bsls::Types::Int64 value);
// Write the 5 octets that comprise the 40-bit, signed, 2's-complement,
// bit-endian representation of the specified integer 'value' to the
// specified 'streamBuf'. Return 0 if successful, and a non-zero value
// otherwise. The operation succeeds if all bytes corresponding to the
// representation of the 'value' are written to the 'streamBuf' without
// the write position becoming unavailable. The behavior is undefined
// unless the 'value' is in the half-open interval
// '[-549755813888, 549755813888)'.
template <class INTEGRAL_TYPE>
static int putIntegerGivenLength(bsl::streambuf *streamBuf,
INTEGRAL_TYPE value,
int length);
// Write exactly the specified 'length' number of contents octets of
// the BER encoding of the specified integer 'value' (as defined in the
// specification) to the output sequence of the specified 'streamBuf'.
// Return 0 if successful, and a non-zero value otherwise. The
// operation succeeds if all bytes corresponding to the contents octets
// are written to the 'streamBuf' without the write position becoming
// unavailable. The behavior is undefined unless there are exactly
// 'length' number of contents octets used to encode the integer
// 'value' according to the specification. The program is ill-formed
// unless the specified 'INTEGRAL_TYPE' is a fundamental integral type.
};
// ===============================
// struct BerUtil_CharacterImpUtil
// ===============================
struct BerUtil_CharacterImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER encoding and decoding
// operations for byte values. Within the definition of this 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690.
// TYPES
typedef BerUtil_IntegerImpUtil IntegerUtil;
// 'IntegerUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for integer
// values.
typedef BerUtil_LengthImpUtil LengthUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
// CLASS METHODS
// Decoding
static int getCharValue(char *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the value of the contents octets of
// a BER-encoded integer according to the specification. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes read contain a valid representation of the contents octets
// of an integer value according to the specification. Note that the
// signedness of the interpreted integer value is the same as the
// signedness of 'char' according to the current platform.
static int getSignedCharValue(signed char *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the value of the contents octets of
// a BER-encoded integer according to the specification. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes read contain a valid representation of the contents octets
// of an integer value according to the specification.
static int getUnsignedCharValue(unsigned char *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the value of the contents octets of
// a BER-encoded integer according to the specification. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes read contain a valid representation of the contents octets
// of an integer value according to the specification.
// Encoding
static int putCharValue(bsl::streambuf *streamBuf, char value);
// Write the length and contents octets of the BER encoding of the
// specified integer 'value' (as defined in the specification) to the
// output sequence of the specified 'streamBuf'. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if all bytes corresponding to the length and contents octets are
// written to the 'streamBuf' without the write position becoming
// unavailable.
static int putSignedCharValue(bsl::streambuf *streamBuf,
signed char value);
// Write the length and contents octets of the BER encoding of the
// specified integer 'value' (as defined in the specification) to the
// output sequence of the specified 'streamBuf'. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if all bytes corresponding to the length and contents octets are
// written to the 'streamBuf' without the write position becoming
// unavailable.
static int putUnsignedCharValue(bsl::streambuf *streamBuf,
unsigned char value);
// Write the length and contents octets of the BER encoding of the
// specified integer 'value' (as defined in the specification) to the
// output sequence of the specified 'streamBuf'. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if all bytes corresponding to the length and contents octets are
// written to the 'streamBuf' without the write position becoming
// unavailable.
};
// ===================================
// struct BerUtil_FloatingPointImpUtil
// ===================================
struct BerUtil_FloatingPointImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER encoding and decoding
// operations for floating point number values. Within the definition of
// this 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690,
//: and
//:
//: *the* *floating* *point* *specification*:
//: Refers to the 2008 revision of the IEE 754 Standard for
//: Floating-Point Arithemtic.
// TYPES
typedef BerUtil_IntegerImpUtil IntegerUtil;
// 'IntegerUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for integer
// values.
typedef BerUtil_LengthImpUtil LengthUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
private:
// PRIVATE TYPES
enum {
k_MAX_MULTI_WIDTH_ENCODING_SIZE = 8,
k_BINARY_NEGATIVE_NUMBER_ID = 0xC0,
k_BINARY_POSITIVE_NUMBER_ID = 0x80,
k_REAL_BINARY_ENCODING = 0x80,
k_DOUBLE_EXPONENT_SHIFT = 52,
k_DOUBLE_OUTPUT_LENGTH = 10,
k_DOUBLE_EXPONENT_MASK_FOR_TWO_BYTES = 0x7FF,
k_DOUBLE_NUM_EXPONENT_BITS = 11,
k_DOUBLE_NUM_MANTISSA_BITS = 52,
k_DOUBLE_NUM_EXPONENT_BYTES = 2,
k_DOUBLE_NUM_MANTISSA_BYTES = 7,
k_DOUBLE_BIAS = 1023,
k_POSITIVE_ZERO_LEN = 0,
k_NEGATIVE_ZERO_LEN = 1,
k_POSITIVE_INFINITY_ID = 0x40,
k_NEGATIVE_INFINITY_ID = 0x41,
k_NAN_ID = 0x42,
k_NEGATIVE_ZERO_ID = 0x43,
k_DOUBLE_INFINITY_EXPONENT_ID = 0x7FF,
k_INFINITY_MANTISSA_ID = 0,
k_REAL_SIGN_MASK = 0x40, // 0x40 = 0b0100'0000
k_REAL_BASE_MASK = 0x20, // 0x20 = 0b0010'0000
k_REAL_SCALE_FACTOR_MASK = 0x0C, // 0x0C = 0b0000'1100
k_REAL_EXPONENT_LENGTH_MASK = 0x03, // 0x03 = 0b0000'0011
k_BER_RESERVED_BASE = 3,
k_REAL_BASE_SHIFT = 4,
k_REAL_SCALE_FACTOR_SHIFT = 2,
k_REAL_MULTIPLE_EXPONENT_OCTETS = 4
};
// PRIVATE CLASS METHODS
// Utilities
static void assembleDouble(double *value,
long long exponent,
long long mantissa,
int sign);
// Load to the specified 'value' the value of the "binary64" object
// having the specified 'exponent' value, the bits of the specified
// 'mantissa' interpreted as the digits of the mantissa, and the value
// of the specified 'sign' interpreted as the sign bit, according to
// the floating point specification. The behavior is undefined unless
// 'exponent' is in the range '[-1023, 1023]', 'mantissa' is in the
// range '[-9007199254740991, 9007199254740991]', and 'sign' is 0 or 1.
// The program is ill-formed unless the platform uses the "binary64"
// interchange format encoding defined in the floating point
// specification as the object representation for 'double' values.
static void normalizeMantissaAndAdjustExp(long long *mantissa,
int *exponent,
bool denormalized);
// Normalize the specified '*mantissa' value by adjusting the implicit
// decimal point to after the rightmost 1 bit in the mantissa. If
// 'false == denormalized' prepend the implicit 1 in the mantissa
// before adjusting the implicit decimal point. Multiply the
// '*exponent' value by 2 to the power of the number of places the
// implicit decimal point moves.
static void parseDouble(int *exponent,
long long *mantissa,
int *sign,
double value);
// Parse the specified 'value' and populate the specified 'exponent',
// 'mantissa', and 'sign' values from the exponent, mantissa, and sign
// of the 'value', respectively.
public:
// CLASS METHODS
// Decoding
static int getFloatValue(float *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the contents octets of a
// BER-encoded real value according to the specification. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes read contain a valid representation of the contents octets
// of a real value according to the specification.
static int getDoubleValue(double *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the contents octets of a
// BER-encoded real value according to the specification. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes read contain a valid representation of the contents octets
// of a real value according to the specification.
static int getDecimal64Value(bdldfp::Decimal64 *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the contents octets of an encoded
// 64-bit decimal value. Return 0 if successful, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes read contain a
// valid representation of the contents octets of an encoded 64-bit
// decimal value. See the package-level documentation of {'balber'}
// for the definition of the format used to encode 64-bit decimal
// values.
// Encoding
static int putFloatValue(bsl::streambuf *streamBuf,
float value,
const BerEncoderOptions *options = 0);
// Write the length and contents octets of the BER encoding of the
// specified real 'value' (as defined in the specification) to the
// output sequence of the specified 'streamBuf'. Optionally specify
// 'options', which will indicate whether '-0.0f' will be preserved or
// encoded as '+0.0f'. Return 0 if successful, and a non-zero value
// otherwise. The operation succeeds if all bytes corresponding to the
// length and contents octets are written to the 'streamBuf' without
// the write position becoming unavailable.
static int putDoubleValue(bsl::streambuf *streamBuf,
double value,
const BerEncoderOptions *options = 0);
// Write the length and contents octets of the BER encoding of the
// specified real 'value' (as defined in the specification) to the
// output sequence of the specified 'streamBuf'. Optionally specify
// 'options', which will indicate whether '-0.0' will be preserved or
// encoded as '+0.0'. Return 0 if successful, and a non-zero value
// otherwise. The operation succeeds if all bytes corresponding to the
// length and contents octets are written to the 'streamBuf' without
// the write position becoming unavailable.
static int putDecimal64Value(bsl::streambuf *streamBuf,
bdldfp::Decimal64 value);
// Write the length and contents octets of the encoding of the BER
// encoding of the specified 'value' to the output sequence of the
// specified 'streamBuf'. Return 0 if successful, and a non-zero value
// otherwise. The operation succeeds if all bytes corresponding to the
// length and contents octets are written to the 'streamBuf' without
// the write position becoming unavailable. See the package-level
// documentation of {'balber'} for the definition of the format used to
// encode 64-bit decimal values.
};
// ============================
// struct BerUtil_StringImpUtil
// ============================
struct BerUtil_StringImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER encoding and decoding
// operations for string values. Within the definition of this 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690.
// TYPES
typedef BerUtil_LengthImpUtil LengthUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
public:
// CLASS METHODS
// Utilities
static int putRawStringValue(bsl::streambuf *streamBuf,
const char *string,
int stringLength);
// Write the length and contents octets of the BER encoding of the
// specified byte 'string' having the specified 'stringLength' (as
// defined in the specification) to the output sequence of the
// specified 'streamBuf'. Return 0 if successful, and a non-zero value
// otherwise. The operation succeeds if all bytes corresponding to the
// length and contents octets are written to the 'streamBuf' without
// the write position becoming unavailable.
static int putChars(bsl::streambuf *streamBuf, char value, int numChars);
// Write the specified 'numChars' number of bytes having the specified
// 'value' to the output sequence of the specified 'streamBuf'. Return
// 0 if successful, and a non-zero value otherwise. The operation
// succeeds if all 'numChars' bytes are written to the 'streamBuf'
// without the write position becoming unavailable.
// 'bsl::string' Decoding
static int getStringValue(bsl::string *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// interpretation of those bytes as the value of the contents octets of
// a BER-encoded character string (more specifically, an unrestricted
// character string) according to the specification, unless an
// alternate value is indicated by the specified 'options', in which
// case, the alternate value is loaded. If the 'DefaultEmptyStrings'
// attribute of the 'options' is 'true' and the witnessed BER-encoded
// character string represents the empty string value, the alternate
// value is the current '*value', otherwise there is no alternate
// value. Return 0 if successful, and a non-zero value otherwise. The
// operation succeeds if 'length' bytes are successfully read from the
// input sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes read contain a valid representation of
// the contents octets of a character string value according to the
// specification.
// 'bsl::string' Encoding
static int putStringValue(bsl::streambuf *streamBuf,
const bsl::string& value);
// Write the length and contents octets of the BER encoding of the
// specified character string 'value' (as defined in the specification)
// to the output sequence of the specified 'streamBuf'. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if all bytes corresponding to the length and contents octets are
// written to the 'streamBuf' without the write position becoming
// unavailable.
// 'bslstl::StringRef' Encoding
static int putStringRefValue(bsl::streambuf *streamBuf,
const bslstl::StringRef& value);
// Write the length and contents octets of the BER encoding of the
// specified character string 'value' (as defined in the specification)
// to the output sequence of the specified 'streamBuf'. Return 0 if
// successful, and a non-zero value otherwise. The operation succeeds
// if all bytes corresponding to the length and contents octets are
// written to the 'streamBuf' without the write position becoming
// unavailable.
};
// =============================
// struct BerUtil_Iso8601ImpUtil
// =============================
struct BerUtil_Iso8601ImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement BER encoding and decoding
// operations for date and time values in the ISO 8601 format. See the
// component-level documentation of {'bdlt_iso8601util'} for a complete
// description of the ISO 8601 format used by the functions provided by
// this 'struct'.
// TYPES
typedef BerUtil_StringImpUtil StringUtil;
// 'StringUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoder and decoding operations for string
// values.
private:
// PRIVATE CLASS METHODS
template <class TYPE>
static int getValue(TYPE *value, bsl::streambuf *streamBuf, int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// value represented by the interpretation of the bytes as an ISO 8601
// date/time value. The specified 'TYPE' defines the expected ISO 8601
// date/time format, which is the format corresponding to the 'TYPE' as
// specified in {'bdlt_iso8601util'}. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of the expected ISO 8601
// date/time format. The program is ill-formed unless 'TYPE' is one
// of: 'bdlt::Date', 'bdlt::DateTz', 'bdlt::Datetime',
// 'bdlt::DatetimeTz', 'bdlt::Time', or 'bdlt::TimeTz'.
template <class TYPE>
static int putValue(bsl::streambuf *streamBuf,
const TYPE& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf'. If the specified
// 'options' is 0, use 3 decimal places of fractional second precision,
// otherwise use the number of decimal places specified by the
// 'datetimeFractionalSecondPrecision' attribute of the 'options'.
// Return 0 on success and a non-zero value otherwise. The operation
// succeeds if all bytes of the ISO 8601 representation of the 'value'
// are written to the 'streamBuf' without the write position becoming
// unavailable. The program is ill-formed unless 'TYPE' is one of
// 'bdlt::Date', 'bdlt::DateTz', 'bdlt::Datetime', 'bdlt::DatetimeTz',
// 'bdlt::Time', or 'bdlt::TimeTz'.
public:
// CLASS METHODS
// Decoding
static int getDateValue(bdlt::Date *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 date. Return 0 on success, and a non-zero value otherwise.
// The operation succeeds if 'length' bytes are successfully read from
// the input sequence of the 'streamBuf' without the read position
// becoming unavailable, and the bytes contain a valid representation
// of an ISO 8601 date.
static int getDateTzValue(bdlt::DateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 date and time zone. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of an ISO 8601 date and time zone.
static int getDatetimeValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 date and time. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of an ISO 8601 date and time.
static int getDatetimeTzValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 date, time, and time zone. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if 'length' bytes
// are successfully read from the input sequence of the 'streamBuf'
// without the read position becoming unavailable, and the bytes
// contain a valid representation of an ISO 8601 date, time, and time
// zone.
static int getTimeValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 time. Return 0 on success, and a non-zero value otherwise.
// The operation succeeds if 'length' bytes are successfully read from
// the input sequence of the 'streamBuf' without the read position
// becoming unavailable, and the bytes contain a valid representation
// of an ISO 8601 time.
static int getTimeTzValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 time and time zone. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of an ISO 8601 time and time zone.
// Encoding
static int putDateValue(bsl::streambuf *streamBuf,
const bdlt::Date& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf'. Return 0 on success
// and a non-zero value otherwise. The operation succeeds if all bytes
// of the ISO 8601 representation of the 'value' are written to the
// 'streamBuf' without the write position becoming unavailable.
static int putDateTzValue(bsl::streambuf *streamBuf,
const bdlt::DateTz& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf'. Return 0 on success
// and a non-zero value otherwise. The operation succeeds if all bytes
// of the ISO 8601 representation of the 'value' are written to the
// 'streamBuf' without the write position becoming unavailable.
static int putDatetimeValue(bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf'. If the specified
// 'options' is 0, use 3 decimal places of fractional second precision,
// otherwise use the number of decimal places specified by the
// 'datetimeFractionalSecondPrecision' attribute of the 'options'.
// Return 0 on success and a non-zero value otherwise. The operation
// succeeds if all bytes of the ISO 8601 representation of the 'value'
// are written to the 'streamBuf' without the write position becoming
// unavailable.
static int putDatetimeTzValue(bsl::streambuf *streamBuf,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf'. If the specified
// 'options' is 0, use 3 decimal places of fractional second precision,
// otherwise use the number of decimal places specified by the
// 'datetimeFractionalSecondPrecision' attribute of the 'options'.
// Return 0 on success and a non-zero value otherwise. The operation
// succeeds if all bytes of the ISO 8601 representation of the 'value'
// are written to the 'streamBuf' without the write position becoming
// unavailable.
static int putTimeValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf'. If the specified
// 'options' is 0, use 3 decimal places of fractional second precision,
// otherwise use the number of decimal places specified by the
// 'datetimeFractionalSecondPrecision' attribute of the 'options'.
// Return 0 on success and a non-zero value otherwise. The operation
// succeeds if all bytes of the ISO 8601 representation of the 'value'
// are written to the 'streamBuf' without the write position becoming
// unavailable.
static int putTimeTzValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf'. If the specified
// 'options' is 0, use 3 decimal places of fractional second precision,
// otherwise use the number of decimal places specified by the
// 'datetimeFractionalSecondPrecision' attribute of the 'options'.
// Return 0 on success and a non-zero value otherwise. The operation
// succeeds if all bytes of the ISO 8601 representation of the 'value'
// are written to the 'streamBuf' without the write position becoming
// unavailable.
};
// ====================================
// struct BerUtil_TimezoneOffsetImpUtil
// ====================================
struct BerUtil_TimezoneOffsetImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions and constants used by 'BerUtil' to encode and decode
// time-zone values.
// TYPES
enum {
k_MIN_OFFSET = -1439,
// The minimum number of minutes in a valid time-zone offset
k_MAX_OFFSET = 1439,
// The maximum number of minutes in a valid time-zone offset
k_TIMEZONE_LENGTH = 2
// The number of octets used in the encoding of a time-zone offset
// value. This number is constant: all time-zone values are
// encoded using 2 octets regardless of numeric value.
};
// CLASS METHODS
static bool isValidTimezoneOffsetInMinutes(int value);
// Return 'true' if the specified 'value' is a valid time-zone offset,
// and return 'false' otherwise. A time-zone offset is valid if it is
// greater than or equal to 'k_MIN_OFFSET' and less than or equal to
// 'k_MAX_OFFSET'.
static int getTimezoneOffsetInMinutes(int *value,
bsl::streambuf *streamBuf);
// Read from the specified 'streamBuf' and load to the specified
// 'value' of the time-zone offset.
static int getTimezoneOffsetInMinutesIfValid(int *value,
bsl::streambuf *streamBuf);
// Read a time zone offset value from the specified 'streamBuf'. If
// the offset is greater than or equal to 'k_MIN_OFFSET' and less than
// or equal to 'k_MAX_OFFSET' then load the value of the offset to the
// specified 'value' and return zero, otherwise do not modify the value
// addressed by 'value' and return non-zero.
static int putTimezoneOffsetInMinutes(bsl::streambuf *streamBuf,
int value);
// Write to the specified 'streamBuf' the value of the specified
// time-zone offset 'value'. The behavior is undefined unless
// 'k_MIN_OFFSET <= value' and 'value <= k_MAX_OFFSET'.
};
// ==================================
// struct BerUtil_DateAndTimeEncoding
// ==================================
struct BerUtil_DateAndTimeEncoding {
// This component-private 'struct' provides a namespace for enumerating the
// union of the sets of date and time formats used to encode and decode all
// date and time types supported by 'BerUtil'.
// TYPES
enum Value {
e_ISO8601_DATE,
e_ISO8601_DATETZ,
e_ISO8601_DATETIME,
e_ISO8601_DATETIMETZ,
e_ISO8601_TIME,
e_ISO8601_TIMETZ,
e_COMPACT_BINARY_DATE,
e_COMPACT_BINARY_DATETZ,
e_COMPACT_BINARY_DATETIME,
e_COMPACT_BINARY_DATETIMETZ,
e_COMPACT_BINARY_TIME,
e_COMPACT_BINARY_TIMETZ,
e_EXTENDED_BINARY_DATETIME,
e_EXTENDED_BINARY_DATETIMETZ,
e_EXTENDED_BINARY_TIME,
e_EXTENDED_BINARY_TIMETZ
};
// TYPES
enum {
k_EXTENDED_BINARY_MIN_BDE_VERSION = 35500
// the minimum BDE version number in which this component supports
// encoding and decoding date and time types using their
// respective extended-binary-encoding formats.
};
};
// =========================================
// struct BerUtil_ExtendedBinaryEncodingUtil
// =========================================
struct BerUtil_ExtendedBinaryEncodingUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to determine if a particular date and/or
// time value should be encoded using its corresponding
// extended-binary-encoding format, its corresponding
// compact-binary-encoding format, or neither format.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
// CLASS METHODS
static bool useExtendedBinaryEncoding(const bdlt::Time& value,
const BerEncoderOptions *options);
static bool useExtendedBinaryEncoding(const bdlt::TimeTz& value,
const BerEncoderOptions *options);
static bool useExtendedBinaryEncoding(const bdlt::Datetime& value,
const BerEncoderOptions *options);
static bool useExtendedBinaryEncoding(const bdlt::DatetimeTz& value,
const BerEncoderOptions *options);
// Return 'true' if the specified 'value' must be encoded using its
// corresponding extended-binary-encoding format according to the
// specified 'options', and return 'false' otherwise.
static bool useBinaryEncoding(const BerEncoderOptions *options);
// Return 'true' if a date and/or time value must be encoded using
// either its corresponding extended-binary-encoding format or its
// corresponding compact-binary-encoding format according to the
// specified 'options', and return 'false' otherwise. Note that, for
// any given 'value' and 'options', the 'value' must be encoded using
// its corresponding compact-binary-encoding format if
// 'useExtendedBinaryEncoding(value, options)' returns 'false' and
// 'useBinaryEncoding(options)' returns 'true'.
};
// ====================================
// struct BerUtil_DateAndTimeHeaderType
// ====================================
struct BerUtil_DateAndTimeHeaderType {
// This component-private 'struct' provides a namespace for enumerating the
// set of "header type" values that may be encoded in the 2-byte header of
// an extended-binary-encoding formatted date-and-time value.
// TYPES
enum Value {
e_NOT_EXTENDED_BINARY,
// header-type value that indicates the encoded value is in either
// its corresponding compact-binary encoding or its corresponding
// ISO 8601 encoding
e_EXTENDED_BINARY_WITHOUT_TIMEZONE,
// header-type value that indicates the encoded value is in its
// corresponding extended-binary encoding and does not carry a
// time-zone offset value
e_EXTENDED_BINARY_WITH_TIMEZONE
// header-type value that indicates the encoded value is in its
// corresponding extended-binary encoding and carries a time-zone
// offset value
};
};
// ===============================
// class BerUtil_DateAndTimeHeader
// ===============================
class BerUtil_DateAndTimeHeader {
// This component-private, in-core, value-semantic attribute class provides
// a representation of the information available in the first two bytes of
// any extended-binary-encoding formatted data. All extended-binary
// encoding schemes for date-and-time types contain a 2-byte header in the
// same format, which can be unambiguously distinguished from the first 2
// bytes of a date-and-time type in its corresponding
// compact-binary-encoding format or its ISO 8601 format.
public:
// TYPES
typedef BerUtil_DateAndTimeHeaderType Type;
// 'Type' is an alias to a namespace for enumerating the set of "header
// type" values that may be encoded in the 2-byte header of an
// extended-binary-encoding formatted date-and-time value.
typedef BerUtil_TimezoneOffsetImpUtil TimezoneUtil;
// 'TimezoneUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for time-zone
// offset values.
private:
// DATA
Type::Value d_type;
// date-and-time header type
int d_timezoneOffsetInMinutes;
// offset in minutes from UTC indicated by the date-and-time header if
// the header contains a time-zone offset, and 0 otherwise
public:
// CREATORS
BerUtil_DateAndTimeHeader();
// Create a 'BerUtil_DateAndTimeHeader' object having a 'type'
// attribute with the 'Type::e_NOT_EXTENDED_BINARY' value and a
// 'timezoneOffsetInMinutes' attribute with the 0 value.
//! BerUtil_DateAndTimeHeader(
//! const BerUtil_DateAndTimeHeader& original) = default;
// Create a 'BerUtil_DateAndTimeHeader' object having the same value as
// the specified 'original' object.
//! ~BerUtil_DateAndTimeHeader() = default;
// Destroy this object.
// MANIPULATORS
//! BerUtil_DateAndTimeHeader&
//! operator=(const BerUtil_DateAndTimeHeader& rhs) = default;
// Assign to this object the value of the specified 'rhs' object, and
// return a non-'const' reference to this object.
void makeNotExtendedBinary();
// Set the 'type' attribute of this object to the
// 'Type::e_NOT_EXTENDED_BINARY' value and the
// 'timezoneOffsetInMinutes' attribute of this object to the 0 value.
void makeExtendedBinaryWithoutTimezone();
// Set the 'type' attribute of this object to the
// 'Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE' value and the
// 'timezoneOffsetInMinutes' attribute of this object to the 0 value.
void makeExtendedBinaryWithTimezone(int offset);
// Set the 'type' attribute of this object to the
// 'Type::e_EXTENDED_BINARY_WITH_TIMEZONE' value and the
// 'timezoneOffsetInMinutes' attribute of this object to the specified
// 'offset'. The behavior is undefined unless
// 'TimezoneUtil::k_MIN_OFFSET <= offset' and
// 'TimezoneUtil::k_MAX_OFFSET >= offset'.
// ACCESSORS
bool isExtendedBinary() const;
// Return 'true' if the 'type' attribute of this object is
// 'Type::e_EXTENDED_BINARY_WITH_TIMEZONE' or
// 'Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE', and 'false' otherwise.
bool isExtendedBinaryWithoutTimezone() const;
// Return 'true' if the 'type' attribute of this object is
// 'Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE', and 'false' otherwise.
bool isExtendedBinaryWithTimezone() const;
// Return 'true' if the 'type' attribute of this object is
// 'Type::e_EXTENDED_BINARY_WITH_TIMEZONE', and 'false' otherwise.
int timezoneOffsetInMinutes() const;
// Return the value of the 'timezoneOffsetInMinutes' attribute of this
// object.
};
// =======================================
// struct BerUtil_DateAndTimeHeaderImpUtil
// =======================================
struct BerUtil_DateAndTimeHeaderImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions used by 'BerUtil' to implement encoding and decoding
// operations for the 2-byte header of extended-binary-encoding formatted
// date-and-time value.
// TYPES
typedef BerUtil_DateAndTimeHeader Header;
// 'Header' is an alias to an in-core, value-semantic attribute class
// that represents the range of valid values of the 2-byte header of
// extended-binary-encoding formatted date-and-time values.
typedef BerUtil_DateAndTimeHeaderType Type;
// 'Type' is an alias to a namespace for enumerating the set of "header
// type" values that may be encoded in the 2-byte header of an
// extended-binary-encoding formatted date-and-time value.
typedef BerUtil_StreambufUtil StreambufUtil;
// 'StreambufUtil' is an alias to a namespace for a suite of functions
// used to implement input and output operations on 'bsl::streambuf'
// objects.
typedef BerUtil_TimezoneOffsetImpUtil TimezoneUtil;
// 'TimezoneUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for time-zone
// offset values.
// CLASS DATA
static const int k_HEADER_LENGTH = 2;
// Number of octets used to encode an extended-binary-encoding header.
// CLASS METHODS
static bool isReserved(unsigned char firstByte);
// Return 'true' if the specified 'firstByte' of an encoded
// date-and-time value indicates it is in a format reserved for future
// use, and return 'false' otherwise. Note that this may indicate the
// value was encoded incorrectly or using a newer version of this
// component.
static bool isExtendedBinary(unsigned char firstByte);
// Return 'true' if the specified 'firstByte' of an encoded
// date-and-time value indicates it is in the extended-binary-encoding
// format, and return 'false' otherwise.
static bool isExtendedBinaryWithoutTimezone(unsigned char firstByte);
// Return 'true' if the specified 'firstByte' of an encoded
// date-and-time value indicates it is in the extended-binary-encoding
// format and does not carry a time-zone offset value, and return
// 'false' otherwise.
static bool isExtendedBinaryWithTimezone(unsigned char firstByte);
// Return 'true' if the specified 'firstByte' if an encoded
// date-and-time value indicates is is in the extended-binary-encoding
// format and carries a time-zone offset value, and return 'false'
// otherwise.
static void detectTypeIfNotReserved(bool *reserved,
Type::Value *type,
unsigned char firstByte);
// If the specified 'firstByte' of an encoded date-and-time value
// indicates it is in a compact-binary-encoding format or an ISO 8601
// format, load the value 'Type::e_NOT_EXTENDED_BINARY' to the
// specified 'type' and 'false' to the specified 'reserved' flag. If
// it indicates it is in an extended-binary format that carries a
// time-zone offset value, load the value
// 'Type::e_EXTENDED_BINARY_WITH_TIMEZONE' to the 'type' and 'false' to
// 'reserved'. If it indicates it is in an extended-binary format that
// does not carry a time-zone offset value, load the value
// 'Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE' to the 'type' and 'false'
// to 'reserved'. Otherwise, load the value 'true' to 'reserved' and
// leave the 'type' in a valid but unspecified state. Note that this
// operation has a wide contract because all possible values of
// 'firstByte' can be interpreted to indicate one of the conditions
// described above.
static void detectType(Type::Value *type, unsigned char firstByte);
// If the specified 'firstByte' of an encoded date-and-time value
// indicates it is in a compact-binary-encoding format or an ISO 8601
// format, load the value 'Type::e_NOT_EXTENDED_BINARY' to the
// specified 'type'. If it indicates it is in an extended-binary
// format that carries a time-zone offset value, load the value
// 'Type::e_EXTENDED_BINARY_WITH_TIMEZONE' to the 'type'. If it
// indicates it is in an extended-binary format that does not carry a
// time-zone offset value, load the value
// 'Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE' to the 'type'. The
// behavior is undefined unless 'isReserved(firstByte)' returns
// 'false'.
static int getValueIfNotReserved(Header *value, bsl::streambuf *streamBuf);
// Read 2 bytes from the input sequence of the specified 'streamBuf'
// and load to the specified 'value' the interpretation of those bytes
// as an extended-binary header value, if that header indicates the
// value is not in a format reserved for future use. Return 0 on
// success, and a non-zero value otherwise.
static int getValueIfNotReserved(Header *value,
unsigned char headerByte0,
unsigned char headerByte1);
// Load to the specified 'value' the interpretation of the specified
// 'headerByte0' and 'headerByte1' as the 2 bytes that comprise an
// encoded extended-binary header value if that value indicates it is
// not in a format reserved for future use. Return 0 on success, and a
// non-zero value otherwise.
static int getValue(Header *value, bsl::streambuf *streamBuf);
// Read 2 bytes from the input sequence of the specified 'streamBuf'
// and load to the specified 'value' the interpretation of those bytes
// as an extended-binary header value Return 0 on success, and a
// non-zero value otherwise. The behavior is undefined if 2 bytes are
// successfully read from the 'streamBuf', but the interpretation of
// those bytes as an extended-binary header indicates the value is in a
// format reserved for future use.
static int getValue(Header *value,
unsigned char headerByte0,
unsigned char headerByte1);
// Load to the specified 'value' the interpretation of the specified
// 'headerByte0' and 'headerByte1' as the 2 bytes that comprise an
// encoded extended-binary header value. Return 0 on success, and a
// non-zero value otherwise. The behavior is undefined if the
// interpretation of the 2 bytes as an extended-binary header indicates
// the value is in a format reserved for future use.
static int putExtendedBinaryWithoutTimezoneValue(
bsl::streambuf *streamBuf);
// Write a representation of an extended-binary header value that does
// not carry a time-zone offset value to the specified 'streamBuf'.
// Return 0 on success, and a non-zero value otherwise.
static int putExtendedBinaryWithTimezoneValue(
bsl::streambuf *streamBuf,
int timezoneOffsetInMinutes);
// Write a representation of an extended-binary header value that
// carries the specified 'timezoneOffsetInMinutes' time-zone offset
// value to the specified 'streamBuf'. Return 0 on success, and a
// non-zero value otherwise.
};
// ===========================
// struct BerUtil_DateEncoding
// ===========================
struct BerUtil_DateEncoding {
// This component-private 'struct' provides a namespace for enumerating the
// set of formats that may be used by 'BerUtil' to encode and decode values
// of 'bdlt::Date' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_DATE = Encoding::e_ISO8601_DATE,
e_COMPACT_BINARY_DATE = Encoding::e_COMPACT_BINARY_DATE
};
};
// =============================
// struct BerUtil_DateTzEncoding
// =============================
struct BerUtil_DateTzEncoding {
// This component-private 'struct' provides a namespace for enumerating the
// set of formats that may be used by 'BerUtil' to encode and decode values
// of 'bdlt::DateTz' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_DATETZ = Encoding::e_ISO8601_DATETZ,
e_COMPACT_BINARY_DATE = Encoding::e_COMPACT_BINARY_DATE,
e_COMPACT_BINARY_DATETZ = Encoding::e_COMPACT_BINARY_DATETZ
};
};
// ===================================
// struct BerUtil_DateOrDateTzEncoding
// ===================================
struct BerUtil_DateOrDateTzEncoding {
// This component-private 'struct' provides a namespace for enumerating the
// set of formats that may be used by 'BerUtil' to encode and decode values
// of 'bdlb::Variant2<bdlt::Date, bdlt::DateTz>' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_DATE = Encoding::e_ISO8601_DATE,
e_ISO8601_DATETZ = Encoding::e_ISO8601_DATETZ,
e_COMPACT_BINARY_DATE = Encoding::e_COMPACT_BINARY_DATE,
e_COMPACT_BINARY_DATETZ = Encoding::e_COMPACT_BINARY_DATETZ
};
};
// ==========================
// struct BerUtil_DateImpUtil
// ==========================
struct BerUtil_DateImpUtil {
// This component-private 'struct' provides a namespace for a suite of
// functions used by 'BerUtil' to implement BER encoding and decoding
// operations for date values. Within the definition of this 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690,
//: and
//:
//: *the* *default* *set* *of* *options*:
//: Refers to a 'balber::BerEncoderOptions' value having a
//: 'datetimeFractionalSecondPrecision' attribute of 3 and a
//: 'encodeDateAndTimeTypesAsBinary' attribute of 'false'.
//
// See the package level documentation of {'balber'} for a definition of
// the compact and extended binary formats for date and time values.
// TYPES
typedef BerUtil_DateAndTimeHeaderImpUtil DateAndTimeHeaderUtil;
// 'DateAndTimeHeaderUtil' is an alias to a namespace for a suite of
// functions used to implement encoding and decoding operations for the
// 2-byte header of an extended-binary-encoding formatted date-and-time
// value.
typedef BerUtil_DateEncoding DateEncoding;
// 'DateEncoding' is an alias to a namespace for enumerating the set of
// formats that may be used by 'BerUtil' to encode and decode values of
// 'bdlt::Date' type.
typedef BerUtil_DateTzEncoding DateTzEncoding;
// 'DateEncoding' is an alias to a namespace for enumerating the set of
// formats that may be used by 'BerUtil' to encode and decode values of
// 'bdlt::DateTz' type.
typedef BerUtil_DateOrDateTzEncoding DateOrDateTzEncoding;
// 'DateEncoding' is an alias to a namespace for enumerating the set of
// formats that may be used by 'BerUtil' to decode to values of
// 'bdlb::Variant2<bdlt::Date, bdlt::DateTz>' type.
typedef BerUtil_IntegerImpUtil IntegerUtil;
// 'IntegerUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for integer
// values.
typedef BerUtil_Iso8601ImpUtil Iso8601Util;
// 'Iso8601Util' is an alias to a namespace for a suite of functions
// used to implementing the encoding and decoding of date and time
// values using the ISO 8601 format.
typedef BerUtil_LengthImpUtil LengthUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
typedef BerUtil_StreambufUtil StreambufUtil;
// 'StreambufUtil' is an alias to a namespace for a suite of functions
// used to implement input and output operations on 'bsl::streambuf'
// objects.
typedef BerUtil_StringImpUtil StringUtil;
// 'StringUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for string values.
typedef BerUtil_TimezoneOffsetImpUtil TimezoneUtil;
// 'TimezoneUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for time-zone
// offset values.
typedef bdlb::Variant2<bdlt::Date, bdlt::DateTz> DateOrDateTz;
// 'DateOrDateTz' is a convenient alias for
// 'bdlb::Variant2<bdlt::Date, bdlt::DateTz>'.
enum {
k_COMPACT_BINARY_DATE_EPOCH = 737425
// The serial date of January 1st, 2020. Note that the serial date
// of a date is defined as the number of days between that date and
// January 1st year 1 in the Proleptic Gregorian calendar.
};
private:
// PRIVATE TYPES
enum {
k_MAX_ISO8601_DATE_LENGTH = bdlt::Iso8601Util::k_DATE_STRLEN,
// the maximum number of content octets used by 'BerUtil' to encode
// a date value using the ISO 8601 format
k_MAX_ISO8601_DATETZ_LENGTH = bdlt::Iso8601Util::k_DATETZ_STRLEN,
// the maximum number of content octets used by 'BerUtil' to
// encode a date and time zone value using the ISO 8601 format
k_MAX_COMPACT_BINARY_DATE_LENGTH = 3,
// the maximum number of content octets used by 'BerUtil' to
// encode a date value using the compact-binary format
k_MIN_COMPACT_BINARY_DATETZ_LENGTH =
k_MAX_COMPACT_BINARY_DATE_LENGTH + 1,
// the minimum number of content octets used by 'BerUtil' to
// encode a date and time zone value using the compact-binary
// format
k_MAX_COMPACT_BINARY_DATETZ_LENGTH = 5
// the maximum number of content octets used by 'BerUtil' to
// encode a date and time zone value using the compact-binary
// format
};
// PRIVATE CLASS METHODS
// 'bdlt::Date' Decoding
static int detectDateEncoding(DateEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::Date' value given the specified
// 'length' and 'firstByte' of the encoded representation. Return 0 on
// success, -1 if the format is reserved for future use, and some other
// non-zero value otherwise.
static int getIso8601DateValue(bdlt::Date *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 date. Return 0 on success, and a non-zero value otherwise.
// The operation succeeds if 'length' bytes are successfully read from
// the input sequence of the 'streamBuf' without the read position
// becoming unavailable, and the bytes contain a valid representation
// of an ISO 8601 date.
static int getCompactBinaryDateValue(bdlt::Date *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as a
// compact-binary date. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of a compact-binary date.
// 'bdlt::Date' Encoding
static DateEncoding::Value selectDateEncoding(
const bdlt::Date& value,
const BerEncoderOptions *options);
// Determine the format that should be used to encode the specified
// 'value' given the 'value' and the specified 'options'. If 'options'
// is 0, the default set of options is used. Return an enumerator
// identifying the selected format.
static int putIso8601DateValue(bsl::streambuf *streamBuf,
const bdlt::Date& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if all bytes of the ISO 8601 representation of
// the 'value' are written to the 'streamBuf' without the write
// position becoming unavailable.
static int putCompactBinaryDateValue(bsl::streambuf *streamBuf,
const bdlt::Date& value,
const BerEncoderOptions *options);
// Write the compact-binary date representation of the specified
// 'value' to the output sequence of the specified 'streamBuf'
// according to the specified 'options'. If 'options' is 0, the
// default set of options is used. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if all bytes of the
// compact-binary date representation of the 'value' are written to the
// 'streamBuf' without the write position becoming unavailable.
// 'bdlt::DateTz' Decoding
static int detectDateTzEncoding(DateTzEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::DateTz' value given the specified
// 'length' and 'firstByte' of the encoded representation. Return 0 on
// success, -1 if the format is reserved for future use, and some other
// non-zero value otherwise.
static int getIso8601DateTzValue(bdlt::DateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time zone value represented by the interpretation of the
// read bytes as an ISO 8601 date and time zone. Return 0 on success,
// and a non-zero value otherwise. The operation succeeds if 'length'
// bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of an ISO 8601 date and time
// zone.
static int getCompactBinaryDateValue(bdlt::DateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time zone value represented by the interpretation of the
// read bytes as a compact-binary date. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if 'length' bytes
// are successfully read from the input sequence of the 'streamBuf'
// without the read position becoming unavailable, and the bytes
// contain a valid representation of a compact-binary date.
static int getCompactBinaryDateTzValue(bdlt::DateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time zone value represented by the interpretation of the
// read bytes as a compact-binary date and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a compact-binary date.
// 'bdlt::DateTz' Encoding
static DateTzEncoding::Value selectDateTzEncoding(
const bdlt::DateTz& value,
const BerEncoderOptions *options);
// Determine the format that should be used to encode the specified
// 'value' given the 'value' and the specified 'options'. If 'options'
// is 0, the default set of options is used. Return an enumerator
// identifying the selected format.
static int putIso8601DateTzValue(bsl::streambuf *streamBuf,
const bdlt::DateTz& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if all bytes of the ISO 8601 representation of
// the 'value' are written to the 'streamBuf' without the write
// position becoming unavailable.
static int putCompactBinaryDateValue(bsl::streambuf *streamBuf,
const bdlt::DateTz& value,
const BerEncoderOptions *options);
// Write the compact-binary date representation of the specified
// 'value' to the output sequence of the specified 'streamBuf'
// according to the specified 'options'. If 'options' is 0, the
// default set of options is used. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if all bytes of the
// compact-binary date representation of the 'value' are written to the
// 'streamBuf' without the write position becoming unavailable. The
// behavior is undefined unless the 'offset' of the 'value' is 0.
static int putCompactBinaryDateTzValue(bsl::streambuf *streamBuf,
const bdlt::DateTz& value,
const BerEncoderOptions *options);
// Write the compact-binary date and time zone representation of the
// specified 'value' to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if all bytes of
// the compact-binary date representation of the 'value' are written to
// the 'streamBuf' without the write position becoming unavailable.
// Variant Decoding
static int detectDateOrDateTzEncoding(
DateOrDateTzEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::Date' or 'bdlt::DateTz' value given
// the specified 'length' and 'firstByte' of the encoded
// representation. Return 0 on success, -1 if the format is reserved
// for future use, and some other non-zero value otherwise.
static int getIso8601DateValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 date. Return 0 on success, and a non-zero value otherwise.
// The operation succeeds if 'length' bytes are successfully read from
// the input sequence of the 'streamBuf' without the read position
// becoming unavailable, and the bytes contain a valid representation
// of an ISO 8601 date.
static int getIso8601DateTzValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as an
// ISO 8601 date and time zone. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of an ISO 8601 date and time zone.
static int getCompactBinaryDateValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as a
// compact-binary date. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of a compact-binary date.
static int getCompactBinaryDateTzValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time zone value represented by the interpretation of the
// read bytes as a compact-binary date and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a compact-binary date and
// time zone.
public:
// CLASS METHODS
// Utilities
static void dateToDaysSinceEpoch(bsls::Types::Int64 *daysSinceEpoch,
const bdlt::Date& date);
// Load to the specified 'daysSinceEpoch' the number of days between
// the compact-binary date epoch and the specified 'date'. The
// compact-binary date epoch is the date defined by the
// 'k_COMPACT_BINARY_DATE_EPOCH' serial date. Note that this quantity
// may be negative if the specified 'date' occurs before the
// compact-binary date epoch.
static int daysSinceEpochToDate(bdlt::Date *date,
bsls::Types::Int64 daysSinceEpoch);
// Load to the specified 'date' the date represented by the serial date
// indicated by adding the specified 'daysSinceEpoch' to
// 'k_COMPACT_BINARY_DATE_EPOCH'. Return 0 on success, and a non-zero
// value otherwise. This operation succeeds if the resulting value
// represents a date in the range '[0001JAN01 .. 9999DEC31]'. Note
// that 'daysSinceEpoch' may be negative to indicate a serial date that
// occurs before 'k_COMPACT_BINARY_DATE_EPOCH'.
// 'bdlt::Date' Decoding
static int getDateValue(bdlt::Date *date,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented those bytes. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if 'length' bytes
// are successfully read from the input sequence of the 'streamBuf'
// without the read position becoming unavailable, and the bytes
// contain a valid representation of a date value. See the
// package-level documentation of {'balber'} for a description of the
// decision procedure used to detect the encoding format for a
// 'bdlt::Date' value.
// 'bdlt::Date' Encoding
static int putDateValue(bsl::streambuf *streamBuf,
const bdlt::Date& value,
const BerEncoderOptions *options);
// Write a representation of the specified 'value' date to the output
// sequence of the specified 'streamBuf' according to the specified
// 'options'. If 'options' is 0, the default set of options is used.
// Return 0 on success, and a non-zero value otherwise. This operation
// succeeds if all bytes in the representation of the 'value' are
// written to the output sequence of the 'streamBuf' without the write
// position becoming unavailable. See the class documentation for a
// description of the default options. See the package-level
// documentation of {'balber'} for a description of the decision
// procedure used to select an encoding format for the 'value'.
// 'bdlt::DateTz' Decoding
static int getDateTzValue(bdlt::DateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time zone value represented by those bytes. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a date and time zone value.
// See the package-level documentation of {'balber'} for a description
// of the decision procedure used to detect the encoding format for a
// 'bdlt::DateTz' value.
// 'bdlt::DateTz' Encoding
static int putDateTzValue(bsl::streambuf *streamBuf,
const bdlt::DateTz& date,
const BerEncoderOptions *options);
// Write a representation of the specified 'value' date and time zone
// to the output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. This
// operation succeeds if all bytes in the representation of the 'value'
// are written to the output sequence of the 'streamBuf' without the
// write position becoming unavailable. See the class documentation
// for a description of the default options. See the package-level
// documentation of {'balber'} for a description of the decision
// procedure used to select an encoding format for the 'value'.
// Variant Decoding
static int getDateOrDateTzValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and optional time zone value represented by those bytes.
// Return 0 on success, and a non-zero value otherwise. The operation
// succeeds if 'length' bytes are successfully read from the input
// sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes contain a valid representation of a date
// and optional time zone value. See the package-level documentation
// of {'balber'} for a description of the decision procedure used to
// detect the encoding format for a 'DateOrDateTz' value.
};
// ===========================
// struct BerUtil_TimeEncoding
// ===========================
struct BerUtil_TimeEncoding {
// This component-private utility 'struct' provides a namespace for
// enumerating the set of formats that may be used by 'BerUtil' to encode
// and decode values of 'bdlt::Time' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_TIME = Encoding::e_ISO8601_TIME,
e_COMPACT_BINARY_TIME = Encoding::e_COMPACT_BINARY_TIME,
e_EXTENDED_BINARY_TIME = Encoding::e_EXTENDED_BINARY_TIME
};
enum {
k_EXTENDED_BINARY_MIN_BDE_VERSION =
Encoding::k_EXTENDED_BINARY_MIN_BDE_VERSION
};
};
// =============================
// struct BerUtil_TimeTzEncoding
// =============================
struct BerUtil_TimeTzEncoding {
// This component-private utility 'struct' provides a namespace for
// enumerating the set of formats that may be used by 'BerUtil' to encode
// and decode values of 'bdlt::TimeTz' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_TIMETZ = Encoding::e_ISO8601_TIMETZ,
e_COMPACT_BINARY_TIME = Encoding::e_COMPACT_BINARY_TIME,
e_COMPACT_BINARY_TIMETZ = Encoding::e_COMPACT_BINARY_TIMETZ,
e_EXTENDED_BINARY_TIMETZ = Encoding::e_EXTENDED_BINARY_TIMETZ
};
enum {
k_EXTENDED_BINARY_MIN_BDE_VERSION =
Encoding::k_EXTENDED_BINARY_MIN_BDE_VERSION
};
};
// ===================================
// struct BerUtil_TimeOrTimeTzEncoding
// ===================================
struct BerUtil_TimeOrTimeTzEncoding {
// This component-private utility 'struct' provides a namespace for
// enumerating the set of formats that may be used by 'BerUtil' to decode
// values of 'bdlb::Variant2<bdlt::Time, bdlt::TimeTz>' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_TIME = Encoding::e_ISO8601_TIME,
e_ISO8601_TIMETZ = Encoding::e_ISO8601_TIMETZ,
e_COMPACT_BINARY_TIME = Encoding::e_COMPACT_BINARY_TIME,
e_COMPACT_BINARY_TIMETZ = Encoding::e_COMPACT_BINARY_TIMETZ,
e_EXTENDED_BINARY_TIME = Encoding::e_EXTENDED_BINARY_TIME,
e_EXTENDED_BINARY_TIMETZ = Encoding::e_EXTENDED_BINARY_TIMETZ
};
};
// ==========================
// struct BerUtil_TimeImpUtil
// ==========================
struct BerUtil_TimeImpUtil {
// This component-private 'struct' provides a namespace for a suite of
// functions used by 'BerUtil' to implement BER encoding and decoding
// operations for time values. Within the definition of this 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690,
//: and
//:
//: *the* *default* *set* *of* *options*:
//: Refers to a 'balber::BerEncoderOptions' value having a
//: 'datetimeFractionalSecondPrecision' attribute of 3 and a
//: 'encodeDateAndTimeTypesAsBinary' attribute of 'false'.
//
// See the package level documentation of {'balber'} for a definition of
// the compact and extended binary formats for date and time values.
// TYPES
typedef BerUtil_ExtendedBinaryEncodingUtil ExtendedBinaryEncodingUtil;
// 'DateAndTimeHeaderUtil' is an alias to a namespace for a suite of
// functions used to implement encoding and decoding operations for the
// 2-byte header of an extended-binary-encoding formatted date-and-time
// value.
typedef BerUtil_DateAndTimeHeader DateAndTimeHeader;
// 'Header' is an alias to an in-core, value-semantic attribute class
// that represents the range of valid values of the 2-byte header of
// extended-binary-encoding formatted date-and-time values.
typedef BerUtil_DateAndTimeHeaderType DateAndTimeHeaderType;
// 'Type' is an alias to a namespace for enumerating the set of "header
// type" values that may be encoded in the 2-byte header of an
// extended-binary-encoding formatted date-and-time value.
typedef BerUtil_DateAndTimeHeaderImpUtil DateAndTimeHeaderUtil;
// 'DateAndTimeHeaderUtil' is an alias to a namespace for a suite of
// functions used to implement encoding and decoding operations for the
// 2-byte header of an extended-binary-encoding formatted date-and-time
// value.
typedef BerUtil_IntegerImpUtil IntegerUtil;
// 'IntegerUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for integer
// values.
typedef BerUtil_Iso8601ImpUtil Iso8601Util;
// 'Iso8601Util' is an alias to a namespace for a suite of functions
// used to implementing the encoding and decoding of date and time
// values using the ISO 8601 format.
typedef BerUtil_LengthImpUtil LengthUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
typedef BerUtil_StringImpUtil StringUtil;
// 'StringUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for string values.
typedef BerUtil_StreambufUtil StreambufUtil;
// 'StreambufUtil' is an alias to a namespace for a suite of functions
// used to implement input and output operations on 'bsl::streambuf'
// objects.
typedef BerUtil_TimeEncoding TimeEncoding;
// 'TimeEncoding' is an alias to a namespace for enumerating the set of
// formats that may be used by 'BerUtil' to encode and decode values of
// 'bdlt::Time' type.
typedef BerUtil_TimeTzEncoding TimeTzEncoding;
// 'TimeTzEncoding' is an alias to a namespace for enumerating the set
// of formats that may be used by 'BerUtil' to encode and decode values
// of 'bdlt::TimeTz' type.
typedef BerUtil_TimeOrTimeTzEncoding TimeOrTimeTzEncoding;
// 'TimeOrTimeTzEncoding' is an alias to a namespace for enumerating
// the set of formats that may be used by 'BerUtil' to decode to values
// of 'bdlb::Variant2<bdlt::Time, bdlt::TimeTz>' type.
typedef BerUtil_TimezoneOffsetImpUtil TimezoneUtil;
// 'TimezoneUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for time-zone
// offset values.
typedef bdlb::Variant2<bdlt::Time, bdlt::TimeTz> TimeOrTimeTz;
// 'TimeOrTimeTz' is a convenient alias for
// 'bdlb::Variant2<bdlt::Time, bdlt::TimeTz>'.
private:
// PRIVATE TYPES
enum {
k_EXTENDED_BINARY_TIME_LENGTH =
+DateAndTimeHeaderUtil::k_HEADER_LENGTH +
+IntegerUtil::k_40_BIT_INTEGER_LENGTH, // = 7
// the number of content octets used by 'BerUtil' to encode
// a time value using the extended-binary time and time zone format
k_EXTENDED_BINARY_TIMETZ_LENGTH =
+DateAndTimeHeaderUtil::k_HEADER_LENGTH +
+IntegerUtil::k_40_BIT_INTEGER_LENGTH, // = 7
// the number of contents octets used by 'BerUtil' to encode
// a time and time zone value using the extended-binary time and
// time zone format
k_MAX_ISO8601_TIME_LENGTH = bdlt::Iso8601Util::k_TIME_STRLEN,
// the maximum number of content octets used by 'BerUtil' to encode
// a time value using the ISO 8601 format
k_MAX_ISO8601_TIMETZ_LENGTH = bdlt::Iso8601Util::k_TIMETZ_STRLEN,
// the maximum number of content octets used by 'BerUtil to encode
// a time and time zone value using the ISO 8601 format
k_MIN_COMPACT_BINARY_TIME_LENGTH = 1,
// the minimum number of content octets used by 'BerUtil' to encode
// a time value using the compact-binary time format
k_MAX_COMPACT_BINARY_TIME_LENGTH = 4,
// the maximum number of content octets used by 'BerUtil' to encode
// a time value using the compact-binary time format
k_MIN_COMPACT_BINARY_TIMETZ_LENGTH =
k_MAX_COMPACT_BINARY_TIME_LENGTH + 1,
// the minimum number of content octets used by 'BerUtil' to encode
// a time and time zone value using the compact-binary time and
// time zone format
k_MAX_COMPACT_BINARY_TIMETZ_LENGTH = 6
// the maximum number of content octets used by 'BerUtil' to encode
// a time and time zone value using the compact-binary time and
// time zone format
};
// PRIVATE CLASS METHODS
// 'bdlt::Time' Decoding
static int detectTimeEncoding(TimeEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::Time' value given the specified
// 'length' and 'firstByte' of the encoded representation. Return 0 on
// success, -1 if the format is reserved for future use, and some other
// non-zero value otherwise.
static int getIso8601TimeValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as an
// ISO 8601 time. Return 0 on success, and a non-zero value otherwise.
// The operation succeeds if 'length' bytes are successfully read from
// the input sequence of the 'streamBuf' without the read position
// becoming unavailable, and the bytes contain a valid representation
// of an ISO 8601 time.
static int getCompactBinaryTimeValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as a
// compact-binary time. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of a compact-binary time.
static int getExtendedBinaryTimeValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as an
// extended-binary time. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of a extended-binary time.
// 'bdlt::Time' Encoding
static TimeEncoding::Value selectTimeEncoding(
const bdlt::Time& value,
const BerEncoderOptions *options);
// Determine the format that should be used to encode the specified
// 'value' given the 'value' and the specified 'options'. If 'options'
// is 0, the default set of options is used. Return an enumerator
// identifying the selected format.
static int putIso8601TimeValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if all bytes of the ISO 8601 representation of
// the 'value' are written to the 'streamBuf' without the write
// position becoming unavailable.
static int putCompactBinaryTimeValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options);
// Write the compact-binary time representation of the specified
// 'value' to the output sequence of the specified 'streamBuf'
// according to the specified 'options'. If 'options' is 0, the
// default set of options is used. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if all bytes of the
// compact-binary time representation of the 'value' are written to the
// 'streamBuf' without the write position becoming unavailable.
static int putExtendedBinaryTimeValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options);
// Write the extended-binary time representation of the specified
// 'value' to the output sequence of the specified 'streamBuf'
// according to the specified 'options'. If 'options' is 0, the
// default set of options is used. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if all bytes of the
// extended-binary time representation of the 'value' are written to
// the 'streamBuf' without the write position becoming unavailable.
// 'bdlt::TimeTz' Decoding
static int detectTimeTzEncoding(TimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::Time' value given the specified
// 'length' and 'firstByte' of the encoded representation. Return 0 on
// success, -1 if the format is reserved for future use, and some other
// non-zero value otherwise.
static int getIso8601TimeTzValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and time zone value represented by the interpretation of the
// read bytes as an ISO 8601 time and time zone. Return 0 on success,
// and a non-zero value otherwise. The operation succeeds if 'length'
// bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of an ISO 8601 time and time
// zone.
static int getCompactBinaryTimeValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as a
// compact-binary time. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of a compact-binary time.
static int getCompactBinaryTimeTzValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and time zone value represented by the interpretation of the
// read bytes as a compact-binary time and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a compact-binary time and
// time zone.
static int getExtendedBinaryTimeTzValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and time zone value represented by the interpretation of the
// read bytes as an extended-binary time and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of an extended-binary time and
// time zone.
// 'bdlt::TimeTz' Encoding
static TimeTzEncoding::Value selectTimeTzEncoding(
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Determine the format that should be used to encode the specified
// 'value' given the 'value' and the specified 'options'. If 'options'
// is 0, the default set of options is used. Return an enumerator
// identifying the selected format.
static int putIso8601TimeTzValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if all bytes of the ISO 8601 representation of
// the 'value' are written to the 'streamBuf' without the write
// position becoming unavailable.
static int putCompactBinaryTimeValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Write the compact-binary time representation of the specified
// 'value' to the output sequence of the specified 'streamBuf'
// according to the specified 'options'. If 'options' is 0, the
// default set of options is used. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if all bytes of the
// compact-binary time representation of the 'value' are written to the
// 'streamBuf' without the write position becoming unavailable. The
// behavior is undefined unless the 'offset' of the 'value' is 0.
static int putCompactBinaryTimeTzValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Write the compact-binary date and time zone representation of the
// specified 'value' to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if all bytes of
// the compact-binary date representation of the 'value' are written to
// the 'streamBuf' without the write position becoming unavailable.
static int putExtendedBinaryTimeTzValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Write the extended-binary date and time zone representation of the
// specified 'value' to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if all bytes of
// the extended-binary date representation of the 'value' are written
// to the 'streamBuf' without the write position becoming unavailable.
// Variant Decoding
static int detectTimeOrTimeTzEncoding(
TimeOrTimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::Time' or 'bdlt::TimeTz' value given
// the specified 'length' and 'firstByte' of the encoded
// representation. Return 0 on success, -1 if the format is reserved
// for future use, and some other non-zero value otherwise.
static int getIso8601TimeValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as an
// ISO 8601 time. Return 0 on success, and a non-zero value otherwise.
// The operation succeeds if 'length' bytes are successfully read from
// the input sequence of the 'streamBuf' without the read position
// becoming unavailable, and the bytes contain a valid representation
// of an ISO 8601 time.
static int getIso8601TimeTzValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and time zone value represented by the interpretation of the
// read bytes as an ISO 8601 time and time zone. Return 0 on success,
// and a non-zero value otherwise. The operation succeeds if 'length'
// bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of an ISO 8601 time and time
// zone.
static int getCompactBinaryTimeValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as a
// compact-binary time. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of a compact-binary time.
static int getCompactBinaryTimeTzValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and time zone value represented by the interpretation of the
// read bytes as a compact-binary time and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a compact-binary time and
// time zone.
static int getExtendedBinaryTimeValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as a
// extended-binary time. Return 0 on success, and a non-zero value
// otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of an extended-binary time.
static int getExtendedBinaryTimeTzValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and time zone value represented by the interpretation of the
// read bytes as an extended-binary time and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of an extended-binary time and
// time zone.
public:
// CLASS METHODS
// Utilities
static void timeToMillisecondsSinceMidnight(
int *millisecondsSinceMidnight,
const bdlt::Time& time);
// Load to the specified 'millisecondsSinceMidnight' the number of
// milliseconds in the specified 'time' value.
static void timeToMicrosecondsSinceMidnight(
bsls::Types::Int64 *microsecondsSinceMidnight,
const bdlt::Time& time);
// Load to the specified 'microsecondsSinceMidnight' the number of
// microseconds in the specified 'time' value.
static int millisecondsSinceMidnightToTime(
bdlt::Time *time,
int millisecondsSinceMidnight);
// Load to the specified 'time' the time value represented by the
// specified 'millisecondsSinceMidnight'.
static int microsecondsSinceMidnightToTime(
bdlt::Time *time,
bsls::Types::Int64 microsecondsSinceMidnight);
// Load to the specified 'time' the time value represented by the
// specified 'microsecondsSinceMidnight'.
// 'bdlt::Time' Decoding
static int getTimeValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented those bytes. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if 'length' bytes
// are successfully read from the input sequence of the 'streamBuf'
// without the read position becoming unavailable, and the bytes
// contain a valid representation of a time value. See the
// package-level documentation of {'balber'} for a description of the
// decision procedure used to detect the encoding format for a
// 'bdlt::Time' value.
// 'bdlt::Time' Encoding
static int putTimeValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options);
// Write a representation of the specified time 'value' to the output
// sequence of the specified 'streamBuf' according to the specified
// 'options'. If 'options' is 0, the default set of options is used.
// Return 0 on success, and a non-zero value otherwise. This operation
// succeeds if all bytes in the representation of the 'value' are
// written to the output sequence of the 'streamBuf' without the write
// position becoming unavailable. See the class documentation for a
// description of the default options. See the package-level
// documentation of {'balber'} for a description of the decision
// procedure used to select an encoding format for the 'value'.
// 'bdlt::TimeTz' Decoding
static int getTimeTzValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and time zone value represented by those bytes. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a time and time zone value.
// See the package-level documentation of {'balber'} for a description
// of the decision procedure used to detect the encoding format for a
// 'bdlt::TimeTz' value.
// 'bdlt::TimeTz' Encoding
static int putTimeTzValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Write a representation of the specified time and time-zone 'value'
// to the output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. This
// operation succeeds if all bytes in the representation of the 'value'
// are written to the output sequence of the 'streamBuf' without the
// write position becoming unavailable. See the class documentation
// for a description of the default options. See the package-level
// documentation of {'balber'} for a description of the decision
// procedure used to select an encoding format for the 'value'.
// Variant Decoding
static int getTimeOrTimeTzValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time and optional time zone value represented by those bytes.
// Return 0 on success, and a non-zero value otherwise. The operation
// succeeds if 'length' bytes are successfully read from the input
// sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes contain a valid representation of a time
// and optional time zone value. See the package-level documentation
// of {'balber'} for a description of the decision procedure used to
// detect the encoding format for a 'TimeOrTimeTz' value.
};
// ===============================
// struct BerUtil_DatetimeEncoding
// ===============================
struct BerUtil_DatetimeEncoding {
// This component-private utility 'struct' provides a namespace for
// enumerating the set of formats that may be used by 'BerUtil' to encode
// and decode values of 'bdlt::Datetime' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_DATETIME = Encoding::e_ISO8601_DATETIME,
e_COMPACT_BINARY_DATETIME = Encoding::e_COMPACT_BINARY_DATETIME,
e_COMPACT_BINARY_DATETIMETZ = Encoding::e_COMPACT_BINARY_DATETIMETZ,
e_EXTENDED_BINARY_DATETIME = Encoding::e_EXTENDED_BINARY_DATETIMETZ
};
enum {
k_EXTENDED_BINARY_MIN_BDE_VERSION =
Encoding::k_EXTENDED_BINARY_MIN_BDE_VERSION
};
};
// =================================
// struct BerUtil_DatetimeTzEncoding
// =================================
struct BerUtil_DatetimeTzEncoding {
// This component-private utility 'struct' provides a namespace for
// enumerating the set of formats that may be used by 'BerUtil' to encode
// and decode values of 'bdlt::DatetimeTz' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_DATETIMETZ = Encoding::e_ISO8601_DATETIMETZ,
e_COMPACT_BINARY_DATETIME = Encoding::e_COMPACT_BINARY_DATETIME,
e_COMPACT_BINARY_DATETIMETZ = Encoding::e_COMPACT_BINARY_DATETIMETZ,
e_EXTENDED_BINARY_DATETIMETZ = Encoding::e_EXTENDED_BINARY_DATETIMETZ
};
enum {
k_EXTENDED_BINARY_MIN_BDE_VERSION =
Encoding::k_EXTENDED_BINARY_MIN_BDE_VERSION
};
};
// ===========================================
// struct BerUtil_DatetimeOrDatetimeTzEncoding
// ===========================================
struct BerUtil_DatetimeOrDatetimeTzEncoding {
// This component-private utility 'struct' provides a namespace for
// enumerating the set of formats that may be used by 'BerUtil' to decode
// to values of 'bdlb::Variant2<bdlt::Datetime, bdlt::DatetimeTz>' type.
// TYPES
typedef BerUtil_DateAndTimeEncoding Encoding;
// 'Encoding' is an alias to a namespace for enumerating the union of
// the sets of date and time formats used to encode and decode all date
// and time types supported by 'BerUtil'.
enum Value {
e_ISO8601_DATETIME = Encoding::e_ISO8601_DATETIME,
e_ISO8601_DATETIMETZ = Encoding::e_ISO8601_DATETIMETZ,
e_COMPACT_BINARY_DATETIME = Encoding::e_COMPACT_BINARY_DATETIME,
e_COMPACT_BINARY_DATETIMETZ = Encoding::e_COMPACT_BINARY_DATETIMETZ,
e_EXTENDED_BINARY_DATETIME = Encoding::e_EXTENDED_BINARY_DATETIME,
e_EXTENDED_BINARY_DATETIMETZ = Encoding::e_EXTENDED_BINARY_DATETIMETZ
};
};
// ==============================
// struct BerUtil_DatetimeImpUtil
// ==============================
struct BerUtil_DatetimeImpUtil {
// This component-private 'struct' provides a namespace for a suite of
// functions used by 'BerUtil' to implement BER encoding and decoding
// operations for date and time values. Within the definition of this
// 'struct':
//
//: *the* *specification*:
//: Refers to the August 2015 revision of the ITU-T Recommendation X.690,
//: and
//:
//: *the* *default* *set* *of* *options*:
//: Refers to a 'balber::BerEncoderOptions' value having a
//: 'datetimeFractionalSecondPrecision' attribute of 3 and a
//: 'encodeDateAndTimeTypesAsBinary' attribute of 'false'.
//
// See the package level documentation of {'balber'} for a definition of
// the compact and extended binary formats for date and time values.
// TYPES
typedef BerUtil_Constants Constants;
// 'Constants' is an alias to a namespace for a suite of
// general-purpose constants that occur when encoding or decoding BER
// data.
typedef BerUtil_ExtendedBinaryEncodingUtil ExtendedBinaryEncodingUtil;
// 'DateAndTimeHeaderUtil' is an alias to a namespace for a suite of
// functions used to implement encoding and decoding operations for the
// 2-byte header of an extended-binary-encoding formatted date-and-time
// value.
typedef BerUtil_DateAndTimeHeader DateAndTimeHeader;
// 'Header' is an alias to an in-core, value-semantic attribute class
// that represents the range of valid values of the 2-byte header of
// extended-binary-encoding formatted date-and-time values.
typedef BerUtil_DateAndTimeHeaderImpUtil DateAndTimeHeaderUtil;
// 'DateAndTimeHeaderUtil' is an alias to a namespace for a suite of
// functions used to implement encoding and decoding operations for the
// 2-byte header of an extended-binary-encoding formatted date-and-time
// value.
typedef BerUtil_DateImpUtil DateUtil;
// 'DateUtil' is an alias to a namespace for a suite of functions used
// to implement BER encoding and decoding operations for date values.
typedef BerUtil_DatetimeEncoding DatetimeEncoding;
// 'DatetimeEncoding' is an alias to a namespace for enumerating the
// set of formats that may be used by 'BerUtil' to encode and decode
// values of 'bdlt::Datetime' type.
typedef BerUtil_DatetimeTzEncoding DatetimeTzEncoding;
// 'DatetimeTzEncoding' is an alias to a namespace for enumerating the
// set of formats that may be used by 'BerUtil' to encode and decode
// values of 'bdlt::DatetimeTz' type.
typedef BerUtil_DatetimeOrDatetimeTzEncoding DatetimeOrDatetimeTzEncoding;
// 'DatetimeOrDatetimeTzEncoding' is an alias to a namespace for
// enumerating the set of formats that may be used by 'BerUtil' to
// decode to values of
// 'bdlb::Variant2<bdlt::Datetime, bdlt::DatetimeTz>' type.
typedef BerUtil_IntegerImpUtil IntegerUtil;
// 'IntegerUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for integer
// values.
typedef BerUtil_Iso8601ImpUtil Iso8601Util;
// 'Iso8601Util' is an alias to a namespace for a suite of functions
// used to implementing the encoding and decoding of date and time
// values using the ISO 8601 format.
typedef BerUtil_LengthImpUtil LengthUtil;
// 'LengthUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for length
// quantities.
typedef BerUtil_StreambufUtil StreambufUtil;
// 'StreambufUtil' is an alias to a namespace for a suite of functions
// used to implement input and output operations on 'bsl::streambuf'
// objects.
typedef BerUtil_StringImpUtil StringUtil;
// 'StringUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for string values.
typedef BerUtil_TimeImpUtil TimeUtil;
// 'DateUtil' is an alias to a namespace for a suite of functions used
// to implement BER encoding and decoding operations for time values.
typedef BerUtil_TimezoneOffsetImpUtil TimezoneUtil;
// 'TimezoneUtil' is an alias to a namespace for a suite of functions
// used to implement BER encoding and decoding operations for time-zone
// offset values.
typedef bdlb::Variant2<bdlt::Datetime, bdlt::DatetimeTz>
DatetimeOrDatetimeTz;
// 'DatetimeOrDatetimeTz' is a convenient alias for
// 'bdlb::Variant2<bdlt::Datetime, bdlt::DatetimeTz>'.
private:
// PRIVATE TYPES
enum {
k_EXTENDED_BINARY_SERIAL_DATE_LENGTH = 3,
k_EXTENDED_BINARY_DATETIME_LENGTH =
DateAndTimeHeaderUtil::k_HEADER_LENGTH +
k_EXTENDED_BINARY_SERIAL_DATE_LENGTH +
IntegerUtil::k_40_BIT_INTEGER_LENGTH, // = 10
// the number of content octets used by 'BerUtil' to encode a date
// and time value using the extended-binary date and time format
k_EXTENDED_BINARY_DATETIMETZ_LENGTH =
DateAndTimeHeaderUtil::k_HEADER_LENGTH +
k_EXTENDED_BINARY_SERIAL_DATE_LENGTH +
IntegerUtil::k_40_BIT_INTEGER_LENGTH, // = 10
// the number of contents octets used by 'BerUtil' to encode a
// date, time, and time zone value using the extended-binary date,
// time, and time zone format
k_MAX_ISO8601_DATETIME_LENGTH = bdlt::Iso8601Util::k_DATETIME_STRLEN,
// the maximum number of content octets used by 'BerUtil' to
// encode a date and time value using the ISO 8601 format
k_MAX_ISO8601_DATETIMETZ_LENGTH =
bdlt::Iso8601Util::k_DATETIMETZ_STRLEN,
// the maximum number of content octets used by 'BerUtil' to
// encode a date, time, and time zone value using the ISO 8601
// format
k_MAX_COMPACT_BINARY_DATETIME_LENGTH = 6,
// the maximum number of content octets used by 'BerUtil' to encode
// a date and time value using the compact-binary date and time
// format
k_MIN_COMPACT_BINARY_DATETIMETZ_LENGTH =
k_MAX_COMPACT_BINARY_DATETIME_LENGTH + 1,
// the minimum number of content octets used by 'BerUtil' to
// encode a date, time, and time zone value using the
// compact-binary date, time, and time zone format
k_MAX_COMPACT_BINARY_DATETIMETZ_LENGTH = 9
// the maximum number of content octets used by 'BerUtil' to
// encode a date, time, and time zone value using the
// compact-binary date, time, and time zone format
};
// PRIVATE CLASS METHODS
// Utilities
static void datetimeToMillisecondsSinceEpoch(
bsls::Types::Int64 *millisecondsSinceEpoch,
const bdlt::Datetime& value);
// Load to the specified 'millisecondsFromEpoch' the number of
// milliseconds between the start of the day on the compact-binary date
// epoch and the specified 'value'. The compact-binary date epoch is
// the date defined by the 'DateUtil::k_COMPACT_BINARY_DATE_EPOCH'
// serial date. Note that this quantity may be negative if the
// specified 'value' occurs before the compact-binary date epoch.
static int millisecondsSinceEpochToDatetime(
bdlt::Datetime *value,
bsls::Types::Int64 millisecondsSinceEpoch);
// Load to the specified 'value' the date and time represented by the
// specified 'millisecondsSinceEpoch' number of milliseconds from the
// compact-binary date epoch. The compact-binary date epoch is the
// date defined by the 'DateUtil::k_COMPACT_BINARY_DATE_EPOCH' serial
// date. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if the resulting date and time is a valid
// 'bdlt::Datetime' value. Note that 'millisecondsSinceEpoch' may be
// negative to indicate a date and time that occurs before the
// compact-binary date epoch.
// 'bdlt::Datetime' Decoding
static int detectDatetimeEncoding(DatetimeEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::Datetime' value given the specified
// 'length' and 'firstByte' of the encoded representation. Return 0 on
// success, -1 if the format is reserved for future use, and some other
// non-zero value otherwise.
static int getIso8601DatetimeValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time value represented by the interpretation of the read
// bytes as an ISO 8601 date and time. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if 'length' bytes
// are successfully read from the input sequence of the 'streamBuf'
// without the read position becoming unavailable, and the bytes
// contain a valid representation of an ISO 8601 date and time.
static int getCompactBinaryDatetimeValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time value represented by the interpretation of the read
// bytes as a compact-binary date and time. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if 'length' bytes
// are successfully read from the input sequence of the 'streamBuf'
// without the read position becoming unavailable, and the bytes
// contain a valid representation of a compact-binary date and time.
static int getCompactBinaryDatetimeTzValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time value represented by the interpretation of the read
// bytes as a compact-binary date, time, and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a compact-binary date, time,
// and time zone.
static int getExtendedBinaryDatetimeValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time value represented by the interpretation of the read
// bytes as an extended-binary date, time, and time zone. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// 'length' bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of an extended-binary date,
// time, and time zone.
// 'bdlt::Datetime' Encoding
static DatetimeEncoding::Value selectDatetimeEncoding(
bsls::Types::Int64 *serialDatetime,
int *length,
const bdlt::Datetime& value,
const BerEncoderOptions *options);
// Determine the format that should be used to encode the specified
// 'value' given the 'value' and the specified 'options'. Load to the
// specified 'serialDatetime' the number of milliseconds since the
// start of the day on the compact-binary date epoch to the 'value',
// and load to the specified 'length' the number of contents octets
// that would be used by the BER encoding of 'serialDatetime' according
// to the specification. If 'options' is 0, the default set of options
// is used. Return an enumerator identifying the selected format.
// Note that the 'serialDatetime' and 'length' of a date and time value
// are frequently used as arguments to date and time encoding
// operations defined in this 'struct'.
static int putIso8601DatetimeValue(bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if all bytes of the ISO 8601 representation of
// the 'value' are written to the 'streamBuf' without the write
// position becoming unavailable.
static int putCompactBinaryDatetimeValue(
bsl::streambuf *streamBuf,
bsls::Types::Int64 serialDatetime,
int length,
const BerEncoderOptions *options);
// Write the specified 'length' number of octets of the compact-binary
// date and time representation of the specified 'serialDatetime'
// number of milliseconds from the start of the day on the
// compact-binary serial epoch to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if all 'length'
// bytes of the representation of the 'serialDatetime' are written to
// the 'streamBuf' without the write position becoming unavailable.
static int putCompactBinaryDatetimeValue(
bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options);
// Write the compact-binary date and time representation of the
// specified 'value' to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if all bytes of
// the compact-binary date and time representation of the 'value' are
// written to the 'streamBuf' without the write position becoming
// unavailable.
static int putCompactBinaryDatetimeTzValue(
bsl::streambuf *streamBuf,
bsls::Types::Int64 serialDatetime,
int length,
const BerEncoderOptions *options);
// Write the specified 'length' number of octets of the compact-binary
// date, time, and time zone representation of the specified
// 'serialDatetime' number of milliseconds from the start of the day on
// the compact-binary serial epoch to the output sequence of the
// specified 'streamBuf' according to the specified 'options'. If
// 'options' is 0, the default set of options is used. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// all 'length' bytes of the representation of the 'serialDatetime' are
// written to the 'streamBuf' without the write position becoming
// unavailable.
static int putExtendedBinaryDatetimeValue(
bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options);
// Write the extended-binary date and time representation of the
// specified 'value' to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if all bytes of
// the extended-binary date and time representation of the 'value' are
// written to the 'streamBuf' without the write position becoming
// unavailable.
// 'bdlt::DatetimeTz' Decoding
static int detectDatetimeTzEncoding(
DatetimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::DatetimeTz' value given the specified
// 'length' and 'firstByte' of the encoded representation. Return 0 on
// success, -1 if the format is reserved for future use, and some other
// non-zero value otherwise.
static int getIso8601DatetimeTzValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date, time, and time zone value represented by the interpretation of
// the read bytes as an ISO 8601 date, time, and time zone. Return 0
// on success, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes contain a valid representation of an ISO 8601 date, time,
// and time zone .
static int getCompactBinaryDatetimeValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date value represented by the interpretation of the read bytes as a
// compact-binary date and time. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of a compact-binary date and time.
static int getCompactBinaryDatetimeTzValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date, time, and time zone value represented by the interpretation of
// the read bytes as a compact-binary date, time, and time zone.
// Return 0 on success, and a non-zero value otherwise. The operation
// succeeds if 'length' bytes are successfully read from the input
// sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes contain a valid representation of a
// compact-binary date, time, and time zone.
static int getExtendedBinaryDatetimeTzValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time zone value represented by the interpretation of the
// read bytes as an extended-binary date, time, and time zone. Return
// 0 on success, and a non-zero value otherwise. The operation
// succeeds if 'length' bytes are successfully read from the input
// sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes contain a valid representation of an
// extended-binary date, time, and time zone.
// 'bdlt::DatetimeTz' Encoding
static DatetimeTzEncoding::Value selectDatetimeTzEncoding(
bsls::Types::Int64 *serialDatetime,
int *length,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options);
// Determine the format that should be used to encode the specified
// 'value' given the 'value' and the specified 'options'. If 'options'
// is 0, the default set of options is used. Return an enumerator
// identifying the selected format.
static int putIso8601DatetimeTzValue(bsl::streambuf *streamBuf,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options);
// Write the ISO 8601 representation of the specified 'value' to the
// output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if all bytes of the ISO 8601 representation of
// the 'value' are written to the 'streamBuf' without the write
// position becoming unavailable.
static int putCompactBinaryDatetimeTzValue(
bsl::streambuf *streamBuf,
int timezoneOffsetInMinutes,
bsls::Types::Int64 serialDatetime,
int serialDatetimeLength,
const BerEncoderOptions *options);
// Write the specified 'serialDatetimeLength' number of octets of the
// compact-binary date, time, and time zone representation using the
// specified the date and time defined by the specified
// 'serialDatetime' number of milliseconds from the start of the day on
// the compact-binary serial epoch and the specified
// 'timezoneOffsetInMinutes' time zone to the output sequence of the
// specified 'streamBuf' according to the specified 'options'. If
// 'options' is 0, the default set of options is used. Return 0 on
// success, and a non-zero value otherwise. The operation succeeds if
// all 'length' bytes of the compact-binary date, time, and time zone
// representation of the 'serialDatetime' and 'timezoneOffsetInMinutes'
// are written to the 'streamBuf' without the write position becoming
// unavailable.
static int putExtendedBinaryDatetimeTzValue(
bsl::streambuf *streamBuf,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options);
// Write the extended-binary date, time, and time zone representation
// of the specified 'value' to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. The operation succeeds if all bytes of
// the extended-binary date, time, and time zone representation of the
// 'value' are written to the 'streamBuf' without the write position
// becoming unavailable.
// Variant Decoding
static int detectDatetimeOrDatetimeTzEncoding(
DatetimeOrDatetimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte);
// Load to the specified 'encoding' the enumerator that describes the
// format used to encode a 'bdlt::Datetime' or 'bdlt::DatetimeTz' value
// given the specified 'length' and 'firstByte' of the encoded
// representation. Return 0 on success, -1 if the format is reserved
// for future use, and some other non-zero value otherwise.
static int getIso8601DatetimeValue(DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date, time, and optional time zone value represented by the
// interpretation of the read bytes as an ISO 8601 date and time.
// Return 0 on success, and a non-zero value otherwise. The operation
// succeeds if 'length' bytes are successfully read from the input
// sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes contain a valid representation of an ISO
// 8601 date and time.
static int getIso8601DatetimeTzValue(DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date, time, and optional time zone value represented by the
// interpretation of the read bytes as an ISO 8601 date, time, and time
// zone. Return 0 on success, and a non-zero value otherwise. The
// operation succeeds if 'length' bytes are successfully read from the
// input sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes contain a valid representation of an ISO
// 8601 date, time, and time zone.
static int getCompactBinaryDatetimeValue(DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date, time, and optional time zone value represented by the
// interpretation of the read bytes as a compact-binary date and time.
// Return 0 on success, and a non-zero value otherwise. The operation
// succeeds if 'length' bytes are successfully read from the input
// sequence of the 'streamBuf' without the read position becoming
// unavailable, and the bytes contain a valid representation of a
// compact-binary date and time.
static int getCompactBinaryDatetimeTzValue(DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date, time, and optional time zone value represented by the
// interpretation of the read bytes as a compact-binary date, time, and
// time zone. Return 0 on success, and a non-zero value otherwise.
// The operation succeeds if 'length' bytes are successfully read from
// the input sequence of the 'streamBuf' without the read position
// becoming unavailable, and the bytes contain a valid representation
// of a compact-binary date, time, and time zone.
static int getExtendedBinaryDatetimeValue(DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as a
// extended-binary date and time. Return 0 on success, and a non-zero
// value otherwise. The operation succeeds if 'length' bytes are
// successfully read from the input sequence of the 'streamBuf' without
// the read position becoming unavailable, and the bytes contain a
// valid representation of an extended-binary date and time.
static int getExtendedBinaryDatetimeTzValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// time value represented by the interpretation of the read bytes as a
// extended-binary date, time, and time zone. Return 0 on success, and
// a non-zero value otherwise. The operation succeeds if 'length'
// bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of an extended-binary date,
// time, and time zone.
public:
// CLASS METHODS
// 'bdlt::Datetime' Decoding
static int getDatetimeValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date and time value represented those bytes. Return 0 on success,
// and a non-zero value otherwise. The operation succeeds if 'length'
// bytes are successfully read from the input sequence of the
// 'streamBuf' without the read position becoming unavailable, and the
// bytes contain a valid representation of a date and time value. See
// the package-level documentation of
// {'balber'} for a description of the decision procedure used to
// detect the encoding format for a 'bdlt::Datetime' value.
// 'bdlt::Datetime' Encoding
static int putDatetimeValue(bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options);
// Write a representation of the specified 'value' date and time to the
// output sequence of the specified 'streamBuf' according to the
// specified 'options'. If 'options' is 0, the default set of options
// is used. Return 0 on success, and a non-zero value otherwise. This
// operation succeeds if all bytes in the representation of the 'value'
// are written to the output sequence of the 'streamBuf' without the
// write position becoming unavailable. See the class documentation
// for a description of the default options. See the package-level
// documentation of {'balber'} for a description of the decision
// procedure used to select an encoding format for the 'value'.
// 'bdlt::DatetimeTz' Decoding
static int getDatetimeTzValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Read the specified 'length' number of bytes from the input sequence
// of the specified 'streamBuf' and load to the specified 'value' the
// date, time, and time zone value represented those bytes. Return 0
// on success, and a non-zero value otherwise. The operation succeeds
// if 'length' bytes are successfully read from the input sequence of
// the 'streamBuf' without the read position becoming unavailable, and
// the bytes contain a valid representation of a date, time, and time
// zone value. See the package-level documentation of {'balber'} for a
// description of the decision procedure used to detect the encoding
// format for a 'bdlt::Datetime' value.
// 'bdlt::DatetimeTz' Encoding
static int putDatetimeTzValue(bsl::streambuf *streamBuf,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options);
// Write a representation of the specified 'value' date, time, and time
// zone to the output sequence of the specified 'streamBuf' according
// to the specified 'options'. If 'options' is 0, the default set of
// options is used. Return 0 on success, and a non-zero value
// otherwise. This operation succeeds if all bytes in the
// representation of the 'value' are written to the output sequence of
// the 'streamBuf' without the write position becoming unavailable.
// See the class documentation for a description of the default
// options. See the package-level documentation of {'balber'} for a
// description of the decision procedure used to select an encoding
// format for the 'value'.
// Variant Decoding
static int getDatetimeOrDatetimeTzValue(DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length);
// Write a representation of the specified 'value' date, time, and
// optional time zone to the output sequence of the specified
// 'streamBuf' according to the specified 'options'. If 'options' is
// 0, the default set of options is used. Return 0 on success, and a
// non-zero value otherwise. This operation succeeds if all bytes in
// the representation of the 'value' are written to the output sequence
// of the 'streamBuf' without the write position becoming unavailable.
// See the class documentation for a description of the default
// options. See the package-level documentation of {'balber'} for a
// description of the decision procedure used to select an encoding
// format for the 'value'.
};
// ==============================
// struct BerUtil_GetValueImpUtil
// ==============================
struct BerUtil_GetValueImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions that define the overload set for the implementation of
// 'balber::BerUtil::getValue'. The set of types used for the 'value'
// parameters in the overload set of 'getValue' in this 'struct' define the
// set of types that 'balber::BerUtil::getValue' supports.
// TYPES
typedef BerUtil_BooleanImpUtil BooleanUtil;
// 'BooleanUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for boolean values.
typedef BerUtil_CharacterImpUtil CharacterUtil;
// 'CharacterUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for byte values.
typedef BerUtil_DateImpUtil DateUtil;
// 'DateUtil' is an alias to a namespace for a suite of functions used
// by 'BerUtil' to implement BER encoding and decoding operations for
// date values.
typedef BerUtil_DatetimeImpUtil DatetimeUtil;
// 'DatetimeUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for date and time values.
typedef BerUtil_FloatingPointImpUtil FloatingPointUtil;
// 'FloatingPointUtil' is an alias to a namespace for a suite of
// functions used by 'BerUtil' to implement BER encoding and decoding
// operations for floating-point number values.
typedef BerUtil_IntegerImpUtil IntegerUtil;
// 'IntegerUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for integer values.
typedef BerUtil_StringImpUtil StringUtil;
// 'StringUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for string values.
typedef BerUtil_TimeImpUtil TimeUtil;
// 'TimeUtil' is an alias to a namespace for a suite of functions used
// by 'BerUtil' to implement BER encoding and decoding operations for
// time values.
typedef bdlb::Variant2<bdlt::Date, bdlt::DateTz> DateOrDateTz;
// 'DateOrDateTz' is a convenient alias for
// 'bdlb::Variant2<bdlt::Date, bdlt::DateTz>'.
typedef bdlb::Variant2<bdlt::Datetime, bdlt::DatetimeTz>
DatetimeOrDatetimeTz;
// 'DatetimeOrDatetimeTz' is a convenient alias for
// 'bdlb::Variant2<bdlt::Datetime, bdlt::DatetimeTz>'.
typedef bdlb::Variant2<bdlt::Time, bdlt::TimeTz> TimeOrTimeTz;
// 'TimeOrTimeTz' is a convenient alias for
// 'bdlb::Variant2<bdlt::Time, bdlt::TimeTz>'.
// CLASS METHODS
template <typename TYPE>
static int getValue(
TYPE *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bool *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
char *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
unsigned char *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
signed char *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
float *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
double *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bdldfp::Decimal64 *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bsl::string *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bdlt::Date *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bdlt::DateTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bdlt::Time *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
static int getValue(
TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options = BerDecoderOptions());
// Decode the specified 'value' from the specified 'streamBuf',
// consuming exactly the specified 'length' bytes. Return 0 on
// success, and a non-zero value otherwise. Optionally specify
// decoding 'options' to control aspects of the decoding. Note that
// the value consists of the contents of the bytes only (no length
// prefix). Also note that only fundamental C++ types, 'bsl::string',
// and BDE date/time types are supported.
};
// ==============================
// struct BerUtil_PutValueImpUtil
// ==============================
struct BerUtil_PutValueImpUtil {
// This component-private utility 'struct' provides a namespace for a suite
// of functions that define the overload set for the implementation of
// 'balber::BerUtil::putValue'. The set of types used for the 'value'
// parameters in the overload set of 'putValue' in this 'struct' define the
// set of types that 'balber::BerUtil::putValue' supports.
// TYPES
typedef BerUtil_BooleanImpUtil BooleanUtil;
// 'BooleanUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for boolean values.
typedef BerUtil_CharacterImpUtil CharacterUtil;
// 'CharacterUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for byte values.
typedef BerUtil_DateImpUtil DateUtil;
// 'DateUtil' is an alias to a namespace for a suite of functions used
// by 'BerUtil' to implement BER encoding and decoding operations for
// date values.
typedef BerUtil_DatetimeImpUtil DatetimeUtil;
// 'DatetimeUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for date and time values.
typedef BerUtil_FloatingPointImpUtil FloatingPointUtil;
// 'FloatingPointUtil' is an alias to a namespace for a suite of
// functions used by 'BerUtil' to implement BER encoding and decoding
// operations for floating-point number values.
typedef BerUtil_IntegerImpUtil IntegerUtil;
// 'IntegerUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for integer values.
typedef BerUtil_StringImpUtil StringUtil;
// 'StringUtil' is an alias to a namespace for a suite of functions
// used by 'BerUtil' to implement BER encoding and decoding operations
// for string values.
typedef BerUtil_TimeImpUtil TimeUtil;
// 'TimeUtil' is an alias to a namespace for a suite of functions used
// by 'BerUtil' to implement BER encoding and decoding operations for
// time values.
// CLASS METHODS
template <typename TYPE>
static int putValue(bsl::streambuf *streamBuf,
const TYPE& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
bool value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
char value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
unsigned char value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
signed char value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
float value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
double value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
bdldfp::Decimal64 value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bsl::string& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bslstl::StringRef& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bdlt::Date& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bdlt::DateTz& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options);
static int putValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options);
// Encode the specified 'value' to the specified 'streamBuf'. Return 0
// on success, and a non-zero value otherwise. Note that the value
// consists of the length and contents primitives. Also note that only
// fundamental C++ types, 'bsl::string', 'bslstl::StringRef' and BDE
// date/time types are supported.
};
// ==================
// struct BerUtil_Imp
// ==================
struct BerUtil_Imp {
// This component-private utility 'struct' exists to provide
// backwards-compatability for external components that depend upon the
// facilities provided by this 'struct'.
// CLASS METHODS
static int putStringValue(bsl::streambuf *streamBuf,
const char *string,
int stringLength);
// Write the length and contents octets of the BER encoding of the
// specified character 'string' having the specified 'stringLength' (as
// defined in the specification) to the output sequence of the
// specified 'streamBuf'. Return 0 if successful, and a non-zero value
// otherwise. The operation succeeds if and only if all bytes
// corresponding to the length and contents octets are written to the
// 'streamBuf' without the write position becoming unavailable.
};
// ============================================================================
// INLINE FUNCTION DEFINITIONS
// ============================================================================
// --------------
// struct BerUtil
// --------------
// CLASS METHODS
inline
int BerUtil::getEndOfContentOctets(bsl::streambuf *streamBuf,
int *accumNumBytesConsumed)
{
return BerUtil_LengthImpUtil::getEndOfContentOctets(accumNumBytesConsumed,
streamBuf);
}
inline
int BerUtil::getLength(bsl::streambuf *streamBuf,
int *result,
int *accumNumBytesConsumed)
{
return BerUtil_LengthImpUtil::getLength(
result, accumNumBytesConsumed, streamBuf);
}
template <class TYPE>
inline
int BerUtil::getValue(bsl::streambuf *streamBuf,
TYPE *value,
int length,
const BerDecoderOptions& options)
{
return BerUtil_GetValueImpUtil::getValue(
value, streamBuf, length, options);
}
template <typename TYPE>
inline
int BerUtil::getValue(bsl::streambuf *streamBuf,
TYPE *value,
int *accumNumBytesConsumed,
const BerDecoderOptions& options)
{
int length;
if (BerUtil_LengthImpUtil::getLength(
&length, accumNumBytesConsumed, streamBuf)) {
return -1; // RETURN
}
if (BerUtil::getValue(streamBuf, value, length, options)) {
return -1; // RETURN
}
*accumNumBytesConsumed += length;
return 0;
}
inline
int BerUtil::putEndOfContentOctets(bsl::streambuf *streamBuf)
{
return BerUtil_LengthImpUtil::putEndOfContentOctets(streamBuf);
}
inline
int BerUtil::putIndefiniteLengthOctet(bsl::streambuf *streamBuf)
{
return BerUtil_LengthImpUtil::putIndefiniteLengthOctet(streamBuf);
}
inline
int BerUtil::putLength(bsl::streambuf *streamBuf, int length)
{
return BerUtil_LengthImpUtil::putLength(streamBuf, length);
}
template <typename TYPE>
inline
int BerUtil::putValue(bsl::streambuf *streamBuf,
const TYPE& value,
const BerEncoderOptions *options)
{
return BerUtil_PutValueImpUtil::putValue(streamBuf, value, options);
}
// ----------------------------
// struct BerUtil_StreambufUtil
// ----------------------------
// CLASS METHODS
inline
int BerUtil_StreambufUtil::peekChar(char *value, bsl::streambuf *streamBuf)
{
const bsl::streambuf::int_type byte = streamBuf->sgetc();
if (bsl::streambuf::traits_type::eof() == byte) {
return -1; // RETURN
}
*value = bsl::streambuf::traits_type::to_char_type(byte);
return 0;
}
inline
int BerUtil_StreambufUtil::getChars(char *buffer,
bsl::streambuf *streamBuf,
int bufferLength)
{
const bsl::streamsize numCharsRead =
streamBuf->sgetn(buffer, static_cast<bsl::streamsize>(bufferLength));
if (numCharsRead != static_cast<bsl::streamsize>(bufferLength)) {
return -1; // RETURN
}
return 0;
}
inline
int BerUtil_StreambufUtil::putChars(bsl::streambuf *streamBuf,
const char *buffer,
int bufferLength)
{
const bsl::streamsize numCharsWritten =
streamBuf->sputn(buffer, static_cast<bsl::streamsize>(bufferLength));
if (numCharsWritten != bufferLength) {
return -1; // RETURN
}
return 0;
}
// --------------------------------
// struct BerUtil_RawIntegerImpUtil
// --------------------------------
// CLASS METHODS
template <typename TYPE>
int BerUtil_RawIntegerImpUtil::putIntegerGivenLength(bsl::streambuf *streamBuf,
TYPE value,
int length)
{
enum { k_BDEM_SUCCESS = 0, k_BDEM_FAILURE = -1 };
if (length <= 0) {
return k_BDEM_FAILURE; // RETURN
}
static const bool isUnsigned = (TYPE(-1) > TYPE(0));
if (isUnsigned && (unsigned)length == sizeof(TYPE) + 1) {
static const TYPE SGN_BIT = static_cast<TYPE>(
static_cast<TYPE>(1)
<< (sizeof(TYPE) * Constants::k_NUM_BITS_PER_OCTET - 1));
// Length may be one greater than 'sizeof(TYPE)' only if type is
// unsigned and the high bit (normally the sign bit) is set. In this
// case, a leading zero octet is emitted.
if (!(value & SGN_BIT)) {
return k_BDEM_FAILURE; // RETURN
}
if (0 != streamBuf->sputc(0)) {
return k_BDEM_FAILURE; // RETURN
}
--length;
}
if (static_cast<unsigned>(length) > sizeof(TYPE)) {
return k_BDEM_FAILURE; // RETURN
}
#if BSLS_PLATFORM_IS_BIG_ENDIAN
return length == streamBuf->sputn(
static_cast<char *>(static_cast<void *>(&value)) +
sizeof(TYPE) - length,
length)
? k_BDEM_SUCCESS
: k_BDEM_FAILURE;
#else
char *dst = static_cast<char *>(static_cast<void *>(&value)) + length;
for (; length > 0; --length) {
unsigned char c = *--dst;
if (c != streamBuf->sputc(c)) {
return k_BDEM_FAILURE; // RETURN
}
}
return k_BDEM_SUCCESS;
#endif
}
// -----------------------------
// struct BerUtil_BooleanImpUtil
// -----------------------------
// Decoding
inline
int BerUtil_BooleanImpUtil::getBoolValue(bool *value,
bsl::streambuf *streamBuf,
int length)
{
if (1 != length) {
return -1; // RETURN
}
int intValue = streamBuf->sbumpc();
if (bsl::streambuf::traits_type::eof() == intValue) {
return -1; // RETURN
}
*value = 0 != intValue;
return 0;
}
// Encoding
inline
int BerUtil_BooleanImpUtil::putBoolValue(bsl::streambuf *streamBuf, bool value)
{
// It has been observed in practice that 'value' may refer to uninitialized
// or overwritten memory, in which case its value may neither be 'true' (1)
// nor 'false' (0). We assert here to ensure that users get a useful error
// message. Note that we assert (rather than returning an error code), as
// it is undefined behavior to examine the value of such an uninitialized
// 'bool'. Also note that gcc complains about this assert when used with
// the '-Wlogical-op' flag. Therefore, to silence this warning/error we
// cast the 'bool' value to a 'char *' and check the value referred to by
// the 'char *'.
BSLMF_ASSERT(sizeof(bool) == sizeof(char));
BSLS_ASSERT(0 == *static_cast<char *>(static_cast<void *>(&value)) ||
1 == *static_cast<char *>(static_cast<void *>(&value)));
typedef bsl::streambuf::char_type char_type;
if (0 != LengthUtil::putLength(streamBuf, 1)) {
return -1; // RETURN
}
if (static_cast<int>(value) !=
streamBuf->sputc(static_cast<char_type>(value ? 1 : 0))) {
return -1; // RETURN
}
return 0;
}
// -----------------------------
// struct BerUtil_IntegerImpUtil
// -----------------------------
// CLASS METHODS
template <typename TYPE>
int BerUtil_IntegerImpUtil::getNumOctetsToStream(TYPE value)
{
int numBytes = sizeof(TYPE);
BSLMF_ASSERT(sizeof(TYPE) > 1);
// The 2 double casts to 'TYPE' in this function are necessary because if
// the type is 64 bits the innermost cast is need to widen the constant
// before the shift, and the outermost cast is needed if the type is
// narrower than 'int'.
static const TYPE NEG_MASK = static_cast<TYPE>(
static_cast<TYPE>(0xff80)
<< ((sizeof(TYPE) - 2) * Constants::k_NUM_BITS_PER_OCTET));
if (0 == value) {
numBytes = 1;
}
else if (value > 0) {
static const TYPE SGN_BIT = static_cast<TYPE>(
static_cast<TYPE>(1)
<< (sizeof(TYPE) * Constants::k_NUM_BITS_PER_OCTET - 1));
if (value & SGN_BIT) {
// If 'value > 0' but the high bit (sign bit) is set, then this is
// an unsigned value and a leading zero byte must be emitted to
// prevent the value from looking like a negative value on the
// wire. The leading zero is followed by all of the bytes of the
// unsigned value.
return static_cast<int>(sizeof(TYPE) + 1); // RETURN
}
// This mask zeroes out the most significant byte and the first bit of
// the next byte.
static const TYPE POS_MASK = TYPE(~NEG_MASK);
while ((value & POS_MASK) == value) {
value = static_cast<TYPE>(value << 8);
// shift out redundant high-order 0x00
--numBytes;
}
}
else { // 0 > value
while ((value | NEG_MASK) == value) {
value = static_cast<TYPE>(value << 8);
// shift out redundant high-order 0xFF
--numBytes;
}
}
BSLS_ASSERT(numBytes > 0);
return numBytes;
}
template <typename TYPE>
int BerUtil_IntegerImpUtil::getIntegerValue(TYPE *value,
bsl::streambuf *streamBuf,
int length)
{
enum { k_SUCCESS = 0, k_FAILURE = -1 };
enum { k_SIGN_BIT_MASK = 0x80 };
static const bool isUnsigned = (TYPE(-1) > TYPE(0));
if (isUnsigned && static_cast<unsigned>(length) == sizeof(TYPE) + 1) {
// Length of an unsigned is allowed to be one larger then
// 'sizeof(TYPE)' only if first byte is zero. (This is so that large
// unsigned numbers do not appear as negative numbers in the BER
// stream). Remove the leading zero byte.
if (0 != streamBuf->sbumpc()) {
// First byte was not zero. Fail.
return k_FAILURE; // RETURN
}
--length;
}
if (static_cast<unsigned>(length) > sizeof(TYPE)) {
// Overflow.
return k_FAILURE; // RETURN
}
*value = static_cast<TYPE>(streamBuf->sgetc() & k_SIGN_BIT_MASK ? -1 : 0);
for (int i = 0; i < length; ++i) {
int nextOctet = streamBuf->sbumpc();
if (bsl::streambuf::traits_type::eof() == nextOctet) {
return k_FAILURE; // RETURN
}
const unsigned long long mask =
(1ull << ((sizeof(TYPE) - 1) * Constants::k_NUM_BITS_PER_OCTET)) -
1;
*value = static_cast<TYPE>((*value & mask)
<< Constants::k_NUM_BITS_PER_OCTET);
*value =
static_cast<TYPE>(*value | static_cast<unsigned char>(nextOctet));
}
return k_SUCCESS;
}
inline
int BerUtil_IntegerImpUtil::get40BitIntegerValue(bsls::Types::Int64 *value,
bsl::streambuf *streamBuf)
{
char bytes[5];
if (0 != StreambufUtil::getChars(bytes, streamBuf, sizeof(bytes))) {
return -1; // RETURN
}
const bsls::Types::Uint64 byte0 =
static_cast<bsls::Types::Uint64>(static_cast<unsigned char>(bytes[0]))
<< (8 * 4);
const bsls::Types::Uint64 byte1 =
static_cast<bsls::Types::Uint64>(static_cast<unsigned char>(bytes[1]))
<< (8 * 3);
const bsls::Types::Uint64 byte2 =
static_cast<bsls::Types::Uint64>(static_cast<unsigned char>(bytes[2]))
<< (8 * 2);
const bsls::Types::Uint64 byte3 =
static_cast<bsls::Types::Uint64>(static_cast<unsigned char>(bytes[3]))
<< (8 * 1);
const bsls::Types::Uint64 byte4 =
static_cast<bsls::Types::Uint64>(static_cast<unsigned char>(bytes[4]))
<< (8 * 0);
const bsls::Types::Uint64 unsignedValue =
byte0 + byte1 + byte2 + byte3 + byte4;
*value = static_cast<bsls::Types::Int64>(unsignedValue);
return 0;
}
template <typename TYPE>
int BerUtil_IntegerImpUtil::putIntegerValue(bsl::streambuf *streamBuf,
TYPE value)
{
typedef bsl::streambuf::char_type char_type;
const int length = getNumOctetsToStream(value);
if (length != streamBuf->sputc(static_cast<char_type>(length))) {
return -1; // RETURN
}
return putIntegerGivenLength(streamBuf, value, length);
}
template <typename TYPE>
int BerUtil_IntegerImpUtil::putIntegerGivenLength(bsl::streambuf *streamBuf,
TYPE value,
int length)
{
return RawIntegerUtil::putIntegerGivenLength(streamBuf, value, length);
}
inline
int BerUtil_IntegerImpUtil::put40BitIntegerValue(bsl::streambuf *streamBuf,
bsls::Types::Int64 value)
///Implementation Note
///-------------------
// This implementation requires the platform use a 2's complement
// representation for signed integer values.
{
BSLS_ASSERT(-549755813888ll <= value);
BSLS_ASSERT(549755813888ll > value);
const bsls::Types::Uint64 unsignedValue = value;
const char bytes[5] = {
static_cast<char>(
static_cast<unsigned char>((unsignedValue >> (8 * 4)) & 0xFF)),
static_cast<char>(
static_cast<unsigned char>((unsignedValue >> (8 * 3)) & 0xFF)),
static_cast<char>(
static_cast<unsigned char>((unsignedValue >> (8 * 2)) & 0xFF)),
static_cast<char>(
static_cast<unsigned char>((unsignedValue >> (8 * 1)) & 0xFF)),
static_cast<char>(
static_cast<unsigned char>((unsignedValue >> (8 * 0)) & 0xFF))};
return StreambufUtil::putChars(streamBuf, bytes, sizeof(bytes));
}
// -------------------------------
// struct BerUtil_CharacterImpUtil
// -------------------------------
// CLASS METHODS
// Decoding
inline
int BerUtil_CharacterImpUtil::getCharValue(char *value,
bsl::streambuf *streamBuf,
int length)
{
switch (length) {
case 1: {
; // do nothing
} break;
case 2: {
if (0 != streamBuf->sbumpc()) {
// see 'getIntegerValue', if this 'char' had been encoded as
// 'unsigned' there might be a leading 0 which is acceptable, but
// any other value for the first byte is invalid
return -1; // RETURN
}
} break;
default: {
return -1; // RETURN
}
}
int valueOctet = streamBuf->sbumpc();
if (bsl::streambuf::traits_type::eof() == valueOctet) {
return -1; // RETURN
}
*value = static_cast<char>(valueOctet);
return 0;
}
inline
int BerUtil_CharacterImpUtil::getSignedCharValue(signed char *value,
bsl::streambuf *streamBuf,
int length)
{
char temp;
if (0 != getCharValue(&temp, streamBuf, length)) {
return -1; // RETURN
}
*value = static_cast<signed char>(temp);
return 0;
}
inline
int BerUtil_CharacterImpUtil::getUnsignedCharValue(unsigned char *value,
bsl::streambuf *streamBuf,
int length)
{
short temp;
if (IntegerUtil::getIntegerValue(&temp, streamBuf, length)) {
return -1; // RETURN
}
*value = static_cast<unsigned char>(temp);
return 0;
}
// Encoding
inline
int BerUtil_CharacterImpUtil::putCharValue(bsl::streambuf *streamBuf,
char value)
{
if (0 != LengthUtil::putLength(streamBuf, 1)) {
return -1; // RETURN
}
if (static_cast<unsigned char>(value) != streamBuf->sputc(value)) {
return -1; // RETURN
}
return 0;
}
inline
int BerUtil_CharacterImpUtil::putSignedCharValue(bsl::streambuf *streamBuf,
signed char value)
{
return putCharValue(streamBuf, static_cast<char>(value));
}
inline
int BerUtil_CharacterImpUtil::putUnsignedCharValue(bsl::streambuf *streamBuf,
unsigned char value)
{
return IntegerUtil::putIntegerValue(streamBuf,
static_cast<unsigned short>(value));
}
// -----------------------------------
// struct BerUtil_FloatingPointImpUtil
// -----------------------------------
// CLASS METHODS
// Decoding
inline
int BerUtil_FloatingPointImpUtil::getFloatValue(float *value,
bsl::streambuf *streamBuf,
int length)
{
double tentativeValue;
if (0 != getDoubleValue(&tentativeValue, streamBuf, length)) {
return -1; // RETURN
}
*value = static_cast<float>(tentativeValue);
return 0;
}
// Encoding
inline
int BerUtil_FloatingPointImpUtil::putFloatValue(
bsl::streambuf *streamBuf,
float value,
const BerEncoderOptions *options)
{
return putDoubleValue(streamBuf,
static_cast<double>(value),
options);
}
// ----------------------------
// struct BerUtil_StringImpUtil
// ----------------------------
// CLASS METHODS
// Encoding Utilities
inline
int BerUtil_StringImpUtil::putRawStringValue(bsl::streambuf *streamBuf,
const char *value,
int valueLength)
{
if (0 != LengthUtil::putLength(streamBuf, valueLength)) {
return -1; // RETURN
}
if (valueLength != streamBuf->sputn(value, valueLength)) {
return -1; // RETURN
}
return 0;
}
// 'bsl::string' Encoding
inline
int BerUtil_StringImpUtil::putStringValue(bsl::streambuf *streamBuf,
const bsl::string& value)
{
return putRawStringValue(
streamBuf, value.data(), static_cast<int>(value.length()));
}
// 'bslstl::StringRef' Encoding
inline
int BerUtil_StringImpUtil::putStringRefValue(
bsl::streambuf *streamBuf,
const bslstl::StringRef& value)
{
return putRawStringValue(
streamBuf, value.data(), static_cast<int>(value.length()));
}
// -----------------------------
// struct BerUtil_Iso8601ImpUtil
// -----------------------------
// PRIVATE CLASS METHODS
template <class TYPE>
int BerUtil_Iso8601ImpUtil::getValue(TYPE *value,
bsl::streambuf *streamBuf,
int length)
{
if (length <= 0) {
return -1; // RETURN
}
char localBuf[32]; // for common case where length < 32
bsl::vector<char> vecBuf; // for length >= 32
char *buf;
if (length < 32) {
buf = localBuf;
}
else {
vecBuf.resize(length);
buf = &vecBuf[0]; // First byte of contiguous string
}
const bsl::streamsize bytesConsumed = streamBuf->sgetn(buf, length);
if (static_cast<int>(bytesConsumed) != length) {
return -1; // RETURN
}
return bdlt::Iso8601Util::parse(value, buf, length);
}
template <class TYPE>
int BerUtil_Iso8601ImpUtil::putValue(bsl::streambuf *streamBuf,
const TYPE& value,
const BerEncoderOptions *options)
{
char buf[bdlt::Iso8601Util::k_MAX_STRLEN];
bdlt::Iso8601UtilConfiguration config;
int datetimeFractionalSecondPrecision =
options ? options->datetimeFractionalSecondPrecision() : 6;
config.setFractionalSecondPrecision(datetimeFractionalSecondPrecision);
int len = bdlt::Iso8601Util::generate(buf, sizeof(buf), value, config);
return StringUtil::putStringRefValue(streamBuf,
bslstl::StringRef(buf, len));
}
// --------------------------------------
// struct BerUtil_ExtendedBinaryEncodingUtil
// --------------------------------------
// CLASS METHODS
inline
bool BerUtil_ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(
const bdlt::Time& value,
const BerEncoderOptions *options)
{
if (!options) {
// If encoding options are not specified, by default the ISO8601 format
// is used.
return false; // RETURN
}
const bool useBinaryEncoding = options->encodeDateAndTimeTypesAsBinary();
const bool useMicrosecondPrecision =
(6 == options->datetimeFractionalSecondPrecision());
const bool compactBinaryEncodingOfValueIsBuggy = (bdlt::Time() == value);
// The compact binary encoding format ambiguously encodes both the
// '00:00:00' time value and the '24:00:00' time value to the same bit
// pattern. The decoder treats this bit pattern as the '00:00:00' time
// value. The extended binary encoding format does not have this
// limitation. Therefore, if the extended binary format is allowed, it
// should be used to encode default time values even if the fractional
// second precision is not 6.
const bool useExtendedBinaryEncodingIfAllowed =
useMicrosecondPrecision || compactBinaryEncodingOfValueIsBuggy;
const bool extendedBinaryEncodingIsAllowed =
(options->bdeVersionConformance() >=
Encoding::k_EXTENDED_BINARY_MIN_BDE_VERSION);
return useBinaryEncoding && useExtendedBinaryEncodingIfAllowed &&
extendedBinaryEncodingIsAllowed;
}
inline
bool BerUtil_ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(
const bdlt::TimeTz& value,
const BerEncoderOptions *options)
{
return useExtendedBinaryEncoding(value.localTime(), options);
}
inline
bool BerUtil_ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(
const bdlt::Datetime& value,
const BerEncoderOptions *options)
{
return useExtendedBinaryEncoding(value.time(), options);
}
inline
bool BerUtil_ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options)
{
return useExtendedBinaryEncoding(value.localDatetime().time(), options);
}
inline
bool BerUtil_ExtendedBinaryEncodingUtil::useBinaryEncoding(
const BerEncoderOptions *options)
{
return options && options->encodeDateAndTimeTypesAsBinary();
}
// -------------------------------
// class BerUtil_DateAndTimeHeader
// -------------------------------
// CREATORS
inline
BerUtil_DateAndTimeHeader::BerUtil_DateAndTimeHeader()
: d_type(Type::e_NOT_EXTENDED_BINARY)
, d_timezoneOffsetInMinutes(0)
{
}
// MANIPULATORS
inline
void BerUtil_DateAndTimeHeader::makeNotExtendedBinary()
{
d_type = Type::e_NOT_EXTENDED_BINARY;
d_timezoneOffsetInMinutes = 0;
}
inline
void BerUtil_DateAndTimeHeader::makeExtendedBinaryWithoutTimezone()
{
d_type = Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE;
d_timezoneOffsetInMinutes = 0;
}
inline
void BerUtil_DateAndTimeHeader::makeExtendedBinaryWithTimezone(int offset)
{
BSLS_ASSERT(TimezoneUtil::isValidTimezoneOffsetInMinutes(offset));
d_type = Type::e_EXTENDED_BINARY_WITH_TIMEZONE;
d_timezoneOffsetInMinutes = offset;
}
// ACCESSORS
inline
bool BerUtil_DateAndTimeHeader::isExtendedBinary() const
{
return (Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE == d_type) ||
(Type::e_EXTENDED_BINARY_WITH_TIMEZONE == d_type);
}
inline
bool BerUtil_DateAndTimeHeader::isExtendedBinaryWithoutTimezone() const
{
return Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE == d_type;
}
inline
bool BerUtil_DateAndTimeHeader::isExtendedBinaryWithTimezone() const
{
return Type::e_EXTENDED_BINARY_WITH_TIMEZONE == d_type;
}
inline
int BerUtil_DateAndTimeHeader::timezoneOffsetInMinutes() const
{
return d_timezoneOffsetInMinutes;
}
// ---------------------------------------
// struct BerUtil_DateAndTimeHeaderImpUtil
// ---------------------------------------
// CLASS METHODS
inline
bool BerUtil_DateAndTimeHeaderImpUtil::isReserved(unsigned char firstByte)
{
// A date-and-time header has a reserved bit pattern if:
//..
// o the first bit is 1, and any of the following are true:
// o the second bit is 1
// o the third bit is 1
//..
const bool bit0 = firstByte & 0x80;
const bool bit1 = firstByte & 0x40;
const bool bit2 = firstByte & 0x20;
return bit0 && (bit1 || bit2);
}
inline
bool BerUtil_DateAndTimeHeaderImpUtil::isExtendedBinary(
unsigned char firstByte)
{
const bool bit0 = firstByte & 0x80;
const bool bit1 = firstByte & 0x40;
const bool bit2 = firstByte & 0x20;
return bit0 && !(bit1 || bit2);
}
inline
bool BerUtil_DateAndTimeHeaderImpUtil::isExtendedBinaryWithoutTimezone(
unsigned char firstByte)
{
const bool bit0 = firstByte & 0x80;
const bool bit1 = firstByte & 0x40;
const bool bit2 = firstByte & 0x20;
const bool bit3 = firstByte & 0x10;
return bit0 && !(bit1 || bit2) && !bit3;
}
inline
bool BerUtil_DateAndTimeHeaderImpUtil::isExtendedBinaryWithTimezone(
unsigned char firstByte)
{
const bool bit0 = firstByte & 0x80;
const bool bit1 = firstByte & 0x40;
const bool bit2 = firstByte & 0x20;
const bool bit3 = firstByte & 0x10;
return bit0 && !(bit1 || bit2) && bit3;
}
inline
void BerUtil_DateAndTimeHeaderImpUtil::detectTypeIfNotReserved(
bool *reserved,
Type::Value *type,
unsigned char firstByte)
{
if (isReserved(firstByte)) {
*reserved = true;
return; // RETURN
}
*reserved = false;
detectType(type, firstByte);
}
inline
void BerUtil_DateAndTimeHeaderImpUtil::detectType(Type::Value *type,
unsigned char firstByte)
{
BSLS_ASSERT_OPT(!isReserved(firstByte));
const bool bit0 = firstByte & 0x80;
const bool bit3 = firstByte & 0x10;
if (bit0 & bit3) {
*type = Type::e_EXTENDED_BINARY_WITH_TIMEZONE;
return; // RETURN
}
if (bit0 & !bit3) {
*type = Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE;
return; // RETURN
}
*type = Type::e_NOT_EXTENDED_BINARY;
}
inline
int BerUtil_DateAndTimeHeaderImpUtil::getValueIfNotReserved(
Header *value,
bsl::streambuf *streamBuf)
{
char headerBytes[2];
if (0 !=
StreambufUtil::getChars(headerBytes, streamBuf, sizeof(headerBytes))) {
return -1; // RETURN
}
const unsigned char headerByte0 =
static_cast<unsigned char>(headerBytes[0]);
const unsigned char headerByte1 =
static_cast<unsigned char>(headerBytes[1]);
return getValueIfNotReserved(value, headerByte0, headerByte1);
}
inline
int BerUtil_DateAndTimeHeaderImpUtil::getValueIfNotReserved(
Header *value,
unsigned char headerByte0,
unsigned char headerByte1)
{
if (isReserved(headerByte0)) {
return -1; // RETURN
}
return getValue(value, headerByte0, headerByte1);
}
inline
int BerUtil_DateAndTimeHeaderImpUtil::getValue(Header *value,
bsl::streambuf *streamBuf)
{
char headerBytes[2];
if (0 !=
StreambufUtil::getChars(headerBytes, streamBuf, sizeof(headerBytes))) {
return -1; // RETURN
}
const unsigned char headerByte0 =
static_cast<unsigned char>(headerBytes[0]);
const unsigned char headerByte1 =
static_cast<unsigned char>(headerBytes[1]);
return getValue(value, headerByte0, headerByte1);
}
inline
int BerUtil_DateAndTimeHeaderImpUtil::getValue(Header *value,
unsigned char headerByte0,
unsigned char headerByte1)
{
BSLS_ASSERT_OPT(!isReserved(headerByte0));
Type::Value type;
detectType(&type, headerByte0);
switch (type) {
case Type::e_NOT_EXTENDED_BINARY: {
value->makeNotExtendedBinary();
return 0; // RETURN
} break;
case Type::e_EXTENDED_BINARY_WITHOUT_TIMEZONE: {
// If the header indicates that it does not carry time-zone
// information, and the low 12 bits of the header are non-zero, then
// the header is malformed.
if ((headerByte0 & 0x0F) | (headerByte1 & 0xFF)) {
return -1; // RETURN
}
value->makeExtendedBinaryWithoutTimezone();
return 0; // RETURN
} break;
case Type::e_EXTENDED_BINARY_WITH_TIMEZONE: {
enum { k_TIMEZONE_SIGN_BIT = 0x08 };
// If the time-zone offset's sign bit is 1, then sign-extend the low
// nibble of the first byte, which encodes the 4 hi bits of the
// 12-bit, 2's-complement number that represents the time-zone offset
// in minutes.
const unsigned char timezoneOffsetHi =
(headerByte0 & k_TIMEZONE_SIGN_BIT)
? ((0x0F & headerByte0) | 0xF0)
: ((0x0F & headerByte0) | 0x00);
const signed char signedTimezoneOffsetHi =
static_cast<signed char>(timezoneOffsetHi);
const unsigned char timezoneOffsetLo = headerByte1;
const int timezoneOffset =
(static_cast<int>(signedTimezoneOffsetHi) << 8) |
(static_cast<int>(timezoneOffsetLo) << 0);
if (!TimezoneUtil::isValidTimezoneOffsetInMinutes(timezoneOffset)) {
return -1; // RETURN
}
value->makeExtendedBinaryWithTimezone(timezoneOffset);
return 0; // RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
inline
int BerUtil_DateAndTimeHeaderImpUtil::putExtendedBinaryWithoutTimezoneValue(
bsl::streambuf *streamBuf)
{
static const char header[k_HEADER_LENGTH] = {'\x80', '\x00'};
return StreambufUtil::putChars(streamBuf, header, k_HEADER_LENGTH);
}
inline
int BerUtil_DateAndTimeHeaderImpUtil::putExtendedBinaryWithTimezoneValue(
bsl::streambuf *streamBuf,
int timezoneOffsetInMinutes)
{
BSLS_ASSERT(
TimezoneUtil::isValidTimezoneOffsetInMinutes(timezoneOffsetInMinutes));
const unsigned short offsetWord =
static_cast<unsigned short>(timezoneOffsetInMinutes);
static const unsigned short k_OFFSET_MASK = 0x0FFF;
const unsigned short headerWord = 0x9000 | (offsetWord & k_OFFSET_MASK);
const char header[k_HEADER_LENGTH] = {
static_cast<char>((headerWord >> 8) & 0xFF),
static_cast<char>((headerWord >> 0) & 0xFF)};
return StreambufUtil::putChars(streamBuf, header, k_HEADER_LENGTH);
}
// --------------------------
// struct BerUtil_DateImpUtil
// --------------------------
// PRIVATE CLASS METHODS
// 'bdlt::Date' Decoding
inline
int BerUtil_DateImpUtil::detectDateEncoding(DateEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
if (k_MAX_COMPACT_BINARY_DATE_LENGTH >= length) {
*encoding = DateEncoding::e_COMPACT_BINARY_DATE;
return 0; // RETURN
}
BSLS_ASSERT_SAFE(k_MAX_COMPACT_BINARY_DATE_LENGTH < length);
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
*encoding = DateEncoding::e_ISO8601_DATE;
return 0;
}
// 'bdlt::Date' Encoding
inline
BerUtil_DateEncoding::Value BerUtil_DateImpUtil::selectDateEncoding(
const bdlt::Date&,
const BerEncoderOptions *options)
{
if (options && options->encodeDateAndTimeTypesAsBinary()) {
return DateEncoding::e_COMPACT_BINARY_DATE; // RETURN
}
return DateEncoding::e_ISO8601_DATE;
}
// 'bdlt::DateTz' Decoding
inline
int BerUtil_DateImpUtil::detectDateTzEncoding(DateTzEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
BSLMF_ASSERT(k_MAX_COMPACT_BINARY_DATE_LENGTH <
k_MIN_COMPACT_BINARY_DATETZ_LENGTH);
if (k_MIN_COMPACT_BINARY_DATETZ_LENGTH > length) {
*encoding = DateTzEncoding::e_COMPACT_BINARY_DATE;
return 0; // RETURN
}
if (k_MAX_COMPACT_BINARY_DATETZ_LENGTH >= length) {
*encoding = DateTzEncoding::e_COMPACT_BINARY_DATETZ;
return 0; // RETURN
}
BSLS_ASSERT_SAFE(k_MAX_COMPACT_BINARY_DATETZ_LENGTH < length);
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
*encoding = DateTzEncoding::e_ISO8601_DATETZ;
return 0;
}
// 'bdlt::DateTz' Encoding
inline
BerUtil_DateTzEncoding::Value BerUtil_DateImpUtil::selectDateTzEncoding(
const bdlt::DateTz& value,
const BerEncoderOptions *options)
{
if (options && options->encodeDateAndTimeTypesAsBinary() &&
0 == value.offset()) {
return DateTzEncoding::e_COMPACT_BINARY_DATE; // RETURN
}
if (options && options->encodeDateAndTimeTypesAsBinary()) {
return DateTzEncoding::e_COMPACT_BINARY_DATETZ; // RETURN
}
return DateTzEncoding::e_ISO8601_DATETZ;
}
// Variant Decoding
inline
int BerUtil_DateImpUtil::detectDateOrDateTzEncoding(
DateOrDateTzEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
if (k_MAX_COMPACT_BINARY_DATE_LENGTH >= length) {
*encoding = DateOrDateTzEncoding::e_COMPACT_BINARY_DATE;
return 0; // RETURN
}
BSLS_ASSERT_SAFE(k_MAX_COMPACT_BINARY_DATE_LENGTH < length);
if (k_MAX_COMPACT_BINARY_DATETZ_LENGTH >= length) {
*encoding = DateOrDateTzEncoding::e_COMPACT_BINARY_DATETZ;
return 0; // RETURN
}
BSLS_ASSERT_SAFE(k_MAX_COMPACT_BINARY_DATETZ_LENGTH < length);
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
if (k_MAX_ISO8601_DATE_LENGTH >= length) {
*encoding = DateOrDateTzEncoding::e_ISO8601_DATE;
return 0; // RETURN
}
BSLS_ASSERT_SAFE(k_MAX_ISO8601_DATE_LENGTH < length);
*encoding = DateOrDateTzEncoding::e_ISO8601_DATETZ;
return 0;
}
inline
int BerUtil_DateImpUtil::getIso8601DateValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Date>();
return getIso8601DateValue(&value->the<bdlt::Date>(), streamBuf, length);
}
inline
int BerUtil_DateImpUtil::getIso8601DateTzValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::DateTz>();
return getIso8601DateTzValue(
&value->the<bdlt::DateTz>(), streamBuf, length);
}
inline
int BerUtil_DateImpUtil::getCompactBinaryDateValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Date>();
return getCompactBinaryDateValue(
&value->the<bdlt::Date>(), streamBuf, length);
}
inline
int BerUtil_DateImpUtil::getCompactBinaryDateTzValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::DateTz>();
return getCompactBinaryDateTzValue(
&value->the<bdlt::DateTz>(), streamBuf, length);
}
// CLASS METHODS
// Variant Decoding
inline
int BerUtil_DateImpUtil::getDateOrDateTzValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length)
{
char firstByte;
if (0 != StreambufUtil::peekChar(&firstByte, streamBuf)) {
return -1; // RETURN
}
DateOrDateTzEncoding::Value encoding;
int rc = detectDateOrDateTzEncoding(&encoding, length, firstByte);
if (0 != rc) {
return -1; // RETURN
}
switch (encoding) {
case DateOrDateTzEncoding::e_ISO8601_DATE: {
return getIso8601DateValue(value, streamBuf, length); // RETURN
} break;
case DateOrDateTzEncoding::e_ISO8601_DATETZ: {
return getIso8601DateTzValue(value, streamBuf, length); // RETURN
} break;
case DateOrDateTzEncoding::e_COMPACT_BINARY_DATE: {
return getCompactBinaryDateValue(value, streamBuf, length); // RETURN
} break;
case DateOrDateTzEncoding::e_COMPACT_BINARY_DATETZ: {
return getCompactBinaryDateTzValue(value, streamBuf, length);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// --------------------------
// struct BerUtil_TimeImpUtil
// --------------------------
// PRIVATE CLASS METHODS
// Utilities
inline
void BerUtil_DateImpUtil::dateToDaysSinceEpoch(
bsls::Types::Int64 *daysSinceEpoch,
const bdlt::Date& date)
{
const int serialDate = bdlt::ProlepticDateImpUtil::ymdToSerial(
date.year(), date.month(), date.day());
*daysSinceEpoch = serialDate - k_COMPACT_BINARY_DATE_EPOCH;
}
inline
int BerUtil_DateImpUtil::daysSinceEpochToDate(
bdlt::Date *date,
bsls::Types::Int64 daysSinceEpoch)
{
const bsls::Types::Int64 serialDate =
daysSinceEpoch + k_COMPACT_BINARY_DATE_EPOCH;
if (!bdlt::ProlepticDateImpUtil::isValidSerial(
static_cast<int>(serialDate))) {
return -1; // RETURN
}
int year;
int month;
int day;
bdlt::ProlepticDateImpUtil::serialToYmd(
&year, &month, &day, static_cast<int>(serialDate));
date->setYearMonthDay(year, month, day);
return 0;
}
// 'bdlt::Time' Decoding
inline
int BerUtil_TimeImpUtil::detectTimeEncoding(TimeEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
if (k_MAX_COMPACT_BINARY_TIME_LENGTH >= length) {
*encoding = TimeEncoding::e_COMPACT_BINARY_TIME;
return 0; // RETURN
}
BSLS_ASSERT_SAFE(k_MAX_COMPACT_BINARY_TIME_LENGTH < length);
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinary(firstByte)) {
*encoding = TimeEncoding::e_EXTENDED_BINARY_TIME;
return 0; // RETURN
}
*encoding = TimeEncoding::e_ISO8601_TIME;
return 0;
}
inline
int BerUtil_TimeImpUtil::getIso8601TimeValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length)
{
return Iso8601Util::getTimeValue(value, streamBuf, length);
}
// 'bdlt::Time' Encoding
inline
BerUtil_TimeEncoding::Value BerUtil_TimeImpUtil::selectTimeEncoding(
const bdlt::Time& value,
const BerEncoderOptions *options)
{
if (ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(value,
options)) {
return TimeEncoding::e_EXTENDED_BINARY_TIME; // RETURN
}
if (ExtendedBinaryEncodingUtil::useBinaryEncoding(options)) {
return TimeEncoding::e_COMPACT_BINARY_TIME; // RETURN
}
return TimeEncoding::e_ISO8601_TIME;
}
inline
int BerUtil_TimeImpUtil::putIso8601TimeValue(
bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options)
{
return Iso8601Util::putTimeValue(streamBuf, value, options);
}
// 'bdlt::Time' Decoding
inline
int BerUtil_TimeImpUtil::detectTimeTzEncoding(TimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
BSLMF_ASSERT(k_MAX_COMPACT_BINARY_TIME_LENGTH <
k_MIN_COMPACT_BINARY_TIMETZ_LENGTH);
BSLMF_ASSERT(k_MIN_COMPACT_BINARY_TIMETZ_LENGTH <=
k_MAX_COMPACT_BINARY_TIMETZ_LENGTH);
if (k_MAX_COMPACT_BINARY_TIME_LENGTH >= length) {
*encoding = TimeTzEncoding::e_COMPACT_BINARY_TIME;
return 0; // RETURN
}
if (k_MAX_COMPACT_BINARY_TIMETZ_LENGTH >= length) {
*encoding = TimeTzEncoding::e_COMPACT_BINARY_TIMETZ;
return 0; // RETURN
}
BSLS_ASSERT(k_MAX_COMPACT_BINARY_TIMETZ_LENGTH < length);
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinary(firstByte)) {
*encoding = TimeTzEncoding::e_EXTENDED_BINARY_TIMETZ;
return 0; // RETURN
}
*encoding = TimeTzEncoding::e_ISO8601_TIMETZ;
return 0;
}
inline
int BerUtil_TimeImpUtil::getIso8601TimeTzValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
return Iso8601Util::getTimeTzValue(value, streamBuf, length);
}
// 'bdlt::TimeTz' Encoding
inline
BerUtil_TimeTzEncoding::Value BerUtil_TimeImpUtil::selectTimeTzEncoding(
const bdlt::TimeTz& value,
const BerEncoderOptions *options)
{
if (ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(value,
options)) {
return TimeTzEncoding::e_EXTENDED_BINARY_TIMETZ; // RETURN
}
if (ExtendedBinaryEncodingUtil::useBinaryEncoding(options) &&
(0 == value.offset())) {
return TimeTzEncoding::e_COMPACT_BINARY_TIME; // RETURN
}
if (ExtendedBinaryEncodingUtil::useBinaryEncoding(options)) {
return TimeTzEncoding::e_COMPACT_BINARY_TIMETZ; // RETURN
}
return TimeTzEncoding::e_ISO8601_TIMETZ;
}
inline
int BerUtil_TimeImpUtil::putIso8601TimeTzValue(
bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options)
{
return Iso8601Util::putTimeTzValue(streamBuf, value, options);
}
// Variant Decoding
inline
int BerUtil_TimeImpUtil::detectTimeOrTimeTzEncoding(
TimeOrTimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
if (k_MAX_COMPACT_BINARY_TIME_LENGTH >= length) {
*encoding = TimeOrTimeTzEncoding::e_COMPACT_BINARY_TIME;
return 0; // RETURN
}
if (k_MAX_COMPACT_BINARY_TIMETZ_LENGTH >= length) {
*encoding = TimeOrTimeTzEncoding::e_COMPACT_BINARY_TIMETZ;
return 0; // RETURN
}
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinaryWithoutTimezone(firstByte)) {
*encoding = TimeOrTimeTzEncoding::e_EXTENDED_BINARY_TIME;
return 0; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinaryWithTimezone(firstByte)) {
*encoding = TimeOrTimeTzEncoding::e_EXTENDED_BINARY_TIMETZ;
return 0; // RETURN
}
if (k_MAX_ISO8601_TIME_LENGTH >= length) {
*encoding = TimeOrTimeTzEncoding::e_ISO8601_TIME;
return 0; // RETURN
}
*encoding = TimeOrTimeTzEncoding::e_ISO8601_TIMETZ;
return 0;
}
inline
int BerUtil_TimeImpUtil::getIso8601TimeValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Time>();
return getIso8601TimeValue(&value->the<bdlt::Time>(), streamBuf, length);
}
inline
int BerUtil_TimeImpUtil::getIso8601TimeTzValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::TimeTz>();
return getIso8601TimeTzValue(
&value->the<bdlt::TimeTz>(), streamBuf, length);
}
inline
int BerUtil_TimeImpUtil::getCompactBinaryTimeValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Time>();
return getCompactBinaryTimeValue(
&value->the<bdlt::Time>(), streamBuf, length);
}
inline
int BerUtil_TimeImpUtil::getCompactBinaryTimeTzValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::TimeTz>();
return getCompactBinaryTimeTzValue(
&value->the<bdlt::TimeTz>(), streamBuf, length);
}
inline
int BerUtil_TimeImpUtil::getExtendedBinaryTimeValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Time>();
return getExtendedBinaryTimeValue(
&value->the<bdlt::Time>(), streamBuf, length);
}
inline
int BerUtil_TimeImpUtil::getExtendedBinaryTimeTzValue(
TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::TimeTz>();
return getExtendedBinaryTimeTzValue(
&value->the<bdlt::TimeTz>(), streamBuf, length);
}
// CLASS METHODS
// Utilities
inline
void BerUtil_TimeImpUtil::timeToMillisecondsSinceMidnight(
int *millisecondsSinceMidnight,
const bdlt::Time& time)
{
const bdlt::Time defaultTime;
*millisecondsSinceMidnight =
static_cast<int>((time - defaultTime).totalMilliseconds());
}
inline
void BerUtil_TimeImpUtil::timeToMicrosecondsSinceMidnight(
bsls::Types::Int64 *millisecondsSinceMidnight,
const bdlt::Time& time)
{
typedef bdlt::TimeUnitRatio Ratio;
typedef bsls::Types::Int64 Int64;
*millisecondsSinceMidnight =
static_cast<Int64>(time.hour()) * Ratio::k_MICROSECONDS_PER_HOUR +
static_cast<Int64>(time.minute()) * Ratio::k_MICROSECONDS_PER_MINUTE +
static_cast<Int64>(time.second()) * Ratio::k_MICROSECONDS_PER_SECOND +
static_cast<Int64>(time.millisecond()) *
Ratio::k_MICROSECONDS_PER_MILLISECOND +
static_cast<Int64>(time.microsecond());
}
inline
int BerUtil_TimeImpUtil::millisecondsSinceMidnightToTime(
bdlt::Time *time,
int millisecondsSinceMidnight)
{
typedef bdlt::TimeUnitRatio Ratio;
static const int k_MIN_NUM_MILLISECONDS = 0;
static const int k_MAX_NUM_MILLISECONDS =
24 * Ratio::k_MILLISECONDS_PER_HOUR;
if (k_MIN_NUM_MILLISECONDS > millisecondsSinceMidnight) {
return -1; // RETURN
}
if (k_MAX_NUM_MILLISECONDS < millisecondsSinceMidnight) {
return -1; // RETURN
}
const int serialTime = millisecondsSinceMidnight;
const int hour = serialTime / Ratio::k_MILLISECONDS_PER_HOUR_32;
const int minute =
(serialTime - hour * Ratio::k_MILLISECONDS_PER_HOUR_32) /
Ratio::k_MILLISECONDS_PER_MINUTE_32;
const int second = (serialTime - hour * Ratio::k_MILLISECONDS_PER_HOUR_32 -
minute * Ratio::k_MILLISECONDS_PER_MINUTE_32) /
Ratio::k_MILLISECONDS_PER_SECOND_32;
const int millisecond =
(serialTime - hour * Ratio::k_MILLISECONDS_PER_HOUR_32 -
minute * Ratio::k_MILLISECONDS_PER_MINUTE_32 -
second * Ratio::k_MILLISECONDS_PER_SECOND_32);
time->setTime(hour, minute, second, millisecond);
return 0;
}
inline
int BerUtil_TimeImpUtil::microsecondsSinceMidnightToTime(
bdlt::Time *time,
bsls::Types::Int64 microsecondsSinceMidnight)
{
typedef bdlt::TimeUnitRatio Ratio;
static const bsls::Types::Int64 k_MIN_NUM_MICROSECONDS = 0;
static const bsls::Types::Int64 k_MAX_NUM_MICROSECONDS =
24 * Ratio::k_MICROSECONDS_PER_HOUR;
if (k_MIN_NUM_MICROSECONDS > microsecondsSinceMidnight) {
return -1; // RETURN
}
if (k_MAX_NUM_MICROSECONDS < microsecondsSinceMidnight) {
return -1; // RETURN
}
const bsls::Types::Int64 serialTime = microsecondsSinceMidnight;
const int hour =
static_cast<int>(serialTime / Ratio::k_MICROSECONDS_PER_HOUR);
const int minute =
static_cast<int>((serialTime - hour * Ratio::k_MICROSECONDS_PER_HOUR) /
Ratio::k_MICROSECONDS_PER_MINUTE);
const int second =
static_cast<int>((serialTime - hour * Ratio::k_MICROSECONDS_PER_HOUR -
minute * Ratio::k_MICROSECONDS_PER_MINUTE) /
Ratio::k_MICROSECONDS_PER_SECOND);
const int millisecond =
static_cast<int>((serialTime - hour * Ratio::k_MICROSECONDS_PER_HOUR -
minute * Ratio::k_MICROSECONDS_PER_MINUTE -
second * Ratio::k_MICROSECONDS_PER_SECOND) /
Ratio::k_MICROSECONDS_PER_MILLISECOND);
const int microsecond = static_cast<int>(
(serialTime - hour * Ratio::k_MICROSECONDS_PER_HOUR -
minute * Ratio::k_MICROSECONDS_PER_MINUTE -
second * Ratio::k_MICROSECONDS_PER_SECOND -
millisecond * Ratio::k_MICROSECONDS_PER_MILLISECOND));
time->setTime(hour, minute, second, millisecond, microsecond);
return 0;
}
// 'bdlt::Time' Decoding
inline
int BerUtil_TimeImpUtil::getTimeValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length)
{
char firstByte;
if (0 != StreambufUtil::peekChar(&firstByte, streamBuf)) {
return -1; // RETURN
}
TimeEncoding::Value encoding;
int rc = detectTimeEncoding(&encoding, length, firstByte);
if (0 != rc) {
return -1; // RETURN
}
switch (encoding) {
case TimeEncoding::e_ISO8601_TIME: {
return getIso8601TimeValue(value, streamBuf, length); // RETURN
} break;
case TimeEncoding::e_COMPACT_BINARY_TIME: {
return getCompactBinaryTimeValue(value, streamBuf, length); // RETURN
} break;
case TimeEncoding::e_EXTENDED_BINARY_TIME: {
return getExtendedBinaryTimeValue(value, streamBuf, length); // RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// 'bdlt::Time' Encoding
inline
int BerUtil_TimeImpUtil::putTimeValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options)
{
switch (selectTimeEncoding(value, options)) {
case TimeEncoding::e_ISO8601_TIME: {
return putIso8601TimeValue(streamBuf, value, options); // RETURN
} break;
case TimeEncoding::e_COMPACT_BINARY_TIME: {
return putCompactBinaryTimeValue(streamBuf, value, options);
// RETURN
} break;
case TimeEncoding::e_EXTENDED_BINARY_TIME: {
return putExtendedBinaryTimeValue(streamBuf, value, options);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// 'bdlt::TimeTz' Decoding
inline
int BerUtil_TimeImpUtil::getTimeTzValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
char firstByte;
if (0 != StreambufUtil::peekChar(&firstByte, streamBuf)) {
return -1; // RETURN
}
TimeTzEncoding::Value encoding;
int rc = detectTimeTzEncoding(&encoding, length, firstByte);
if (0 != rc) {
return -1; // RETURN
}
switch (encoding) {
case TimeTzEncoding::e_ISO8601_TIMETZ: {
return getIso8601TimeTzValue(value, streamBuf, length); // RETURN
} break;
case TimeTzEncoding::e_COMPACT_BINARY_TIME: {
return getCompactBinaryTimeValue(value, streamBuf, length); // RETURN
} break;
case TimeTzEncoding::e_COMPACT_BINARY_TIMETZ: {
return getCompactBinaryTimeTzValue(value, streamBuf, length);
// RETURN
} break;
case TimeTzEncoding::e_EXTENDED_BINARY_TIMETZ: {
return getExtendedBinaryTimeTzValue(value, streamBuf, length);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// 'bdlt::TimeTz' Encoding
inline
int BerUtil_TimeImpUtil::putTimeTzValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options)
{
switch (selectTimeTzEncoding(value, options)) {
case TimeTzEncoding::e_ISO8601_TIMETZ: {
return putIso8601TimeTzValue(streamBuf, value, options); // RETURN
} break;
case TimeTzEncoding::e_COMPACT_BINARY_TIME: {
return putCompactBinaryTimeValue(streamBuf, value, options);
// RETURN
} break;
case TimeTzEncoding::e_COMPACT_BINARY_TIMETZ: {
return putCompactBinaryTimeTzValue(streamBuf, value, options);
// RETURN
} break;
case TimeTzEncoding::e_EXTENDED_BINARY_TIMETZ: {
return putExtendedBinaryTimeTzValue(streamBuf, value, options);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// Variant Decoding
inline
int BerUtil_TimeImpUtil::getTimeOrTimeTzValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
char firstByte;
if (0 != StreambufUtil::peekChar(&firstByte, streamBuf)) {
return -1; // RETURN
}
TimeOrTimeTzEncoding::Value encoding;
int rc = detectTimeOrTimeTzEncoding(&encoding, length, firstByte);
if (0 != rc) {
return -1; // RETURN
}
switch (encoding) {
case TimeOrTimeTzEncoding::e_ISO8601_TIME: {
return getIso8601TimeValue(value, streamBuf, length); // RETURN
} break;
case TimeOrTimeTzEncoding::e_ISO8601_TIMETZ: {
return getIso8601TimeTzValue(value, streamBuf, length); // RETURN
} break;
case TimeOrTimeTzEncoding::e_COMPACT_BINARY_TIME: {
return getCompactBinaryTimeValue(value, streamBuf, length); // RETURN
} break;
case TimeOrTimeTzEncoding::e_COMPACT_BINARY_TIMETZ: {
return getCompactBinaryTimeTzValue(value, streamBuf, length);
// RETURN
} break;
case TimeOrTimeTzEncoding::e_EXTENDED_BINARY_TIME: {
return getExtendedBinaryTimeValue(value, streamBuf, length); // RETURN
} break;
case TimeOrTimeTzEncoding::e_EXTENDED_BINARY_TIMETZ: {
return getExtendedBinaryTimeTzValue(value, streamBuf, length);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// ------------------------------
// struct BerUtil_DatetimeImpUtil
// ------------------------------
// PRIVATE CLASS METHODS
// 'bdlt::Datetime' Decoding
inline
int BerUtil_DatetimeImpUtil::detectDatetimeEncoding(
DatetimeEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
if (k_MAX_COMPACT_BINARY_DATETIME_LENGTH >= length) {
*encoding = DatetimeEncoding::e_COMPACT_BINARY_DATETIME;
return 0; // RETURN
}
if (k_MAX_COMPACT_BINARY_DATETIMETZ_LENGTH >= length) {
*encoding = DatetimeEncoding::e_COMPACT_BINARY_DATETIMETZ;
return 0; // RETURN
}
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinary(firstByte)) {
*encoding = DatetimeEncoding::e_EXTENDED_BINARY_DATETIME;
return 0; // RETURN
}
*encoding = DatetimeEncoding::e_ISO8601_DATETIME;
return 0;
}
// 'bdlt::Datetime' Encoding
inline
BerUtil_DatetimeEncoding::Value
BerUtil_DatetimeImpUtil::selectDatetimeEncoding(
bsls::Types::Int64 *serialDatetime,
int *serialDatetimeLength,
const bdlt::Datetime& value,
const BerEncoderOptions *options)
{
if (ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(value,
options)) {
return DatetimeEncoding::e_EXTENDED_BINARY_DATETIME; // RETURN
}
if (ExtendedBinaryEncodingUtil::useBinaryEncoding(options)) {
bsls::Types::Int64 serialDatetimeValue;
datetimeToMillisecondsSinceEpoch(&serialDatetimeValue, value);
const int serialDatetimeLengthValue =
IntegerUtil::getNumOctetsToStream(serialDatetimeValue);
if (k_MIN_COMPACT_BINARY_DATETIMETZ_LENGTH <=
serialDatetimeLengthValue) {
*serialDatetime = serialDatetimeValue;
*serialDatetimeLength = serialDatetimeLengthValue;
return DatetimeEncoding::e_COMPACT_BINARY_DATETIMETZ; // RETURN
}
*serialDatetime = serialDatetimeValue;
*serialDatetimeLength = serialDatetimeLengthValue;
return DatetimeEncoding::e_COMPACT_BINARY_DATETIME; // RETURN
}
return DatetimeEncoding::e_ISO8601_DATETIME;
}
// 'bdlt::DatetimeTz' Decoding
inline
int BerUtil_DatetimeImpUtil::detectDatetimeTzEncoding(
DatetimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
if (k_MAX_COMPACT_BINARY_DATETIME_LENGTH >= length) {
*encoding = DatetimeTzEncoding::e_COMPACT_BINARY_DATETIME;
return 0; // RETURN
}
if (k_MAX_COMPACT_BINARY_DATETIMETZ_LENGTH >= length) {
*encoding = DatetimeTzEncoding::e_COMPACT_BINARY_DATETIMETZ;
return 0; // RETURN
}
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinary(firstByte)) {
*encoding = DatetimeTzEncoding::e_EXTENDED_BINARY_DATETIMETZ;
return 0; // RETURN
}
*encoding = DatetimeTzEncoding::e_ISO8601_DATETIMETZ;
return 0;
}
// 'bdlt::DatetimeTz' Encoding
inline
BerUtil_DatetimeTzEncoding::Value
BerUtil_DatetimeImpUtil::selectDatetimeTzEncoding(
bsls::Types::Int64 *serialDatetime,
int *length,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options)
{
if (ExtendedBinaryEncodingUtil::useExtendedBinaryEncoding(value,
options)) {
return DatetimeTzEncoding::e_EXTENDED_BINARY_DATETIMETZ; // RETURN
}
if (ExtendedBinaryEncodingUtil::useBinaryEncoding(options)) {
bsls::Types::Int64 serialDatetimeValue;
datetimeToMillisecondsSinceEpoch(&serialDatetimeValue,
value.localDatetime());
const int lengthValue =
IntegerUtil::getNumOctetsToStream(serialDatetimeValue);
if (0 == value.offset() &&
k_MIN_COMPACT_BINARY_DATETIMETZ_LENGTH > lengthValue) {
*serialDatetime = serialDatetimeValue;
*length = lengthValue;
return DatetimeTzEncoding::e_COMPACT_BINARY_DATETIME; // RETURN
}
*serialDatetime = serialDatetimeValue;
*length = lengthValue;
return DatetimeTzEncoding::e_COMPACT_BINARY_DATETIMETZ; // RETURN
}
return DatetimeTzEncoding::e_ISO8601_DATETIMETZ;
}
// Variant Decoding
inline
int BerUtil_DatetimeImpUtil::detectDatetimeOrDatetimeTzEncoding(
DatetimeOrDatetimeTzEncoding::Value *encoding,
int length,
unsigned char firstByte)
{
BSLS_ASSERT(0 < length);
if (k_MAX_COMPACT_BINARY_DATETIME_LENGTH >= length) {
*encoding = DatetimeOrDatetimeTzEncoding::e_COMPACT_BINARY_DATETIME;
return 0; // RETURN
}
if (k_MAX_COMPACT_BINARY_DATETIMETZ_LENGTH >= length) {
*encoding = DatetimeOrDatetimeTzEncoding::e_COMPACT_BINARY_DATETIMETZ;
return 0; // RETURN
}
if (DateAndTimeHeaderUtil::isReserved(firstByte)) {
return -1; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinaryWithoutTimezone(firstByte)) {
*encoding = DatetimeOrDatetimeTzEncoding::e_EXTENDED_BINARY_DATETIME;
return 0; // RETURN
}
if (DateAndTimeHeaderUtil::isExtendedBinaryWithTimezone(firstByte)) {
*encoding = DatetimeOrDatetimeTzEncoding::e_EXTENDED_BINARY_DATETIMETZ;
return 0; // RETURN
}
if (k_MAX_ISO8601_DATETIME_LENGTH >= length) {
*encoding = DatetimeOrDatetimeTzEncoding::e_ISO8601_DATETIME;
return 0; // RETURN
}
*encoding = DatetimeOrDatetimeTzEncoding::e_ISO8601_DATETIMETZ;
return 0;
}
inline
int BerUtil_DatetimeImpUtil::getIso8601DatetimeValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Datetime>();
return getIso8601DatetimeValue(
&value->the<bdlt::Datetime>(), streamBuf, length);
}
inline
int BerUtil_DatetimeImpUtil::getIso8601DatetimeTzValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::DatetimeTz>();
return getIso8601DatetimeTzValue(
&value->the<bdlt::DatetimeTz>(), streamBuf, length);
}
inline
int BerUtil_DatetimeImpUtil::getCompactBinaryDatetimeValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Datetime>();
return getCompactBinaryDatetimeValue(
&value->the<bdlt::Datetime>(), streamBuf, length);
}
inline
int BerUtil_DatetimeImpUtil::getCompactBinaryDatetimeTzValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::DatetimeTz>();
return getCompactBinaryDatetimeTzValue(
&value->the<bdlt::DatetimeTz>(), streamBuf, length);
}
inline
int BerUtil_DatetimeImpUtil::getExtendedBinaryDatetimeValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::Datetime>();
return getExtendedBinaryDatetimeValue(
&value->the<bdlt::Datetime>(), streamBuf, length);
}
inline
int BerUtil_DatetimeImpUtil::getExtendedBinaryDatetimeTzValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
value->createInPlace<bdlt::DatetimeTz>();
return getExtendedBinaryDatetimeTzValue(
&value->the<bdlt::DatetimeTz>(), streamBuf, length);
}
// CLASS METHODS
// 'bdlt::Datetime' Encoding
inline
int BerUtil_DatetimeImpUtil::putDatetimeValue(
bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options)
{
const bdlt::Time& time = value.time();
bdlt::Date date = value.date();
if (0 != date.addDaysIfValid(0) ||
!bdlt::Time::isValid(
time.hour(), time.minute(), time.second(), time.millisecond())) {
return -1; // RETURN
}
bsls::Types::Int64 serialDatetime;
int length;
switch (selectDatetimeEncoding(&serialDatetime, &length, value, options)) {
case DatetimeEncoding::e_ISO8601_DATETIME: {
return putIso8601DatetimeValue(streamBuf, value, options); // RETURN
} break;
case DatetimeEncoding::e_COMPACT_BINARY_DATETIME: {
return putCompactBinaryDatetimeValue(
streamBuf, serialDatetime, length, options); // RETURN
} break;
case DatetimeEncoding::e_COMPACT_BINARY_DATETIMETZ: {
return putCompactBinaryDatetimeTzValue(
streamBuf, serialDatetime, length, options); // RETURN
} break;
case DatetimeEncoding::e_EXTENDED_BINARY_DATETIME: {
return putExtendedBinaryDatetimeValue(streamBuf, value, options);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// 'bdlt::Datetime' Decoding
inline
int BerUtil_DatetimeImpUtil::getDatetimeValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length)
{
char firstByte;
if (0 != StreambufUtil::peekChar(&firstByte, streamBuf)) {
return -1; // RETURN
}
DatetimeEncoding::Value encoding;
int rc = detectDatetimeEncoding(&encoding, length, firstByte);
if (0 != rc) {
return -1; // RETURN
}
switch (encoding) {
case DatetimeEncoding::e_ISO8601_DATETIME: {
return getIso8601DatetimeValue(value, streamBuf, length); // RETURN
} break;
case DatetimeEncoding::e_COMPACT_BINARY_DATETIME: {
return getCompactBinaryDatetimeValue(value, streamBuf, length);
// RETURN
} break;
case DatetimeEncoding::e_COMPACT_BINARY_DATETIMETZ: {
return getCompactBinaryDatetimeTzValue(value, streamBuf, length);
// RETURN
} break;
case DatetimeEncoding::e_EXTENDED_BINARY_DATETIME: {
return getExtendedBinaryDatetimeValue(value, streamBuf, length);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// 'bdlt::DatetimeTz' Encoding
inline
int BerUtil_DatetimeImpUtil::putDatetimeTzValue(
bsl::streambuf *streamBuf,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options)
{
// Applications can create invalid 'bdlt::DatetimeTz' objects in optimized
// build modes. As this function assumes that 'value' is valid, it is
// possible to encode an invalid 'bdlt::DatetimeTz' without returning an
// error. Decoding the corresponding output can result in hard-to-trace
// decoding errors. So to identify such errors early, we return an error
// if 'value' is not valid.
const bdlt::DateTz& dateTz = value.dateTz();
const bdlt::TimeTz& timeTz = value.timeTz();
if (0 != dateTz.localDate().addDaysIfValid(0) ||
!bdlt::DateTz::isValid(dateTz.localDate(), dateTz.offset()) ||
!bdlt::TimeTz::isValid(timeTz.utcTime(), timeTz.offset())) {
return -1; // RETURN
}
bsls::Types::Int64 serialDatetime;
int serialDatetimeLength;
switch (selectDatetimeTzEncoding(
&serialDatetime, &serialDatetimeLength, value, options)) {
case DatetimeTzEncoding::e_ISO8601_DATETIMETZ: {
return putIso8601DatetimeTzValue(streamBuf, value, options);
// RETURN
} break;
case DatetimeTzEncoding::e_COMPACT_BINARY_DATETIME: {
return putCompactBinaryDatetimeValue(
streamBuf, serialDatetime, serialDatetimeLength, options);
// RETURN
} break;
case DatetimeTzEncoding::e_COMPACT_BINARY_DATETIMETZ: {
return putCompactBinaryDatetimeTzValue(streamBuf,
value.offset(),
serialDatetime,
serialDatetimeLength,
options);
// RETURN
} break;
case DatetimeTzEncoding::e_EXTENDED_BINARY_DATETIMETZ: {
return putExtendedBinaryDatetimeTzValue(streamBuf, value, options);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// 'bdlt::DatetimeTz' Decoding
inline
int BerUtil_DatetimeImpUtil::getDatetimeTzValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
char firstByte;
if (0 != StreambufUtil::peekChar(&firstByte, streamBuf)) {
return -1; // RETURN
}
DatetimeTzEncoding::Value encoding;
int rc = detectDatetimeTzEncoding(&encoding, length, firstByte);
if (0 != rc) {
return -1; // RETURN
}
switch (encoding) {
case DatetimeTzEncoding::e_ISO8601_DATETIMETZ: {
return getIso8601DatetimeTzValue(value, streamBuf, length); // RETURN
} break;
case DatetimeTzEncoding::e_COMPACT_BINARY_DATETIME: {
return getCompactBinaryDatetimeValue(value, streamBuf, length);
// RETURN
} break;
case DatetimeTzEncoding::e_COMPACT_BINARY_DATETIMETZ: {
return getCompactBinaryDatetimeTzValue(value, streamBuf, length);
// RETURN
} break;
case DatetimeTzEncoding::e_EXTENDED_BINARY_DATETIMETZ: {
return getExtendedBinaryDatetimeTzValue(value, streamBuf, length);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// Variant Decoding
inline
int BerUtil_DatetimeImpUtil::getDatetimeOrDatetimeTzValue(
DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length)
{
char firstByte;
if (0 != StreambufUtil::peekChar(&firstByte, streamBuf)) {
return -1; // RETURN
}
DatetimeOrDatetimeTzEncoding::Value encoding;
int rc = detectDatetimeOrDatetimeTzEncoding(&encoding, length, firstByte);
if (0 != rc) {
return -1; // RETURN
}
switch (encoding) {
case DatetimeOrDatetimeTzEncoding::e_ISO8601_DATETIME: {
return getIso8601DatetimeValue(value, streamBuf, length); // RETURN
} break;
case DatetimeOrDatetimeTzEncoding::e_ISO8601_DATETIMETZ: {
return getIso8601DatetimeTzValue(value, streamBuf, length); // RETURN
} break;
case DatetimeOrDatetimeTzEncoding::e_COMPACT_BINARY_DATETIME: {
return getCompactBinaryDatetimeValue(value, streamBuf, length);
// RETURN
} break;
case DatetimeOrDatetimeTzEncoding::e_COMPACT_BINARY_DATETIMETZ: {
return getCompactBinaryDatetimeTzValue(value, streamBuf, length);
// RETURN
} break;
case DatetimeOrDatetimeTzEncoding::e_EXTENDED_BINARY_DATETIME: {
return getExtendedBinaryDatetimeValue(value, streamBuf, length);
// RETURN
} break;
case DatetimeOrDatetimeTzEncoding::e_EXTENDED_BINARY_DATETIMETZ: {
return getExtendedBinaryDatetimeTzValue(value, streamBuf, length);
// RETURN
} break;
}
BSLS_ASSERT_OPT(!"Reachable");
#if BSLA_UNREACHABLE_IS_ACTIVE
BSLA_UNREACHABLE;
#else
return -1; // RETURN
#endif
}
// ------------------------------
// struct BerUtil_GetValueImpUtil
// ------------------------------
// CLASS METHODS
template <typename TYPE>
int BerUtil_GetValueImpUtil::getValue(TYPE *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return IntegerUtil::getIntegerValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bool *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return BooleanUtil::getBoolValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(char *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return CharacterUtil::getCharValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(unsigned char *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return CharacterUtil::getUnsignedCharValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(signed char *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return CharacterUtil::getSignedCharValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(float *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return FloatingPointUtil::getFloatValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(double *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return FloatingPointUtil::getDoubleValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bdldfp::Decimal64 *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return FloatingPointUtil::getDecimal64Value(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bsl::string *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions& options)
{
return StringUtil::getStringValue(value, streamBuf, length, options);
}
inline
int BerUtil_GetValueImpUtil::getValue(bdlt::Date *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return DateUtil::getDateValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bdlt::DateTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return DateUtil::getDateTzValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(DateOrDateTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return DateUtil::getDateOrDateTzValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bdlt::Datetime *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return DatetimeUtil::getDatetimeValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bdlt::DatetimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return DatetimeUtil::getDatetimeTzValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(DatetimeOrDatetimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return DatetimeUtil::getDatetimeOrDatetimeTzValue(
value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bdlt::Time *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return TimeUtil::getTimeValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(bdlt::TimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return TimeUtil::getTimeTzValue(value, streamBuf, length);
}
inline
int BerUtil_GetValueImpUtil::getValue(TimeOrTimeTz *value,
bsl::streambuf *streamBuf,
int length,
const BerDecoderOptions&)
{
return TimeUtil::getTimeOrTimeTzValue(value, streamBuf, length);
}
// ------------------------------
// struct BerUtil_PutValueImpUtil
// ------------------------------
// CLASS METHODS
template <class TYPE>
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const TYPE& value,
const BerEncoderOptions *)
{
return IntegerUtil::putIntegerValue(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
bool value,
const BerEncoderOptions *)
{
return BooleanUtil::putBoolValue(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
char value,
const BerEncoderOptions *)
{
return CharacterUtil::putCharValue(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
unsigned char value,
const BerEncoderOptions *)
{
return CharacterUtil::putUnsignedCharValue(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
signed char value,
const BerEncoderOptions *)
{
return CharacterUtil::putSignedCharValue(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
float value,
const BerEncoderOptions *options)
{
return FloatingPointUtil::putFloatValue(streamBuf,
value,
options);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
double value,
const BerEncoderOptions *options)
{
return FloatingPointUtil::putDoubleValue(streamBuf,
value,
options);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
bdldfp::Decimal64 value,
const BerEncoderOptions *)
{
return FloatingPointUtil::putDecimal64Value(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bsl::string& value,
const BerEncoderOptions *)
{
return StringUtil::putStringValue(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bslstl::StringRef& value,
const BerEncoderOptions *)
{
return StringUtil::putStringRefValue(streamBuf, value);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bdlt::Date& value,
const BerEncoderOptions *options)
{
return DateUtil::putDateValue(streamBuf, value, options);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bdlt::DateTz& value,
const BerEncoderOptions *options)
{
return DateUtil::putDateTzValue(streamBuf, value, options);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bdlt::Datetime& value,
const BerEncoderOptions *options)
{
return DatetimeUtil::putDatetimeValue(streamBuf, value, options);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bdlt::DatetimeTz& value,
const BerEncoderOptions *options)
{
return DatetimeUtil::putDatetimeTzValue(streamBuf, value, options);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bdlt::Time& value,
const BerEncoderOptions *options)
{
return TimeUtil::putTimeValue(streamBuf, value, options);
}
inline
int BerUtil_PutValueImpUtil::putValue(bsl::streambuf *streamBuf,
const bdlt::TimeTz& value,
const BerEncoderOptions *options)
{
return TimeUtil::putTimeTzValue(streamBuf, value, options);
}
// ------------------
// struct BerUtil_Imp
// ------------------
// CLASS METHODS
inline
int BerUtil_Imp::putStringValue(bsl::streambuf *streamBuf,
const char *string,
int stringLength)
{
typedef BerUtil_StringImpUtil StringUtil;
return StringUtil::putRawStringValue(streamBuf, string, stringLength);
}
} // close package namespace
} // close enterprise namespace
#endif
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
| true |
322f4f05c4fabf965dd743f72940ea8d99f06003 | C++ | athena255/CacheCash | /src/DuplexPipe.h | UTF-8 | 2,889 | 2.71875 | 3 | [] | no_license | //
// Created by sage on 1/22/21.
//
#ifndef CACHECASH_DUPLEXPIPE_H
#define CACHECASH_DUPLEXPIPE_H
#include <poll.h>
#include <cstdarg>
class DuplexPipe
{
public:
static constexpr int READ = 0;
static constexpr int WRITE = 1;
static constexpr size_t BUF_SIZE = MAX_RX_BUF;
DuplexPipe(char const *cmd, char * const *args)
{
pipe(rx);
pipe(tx);
if (fork() == 0)
{
close(STDOUT_FILENO);
dup(rx[WRITE]);
close(STDIN_FILENO);
dup(tx[READ]);
close(rx[READ]);
close(tx[WRITE]);
close(tx[READ]);
close(rx[WRITE]);
if (-1 == execve(cmd, args, NULL))
ERR("[!] Failed to execute: %s", cmd);
}
else
{
close(rx[WRITE]);
close(tx[READ]);
in_stream = fdopen(tx[WRITE], "w");
pfd[READ].fd = rx[READ];
pfd[READ].events = POLLIN;
pfd[WRITE].fd = tx[WRITE];
pfd[WRITE].events = POLLOUT;
}
}
~DuplexPipe()
{
close(tx[WRITE]);
close(rx[READ]);
}
inline void send(char const * const msg)
{
if (poll(&pfd[WRITE], 1, -1) == 1)
write(tx[WRITE], msg, strlen(msg)+1);
}
inline void send(char * const buf, size_t buf_size)
{
if (poll(&pfd[WRITE], 1, -1) == 1)
write(tx[WRITE], buf, buf_size);
}
inline void fmt_send(const char *format, ...)
{
if (poll(&pfd[WRITE], 1, -1) == 1)
{
va_list args;
va_start(args, format);
vfprintf(in_stream, format, args);
va_end(args);
fflush(in_stream);
}
}
inline size_t receive(char *buf, size_t buf_size)
{
return read(rx[READ], buf, buf_size);
}
inline size_t receive_str()
{
auto n_bytes = read(rx[READ], rx_buf, BUF_SIZE-1);
rx_buf[n_bytes] = 0;
return n_bytes;
}
// This function will wait until there is something in the pipe
inline void wait_clear_rx()
{
auto n_bytes = read(rx[READ], rx_buf, BUF_SIZE-1);
rx_buf[n_bytes] = 0;
D("%s", rx_buf);
clear_rx();
}
// This function will return immediately if there is nothing to read in the pipe
inline void clear_rx()
{
size_t n_bytes;
while(poll(&pfd[READ], 1, 0) == 1)
{
n_bytes = read(rx[READ], rx_buf, BUF_SIZE-1);
rx_buf[n_bytes] = 0;
D("%s", rx_buf);
}
}
void print_rx_buf()
{
printf("\n============ BEG ============\n%s\n=============================\n", rx_buf);
}
char rx_buf[BUF_SIZE];
private:
int rx[2];
int tx[2];
struct pollfd pfd[2]{};
FILE *in_stream;
};
#endif //CACHECASH_DUPLEXPIPE_H
| true |
30f4af09752baed7c78c8eccd966e85252b300f2 | C++ | sri-soham/mapnik-utf8grid-tester | /json_object.hpp | UTF-8 | 1,281 | 2.890625 | 3 | [] | no_license | #ifndef JSON_OBJECT_HPP
#define JSON_OBJECT_HPP
#include <typeinfo>
#include <boost/variant.hpp>
#include <mapnik/value.hpp>
#include <mapnik/unicode.hpp>
class JsonObject;
class JsonArray;
typedef boost::variant<mapnik::value, std::string, JsonObject, JsonArray> json_type;
class JsonObject {
private:
std::map<std::string, json_type> json;
public:
void put(const std::string& key, json_type value);
json_type get(std::string key);
json_type& operator[](const std::string& key);
std::string to_string();
};
class JsonArray {
private:
std::vector<json_type> json_array;
public:
void add(json_type value);
json_type get(int index);
json_type& operator[](int index);
int size();
std::string to_string();
};
class to_string_visitor : public boost::static_visitor<std::string> {
private:
static to_string_visitor *instance;
to_string_visitor() {};
public:
static to_string_visitor& get_instance();
std::string operator()(mapnik::value& value) const;
std::string operator()(JsonObject& value) const;
std::string operator()(JsonArray& value) const;
std::string operator()(std::string& value) const;
};
#endif
| true |
865c5e43f524fe79cf55cc4c46f079c27ad1809e | C++ | Anmol2307/Hackerrank | /101Aug14/Pangrams.cpp | UTF-8 | 812 | 2.671875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
inline void inp(int &n ) {//fast input function
n=0;
int ch=getchar(),sign=1;
while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=getchar();}
while( ch >= '0' && ch <= '9' )
n=(n<<3)+(n<<1)+ ch-'0', ch=getchar();
n=n*sign;
}
int main () {
string ch;
getline(cin,ch);
int len = ch.size();
int arr[26];
memset(arr,0,sizeof(arr));
int total = 0;
for (int i = 0; i < len; i++) {
if (ch[i] - 'a' >= 0 && ch[i] - 'a' <= 25 && arr[ch[i] - 'a'] == 0) {
arr[ch[i] - 'a'] = 1;
total++;
}
else if (ch[i] - 'A' >= 0 && ch[i] - 'A' <= 25 && arr[ch[i] - 'A'] == 0) {
arr[ch[i] - 'A'] = 1;
total++;
}
}
if (total == 26) {
printf("pangram\n");
}
else printf("not pangram\n");
} | true |
6403316750ebee032f3c1a572c84ae446b97edc0 | C++ | sayandodo1234/compe_codes | /tries/maximum_xor_subarray.cpp | UTF-8 | 2,022 | 3.421875 | 3 | [] | no_license | // Maximum XOR Subarray
// Send Feedback
// Given an array of n integers, find subarray whose xor is maximum.
// Input Format
// First line contains single integer n (1<=n<=1000000).
// Next line contains n space separated integers.
// Output Format
// Print xor of the subarray whose xor of all elements in subarray is maximum over all subarrays.
// Constraints
// 1 <= n <= 1000000
// 1 <= A[i] <=100000
// Sample Input
// 4
// 1 2 3 4
// Sample Output
// 7
#include<bits/stdc++.h>
using namespace std;
class TrieNode{
public:
int value ;
TrieNode *arr[2] ;
} ;
// Inserts pre_xor to trie with given root
void insert(TrieNode *root, int pre_xor)
{
TrieNode *temp = root;
// Start from the msb, insert all bits of
// pre_xor into Trie
for (int i=31; i>=0; i--)
{
// Find current bit in given prefix
bool val = pre_xor & (1<<i);
// Create a new node if needed
if (temp->arr[val] == NULL) {
// temp->arr[val] = newNode();
temp->arr[val] = new TrieNode ;
}
temp = temp->arr[val];
}
// Store value at leaf node
temp->value = pre_xor;
}
int main()
{
int n ;
cin>>n ;
int a[n] ;
TrieNode *root = new TrieNode ;
insert(root, 0);
int result = INT_MIN, pre_xor =0;
for(int i = 0 ; i<n ; i++){
cin>>a[i] ;
pre_xor = pre_xor^a[i];
insert(root, pre_xor);
TrieNode *temp = root;
for (int i=31; i>=0; i--) {
// Find current bit in given prefix
bool val = pre_xor & (1<<i);
// Traverse Trie, first look for a
// prefix that has opposite bit
if (temp->arr[1-val]!=NULL) {
temp = temp->arr[1-val];
}
// If there is no prefix with opposite
// bit, then look for same bit.
else if (temp->arr[val] != NULL)
temp = temp->arr[val];
}
int curr_xor = pre_xor^(temp->value) ;
result = max(result, curr_xor) ;
}
cout<<result;
return 0;
}
| true |
565d09286ded5b8d10cd08ad641c410a0ad0ccef | C++ | arni30/marathon-cpp | /sprint04/t03/app/main.cpp | UTF-8 | 912 | 2.578125 | 3 | [
"MIT"
] | permissive | #include "src/dwemerCalculator.h"
int main(){
dwemerCalculator calc;
std::string input_str;
std::smatch match;
std::regex regex("^[[:blank:]]*([\\+\\-]{0,1}[a-zA-Z0-9]+)[[:blank:]]*([\\+\\-\\*\\/]{1})[[:blank:]]*([\\+\\-]{0,1}[a-zA-Z0-9]+)[[:blank:]]*$");
std::regex regex_var("^[[:blank:]]*([\\+\\-]{0,1}[a-zA-Z0-9]+)[[:blank:]]*([\\+\\-\\*\\/]{1})[[:blank:]]*([\\+\\-]{0,1}[a-zA-Z0-9]+)[[:blank:]]*\\=[[:blank:]]*([\\+\\-]{0,1}[a-zA-Z0-9]+)[[:blank:]]*$");
while (1) {
std::cout << ":>";
std::getline(std::cin, input_str, '\n');
if (!input_str.empty() && (std::regex_match(input_str, match, regex) != false
|| std::regex_match(input_str, match, regex_var) != false)) {
calc.parser(match);
}
else if (input_str == "quit")
exit(0);
else
std::cerr << "invalid input" << std::endl;
}
}
| true |
93ca9956139f2d55770004593254b7ed7a8bef47 | C++ | AbraaoLincoln/LP1 | /lista_aquecimento/problem5.cpp | UTF-8 | 474 | 4.25 | 4 | [] | no_license | #include <iostream>
int fat1 (int n);//iterative version.
int fat2 (int n);//recursive version.
int main(void)
{
int n{0};
std::cout << "Type a interage number: " << std::endl;
std::cin >> n;
std::cout << fat2(n) << std::endl;
return 0;
}
int fat1 (int n)
{
int fat{n};
for(int i{n - 1}; i > 0; i--)
{
fat *= i;
}
return fat;
}
int fat2(int n)
{
int fat{n};
if(n == 1)
{
return 1;
}else
{
fat *= fat2(n - 1);
}
return fat;
}
| true |
1ea89ff61134769ff82d4a8dc64deb7c1cbbc6c0 | C++ | CLDP/USACO-Contest | /2011-2012 Season/2012 February/Gold/coupons.cpp | UTF-8 | 1,233 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
struct coupons {
long long p, c;
};
bool compare(const coupons &a, const coupons &b) {
if (a.c != b.c) return a.c < b.c;
return a.p < b.p;
}
int main() {
freopen("coupons.in", "r", stdin);
freopen("coupons.out", "w", stdout);
int n, k;
long long m;
cin >> n >> k >> m;
vector<coupons> x;
for (int i = 0; i < n; ++i) {
coupons p;
cin >> p.p >> p.c;
x.push_back(p);
}
sort(x.begin(), x.end(), compare);
priority_queue<long long> reuse;
int ans = 0;
for (int i = 0; i < n; ++i) {
if (k > 0) {
if (m < x[i].c) break;
m -= x[i].c;
--k;
reuse.push(x[i].p - x[i].c);
} else {
long long t1 = reuse.top() + x[i].c, t2 = x[i].p;
if (t1 < t2) {
if (m < t1) break;
reuse.pop();
reuse.push(x[i].p - x[i].c);
m -= t1;
} else {
if (m < t2) break;
m -= t2;
}
}
ans = i + 1;
}
cout << ans << endl;
return 0;
}
| true |
51b3198d3907c58d524b30887574007882b000e7 | C++ | rafidmahin20/CG-summer | /Lake view city/main.cpp | UTF-8 | 103,450 | 2.546875 | 3 | [] | no_license | #include<windows.h>
#include<mmsystem.h>
#include <GL/glut.h>
#include <stdlib.h>
#include <math.h>
#include <fstream>
#include<iostream>
#define PI 3.1416
//#include<MMSystem.h>
using namespace std;
void introscreen();
static float tx= 0.0, cloudleftx=0,cloudmiddlex=0,cloudrightx=0,cloudrightupx=0;
static float ty=0.0;
static float txA=0.0;
static float tyA=0.0;
static float txB2=0.0;
static float tyB2=0.0;
static float txC=0.0;
static float tyC=0.0;
static float txS=0.0;
static float tyS=0.0;
static float txR=0.0;
static float tyR=0.0;
void circle(float radius_x, float radius_y)
{
int i = 0;
float angle1 = 0.0;
glBegin(GL_POLYGON);
for(i = 0; i < 100; i++)
{
angle1 = 2 * PI * i / 100;
glVertex3f (cos(angle1) * radius_x, sin(angle1) * radius_y, 0);
}
glEnd();
}
void renderbitmap(float x, float y, void *font, char *string){
char *c;
glRasterPos2f(x,y);
for(c=string; *c!= '\0'; c++)
{
glutBitmapCharacter(font, *c);
}
}
void introscreen(){
glColor3ub(41,106,119);
char buf[100]={0};
sprintf(buf, "Lake View City");
renderbitmap(-10,30, GLUT_BITMAP_TIMES_ROMAN_24,buf);
sprintf(buf, "press 'r', 'd' and 'n' to see the different views of the city");
renderbitmap(-19,10, GLUT_BITMAP_TIMES_ROMAN_24,buf);
}
void screen(){
glBegin(GL_QUADS);
glColor3ub(234, 243, 245);
glVertex2f(-50.0f, 110.0f);
glColor3ub(210, 233, 238);
glVertex2f(50.0f, 110.0f);
glColor3ub(151, 191, 208);
glVertex2f(50.0f, -90.0f);
glColor3ub(111, 191, 208);
glVertex2f(-50.0f, -90.0f);
glEnd();
}
void sun(){
glPushMatrix();
glTranslated(33,90,0);
glScaled(0.5,1.5,0);
glColor3f(1,0.843,0);
circle(9,9);
glPopMatrix();
}
void sunR(){
glPushMatrix();
glTranslated(-10,90,0);
glScaled(0.5,1.5,0);
glColor3ub(248,253,111);
circle(9,9);
glPopMatrix();
}
void moon(){
glPushMatrix();
glTranslated(-30,85,0);
glScaled(0.5,1.5,0);
glColor3f(254, 252, 215);
circle(9,9);
glPopMatrix();
}
void star1(){
glPushMatrix();
glTranslated(-10,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star2(){
glPushMatrix();
glTranslated(-9,85,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star3(){
glPushMatrix();
glTranslated(-7,75,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star4(){
glPushMatrix();
glTranslated(-6,60,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star5(){
glPushMatrix();
glTranslated(-5,50,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star6(){
glPushMatrix();
glTranslated(-5,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star7(){
glPushMatrix();
glTranslated(-1,96,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star8(){
glPushMatrix();
glTranslated(5,97,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star9(){
glPushMatrix();
glTranslated(10,96.5,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star10(){
glPushMatrix();
glTranslated(14,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star11(){
glPushMatrix();
glTranslated(18,95,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star12(){
glPushMatrix();
glTranslated(5,97,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star13(){
glPushMatrix();
glTranslated(-2,85,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star14(){
glPushMatrix();
glTranslated(-39,85,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star15(){
glPushMatrix();
glTranslated(-33,85,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star16(){
glPushMatrix();
glTranslated(-33,105,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star17(){
glPushMatrix();
glTranslated(-40,105,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star18(){
glPushMatrix();
glTranslated(-48,107,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-48,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-48,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-48,60,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-48,45,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-46,105,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-46,93,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-46,75,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-46,50,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-46,62,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-34,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-34,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-34,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-34,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-34,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-34,115,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-31,46,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-31,58,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-31,70,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-31,83,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-31,101,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-31,116,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-7,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-7,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-7,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-7,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-7,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-7,115,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-4.75,46,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-4.75,58,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-4.75,70,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-4.75,83,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-4.75,101,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-4.75,116,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(6,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(6,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(6,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(6,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(6,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(6,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(7,40,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(7,58,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(7,70,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(7,83,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(7,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(7,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(19,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(19,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(19,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(19,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(19,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(19,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(21,40,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(21,58,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(21,70,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(21,83,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(21,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(21,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(32,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(32,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(32,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(32,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(32,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(32,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(33.5,40,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(33.5,58,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(33.5,70,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(33.5,83,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(33.5,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(33.5,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(44,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(44,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(44,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(44,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(44,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(44,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(46,40,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(46,58,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(46,70,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(46,83,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(46,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(46,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(48,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(48,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(48,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(48,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(48,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(48,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-20,40,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-20,58,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-20,70,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-20,83,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-20,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-20,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-18,44,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-18,56,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-18,68,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-18,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-18,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-18,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star19(){
glPushMatrix();
glTranslated(-44,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-44,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-44,100,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-44,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-41,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-41,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-41,100,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-41,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-36,80,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-36,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-36,100,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-36,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-28,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-28,100,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-28,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-23,94,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-23,104,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-23,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-26,85,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-15,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-15,100,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-15,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-10,94,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-10,104,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-10,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(-13,85,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void star20(){
glPushMatrix();
glTranslated(-3,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(3,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(11,87,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(11,97,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(11,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(16,89,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(16,99,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(16,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(24,92,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(24,102,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(24,115,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(29,95,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(29,105,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(29,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(27,93,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(36,86,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(36,98,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(36,117,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(42,88,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(42,100,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(42,119,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(40,88,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(38,90,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
glPushMatrix();
glTranslated(38,118,0);
glScaled(0.5,1.5,0);
glColor3ub(224,224,224);
circle(.4,.4);
glPopMatrix();
}
void cloudLeft(){
cloudleftx=cloudleftx-0.05;
if(cloudleftx<-50){
cloudleftx=50;
}
glPushMatrix();
glTranslated(-3.5+cloudleftx,8.5,3);
glScaled(1,1,1);
glColor3f(1.0f,1.0f,1.0f);
glPushMatrix();
glTranslated(0,83.5,1),
circle(1.5,2.5);
glPopMatrix();
glPushMatrix();
glTranslated(1,86.5,1),
circle(2,3);
glPopMatrix();
glPushMatrix();
glTranslated(3,86.5,1),
circle(2,3);
glPopMatrix();
glPushMatrix();
glTranslated(4.5,84,1),
circle(1.5,2.5);
glPopMatrix();
glPushMatrix();
glTranslated(2.5,83,1),
circle(1.5,2.5);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void cloudRight(){
cloudrightx=cloudrightx-0.07;
if(cloudrightx<-50){
cloudrightx=50;
}
glPushMatrix();
glTranslated(-3.5+cloudrightx,2.5,-5);
glScaled(1,1,1);
glColor3f(1.0f,1.0f,1.0f);
glPushMatrix();
glTranslated(0,83.5,1),
circle(1.5,2.5);
glPopMatrix();
glPushMatrix();
glTranslated(1,86.5,1),
circle(2,3);
glPopMatrix();
glPushMatrix();
glTranslated(3,86.5,1),
circle(2,3);
glPopMatrix();
glPushMatrix();
glTranslated(4.5,84,1),
circle(1.5,2.5);
glPopMatrix();
glPushMatrix();
glTranslated(2.5,83,1),
circle(1.5,2.5);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void cloudMiddle(){
cloudmiddlex=cloudmiddlex-0.04;
if(cloudmiddlex<-50){
cloudmiddlex=50;
}
glPushMatrix();
glTranslated(-3.5+cloudmiddlex,9,1);
glScaled(1,1,1);
glColor3f(1.0f,1.0f,1.0f);
glPushMatrix();
glTranslated(0,83.5,1),
circle(1.5,2.5);
glPopMatrix();
glPushMatrix();
glTranslated(1,86.5,1),
circle(2,3);
glPopMatrix();
glPushMatrix();
glTranslated(3,86.5,1),
circle(2,3);
glPopMatrix();
glPushMatrix();
glTranslated(4.5,84,1),
circle(1.5,2.5);
glPopMatrix();
glPushMatrix();
glTranslated(2.5,83,1),
circle(1.5,2.5);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void sky()
{
glBegin(GL_QUADS);
glColor3ub(202, 235, 245);
glVertex2f(-50.0f, 110.0f);
glVertex2f(50.0f, 110.0f);
glColor3ub(197, 233, 238);
glVertex2f(50.0f, 20.0f);
glVertex2f(-50.0f, 20.0f);
glEnd();
}
void skyN()
{
glBegin(GL_QUADS);
glColor3ub(7, 11, 52);
glVertex2f(-50.0f, 110.0f);
glColor3ub(7, 11, 52);
glVertex2f(50.0f, 110.0f);
glColor3ub(7, 11, 52);
glVertex2f(50.0f, 20.0f);
glColor3ub(7, 11, 52);
glVertex2f(-50.0f, 20.0f);
glEnd();
}
void skyR(){
glBegin(GL_QUADS);
glColor3ub(224, 224, 224);
glVertex2f(-50.0f, 110.0f);
glVertex2f(50.0f, 110.0f);
glColor3ub(160, 160, 160);
glVertex2f(50.0f, 20.0f);
glVertex2f(-50.0f, 20.0f);
glEnd();
}
void RiverBorder(){
glBegin(GL_QUADS);
glColor3ub(145, 139, 139);
glVertex2f(-50.0f, 40.0f);
glVertex2f(-50.0f, 41.0f);
glVertex2f(50.0f, 41.0f);
glVertex2f(50.0f, 40.0f);
glEnd();
}
void River(){
glBegin(GL_QUADS);
glColor3ub(249, 254, 255);
glVertex2f(-50.0f, 40.0f);
glVertex2f(50.0f, 40.0f);
glColor3ub(128, 185, 235);
glVertex2f(50.0f, -10.0f);
glVertex2f(-50.0f, -10.0f);
glEnd();
}
void RiverR(){
glBegin(GL_QUADS);
glColor3ub(115, 126,135);
glVertex2f(-50.0f, 40.0f);
glVertex2f(50.0f, 40.0f);
glColor3ub(56, 92, 122);
glVertex2f(50.0f, -10.0f);
glVertex2f(-50.0f, -10.0f);
glEnd();
}
void RiverN(){
glBegin(GL_QUADS);
glColor3ub(204, 229, 255);
glVertex2f(-50.0f, 40.0f);
glVertex2f(50.0f, 40.0f);
glColor3ub(42, 57, 191);
glVertex2f(50.0f, -10.0f);
glVertex2f(-50.0f, -10.0f);
glEnd();
}
void Roadborder(){
glBegin(GL_QUADS);
glColor3ub(19, 19, 20);
glVertex2f(-50.0f, -10.0f);
glVertex2f(-40.0f, -10.0f);
glVertex2f(-40.0f, -13.0f);
glVertex2f(-50.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(255, 255, 255);
glVertex2f(-40.0f, -10.0f);
glVertex2f(-30.0f, -10.0f);
glVertex2f(-30.0f, -13.0f);
glVertex2f(-40.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(19, 19, 20);
glVertex2f(-30.0f, -10.0f);
glVertex2f(-20.0f, -10.0f);
glVertex2f(-20.0f, -13.0f);
glVertex2f(-30.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(255, 255, 255);
glVertex2f(-20.0f, -10.0f);
glVertex2f(-10.0f, -10.0f);
glVertex2f(-10.0f, -13.0f);
glVertex2f(-20.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(19, 19, 20);
glVertex2f(-10.0f, -10.0f);
glVertex2f(0.0f, -10.0f);
glVertex2f(0.0f, -13.0f);
glVertex2f(-10.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(255, 255, 255);
glVertex2f(0.0f, -10.0f);
glVertex2f(10.0f, -10.0f);
glVertex2f(10.0f, -13.0f);
glVertex2f(0.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(19, 19, 20);
glVertex2f(10.0f, -10.0f);
glVertex2f(20.0f, -10.0f);
glVertex2f(20.0f, -13.0f);
glVertex2f(10.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(255, 255, 255);
glVertex2f(20.0f, -10.0f);
glVertex2f(30.0f, -10.0f);
glVertex2f(30.0f, -13.0f);
glVertex2f(20.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(19, 19, 20);
glVertex2f(30.0f, -10.0f);
glVertex2f(40.0f, -10.0f);
glVertex2f(40.0f, -13.0f);
glVertex2f(30.0f, -13.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(255, 255, 255);
glVertex2f(40.0f, -10.0f);
glVertex2f(50.0f, -10.0f);
glVertex2f(50.0f, -13.0f);
glVertex2f(40.0f, -13.0f);
glEnd();
}
void LightStand(){
glBegin(GL_QUADS);
glColor3ub(102, 0, 0);
glVertex2f(-25.0f, -5.0f);
glVertex2f(-26.0f, -5.0f);
glVertex2f(-26.0f, -10.0f);
glVertex2f(-25.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(102, 0, 0);
glVertex2f(0.0f, -5.0f);
glVertex2f(1.0f, -5.0f);
glVertex2f(1.0f, -10.0f);
glVertex2f(0.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(102, 0, 0);
glVertex2f(25.0f, -5.0f);
glVertex2f(26.0f, -5.0f);
glVertex2f(26.0f, -10.0f);
glVertex2f(25.0f, -10.0f);
glEnd();
glBegin(GL_POLYGON);// 1st light
glColor3ub(255, 255, 255);
glVertex2f(-28.0f, -5.0f);
glVertex2f(-28.0f, -3.0f);
glVertex2f(-25.5f, 0.0f);
glVertex2f(-23.0f, -3.0f);
glVertex2f(-23.0f, -5.0f);
glEnd();
glBegin(GL_POLYGON);// 2nd light
glColor3ub(255, 255, 255);
glVertex2f(-2.0f, -5.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(0.5f, 0.0f);
glVertex2f(3.0f, -3.0f);
glVertex2f(3.0f, -5.0f);
glEnd();
glBegin(GL_POLYGON);// 3rd light
glColor3ub(255, 255, 255);
glVertex2f(23.0f, -5.0f);
glVertex2f(23.0f, -3.0f);
glVertex2f(25.5f, 0.0f);
glVertex2f(28.0f, -3.0f);
glVertex2f(28.0f, -5.0f);
glEnd();
}
void LightStandN(){
glBegin(GL_QUADS);
glColor3ub(102, 0, 0);
glVertex2f(-25.0f, -5.0f);
glVertex2f(-26.0f, -5.0f);
glVertex2f(-26.0f, -10.0f);
glVertex2f(-25.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(102, 0, 0);
glVertex2f(0.0f, -5.0f);
glVertex2f(1.0f, -5.0f);
glVertex2f(1.0f, -10.0f);
glVertex2f(0.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(102, 0, 0);
glVertex2f(25.0f, -5.0f);
glVertex2f(26.0f, -5.0f);
glVertex2f(26.0f, -10.0f);
glVertex2f(25.0f, -10.0f);
glEnd();
glBegin(GL_POLYGON);// 1st light
glColor3ub(243, 243, 57);
glVertex2f(-28.0f, -5.0f);
glVertex2f(-28.0f, -3.0f);
glVertex2f(-25.5f, 0.0f);
glVertex2f(-23.0f, -3.0f);
glVertex2f(-23.0f, -5.0f);
glEnd();
glBegin(GL_POLYGON);// 2nd light
glColor3ub(243, 243, 57);
glVertex2f(-2.0f, -5.0f);
glVertex2f(-2.0f, -3.0f);
glVertex2f(0.5f, 0.0f);
glVertex2f(3.0f, -3.0f);
glVertex2f(3.0f, -5.0f);
glEnd();
glBegin(GL_POLYGON);// 3rd light
glColor3ub(243, 243, 57);
glVertex2f(23.0f, -5.0f);
glVertex2f(23.0f, -3.0f);
glVertex2f(25.5f, 0.0f);
glVertex2f(28.0f, -3.0f);
glVertex2f(28.0f, -5.0f);
glEnd();
}
void Road(){
glBegin(GL_QUADS);
glColor3ub(96, 96, 96);
glVertex2f(-50.0f, -13.0f);
glVertex2f(50.0f, -13.0f);
glVertex2f(50.f, -90.0f);
glVertex2f(-50.0f, -90.0f);
glEnd();
}
void footpath(){
glBegin(GL_QUADS);
glColor3ub(224, 224, 224);
glVertex2f(-36.6f, -42.0f);
glVertex2f(-26.6f, -42.0f);
glVertex2f(-25.0f, -44.5f);
glVertex2f(-35.0f, -44.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(224, 224, 224);
glVertex2f(-6.6f, -42.0f);
glVertex2f(3.4f, -42.0f);
glVertex2f(5.0f, -44.5f);
glVertex2f(-5.0f, -44.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(224, 224, 224);
glVertex2f(23.4f, -42.0f);
glVertex2f(33.4f, -42.0f);
glVertex2f(35.0f, -44.5f);
glVertex2f(25.0f, -44.5f);
glEnd();
}
void Bus1(){
tx=tx+0.2;
if(tx>90){
tx=-30;
}
glBegin(GL_QUADS); //red
glColor3ub(213, 50, 9);
glVertex2f(-30.0f, 0.0f);
glVertex2f(-12.0f, 0.0f);
glVertex2f(-12.0f, -11.0f);
glVertex2f(-30.0f, -11.0f);
glEnd();
glBegin(GL_QUADS); //blue
glColor3ub(28, 58, 205);
glVertex2f(-30.0f, -11.0f);
glVertex2f(-12.0f, -11.0f);
glVertex2f(-12.0f, -27.0f);
glVertex2f(-30.0f, -27.0f);
glEnd();
glBegin(GL_QUADS); //left window
glColor3ub(128, 217, 245);
glVertex2f(-29.0f, -1.0f);
glVertex2f(-26.0f, -1.0f);
glVertex2f(-26.0f, -10.0f);
glVertex2f(-29.0f, -10.0f);
glEnd();
glBegin(GL_QUADS); //middle window
glColor3ub(128, 217, 245);
glVertex2f(-25.0f, -1.0f);
glVertex2f(-22.0f, -1.0f);
glVertex2f(-22.0f, -10.0f);
glVertex2f(-25.0f, -10.0f);
glEnd();
glBegin(GL_QUADS); //right window
glColor3ub(128, 217, 245);
glVertex2f(-21.0f, -1.0f);
glVertex2f(-18.0f, -1.0f);
glVertex2f(-18.0f, -10.0f);
glVertex2f(-21.0f, -10.0f);
glEnd();
glBegin(GL_QUADS); //front glass
glColor3ub(128, 217, 245);
glVertex2f(-17.0f, -1.0f);
glVertex2f(-12.0f, -1.0f);
glVertex2f(-12.0f, -10.0f);
glVertex2f(-17.0f, -10.0f);
glEnd();
glPushMatrix();
glTranslated(-27,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPushMatrix();
glTranslated(-15,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void FirstBuild(){
glBegin(GL_POLYGON);
glColor3ub(218, 65, 147);
glVertex2f(-38.0f, 41.0f);
glVertex2f(-36.0f, 41.0f);
glVertex2f(-36.0f, 74.0f);
glVertex2f(-38.0f, 77.0f);
glColor3ub(236, 197, 218);
glVertex2f(-38.0f, 77.0f);
glVertex2f(-45.0f, 77.0f);
glVertex2f(-45.0f, 41.0f);
glVertex2f(-38.0f, 41.0f);
glEnd();
}
void FrstBuildWindow(){
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st window
glVertex2f(-44.0f, 73.0f);
glVertex2f(-42.5f, 73.0f);
glVertex2f(-42.5f, 68.0f);
glVertex2f(-44.0f, 68.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd window
glVertex2f(-41.0f, 73.0f);
glVertex2f(-39.5f, 73.0f);
glVertex2f(-39.5f, 68.0f);
glVertex2f(-41.0f, 68.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //3rd window
glVertex2f(-44.0f, 62.0f);
glVertex2f(-42.5f, 62.0f);
glVertex2f(-42.5f, 57.0f);
glVertex2f(-44.0f, 57.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //4rth window
glVertex2f(-41.0f, 62.0f);
glVertex2f(-39.5f, 62.0f);
glVertex2f(-39.5f, 57.0f);
glVertex2f(-41.0f, 57.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //5th window
glVertex2f(-44.0f, 51.0f);
glVertex2f(-42.5f, 51.0f);
glVertex2f(-42.5f, 46.0f);
glVertex2f(-44.0f, 46.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //6th window
glVertex2f(-41.0f, 51.0f);
glVertex2f(-39.5f, 51.0f);
glVertex2f(-39.5f, 46.0f);
glVertex2f(-41.0f, 46.0f);
glEnd();
}
void SecondBuilding(){
glBegin(GL_POLYGON);
glColor3ub(38, 17, 97);
glVertex2f(-23.0, 79.0f);
glVertex2f(-21.0f, 76.0f);
glVertex2f(-21.0f, 41.0f);
glVertex2f(-23.0f, 41.0f);
glColor3ub(191, 185, 208);
glVertex2f(-23.0f, 41.0f);
glVertex2f(-30.0f, 41.0f);
glVertex2f(-30.0f, 79.0f);
glVertex2f(-23.0f, 79.0f);
glEnd();
}
void secndBuildWindow(){
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st window
glVertex2f(-29.0f, 75.0f);
glVertex2f(-27.5f, 75.0f);
glVertex2f(-27.5f, 70.0f);
glVertex2f(-29.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd window
glVertex2f(-26.0f, 75.0f);
glVertex2f(-24.5f, 75.0f);
glVertex2f(-24.5f, 70.0f);
glVertex2f(-26.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //3rd window
glVertex2f(-29.0f, 63.0f);
glVertex2f(-27.5f, 63.0f);
glVertex2f(-27.5f, 58.0f);
glVertex2f(-29.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //4rth window
glVertex2f(-26.0f, 63.0f);
glVertex2f(-24.5f, 63.0f);
glVertex2f(-24.5f, 58.0f);
glVertex2f(-26.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //5th window
glVertex2f(-29.0f, 52.0f);
glVertex2f(-27.5f, 52.0f);
glVertex2f(-27.5f, 47.0f);
glVertex2f(-29.0f, 47.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //6th window
glVertex2f(-26.0f, 52.0f);
glVertex2f(-24.5f, 52.0f);
glVertex2f(-24.5f, 47.0f);
glVertex2f(-26.0f, 47.0f);
glEnd();
}
void thrdBuilding(){
glBegin(GL_POLYGON);
glColor3ub(135, 73, 19);
glVertex2f(-10.0, 79.0f);
glVertex2f(-8.0f, 76.0f);
glVertex2f(-8.0f, 41.0f);
glVertex2f(-10.0f, 41.0f);
glColor3ub(205, 146, 94);
glVertex2f(-10.0f, 41.0f);
glVertex2f(-17.0f, 41.0f);
glVertex2f(-17.0f, 79.0f);
glVertex2f(-10.0f, 79.0f);
glEnd();
}
void thirdBildWindow(){
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st window
glVertex2f(-16.0f, 75.0f);
glVertex2f(-14.5f, 75.0f);
glVertex2f(-14.5f, 70.0f);
glVertex2f(-16.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd window
glVertex2f(-13.0f, 75.0f);
glVertex2f(-11.5f, 75.0f);
glVertex2f(-11.5f, 70.0f);
glVertex2f(-13.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //3rd window
glVertex2f(-16.0f, 63.0f);
glVertex2f(-14.5f, 63.0f);
glVertex2f(-14.5f, 58.0f);
glVertex2f(-16.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //4rth window
glVertex2f(-13.0f, 63.0f);
glVertex2f(-11.5f, 63.0f);
glVertex2f(-11.5f, 58.0f);
glVertex2f(-13.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //5th window
glVertex2f(-16.0f, 52.0f);
glVertex2f(-14.5f, 52.0f);
glVertex2f(-14.5f, 47.0f);
glVertex2f(-16.0f, 47.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //6th window
glVertex2f(-13.0f, 52.0f);
glVertex2f(-11.5f, 52.0f);
glVertex2f(-11.5f, 47.0f);
glVertex2f(-13.0f, 47.0f);
glEnd();
}
void FrthBuilding(){
glBegin(GL_POLYGON);
glColor3ub(29,122,97);
glVertex2f(3.0, 90.0f);
glVertex2f(5.0f, 87.0f);
glVertex2f(5.0f, 41.0f);
glVertex2f(3.0f, 41.0f);
glColor3ub(108,220,190);
glVertex2f(3.0f, 41.0f);
glVertex2f(-4.0f, 41.0f);
glVertex2f(-4.0f, 90.0f);
glVertex2f(3.0f, 90.0f);
glEnd();
}
void frthBuildingWindow(){
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st1st window
glVertex2f(-3.0f, 87.0f);
glVertex2f(-1.5f, 87.0f);
glVertex2f(-1.5f, 82.5f);
glVertex2f(-3.0f, 82.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd2nd window
glVertex2f(0.0f, 87.0f);
glVertex2f(1.5f, 87.0f);
glVertex2f(1.5f, 82.5f);
glVertex2f(0.0f, 82.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st window
glVertex2f(-3.0f, 78.0f);
glVertex2f(-1.5f, 78.0f);
glVertex2f(-1.5f, 73.0f);
glVertex2f(-3.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd window
glVertex2f(0.0f, 78.0f);
glVertex2f(1.5f, 78.0f);
glVertex2f(1.5f, 73.0f);
glVertex2f(0.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //3rd window
glVertex2f(-3.0f, 68.0f);
glVertex2f(-1.5f, 68.0f);
glVertex2f(-1.5f, 63.0f);
glVertex2f(-3.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //4rth window
glVertex2f(0.0f, 68.0f);
glVertex2f(1.5f, 68.0f);
glVertex2f(1.5f, 63.0f);
glVertex2f(0.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //5th window
glVertex2f(-3.0f, 57.0f);
glVertex2f(-1.5f, 57.0f);
glVertex2f(-1.5f, 52.0f);
glVertex2f(-3.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //6th window
glVertex2f(0.0f, 57.0f);
glVertex2f(1.5f, 57.0f);
glVertex2f(1.5f, 52.0f);
glVertex2f(0.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //7th window
glVertex2f(-3.0f, 47.0f);
glVertex2f(-1.5f, 47.0f);
glVertex2f(-1.5f, 42.5f);
glVertex2f(-3.0f, 42.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //8th window
glVertex2f(0.0f, 47.0f);
glVertex2f(1.5f, 47.0f);
glVertex2f(1.5f, 42.5f);
glVertex2f(0.0f, 42.5f);
glEnd();
}
void fthBuilding(){
glBegin(GL_POLYGON);
glColor3ub(148,35,23);
glVertex2f(16.0, 82.0f);
glVertex2f(18.0f, 79.0f);
glVertex2f(18.0f, 41.0f);
glVertex2f(16.0f, 41.0f);
glColor3ub(218,101,88);
glVertex2f(16.0f, 41.0f);
glVertex2f(9.0f, 41.0f);
glVertex2f(9.0f, 82.0f);
glVertex2f(16.0f, 82.0f);
glEnd();
}
void fthBuildingWindow(){
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st window
glVertex2f(10.0f, 78.0f);
glVertex2f(11.5f, 78.0f);
glVertex2f(11.5f, 73.0f);
glVertex2f(10.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd window
glVertex2f(13.0f, 78.0f);
glVertex2f(14.5f, 78.0f);
glVertex2f(14.5f, 73.0f);
glVertex2f(13.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //3rd window
glVertex2f(10.0f, 68.0f);
glVertex2f(11.5f, 68.0f);
glVertex2f(11.5f, 63.0f);
glVertex2f(10.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //4rth window
glVertex2f(13.0f, 68.0f);
glVertex2f(14.5f, 68.0f);
glVertex2f(14.5f, 63.0f);
glVertex2f(13.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //5th window
glVertex2f(10.0f, 57.0f);
glVertex2f(11.5f, 57.0f);
glVertex2f(11.5f, 52.0f);
glVertex2f(10.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //6th window
glVertex2f(13.0f, 57.0f);
glVertex2f(14.5f, 57.0f);
glVertex2f(14.5f, 52.0f);
glVertex2f(13.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //7th window
glVertex2f(10.0f, 47.0f);
glVertex2f(11.5f, 47.0f);
glVertex2f(11.5f, 42.5f);
glVertex2f(10.0f, 42.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //8th window
glVertex2f(13.0f, 47.0f);
glVertex2f(14.5f, 47.0f);
glVertex2f(14.5f, 42.5f);
glVertex2f(13.0f, 42.5f);
glEnd();
}
void SixBuilding(){
glBegin(GL_POLYGON);
glColor3ub(128,128,128);
glVertex2f(29.0, 86.0f);
glVertex2f(31.0f, 83.0f);
glVertex2f(31.0f, 41.0f);
glVertex2f(29.0f, 41.0f);
glColor3ub(192,192,192);
glVertex2f(29.0f, 41.0f);
glVertex2f(22.0f, 41.0f);
glVertex2f(22.0f, 86.0f);
glVertex2f(29.0f, 86.0f);
glEnd();
}
void SxthBuildingWindow(){
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st window
glVertex2f(23.0f, 82.0f);
glVertex2f(24.5f, 82.0f);
glVertex2f(24.5f, 77.0f);
glVertex2f(23.0f, 77.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd window
glVertex2f(26.0f, 82.0f);
glVertex2f(27.5f, 82.0f);
glVertex2f(27.5f, 77.0f);
glVertex2f(26.0f, 77.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //3rd window
glVertex2f(23.0f, 71.0f);
glVertex2f(24.5f, 71.0f);
glVertex2f(24.5f, 66.0f);
glVertex2f(23.0f, 66.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //4rth window
glVertex2f(26.0f, 71.0f);
glVertex2f(27.5f, 71.0f);
glVertex2f(27.5f, 66.0f);
glVertex2f(26.0f, 66.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //5th window
glVertex2f(23.0f, 60.0f);
glVertex2f(24.5f, 60.0f);
glVertex2f(24.5f, 55.0f);
glVertex2f(23.0f, 55.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //6th window
glVertex2f(26.0f, 60.0f);
glVertex2f(27.5f, 60.0f);
glVertex2f(27.5f, 55.0f);
glVertex2f(26.0f, 55.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //7th window
glVertex2f(23.0f, 49.0f);
glVertex2f(24.5f, 49.0f);
glVertex2f(24.5f, 44.0f);
glVertex2f(23.0f, 44.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //8th window
glVertex2f(26.0f, 49.0f);
glVertex2f(27.5f, 49.0f);
glVertex2f(27.5f, 44.0f);
glVertex2f(26.0f, 44.0f);
glEnd();
}
void sevenBuilding(){
glBegin(GL_POLYGON);
glColor3ub(153,153,0);
glVertex2f(41.0, 78.0f);
glVertex2f(43.0f, 75.0f);
glVertex2f(43.0f, 41.0f);
glVertex2f(41.0f, 41.0f);
glColor3ub(204,204,0);
glVertex2f(41.0f, 41.0f);
glVertex2f(34.0f, 41.0f);
glVertex2f(34.0f, 78.0f);
glVertex2f(41.0f, 78.0f);
glEnd();
}
void sevenBuildingWindow(){
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //1st window
glVertex2f(35.0f, 74.0f);
glVertex2f(36.5f, 74.0f);
glVertex2f(36.5f, 69.0f);
glVertex2f(35.0f, 69.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //2nd window
glVertex2f(38.0f, 74.0f);
glVertex2f(39.5f, 74.0f);
glVertex2f(39.5f, 69.0f);
glVertex2f(38.0f, 69.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //3rd window
glVertex2f(35.0f, 63.0f);
glVertex2f(36.5f, 63.0f);
glVertex2f(36.5f, 58.0f);
glVertex2f(35.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //4th window
glVertex2f(38.0f, 63.0f);
glVertex2f(39.5f, 63.0f);
glVertex2f(39.5f, 58.0f);
glVertex2f(38.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //5th window
glVertex2f(35.0f, 52.0f);
glVertex2f(36.5f, 52.0f);
glVertex2f(36.5f, 47.0f);
glVertex2f(35.0f, 47.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(50, 46, 48); //6th window
glVertex2f(38.0f, 52.0f);
glVertex2f(39.5f, 52.0f);
glVertex2f(39.5f, 47.0f);
glVertex2f(38.0f, 47.0f);
glEnd();
}
void airoplane(){
txA=txA+0.2;
if(txA>90){
txA=-30;
}
glBegin(GL_QUADS);
glColor3ub(220, 132, 132);
glVertex2f(-41.0f, 98.0f);
glVertex2f(-35.0f, 101.0f);
glVertex2f(-33.0f, 95.0f);
glVertex2f(-43.0f, 90.0f);
glEnd();
glBegin(GL_TRIANGLES); //1st wing
glColor3ub(181, 32, 32);
glVertex2f(-39.5f, 96.0f);
glVertex2f(-38.0f, 98.0f);
glVertex2f(-41.5f, 105.0f);
glEnd();
glBegin(GL_TRIANGLES);//2nd wing
glColor3ub(181, 32, 32);
glVertex2f(-39.5f, 92.0f);
glVertex2f(-37.0f, 94.0f);
glVertex2f(-41.5f, 84.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(0, 12, 13);
glVertex2f(-38.0f, 97.0f);
glVertex2f(-36.5f, 97.0f);
glVertex2f(-36.5f, 96.0f);
glVertex2f(-38.0f, 96.0f);
glEnd();
glutPostRedisplay();
}
void Bus2(){
txB2=txB2-0.2;
if(txB2<-50){
txB2=50;
}
glBegin(GL_QUADS); //red
glColor3ub(139,69,19);
glVertex2f(-29.0f, -40.0f);
glVertex2f(-13.0f, -40.0f);
glVertex2f(-13.0f, -52.0f);
glVertex2f(-31.0f, -52.0f);
glEnd();
glBegin(GL_QUADS); //blue
glColor3ub(255,59, 0);
glVertex2f(-31.0f, -52.0f);
glVertex2f(-13.0f, -52.0f);
glVertex2f(-13.0f, -67.0f);
glVertex2f(-31.0f, -67.0f);
glEnd();
glBegin(GL_QUADS); //front glass
glColor3ub(128, 217, 245);
glVertex2f(-29.0f, -41.0f);
glVertex2f(-26.0f, -41.0f);
glVertex2f(-26.0f, -51.0f);
glVertex2f(-31.0f, -51.0f);
glEnd();
glBegin(GL_QUADS); //r8 window
glColor3ub(128, 217, 245);
glVertex2f(-25.0f, -41.0f);
glVertex2f(-22.0f, -41.0f);
glVertex2f(-22.0f, -51.0f);
glVertex2f(-25.0f, -51.0f);
glEnd();
glBegin(GL_QUADS); //middle window
glColor3ub(128, 217, 245);
glVertex2f(-21.0f, -41.0f);
glVertex2f(-18.0f, -41.0f);
glVertex2f(-18.0f, -51.0f);
glVertex2f(-21.0f, -51.0f);
glEnd();
glBegin(GL_QUADS); //right window
glColor3ub(128, 217, 245);
glVertex2f(-17.0f, -41.0f);
glVertex2f(-14.0f, -41.0f);
glVertex2f(-14.0f, -51.0f);
glVertex2f(-17.0f, -51.0f);
glEnd();
glPushMatrix(); //wheel
glTranslated(-28,-67,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPushMatrix(); //whee2
glTranslated(-16,-67,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void Car(){
txC=txC+0.1;
if(txC>90){
txC=-30;
}
glBegin(GL_QUADS); //upper part
glColor3ub(205,95,95);
glVertex2f(-3.0f, -11.0f);
glVertex2f(3.0f, -11.0f);
glVertex2f(4.0f, -17.0f);
glVertex2f(-4.0f, -17.0f);
glEnd();
glBegin(GL_QUADS); //lower part
glColor3ub(50,205,50);
glVertex2f(-6.0f, -17.0f);
glVertex2f(6.0f, -17.0f);
glVertex2f(7.0f, -27.0f);
glVertex2f(-6.0f, -27.0f);
glEnd();
glBegin(GL_QUADS); //window1
glColor3ub(128,117,245);
glVertex2f(-2.0f, -14.0f);
glVertex2f(-1.0f,-14.0f);
glVertex2f(-1.0f,-16.0f);
glVertex2f(-2.0f, -16.0f);
glEnd();
glBegin(GL_QUADS); //window2
glColor3ub(128,117,245);
glVertex2f(1.0f, -14.0f);
glVertex2f(2.0f, -14.0f);
glVertex2f(2.0f, -16.0f);
glVertex2f(1.0f, -16.0f);
glEnd();
glBegin(GL_QUADS); //middle border
glColor3ub(34,139,34);
glVertex2f(0.0f, -17.0f);
glVertex2f(0.3f, -17.0f);
glVertex2f(0.3f, -25.0f);
glVertex2f(0.0f, -25.0f);
glEnd();
glPushMatrix(); //wheel
glTranslated(-4,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(2,2);
glPopMatrix();
glPushMatrix(); //wheel
glTranslated(4,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(2,2);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void Ship(){
txS=txS+0.09;
if(txS>85){
txS=-50;
}
glBegin(GL_QUADS); //lower1 part
glColor3ub(205,192,176);
glVertex2f(-10.0f, 12.0f);
glVertex2f(6.0f,12.0f);
glVertex2f(4.0f,3.0f);
glVertex2f(-10.0f, 3.0f);
glEnd();
glBegin(GL_QUADS); //lower2 part
glColor3ub(139,137,112);
glVertex2f(-8.0f, 18.0f);
glVertex2f(0.0f,18.0f);
glVertex2f(2.0f,12.0f);
glVertex2f(-8.0f, 12.0f);
glEnd();
glBegin(GL_QUADS); //upper2 part
glColor3ub(72,209,204);
glVertex2f(-7.0f, 22.0f);
glVertex2f(-2.0f,22.0f);
glVertex2f(-1.0f,18.0f);
glVertex2f(-7.0f, 18.0f);
glEnd();
glBegin(GL_QUADS); //upper1 part
glColor3ub(106,90,205);
glVertex2f(-6.0f, 26.0f);
glVertex2f(-3.0f,26.0f);
glVertex2f(-2.5f,22.0f);
glVertex2f(-6.0f, 22.0f);
glEnd();
glBegin(GL_QUADS); //lower window1
glColor3ub(255,0,0);
glVertex2f(-7.0f, 16.5f);
glVertex2f(-6.0f,16.5f);
glVertex2f(-6.0f,14.0f);
glVertex2f(-7.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //lower window2
glColor3ub(255,0,0);
glVertex2f(-5.0f, 16.5f);
glVertex2f(-4.0f,16.5f);
glVertex2f(-4.0f,14.0f);
glVertex2f(-5.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //lower window2
glColor3ub(255,0,0);
glVertex2f(-3.0f, 16.5f);
glVertex2f(-2.0f,16.5f);
glVertex2f(-2.0f,14.0f);
glVertex2f(-3.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //lower window3
glColor3ub(255,0,0);
glVertex2f(-1.0f, 16.5f);
glVertex2f(0.0f,16.5f);
glVertex2f(0.0f,14.0f);
glVertex2f(-1.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //middle window1
glColor3ub(173,255,47);
glVertex2f(-6.0f, 21.0f);
glVertex2f(-5.0f,21.0f);
glVertex2f(-5.0f,19.0f);
glVertex2f(-6.0f, 19.0f);
glEnd();
glBegin(GL_QUADS); //middle window2
glColor3ub(173,255,47);
glVertex2f(-4.0f, 21.0f);
glVertex2f(-3.0f,21.0f);
glVertex2f(-3.0f,19.0f);
glVertex2f(-4.0f, 19.0f);
glEnd();
glBegin(GL_QUADS); //upper window
glColor3ub(255,255,0);
glVertex2f(-5.5f, 25.0f);
glVertex2f(-3.5f,25.0f);
glVertex2f(-3.5f,23.0f);
glVertex2f(-5.5f, 23.0f);
glEnd();
glutPostRedisplay();
}
void FrstBuildWindowN(){
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st window
glVertex2f(-44.0f, 73.0f);
glVertex2f(-42.5f, 73.0f);
glVertex2f(-42.5f, 68.0f);
glVertex2f(-44.0f, 68.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd window
glVertex2f(-41.0f, 73.0f);
glVertex2f(-39.5f, 73.0f);
glVertex2f(-39.5f, 68.0f);
glVertex2f(-41.0f, 68.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //3rd window
glVertex2f(-44.0f, 62.0f);
glVertex2f(-42.5f, 62.0f);
glVertex2f(-42.5f, 57.0f);
glVertex2f(-44.0f, 57.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //4rth window
glVertex2f(-41.0f, 62.0f);
glVertex2f(-39.5f, 62.0f);
glVertex2f(-39.5f, 57.0f);
glVertex2f(-41.0f, 57.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //5th window
glVertex2f(-44.0f, 51.0f);
glVertex2f(-42.5f, 51.0f);
glVertex2f(-42.5f, 46.0f);
glVertex2f(-44.0f, 46.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57);
glVertex2f(-41.0f, 51.0f);
glVertex2f(-39.5f, 51.0f);
glVertex2f(-39.5f, 46.0f);
glVertex2f(-41.0f, 46.0f);
glEnd();
}
void secndBuildWindowN(){
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st window
glVertex2f(-29.0f, 75.0f);
glVertex2f(-27.5f, 75.0f);
glVertex2f(-27.5f, 70.0f);
glVertex2f(-29.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd window
glVertex2f(-26.0f, 75.0f);
glVertex2f(-24.5f, 75.0f);
glVertex2f(-24.5f, 70.0f);
glVertex2f(-26.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //3rd window
glVertex2f(-29.0f, 63.0f);
glVertex2f(-27.5f, 63.0f);
glVertex2f(-27.5f, 58.0f);
glVertex2f(-29.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //4rth window
glVertex2f(-26.0f, 63.0f);
glVertex2f(-24.5f, 63.0f);
glVertex2f(-24.5f, 58.0f);
glVertex2f(-26.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //5th window
glVertex2f(-29.0f, 52.0f);
glVertex2f(-27.5f, 52.0f);
glVertex2f(-27.5f, 47.0f);
glVertex2f(-29.0f, 47.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //6th window
glVertex2f(-26.0f, 52.0f);
glVertex2f(-24.5f, 52.0f);
glVertex2f(-24.5f, 47.0f);
glVertex2f(-26.0f, 47.0f);
glEnd();
}
void thirdBildWindowN(){
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st window
glVertex2f(-16.0f, 75.0f);
glVertex2f(-14.5f, 75.0f);
glVertex2f(-14.5f, 70.0f);
glVertex2f(-16.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd window
glVertex2f(-13.0f, 75.0f);
glVertex2f(-11.5f, 75.0f);
glVertex2f(-11.5f, 70.0f);
glVertex2f(-13.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //3rd window
glVertex2f(-16.0f, 63.0f);
glVertex2f(-14.5f, 63.0f);
glVertex2f(-14.5f, 58.0f);
glVertex2f(-16.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //4rth window
glVertex2f(-13.0f, 63.0f);
glVertex2f(-11.5f, 63.0f);
glVertex2f(-11.5f, 58.0f);
glVertex2f(-13.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //5th window
glVertex2f(-16.0f, 52.0f);
glVertex2f(-14.5f, 52.0f);
glVertex2f(-14.5f, 47.0f);
glVertex2f(-16.0f, 47.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //6th window
glVertex2f(-13.0f, 52.0f);
glVertex2f(-11.5f, 52.0f);
glVertex2f(-11.5f, 47.0f);
glVertex2f(-13.0f, 47.0f);
glEnd();
}
void frthBuildingWindowN(){
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st1st window
glVertex2f(-3.0f, 87.0f);
glVertex2f(-1.5f, 87.0f);
glVertex2f(-1.5f, 82.5f);
glVertex2f(-3.0f, 82.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd2nd window
glVertex2f(0.0f, 87.0f);
glVertex2f(1.5f, 87.0f);
glVertex2f(1.5f, 82.5f);
glVertex2f(0.0f, 82.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st window
glVertex2f(-3.0f, 78.0f);
glVertex2f(-1.5f, 78.0f);
glVertex2f(-1.5f, 73.0f);
glVertex2f(-3.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd window
glVertex2f(0.0f, 78.0f);
glVertex2f(1.5f, 78.0f);
glVertex2f(1.5f, 73.0f);
glVertex2f(0.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //3rd window
glVertex2f(-3.0f, 68.0f);
glVertex2f(-1.5f, 68.0f);
glVertex2f(-1.5f, 63.0f);
glVertex2f(-3.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //4rth window
glVertex2f(0.0f, 68.0f);
glVertex2f(1.5f, 68.0f);
glVertex2f(1.5f, 63.0f);
glVertex2f(0.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //5th window
glVertex2f(-3.0f, 57.0f);
glVertex2f(-1.5f, 57.0f);
glVertex2f(-1.5f, 52.0f);
glVertex2f(-3.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //6th window
glVertex2f(0.0f, 57.0f);
glVertex2f(1.5f, 57.0f);
glVertex2f(1.5f, 52.0f);
glVertex2f(0.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //7th window
glVertex2f(-3.0f, 47.0f);
glVertex2f(-1.5f, 47.0f);
glVertex2f(-1.5f, 42.5f);
glVertex2f(-3.0f, 42.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //8th window
glVertex2f(0.0f, 47.0f);
glVertex2f(1.5f, 47.0f);
glVertex2f(1.5f, 42.5f);
glVertex2f(0.0f, 42.5f);
glEnd();
}
void fthBuildingWindowN(){
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st window
glVertex2f(10.0f, 78.0f);
glVertex2f(11.5f, 78.0f);
glVertex2f(11.5f, 73.0f);
glVertex2f(10.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd window
glVertex2f(13.0f, 78.0f);
glVertex2f(14.5f, 78.0f);
glVertex2f(14.5f, 73.0f);
glVertex2f(13.0f, 73.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //3rd window
glVertex2f(10.0f, 68.0f);
glVertex2f(11.5f, 68.0f);
glVertex2f(11.5f, 63.0f);
glVertex2f(10.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //4rth window
glVertex2f(13.0f, 68.0f);
glVertex2f(14.5f, 68.0f);
glVertex2f(14.5f, 63.0f);
glVertex2f(13.0f, 63.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //5th window
glVertex2f(10.0f, 57.0f);
glVertex2f(11.5f, 57.0f);
glVertex2f(11.5f, 52.0f);
glVertex2f(10.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //6th window
glVertex2f(13.0f, 57.0f);
glVertex2f(14.5f, 57.0f);
glVertex2f(14.5f, 52.0f);
glVertex2f(13.0f, 52.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //7th window
glVertex2f(10.0f, 47.0f);
glVertex2f(11.5f, 47.0f);
glVertex2f(11.5f, 42.5f);
glVertex2f(10.0f, 42.5f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //8th window
glVertex2f(13.0f, 47.0f);
glVertex2f(14.5f, 47.0f);
glVertex2f(14.5f, 42.5f);
glVertex2f(13.0f, 42.5f);
glEnd();
}
void SxthBuildingWindowN(){
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st window
glVertex2f(23.0f, 82.0f);
glVertex2f(24.5f, 82.0f);
glVertex2f(24.5f, 77.0f);
glVertex2f(23.0f, 77.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd window
glVertex2f(26.0f, 82.0f);
glVertex2f(27.5f, 82.0f);
glVertex2f(27.5f, 77.0f);
glVertex2f(26.0f, 77.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //3rd window
glVertex2f(23.0f, 71.0f);
glVertex2f(24.5f, 71.0f);
glVertex2f(24.5f, 66.0f);
glVertex2f(23.0f, 66.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //4rth window
glVertex2f(26.0f, 71.0f);
glVertex2f(27.5f, 71.0f);
glVertex2f(27.5f, 66.0f);
glVertex2f(26.0f, 66.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //5th window
glVertex2f(23.0f, 60.0f);
glVertex2f(24.5f, 60.0f);
glVertex2f(24.5f, 55.0f);
glVertex2f(23.0f, 55.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //6th window
glVertex2f(26.0f, 60.0f);
glVertex2f(27.5f, 60.0f);
glVertex2f(27.5f, 55.0f);
glVertex2f(26.0f, 55.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //7th window
glVertex2f(23.0f, 49.0f);
glVertex2f(24.5f, 49.0f);
glVertex2f(24.5f, 44.0f);
glVertex2f(23.0f, 44.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //8th window
glVertex2f(26.0f, 49.0f);
glVertex2f(27.5f, 49.0f);
glVertex2f(27.5f, 44.0f);
glVertex2f(26.0f, 44.0f);
glEnd();
}
void sevenBuildingWindowN(){
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //1st window
glVertex2f(35.0f, 74.0f);
glVertex2f(36.5f, 74.0f);
glVertex2f(36.5f, 69.0f);
glVertex2f(35.0f, 69.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //2nd window
glVertex2f(38.0f, 74.0f);
glVertex2f(39.5f, 74.0f);
glVertex2f(39.5f, 69.0f);
glVertex2f(38.0f, 69.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //3rd window
glVertex2f(35.0f, 63.0f);
glVertex2f(36.5f, 63.0f);
glVertex2f(36.5f, 58.0f);
glVertex2f(35.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //4th window
glVertex2f(38.0f, 63.0f);
glVertex2f(39.5f, 63.0f);
glVertex2f(39.5f, 58.0f);
glVertex2f(38.0f, 58.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //5th window
glVertex2f(35.0f, 52.0f);
glVertex2f(36.5f, 52.0f);
glVertex2f(36.5f, 47.0f);
glVertex2f(35.0f, 47.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57); //6th window
glVertex2f(38.0f, 52.0f);
glVertex2f(39.5f, 52.0f);
glVertex2f(39.5f, 47.0f);
glVertex2f(38.0f, 47.0f);
glEnd();
}
void ShipN(){
txS=txS+0.09;
if(txS>85){
txS=-50;
}
glBegin(GL_QUADS); //lower1 part
glColor3ub(205,192,176);
glVertex2f(-10.0f, 12.0f);
glVertex2f(6.0f,12.0f);
glVertex2f(4.0f,3.0f);
glVertex2f(-10.0f, 3.0f);
glEnd();
glBegin(GL_QUADS); //lower2 part
glColor3ub(139,137,112);
glVertex2f(-8.0f, 18.0f);
glVertex2f(0.0f,18.0f);
glVertex2f(2.0f,12.0f);
glVertex2f(-8.0f, 12.0f);
glEnd();
glBegin(GL_QUADS); //upper2 part
glColor3ub(72,209,204);
glVertex2f(-7.0f, 22.0f);
glVertex2f(-2.0f,22.0f);
glVertex2f(-1.0f,18.0f);
glVertex2f(-7.0f, 18.0f);
glEnd();
glBegin(GL_QUADS); //upper1 part
glColor3ub(106,90,205);
glVertex2f(-6.0f, 26.0f);
glVertex2f(-3.0f,26.0f);
glVertex2f(-2.5f,22.0f);
glVertex2f(-6.0f, 22.0f);
glEnd();
glBegin(GL_QUADS); //lower window1
glColor3ub(243, 243, 57);
glVertex2f(-7.0f, 16.5f);
glVertex2f(-6.0f,16.5f);
glVertex2f(-6.0f,14.0f);
glVertex2f(-7.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //lower window2
glColor3ub(243, 243, 57);
glVertex2f(-5.0f, 16.5f);
glVertex2f(-4.0f,16.5f);
glVertex2f(-4.0f,14.0f);
glVertex2f(-5.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //lower window2
glColor3ub(243, 243, 57);
glVertex2f(-3.0f, 16.5f);
glVertex2f(-2.0f,16.5f);
glVertex2f(-2.0f,14.0f);
glVertex2f(-3.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //lower window3
glColor3ub(243, 243, 57);
glVertex2f(-1.0f, 16.5f);
glVertex2f(0.0f,16.5f);
glVertex2f(0.0f,14.0f);
glVertex2f(-1.0f, 14.0f);
glEnd();
glBegin(GL_QUADS); //middle window1
glColor3ub(243, 243, 57);
glVertex2f(-6.0f, 21.0f);
glVertex2f(-5.0f,21.0f);
glVertex2f(-5.0f,19.0f);
glVertex2f(-6.0f, 19.0f);
glEnd();
glBegin(GL_QUADS); //middle window2
glColor3ub(243, 243, 57);
glVertex2f(-4.0f, 21.0f);
glVertex2f(-3.0f,21.0f);
glVertex2f(-3.0f,19.0f);
glVertex2f(-4.0f, 19.0f);
glEnd();
glBegin(GL_QUADS); //upper window
glColor3ub(243, 243, 57);
glVertex2f(-5.5f, 25.0f);
glVertex2f(-3.5f,25.0f);
glVertex2f(-3.5f,23.0f);
glVertex2f(-5.5f, 23.0f);
glEnd();
glutPostRedisplay();
}
void CarN(){
txC=txC+.3;
if(txC>90){
txC=-30;
}
glBegin(GL_QUADS); //upper part
glColor3ub(205,95,95);
glVertex2f(-3.0f, -11.0f);
glVertex2f(3.0f, -11.0f);
glVertex2f(4.0f, -17.0f);
glVertex2f(-4.0f, -17.0f);
glEnd();
glBegin(GL_QUADS); //lower part
glColor3ub(50,205,50);
glVertex2f(-6.0f, -17.0f);
glVertex2f(6.0f, -17.0f);
glVertex2f(7.0f, -27.0f);
glVertex2f(-6.0f, -27.0f);
glEnd();
glBegin(GL_QUADS); //window1
glColor3ub(243, 243, 57);
glVertex2f(-2.0f, -14.0f);
glVertex2f(-1.0f,-14.0f);
glVertex2f(-1.0f,-16.0f);
glVertex2f(-2.0f, -16.0f);
glEnd();
glBegin(GL_QUADS); //window2
glColor3ub(243, 243, 57);
glVertex2f(1.0f, -14.0f);
glVertex2f(2.0f, -14.0f);
glVertex2f(2.0f, -16.0f);
glVertex2f(1.0f, -16.0f);
glEnd();
glBegin(GL_QUADS); //middle border
glColor3ub(34,139,34);
glVertex2f(0.0f, -17.0f);
glVertex2f(0.3f, -17.0f);
glVertex2f(0.3f, -25.0f);
glVertex2f(0.0f, -25.0f);
glEnd();
glPushMatrix(); //wheel
glTranslated(-4,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(2,2);
glPopMatrix();
glPushMatrix(); //wheel
glTranslated(4,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(2,2);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void Bus2N(){
txB2=txB2-0.2;
if(txB2<-50){
txB2=50;
}
glBegin(GL_QUADS); //red
glColor3ub(139,69,19);
glVertex2f(-29.0f, -40.0f);
glVertex2f(-13.0f, -40.0f);
glVertex2f(-13.0f, -52.0f);
glVertex2f(-31.0f, -52.0f);
glEnd();
glBegin(GL_QUADS); //blue
glColor3ub(255,59, 0);
glVertex2f(-31.0f, -52.0f);
glVertex2f(-13.0f, -52.0f);
glVertex2f(-13.0f, -67.0f);
glVertex2f(-31.0f, -67.0f);
glEnd();
glBegin(GL_QUADS); //front glass
glColor3ub(243, 243, 57);
glVertex2f(-29.0f, -41.0f);
glVertex2f(-26.0f, -41.0f);
glVertex2f(-26.0f, -51.0f);
glVertex2f(-31.0f, -51.0f);
glEnd();
glBegin(GL_QUADS); //r8 window
glColor3ub(243, 243, 57);
glVertex2f(-25.0f, -41.0f);
glVertex2f(-22.0f, -41.0f);
glVertex2f(-22.0f, -51.0f);
glVertex2f(-25.0f, -51.0f);
glEnd();
glBegin(GL_QUADS); //middle window
glColor3ub(243, 243, 57);
glVertex2f(-21.0f, -41.0f);
glVertex2f(-18.0f, -41.0f);
glVertex2f(-18.0f, -51.0f);
glVertex2f(-21.0f, -51.0f);
glEnd();
glBegin(GL_QUADS); //right window
glColor3ub(243, 243, 57);
glVertex2f(-17.0f, -41.0f);
glVertex2f(-14.0f, -41.0f);
glVertex2f(-14.0f, -51.0f);
glVertex2f(-17.0f, -51.0f);
glEnd();
glPushMatrix(); //wheel
glTranslated(-28,-67,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPushMatrix(); //whee2
glTranslated(-16,-67,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void Bus1N(){
tx=tx+0.2;
if(tx>90){
tx=-30;
}
glBegin(GL_QUADS); //red
glColor3ub(213, 50, 9);
glVertex2f(-30.0f, 0.0f);
glVertex2f(-12.0f, 0.0f);
glVertex2f(-12.0f, -11.0f);
glVertex2f(-30.0f, -11.0f);
glEnd();
glBegin(GL_QUADS); //blue
glColor3ub(28, 58, 205);
glVertex2f(-30.0f, -11.0f);
glVertex2f(-12.0f, -11.0f);
glVertex2f(-12.0f, -27.0f);
glVertex2f(-30.0f, -27.0f);
glEnd();
glBegin(GL_QUADS); //left window
glColor3ub(243, 243, 57);
glVertex2f(-29.0f, -1.0f);
glVertex2f(-26.0f, -1.0f);
glVertex2f(-26.0f, -10.0f);
glVertex2f(-29.0f, -10.0f);
glEnd();
glBegin(GL_QUADS); //middle window
glColor3ub(243, 243, 57);
glVertex2f(-25.0f, -1.0f);
glVertex2f(-22.0f, -1.0f);
glVertex2f(-22.0f, -10.0f);
glVertex2f(-25.0f, -10.0f);
glEnd();
glBegin(GL_QUADS); //right window
glColor3ub(243, 243, 57);
glVertex2f(-21.0f, -1.0f);
glVertex2f(-18.0f, -1.0f);
glVertex2f(-18.0f, -10.0f);
glVertex2f(-21.0f, -10.0f);
glEnd();
glBegin(GL_QUADS); //front glass
glColor3ub(243, 243, 57);
glVertex2f(-17.0f, -1.0f);
glVertex2f(-12.0f, -1.0f);
glVertex2f(-12.0f, -10.0f);
glVertex2f(-17.0f, -10.0f);
glEnd();
glPushMatrix();
glTranslated(-27,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPushMatrix();
glTranslated(-15,-27,0);
glScaled(0.5,1.5,0);
glColor3f(0.0,0.0,0.0);
circle(3,3);
glPopMatrix();
glPopMatrix();
glutPostRedisplay();
}
void Rain(){
tyR=tyR-11;
if(tyR<-190){
tyR=100;
}
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-49.0f, 110.0f);
glVertex2f(-48.5f, 110.0f);
glVertex2f(-48.5f, 100.0f);
glVertex2f(-49.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-49.0f, 70.0f);
glVertex2f(-48.5f, 70.0f);
glVertex2f(-48.5f, 60.0f);
glVertex2f(-49.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-49.0f, 30.0f);
glVertex2f(-48.5f, 30.0f);
glVertex2f(-48.5f, 20.0f);
glVertex2f(-49.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-49.0f, -10.0f);
glVertex2f(-48.5f, -10.0f);
glVertex2f(-48.5f, -20.0f);
glVertex2f(-49.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-49.0f, -50.0f);
glVertex2f(-48.5f, -50.0f);
glVertex2f(-48.5f, -60.0f);
glVertex2f(-49.0f, -50.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-45.0f, 110.0f);
glVertex2f(-44.5f, 110.0f);
glVertex2f(-44.5f, 100.0f);
glVertex2f(-45.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-45.0f, 70.0f);
glVertex2f(-44.5f, 70.0f);
glVertex2f(-44.5f, 60.0f);
glVertex2f(-45.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-45.0f, 30.0f);
glVertex2f(-44.5f, 30.0f);
glVertex2f(-44.5f, 20.0f);
glVertex2f(-45.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-45.0f, -10.0f);
glVertex2f(-44.5f, -10.0f);
glVertex2f(-44.5f, -20.0f);
glVertex2f(-45.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-41.0f, 110.0f);
glVertex2f(-40.5f, 110.0f);
glVertex2f(-40.5f, 100.0f);
glVertex2f(-41.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-41.0f, 70.0f);
glVertex2f(-40.5f, 70.0f);
glVertex2f(-40.5f, 60.0f);
glVertex2f(-41.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-41.0f, 30.0f);
glVertex2f(-40.5f, 30.0f);
glVertex2f(-40.5f, 20.0f);
glVertex2f(-41.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-41.0f, -10.0f);
glVertex2f(-40.5f, -10.0f);
glVertex2f(-40.5f, -20.0f);
glVertex2f(-41.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-37.0f, 110.0f);
glVertex2f(-36.5f, 110.0f);
glVertex2f(-36.5f, 100.0f);
glVertex2f(-37.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-37.0f, 70.0f);
glVertex2f(-36.5f, 70.0f);
glVertex2f(-36.5f, 60.0f);
glVertex2f(-37.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-37.0f, 30.0f);
glVertex2f(-36.5f, 30.0f);
glVertex2f(-36.5f, 20.0f);
glVertex2f(-37.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-37.0f, -10.0f);
glVertex2f(-36.5f, -10.0f);
glVertex2f(-36.5f, -20.0f);
glVertex2f(-37.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-33.0f, 110.0f);
glVertex2f(-32.5f, 110.0f);
glVertex2f(-32.5f, 100.0f);
glVertex2f(-33.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-33.0f, 70.0f);
glVertex2f(-32.5f, 70.0f);
glVertex2f(-32.5f, 60.0f);
glVertex2f(-33.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-33.0f, 30.0f);
glVertex2f(-32.5f, 30.0f);
glVertex2f(-32.5f, 20.0f);
glVertex2f(-33.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-33.0f, -10.0f);
glVertex2f(-32.5f, -10.0f);
glVertex2f(-32.5f, -20.0f);
glVertex2f(-33.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-29.0f, 110.0f);
glVertex2f(-28.5f, 110.0f);
glVertex2f(-28.5f, 100.0f);
glVertex2f(-29.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-29.0f, 70.0f);
glVertex2f(-28.5f, 70.0f);
glVertex2f(-28.5f, 60.0f);
glVertex2f(-29.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-29.0f, 30.0f);
glVertex2f(-28.5f, 30.0f);
glVertex2f(-28.5f, 20.0f);
glVertex2f(-29.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-29.0f, -10.0f);
glVertex2f(-28.5f, -10.0f);
glVertex2f(-28.5f, -20.0f);
glVertex2f(-29.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-25.0f, 110.0f);
glVertex2f(-24.5f, 110.0f);
glVertex2f(-24.5f, 100.0f);
glVertex2f(-25.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-25.0f, 70.0f);
glVertex2f(-24.5f, 70.0f);
glVertex2f(-24.5f, 60.0f);
glVertex2f(-25.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-25.0f, 30.0f);
glVertex2f(-24.5f, 30.0f);
glVertex2f(-24.5f, 20.0f);
glVertex2f(-25.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-25.0f, -10.0f);
glVertex2f(-24.5f, -10.0f);
glVertex2f(-24.5f, -20.0f);
glVertex2f(-25.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-21.0f, 110.0f);
glVertex2f(-20.5f, 110.0f);
glVertex2f(-20.5f, 100.0f);
glVertex2f(-21.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-21.0f, 70.0f);
glVertex2f(-20.5f, 70.0f);
glVertex2f(-20.5f, 60.0f);
glVertex2f(-21.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-21.0f, 30.0f);
glVertex2f(-20.5f, 30.0f);
glVertex2f(-20.5f, 20.0f);
glVertex2f(-21.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-21.0f, -10.0f);
glVertex2f(-20.5f, -10.0f);
glVertex2f(-20.5f, -20.0f);
glVertex2f(-21.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-17.0f, 110.0f);
glVertex2f(-16.5f, 110.0f);
glVertex2f(-16.5f, 100.0f);
glVertex2f(-17.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-17.0f, 70.0f);
glVertex2f(-16.5f, 70.0f);
glVertex2f(-16.5f, 60.0f);
glVertex2f(-17.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-17.0f, 30.0f);
glVertex2f(-16.5f, 30.0f);
glVertex2f(-16.5f, 20.0f);
glVertex2f(-17.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-17.0f, -10.0f);
glVertex2f(-16.5f, -10.0f);
glVertex2f(-16.5f, -20.0f);
glVertex2f(-17.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-13.0f, 110.0f);
glVertex2f(-12.5f, 110.0f);
glVertex2f(-12.5f, 100.0f);
glVertex2f(-13.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-13.0f, 70.0f);
glVertex2f(-12.5f, 70.0f);
glVertex2f(-12.5f, 60.0f);
glVertex2f(-13.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-13.0f, 30.0f);
glVertex2f(-12.5f, 30.0f);
glVertex2f(-12.5f, 20.0f);
glVertex2f(-13.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-13.0f, -10.0f);
glVertex2f(-12.5f, -10.0f);
glVertex2f(-12.5f, -20.0f);
glVertex2f(-13.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-9.0f, 110.0f);
glVertex2f(-8.5f, 110.0f);
glVertex2f(-8.5f, 100.0f);
glVertex2f(-9.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-9.0f, 70.0f);
glVertex2f(-8.5f, 70.0f);
glVertex2f(-8.5f, 60.0f);
glVertex2f(-9.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-9.0f, 30.0f);
glVertex2f(-8.5f, 30.0f);
glVertex2f(-8.5f, 20.0f);
glVertex2f(-9.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-9.0f, -10.0f);
glVertex2f(-8.5f, -10.0f);
glVertex2f(-8.5f, -20.0f);
glVertex2f(-9.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-5.0f, 110.0f);
glVertex2f(-4.5f, 110.0f);
glVertex2f(-4.5f, 100.0f);
glVertex2f(-5.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-5.0f, 70.0f);
glVertex2f(-4.5f, 70.0f);
glVertex2f(-4.5f, 60.0f);
glVertex2f(-5.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-5.0f, 30.0f);
glVertex2f(-4.5f, 30.0f);
glVertex2f(-4.5f, 20.0f);
glVertex2f(-5.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-5.0f, -10.0f);
glVertex2f(-4.5f, -10.0f);
glVertex2f(-4.5f, -20.0f);
glVertex2f(-5.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-1.0f, 110.0f);
glVertex2f(-0.5f, 110.0f);
glVertex2f(-0.5f, 100.0f);
glVertex2f(-1.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-1.0f, 70.0f);
glVertex2f(-0.5f, 70.0f);
glVertex2f(-0.5f, 60.0f);
glVertex2f(-1.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-1.0f, 30.0f);
glVertex2f(-0.5f, 30.0f);
glVertex2f(-0.5f, 20.0f);
glVertex2f(-1.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(-1.0f, -10.0f);
glVertex2f(-0.5f, -10.0f);
glVertex2f(-0.5f, -20.0f);
glVertex2f(-1.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(3.0f, 110.0f);
glVertex2f(3.5f, 110.0f);
glVertex2f(3.5f, 100.0f);
glVertex2f(3.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(3.0f, 70.0f);
glVertex2f(3.5f, 70.0f);
glVertex2f(3.5f, 60.0f);
glVertex2f(3.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(3.0f, 30.0f);
glVertex2f(3.5f, 30.0f);
glVertex2f(3.5f, 20.0f);
glVertex2f(3.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(3.0f, -10.0f);
glVertex2f(3.5f, -10.0f);
glVertex2f(3.5f, -20.0f);
glVertex2f(3.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(7.0f, 110.0f);
glVertex2f(7.5f, 110.0f);
glVertex2f(7.5f, 100.0f);
glVertex2f(7.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(7.0f, 70.0f);
glVertex2f(7.5f, 70.0f);
glVertex2f(7.5f, 60.0f);
glVertex2f(7.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(7.0f, 30.0f);
glVertex2f(7.5f, 30.0f);
glVertex2f(7.5f, 20.0f);
glVertex2f(7.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(7.0f, -10.0f);
glVertex2f(7.5f, -10.0f);
glVertex2f(7.5f, -20.0f);
glVertex2f(7.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(11.0f, 110.0f);
glVertex2f(11.5f, 110.0f);
glVertex2f(11.5f, 100.0f);
glVertex2f(11.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(11.0f, 70.0f);
glVertex2f(11.5f, 70.0f);
glVertex2f(11.5f, 60.0f);
glVertex2f(11.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(11.0f, 30.0f);
glVertex2f(11.5f, 30.0f);
glVertex2f(11.5f, 20.0f);
glVertex2f(11.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(11.0f, -10.0f);
glVertex2f(11.5f, -10.0f);
glVertex2f(11.5f, -20.0f);
glVertex2f(11.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(15.0f, 110.0f);
glVertex2f(15.5f, 110.0f);
glVertex2f(15.5f, 100.0f);
glVertex2f(15.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(15.0f, 70.0f);
glVertex2f(15.5f, 70.0f);
glVertex2f(15.5f, 60.0f);
glVertex2f(15.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(15.0f, 30.0f);
glVertex2f(15.5f, 30.0f);
glVertex2f(15.5f, 20.0f);
glVertex2f(15.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(15.0f, -10.0f);
glVertex2f(15.5f, -10.0f);
glVertex2f(15.5f, -20.0f);
glVertex2f(15.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(19.0f, 110.0f);
glVertex2f(19.5f, 110.0f);
glVertex2f(19.5f, 100.0f);
glVertex2f(19.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(19.0f, 70.0f);
glVertex2f(19.5f, 70.0f);
glVertex2f(19.5f, 60.0f);
glVertex2f(19.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(19.0f, 30.0f);
glVertex2f(19.5f, 30.0f);
glVertex2f(19.5f, 20.0f);
glVertex2f(19.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(19.0f, -10.0f);
glVertex2f(19.5f, -10.0f);
glVertex2f(19.5f, -20.0f);
glVertex2f(19.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(23.0f, 110.0f);
glVertex2f(23.5f, 110.0f);
glVertex2f(23.5f, 100.0f);
glVertex2f(23.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(23.0f, 70.0f);
glVertex2f(23.5f, 70.0f);
glVertex2f(23.5f, 60.0f);
glVertex2f(23.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(23.0f, 30.0f);
glVertex2f(23.5f, 30.0f);
glVertex2f(23.5f, 20.0f);
glVertex2f(23.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(23.0f, -10.0f);
glVertex2f(23.5f, -10.0f);
glVertex2f(23.5f, -20.0f);
glVertex2f(23.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(27.0f, 110.0f);
glVertex2f(27.5f, 110.0f);
glVertex2f(27.5f, 100.0f);
glVertex2f(27.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(27.0f, 70.0f);
glVertex2f(27.5f, 70.0f);
glVertex2f(27.5f, 60.0f);
glVertex2f(27.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(27.0f, 30.0f);
glVertex2f(27.5f, 30.0f);
glVertex2f(27.5f, 20.0f);
glVertex2f(27.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(27.0f, -10.0f);
glVertex2f(27.5f, -10.0f);
glVertex2f(27.5f, -20.0f);
glVertex2f(27.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(31.0f, 110.0f);
glVertex2f(31.5f, 110.0f);
glVertex2f(31.5f, 100.0f);
glVertex2f(31.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(31.0f, 70.0f);
glVertex2f(31.5f, 70.0f);
glVertex2f(31.5f, 60.0f);
glVertex2f(31.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(31.0f, 30.0f);
glVertex2f(31.5f, 30.0f);
glVertex2f(31.5f, 20.0f);
glVertex2f(31.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(31.0f, -10.0f);
glVertex2f(31.5f, -10.0f);
glVertex2f(31.5f, -20.0f);
glVertex2f(31.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(35.0f, 110.0f);
glVertex2f(35.5f, 110.0f);
glVertex2f(35.5f, 100.0f);
glVertex2f(35.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(35.0f, 70.0f);
glVertex2f(35.5f, 70.0f);
glVertex2f(35.5f, 60.0f);
glVertex2f(35.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(35.0f, 30.0f);
glVertex2f(35.5f, 30.0f);
glVertex2f(35.5f, 20.0f);
glVertex2f(35.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(35.0f, -10.0f);
glVertex2f(35.5f, -10.0f);
glVertex2f(35.5f, -20.0f);
glVertex2f(35.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(39.0f, 110.0f);
glVertex2f(39.5f, 110.0f);
glVertex2f(39.5f, 100.0f);
glVertex2f(39.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(39.0f, 70.0f);
glVertex2f(39.5f, 70.0f);
glVertex2f(39.5f, 60.0f);
glVertex2f(39.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(39.0f, 30.0f);
glVertex2f(39.5f, 30.0f);
glVertex2f(39.5f, 20.0f);
glVertex2f(39.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(39.0f, -10.0f);
glVertex2f(39.5f, -10.0f);
glVertex2f(39.5f, -20.0f);
glVertex2f(39.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(43.0f, 110.0f);
glVertex2f(43.5f, 110.0f);
glVertex2f(43.5f, 100.0f);
glVertex2f(43.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(43.0f, 70.0f);
glVertex2f(43.5f, 70.0f);
glVertex2f(43.5f, 60.0f);
glVertex2f(43.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(43.0f, 30.0f);
glVertex2f(43.5f, 30.0f);
glVertex2f(43.5f, 20.0f);
glVertex2f(43.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(43.0f, -10.0f);
glVertex2f(43.5f, -10.0f);
glVertex2f(43.5f, -20.0f);
glVertex2f(43.0f, -10.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(47.0f, 110.0f);
glVertex2f(47.5f, 110.0f);
glVertex2f(47.5f, 100.0f);
glVertex2f(47.0f, 110.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(47.0f, 70.0f);
glVertex2f(47.5f, 70.0f);
glVertex2f(47.5f, 60.0f);
glVertex2f(47.0f, 70.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(47.0f, 30.0f);
glVertex2f(47.5f, 30.0f);
glVertex2f(47.5f, 20.0f);
glVertex2f(47.0f, 30.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(160, 160, 160);
glVertex2f(47.0f, -10.0f);
glVertex2f(47.5f, -10.0f);
glVertex2f(47.5f, -20.0f);
glVertex2f(47.0f, -10.0f);
glEnd();
glutPostRedisplay();
}
void airoplaneN(){
txA=txA+0.2;
if(txA>90){
txA=-30;
}
glBegin(GL_QUADS);
glColor3ub(220, 132, 132);
glVertex2f(-41.0f, 98.0f);
glVertex2f(-35.0f, 101.0f);
glVertex2f(-33.0f, 95.0f);
glVertex2f(-43.0f, 90.0f);
glEnd();
glBegin(GL_TRIANGLES); //1st wing
glColor3ub(181, 32, 32);
glVertex2f(-39.5f, 96.0f);
glVertex2f(-38.0f, 98.0f);
glVertex2f(-41.5f, 105.0f);
glEnd();
glBegin(GL_TRIANGLES);//2nd wing
glColor3ub(181, 32, 32);
glVertex2f(-39.5f, 92.0f);
glVertex2f(-37.0f, 94.0f);
glVertex2f(-41.5f, 84.0f);
glEnd();
glBegin(GL_QUADS);
glColor3ub(243, 243, 57);
glVertex2f(-38.0f, 97.0f);
glVertex2f(-36.5f, 97.0f);
glVertex2f(-36.5f, 96.0f);
glVertex2f(-38.0f, 96.0f);
glEnd();
glutPostRedisplay();
}
void Daydisplay(void){
glClear(GL_COLOR_BUFFER_BIT);
sky();
RiverBorder();
River();
Roadborder();
LightStand();
Road();
footpath();
sun();
glPushMatrix(); // Draws The Bus1
glTranslatef(tx,ty,0);
Bus1();
glPopMatrix();
glPushMatrix(); // Draws The Bus1
glTranslatef(txB2,tyB2,0);
Bus2();
glPopMatrix();
glPushMatrix(); // Draws The Car
glTranslatef(txC,0,0);
Car();
glPopMatrix();
glPushMatrix(); // Draws The ship
glTranslatef(txS,tyS,0);
Ship();
glPopMatrix();
cloudLeft();
cloudRight();
cloudMiddle();
glPushMatrix(); // Draws The airoplane
glTranslatef(txA,tyA,0);
airoplane();
glPopMatrix();
FirstBuild();
FrstBuildWindow();
SecondBuilding();
secndBuildWindow();
thrdBuilding();
thirdBildWindow();
FrthBuilding();
frthBuildingWindow();
fthBuilding();
fthBuildingWindow();
SixBuilding();
SxthBuildingWindow();
sevenBuilding();
sevenBuildingWindow();
glFlush();
}
void NightDisplay(){
glClear(GL_COLOR_BUFFER_BIT);
skyN();
star1();
star2();
star3();
star4();
star5();
star6();
star7();
star8();
star9();
star10();
star11();
star12();
star13();
star14();
star15();
star16();
star17();
star18();
star19();
star20();
RiverBorder();
RiverN();
Roadborder();
LightStandN();
Road();
footpath();
glPushMatrix(); // Draws The Bus1
glTranslatef(tx,ty,0);
Bus1N();
glPopMatrix();
glPushMatrix(); // Draws The Bus1
glTranslatef(txB2,tyB2,0);
Bus2N();
glPopMatrix();
glPushMatrix(); // Draws The Car
glTranslatef(txC,tyC,0);
CarN();
glPopMatrix();
glPushMatrix(); // Draws The ship
glTranslatef(txS,tyS,0);
ShipN();
glPopMatrix();
moon();
cloudLeft();
cloudRight();
cloudMiddle();
glPushMatrix(); // Draws The airoplane
glTranslatef(txA,tyA,0);
airoplaneN();
glPopMatrix();
FirstBuild();
FrstBuildWindowN();
SecondBuilding();
secndBuildWindowN();
thrdBuilding();
thirdBildWindowN();
FrthBuilding();
frthBuildingWindowN();
fthBuilding();
fthBuildingWindowN();
SixBuilding();
SxthBuildingWindowN();
sevenBuilding();
sevenBuildingWindowN();
glFlush();
}
void RainDisplay(){
glClear(GL_COLOR_BUFFER_BIT);
skyR();
RiverBorder();
RiverR();
Roadborder();
LightStand();
Road();
footpath();
sunR();
glPushMatrix(); // Draws The Bus1
glTranslatef(tx,ty,0);
Bus1();
glPopMatrix();
glPushMatrix(); // Draws The Bus1
glTranslatef(txB2,tyB2,0);
Bus2();
glPopMatrix();
glPushMatrix(); // Draws The Car
glTranslatef(txC,tyC,0);
Car();
glPopMatrix();
glPushMatrix(); // Draws The ship
glTranslatef(txS,tyS,0);
Ship();
glPopMatrix();
cloudLeft();
cloudRight();
cloudMiddle();
glPushMatrix(); // Draws The airoplane
glTranslatef(txA,tyA,0);
airoplane();
glPopMatrix();
FirstBuild();
FrstBuildWindow();
SecondBuilding();
secndBuildWindow();
thrdBuilding();
thirdBildWindow();
FrthBuilding();
frthBuildingWindow();
fthBuilding();
fthBuildingWindow();
SixBuilding();
SxthBuildingWindow();
sevenBuilding();
sevenBuildingWindow();
glPushMatrix(); // Draws The Rain
glTranslatef(txR,tyR,0);
Rain();
glPopMatrix();
glFlush();
}
void Display(){
screen();
introscreen();
glFlush();
glutPostRedisplay();
}
void init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glMatrixMode(GLUT_SINGLE| GLUT_RGB);
glLoadIdentity();
glOrtho(-50.0, 50.0, -90.0, 110.0, -50.0, 50.0);
}
void my_keyboard(unsigned char key, int x, int y)
{
switch (key) {
case 'd':
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (1600, 1000);
glutInitWindowPosition (0, 0);
glutCreateWindow ("Day scenerio");
init();
glutKeyboardFunc(my_keyboard);
glutDisplayFunc(Daydisplay);
glutPostRedisplay();
break;
case 'n':
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (1600, 1000);
glutInitWindowPosition (0, 0);
glutCreateWindow ("Night scenerio");
init();
glutKeyboardFunc(my_keyboard);
glutDisplayFunc(NightDisplay);
glutPostRedisplay();
break;
case 'r':
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (1600, 1000);
glutInitWindowPosition (0, 0);
glutCreateWindow ("Rain scenerio");
init();
glutKeyboardFunc(my_keyboard);
glutDisplayFunc(RainDisplay);
glutPostRedisplay();
break;
default:
break;
}
}
int main(int arg, char **argv)
{
glutInit(&arg, argv);
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize (1600, 1000);
glutInitWindowPosition (0, 0);
glutCreateWindow ("Lake View City");
init();
glutKeyboardFunc(my_keyboard);
glutDisplayFunc(Display);
glutMainLoop();
return 0;
}
| true |
24efe9bfdccf1c3cbce42ca6cc89f0b46c1e7903 | C++ | Delaunay/hydrafs | /src/bencode.h | UTF-8 | 1,678 | 2.90625 | 3 | [] | no_license | #ifndef HYDRAFS_BENCODE_HEADER
#define HYDRAFS_BENCODE_HEADER
// simple bencode parsing
// https://en.wikipedia.org/wiki/Bencode
#include <ostream>
#include <string>
#include <vector>
namespace hydrafs{
namespace bencode{
struct Value{
Value() = default;
Value(std::string bytes):
_string(std::move(bytes)), dtype(STR)
{}
Value(int integer):
_integer(integer), dtype(INT)
{}
Value(std::vector<std::pair<std::string, Value>> dict):
_dict(std::move(dict)), dtype(DICT)
{}
Value(std::vector<Value> list):
_list(std::move(list)), dtype(LIST)
{}
std::string const& string() const {
return _string;
}
int integer() const {
return _integer;
}
std::vector<Value> const& list() const {
return _list;
}
std::vector<std::pair<std::string, Value>> const& dict() const {
return _dict;
}
bool is_integer() const { return dtype == INT; }
bool is_string() const { return dtype == STR; }
bool is_list() const { return dtype == LIST; }
bool is_dict() const { return dtype == DICT; }
std::ostream& print(std::ostream& out) const;
private:
std::string _string;
int _integer = 0;
std::vector<Value> _list;
// this should be sorted in lexicographical order
std::vector<std::pair<std::string, Value>> _dict;
public:
const enum {
INT,
STR,
LIST,
DICT,
NONE
} dtype = NONE;
};
Value parse_bencode(FILE* file, int depth = 0);
std::ostream& pprint(std::ostream& out, Value const& val, std::size_t depth = 0);
} // namespace bencode
} // namespace hydrafs
#endif
| true |
f60e8250b0407afb4feb6f0a0ea9f6afad36867a | C++ | SeisSol/Device | /interfaces/sycl/DeviceCircularQueueBuffer.cpp | UTF-8 | 2,017 | 2.984375 | 3 | [
"BSD-3-Clause"
] | permissive | #include "DeviceCircularQueueBuffer.h"
#include "utils/logger.h"
namespace device {
DeviceCircularQueueBuffer::DeviceCircularQueueBuffer(
cl::sycl::device dev,
std::function<void(cl::sycl::exception_list)> handler,
size_t capacity)
: queues{std::vector<cl::sycl::queue>(capacity)} {
if (capacity <= 0)
throw std::invalid_argument("Capacity must be at least 1!");
this->defaultQueue = cl::sycl::queue{dev, handler, cl::sycl::property::queue::in_order()};
this->genericQueue = cl::sycl::queue{dev, handler, cl::sycl::property::queue::in_order()};
for (size_t i = 0; i < capacity; i++) {
this->queues[i] = cl::sycl::queue{dev, handler, cl::sycl::property::queue::in_order()};
}
}
cl::sycl::queue& DeviceCircularQueueBuffer::getDefaultQueue() {
return defaultQueue;
}
cl::sycl::queue& DeviceCircularQueueBuffer::getGenericQueue() {
return genericQueue;
}
cl::sycl::queue& DeviceCircularQueueBuffer::getNextQueue() {
(++this->counter) %= getCapacity();
return (this->queues[this->counter]);
}
void DeviceCircularQueueBuffer::resetIndex() {
this->counter = 0;
}
size_t DeviceCircularQueueBuffer::getCapacity() {
return queues.size();
}
void DeviceCircularQueueBuffer::syncQueueWithHost(cl::sycl::queue *queuePtr) {
if (!this->exists(queuePtr))
throw std::invalid_argument("DEVICE::ERROR: passed stream does not belong to circular stream buffer");
queuePtr->wait_and_throw();
}
void DeviceCircularQueueBuffer::syncAllQueuesWithHost() {
defaultQueue.wait_and_throw();
for (auto &q : this->queues) {
q.wait_and_throw();
}
}
bool DeviceCircularQueueBuffer::exists(cl::sycl::queue *queuePtr) {
bool isDefaultQueue = queuePtr == (&defaultQueue);
bool isGenericQueue = queuePtr == (&genericQueue);
bool isReservedQueue{true};
for (auto& reservedQueue : queues) {
if (queuePtr != (&reservedQueue)) {
isReservedQueue = false;
break;
}
}
return isDefaultQueue || isGenericQueue || isReservedQueue;
}
} // namespace device
| true |
d1d9110894ca568603a473564208d8aee9b42c0f | C++ | saturneric/LR1Generator | /src/SyntaxParser.cpp | GB18030 | 6,339 | 2.859375 | 3 | [] | no_license | //
// Created by Administrator on 2021/4/30.
//
#include "SyntaxParser.h"
void SyntaxParser::parse() {
status_stack.push(0);
now_line = 1;
size_t _line_index = 0, max_line_index = lines_index[now_line - 1];
while (!tokens_queue.empty()) {
auto *p_step = atg->findActionStep(status_stack.top(), tokens_queue.front());
if (p_step == nullptr) {
printError();
return;
}
if (p_step->action == MOVE) {
output << "MOVE IN" << "(AUTOMATA STATUS " << status_stack.top() << "): ";
printSymbol(tokens_queue.front());
auto *node = new TreeNode(tokens_queue.front());
auto *p_symbol = pool->getSymbol(tokens_queue.front());
if (p_symbol->terminator) {
node->addInfo(L"terminator");
}
node->addInfo(p_symbol->name);
status_stack.push(p_step->target.index);
analyse_stack.push(tokens_queue.front());
tree_stack.push(node);
if (_line_index > max_line_index) {
string_buffer.str(L"");
string_buffer.clear();
max_line_index = lines_index[now_line++];
}
string_buffer << p_symbol->name << " ";
tokens_queue.pop();
_line_index++;
} else if (p_step->action == REDUCE) {
auto *p_pdt = p_step->target.production;
output << "REDUCE BY" << "(AUTOMATA STATUS " << status_stack.top() << "): [";
printProduction(p_pdt);
output << "]";
std::stack<TreeNode *> temp_stack;
for (int i : p_pdt->right) {
if (i == 0)
continue;
analyse_stack.pop();
status_stack.pop();
temp_stack.push(tree_stack.top());
tree_stack.pop();
}
auto *fatherNode = new TreeNode(p_pdt->left);
fatherNode->addInfo(pool->getSymbol(p_pdt->left)->name);
// std::wcout << fatherNode->getInfoVec()[0] << std::endl;
while (!temp_stack.empty()) {
// std::wcout << temp_stack.top()->getInfoVec()[0] << std::endl;
const auto &childInfo = temp_stack.top()->getInfoVec();
if (childInfo[0] == L"terminator") {
for (int i = 1; i < childInfo.size(); i++) {
fatherNode->addInfo(childInfo[i]);
}
delete temp_stack.top();
} else {
temp_stack.top()->setFather(fatherNode);
}
temp_stack.pop();
}
// std::wcout << std::endl;
auto *p_goto_step =
atg->findGotoStep(status_stack.top(), p_pdt->left);
if (p_goto_step == nullptr) {
printError();
return;
}
analyse_stack.push(p_pdt->left);
tree_stack.push(fatherNode);
status_stack.push(p_goto_step->target.index);
} else if (p_step->action == ACC) {
syntaxTree.setRoot(tree_stack.top());
tree_stack.pop();
output << "ACC";
printDone();
return;
} else {
printError();
return;
}
output << std::endl;
}
}
void SyntaxParser::printProduction(const Production *p_pdt) {
output << pool->getSymbol(p_pdt->left)->name << L" -> ";
int i = 0;
for (const auto &symbol_index : p_pdt->right) {
if (i++ > 0) output << " ";
printSymbol(symbol_index);
}
}
void SyntaxParser::printSymbol(int symbol_index) {
auto *symbol = pool->getSymbol(symbol_index);
if (!symbol->index) {
output << L"[Epsilon]";
return;
}
if (!symbol->terminator)
output << pool->getSymbol(symbol_index)->name;
else
output << L'"' << pool->getSymbol(symbol_index)->name << L'"';
}
void SyntaxParser::getToken() {
// ķļ
std::wstring temp_line;
size_t _line_index = 0;
while (getline(input, temp_line)) {
if (temp_line.size() > 2 && temp_line[0] != '#') {
std::vector<std::wstring> tokens = ws_split(temp_line, L" ");
for (int i = 1; i < tokens.size(); i++) {
if (tokens[i] == L"\r") continue;;
auto token_info = get_token_info(tokens[i]);
tokens_queue.push(pool->getSymbolIndex(token_info.first));
_line_index++;
}
lines_index.push_back(_line_index - 1);
}
}
// ս$
tokens_queue.push(-1);
}
std::vector<std::wstring> SyntaxParser::ws_split(const std::wstring &in, const std::wstring &delim) {
std::wregex re{delim};
return std::vector<std::wstring>{
std::wsregex_token_iterator(in.begin(), in.end(), re, -1),
std::wsregex_token_iterator()
};
}
std::pair<std::wstring, std::wstring> SyntaxParser::get_token_info(const std::wstring &token) {
auto pre_index = token.find(L'(');
auto back_index = token.find(L')');
std::wstring name = token.substr(0, pre_index);
std::wstring value = token.substr(pre_index + 1, back_index - pre_index - 1);
return std::pair<std::wstring, std::wstring>(name, value);
}
void SyntaxParser::printDone() {
output << std::endl;
output << "------------------------------------------------------" << std::endl;
output << "Syntax Parser Work Done, No Error Found." << std::endl << std::endl;
syntaxTree.print(treeOutput);
}
void SyntaxParser::printError(std::wofstream &errOutput) {
std::wstring temp_line = string_buffer.str();
errOutput << std::endl;
errOutput << "------------------------------------------------------" << std::endl;
errOutput.fill('-');
errOutput.width(24);
errOutput << "Syntax Parser Found Error: " << std::endl
<< "At [Line " << now_line << "]: " << temp_line
<< "<- Next Token{" << pool->getSymbol(tokens_queue.front())->name << "}" << std::endl;
errOutput << "AUTOMATA STATUS " << status_stack.top() << std::endl;
}
void SyntaxParser::printError() {
printError(output);
printError(treeOutput);
}
| true |
96cf6be3e34b0bbd10fc88d1d23350f5068d7223 | C++ | chikashimiyama/Interface-Entwicklung_ZHDK_2014 | /Klasse5/sketches/no_interrupt_improved/no_interrupt_improved.ino | UTF-8 | 499 | 2.578125 | 3 | [] | no_license | int switchPin = 2;
int speakerPin = 13;
int switchState = 0;
int interval = 1000;
void setup()
{
pinMode(speakerPin, OUTPUT);
digitalWrite(switchPin , HIGH); // pull up
}
void loop()
{
if(digitalRead(switchPin) == 0){
if(switchState == 0 ){
interval = 1000000 / random(220, 440) / 2;
switchState = 1;
}
}else{
switchState = 0;
}
digitalWrite(speakerPin, 1);
delayMicroseconds(interval);
digitalWrite(speakerPin, 0);
delayMicroseconds(interval);
}
| true |
2323205f05a348f84c0e84217ea7c0e9a80d03fc | C++ | 42yeah/rc | /server/Client.h | UTF-8 | 1,226 | 2.65625 | 3 | [] | no_license | #pragma once
#include <WinSock2.h>
#include <iostream>
#include <vector>
#include <optional>
#define CLIENT_TOKEN_LEN 8
#define ACCESS_CODE "access_code"
class Clients;
class Client {
public:
Client(Clients& clients, sockaddr_in sin);
~Client();
unsigned int get_id() const;
bool authenticate(std::string in_token);
std::string get_token();
bool write_frame(unsigned long frame_id, unsigned int frame_len, unsigned int part_id, const char* data, unsigned int part_length);
sockaddr_in get_sockaddr_in() const;
bool pair(std::string other_token);
private:
unsigned int id;
std::optional<std::reference_wrapper<Client>> paired_with;
std::string token;
sockaddr_in sin;
Clients& clients;
};
class Clients {
public:
Clients(int& server_socket);
~Clients();
std::optional<std::reference_wrapper<Client>> register_client(sockaddr_in sin, std::string access_code);
std::optional<std::reference_wrapper<const Client>> find_client(unsigned int id) const;
std::optional<std::reference_wrapper<Client>> login_client(unsigned int id, std::string token);
const int& get_server_socket() const;
const std::vector<Client>& get_clients();
private:
int& server_socket;
std::vector<Client> clients;
}; | true |
492ec31df2ccf00c116579a1b832bc3ed15d01e3 | C++ | ldt9/ECE0302_ICEs_and_Projects | /Projects/Project5/Project5/Starter Code/state.hpp | UTF-8 | 499 | 2.84375 | 3 | [] | no_license | #ifndef STATE_HPP
#define STATE_HPP
// generic state holding a value of type T
template <typename T>
class State {
public:
State(const T &p, std::size_t cost, std::size_t heur);
T getValue() const;
// copy assignment
State& operator=(const State& rhs);
void updatePathCost(std::size_t cost);
std::size_t getPathCost() const;
std::size_t getFCost() const;
private:
T value;
std::size_t g {0};
std::size_t h {0};
std::size_t f {0};
};
#include "state.tpp"
#endif
| true |
c2bbb63aaa67c820fa52743950352c9a322dc409 | C++ | atrin-hojjat/CompetetiveProgramingCodes | /sorts.cpp | UTF-8 | 5,415 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <random>
#include <time.h>
#include <algorithm>
#include <chrono>
using namespace std;
using namespace chrono;
// #define ARR_SIZE 1e10
const int ARR_SIZE = 2e5;
// const int ARR_SIZE = 10;
void min_max(int i,int j,double*arr,double*min,double*max);
void min_max_pos(int i,int j,double*arr,int*min,int*max);
void min_max_sort(double*arr);
void bubble_sort(double*arr);
void merge_sort(double*arr,int size);
void merge_sort(double*a,double*b,int left,int right);
void min_max(int i,int j,double*arr,double*min,double*max) {
int mid;
double lmin, lmax, rmin, rmax;
if (i == j) {
*min = *(arr+i);
*max = *(arr+j);
} else if (j == i + 1) {
if (*(arr+i)>*(arr+j)) {
*min = *(arr+j);
*max = *(arr+i);
} else {
*min = *(arr+i);
*max = *(arr+j);
}
} else {
mid = (i + j) / 2;
min_max(i, mid,arr, &lmin, &lmax);
min_max(mid + 1, j,arr, &rmin, &rmax);
*min = lmin<rmin ? lmin : rmin;
*max = lmax>rmax ? lmax : rmax;
}
}
void min_max_pos(int i,int j,double*arr,int*min,int*max) {
int mid;
int lmin, lmax, rmin, rmax;
if (i == j) {
*min = i;
*max = j;
} else if (j == i + 1) {
if (*(arr+i)>*(arr+j)) {
*min = j;
*max = i;
} else {
*min = i;
*max = j;
}
} else {
mid = (i + j) / 2;
min_max_pos(i, mid,arr, &lmin, &lmax);
min_max_pos(mid + 1, j,arr, &rmin, &rmax);
*min = *(arr+lmin)<*(arr+rmin) ? lmin : rmin;
*max = *(arr+lmax)>*(arr+rmax) ? lmax : rmax;
}
}
void min_max_sort(double*arr){
int midpt = ARR_SIZE/2 ;
int min,max;
int n = ARR_SIZE-1;
double temp;
for(int i = 0;i<midpt;i++){
min_max_pos(i,n-i,arr,&min,&max);
// if(min!=i){
temp = arr[i];
*(arr+i) = *(arr+min);
*(arr+min) = temp;
// }
// if(max!=n-i){
temp = arr[n-i];
*(arr+n-i) = *(arr+max);
*(arr+max) = temp;
// }
}
}
void bubble_sort(double*arr){
bool done = false;
double temp;
for(int k = 1;k<ARR_SIZE-1;k++){
done = true;
for(int i=0;i<ARR_SIZE-k;i++){
if(arr[i]>arr[i+1]){
temp = arr[i+1];
*(arr+i+1) = *(arr+i);
*(arr+i) = temp;
done = false;
}
}
if (done)break;
}
}
void merge_sort(double*arr,int size){
double*b = new double[size];
merge_sort(b,arr,0,size);
}
void merge_sort(double*a,double*b,int left,int right){
if(left+1==right)
return;
int mid = (left+right)/2;
merge_sort(b,a,left,mid);
merge_sort(b,a,mid,right);
for (int i=left,j=mid,pos=left; pos < right; ++pos)
{
if(j>=right || (i<mid && a[i]<a[j]))
b[pos]=a[i++];
else
b[pos]=a[j++];
}
}
int main(){
double*arr = new double[ARR_SIZE];
high_resolution_clock::time_point t1,t2;
t1 = high_resolution_clock::now();
{
const long double stddev =100;
random_device rd;
mt19937 e2(rd());
normal_distribution<double> dist(0,stddev);
double r;
for(int i = 0; i<ARR_SIZE;i++){
r = dist(e2);
*(arr+i) = r;
}
// double temp;
// for(int i=0;i<ARR_SIZE;i++){
// cin >> temp;
// arr[i] = temp;
// }
// cout << endl;
}
t2 = high_resolution_clock::now();
auto generation_duration = duration_cast<milliseconds>( t2 - t1 ).count();
cout << "Generatoin Duration : "<< generation_duration << endl;
cout << endl << endl;
// t1 = high_resolution_clock::now();
// {
// double min_max_arr[ARR_SIZE];
// for(int i=0;i<ARR_SIZE;i++){
// min_max_arr[i] = *(arr+i);
// }
// min_max_sort(&min_max_arr[0]);
// cout << endl << endl;
// }
// t2 = high_resolution_clock::now();
// auto min_max_sort_duration = duration_cast<milliseconds>( t2 - t1 ).count();
// cout << "Min-Max Sort Duration : "<< min_max_sort_duration << endl;
// cout << endl << endl;
// t1 = high_resolution_clock::now();
// {
// double bubble_arr[ARR_SIZE];
// for(int i=0;i<ARR_SIZE;i++){
// bubble_arr[i] = *(arr+i);
// }
// cout << endl;
// bubble_sort(&bubble_arr[0]);
// cout << endl << endl;
// }
// t2 = high_resolution_clock::now();
// auto bubble_sort_duration = duration_cast<milliseconds>( t2 - t1 ).count();
// cout << "Bubble Sort Duration : "<< bubble_sort_duration << endl;
// cout << endl << endl;
t1 = high_resolution_clock::now();
{
double merge_arr[ARR_SIZE];
for(int i=0;i<ARR_SIZE;i++){
merge_arr[i] = *(arr+i);
}
cout << endl;
merge_sort(&merge_arr[0],ARR_SIZE);
cout << endl << endl;
}
t2 = high_resolution_clock::now();
auto merge_sort_duration = duration_cast<milliseconds>( t2 - t1 ).count();
cout << "Merge Sort Duration : "<< merge_sort_duration << endl;
cout << endl << endl;
return 0;
} | true |
da38440f142bc233cb1a7c30ff8539921eab7210 | C++ | dittoo8/algorithm_cpp | /BOJ/14442.cpp | UTF-8 | 1,126 | 2.640625 | 3 | [] | no_license | #include <cstdio>
#include <queue>
using namespace std;
struct map {
int x, y, w;
};
int n,m,k, dist[1001][1001][11]; // dist (x좌표, y좌표, 벽 부순 횟수);
char a[1001][1001];
const int dx[] = {-1,0,1,0}, dy[]={0,1,0,-1};
int bfs(){
queue<map> q;
q.push({0,0,0});
dist[0][0][0]= 1;
while(!q.empty()){
int x = q.front().x, y=q.front().y;
int w = q.front().w; q.pop();
if (x == n-1 && y == m-1){
return dist[x][y][w];
}
for(int i=0;i<4;i++){
int nx = x+dx[i], ny=y+dy[i],nw = w+1;
if (nx <0 || nx >= n || ny<0 || ny>= m) continue;
if (dist[nx][ny][w]) continue;
if (a[nx][ny]=='0'){
dist[nx][ny][w] = dist[x][y][w]+1;
q.push({nx,ny,w});
}else if (a[nx][ny]=='1' && nw <=k){
dist[nx][ny][nw]= dist[x][y][w]+1;
q.push({nx,ny,nw});
}
}
}
return -1;
}
int main(){
scanf("%d %d %d", &n, &m, &k);
for(int i=0;i<n;i++){
scanf("%s", a[i]);
}
printf("%d\n",bfs());
return 0;
} | true |
7c4f98eefef0ee3b98f4165775c0409d9d64b1e7 | C++ | bashell/leetcode | /70_ClimbingStairs.cpp | UTF-8 | 461 | 3.40625 | 3 | [] | no_license | class Solution {
public:
// 设爬n层梯子有f(n)种方法,则f(n) = f(n-1) + f(n-2).
// Note: f(n-1)再爬1 step即可,f(n-2)再爬2 steps即可.
// Fibonacci: f(1) = f(2) = 1
int climbStairs(int n) {
if(n <= 2) // i = 0, 1
return n;
int a = 1, b = 1, c;
for(int i = 2; i <= n; ++i) { // i = 2, 3, ..., n
c = a + b;
a = b;
b = c;
}
return c;
}
};
| true |
1a65c0d6b80a687793b981a760438d7b1f38a8b6 | C++ | root-jeong/BOJ | /~9999/2718_타일 채우기.cpp | UTF-8 | 2,083 | 2.5625 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
int dp[501][16];
int N;
int fun(int n, int nowState) {
if (n == 0) {
return 1;
}
if (dp[n][nowState] != -1) return dp[n][nowState];
int ret = 0;
if (nowState == 0) {
ret += fun(n-1, 0);
ret += fun(n-1, 5);
ret += fun(n-1, 8);
ret += fun(n-1, 10);
ret += fun(n-1, 15);
}else if (nowState == 1) {
ret += fun(n-1, 14);
ret += fun(n-1, 4);
ret += fun(n-1, 2);
}
else if (nowState == 2) {
ret += fun(n-1, 1);
ret += fun(n-1, 13);
}
else if (nowState == 3) {
ret += fun(n-1, 4);
ret += fun(n-1, 12);
}
else if (nowState == 4) {
ret += fun(n-1, 5);
ret += fun(n-1, 8);
ret += fun(n-1, 11);
}
else if (nowState == 5) {
ret += fun(n-1, 0);
ret += fun(n-1, 10);
}
else if (nowState == 6) {
ret += fun(n-1, 9);
}
else if (nowState == 7) {
ret += fun(n-1, 0);
ret += fun(n-1, 8);
}
else if (nowState == 8) {
ret += fun(n-1, 7);
}
else if (nowState == 9) {
ret += fun(n-1, 6);
}
else if (nowState == 10) {
ret += fun(n-1, 0);
ret += fun(n-1, 5);
}
else if (nowState == 11) {
ret += fun(n-1, 4);
}
else if (nowState == 12) {
ret += fun(n-1, 3);
}
else if (nowState == 13) {
ret += fun(n-1, 2);
}
else if (nowState == 14) {
ret += fun(n-1, 1);
}
else if (nowState == 15) {
ret += fun(n-1, 0);
}
dp[n][nowState] = ret;
//cout << n << " , " << nowState << " : " << ret << endl;
return dp[n][nowState];
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
memset(dp, -1, sizeof(dp));
int t; cin >> t;
while (t--) {
cin >> N;
cout << fun(N, 0) << endl;
}
return 0;
} | true |
69177e44afd2a59a856f0e588be165b669f02382 | C++ | walkccc/LeetCode | /solutions/0410. Split Array Largest Sum/0410-3.cpp | UTF-8 | 675 | 3.234375 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int splitArray(vector<int>& nums, int m) {
int l = *max_element(nums.begin(), nums.end());
int r = accumulate(nums.begin(), nums.end(), 0) + 1;
while (l < r) {
const int mid = (l + r) / 2;
if (numGroups(nums, mid) > m)
l = mid + 1;
else
r = mid;
}
return l;
}
private:
int numGroups(const vector<int>& nums, int maxSumInGroup) {
int groupCount = 1;
int sumInGroup = 0;
for (const int num : nums)
if (sumInGroup + num <= maxSumInGroup) {
sumInGroup += num;
} else {
++groupCount;
sumInGroup = num;
}
return groupCount;
}
};
| true |
1f10f8bd39cd86ff7d34c631836dee610526d686 | C++ | pppoe/robot-photographer | /src/rp_locomotion/include/locomotion.hpp | UTF-8 | 4,255 | 2.765625 | 3 | [] | no_license | /**
* @class RPLocomotionNode
*
* @brief Robot photographer's locomotion node, which converts driving direction messages
* and bumper press events into linear/angular velocity messages.
*
* @copyright Manfredas Zabarauskas, 2013. All rights reserved. This project is released under
* CC BY-NC-SA (Creative Commons Attribution-NonCommercial-ShareAlike) license.
*/
#ifndef LOCOMOTION_HPP_
#define LOCOMOTION_HPP_
// ROS includes
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <std_msgs/UInt16.h>
// Boost includes
#include <boost/thread/mutex.hpp>
// Kobuki includes
#include <kobuki_msgs/BumperEvent.h>
// RPNavigation includes
#include <direction_source.h>
// Constants
#define FRAMING_LINEAR_VELOCITY_DEFAULT 0.1
#define FRAMING_ANGULAR_VELOCITY_DEFAULT 0.33
#define OBSTACLE_AVOIDANCE_LINEAR_VELOCITY_DEFAULT 0.15
#define OBSTACLE_AVOIDANCE_ANGULAR_VELOCITY_DEFAULT 0.5
class RPLocomotionNode
{
private:
ros::NodeHandle& node; /**< Node's handle. */
geometry_msgs::TwistPtr locomotion_message; /**< Pointer to locomotion message. */
boost::mutex locomotion_message_mutex; /**< Locomotion message's mutex. */
ros::Publisher locomotion_publisher; /**< Locomotion publisher. */
ros::Publisher state_publisher; /**< Locomotion state publisher. */
ros::Publisher motor_power_publisher; /**< Motor power publisher. */
ros::Subscriber navigation_subscriber; /**< Navigation input subscriber. */
ros::Subscriber bumper_subscriber; /**< Bumper events subscriber. */
ros::Subscriber cnc_subscriber; /**< C&C input subscriber which determines
the source of driving direction. */
ros::WallTimer bumper_timer; /**< Timer for a turn-around motion when
the bumper event is triggered. */
volatile bool processing_bumper_event; /**< Bumper event flag. */
double FRAMING_LINEAR_VELOCITY; /**< Framing linear velocity OP. */
double FRAMING_ANGULAR_VELOCITY; /**< Framing angular velocity OP. */
double OBSTACLE_AVOIDANCE_LINEAR_VELOCITY; /**< Obstacle avoidance linear velocity OP. */
double OBSTACLE_AVOIDANCE_ANGULAR_VELOCITY; /**< Obstacle avoidance angular velocity OP.*/
/**
* Resets the locomotion message to stop the robot.
* @param frame_message Input framing status message.
*/
void clearLocomotionMessage();
/**
* Sets the motor enabled state.
* @param enabled Desired motors state (enabled/disabled).
*/
void motorsEnabled(bool enabled);
/**
* Sets/clears the "processing bumper event" flag.
* @param processing Desired "processing bumper event" flag.
*/
void setProcessingBumperEvent(bool processing);
/**
* Callback for the received navigation message.
* @param direction_and_source_code Driving direction and direction source message.
*/
void navigationMessageCallback(const std_msgs::UInt16& direction_and_source_code);
/**
* Callback for the received bumper event.
* @param timer_event Pointer to the bumper event object.
*/
void bumperEventCallback(const kobuki_msgs::BumperEventConstPtr bumper_event);
/**
* Callback for the bumper timer event.
* @param timer_event Timer callback object.
*/
void bumperTimerCallback(const ros::WallTimerEvent& timer_event);
/**
* Gets the overridable parameters from the parameter server.
*/
void getOverridableParameters();
public:
/**
* Default locomotion node's constructor.
* @param node Handle to ROS node.
*/
RPLocomotionNode(ros::NodeHandle& node);
};
#endif /* LOCOMOTION_HPP_ */
| true |
cc0362cd4cffef64c227755a89730ebd8ebae0fa | C++ | meiring13/Project2_CS2413 | /project2.cpp | UTF-8 | 9,586 | 3.484375 | 3 | [] | no_license | /*
* project2.cpp
*
* Created on: Feb 18, 2020
* Author: Ike Meiring
*/
#include <iostream>
using namespace std;
//exceptions go here
double round(double var)
{
double value = (int)(var * 100.0);
return (double)value / 100.0;
}
template <class DT>
class Point; //class prototype
template <class DT>
ostream& operator <<(ostream& s, Point<DT>& otherOne);
template <class DT>
class Point {
friend ostream& operator << <DT> (ostream& s, Point<DT>& otherOne);
public:
DT x;
DT y;
Point();
Point(DT xvalue, DT yvalue);
void setLocation(DT xvalue, DT yvalue);
void display();
virtual ~Point();
double getXValue() {
return x;
}
double getYValue() {
return y;
}
//function prototype
};
template <class DT>
Point<DT>::Point()
{
x = 0.0;
y = 0.0;
}
template <class DT>
Point<DT>::Point(DT xvalue, DT yvalue)
{
x = xvalue; //this constructor will be called when creating new points
y = yvalue;
}
template <class DT>
void Point<DT>::setLocation(DT xvalue, DT yvalue)
{
x = xvalue;
y = yvalue;
}
template <class DT>
void Point<DT>::display()
{
cout << "(" << round(x) << ", " << round(y) << ")" << endl;
}
template <class DT>
ostream& operator << (ostream& s, Point<DT>& otherOne)
{
s << "(" << (otherOne.x) << ", " << (otherOne.y) << ")";
return s;
}
template <class DT>
Point <DT>:: ~Point()
{
//TODO
}
template <class DT>
class LineSegment;
template <class DT>
ostream& operator <<(ostream& s, LineSegment<DT>& one);
template <class DT>
class LineSegment {
public:
Point<DT> PointOne;
Point<DT> PointTwo;
LineSegment();
LineSegment(Point<DT> PointOne, Point<DT> PointTwo);
double lengthOfLine();
Point<DT> midpoint();
Point<DT> xIntercept();
Point<DT> yIntercept();
double slope();
double squareroot(double a);
bool itIntersects(LineSegment<DT> L);
Point<DT> intersectionPoint(LineSegment<DT> L);
bool isParallel(LineSegment<DT> L);
void displayEquation();
void displayLineSegment(); //optional added
};
template<class DT>
LineSegment<DT>::LineSegment()
{
PointOne.setLocation(0.0, 0.0);
PointTwo.setLocation(0.0, 0.0);
}
template<class DT>
LineSegment<DT>::LineSegment(Point<DT> one, Point<DT> two)
{
PointOne = one;
PointTwo = two;
}
template<class DT>
ostream& operator <<(ostream& s, LineSegment<DT>& one)
{
//rounding on the display instead of during calculation will produce less errors
s << "(" << round(one.PointOne.x) << ", " << round(one.PointOne.y) << "),"
<< "(" << round(one.PointTwo.x) << ", " << round(one.PointTwo.y) << ")";
return s;
}
template<class DT>
double LineSegment<DT>::slope()
{
double slope;
double x1 = PointOne.x;
double y1 = PointOne.y;
double x2 = PointTwo.x;
double y2 = PointTwo.y;
slope = ((y2 - y1) / (x2 - x1));
return slope;
}
template <class DT>
double LineSegment<DT>::squareroot(double a)
{
//given square root function, modified by passing in a variable and setting k = a so i
//could calculate a specific spot in the segments array
double eps = 1e-6;
double k = a;
double l = 0.0, r, mid;
if (k>=1) {
r = k;
}
if (k<1) {
r = 1;
}
while (l-k/l > eps || l-k/l < -eps)
{
mid = l + (r - l) /2 ;
if (mid<k/mid)
{
l = mid;
}
else {
r = mid;
}
}
return l;
}
template<class DT>
bool LineSegment<DT>::itIntersects(LineSegment<DT> L)
{
// Points P and Q
Point<DT> one(this->PointOne);
Point<DT> two(this->PointTwo);
Point<DT> thisOne(L.PointOne);
Point<DT> thisTwo(L.PointTwo);
//cross product obtained from reference sheet
double x1 = one.getXValue();
double x2 = two.getXValue();
double x3 = thisOne.getXValue();
double x4 = thisTwo.getXValue();
double y1 = one.getYValue();
double y2 = two.getYValue();
double y3 = thisOne.getYValue();
double y4 = thisTwo.getYValue();
//cross product applied here
double d1 = ((x2 - x1)*(y3 - y1)) - ((x3 - x1)*(y2 - y1));
double d2 = ((x2 - x1)*(y4 - y1)) - ((x4 - x1)*(y2 - y1));
double d3 = ((x4 - x3)*(y1 - y3)) - ((x1 - x3)*(y4 - y3));
double d4 = ((x4 - x3)*(y2 - y1)) - ((x2 - x1)*(y4 - y3));
//checking if lines intersect
if((d1*d2) <= 0 && (d3*d4) <= 0)
{
return true;
}
return false;
}
template <class DT>
bool LineSegment<DT>::isParallel(LineSegment<DT> L)
{
return (L.slope() == this->slope());
}
template <class DT>
Point<DT> LineSegment<DT>::intersectionPoint(LineSegment<DT> L)
{
double c1 = L.yIntercept().getYValue();
double c2 = this->yIntercept().getYValue(); //this represents the other yint being calculated
double m1 = L.slope();
double m2 = this->slope();
double xintersect = (c2 - c1)/(m1-m2); //got equations from reference sheet
double yintersect = ((c1*m2) - (c2*m1))/(m2-m1);
Point<DT> intersectionPoint(xintersect, yintersect);
return intersectionPoint;
}
template <class DT>
double LineSegment<DT>::lengthOfLine()
{
double length;
double x1 = PointOne.x;
double y1 = PointOne.y;
double x2 = PointTwo.x;
double y2 = PointTwo.y;
length = (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2);
length = squareroot(length);
return length;
}
template <class DT>
Point<DT> LineSegment<DT>::midpoint()
{
double xm = (PointOne.x + PointTwo.x)/2;
double ym = (PointOne.x + PointTwo.y)/2; //from reference sheet
Point<DT> midPoint(xm, ym);
return midPoint;
}
template <class DT>
Point<DT>LineSegment<DT>::xIntercept()
{
double x;
double x1 = PointOne.x;
double y1 = PointOne.y;
double x2 = PointOne.x;
double y2 = PointTwo.y;
x = x1 - y1*(x2-x1)/(y2-y1);
Point<DT> xint(x, 0); // y = 0 because thats how x-int is found
return xint;
}
template<class DT>
Point<DT> LineSegment<DT>::yIntercept()
{
double c;
double y1 = PointOne.y;
double x1 = PointOne.x;
double y2 = PointTwo.y;
double x2 = PointTwo.x;
c = y1 - ((y2 - y1)/(x2 - x1))*x1;
Point<DT> yint(0, c); //setting x = 0 because thats how the y-int is found
return yint;
}
template <class DT>
class Segments;
template <class DT>
ostream& operator >> (ostream& s, Segments<DT>& one);
template <class DT>
class Segments {
public:
//changed these variables from protected to public so i can access them
LineSegment<DT>* segments;
int count;
int maxSize;
Segments ();
Segments (int size);
void addLineSegment(LineSegment<DT> L);
void display();
};
template <class DT>
Segments<DT>::Segments()
{
segments = new LineSegment<DT>[0];
count = 0;
maxSize = 0;
}
template <class DT>
Segments<DT>::Segments(int size)
{
segments = new LineSegment<DT>[size];
count = 0;
maxSize = 0;
}
template <class DT>
void Segments<DT>::addLineSegment(LineSegment<DT> L)
{
segments[count] = L;
++count; //increment count to store lineSegments properly
}
//TODO make a method for creating all points
//TODO ostream operators
int main()
{
int numOfSegments;
double x1, y1, x2, y2;
char command;
Segments<double>*interval = new Segments<double>(numOfSegments);
cin >> numOfSegments;
while (!cin.eof())
{
cin >> command;
switch (command)
{
case 'A':{}
for (int i = 0; i < numOfSegments; i++)
{
cin >> x1 >> y1 >> x2 >> y2;
Point<double> pointOne(x1, y1);
Point<double> pointTwo(x2, y2);
LineSegment<double> segment(pointOne, pointTwo);
interval->segments[i] = segment;
cout << interval->segments[i];
}
break;
case 'R':{
break;
}
case 'D':{
break;
}
case 'P':{
break;
}
case 'I':{
break;
}
case 'C':{
break;
}
default : cout << "Invalid command";
}
}
}
// rounded on the ouputs to have every calculation go through the rounding function
/*
for (int i = 0; i < numOfSegments; i++)
{
// all rounding done here on output to avoid autograder error
cout << "Line Segment " << (i + 1) << ":"; // << endl; //colon number needs to be 1 ahead of the increment
interval->addLineSegment(interval->segments[i]);
cout << interval->segments[i];
cout << "Slope:" << round(interval->segments[i].slope()); //<< endl;
Point<double> midpoint(interval->segments[i].midpoint());
cout << "Midpoint:";
cout << "X Intercept:";
Point<double> Xint(interval->segments[i].xIntercept());
Xint.display();// << endl;
cout << "Y Intercept:";
Point<double> Yint(interval->segments[i].yIntercept());
Yint.display(); // << endl;
cout << "Length:";
cout << round(interval->segments[i].lengthOfLine()); // << endl;
cout << "y=" << round(interval->segments[i].slope()) << "*x+";
Yint.display();//<< endl;
}
for (int i = 0; i < numOfSegments - 1; i++) //always want the outer loop one behind the inner loop
{
for (int j = i + 1; j < numOfSegments; j++) //want to start the inner loop 1 ahead
{
if (interval->segments[i].itIntersects(interval->segments[j]))
{
cout << "The line segments compared are segments[" << i << "] and segments[" << j << "]: ";
cout << "Intersection Point :";
interval->segments[i].intersectionPoint(interval->segments[j]).display();
}
else if (interval->segments[i].isParallel(interval->segments[j]))
{
cout << "The line segments compared are segments[" << i << "] and segments"
"[" << j << "]: Lines are Parallel";
}
else
{
cout << "The line segments compared are segments[" << i << "] and segments"
"[" << j << "]: Not Parallel and not Intersecting";
}
}
}
}
int main() {
Point<double>* point = new Point<double>(1.2, 1.2);
Point<double>* pointTwo = new Point<double>(1.0, 1.0);
cout << *point;
LineSegment<double>* segment = new LineSegment<double>(*point, *pointTwo);
cout << *segment;
}
*/
| true |
8da6651c12a4dc75fee7a0a8a980f901f88cf70e | C++ | 1337hunter/cpp_modules | /module07/ex02/main.cpp | UTF-8 | 2,108 | 3.0625 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gbright <gbright@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/26 23:21:32 by gbright #+# #+# */
/* Updated: 2020/09/28 22:02:13 by gbright ### ########.fr */
/* */
/* ************************************************************************** */
#include "Array.h"
int main(void)
{
Array<char> arr(10);
Array<int> iarr(10);
Array<double> empty;
std::cout << "empty.size(): " << empty.size() << '\n';
try
{
empty[0] = 0;
}
catch (std::exception &e)
{
std::cout << "empty error\n";
}
std::cout << "arr.size(): " << arr.size() << '\n';
std::cout << "arr[2]: " << static_cast<int>(arr[2]) << '\n';
arr[2] = 'A';
iarr[0] = 100500;
iarr[1] = 1;
std::cout << "arr[2]: " << arr[2] << '\n';
try
{
arr[20] = 'a';
}
catch (std::exception &e)
{
std::cout << e.what() << '\n';
}
std::cout << iarr[0] << '\n';
std::cout << iarr[1] << '\n';
std::cout << iarr[2] << iarr[3] << iarr[4] << iarr[5] << " << default values" <<'\n';
try
{
iarr[21] = 21;
}
catch (std::exception &e)
{
std::cout << e.what() << '\n';
}
try
{
iarr[1] = 1;
std::cout << "Done!\n";
}
catch (std::exception &e)
{
std::cout << e.what() << '\n';
}
std::cout << "--------------copy constractor and operator= test-----------\n";
Array<char> copy(arr);
std::cout << "copy[2]: " << copy[2] << '\n';
arr[1] = 'Z';
arr[2] = 'Z';
arr[3] = 'Z';
copy = arr;
std::cout << copy[1] << copy[2] << copy[3] << std::endl;
}
| true |
e9b6d431ae590da89480fdd5e7a823fa4c61b19f | C++ | Andreskammerath/Competitive_Programming | /Spoj/l_digit.cpp | UTF-8 | 706 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int last_dig(int num)
{
return (num % 10);
}
int pot1(int a, int b)
{
if(b == 0) return 1;
if(a == 0) return 0;
int res = 1;
int b1 = b;
while(b1 > 0)
{
if(b1 % 2 == 1){
res *= a;
b1 -= 1;
}
a *= a;
a =
res = last_dig(res);
b1 /= 2;
cout << res << " "<< b1 << endl;
if(res == 0) break;
}
return res;
}
int main()
{
int t; //number of testcases
vector<int> a; // base
vector<int> b; // index
int aux1,aux2;
cin >> t;
for (int i = 0; i < t; ++i)
{
cin >> aux1 >> aux2;
a.push_back(aux1);
b.push_back(aux2);
}
for (int i = 0; i < t; ++i)
{
cout << pot1(last_dig(a[i]),b[i]) << endl;
}
} | true |
ab4b5911807a27547c81a2a1d941b83d20c12f07 | C++ | scgyong/cpp2018 | /cp_bricks/cp_bricks/GameScene.cpp | UTF-8 | 1,158 | 2.84375 | 3 | [
"MIT"
] | permissive | //#include <SFML/Graphics.hpp>
#include "GameScene.h"
#include "main.h"
#define PADDLE_Y_OFFSET 50.0
using namespace sf;
GameScene::GameScene(RenderWindow &window) :
Scene(window),
ball(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2),
paddle(WINDOW_WIDTH / 2, WINDOW_HEIGHT - PADDLE_Y_OFFSET)
{
for (int y = 0; y < 5; y++) {
for (int x = 0; x < 10; x++) {
Brick brick(
(float)(x * (60 + 3) + 20),
(float)(y * (20 + 3) + 40)
);
bricks.push_back(brick);
}
}
}
GameScene::~GameScene()
{
}
void GameScene::update()
{
Vector2i mousePos = Mouse::getPosition(window);
float x = mousePos.x;
if (x < 0) {
x = 0;
} else if (x > WINDOW_WIDTH - PADDLE_WIDTH ) {
x = WINDOW_WIDTH - PADDLE_WIDTH;
}
paddle.update(x);
ball.update();
if (ball.collides(paddle)) {
ball.bounceUp();
}
for (auto it = bricks.begin(); it != bricks.end(); it++) {
if (ball.collides(*it)) {
ball.bounceY();
bricks.erase(it);
break;
}
}
}
void GameScene::draw()
{
window.clear(Color::Blue);
window.draw(ball);
for (auto &b : bricks) {
window.draw(b);
}
window.draw(paddle);
}
| true |
b6e7125492eafd72c2595e0e5c2e6b9b2e350c53 | C++ | Omlala97/ChamberCrawler3000 | /character.h | UTF-8 | 875 | 3.125 | 3 | [] | no_license | #ifndef CHARACTER_H
#define CHARACTER_H
#include <iostream>
#include <vector>
using namespace std;
class Character {
protected:
vector<int> charPos;
int cur_HP;
int max_HP;
int cur_atk;
int max_atk;
int cur_def;
int max_def;
string Name;
char symbol; // for single alphabet
public:
Character(string Name, int HP, int atk, int def, char symbol);
virtual ~Character();
int getHP();
int getAtk();
int getDef();
int getMaxHP();
int changeHP(int change); // change character HP when being attacked.
void resetAtk(); // get into another floor
void resetDef();
string getName();
char getSymbol();
void setCharPos(vector<int> charPos);
vector<int> getCharPos();
};
#endif
| true |
079372b496e4e88c5d0584996dbb7c4ea2022292 | C++ | ChillMagic/PrivateLibrary | /include/memory.h | UTF-8 | 3,617 | 2.953125 | 3 | [
"MIT"
] | permissive | // memory.h
// * PrivateLibrary
#pragma once
#ifndef _PRILIB_MEMORY_H_
#define _PRILIB_MEMORY_H_
#include "macro.h"
#include <utility>
#include <cstdint>
#include <cstdlib>
#include <cstring>
PRILIB_BEGIN
#if _ITERATOR_DEBUG_LEVEL != 0
PRILIB_END
#include <iterator>
PRILIB_BEGIN
template <typename T>
class pointer_iterator : public std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, T*, T&>
{
public:
using _Unchecked_type = std::iterator<std::random_access_iterator_tag, T, ptrdiff_t, T*, T&>;
explicit pointer_iterator(T* p) : p(p) {}
bool operator!=(const pointer_iterator& i) const {
return p != i.p;
}
bool operator<(const pointer_iterator& i) const {
return p < i.p;
}
T& operator*() const {
return *p;
}
const pointer_iterator& operator++() {
++p;
return *this;
}
ptrdiff_t operator+(const pointer_iterator &i) const {
return p + i.p;
}
ptrdiff_t operator-(const pointer_iterator &i) const {
return p - i.p;
}
pointer_iterator operator+(ptrdiff_t i) const {
return pointer_iterator(p + i);
}
pointer_iterator operator-(ptrdiff_t i) const {
return pointer_iterator(p - i);
}
T* p;
};
template <typename T>
inline pointer_iterator<T> _PointerIterator(T* p) {
return pointer_iterator<T>(p);
}
#else
template <typename T>
inline T* _PointerIterator(T* p) {
return p;
}
#endif
using byte = uint8_t;
using word = uint16_t;
using dword = uint32_t;
using qword = uint64_t;
namespace Memory
{
template <typename T>
inline constexpr size_t get_size(size_t length) {
return length * sizeof(T);
}
template <>
inline constexpr size_t get_size<void>(size_t length) {
return length;
}
// Alloc/Free
template <typename T = byte>
inline T* alloc(size_t length) {
return (T*)std::malloc(length * sizeof(T));
}
template <typename T = byte>
inline T* calloc(size_t length) {
return (T*)std::calloc(length * sizeof(T), 1);
}
template <typename T = void>
inline void free(T *p) {
std::free(p);
}
// New/Delete
template <typename T>
inline T* new_(size_t length) {
return new T[length]();
}
template <typename T>
inline void new_n(T *data, size_t length) {
for (size_t i = 0; i < length; i++) {
new (data + i) T();
}
}
template <typename T>
inline void delete_(T *p) {
delete[] p;
}
template <typename T>
inline void delete_n(T *p, size_t n) {
for (size_t i = 0; i < n; i++) {
p[i]. ~T();
}
free(p);
}
template <typename T>
inline void copy_n(T *data, T *begin, size_t length) {
for (size_t i = 0; i < length; i++) {
new (data + i) T(*(begin + i));
}
}
template <typename T, typename Iter>
inline void copy_n(T *data, Iter begin, size_t length) {
for (size_t i = 0; i < length; i++) {
new (data + i) T(*(begin + i));
}
}
// Construct/Destruct
template <typename T>
inline void construct(T *data) {
new (data) T();
}
template <typename T>
inline void destruct(T *data) {
data->~T();
}
// MCopy/NCopy
inline void* mcopy(void* to, const void* from, size_t length) {
return std::memcpy(to, from, length);
}
template <typename T>
inline T& ncopy(T& to, const T& from) {
return to = from;
}
template <typename T>
inline T* clear(T* dat, size_t length) {
std::memset((void*)dat, 0, get_size<T>(length));
return dat;
}
template <typename T>
inline T* copyTo(T* to, const T* from, size_t length) {
return (T*)std::memcpy((void*)to, (void*)from, get_size<T>(length));
}
template <typename T>
inline T* copyOf(const T* from, size_t length) {
if (from == nullptr)
return nullptr;
else
return copyTo(new_<T>(length), from, length);
}
}
PRILIB_END
#endif
| true |
610bfeefd70def514e3dfcd169d4701973c71ff1 | C++ | f4goh/WSPR | /src/ds18s20_read/ds18s20_read.ino | UTF-8 | 2,113 | 2.75 | 3 | [] | no_license | /* read ds18s20 sensor
Anthony LE CREN F4GOH@orange.fr
Created 26/7/2020
send dds outpout to zero to prevent conduction in the bs170
*/
#include <SPI.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define SENSOR 7 //ds18s20 sensor
#define LED 8
#define W_CLK 13
#define FQ_UD 10
#define RESET 9 // or 10
long factor = -1500; //adjust frequency
OneWire ds(SENSOR); // on pin 7 (a 3.3k or 4.7K resistor is necessary)
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&ds);
/*
* The setup function. We only start the sensors here
*/
void setup(void)
{
// start serial port
Serial.begin(115200);
Serial.println("Dallas Temperature IC Control Library");
// Start up the library
sensors.begin();
initDds();
setfreq(0, 0);
setfreq(0, 0);
}
/*
* Main function, get and show the temperature
*/
void loop(void)
{
// call sensors.requestTemperatures() to issue a global temperature
// request to all devices on the bus
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures
Serial.println("DONE");
// After we got the temperatures, we can print them here.
// We use the function ByIndex, and as an example get the temperature from the first sensor only.
Serial.print("Temperature for the device 1 (index 0) is: ");
Serial.println(sensors.getTempCByIndex(0));
}
/********************************************************
AD9850 routines
********************************************************/
void initDds()
{
SPI.begin();
pinMode(W_CLK, OUTPUT);
pinMode(FQ_UD, OUTPUT);
pinMode(RESET, OUTPUT);
SPI.setBitOrder(LSBFIRST);
SPI.setDataMode(SPI_MODE0);
pulse(RESET);
pulse(W_CLK);
pulse(FQ_UD);
}
void pulse(int pin) {
digitalWrite(pin, HIGH);
// delay(1);
digitalWrite(pin, LOW);
}
void setfreq(double f, uint16_t p) {
uint32_t deltaphase;
deltaphase = f * 4294967296.0 / (125000000 + factor);
for (int i = 0; i < 4; i++, deltaphase >>= 8) {
SPI.transfer(deltaphase & 0xFF);
}
SPI.transfer((p << 3) & 0xFF) ;
pulse(FQ_UD);
}
| true |
aacbe5309e3e7ab8f8a52a77e924e39ecf21a403 | C++ | zhichao281/study_test | /QWhiteBoard/HCanvas/DrawWidget.cpp | GB18030 | 7,184 | 2.5625 | 3 | [] | no_license | #include "DrawWidget.h"
#include <QPainter>
CDrawWidget::CDrawWidget(QWidget *parent)
: QWidget(parent)
{
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
this->setAttribute(Qt::WA_TranslucentBackground, true);
setWindowOpacity(1);
this->setMouseTracking(true);
_Init();
}
CDrawWidget::~CDrawWidget()
{
}
/**
* @brief ʼ
*/
void CDrawWidget::_Init()
{
m_nEraseSize = 5;
m_nPenSize = 2;
m_bFlagDrawing = false;
m_bFlagClear = false;
m_nPenId = 0;
_InitUI();
}
/**
* @brief ʼUI
*/
void CDrawWidget::_InitUI()
{
}
/**
* @brief ¼
*/
void CDrawWidget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.setPen(Qt::NoPen);
painter.setBrush(Qt::white);
QRect rt = rect();
//painter.drawRect(rt);
QImage image = _PaintDrawItem(rt.size(), true);
painter.drawImage(rt, image);
QWidget::paintEvent(event);
return;
}
/**
* @brief ƵͼƬ
* @param size С
* @param bDrawing Ƿڻ
* @return
*/
QImage CDrawWidget::_PaintDrawItem(QSize size, bool bDrawing)
{
QImage image(size, QImage::Format_ARGB32);
image.fill(qRgba(0, 0xFF, 0xFF, 0));
//ƾ
QPainter painter(&image);
for (int i = 0; i < m_queDrawItem.size(); ++i)
{
DRAW_ITEM item = m_queDrawItem[i];
if (item.penData.nPenType == DT_ERASE)
_DrawEraseItem(image, item);
else
_DrawItem(painter, item);
}
//
if (bDrawing)
{
if (m_drawItem.penData.nPenState == PS_WRITE)
{
if (m_drawItem.penData.nPenType == DT_ERASE)
_DrawEraseItem(image, m_drawItem);
else
_DrawItem(painter, m_drawItem);
}
}
return image;
//ͼƬ:ͼƬ+ƹ켣
QImage retImage(size, QImage::Format_ARGB32);
retImage.fill(Qt::white);
//ƹ켣
QPainter retPainter(&retImage);
retPainter.drawImage(0, 0, image);
return retImage;
}
/**
* @brief
* @param item
*/
void CDrawWidget::_SaveItem(const DRAW_ITEM &item)
{
if (item.penData.nPenType == DT_ERASE &&
m_queDrawItem.isEmpty())
{
return;
}
m_queDrawItem.push_back(item);
m_queRedoItem.clear();
m_bFlagClear = false;
}
/**
* @brief
* @param painter
* @param item
*/
void CDrawWidget::_DrawItem(QPainter &painter, const DRAW_ITEM &item)
{
QPen pen(item.penData.color, item.penData.nSize);
Qt::PenCapStyle PenCapstyle = Qt::RoundCap; //ߵĶ˵ʽ
if (item.penData.nSize == 2 || item.penData.nSize == 6)
PenCapstyle = Qt::RoundCap;
else
{
PenCapstyle = Qt::SquareCap;
}
pen.setCapStyle(PenCapstyle);
pen.setJoinStyle(Qt::RoundJoin);
painter.setPen(pen);
painter.setBrush(Qt::transparent);
switch (item.penData.nPenType)
{
case DT_TRACE:
_DrawBrushItem(painter, item);
break;
}
}
/**
* @brief Ʊˢ
* @param painter
* @param item
*/
void CDrawWidget::_DrawBrushItem(QPainter &painter, const DRAW_ITEM &item)
{
painter.setRenderHint(QPainter::Antialiasing, true);
painter.drawPolyline(item.vectPath);
}
/**
* @brief Ƥ
* @param image ԭʼͼƬ
* @param item
*/
void CDrawWidget::_DrawEraseItem(QImage &image, const DRAW_ITEM &item)
{
//ͼƬС
int nWidth = image.width();
int nHeight = image.height();
//ƤͼƬ
QImage imageErase(nWidth, nHeight, QImage::Format_ARGB32);
QPainter painter(&imageErase);
//Ʋ
painter.setPen(QPen(QColor(0xFF, 0xFF, 0xFF, 0xFF), item.penData.nSize));
painter.setRenderHint(QPainter::Antialiasing, true);
painter.drawPolyline(item.vectPath);
//ϳͼƬ
int nCnt = nWidth * nHeight;
quint32 *pBits = (quint32*)image.bits();
quint32 *pBitsErase = (quint32*)imageErase.bits();
for (int i = 0; i < nCnt; ++i)
{
if (pBitsErase[i] == 0xFFFFFFFF && (pBits[i] < 0 || pBits[i] > 255))
{
pBits[i] = 0;
}
}
}
/**
* @brief ӵ
* @param data
*/
void CDrawWidget::AddPoint(PEN_DATA data)
{
if (data.nPenType == DT_NULL)
return;
if (data.nPenType == DT_TRACE ||data.nPenType == DT_ERASE)
{
//ʼͽ
if (data.nPenState != PS_DOWN && data.nPenState != PS_UP)
{
//Ըһͬĵ
QVector<QPoint> vectPos = m_drawItem.vectPath;
if (!vectPos.isEmpty())
{
if (vectPos.last() == data.pos)
return;
}
m_drawItem.penData = data;
m_drawItem.vectTimestamp.push_back(data.nTimestamp);
m_drawItem.vectPath.push_back(data.pos);
}
else
{
m_drawItem.penData.nPenState = data.nPenState;
m_drawItem.penData.nPenType = data.nPenType;
}
}
update();
}
/**
* @brief ȡ
* @param data
* @return
*/
bool CDrawWidget::GetDrawItem(DRAW_ITEM &data)
{
data = m_drawItem;
//ʼͽ
if (!data.vectPath.isEmpty())
{
data.posBegin = data.vectPath.first();
data.posEnd = data.vectPath.last();
}
int nType = data.penData.nPenType;
if (nType != DT_NULL)
{
if (data.penData.nPenType == DT_ERASE &&
m_queDrawItem.isEmpty() )
{
}
else
{
if (data.vectPath.size() > 0)
{
m_nPenId++;
data.penData.nPenId = m_nPenId;
data.penData.nChangeId = 0;
_SaveItem(data);
}
}
}
if (data.penData.nPenState == PS_UP)
{
m_drawItem.Init();
}
return true;
}
/**
* @brief
*/
int CDrawWidget::Undo()
{
int res = 0;
DRAW_ITEM drawItem;
if (!m_queDrawItem.isEmpty())
{
if (!m_bFlagClear)
{
drawItem = m_queDrawItem.back();
res = drawItem.penData.nPenId;
m_queRedoItem.push_back(drawItem);
m_queDrawItem.pop_back();
m_nPenId++;
}
else
{
m_queRedoItem = m_queDrawItem;
m_queDrawItem.clear();
}
}
update();
return res;
}
/**
* @brief
*/
int CDrawWidget::Redo()
{
int res = 0;
DRAW_ITEM drawItem;
if (!m_queRedoItem.isEmpty())
{
if (!m_bFlagClear)
{
drawItem = m_queRedoItem.back();
res = drawItem.penData.nPenId;
m_queDrawItem.push_back(m_queRedoItem.back());
m_queRedoItem.pop_back();
m_nPenId++;
}
else
{
m_queDrawItem = m_queRedoItem;
m_queRedoItem.clear();
}
}
update();
return res;
}
/**
* @brief
*/
void CDrawWidget::Clear()
{
m_bFlagClear = true;
m_queRedoItem = m_queDrawItem;
m_queDrawItem.clear();
m_nPenId++;
}
void CDrawWidget::GetQueSize(int &RedoSize, int &UndoSize)
{
RedoSize = m_queRedoItem.size();
UndoSize = m_queDrawItem.size();
}
/**
* @brief ƤС
* @param nSize С
*/
void CDrawWidget::SetEraseSize(int nSize)
{
m_nEraseSize = nSize;
}
/**
* @brief ûʴС
* @param nSize С
*/
void CDrawWidget::SetPenSize(int nSize)
{
m_nPenSize = nSize;
}
/**
* @brief ûɫ
* @param color ɫ
*/
void CDrawWidget::SetPenColor(const QColor &color)
{
m_penColor = color;
}
/**
* @brief û
* @param nType
*/
void CDrawWidget::SetPenType(DRAW_TYPE nType)
{
m_drawItem.penData.nPenType = nType;
}
void CDrawWidget::ClearLastDrawItem()
{
m_drawItem.Init();
}
/**
* @brief ¿ʼ
*/
void CDrawWidget::ReStart()
{
m_bFlagClear = true;
m_queRedoItem.clear();
m_queDrawItem.clear();
m_nPenId = 0;
} | true |
4b879632a887bf8070e31e00a8ec0c8ba25aefee | C++ | electrosy/sdl2-blocks | /Sprite.cpp | UTF-8 | 1,366 | 2.5625 | 3 | [] | no_license | /*
sdl2-blocks
Copyright (C) 2020 Steven Philley
Purpose: see header.
Date: Feb/14/2020
*/
#include "Sprite.h"
ley::Sprite::Sprite()
:
Renderable() {
}
ley::Sprite::Sprite(SDL_Texture * t, unsigned int s, std::vector<SDL_Rect> v)
:
Renderable(),
animSpeed(s),
texture(t) {
if (!texture) {
return;//EARLY EXIT
}
bool multiframe = false;
multiframe = v.size() > 1;
SDL_Rect source_rect;
dest_rect.y = source_rect.y = 0;
if(multiframe) {
for(auto rect : v) {
source_rect.x = rect.x; source_rect.y = rect.y;
source_rect.w = dest_rect.w = rect.w; source_rect.h = dest_rect.h = rect.h;
frames.push_back(source_rect);
}
} else {
SDL_QueryTexture(texture, NULL, NULL, &source_rect.w, &source_rect.h);
dest_rect.w = source_rect.w;
dest_rect.h = source_rect.h;
dest_rect.x = source_rect.x = 0;
}
}
ley::Sprite::~Sprite() {
}
/* Accessors */
void ley::Sprite::setPos(unsigned int x, unsigned int y) {
pos.first = x; pos.second = y;
}
void ley::Sprite::render(SDL_Renderer * r) {
unsigned int frameIndex = frames.size() > 1 ?
(SDL_GetTicks() / animSpeed) % frames.size() : 0;
dest_rect.x = pos.first; dest_rect.y = pos.second;
SDL_RenderCopy(r, texture, &frames[frameIndex], &dest_rect);
}
/* Functions */
| true |
dd08712bf6c6b800d00243fa547aa1859f958309 | C++ | bingxinfeng/Fascinating-Face | /FascinatingFace/FascinatingFace.ino | UTF-8 | 1,065 | 2.953125 | 3 | [] | no_license | /*
Physical Computing Project : Fascinating Face ;-)
Author: Bingxin Feng
To do:
1. Use light dependent resistor to sense the facial expression changing.
2. Put the serial data into Processing.
3. Use a rotatory pot to switch the output of two different light dependent resistors data.
*/
//ldr1 for wink mode, ldr2 for smile mode
const int ldrPin1 = A5;
const int ldrPin2 = A2;
const int potPin = A0;
void setup() {
// initial the serial port for data upload:
Serial.begin(9600); //the boundary it runs per second
}
void loop() {
// capture data in arduino:
// my code here:
int ldrVal1;
int ldrVal2;
int potPinVal;
potPinVal = analogRead(potPin);
// switch to wink mode
if (potPinVal == 1023) {
ldrVal1 = analogRead(ldrPin1);
ldrVal2 = 0;
// put the data onto the serials port:
Serial.println(ldrVal1);
delay(100);
}
// switch to smile mode
if (potPinVal == 0) {
ldrVal1 = 0;
ldrVal2 = analogRead(ldrPin2);
// put the data onto the serials port:
Serial.println(ldrVal2);
delay(100);
}
}
| true |
53fccdb1fba888a281428b48ca04439f71a72c74 | C++ | kobake/KppLibs | /MathLib/src/range.h | SHIFT_JIS | 3,918 | 3.265625 | 3 | [] | no_license | #pragma once
#ifdef min
#undef min
#undef max
#endif
template <class T> T adjust(T t, T min_value, T max_value)
{
if(t<min_value)return min_value;
if(t>max_value)return max_value;
return t;
}
template <class T> class range{ //###ASSERT_POLICY=DEFAULT_ASSERT,EXIT_ASSERT,EXCEPTION_ASSERT,NO_ASSERT
public:
class invalid_range{};
public:
range(T _min_value, T _max_value)
: min_value(_min_value), max_value(_max_value)
{
}
range()
{
min_value=numeric_limits<T>::min();
max_value=numeric_limits<T>::max();
}
T Adjust(T t) const
{
return ::adjust<T>(t, min_value, max_value);
}
//
T GetMin() const{ return min_value; }
T GetMax() const{ return max_value; }
void SetMin(T t){ min_value=t; _check(); }
void SetMax(T t){ max_value=t; _check(); }
protected:
void _check() //###{ASSERT_POLICYɊÂ
{
if(min_value>max_value)throw invalid_range();
}
private:
T min_value;
T max_value;
};
#include <limits>
using namespace std;
template <class T> class range_value{
public:
typedef range_value<T> Me;
public:
//RXgN^EfXgN^
range_value()
{
m_value=T();
}
range_value(T _value, const range<T>& _range)
{
reset(_value, _range);
}
void reset(T _value, const range<T>& _range)
{
m_value=_value;
m_range=_range;
_adjust();
}
//^ϊ
operator T() const
{
return m_value;
}
//Zq
Me& operator = (T t)
{
m_value=m_range.Adjust(t);
return *this;
}
Me& operator += (T t)
{
m_value=m_range.Adjust(m_value+t);
return *this;
}
Me& operator -= (T t)
{
m_value=m_range.Adjust(m_value-t);
return *this;
}
Me& operator ++ ()
{
return (*this)+=1;
}
Me operator ++ (int)
{
Me ret=*this;
(*this)+=1;
return ret;
}
Me& operator -- ()
{
return (*this)-=1;
}
Me operator -- (int)
{
Me ret=*this;
(*this)-=1;
return ret;
}
//
const range<T>& getRange() const{ return m_range; }
void SetRange(const range<T>& _range)
{
m_range=_range;
_Adjust();
}
protected:
void _Adjust()
{
m_value=m_range.Adjust(m_value);
}
private:
T m_value;
range<T> m_range;
};
//! FROM <= X <= TO X \B
template <int FROM, int TO>
class TRangedValue{
public:
typedef TRangedValue<FROM,TO> Me;
public:
//RXgN^EfXgN^
TRangedValue()
{
m_value=0;
_Adjust();
}
TRangedValue(int value)
{
m_value = value;
_Adjust();
}
//^ϊ
operator int() const{ return m_value; }
int Value() const{ return m_value; }
//Zq
Me& operator = (int t) { _Set(t); return *this; }
Me& operator += (int t) { _Set(m_value+t); return *this; }
Me& operator -= (int t) { _Set(m_value-t); return *this; }
Me& operator ++ () { return (*this)+=1; }
Me operator ++ (int) { Me ret=*this; (*this)+=1; return ret; }
Me& operator -- () { return (*this)-=1; }
Me operator -- (int) { Me ret=*this; (*this)-=1; return ret; }
protected:
void _Adjust()
{
m_value = ::adjust(m_value, FROM, TO);
}
void _Set(int n)
{
m_value = ::adjust(n, FROM, TO);
}
private:
int m_value;
};
/*!
FROM <= X <= TO
FROM <= Y <= TO
X <= Y
X ` Y \B
*/
template <int FROM, int TO>
class TRangedRange{
public:
//^
typedef TRangedValue<FROM,TO> ValueType;
public:
//RXgN^EfXgN^
TRangedRange()
{
Set(FROM,TO);
}
TRangedRange(int from, int to)
{
Set(from,to);
}
//ݒ
void SetFrom(int n){ m_from = n; _Adjust(); }
void SetTo(int n){ m_to = n; _Adjust(); }
void Set(int from, int to){ m_from = from; m_to = to; _Adjust(); }
//擾
const ValueType& GetFrom() const{ return m_from; }
const ValueType& GetTo() const{ return m_to; }
protected:
//
void _Adjust()
{
if(m_from>m_to)m_to=m_from; //####]邩fromɍ킹邩toɍ킹邩Ƃ낾c
}
private:
ValueType m_from;
ValueType m_to;
};
| true |
07ef1675b63a4572b085c2eb968a7c6f28f8a25f | C++ | zxc123qwe456asd789/library | /modint/barrett-reduction.hpp | UTF-8 | 906 | 2.84375 | 3 | [
"CC0-1.0"
] | permissive | #pragma once
#include <utility>
using namespace std;
struct Barrett {
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
u32 m;
u64 im;
Barrett() : m(), im() {}
Barrett(int n) : m(n), im(u64(-1) / m + 1) {}
constexpr inline i64 quo(u64 n) {
u64 x = u64((__uint128_t(n) * im) >> 64);
u32 r = n - x * m;
return m <= r ? x - 1 : x;
}
constexpr inline i64 rem(u64 n) {
u64 x = u64((__uint128_t(n) * im) >> 64);
u32 r = n - x * m;
return m <= r ? r + m : r;
}
constexpr inline pair<i64, int> quorem(u64 n) {
u64 x = u64((__uint128_t(n) * im) >> 64);
u32 r = n - x * m;
if (m <= r) return {x - 1, r + m};
return {x, r};
}
constexpr inline i64 pow(u64 n, i64 p) {
u32 a = rem(n), r = 1;
while (p) {
if (p & 1) r = rem(u64(r) * a);
a = rem(u64(a) * a);
p >>= 1;
}
return r;
}
}; | true |
df79cb606654eb502ec07628f509ccd015d8532c | C++ | AndreJesusBrito/OpenGL-Tetris | /src/matrix.h | UTF-8 | 1,354 | 3.171875 | 3 | [
"MIT"
] | permissive | #ifndef MATRIX_H
#define MATRIX_H
// #include <array>
#include <stdexcept>
#include <iostream>
namespace mycontainers {
// Aggregate class for a matrix of T objects
template<class T, std::size_t width, std::size_t height>
class Matrix {
public:
// Support height = 0 and width = 0
T m_matrix[height ? height : 1][width ? width : 1];
std::size_t getWidth() const;
std::size_t getHeight() const;
// Returns reference to element at row and col
T& at(const std::size_t row, const std::size_t col);
// Returns const reference to element at row and col
const T& view(const std::size_t row, std::size_t col) const;
// Returns an array with indexes for the requested row
// std::array<std::size_t, width> atRow(std::size_t row) const;
// Returns an array with indexes for the requested col
// std::array<std::size_t, height> atCol(std::size_t col) const;
friend std::ostream& operator<<(std::ostream &out, const Matrix<T, width, height> &matrix) {
for (std::size_t i = 0; i < height; ++i) {
for (std::size_t j = 0; j < width; ++j)
out << matrix.m_matrix[i][j] << ' ';
out << '\n';
}
return out;
}
};
}
#include "matrix.inl"
#endif | true |
883aa4e041c4ca9f261c969699968244e9004048 | C++ | rubenvereecken/challenges | /Elements of Programming Interviews/8-StacksQueues/MaxStackNode.h | UTF-8 | 519 | 2.75 | 3 | [] | no_license | /*!
* \file
* \brief MaxStackNode.h
*
* \date Aug 14, 2013
* \author Ruben Vereecken
*/
#ifndef MAXSTACKNODE_H_
#define MAXSTACKNODE_H_
#include <memory>
template <typename T>
class MaxStackNode;
//typedef MaxStackNode MSNode;
template <typename T>
using MSNodePtr = std::shared_ptr<MaxStackNode<T> >;
template <typename T>
class MaxStackNode {
public:
MaxStackNode();
MaxStackNode(T);
MaxStackNode(T, MSNodePtr<T>);
virtual ~MaxStackNode();
T data;
MSNodePtr<T> under;
};
#endif /* MAXSTACKNODE_H_ */
| true |
d2a25fc3a6c2fb033480d0f1e3cd38f491f03db2 | C++ | bugsb/CPP | /shuffle-Leet.cpp | UTF-8 | 813 | 3.328125 | 3 | [] | no_license | /* Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn]. */
class Solution {
public:
vector<int> shuffle(vector<int>& nums, int n) {
// vector<int> soln(2*n,0);
// for(int i{0},j{0}; i<n*2 && j<n; i+=2,j++)
// {
// soln[i] = nums[j];
// soln[i+1] = nums[n+j];
// }
// vector<int> soln{};
// for(int i{0}; i<n; ++i)
// {
// soln.push_back(nums[i]);
// soln.push_back(nums[n+i]);
// }
vector<int> soln(2*n,0);
for (int i = 0; i < n; i++)
{
soln[2*i] = nums[i];
soln[2*i+1] = nums[n+i];
}
return soln;
}
}; | true |
6ca36f84914f018c10d3a2d7279b7a6015355444 | C++ | F2i/dsa | /assignment2/Cache.h | UTF-8 | 1,660 | 3.140625 | 3 | [] | no_license | #ifndef CACHE_H
#define CACHE_H
#include "main.h"
class Node {
public:
int key;
Node *left;
Node *right;
int height;
Elem* cont;
~Node(){delete cont;}
};
class AVL
{
public:
Node * root;
AVL(){
this->root = NULL;
}
~AVL(){
this->emptyTree(this->root);
}
int height(Node *N);
int max(int a, int b);
Node *newNode(int key, Elem* cont);
Node *rightRotate(Node *y);
Node *leftRotate(Node *x);
int getBalanceFactor(Node *N);
Node *insertNode(Node *node, int key, Elem* cont);
Node *nodeWithMimumValue(Node *node);
Node *deleteNode(Node *root, int key);
Node* search(Node* root, int key);
void printTree(Node *root, string indent, bool last);
void printPreO(Node *root);
void printInO(Node *root);
void emptyTree(Node *root);
};
// Circular Queue implementation in C++
class Queue {
private:
int front, rear;
Elem **arr;
int maxsize;
public:
Queue(int s) {
front = -1;
rear = -1;
arr = new Elem*[s];
maxsize = s;
}
~Queue(){
delete[] arr;
}
bool isFull();
bool isEmpty();
void enQueue(Elem * element);
Elem * deQueue();
void display();
//Elem * front();
Elem * Erear();
};
class Cache {
int p;
public:
AVL * tree;
Queue * cqueue;
Cache(int s) {
p = 0;
tree = new AVL;
cqueue = new Queue(s);
}
~Cache() {
delete tree;
delete cqueue;
}
Data* read(int addr);
Elem* put(int addr, Data* cont, bool bsync);
Elem* write(int addr, Data* cont);
void print();
void preOrder();
void inOrder();
};
#endif | true |
30769fd20f43851dc8283b6dbfb6eb3926d5e1d3 | C++ | green-fox-academy/Arubechama | /W03D05/Power.cpp | UTF-8 | 434 | 3.828125 | 4 | [] | no_license | #include <iostream>
int powerN(int base, int n);
int main()
{
int base, n;
std::cout << "Enter the base value:" << std::endl;
std::cin >> base;
std::cout << "Enter the power value:" << std::endl;
std::cin >> n;
std::cout << "Your number is " << powerN(base, n) << "." << std::endl;
}
int powerN(int base, int n) {
if (n!=0) {
return (base*powerN(base, n-1));
} else {
return 1;
}
}
| true |
ed731f3d04646c0d168071d5a0f54372e540ab8b | C++ | nanfang-wuyu/proj19-process-memory-tracker | /src/memoryFile/allocation_info.cpp | UTF-8 | 898 | 2.9375 | 3 | [
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mulanpsl-2.0-en",
"MIT"
] | permissive | // reference https://www.codeproject.com/articles/393957/cplusplus-memory-leak-finder
#include "allocation_info.hpp"
allocation_info::allocation_info(void* address, size_t size, char** stacktrace, size_t depth, pthread_t thread_id)
{
this->address = reinterpret_cast<allocation_info::address_type>(address);
this->size = size;
this->thread_id = thread_id;
// Skip first frame as that is the overriden malloc method
for(int i = 0; i < depth; ++i)
{
string frame = stacktrace[i];
this->stacktrace.push_back(frame);
}
}
allocation_info::address_type allocation_info::get_address() const
{
return address;
}
size_t allocation_info::get_size() const
{
return size;
}
vector<string> allocation_info::get_stacktrace() const
{
return stacktrace;
}
pthread_t allocation_info::get_thread_id() const
{
return thread_id;
}
| true |
e83bb2236a8aa7d0ad16729ac25f35a2e7bdc433 | C++ | mebbaid/scs-eigen | /src/ScsEigen/include/ScsEigen/Math.h | UTF-8 | 805 | 2.84375 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /**
* @file Math.h
* @author Giulio Romualdi
* @copyright Released under the terms of the MIT License.
* @date 2021
*/
#ifndef SCS_EIGEN_LINEAR_MATH_H
#define SCS_EIGEN_LINEAR_MATH_H
#include <utility>
#include <Eigen/Dense>
/**
* ScsEigen namespace.
*/
namespace ScsEigen
{
/**
* @brief Compute the Cholesky decomposition of a PSD matrix A.
* @param A a PSD matrix
* @return a pair containing a Boolean and and the Cholesky decomposition of the matrix A. The
* bolean is true if the decomposition went fine.
* @note please be sure the matrix A is PSD.
*/
std::pair<bool, Eigen::MatrixXd> choleskyDecomposition(const Eigen::Ref<const Eigen::MatrixXd>& A);
/**
* @brief Unitary vector
*/
using Vector1d = Eigen::Matrix<double, 1, 1>;
} // namespace ScsEigen
#endif // SCS_EIGEN_LINEAR_MATH_H
| true |
fbd3b475d1743ffa85ccee18676a2c00e6838edf | C++ | NitefullWind/gamesByQt | /snake/controller.cpp | UTF-8 | 6,275 | 3 | 3 | [] | no_license | #include "controller.h"
#include "constants.h"
Controller::Controller(QGraphicsScene &scene, QObject *parent):
QObject(parent),
scene(scene),
food(new Food(0,0)),
gameIsOver(false),
gameIsPause(false)
{
drawWall();
drawSnake();
drawFood();
info = new InfoWidget();
scene.addItem(info);
scene.installEventFilter(this); //安装事件过滤器
connect(&timer, SIGNAL(timeout()), &scene, SLOT(advance())); //连接计时器与scene的advance函数
connect(&timer, SIGNAL(timeout()), &scene, SLOT(update())); //调用update(),这样元素重绘后才会刷新界面
connect(&timer, SIGNAL(timeout()), this, SLOT(checkCollisions())); //检测碰撞
pause();
info->setInformation("空格:开始\暂停\nEsc:Play Again");
}
/* (-450,-300)(-PosX,-PosY)(SceneX,300)
* +---+-----------+
* | | |
* | |600 : |
* |150| 750 |
* +---+-----------+
* (-450,300)(-300,300)(450,300)
*/
void Controller::drawWall()
{
//初始化四周的墙
wall[0] = new Wall(-PosX,-PosY,SceneWidth,Width);
wall[1] = new Wall(SceneX-Width,-PosY,Width,SceneHeight);
wall[2] = new Wall(-PosX,PosY-Width,SceneWidth,Width);
wall[3] = new Wall(-PosX,-PosY,Width,SceneHeight);
//添加到场景中
for(int i=0;i<4;i++){
scene.addItem(wall[i]);
}
}
void Controller::drawSnake()
{
snake[0] = new Snake(-PosX+Width,-PosY+Width,3,Right,Qt::red,"红蛇");
scene.addItem(snake[0]);
snake[1] = new Snake(SceneX-2*Width,PosY-2*Width,3,Left,Qt::green,"绿蛇");
scene.addItem(snake[1]);
}
void Controller::drawFood()
{
if(!food){
scene.removeItem(food);
}
qreal x=0, y=0;
do{ //随机产生食物坐标
x = (qrand() % (SceneWidth/Width-2))*Width-PosX+Width;
y = (qrand() % (SceneHeight/Width-2))*Width-SceneHeight/2+Width;
}while(snake[0]->shape().contains(QPointF(x,y))||snake[1]->shape().contains(QPointF(x,y))||food->x()==x&&food->y()==y); //检测食物的坐标是否在蛇身上
food = new Food(x,y);
scene.addItem(food);
}
void Controller::newGame()
{
scene.removeItem(snake[0]);
scene.removeItem(snake[1]);
scene.removeItem(food);
drawSnake();
drawFood();
info->setScore(snake[0]->getScore(), snake[1]->getScore());
gameIsOver = false;
gameIsPause = false;
pause();
}
void Controller::pause()
{
if(!gameIsOver){
//游戏暂停中则开始计时,否则停止计时
if(gameIsPause){
info->setInformation("快跑啊,游戏开始啦~");
timer.start(1000/3);
gameIsPause = false;
}else{
info->setInformation("兄弟别急,游戏正暂停着...");
timer.stop();
gameIsPause = true;
}
}
}
bool Controller::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::KeyPress){
keyPress((QKeyEvent *) event); //QEvent强制转换为QKeyEvent类型,传递给keyPress函数
return true;
}else{
return QObject::eventFilter(object,event); //否则传给QObject的事件过滤器
}
}
void Controller::keyPress(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Up:
if(snake[0]->nowDirection()!=Down)
snake[0]->setDirection(Up);
break;
case Qt::Key_Down:
if(snake[0]->nowDirection()!=Up)
snake[0]->setDirection(Down);
break;
case Qt::Key_Left:
if(snake[0]->nowDirection()!=Right)
snake[0]->setDirection(Left);
break;
case Qt::Key_Right:
if(snake[0]->nowDirection()!=Left)
snake[0]->setDirection(Right);
break;
case Qt::Key_W:
if(snake[1]->nowDirection()!=Down)
snake[1]->setDirection(Up);
break;
case Qt::Key_S:
if(snake[1]->nowDirection()!=Up)
snake[1]->setDirection(Down);
break;
case Qt::Key_A:
if(snake[1]->nowDirection()!=Right)
snake[1]->setDirection(Left);
break;
case Qt::Key_D:
if(snake[1]->nowDirection()!=Left)
snake[1]->setDirection(Right);
break;
case Qt::Key_Space:
pause();
break;
case Qt::Key_Escape:
newGame();
break;
default:
break;
}
}
void Controller::checkCollisions()
{
if(snake[0]->shape().contains(food->pos())){
snake[0]->grow(food->pos());
scene.removeItem(food);
info->setInformation(snake[0]->getName()+"吃了食物");
drawFood();
}else if(snake[1]->shape().contains(food->pos())){
snake[1]->grow(food->pos());
scene.removeItem(food);
info->setInformation(snake[1]->getName()+"吃了食物");
drawFood();
}
if(snake[0]->eatItself){
gameOver(snake[0]->getName()+"\n把自己给咬了,233333");
}
if(snake[1]->eatItself){
gameOver(snake[1]->getName()+"\n咬自己真的不疼吗 = =! ");
}
//检测两条蛇的碰撞
if(snake[0]->shape().contains(snake[1]->getHead())){
if(snake[1]->getHead()==snake[0]->getTail()){ //snake[0]被吃
snake[1]->grow(snake[1]->getHead());
snake[0]->beEaten();
info->setInformation(snake[1]->getName()+"咬了"+snake[0]->getName());
}else{ //没吃到尾巴则snake[0]撞死
gameOver(snake[1]->getName()+"兄弟,只能咬人家尾巴好不好...");
}
}
if(snake[1]->shape().contains(snake[0]->getHead())){
if(snake[0]->getHead()==snake[1]->getTail()){ //snake[1]被吃
snake[0]->grow(snake[0]->getHead());
snake[1]->beEaten();
info->setInformation(snake[0]->getName()+"咬了"+snake[1]->getName());
}else{
gameOver("嘿,"+snake[0]->getName()+"\n去咬他的尾巴啊!!!");
}
}
info->setScore(snake[0]->getScore(), snake[1]->getScore());
}
void Controller::gameOver(QString information)
{
pause();
gameIsOver = true;
info->setInformation(information);
}
Controller::~Controller()
{
}
| true |
fba419eaaa70bf392a7e81d65ee5809c33d0c270 | C++ | EtiTheSpirit/LovePotion | /source/objects/thread/wrap_thread.cpp | UTF-8 | 2,023 | 2.625 | 3 | [
"MIT"
] | permissive | #include "common/runtime.h"
#include "modules/mod_thread.h"
#include "objects/thread/thread.h"
#define CLASS_TYPE LUAOBJ_TYPE_THREAD
#define CLASS_NAME "Thread"
int threadNew(lua_State * L)
{
const char * arg = luaL_checkstring(L, 1);
void * raw_self = luaobj_newudata(L, sizeof(LuaThread));
luaobj_setclass(L, CLASS_TYPE, CLASS_NAME);
new (raw_self) LuaThread(arg);
return 1;
}
int threadStart(lua_State * L)
{
LuaThread * self = (LuaThread *)luaobj_checkudata(L, 1, CLASS_TYPE);
uint argc = lua_gettop(L) - 1;
vector<Variant> args;
if (argc > 0)
{
for (uint i = 0; i < argc; ++i)
{
if (!lua_isnone(L, i + 2))
args.push_back(Variant::FromLua(L, i + 2));
}
}
if (!self->IsRunning())
self->Start(args);
return 0;
}
int threadWait(lua_State * L)
{
LuaThread * self = (LuaThread *)luaobj_checkudata(L, 1, CLASS_TYPE);
if (self->IsRunning())
self->Wait();
return 0;
}
int threadGetError(lua_State * L)
{
LuaThread * self = (LuaThread *)luaobj_checkudata(L, 1, CLASS_TYPE);
string error = self->GetError();
lua_pushstring(L, error.c_str());
return 1;
}
int threadIsRunning(lua_State * L)
{
LuaThread * self = (LuaThread *)luaobj_checkudata(L, 1, CLASS_TYPE);
lua_pushboolean(L, self->IsRunning());
return 1;
}
int threadToString(lua_State * L)
{
LuaThread * self = (LuaThread *)luaobj_checkudata(L, 1, CLASS_TYPE);
char * data = self->ToString();
lua_pushstring(L, data);
free(data);
return 1;
}
int initLuaThread(lua_State * L)
{
luaL_Reg reg[] =
{
{ "__tostring", threadToString },
{ "getError", threadGetError },
{ "isRunning", threadIsRunning },
{ "new", threadNew },
{ "start", threadStart },
{ "wait", threadWait },
{ 0, 0 }
};
luaobj_newclass(L, CLASS_NAME, NULL, threadNew, reg);
return 1;
} | true |
0b36cf440e702c395fa7d0c9633f478081084979 | C++ | vtienhieu/GCH0715-Cloud-VuTienHieu | /ASM/include/program.h | UTF-8 | 454 | 2.546875 | 3 | [] | no_license | #ifndef __PROGRAM__H__
#define __PROGRAM__H__
#include "Document.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// define option constant
#define ADD_DOCUMENT 1
#define DISPLAY 2
#define EXIT 0
class Program
{
private:
vector<Document *> Doc;
public:
void print_menu();
int get_option();
void do_task(const int &option);
void add_document();
void display_document();
void run();
};
#endif
| true |
77f8fccf383d49ce1171bab83ee73565fcf77aa9 | C++ | 8emi95/elte-ik-cpp | /cpp_schaum/msvec_170619/msvecmain.cpp | UTF-8 | 4,111 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include <iterator>
#include <numeric>
#include <algorithm>
#include "msetvec.h"
#include <vector>
#include <string>
#include "msetvec.h"
struct string_size_less
{
bool operator()( const std::string& a,
const std::string& b ) const
{
return a.size() < b.size();
}
};
struct employee
{
std::string name;
std::string userid;
int salary;
employee( const std::string& n, const std::string& u, int s )
: name( n ), userid( u ), salary( s ) { }
};
struct employee_name_comp
{
bool operator()( const employee& a, const employee& b ) const
{
return a.name < b.name;
}
};
struct employee_salary_less
{
bool operator()( const employee& a, const employee& b ) const
{
return a.salary < b.salary;
}
};
struct employee_salary_greater
{
bool operator()( const employee& a, const employee& b ) const
{
return a.salary > b.salary;
}
};
struct employee_userid_less
{
bool operator()( const employee& a, const employee& b ) const
{
return a.userid < b.userid;
}
};
const int max = 1024;
int main()
{
int your_mark = 1;
//* 2-es
std::vector<int> v;
v.reserve( max );
for( int i = 0; i < max; ++i )
{
v.push_back( 0 == i % 2 ? max - i : 2 * i );
}
multiset_vector<int, std::greater<int> > m( v );
std::vector<employee> emps;
emps.push_back( employee( "John Doe", "john.doe", 600 ) );
emps.push_back( employee( "John Doe", "doej", 700 ) );
emps.push_back( employee( "John Doe", "jdoe", 800 ) );
emps.push_back( employee( "Maximus Dickus", "max", 490 ) );
emps.push_back( employee( "Jane Doe", "jane.doe", 750 ) );
const multiset_vector<employee, employee_name_comp> emps_ms( emps );
const employee c( "John Doe", "", 0 );
if ( 'M' == emps[ 4 ].name[ 0 ] && 'n' == emps[ 0 ].userid[ 2 ] &&
3 == emps_ms.count( c ) && 2 * ( max - 1 ) == v[ 0 ] &&
2 == v[ max - 1 ] && v[ 0 ] != v[ 1 ] )
{
your_mark = m.count( 2 );
}
//*/
//* 3-as
std::vector<int> nv;
nv.push_back( 5 );
nv.push_back( 2 );
nv.push_back( 1 );
nv.push_back( 7 );
m.use( nv );
const employee cm( "Maximus Dickus", "", 0 );
const employee nf( "Bjarne Stroustrup", "bs", 1000 );
std::vector<employee>::const_iterator cim = emps_ms.find( cm );
std::vector<employee>::const_iterator cib = emps_ms.find( nf );
if ( cib == emps.end() && 'M' == cim->name[ 0 ] )
{
your_mark = nv[ 2 ] + nv[ 3 ] + m.count( 6 );
}
//*/
//* 4-es
std::vector<employee> veu = emps;
std::vector<employee> ves = emps;
std::vector<employee> vesg = emps;
multiset_vector<employee, employee_name_comp> a( veu );
multiset_vector<employee, employee_name_comp> b( ves );
multiset_vector<employee, employee_name_comp> s( vesg );
a.secondary_ordering( employee_userid_less() );
b.secondary_ordering( employee_salary_less() );
s.secondary_ordering( employee_salary_greater() );
if ( veu[ 0 ].name == ves[ 0 ].name && veu[ 4 ].name == vesg[ 4 ].name &&
800 == vesg[ 1 ].salary && 600 == ves[ 1 ].salary &&
"doej" == veu[ 1 ].userid && "jdoe" == veu[ 2 ].userid )
{
your_mark = a.count( c ) + b.count( cm );
}
//*/
//* 5-os
const std::vector<employee> ce = emps;
sorted_iterator<employee, employee_salary_less> its =
sorted_iterator_begin( ce, employee_salary_less() );
sorted_iterator<employee, employee_userid_less> itu =
sorted_iterator_begin( ce, employee_userid_less() );
sorted_iterator<int, std::less<int> > iti =
sorted_iterator_begin( v, std::less<int>() );
int x = std::accumulate( iti,
sorted_iterator_end( v, std::less<int>() ),
0 );
if ( 490 == its->salary && &(*its) == &(ce[ 4 ] ) && 700 == itu->salary &&
x == std::accumulate( v.begin(), v.end(), 0 ) && 2 == *iti )
{
sorted_iterator<int, std::less<int> > i =
std::find( sorted_iterator_begin( nv, std::less<int>() ),
sorted_iterator_end( nv, std::less<int>() ),
5 );
your_mark = *i;
}
//*/
std::cout << "Your mark is " << your_mark;
std::endl( std::cout );
}
| true |
1f66c729c2f55bdeeb09b77cfd62a913a7b393e9 | C++ | ZhouXing-19/nailit_cpp | /3/refer.cpp | WINDOWS-1252 | 362 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int x = 100;
int y = x; //ֵ
cout<<"x=" <<x<<" y="<<y<<endl;
y+=100;
cout<<"x=" <<x<<" y="<<y<<endl; //x,yͬ
int &refx = x ;
cout<<"x=" <<x<<" refx="<<refx<<endl;
x*=10;
cout<<"x=" <<x<<" efx="<<refx<<endl;
refx+=50;
cout<<"x=" <<x<<" refx="<<refx<<endl;
return 0;
}
| true |
ffbcd299936c73c4f1ad4033afb6311b8eba9a88 | C++ | mephi82/ssufarm | /DFRobot_PH_EC2/DFRobot_PH_EC2.ino | UTF-8 | 4,607 | 2.65625 | 3 | [] | no_license |
#include "DFRobot_PH.h"
#include "DFRobot_EC.h"
#include <EEPROM.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>
#define PH_PIN A2
#define EC_PIN1 A1
#define EC_PIN2 A3
#define ONE_WIRE_BUS 4
#define KVALUEADDR 0x0A
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
float voltagePH,voltageEC1,voltageEC2,phValue,ecValue1,ecValue2,temperature = 23;
volatile int flow_frequency1, flow_frequency2; // Measures flow sensor pulses
unsigned int l_hour1, l_hour2; // Calculated litres/hour
unsigned char flowsensor1 = 2; // Sensor Input
unsigned char flowsensor2 = 3; // Sensor Input
//unsigned long currentTime;
//unsigned long cloopTime;
DFRobot_PH ph;
DFRobot_EC ec;
void flow1() // Interrupt function
{
flow_frequency1++;
}
void flow2() // Interrupt function
{
flow_frequency2++;
}
void setup()
{
Serial.begin(115200);
ph.begin();
ec.begin();
sensors.begin();
for(byte i = 0;i< 8; i++ ){
EEPROM.write(KVALUEADDR+i, 0xFF);
}
Serial.println(EEPROM.read(KVALUEADDR));
pinMode(flowsensor1, INPUT);
digitalWrite(flowsensor1, HIGH); // Optional Internal Pull-Up
attachInterrupt(digitalPinToInterrupt(flowsensor1), flow1, RISING);
pinMode(flowsensor2, INPUT);
digitalWrite(flowsensor2, HIGH); // Optional Internal Pull-Up
attachInterrupt(digitalPinToInterrupt(flowsensor2), flow2, RISING);
// attachInterrupt(0, flow, RISING); // Setup Interrupt
sei(); // Enable interrupts
// currentTime = millis();
// cloopTime = currentTime;
}
void loop()
{
char cmd[10];
StaticJsonDocument<200> doc;
static unsigned long timepoint = millis();
// Serial.println(flow_frequency1);
// Serial.println(flow_frequency2);
if(millis()-timepoint>1000U){ //time interval: 1s
l_hour1 = (flow_frequency1 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
flow_frequency1 = 0; // Reset Counter
l_hour2 = (flow_frequency2 * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flowrate in L/hour
flow_frequency2 = 0; // Reset Counter
timepoint = millis();
temperature = readTemperature(temperature); // read your temperature sensor to execute temperature compensation
voltagePH = analogRead(PH_PIN)/1024.0*5000; // read the ph voltage
phValue = ph.readPH(voltagePH,temperature); // convert voltage to pH with temperature compensation
voltageEC1 = analogRead(EC_PIN1)/1024.0*5000;
ecValue1 = 0.3+ec.readEC(voltageEC1,temperature); // convert voltage to EC with temperature compensation
voltageEC2 = analogRead(EC_PIN2)/1024.0*5000;
ecValue2 = 0.3+ec.readEC(voltageEC2,temperature); // convert voltage to EC with temperature compensation
Serial.print("{\"Temp\":");
Serial.print(temperature,1);
Serial.print(", \"EC1\":");
Serial.print(ecValue1,2);
Serial.print(", \"EC2\":");
Serial.print(ecValue2,2);
// Serial.println("ms/cm");
Serial.print(", \"pH2\":");
Serial.print(phValue,2);
// Serial.print(", \"Voltage\":'");
// Serial.print(voltageEC1,1);
// Serial.print("/");
// Serial.print(voltageEC2,1);
// Serial.print("'");
Serial.print(", \"Flow1\":");
Serial.print(l_hour1, DEC);
Serial.print(", \"Flow2\":");
Serial.print(l_hour2, DEC);
Serial.println("}");
}
if(readSerial(cmd)){
DeserializationError error = deserializeJson(doc, cmd);
temperature = doc["Temp"];
}
}
//
int i = 0;
bool readSerial(char result[]){
while(Serial.available() > 0){
char inChar = Serial.read();
if(inChar == '\n'){
result[i] = '\0';
Serial.flush();
i=0;
return true;
}
if(inChar != '\r'){
result[i] = inChar;
i++;
}
delay(1);
}
return false;
}
float readTemperature(float oldtemp)
{
sensors.requestTemperatures(); // Send the command to get temperatures
//add your code here to get the temperature from your temperature sensor
float tempC = sensors.getTempCByIndex(0);
if(tempC != DEVICE_DISCONNECTED_C)
{
return tempC;
}
else {
// Serial.print("temp not read");
return oldtemp;
}
}
| true |
885361918e84a04930b25d7df4faa9dad20aa3bf | C++ | aart11330056/Project_Smart-Apartment_full | /ArduinoUnoKeypadPassword.ino | UTF-8 | 3,799 | 2.8125 | 3 | [] | no_license | #include <Keypad.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include<EEPROM.h>
#define I2C_ADDR 0x27 //defining the LCD pins
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
LiquidCrystal_I2C lcd(I2C_ADDR, En_pin, Rw_pin, Rs_pin, D4_pin, D5_pin, D6_pin, D7_pin);
char password[4];
char initial_password[4], new_password[4];
int i = 0;
int relay_pin = 10;
char key_pressed = 0;
const byte rows = 4;
const byte columns = 4;
char hexaKeys[rows][columns] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte row_pins[rows] = {9, 8, 7, 6};
byte column_pins[columns] = {5, 4, 3, 2};
Keypad keypad_key = Keypad( makeKeymap(hexaKeys), row_pins, column_pins, rows, columns);
void setup()
{
lcd.setBacklightPin(BACKLIGHT_PIN, POSITIVE);
lcd.setBacklight(HIGH);
pinMode(relay_pin, OUTPUT);
lcd.begin(16, 2);
lcd.setCursor(3, 0);
lcd.print(" Welcome ");
lcd.setCursor(0, 1);
lcd.print("Electronic Lock!");
delay(2000);
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Enter Password");
lcd.setCursor(6, 1);
initialpassword();
}
void loop()
{
digitalWrite(relay_pin, LOW);
key_pressed = keypad_key.getKey();
if (key_pressed == '#')
change();
if (key_pressed)
{
password[i++] = key_pressed;
lcd.print(key_pressed);
}
if (i == 4)
{
delay(200);
for (int j = 0; j < 4; j++)
initial_password[j] = EEPROM.read(j);
if (!(strncmp(password, initial_password, 4)))
{
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Pass Accepted!");
digitalWrite(relay_pin, HIGH);
delay(2000);
lcd.setCursor(0, 1);
lcd.print("Pres # to change");
delay(2000);
lcd.clear();
lcd.print("Enter Password:");
lcd.setCursor(6, 1);
i = 0;
}
else
{
digitalWrite(relay_pin, LOW);
lcd.clear();
lcd.print("Wrong Password");
lcd.setCursor(0, 1);
lcd.print("Pres # to Change");
delay(2000);
lcd.clear();
lcd.print("Enter Password");
lcd.setCursor(6, 1);
i = 0;
}
}
}
void change()
{
int j = 0;
lcd.clear();
lcd.print("Current Password");
lcd.setCursor(6, 1);
while (j < 4)
{
char key = keypad_key.getKey();
if (key)
{
new_password[j++] = key;
lcd.print(key);
}
key = 0;
}
delay(500);
if ((strncmp(new_password, initial_password, 4)))
{
lcd.clear();
lcd.print("Wrong Password");
lcd.setCursor(3, 1);
lcd.print("Try Again");
delay(1000);
}
else
{
j = 0;
lcd.clear();
lcd.print("New Password:");
lcd.setCursor(6, 1);
while (j < 4)
{
char key = keypad_key.getKey();
if (key)
{
initial_password[j] = key;
lcd.print(key);
EEPROM.write(j, key);
j++;
}
}
delay(1000);
lcd.clear();
lcd.setCursor(2, 0);
lcd.print("Pass Changed");
delay(1500);
}
lcd.clear();
lcd.setCursor(1, 0);
lcd.print("Enter Password");
lcd.setCursor(6, 1);
key_pressed = 0;
}
void initialpassword() {
for (int j = 0; j < 4; j++)
EEPROM.write(j, j + 49);
for (int j = 0; j < 4; j++)
initial_password[j] = EEPROM.read(j);
}
| true |
015e44516ad4cd3d739161930a98b8a983a19f2c | C++ | akashrajkn/spoj-solutions | /spoj_absp1.cpp | UTF-8 | 1,327 | 2.53125 | 3 | [] | no_license | /*
problem code: ABSP1
problem number: 18155
problem link: http://www.spoj.com/problems/ABSP1/
*/
#include<cstdio>
#include<cstdlib>
#include<cctype>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<iterator>
#include<set>
#include<map>
#include<iostream>
#include<sstream>
#include<deque>
#include<cmath>
#include<memory.h>
#include<algorithm>
#include<utility>
#include<climits>
using namespace std;
#define rep(i,n) for(long long i=0; i<n; ++i)
#define gRep(i,p,n) for(long long i=p; i<n; ++i)
#define mp make_pair
#define all(c) c.begin(),c.end()
#define sc(a) scanf("%lld", &a)
#define pf(a) printf("%lld\n",a)
#define ub upper_bound
#define lb lower_bound
#define bs binary_search
#define pb push_back
typedef pair<long long,long long> pii;
typedef long long ll;
int main()
{
int t, n;
scanf("%d", &t);
while(t--)
{
scanf("%d", &n);
ll a[n];
rep(i,n)
{
sc(a[i]);
}
ll sum = 0;
rep(i, n/2)
{
sum += ((n- 2*i -1)*(a[n-i-1]-a[i])); //look at teh pattern,,,,,
/*
last number is added n-1 times, last but 1 number is added n-3 (add n-2 times, subtract 1 time)....
and so on..... starting numbers will be the opposite ..... they will be subtracted so many times
*/
}
pf(sum);
}
return 0;
} | true |
1b99c33cdfebab6cac638764ca1dbabc5c7e4788 | C++ | Mansterteddy/Cracking-the-Coding-Interview | /language/c++/data structure/Class/ComputeAreaAndPermiter/Circle.h | UTF-8 | 434 | 3.09375 | 3 | [] | no_license | #ifndef CIRCLE_H_
#define CIRCLE_H_
#include "Shape.h"
class Circle : public virtual Shape
{
public:
Circle(): radius(0) {}
Circle(int the_radius) : radius(the_radius){}
int get_radius() const {return radius;}
double compute_area() const;
double compute_perimeter() const;
void read_shape_data();
std::string to_string() const;
private:
int radius;
};
#endif | true |
8afdbaa2de60cc167f33a228b49aed557231bb73 | C++ | menguan/toj_code | /tojcode/3100.cpp | UTF-8 | 1,104 | 2.546875 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
char map[60][60];
bool trap[60][60];
bool vis[60][60];
int r,c;
int ans;
int dir[4][2]={0,1,1,0,-1,0,0,-1};
void dfs(int x,int y)
{
if(x==0||y==0||x>r||y>c) return;
vis[x][y]=1;
int tx,ty;
if(map[x][y]=='G') ans++;
if(trap[x][y]) return ;
for(int i=0;i<4;i++)
{
tx=x+dir[i][0];ty=y+dir[i][1];
if(vis[tx][ty]) continue;
if(map[tx][ty]=='#') continue;
dfs(tx,ty);
}
}
int main()
{
while(cin>>c>>r)
{
memset(vis,0,sizeof(vis));
memset(trap,0,sizeof(trap));
int sx,sy;ans=0;
for(int i=1;i<=r;i++)
{
for(int j=1;j<=c;j++)
{
cin>>map[i][j];
if(map[i][j]=='P')
{sx=i;sy=j;}
else if(map[i][j]=='T')
{
trap[i+1][j]=trap[i][j+1]=trap[i-1][j]=trap[i][j-1]=1;
}
}
}
dfs(sx,sy);
cout<<ans<<endl;
}
}
| true |
71c117966d37842e97dd0bcfab082775c2de0678 | C++ | tatiotir/QJabberd | /NodeSubscriber.cpp | UTF-8 | 1,256 | 2.640625 | 3 | [] | no_license | #include "NodeSubscriber.h"
NodeSubscriber::NodeSubscriber(QString jid, QString affiliation, QString subscription)
{
m_jid = jid;
m_affiliation = affiliation;
m_subscription = subscription;
}
NodeSubscriber::NodeSubscriber()
{
m_jid = "";
m_affiliation = "";
m_subscription = "";
}
QString NodeSubscriber::jid() const
{
return m_jid;
}
void NodeSubscriber::setJid(const QString &jid)
{
m_jid = jid;
}
QString NodeSubscriber::affiliation() const
{
return m_affiliation;
}
void NodeSubscriber::setAffiliation(const QString &affiliation)
{
m_affiliation = affiliation;
}
QString NodeSubscriber::subscription() const
{
return m_subscription;
}
void NodeSubscriber::setSubscription(const QString &subscription)
{
m_subscription = subscription;
}
QJsonObject NodeSubscriber::toJsonObject()
{
QJsonObject object;
object.insert("jid", m_jid);
object.insert("affiliation", m_affiliation);
object.insert("subscription", m_subscription);
return object;
}
NodeSubscriber NodeSubscriber::fromJsonObject(QJsonObject object)
{
return NodeSubscriber(object.value("jid").toString(), object.value("affiliation").toString(),
object.value("subscription").toString());
}
| true |
37cadea32afff0e118ac5a9032c2b2e8f9ea3731 | C++ | heiseish/CPLib | /Graph/KirchoffTheorem.hpp | UTF-8 | 1,335 | 3.140625 | 3 | [] | no_license | #include <vector>
class KirchoffTheorem {
private:
std::vector<std::vector<double> > AdjMat, DegreeMat;
int N;
long long determinant(std::vector<std::vector<double> >& a) {
const double EPS = 1E-9;
int n = a.size();
double det = 1;
for (int i=0; i<n; ++i) {
int k = i;
for (int j=i+1; j<n; ++j)
if (abs (a[j][i]) > abs (a[k][i]))
k = j;
if (abs (a[k][i]) < EPS) {
det = 0;
break;
}
swap (a[i], a[k]);
if (i != k)
det = -det;
det *= a[i][i];
for (int j=i+1; j<n; ++j)
a[i][j] /= a[i][i];
for (int j=0; j<n; ++j)
if (j != i && abs (a[j][i]) > EPS)
for (int k=i+1; k<n; ++k)
a[j][k] -= a[i][k] * a[j][i];
}
return (long long) det;
}
public:
// 0-based
KirchoffTheorem(const std::vector<std::vector<int> >& AdjList) : N(AdjList.size()) {
AdjMat.assign(N, std::vector<double>(N, 0.0));
DegreeMat.assign(N, std::vector<double>(N, 0.0));
for(int i = 0; i < N; ++i) {
for (auto &v : AdjList[i]) {
AdjMat[i][v]++;
AdjMat[v][i]++;
}
DegreeMat[i][i] = AdjList[i].size();
}
}
long long number_of_Spanning_Tree() {
std::vector<std::vector<double> > res(N, std::vector<double>(N));
for(int i =0; i < N; ++i) {
for(int j = 0; j < N; ++j) {
res[i][j] = DegreeMat[i][j] - AdjMat[i][j];
}
}
return determinant(res);
}
}; | true |
25e390c520cfe28308a1aed4982adbb8f7c9ef0f | C++ | beshaya/bwas | /examples/bwasSerial/bwasSerial.ino | UTF-8 | 3,206 | 2.671875 | 3 | [] | no_license | #include <bwas.h>
#include <thermistor.h>
#include <pwm.h>
#include <Wire.h>
#include "Adafruit_TMP007.h"
//choose thermistor types for the 8 channels
thermistor_t thermistor_config[8];
//array for reading temperatures
int16_t temperatures[8];
Adafruit_TMP007 tmp007;
uint8_t sensor_found = 0;
void setup() {
thermistor_config[0] = THERMISTOR_NTCLG100E2103JB;
thermistor_config[1] = THERMISTOR_NTCLE400E3103H;
thermistor_config[2] = THERMISTOR_NTCALUG03A103H;
thermistor_config[3] = THERMISTOR_NTCALUG03A103H;
thermistor_config[4] = THERMISTOR_NTCALUG03A103H;
thermistor_config[5] = THERMISTOR_NTCALUG03A103H;
thermistor_config[6] = THERMISTOR_NTCLE400E3103H;
thermistor_config[7] = THERMISTOR_NTCLE400E3103H;
Serial.begin(19200);
//initialize pins
bwasInit();
//configure thermistors
configureThermistors(thermistor_config);
if (! tmp007.begin(TMP007_CFG_1SAMPLE)) {
Serial.println("No IR sensor found");
} else {
sensor_found = 1;
}
//setPwmFrequency(10,2); //set pwm frequency to 15625hz
//setPwmFrequency(11,2);
Serial.println("BWAS READY");
}
void readOne(uint8_t channel) {
printDecimal(readThermistor(channel));
}
void readTouchSwitch(uint8_t channel) {
if (channel == 1) {
Serial.print(readTouch1());
} else if (channel == 2) {
Serial.print(readTouch2());
}
}
void readCurrent(uint8_t arg) {
if (arg == 0) {
printDecimal(heaterCurrent());
} else if (arg == 1) {
printDecimal(coolerCurrent());
}
}
uint8_t parseNibble(char hex) {
if ( hex >= '0' && hex <= '9' ) {
return hex - '0';
}else if ( hex >= 'A' && hex <= 'F' ) {
return hex - 'A' + 10;
}else if ( hex >= 'a' && hex <= 'f' ) {
return hex - 'a' + 10;
}else {
return 0;
}
}
uint8_t parseHex(char hex1, char hex2) {
return (parseNibble(hex1) << 4) + parseNibble(hex2);
}
void loop() {
//wait for 4 bytes - [cmd][hex][hex]\n
if (Serial.available() >= 4) {
char cmd = Serial.read();
if (cmd == '\n') return;
char hex1 = Serial.read();
if (hex1 == '\n') return;
char hex2 = Serial.read();
if (hex2 == '\n') return;
char newline = Serial.read();
if (newline != '\n') return;
uint8_t arg = parseHex(hex1,hex2);
switch (cmd) {
case 'h':
setHeater(arg);
break;
case 'c':
setCooler(arg);
break;
case 'H':
//set heater still takes arg
setHeaterFan(arg);
break;
case 'C':
setCoolerFan(arg);
case 't':
readOne(arg);
break;
case 'r':
analogWriteRed(arg);
break;
case 'g':
analogWriteGreen(arg);
break;
case 'b':
analogWriteBlue(arg);
break;
case 'o':
coolerOff();
heaterOff();
setCoolerFan(0);
setHeaterFan(0);
break;
case 's':
readTouchSwitch(arg);
break;
//I'm out of descriptive letters for heating vs cooling
case 'I':
readCurrent(arg);
break;
case 'i':
Serial.print(tmp007.readObjTempC());
break;
default:
Serial.flush();
return;
}
Serial.println(" ");
}
}
| true |
d693b1971c59abec8353f66422c1e134572a621e | C++ | zhaozhao/leetcode | /power_of_three.cpp | UTF-8 | 438 | 3.265625 | 3 | [] | no_license | #include "catch.hpp"
bool isPowerOfThree(int n) {
if (n <= 0) return false;
if (n == 1) return true;
if (n % 3) return false;
return isPowerOfThree(n / 3);
}
TEST_CASE("is power of three") {
REQUIRE(!isPowerOfThree(0));
REQUIRE(isPowerOfThree(1));
REQUIRE(!isPowerOfThree(2));
REQUIRE(isPowerOfThree(3));
REQUIRE(!isPowerOfThree(4));
REQUIRE(!isPowerOfThree(5));
REQUIRE(isPowerOfThree(9));
} | true |
bb933e4d29654f5dcdb8947add1ef467d6ce791f | C++ | Unity-Technologies/com.unity.webrtc | /Plugin~/WebRTCPlugin/VideoFrameScheduler.h | UTF-8 | 1,487 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <rtc_base/task_utils/repeating_task.h>
#include "VideoFrame.h"
namespace unity
{
namespace webrtc
{
class VideoFrameScheduler
{
public:
VideoFrameScheduler(TaskQueueBase* queue, Clock* clock = Clock::GetRealTimeClock());
VideoFrameScheduler(const VideoFrameScheduler&) = delete;
VideoFrameScheduler& operator=(const VideoFrameScheduler&) = delete;
virtual ~VideoFrameScheduler();
// Starts the scheduler. |capture_callback| will be called whenever a new
// frame should be captured.
virtual void Start(std::function<void()> capture_callback);
// Pause and resumes the scheduler.
virtual void Pause(bool pause);
// Called after |frame| has been captured. |frame| may be set to nullptr
// if the capture request failed.
virtual void OnFrameCaptured(const VideoFrame* frame);
// Called when WebRTC requests the VideoTrackSource to provide frames
// at a maximum framerate.
virtual void SetMaxFramerateFps(int maxFramerate);
private:
absl::optional<TimeDelta> ScheduleNextFrame();
void CaptureNextFrame();
void StartRepeatingTask();
void StopTask();
std::function<void()> callback_;
bool paused_ = false;
int maxFramerate_;
RepeatingTaskHandle task_;
TaskQueueBase* queue_;
Timestamp lastCaptureStartedTime_;
Clock* clock_;
};
}
}
| true |
53956fa906c129d007777a1951872609a0aff8f6 | C++ | v1nnyc/W18-PA3 | /RodCut.cpp | UTF-8 | 1,991 | 2.921875 | 3 | [] | no_license | // CSE 101 Winter 2018, PA 3
//
// Name: Vincent Cannalla
// PID: A13006747
// Sources of Help: TODO
// Due: February 23rd, 2018 at 11:59 PM
/* to run:
make TestRodCut
build/TestRodCut testcases/rod-22.txt
*/
#ifndef __RODCUT_CPP__
#define __RODCUT_CPP__
#include "RodCut.hpp"
#include "TwoD_Array.hpp"
#include <iostream>
#include <algorithm>
int cols;
TwoD_Array<int> * arr;
std::map<int, int> * price_map;
//first length will always be 1
void firstLengthSet(){
for(int i = 0; i <= cols; i++){
if(1 <= i)
arr->at(1, i) = i;
}
}
void set(std::map<int, int> * prices, int length){
price_map = prices;
cols = length + 1;
arr = new TwoD_Array<int>(std::max_element(price_map->begin(), price_map->end(),
[](const std::pair<int, int>& p1, const std::pair<int, int>& p2) {
return p1.second < p2.second; })->second, cols);
firstLengthSet();
}
int findMax(){
int max = 0;
int value;
//go through price map
for(auto price_it = next(price_map->begin(),1); price_it != price_map->end(); price_it++){
//for each amount of cuts, determine how much money can be made
int cut_amounts = price_it->first;
for(int curr = 0; curr < cols; curr++){
if(cut_amounts > curr){
value = arr->at((prev(price_it,1))->first, curr);
max = (value > max)? max = value : max;
arr->at(cut_amounts, curr) = value;
}
if(cut_amounts < curr){
int use = (curr / cut_amounts) * price_it->second;
use += ((curr%cut_amounts) != 0)? arr->at((prev(price_it,1))->first,
(curr%cut_amounts)): 0;
value = MAX(arr->at((prev(price_it,1))->first, curr), use);
max = (value > max)? max = value : max;
arr->at(cut_amounts, curr) = value;
}
if(cut_amounts == curr){
value = MAX(arr->at((prev(price_it,1))->first, curr), price_it->second);
max = (value > max)? max = value : max;
arr->at(cut_amounts, curr) = value;
}
}
}
return max;
}
int rodcut(std::map<int, int> prices, int length) {
set(&prices, length);
return findMax();
}
#endif
| true |
20769b64b742e95cfc01d59dff3dde72b9532af0 | C++ | Garrett-Webb/Application-using-lists | /Drum_Channel_Application/Drum_Channel_Application/Node.cpp | UTF-8 | 690 | 2.953125 | 3 | [] | no_license | #include "stdafx.h"
#include "Node.h"
Node::Node()
{
name = "Default";
units = 0;
year = 0;
studentID = "xxxx-xxxx-xxxx";
gpa = 0.0;
}
Node::Node(string N, int U, int Y, string S, double G)
{
name = N;
units = U;
year = Y;
studentID = S;
gpa = G;
}
Node::~Node()
{
}
string Node::getName()
{return name;}
void Node::setName(string x)
{name = x;}
int Node::getUnits()
{return units;}
void Node::setUnits(int x)
{units = x;}
int Node::getYear()
{return year;}
void Node::setYear(int x)
{year = x;}
string Node::getStudentID()
{return studentID;}
void Node::setStudentID(int x)
{studentID = x;}
double Node::getGPA()
{return gpa;}
void Node::setGPA(double x)
{gpa = x;} | true |
4b4190f9202d9771ad7082e2b43d462cceea8ba6 | C++ | Juditmartin/ARDUINO | /Dau/CFGS_MP10_LL009_002_DAUS_JUDIT_MARTIN_VILA/CFGS_MP10_LL009_002_DAUS_JUDIT_MARTIN_VILA.ino | UTF-8 | 2,511 | 3.109375 | 3 | [] | no_license | /**********************************************************************************
** **
** Daus LED **
** **
** NOM: JUDIT MARTIN DATA: 27/03/2021 **
**********************************************************************************/
//********** Includes *************************************************************
//********** Variables ************************************************************
const int led1 = 8;
const int led2 = 7;
const int led3 = 6;
const int led4 = 5;
const int buttonPin = 2; // donar nom al pin 2 de l’Arduino
int buttonState = 0; // per guardar l’estat en que és troba el button
int temps = 500;
int randomNumber;
//********** Setup ****************************************************************
void setup()
{
Serial.begin(9600);
pinMode(8, OUTPUT);
pinMode(7, OUTPUT);
pinMode(6, OUTPUT);
pinMode(5, OUTPUT);
pinMode(buttonPin, INPUT); // definir el pin 2 com una entrada
}
//********** Loop *****************************************************************
void loop()
{
// RESET TOTS ELS LEDS
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
buttonState = digitalRead(buttonPin); //llegir l’estat del button i gardar-lo
if (buttonState == 0){
randomNumber = random(1,7);
Serial.println(randomNumber);
switch(randomNumber){
case 1:
digitalWrite(led1, HIGH);
delay(temps);
break;
case 2:
digitalWrite(led2, HIGH);
delay(temps);
break;
case 3:
digitalWrite(led1, HIGH);
digitalWrite(led3, HIGH);
delay(temps);
break;
case 4:
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
delay(temps);
break;
case 5:
digitalWrite(led1, HIGH);
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
delay(temps);
break;
case 6:
digitalWrite(led2, HIGH);
digitalWrite(led3, HIGH);
digitalWrite(led4, HIGH);
delay(temps);
break;
}
}
}
//********** Funcions *************************************************************
| true |
4262a51165be26d04b8f5d121322c2b02a899602 | C++ | Moyaro/Cpp-Primer-Note | /Practice/chapter_03/exercise_3_42.cpp | UTF-8 | 276 | 3.296875 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> ivec = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int arr[ivec.size()];
for (int i=0; i < ivec.size(); ++i)
arr[i] = ivec[i];
for (auto i : arr)
cout << i << " ";
cout << endl;
return 0;
}
| true |
c2a4b3bd70c38aa3b044703a94a3d9813b08341e | C++ | laziestcoder/Problem-Solvings | /codeforces/321b.cpp | UTF-8 | 1,565 | 2.71875 | 3 | [] | no_license | /************************************************************************/
/* Name: Towfiqul Islam */
/* uva id: 448714 */
/* email id: towfiq.106@gmail.com */
/* institute: IIUC */
/* address: Chittagong, Bangladesh */
/* */
/************************************************************************/
#include<bits/stdc++.h>
using namespace std;
template<typename P> struct Cmp //compare function or sort function for descending order 3 2 1
{
bool operator()(const P &p1, const P &p2)
{
if(p1.second < p2.second) return true; // change > to < for ascending order
if(p1.second == p2.second) return p1.first < p2.first;
return false;
}
};
pair < long long int, long long int > v[100005];
int main ()
{
long long int n,d,i,a,b,s=0,j=0,mx=0;
cin>>n>>d;
for(i=0; i<n; i++)
{
cin>>a>>b;
v[i].second=b;
v[i].first=a;
}
// sort(v,v+n, Cmp<pair<long long int, long long int> >());
sort(v,v+n);
// cout<<v[n-1].first<<endl<<v[n-1].second<<endl;
for(i=1; i<n; i++)
v[i].second+=v[i-1].second;
// cout<<s<<endl;
for(i=0;i<n;i++)
{
for(; j<n;j++)
{
if(v[j].first<v[i].first+d)
continue;
else
break;
}
s=v[j-1].second;
if(i)
s-=v[i-1].second;
mx=max(mx,s);
}
cout<<mx<<endl;
return 0;
}
| true |
c850b70806d49170d32d07ae2395d1099a040259 | C++ | lihao1992/Visual-Odometry | /VO/main.cpp | WINDOWS-1252 | 1,669 | 2.546875 | 3 | [] | no_license | #include <fstream>
#include <iostream>
#include <iomanip>
#include "visual_odometry.h"
int main(int argc, char* argv[]){
Camera* cam = new Camera(320.0, 240.0,
608.662263, 806.280756, 330.413538, 174.888673);
VisualOdometry vo(cam);
std::ofstream out("position.txt");
char text[100];
int font_face = cv::FONT_HERSHEY_PLAIN;
double font_scale = 1;
int thickness = 1;
cv::Point text_org(10, 50);
cv::namedWindow("Road facing camera", cv::WINDOW_AUTOSIZE);
cv::namedWindow("Trajectory", cv::WINDOW_AUTOSIZE);
cv::Mat traj = cv::Mat::zeros(600, 600, CV_8UC3);
double x = 0.0, y = 0.0, z = 0.0;
for (int img_id = 1; img_id < 2000; ++img_id){
std::stringstream ss;
ss << "E:/SLAMDataset/myVideo/GalaxyNote3/sequence/01/"
<< std::setw(4) << std::setfill('0') << img_id << ".png";
cv::Mat img(cv::imread(ss.str().c_str(), 0));
assert(!img.empty());
// ֡
vo.addImage(img, img_id);
cv::Mat cur_t = vo.getCurrentT();
if (cur_t.rows != 0){
x = cur_t.at<double>(0);
y = cur_t.at<double>(1);
z = cur_t.at<double>(2);
}
out << x << " " << y << " " << z << std::endl;
int draw_x = int(x) + 300;
int draw_y = int(y) + 100;
cv::circle(traj, cv::Point(draw_x, draw_y), 1, CV_RGB(255, 0, 0), 2);
cv::rectangle(traj, cv::Point(10, 30), cv::Point(580, 60), CV_RGB(0, 0, 0), CV_FILLED);
sprintf(text, "Coordinates: x = %02fm y = %02fm z = %02fm", x, y, z);
cv::putText(traj, text, text_org, font_face, font_scale, cv::Scalar::all(255), thickness, 8);
cv::imshow("Road facing camera", img);
cv::imshow("Trajectory", traj);
cv::waitKey(100);
}
delete cam;
// out.close;
getchar();
return 0;
} | true |
a486608beeb864590740412de08a27b319399f83 | C++ | niuxu18/logTracker-old | /second/download/CMake/CMake/CMake-joern/Kitware_CMake_repos_function_1381.cpp | UTF-8 | 2,377 | 2.546875 | 3 | [] | no_license | static int
archive_write_client_write(struct archive_write_filter *f,
const void *_buff, size_t length)
{
struct archive_write *a = (struct archive_write *)f->archive;
struct archive_none *state = (struct archive_none *)f->data;
const char *buff = (const char *)_buff;
ssize_t remaining, to_copy;
ssize_t bytes_written;
remaining = length;
/*
* If there is no buffer for blocking, just pass the data
* straight through to the client write callback. In
* particular, this supports "no write delay" operation for
* special applications. Just set the block size to zero.
*/
if (state->buffer_size == 0) {
while (remaining > 0) {
bytes_written = (a->client_writer)(&a->archive,
a->client_data, buff, remaining);
if (bytes_written <= 0)
return (ARCHIVE_FATAL);
remaining -= bytes_written;
buff += bytes_written;
}
return (ARCHIVE_OK);
}
/* If the copy buffer isn't empty, try to fill it. */
if (state->avail < state->buffer_size) {
/* If buffer is not empty... */
/* ... copy data into buffer ... */
to_copy = ((size_t)remaining > state->avail) ?
state->avail : (size_t)remaining;
memcpy(state->next, buff, to_copy);
state->next += to_copy;
state->avail -= to_copy;
buff += to_copy;
remaining -= to_copy;
/* ... if it's full, write it out. */
if (state->avail == 0) {
char *p = state->buffer;
size_t to_write = state->buffer_size;
while (to_write > 0) {
bytes_written = (a->client_writer)(&a->archive,
a->client_data, p, to_write);
if (bytes_written <= 0)
return (ARCHIVE_FATAL);
if ((size_t)bytes_written > to_write) {
archive_set_error(&(a->archive),
-1, "write overrun");
return (ARCHIVE_FATAL);
}
p += bytes_written;
to_write -= bytes_written;
}
state->next = state->buffer;
state->avail = state->buffer_size;
}
}
while ((size_t)remaining >= state->buffer_size) {
/* Write out full blocks directly to client. */
bytes_written = (a->client_writer)(&a->archive,
a->client_data, buff, state->buffer_size);
if (bytes_written <= 0)
return (ARCHIVE_FATAL);
buff += bytes_written;
remaining -= bytes_written;
}
if (remaining > 0) {
/* Copy last bit into copy buffer. */
memcpy(state->next, buff, remaining);
state->next += remaining;
state->avail -= remaining;
}
return (ARCHIVE_OK);
} | true |
2e1d1f6b03c7389b003fe96a94ed62bc3345155f | C++ | arunvaishy2000/cb | /DeleteNodeBST.cpp | UTF-8 | 2,039 | 3.703125 | 4 | [] | no_license | #include<iostream>
using namespace std;
class node
{
public:
int data;
node* left;
node* right;
node(int data)
{
data = data;
left = NULL;
right = NULL;
}
};
node* insertInBST(node*root,int data){
if(root==NULL){
return new node(data);
}
if(data<=root->data){
root->left = insertInBST(root->left,data);
}
else{
root->right = insertInBST(root->right,data);
}
return root;
}
void print(node*root){
if(root==NULL){
return;
}
cout<<root->data<<" ";
print(root->left);
print(root->right);
return;
}
node* deleteINBST(node *root,int val)
{
if(val<root->data)
{
root->left = deleteINBST(root->left,val);
}
if(val>root->data)
{
root->right = deleteINBST(root->right,val);
}
if(val == root->data)
{
if(root->left && root->right)
{
delete root;
return NULL;
}
else if(root->left==NULL and root->right!=NULL){
node*temp = root->right;
delete root;
return temp;
}
else if(root->right==NULL and root->left!=NULL){
node*temp = root->left;
delete root;
return temp;
}
else{
//find the inorder successor
node*temp = root->right;
while(temp->left!=NULL){
temp = temp->left;
}
root->data = temp->data;
root->right = deleteINBST(root->right,root->data);
return root;
}
}
return root;
}
int main()
{
int t;
cin>>t;
for(int z=0;z<t;z++)
{
int n;
cin>>n;
int arr1[1000];
int arr2[1000];
node* root;
for (int i = 0; i < n; i++)
{
cin>>arr1[i];
}
int m;
cin>>m;
for (int j = 0; j < m; j++)
{
cin>>arr2[j];
}
for (int i = 0; i < n; i++)
{
root = insertInBST(root,arr1[i]);
}
print(root);
for (int j = 0; j < m; j++)
{
root = deleteINBST(root,arr2[j]);
}
print(root);
}
} | true |
f905466d3a05e5fb83a97969063717620fbbace0 | C++ | alcohololismm/alcoholism | /2-bfs/[2573]broccolism.cpp | UTF-8 | 3,082 | 3.015625 | 3 | [] | no_license | #include <iostream>
#include <queue>
using namespace std;
int R, C;
int SEA[300][300];
int TMP_SEA[300][300];
bool BEEN[300][300];
/**
* returns true if the iceberg is broken, false if not
* using queue.
*/
bool is_broken()
{
queue<pair<int, int>> Q;
int num_of_iceberg = 0;
bool return_me = false;
for (int i = 0; i < R; ++i)
{
for (int j = 0; j < C; ++j)
{
if (SEA[i][j] != 0 && BEEN[i][j] != true)
{
if (num_of_iceberg > 0)
return true;
Q.push(make_pair(i, j));
int cur_row, cur_col;
while (!Q.empty())
{
cur_row = Q.front().first;
cur_col = Q.front().second;
Q.pop();
if (BEEN[cur_row][cur_col] == true)
continue;
BEEN[cur_row][cur_col] = true;
if (cur_row + 1 < R && SEA[cur_row + 1][cur_col] != 0)
Q.push(make_pair(cur_row + 1, cur_col));
if (cur_row - 1 > -1 && SEA[cur_row - 1][cur_col] != 0)
Q.push(make_pair(cur_row - 1, cur_col));
if (cur_col + 1 < C && SEA[cur_row][cur_col + 1] != 0)
Q.push(make_pair(cur_row, cur_col + 1));
if (cur_col - 1 > -1 && SEA[cur_row][cur_col - 1] != 0)
Q.push(make_pair(cur_row, cur_col - 1));
}
++num_of_iceberg;
}
}
}
for (int i = 0; i < R; ++i)
for (int j = 0; j < C; ++j)
BEEN[i][j] = false;
return false;
}
void melting(int i, int j)
{
int origin = SEA[i][j];
int how_much = 0;
if (i - 1 > -1 && SEA[i - 1][j] == 0)
++how_much;
if (i + 1 < R && SEA[i + 1][j] == 0)
++how_much;
if (j - 1 > -1 && SEA[i][j - 1] == 0)
++how_much;
if (j + 1 < C && SEA[i][j + 1] == 0)
++how_much;
if (origin - how_much < 0)
how_much = origin;
TMP_SEA[i][j] = origin - how_much;
}
bool all_melted()
{
for (int i = 0; i < R; ++i)
for (int j = 0; j < C; ++j)
if (SEA[i][j] != 0)
return false;
return true;
}
int main()
{
//get input
cin >> R >> C;
for (int i = 0; i < R; ++i)
for (int j = 0; j < C; ++j)
{
cin >> SEA[i][j];
TMP_SEA[i][j] = SEA[i][j];
}
int year = 0;
bool done = false;
while(!done)
{
++year;
if (all_melted())
{
year = 0;
break;
}
for (int i = 0; i < R; ++i)
for (int j = 0; j < C; ++j)
if (SEA[i][j] != 0)
melting(i, j);
for (int i = 0; i < R; ++i)
for (int j = 0; j < C; ++j)
SEA[i][j] = TMP_SEA[i][j];
done = is_broken();
}
cout << year << endl;
} | true |
6975f6d01396b8fd3773de5ad5970e4955e80324 | C++ | jskz/flowcpp | /main.cpp | UTF-8 | 3,591 | 3.21875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <flowcpp/flow.h>
enum class counter_action_type {
thunk,
increment,
decrement,
};
struct increment_action {
flow::any payload() const { return _payload; }
flow::any type() const { return _type; }
flow::any meta() const { return _meta; }
bool error() const { return _error; }
int _payload = {1};
counter_action_type _type = {counter_action_type::increment};
flow::any _meta;
bool _error = false;
};
struct decrement_action {
flow::any payload() const { return _payload; }
flow::any type() const { return _type; }
flow::any meta() const { return _meta; }
bool error() const { return _error; }
int _payload = {1};
counter_action_type _type = {counter_action_type::decrement};
flow::any _meta;
bool _error = false;
};
struct counter_state {
std::string to_string() { return "counter: " + std::to_string(_counter); }
int _counter{0};
};
auto reducer = [](counter_state state, flow::action action) {
int multiplier = 1;
auto type = action.type().as<counter_action_type>();
switch (type) {
case counter_action_type::decrement:
multiplier = -1;
break;
case counter_action_type::increment:
multiplier = 1;
break;
default:
break;
}
auto payload = action.payload().as<int>();
state._counter += multiplier * payload;
return state;
};
std::string to_string(counter_action_type type) {
switch (type) {
case counter_action_type::increment:
return "inc";
case counter_action_type::decrement:
return "dec";
case counter_action_type::thunk:
return "thunk";
}
}
auto logging_middleware = [](flow::basic_middleware<counter_state>) {
return [=](const flow::dispatch_t &next) {
return [=](flow::action action) {
auto next_action = next(action);
std::cout << "after dispatch: " << to_string(action.type().as<counter_action_type>()) << std::endl;
return next_action;
};
};
};
void simple_example() {
std::cout << "Start: Simple example" << std::endl;
auto store = flow::create_store_with_action<counter_state>(reducer, counter_state{}, increment_action{5});
auto disposable = store.subscribe([](counter_state state) { std::cout << state.to_string() << std::endl; });
store.dispatch(increment_action{2});
store.dispatch(decrement_action{10});
disposable.dispose(); // call dispose to stop notification prematurely
store.dispatch(increment_action{3});
store.dispatch(decrement_action{6});
std::cout << "End: Simple example " << store.state().to_string() << std::endl;
}
void thunk_middleware_example() {
std::cout << "Start: Thunk Middleware example" << std::endl;
auto store = flow::apply_middleware<counter_state>(
reducer, counter_state(), {flow::thunk_middleware<counter_state, counter_action_type>, logging_middleware});
std::cout << store.state().to_string() << std::endl;
store.dispatch(flow::thunk_action<counter_state, counter_action_type>{[&](auto dispatch, auto get_state) {
dispatch(increment_action{1});
dispatch(decrement_action{2});
dispatch(increment_action{3});
}});
store.dispatch(flow::thunk_action<counter_state, counter_action_type>{[&](auto dispatch, auto get_state) {
dispatch(increment_action{4});
dispatch(decrement_action{5});
dispatch(increment_action{6});
}});
std::cout << "End: Thunk Middleware example " << store.state().to_string() << std::endl;
}
int main() {
simple_example();
std::cout << "------------------------------" << std::endl;
thunk_middleware_example();
return 0;
}
| true |
48c02fba7779b71fb7ae416350c11e80a5ec7cff | C++ | rahulsbisen/interview | /leetcode/palindrome_interger_without_extra_space.cpp | UTF-8 | 524 | 2.765625 | 3 | [] | no_license | class Solution {
public:
bool isPalindrome(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (x < 0) return false;
int d = x;
int t = 1;
while (d = d / 10) ++t;
if (t == 1) return true;
d = x;
int n = 0;
for (int i = 0; i < t / 2; ++i) {
n = 10 * n + d % 10;
d = d / 10;
}
if (t & 1) d = d / 10;
if (d == n) return true;
return false;
}
};
| true |
f3ce1cfbbe3766e3ed754327d80ece155410e12f | C++ | alcasa04/Pac-Man-de-los-huevos | /Pacaman2/ProyectosSDL(1.07)/HolaSDL/Texture.cpp | UTF-8 | 2,041 | 3.15625 | 3 | [] | no_license | #include "Texture.h"
//inlcusiones circulares, romper el ciclo e include el.h de uno en el cpp del otro
using namespace std;
Texture::Texture()
{
//constructora dificil
}
bool Texture::loadText(const string filename,int numRows, int numCols, SDL_Renderer* render)
{
this->numRows = numRows;
this->numCols = numCols;
//this apunta a texture.h
SDL_Surface* surface = IMG_Load(filename.c_str());
//surface con el string que pase el user
if (surface != nullptr) {
//Si no ha habido un error al cargar la surface
free();
//destruimos por si hay una textura anterior (prevencion de errores)
texture = SDL_CreateTextureFromSurface(render, surface);
//textura con la surface anterior
if (texture != nullptr) {
//si no ha habido un error al cargar la textura
w = surface->w;
h = surface->h;
fw = w / numCols;
fh = h / numRows;
//variables para el numero de frames
//asignamos las variables necesarias
}
return texture != nullptr;
//si es igual es que ha habido un error en la carga
}
else
//si falla la carga de surface devolvemos false indicando que ha habido un error
return false;
}
//Carga una imagen
void Texture::free() {
SDL_DestroyTexture(texture);
texture = nullptr;
//lo dejamos vacio
w = h = 0;
//reseteo de variables
}
//Destruye una textura
void Texture::Render(SDL_Rect& dest, SDL_Renderer* render) {
srcRect.x = srcRect.y = 0;
//para coger la imagen entera
srcRect.h = h;
srcRect.w = w;
//asignamos los valores del srcRect a los que queremos
SDL_RenderCopy(render, texture, &srcRect, &dest);
//copiamos la textura para renderizarla
}
//Pinta una imagen en un rectangulo destino y en unas cordenadas
void Texture::RenderFrame(const int x, const int y, SDL_Rect& dest, SDL_Renderer* render) {
srcRect.x = x*fw;
srcRect.y = y*fh;
srcRect.w = fw;
srcRect.h = fh;
//asignamos los valores a los deseados
SDL_RenderCopy(render, texture, &srcRect, &dest);
//copiamos para poder renderizar posteriormente
}
//Pinta una imagen, dividida por frames | true |
8fd6002a428cb58a6dcd5a805113ba33f9c6ec69 | C++ | JayeshS-02/DSA-college-practical-code | /D1.cpp | UTF-8 | 1,418 | 3.734375 | 4 | [] | no_license | #include<iostream>
#define MAX 20
using namespace std;
class queue
{
public:
int q[MAX];
int front;
int rear;
queue()
{
front=-1;
rear=-1;
}
void insert();
void remove();
int q_overflow();
int q_undeflow();
void display();
};
int queue::q_overflow()
{
if(rear==MAX-1)
return 1;
else
return 0;
}
int queue::q_undeflow()
{
if(front==-1&rear==-1)
return 1;
else
return 0;
}
void queue::insert()
{
int x;
cout << "\n Enter the element : \n ";
cin >> x;
if(q_overflow()==1)
cout << "\nQueue is full \n";
else
{
if(front==-1&&rear==-1)
{
front=0;
rear=0;
q[rear]=x;
}
else
{
rear++;
q[rear]=x;
}
}
}
void queue::remove()
{
int x;
if(q_undeflow()==1)
cout << "\n Queue is empty \n";
else
{
if(front==rear)
{
x=q[front];
front=-1;
rear=-1;
}
else
{
x=q[front];
front++;
}
cout << x << " is deleted \n";
}
}
void queue::display()
{
int i;
if(q_undeflow()==1)
cout << "\n Queue is empty \n";
else
{
for(i=front;i<=rear;i++)
{
cout << "\t" << q[i];
}
}
}
int main()
{
int ch;
char c;
queue q;
do{
cout << "\n1.Add job \n2.display Queue \n3. delete job\n";
cout << "Enter your choice \n";
cin >> ch;
switch(ch)
{
case 1:
q.insert();
break;
case 2:
q.display();
break;
case 3:
q.remove();
break;
}
cout<< "\nDo you want to continue\n";
cin >> c;
}while(c=='y'||c=='Y');
return 0;
} | true |
8131d5a3c5882daa303a181676545fbbac573ac9 | C++ | silicondosa/AnimatLabPublicSource | /Libraries/RoboticsAnimatSim/RbStructure.h | UTF-8 | 825 | 2.515625 | 3 | [] | no_license | /**
\file RbStructure.h
\brief Declares the vortex structure class.
**/
#pragma once
namespace RoboticsAnimatSim
{
/**
\namespace RoboticsAnimatSim::Environment
\brief Classes for the virtual world simulation that use the vortex physics engine.
**/
namespace Environment
{
/**
\brief Vortex physical structure implementation.
\author dcofer
\date 4/25/2011
**/
class ROBOTICS_PORT RbStructure : public AnimatSim::Environment::Structure, public RbMovableItem
{
protected:
Structure *m_lpThisST;
RbMovableItem *m_lpRbBody;
virtual void SetThisPointers();
public:
RbStructure();
virtual ~RbStructure();
virtual void Body(RigidBody *lpBody);
virtual void Create();
virtual void ResetSimulation();
};
} // Environment
} //RoboticsAnimatSim
| true |
8d416a2a255990b40db580a4a5ce27fb4337e652 | C++ | xiazhiyiyun/C-Primer | /Test/testEnumAddr.cpp | UTF-8 | 184 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <cstring>
using namespace std;
enum color{red,green,blue};
int main()
{
int i;
cout << &i << endl;
color c;
c=green;
cout<<&c<<endl;
}
| true |
c383e2998fcbb31716e696cdbaff448e6fbc7429 | C++ | GustaFreitas/Cpp | /Prova Oficial 02/Gustavo Luiz de Freitas (Questão 02).cpp | UTF-8 | 2,532 | 2.890625 | 3 | [] | no_license | #include <stdlib.H>
#include <stdio.H>
struct vendedor
{
int Cod, Ven;
};
int main ()
{
char Opc;
int Tot_Ven, Qtd = 0, Tie_1 = 0, Tie_2 = 0, Tie_3 = 0, Cod_Mai = 0;
float Sal = 0, Com = 0, Tot_Fol = 0, Med_1 = 0, Med_2 = 0, Med_3 = 0, Med_Ger = 0, Mai = 0;
struct vendedor v;
do
{
system ("cls");
printf ("Digite o codigo do funcionario: ");
scanf ("%d", &v.Cod);
printf ("Digite o valor total de vendas do funcionario: ");
scanf ("%d", &v.Ven);
if (v.Ven <= 10)
{
//tier 1
Sal = 700;
Med_1 = Med_1 + v.Ven;
Tie_1++;
Med_Ger = Med_Ger + v.Ven;
Qtd++;
printf ("\nO vendedor com o codigo numero %d pertence ao grupo 1.", v.Cod);
printf ("\nO salario total do vendedor e de: R$%.2f", Sal);
}
else if (v.Ven > 10 && v.Ven <= 20)
{
//tier 2
Sal = 1000;
if (v.Ven > 16)
{
Com = v.Ven - 16;
Com = 21 * Com;
Sal = Sal + Com;
}
Med_2 = Med_2 + v.Ven;
Tie_2++;
Med_Ger = Med_Ger + v.Ven;
Qtd++;
printf ("\nO vendedor com o codigo numero %d pertence ao grupo 2.", v.Cod);
printf ("\nO salario total do vendedor e de: R$%.2f", Sal);
}
else if (v.Ven > 20)
{
//tier 3
Sal = 2000;
if (v.Ven > 30)
{
Com = v.Ven - 30;
Com = 30 * Com;
Sal = Sal + Com;
}
Med_3 = Med_3 + v.Ven;
Tie_3++;
Med_Ger = Med_Ger + v.Ven;
printf ("%f", Med_3);
Qtd++;
printf ("\nO vendedor com o codigo numero %d pertence ao grupo 3.", v.Cod);
printf ("\nO salario total do vendedor e de: R$%.2f", Sal);
}
Tot_Fol = Tot_Fol + Sal;
Tot_Ven = Tot_Ven + v.Ven;
if (Sal > Mai)
{
Mai = Sal;
Cod_Mai = v.Cod;
}
printf ("\n\nDeseja cadastrar um novo vendedor? (S/N) -");
fflush (stdin);
scanf ("%c", &Opc);
}
while (Opc == 's');
Med_1 = Med_1 / Tie_1;
Med_2 = Med_2 / Tie_2;
Med_3 = Med_3 / Tie_3;
Med_Ger = Med_Ger / Qtd;
system ("cls");
printf ("Programa executado %d vezes.", Qtd);
printf ("\nO total da folha de pagamento da empresa foi de: %.2f", Tot_Fol);
printf ("\nO total de vendas da empresa foi de: %d", Tot_Ven);
printf ("\nA media de vendas do grupo 1 foi de: %.1f", Med_1);
printf ("\nA media de vendas do grupo 2 foi de: %.1f", Med_2);
printf ("\nA media de vendas do grupo 3 foi de: %.1f", Med_3);
printf ("\nA media geral de vendas foi de: %.1f", Med_Ger);
printf ("\nO vendedor de maior salario foi o vendedor com o codigo de numero %d. Total do salario: %.2f", Cod_Mai, Mai);
}
| true |
f1503be9980a20c8453320d7bdcc2c7b702c1d39 | C++ | trojancode95/Data-Structure-and-Algorithm | /Trie/Longest_Common_Prefix.cpp | UTF-8 | 1,619 | 3.171875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
class Node{
public:
char data;
unordered_map<char,Node*>children;
bool terminal;
int cnt;
Node(char d){
data=d;
terminal=false;
cnt=0;
}
};
class Trie{
public:
Node*root;
Trie(){
root=new Node('\0');
}
void insert(string s){
Node*temp=root;
for(int i=0;s[i]!='\0';i++){
char ch=s[i];
if(temp->children.count(ch)){
temp=temp->children[ch];
(temp->cnt)++;
}
else{
Node*n=new Node(ch);
temp->children[ch]=n;
temp=n;
(temp->cnt)++;
}
}
temp->terminal=true;
}
bool find(string s){
Node*temp=root;
for(int i=0;s[i]!='\0';i++){
char ch=s[i];
if(temp->children.count(ch)==0)
return false;
else
temp=temp->children[ch];
}
return temp->terminal;
}
};
string longestPrefix(Trie t,string s,int n){
Node*temp=t.root;
int length=s.length();
string ans="";
for(int i=0;s[i]!='\0';i++){
if(temp->children[s[i]]->cnt==n){
ans+=s[i];
temp=temp->children[s[i]];
}
else
break;
}
return ans;
}
int main(){
Trie t;
int n;
cin>>n;
string s[n];
// cin.get();
for(int i=0;i<n;i++){
cin>>s[i];
t.insert(s[i]);
}
cout<<longestPrefix(t,s[0],n)<<endl;
return 0;
}
| true |
cd6c4f0d1ce0651dda83b77f8d8e486082994fdd | C++ | i-am-mike-m/LeetCode | /832.cpp | UTF-8 | 786 | 3.453125 | 3 | [] | no_license | /***********************
This is fairly straightforward on reversing the rows.
To invert using abs(A[row][i] - 1) will take all 1's to 0's and all 0's to -1's, which become 1's.
O(n^2) time - assuming that n x n size is a requirment
O(n) space
***********************/
class Solution {
public:
vector<vector<int>> flipAndInvertImage(vector<vector<int>>& A) {
for (int row = 0; row < A.size(); row++) {
for (int i = 0, j = A[row].size()-1; i < j; i++, j--) {
int temp = A[row][i];
A[row][i] = A[row][j];
A[row][j] = temp;
}
for (int i = 0; i < A[row].size(); i++) {
A[row][i] = abs(A[row][i] - 1);
}
}
return A;
}
}; | true |