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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1296308e769346bfc2474a8192bedb6ad94d5c0a | C++ | Heartran/HOD | /Source/GUI/DraggableLabel.cpp | SHIFT_JIS | 2,373 | 2.65625 | 3 | [] | no_license | #include"DraggableLabel.h"
#include"Manager.h"
#include<GameLib/Graphics/Manager.h>
#include<GameLib/GameLib.h>
#include<GameLib/Framework.h>
#include<string.h>
#include<assert.h>
#include<GameLib/Input/Mouse.h>
#include<algorithm>
using GameLib::Math::Vector2;
namespace GUI {
DraggableLabel::DraggableLabel(
int x, int y,
int sizeX, int sizeY,
int minX, int maxX,
int minY, int maxY,
unsigned int color,
unsigned int fontColor,
float u0, float v0,
float u1, float v1 )
:Label(
x, y,
sizeX, sizeY,
color,
fontColor,
u0, v0,
u1, v1
),
mClickedX(0), mClickedY(0),
mClickedOffsetX(0), mClickedOffsetY(0),
mIsDragging(false),
mIsDropped(false),
mArea( minX, minY, maxX, maxY )
{}
DraggableLabel::~DraggableLabel(){
}
void DraggableLabel::update(){
GameLib::Input::Mouse m;
const int &x = m.x();
const int &y = m.y();
mIsDropped = false;
//windowŃNbNƂ
if( m.isTriggered(m.BUTTON_LEFT) ){
//}EXJ\[{^ɂ邩H
if( isHover(x,y) )
{
//draggingԂɈڍs
mIsDragging = true;
mClickedX = x;
mClickedY = y;
mClickedOffsetX = x-mX;
mClickedOffsetY =y-mY;
}
}
//dragging
if( mIsDragging ) {
//ꍇ
if( m.isReleased( m.BUTTON_LEFT ) ) {
mIsDropped = true;
mIsDragging = false;
} else {
}
}
if( mIsDragging ) {
GameLib::Input::Mouse m;
//int x = std::min( std::max( mArea.left, m.x()-mClickedOffsetX ), mArea.right );
//int y = std::min( std::max( mArea.top, m.y()-mClickedOffsetY ), mArea.bottom );
//setPos( x, y);
setPos( m.x()-mClickedOffsetX, m.y()-mClickedOffsetY );
}
if( mIsDropped ) {
GameLib::Input::Mouse m;
//int x = std::min( std::max( mArea.left, m.x()-mClickedOffsetX ), mArea.right );
//int y = std::min( std::max( mArea.top, m.y()-mClickedOffsetY ), mArea.bottom );
//setPos( x, y);
setPos( m.x()-mClickedOffsetX, m.y()-mClickedOffsetY );
}
Label::update();
}
void DraggableLabel::draw( Manager* mngr ){
Label::draw( mngr );
}
//void DraggableLabel::limitPosition(){
// mX = std::min( std::max( mArea.left, mX ), mArea.right );
// mY = std::min( std::max( mArea.top, mY ), mArea.bottom );
//}
void DraggableLabel::setPos( int x, int y ){
mX = std::min( std::max( mArea.left, x ), mArea.right );
mY = std::min( std::max( mArea.top, y ), mArea.bottom );
}
}//namespace GUI | true |
d5474693a4340f3aaf8eedd24214817bdd32a92f | C++ | Paul-St-Young/cppDFT | /src/Interface/InputManager.h | UTF-8 | 419 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef _INPUTMANAGER_H
#define _INPUTMANAGER_H
#include <map>
#include <vector>
typedef std::map<std::string,std::string> Input;
class InputManager{
std::map<std::string,Input> _inputs;
std::string _remove_comments(std::string input);
void _strip_empties(std::vector<std::string>& vec);
public:
InputManager(std::string filename);
Input operator[](std::string input){ return _inputs[input]; };
};
#endif
| true |
815b142b350400c4570f30acb3c8d95a50256ca0 | C++ | chenhao07023/algorithm017 | /Week_04/canJump.cpp | UTF-8 | 537 | 2.53125 | 3 | [] | no_license | #include <string>
#include <stdio.h>
#include <vector>
#include <assert.h>
#include <unordered_set>
#include <queue>
using namespace std;
class Solution {
public:
bool canJump(vector<int>& nums) {
int farest = 0;
int size = nums.size();
for (int i = 0; i < size; i++)
{
if (i <= farest)
{
farest = max(farest, i+nums[i]);
if (farest >= size-1) return true;
}
}
return false;
}
};
int main() {
return 0;
} | true |
b6918dbd65d8f52a2fb48ada07ba148acc2f093d | C++ | robatbobat/labs | /laba1_double_linked_list/dlist.cpp | UTF-8 | 602 | 2.65625 | 3 | [] | no_license | using namespace std;
#include "dlist.h"
int main()
{
cList list;
list.push(10);
list.push(20);
list.push(30);
list.push(40);
list.push(50);
list.push(99);
list.list_elements_forward();
list.insert_before(1,10);
list.insert_before(5,20);
list.insert_before(90,99);
list.list_elements_forward();
list.insert_past(25,20);
list.insert_past(2,40);
list.insert_past(100,99);
list.list_elements_forward();
list.delete_element(20);
list.delete_element(100);
list.delete_element(99);
list.delete_element(1);
list.list_elements_forward();
list.list_elements_backward();
return 0;
} | true |
5b5141be132d2236862f0db51791232d06917579 | C++ | yjbong/problem-solving | /boj/11722/11722.cpp | UTF-8 | 437 | 2.96875 | 3 | [] | no_license | #include <cstdio>
int n; // 수열의 길이
int a[1000];
int d[1000]; // d[i]=a[i]를 마지막으로 하는 최장 감소 수열의 길이
int main(void){
scanf("%d",&n);
for(int i=0; i<n; i++) scanf("%d",&a[i]);
for(int i=0; i<n; i++) d[i]=1;
for(int i=0; i<n; i++)
for(int j=0; j<i; j++)
if(a[i]<a[j] && d[i]<d[j]+1) d[i]=d[j]+1;
int ans=0;
for(int i=0; i<n; i++) if(ans<d[i]) ans=d[i];
printf("%d\n",ans);
return 0;
} | true |
91a89439de18d17682757787689c6d655b3e61ae | C++ | jovetickop/Xiao2Jie_Book_Coding-Interviews_Code | /面试题38 : 数字在排序数组中出现的次数.cpp | UTF-8 | 1,581 | 3.8125 | 4 | [] | no_license | //如果直接遍历数组,则时间复杂度是O(n);
//如果用二分法分别找出第一次出现的位置和最后一次的位置,再相减,时间复杂度就是O(log(n));
#include<iostream>
using namespace std;
int GetFirstK(int Array[], int length, int K, int start, int end)
{
if(Array == NULL || length <= 0 || start<0 || end<0 || start>end)
return -1;
int mid = (start+end)/2;
int midData = Array[mid];
if(midData == K)
{
if((mid > 0 && Array[mid-1] < K) || mid == 0)
return mid;
else
return GetFirstK(Array, length, K, start, mid-1);
}
else if(midData > K)
{
return GetFirstK(Array, length, K, start, mid-1);
}
else
{
return GetFirstK(Array, length, K, mid+1, end);
}
}
int GetLastK(int Array[], int length, int K, int start, int end)
{
if(Array == NULL || length <= 0 || start<0 || end<0 || start>end)
return -1;
int mid = (start+end)/2;
int midData = Array[mid];
if(midData == K)
{
if((mid < length-1 && Array[mid+1] > K) || mid == length-1)
return mid;
else
return GetLastK(Array, length, K, mid+1, end);
}
else if(midData > K)
{
return GetLastK(Array, length, K, start, mid-1);
}
else
{
return GetLastK(Array, length, K, mid+1, end);
}
}
int GetNumberOfK(int Array[], int length, int K)
{
if(Array == NULL || length <= 0)
return -1;
int first = GetFirstK(Array, length, K, 0, length-1);
int last = GetLastK(Array, length, K, 0, length-1);
if(first > -1 && last > -1)
return last-first+1;
else
return 0;
}
int main()
{
int a[]={1,2,3,3,3,3,4,4,5,6,7};
cout<<GetNumberOfK(a, 10, 4)<<endl;
}
| true |
5b0e6347c81a2a72548280c64d445d4865acc0f0 | C++ | Vijay-Giri/Compiler-Design-ICOD632C-Assignment-1 | /3.cpp | UTF-8 | 3,123 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void e_prime();
void e();
void t_prime();
void t();
void f();
void advance();
char ip_sym[15],ip_ptr=0,op[50],tmp[50];
int n=0;
void advance()
{
ip_ptr++;
}
void f()
{
int i,n=0,l;
for(i=0;i<=strlen(op);i++)
if(op[i]!='e')
tmp[n++]=op[i];
strcpy(op,tmp);
l=strlen(op);
for(n=0;n < l && op[n]!='F';n++);
if((ip_sym[ip_ptr]=='i')||(ip_sym[ip_ptr]=='I'))
{
op[n]='i';
printf("E=%-25s",op);
printf("F->i\n");
advance();
}
else
{
if(ip_sym[ip_ptr]=='(')
{
advance();
e();
if(ip_sym[ip_ptr]==')')
{
advance();
i=n+2;
do
{
op[i+2]=op[i];
i++;
}while(i<=l);
op[n++]='(';
op[n++]='E';
op[n++]=')';
printf("E=%-25s",op);
printf("F->(E)\n");
}
}
else
{
printf("syntax error\n");
exit(1);
}
}
}
void t(){
int i,n=0,l;
for(i=0;i<=strlen(op);i++)
if(op[i]!='e')
tmp[n++]=op[i];
strcpy(op,tmp);
l=strlen(op);
for(n=0;n < l && op[n]!='T';n++);
i=n+1;
do
{
op[i+2]=op[i];
i++;
}while(i < l);
op[n++]='F';
op[n++]='T';
op[n++]=39;
printf("E=%-25s",op);
printf("T->FT'\n");
f();
t_prime();
}
void e_prime()
{
int i,n=0,l;
for(i=0;i<=strlen(op);i++)
if(op[i]!='e')
tmp[n++]=op[i];
strcpy(op,tmp);
l=strlen(op);
for(n=0;n < l && op[n]!='E';n++);
if(ip_sym[ip_ptr]=='+')
{
i=n+2;
do
{
op[i+2]=op[i];
i++;
}while(i<=l);
op[n++]='+';
op[n++]='T';
op[n++]='E';
op[n++]=39;
printf("E=%-25s",op);
printf("E'->+TE'\n");
advance();
t();
e_prime();
}
else
{
op[n]='e';
for(i=n+1;i<=strlen(op);i++)
op[i]=op[i+1];
printf("E=%-25s",op);
printf("E'->e");
}
}
void e()
{
strcpy(op,"TE'");
printf("E=%-25s",op);
printf("E->TE'\n");
t();
e_prime();
}
void t_prime()
{
int i,n=0,l;
for(i=0;i<=strlen(op);i++)
if(op[i]!='e')
tmp[n++]=op[i];
strcpy(op,tmp);
l=strlen(op);
for(n=0;n < l && op[n]!='T';n++);
if(ip_sym[ip_ptr]=='*')
{
i=n+2;
do
{
op[i+2]=op[i];
i++;
}while(i < l);
op[n++]='*';
op[n++]='F';
op[n++]='T';
op[n++]=39;
printf("E=%-25s",op);
printf("T'->*FT'\n");
advance();
f();
t_prime();
}
else
{
op[n]='e';
for(i=n+1;i<=strlen(op);i++)
op[i]=op[i+1];
printf("E=%-25s",op);
printf("T'->e\n");
}
}
int main()
{
int i;
printf("Right Recursive Productions:\n");
printf("\n\t\t E->TE' \n\t\t E'->+TE'|e \n\t\t T->FT' ");
printf("\n\t\t T'->*FT'|e \n\t\t F->(E)|i");
printf("\n Enter the input expression:");
cin>>ip_sym;
printf("Expressions");
printf("\t Sequence of production rules\n");
e();
for(i=0;i < strlen(ip_sym);i++)
{
if(ip_sym[i]!='+'&&ip_sym[i]!='*'&&ip_sym[i]!='('&&
ip_sym[i]!=')'&&ip_sym[i]!='i'&&ip_sym[i]!='I')
{
printf("\nSyntax error");
break;
}
for(i=0;i<=strlen(op);i++)
if(op[i]!='e')
tmp[n++]=op[i];
strcpy(op,tmp);
printf("\nE=%-25s",op);
}
return 0;
}
| true |
834299e27fb56256eb93f25c8529db814f8fcaa6 | C++ | L-dana/limited | /BinarySearch_recursion.cpp | UHC | 893 | 3.421875 | 3 | [] | no_license | #include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int* s;
int location(int low, int high,int node) {
int mid;
if (low > high)return 0;
else {
mid = (low+high) / 2;
if (node == s[mid])return mid;
else if (node < s[mid])return location(low, mid-1, node); //left
else return location(mid+1, high, node); //right
}
}
int main() {
int node,size;
int low, high;
int answer_location;
s = (int*)malloc(sizeof(int) * 1);
cout << "ũ ã Է";
cin >> size;
cin >> node;
s = (int*)realloc(s,sizeof(int)*(size + 1));
s[0] = 0;
cout << "迭 Է()";
for (int i = 1; i <= size; i++) {
cin >> s[i];
}
cout << " Է ";
low = 1;
high =size;
cout << endl<<" ġ"<< location(low,high,node);
return 0;
} | true |
08e6fb009b67022dc2cf9d9774bc0372b7bac400 | C++ | lengxi/Strategy | /src/Queue.h | UTF-8 | 486 | 2.578125 | 3 | [] | no_license | // Queue.h: interface for the Queue class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(QUEUE)
#define QUEUE
#ifndef UNIT
#include "Unit.h"
#endif
#include "time.h"
class Queue
{
public:
void SetUnit(char buildtype);
string GetUnit();
//char GetUnit(int type);
void SetTime(int set);
int GetTime();
void SubTimer(int set);
int GetTimer();
Queue();
virtual ~Queue();
private:
int timer;
int ltime;
string unitname;
};
#endif | true |
83d08c2bf733ece2571dae72060d3741798902ac | C++ | jasonblog/note | /c++/data/cpp-concurrency-in-action/src/ch6/queuelist.cpp | UTF-8 | 1,958 | 3.859375 | 4 | [] | no_license | #include <iostream>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
template <typename T>
class queue
{
private:
struct node {
std::shared_ptr<T> data;
std::unique_ptr<node> next;
};
std::mutex head_mutex;
std::unique_ptr<node> head;
std::mutex tail_mutex;
node* tail;
node* get_tail()
{
std::lock_guard<std::mutex> tail_lock(tail_mutex);
return tail;
}
std::unique_ptr<node> pop_head()
{
std::lock_guard<std::mutex> head_lock(head_mutex);
if (head.get() == get_tail()) {
return nullptr;
}
std::unique_ptr<node> old_head = std::move(head);
head = std::move(old_head->next);
return old_head;
}
public:
queue(): head(new node), tail(head.get())
{}
queue(const queue& other) = delete;
queue& operator=(const queue& other) = delete;
std::shared_ptr<T> try_pop()
{
std::unique_ptr<node> old_head = pop_head();
return old_head ? old_head->data : std::shared_ptr<T>();
}
void push(T new_value)
{
std::shared_ptr<T> new_data(
std::make_shared<T>(std::move(new_value)));
std::unique_ptr<node> p(new node);
node* const new_tail = p.get();
std::lock_guard<std::mutex> tail_lock(tail_mutex);
tail->data = new_data;
tail->next = std::move(p);
tail = new_tail;
}
};
void push(queue<int>* q)
{
for (int i = 0; i < 10; ++i) {
printf("pushing %d\n", i);
q->push(i);
}
}
void pop(queue<int>* q)
{
int i = 0;
while (true) {
if (std::shared_ptr<int> p = q->try_pop()) {
printf("poping %d\n", *p);
++i;
}
if (i == 10) {
break;
}
}
}
int main()
{
queue<int> q;
std::thread th1(push, &q);
std::thread th2(pop, &q);
th1.join();
th2.join();
return 0;
}
| true |
5bd064d266d6a4b14f52e1e71ce79775a72ef8c0 | C++ | s6tsschu/VRLAB | /Source/VR/Parser.cpp | UTF-8 | 4,896 | 2.703125 | 3 | [] | no_license | // Fill out your copyright notice in the Description page of Project Settings.
#include "VR.h"
#include "Parser.h"
#include <algorithm>
Parser::Parser()
{
}
std::vector<std::pair<float, std::map<std::string, FTransObject>>> Parser::parseXml(std::string url)
{
std::vector<std::pair<float, std::map<std::string, FTransObject>>> animation;
std::vector<float> test;
std::ifstream File(url);
std::string time("\"time\": ");
std::string leftHand("\"LeftHand\"");
std::string rightHand("\"RightHand\"");
std::string hmd("\"HMD\"");
int offsetTime = 3;
if (File.is_open()) {
std::string line;
std::getline(File, line);
while (!File.eof())
{
size_t dt = line.find(time);
if (dt != std::string::npos)
{
size_t numberEnd = line.find(",");
int numberSize = numberEnd - (dt + time.length());
std::string timeStamp = line.substr(dt + time.length() , numberSize);
float timeValue = atof(timeStamp.c_str());
getline(File, line);
std::map<std::string, FTransObject> map;
while (line.find("]") == std::string::npos) {
if (line.find(leftHand) != std::string::npos) {
FTransObject obj;
parseRotTransScale(File, obj);
map["LeftHand"] = obj;
}
if (line.find(rightHand) != std::string::npos) {
FTransObject obj;
parseRotTransScale(File, obj);
map["RightHand"] = obj;
}
if (line.find(hmd) != std::string::npos) {
FTransObject obj;
parseRotTransScale(File, obj);
map["HMD"] = obj;
}
getline(File, line);
}
animation.push_back(std::pair<float, std::map<std::string, FTransObject>>(timeValue, map));
}
getline(File, line);
}
}
return animation;
}
Parser::~Parser()
{
}
void Parser::parseRotTransScale(std::ifstream & File, FTransObject & obj)
{
std::string line;
getline(File, line);
while (line.find("{") == std::string::npos) {
getline(File, line);
}
while (line.find("}") == std::string::npos) {
if (line.find("rotation") != std::string::npos) {
parseRotation(File, obj);
}
if (line.find("translation") != std::string::npos) {
parseTranslation(File, obj);
}
if (line.find("scale3D") != std::string::npos) {
parseScale(File, obj);
}
getline(File, line);
}
}
void Parser::parseRotation(std::ifstream & File, FTransObject & obj)
{
parseXYZW(File, obj.rotX, obj.rotY, obj.rotZ,obj.rotW);
}
void Parser::parseTranslation(std::ifstream & File, FTransObject & obj)
{
parseXYZ(File, obj.transX, obj.transY, obj.transZ);
}
void Parser::parseScale(std::ifstream & File, FTransObject & obj)
{
parseXYZ(File, obj.scaleX, obj.scaleY, obj.scaleZ);
}
void Parser::parseXYZ(std::ifstream & File, float & x, float & y, float & z)
{
std::string line;
std::string X("x\": "), Y("y\": "), Z("z\": ");
getline(File, line);
while (line.find("}") == std::string::npos) {
size_t pos = line.find("x");
if (pos != std::string::npos) {
int length = line.find(",") - (pos + X.length());
std::string value = line.substr(pos + X.length(), length);
x = std::atof(value.c_str());
}
pos = line.find("y");
if (pos != std::string::npos) {
int length = line.find(",") - (pos + Y.length());
std::string value = line.substr(pos + Y.length(), length);
y = std::atof(value.c_str());
}
pos = line.find("z");
if (pos != std::string::npos) {
std::string value = line.substr(pos + Z.length());
value.erase(std::remove(value.begin(), value.end(), ','), value.end());
value.erase(std::remove(value.begin(), value.end(), '\r'), value.end());
z = std::atof(value.c_str());
}
getline(File, line);
}
}
void Parser::parseXYZW(std::ifstream & File, float & x, float & y, float & z, float & w) {
std::string line;
std::string X("x\": "), Y("y\": "), Z("z\": "), W("w\": ");
getline(File, line);
while (line.find("}") == std::string::npos) {
size_t pos = line.find("x");
if (pos != std::string::npos) {
int length = line.find(",") - (pos + X.length());
std::string value = line.substr(pos + X.length(), length);
x = std::atof(value.c_str());
}
pos = line.find("y");
if (pos != std::string::npos) {
int length = line.find(",") - (pos + Y.length());
std::string value = line.substr(pos + Y.length(), length);
y = std::atof(value.c_str());
}
pos = line.find("z");
if (pos != std::string::npos) {
std::string value = line.substr(pos + Z.length());
value.erase(std::remove(value.begin(), value.end(), ','), value.end());
value.erase(std::remove(value.begin(), value.end(), '\r'), value.end());
z = std::atof(value.c_str());
}
pos = line.find("w");
if (pos != std::string::npos) {
std::string value = line.substr(pos + W.length());
value.erase(std::remove(value.begin(), value.end(), ','), value.end());
value.erase(std::remove(value.begin(), value.end(), '\r'), value.end());
w = std::atof(value.c_str());
}
getline(File, line);
}
} | true |
07ca33743dbb584b8d4f006fa41e24239fbbddc9 | C++ | eschild2/test | /lib/StringList.cpp | UTF-8 | 2,200 | 3.75 | 4 | [] | no_license | #include <stdio.h>
#include <string.h>
namespace ece309{
// class for a list node
class ListNode{
private:
char* str;
ListNode *next;
public:
ListNode(char* a){
str = a;
next = 0;
}
ListNode* getNext() {
return next;
}
void setNext(ListNode *n){
next = n;
}
char* getStr() {
return str;
}
};
// class for the list of strings
class listOfStrings{
private:
ListNode *head;
ListNode *tail;
public:
listOfStrings();
bool remove(char* a);
bool empty();
void push_back(char* a);
char* get(int n);
int length();
char* remove_front();
~listOfStrings();
};
//initializes blank list of strings
listOfStrings::listOfStrings(){
head = 0;
tail = 0;
}
bool listOfStrings::remove(char* a){
if(!empty()){
a = head->getStr();
ListNode *tmp = head->getNext();
delete head;
head = tmp;
if(tmp == NULL)
tail = NULL;
return true;
}
return false;
}
// allows you to add another string to the list
void listOfStrings::push_back(char* p){
ListNode *node = new ListNode(p);
if(head == 0){
head = node;
tail = node;
}
else{
tail->setNext(node);
tail = node;
}
}
bool listOfStrings::empty(){
return head==NULL;
}
// returns the string at the nth term on the list
char* listOfStrings::get(int n){
int x = 1;
ListNode* temp1;
ListNode* temp2 = head;
while(x != n){
if(x == 1){
temp1 = head;
temp2 = head->getNext();
x++;
}
else{
temp1 = temp2;
temp2 = temp1->getNext();
x++;
}
}
return temp2->getStr();
}
int listOfStrings::length(){
int n = 0;
ListNode* temp1 = head;
while(temp1 != 0){
n++;
temp1 = temp1->getNext();
}
return n;
}
// removes the head and returns string that was removed
char* listOfStrings::remove_front(){
ListNode* temp;
ListNode* temp2;
if(head == 0){
return 0;
}
temp = head;
temp2 = head->getNext();
head = temp2;
return temp->getStr();
}
//destructor
listOfStrings::~listOfStrings(){
while(!(empty())){
ListNode* next = head->getNext();
remove(head->getStr());
head = next;
}
}
}
| true |
b3e65f12b1de291a9c637678010d3ae611d46279 | C++ | jetpotion/HEAPCPP | /Heap/Heap.hpp | UTF-8 | 2,338 | 3.4375 | 3 | [] | no_license | #ifndef HEAP_HPP
#define HEAP_HPP
#include <vector>
#include <array>
template<typename T>
class Heap
{
private:
std::vector<T>data;
bool ismax = true;
//These should be include functions that dont modify any of the data
constexpr int Parent(int i) const;
constexpr int Left(int i) const;
constexpr int Right(int i) const;
void Heapify(int i, bool turn_max);
public:
//Shall have a default construct
Heap() = default;
//Shall have a constructor taking in vector
explicit constexpr Heap(const std::vector<T>& arr);
//Takies in a explicit array of point type
explicit constexpr Heap(const T* arr);
//Takes in a explicit array array
template<std::size_t SIZE>
explicit constexpr Heap(const std::array<T, SIZE>& array);
//Take into two ranges of variable types
template<typename InputIterator>
constexpr Heap(const InputIterator& start, const InputIterator& end);
//Take in initalizer list
constexpr Heap(const std::initializer_list<T>& list);
//Copy construction
Heap(const Heap<T>& target);
//Move constructor
Heap(Heap<T>&& source);
//Assignment operator
Heap<T>& operator =(const Heap<T>& target);
//Move semantics
Heap<T>& operator=(Heap<T>&& source);
//Allow the user to switch between heaps if they want to Max heap they make Max heap (Pass into heapify to notify that we are max heapify
void MakeMaxHeap();
//Allow the user to swtich between heaps if they want a Min then they make min heap(Pass into heapify to notify that we want to mainatain heapfify
void MakeMinHeap();
T& top(); //Gets the top of the array and eliminates it. And then reheapify according to if its a min heap or a max heap
T& remove();// Remove top element and return it
//Insert element accordinat to its position.Inserts at the end and then heapify
void Insert(T& element);
//Increase the key
void KeyChange(int& x, int newval);
};
#ifndef HEAP_CPP
#include "Heap.cpp"
#endif //
//Shifting right by 1
template<typename T>
inline constexpr int Heap<T>::Parent(int i) const
{
return i >> 1;
}
//Shifting left by one
template<typename T>
inline constexpr int Heap<T>::Left(int i) const
{
return i << 1;
}
//Shifting left by 1 and adding one
template<typename T>
inline constexpr int Heap<T>::Right(int i) const
{
return (i << 1) + 1;
}
#endif | true |
9f72d79ac291daef045a981618389bdcb9d9c3c9 | C++ | kentlc/camera_module | /include/pipes/tx_pipe.hpp | UTF-8 | 387 | 2.609375 | 3 | [] | no_license | /**
* @file tx_pipe.hpp
* @brief Transmitter pipe class definition.
*/
#ifndef DEF_TX_PIPE_HPP
#define DEF_TX_PIPE_HPP
#include <fstream>
#include <string>
class TXPipe {
public:
TXPipe(const std::string &pipefile);
~TXPipe();
void send(const char *data, int dataSize);
private:
std::filebuf *m_pipe;
};
#endif /* DEF_TX_PIPE_HPP */
| true |
a45c728cce0f49f01434d28606df0e38c3580390 | C++ | xodud001/coding-test-study | /sally/dynamic_programming_1/1106_호텔.cpp | UTF-8 | 1,023 | 2.90625 | 3 | [] | no_license | /*
# DP
# Problem: 1106
# Memory: 2028KB
# Time: 0ms
*/
#include <iostream>
#include <cmath>
using namespace std;
#define INF 2147483646
int C; // goal
int N; // city num
int cost[201] = {0,};
int customer[201] = {0,};
int result = INF;
int dp[1001] = {0,}; // ind:customer val:min_cost
int main(void){
cin.tie(NULL);
ios::sync_with_stdio(false);
// input
cin >> C >> N;
for(int i = 0; i < C; i++) dp[i] = INF; // init
for(int i = 0; i < N; i++){
cin >> cost[i] >> customer[i];
if(customer[i] >= C) result = min(result, cost[i]);
else dp[customer[i]] = min(dp[customer[i]], cost[i]);
}
// process
for(int i = 1; i < C; i++){
if (dp[i] == INF) continue;
// cout << dp[i] << '\n';
for(int j = 0; j < N; j++){
int ind = i + customer[j];
if(ind >= C) result = min(result, dp[i]+cost[j]);
else dp[ind] = min(dp[ind], dp[i] + cost[j]);
}
}
cout << result;
return 0;
} | true |
cbecf1179fcecd9cfbb673c4db191dee243e2450 | C++ | hsondd/learn | /LearnCPP/5.Overload/35.NhapXuat.cc | UTF-8 | 1,454 | 3.46875 | 3 | [] | no_license | #include <iostream>
using namespace std;
//Cach 1: Member-func
class PhanSo
{
private:
int Tu, Mau;
public:
//getter
int LayTu()
{
return Tu;
}
int LayMau()
{
return Mau;
}
//setter
void SetTu(int a)
{
Tu = a;
}
void SetMau(int b)
{
Mau = b;
}
void Xuat() {
cout << Tu << "/" << Mau;
}
PhanSo(){};
PhanSo(int a, int b)
{
Tu = a;
Mau = b;
}
PhanSo operator+(PhanSo);//-Phan so
PhanSo operator+(int); //A + int
friend PhanSo operator+(int, PhanSo);
};
// //non-mem func
istream &operator>>(istream &input, PhanSo &ps)
{
int a, b;
cout << "Nhap tu = ";
input >> a;
cout << "\nNhap mau = ";
input >> b;
ps = PhanSo(a,b);
return input;
}
ostream &operator<<(ostream &output, PhanSo ps)
{
return output << ps.LayTu() << "/" << ps.LayMau();
}
// hAM BAN
PhanSo operator+(int a, PhanSo ps)
{
PhanSo temp;
temp.Tu = a * ps.Mau + ps.Tu;
temp.Mau = ps.Mau;
return temp;
}
PhanSo PhanSo::operator+(PhanSo ps)
{
PhanSo temp;
temp.Tu = Tu * ps.Mau + ps.Tu * Mau;
temp.Mau = Mau * ps.Mau;
return temp;
}
PhanSo PhanSo::operator+(int a)
{
PhanSo temp;
temp.Tu = a*Mau + Tu;
temp.Mau = Mau;
return temp;
}
int main() {
PhanSo A(1,2), B(3,5), C;
C = 2 + A;
C.Xuat();
cin >> A;
cout << A;
return 0;
}
| true |
bae77c8da3d19b9fabac45a3703ea17fd319cd22 | C++ | roboteur/proof-of-code-concepts-arduino | /deepsleep_timer_wakeup/deepsleep_timer_wakeup.ino | UTF-8 | 918 | 2.953125 | 3 | [
"MIT"
] | permissive | /* Deep Sleep and Wake-up Using Timer */
#define uS_TO_S_FACTOR 1000000ULL /* Conversion factor for micro seconds to seconds */
#define TIME_TO_SLEEP 10 /* Time ESP32 will go to sleep (in seconds) */
RTC_DATA_ATTR int bootCount = 0;
void functionWorkOnAnything() {
Serial.println("Place all processes and arguments here before going deep sleep.");
}
void setup(){
Serial.begin(115200);
delay(1000);
++bootCount;
Serial.println("Boot number: " + String(bootCount));
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) +
" Seconds");
functionWorkOnAnything();
esp_deep_sleep_start();
}
void loop(){
// Serial.println("Code execution will not reach here.");
// Serial.println("There might be cases though that esp_deep_sleep_start() might strategically be placed here.);
}
| true |
1e7c48a6e2a4f622121dc1e6ee4ab496adba2f8b | C++ | olcf/CSGF_2017 | /Kokkos/VectorAddition/VecAdd.cpp | UTF-8 | 1,170 | 2.921875 | 3 | [] | no_license | #include <iostream>
#include <Kokkos_Core.hpp>
#include <Kokkos_Parallel.hpp>
#include <Kokkos_View.hpp>
#include "mpi.h"
#include <assert.h>
#include <limits>
int main(int argc, char **argv) {
// Initialize MPI before Kokkos
MPI_Init(&argc, &argv);
// Initialize Kokkos
Kokkos::initialize(argc, argv);
const int dim = 1000;
// Allocate our arrays
Kokkos::View<double*> a("a", dim);
Kokkos::View<double*> b("b", dim);
Kokkos::View<double*> c("c", dim);
// Create host mirror of C
auto c_mirror = Kokkos::create_mirror_view(c);
// Initialize a and b
Kokkos::parallel_for(dim, KOKKOS_LAMBDA(int i) {
a(i) = sin((double)i)*sin((double)i);
b(i) = cos((double)i)*cos((double)i);
});
// Preform the vector addition
Kokkos::parallel_for(dim, KOKKOS_LAMBDA(int i) {
c(i) = a(i) + b(i);
});
// Update the mirror
deep_copy(c_mirror, c);
// Verify the results of the host mirror
for(int i=0; i<dim; i++) {
double eps = abs(1.0 - c_mirror(i));
assert(eps <= std::numeric_limits<double>::epsilon());
};
std::cout<<"Sum Correct\n";
Kokkos::finalize();
MPI_Finalize();
return 0;
}
| true |
52f8db6caa8f59a738ffcd7da89f2e7fe669ae1d | C++ | zzuummaa/yandex_interview_training | /contest/interesting_travaling/main.cpp | UTF-8 | 1,483 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <map>
#include <vector>
#include <queue>
struct Coordinate {
long x;
long y;
long dist(Coordinate& other) const {
return labs(this->x - other.x) + labs(this->y - other.y);
}
};
int main() {
int city_count;
std::cin >> city_count;
std::vector<Coordinate> city_coordinates(city_count);
for (int i = 0; i < city_count; ++i) {
Coordinate c;
std::cin >> c.x >> c.y;
city_coordinates[i] = c;
}
long max_dist;
std::cin >> max_dist;
int begin_city_idx, end_city_idx;
std::cin >> begin_city_idx >> end_city_idx;
begin_city_idx--; end_city_idx--;
std::vector<std::vector<int>> adjacency_list(city_coordinates.size());
for (int i = 0; i < city_coordinates.size(); ++i) {
for (int j = 0; j < city_coordinates.size(); ++j) {
if (i == j) continue;
if (city_coordinates[i].dist(city_coordinates[j]) <= max_dist) adjacency_list[i].push_back(j);
}
}
std::vector<bool> visited_cities(city_coordinates.size(), false);
visited_cities[begin_city_idx] = true;
std::vector<int> distances(city_coordinates.size(), -1);
distances[begin_city_idx] = 0;
std::queue<int> next_cities;
next_cities.push(begin_city_idx);
while (!next_cities.empty()) {
int next = next_cities.front();
next_cities.pop();
for (int adj: adjacency_list[next]) {
if (visited_cities[adj]) continue;
visited_cities[adj] = true;
distances[adj] = distances[next] + 1;
next_cities.push(adj);
}
}
std::cout << distances[end_city_idx];
} | true |
35aed7fee0ecb448906daf24906efd714503b31c | C++ | BlueButterflyTeam/SeminaireMath | /SeminaireMath/controls.cpp | WINDOWS-1252 | 5,342 | 2.9375 | 3 | [] | no_license | // Include GLFW
#include <GLFW/glfw3.h>
extern GLFWwindow* window; // The "extern" keyword here is to access the variable "window" declared in tutorialXXX.cpp. This is a hack to keep the tutorials simple. Please avoid this.
// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/transform.hpp>
#include "controls.hpp"
glm::mat4 ViewMatrix;
glm::mat4 ProjectionMatrix;
glm::mat4 getViewMatrix(){
return ViewMatrix;
}
glm::mat4 getProjectionMatrix(){
return ProjectionMatrix;
}
// Initial position : on +Z
glm::vec3 position = glm::vec3( 0, 0, 10 );
// Initial horizontal angle : toward -Z
float horizontalAngle = 3.14f;
// Initial vertical angle : none
float verticalAngle = 0.0f;
// Initial Field of View
float initialFoV = 45.0f;
float speed = 3.0f; // 3 units / second
float mouseSpeed = 0.005f;
// Initial cube rotation : 0
glm::quat cube_rotation;
glm::mat4 cube_translation;
glm::mat4 cube_scaling;
glm::mat4 shearing_mat;
glm::mat4 computeMatricesFromInputs(){
// glfwGetTime is called only once, the first time this function is called
static double lastTime = glfwGetTime();
// Compute time difference between current and last frame
double currentTime = glfwGetTime();
float deltaTime = float(currentTime - lastTime);
// Get mouse position
double xpos = 1024 / 2, ypos = 768 / 2;
//glfwGetCursorPos(window, &xpos, &ypos);
// Reset mouse position for next frame
glfwSetCursorPos(window, 1024/2, 768/2);
// Compute new orientation
horizontalAngle += mouseSpeed * float(1024/2 - xpos );
verticalAngle += mouseSpeed * float( 768/2 - ypos );
// Direction : Spherical coordinates to Cartesian coordinates conversion
glm::vec3 direction(
cos(verticalAngle) * sin(horizontalAngle),
sin(verticalAngle),
cos(verticalAngle) * cos(horizontalAngle)
);
// Right vector
glm::vec3 right = glm::vec3(
sin(horizontalAngle - 3.14f/2.0f),
0,
cos(horizontalAngle - 3.14f/2.0f)
);
// Up vector
glm::vec3 up = glm::cross( right, direction );
// -===- TRANSLATION -===-
// Strafe up
if (glfwGetKey( window, GLFW_KEY_UP ) == GLFW_PRESS){
cube_translation *= glm::translate(glm::vec3(0, .05, 0));
glm::scale(glm::vec3(2, 2, 2));
glm::translate(glm::vec3(1, 0, 0));
}
// Strafe down
if (glfwGetKey( window, GLFW_KEY_DOWN ) == GLFW_PRESS){
cube_translation *= glm::translate(glm::vec3(0, -.05, 0));
}
// Strafe right
if (glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS) {
cube_translation *= glm::translate(glm::vec3(.05, 0, 0));
}
// Strafe left
if (glfwGetKey( window, GLFW_KEY_LEFT ) == GLFW_PRESS){
cube_translation *= glm::translate(glm::vec3(-.05, 0, 0));
}
// -===- ROTATION -===-
// Roatate down
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
{
glm::vec3 EulerAngles(.5 * PI, 0, 0);
cube_rotation = glm::quat(EulerAngles);
}
// Roatate up
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
{
glm::vec3 EulerAngles(-.5 * PI, 0, 0);
cube_rotation = glm::quat(EulerAngles);
}
// Roatate left
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
{
//glm::rotate()
glm::vec3 EulerAngles(0, -.5 * PI, 0);
cube_rotation = glm::quat(EulerAngles);
}
// Roatate right
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
{
glm::vec3 EulerAngles(0, .5 * PI, 0);
cube_rotation = glm::quat(EulerAngles);
}
// Roatate falling left
if (glfwGetKey(window, GLFW_KEY_Q) == GLFW_PRESS)
{
glm::vec3 EulerAngles(0, 0, .5 * PI);
cube_rotation = glm::quat(EulerAngles);
}
// Roatate falling right
if (glfwGetKey(window, GLFW_KEY_E) == GLFW_PRESS)
{
glm::vec3 EulerAngles(0, 0, -.5 * PI);
cube_rotation = glm::quat(EulerAngles);
}
// -===- SCALING -===-
// Scaling bigger
if (glfwGetKey(window, GLFW_KEY_P) == GLFW_PRESS)
{
cube_scaling += glm::scale(glm::vec3(2, 2, 2));
}
// Scaling smaller
if (glfwGetKey(window, GLFW_KEY_O) == GLFW_PRESS)
{
cube_scaling += glm::scale(glm::vec3(.5, .5, .5));
}
// -===- SHEARING -===-
// Shearing X-Y
if (glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS)
{
shearing_mat += glm::mat4( 1, 0, 0, 0,
0, 1, 0, 0,
2, 2, 1, 0,
0, 0, 0, 1);
}
// Shearing Y-Z
if (glfwGetKey(window, GLFW_KEY_K) == GLFW_PRESS)
{
shearing_mat += glm::mat4( 1, 2, 2, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
}
// -===- RESET -===-
if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS)
{
cube_translation = glm::mat4();
cube_rotation = glm::quat();
cube_scaling = glm::mat4();
shearing_mat = glm::mat4();
}
float FoV = initialFoV;// - 5 * glfwGetMouseWheel(); // Now GLFW 3 requires setting up a callback for this. It's a bit too complicated for this beginner's tutorial, so it's disabled instead.
// Projection matrix : 45 Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
ProjectionMatrix = glm::perspective(FoV, 4.0f / 3.0f, 0.1f, 100.0f);
// Camera matrix
ViewMatrix = glm::lookAt(
position, // Camera is here
position+direction, // and looks here : at the same position, plus "direction"
up // Head is up (set to 0,-1,0 to look upside-down)
);
// For the next frame, the "last time" will be "now"
lastTime = currentTime;
return cube_translation * toMat4(cube_rotation) * shearing_mat * cube_scaling;
} | true |
17bb91073dfd430d593517673b126807cc12f325 | C++ | bluemix/Online-Judge | /CodeForce/347A Difference Row.cpp | UTF-8 | 2,235 | 3.34375 | 3 | [] | no_license | /* 4566942 Sep 26, 2013 4:01:53 PM Shark 347A - Difference Row GNU C++ Accepted 30 ms 0 KB */
#include<stdio.h>
#include<stdlib.h>
#define SWAP(x,y) { int temp=x; x=y; y=temp; }
int main(){
int n;
int M[10000];
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&M[i]);
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
if(M[i]>M[j])
SWAP(M[i],M[j]);
SWAP(M[0],M[n-1]);
printf("%d",M[0]);
for(int i=1;i<n;i++)
printf(" %d",M[i]);
putchar('\n');
return 0;
}
/*
A. Difference Row
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You want to arrange n integers a1, a2, ..., an in some order in a row. Let's define the value of an arrangement as the sum of differences between all pairs of adjacent integers.
More formally, let's denote some arrangement as a sequence of integers x1, x2, ..., xn, where sequence x is a permutation of sequence a. The value of such an arrangement is (x1 - x2) + (x2 - x3) + ... + (xn - 1 - xn).
Find the largest possible value of an arrangement. Then, output the lexicographically smallest sequence x that corresponds to an arrangement of the largest possible value.
Input
The first line of the input contains integer n (2 ≤ n ≤ 100). The second line contains n space-separated integers a1, a2, ..., an (|ai| ≤ 1000).
Output
Print the required sequence x1, x2, ..., xn. Sequence x should be the lexicographically smallest permutation of a that corresponds to an arrangement of the largest possible value.
Sample test(s)
input
5
100 -100 50 0 -50
output
100 -50 0 50 -100
Note
In the sample test case, the value of the output arrangement is (100 - ( - 50)) + (( - 50) - 0) + (0 - 50) + (50 - ( - 100)) = 200. No other arrangement has a larger value, and among all arrangements with the value of 200, the output arrangement is the lexicographically smallest one.
Sequence x1, x2, ... , xp is lexicographically smaller than sequence y1, y2, ... , yp if there exists an integer r (0 ≤ r < p) such that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 < yr + 1.
*/ | true |
7eac7f529ce96ce9c3eeb08c9f5b1b0bf0afd095 | C++ | Nikhilsharmaiiita/LeetcodeCracker | /maximum-69-number/maximum-69-number.cpp | UTF-8 | 242 | 2.765625 | 3 | [] | no_license | class Solution {
public:
int maximum69Number (int num) {
string s=to_string(num);
for(int i=0;i<s.size();i++)
{
if(s[i]=='6'){s[i]='9';break;}
}
int x=stoi(s);
return x;
}
}; | true |
0d346794a6ccbfe34fe0c20c9e258699b43c5c20 | C++ | nathanj96/Cinnabar-Engine | /Commands/CAudio Commands/ChannelBase/CChannelSetPitchCommand.h | UTF-8 | 660 | 2.6875 | 3 | [] | no_license | #ifndef C_CHANNEL_SET_PITCH_COMMAND
#define C_CHANNEL_SET_PITCH_COMMAND
class CSoundChannelBase;
#include "CAudioCommandBase.h"
class CChannelSetPitchCommand : public CAudioCommandBase
{
private:
CSoundChannelBase* chnl;
float pitch;
public:
CChannelSetPitchCommand() = delete;
CChannelSetPitchCommand(const CChannelSetPitchCommand&) = delete;
CChannelSetPitchCommand& operator=(const CChannelSetPitchCommand&) = delete;
~CChannelSetPitchCommand() = default;
CChannelSetPitchCommand(CSoundChannelBase* chn);
virtual void Execute() override;
//reset pitch to reuse command
void setNewPitch(float newPitch);
};
#endif C_CHANNEL_SET_PITCH_COMMAND | true |
5d1b309929587fb07b5c4549aa6a16949911e316 | C++ | Poukiaaaaaaaaaaaaaaa/hnsm | /hnsm/src/engine/Audio.cpp | ISO-8859-1 | 9,112 | 2.84375 | 3 | [] | no_license | #include "Audio.h"
/*
* 'streamCallback': fonction appele automatiquement une certaine frquence
* (dfinie lors de l'initialisation du flux audio)
*
* Paramtres:
* - 'input': pointeur utilis pour l'enregistrement audio, dsigne un emplacement
* mmoire dans lequel sont stockes les donnes enregistres (membre inutilis
* dans notre cas)
*
* - 'output': pointeur dsignant un emplacement mmoire directement lu par l'appareil
* audio, c'est cet emplacement mmoire que les donnes audio seront places
*
* - 'frameCount': membre gr par l'appareil audio, contenant le nombre d'chantillons
* audio pouvant tres placs l'emplacement point par 'output'
*
* - 'tInfo': informations de temps concernant les buffers 'input' et 'output' (membre
* non utilis dans notre cas)
*
* - 'statusFlags': informations concernant le callback audio, permet de savoir si
* les buffers 'input' et 'output' manquent ou dbordent de donnes (non utilis)
*
* - 'userData': membre contenant la totalit des donnes audio, places l'adresse
* pointe par 'output' dans notre cas.
*
*/
static int streamCallback(const void *input, void *output, unsigned long frameCount,
const PaStreamCallbackTimeInfo *tInfo, PaStreamCallbackFlags statusFlags,
void *userData)
{
/*
* Rcupration des donnes audio dans un conteneur utilisable (autre que `void*`).
* Mme procd pour 'output': un membre de type `void*` est inutilisable
*
*/
AudioCallbackData *data = (AudioCallbackData*)userData;
float *out = (float*)output;
/*
* Variables permettant de rcuprer le nombre d'chantillons chargs depuis
* les fichiers audio (spars en deux catgories: "loop" et "sounds")
*
*/
sf_count_t loop_item_count;
sf_count_t sound_item_count;
/*
* Paramtres unutiliss, convertis en `void` afin de librer de la mmoire
*
*/
(void)tInfo;
(void)statusFlags;
(void)input;
/*
* Buffer temporaire, dans lequel sont places les donnes audio non
* traites. Ce dernier est ensuite directement plac l'emplacement point
* par 'out' une fois les donnes audio traites (c.f. gestion du volume, etc)
*
*/
float *temp = (float*)malloc(sizeof(float) * frameCount * CHANNELS);
/*
* L'emplacement point par 'out' est vid chaque appel.
* Est possible car les donnes audio places 'out' crrespondent
* exactement aux donnes audio lues par l'appareil entre deux
* appels du callback
*
*/
memset(out, 0, sizeof(float) * frameCount * CHANNELS);
/*
* Chargement des donnes audio prsentes dans les fichiers audio.
* Les donnes charges font au final une taille correspondant
* au nombre d'chantillons lus par l'appareil entre deux appels
* (ce nombre tant contenu par 'frameCount')
*
*/
if (data->loop.exists == true)
{
/*
* Les donnes ne seront pas charges si le fichier audio est
* en train d'tre charg, le contraire entranant une fuite mmoire
*
*/
if (data->loop.reloaded == true)
loop_item_count = sf_read_float(data->loop.audioFile, temp, frameCount *
data->loop.info.channels);
else loop_item_count = frameCount;
/*
* Placement des donnes audio dans 'out' une fois traites
* Le traitement, dans notre cas, consiste uniquement en la
* gestion du volume
*
*/
for (unsigned i = 0; i < frameCount * CHANNELS; i++)
{
out[i] += temp[i] * data->getLoopVol();
}
/*
* Une fois arriv la fin du fichier audio, celui-ci et recharg.
* Se lecture sera alors impossible jusqu' ce qu'il le soit
* Ce procd est unique la "loop" qui, contrairement aux "sounds",
* se rpte indfiniment
*
*/
if (loop_item_count < frameCount)
{
data->loop.reload();
}
}
/*
* Les sons "loop" et "sounds" sont procds diffremment, donc sparment:
* La principale diffrence tant qu'une seule "loop" peut tre lue la fois,
* contrairement aux "sounds" pour lesquels le nombre des lectures simultanes est
* limit `MAX_SOUNDS` (ici 32)
*
*/
for (unsigned i = 0; i < MAX_SOUNDS; i++)
{
if (data->sounds[i].exists == true)
{
if (data->sounds[i].reloaded == true)
sound_item_count = sf_read_float(data->sounds[i].audioFile, temp, frameCount *
data->sounds[i].info.channels);
else sound_item_count = frameCount;
for (unsigned i = 0; i < frameCount * CHANNELS; i++)
{
out[i] += temp[i] * data->getSoundsVol();
}
if (sound_item_count < frameCount)
{
/*
* Une fois un son termin, l'objet du type 'AudioData' le
* contenant est rinitialis
*
*/
for (unsigned j = i; j < MAX_SOUNDS - 1; j++)
{
data->sounds[j] = data->sounds[j + 1];
}
data->sounds[MAX_SOUNDS - 1] = AudioData();
}
}
}
/*
* Le buffer temporaire est libr aprs chaque appel, permet
* une utilisation fixe de la mmoire
*
*/
free(temp);
/*
* 'paContinue' est un tag utilis par PortAudio, indiquant que le
* callback devrait tre appel normalement aprs celui-ci
*
*/
return paContinue;
}
/*
* Le constructeur de la classe Audio s'occupe principalement de
* l'initialisation du flux audio.
*
*/
Audio::Audio()
{
/*
* Rcupration des informations concernant l'appareil de
* sortie par dfaut
*
*/
PaDeviceIndex index = Pa_GetDefaultOutputDevice();
const PaDeviceInfo *info = Pa_GetDeviceInfo(index);
/*
* Initialisation du flux audio partir des paramtres audio
* de l'appareil de lecture par dfaut
*
*/
if (info == nullptr)
{
Log::toFile("error.log", "[ERROR]:Couldn't retrieve device information");
}
else
{
/*
* Pa_OpenDefaultStream initialise le flux audio puis dfinit le
* callback lui tant li (ici 'streamCallback')
*
*/
Pa_OpenDefaultStream(&audioStream, 0, 2, paFloat32, info->defaultSampleRate,
paFramesPerBufferUnspecified, streamCallback, &userData
);
}
}
/*
* Mthode 'startStream': dmarre le flux audio, ne fonctionne
* que si ce dernier a correctement t initialis
*
*/
void Audio::startStream()
{
Pa_StartStream(audioStream);
}
/*
* Mthode 'stopStream': stoppe le flux audio.
* L'arrt possdant le tag `STOP` finira de lire les donnes
* audio avant d'arrter le flux.
* Celui possdant le tag `ABORT` forcera l'arrt du flux.
*
*/
void Audio::stopStream(StopTag tag)
{
if (tag == STOP)
Pa_StopStream(audioStream);
else if (tag == ABORT)
Pa_AbortStream(audioStream);
}
/*
* Mthode 'get_streamStopped': retourne l'tat d'arrt du flux
* sous la forme d'un boolen
*
*/
PaError Audio::get_streamStopped() const
{
return Pa_IsStreamStopped(audioStream);
}
/*
* Mthode 'setLoop': modifie la "loop" pour un autre lment du type 'AudioData'
*
*/
void Audio::setLoop(AudioData data)
{
userData.setLoop(data);
}
/*
* Mthode 'playSound': vide l'intgralit des "sounds" actuels
* pour n'en jouer qu'un seul (correspondant au paramtre 'data')
*
*/
void Audio::playSound(AudioData data)
{
for (unsigned i = 0; i < MAX_SOUNDS; i++)
{
userData.sounds[i] = AudioData();
}
userData.setSound(0, data);
}
/*
* Les mthodes suivantes servent la gestion des "sounds" et "loop"
* ainsi qu' la gestion de leur volume.
*
* Celles-ci utilisent principalement les mthode de la classe 'AudioData'
* (voir AudioData.h et AudioData.cpp pour plus de dtails), elles seront
* donc peu ou non commentes
*
*/
/*
* Ajoute un son l'array 'sounds' du membre 'userData'
*
*/
void Audio::addSound(AudioData data)
{
userData.addSound(data);
}
/*
* Vide l'array 'sounds' de 'userData'
*
*/
void Audio::clearSounds()
{
userData.clearSounds();
}
/*
* Rinitialise le membre 'loop' de 'userData'
*
*/
void Audio::clearLoop()
{
userData.clearLoop();
}
void Audio::setGlobalVolume(float vol)
{
setLoopVol(vol);
setSoundsVol(vol);
}
void Audio::globalVolumeUp(float inc)
{
loopVolUp(inc);
soundsVolUp(inc);
}
void Audio::globalVolumeDown(float dec)
{
loopVolDown(dec);
soundsVolDown(dec);
}
void Audio::setLoopVol(float vol)
{
userData.setLoopVol(vol);
}
void Audio::setSoundsVol(float vol)
{
userData.setSoundsVol(vol);
}
void Audio::loopVolUp(float inc)
{
if (userData.getLoopVol() + inc <= 2.0f)
{
userData.setLoopVol(userData.getLoopVol() + inc);
}
else
{
userData.setLoopVol(2.0f);
}
}
void Audio::loopVolDown(float dec)
{
if (userData.getLoopVol() - dec >= 0.0f)
{
userData.setLoopVol(userData.getLoopVol() - dec);
}
else
{
userData.setLoopVol(0.0f);
}
}
void Audio::soundsVolUp(float inc)
{
if (userData.getSoundsVol() + inc <= 2.0f)
{
userData.setSoundsVol(userData.getSoundsVol() + inc);
}
else
{
userData.setSoundsVol(2.0f);
}
}
void Audio::soundsVolDown(float inc)
{
if (userData.getSoundsVol() - inc >= 0.0f)
{
userData.setSoundsVol(userData.getSoundsVol() - inc);
}
else
{
userData.setSoundsVol(0.0f);
}
}
/*
* Dconstructeur de la classe Audio: ferme le flux audio
*
*/
Audio::~Audio()
{
Pa_CloseStream(audioStream);
}
| true |
a9b652907da474adcc7a29bf80f271577a381c8c | C++ | marciodrosa/sc-game-2 | /Source/Models/GameState.cpp | UTF-8 | 1,685 | 3.015625 | 3 | [] | no_license | #include "GameState.h"
#include <set>
using namespace sc;
using namespace std;
GameState::GameState()
{
SelectedCharacterIndex = 0;
CurrentMovieIndex = 0;
IsInModuleInTransition = false;
IsInModuleOutTransition = false;
RingoAlreadyAppeared = false;
}
Movie* GameState::FindMovieById(MovieId id)
{
for (Movie& movie : Movies)
{
if (movie.Id == id)
return &movie;
}
return nullptr;
}
void GameState::ResetAvailableAndSelectedMovies()
{
SelectedMovies.clear();
AvailableMoviesToSelect.clear();
for (Movie& movie : Movies)
{
AvailableMoviesToSelect.push_back(movie.Id);
}
}
void GameState::MoveFromAvailableToSelectedMovies(int index)
{
vector<MovieId> temp;
for (int i = 0; i < AvailableMoviesToSelect.size(); i++)
{
if (i == index)
SelectedMovies.push_back(AvailableMoviesToSelect[i]);
else
temp.push_back(AvailableMoviesToSelect[i]);
}
AvailableMoviesToSelect = temp;
}
void GameState::MoveFromSelectedToAvailableMovies(int index)
{
vector<MovieId> temp;
for (int i = 0; i < SelectedMovies.size(); i++)
{
if (i == index)
AvailableMoviesToSelect.push_back(SelectedMovies[i]);
else
temp.push_back(SelectedMovies[i]);
}
SelectedMovies = temp;
}
void GameState::MoveSelectedMovieUp(int index)
{
if (index > 0)
{
MovieId temp1 = SelectedMovies[index - 1];
MovieId temp2 = SelectedMovies[index];
SelectedMovies[index - 1] = temp2;
SelectedMovies[index] = temp1;
}
}
void GameState::MoveSelectedMovieDown(int index)
{
if (index < SelectedMovies.size() - 1)
{
MovieId temp1 = SelectedMovies[index + 1];
MovieId temp2 = SelectedMovies[index];
SelectedMovies[index + 1] = temp2;
SelectedMovies[index] = temp1;
}
}
| true |
54c668a79bfb7cd707d4832fc270df16065a8427 | C++ | MitkoZ/PingPong | /main.cpp | UTF-8 | 3,420 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include <GL\gl.h>
#include <GL\glu.h>
#include <C:\My Files\GLUT\glutdlls36\glut.h>
#include "Player.h"
#include "Ball.h"
#include "Constants.hpp"
Player* bottomPlayer = new Player(300);
Player* topPlayer = new Player(300);
Ball* ball;
using namespace std;
void specialHandler(int key, int x, int y)
{
switch(key)
{
case GLUT_KEY_LEFT:
{
bottomPlayer->moveLeft(30);
glutPostRedisplay();
break;
}
case GLUT_KEY_RIGHT:
{
bottomPlayer->moveRight(30);
glutPostRedisplay();
break;
}
}
}
void keyboardHandler(unsigned char key, int x, int y)
{
switch(toupper(key))
{
case 'A':
{
topPlayer->moveLeft(20);
glutPostRedisplay();
break;
}
case 'D':
{
topPlayer->moveRight(20);
glutPostRedisplay();
break;
}
case 32: //spacebar
{
if(!ball) //release a new ball only when the current ball's pointer is deleted (out of the screen)
{
ball = new Ball(bottomPlayer->getLeftX() , bottomPlayer->getRightY() -1, bottomPlayer, topPlayer);
glutPostRedisplay();
}
break;
}
}
}
void printScore(Player* topPlayer, Player* bottomPlayer)
{
system("cls");
cout << "Top player : Bottom player \n";
cout << "\n" << topPlayer->getScore() << " : " << bottomPlayer->getScore();
}
void checkIsScore()
{
if (ball->getY() > Constants::WindowHeight)
{
topPlayer->setScore(topPlayer->getScore() + 1);
printScore(topPlayer, bottomPlayer);
delete ball;
ball = NULL;
}
else if (ball->getY() < 0)
{
bottomPlayer->setScore(bottomPlayer->getScore() + 1);
printScore(topPlayer, bottomPlayer);
delete ball;
ball = NULL;
}
}
void displayScene()
{
glBegin(GL_LINES);
glColor3f(0, 1, 0);
glVertex2i(topPlayer->getLeftX(), topPlayer->getLeftY());
glVertex2i(topPlayer->getRightX(), topPlayer->getRightY());
glColor3f(1, 0, 0);
glVertex2i(bottomPlayer->getLeftX(), bottomPlayer->getLeftY());
glVertex2i(bottomPlayer->getRightX(), bottomPlayer->getRightY());
glEnd();
if (ball)
{
glPointSize(50);
glBegin(GL_POINTS);
glColor3f(0, 0, 1);
glVertex2i(ball->getX(), ball->getY());
ball->moveBall(1);
checkIsScore();
glutPostRedisplay();
glEnd();
}
glFlush();
}
void displayFunc()
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0, 0, 0);
glLineWidth(33);
displayScene();
}
int main(int argc, char *argv[])
{
glutInit(&argc, argv);
glutInitWindowSize(Constants::WindowWidth, Constants::WindowHeight);
glutCreateWindow("Ping - Pong");
glClearColor(1.0, 1.0, 1.0, 1.0);
glOrtho(0, Constants::WindowWidth, Constants::WindowHeight, 0, -1, 1);
topPlayer->setLeftY(1);
topPlayer->setRightY(1);
bottomPlayer->setLeftY(Constants::WindowHeight - 1);
bottomPlayer->setRightY(Constants::WindowHeight - 1);
glutKeyboardFunc(keyboardHandler);
glutSpecialFunc(specialHandler);
glutDisplayFunc(displayFunc);
glutMainLoop();
return 0;
}
| true |
72ba509e137090bc9b41cd30a17fe8cbf7357bfc | C++ | jdelezenne/Sonata | /Sources/Engine/Graphics/VertexFormats/VertexPositionNormalColor.cpp | UTF-8 | 911 | 2.78125 | 3 | [
"MIT"
] | permissive | /*=============================================================================
VertexPositionNormalColor.cpp
Project: Sonata Engine
Author: Julien Delezenne
=============================================================================*/
#include "VertexPositionNormalColor.h"
namespace SonataEngine
{
const VertexElement VertexPositionNormalColor::VertexElements[] =
{
VertexElement(0, 0, VertexFormat_Float3, VertexSemantic_Position, 0),
VertexElement(0, 12, VertexFormat_Float3, VertexSemantic_Normal, 0),
VertexElement(0, 24, VertexFormat_Color, VertexSemantic_Color, 0)
};
const int VertexPositionNormalColor::ElementCount = 3;
const int VertexPositionNormalColor::SizeInBytes = sizeof(VertexPositionNormalColor);
VertexPositionNormalColor::VertexPositionNormalColor(const Vector3& position, const Vector3& normal, const Color32& color)
{
Position = position;
Normal = normal;
Color = color.ToARGB();
}
}
| true |
1b7b390aa5530aa4e0a06eaa213a9ec0e7ed7f7f | C++ | vpantanella/SnakeGame | /src/Node.cpp | UTF-8 | 329 | 3.265625 | 3 | [] | no_license | #include "Node.h"
Node::Node(int data) :data(data),next(0){}
void Node::setData(int data)
{
this->data = data;
}
int Node::getData() const
{
return data;
}
void Node::setNext(Node *node)
{
next = node;
}
Node* Node::getNext() const
{
return next;
}
Node::~Node()
{
delete next;
next = 0;
} | true |
38b52de947ecad35b9a1eef2e96b58cbf1567b6b | C++ | Yan-Song/burdakovd | /c++/sdl/sdlapplication/SDLApplication.h | UTF-8 | 5,254 | 2.796875 | 3 | [] | no_license | #ifndef SDLAPPLICATION_H
#define SDLAPPLICATION_H
#include <cmath>
#include <ctime>
#include <iostream>
#include <list>
#include <sstream>
#include <string>
#include <SDL.h>
#include "Color.h"
#include "IGameLoop.h"
#include "Shared.h"
#include "Timer.h"
#include "Utils.h"
#include "Vector.h"
struct FrameInfo
{
double cticks;
double dt;
FrameInfo(Uint32 c, double d) : cticks(c), dt(d)
{
};
};
typedef std::list<FrameInfo> FrameInfoList;
class SDLApplication : protected IGameLoop
{
public:
SDLApplication();
// установить заголовок окна
void SetCaption(const std::string& text);
void Lock(); // Заблокировать экран чтобы можно было рисовать
inline bool isLocked() const
{
return _locked > 0;
}
void Unlock(); // Разблокировать экран
void Flip() const ; // SDL_Flip
// координаты Декартовы, направление осей нормальное (X - вправо, Y - вверх)
void DrawPixel(const int x, int y, const Color& color);
// не блокирует экран (предполагается что он уже заблокирован)
void RawDrawPixel(const int x, int y, const Color& color) const;
void DrawPixel(const ScreenPoint& point, const Color& color);
// нарисовать отрезок
void DrawSegment(const ScreenPoint& A, const ScreenPoint& B, const Color& color);
// нарисовать закрашенный прямоугольник, содержащий указанные точки в качестве угловых
void FillRectangle(const ScreenPoint& A, const ScreenPoint& B, const Color& color) const;
// очистить экран
void ClearScreen(const Color& color = Palette::Black) const;
// число из полуинтервала [0, x)
static int Rand(const int x);
// из отрезка [x, y]
static int Rand(const int x, int y);
void Run(); // вызывать извне класса один раз, будет работать пока изнутри не будет вызван Stop()
// время с момента инициализации библиотеки SDL в секундах, точность около 1мс.
// До вызова InitializeSDL результат вызова функции не определён.
inline double GetTime() const
{
return timer.GetTime();
}
inline double GetTicks() const
{
return timer.GetTicks();
}
inline unsigned int FPS() const
{
return static_cast<unsigned int>(stats.size());
}
inline bool isPressed(const SDLKey& key) const
{
return KeyState[key] != 0;
}
inline void MakeScreenshot(const std::string& path) const
{
if(isLocked())
{
std::cout<<"Failed to make screenshot: Screen is locked"<<std::endl;
}
else
{
if(SDL_SaveBMP(Screen, path.c_str()) == 0)
std::cout<<"Screenshot saved to "<<path<<std::endl;
else
std::cout<<"Failed to save screenshot to "<<path<<": "<<SDL_GetError()<<std::endl;
}
}
inline void MakeScreenshot()
{
std::ostringstream path;
path<<"./Screenshots/Screenshot-";
path<<startTime<<"-"<<GetTime();
path<<".bmp";
MakeScreenshot(path.str());
}
SDL_Surface* Screen;
virtual ~SDLApplication(); // деструктор
// ограничить число кадров в секунду, 0 - не ограничивать
void SetFPSCap(const Uint32 value)
{
fpsCap = value;
}
Uint32 GetFPSCap() const
{
return fpsCap;
}
bool CappedFPS() const
{
return fpsCap != 0;
}
ScreenPoint GetMousePosition() const;
inline Uint32 MapColor(const Color& rgb) const
{
assert(rgb.R >= 0 && rgb.B >=0 && rgb.G >= 0 && rgb.R < 256 && rgb.G < 256 && rgb.B < 256);
return SDL_MapRGB(Screen->format, static_cast<Uint8>(rgb.R), static_cast<Uint8>(rgb.G), static_cast<Uint8>(rgb.B));
}
void Stop();
protected:
virtual void InitialRender() {};
void InitializeSDL(size_t ScreenHeight, size_t ScreenWidth, int ColorDepth, Uint32 SDLflags); // инициализировать библиотеку SDL
virtual void ProcessEvents(); // обработать ввод пользователя
// количество кадров всего
unsigned int frames;
// минимальный dt за последнюю секунду, мс
int dtMin() const;
// средний dt за последнюю секунду, мс
int dtAvg() const;
// максимальный dt за последнюю секунду, мс
int dtMax() const;
// время, прошедшее с предыдущего кадра, сек.
double dt;
// обновить dt, FPS и прочую информацию
void UpdateStats();
Uint8* KeyState;
bool Running;
private:
time_t startTime;
int _locked;
Uint32 fpsCap;
// нельзя копировать
SDLApplication(const SDLApplication&);
SDLApplication& operator =(const SDLApplication&);
// статистика за последнюю секунду
FrameInfoList stats;
Timer timer, fps;
};
#endif
| true |
b91762d246322eea0b9316526eac7ec4c9ebc2bf | C++ | keithlowc/health-companion | /Arduino_code/main.cpp | UTF-8 | 323 | 2.546875 | 3 | [] | no_license | #include "pulse_sensor.h";
#include "temp_sensor.h";
Pulse pulsing(0); // Analog input
TemperatureSensor tempSensor; // Digital pin #2
void setup()
{
Serial.begin(9600);
pulsing.PulseSetUp();
tempSensor.InitializeTemperatureSensing();
}
void loop()
{
pulsing.PulseSensing();
tempSensor.CaptureTemperature();
} | true |
e21f29989c3d09fa98e75bb0d4d99cb9791c25a5 | C++ | nealwu/UVa | /volume009/996 - Find the Sequence.cpp | UTF-8 | 2,674 | 2.75 | 3 | [] | no_license | #include <stdio.h>
#include <set>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
string num2str(int x) {
string s;
stringstream sin(s);
sin << x;
return sin.str();
}
int dfs(vector<int> A, int M, string &solution) {
// printf("[");
// for (int i = 0; i < A.size(); i++)
// printf("%d ", A[i]);
// puts("]");
int same = 1;
for (int i = 1; i < A.size(); i++)
same &= A[i] == A[0];
if (same == 1) {
solution = "[" + num2str(A[0]) + "]";
return 1;
}
if (M <= 0) return 0;
int g = A[0];
for (int i = 0; i < A.size(); i++) {
if (A[i] == 0) {
g = 0;
break;
}
g = __gcd(g, A[i]);
}
for (int i = 1; i < A.size(); i++) {
if (A[i-1] != 0 && A[i]%A[i-1] != 0)
g = 0;
if (A[i-1] == 0 && A[i] != 0)
g = 0;
}
if (g < 0) g = -g;
if (g > 0) {
for (int m = 1; m <= g; m++) {
if (g%m == 0) {
vector<int> nA;
nA.push_back(A[0] / m);
for (int j = 1; j < A.size(); j++) {
if (A[j-1] == 0)
nA.push_back(0);
else
nA.push_back(A[j] / A[j-1]);
}
if (dfs(nA, M-1, solution)) {
solution = "[" + num2str(m) + "*" + solution + "]";
return 1;
}
nA.clear();
nA.push_back(A[0] / (-m));
for (int j = 1; j < A.size(); j++) {
if (A[j-1] == 0)
nA.push_back(0);
else
nA.push_back(A[j] / A[j-1]);
}
if (dfs(nA, M-1, solution)) {
solution = "[" + num2str(-m) + "*" + solution + "]";
return 1;
}
}
}
}
vector<int> nA;
for (int i = 1; i < A.size(); i++)
nA.push_back(A[i] - A[i-1]);
if (dfs(nA, M-1, solution)) {
solution = "[" + num2str(A[0]) + "+" + solution + "]";
return 1;
}
return 0;
}
int main() {
int M, x;
string line;
while (getline(cin, line)) {
stringstream sin(line);
sin >> M;
vector<int> A;
while (sin >> x)
A.push_back(x);
string solution;
int f = dfs(A, M, solution);
if (f == 0)
puts("[0]");
else
puts(solution.c_str());
}
return 0;
}
/*
3 10 30 30 -30 90 -450 3150
2 2 6 36 360 5400 113400
*/ | true |
1b70d28b1130b9e1289aedbb123fa6491f1cafee | C++ | ekirshey/WorldBuilder | /include/ChunkGeometry.h | UTF-8 | 1,201 | 2.703125 | 3 | [] | no_license | #pragma once
#include <vector>
#include <GL/glew.h>
#include "Ray.h"
#include "ChunkModel.h"
#include "ShapePrimitives.h"
namespace chunk {
class Geometry {
public:
Geometry(glm::vec3 localcoords, glm::vec3 translation, GLfloat width);
~Geometry();
bool intersectsWithRay(const Ray& ray, float& intersect_point) const;
bool intersectsWithRay(const Ray& ray) const;
bool intersectsWithCube(GLfloat leftbound,
GLfloat rightbound,
GLfloat frontbound,
GLfloat backbound,
bool& surrounds) const;
bool intersectsWithCircle(const shapes::Circle& circle);
void buildModelMatrix(glm::mat4& model) const;
void vectorToChunkLocalCoords(glm::vec4& vec);
glm::vec3 currentPosition() const {
glm::mat4 transform;
buildModelMatrix(transform);
return transform * glm::vec4(_localcoords,1.0f);
}
private:
// Geometry
glm::vec3 _normal;
glm::vec3 _offset; // offset from the world origin (0,0,0)
glm::vec3 _localcoords;
glm::vec3 _translation;
glm::vec3 _position;
GLfloat _yaw;
GLfloat _roll;
GLfloat _pitch;
GLfloat _width;
//2d plane so no y vals
GLfloat _xmax;
GLfloat _xmin;
GLfloat _zmax;
GLfloat _zmin;
};
}
| true |
c1688e637f92ecec2064f7d07175840f7ab34df1 | C++ | nikopa96/C-Advanced | /Prax02/src/number.cpp | UTF-8 | 741 | 2.71875 | 3 | [] | no_license | #include "number.hpp"
int Number::add(int a, int b) { return 0; }
int Number::difference(int a, int b) { return 0; }
int Number::product(int a, int b) { return 0; }
int Number::quotient(int a, int b) { return 0; }
int Number::remainder(int a, int b) { return 0; }
int Number::gcd(int a, int b) { return 0; }
int Number::max(int a, int b) { return 0; }
int Number::min(int a, int b) { return 0; }
float Number::mean(int a, int b) { return 0; }
bool Number::coPrime(int a, int b) { return true; }
bool Number::isEven(int a) { return true; }
bool Number::isOdd(int a) { return true; }
int Number::Series::factorial(int a) { return 0; }
int Number::Series::fibonacci(int a) { return 0; }
double Number::Series::harmonicSum(int a) { return 0; }
| true |
c11c0644a14a7243399613ef603e5e037aa6c5d4 | C++ | AdamMoffitt/portfolio | /C++ projects/Maze Solver/mazesolver.h | UTF-8 | 1,098 | 2.75 | 3 | [] | no_license | #ifndef MAZESOLVER_H
#define MAZESOLVER_H
#include "visitedtracker.h"
#include "maze.h"
#include <QMessageBox>
#include <queue>
#include <stack>
#include <vector>
#include <exception>
/*
* I didn't want the students to have to deal
* with function pointers, so I'm making the
* MazeSolver an object with various solve
* methods.
*
* I won't be offended if anyone wants to refactor
* this to make specific functions for them to call.
*/
class MazeDisplay;
class Maze;
class MazeSolver
{
public:
MazeSolver(Maze * m, MazeDisplay * md);
void solveByBFS();
void solveByDFSIterative();
void solveByDFSRecursive();
void recursion(int r,int c, VisitedTracker &vt, std::vector<Direction> &parent, int &numExplored);
void solveByAStar(int Choice);
int AStarHeuristic(int choice, int r, int c, std::vector<int> cost);
void setMaze(Maze* m);
private:
int squareNumber(int r, int c) const;
int getManhattanDistance(int r, int c);
int getEuclideanDistance(int r, int c);
Maze * maze;
MazeDisplay * display;
};
#endif // MAZESOLVER_H
| true |
94657f8cdead804a672a7273b113c00046cd499e | C++ | LemuriaX/luogu | /方块分割.cpp | UTF-8 | 682 | 2.71875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int sum = 0;
int fz[7][7] = {0};
int xx1[4] = {1,-1,0,0};
int yy1[4] = {0,0,-1,1};
int vis[7][7] = {0};
void dfs(int x,int y){
//cout << x<<" "<<y<<endl;
if(x == 0||y == 0||x == 6||y == 6){
sum++;
/*for(int i = 0;i<7;i++){
for(int j = 0;j<7;j++){
cout << vis[i][j]<<" ";
}
cout << endl;
}
cout << endl;*/
return;
}
for(int i = 0;i<4;i++){
int dx1 = x + xx1[i];
int dy1 = y + yy1[i];
if(!vis[dx1][dy1]&&!vis[6-dx1][6-dy1]){
vis[dx1][dy1] = 1;
vis[6-dx1][6-dy1] = 1;
dfs(dx1,dy1);
vis[dx1][dy1] = 0;
vis[6-dx1][6-dy1] = 0;
}
}
}
int main(){
vis[3][3] = 1;
dfs(3,3);
cout << sum/4;
}
| true |
d38cc2e66c7eda67d6729e3112e6fd751cd8f6c7 | C++ | sanghoon23/Algorithm | /QBaekJoon_210129_일요일아침의데이트/ConsoleApplication1_Test/ConsoleApplication1_Test.cpp | UTF-8 | 5,322 | 2.765625 | 3 | [] | no_license | #include "pch.h"
#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <string.h>
using namespace std;
/*@210129
여기서 중요한 것은 값을 과정에서 구하지 말고
미리 구할 수 있는 값들은 미리 구해서 사용하자. ex) FindAround
첫번째 코드와 밑의 삽질 코드는 이 차이밖에 없었는데,
우선순위 큐 안에서 주변의 'g' 를 구하는 과정에서 내가 파악하지 못한 다른 상황이 발생하는 것으로 추측됨.
이런 과정은 미묘하고 찾기 어려워서 시간이 오래 걸릴거 같다. 지금도 굉장히 시간이 오래 걸렸다.
사전에 방지하자.
*/
#define FASTIO ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define PII pair<int, int>
#define MSIZE 51
#define MMAX 987654321
int N, M, Around[MSIZE][MSIZE];
char Board[MSIZE][MSIZE];
PII Start, End;
PII Dir[4] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
struct Node
{
int SC = 0, Y = 0, X = 0;
Node(int SCC, int YY, int XX)
{
SC = SCC;
Y = YY;
X = XX;
}
};
struct Comp { bool operator()(pair<int, Node> A, pair<int, Node> B) { return A.first > B.first; } };
void FindAround(int Y, int X)
{
for (int k = 0; k < 4; ++k)
{
int YY = Y + Dir[k].first, XX = X + Dir[k].second;
if (YY < 0 || YY >= N || XX < 0 || XX >= M) continue;
if (Board[YY][XX] == 'g') { Around[Y][X] = 1; break; }
}
}
int main()
{
FASTIO;
memset(Board, 0, sizeof(Board));
cin >> N >> M;
for (int j = 0; j < N; ++j)
{
string Str; cin >> Str;
for (int i = 0; i < M; ++i)
{
Board[j][i] = Str[i];
if (Board[j][i] == 'S') Start = { j, i };
else if (Board[j][i] == 'F') End = { j, i };
}
}
for (int j = 0; j < N; ++j)
for (int i = 0; i < M; ++i)
FindAround(j, i);
vector<vector<PII>> Dist(N + 1, vector<PII>(M + 1, { MMAX, MMAX }));
Dist[Start.first][Start.second].first = 0;
Dist[Start.first][Start.second].second = 0;
priority_queue<pair<int, Node>, vector<pair<int, Node>>, Comp> PQ;
PQ.push({ 0, Node(0, Start.first, Start.second) });
while (!PQ.empty())
{
int SS = PQ.top().first, SC = PQ.top().second.SC, Y = PQ.top().second.Y, X = PQ.top().second.X;
PQ.pop();
for (int k = 0; k < 4; ++k)
{
int YY = Y + Dir[k].first, XX = X + Dir[k].second;
if (YY < 0 || YY >= N || XX < 0 || XX >= M) continue;
int NextSS = SS, NextSC = SC;
if (Board[YY][XX] == 'g') ++NextSS;
else if(Board[YY][XX] == '.') NextSC += Around[YY][XX];
if (Dist[YY][XX].first > NextSS)
{
Dist[YY][XX].first = NextSS;
Dist[YY][XX].second = NextSC;
PQ.push({ NextSS, Node(NextSC, YY, XX) });
}
else if (Dist[YY][XX].first == NextSS && Dist[YY][XX].second > NextSC)
{
Dist[YY][XX].second = NextSC;
PQ.push({ NextSS, Node(NextSC, YY, XX) });
}
}
}
cout << Dist[End.first][End.second].first << " " << Dist[End.first][End.second].second << '\n';
return 0;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//@삽질
//#define FASTIO ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//#define PII pair<int, int>
//#define MSIZE 51
//#define MMAX 987654321
//int N, M;
//char Board[MSIZE][MSIZE];
//PII Start, End;
//PII Dir[4] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
//
//struct Node
//{
// int SC = 0, Y = 0, X = 0;
// Node(int SCC, int YY, int XX)
// {
// SC = SCC;
// Y = YY;
// X = XX;
// }
//};
//
//struct Comp { bool operator()(pair<int, Node> A, pair<int, Node> B) { return A.first > B.first; } };
//
//int main()
//{
// FASTIO;
// cin >> N >> M;
// for (int j = 0; j < N; ++j)
// {
// for (int i = 0; i < M; ++i)
// {
// char Input; cin >> Input;
// Board[j][i] = Input;
// if (Input == 'F') End = { j, i };
// else if (Input == 'S') Start = { j, i };
// }
// }
//
// vector<vector<PII>> Dist(N + 1, vector<PII>(M + 1, { MMAX, MMAX })); //@차있는칸, 인접한칸
// Dist[Start.first][Start.second].first = 0;
// Dist[Start.first][Start.second].second = 0;
//
// priority_queue<pair<int, Node>, vector<pair<int, Node>>, Comp> PQ; //@차있는칸(SS),인접한칸(SC), Y,X
// PQ.push({ 0, Node(0, Start.first, Start.second) });
// while (!PQ.empty())
// {
// int SS = (PQ.top().first), SC = PQ.top().second.SC, Y = PQ.top().second.Y, X = PQ.top().second.X;
// PQ.pop();
//
// for (int k = 0; k < 4; ++k)
// {
// int YY = Y + Dir[k].first, XX = X + Dir[k].second;
// if (YY < 0 || YY >= N || XX < 0 || XX >= M) continue;
//
// int NextSS = SS;
// int NextSC = SC;
// if (Board[YY][XX] == 'g') ++NextSS;
// else if(Board[YY][XX] == '.')
// {
// for (int j = 0; j < 4; ++j)
// {
// int SCYY = YY + Dir[j].first, SCXX = XX + Dir[j].second;
// if (SCYY < 0 || SCYY >= N || SCXX < 0 || SCXX >= M) continue;
// if (Board[SCYY][SCXX] == 'g') { ++NextSC; break; }
// }
// }
//
// if (Dist[YY][XX].first > NextSS)
// {
// Dist[YY][XX].first = NextSS;
// Dist[YY][XX].second = NextSC;
// PQ.push({ NextSS, Node(NextSC, YY, XX) });
// }
// else if (Dist[YY][XX].first == NextSS && Dist[YY][XX].second > NextSC)
// {
// Dist[YY][XX].second = NextSC;
// PQ.push({ NextSS, Node(NextSC, YY, XX) });
// }
// }
// }
// cout << Dist[(End.first)][(End.second)].first << " " << Dist[(End.first)][(End.second)].second - 1 << '\n';
// return 0;
//}
| true |
899204db3eaec29ece6d9ba68857270666a07837 | C++ | MelisaLuciano/SistemasDistribuidos | /Proyecto3/cliente.cpp | UTF-8 | 841 | 2.5625 | 3 | [] | no_license | #include "Solicitud.h"
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
using namespace std;
int nbytes;
char buffer[BUFSIZ];
int main(int argc, char *argv[]){
if(argc!=6){
cout<<"Agregue: direccion_ip puerto archivo_original nuevo_nombre archivo_deseado"<<endl;
return 0;
}
Solicitud cliente1;
cout<<"Se procedera a enviar el archivo..."<<endl;
int a,b;
int origen=open(argv[3],O_RDONLY);
cliente1.doOperation(argv[1],atoi(argv[2]),ENVIAR,argv[4],argv[4],OPEN,0);
while((nbytes=read(origen,buffer,sizeof(buffer)))>0){
cliente1.doOperation(argv[1],atoi(argv[2]),ENVIAR,argv[4],buffer,WRITE,nbytes);
}
cliente1.doOperation(argv[1],atoi(argv[2]),ENVIAR,argv[4],buffer,CLOSE,0);
close(origen);
return 0;
}
| true |
a2e57bd2878759e0d2ebe59831e175ca07236c29 | C++ | opensupport-ceo/beaglebone-ai-tutorial | /GPIO.cpp | UTF-8 | 2,210 | 2.921875 | 3 | [] | no_license | #include "GPIO.h"
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <iostream>
#include <fstream>
#include <fcntl.h>
#include <sys/ioctl.h>
GPIO::GPIO(int init_num) {
path = default_path + "gpio" + to_string(init_num) ;
num = init_num ;
num_str = to_string(num) ;
gpio_export() ;
}
GPIO::~GPIO() {
gpio_unexport() ;
}
int GPIO::read_value(char* buffer, int len) {
string value_path = path + "/value" ;
f_temp = open(value_path.c_str(), O_RDONLY | O_CLOEXEC) ;
if (f_temp < 0) return f_temp ; // 파일 열기
status = read(f_temp, buffer, len) ;
if (status < 0) return status ;
close(f_temp) ;
return 0 ;
}
int GPIO::write_value(string value) {
string value_path = path + "/value" ;
f_temp = open(value_path.c_str(), O_WRONLY | O_CLOEXEC) ;
if (f_temp < 0) return f_temp ; // 파일 열기
status = write(f_temp, value.c_str(), value.length()) ;
if (status < 0) return status ; // 파일에 값 쓰기
close(f_temp) ; // 파일 닫기
return 0 ;
}
int GPIO::set_dir(string dir) {
string dir_path = path + "/direction" ;
f_temp = open(dir_path.c_str(), O_WRONLY | O_CLOEXEC) ;
if (f_temp < 0) return f_temp ; // 파일 열기
status = write(f_temp, dir.c_str(), dir.length()) ;
if (status < 0) return status ; // 파일에 값 쓰기
close(f_temp) ; // 파일 닫기
return 0 ;
}
int GPIO::gpio_export() {
export_path = default_path + "export" ;
f_temp = open(export_path.c_str(), O_WRONLY | O_CLOEXEC) ;
if (f_temp < 0) return f_temp ; // 파일 열기
status = write(f_temp, num_str.c_str(), num_str.length()) ;
if (status < 0) return status ; // 파일에 값 쓰기
close(f_temp) ; // 파일 닫기
return 0 ;
}
int GPIO::gpio_unexport() {
unexport_path = default_path + "unexport" ;
f_temp = open(unexport_path.c_str(), O_WRONLY | O_CLOEXEC) ;
if (f_temp < 0) return f_temp ; // 파일 열기
status = write(f_temp, num_str.c_str(), num_str.length()) ;
if (status < 0) return status ; // 파일에 값 쓰기
close(f_temp) ; // 파일 닫기
return 0 ;
}
| true |
eb902b548d54ef4e0f6d4dbbe91a1c40ff453f62 | C++ | RedOni3007/Itsukushima | /Itsukushima/Game/Camera.cpp | UTF-8 | 2,619 | 2.5625 | 3 | [] | no_license | #include <Game/Camera.h>
Camera::Camera(void)
{
m_vUP = Vector3(0.0f,1.0f,0.0f);
m_fFOV = 60.0f;
m_fRatio = 16.0f/9.0f;
m_fNearClip = 0.1f;
m_fFarClip = 1000.0f;
m_mProjectionMatrix = glm::perspective( m_fFOV, m_fRatio, m_fNearClip, m_fFarClip);
}
Camera::~Camera(void)
{
}
void Camera::RefreshViewMatrix()
{
if(m_pGameObject != nullptr)
{
Vector3 vPos = m_pGameObject->GetWorldPos();
Vector3 vForward = MFD_Normalize(-m_pGameObject->GetWorldForward());
//camera looking -z, object default facing z, so opposite direction
m_mViewMatrix = glm::lookAt( vPos, vPos + vForward, m_vUP);
}
}
void
Camera::SetFOV(float32 fFOV)
{
m_fFOV = fFOV;
m_mProjectionMatrix = glm::perspective( m_fFOV, m_fRatio, m_fNearClip, m_fFarClip);
}
void
Camera::SetRatio(float32 fRatio)
{
m_fRatio = fRatio;
m_mProjectionMatrix = glm::perspective( m_fFOV, m_fRatio, m_fNearClip, m_fFarClip);
}
void
Camera::SetNearClip(float32 fNearClip)
{
m_fNearClip = fNearClip;
m_mProjectionMatrix = glm::perspective( m_fFOV, m_fRatio, m_fNearClip, m_fFarClip);
}
void
Camera::SetFarClip(float32 fFarClip)
{
m_fFarClip = fFarClip;
m_mProjectionMatrix = glm::perspective( m_fFOV, m_fRatio, m_fNearClip, m_fFarClip);
}
Vector3
Camera::GetUp()
{
return m_vUP;
}
float32
Camera::GetNearClip()
{
return m_fNearClip;
}
float32
Camera::GetFarClip()
{
return m_fFarClip;
}
const Matrix44*
Camera::GetViewMat()
{
return &m_mViewMatrix;
}
const Matrix44*
Camera::GetProjectMat()
{
return &m_mProjectionMatrix;
}
void
Camera::PreLogicUpdate()
{
}
void
Camera::LogicUpdate()
{
RefreshViewMatrix();
}
void
Camera::PostLogicUpdate()
{
RefreshViewMatrix();
}
Vector3
Camera::GetPos()
{
return m_pGameObject->GetWorldPos();
}
Vector3
Camera::GetDir()
{
return -m_pGameObject->GetForward();
}
const char*
Camera::GetName()
{
return "Camera";
}
const char*
Camera::ClassName()
{
return "Camera";
}
void
Camera::CalculateScreenToWorldRay(float32 fSX, float32 fSY, uint32 uWidth, uint32 uHeight,Vector3& vPos, Vector3 &vDir)
{
float32 x = (2.0f * fSX) / uWidth - 1.0f;
float32 y = 1.0f - (2.0f * fSY) / uHeight;
float32 z = 1.0f;
Vector3 ray_screen = Vector3 (x, y, z);
Vector4 ray_clip = Vector4 (ray_screen.x, ray_screen.y, -1.0f, 1.0f);
Vector4 ray_camera = MFD_Inverse(m_mProjectionMatrix) * ray_clip;
ray_camera = Vector4 (ray_camera.x,ray_camera.y, -1.0f, 0.0f);
Vector3 ray_world = Vector3(MFD_Inverse(m_mViewMatrix) * ray_camera);
// don't forget to normalise the vector at some point
ray_world = MFD_Normalize(ray_world);
vPos = m_pGameObject->GetWorldPos();
vDir = ray_world;
} | true |
89d59e53132cda88110418382afdd0c3d42e1205 | C++ | moh008/CS100-lab4-1- | /Composite.h | UTF-8 | 1,590 | 3.21875 | 3 | [] | no_license | #ifndef COMPOSITE_H
#define COMPOSITE_H
#include <iostream>
/*Antonio Martinez and Minwhan Oh*/
using namespace std;
class Base{
public:
/* Constructors */
Base() {};
/* Pure Virtual Functions */
virtual double evaluate() = 0;
};
class Op : public Base{
protected:
double var;
public:
Op(double v): var(v) {};
double evaluate()
{
return this->var;
}
};
/*
class DOp : public Base{
protected:
//Base* left;
//Base* right;
double data;
double data2;
public:
DOp(double d,double d2): data(d), data2(d2){};
virtual double evaluate() = 0;
};*/
class Add: public Base{
protected:
Base* left;
Base* right;
public:
Add(Base* l,Base* r): left(l), right(r) {};
double evaluate()
{
return this->left->evaluate() + this->right->evaluate();
}
};
class Div : public Base{
protected:
Base* left;
Base* right;
public:
Div(Base* l, Base* r): left(l), right(r){};
double evaluate()
{
return this->left->evaluate() / this->right->evaluate();
}
};
class Mult : public Base{
protected:
Base* left;
Base* right;
public:
Mult(Base* l,Base* r): left(l), right(r){};
double evaluate()
{
return this->left->evaluate() * this->right->evaluate();
}
};
class Sub : public Base{
protected:
Base* left;
Base* right;
public:
Sub(Base* l, Base* r): left(l), right(r){};
double evaluate()
{
return this->left->evaluate() - this->right->evaluate();
}
};
class Sqr : public Base{
protected:
Base* var;
public:
Sqr(Base* v): var(v) {};
double evaluate()
{
return this->var->evaluate() * this->var->evaluate();
}
};
#endif
| true |
ca8b39e6663c03ebc12b57514323ca569e2473b8 | C++ | Crisspl/GPU-particle-system | /particles/maths/VecBase.h | UTF-8 | 7,752 | 3.140625 | 3 | [
"MIT"
] | permissive | #ifndef FHL_MATHS_VEC_BASE_H
#define FHL_MATHS_VEC_BASE_H
#include <type_traits>
#include <cmath>
#include <ostream>
#include "BoolVec.h"
#include "Compare.h"
namespace fhl { namespace detail
{
namespace impl
{
template<typename _T>
constexpr _T repeatValue(_T _value, std::size_t) { return _value; }
}
template<std::size_t _N, typename _T>
class VecBase
{
static_assert(std::is_pod<_T>::value, "fhl::detail::VecBase value type must be POD");
static_assert(_N > 1 && _N < 5, "fhl::detail::VecBase dimensions must fit between 2 and 4");
public:
using valueType = _T;
enum { Dimensions = _N };
template<typename ...Args>
constexpr VecBase(_T _first, Args... _args) : m_data{ _first, _T(_args)... }
{
static_assert(sizeof...(Args) == _N - 1, "Arguments count must be equal to `Dimensions`");
}
constexpr VecBase(_T _value) : VecBase(std::make_index_sequence<_N>{}, _T(_value)) {}
private:
template<std::size_t... Is> /* helper ctor for one value constexpr init */
constexpr VecBase(std::index_sequence<Is...>, _T _value) : m_data{ impl::repeatValue(_value, Is)... } {}
public:
template<typename _U>
VecBase(const VecBase<_N, _U> & _other) { *this = _other; }
constexpr VecBase() : VecBase(0) {}
template<typename _U>
VecBase<_N, _T> & operator=(const VecBase<_N, _U> & _other)
{
for (std::size_t i = 0; i < _N; i++)
m_data[i] = _T(_other[i]);
return *this;
}
BoolVec<_N> operator==(const VecBase<_N, _T> & _other) const
{
return getComparisonVector<EqualTo<_T>>(_other, std::make_index_sequence<_N>{});
}
BoolVec<_N> operator!=(const VecBase<_N, _T> & _other) const
{
return ~(*this == _other);
}
BoolVec<_N> operator<(const VecBase<_N, _T> & _other) const
{
return getComparisonVector<Less<_T>>(_other, std::make_index_sequence<_N>{});
}
BoolVec<_N> operator<=(const VecBase<_N, _T> & _other) const
{
return getComparisonVector<LessEqual<_T>>(_other, std::make_index_sequence<_N>{});
}
BoolVec<_N> operator>(const VecBase<_N, _T> & _other) const
{
return getComparisonVector<Greater<_T>>(_other, std::make_index_sequence<_N>{});
}
BoolVec<_N> operator>=(const VecBase<_N, _T> & _other) const
{
return getComparisonVector<GreaterEqual<_T>>(_other, std::make_index_sequence<_N>{});
}
VecBase<_N, _T> operator+(const VecBase<_N, _T> & _other) const { return VecBase<_N, _T>(*this) += _other; }
VecBase<_N, _T> operator-(const VecBase<_N, _T> & _other) const { return VecBase<_N, _T>(*this) -= _other; }
VecBase<_N, _T> operator*(const VecBase<_N, _T> & _other) const { return VecBase<_N, _T>(*this) *= _other; }
VecBase<_N, _T> operator*(_T _scalar) const { return VecBase<_N, _T>(*this) *= _scalar; }
VecBase<_N, _T> operator/(const VecBase<_N, _T> & _other) const { return VecBase<_N, _T>(*this) /= _other; }
VecBase<_N, _T> operator/(_T _scalar) const { return VecBase<_N, _T>(*this) /= _scalar; }
VecBase<_N, _T> operator-() const
{
VecBase<_N, _T> ret;
for (std::size_t i = 0u; i < _N; i++)
ret.m_data[i] = -m_data[i];
return ret;
}
VecBase<_N, _T> & operator+=(const VecBase<_N, _T> & _other)
{
for (std::size_t i = 0u; i < _N; i++)
m_data[i] += _other[i];
return *this;
}
VecBase<_N, _T> & operator-=(const VecBase<_N, _T> & _other)
{
for (std::size_t i = 0u; i < _N; i++)
m_data[i] -= _other[i];
return *this;
}
VecBase<_N, _T> & operator*=(const VecBase<_N, _T> & _other)
{
for (std::size_t i = 0u; i < _N; i++)
m_data[i] *= _other[i];
return *this;
}
VecBase<_N, _T> & operator*=(_T _scalar)
{
for (std::size_t i = 0u; i < _N; i++)
m_data[i] *= _scalar;
return *this;
}
VecBase<_N, _T> & operator/=(const VecBase<_N, _T> & _other)
{
for (std::size_t i = 0u; i < _N; i++)
m_data[i] /= _other[i];
return *this;
}
VecBase<_N, _T> & operator/=(_T _scalar)
{
for (std::size_t i = 0u; i < _N; i++)
m_data[i] /= _scalar;
return *this;
}
_T dot(const VecBase<_N, _T> & _other) const
{
_T dot = 0;
for (std::size_t i = 0; i < _N; i++)
dot += m_data[i] * _other[i];
return dot;
}
double length() const { return std::sqrt(squaredLength()); }
double squaredLength() const { return dot(*this); }
VecBase<_N, _T> normalized() const { return *this / (_T)length(); }
_T & operator[](std::size_t _idx) { return m_data[_idx]; }
constexpr _T operator[](std::size_t _idx) const { return m_data[_idx]; }
constexpr const _T * data() const { return m_data; }
private:
template<typename Op>
/*constexpr */bool idxCompare(const VecBase<_N, _T> & _other, std::size_t _idx) const { return Op{}(m_data[_idx], _other[_idx]); }
template<typename Op, std::size_t... Is>
/*constexpr */BoolVec<_N> getComparisonVector(const VecBase<_N, _T> & _other, std::index_sequence<Is...>) const
{
return BoolVec<_N>(idxCompare<Op>(_other, Is)...);
}
private:
_T m_data[_N];
};
template<std::size_t N, typename T>
VecBase<N, T> operator*(T scalar, const VecBase<N, T> & vec) { return vec * scalar; }
template<std::size_t N, typename T>
std::ostream & operator<<(std::ostream & _out, const VecBase<N, T> & _v)
{
_out << "{ ";
for (int i = 0; i < N; ++i)
_out << _v[i] << (i < N - 1 ? ", " : " }");
return _out;
}
}}
/* put inside class definition in public scope */
/* implements also normalized() method */
#define _FHL_VECTOR_OPERATORS_IMPLEMENTATION(ValueType, VecType) \
VecType<ValueType> operator+(const VecType<ValueType> & _other) const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator+(_other); } \
\
VecType<ValueType> operator-(const VecType<ValueType> & _other) const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator-(_other); } \
\
VecType<ValueType> operator*(const VecType<ValueType> & _other) const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator*(_other); } \
VecType<ValueType> operator*(_T _scalar) const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator*(_scalar); } \
\
VecType<ValueType> operator/(const VecType<ValueType> & _other) const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator/(_other); } \
VecType<ValueType> operator/(_T _scalar) const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator/(_scalar); } \
\
VecType<ValueType> operator-() const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator-(); } \
\
VecType<ValueType> & operator+=(const VecType<ValueType> & _other) \
{ \
fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator+=(_other); \
return *this; \
} \
VecType<ValueType> & operator-=(const VecType<ValueType> & _other) \
{ \
fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator-=(_other); \
return *this; \
} \
VecType<ValueType> & operator*=(const VecType<ValueType> & _other) \
{ \
fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator*=(_other); \
return *this; \
} \
VecType<ValueType> & operator*=(_T _scalar) \
{ \
fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator*=(_scalar); \
return *this; \
} \
VecType<ValueType> & operator/=(const VecType<ValueType> & _other) \
{ \
fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator/=(_other); \
return *this; \
} \
VecType<ValueType> & operator/=(_T _scalar) \
{ \
fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::operator/=(_scalar); \
return *this; \
} \
VecType<ValueType> normalized() const { return fhl::detail::VecBase<VecType<ValueType>::Dimensions, ValueType>::normalized(); }
#endif
| true |
b91f62fa7f508026fcc17bae081d7220820c474d | C++ | James-Sneyd-Gomm/DirectXProject | /DX11 Framework 2018/DX11 Framework 2018/Camera.cpp | UTF-8 | 2,465 | 2.75 | 3 | [] | no_license | #include <iostream>
#include "Camera.h"
using namespace std;
Camera::Camera(XMFLOAT4 eye, XMFLOAT4 up, XMFLOAT4 at, bool free)
{
eyeVal = eye;
upVal = up;
atVal = at;
freeCam = free;
r = 0.0;
if (!freeCam)
{
XMVECTOR Eye = XMVectorSet(eyeVal.x, eyeVal.y, eyeVal.z, eyeVal.w);
XMVECTOR At = XMVectorSet(atVal.x, atVal.y, atVal.z, atVal.w);
XMVECTOR Up = XMVectorSet(upVal.x, upVal.y, upVal.z, upVal.w);
XMStoreFloat4x4(&_viewM, XMMatrixLookAtLH(Eye, At, Up));
}
else if (freeCam)
{
XMVECTOR Eye = XMVectorSet(eyeVal.x, eyeVal.y, eyeVal.z, eyeVal.w);
XMVECTOR At = XMVectorSet(eyeVal.x, eyeVal.y, eyeVal.z + 1.0f, atVal.w);
XMVECTOR Up = XMVectorSet(upVal.x, upVal.y, upVal.z, upVal.w);
XMStoreFloat4x4(&_viewM, XMMatrixLookToLH(Eye, At, Up));
}
}
Camera::~Camera()
{
}
void Camera::SetEye(XMFLOAT4 eye)
{
eyeVal = eye;
}
void Camera::SetAt(XMFLOAT4 at)
{
atVal = at;
}
XMFLOAT4 Camera::GetEye()
{
return eyeVal;
}
XMFLOAT4 Camera::GetAt()
{
return atVal;
}
XMFLOAT4 Camera::GetUp()
{
return upVal;
}
XMFLOAT4X4 Camera::GetView()
{
return _viewM;
}
void Camera::Update()
{
if (freeCam)
{
if (GetAsyncKeyState(VK_UP))
{
eyeVal.x += (atVal.x / 10);
eyeVal.y += (atVal.y / 10);
eyeVal.z += (atVal.z / 10);
}
else if (GetAsyncKeyState(VK_DOWN))
{
eyeVal.x -= (atVal.x / 10);
eyeVal.y -= (atVal.y / 10);
eyeVal.z -= (atVal.z / 10);
}
if (GetAsyncKeyState(VK_LEFT))
{
r -= 0.5;
atVal.x = toF.x;
atVal.y = toF.y;
atVal.z = toF.z;
}
else if (GetAsyncKeyState(VK_RIGHT))
{
r += 0.5;
atVal.x = toF.x;
atVal.y = toF.y;
atVal.z = toF.z;
}
r = XMConvertToRadians(r);
XMVECTOR Eye = XMVectorSet(eyeVal.x, eyeVal.y, eyeVal.z, eyeVal.w);
XMVECTOR To = XMVectorSet(atVal.x, atVal.y, atVal.z, atVal.w);
XMVECTOR Up = XMVectorSet(upVal.x, upVal.y, upVal.z, upVal.w);
XMMATRIX rot = XMMatrixRotationAxis(Up, r);
To = XMVector3Transform(To, rot);
XMStoreFloat4(&toF, To);
XMStoreFloat4x4(&_viewM, XMMatrixLookToLH(Eye, To, Up) * rot);
}
if (!freeCam)
{
XMVECTOR Eye = XMVectorSet(eyeVal.x, eyeVal.y, eyeVal.z, eyeVal.w);
XMVECTOR At = XMVectorSet(atVal.x, atVal.y, atVal.z, atVal.w);
XMVECTOR Up = XMVectorSet(upVal.x, upVal.y, upVal.z, upVal.w);
XMStoreFloat4x4(&_viewM, XMMatrixLookAtLH(Eye, At, Up));
}
}
| true |
34df9d96f7a84bdf7d721a42ea2a707a9da2f38f | C++ | ashwinsuresh83/Data-structures-and-algorithms | /matrix/median of row sorted matrix.cpp | UTF-8 | 641 | 2.59375 | 3 | [] | no_license | int median(int matrix[][100], int r, int c){
// code here
int min=INT_MAX,max=INT_MIN;
for(int i=0;i<r;i++){
if(matrix[i][0]<min)
min=matrix[i][0];
if(matrix[i][c-1]>max)
max=matrix[i][c-1];
}
int desired=(r*c+1)/2;
while(min<max){
int count=0;
int mid=min+(max-min)/2;
for(int i=0;i<r;i++)
count+= upper_bound(matrix[i],matrix[i]+c,mid)-matrix[i];
if(count<desired)
min=mid;
else
max=mid;
}
return min;
}
| true |
1de258b20b8def06c599acd4d0e16dbe252e5b82 | C++ | Dermofet/OOP | /lab2/MyErrors.h | WINDOWS-1251 | 534 | 3.15625 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
class Error : public exception { //
public:
Error() = default; //
explicit Error(const char* msg) : str(msg) {}; //
string what() { return str; }; //
~Error() override = default; //
private:
string str; //
}; | true |
cbf43ae8935a15bc7ac64b90b192770e33597b7f | C++ | caolandix/DarkSynthesis | /jumpdrive/CustomOperator.cpp | UTF-8 | 833 | 3.0625 | 3 | [] | no_license | #include "CustomOperator.h"
CustomOperator::CustomOperator(const string symbol, const bool leftAssociative, const int precedence) {
m_leftAssociative = leftAssociative;
m_symbol = symbol;
m_precedence = precedence;
m_operandCount = 2;
}
CustomOperator::CustomOperator(const string symbol, const bool leftAssociative, const int precedence, const int operandCount) {
m_leftAssociative = leftAssociative;
m_symbol = symbol;
m_precedence = precedence;
m_operandCount = operandCount == 1 ? operandCount : 2;
}
CustomOperator::CustomOperator(const string symbol) {
m_leftAssociative = true;
m_symbol = symbol;
m_precedence = 1;
m_operandCount = 2;
}
CustomOperator::CustomOperator(const string symbol, const int precedence) {
m_leftAssociative = true;
m_symbol = symbol;
m_precedence = precedence;
m_operandCount = 2;
}
| true |
b1aaf548a94f077ba1ca0c312f036cf797d73782 | C++ | torbjornmolin/Stagetimer | /Timer.h | UTF-8 | 617 | 2.625 | 3 | [] | no_license | #pragma once
#include <SDL2/SDL.h>
#include <functional>
#include <SDL2/SDL_timer.h>
#include "TimeDisplay.h"
class Timer
{
public:
Timer();
~Timer();
void Start();
void SetTime(int duration);
void Pause();
void SetTimeDisplay(TimeDisplay *td);
bool IsPaused();
private:
static Uint32 TimerCallback(Uint32 interval, void *param);
int GetSecondsLeft();
bool paused;
int duration;
SDL_TimerID timerID;
static TimeDisplay *_timeDisplay;
static Timer *_timer;
Uint32 Callback2(Uint32 interval);
const int standardInterval = 200;
int startTime;
};
| true |
9f031be01a5bfec4c9956448593e57bdeb6da1c5 | C++ | edujguevara100/P3Lab-6_EduardoGuevara | /Vagon.cpp | UTF-8 | 253 | 2.875 | 3 | [] | no_license | #include "Vagon.h"
Vagon::Vagon(char ident, int posx, int posy): Item(ident){
x = posx;
y = posy;
}
void Vagon::setX(int posx){
x = posx;
}
void Vagon::setY(int posy){
y = posy;
}
int Vagon::getX(){
return x;
}
int Vagon::getY(){
return y;
}
| true |
f75f95d833b59b4a1817246ab38d35022bf3620f | C++ | eaglesky/leetcode | /C++/OneEditDistance.cc | UTF-8 | 809 | 3.359375 | 3 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
bool isOneEditDistance(string s, string t)
{
int ns = s.size();
int nt = t.size();
if (abs(ns - nt) > 1)
return false;
if (ns > nt) {
swap(s, t);
swap(ns, nt);
}
int i = 0;
for (; (i < ns) && (s[i] == t[i]); ++i);
if (i == ns) {
if (nt > ns)
return true;
else
return false;
}
int j = i + 1;
if (ns == nt)
i++;
for (; j < nt; ++j, ++i)
{
if (t[j] != s[i])
return false;
}
return true;
}
int main(int argc, char** argv)
{
string s(argv[1]);
string t(argv[2]);
cout << "s = " << s << endl;
cout << "t = " << t << endl;
cout << isOneEditDistance(s, t) << endl;
return 0;
}
| true |
8b9e60ae79e8d45d2f0f63830f3eac15590ca9a0 | C++ | IAmFunkyFrog/EigenValuesFinder | /libs/RationalNum/RationalNum.cpp | UTF-8 | 9,024 | 3.1875 | 3 | [] | no_license | #include "RationalNum.h"
#include <iostream>
#include <string>
#include <cmath>
#include <vector>
#include <limits.h>
using namespace std;
int absInt(long long int x) {
if (x >= 0) {
return x;
} else {
return -x;
}
}
void getFactors(long long int num, vector<long long int> &factorSet) {
if (num != 1) {
factorSet.push_back(num);
}
for (int i = 2; i <= sqrt(static_cast<double>(num)); i++) {
if (num % i == 0) {
factorSet.push_back(i);
factorSet.push_back(num / i);
}
}
}
void simplifyFun(long long int &a, long long int &b) {
long long int tempN = a;
long long int tempD = b;
long long int small, temp;
vector<long long int> factorSet;
if(tempD < 0) {
tempN = -tempN;
tempD = -tempD;
}
if (tempN == tempD) {
a = 1;
b = 1;
return;
} else if (tempN == -tempD) {
a = -1;
b = 1;
return;
} else if (tempN == 0) {
b = 1;
return;
}
if (absInt(tempN) < absInt(tempD)) {
small = absInt(tempN);
} else {
small = absInt(tempD);
}
getFactors(small, factorSet);
for (int i = 0; i < factorSet.size(); i++) {
temp = factorSet[i];
while (tempN % temp == 0 && tempD % temp == 0) {
tempN /= temp;
tempD /= temp;
}
}
a = tempN;
b = tempD;
}
//friend functions definitions
RationalNum operator+(const RationalNum &left, const RationalNum &right) {
RationalNum temp;
long long int tempLD = left.getDenominator();
long long int tempRD = right.getDenominator();
simplifyFun(tempLD, tempRD);
temp.setDenominator(left.getDenominator() * tempRD);
temp.setNumerator(left.getNumerator() * tempRD + right.getNumerator() * tempLD);
temp.simplify();
return temp;
}
RationalNum operator-(const RationalNum &left, const RationalNum &right) {
return left + (-right);
}
RationalNum operator*(const RationalNum &left, const RationalNum &right) {
RationalNum temp;
RationalNum temp_2(right.getNumerator(), left.getDenominator());
RationalNum temp_3(left.getNumerator(), right.getDenominator());
long long int a = temp_2.getDenominator();
long long int b = temp_2.getNumerator();
long long int c = temp_3.getDenominator();
long long int d = temp_3.getNumerator();
temp.setNumerator(b * d);
temp.setDenominator(a * c);
return temp;
}
RationalNum operator/(const RationalNum &left, const RationalNum &right) {
RationalNum temp_1(left.getNumerator(), left.getDenominator());
RationalNum temp_2(right.getDenominator(), right.getNumerator());
return temp_1 * temp_2;
}
bool operator==(const RationalNum &left, const RationalNum &right) {
return (left.numerator == right.numerator && left.denominator == right.denominator);
}
bool operator!=(const RationalNum &left, const RationalNum &right) {
return !(left == right);
}
bool operator<(const RationalNum &left, const RationalNum &right) {
long long int lside = left.getNumerator() * right.getDenominator();
long long int rside = left.getDenominator() * right.getNumerator();
return (lside < rside);
}
bool operator>(const RationalNum &left, const RationalNum &right) {
long long int lside = left.getNumerator() * right.getDenominator();
long long int rside = left.getDenominator() * right.getNumerator();
return (lside > rside);
}
bool operator<=(const RationalNum &left, const RationalNum &right) {
return ((left < right) || (left == right));
}
bool operator>=(const RationalNum &left, const RationalNum &right) {
return ((left > right) || (left == right));
}
ostream &operator<<(ostream &out, const RationalNum &obj) {
out << obj.numerator;
if (obj.numerator != 0 && obj.denominator != 1) {
out << "/" << obj.denominator;
}
return out;
}
istream &operator>>(istream &in, RationalNum &obj) {
string inputstr;
long long int num = 0;
long long int sign = 1;
bool slashExist = false;
bool dotExist = false;
bool validInput = true;
long long int virtualDenominator = 1;
in >> inputstr;
for (int i = 0; i < inputstr.size(); i++) {
char temp = inputstr[i];
if (temp == '.') {
if (!dotExist && !slashExist && i != 0) {
dotExist = true;
} else {
validInput = false;
break;
}
} else if (temp == '/') {
if (dotExist == false && slashExist == false && i != 0) {
slashExist = true;
obj.setNumerator(sign * num);
num = 0;
sign = 1;
} else {
validInput = false;
break;
}
} else if (temp == '-') {
if (i == 0) {
sign = -sign;
} else if (inputstr[i - 1] == '/') {
sign = -sign;
} else {
validInput = false;
break;
}
} else if (temp <= '9' && temp >= '0') {
if (dotExist) {
if (virtualDenominator > INT_MAX / 10) {
cout << "this frational is too long to handle.";
validInput = false;
break;
} else {
virtualDenominator *= 10;
}
}
if (num > INT_MAX / 10) {
cout << "this number is too long to handle.";
validInput = false;
break;
}
num *= 10;
num += inputstr[i] - '0';
} else {
validInput = false;
break;
}
}
if (validInput == false) {
obj.setNumerator(0);
obj.setDenominator(1);
cout << "Input is not valid! The whole set to 0" << endl;
} else {
if (slashExist == true) {
obj.setDenominator(sign * num);
} else if (dotExist) {
obj.setNumerator(sign * num);
obj.setDenominator(virtualDenominator);
} else {
obj.setNumerator(sign * num);
obj.setDenominator(1);
}
}
obj.simplify();
return in;
}
//member function definition
RationalNum::RationalNum() {
setNumerator(0);
setDenominator(1);
}
RationalNum::RationalNum(double x) {
long long int i = 1;
while (x * i - static_cast<long long int>(x * i) != 0) {
if (i > INT_MAX / 10) {
cout << "this frational number : " << x
<< " can not be transfer to rational number, it's too long, now set it 0." << endl;
setNumerator(0);
setDenominator(1);
return;
} else {
i *= 10;
}
}
setNumerator(x * i);
setDenominator(i);
simplify();
}
RationalNum::RationalNum(long long int numerator_, long long int denominator_) {
setNumerator(numerator_);
setDenominator(denominator_);
simplify();
}
RationalNum &RationalNum::operator=(const RationalNum &obj) {
setNumerator(obj.getNumerator());
setDenominator(obj.getDenominator());
return *this;
}
RationalNum &RationalNum::operator+=(const RationalNum &obj) {
*this = *this + obj;
return *this;
}
RationalNum &RationalNum::operator-=(const RationalNum &obj) {
*this = *this - obj;
return *this;
}
RationalNum &RationalNum::operator*=(const RationalNum &obj) {
*this = *this * obj;
return *this;
}
RationalNum &RationalNum::operator/=(const RationalNum &obj) {
*this = *this / obj;
return *this;
}
RationalNum &RationalNum::operator++() {
*this = *this + 1ll;
return *this;
}
RationalNum RationalNum::operator++(int) {
RationalNum before = *this;
*this = *this + 1ll;
return before;
}
RationalNum &RationalNum::operator--() {
*this = *this - 1ll;
return *this;
}
RationalNum RationalNum::operator--(int) {
RationalNum before = *this;
*this = *this - 1ll;
return before;
}
RationalNum RationalNum::operator+() const {
return *this;
}
RationalNum RationalNum::operator-() const {
RationalNum temp;
temp.setNumerator(-getNumerator());
temp.setDenominator(getDenominator());
return temp;
}
void RationalNum::setNumerator(long long int numerator_) {
numerator = numerator_;
}
int RationalNum::getNumerator() const {
return numerator;
}
void RationalNum::setDenominator(long long int denominator_) {
if (denominator_ == 0) {
denominator = 1;
numerator = 0;
cout << "Denominator is 0! Not good! THe whole is set to 0." << endl;
} else {
denominator = denominator_;
}
}
int RationalNum::getDenominator() const {
return denominator;
}
void RationalNum::simplify() {
long long int tempN = numerator;
long long int tempD = denominator;
simplifyFun(tempN, tempD);
setNumerator(tempN);
setDenominator(tempD);
}
| true |
9ec52edc3be050d3d0b5b2bded867ca493ee6529 | C++ | junkoda/junkoda.github.io | /codes/mockgallib/src/_src/nbar.cpp | UTF-8 | 3,774 | 2.53125 | 3 | [] | no_license | //
// Computes n(z) for given HOD parameter
//
#include <iostream>
#include <string>
#include <cmath>
#include <boost/program_options.hpp>
#include <gsl/gsl_integration.h>
#include "msg.h"
#include "const.h" // -> delta_c
#include "cosmology.h"
#include "growth.h"
#include "power.h"
#include "sigma.h"
#include "mf.h"
#include "hod.h"
#include "nbar.h"
using namespace std;
using namespace boost::program_options;
static double integrand_n_hod(double nu, void* params);
NbarIntegration::NbarIntegration()
{
}
NbarIntegration::NbarIntegration(NbarIntegration const * const ni)
{
// use same setting as ni (for different redshift)
w= ni->w;
s= ni->s;
mf= ni->mf;
hod= ni->hod;
rho_m= ni->rho_m;
D= 0.0;
z= 0.0;
}
NbarIntegration* nbar_integration_alloc(PowerSpectrum const * const ps,
Hod* const hod)
{
NbarIntegration* const ni= new NbarIntegration();
const double M_min= 1.0e10;
const double M_max= 1.0e16;
ni->w= gsl_integration_cquad_workspace_alloc(100);
ni->s= new Sigma(ps, M_min, M_max);
ni->mf= mf_alloc();
ni->hod= hod;
ni->rho_m= cosmology_rho_m();
ni->D= 0.0;
ni->z= 0.0;
msg_printf(msg_debug, "Allocated an nbar_integration\n");
return ni;
}
void nbar_integration_free(NbarIntegration* const ni)
{
gsl_integration_cquad_workspace_free(ni->w);
delete ni->s;
mf_free(ni->mf);
delete ni;
}
void nbar_read(const char filename[], const double z_min, const double z_max,
vector<Nbar>& v)
{
cerr << "nbar file " << filename << endl;
FILE* fp= fopen(filename, "r");
if(fp == 0) {
cerr << "Error: unable to open nbar file " << filename << endl;
throw filename;
}
char buf[256];
while(fgets(buf, 255, fp)) {
Nbar n; n.nbar= 0;
if(buf[0] == '#') continue;
int ret= sscanf(buf, "%le %le", &n.z, &n.nbar); assert(ret == 2);
if(z_min <= n.z && n.z < z_max)
v.push_back(n);
}
fclose(fp);
// set error in the chi2 fitting
for(vector<Nbar>::iterator p= v.begin(); p != v.end(); ++p)
p->dnbar= p->nbar; // relative error
}
double integrand_n_hod(double nu, void* params)
{
// Returns number density dn/dnu of HOD parameters
// requirement: D computed for z
// tinker_set_redshift(z)
//
// dn= P(n|HOD)*n(M) dnu
// nu = delta_c/sigma(M,z), sigma(M,z) = D(z) sigma0(M)
// rho_m
NbarIntegration* const ni= (NbarIntegration*) params;
const double sigma0= delta_c/(ni->D*nu);
const double M= ni->s->M(sigma0);
return ni->hod->ncen(M)*(1.0 + ni->hod->nsat(M))*
mf_f(ni->mf, nu)*ni->rho_m/M;
}
/*
void nbar_compute_nz(const double c[], vector<Nbar>* const v)
{
// Input: parameters c[10]
// Ouput: v
Hod hod;
// Computes nbar(z) from given parametrisation c[10]
for(vector<Nbar>::iterator p= v->begin(); p != v->end(); ++p) {
double z= p->z;
hod_compute(c, z, &hod); // c, z --> hod(z; c)
p->nbar= compute_n_hod(&hod, z); // hod(z) --> nbar(z)
}
}
*/
double nbar_compute(NbarIntegration* const ni, const double z)
{
// Computes number density of HOD galaxies from HOD parameters 'hod'
// n = \int P(n|HOD)*n(M) dnu
const double a= 1.0/(1.0 + z);
ni->hod->compute_param_z(z);
if(ni->D == 0.0 || ni->z != z) {
mf_set_redshift(ni->mf, a);
ni->D= growth_D(a);
ni->z= z;
msg_printf(msg_verbose,
"setting nbar_integration at z=%.3f, D=%.4f, mf->alpha=%.4f\n",
ni->z, ni->D, ni->mf->alpha);
}
gsl_function F;
F.function= &integrand_n_hod;
F.params= (void*) ni;
const double nu_min= delta_c*ni->s->sinv_min/ni->D;
const double nu_max= delta_c*ni->s->sinv_max/ni->D;
double result;
gsl_integration_cquad(&F, nu_min, nu_max, 1.0e-5, 1.0e-5, ni->w,
&result, 0, 0);
return result;
}
| true |
14cafac82fc238c098ee170d3b188e9d00ab57d2 | C++ | ghazi-naceur/arduino-sketchs | /src/main/c/sensors/hc-sr04-ultrasonic-sensor/hc-sr04-ultrasonic-sensor.ino | UTF-8 | 817 | 2.96875 | 3 | [] | no_license |
const byte TRIGGER_PIN = 2; // Broche TRIGGER
const byte ECHO_PIN = 3; // Broche ECHO
const unsigned long MEASURE_TIMEOUT = 25000UL; // 25ms = ~8m à 340m/s
const float SOUND_SPEED = 340.0 / 1000;
void setup() {
Serial.begin(115200);
pinMode(TRIGGER_PIN, OUTPUT);
digitalWrite(TRIGGER_PIN, LOW);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
long measure = pulseIn(ECHO_PIN, HIGH, MEASURE_TIMEOUT);
float distance_mm = measure / 2.0 * SOUND_SPEED;
Serial.print(F("Distance: "));
Serial.print(distance_mm);
Serial.print(F("mm ("));
Serial.print(distance_mm / 10.0, 2);
Serial.print(F("cm, "));
Serial.print(distance_mm / 1000.0, 2);
Serial.println(F("m)"));
delay(500);
}
| true |
ea244fa1be83d266006853ffe07ac4774366e6d6 | C++ | TemporalKing/Distributed-Minimum-Spanning-Tree | /Prims.cpp | UTF-8 | 1,518 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <limits.h>
#include "Prims.h"
using namespace std;
extern int number_of_nodes;
int Prims::getEdgeBetween(int i, int j) {
return graph[i*number_of_nodes + j];
}
int Prims::minIndexNotInSet(const vector <int> key) {
int min = INT_MAX, min_index;
for (int i = 0; i < number_of_nodes; i++) {
if (mst_set.find(i) == mst_set.end() && key[i] < min) {
min = key[i];
min_index = i;
}
}
return min_index;
}
void Prims::printMst() {
for (int i = 0; i < number_of_nodes; i++) {
if (mst[i] != -1)
cout << i<< " --- " << mst[i] << " " << getEdgeBetween(mst[i], i)<< endl;
}
}
void Prims::findMst() {
// Key vector to manage the validity of various vertices.
vector <int> key(number_of_nodes);
mst.resize(number_of_nodes);
for (int i = 0; i < number_of_nodes; i++) {
key[i] = INT_MAX;
mst[i] = -1;
}
// Include 1st node;
key[0] = 0;
// Include one vertex in every iteration.
for (int i = 0; i < number_of_nodes; i++) {
int min_index = minIndexNotInSet(key);
mst_set.insert(min_index);
for (int i = 0; i < number_of_nodes; i++) {
if (getEdgeBetween(min_index, i) && mst_set.find(i) == mst_set.end()
&& getEdgeBetween(min_index, i) <= key[i]) {
mst[i] = min_index;
key[i] = getEdgeBetween(min_index, i);
}
}
}
}
| true |
6b3af30889ce6907a62c6085e9a9931a0fe91e27 | C++ | icsfy/some_little_stuff | /c++/ch12/cow.h | UTF-8 | 1,691 | 3.6875 | 4 | [] | no_license | #ifndef COW_H
#define COW_H
class Cow {
char name[20];
char * hobby;
double weight;
public:
Cow();
Cow(const char * nm, const char * ho, double wt);
Cow(const Cow & c);
~Cow();
Cow & operator=(const Cow & c);
void ShowCow() const; //display all cow data
};
#endif
#ifndef COW_C
#define COW_C
#include <iostream>
#include <cstring>
Cow::Cow()
{
name[0] = 'C', name[1] = 'o', name[2] = 'w', name[3] = '\0';
hobby = new char[4];
std::strcpy(hobby, "Cow's hobby");
weight = 0.0;
}
Cow::Cow(const char * nm, const char * ho, double wt)
{
for(int i=0;nm[i] != '\0' && i<20;i++){
name[i] = nm[i];
i<19?name[i+1] = '\0':name[19]='\0';
}
// name[19] = '\0';
hobby = new char[std::strlen(ho)+1];
std::strcpy(hobby, ho);
weight = wt;
}
Cow::Cow(const Cow & c)
{
for(int i=0;c.name[i] != '\0' && i<20;i++){
name[i] = c.name[i];
i<19?name[i+1] = '\0':name[19]='\0';
}
// name[19] = '\0';
hobby = new char[std::strlen(c.hobby)+1];
std::strcpy(hobby, c.hobby);
weight = c.weight;
}
Cow::~Cow()
{
std::cout << " [" << name << ',' << hobby << ',' << weight << "] destoryed.\n";
delete [] hobby;
}
Cow & Cow::operator=(const Cow & c)
{
if(&c == this)
return *this;
delete [] hobby;
for(int i=0;c.name[i] != '\0' && i<20;i++){
name[i] = c.name[i];
i<19?name[i+1] = '\0':name[19]='\0';
}
// name[19] = '\0';
hobby = new char[std::strlen(c.hobby)+1];
std::strcpy(hobby, c.hobby);
weight = c.weight;
return *this;
}
void Cow::ShowCow() const
{
std::cout << " name: " << name << std::endl
<< " hobby: " << hobby << std::endl
<< " weight: " << weight << std::endl;
}
#endif
| true |
db0fbcd5076598160e40c41ef1471ae46af96954 | C++ | pengchant/C-C- | /2.数据结构/2.3线性表-栈结构/main.cpp | UTF-8 | 1,846 | 3.78125 | 4 | [] | no_license | #include <iostream>
#include <cstring>
#include <cstdlib>
#define MAXLEN 50
using namespace std;
// 定义栈的数据结构
typedef struct{
char name[10];
int age;
}DATA;
typedef struct stack{
DATA data[MAXLEN+1];
int top;
}StackType;
// 初始化栈
StackType* STInit(){
StackType* p;
if(p = (StackType*)malloc(sizeof(StackType))){
p->top = 0;
return p;
}
return NULL;
}
// 判断空栈
int STIsEmpty(StackType* s){
if(s&&s->top!=0){
return 0;
}
return 1;
}
// 判断满栈
int STIsFull(StackType* s){
if(s&&s->top==MAXLEN){
return 1;
}
return 0;
}
// 清空栈
void STClear(StackType* s){
s->top = 0;
}
// 释放空间
void STFree(StackType* s){
if(s){
free(s);
}
}
// 入栈
int PushST(StackType* s,DATA data){
if((s->top+1)>MAXLEN){
cout<<"栈溢出!"<<endl;
return 0;
}
s->data[++s->top] = data;
return 1;
}
// 出栈
DATA PopST(StackType* s){
if(STIsEmpty(s)){
cout<<"栈为空"<<endl;
exit(0);
}
return (s->data[s->top--]);
}
// 读取结点数据
DATA PeekST(StackType* s){
if(STIsEmpty(s)){
cout<<"栈为空"<<endl;
exit(0);
}
return (s->data[s->top]);
}
// 栈结构操作实例
int main(){
StackType* stack;
DATA data,data1;
stack = STInit();
cout<<"入栈操作"<<endl;
cout<<"输入姓名 年龄进入栈操作"<<endl;
do{
cin>>data.name>>data.age;
if(strcmp(data.name,"0")==0){
break;
}
PushST(stack,data);
}while(1);
do{
cout<<"出栈操作"<<endl;
getchar();
data1 = PopST(stack);
cout<<"出栈的数据是:"<<data1.name<<data1.age<<endl;
}while(1);
STFree(stack);
getchar();
return 0;
}
| true |
68bb8e36e0f141c7c676249a871f5bb393faf834 | C++ | KrzysiekJa/Warehouse-System | /Warehouse-System/Seller.cpp | UTF-8 | 2,371 | 2.96875 | 3 | [] | no_license | #include <string>
#include <iostream>
#include "Employee.h"
#include "Seller.h"
#include "OrderCreationInterface.h"
#include "OrdersControlSystem.h"
#include "Messenger.h"
#include "Receipt.h"
#include "Client.h"
Seller::Seller(int n_id) : Employee(n_id) {}
void Seller::sendReceipt(std::string receipt_id) {
sql_string = "SELECT OWNER_ID, ORDER_ID, DATA FROM RECEIPTS WHERE ID = " + receipt_id + "";
executeQuery(sql_string);
}
void Seller::sellerMenu() {
while (true) {
OrdersControlSystem oCSys;
OrderCreationInterface oCInter;
Messenger mess;
std::string str;
std::string client_id, status, name, amount, messageID, message, receiver, order_id, receipt_id, data;
std::cout << "Choose : create, show all (order(s)), add (product), receipt, read, send (message), logout" << std::endl;
std::cin >> str;
if (str == "create") {
std::cout << "Client's id : ";
std::cin >> client_id;
std::cout << "Product's status : ";
std::cin >> status;
oCInter.createOrder(client_id, status);
}
if (str == "show all" || str == "all") {
oCSys.showListOfOrdres();
}
if (str == "add") {
std::cout << "Product's name : ";
std::cin >> name;
std::cout << "Amount : ";
std::cin >> amount;
std::cout << "Order id : ";
std::cin >> order_id;
std::cout << "Status : ";
std::cin >> status;
oCInter.addProduct(name, amount, order_id, status);
}
if (str == "receipt") {
std::cout << "Choose : create, show" << std::endl;
std::cin >> str;
if (str == "create") {
Receipt receipt;
std::cout << "Client's id : ";
std::cin >> client_id;
std::cout << "Order id : ";
std::cin >> order_id;
std::cout << "Receipt data: ";
std::cin >> data;
receipt.create(client_id, order_id, data);
}
if (str == "show") {
std::cout << "Receipt's id : ";
std::cin >> receipt_id;
sendReceipt(receipt_id);
}
}
if (str == "read") {
std::cout << "Massage's id : ";
std::cin >> messageID;
mess.readMessage(messageID);
}
if (str == "send") {
std::cout << "Sender id : ";
int id;
std::cin >> id;
std::cout << "Receiver's id : ";
std::cin >> receiver;
std::cout << "Massage : ";
std::cin >> message;
std::string ss = std::to_string(id);
mess.sendMessage(message, receiver, ss);
}
if (str == "logout") {
return;
}
}
} | true |
62e088c2df5575d3b2af050d392fc801c99ff3db | C++ | BarIfrah/Hulda-FinalProject | /src/MovingObject.cpp | UTF-8 | 2,876 | 2.78125 | 3 | [] | no_license | #include "MovingObject.h"
#include "Resources.h"
#include <iostream>
//==================== Constructors & destructors section ====================
MovingObject::MovingObject(b2World& world, const sf::Vector2f& location,
const sf::Vector2f& size, int objectType,int ID)
: GameObject(DYNAMIC, world, location, size, objectType, true,ID),
m_direction(RIGHT), m_state(IDLE), m_initialLocation(location)
{
m_objectSprite = getSpritePtr();
}
//===========================================================================
void MovingObject::setState(int state, int height, int width, int regOffset, int specialOffset) {
int offset;
switch (state) {
case RUN:
offset = height + regOffset;
break;
case JUMP: /// Also applies to 'FALL' state
offset = 2 * height + regOffset + specialOffset;
break;
case DIE:
offset = DIE * height + regOffset + specialOffset;
break;
default:
offset = 0;
break;
}
//std:: cout << offset << " state: " << state << " mstate " << m_state << '\n';
if (m_state != state) {
sf::IntRect updatedRect = getIntRect();
updatedRect.top = offset;
updatedRect.left = 0;
if (updatedRect.width < 0)
updatedRect.left += width;
setIntRect(updatedRect);
}
m_state = state;
}
//===========================================================================
int MovingObject::getState()const {
return m_state;
}
//===========================================================================
void MovingObject::setDirection(int direction) {
m_direction = direction;
}
//===========================================================================
int MovingObject::getDirection()const {
return m_direction;
}
//===========================================================================
sf::Vector2f MovingObject::getInitialLocation() const
{
return m_initialLocation;
}
//===========================================================================
void MovingObject::reset()
{
setState(IDLE, PLAYER_BOX_HEIGHT, PLAYER_BOX_WIDTH, PLAYER_OFFSET, PLAYER_SPECIAL_OFFSET);
setPhysicsObjectPos(getInitialLocation(), b2Vec2(0, 0));
}
//===========================================================================
void MovingObject::resetAnimationTime() {
m_animationTime = sf::seconds(0);
}
//===========================================================================
//sf::Sprite MovingObject::getObjectSprite() {
// return *m_objectSprite;
//}
//===========================================================================
void MovingObject::setAnimationTime(const sf::Time & deltaTime) {
m_animationTime += deltaTime;
}
//===========================================================================
sf::Time MovingObject::getAnimationTime() const {
return m_animationTime;
} | true |
69640ab702f5f57a3dd4c34bad767b35eeb87e88 | C++ | xienezheng/cPractice | /dataStruct/数据结构练习初级/栈,队列/数据结构--队列栈应用3.12进制转换/main.cpp | UTF-8 | 925 | 3.328125 | 3 | [] | no_license | #include <iostream>
using namespace std;
template<class T>
class queue1
{
private:
T *p;
int top;
int next;
int size;
public:
queue1()
{
p=new T[20];
size=0;
next=top=0;
}
void push(const T&temp)
{
p[next]=temp;
size=size+1;
next=next+1;
}
T size1()
{
return(size);
}
T getdate()
{
return(p[top]);
}
void pop()
{
top=top+1;
size=size-1;
}
bool empty()
{
if(size==0)
{
return(true);
}
else{
return(false);
}
}
};
int main()
{
queue1<int>q;
int i,j,temp,N,B;
cout<<"Please enter the Nand B"<<endl;
cin>>N>>B;
while(N!=0)
{
temp=N%B;
q.push(temp);
N=N/B;
}
while(q.empty()==false)
{
cout<<q.getdate();
q.pop();
}
}
| true |
e8a82dbf9d89235f0edeb805a441edd7ba7b49ed | C++ | lzj112/Data-Structure | /BinaryTree/AVL.cpp | UTF-8 | 7,798 | 3.890625 | 4 | [] | no_license | #include <queue>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
struct AVLNode
{
AVLNode()
: val(0), left(nullptr), right(nullptr)
{}
AVLNode(int v)
: val(v), left(nullptr), right(nullptr)
{}
int val; //data
// int height; //当前结点高度
AVLNode* left;
AVLNode* right;
};
class AVLTree
{
public:
AVLTree() : root(nullptr)
{}
~AVLTree()
{}
//查找某特定值结点
AVLNode* findNode(int val)
{
return findNodeInTree(root, val);
}
//插入结点,t为插入节点
void insert(int v)
{
insertNode(&root, v);
}
//删除结点,val是待删除结点data
void delNode(int val)
{
delNodeFromTree(&root, val);
}
//层次遍历
void traverse()
{
if (root != nullptr)
{
queue<AVLNode *> q;
q.push(root);
AVLNode* tmpPtr;
while (!q.empty())
{
tmpPtr = q.front();
q.pop();
cout << tmpPtr->val << ' ';
if (tmpPtr->left != nullptr)
q.push(tmpPtr->left);
if (tmpPtr->right != nullptr)
q.push(tmpPtr->right);
}
cout << endl;
}
}
//求结点所在高度(只有一个根结点时高度为1)
int getHeight(AVLNode* t)
{
int leftHeight, rightHeight;
if (t != nullptr)
{
leftHeight = getHeight(t->left);
rightHeight = getHeight(t->right);
return (leftHeight > rightHeight) ?
(leftHeight + 1) : (rightHeight + 1);
}
else
return 0;
}
private:
//左左情况旋转(t是失衡结点)
void LL(AVLNode** t)
{
if (t != nullptr)
{
AVLNode* tmpPtr = (*t)->left;
(*t)->left = tmpPtr->right; //t左子树的右子树作为t的左子树
tmpPtr->right = *t;
*t = tmpPtr;
}
}
//右右情况旋转
void RR(AVLNode** t)
{
if (t != nullptr)
{
AVLNode* tmpPtr = (*t)->right;
(*t)->right = tmpPtr->left;
tmpPtr->left = *t;
*t = tmpPtr;
}
}
//左右情况旋转 (t为失衡结点,新节点位于t的左子树的右子树)
void LR(AVLNode** t)
{
RR(&(*t)->left);
LL(t);
}
//右左情况旋转
void RL(AVLNode** t)
{
LL(&(*t)->right);
RR(t);
}
//插入结点
void insertNode(AVLNode** t, int v)
{
//插入结点,使用二级指针改变父节点左右子树指针指向
if (*t == nullptr)
*t = new AVLNode(v);
else if (v < (*t)->val)
{
insertNode(&((*t)->left), v);
int leftH = getHeight((*t)->left);
int rightH = getHeight((*t)->right);
//插入到左子树,肯定是左子树高度更高,判断这时平衡因子是否大于1
if ((leftH - rightH) > 1)
{
if (v < (*t)->left->val)
LL(t);
else
LR(t);
}
}
else if (v > (*t)->val)
{
insertNode(&((*t)->right), v);
int leftH = getHeight((*t)->left);
int rightH = getHeight((*t)->right);
if ((rightH - leftH) > 1)
{
if (v > (*t)->right->val)
RR(t);
else
RL(t);
}
}
else
return ;
}
AVLNode* findNodeInTree(AVLNode* node, int val)
{
if (node != nullptr)
{
if (val < node->val)
return findNodeInTree(node->left, val);
else if (val > node->val)
return findNodeInTree(node->right, val);
else
return node;
}
else
return nullptr;
}
int findMaxKeyInLef(AVLNode* node)
{
if (node == nullptr)
return 0;
else if (node->right == nullptr)
return node->val;
return findMaxKeyInLef(node->right);
}
AVLNode* delNodeFromTree(AVLNode** node, int val)
{
if (node == nullptr)
return nullptr;
else if (val < (*node)->val)
{
(*node)->left = delNodeFromTree(&(*node)->left, val);
//判断是否失衡,删了左子树一个结点,所以判断右子树高度是否过高
if ((getHeight((*node)->right) - getHeight((*node)->left)) > 1)
//右子树的左子树高度比右子树的右子树更高,相当于给右子树的右子树插入了新节点,相当于"右右"情况
if (getHeight((*node)->right->left) > getHeight((*node)->right->right))
RL(node);
else
RR(node);
return (*node);
}
else if (val > (*node)->val)
{
(*node)->right = delNodeFromTree(&(*node)->right, val);
//判断是否失衡,删了右子树一个结点,所以判断左子树高度是否过高
if ((getHeight((*node)->left) - getHeight((*node)->right)) > 1)
//左子树的左子树高度比右子树的右子树更高,相当于给左子树的左子树插入了新节点,相当于"左左"情况
if (getHeight((*node)->left->left) > getHeight((*node)->left->right))
LL(node);
else
LR(node);
return (*node);
}
else if (val == (*node)->val)
{
//如果是叶子节点
if ((*node)->left == nullptr && (*node)->right == nullptr)
{
delete (*node);
(*node) = nullptr;
return (*node);;
}
//如果左子树非空,将右子树续接到父节点
else if ((*node)->left != nullptr)
{
AVLNode* tmp = (*node)->left;
delete (*node);
return tmp;
}
//如果右子树非空,将左子树续接到父节点
else if ((*node)->right != nullptr)
{
AVLNode* tmp = (*node)->right;
delete (*node);
return tmp;
}
//左右子树皆非空
else
{
//寻找左子树中最大节点,即左子树中最右节点
//(也可以寻找右子树中最小节点,即右子树中最左节点)
int maxVal = findMaxKeyInLef((*node)->left);
//交换这两个节点
(*node)->val = maxVal;
//删除那个用来交换的节点
(*node)->left = delNodeFromTree(&(*node)->left, maxVal);
return *node;
}
}
}
AVLNode* root;
};
int main()
{
AVLTree tree;
// vector<int> tmp = {99, 1, 34, 23, 67, 7};
vector<int> tmp = {99, 1, 34, 56, 23, 67, 78, 9, 45, 684, 35, 678, 234, 89, 90, 24, 672, 1, 1, 4};
for (auto x : tmp)
{
tree.insert(x);
}
tree.traverse();
AVLNode* p = tree.findNode(672);
if (p == nullptr)
cout << "672 is not in the tree" << endl;
else
cout << "succeed in finding " << p->val << endl;
tree.delNode(672);
tree.traverse();
p = tree.findNode(672);
if (p == nullptr)
cout << "672 is not in the tree" << endl;
else
cout << "succeed in finding " << p->val << endl;
} | true |
91f813a241fcb79f2f063943df156cc2af93bffc | C++ | kodo-pp/ModBox | /Project/include/modules/module_manager.hpp | UTF-8 | 829 | 2.578125 | 3 | [
"MIT"
] | permissive | #ifndef MODULES_MODULE_MANAGER_HPP
#define MODULES_MODULE_MANAGER_HPP
#include <string>
#include <map>
#include <modules/module.hpp>
// TEMP: maybe we should change it to something more complex
using ModuleMessage = std::wstring;
/**
* Manages modules
*
* There should be only one instance of it
*/
class ModuleManager {
public:
ModuleManager(std::unordered_map <ModuleId, Module> _modules);
void loadModule(ModuleId id);
void unloadModule(ModuleId id);
void deleteModule(ModuleId id);
void sendModuleMessage(ModuleId moduleId, ModuleMessage message);
ModuleMessage recieveModuleMessage(ModuleId moduleId, ModuleMessage message);
protected:
std::unordered_map <ModuleId, Module> modules;
};
extern ModuleManager moduleManager;
#endif /* end of include guard: MODULES_MODULE_MANAGER_HPP */
| true |
d6511c4ad08be2675fed228e5f676a6ca39b9fc9 | C++ | J-Vernay/Ariane-simulator-NX-move | /src/widgets/glscenewidget.hpp | UTF-8 | 1,296 | 2.953125 | 3 | [] | no_license | #ifndef GLSCENEWIDGET_HPP
#define GLSCENEWIDGET_HPP
#include <QOpenGLWidget>
#include "../gameobjects/maze.h"
#include "../gameobjects/cell.h"
#include "../gameobjects/player.hpp"
#include "../gameobjects/abstractitem.hpp"
/**
* @brief Classe d'affichage de la scene 3D OpenGL
*/
class GLSceneWidget : public QOpenGLWidget
{
Q_OBJECT
Maze * mMaze; // Labyrinthe
Player * mPlayer; // Joueur
std::vector<AbstractItem *> * mGameItems; // Objets collectibles
public:
// Constructeur
explicit GLSceneWidget(QWidget *parent = nullptr);
// Asssociation avec le labyrinthe
void setMaze(Maze * maze) { mMaze = maze; };
// Association avec le joueur
void setPlayer(Player * player) { mPlayer = player; };
// Association avec la collection d'items
void setGameItems(std::vector<AbstractItem *> * gameItems) { mGameItems = gameItems; };
protected:
// Fonction d'initialisation d'OpenGL
void initializeGL();
// Fonction de redimensionnement du widget OpenGL
void resizeGL(int width, int height);
// Fonction d'affichage OpenGL
void paintGL();
// Mise à jour de la position de la caméra
void updateView();
// Affichage du labyrinthe
void displayWorld();
};
#endif // GLSCENEWIDGET_HPP
| true |
cd7350016eca786af9ac2a734700e9b3b0ccfaa9 | C++ | dhruvsasuke/reachy_ibvs | /src/reachy_vel_moveit/src/Jacobians_base_wrist_hand.cpp | UTF-8 | 12,658 | 2.53125 | 3 | [] | no_license | void getJacobianBaseShoulder(std::vector<double> q,Eigen::Matrix<double,6,6> &J)
{
J.setZero();
double shoulder_pitch=q[0];
double shoulder_roll=q[1];
double arm_yaw=q[2];
double elbow_pitch=q[3];
double forearm_yaw=q[4];
double wrist_pitch=q[5];
J(0,0)=0;
J(1,0)=0;
J(2,0)=0;
J(3,0)=0;
J(4,0)=1.00000000000000;
J(5,0)=0;
}
void getJacobianBaseShoulder_to_arm(std::vector<double> q,Eigen::Matrix<double,6,6> &J)
{
J.setZero();
double shoulder_pitch=q[0];
double shoulder_roll=q[1];
double arm_yaw=q[2];
double elbow_pitch=q[3];
double forearm_yaw=q[4];
double wrist_pitch=q[5];
J(0,0)=0;
J(0,1)=0;
J(1,0)=0;
J(1,1)=0;
J(2,0)=0;
J(2,1)=0;
J(3,0)=0;
J(3,1)=1.0*cos(shoulder_pitch);
J(4,0)=1.00000000000000;
J(4,1)=0;
J(5,0)=0;
J(5,1)=-1.0*sin(shoulder_pitch);
}
void getJacobianBaseUpper_arm(std::vector<double> q,Eigen::Matrix<double,6,6> &J)
{
J.setZero();
double shoulder_pitch=q[0];
double shoulder_roll=q[1];
double arm_yaw=q[2];
double elbow_pitch=q[3];
double forearm_yaw=q[4];
double wrist_pitch=q[5];
J(0,0)=0;
J(0,1)=0;
J(0,2)=0;
J(1,0)=0;
J(1,1)=0;
J(1,2)=0;
J(2,0)=0;
J(2,1)=0;
J(2,2)=0;
J(3,0)=0;
J(3,1)=1.0*cos(shoulder_pitch);
J(3,2)=1.0*sin(shoulder_pitch)*cos(shoulder_roll);
J(4,0)=1.00000000000000;
J(4,1)=0;
J(4,2)=-1.0*sin(shoulder_roll);
J(5,0)=0;
J(5,1)=-1.0*sin(shoulder_pitch);
J(5,2)=1.0*cos(shoulder_pitch)*cos(shoulder_roll);
}
void getJacobianBaseForearm(std::vector<double> q,Eigen::Matrix<double,6,6> &J)
{
J.setZero();
double shoulder_pitch=q[0];
double shoulder_roll=q[1];
double arm_yaw=q[2];
double elbow_pitch=q[3];
double forearm_yaw=q[4];
double wrist_pitch=q[5];
J(0,0)=-0.30745*cos(shoulder_pitch)*cos(shoulder_roll);
J(0,1)=0.30745*sin(shoulder_pitch)*sin(shoulder_roll);
J(0,2)=0;
J(0,3)=0;
J(1,0)=0;
J(1,1)=0.30745*(sin(shoulder_pitch)*sin(shoulder_pitch))*cos(shoulder_roll) + 0.30745*(cos(shoulder_pitch)*cos(shoulder_pitch))*cos(shoulder_roll);
J(1,2)=0;
J(1,3)=0;
J(2,0)=0.30745*sin(shoulder_pitch)*cos(shoulder_roll);
J(2,1)=0.30745*sin(shoulder_roll)*cos(shoulder_pitch);
J(2,2)=0;
J(2,3)=0;
J(3,0)=0;
J(3,1)=1.0*cos(shoulder_pitch);
J(3,2)=1.0*sin(shoulder_pitch)*cos(shoulder_roll);
J(3,3)=-1.0*sin(arm_yaw)*cos(shoulder_pitch) + 1.0*sin(shoulder_pitch)*sin(shoulder_roll)*cos(arm_yaw);
J(4,0)=1.00000000000000;
J(4,1)=0;
J(4,2)=-1.0*sin(shoulder_roll);
J(4,3)=1.0*cos(arm_yaw)*cos(shoulder_roll);
J(5,0)=0;
J(5,1)=-1.0*sin(shoulder_pitch);
J(5,2)=1.0*cos(shoulder_pitch)*cos(shoulder_roll);
J(5,3)=1.0*sin(arm_yaw)*sin(shoulder_pitch) + 1.0*sin(shoulder_roll)*cos(arm_yaw)*cos(shoulder_pitch);
}
void getJacobianBaseWrist(std::vector<double> q,Eigen::Matrix<double,6,6> &J)
{
J.setZero();
double shoulder_pitch=q[0];
double shoulder_roll=q[1];
double arm_yaw=q[2];
double elbow_pitch=q[3];
double forearm_yaw=q[4];
double wrist_pitch=q[5];
J(0,0)=-0.30745*cos(shoulder_pitch)*cos(shoulder_roll);
J(0,1)=0.30745*sin(shoulder_pitch)*sin(shoulder_roll);
J(0,2)=0;
J(0,3)=0;
J(0,4)=0;
J(1,0)=0;
J(1,1)=0.30745*(sin(shoulder_pitch)*sin(shoulder_pitch))*cos(shoulder_roll) + 0.30745*(cos(shoulder_pitch)*cos(shoulder_pitch))*cos(shoulder_roll);
J(1,2)=0;
J(1,3)=0;
J(1,4)=0;
J(2,0)=0.30745*sin(shoulder_pitch)*cos(shoulder_roll);
J(2,1)=0.30745*sin(shoulder_roll)*cos(shoulder_pitch);
J(2,2)=0;
J(2,3)=0;
J(2,4)=0;
J(3,0)=0;
J(3,1)=1.0*cos(shoulder_pitch);
J(3,2)=1.0*sin(shoulder_pitch)*cos(shoulder_roll);
J(3,3)=-1.0*sin(arm_yaw)*cos(shoulder_pitch) + 1.0*sin(shoulder_pitch)*sin(shoulder_roll)*cos(arm_yaw);
J(3,4)=1.0*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) + 1.0*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll);
J(4,0)=1.00000000000000;
J(4,1)=0;
J(4,2)=-1.0*sin(shoulder_roll);
J(4,3)=1.0*cos(arm_yaw)*cos(shoulder_roll);
J(4,4)=1.0*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) - 1.0*sin(shoulder_roll)*cos(elbow_pitch);
J(5,0)=0;
J(5,1)=-1.0*sin(shoulder_pitch);
J(5,2)=1.0*cos(shoulder_pitch)*cos(shoulder_roll);
J(5,3)=1.0*sin(arm_yaw)*sin(shoulder_pitch) + 1.0*sin(shoulder_roll)*cos(arm_yaw)*cos(shoulder_pitch);
J(5,4)=1.0*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) + 1.0*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll);
}
void getJacobianBaseWrist_hand(std::vector<double> q,Eigen::Matrix<double,6,6> &J)
{
J.setZero();
double shoulder_pitch=q[0];
double shoulder_roll=q[1];
double arm_yaw=q[2];
double elbow_pitch=q[3];
double forearm_yaw=q[4];
double wrist_pitch=q[5];
J(0,0)=-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll) - 0.30745*cos(shoulder_pitch)*cos(shoulder_roll);
J(0,1)=1.0*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch) + 0.30745*sin(shoulder_roll))*sin(shoulder_pitch);
J(0,2)=-1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll) - 0.30745*cos(shoulder_pitch)*cos(shoulder_roll))*sin(shoulder_roll) - 1.0*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch) + 0.30745*sin(shoulder_roll))*cos(shoulder_pitch)*cos(shoulder_roll);
J(0,3)=1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll))*cos(arm_yaw)*cos(shoulder_roll) + (-1.0*sin(arm_yaw)*sin(shoulder_pitch) - 1.0*sin(shoulder_roll)*cos(arm_yaw)*cos(shoulder_pitch))*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch));
J(0,4)=(-1.0*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 1.0*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll))*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch)) + (-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll))*(1.0*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) - 1.0*sin(shoulder_roll)*cos(elbow_pitch));
J(0,5)=0;
J(1,0)=0;
J(1,1)=-1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll) - 0.30745*sin(shoulder_pitch)*cos(shoulder_roll))*sin(shoulder_pitch) - 1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll) - 0.30745*cos(shoulder_pitch)*cos(shoulder_roll))*cos(shoulder_pitch);
J(1,2)=1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll) - 0.30745*sin(shoulder_pitch)*cos(shoulder_roll))*cos(shoulder_pitch)*cos(shoulder_roll) - 1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll) - 0.30745*cos(shoulder_pitch)*cos(shoulder_roll))*sin(shoulder_pitch)*cos(shoulder_roll);
J(1,3)=(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll))*(1.0*sin(arm_yaw)*sin(shoulder_pitch) + 1.0*sin(shoulder_roll)*cos(arm_yaw)*cos(shoulder_pitch)) + (-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll))*(1.0*sin(arm_yaw)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*sin(shoulder_roll)*cos(arm_yaw));
J(1,4)=(-1.0*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 1.0*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll))*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) - 0.22425*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll)) + (-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll))*(1.0*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) + 1.0*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll));
J(1,5)=0;
J(2,0)=0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) + 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll) + 0.30745*sin(shoulder_pitch)*cos(shoulder_roll);
J(2,1)=1.0*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch) + 0.30745*sin(shoulder_roll))*cos(shoulder_pitch);
J(2,2)=1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll) - 0.30745*sin(shoulder_pitch)*cos(shoulder_roll))*sin(shoulder_roll) + 1.0*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch) + 0.30745*sin(shoulder_roll))*sin(shoulder_pitch)*cos(shoulder_roll);
J(2,3)=-1.0*(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll))*cos(arm_yaw)*cos(shoulder_roll) + (-1.0*sin(arm_yaw)*cos(shoulder_pitch) + 1.0*sin(shoulder_pitch)*sin(shoulder_roll)*cos(arm_yaw))*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch));
J(2,4)=(-0.22425*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) - 0.22425*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll))*(-1.0*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 1.0*sin(shoulder_roll)*cos(elbow_pitch)) + (1.0*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) + 1.0*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll))*(-0.22425*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) + 0.22425*sin(shoulder_roll)*cos(elbow_pitch));
J(2,5)=0;
J(3,0)=0;
J(3,1)=1.0*cos(shoulder_pitch);
J(3,2)=1.0*sin(shoulder_pitch)*cos(shoulder_roll);
J(3,3)=-1.0*sin(arm_yaw)*cos(shoulder_pitch) + 1.0*sin(shoulder_pitch)*sin(shoulder_roll)*cos(arm_yaw);
J(3,4)=1.0*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*sin(elbow_pitch) + 1.0*sin(shoulder_pitch)*cos(elbow_pitch)*cos(shoulder_roll);
J(3,5)=-1.0*(1.0*(1.0*sin(arm_yaw)*sin(shoulder_pitch)*sin(shoulder_roll) + 1.0*cos(arm_yaw)*cos(shoulder_pitch))*cos(elbow_pitch) - 1.0*sin(elbow_pitch)*sin(shoulder_pitch)*cos(shoulder_roll))*sin(forearm_yaw) + 1.0*(-1.0*sin(arm_yaw)*cos(shoulder_pitch) + 1.0*sin(shoulder_pitch)*sin(shoulder_roll)*cos(arm_yaw))*cos(forearm_yaw);
J(4,0)=1.00000000000000;
J(4,1)=0;
J(4,2)=-1.0*sin(shoulder_roll);
J(4,3)=1.0*cos(arm_yaw)*cos(shoulder_roll);
J(4,4)=1.0*sin(arm_yaw)*sin(elbow_pitch)*cos(shoulder_roll) - 1.0*sin(shoulder_roll)*cos(elbow_pitch);
J(4,5)=-1.0*(1.0*sin(arm_yaw)*cos(elbow_pitch)*cos(shoulder_roll) + 1.0*sin(elbow_pitch)*sin(shoulder_roll))*sin(forearm_yaw) + 1.0*cos(arm_yaw)*cos(forearm_yaw)*cos(shoulder_roll);
J(5,0)=0;
J(5,1)=-1.0*sin(shoulder_pitch);
J(5,2)=1.0*cos(shoulder_pitch)*cos(shoulder_roll);
J(5,3)=1.0*sin(arm_yaw)*sin(shoulder_pitch) + 1.0*sin(shoulder_roll)*cos(arm_yaw)*cos(shoulder_pitch);
J(5,4)=1.0*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*sin(elbow_pitch) + 1.0*cos(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll);
J(5,5)=-1.0*(1.0*(1.0*sin(arm_yaw)*sin(shoulder_roll)*cos(shoulder_pitch) - 1.0*sin(shoulder_pitch)*cos(arm_yaw))*cos(elbow_pitch) - 1.0*sin(elbow_pitch)*cos(shoulder_pitch)*cos(shoulder_roll))*sin(forearm_yaw) + 1.0*(1.0*sin(arm_yaw)*sin(shoulder_pitch) + 1.0*sin(shoulder_roll)*cos(arm_yaw)*cos(shoulder_pitch))*cos(forearm_yaw);
}
| true |
81bfe83f148e391b034ff2a50b5ceefc6bd6d453 | C++ | TianhuaTao/computer-graphics-assignment | /rt-compact/src/util/imageio.cpp | UTF-8 | 3,263 | 2.859375 | 3 | [] | no_license | //
// Created by Sam on 2020/6/15.
//
#include "imageio.h"
#include "color.h"
static inline int isWhitespace(char c) {
return c == ' ' || c == '\n' || c == '\t';
}
// Reads a "word" from the fp and puts it into buffer and adds a null
// terminator. i.e. it keeps reading until whitespace is reached. Returns
// the number of characters read *not* including the whitespace, and
// returns -1 on an error.
static int readWord(FILE *fp, char *buffer, int bufferLength) {
int n;
int c;
if (bufferLength < 1) return -1;
n = 0;
c = fgetc(fp);
while (c != EOF && !isWhitespace(c) && n < bufferLength) {
buffer[n] = c;
++n;
c = fgetc(fp);
}
if (n < bufferLength) {
buffer[n] = '\0';
return n;
}
return -1;
}
const int BUFFER_SIZE = 1024;
Color *ReadImagePFM(const std::string &filename, int *xres,
int *yres) {
float *data = nullptr;
Color *rgb = nullptr;
char buffer[BUFFER_SIZE];
unsigned int nFloats;
int nChannels, width, height;
float scale;
bool fileLittleEndian;
FILE *fp = fopen(filename.c_str(), "rb");
if (!fp) goto fail;
// read either "Pf" or "PF"
if (readWord(fp, buffer, BUFFER_SIZE) == -1) goto fail;
if (strcmp(buffer, "Pf") == 0)
nChannels = 1;
else if (strcmp(buffer, "PF") == 0)
nChannels = 3;
else
goto fail;
// read the rest of the header
// read width
if (readWord(fp, buffer, BUFFER_SIZE) == -1) goto fail;
width = atoi(buffer);
*xres = width;
// read height
if (readWord(fp, buffer, BUFFER_SIZE) == -1) goto fail;
height = atoi(buffer);
*yres = height;
// read scale
if (readWord(fp, buffer, BUFFER_SIZE) == -1) goto fail;
sscanf(buffer, "%f", &scale);
// read the data
nFloats = nChannels * width * height;
data = new float[nFloats];
// Flip in Y, as P*M has the origin at the lower left.
for (int y = height - 1; y >= 0; --y) {
if (fread(&data[y * nChannels * width], sizeof(float),
nChannels * width, fp) != nChannels * width)
goto fail;
}
// apply endian conversian and scale if appropriate
fileLittleEndian = (scale < 0.f);
if (hostLittleEndian ^ fileLittleEndian) {
uint8_t bytes[4];
for (unsigned int i = 0; i < nFloats; ++i) {
memcpy(bytes, &data[i], 4);
std::swap(bytes[0], bytes[3]);
std::swap(bytes[1], bytes[2]);
memcpy(&data[i], bytes, 4);
}
}
if (std::abs(scale) != 1.f)
for (unsigned int i = 0; i < nFloats; ++i) data[i] *= std::abs(scale);
// create RGBs...
rgb = new Color[width * height];
if (nChannels == 1) {
for (int i = 0; i < width * height; ++i) rgb[i] = Color(data[i]);
} else {
for (int i = 0; i < width * height; ++i) {
Float frgb[3] = {data[3 * i], data[3 * i + 1], data[3 * i + 2]};
rgb[i] = Color::FromRGB(frgb);
}
}
delete[] data;
fclose(fp);
return rgb;
fail:
Error("Error reading PFM file \"%s\"", filename.c_str());
if (fp) fclose(fp);
delete[] data;
delete[] rgb;
return nullptr;
} | true |
4685d452730d7f7748c0e75662829fd2d86f486d | C++ | thatianajessica/EstruturaDeDadosLab | /Lista1/Q04/main.cpp | UTF-8 | 438 | 3.609375 | 4 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int num;
cout<<"Digite o numero:"<<endl;
cin>>num;
for (int i=0;;i++) {
int valor = i*(i+1)*(i+2);
if(valor == num){
cout<<"Numero eh triangular"<<endl;
cout<<i<<"*" <<i+1<<"*"<<i+2<<endl;
break;
}
if(valor > num){//varreu ate o proprio numero
break;
}
}
return 0;
}
| true |
78539d47455e1dffb6895b872807ac1009830122 | C++ | zhuhui1990/poj | /3279/main.cpp | UTF-8 | 1,302 | 2.578125 | 3 | [] | no_license | #include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxm = 20;
const int maxn = 20;
const int dx[5] = {-1,0,0,0,1};
const int dy[5] = {0,-1,0,1,0};
int m,n;
int tile[maxm][maxn];
int opt[maxm][maxn];
int flip[maxm][maxn];
int get(int x,int y){
int c = tile[x][y];
for(int d=0;d<5;++d){
int x2 = x+dx[d], y2 = y+dy[d];
if(x2>=0 && x2<m && y2>=0 && y2<n){
c += flip[x2][y2];
}
}
return c%2;
}
int calc(){
for(int i=1;i<m;++i){
for(int j=0;j<n;++j){
if(get(i-1,j) != 0){
flip[i][j] = 1;
}
}
}
for(int j=0;j<n;++j){
if(get(m-1,j) != 0){
return -1;
}
}
int res = 0;
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
res += flip[i][j];
}
}
return res;
}
int main(){
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif
cin>>m>>n;
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
cin>>tile[i][j];
}
}
int res = -1;
for(int i=0;i< 1<<n;++i){
memset(flip,0,sizeof(flip));
for(int j=0;j<n;++j){
flip[0][n-j-1] = (i>>j)&1;
}
int num = calc();
if(num >= 0 && (res<0 || res>num)){
res = num;
memcpy(opt,flip,sizeof(flip));
}
}
if(res<0){
cout<<"IMPOSSIBLE"<<endl;
}else{
for(int i=0;i<m;++i){
for(int j=0;j<n;++j){
cout<<opt[i][j];
cout<<(j+1==n ? '\n':' ');
}
}
}
return 0;
} | true |
b3f89c5ab5bc21e5da9c8f81719aabbb45923b53 | C++ | AnsgarGM/Estructuras-de-datos | /ArbolSimulado.cpp | UTF-8 | 3,206 | 3.203125 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
class nodo{
public:
int dato;
int id, id_padre;
nodo *sig;
nodo(int x, int y, int z){
dato=x;
id=y;
id_padre=z;
sig=NULL;
}
};
class ArbolSimulado{
public:
nodo *inicio, *aux, *aux2;
void ingresar(nodo *n){
aux=n;
aux2=inicio;
if(inicio==NULL){
inicio=aux;
inicio->sig=NULL;
}else{
while(aux2->sig!=NULL){
aux2=aux2->sig;
}
aux2->sig=aux;
}
system("clear");
printf("\nAgregado\n");
}
void eliminar(int borrar){
aux=inicio;
/*while(aux->sig!=NULL){
if(aux->id==borrar){
//Aqui borra pero hay que buscar todos los hijos los desendientes
}
if(aux->id_padre==borrar){
}
aux=aux->sig;
}*/
printf("\nBorrado\n");
}
void borrar(nodo *otro){
}
void mostrar(int cont){
int aux_cont;
aux=inicio;
aux2=inicio;
if(inicio==NULL){
system("clear");
printf("\nNada que mostrar\n");
}else{
system("clear");
printf("\n%d\n", cont);
//Imprime por orde de ID padre
printf("\nID Padre\tID\tDato\n");
for(aux_cont=0;aux_cont<=cont;aux_cont++){
aux=inicio;
while(aux!=NULL){
if(aux->id_padre==aux_cont){
printf("\n\t%d\t%d\t%d", aux->id_padre, aux->id, aux->dato);
}
aux=aux->sig;
}
}
aux=inicio;
//Imprime por orden de ID propio de cada nodo
/*printf("\nID Padre\tID\tDato\n");
while(aux!=NULL){
printf("\n\t%d\t%d\t%d", aux->id_padre, aux->id, aux->dato);
aux=aux->sig;
}*/
printf("\n");
}
}
ArbolSimulado(){
inicio=NULL;
aux=NULL;
}
};
int main(){
ArbolSimulado arbol;
nodo *node;
int opc, num, aux_padre=0, cont_id=1, aborrar;
do {
printf("\n1.-Agregar\n2.-Mostrar\n3.-Salir\n");
scanf("%d", &opc);
switch(opc){
case 1:
printf("\nIngrese el valor:\t");
scanf("%d", &num);
if(cont_id>1){
printf("\nHijo de qiuen?\t");
scanf("%d", &aux_padre);
}
if(aux_padre>=cont_id){
system("clear");
printf("\nEl nodo %d no existe\n", aux_padre);
}else{
node = new nodo(num, cont_id, aux_padre);
arbol.ingresar(node);
cont_id++;
}
break;
case 2:
arbol.mostrar(cont_id);
break;
/*case 3:
//Para borrar se tienen que borrar todos los hijos que tenga, empezando por el nivel mas bajo hasta el nodo que se desea borrar
printf("\nQue nodo desea eliminar?\t");
scanf("%d", &aborrar);
if(aborrar>cont_id){
printf("\nNo existe ese nodo");
}else{
arbol.eliminar(aborrar);
}
break;*/
case 3:
break;
default:
printf("***Opcion Invalida***");
}
} while(opc!=3);
return 0;
}
| true |
dc82d4a08a9d92790352e1d65d1b3d4615ab4be4 | C++ | IceBirdCiel/Traitement-d-image | /Traitement d'Image/Image.h | UTF-8 | 695 | 2.875 | 3 | [] | no_license | #ifndef _IMAGE_HPP_
#define _IMAGE_HPP_
#include <cstdint>
#include <cstdio>
#include "stb_image.h"
#include "stb_image_write.h"
enum ImageType {
PNG, JPG, BMP, TGA
};
struct Color {
int r, g, b;
};
class Image {
private:
size_t size = 0;
int width, height, channels;
public:
uint8_t* data = NULL;
Image(const char* filename);
Image(int width, int height, int channels);
Image(const Image& img);
~Image();
bool read(const char* filename);
bool write(const char* filename);
ImageType getFileType(const char* filename);
int getWidth()const;
int getHeight()const;
int getChannels()const;
Color getColor(int x, int y)const;
void setColor(int x, int y, Color c);
};
#endif | true |
76e892a75a184d3306371de55f01b4a79649ce59 | C++ | loyinglin/Codeforces | /741/A/Codeforces/main.cpp | UTF-8 | 2,159 | 2.953125 | 3 | [] | no_license | //
// main.cpp
// Codeforces
//
// Created by loying on 16/7/27.
// Copyright © 2016年 loying. All rights reserved.
/************************** 题解 **********************
题目链接:http://codeforces.com/contest/741/problem/A
题目大意:
输入n个数字a[i],设定一个操作x=a[x];
找到一个最小的k,要求:
执行k次,x=a[x]之后,x的最终值是y;
如果对y也执行k次,y=a[y],y的最终值是x;
举例:
3
2 3 1
k = 3
(2->3->1->2, 3->1->2->3)
2
2 1
k = 1
(1->2,2->1)
题目解析:
因为n个数,每个数只有一个出去的选择;
那么对于a[i],可以连一条边i->a[i],表示选择;
题目要求就是从i出去的边,能最后指向自己;
那么按照边遍历,如果n个数字能划分成若干个圈即可;
每个圈按照各自的k求出最小公倍数;(因为可以x、y互换,所以如果k%2==0,要除以2)
************************* 题解 ***********************/
#include<cstdio>
#include<cmath>
#include<stack>
#include<map>
#include<set>
#include<queue>
#include<deque>
#include<string>
#include<utility>
#include<sstream>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long lld;
const int N = 101001;
int a[N], used[N];
//最大公约数
int gcd(int m,int n){
int t;
if(m<n){t = n;n = m;m = t;}
if(n == 0)
return m;
else
return gcd(n,m % n);
}
//最小公倍数
int lcm(int a,int b){
return a/gcd(a,b) * b;
}
int main(int argc, const char * argv
[]) {
lld n;
cin >> n;
for (int i = 1; i <= n; ++i) {
cin >> a[i];
}
int ans = 1;
for (int i = 1; i <= n; ++i) {
if (!used[i]) {
int t = i, k = 0;
while (!used[t]) {
used[t] = 1;
++k;
t = a[t];
}
if (t != i) {
ans = -1;
break;
}
if (k % 2 == 0) {
k /= 2;
}
ans = lcm(ans, k);
}
}
cout << ans << endl;
return 0;
}
| true |
53165d386a9c912eae3c99720a2719fe67e8f8e8 | C++ | ksaveljev/UVa-online-judge | /10004.cpp | UTF-8 | 1,786 | 3.671875 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <vector>
#include <queue>
using namespace std;
struct Vertex
{
public:
int id;
int color;
vector<Vertex*> adj;
Vertex (int id) : id(id) { color = -1; }
};
typedef map<int, Vertex*> vmap;
typedef pair<int, Vertex*> vpair;
class Graph
{
public:
Graph() {}
~Graph();
void addEdge (int begin, int end, bool directed);
bool bicolor(Vertex* v, int color);
Vertex* firstVertex();
private:
Vertex* getVertex (int v);
vmap vertexMap;
vector<Vertex*> allVertexes;
};
Graph::~Graph()
{
for (int i = 0; i < allVertexes.size(); i++)
delete allVertexes[i];
}
void Graph::addEdge (int begin, int end, bool directed = false)
{
Vertex* v = getVertex (begin);
Vertex* w = getVertex (end);
v->adj.push_back (w);
if (!directed)
w->adj.push_back (v);
}
Vertex* Graph::getVertex (int v)
{
vmap::iterator it = vertexMap.find (v);
if (it == vertexMap.end()) {
Vertex* newv = new Vertex (v);
allVertexes.push_back (newv);
vertexMap.insert (vpair (v, newv));
return newv;
}
return (*it).second;
}
Vertex* Graph::firstVertex()
{
return allVertexes[0];
}
bool Graph::bicolor(Vertex* v, int color)
{
bool result = true;
if (v->color == -1) {
v->color = color;
for (int i = 0; i < v->adj.size(); i++) {
result = bicolor(v->adj[i], (color + 1) % 2);
if (!result) break;
}
} else {
if (v->color != color)
result = false;
}
return result;
}
int main (void) {
int nodes, edges, a, b;
while (cin >> nodes) {
if (nodes == 0) break;
cin >> edges;
Graph* g = new Graph();
while (edges--) {
cin >> a >> b;
g->addEdge (a,b);
}
if (g->bicolor(g->firstVertex(), 0))
cout << "BICOLORABLE." << endl;
else
cout << "NOT BICOLORABLE." << endl;
delete g;
}
} | true |
a254137fba29a23212fc18b52a9e3bed3d60085c | C++ | huolab-datastructures/Data_structures_knight | /knight.h | UTF-8 | 436 | 2.828125 | 3 | [] | no_license | //Created by Alex Schrepfer
//CS151, University of Hawaii-Hilo
//April 5th, 2001
#include <iostream>
using namespace std;
const int max_board = 18;
class Knights {
public:
Knights(int size);
int size() const;
bool valid(int x, int y) const;
void insert(int x, int y, int move);
void remove(int x, int y);
void print() const;
int attempts;
private:
int count;
int board_size;
int used[max_board][max_board];
};
| true |
ce1d1525900f708a2a02e7987abc6d4f7b84212f | C++ | yuecheng11/ThreadPool | /examCsdn/Thread.cpp | UTF-8 | 3,321 | 2.765625 | 3 | [] | no_license | #include "Thread.h"
using namespace std;
void CTask::SetData(void * data)
{
m_ptrData = data;
}
vector<CTask*> CThreadPool::m_vecTaskList; //\u4efb\u52a1\u5217\u8868
bool CThreadPool::shutdown = false;
pthread_mutex_t CThreadPool::m_pthreadMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t CThreadPool::m_pthreadCond = PTHREAD_COND_INITIALIZER;
/**
* \u7ebf\u7a0b\u6c60\u7ba1\u7406\u7c7b\u6784\u9020\u51fd\u6570
*/
CThreadPool::CThreadPool(int threadNum)
{
this->m_iThreadNum = threadNum;
cout << "I will create " << threadNum << " threads" << endl;
Create();
}
/**
* \u7ebf\u7a0b\u56de\u8c03\u51fd\u6570
*/
void* CThreadPool::ThreadFunc(void* threadData)
{
pthread_t tid = pthread_self();
while (1)
{
pthread_mutex_lock(&m_pthreadMutex);
while (m_vecTaskList.size() == 0 && !shutdown)
{
pthread_cond_wait(&m_pthreadCond, &m_pthreadMutex);
}
if (shutdown)
{
pthread_mutex_unlock(&m_pthreadMutex);
cout<<"thread "<<pthread_self()<<" will exit/n"<<endl;
pthread_exit(NULL);
}
cout<<"tid"<<tid<<" run/n"<<endl;
vector<CTask*>::iterator iter = m_vecTaskList.begin();
/**
* \u53d6\u51fa\u4e00\u4e2a\u4efb\u52a1\u5e76\u5904\u7406\u4e4b
*/
CTask* task = *iter;
if (iter != m_vecTaskList.end())
{
task = *iter;
m_vecTaskList.erase(iter);
}
pthread_mutex_unlock(&m_pthreadMutex);
task->Run(); /** \u6267\u884c\u4efb\u52a1 */
cout<<"tid: "<<tid<<" idle/n"<<endl;
}
return (void*)0;
}
/**
* \u5f80\u4efb\u52a1\u961f\u5217\u91cc\u8fb9\u6dfb\u52a0\u4efb\u52a1\u5e76\u53d1\u51fa\u7ebf\u7a0b\u540c\u6b65\u4fe1\u53f7
*/
int CThreadPool::AddTask(CTask *task)
{
pthread_mutex_lock(&m_pthreadMutex);
this->m_vecTaskList.push_back(task);
pthread_mutex_unlock(&m_pthreadMutex);
pthread_cond_signal(&m_pthreadCond);
return 0;
}
/**
* \u521b\u5efa\u7ebf\u7a0b
*/
int CThreadPool::Create()
{
pthread_id = (pthread_t*)malloc(sizeof(pthread_t) * m_iThreadNum);
for(int i = 0; i < m_iThreadNum; i++)
{
pthread_create(&pthread_id[i], NULL, ThreadFunc, NULL);
}
return 0;
}
/**
* \u505c\u6b62\u6240\u6709\u7ebf\u7a0b
*/
int CThreadPool::StopAll()
{
/** \u907f\u514d\u91cd\u590d\u8c03\u7528 */
if (shutdown)
{
return -1;
}
printf("Now I will end all threads!!/n");
/** \u5524\u9192\u6240\u6709\u7b49\u5f85\u7ebf\u7a0b\uff0c\u7ebf\u7a0b\u6c60\u8981\u9500\u6bc1\u4e86 */
shutdown = true;
pthread_cond_broadcast(&m_pthreadCond);
/** \u963b\u585e\u7b49\u5f85\u7ebf\u7a0b\u9000\u51fa\uff0c\u5426\u5219\u5c31\u6210\u50f5\u5c38\u4e86 */
for (int i = 0; i < m_iThreadNum; i++)
{
pthread_join(pthread_id[i], NULL);
}
free(pthread_id);
pthread_id = NULL;
/** \u9500\u6bc1\u6761\u4ef6\u53d8\u91cf\u548c\u4e92\u65a5\u4f53 */
pthread_mutex_destroy(&m_pthreadMutex);
pthread_cond_destroy(&m_pthreadCond);
return 0;
}
/**
* \u83b7\u53d6\u5f53\u524d\u961f\u5217\u4e2d\u4efb\u52a1\u6570
*/
int CThreadPool::getTaskSize()
{
return m_vecTaskList.size();
}
| true |
c75429fc6cee45dadab177da3ce3a152d0ef14b8 | C++ | EmreTech/File_Manager | /include/file_mangement.hpp | UTF-8 | 1,802 | 3.46875 | 3 | [
"MIT"
] | permissive | #pragma once
#include <iostream>
#include <filesystem>
#include <fstream>
#include <iomanip>
using namespace std::chrono;
using namespace std::filesystem;
namespace FileOperations {
struct FileCreate {
FileCreate(){}
// Creates a file with some sample content using ofstream
static void createFile(std::string file_name, std::string content) {
std::ofstream File(file_name);
File << content;
File.close();
}
};
struct FileDelete {
FileDelete(){}
// Deletes a file at the specifed path
static void deleteFile(path file_path) {
remove(file_path);
}
};
struct FileMove {
FileMove(){}
// Copies one file to another location
static void copyFile(path first_file, path second_file) {
copy(first_file, second_file);
}
// Copies one file to another location with copying options
static void copyFile(path first_file, path second_file, copy_options options) {
copy(first_file, second_file, options);
}
// Moves one file to another location
static void moveFile(path first_file, path second_file) {
copy(first_file, second_file);
remove(first_file);
}
// Moves one file to another location with copying options
static void moveFile(path first_file, path second_file, copy_options options) {
copy(first_file, second_file, options);
remove(first_file);
}
};
struct FileRename {
FileRename(){}
// Renames a file to another name
static void renameFile(path file_to_rename, std::string rename_to) {
rename(file_to_rename, rename_to);
}
};
} | true |
f64fc00dc4f6c597c77095ee5854092a57896e03 | C++ | blake-sheridan/py-postgresql | /include/postgresql/parameters.hpp | UTF-8 | 5,767 | 2.515625 | 3 | [] | no_license | #ifndef POSTGRESQL_PARAMETERS_HPP_
#define POSTGRESQL_PARAMETERS_HPP_
#include "Python.h"
#include "libpq-fe.h"
#include "postgresql/network.hpp"
#include "postgresql/type.hpp"
namespace postgresql {
namespace parameters {
static const size_t MAX_BYTES_PER = 8;
class Parameters
{
public:
Oid *types_i;
char **values_i;
int *lengths_i;
int *formats_i;
char *scratch_i;
// Constants
inline bool
append_true()
{
TODO();
return false;
}
inline bool
append_false()
{
TODO();
return false;
}
inline bool
append(PyObject *x)
{
PyTypeObject *cls = Py_TYPE(x);
// Priority to builtin exact types
if (cls == &PyUnicode_Type) return this->append((PyUnicodeObject *)x);
if (cls == &PyLong_Type) return this->append( (PyLongObject *)x);
if (cls == &PyFloat_Type) return this->append( (PyFloatObject *)x);
if (cls == &PyBool_Type) return (x == Py_True) ? this->append_true() : this->append_false();
if (cls == &PyBytes_Type) return this->append( (PyBytesObject *)x);
PyErr_Format(PyExc_NotImplementedError, "encode(%R)", x);
return false;
}
inline bool
append(int16_t x)
{
char *scratch = this->scratch_i;
*this->types_i++ = INT2::OID;
*this->values_i++ = scratch;
*this->lengths_i++ = 2;
*this->formats_i++ = 1;
*(int16_t *)scratch = postgresql::network::order(x);
this->scratch_i += 2;
return true;
}
inline bool
append(int32_t x)
{
char *scratch = this->scratch_i;
*this->types_i++ = INT4::OID;
*this->values_i++ = scratch;
*this->lengths_i++ = 4;
*this->formats_i++ = 1;
*(int32_t *)scratch = postgresql::network::order(x);
this->scratch_i += 4;
return true;
}
inline bool
append(int64_t x)
{
char *scratch = this->scratch_i;
*this->types_i++ = INT8::OID;
*this->values_i++ = scratch;
*this->lengths_i++ = 8;
*this->formats_i++ = 1;
*(int64_t *)scratch = postgresql::network::order(x);
this->scratch_i += 8;
return true;
}
inline bool
append(PyBytesObject *x)
{
TODO();
return false;
}
inline bool
append(PyFloatObject *x)
{
TODO();
return false;
}
inline bool
append(PyLongObject *x)
{
// Implementation details
Py_ssize_t size = Py_SIZE(x);
digit d;
switch (size) {
case 1:
d = x->ob_digit[0];
if (d < 32768)
return this->append((int16_t)d);
else
return this->append((int32_t)d);
case 0:
return this->append((int16_t)0);
case -1:
d = x->ob_digit[0];
if (d <= 32768)
return this->append(-(int16_t)d);
else
return this->append(-(int32_t)d);
}
bool negative = size < 0;
if (negative)
size = -size;
uint64_t total = 0;
while (--size >= 0)
total = (total << PyLong_SHIFT) | x->ob_digit[size];
if (negative) {
if (total <= 2147483648)
return this->append(-(int32_t)total);
else
return this->append(-(int64_t)total);
} else {
if (total < 2147483648)
return this->append((int32_t)total);
else
return this->append((int64_t)total);
}
}
inline bool
append(PyUnicodeObject *x)
{
Py_ssize_t size;
char *utf8 = PyUnicode_AsUTF8AndSize((PyObject *)x, &size);
if (utf8 == NULL)
return false;
*this->types_i++ = TEXT::OID;
*this->values_i++ = utf8;
*this->lengths_i++ = size;
*this->formats_i++ = 1;
return true;
}
};
template <size_t N>
class Static : public Parameters
{
public:
Oid types[N];
char *values[N];
int lengths[N];
int formats[N];
char scratch[N * MAX_BYTES_PER];
Static()
{
this->types_i = this->types;
this->values_i = this->values;
this->lengths_i = this->lengths;
this->formats_i = this->formats;
this->scratch_i = this->scratch;
}
};
class Dynamic : public Parameters
{
public:
Oid *types;
char **values;
int *lengths;
int *formats;
char *scratch;
Dynamic(size_t n)
{
size_t types_size = n * sizeof(Oid);
size_t values_size = n * sizeof(char *);
size_t lengths_size = n * sizeof(int);
size_t formats_size = n * sizeof(int);
size_t scratch_size = n * MAX_BYTES_PER;
size_t total_size = (types_size +
values_size +
lengths_size +
formats_size +
scratch_size);
// Must be OK if malloc fails
this->types = this->types_i = (Oid *)PyMem_MALLOC(total_size);
this->values = this->values_i = (char **)((size_t)this->types + types_size);
this->lengths = this->lengths_i = (int *)((size_t)this->values + values_size);
this->formats = this->formats_i = (int *)((size_t)this->lengths + lengths_size);
this->scratch = this->scratch_i = (char *)((size_t)this->formats + formats_size);
}
~Dynamic()
{
PyMem_FREE(this->types);
}
};
} // namespace parameters
} // namespace postgresql
#endif
| true |
66985dc483eed3d968f5739827a7c426da778d91 | C++ | nickyc975/VScript | /src/objects/VSCellObject.cpp | UTF-8 | 2,575 | 2.765625 | 3 | [
"MIT"
] | permissive | #include "objects/VSCellObject.hpp"
#include <cassert>
#include "error.hpp"
#include "objects/VSBoolObject.hpp"
#include "objects/VSFunctionObject.hpp"
#include "objects/VSIntObject.hpp"
#include "objects/VSNoneObject.hpp"
#include "objects/VSStringObject.hpp"
NEW_IDENTIFIER(__hash__);
NEW_IDENTIFIER(__eq__);
NEW_IDENTIFIER(__str__);
NEW_IDENTIFIER(__bytes__);
VSObject *vs_cell(VSObject *, VSObject *const *args, vs_size_t nargs) {
if (nargs != 1) {
ERR_NARGS("cell()", 1, nargs);
terminate(TERM_ERROR);
}
VSCellObject *cell = new VSCellObject(args[0]);
INCREF_RET(AS_OBJECT(cell));
}
VSObject *vs_cell_hash(VSObject *self, VSObject *const *, vs_size_t nargs) {
assert(self != NULL);
if (nargs != 0) {
ERR_NARGS("cell.__hash__()", 0, nargs);
terminate(TERM_ERROR);
}
ENSURE_TYPE(self, T_CELL, "cell.__hash__()");
INCREF_RET(C_INT_TO_INT((cint_t)self));
}
VSObject *vs_cell_str(VSObject *self, VSObject *const *, vs_size_t nargs) {
assert(self != NULL);
if (nargs != 0) {
ERR_NARGS("cell.__hash__()", 0, nargs);
terminate(TERM_ERROR);
}
ENSURE_TYPE(self, T_CELL, "cell.__hash__()");
INCREF_RET(C_STRING_TO_STRING("cell"));
}
VSObject *vs_cell_bytes(VSObject *self, VSObject *const *, vs_size_t nargs) {
assert(self != NULL);
if (nargs != 0) {
ERR_NARGS("cell.__hash__()", 0, nargs);
terminate(TERM_ERROR);
}
ENSURE_TYPE(self, T_CELL, "cell.__hash__()");
INCREF_RET(VS_NONE);
}
const str_func_map VSCellObject::vs_cell_methods = {
{ID___hash__, vs_cell_hash},
{ID___eq__, vs_default_eq},
{ID___str__, vs_cell_str},
{ID___bytes__, vs_cell_bytes}
};
VSCellObject::VSCellObject(VSObject *item) {
this->type = T_CELL;
this->mut = true;
this->item = item;
INCREF(item);
}
VSCellObject::~VSCellObject() {
DECREF_EX(this->item);
}
bool VSCellObject::hasattr(std::string &attrname) {
return vs_cell_methods.find(attrname) != vs_cell_methods.end();
}
VSObject *VSCellObject::getattr(std::string &attrname) {
auto iter = vs_cell_methods.find(attrname);
if (iter == vs_cell_methods.end()) {
ERR_NO_ATTR(this, attrname);
terminate(TERM_ERROR);
}
VSFunctionObject *attr = new VSNativeFunctionObject(
this, C_STRING_TO_STRING(attrname), vs_cell_methods.at(attrname));
INCREF_RET(attr);
}
void VSCellObject::setattr(std::string &, VSObject *) {
err("Unable to apply setattr on native type: \"%s\"", TYPE_STR[this->type]);
terminate(TERM_ERROR);
} | true |
47cb61700c078b392391af66223e9309ecf05340 | C++ | bopopescu/projects-2 | /cs140/lab5/notes1.cpp | UTF-8 | 2,087 | 3.296875 | 3 | [] | no_license | //DONT MODIFY HIS CODE
//Rename something so the code will work
//Bit-matrices - Linear Algebra Class
//Adding them is XOR or add them and mod 2
//TRIPLE FOR LOOP
// for each row do it for each collumn
// this times this, this times this, etc.
//Do error checking to make sure they are the same size
//a*b is not b*a
// This test case is an inverse because it gives you a horizontal line of 1's
// Bitmatrix(int rows, int cols); <-- this constructor needs to be made
// He does one constructor for us and also print
// The double int constructor makes a bit matrix of that size
// Your representation is a big string of 0's and 1's
// X X X X X X X
// X X <--- the 9th spot
// Often its easier to have a double index vector rather than some single
// index vector because you just do some math and then store it
// You have to do it that way
// Error check for a bit-matrix of -2 and -2 as not possible
// a 1x1 bit matrix is zero
// The bitmatrix is a vector of strings
// Print the vector, print a new line, etc.
// So yes you can double index this, sorry
// The first string is what matrix your looking at? the second is the character // you are looking at?
// write to a file pgm, you need the same header, P2 rows columns etc.
// For each bit, it is a pixel by pixel square
// A whole previous lab is one function
// int Rows and int Colls are basically accessor functions
// call the size on m to get the rows and oclumns
// set <-- specify a row and column and you can pick a element to change?
// You need to error check
// You can be passed the '0' or '1' or the 0 the number or the character,
// you need to check for 4 different things
// There is a difference between the numbers 0 and 1 and the characters 0 and 1
// You are allowed to use the swap function
// Each row is a string you are litterally switching them
// Important note on copy: you can't access that m, you have to go through M to
// get the M
// The last few parts are doing math on the bit matrixes and also doing hash
// tables. Its not open addressing so you get to dodge a huge portion of the
// code
| true |
e8a668c5c438ed1109737a87c876c91f91a55a87 | C++ | isysoi3/Programming | /c++/1 сем/лаба/б/15_1/15_1/15_1.cpp | WINDOWS-1251 | 562 | 3.078125 | 3 | [] | no_license | // 15_1.cpp: .
//
#include <iostream>
using namespace std;
int main()
{
setlocale ( LC_ALL, "RUS" );
int a[10];
int n, c, k;
k = 0;
cout << " " << endl;
cin >> n;
while (n != 0)
{
c = n % 10;
a[c] = 1;
n = n / 10;
}
for ( int i = 0 ; i <= 9 ; i++ )
{
if ( a[i] == 1 )
k++;
}
cout << " = " << k << endl;
return 0;
} | true |
61be70579d509d97c546fe7efe00b1c6c208333b | C++ | cakkae/tasks-in-cpp | /tekst1.cpp | UTF-8 | 1,190 | 3.09375 | 3 | [] | no_license | // tekst1.C - Definicije metoda i funkcija uz klasu tekstova.
#include "tekst1.h"
void Tekst::kopiraj (const char* n) { // Kopiranje teksta.
if (n && strlen(n)) {
niz = new char [strlen(n)+1]; strcpy (niz, n);
} else niz = 0;
}
Tekst operator+ (const Tekst& t1, const Tekst& t2) { // Spajanje tekstova.
if (!t1.niz) return t2;
if (!t2.niz) return t1;
Tekst t; t.niz = new char [len(t1) + len(t2) + 1];
strcpy (t.niz, t1.niz); strcat (t.niz, t2.niz);
return t;
}
Tekst Tekst::operator() (int i, int j) const { // Podniz teksta.
if (i<0 || j<i || len(*this)<=j) exit(1);
Tekst t; int d = j - i + 1;
t.niz = new char [d+1]; strncpy (t.niz, niz+i, d); t.niz[d] = 0;
return t;
}
int operator% (const Tekst& t1, const Tekst& t2) { // Mesto podniza.
int d1 = len (t1), d2 = len (t2);
if (!d1 || !d2) return -1;
for (int i=0; i<d1-d2+1; i++) {
int j;
for (j=0; j<d2 && t1.niz[i+j]==t2.niz[j]; j++);
if (j == d2) return i;
}
return -1;
}
istream& operator>> (istream& it, Tekst& t) { // Citanje teksta.
char* n = new char [81]; it >> n; t = n; delete [] n;
return it;
}
| true |
cdea29d21021b79881b58b03de4f2520e308eb81 | C++ | VIPUL1306/cp_practice | /src/codeforces/Selling Souvenirs.cpp | UTF-8 | 689 | 2.96875 | 3 | [] | no_license | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
ll knapsack(vector<pair<ll,ll>> arr,int m){
int n = arr.size();
vector<ll> present(m+1,0);
vector<ll> prev(m+1,0);
for(int i = 1;i<n+1;i++){
present.resize(m+1,0);
for(int j = 1;j<m+1;j++){
if(j - arr[i-1].first >= 0){
present[j] = max(arr[i-1].second + prev[j - arr[i-1].first] , prev[j]);
}else{
present[j] = prev[j];
}
}
prev = present;
present.clear();
}
return prev.back();
}
int main(){
int n,m;
cin>>n>>m;
//weight, cost pair
vector<pair<ll,ll>> arr(n);
for(int i = 0;i<n;i++)
cin>>arr[i].first>>arr[i].second;
cout<<knapsack(arr,m)<<"\n";
return 0;
}
| true |
fa8dd2185d86719d49ebc4960663a309c44b5928 | C++ | cvejoski/CUDALab | /CUDABase/Algorithms/KernelClassification.cpp | UTF-8 | 8,953 | 2.625 | 3 | [] | no_license | /*
* KernelClassification.cpp
*
* Created on: Jul 8, 2014
* Author: cve
*/
#include "KernelClassification.h"
template <typename M>
KernelClassification<M>::KernelClassification() {
this->n_iter = 0;
this->n_dim = 0;
this->n_classes = 0;
this->l_rate = 0.0;
this->r_rate = 0.0;
this->kernel = NULL;
}
template <typename M>
KernelClassification<M>::KernelClassification(float l_rate, float r_rate, int n_iter, int n_classes, int n_dim, Kernel<M>* kernel) {
this->l_rate = l_rate;
this->n_iter = n_iter;
this->n_classes = n_classes;
this->n_dim = n_dim;
this->r_rate = r_rate;
this->kernel = kernel;
this->b = tensor<float, M>(extents[1][n_classes]);
this->b = 0.f;
}
template<typename M>
tensor<float, M> KernelClassification<M>::calcLinearEq(const tensor<float, M>& X_test) {
tensor<float, M> result(extents[X_test.shape(0)][this->n_classes]);
tensor<float, M> result_t(extents[this->n_classes][X_test.shape(0)]);
gramMatrix = tensor<float, M>(extents[X.shape(0)][X_test.shape(0)]);
kernel->calculate(gramMatrix, X, X_test);
prod(result_t, alpha, gramMatrix, 't', 'n', 1.f, 0.f);
transpose(result, result_t);
matrix_plus_row(result, b);
return result;
}
template<typename M>
tensor<float, M> KernelClassification<M>::calcSigma(const tensor<float, M>& linearEq) {
tensor<float, M> result(linearEq.shape());
tensor<float, M> denomi(extents[linearEq.shape(0)]);
tensor<float, M> tmpResulst = linearEq.copy();
result = 0.f;
denomi = 0.f;
apply_scalar_functor(tmpResulst, SF_EXP);
reduce_to_col(denomi, linearEq, RF_ADDEXP);
matrix_divide_col(tmpResulst, denomi);
return tmpResulst;
}
template<typename M>
tensor<float, M> KernelClassification<M>::calcSigmaReduced(const tensor<float, M>& linearEq) {
tensor<float, M> result(linearEq.shape());
tensor<float, M> tmpResulst = linearEq.copy();
tensor<float, M> denomi(extents[linearEq.shape(0)]);
result = 0.f;
denomi = 0.f;
reduce_to_col(denomi, linearEq, RF_LOGADDEXP);
denomi = denomi * -1.f;
matrix_plus_col(tmpResulst, denomi);
apply_scalar_functor(result, tmpResulst, SF_EXP);
return result;
}
template<typename M>
double KernelClassification<M>::calcGradientDescent_2C(const tensor<float, M>& X, const tensor<float, M>& Y) {
tensor<float, M> d_alpha(this->alpha.shape());
tensor<float, M> d_b(this->b.shape());
float n_data = X.shape(0);
tensor<float, M> linear_eq = calcLinearEq(X);
//Calculating sigmoid
apply_scalar_functor(linear_eq, SF_SIGM);
matrix_plus_col(linear_eq, -1.f*Y);
//calcualting delta a
prod(d_alpha, gramMatrix, linear_eq, 'n', 'n', 2.f/n_data, 0.f);
//calculatind delta b
reduce_to_row(d_b, linear_eq, RF_ADD, 2.f/n_data);
//update w and b
alpha -= l_rate * d_alpha + r_rate * this->alpha;
b -= l_rate * d_b + r_rate * b;
return isConverging(0.008, d_alpha);
}
template<typename M>
double KernelClassification<M>::calcGradientDesc_MC(const tensor<float, M>& X, const tensor<float, M>& Y) {
tensor<float, M> d_alpha(this->alpha.shape());
tensor<float, M> d_b(this->b.shape());
double result = 0.0;
float n_data = X.shape(0);
tensor<float, M> linear_eq = calcLinearEq(X);
//Calculating sigmoid
tensor<float, M> sigma = calcSigmaReduced(linear_eq);
//result = maximum(calcError(sigma, Y));
sigma = sigma - Y;
//calcualting delta w
prod(d_alpha, gramMatrix, sigma, 'n', 'n', 2.f/n_data, 0.f);
//calculatind delta b
reduce_to_row(d_b, sigma, RF_ADD, 2.f/n_data);
//update w and b
alpha -= l_rate * d_alpha + r_rate * alpha / n_data;
b -= l_rate * d_b + r_rate * b / n_data;
result = isConverging(0.001, d_alpha);
return result;
}
template<typename M>
void KernelClassification<M>::init() {
this->alpha = 0.f;
this->b = 0.f;
add_rnd_normal(alpha);
add_rnd_normal(b);
alpha *= .01f;
b *= .01f;
}
template<typename M>
void KernelClassification<M>::fit(const tensor<float, M>& X, const tensor<float, M>& Y ) {
tensor<float, M> Y_Multi = convertYtoM(Y);
this->X = X;
this->alpha = tensor<float, M>(extents[X.shape(0)][n_classes]);
this->alpha = 0.f;
int iter = 0;
double con = 0.0;
// int miss = 0;
do {
if (this->n_classes == 2)
calcGradientDescent_2C(X, Y);
else
calcGradientDesc_MC(X, Y_Multi);
// miss = missClassified(X, Y);
cout<<"iter: "<<iter<<" "<<con<<" MissClass Train# "<<missClassified(X, Y)<<endl;
iter++;
} while ((iter < this->n_iter) );
}
template<typename M>
tensor<float, M> KernelClassification<M>::predict(const tensor<float, M>& X_test) {
tensor<float, M> result;
if (this->n_classes == 2)
result = predict_2C(X_test);
else
result = predict_MC(X_test);
return result;
}
template<typename M>
void KernelClassification<M>::predict(const tensor<float, M>& X_test, char* fileName) {
tensor<float, M> Y = predict(X_test);
ofstream fs(fileName);
if(!fs){
cerr<<"Cannot open the output file."<<endl;
exit(1);
}
tensor<float, host_memory_space> tmpX = X_test;
tensor<float, host_memory_space> tmpY = Y;
for (unsigned int i = 0; i < tmpX.shape(0); i++){
for (unsigned int j = 0; j < tmpX.shape(1); j++) {
fs<<tmpX(i, j)<<" ";
}
fs<<tmpY[i]<<endl;
}
}
template<typename M>
tensor<float, M> KernelClassification<M>::predict_2C(const tensor<float, M>& X_test) {
tensor<float, M> result(X_test.shape());
tensor<float, M> linear_eq = calcLinearEq(X_test);
apply_scalar_functor(linear_eq, linear_eq, SF_SIGM);
apply_scalar_functor(result, linear_eq, SF_GT, .5f);
return result[indices[index_range()][index_range(0, 1)]].copy();
}
template<typename M>
tensor<float, M> KernelClassification<M>::predict_MC(const tensor<float, M>& X_test) {
tensor<float, M> result(extents[X_test.shape(0)][1]);
tensor<float, M> linear_eq = calcLinearEq(X_test);
tensor<float, M> sigma = calcSigmaReduced(linear_eq);
reduce_to_col(result, sigma, RF_ARGMAX);
return result[indices[index_range()][index_range(0, 1)]].copy();
}
template<typename M>
tensor<float, M> KernelClassification<M>::convertYtoM(const tensor<float, M>& Y) {
tensor<float, host_memory_space> result_h(extents[Y.shape(0)][n_classes]);
tensor<float, M> result(extents[Y.shape(0)][n_classes]);
result_h = 0.f;
tensor<float, host_memory_space> y_host(Y.shape());
y_host = Y;
for (unsigned i = 0, ii = Y.shape(0); i < ii; ++i) {
// use the class number as index to set the cell to 1
result_h(i, y_host[i]) = 1.f;
}
result = result_h;
return result;
}
template<typename M>
double KernelClassification<M>::isConverging(const float& epsilon, const tensor<float, M>& delta_w) {
double result = 0.0;
tensor_view<float, M> slice = delta_w[indices[index_range()][index_range(0, 1)]];
tensor<float, M> n = slice.copy();
result = norm2(slice);
// cout<<"delta_W\n"<<delta_w<<endl;
// cout<<"Slice\n"<<n<<endl;
return result;
}
template<typename M>
tensor<float, M> KernelClassification<M>::calcError(const tensor<float, M>& sigma, const tensor<float, M>& Y) {
tensor<float, M> sigma_1 = sigma.copy();
tensor<float, M> sigma_0 = 1.f - sigma;
tensor<float, M> tmpSigma(sigma.shape());
tensor<float, M> result(extents[n_classes]);
for (int i = 0; i < this->n_classes; i++) {
tensor_view<float, M> slice_Y1 = Y[indices[index_range()][index_range(i, i+1)]];
tensor_view<float, M> slice_S1 = sigma_1[indices[index_range()][index_range(i, i+1)]];
tensor_view<float, M> slice_S0 = sigma_0[indices[index_range()][index_range(i, i+1)]];
tensor<float, M> yy = slice_Y1.copy();
tensor<float, M> ss1 = slice_S1.copy();
tensor<float, M> ss0 = slice_S0.copy();
apply_scalar_functor(ss1, SF_LOG);
apply_scalar_functor(ss0, SF_LOG);
matrix_times_col(ss1, yy[indices[index_range()][0]]);
matrix_times_col(ss0, 1.f - yy[indices[index_range()][0]]);
sigma_1[indices[index_range()][index_range(i, i+1)]] = ss1;
sigma_0[indices[index_range()][index_range(i, i+1)]] = ss0;
}
tmpSigma = sigma_1 + sigma_0;
reduce_to_row(result, tmpSigma);
return -1.f * result;
}
template<typename M>
int KernelClassification<M>::missClassified(const tensor<float, M>& X, const tensor<float, M>& Y) {
int result = 0;
tensor<float, M> predicted = predict(X);
tensor<float, M> diff(Y.shape());
apply_binary_functor(diff, Y, predicted, BF_EQ);
result = Y.shape(0) - sum(diff);
return result;
}
template<typename M>
tensor<float, M> KernelClassification<M>::getAlpha() {
return this->alpha;
}
template<typename M>
tensor<float, M> KernelClassification<M>::getB() {
return b;
}
template<typename M>
double KernelClassification<M>::predictWithError(const tensor<float, M>& X_test, const tensor<float, M>& Y_test) {
double result = 0.0;
result = missClassified(X_test, Y_test);
return result;
}
template<typename M>
void KernelClassification<M>::printParamToScreen() {
}
template <typename M>
KernelClassification<M>::~KernelClassification() {
// TODO Auto-generated destructor stub
}
//template class KernelClassification<dev_memory_space>;
//template class KernelClassification<host_memory_space>;
| true |
75bdadaa580a234030ba3bd4065c8687bc8a312c | C++ | liuxuanhai/C-code | /Qt4精彩实例分析/C++ GUI Programming with QT4/01 HelloWorld.cpp | GB18030 | 554 | 2.609375 | 3 | [] | no_license | // : 2014-08-26 13:00:08
#include <QApplication> // QtͼλӦó Դ, , , ¼...
// QtķͼλӦó, Ҫ<QCoreApplication>
#include <QPushButton>
int main(int argc, char ** argv) // ͼʾ, ¼Ĺ
{
QApplication app(argc, argv);
QPushButton b("Hello World!"); // ûָťĸ, ԼΪ
b.show();
QObject::connect(&b, SIGNAL(clicked()), &app, SLOT(quit()));
return app.exec();
} | true |
5819ef837a66b6aee1601c989761f611318d2caa | C++ | lakshmanaram/penguinV | /PenguinV/unit_tests/cuda/unit_test_helper_cuda.h | UTF-8 | 1,512 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | #pragma once
#include <algorithm>
#include <cstdlib>
#include <vector>
#include "../../Library/image_exception.h"
#include "../../Library/cuda/image_buffer_cuda.cuh"
// A bunch of functions to help writing unit tests
namespace Unit_Test
{
namespace Cuda
{
// Generate images
Bitmap_Image_Cuda::ImageCuda uniformImage();
Bitmap_Image_Cuda::ImageCuda uniformImage(uint8_t value);
Bitmap_Image_Cuda::ImageCuda blackImage();
Bitmap_Image_Cuda::ImageCuda whiteImage();
std::vector < Bitmap_Image_Cuda::ImageCuda > uniformImages( uint32_t images );
std::vector < Bitmap_Image_Cuda::ImageCuda > uniformImages( std::vector < uint8_t > intensityValue );
// Image size and ROI verification
template <typename data>
bool equalSize( const data & image1, const data & image2 )
{
return image1.height() == image2.height() && image1.width() == image2.width() &&
image1.colorCount() == image2.colorCount();
};
bool verifyImage( const Bitmap_Image_Cuda::ImageCuda & image, uint8_t value );
// Return random value for specific range or variable type
template <typename data>
data randomValue(int maximum)
{
if( maximum <= 0 )
return 0;
else
return static_cast<data>( rand() ) % maximum;
};
template <typename data>
data randomValue(data minimum, int maximum)
{
if( maximum <= 0 ) {
return 0;
}
else {
data value = static_cast<data>( rand() ) % maximum;
if( value < minimum )
value = minimum;
return value;
}
};
};
};
| true |
9a090573cad880a58784965f272eccc975d2063c | C++ | qiuyuoye/StockMonitor | /Stocks/analyse/TrendAnalyse.h | UTF-8 | 2,293 | 2.734375 | 3 | [] | no_license | #pragma once
#include "Analyse.h"
#include "stock/Stock.h"
#include <vector>
#include <set>
#include <map>
enum Trend
{
E_TRD_NONE,
E_TRD_UP,
E_TRD_FLUCTUATION_UP,
E_TRD_DOWN,
E_TRD_FLUCTUATION_DOWN,
};
class __declspec(dllexport) PeriodItem
{
public:
static double getSlopDiff(const PeriodItem& item1, const PeriodItem& item2);
static double getSDDiff(const PeriodItem& item1, const PeriodItem& item2);
static double getFluctuationDiff(const PeriodItem& item1, const PeriodItem& item2);
PeriodItem();
explicit PeriodItem(float ratio);
~PeriodItem();
void initResult();
void compute(const std::vector<double>& datas);
void computeParams(const std::vector<double>& datas);
void computeTrend(const std::vector<double>& datas);
void print(StockCPtr pStock, int offset);
int getDays() const { return m_endIndex - m_startIndex + 1;};
std::string getPeriod();
Trend m_period;
unsigned int m_startIndex;
unsigned int m_endIndex;
double m_avg;
double m_max;
double m_min;
double m_avgSlope;
double m_slopSD; //Standard Deviation
double m_fluctuation;
double m_maxGain;
double m_maxLoss;
private:
float m_ratio;
};
typedef std::vector<PeriodItem> PeriodItemVec;
class __declspec(dllexport) TrendAnalyse : public Analyse
{
public:
explicit TrendAnalyse(StockCPtr stockPtr, IndexType majorIndex);
~TrendAnalyse(void);
virtual void analyse();
virtual void print();
void pushRelative(IndexType relIdx)
{
m_relIdxVec.push_back(relIdx);
}
const PeriodItemVec& getMajor()
{
return m_majorVec;
}
const PeriodItemVec& getRelative(IndexType relIdx)
{
return m_relPrdsMap[relIdx];
}
private:
class DiffItem
{
public:
unsigned int m_index;
double m_value;
};
typedef std::map<IndexType, PeriodItemVec> PrdItemVecMap;
void analysisMajor();
void initMajorPrds(const std::vector<double>& datas);
void mergePeriods(const std::vector<double>& datas, unsigned int size);
void mergeSimilarPeriods(const std::vector<double>& datas);
double getAvgSlops(const PeriodItemVec& prdItems);
double getAvgStandardDeviation(const PeriodItemVec& prdItems);
void analyseRelPeriods();
IndexType m_majorIdx;
std::vector<IndexType> m_relIdxVec;
PeriodItemVec m_majorVec;
PrdItemVecMap m_relPrdsMap;
int m_mergedSize;
};
| true |
52b14144b64515704a6c0e3316b0db35811603ea | C++ | hanzhuoran/UchicagoHPC | /PS1/serial/main.cpp | UTF-8 | 2,514 | 3 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <math.h>
#include <vector>
#include <iomanip>
using namespace std;
int prev (int i, int N);
int next (int i, int N);
int main (int argc, char *argv[])
{
if(argc != 7)
{
cout<<"Wrong Number of Inputs."<<endl;
}
else
{
int N = stod(argv[1]);
int NT = stod(argv[2]);
double L = stod(argv[3]);
double T = stod(argv[4]);
double u = stod(argv[5]);
double v = stod(argv[6]);
cout<<"You have all the inputs."<<endl;
double dx = L/N;
double dy = dx;
double dt = T/(NT);
cout <<"dt is "<< dt<<endl;
cout <<"dx is "<< dx<<endl;
cout << "dt/(2dx) "<< dt/(2*dx)<< endl;
double x0 = L/2;
double y0 = L/2;
double deltax = L/4;
double deltay = L/4;
double val;
double x;
double y;
int iprev;
int inext;
int jprev;
int jnext;
// double test;
if (dt > dx/sqrt(2*(u*u+v*v)))
{
cout<<"Numerically Instable"<<endl;
exit(1);
}
// Open Files
ofstream outfile;
outfile.open("data.txt");
//Initialization
// double C[N][N];
// double Cnext[N][N];
vector< vector<double> > C(N,vector<double>(N));
vector< vector<double> > Cnext(N,vector<double>(N));
for (int i=0; i<N ; i++)
{
for (int j=0; j<N ; j++)
{
x = i*dx;
y = j*dy;
val = pow((x-x0),2)/(2*pow(deltax,2))+pow((y-y0),2)/(2*pow(deltay,2));
C[i][j] = exp(-val);
Cnext[i][j] = 0;
}
}
//Lax Scheme
for (int n = 0; n < NT ; n++)
{
for(int i = 0; i< N ; i++)
{
for(int j = 0; j < N; j++)
{
iprev = prev(i,N);
inext = next(i,N);
jprev = prev(j,N);
jnext = next(j,N);
//update t_n+1 at i,j
Cnext[i][j] = 0.25*(C[iprev][j]+C[inext][j]+C[i][jprev]+C[i][jnext])
- dt/(2*dx)*(u*(C[inext][j]-C[iprev][j])+v*(C[i][jnext]-C[i][jprev]));
}
}
if (n% 10000 == 0)
{
// Write to ASCII
for (int i=0; i < N ; i++)
{
for (int j=0; j < N ; j++)
{
outfile<<fixed << setprecision(4)<<C[i][j]<<' ';
}
outfile<<endl;
}
}
C = Cnext;
}
// Write to ASCII
for (int i=0; i < N ; i++)
{
for (int j=0; j < N ; j++)
{
outfile<<fixed << setprecision(4)<<C[i][j]<<' ';
}
outfile<<endl;
}
//Close file
outfile.close();
}
return 0;
}
int prev (int i, int N)
{
int prev;
if (i == 0)
{
prev = N-1;
}
else
{
prev = i-1;
}
return prev;
}
int next (int i, int N)
{
int next;
if (i == N-1)
{
next = 0;
}
else
{
next = i+1;
}
return next;
}
| true |
f74ea70d4543bd6148bd3f1782f9fc2bcb8a2b43 | C++ | cjlcarvalho/patterns | /Implementations/Behavioral/Iterator/iterator-composite/iterator.h | UTF-8 | 298 | 2.734375 | 3 | [] | no_license | #ifndef ITERATOR_H
#define ITERATOR_H
class Component;
class Iterator
{
public:
Iterator(Component *component);
void first();
void next();
bool hasNext() const;
Component *current() const;
private:
Component *m_component;
unsigned int m_top;
};
#endif // ITERATOR_H
| true |
fbd8ac1f651cca811569ebe8f533b6243b431170 | C++ | Lppy/Calculation | /Model/Function/eigenvalue.h | UTF-8 | 350 | 2.515625 | 3 | [] | no_license | #pragma once
#include "matrix.h"
class Eigenvalue
{
private:
static const int MAX_N = 30;
public:
Eigenvalue();
~Eigenvalue();
void swap(double &a, double &b);
void MatrixToArray(Matrix a, double * A);
void MatrixHessenberg(double * A, int n, double * result);
bool MatrixEigenValue(Matrix a, int n, int LoopNumber, double *result);
};
| true |
8d96eb90b696b9f15eb8e133d8e182b4f488ebb9 | C++ | sstanitski/CISC360Project | /SeqSorts.cpp | UTF-8 | 2,254 | 3.953125 | 4 | [] | no_license | //Author Eric
//CPP Code for various sorts
//Website linked above
// A function to implement bubble sort
//http://www.geeksforgeeks.org/bubble-sort/
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
//http://www.geeksforgeeks.org/comb-sort/
// Function to sort a[0..n-1] using Comb Sort
void combSort(int a[], int n)
{
// Initialize gap
int gap = n;
// Initialize swapped as true to make sure that
// loop runs
bool swapped = true;
// Keep running while gap is more than 1 and last
// iteration caused a swap
while (gap != 1 || swapped == true)
{
// Find next gap
gap = getNextGap(gap);
// Initialize swapped as false so that we can
// check if swap happened or not
swapped = false;
// Compare all elements with current gap
for (int i=0; i<n-gap; i++)
{
if (a[i] > a[i+gap])
{
swap(a[i], a[i+gap]);
swapped = true;
}
}
}
}
//https://geeksforgeeks.org/shellsort
/* function to sort arr using shellSort */
int shellSort(int arr[], int n)
{
// Start with a big gap, then reduce the gap
for (int gap = n/2; gap > 0; gap /= 2)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements a[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is
// gap sorted
for (int i = gap; i < n; i += 1)
{
// add a[i] to the elements that have been gap sorted
// save a[i] in temp and make a hole at position i
int temp = arr[i];
// shift earlier gap-sorted elements up until the correct
// location for a[i] is found
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
// put temp (the original a[i]) in its correct location
arr[j] = temp;
}
}
return 0;
}
| true |
83a7c01980daed7720c52ee4dccb2b8f657463e6 | C++ | jgreitemann/aoc18 | /day7/parallel_make.cpp | UTF-8 | 2,650 | 2.859375 | 3 | [] | no_license | #include <algorithm>
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <regex>
#include <set>
#include <string>
constexpr inline static int base_duration = 60;
constexpr inline static size_t n_workers = 4;
int main() {
auto str = [] () -> std::string {
std::ifstream is("input");
return {
std::istreambuf_iterator<char>{is},
std::istreambuf_iterator<char>{}
};
}();
std::regex re{"Step ([A-Z]) must be finished before step ([A-Z]) can begin"};
std::map<char, std::set<char>> rules;
std::for_each(std::sregex_iterator{str.begin(), str.end(), re},
std::sregex_iterator{},
[&] (std::smatch const& match) {
auto it = rules.insert({match[2].str()[0], {}}).first;
rules.insert({match[1].str()[0], {}});
it->second.insert(match[1].str()[0]);
});
auto yield = [&] {
auto it = rules.begin();
while (it != rules.end() && !it->second.empty())
++it;
return it;
};
std::map<char, int> running;
std::string done;
for (size_t s = 0; !rules.empty() || !running.empty(); ++s) {
// log progress
for (auto & [c, t] : running) {
t--;
}
// clear done tasks
for (auto it = running.begin(); it != running.end();) {
if (it->second < 0) {
// announce done
done += it->first;
// update dependencies
for (auto & [c, d] : rules) {
d.erase(it->first);
}
// remove running task
it = running.erase(it);
} else {
++it;
}
}
// check for idle workers and dispatch tasks
decltype(yield()) task_it;
while (running.size() < n_workers && (task_it = yield()) != rules.end()) {
running[task_it->first] = task_it->first - 'A' + base_duration;
rules.erase(task_it);
}
// print
std::cout << s << '\t';
std::transform(running.begin(), running.end(),
std::ostream_iterator<char>{std::cout, "\t"},
[] (auto const& p) { return p.first; });
std::fill_n(std::ostream_iterator<char>{std::cout, "\t"},
n_workers - running.size(), '.');
std::cout << done << std::endl;
}
}
| true |
3598dc3bcd8222520ac13bed98e186f8b329d025 | C++ | bughunter9/DataStructuresandAlgorithms | /Practice/Queue/base.cpp | UTF-8 | 1,048 | 3.9375 | 4 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define n 20
// Queue: FIFO - First In First Out
// push is similar to enqueue
// pop is similar to dequeue
// top is similar to peek
class Queue{
int *arr;
int front;
int back;
public:
Queue()
{
arr = new int[n];
front = -1;
back = -1;
}
void push(int x)
{
if(back == n-1)
{
cout<<"Queue OverFlow"<<endl;
return;
}
back++;
arr[back]=x;
if(front == -1)
{
front++;
}
}
void pop()
{
if(front == -1 || front > back)
{
cout<<"No element in queue"<<endl;
return;
}
front++;
}
int peek()
{
if(front == -1 || front > back)
{
cout<<"No element in queue"<<endl;
return -1;
}
return arr[front];
}
bool empty()
{
if(front == -1 || front > back)
{
return true;
}
return false;
}
};
int main()
{
Queue q;
q.push(1);
q.push(2);
q.push(3);
q.push(4);
cout<<q.peek()<<endl;
q.pop();
cout<<q.peek()<<endl;
q.pop();
cout<<q.peek()<<endl;
q.pop();
cout<<q.peek()<<endl;
q.pop();
cout<<q.empty()<<endl;
} | true |
4a40e645f44d8d85ae720d30eaa5a54318a0281d | C++ | xx8086/liuhan_pipeline | /liuhan_pipeline/lhpipeline/lhrasterization/lhlinesegment.cpp | GB18030 | 1,858 | 3.046875 | 3 | [] | no_license | #include "lhlinesegment.h"
#include<algorithm>
LhLineSegment::LhLineSegment()
{
}
LhLineSegment::~LhLineSegment()
{
}
bool LhLineSegment::on_segment(Point Pi, Point Pj, Point Q)
{
if ((Q.x - Pi.x) * (Pj.y - Pi.y) == (Pj.x - Pi.x) * (Q.y - Pi.y) //
//֤Qpi,pj֮
&& std::min(Pi.x, Pj.x) <= Q.x && Q.x <= std::max(Pi.x, Pj.x)
&& std::min(Pi.y, Pj.y) <= Q.y && Q.y <= std::max(Pi.y, Pj.y))
return true;
else
return false;
}
void LhLineSegment::getlinepara(Line &l)
{
l.a = l.p1.y - l.p2.y;
l.b = l.p2.x - l.p1.x;
l.c = l.p1.x*l.p2.y - l.p1.y*l.p2.x;
}
bool LhLineSegment::getcrosspoint(Line &l1, Line &l2, Point& p)
{
getlinepara(l1);
getlinepara(l2);
float D = l1.a*l2.b - l2.a*l1.b;
if (0.0 == D)return false;
p.x = (l1.b*l2.c - l2.b*l1.c) / D;
p.y = (l1.c*l2.a - l2.c*l1.a) / D;
return true;
}
bool LhLineSegment::line_segment_cross(float a_x, float a_y, float b_x, float b_y,
float c_x, float c_y, float d_x, float d_y,
float& x, float & y) {
Point p;
Point a(a_x, a_y);
Point b(b_x, b_y);
Point c(c_x, c_y);
Point d(d_x, d_y);
Line l1(a, b);
Line l2(c, d);
bool iscross = false;
iscross = getcrosspoint(l1, l2, p);
if (iscross) {
iscross = on_segment(c, d, p);
}
return iscross;
}
bool LhLineSegment::line_cross(float a_x, float a_y, float b_x, float b_y,
float c_x, float c_y, float d_x, float d_y,
float& x, float & y) {
//Point a(a_x, a_y);
//Point b(b_x, b_y);
//Point c(c_x, c_y);
//Point d(d_x, d_y);
Point p;
Line l1(Point(a_x, a_y), Point(b_x, b_y));
Line l2(Point(c_x, c_y), Point(d_x, d_y));
bool iscross = false;
iscross = getcrosspoint(l1, l2, p);
return iscross;
}
| true |
19a987bd22247a71cdd6a3fe92c081956a1ad06e | C++ | WinningLiu/SCU | /COEN/coen175/Lab 3/phase3/parser.cpp | UTF-8 | 17,257 | 3.21875 | 3 | [] | no_license | /*
* File: parser.cpp
*
* Description: This file contains the public and private function and
* variable definitions for the recursive-descent parser for
* Simple C.
*/
# include <cstdlib>
# include <iostream>
# include "tokens.h"
# include "lexer.h"
# include "Type.h"
# include "checker.h"
# include <vector>
using namespace std;
typedef std::vector<class Type> Parameters;
static int lookahead;
static string lexbuf;
static void expression();
static void statement();
/*
* Function: error
*
* Description: Report a syntax error to standard error.
*/
static void error()
{
if (lookahead == DONE)
report("syntax error at end of file");
else
report("syntax error at '%s'", lexbuf);
exit(EXIT_FAILURE);
}
/*
* Function: match
*
* Description: Match the next token against the specified token. A
* failure indicates a syntax error and will terminate the
* program since our parser does not do error recovery.
*/
static void match(int t)
{
if (lookahead != t)
error();
lookahead = lexan(lexbuf);
}
// Identifier
static string identifier() {
string str = lexbuf;
match(ID);
return str;
}
// Number
static unsigned number() {
unsigned num = stoul(lexbuf);
match(NUM);
return num;
}
/*
* Function: isSpecifier
*
* Description: Return whether the given token is a type specifier.
*/
static bool isSpecifier(int token)
{
return token == INT || token == CHAR || token == STRUCT;
}
/*
* Function: specifier
*
* Description: Parse a type specifier. Simple C has int, char, and
* structure types.
*
* specifier:
* int
* char
* struct identifier
*/
static string specifier()
{
if (lookahead == INT) {
match(INT);
return "int";
}
if (lookahead == CHAR) {
match(CHAR);
return "char";
}
match(STRUCT);
return identifier();
}
/*
* Function: pointers
*
* Description: Parse pointer declarators (i.e., zero or more asterisks).
*
* pointers:
* empty
* * pointers
*/
static unsigned pointers()
{
unsigned count = 0;
while (lookahead == '*') {
count += 1;
match('*');
}
return count;
}
/*
* Function: declarator
*
* Description: Parse a declarator, which in Simple C is either a scalar
* variable or an array, both with optional pointer
* declarators, or a callback (i.e., a simple function
* pointer).
*
* declarator:
* pointers identifier
* pointers identifier [ num ]
* pointers ( * identifier ) ( )
*/
static void declarator(const string &spec)
{
unsigned indirection = pointers();
if (lookahead == '(') {
match('(');
match('*');
string id = identifier();
declareVariable(id, Type(CALLBACK, spec, indirection));
match(')');
match('(');
match(')');
} else {
string id = identifier();
if (lookahead == '[') {
match('[');
unsigned num = number();
match(']');
declareVariable(id, Type(ARRAY, spec, indirection, num));
}
else {
declareVariable(id, Type(SCALAR, spec, indirection));
}
}
}
/*
* Function: declaration
*
* Description: Parse a local variable declaration. Global declarations
* are handled separately since we need to detect a function
* as a special case.
*
* declaration:
* specifier declarator-list ';'
*
* declarator-list:
* declarator
* declarator , declarator-list
*/
static void declaration()
{
string spec = specifier();
declarator(spec);
while (lookahead == ',') {
match(',');
declarator(spec);
}
match(';');
}
/*
* Function: declarations
*
* Description: Parse a possibly empty sequence of declarations.
*
* declarations:
* empty
* declaration declarations
*/
static void declarations()
{
while (isSpecifier(lookahead))
declaration();
}
/*
* Function: primaryExpression
*
* Description: Parse a primary expression.
*
* primary-expression:
* ( expression )
* identifier
* character
* string
* num
*/
static void primaryExpression(bool lparen)
{
if (lparen) {
expression();
match(')');
} else if (lookahead == CHARACTER)
match(CHARACTER);
else if (lookahead == STRING)
match(STRING);
else if (lookahead == NUM)
match(NUM);
else if (lookahead == ID) {
string id = identifier();
checkID(id);
}
else
error();
}
/*
* Function: postfixExpression
*
* Description: Parse a postfix expression.
*
* postfix-expression:
* primary-expression
* postfix-expression [ expression ]
* postfix-expression ( expression-list )
* postfix-expression ( )
* postfix-expression . identifier
* postfix-expression -> identifier
*
* expression-list:
* expression
* expression , expression-list
*/
static void postfixExpression(bool lparen)
{
primaryExpression(lparen);
while (1) {
if (lookahead == '[') {
match('[');
expression();
match(']');
cout << "index" << endl;
} else if (lookahead == '(') {
match('(');
if (lookahead != ')') {
expression();
while (lookahead == ',') {
match(',');
expression();
}
}
match(')');
cout << "call" << endl;
} else if (lookahead == '.') {
match('.');
match(ID);
cout << "dot" << endl;
} else if (lookahead == ARROW) {
match(ARROW);
match(ID);
cout << "arrow" << endl;
} else
break;
}
}
/*
* Function: prefixExpression
*
* Description: Parse a prefix expression.
*
* prefix-expression:
* postfix-expression
* ! prefix-expression
* - prefix-expression
* * prefix-expression
* & prefix-expression
* sizeof prefix-expression
* sizeof ( specifier pointers )
* ( specifier pointers ) prefix-expression
*
* This grammar is still ambiguous since "sizeof(type) * n"
* could be interpreted as a multiplicative expression or as a
* cast of a dereference. The correct interpretation is the
* former, as the latter makes little sense semantically. We
* resolve the ambiguity here by always consuming the "(type)"
* as part of the sizeof expression.
*/
static void prefixExpression()
{
if (lookahead == '!') {
match('!');
prefixExpression();
cout << "not" << endl;
} else if (lookahead == '-') {
match('-');
prefixExpression();
cout << "neg" << endl;
} else if (lookahead == '*') {
match('*');
prefixExpression();
cout << "deref" << endl;
} else if (lookahead == '&') {
match('&');
prefixExpression();
cout << "addr" << endl;
} else if (lookahead == SIZEOF) {
match(SIZEOF);
if (lookahead == '(') {
match('(');
if (isSpecifier(lookahead)) {
specifier();
pointers();
match(')');
} else
postfixExpression(true);
} else
prefixExpression();
cout << "sizeof" << endl;
} else if (lookahead == '(') {
match('(');
if (isSpecifier(lookahead)) {
specifier();
pointers();
match(')');
prefixExpression();
cout << "cast" << endl;
} else
postfixExpression(true);
} else
postfixExpression(false);
}
/*
* Function: multiplicativeExpression
*
* Description: Parse a multiplicative expression.
*
* multiplicative-expression:
* prefix-expression
* multiplicative-expression * prefix-expression
* multiplicative-expression / prefix-expression
* multiplicative-expression % prefix-expression
*/
static void multiplicativeExpression()
{
prefixExpression();
while (1) {
if (lookahead == '*') {
match('*');
prefixExpression();
cout << "mul" << endl;
} else if (lookahead == '/') {
match('/');
prefixExpression();
cout << "div" << endl;
} else if (lookahead == '%') {
match('%');
prefixExpression();
cout << "rem" << endl;
} else
break;
}
}
/*
* Function: additiveExpression
*
* Description: Parse an additive expression.
*
* additive-expression:
* multiplicative-expression
* additive-expression + multiplicative-expression
* additive-expression - multiplicative-expression
*/
static void additiveExpression()
{
multiplicativeExpression();
while (1) {
if (lookahead == '+') {
match('+');
multiplicativeExpression();
cout << "add" << endl;
} else if (lookahead == '-') {
match('-');
multiplicativeExpression();
cout << "sub" << endl;
} else
break;
}
}
/*
* Function: relationalExpression
*
* Description: Parse a relational expression. Note that Simple C does not
* have shift operators, so we go immediately to additive
* expressions.
*
* relational-expression:
* additive-expression
* relational-expression < additive-expression
* relational-expression > additive-expression
* relational-expression <= additive-expression
* relational-expression >= additive-expression
*/
static void relationalExpression()
{
additiveExpression();
while (1) {
if (lookahead == '<') {
match('<');
additiveExpression();
cout << "ltn" << endl;
} else if (lookahead == '>') {
match('>');
additiveExpression();
cout << "gtn" << endl;
} else if (lookahead == LEQ) {
match(LEQ);
additiveExpression();
cout << "leq" << endl;
} else if (lookahead == GEQ) {
match(GEQ);
additiveExpression();
cout << "geq" << endl;
} else
break;
}
}
/*
* Function: equalityExpression
*
* Description: Parse an equality expression.
*
* equality-expression:
* relational-expression
* equality-expression == relational-expression
* equality-expression != relational-expression
*/
static void equalityExpression()
{
relationalExpression();
while (1) {
if (lookahead == EQL) {
match(EQL);
relationalExpression();
cout << "eql" << endl;
} else if (lookahead == NEQ) {
match(NEQ);
relationalExpression();
cout << "neq" << endl;
} else
break;
}
}
/*
* Function: logicalAndExpression
*
* Description: Parse a logical-and expression. Note that Simple C does
* not have bitwise-and expressions.
*
* logical-and-expression:
* equality-expression
* logical-and-expression && equality-expression
*/
static void logicalAndExpression()
{
equalityExpression();
while (lookahead == AND) {
match(AND);
equalityExpression();
cout << "and" << endl;
}
}
/*
* Function: expression
*
* Description: Parse an expression, or more specifically, a logical-or
* expression, since Simple C does not allow comma or
* assignment as an expression operator.
*
* expression:
* logical-and-expression
* expression || logical-and-expression
*/
static void expression()
{
logicalAndExpression();
while (lookahead == OR) {
match(OR);
logicalAndExpression();
cout << "or" << endl;
}
}
/*
* Function: statements
*
* Description: Parse a possibly empty sequence of statements. Rather than
* checking if the next token starts a statement, we check if
* the next token ends the sequence, since a sequence of
* statements is always terminated by a closing brace.
*
* statements:
* empty
* statement statements
*/
static void statements()
{
while (lookahead != '}')
statement();
}
/*
* Function: assignment
*
* Description: Parse an assignment statement.
*
* assignment:
* expression = expression
* expression
*/
static void assignment()
{
expression();
if (lookahead == '=') {
match('=');
expression();
}
}
/*
* Function: statement
*
* Description: Parse a statement. Note that Simple C has so few
* statements that we handle them all in this one function.
*
* statement:
* { declarations statements }
* return expression ;
* while ( expression ) statement
* for ( assignment ; expression ; assignment ) statement
* if ( expression ) statement
* if ( expression ) statement else statement
* assignment ;
*/
static void statement()
{
if (lookahead == '{') {
openScope();
match('{');
declarations();
statements();
match('}');
closeScope();
} else if (lookahead == RETURN) {
match(RETURN);
expression();
match(';');
} else if (lookahead == WHILE) {
match(WHILE);
match('(');
expression();
match(')');
statement();
} else if (lookahead == FOR) {
match(FOR);
match('(');
assignment();
match(';');
expression();
match(';');
assignment();
match(')');
statement();
} else if (lookahead == IF) {
match(IF);
match('(');
expression();
match(')');
statement();
if (lookahead == ELSE) {
match(ELSE);
statement();
}
} else {
assignment();
match(';');
}
}
/*
* Function: parameter
*
* Description: Parse a parameter, which in Simple C is always either a
* simple variable with optional pointer declarators, or a
* callback (i.e., a simple function pointer)
*
* parameter:
* specifier pointers identifier
* specifier pointers ( * identifier ) ( )
*/
static Type parameter()
{
string spec = specifier();
unsigned indirection = pointers();
if (lookahead == '(') {
match('(');
match('*');
string id = identifier();
match(')');
match('(');
match(')');
declareParameter(id, Type(CALLBACK, spec, indirection));
return Type(CALLBACK, spec, indirection);
} else {
string id = identifier();
Type type(SCALAR, spec, indirection);
declareParameter(id, Type(SCALAR, spec, indirection));
return Type(CALLBACK, spec, indirection);
}
}
/*
* Function: parameters
*
* Description: Parse the parameters of a function, but not the opening or
* closing parentheses.
*
* parameters:
* void
* parameter-list
*
* parameter-list:
* parameter
* parameter , parameter-list
*/
static Parameters* parameters()
{
Parameters *param = new Parameters();
if (lookahead == VOID)
match(VOID);
else {
param->push_back(parameter());
while (lookahead == ',') {
match(',');
param->push_back(parameter());
}
}
return param;
}
/*
* Function: globalDeclarator
*
* Description: Parse a declarator, which in Simple C is either a scalar
* variable, an array, or a function, all with optional
* pointer declarators, or a callback (i.e., a simple function
* pointer).
*
* global-declarator:
* pointers identifier
* pointers identifier ( )
* pointers identifier [ num ]
* pointers ( * identifier ) ( )
*/
static void globalDeclarator(const string &spec)
{
unsigned indirection = pointers();
if (lookahead == '(') {
match('(');
match('*');
string id = identifier();
match(')');
match('(');
match(')');
declareVariable(id, Type(CALLBACK, spec, indirection));
} else {
string id = identifier();
if (lookahead == '(') {
match('(');
match(')');
declareFunction(id, Type(FUNCTION, spec, indirection));
} else if (lookahead == '[') {
match('[');
unsigned num = number();
match(']');
declareVariable(id, Type(ARRAY, spec, indirection, num));
}
else {
declareVariable(id, Type(SCALAR, spec, indirection));
}
}
}
/*
* Function: remainingDeclarators
*
* Description: Parse any remaining global declarators after the first.
*
* remaining-declarators:
* ; Type(int kind, const string &specifier, unsigned indirection = 0);
*/
static void remainingDeclarators(const string &spec) {
while (lookahead == ',') {
match(',');
globalDeclarator(spec);
}
match(';');
}
/*
* Function: globalOrFunction
*
* Description: Parse a global declaration or function definition.
*
* global-or-function:
* struct identifier { declaration declarations } ;
* specifier pointers identifier remaining-decls
* specifier pointers identifier ( ) remaining-decls
* specifier pointers identifier [ num ] remaining-decls
* specifier pointers identifier ( parameters ) { ... }
*/
static void globalOrFunction()
{
string spec = specifier();
if (spec != "int" && spec != "char" && lookahead == '{') {
openStruct(spec);
match('{');
declaration();
declarations();
match('}');
match(';');
closeStruct(spec);
} else {
unsigned indirection = pointers();
if (lookahead == '(') {
match('(');
match('*');
string id = identifier();
match(')');
match('(');
match(')');
declareVariable(id, Type(CALLBACK, spec, indirection));
remainingDeclarators(spec);
} else {
string id = identifier();
if (lookahead == '[') {
match('[');
unsigned num = number();
match(']');
declareVariable(id, Type(ARRAY, spec, indirection, num));
remainingDeclarators(spec);
} else if (lookahead == '(') {
match('(');
if (lookahead == ')') {
declareFunction(id, Type(FUNCTION, spec, indirection));
match(')');
remainingDeclarators(spec);
} else {
openScope();
Parameters *param = parameters();
match(')');
defineFunction(id, Type(FUNCTION, spec, indirection, param));
match('{');
declarations();
statements();
match('}');
closeScope();
}
} else {
declareVariable(id, Type(SCALAR, spec, indirection));
remainingDeclarators(spec);
}
}
}
}
/*
* Function: main
*
* Description: Analyze the standard input stream.
*/
int main()
{
lookahead = lexan(lexbuf);
openScope();
while (lookahead != DONE)
globalOrFunction();
closeScope();
exit(EXIT_SUCCESS);
}
| true |
b33c3953e61a8b6bff4f2898248c4ae3c24aba45 | C++ | tyanmahou/Re-Abyss | /Re-Abyss/app/components/Actor/Player/ChargeCtrl.hpp | UTF-8 | 672 | 2.703125 | 3 | [] | no_license | #pragma once
#include <abyss/modules/GameObject/IComponent.hpp>
namespace abyss::Actor::Player
{
/// <summary>
/// player attack charge
/// </summary>
class ChargeCtrl : public IComponent
{
double m_charge;
public:
ChargeCtrl();
/// <summary>
/// charge update
/// </summary>
/// <param name="dt"></param>
/// <returns>true: attack</returns>
bool update(double dt);
/// <summary>
/// return charge and charge reset
/// </summary>
/// <returns>charge</returns>
double pop();
void reset();
double getCharge() const;
};
} | true |
45c346f4e245feca1c7587a7cfd766182496a682 | C++ | WeyrSDev/SFML-Blueprints | /Chapter-2/include/ResourceManager.hpp | UTF-8 | 2,445 | 3.1875 | 3 | [] | no_license | //
// Created by scastner on 11/7/2015.
//
#ifndef SFML_BLUEPRINTS_RESOURCEMANAGER_HPP
#define SFML_BLUEPRINTS_RESOURCEMANAGER_HPP
#include <SFML/Audio.hpp>
#include <unordered_map>
#include <memory>
template<typename RESOURCE, typename IDENTIFIER = int>
class ResourceManager
{
public:
/**
* This c++11 feature lets us delete the copy constructor and operator,
* which makes this class non-copyable.
*/
ResourceManager(const ResourceManager &) = delete;
ResourceManager &operator=(const ResourceManager &) = delete;
ResourceManager() = default;
/**
* This c++11 feature, variadic template, simply forwards any arguments to the
* parent class without knowing them. This method uses it because not all SFML
* resource classes use the same parameters.
*/
template<typename ... Args>
void load(const IDENTIFIER &id, Args &&... args)
{
std::unique_ptr<RESOURCE> ptr(new RESOURCE);
if (!ptr->loadFromFile(std::forward<Args>(args)...))
throw std::runtime_error("Impossible to load file");
_map.emplace(id, std::move(ptr));
}
RESOURCE &get(const IDENTIFIER &id) const
{
return *_map.at(id);
}
private:
std::unordered_map<IDENTIFIER, std::unique_ptr<RESOURCE>> _map;
};
template<typename IDENTIFIER>
class ResourceManager<sf::Music, IDENTIFIER>
{
public:
/**
* This c++11 feature lets us delete the copy constructor and operator,
* which makes this class non-copyable.
*/
ResourceManager(const ResourceManager &) = delete;
ResourceManager &operator=(const ResourceManager &) = delete;
ResourceManager() = default;
/**
* This c++11 feature, variadic template, simply forwards any arguments to the
* parent class without knowing them. This method uses it because not all SFML
* resource classes use the same parameters.
*/
template<typename ... Args>
void load(const IDENTIFIER &id, Args &&... args)
{
std::unique_ptr<sf::Music> ptr(new sf::Music);
if (!ptr->openFromFile(std::forward<Args>(args)...))
throw std::runtime_error("Impossible to load file");
_map.emplace(id, std::move(ptr));
}
sf::Music &get(const IDENTIFIER &id) const
{
return *_map.at(id);
}
private:
std::unordered_map<IDENTIFIER, std::unique_ptr<sf::Music>> _map;
};
#endif //SFML_BLUEPRINTS_RESOURCEMANAGER_HPP | true |
14129ddd2c4bf44138e151af31867039ad1b6873 | C++ | zmudson/World-Simulation | /Projekt1/Human.cpp | UTF-8 | 3,216 | 2.828125 | 3 | [] | no_license | #include "Human.h"
#include "Grass.h"
#include "Guarana.h"
#include "Dandelion.h"
#include <iostream>
#define STRENGTH 5
#define INITIATIVE 4
#define SYMBOL 'C'
#define NAME "czlowiek"
#define SKILL_STRENGTH 10
#define SKILL_DURATION_TIME 5
#define SKILL_RENEWING_TIME 5
#define YELLOW_COLOR_CODE 14
Human::Human(World* world, int positionX, int positionY) :
Animal(world, STRENGTH, INITIATIVE, positionX, positionY, SYMBOL, NAME) {
}
void Human::reproduce(Field* field) {
// human can't have children
}
void Human::action(World::directions direction) {
int x = position->getX();
int y = position->getY();
Field* currentField = world->getField(x, y);
if (direction == World::directions::LEFT)
x--;
else if (direction == World::directions::RIGHT)
x++;
else if (direction == World::directions::UP)
y--;
else if (direction == World::directions::DOWN)
y++;
Field* newField = world->getField(x, y);
if (newField->empty()) {
currentField->removeOrganism();
newField->setOrganism(this);
}
else {
newField->getOrganism()->collision(this);
}
if (skillActivationTime == SKILL_DURATION_TIME) {
std::string message = name + " traci moc magicznego eliksiru";
world->appendMessage(message);
isSkillActive = false;
skillActivationTime++;
}
else if (skillActivationTime == SKILL_DURATION_TIME + SKILL_RENEWING_TIME) {
isSkillReady = true;
skillActivationTime = 0;
}
else if (isSkillActive) {
strength--;
skillActivationTime++;
}
else if (skillActivationTime > SKILL_DURATION_TIME) {
skillActivationTime++;
}
}
void Human::draw() {
world->setOutputColor(YELLOW_COLOR_CODE);
Organism::draw();
}
bool Human::validateMove(World::directions direction) {
bool isValid = true;
if (position->getX() == 0 && direction == World::directions::LEFT)
isValid = false;
else if (position->getX() == world->getWidth() - 1 && direction == World::directions::RIGHT)
isValid = false;
else if (position->getY() == 0 && direction == World::directions::UP)
isValid = false;
else if (position->getY() == world->getHeight() - 1 && direction == World::directions::DOWN)
isValid = false;
return isValid;
}
void Human::activateSkill() {
if (isSkillReady) {
isSkillActive = true;
isSkillReady = false;
strength = SKILL_STRENGTH;
std::string message = name + " wypija magiczny eliksir";
std::cout << message << std::endl;
}
}
bool Human::getSkillActive() {
return isSkillActive;
}
std::string Human::describeCollisionWithPlant(Organism* plant) {
std::string message;
if (dynamic_cast<Dandelion*>(plant) != nullptr) {
message = name + " zdeptuje mlecz";
}
else if (dynamic_cast<Grass*>(plant) != nullptr) {
message = name + " kosi trawe";
}
else if (dynamic_cast<Guarana*>(plant) != nullptr) {
message = name + " je guarane, jego sila wzrasta do " + std::to_string(strength);
}
return message;
}
void Human::initSkillsFlags(int) {
if (skillActivationTime == 0) {
isSkillActive = false;
isSkillReady = true;
}
else if (skillActivationTime < SKILL_DURATION_TIME) {
isSkillActive = true;
isSkillReady = false;
}
else {
isSkillActive = false;
isSkillReady = false;
}
}
int Human::getSkillActivationTime() {
return skillActivationTime;
}
| true |
866e7a722b90161b2ae916528ed66a3b415e4736 | C++ | Uedaki/Jotun | /Collada/Collada.cpp | UTF-8 | 3,737 | 2.8125 | 3 | [] | no_license | #include "stdafx.h"
#include "Collada.h"
#include <map>
#include <functional>
#include "GeometryInstance.h"
#include "LightInstance.h"
#include "Camera.h"
void collada::Collada::loadFile(const std::string &file)
{
xmlParser::Parser parser(file);
root = parser.getRoot();
mapNodeById(*root);
}
void collada::Collada::mapNodeById(const xmlParser::Node &node)
{
if (node.isParameterExist("id"))
idToNode.emplace(node.getParameter("id").getString(), node);
for (auto &child : node.getChildren())
{
mapNodeById(child);
}
}
std::shared_ptr<graphic::Scene> collada::Collada::createScene()
{
scene = std::make_shared<graphic::Scene>();
const xmlParser::Node &instVisualScene = (*root)["scene"]["instance_visual_scene"];
const std::string &url = instVisualScene.getParameter("url").getString();
const xmlParser::Node &visualScene = idToNode.at(url.substr(1, url.length() - 1));
createVisualScene(visualScene);
return (scene);
}
void collada::Collada::createVisualScene(const xmlParser::Node &visualScene)
{
const std::map<std::string, std::function<std::shared_ptr<ObjectInstance>(const xmlParser::Node &node, std::vector<std::shared_ptr<Light>> &lightContext)>> router = {
{"instance_geometry", [this](const xmlParser::Node &node, std::vector<std::shared_ptr<Light>> &lightContext)
{
return (std::make_shared<GeometryInstance>(node, lightContext, this->getIdToNode()));
}
},
{"instance_camera", [this](const xmlParser::Node &node, std::vector<std::shared_ptr<Light>> &lightContext)
{
return (std::make_shared<BasicObjectInstance<Camera>>(node, this->getIdToNode()));
}
}
};
std::vector<std::shared_ptr<Light>> lightContext;
for (auto &node : visualScene.getChildren())
{
if (node.getTag() != "node")
continue;
for (auto &child : node.getChildren())
{
if (child.getTag() == "instance_light")
{
const std::string &url = child.getParameter("url").getString();
LightInstance inst(idToNode.at(url.substr(1, url.length() - 1)));
modifyInstance(node, inst);
lightContext.push_back(inst.getLight());
break;
}
}
}
for (auto &node : visualScene.getChildren())
{
std::shared_ptr<ObjectInstance> object = nullptr;
if (node.getTag() != "node")
continue;
for (auto &child : node.getChildren())
{
if (child.getTag().find_first_of("instance") == 0
&& router.find(child.getTag()) != router.cend())
{
object = router.at(child.getTag())(child, lightContext);
break;
}
}
if (!object)
continue;
modifyInstance(node, *object);
object->instanciate(*scene);
}
}
void collada::Collada::modifyInstance(const xmlParser::Node &node, ObjectInstance &instance)
{
const std::map<std::string, std::function<void(const xmlParser::Node &node, ObjectInstance &)>> modifier = {
{"lookat", [](const xmlParser::Node &node, ObjectInstance &instance)
{
instance.lookAt(node);
}
},
{"matrix", [](const xmlParser::Node &node, ObjectInstance &instance)
{
instance.matrix(node);
}
},
{"rotate", [](const xmlParser::Node &node, ObjectInstance &instance)
{
instance.rotate(node);
}
},
{"scale", [](const xmlParser::Node &node, ObjectInstance &instance)
{
instance.scale(node);
}
},
{"skew", [](const xmlParser::Node &node, ObjectInstance &instance)
{
instance.skew(node);
}
},
{"translate", [](const xmlParser::Node &node, ObjectInstance &instance)
{
instance.translate(node);
}
},
};
for (auto &child : node.getChildren())
{
if (modifier.find(child.getTag()) != modifier.cend())
modifier.at(child.getTag())(child, instance);
}
}
const std::map<std::string, const xmlParser::Node &> &collada::Collada::getIdToNode() const
{
return (idToNode);
} | true |
598b0bfcb4671aa2ea327e139bd5d6b360c23706 | C++ | i74n/COSMOSTARS | /COSMOSTARS/Map.cpp | UTF-8 | 228 | 2.515625 | 3 | [] | no_license | #include "Map.h"
Map::Map(){
makeTexture("images/cosmos.png", 1);
displace = 0;
}
Status Map::update(float time){
displace += time*1000;
if (displace >= 960)
displace = 0;
setPosition(-displace, 0);
return stay;
}
| true |
ad2287e19170ebb8748bb838d3731837f64c507a | C++ | HeliosInteractive/ofxHeliosLibs | /src/mediaBanks/VideoBank.cpp | UTF-8 | 3,806 | 2.84375 | 3 | [] | no_license | #include "VideoBank.h"
void VideoBank::setup ( float _x , float _y , float videoDelay , bool _bLoop )
{
x = _x ;
y = _y ;
bLoop = _bLoop ;
videoDelayTimer.setup( videoDelay ) ;
ofAddListener( videoDelayTimer.TIMER_COMPLETE , this , &VideoBank::videoDelayTimerComplete ) ;
}
void VideoBank::videoDelayTimerComplete( int &args )
{
if ( bLoop == true )
playRandomVideo( ) ;
}
void VideoBank::loadFolder( string folderPath , float _volume )
{
x = 0 ;
y = 0 ;
volume = _volume ;
ofDirectory dir ;
dir.allowExt( "mov" ) ;
dir.allowExt( "mp4" ) ;
dir = ofDirectory( folderPath ) ;
dir.listDir( ) ;
if ( dir.size() < 1 )
{
ofLogError( "VideoBank::loadFolder" ) << folderPath << " could not be loaded ! " << endl ;
}
else
{
for ( int i = 0 ; i < dir.size() ; i++ )
{
addVideo( dir.getPath( i ) , volume ) ;
}
}
}
void VideoBank::addVideo( string videoPath , float _volume )
{
int index = videos.size() ;
videos.push_back ( new ofVideoPlayer() ) ;
bool bLoaded = videos[ index ]->loadMovie( videoPath ) ;
ofLogNotice( " VideoBank::addVideo " ) << videoPath << " RESULT : " << bLoaded << endl ;
videos[ index ]->setVolume( _volume ) ;
videos[ index ]->setLoopState( OF_LOOP_NONE ) ;
}
void VideoBank::update( )
{
if ( currentVideo >= 0 )
{
videos[ currentVideo ]->update( ) ;
if ( videos[ currentVideo ]->getIsMovieDone() == true && videoDelayTimer.bIsRunning == false )
{
videos[ currentVideo ]->firstFrame() ;
videos[ currentVideo ]->update() ;
videos[ currentVideo ]->stop() ;
//cout << " STARTING TIMER @" << ofGetElapsedTimeMillis() << " when delay is " << videoDelayTimer.delayMillis << endl ;
videoDelayTimer.start( false , true ) ;
}
}
videoDelayTimer.update( ) ;
}
void VideoBank::draw( )
{
ofPushMatrix( ) ;
// ofTranslate( x , y , 0 ) ;
if ( currentVideo >= 0 )
{
//cout << "drawing ! !" << currentVideo << endl ;
videos[ currentVideo ]->draw( 0 ,0 ) ;
}
ofPopMatrix( ) ;
}
void VideoBank::playRandomVideo( )
{
if ( videos.size() == 0 )
{
ofLogError( "VideoBank::playRandomVideo()" ) << " is empty ! Not loading any sounds" << endl ;
return ;
}
if ( currentVideo > 0 )
{
if ( videos[ currentVideo ]->isPlaying() == true )
{
ofLogError( " CURRENT VIDEO IS PLAYING. ABORT" ) ;
return ;
}
}
//We wouldn't want to play the same random sound 2x in a row
int randomIndex = lastRandomIndex ;
if ( videos.size() > 1 )
{
while ( randomIndex == lastRandomIndex )
{
randomIndex = ofWrap( (int)floor( ofRandom( 0 , videos.size() ) ) , 0 , videos.size() ) ;
}
}
currentVideo = randomIndex ;
lastRandomIndex = randomIndex ;
ofLogVerbose( "VideoBank::playRandomVideo" ) << " random index was : " << randomIndex << " of : " << (videos.size()-1) << endl ;
//videos[ currentVideo ]->setVolume( volume ) ;
//videos[ currentVideo ]->firstFrame() ;
videos[ currentVideo ]->play() ;
}
void VideoBank::playVideoAt( int index )
{
currentVideo = index ;
lastRandomIndex = index ;
//videos[ currentVideo ]->setVolume( volume ) ;
videos[ currentVideo ]->firstFrame() ;
videos[ currentVideo ]->play() ;
}
void VideoBank::stop ( )
{
for ( int i = 0 ; i < videos.size() ; i++ )
{
videos[ i ]->stop( );
}
currentVideo = -1 ;
videoDelayTimer.stop() ;
}
void VideoBank::reset( )
{
for ( int i = 0 ; i < videos.size() ; i++ )
{
// This seems like overkill but it will prevent the white texture showing up at the beginning
// and is overall better for seamlessness
videos[ i ]->stop( );
videos[ i ]->firstFrame() ;
/*setFrame( 0 ) ;
videos[ i ]->play( ) ;
videos[ i ]->update( ) ;
videos[ i ]->stop( ) ; */
}
videoDelayTimer.stop() ;
currentVideo = -1 ;
} | true |
0d0f0bead5b961448a17d3d1d317233cf0657e7a | C++ | zhangergaici/cnpl | /VM/VM.cpp | UTF-8 | 31,903 | 2.71875 | 3 | [] | no_license | #include "VM.h"
#include <locale>
#include <codecvt>
#include <cassert>
#include <cstring>
namespace VM
{
Engine::Engine() :
mConstants(),
mInstructionCount(0),
mInstructions(nullptr),
mIP(nullptr),
mCallParameters(),
mCallStack(),
mCALCStack(),
mDATAStack(nullptr),
mGlobalVariableTable(),
mGC()
{
mCallParameters.reserve(1024);
}
Engine::~Engine()
{
ClearProgram();
}
size_t Engine::AppendHostCall(PFN_HOST_CALL hostCall)
{
auto r = mHostCalls.size();
mHostCalls.push_back(hostCall);
return r;
}
void Engine::LoadProgram(std::fstream& in)
{
const uint8_t file_flag[] = { 0xDA,0xE6,0x9F,0xF3,0xF6,0x98,0x54,0x48,0xB0,0xCB,0x65,0x9E,0xF6,0xB8,0x38,0xCE };
ClearProgram();
uint8_t flagbuffer[16];
ReadBytes(in, flagbuffer, sizeof(flagbuffer));
if (memcmp(flagbuffer, file_flag, sizeof(flagbuffer)) != 0)
throw Exception(10001, "File is not in the correct format.");
uint32_t constantsCount = ReadNumber<uint32_t>(in);
uint32_t instructionCount = ReadNumber<uint32_t>(in);
ReadNumber<uint64_t>(in);
in.seekg(24, std::ios::cur);
for (uint32_t i = 0; i < constantsCount; ++i)
{
mConstants.push_back(ReadValue(in));
}
mInstructions = new Instruction[instructionCount];
Instruction* instruction = mInstructions;
for (uint32_t i = 0; i < instructionCount; ++i)
{
ReadInstruction(in, instruction++);
}
mInstructionCount = instructionCount;
}
InstructionID Engine::ReadIID(std::fstream& in)
{
auto id = ReadNumber<uint16_t>(in);
return static_cast<InstructionID>(id);
}
template<class TNumber>
TNumber Engine::ReadNumber(std::fstream& in)
{
TNumber value;
in.read(reinterpret_cast<char*>(&value), sizeof(value));
return value;
}
uint64_t Engine::Read7BitInt(std::fstream& in)
{
uint64_t mask = 0x7F;
uint64_t temp = 0;
uint64_t result = 0;
size_t bit = 0;
for (size_t i = 0; (!in.eof()) && i < 10; ++i)
{
uint8_t ch = 0;
in.read(reinterpret_cast<char*>(&ch), sizeof(ch));
temp = ch;
result = result | ((temp & mask) << bit);
if ((temp & 0x80) != 0x80)
break;
bit += 7;
}
return result;
}
void Engine::ReadString(std::fstream& in, std::wstring& value)
{
std::wstring_convert<std::codecvt_utf8<wchar_t>> strCnv;
auto len = static_cast<size_t>(Read7BitInt(in));
std::vector<char> utf8;
utf8.resize(len);
in.read(utf8.data(), len);
value = strCnv.from_bytes(utf8.data(), utf8.data() + utf8.size());
}
bool Engine::ReadBoolean(std::fstream& in)
{
uint8_t bytes[2];
ReadBytes(in, bytes, sizeof(bytes));
return bytes[0] == 0x00 && bytes[1] == 0xFF;
}
void Engine::ReadBytes(std::fstream& in, void* buffer, size_t size)
{
in.read(reinterpret_cast<char*>(buffer), size);
}
void Engine::ReadInstruction(std::fstream& in, Instruction* instruction)
{
auto iid = ReadIID(in);
switch (iid)
{
case InstructionID::NOOP:
instruction->func = &Engine::InstructionNOOP;
instruction->tag = 0;
break;
case InstructionID::ADD:
instruction->func = &Engine::InstructionADD;
instruction->tag = 0;
break;
case InstructionID::AND:
instruction->func = &Engine::InstructionAND;
instruction->tag = 0;
break;
case InstructionID::ALLOCDSTK:
instruction->func = &Engine::InstructionALLOCDSTK;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::ARRAYMAKE:
instruction->func = &Engine::InstructionARRAYMAKE;
instruction->tag = 0;
break;
case InstructionID::ARRAYREAD:
instruction->func = &Engine::InstructionARRAYREAD;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::ARRAYWRITE:
instruction->func = &Engine::InstructionARRAYWRITE;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::CALL:
instruction->func = &Engine::InstructionCALL;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::CALLSYS:
instruction->func = &Engine::InstructionCALLSYS;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::DIV:
instruction->func = &Engine::InstructionDIV;
instruction->tag = 0;
break;
case InstructionID::EQ:
instruction->func = &Engine::InstructionEQ;
instruction->tag = 0;
break;
case InstructionID::GT:
instruction->func = &Engine::InstructionGT;
instruction->tag = 0;
break;
case InstructionID::JMP:
instruction->func = &Engine::InstructionJMP;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::JMPC:
instruction->func = &Engine::InstructionJMPC;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::JMPN:
instruction->func = &Engine::InstructionJMPN;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::LT:
instruction->func = &Engine::InstructionLT;
instruction->tag = 0;
break;
case InstructionID::LC:
instruction->func = &Engine::InstructionLC;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::LD:
instruction->func = &Engine::InstructionLD;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
case InstructionID::MOD:
instruction->func = &Engine::InstructionMOD;
instruction->tag = 0;
break;
case InstructionID::MUL:
instruction->func = &Engine::InstructionMUL;
instruction->tag = 0;
break;
case InstructionID::NE:
instruction->func = &Engine::InstructionNE;
instruction->tag = 0;
break;
case InstructionID::NOT:
instruction->func = &Engine::InstructionNOT;
instruction->tag = 0;
break;
case InstructionID::OR:
instruction->func = &Engine::InstructionOR;
instruction->tag = 0;
break;
case InstructionID::POP:
instruction->func = &Engine::InstructionPOP;
instruction->tag = 0;
break;
case InstructionID::PUSH:
instruction->func = &Engine::InstructionPUSH;
instruction->tag = 0;
break;
case InstructionID::RET:
instruction->func = &Engine::InstructionRET;
instruction->tag = 0;
break;
case InstructionID::SUB:
instruction->func = &Engine::InstructionSUB;
instruction->tag = 0;
break;
case InstructionID::SD:
instruction->func = &Engine::InstructionSD;
instruction->tag = static_cast<size_t>(Read7BitInt(in));
break;
default:
throw Exception(10003, "Unrecognized instruction.");
}
}
Value* Engine::ReadValue(std::fstream& in)
{
Value* result = nullptr;
uint8_t type[2];
ReadBytes(in, type, sizeof(type));
if (type[1] == 0)
{
switch (static_cast<Value::Type>(type[0]))
{
case Value::Integer:
result = mGC.RawMemory().NewValue(static_cast<int64_t>(Read7BitInt(in)));
break;
case Value::Real:
result = mGC.RawMemory().NewValue(ReadNumber<double>(in));
break;
case Value::String:
{
std::wstring s;
ReadString(in, s);
result = mGC.RawMemory().NewValue(s);
}
break;
case Value::Boolean:
result = mGC.RawMemory().BooleanValue(ReadBoolean(in));
break;
case Value::Array:
{
size_t rx = static_cast<size_t>(Read7BitInt(in));
size_t cx = static_cast<size_t>(Read7BitInt(in));
auto arr = mGC.RawMemory().NewValue(rx, cx, nullptr);
try
{
for (size_t r = 0; r < rx; ++r)
{
for (size_t c = 0; c < cx; ++c)
{
arr->SetValue(r, c, ReadValue(in));
}
}
result = arr;
}
catch (const Exception&)
{
mGC.RawMemory().FreeValue(arr);
throw;
}
}
break;
default:
throw Exception(10002, "Data type is not supported.");
break;
}
}
else
{
throw Exception(10002, "Data type is not supported.");
}
return result;
}
void Engine::ClearProgram(void)
{
for (auto v : mConstants)
{
mGC.RawMemory().FreeValue(v);
}
mConstants.clear();
if (mInstructions != nullptr)
delete[] mInstructions;
mInstructions = nullptr;
mInstructionCount = 0;
mIP = 0;
for (auto n : mCallStack)
{
n.datastack->clear();
delete n.datastack;
}
mCallStack.clear();
mCALCStack.clear();
mDATAStack = nullptr;
mCallParameters.clear();
mGlobalVariableTable.clear();
mGC.Clean();
}
int Engine::Run(void)
{
mIP = mInstructions;
const Instruction* end = mInstructions + mInstructionCount;
CallNode cn =
{
end,
nullptr
};
mCallStack.push_back(cn);
mGC.Start();
while (mIP < end)
{
(this->*(mIP->func))(mIP->tag);
++mIP;
mGC.CheckMemoryGC(this);
}
return static_cast<int>(CALCStackPop()->AsReal());
}
void Engine::SetGlobalVariable(const std::wstring& name, Value* value)
{
mGlobalVariableTable[name] = value;
}
Value* Engine::GetGlobalVariable(const std::wstring& name)
{
auto it = mGlobalVariableTable.find(name);
if (it == mGlobalVariableTable.end())
return mGC.NewBooleanValue(false);
return it->second;
}
void Engine::DATAStackAlloc(size_t size)
{
mDATAStack = new std::vector<Value*>();
mDATAStack->reserve(size);
for (size_t i = 0; i < size; ++i)
{
mDATAStack->push_back(mGC.NewBooleanValue(false));
}
}
Value* Engine::DATAStackGet(size_t index)
{
return mDATAStack->at(index);
}
void Engine::DATAStackPut(size_t index, Value* value)
{
mDATAStack->at(index) = value;
}
Value* Engine::CALCStackPop(void)
{
auto r = mCALCStack.back();
mCALCStack.pop_back();
return r;
}
void Engine::CALCStackPush(Value* value)
{
mCALCStack.push_back(value);
}
void Engine::InstructionAND(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
auto r = mGC.NewBooleanValue(a->AsBoolean() && b->AsBoolean());
CALCStackPush(r);
}
void Engine::InstructionADD(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
Value* r;
if (a->GetType() == b->GetType())
{
switch (a->GetType())
{
case Value::String:
{
std::wstring sa;
std::wstring sb;
a->AsString(sa);
b->AsString(sb);
r = mGC.NewStringValue(sa.append(sb));
}
break;
case Value::Integer:
{
r = mGC.NewIntegerValue(a->AsInteger() + b->AsInteger());
}
break;
default:
{
r = mGC.NewRealValue(a->AsReal() + b->AsReal());
}
break;
}
}
else
{
if (a->Is(Value::String) || b->Is(Value::String))
{
std::wstring sa;
std::wstring sb;
a->AsString(sa);
b->AsString(sb);
r = mGC.NewStringValue(sa.append(sb));
}
else
{
r = mGC.NewRealValue(a->AsReal() + b->AsReal());
}
}
CALCStackPush(r);
}
void Engine::InstructionALLOCDSTK(size_t tag)
{
DATAStackAlloc(tag);
}
void Engine::InstructionARRAYMAKE(size_t tag)
{
auto vf = CALCStackPop();
auto vc = CALCStackPop();
auto vr = CALCStackPop();
auto r = mGC.NewArrayValue(
static_cast<size_t>(vr->AsReal()),
static_cast<size_t>(vc->AsReal()),
vf);
CALCStackPush(r);
}
void Engine::InstructionARRAYREAD(size_t tag)
{
auto vc = CALCStackPop();
auto vr = CALCStackPop();
auto d = DATAStackGet(tag);
auto r = d->GetValue(
static_cast<size_t>(vr->AsReal()),
static_cast<size_t>(vc->AsReal())
);
CALCStackPush(r);
}
void Engine::InstructionARRAYWRITE(size_t tag)
{
auto vv = CALCStackPop();
auto vc = CALCStackPop();
auto vr = CALCStackPop();
auto d = DATAStackGet(tag);
d->SetValue(
static_cast<size_t>(vr->AsReal()),
static_cast<size_t>(vc->AsReal()),
vv
);
}
void Engine::InstructionCALL(size_t tag)
{
CallNode cn =
{
mIP,
mDATAStack
};
mCallStack.push_back(cn);
mIP = mInstructions + (tag - 1);
}
void Engine::InstructionCALLSYS(size_t tag)
{
auto pc = (tag & 0xFFC00000) >> 22;
auto idx = tag & 0x003FFFFF;
if (idx >= mHostCalls.size())
throw Exception(20001, "Function index out of bounds.");
auto sc = mHostCalls[idx];
mCallParameters.clear();
for (size_t i = 0; i < pc; ++i)
mCallParameters.push_back(CALCStackPop());
auto r = sc(this, pc, mCallParameters.data());
mCallParameters.clear();
CALCStackPush(r);
}
void Engine::InstructionDIV(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
Value* r;
if (a->GetType() == b->GetType() && a->GetType() == Value::Integer)
{
r = mGC.NewIntegerValue(a->AsInteger() / b->AsInteger());
}
else
{
r = mGC.NewRealValue(a->AsReal() / b->AsReal());
}
CALCStackPush(r);
}
void Engine::InstructionEQ(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
auto r = mGC.NewBooleanValue(a->VEquals(b));
CALCStackPush(r);
}
void Engine::InstructionGT(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
Value* r;
if (a->Is(Value::String) || b->Is(Value::String))
{
std::wstring sa;
std::wstring sb;
a->AsString(sa);
b->AsString(sb);
r = mGC.NewBooleanValue(sa.size() > sb.size());
}
else
{
r = mGC.NewBooleanValue(a->AsReal() > b->AsReal());
}
CALCStackPush(r);
}
void Engine::InstructionJMP(size_t tag)
{
mIP = mInstructions + (tag - 1);
}
void Engine::InstructionJMPC(size_t tag)
{
auto a = CALCStackPop();
if (a->AsBoolean())
mIP = mInstructions + (tag - 1);
}
void Engine::InstructionJMPN(size_t tag)
{
auto a = CALCStackPop();
if (!a->AsBoolean())
mIP = mInstructions + (tag - 1);
}
void Engine::InstructionLT(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
Value* r;
if (a->Is(Value::String) || b->Is(Value::String))
{
std::wstring sa;
std::wstring sb;
a->AsString(sa);
b->AsString(sb);
r = mGC.NewBooleanValue(sa.size() < sb.size());
}
else
{
r = mGC.NewBooleanValue(a->AsReal() < b->AsReal());
}
CALCStackPush(r);
}
void Engine::InstructionLC(size_t tag)
{
auto r = mConstants[tag];
CALCStackPush(r);
}
void Engine::InstructionLD(size_t tag)
{
auto r = DATAStackGet(tag);
CALCStackPush(r);
}
void Engine::InstructionMOD(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
Value* r = mGC.NewIntegerValue(a->AsInteger() % b->AsInteger());
CALCStackPush(r);
}
void Engine::InstructionMUL(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
Value* r;
if (a->GetType() == b->GetType() && a->GetType() == Value::Integer)
{
r = mGC.NewIntegerValue(a->AsInteger() * b->AsInteger());
}
else
{
r = mGC.NewRealValue(a->AsReal() * b->AsReal());
}
CALCStackPush(r);
}
void Engine::InstructionNE(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
auto r = mGC.NewBooleanValue(!a->VEquals(b));
CALCStackPush(r);
}
void Engine::InstructionNOT(size_t tag)
{
auto a = CALCStackPop();
auto r = mGC.NewBooleanValue(!a->AsBoolean());
CALCStackPush(r);
}
void Engine::InstructionOR(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
auto r = mGC.NewBooleanValue(
a->AsBoolean() ||
b->AsBoolean());
CALCStackPush(r);
}
void Engine::InstructionPOP(size_t tag)
{
CALCStackPop();
}
void Engine::InstructionPUSH(size_t tag)
{
CALCStackPush(mGC.NewBooleanValue(false));
}
void Engine::InstructionRET(size_t tag)
{
const CallNode& cn = mCallStack.back();
delete mDATAStack;
mIP = cn.ip;
mDATAStack = cn.datastack;
mCallStack.pop_back();
}
static std::wstring& trim_end(std::wstring &s)
{
if (s.empty())
return s;
s.erase(s.find_last_not_of(L" ") + 1);
return s;
}
static std::wstring& trim_start(std::wstring &s)
{
if (s.empty())
return s;
s.erase(0, s.find_first_not_of(L" "));
return s;
}
void Engine::InstructionSUB(size_t tag)
{
auto b = CALCStackPop();
auto a = CALCStackPop();
Value* r;
if (a->GetType() == b->GetType())
{
switch (a->GetType())
{
case Value::String:
{
std::wstring sa;
std::wstring sb;
a->AsString(sa);
b->AsString(sb);
r = mGC.NewStringValue(sa.append(sb));
}
break;
case Value::Integer:
{
r = mGC.NewIntegerValue(a->AsInteger() - b->AsInteger());
}
break;
default:
{
r = mGC.NewRealValue(a->AsReal() - b->AsReal());
}
break;
}
}
else
{
if (a->Is(Value::String) || b->Is(Value::String))
{
std::wstring sa;
std::wstring sb;
a->AsString(sa);
b->AsString(sb);
r = mGC.NewStringValue(trim_end(sa).append(trim_start(sb)));
}
else
{
r = mGC.NewRealValue(a->AsReal() - b->AsReal());
}
}
CALCStackPush(r);
}
void Engine::InstructionSD(size_t tag)
{
auto v = CALCStackPop();
DATAStackPut(tag, v);
}
bool Value::VEquals(const Value* value)const
{
if (value == this)
return true;
if (value->Is(GetType()))
{
switch (GetType())
{
case Integer: return mValue.iValue == value->mValue.iValue;
case Real: return mValue.dValue == value->mValue.dValue;
case String:
{
if (mValue.sValue.length == value->mValue.sValue.length)
{
return memcmp(
mValue.sValue.str,
value->mValue.sValue.str,
value->mValue.sValue.length * sizeof(wchar_t))==0;
}
return false;
}
case Boolean: return mValue.bValue == value->mValue.bValue;
case Array:
return false;
default:
break;
}
}
else
{
if (Is(String) || value->Is(String))
{
std::wstring s0;
std::wstring s1;
AsString(s0);
value->AsString(s1);
return s0 == s1;
}
else if (Is(Real))
{
return AsReal() == value->AsReal();
}
else if (Is(Boolean))
{
return AsBoolean() == value->AsBoolean();
}
}
return false;
}
bool Value::AsBoolean(void) const
{
switch (GetType())
{
case Integer: return mValue.iValue != int64_t(0);
case Real: return mValue.dValue != double(0);
case String: return (mValue.sValue.length != 0);
case Boolean: return mValue.bValue;
case Array: return true;
default:
break;
}
return false;
}
void Value::AsString(std::wstring& s) const
{
switch (GetType())
{
case Integer: s = std::to_wstring(mValue.iValue); break;
case Real:
{
s = std::to_wstring(mValue.dValue);
s.erase(s.find_last_not_of(L'0') + 1, std::string::npos);
s.erase(s.find_last_not_of(L'.') + 1, std::string::npos);
}
break;
case String: s.assign(mValue.sValue.str, mValue.sValue.length); break;
case Boolean: s = mValue.bValue ? L"True" : L"False"; break;
case Array: s = L"[" + std::to_wstring(mValue.aValue.row) + L"," + std::to_wstring(mValue.aValue.col) + L"]"; break;
default:
s = std::wstring();
break;
}
}
int64_t Value::AsInteger(void) const
{
switch (GetType())
{
case Integer: return mValue.iValue;
case Real: return static_cast<int64_t>(mValue.dValue);
case String: return std::wcstoll(mValue.sValue.str, nullptr, 10);
case Boolean: return mValue.bValue ? int64_t(1) : int64_t(0);
case Array: return int64_t(0);
default:
break;
}
return int64_t(0);
}
double Value::AsReal(void) const
{
switch (GetType())
{
case Integer: return static_cast<double>(mValue.iValue);
case Real: return mValue.dValue;
case String: return std::wcstod(mValue.sValue.str, nullptr);
case Boolean: return mValue.bValue ? double(1) : double(0);
case Array: return double(0);
default:
break;
}
return double(0);
}
size_t Value::GetRow(void)const
{
if (Is(Array))
return mValue.aValue.row;
return 0;
}
size_t Value::GetCol(void)const
{
if (Is(Array))
return mValue.aValue.col;
return 0;
}
Value* Value::GetValue(size_t r, size_t c) const
{
if (Is(Array))
{
if (r < mValue.aValue.row && c < mValue.aValue.col)
{
auto result = mValue.aValue.data[r*mValue.aValue.col + c];
if (result != nullptr)
return result;
}
}
return MemoryAllocator::BooleanValue(false);
}
void Value::SetValue(size_t r, size_t c, Value* v)
{
if (Is(Array))
{
if (r < mValue.aValue.row && c < mValue.aValue.col)
{
if (IsGCMarked())
v->GCMarkSet();
mValue.aValue.data[r*mValue.aValue.col + c] = v;
}
}
}
MemoryGC::MemoryGC(void) :
mMemoryPool(),
mGenerationFullFlags{ false,false,false,false },
mGeneration()
{
}
MemoryGC::~MemoryGC(void)
{
Clean();
}
void MemoryGC::GCMarkRoots(Engine* engine)
{
for (auto v : engine->mCallParameters)
{
v->GCMarkSet();
}
for (auto& n : engine->mCallStack)
{
if (n.datastack != nullptr)
{
for (auto v : *(n.datastack))
{
v->GCMarkSet();
}
}
}
for (auto v : engine->mCALCStack)
{
v->GCMarkSet();
}
if (engine->mDATAStack != nullptr)
{
for (auto v : *(engine->mDATAStack))
{
v->GCMarkSet();
}
}
for (auto v : engine->mGlobalVariableTable)
{
v.second->GCMarkSet();
}
}
void MemoryGC::GCGenerationMarkClear(int gen)
{
auto g = mGeneration + gen;
for (auto v : *g)
{
v->GCMarkClear();
}
}
void MemoryGC::GCGenerationClean(int gen)
{
if (gen >= 3)
{
mGenerationFullFlags[gen] = false;
auto generation = mGeneration + gen;
auto i = generation->begin();
while (i != generation->end())
{
if ((*i)->IsGCMarkFreed())
{
RawMemory().FreeValue(*i);
i = generation->erase(i);
}
else
{
++i;
}
}
}
else
{
mGenerationFullFlags[gen] = false;
auto generation = mGeneration + gen;
auto nextGeneration = mGeneration + (++gen);
while (generation->size() > 0)
{
auto v = generation->back();
if (v->IsGCMarkFreed())
{
RawMemory().FreeValue(v);
}
else
{
nextGeneration->push_back(v);
}
generation->pop_back();
}
if (nextGeneration->size() > nextGeneration->capacity() - 32)
{
mGenerationFullFlags[gen] = true;
}
}
}
void MemoryGC::GC(Engine* engine)
{
if (mGenerationFullFlags[3])
{
GCGenerationMarkClear(3);
GCMarkRoots(engine);
GCGenerationClean(3);
}
if (mGenerationFullFlags[2])
{
GCGenerationMarkClear(2);
GCMarkRoots(engine);
GCGenerationClean(2);
}
if (mGenerationFullFlags[1])
{
GCGenerationMarkClear(1);
GCMarkRoots(engine);
GCGenerationClean(1);
}
GCGenerationMarkClear(0);
GCMarkRoots(engine);
GCGenerationClean(0);
}
void MemoryGC::CheckMemoryGC(Engine* engine)
{
if (mGeneration->size() > mGeneration->capacity() - 32)
{
GC(engine);
}
}
Value* MemoryGC::NewIntegerValue(int32_t value)
{
return NewIntegerValue(static_cast<int64_t>(value));
}
Value* MemoryGC::NewIntegerValue(uint32_t value)
{
return NewIntegerValue(static_cast<int64_t>(value));
}
Value* MemoryGC::NewIntegerValue(int64_t value)
{
auto v = RawMemory().NewValue(value);
mGeneration->push_back(v);
return v;
}
Value* MemoryGC::NewIntegerValue(uint64_t value)
{
return NewIntegerValue(static_cast<int64_t>(value));
}
Value* MemoryGC::NewRealValue(float value)
{
return NewRealValue(static_cast<double>(value));
}
Value* MemoryGC::NewRealValue(double value)
{
auto v = RawMemory().NewValue(value);
mGeneration->push_back(v);
return v;
}
Value* MemoryGC::NewStringValue(const std::wstring& value)
{
auto v = RawMemory().NewValue(value);
mGeneration->push_back(v);
return v;
}
Value* MemoryGC::NewStringValue(const wchar_t* value, size_t length)
{
auto v = RawMemory().NewValue(value, length);
mGeneration->push_back(v);
return v;
}
Value* MemoryGC::NewBooleanValue(bool value)
{
return RawMemory().BooleanValue(value);
}
Value* MemoryGC::NewArrayValue(size_t row, size_t col, Value* fill)
{
auto v = RawMemory().NewValue(row, col, fill);
mGeneration->push_back(v);
return v;
}
void MemoryGC::Start(void)
{
Clean();
mGenerationFullFlags[0] = false;
mGenerationFullFlags[1] = false;
mGenerationFullFlags[2] = false;
mGenerationFullFlags[3] = false;
mGeneration->reserve(1024 * 16);
(mGeneration + 1)->reserve(1024 * 64);
(mGeneration + 2)->reserve(1024 * 128);
(mGeneration + 3)->reserve(1024 * 512);
}
void MemoryGC::Clean(void)
{
for (auto& g : mGeneration)
{
for (auto v : g)
{
RawMemory().FreeValue(v);
}
g.clear();
g.reserve(0);
}
mMemoryPool.Clean();
}
MemoryAllocator::MemoryAllocator() :
mMB0Count(0),
mMB1Count(0),
mMB2Count(0),
mMB3Count(0),
mMB4Count(0),
mMB5Count(0),
mMB0Head(nullptr),
mMB1Head(nullptr),
mMB2Head(nullptr),
mMB3Head(nullptr),
mMB4Head(nullptr),
mMB5Head(nullptr)
{
}
MemoryAllocator::~MemoryAllocator()
{
Clean();
}
Value* MemoryAllocator::mTrue = MemoryAllocator::InitBoolean(true);
Value* MemoryAllocator::mFalse = MemoryAllocator::InitBoolean(false);
Value* MemoryAllocator::InitBoolean(bool value)
{
auto pValue = reinterpret_cast<Value*>(new uint8_t[sizeof(Value)]);
pValue->mValue.bValue = value;
pValue->mType = Value::Boolean;
pValue->mFlag = 0;
return pValue;
}
Value* MemoryAllocator::BooleanValue(bool value)
{
return value ? mTrue : mFalse;
}
void* MemoryAllocator::AllocMemory(size_t size)
{
if (size <= sizeof(MemoryBlock0::data))
{
MemoryBlock0* mb = mMB0Head;
if (mb == nullptr)
mb = new MemoryBlock0();
else
{
mMB0Head = mMB0Head->next;
--mMB0Count;
}
mb->next = nullptr;
return mb->data;
}
else if (size <= sizeof(MemoryBlock1::data))
{
MemoryBlock1* mb = mMB1Head;
if (mb == nullptr)
mb = new MemoryBlock1();
else
{
mMB1Head = mMB1Head->next;
--mMB1Count;
}
mb->next = nullptr;
return mb->data;
}
else if (size <= sizeof(MemoryBlock2::data))
{
MemoryBlock2* mb = mMB2Head;
if (mb == nullptr)
mb = new MemoryBlock2();
else
{
mMB2Head = mMB2Head->next;
--mMB2Count;
}
mb->next = nullptr;
return mb->data;
}
else if (size <= sizeof(MemoryBlock3::data))
{
MemoryBlock3* mb = mMB3Head;
if (mb == nullptr)
mb = new MemoryBlock3();
else
{
mMB3Head = mMB3Head->next;
--mMB3Count;
}
mb->next = nullptr;
return mb->data;
}
else if (size <= sizeof(MemoryBlock4::data))
{
MemoryBlock4* mb = mMB4Head;
if (mb == nullptr)
mb = new MemoryBlock4();
else
{
mMB4Head = mMB4Head->next;
--mMB4Count;
}
mb->next = nullptr;
return mb->data;
}
else if (size <= sizeof(MemoryBlock5::data))
{
MemoryBlock5* mb = mMB5Head;
if (mb == nullptr)
mb = new MemoryBlock5();
else
{
mMB5Head = mMB5Head->next;
--mMB5Count;
}
mb->next = nullptr;
return mb->data;
}
return new uint8_t[size];
}
void MemoryAllocator::FreeMemory(void* p, size_t size)
{
if (size <= sizeof(MemoryBlock0::data))
{
MemoryBlock0* mb = reinterpret_cast<MemoryBlock0*>(reinterpret_cast<uint8_t*>(p) - sizeof(MemoryBlock0*));
if (mMB0Count < 32 * 1024)
{
mb->next = mMB0Head;
mMB0Head = mb;
++mMB0Count;
}
else
{
delete mb;
}
}
else if (size <= sizeof(MemoryBlock1::data))
{
MemoryBlock1* mb = reinterpret_cast<MemoryBlock1*>(reinterpret_cast<uint8_t*>(p) - sizeof(MemoryBlock1*));
if (mMB1Count < 16 * 1024)
{
mb->next = mMB1Head;
mMB1Head = mb;
++mMB1Count;
}
else
{
delete mb;
}
}
else if (size <= sizeof(MemoryBlock2::data))
{
MemoryBlock2* mb = reinterpret_cast<MemoryBlock2*>(reinterpret_cast<uint8_t*>(p) - sizeof(MemoryBlock2*));
if (mMB2Count < 8 * 1024)
{
mb->next = mMB2Head;
mMB2Head = mb;
++mMB2Count;
}
else
{
delete mb;
}
}
else if (size <= sizeof(MemoryBlock3::data))
{
MemoryBlock3* mb = reinterpret_cast<MemoryBlock3*>(reinterpret_cast<uint8_t*>(p) - sizeof(MemoryBlock3*));
if (mMB3Count < 2 * 1024)
{
mb->next = mMB3Head;
mMB3Head = mb;
++mMB3Count;
}
else
{
delete mb;
}
}
else if (size <= sizeof(MemoryBlock4::data))
{
MemoryBlock4* mb = reinterpret_cast<MemoryBlock4*>(reinterpret_cast<uint8_t*>(p) - sizeof(MemoryBlock4*));
if (mMB4Count < 1024)
{
mb->next = mMB4Head;
mMB4Head = mb;
++mMB4Count;
}
else
{
delete mb;
}
}
else if (size <= sizeof(MemoryBlock5::data))
{
MemoryBlock5* mb = reinterpret_cast<MemoryBlock5*>(reinterpret_cast<uint8_t*>(p) - sizeof(MemoryBlock5*));
if (mMB5Count < 512)
{
mb->next = mMB5Head;
mMB5Head = mb;
++mMB5Count;
}
else
{
delete mb;
}
}
else
{
delete[](reinterpret_cast<uint8_t*>(p));
}
}
void MemoryAllocator::Clean(void)
{
{
MemoryBlock0* mb = mMB0Head;
while (mb != nullptr)
{
auto t = mb->next;
delete mb;
mb = t;
--mMB0Count;
}
mMB0Head = nullptr;
mMB0Count = 0;
}
{
MemoryBlock1* mb = mMB1Head;
while (mb != nullptr)
{
auto t = mb->next;
delete mb;
mb = t;
}
mMB1Head = nullptr;
mMB1Count = 0;
}
{
MemoryBlock2* mb = mMB2Head;
while (mb != nullptr)
{
auto t = mb->next;
delete mb;
mb = t;
}
mMB2Head = nullptr;
mMB2Count = 0;
}
{
MemoryBlock3* mb = mMB3Head;
while (mb != nullptr)
{
auto t = mb->next;
delete mb;
mb = t;
}
mMB3Head = nullptr;
mMB3Count = 0;
}
{
MemoryBlock4* mb = mMB4Head;
while (mb != nullptr)
{
auto t = mb->next;
delete mb;
mb = t;
}
mMB4Head = nullptr;
mMB4Count = 0;
}
{
MemoryBlock5* mb = mMB5Head;
while (mb != nullptr)
{
auto t = mb->next;
delete mb;
mb = t;
}
mMB5Head = nullptr;
mMB5Count = 0;
}
}
Value* MemoryAllocator::NewValue(int64_t value)
{
auto pValue = reinterpret_cast<Value*>(AllocMemory(sizeof(MemoryBlock0::data)));
pValue->mValue.iValue = value;
pValue->mType = Value::Integer;
pValue->mFlag = 0;
return pValue;
}
Value* MemoryAllocator::NewValue(double value)
{
auto pValue = reinterpret_cast<Value*>(AllocMemory(sizeof(MemoryBlock0::data)));
pValue->mValue.dValue = value;
pValue->mType = Value::Real;
pValue->mFlag = 0;
return pValue;
}
Value* MemoryAllocator::NewValue(const std::wstring& value)
{
return NewValue(value.data(), value.length());
}
Value* MemoryAllocator::NewValue(const wchar_t* value, size_t length)
{
if (value != nullptr && length == static_cast<size_t>(-1))
length = std::wcslen(value);
size_t baselen = ((size_t) &((Value *)0)->mValue.sValue.str);
size_t datalen = (length + 1) * sizeof(wchar_t);
auto pValue = reinterpret_cast<Value*>(AllocMemory(baselen + datalen));
pValue->mValue.sValue.length = length;
if (value != nullptr && length > 0)
memcpy(pValue->mValue.sValue.str, value, length * sizeof(wchar_t));
pValue->mType = Value::String;
pValue->mFlag = 0;
return pValue;
}
Value* MemoryAllocator::NewValue(size_t row, size_t col, Value* fill)
{
size_t count = row * col;
const size_t baselen = ((size_t) &((Value *)0)->mValue.aValue.data);
size_t datalen = (count) * sizeof(Value*);
auto pValue = reinterpret_cast<Value*>(AllocMemory(baselen + datalen));
pValue->mValue.aValue.row = row;
pValue->mValue.aValue.col = col;
if (fill == nullptr)
{
fill = BooleanValue(false);
}
for (size_t i = 0; i < count; ++i)
{
pValue->mValue.aValue.data[i] = fill;
}
pValue->mType = Value::Array;
pValue->mFlag = 0;
return pValue;
}
void MemoryAllocator::FreeValue(Value* value)
{
if (value == mTrue || value == mFalse)
return;
size_t size=0;
switch (value->GetType())
{
case Value::Integer:
case Value::Real:
case Value::Boolean:
size = sizeof(MemoryBlock0::data);
break;
case Value::String:
{
const size_t baselen = ((size_t) &((Value *)0)->mValue.sValue.str);
size_t datalen = (value->mValue.sValue.length + 1) * sizeof(wchar_t);
size = baselen + datalen;
}
break;
case Value::Array:
{
size_t count = value->mValue.aValue.row * value->mValue.aValue.col;
size_t baselen = ((size_t) &((Value *)0)->mValue.aValue.data);
size_t datalen = (count) * sizeof(Value*);
size = baselen + datalen;
}
break;
default:
assert(true);
break;
}
FreeMemory(value, size);
}
}
| true |
fe5caa103c263af2659708a432152db45748bb1f | C++ | SahilMadan/ProgrammingWindows | /02_WideCharacterFormatting/Main.cpp | UTF-8 | 1,590 | 3.03125 | 3 | [] | no_license | #include <Windows.h>
#include <stdio.h>
#include <tchar.h>
// Use cdecl instead of stdcall.
int CDECL MessageBoxPrintf(const TCHAR* szCaption, const TCHAR* szFormat, ...) {
// TCHAR points to WCHAR if unicode is defined; else CHAR.
TCHAR szBuffer[1024];
va_list pArgList;
// The va_start macro (defined in STDARG.H) is usually equivalent to:
// pArgList = (char *)&szFormat + sizeof(szFormat);
// i.e. points to argument just above szFormat on the stack.
va_start(pArgList, szFormat);
// Generic macro (defined to normal or wide functions) to write formatted
// output using a pointer to a list of arguments.
_vsntprintf_s(szBuffer, sizeof(szBuffer) / sizeof(TCHAR), szFormat, pArgList);
// Macro just zeroes out pArgList.
va_end(pArgList);
// Generic definition adds L## in front of wide strings.
TEXT("Hello");
// Generic definition points to MessageBoxA for ASCII and MessageBoxW for
// Wide.
return MessageBox(NULL, szBuffer, szCaption, MB_OK);
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine,
int iCmdShow) {
int cxScreen;
int cyScreen;
// Function retrieves the specified system metric or configuration setting (in
// pixels).
cxScreen = GetSystemMetrics(SM_CXSCREEN);
cyScreen = GetSystemMetrics(SM_CYSCREEN);
// Note that TEXT macro is a generic definition adds L## in front of wide
// strings.
MessageBoxPrintf(TEXT("ScreenSize"),
TEXT("The screen size is %i pixels wide by %i pixels high."),
cxScreen, cyScreen);
return 0;
}
| true |
d83a648134056d1a926692d1553591a4906878a1 | C++ | university-studies/ipk-isa-networking | /isa-project/mtu_ipv6.h | UTF-8 | 1,142 | 2.796875 | 3 | [] | no_license | /**
* File: mtu_ipv6.h
* Author: Pavol Loffay, xloffa00@stud.fit.vutbr.cz
* Date: 25.9.2012
* Description: modul spracujuci checksum protolu TCP, UDP
*/
#ifndef MTU_IPV6_H
#define MTU_IPV6_H
#include <string>
#include <netinet/ip6.h>
#include <netinet/icmp6.h>
#include <netdb.h>
/*
* @brief Trieda spracujuca MTU path discovery pre IPv6
*/
class mtu_ipv6
{
public:
mtu_ipv6(struct sockaddr_in6 h_sockaddr, int max_mtu) throw (const char *);
~mtu_ipv6();
int calculate() throw (const char *);
private:
int max_mtu;
int min_mtu;
struct icmp6_hdr * icmp_send;
struct icmp6_hdr * icmp_recv;
//struct ip6_hdr * ip_recv;
int id;
int sequence;
int packet_len;
protoent * protocol;
int socket_id;
char * packet_send;
char * packet_recv;
struct sockaddr_in6 send_sockaddr_in6;
struct sockaddr_in6 recv_sockaddr_in6;
timeval time;
void make_icmp();
enum
{
MIN_MTU = 150, //1280 rfc2460
MAX_MTU = 1500,
MAX_TTL = 30,
TIMEOUT_S = 3
};
};
#endif // MTU_IPV6_H
| true |
8cff8faa1889eb614844d6df96a6885c567b6d55 | C++ | NazarovDevelopment/OOP | /OOP2014/quadtree/tree.cpp | UTF-8 | 795 | 2.859375 | 3 | [] | no_license | #include "quadtree.h"
void CoolQuadTree::separate()
{
CoolPoint center(border.lower_right.x / 2 - border.upper_left.x / 2, border.lower_right.y / 2 - border.upper_left.y / 2);
CoolRectangle q1(border.upper_left, center);
CoolRectangle q2(CoolPoint(border.upper_left.x, center.y), CoolPoint(center.x,border.lower_right.y));
CoolRectangle q3(CoolPoint(center.x,border.upper_left.y),CoolPoint(border.lower_right.x,center.y));
CoolRectangle q4(center,border.lower_right);
upper_left = new CoolQuadTree(q1);
lower_left= new CoolQuadTree(q2);
upper_right = new CoolQuadTree(q3);
lower_right = new CoolQuadTree(q4);
}
bool CoolQuadTree::insert(const CoolPoint& point)
{
if (!border.point_in(point))
{
return false;
}
if (points.size < NUMBER_POINT){
points.push_back(point);
}
}
| true |
11c8c6c0c3873f3c3c060bdeb99982b5ac3fffe8 | C++ | 2302053453/MyStudy | /C++Study/C++Study/STL/Chapter4_Linked List/Chapter4_02.cpp | UHC | 1,395 | 3.734375 | 4 | [] | no_license | //#include<iostream>
//#include<list>
//using namespace std;
///*
// 2016-03-03
// STL LIST insert
//*/
//
//void main()
//{
// list<int> list1;
// list1.push_back(20);
// list1.push_back(30);
//
// cout << " Ʈ 1" << endl;
// // ù° ġ Ѵ.
// list<int>::iterator iterInserrtPos = list1.begin();
// list1.insert(iterInserrtPos, 100);
//
// list<int>::iterator iterEnd = list1.end();
// for (list<int>::iterator iterPos = list1.begin(); iterPos != iterEnd; ++iterPos)
// cout << "list 1 : " << *iterPos << endl;
//
// cout << " Ʈ 2" << endl;
// // ° ġ 200 2 Ѵ.
// iterInserrtPos = list1.begin();
// iterInserrtPos++;
// list1.insert(iterInserrtPos, 2, 200);
//
// iterEnd = list1.end();
// for (list<int>::iterator iterPos = list1.begin(); iterPos != iterEnd; ++iterPos)
// cout << "list 1 : " << *iterPos << endl;
//
// cout << " Ʈ 3" << endl;
//
// list<int> list2;
// list2.push_back(1000);
// list2.push_back(2000);
// list2.push_back(3000);
//
// // ° ġ list2 ѵ.
// iterInserrtPos = list1.begin();
//
// list1.insert(++iterInserrtPos, list2.begin(), list2.end());
//
// iterEnd = list1.end();
// for (list<int>::iterator iterPos = list1.begin(); iterPos != iterEnd; ++iterPos)
// cout << "list 1 : " << *iterPos << endl;
//
//
//} | true |