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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
d1f449f09b3d7f5bebe4befc7bf0ec970f7418d8 | C++ | yingziyu-llt/OI | /c/北大题库/1.7/17 字符串判等 hash.cpp | UTF-8 | 862 | 2.921875 | 3 | [] | no_license | #include<algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
#define bigprime 233317
unsigned long long hashf(char s[])
{
int i = 0,len = strlen(s);
unsigned long long ans = 0;
while(i < len)
{
ans = ans * bigprime + (s[i] - 'A' + 1);
i++;
}
return ans;
}
int main()
{
char str1[10000],str2[10000];
char c = '\0';
int i = 0;
do
{
c = getchar();
if(c == ' ')
continue;
if(c >= 'a' && c <= 'z')
str1[i] = c - 'a' + 'A';
if(c >= 'A' && c <= 'Z')
str1[i] = c;
i++;
}while(c != '\n');
i = 0;
do
{
c = getchar();
if(c == ' ')
continue;
if(c >= 'a' && c <= 'z')
str2[i] = c - 'a' + 'A';
if(c >= 'A' && c <= 'Z')
str2[i] = c;
i++;
}while(c != '\n');
i = 0;
if(hashf(str1) == hashf(str2))
printf("YES");
else
printf("NO");
return 0;
}
| true |
251412f91123e6a460775dd4b6b0831b37e13be0 | C++ | V-vp/SPOJ | /last_digit_revisited.cpp | UTF-8 | 668 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define ll unsigned long long int
using namespace std;
ll ModularExponentiaion(ll x,ll n,int p=10)
{
ll ans=1,temp=x%p;
while(n)
{
if(n&1)
{
ans=(ans*temp)%p;
}
n>>=1;
temp=(temp*temp)%p;
}
return ans;
}
int main() {
ll b,t;
string a;cin>>t;
while(t--)
{
cin>>a>>b;
ll c = a[a.length()-1]-'0';
cout<<ModularExponentiaion(c,b)<<"\n";
}
return 0;
}
| true |
f69d8f72dd5a0e9b7c277c36676034454458ffd9 | C++ | ping28198/Thailand_projects | /Projects/ImgprcOCRInstance3.0_0518/ImgprcOCRInstance/Timer.cpp | GB18030 | 2,705 | 2.5625 | 3 | [] | no_license | // Timer.cpp
/*************************
20130827: Timer::Start()һڴݵ̵߳Ķָ
Timer::Start()->Timer::Start(DWORD_PTR dwUser)
************************/
#include "stdafx.h"
#include "Timer.h"
//
Timer::Timer(long p, int id, BOOL r, LPTIMECALLBACK fservice)
{
Init();
lPeriod=p;
wUserID=id;
bRepeat=r;
lpFunction=fservice;
}
Timer::Timer(long p, int id, BOOL r)
{
Init();
lPeriod=p;
wUserID=id;
bRepeat=r;
}
Timer::Timer(long p, int id)
{
Init();
lPeriod=p;
wUserID=id;
}
Timer::Timer(long p)
{
Init();
lPeriod=p;
}
void Timer::Init()
{
hTimer = NULL;
hTimerQueue = CreateTimerQueue();
WORD wRet;
lpFunction=NULL;
bRepeat=TIME_PERIODIC;
wUserID=0;
uSystemID=0;
wLastError=0;
bRunning=0;
lPeriod=1000;
wRet=GetResolution();
if(wRet==0)
{
//AfxMessageBox("");
}
}
WORD Timer::GetUserID()
{
return wUserID;
}
UINT Timer::GetSystemID()
{
return uSystemID;
}
BOOL Timer::IsRepeat()
{
return bRepeat;
}
BOOL Timer::IsRunning()
{
return bRunning;
}
int Timer::AddTimerListener(LPTIMECALLBACK fservice)
{
lpFunction=fservice;
return (int)0;
}
long Timer::GetPeroid()
{
return (long)lPeriod;
}
//
UINT Timer::Start(DWORD_PTR dwUser)
{
// DWORD dwUser=0xffffffff; //tx20130827
MMRESULT ret;
UINT uTimerType;
if (NULL == hTimerQueue)
{
return 0;
}
if(bRunning==1)
{
wLastError=5;
return 0;
}
if(lpFunction==NULL)
{
wLastError=6;
return 0;
}
if (hTimer != NULL)
{
return 0;
}
int due_time = 1000;// ʱȴʱ֮ʼ
if (!CreateTimerQueueTimer(&hTimer, hTimerQueue,
(WAITORTIMERCALLBACK)lpFunction, (PVOID)dwUser, due_time, lPeriod, 0))
{
wLastError = 2;
return 0;
}
//ret=timeBeginPeriod(wTimerRes);
//if(bRepeat==1) uTimerType=TIME_PERIODIC;
//else uTimerType=TIME_ONESHOT;
//
//uSystemID=timeSetEvent(lPeriod,wTimerRes,(LPTIMECALLBACK)lpFunction,
// (DWORD_PTR )dwUser,uTimerType);
//
//if(uSystemID==NULL)
//{
// wLastError=2;
// return 0;
//}
bRunning=1;
return 1;
}
int Timer::Stop()
{
if(hTimer!=NULL)
{
if (!DeleteTimerQueueTimer(hTimerQueue, hTimer, NULL))
{
return 0;
}
bRunning=0;
hTimer = NULL;
return (int)1;
}
else
{
return 0;
}
}
WORD Timer::GetResolution()
{
//TIMECAPS tc;
//if(timeGetDevCaps(&tc,sizeof(TIMECAPS))!=TIMERR_NOERROR)
//{
// //Record Error
// wLastError=1;
// return 0;
//}
// wTimerRes=min(max(tc.wPeriodMin,1),tc.wPeriodMax);
return 0;
}
Timer::~Timer()
{
Stop();
if (hTimerQueue != NULL)
DeleteTimerQueue(hTimerQueue);
}
WORD Timer::GetLastError()
{
WORD wLast=wLastError;
wLastError=0;
return wLast;
}
| true |
f47b0c7a963c79be7bb8fa298981080cd4248b5d | C++ | orangezeit/leetcode | /CPP/0501-0600/0519-Random-Flip-Matrix.cpp | UTF-8 | 599 | 2.96875 | 3 | [
"BSD-3-Clause"
] | permissive | class Solution {
private:
unordered_set<int> record;
int n, c;
public:
Solution(int n_rows, int n_cols) {
c = n_cols;
n = n_rows * n_cols;
}
vector<int> flip() {
int k;
do {
k = rand() % n;
} while (record.find(k) != record.end());
record.insert(k);
return {k / c, k % c};
}
void reset() {
record.clear();
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(n_rows, n_cols);
* vector<int> param_1 = obj.flip();
* obj.reset();
*/
| true |
70fce16a26fad58eec9b1740ce301b08b8578460 | C++ | ArutoriaWhite/Competitive-programming | /zojc296.cpp | UTF-8 | 206 | 2.640625 | 3 | [] | no_license | #include<iostream>
using namespace std;
int n, m, k;
int f( int n, int k)
{
if (k==0) return 0;
return (f(n-1,k-1)+m%n)%n;
}
int main() {
cin >> n >> m >> k;
cout << f( n, k)+1 << '\n';
return 0;
}
| true |
8e0e3aad530620a308fe6995b5fcb0a9e718d901 | C++ | cratas/dfs-bfs-graph-iterator | /ALG_project-master/Graph_iteratpr/BFSIterator.cpp | UTF-8 | 1,618 | 2.875 | 3 | [] | no_license | #include "BFSIterator.h"
BFSIterator::BFSIterator(Graph* graph)
{
this->graph = graph;
this->verticesCount = graph->GetVerticesCount();
this->minValue = graph->GetMinValue();
isDone = new bool[verticesCount];
for(int i = 0; i < verticesCount; i++)
{
isDone[i] = false;
}
}
BFSIterator::~BFSIterator()
{
delete[] isDone;
}
void BFSIterator::Reset()
{
queue.push_back(minValue);
isDone[minValue] = true;
currentKey = queue.front();
}
void BFSIterator::Next()
{
currentKey = queue.front();
list<int>::iterator i;
if(!queue.empty())
{
queue.pop_front();
for (i = graph->GetVertices()[currentKey].begin(); i != graph->GetVertices()[currentKey].end(); ++i)
{
if(!isDone[*i])
{
isDone[*i] = true;
queue.push_back(*i);
}
}
}
if(queue.empty())
{
for(int i = 0; i < verticesCount; i++)
{
if(isDone[i] == false)
{
queue.push_back(i);
isDone[i] = true;
break;
}
}
}
}
bool BFSIterator::IsEnd()
{
bool allTrue = true;
for(int i = 0; i < verticesCount; i++)
{
if(isDone[i] == true )
{
allTrue = true;
}
else
{
allTrue = false;
break;
}
}
if(allTrue && queue.empty())
{
return true;
}
else
{
return false;
}
}
int BFSIterator::CurrentKey()
{
return currentKey;
} | true |
ece17ece24bc645bb67dc45f1de82b186ed4ff51 | C++ | KB9/BraccioVisualAttention | /environment_analysis/FocusMapper.hpp | UTF-8 | 491 | 2.875 | 3 | [] | no_license | #ifndef _GAUSSIANMAP_H_
#define _GAUSSIANMAP_H_
#include <unordered_map>
#include <vector>
struct FocusPoint
{
float x, y, z;
float radius;
FocusPoint(float x, float y, float z, float radius) :
x(x), y(y), z(z), radius(radius) {}
};
class FocusMapper
{
public:
FocusMapper();
void add(float x, float y, float z, float radius = 10.0f);
void clear();
float calculate(float x, float y, float z);
void decay(float rate = 1.0f);
private:
std::vector<FocusPoint> points;
};
#endif | true |
b10777f7ee1947427a20789dee14ba91ae3afb5f | C++ | arron-tij/ArabicCompetitiveProgramming | /18-Programming-4kids/11_homework_1_answer_TODO_1-7.cpp | UTF-8 | 559 | 3.078125 | 3 | [] | no_license | // By Basel Bairkdar: https://www.facebook.com/baselbairkdar
#include<iostream>
using namespace std;
string input,str;
int main()
{
cin >> input >> str;
bool is_prefix=1; /** we will say that it's prefix at the beginning **/
int n=str.size();
/**
check if str is eqaul
to the first n letter of input
**/
for (int i=0;i<n;i++)
{
if (input[i]!=str[i])
{
is_prefix=0;
break;
}
}
if (is_prefix)
cout << "YES\n";
else
cout << "NO\n";
return 0;
}
| true |
22dc1fbf3bc3af014f6e3d05e940f80225cf2e5a | C++ | WickedShell/zubax_chibios | /zubax_chibios/platform/stm32/flash_writer.hpp | UTF-8 | 2,850 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
* Copyright (c) 2015 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
#pragma once
#include <ch.hpp>
#include <hal.h>
#include <cassert>
#include <cstring>
#include <cstdint>
#if !defined(FLASH_SR_WRPRTERR)
# define FLASH_SR_WRPRTERR FLASH_SR_WRPERR
#endif
namespace os
{
namespace stm32
{
/**
* The code below assumes that HSI oscillator is up and running,
* otherwise the Flash controller (FPEC) may misbehave.
* Any FPEC issues will be detected at run time during write/erase verification.
*/
class FlashWriter
{
static void waitReady()
{
do
{
assert(!(FLASH->SR & FLASH_SR_PGERR));
assert(!(FLASH->SR & FLASH_SR_WRPRTERR));
}
while (FLASH->SR & FLASH_SR_BSY);
FLASH->SR |= FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR; // Reset flags
}
struct Prologuer
{
Prologuer()
{
chSysLock();
waitReady();
if (FLASH->CR & FLASH_CR_LOCK)
{
FLASH->KEYR = 0x45670123UL;
FLASH->KEYR = 0xCDEF89ABUL;
}
FLASH->SR |= FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR; // Reset flags
FLASH->CR = 0;
}
~Prologuer()
{
FLASH->CR = FLASH_CR_LOCK; // Reset the FPEC configuration and lock
chSysUnlock();
}
};
public:
/**
* Source and destination must be aligned at two bytes.
*/
bool write(const void* const where,
const void* const what,
const unsigned how_much)
{
if (((reinterpret_cast<std::size_t>(where)) % 2 != 0) ||
((reinterpret_cast<std::size_t>(what)) % 2 != 0) ||
(where == nullptr) || (what == nullptr))
{
assert(false);
return false;
}
const unsigned num_halfwords = (how_much + 1U) / 2U;
volatile std::uint16_t* flashptr16 = static_cast<std::uint16_t*>(const_cast<void*>(where));
const std::uint16_t* ramptr16 = static_cast<const std::uint16_t*>(what);
Prologuer prologuer;
FLASH->CR = FLASH_CR_PG;
for (unsigned i = 0; i < num_halfwords; i++)
{
*flashptr16++ = *ramptr16++;
waitReady();
}
waitReady();
FLASH->CR = 0;
return std::memcmp(what, where, how_much) == 0;
}
/**
* Erases the page located at the specified address.
*/
bool erasePageAt(const unsigned page_address)
{
Prologuer prologuer;
FLASH->CR = FLASH_CR_PER;
FLASH->AR = page_address;
FLASH->CR = FLASH_CR_PER | FLASH_CR_STRT;
waitReady();
FLASH->CR = 0;
return true;
}
};
}
}
| true |
2d1cde20233205c61880bda8a59e8b27caa2062c | C++ | VittalT/USACO-Solutions | /Silver/US Open 2019, Silver/US Open 2019, Silver P1/US Open 2019, Silver P1/main.cpp | UTF-8 | 2,060 | 2.65625 | 3 | [] | no_license | /*
ID: vittalt
TASK: leftout
LANG: C++
*/
/* LANG can be C++11 or C++14 for those more recent releases */
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <list>
#include <map>
#include <deque>
#include <queue>
using namespace std;
int N;
string cows[1000];
void changeRow(int row){
for(int i = 0; i < N; i++){
if(cows[row][i] == 'R')
cows[row][i] = 'L';
else if(cows[row][i] == 'L')
cows[row][i] = 'R';
}
}
void changeCol(int col){
for(int i = 0; i < N; i++){
if(cows[i][col] == 'R')
cows[i][col] = 'L';
else if(cows[i][col] == 'L')
cows[i][col] = 'R';
}
}
int main()
{
ofstream fout ("leftout.out");
ifstream fin ("leftout.in");
fin >> N;
for(int i = 0; i < N; i++)
fin >> cows[i];
if(N == 2) {
fout << 1 << " " << 1;
return 0;
}
for(int i = 0; i < N; i++){
if(cows[0][i] == 'L')
changeCol(i);
}
vector< pair<int,int> > posBad;
for(int i = 1; i < N; i++){
if(cows[i][0] == 'L' && cows[i][1] == 'L' && cows[i][2] == 'L')
changeRow(i);
for(int j = 0; j < 3; j++)
if(cows[i][j] == 'R' && cows[i][(j+1)%3] == 'L' && cows[i][(j+2)%3] == 'L')
changeRow(i);
for(int j = 0; j < N; j++){
if(cows[i][j] != 'R'){
posBad.push_back(make_pair(i, j));
}
}
}
if(posBad.size() == 0){
fout << -1;
}
else if(posBad.size() == 1){
fout << posBad[0].first + 1 << " " << posBad[0].second + 1;
} else {
int badCol = posBad[0].second;
for(auto p : posBad){
if(p.second != badCol){
fout << -1;
return 0;
}
}
if(posBad.size() != N-1) {
fout << -1;
return 0;
}
fout << 1 << " " << badCol + 1;
}
return 0;
}
| true |
b1ab6bcdb82738101e3b17b0e82647bb86e59896 | C++ | JianHangChen/LeetCode | /Lint130. Heapify.cpp | UTF-8 | 2,927 | 3.40625 | 3 | [] | no_license |
//!!! sol2, my shiftdown, O(n), O(1), iteratively
class Solution {
public:
void heapify(vector<int> &A) {
int n = A.size();
for(int i = n/2 - 1; i >= 0; i--){
shiftDown(i, A);
}
}
void shiftDown(int i, vector<int>& A){
int n = A.size();
while(i < n){
int left = i * 2 + 1, right = i * 2 + 2;
if(left >= n) return;
if(right == n || right < n && A[left] < A[right]){
if(A[i] <= A[left]) return;
swap(A[i], A[left]);
i = left;
}
else{
if(A[i] <= A[right]) return;
swap(A[i], A[right]);
i = right;
}
}
}
};
//!!sol1, my shift down, O(n), O(logn)
class Solution {
public:
void heapify(vector<int> &A) {
int n = A.size();
for(int i = n - 1; i >= 0; i--){
shiftDown(i, A);
}
}
void shiftDown(int i, vector<int>& A){
int n = A.size();
int left = i * 2 + 1, right = i * 2 + 2;
if(left >= n) return;
if(right == n || right < n && A[left] < A[right]){
if(A[i] <= A[left]) return;
swap(A[i], A[left]);
shiftDown(left, A);
}
else{
if(A[i] <= A[right]) return;
swap(A[i], A[right]);
shiftDown(right, A);
}
}
};
class Solution:
"""
@param: A: Given an integer array
@return: nothing
"""
# sol2: siftdown O(n)
def heapify(self, A):
length = len(A)
father = (length-2)//2
for i in range(father,-1,-1):
self.siftdown(A,i)
def siftdown(self, A, i):
smallest = i
while i >= 0:
leftchild = 2 * i + 1
rightchild = 2 * i + 2
if leftchild < len(A) and A[smallest] > A[leftchild]:
smallest = leftchild
if rightchild < len(A) and A[smallest] > A[rightchild]:
smallest = rightchild
if smallest == i:
break
else:
temp = A[smallest]
A[smallest] = A[i]
A[i] = temp
i = smallest
# # sol1: siftup O(nlogn)
# def heapify(self, A):
# # write your code here
# length = len(A)
# for index in range(length):
# self.siftup(A,index)
# # print(A)
# def siftup(self,A, index):
# child = index
# father = (child-1)//2
# while child != 0 and A[father] > A[child]:
# temp = A[father]
# A[father] = A[child]
# A[child] = temp
# child = father
# father = (child-1)//2
# # sol3: just fun
# def heapify(self, A):
# import heapq
# heapq.heapify(A)
| true |
078317a9737e89850f25b6d8211ad75fee5933c3 | C++ | a-nikolaev/a-nikolaev.github.io | /cpp-spring-2015/lab/13/demo2/main.cpp | UTF-8 | 330 | 2.859375 | 3 | [] | no_license | #include <iostream>
#include "intset.h"
using namespace std;
int main () {
IntSet s;
s.empty();
s.add(10);
s.add(20);
s.add(15);
s.add(5);
s.add(5);
s.add(15);
s.add(7);
s.remove(15);
for(int i = 0; i < 25; i++) {
cout << i << " ";
if (s.member(i)) cout << "yes";
cout << endl;
}
}
| true |
bde0615b48157dbe5a3db32b17f5a23d0304f9c4 | C++ | akstraw/PokerAI | /game/deck.cpp | UTF-8 | 785 | 3.484375 | 3 | [] | no_license | #include "deck.h"
#include "card.h"
#include <chrono>
#include <algorithm>
#include <random>
//create standard 52 card deck
void Deck::fill()
{
for (int suit = CLUB; suit <= SPADE; suit++)
{
for(int rank = TWO; rank <= ACE; rank++)
{
cards.push_back( Card{ static_cast<Rank>(rank), static_cast<Suit>(suit)});
}
}
}
//empties and refills deck
void Deck::reset()
{
cards.clear();
fill();
shuffle();
}
//draw card at top of deck
Card Deck::draw()
{
Card rv = cards.back();
cards.pop_back();
return rv;
}
//shuffle cards in deck
void Deck::shuffle()
{
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle ( cards.begin(), cards.end(),std::default_random_engine(seed));
}
| true |
7bec6e1e01fd16793e416c00d431f725473022f7 | C++ | ssyzkhan/mixCode | /cppex/res/mainDijkstra.cpp | UTF-8 | 354 | 2.515625 | 3 | [] | no_license | #include"dijkstra.h"
int main(int argc, char** argv){
pair<double*, int*> r;
double a[]={0,10,0,5,0,
0,0,1,2,0,
0,0,0,0,4,
0,3,9,0,2,
7,0,6,0,0
},*d;
int *pi,i,s=0,n=5;
r=dijkstra(a,n,s);
d=r.first;
pi=r.second;
for(i=0;i<n;i++){
if(i!=s){
printPath(pi,s,i);
cout<<endl<<d[i]<<endl;
}
}
delete []d;
delete []pi;
}
| true |
3c73d9c86828d69039914805878409653e7c74ff | C++ | derrick0714/web_search_engine | /indexing/src/generating/analysis_ctrl.cpp | UTF-8 | 8,283 | 2.6875 | 3 | [] | no_license | #include "analysis_ctrl.h"
#include <sys/stat.h>
#include <iostream>
using namespace std;
#define INDEX_CHUNK 409600 //50KB
#define DATA_CHUNK 20971520 //2.5MB
analysis_ctrl::analysis_ctrl()
{
_dataset_path = "./dataset/";
_file_start = 0;
_file_end = 82;
_file_now = _file_start;
_doc_id = 1;
_word_id =1;
buffer = new StreamBuffer(12*1024*1024/4);
mkdir("intermediate", S_IRWXU|S_IRGRP|S_IXGRP);
buffer->setfilename("intermediate/posting");
buffer->setpostingsize(12);
buffer->set_sort(true);
_time_now = time(0);
}
analysis_ctrl::~analysis_ctrl()
{
if(buffer != NULL)
delete buffer;
}
bool analysis_ctrl::start()
{
//set display call back
//display::get_instance()->set_input_call_back(this);
do_it();
return true;
}
void analysis_ctrl::stop()
{
//stop display
display::get_instance()->stop();
}
void analysis_ctrl::input_event( char* key )
{
if( strcmp(key,"quit") == 0)
stop();
else
cout<<"press 'quit' to exit"<<endl;
}
// core algorithm
void analysis_ctrl::do_it()
{
DataSet data_set(_dataset_path);
while( get_next_file_name(data_set) )
{
//cout<<"loop"<<endl;
int already_len = 0;
//get index data from file
char* index_data = gzip::uncompress_from_file(data_set._index.c_str(), INDEX_CHUNK, already_len);
if( index_data == NULL || already_len == 0)
{
cout<<"read index data error: "<<data_set._index.c_str()<<endl;
continue;
}
//cout<<"doc_id:"<<doc_id<<endl;
//save raw data into orgnized data structer
original_index index;
if( !save_index(index_data, already_len, index, data_set._file_num) )
{
cout<<"save index data error"<<endl;
continue;
}
free(index_data);
//get html data from file
char* html_data = gzip::uncompress_from_file(data_set._data.c_str(), DATA_CHUNK, already_len);
if( html_data == NULL || already_len == 0)
{
cout<<"read html data error :"<<data_set._data.c_str()<<endl;
continue;
}
//parse word from html data
if(!parse_data(html_data, already_len, index))
{
cout<<"parse index data error"<<endl;
continue;
}
free(html_data);
//break;
// cout<<"loop"<<endl;
}
//save word map;
//_word_map
StreamBuffer buffer1(50*1024*1024);
buffer1.setfilename("intermediate/word_map.data");
buffer1>>_word_map;
buffer1.savetofile();
//save docs map;
StreamBuffer buffer2(50*1024*1024);
buffer2.setfilename("intermediate/docs_map.data");
buffer2>>_docs_map;
buffer2.savetofile();
//
buffer->savetofile();
cout<<"[finish] time consumed: "<<time(0)-_time_now<<"s"<<endl;
}
//read file name
bool analysis_ctrl::get_next_file_name(DataSet& data_set)
{
if( _file_now <= _file_end)
{
data_set.set_num(_file_now);
_file_now++;
return true;
}
return false;
}
bool analysis_ctrl::parse()
{
}
bool analysis_ctrl::parse_data(char* html_data, int len, original_index& index)
{
original_index_content index_val;
int doc_id =0;
index.set_to_start();
// get one doc offset and id from index list
while(index.get_next(doc_id ,index_val))
{
cout<<"parsing: "<<doc_id<<" => "<<index_val.url<<":"<<index_val.offset<<":"<<index_val.len<<endl;
char *pool;
pool = (char*)malloc(2*index_val.len+1);
//parsing page
char* page = new char[index_val.len+1];
memcpy(page, html_data+index_val.offset, index_val.len);
page[index_val.len]='\0';
int ret = parser((char*)index_val.url.c_str(), page , pool, 2*index_val.len+1);
delete page;
// cout<<pool<<endl;
//return false;
//output words and their contexts
if (ret > 0)
{
//printf("%s", pool);
//save raw data into rgnized data structer
if( !save_data( doc_id , pool, 2*index_val.len+1) )
{
cout<<"save index data error"<<endl;
// continue;
}
}
free(pool);
}
return true;
}
bool analysis_ctrl::save_index(char* index_data , int len ,original_index& index, int file_num)
{
if( index_data == NULL || len == 0)
return false;
cout<<len<<" "<<strlen(index_data)<<endl;
int pos = 0;
int offset_val =0;
while(pos < len)
{
string url ="", ip="", port="",state="",len="",unknow1="",unknow2="";
//get host
if(
!get_one_word(index_data,pos,url) ||
!get_one_word(index_data,pos,unknow1) ||
!get_one_word(index_data,pos,unknow2) ||
!get_one_word(index_data,pos,len) ||
!get_one_word(index_data,pos,ip) ||
!get_one_word(index_data,pos,port)||
!get_one_word(index_data,pos,state)
)
break; // if read finish, break
int len_val = atoi(len.c_str());
// if exit doc id, return it else create new id
int doc_id = get_doc_id(url.c_str(),file_num, offset_val,len_val);
index.put(doc_id,(url).c_str(), offset_val,len_val);
offset_val+=len_val;
}
return true;
}
bool analysis_ctrl::save_data(int doc_id, char* save_data, int len)
{
int pos = 0;
int offset_val =0;
int percent = _file_end - _file_start == 0? 100 : ( (float)(_file_now -1 - _file_start) / (float)(_file_end - _file_start) )*100;
int pos_count = 0;
// cout<<"[-"<<percent<<"\%-][doc:"<<doc_id<<"]"<<endl;
while(pos < len )
{
string word="";
string context="";
string positon="";
if(
!get_one_word(save_data , pos, word) ||
!get_one_word(save_data , pos, positon) ||
!get_one_word(save_data , pos, context)
)
break;
//cout<<"["<<pos<<"]"<<"word=>"<<word<<" pos=>"<<positon<<" context=>"<<context<<endl ;
//continue;
//if it is word
TempLexicon new_lexicon;
new_lexicon.word_id = get_word_id(word);
new_lexicon.doc_id = doc_id;
new_lexicon.startpos =pos_count++;//atoi(positon.c_str()); //atoi(positon.c_str());
//cout<<"[-"<<percent<<"\%-][doc:"<<new_lexicon.doc_id<<"] : "<<word<<"=>word_id:"<<new_lexicon.word_id<<" position:"<<new_lexicon.startpos<<endl;
//save temp Lexicon
(*buffer)>>new_lexicon;
}
//cout<<pos<<"--------------------------------"<<endl<<endl<<endl<<endl<<endl;
return true;
}
//get on word from file
bool analysis_ctrl::get_one_word(char* source ,int& pos,string& str)
{
char get_num = 0;
while( source[pos] != '\0')
{
if(source[pos] == '\r' || source[pos]=='\n' || source[pos] == ' ')
{
if( get_num == 0)
{
pos++;
continue;
}
else
{
pos++;
return true;
}
}
else
{
str+=source[pos++];
get_num++;
//cout<<str.c_str()<<endl;
}
}
//if( source[pos] == '\0')
return false;
}
int analysis_ctrl::get_doc_id(string doc_name,int file_num, int offset, int len)
{
if(_checker.find(doc_name) != _checker.end())
{
cout<<"doc repeat:"<<doc_name<<"=>"<<_checker[doc_name]<<endl;
return _checker[doc_name];
}
_checker[doc_name]= _doc_id;
_docs_map[_doc_id].doc_name = doc_name;
_docs_map[_doc_id].file_id = file_num;
_docs_map[_doc_id].offset = offset;
_docs_map[_doc_id].len = len;
return _doc_id++;
}
int analysis_ctrl::get_word_id(string word)
{
if(_word_map.isHas(word))
{
// cout<<"word repeat:"<<word<<"=>"<<_word_map[word]<<endl;
return _word_map[word];
}
_word_map[word] = _word_id;
return _word_id++;
}
| true |
04dd6c9888f8ab79f83723c095d771b11f7bea00 | C++ | InsightSoftwareConsortium/ITK | /Modules/Core/Common/include/itkAnnulusOperator.hxx | UTF-8 | 5,407 | 2.609375 | 3 | [
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
... | permissive | /*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkAnnulusOperator_hxx
#define itkAnnulusOperator_hxx
#include "itkMath.h"
#include "itkSphereSpatialFunction.h"
#include <memory> // For make_unique.
namespace itk
{
/** Create the operator */
template <typename TPixel, unsigned int TDimension, typename TAllocator>
void
AnnulusOperator<TPixel, TDimension, TAllocator>::CreateOperator()
{
CoefficientVector coefficients;
coefficients = this->GenerateCoefficients();
this->Fill(coefficients);
}
/** This function fills the coefficients into the corresponding
* neighborhood. */
template <typename TPixel, unsigned int TDimension, typename TAllocator>
void
AnnulusOperator<TPixel, TDimension, TAllocator>::Fill(const CoefficientVector & coeff)
{
const std::slice temp_slice(0, coeff.size(), 1);
typename Self::SliceIteratorType data(this, temp_slice);
auto it = coeff.begin();
// Copy the coefficients into the neighborhood
for (data = data.Begin(); data < data.End(); ++data, ++it)
{
*data = *it;
}
}
template <typename TPixel, unsigned int TDimension, typename TAllocator>
auto
AnnulusOperator<TPixel, TDimension, TAllocator>::GenerateCoefficients() -> CoefficientVector
{
// Determine the initial kernel values...
double interiorV, annulusV, exteriorV;
if (m_Normalize)
{
double bright = (m_BrightCenter ? 1.0 : -1.0);
// Initial values for a normalized kernel
interiorV = bright;
annulusV = -1.0 * bright;
exteriorV = 0.0;
}
else
{
// values for a specified kernel
interiorV = m_InteriorValue;
annulusV = m_AnnulusValue;
exteriorV = m_ExteriorValue;
}
// Compute the size of the kernel in pixels
SizeType r;
unsigned int i, j;
double outerRadius = m_InnerRadius + m_Thickness;
for (i = 0; i < TDimension; ++i)
{
r[i] = Math::Ceil<SizeValueType>(outerRadius / m_Spacing[i]);
}
this->SetRadius(r);
// Use a couple of sphere spatial functions...
using SphereType = SphereSpatialFunction<TDimension>;
auto innerS = SphereType::New();
auto outerS = SphereType::New();
innerS->SetRadius(m_InnerRadius);
outerS->SetRadius(m_InnerRadius + m_Thickness);
// Walk the neighborhood (this) and evaluate the sphere spatial
// functions
double sumNotExterior = 0.0;
double sumNotExteriorSq = 0.0;
unsigned int countNotExterior = 0;
const typename SizeType::SizeValueType w = this->Size();
const auto outside = std::make_unique<bool[]>(w);
CoefficientVector coeffP(w);
OffsetType offset;
typename SphereType::InputType point;
for (i = 0; i < w; ++i)
{
// get the offset from the center pixel
offset = this->GetOffset(i);
// convert to a position
for (j = 0; j < TDimension; ++j)
{
point[j] = m_Spacing[j] * offset[j];
}
// evaluate the spheres
const bool inInner = innerS->Evaluate(point);
const bool inOuter = outerS->Evaluate(point);
// set the coefficients
if (!inOuter)
{
// outside annulus
coeffP[i] = exteriorV;
outside[i] = true;
}
else if (!inInner)
{
// inside the outer circle but outside the inner circle
coeffP[i] = annulusV;
sumNotExterior += annulusV;
sumNotExteriorSq += (annulusV * annulusV);
++countNotExterior;
outside[i] = false;
}
else
{
// inside inner circle
coeffP[i] = interiorV;
sumNotExterior += interiorV;
sumNotExteriorSq += (interiorV * interiorV);
++countNotExterior;
outside[i] = false;
}
}
// Normalize the kernel if necessary
if (m_Normalize)
{
// Calculate the mean and standard deviation of kernel values NOT
// the exterior
auto num = static_cast<double>(countNotExterior);
double mean = sumNotExterior / num;
double var = (sumNotExteriorSq - (sumNotExterior * sumNotExterior / num)) / (num - 1.0);
double std = std::sqrt(var);
// convert std to a scaling factor k such that
//
// || (coeffP - mean) / k || = 1.0
//
double k = std * std::sqrt(num - 1.0);
// Run through the kernel again, shifting and normalizing the
// elements that are not exterior to the annulus. This forces the
// kernel to have mean zero and norm 1 AND forces the region
// outside the annulus to have no influence.
for (i = 0; i < w; ++i)
{
// normalize the coefficient if it is inside the outer circle
// (exterior to outer circle is already zero)
if (!outside[i])
{
coeffP[i] = (coeffP[i] - mean) / k;
}
}
}
return coeffP;
}
} // namespace itk
#endif
| true |
7499cb0ac09141c50c56c0d5dd0cbe89a81759fa | C++ | pitybea/pmss | /pms/PyramidMatchScore/PMS.h | UTF-8 | 2,982 | 2.53125 | 3 | [] | no_license | #include <vector>
#include <string>
#include <map>
#include <math.h>
using namespace std;
template<class T>
static void prshl(vector<T> p,int n,vector<int>& index)
{
int k,j,i;
T t;
int ii;
k=n/2;
while(k>0)
{
for(j=k;j<=n-1;j++)
{
t=p[j]; ii=index[j]; i=j-k;
while((i>=0)&&(p[i]>t))
{
p[i+k]=p[i]; index[i+k]=index[i]; i=i-k;
}
p[i+k]=t; index[i+k]=ii;
}
k=k/2;
}
};
template <class T,class U>
int bendPsnToApea(vector<vector<T> > &features,vector<U> pts)
{
if (features.size()==pts.size())
{
for (int i=0;i<pts.size();i++)
{
features[i].push_back(pts[i].x);
features[i].push_back(pts[i].y);
}
}
return 0;
}
template<class T>
int NormalVec(vector<vector<T> >& dataset)
{
if (dataset.size()>0)
{
if (dataset[0].size()>0)
{
for (int i=0;i<dataset.size();i++)
{
double temtot(0.0);
for (int j=0;j<temtot;j++)
{
temtot+=dataset[i][j];
}
temtot+=0.0001;
for (int j=0;j<temtot;j++)
{
dataset[i][j]/=temtot;
}
}
}
}
return 0;
}
template<class T>
int TransitMtx(vector<vector<T> > oData,vector<vector<T> >trasM,vector<vector<T> > & tData)
{
tData.resize(oData.size(),vector<T>(trasM[0].size(),0.0));
for (int i=0;i<oData.size();i++)
{
for (int j=0;j<trasM[0].size();j++)
{
for (int k=0;k<trasM.size();k++)
{
tData[i][j]+=oData[i][k]*trasM[k][j];
}
}
}
return 0;
}
template<class T>
int ZeroMnVec(vector<vector<T> >& dataset)
{
if (dataset.size()>0)
{
if (dataset[0].size()>0)
{
for (int i=0;i<dataset.size();i++)
{
double temtol(0.0);
for (int j=0;j<dataset[i].size();j++)
{
temtol+=dataset[i][j];
}
temtol/=dataset[0].size();
for (int j=0;j<dataset[i].size();j++)
{
dataset[i][j]-=temtol;
}
}
}
}
return 0;
}
template <class T>
int MAxInd(vector<T> data)
{
T a;
a=data[0];
int ind=0;
for (int i=0;i<data.size();i++)
{
if (data[i]>a)
{
a=data[i];
ind=i;
}
}
return ind;
}
class PMStruc
{
public:
PMStruc(int i);
int totalLvls;
int dataToPym(vector<vector<double> > data);
int dataToPymAver(vector<vector<double> > data);
double MatchDttoPym(vector<vector<double> > dataset);
double MatchDttoPymAv(vector<vector<double> > dataset);
private:
void valueToInx(pair<double,double> minMax,pair<double,double>& aAndB,int levl);
void dataToPymLvl(vector<vector<double> > datas,int lvel,map<int,map<int,int> >& pymlvl,vector<pair<double,double> > aAndB);
void dataToPymLvl(vector<vector<double> > datas,int lvel,map<int,map<int,int> >& pymlvl,vector<vector<double> > aintvl);
int matchDToOneLv(vector<vector<double> > dataset,int levl,map<int,map<int,int> > pmlv,vector<pair<double,double> > aAndB );
int matchDToOneLv(vector<vector<double> > dataset,int levl,map<int,map<int,int> > pmlv,vector<vector<double> > invs );
vector<map<int,map<int,int> > > pym;
vector<vector<pair<double,double> > > aAbs;
vector<vector<vector<double> > > intvDecs;
};
| true |
c811cba2a28610de5667cc1a148bde2a9cf2a5b2 | C++ | aiekick/engine | /src/modules/voxel/polyvox/Picking.h | UTF-8 | 1,980 | 3.140625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "core/Common.h"
#include "core/Trace.h"
#include "Voxel.h"
#include "Picking.h"
#include "Raycast.h"
namespace voxel {
/**
* @brief A structure containing the information about a picking operation
*/
struct PickResult {
PickResult() {
}
/** Did the picking operation hit anything */
bool didHit = false;
bool validPreviousPosition = false;
/** The location of the solid voxel it hit */
glm::ivec3 hitVoxel;
/** The location of the step before we end the trace - see @a validPreviousLocation */
glm::ivec3 previousPosition;
};
namespace {
/**
* @brief This is just an implementation class for the pickVoxel function
*
* It makes note of the sort of empty voxel you're looking for in the constructor.
*
* Each time the operator() is called:
* * if it's hit a voxel it sets up the result and returns false
* * otherwise it preps the result for the next iteration and returns true
*/
template<typename VolumeType>
class RaycastPickingFunctor {
public:
RaycastPickingFunctor(const Voxel& emptyVoxelExample) :
_emptyVoxelExample(emptyVoxelExample), _result() {
}
bool operator()(typename VolumeType::Sampler& sampler) {
if (sampler.voxel() != _emptyVoxelExample) {
// If we've hit something
_result.didHit = true;
_result.hitVoxel = sampler.position();
return false;
}
if (sampler.currentPositionValid()) {
_result.validPreviousPosition = true;
_result.previousPosition = sampler.position();
}
return true;
}
const Voxel& _emptyVoxelExample;
PickResult _result;
};
}
/** Pick the first solid voxel along a vector */
template<typename VolumeType>
PickResult pickVoxel(const VolumeType* volData, const glm::vec3& v3dStart, const glm::vec3& v3dDirectionAndLength, const Voxel& emptyVoxelExample) {
core_trace_scoped(pickVoxel);
RaycastPickingFunctor<VolumeType> functor(emptyVoxelExample);
raycastWithDirection(volData, v3dStart, v3dDirectionAndLength, functor);
return functor._result;
}
}
| true |
4c71e24a4e5896e178fe2796ab4b1c7df051449d | C++ | praesepe/study | /leetcode/067-Add-Binary/lala.cpp | UTF-8 | 589 | 3.203125 | 3 | [] | no_license | #include <string>
using namespace std;
class Solution {
public:
string addBinary(string a, string b) {
// filling leading zero
if (a.size() > b.size()) {
b = string(a.size() - b.size(), '0') + b;
} else if (b.size() > a.size()) {
a = string(b.size() - a.size(), '0') + a;
}
// added
bool carry = false;
for (int i = a.size(); i >= 0 ; i--) {
char sum = (a[i] == b[i]) ?
(carry ? '1' : '0') :
(carry ? '0' : '1');
carry = (a[i] == '1' && b[i] == '1') || (carry && (b[i] == '1' || a[i] == '1'));
a[i] = sum;
}
return carry ? "1" + a : a;
}
};
| true |
7dc288caf96e2ae6d69e4c1e3bdd54412a7025a5 | C++ | alongoria/mines | /CSCI261_programming_concepts_c++/29_trollBattle/src/battle.cpp | UTF-8 | 561 | 3.46875 | 3 | [] | no_license | #include "battle.h"
#include <iostream>
using namespace std;
void fight(Troll &A, Troll &B) {
cout << A.name << " is fighting " << B.name << "!" << endl;
while (A.health > 0 || B.health > 0) {
if (A.health > 0) {
A.attack(B);
B.health -= A.strength;
}
else {
break;
}
if (B.health > 0) {
B.attack(A);
A.health -= B.strength;
}
else {
break;
}
}
}
void declareWinner(Troll A, Troll B) {
if (A.health > 0) {
cout << A.name << " is the victor!" << endl;
}
else {
cout << B.name << " is the victor!" << endl;
}
}
| true |
ad39fce83f42ec330b695d50cc10a717d1266776 | C++ | jjcomline/laser-arduino | /laser.ino | UTF-8 | 637 | 2.6875 | 3 | [] | no_license | int giallo = 4;
int pulsante = 7;
int transistor = 5;
int stato=0; // All'inizio il sistema è spento.
int val=0; // Memorizza il valore dello stato tra un ciclo e l'altro
int luce;
void setup() {
pinMode(giallo, OUTPUT);
pinMode(transistor, OUTPUT);
pinMode(A0,INPUT);
}
void loop() {
val = digitalRead(pulsante); // Leggo lo stato del segnale (se o cliccato o no)
delay(10);
digitalWrite(transistor, 1);
luce = analogRead(A0);
if (luce<10) {
digitalWrite(giallo, HIGH);
}
else
digitalWrite(giallo, LOW); // Da eliminare nel caso spiegato nel paragrafo "All'opera"
}
| true |
b5154f8b5a3ba1861dae4a25757af98884354ba8 | C++ | RieLCho/Speaka | /Speaka/Speaka.cpp | UTF-8 | 1,587 | 2.96875 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include "../SpeakaLib/SpeakaLib.h"
void usage()
{
printf("Speaka (https://github.com/sokcuri/speaka)\n");
printf("Easy switch to default audio device\n");
printf("\n");
printf("usage:\n");
printf("Speaka [FormFactor] [Sequence]\n");
printf("\n");
printf("[FormFactor]: Specifies the type of audio device form factor (not case sensitive)\n");
printf("- Speakers\n- Headphones\n- Headset\n- SPDIF\n- DigitalAudioDisplayDevice\n");
printf("\n");
printf("[Sequence]: Specifies the audio device sequence number\n(If you are not sure, execute AudioDeviceList.exe)\n");
printf("\n");
printf("example:\n");
printf("- speaka Speakers 0\n");
printf("- speaka Headset 1\n");
}
int main(int argc, char** argv)
{
if (argc != 3)
{
usage();
return -1;
}
for (int i = 0; argv[1][i]; i++) {
argv[1][i] = tolower(argv[1][i]);
}
FormFactor formFactor = FormFactor::UnknownFormFactor;
if (!strcmp(argv[1], "speakers"))
formFactor = FormFactor::Speakers;
else if (!strcmp(argv[1], "headphones"))
formFactor = FormFactor::Headphones;
else if (!strcmp(argv[1], "headset"))
formFactor = FormFactor::Headset;
else if (!strcmp(argv[1], "spdif"))
formFactor = FormFactor::SPDIF;
else if (!strcmp(argv[1], "digitalaudiodisplaydevice"))
formFactor = FormFactor::DigitalAudioDisplayDevice;
if (formFactor == FormFactor::UnknownFormFactor)
{
printf("Invalid Form Factor String");
usage();
return -2;
}
int sequence = atoi(argv[2]);
SetAudioDevice(formFactor, sequence);
return 0;
} | true |
57977ad937ac95c974257c0bdae0e553d5033b68 | C++ | PLomax/k9code | /k9ControlPanel/k9ControlPanel.ino | UTF-8 | 5,142 | 2.765625 | 3 | [] | no_license |
/*
* Version 1.0
* 2-12-2017
*/
#include <Wire.h>
#include <Math.h>
#include <String.h>
const int ROW1 = 11;
const int ROW2 = 12;
const int ROW3 = 13;
const int COL1 = 4;
const int COL2 = 5;
const int COL3 = 6;
const int COL4 = 7;
const int LASEROUT = 97; //a
const int EARS = 98; //b
const int TAIL = 99; //c
const int MISC1 = 100; //d
const int MISC2 = 101; //e
const int MISC3 = 102; //f
const int MISC4 = 103; //g
const int MISC5 = 104; //h
const int MISC6 = 105; //i
int delayInt = 400;
const int digCtrlPanelWireSlaveAddress = 10;
int wireReceivedValue =0;
int received=0;
int randNumber = random(1,5);
String versionNumber = "Version 1.0";
// the setup function runs once when you press reset or power the board
void setup() {
Wire.begin(digCtrlPanelWireSlaveAddress);
Wire.onReceive(receiveEvent);
pinMode(ROW1, OUTPUT);
pinMode(ROW2, OUTPUT);
pinMode(ROW3, OUTPUT);
pinMode(COL1, OUTPUT);
pinMode(COL2, OUTPUT);
pinMode(COL3, OUTPUT);
pinMode(COL4, OUTPUT);
setAll(HIGH);
Serial.begin(9600); //set baud rate
Serial.println("K9 Control Panel");
Serial.println(versionNumber);
}
void receiveEvent() {
wireReceivedValue = Wire.read();
Serial.print("wire received:");
Serial.print(wireReceivedValue);
}
void setAll(int val)
{
digitalWrite(COL1, val);
digitalWrite(COL2, val);
digitalWrite(COL3, val);
digitalWrite(COL4, val);
digitalWrite(ROW1, val);
digitalWrite(ROW2, val);
digitalWrite(ROW3, val);
}
void randomSim()
{
randNumber = random(1,6);
setAll(HIGH);
switch(randNumber)
{
case 1:
{
for(int col=COL1;col <= COL4;col++)
{
digitalWrite(col, LOW);
delay(delayInt/randNumber);
}
break;
}
case 2:
{
for (int rw =ROW1;rw<=ROW3;rw++)
{
digitalWrite(rw, LOW);
delay(delayInt/randNumber);
}
break;
}
case 3:
{
for(int col=COL4;col > COL1;col--)
{
digitalWrite(col, LOW);
delay(delayInt/randNumber);
}
break;
}
case 4:
{
for(int col=COL4;col > COL1;col--)
{
digitalWrite(col, LOW);
delay(delayInt/randNumber);
}
break;
}
case 5:
{
for(int rw=ROW3;rw > ROW1;rw--)
{
digitalWrite(rw, LOW);
delay(delayInt/randNumber);
}
break;
}
}
setAll(HIGH);
}
void ears()
{
Serial.println("ears");
setAll(HIGH);
for(int i=0;i<6;i++)
{
digitalWrite(COL1, HIGH);
delay(200);
digitalWrite(COL1, LOW);
delay(200);
}
}
void laserOut()
{
Serial.println("laser Out");
setAll(HIGH);
for(int i=0;i<15;i++)
{
digitalWrite(COL2, HIGH);
delay(30);
digitalWrite(COL2, LOW);
delay(100);
}
}
void tail()
{
Serial.println("tail");
setAll(HIGH);
for(int i=0;i<8;i++)
{
digitalWrite(COL2, LOW);
digitalWrite(COL4, HIGH);
delay(200);
digitalWrite(COL4, LOW);
digitalWrite(COL2, HIGH);
// digitalWrite(COL3, LOW);
// digitalWrite(COL2, LOW);
// digitalWrite(COL1, LOW);
delay(200);
}
}
void misc(int cnt)
{
Serial.print("misc:");
Serial.println(cnt);
setAll(HIGH);
if(cnt == MISC1 || cnt == MISC2 || cnt == MISC3 )
{
for(int i=0;i<3;i++)
{
digitalWrite(ROW3, HIGH);
delay(500);
digitalWrite(ROW3, LOW);
delay(1000);
}
}
else
{
for(int i=0;i<3;i++)
{
digitalWrite(ROW1, HIGH);
delay(1000);
digitalWrite(ROW1, LOW);
delay(400);
}
}
}
// the loop function runs over and over again forever
void loop() {
received = wireReceivedValue;
wireReceivedValue=0;
Serial.print(".");
if (Serial.available() > 0)
{
received = Serial.read();
Serial.println(received);
}
switch(received)
{
case LASEROUT:
{
Serial.println("bhho");
laserOut();
break;
}
case EARS:
{
ears();
break;
}
case TAIL:
{
tail();
break;
}
case MISC1:
{
misc(1);
break;
}
case MISC2:
{
misc(2);
break;
}
case MISC3:
{
misc(3);
break;
}
case MISC4:
{
misc(4);
break;
}
case MISC5:
{
misc(5);
break;
}
case MISC6:
{
misc(6);
break;
}
}
randomSim();
}
| true |
35ef19ad2a3a870d7125b5411a010baa1b74e283 | C++ | Sorally/ColorShop | /ColorFunctions.cpp | UTF-8 | 5,515 | 2.96875 | 3 | [] | no_license | #include "ColorFunctions.h"
#include <math.h>
/****************************************************************************
* rgb2hsb()
*
*
****************************************************************************/
void rgb2hsb(BYTE r, BYTE g, BYTE b, HSB* hsb)
{
float x, f, i, hue, sat, bright;
x = min( min(r, g), b );
bright = max( max( r, g ), b );
if (x == bright) {
hsb->h = 0;
hsb->s = 0;
hsb->b = bright * 100.0f / 255.0f;
return;
}
f = (r == x) ? g - b : ((g == x) ? b - r : r - g);
i = (r == x) ? 3 : ((g == x) ? 5 : 1);
hsb->h = (int)floor((i - f / (bright - x)) * 60) % 360;
hsb->s = floor(((bright - x) / bright) * 100);
hsb->b = bright * 100.0f / 255.0f;
}
/****************************************************************************
* hsv2rgb()
*
*
****************************************************************************/
COLORREF hsv2rgb(float hue, float saturation, float brightness)
{
RGBQUAD quad;
//hsv2rgb_quad(hue, saturation, brightness, &quad);
hsv2rgb_quad(hue, saturation, brightness, &quad);
// reverse the buffer contents from RGB to BGR
return RGB((int)(quad.rgbBlue), (int)(quad.rgbGreen), (int)(quad.rgbRed));
}
//
//void hsv2rgb_quad(float hue, float saturation, float brightness, RGBQUAD* quad) {
//
// if (hue < 0.0f || hue > 360.0f || saturation < 0.0f || saturation > 1.0f || brightness < 0.0f || brightness > 1.0f) {
// MessageBox(0, L"hsv2rgb error", 0, 0);
// return;
// }
//
// float r, g, b;
// if (saturation == 0) {
// r = g = b = brightness;
// } else {
// if (hue == 360) hue = 0;
// hue /= 60;
// int i = (int)hue;
// float f = hue - i;
// float p = brightness * (1 - saturation);
// float q = brightness * (1 - saturation * f);
// float t = brightness * (1 - saturation * (1 - f));
// switch(i) {
// case 0:
// r = brightness;
// g = t;
// b = p;
// break;
// case 1:
// r = q;
// g = brightness;
// b = p;
// break;
// case 2:
// r = p;
// g = brightness;
// b = t;
// break;
// case 3:
// r = p;
// g = q;
// b = brightness;
// break;
// case 4:
// r = t;
// g = p;
// b = brightness;
// break;
// case 5:
// default:
// r = brightness;
// g = p;
// b = q;
// break;
// }
// }
//
// quad->rgbRed = r * 0xff;
// quad->rgbGreen = g * 0xff;
// quad->rgbBlue = b * 0xff;
//
//
//}
/****************************************************************************
* hsv2rgb_quad()
*
*
****************************************************************************/
//void hsv2rgb_quad(float hue, float saturation, float brightness, RGBQUAD* quad)
//{
// if (hue < 0 || hue > 360 || saturation < 0 || saturation > 1 || brightness < 0 || brightness > 1) {
// MessageBox(0, L"hsv2rgb error", 0, 0);
// }
//
// float r, g, b;
// if (saturation == 0) {
// r = g = b = brightness;
// } else {
// if (hue == 360) hue = 0;
// hue /= 60;
// int i = (int)hue;
// float f = hue - i;
// float p = brightness * (1 - saturation);
// float q = brightness * (1 - saturation * f);
// float t = brightness * (1 - saturation * (1 - f));
// switch(i) {
// case 0:
// r = brightness;
// g = t;
// b = p;
// break;
// case 1:
// r = q;
// g = brightness;
// b = p;
// break;
// case 2:
// r = p;
// g = brightness;
// b = t;
// break;
// case 3:
// r = p;
// g = q;
// b = brightness;
// break;
// case 4:
// r = t;
// g = p;
// b = brightness;
// break;
// case 5:
// default:
// r = brightness;
// g = p;
// b = q;
// break;
// }
// }
//
// //// reverse the buffer contents from RGB to BGR
// quad->rgbBlue = (BYTE)(b * 255 + 0.5);
// quad->rgbGreen = (BYTE)(g * 255 + 0.5);
// quad->rgbBlue = (BYTE)(r * 255 + 0.5);
//
//}
/****************************************************************************
* HSVtoRGB()
*
*
****************************************************************************/
void hsv2rgb_quad(float h, float s, float b, RGBQUAD* quad )
{
int i;
double f;
double bb;
u_char p;
u_char q;
u_char t;
h -= floor(h); /* remove anything over 1 */
h *= 6.0;
i = (int)floor(h); /* 0..5 */
f = h - (float) i; /* f = fractional part of H */
bb = 255.0 * b;
p = (u_char) (bb * (1.0 - s));
q = (u_char) (bb * (1.0 - (s * f)));
t = (u_char) (bb * (1.0 - (s * (1.0 - f))));
switch (i) {
case 0:
quad->rgbRed = (u_char) bb;
quad->rgbGreen = t;
quad->rgbBlue = p;
break;
case 1:
quad->rgbRed = q;
quad->rgbGreen = (u_char) bb;
quad->rgbBlue = p;
break;
case 2:
quad->rgbRed = p;
quad->rgbGreen = (u_char) bb;
quad->rgbBlue = t;
break;
case 3:
quad->rgbRed = p;
quad->rgbGreen = q;
quad->rgbBlue = (u_char) bb;
break;
case 4:
quad->rgbRed = t;
quad->rgbGreen = p;
quad->rgbBlue = (u_char) bb;
break;
case 5:
quad->rgbRed = (u_char) bb;
quad->rgbGreen = p;
quad->rgbBlue = q;
break;
}
}
HBITMAP CreateBitmapMask(HBITMAP hbmColour, COLORREF crTransparent)
{
HDC hdcMem, hdcMem2;
HBITMAP hbmMask;
BITMAP bm;
GetObject(hbmColour, sizeof(BITMAP), &bm);
hbmMask = CreateBitmap(bm.bmWidth, bm.bmHeight, 1, 1, NULL);
hdcMem = CreateCompatibleDC(0);
hdcMem2 = CreateCompatibleDC(0);
SelectObject(hdcMem, hbmColour);
SelectObject(hdcMem2, hbmMask);
SetBkColor(hdcMem, crTransparent);
BitBlt(hdcMem2, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);
BitBlt(hdcMem, 0, 0, bm.bmWidth, bm.bmHeight, hdcMem2, 0, 0, SRCINVERT);
DeleteDC(hdcMem);
DeleteDC(hdcMem2);
return hbmMask;
} | true |
6dc7f47de5e316f7c4d5383268f363fa044ccdf2 | C++ | JasonDeras/P3Lab4_JasonDeras | /Edificios.cpp | UTF-8 | 1,493 | 3.34375 | 3 | [
"MIT"
] | permissive | #include<iostream>
#include<string>
#include<vector>
#include<bits/stdc++.h>
#ifndef EDIFICIOS_CPP
#define EDIFICIOS_CPP
using namespace std;
class Edificios{
private:
string nombre;
int precio_base;
int produccion_base;
protected:
public:
Edificios(){
nombre="";
precio_base=0;
produccion_base=0;
}//Fin del constructor simple
Edificios(string nombre,int precio_base,int produccion_base){
this->nombre=nombre;
this->precio_base=precio_base;
this->produccion_base=produccion_base;
}//Fin del constructor sobrecargado
void setNombre(string nombre){
this->nombre.assign(nombre);
}//Set del nombre
string getNombre(){
return this->nombre;
}//Get del nombre
void setPrecio_base(int precio_base){
this->precio_base=precio_base;
}//Set del precio base
int getPrecio_Base(){
return this->precio_base;
}//Get del precio base
void setProduccion_base(int producion_base){
this->produccion_base=produccion_base;
}//Set del produccion de base
int getProduccion_base(){
return this->produccion_base;
}//Get de la produccion base
void print(){
cout<<"Nombre del edificio: "<<nombre<<endl;
cout<<"Precio base: "<<precio_base<<endl;
cout<<"Produccion base: "<<produccion_base<<endl;
}//Metodo print
virtual int Aumento()=0;//Metodo polimorfico del aumento
virtual int Especial()=0;//Metodo polimofico del bono
virtual ~Edificios(){
}//Destructor
};
#endif
| true |
b680d5e2a86f35e11d1f251e8236c1c90988b33a | C++ | ruiwng/program | /PAT/data_structure_2015/04-3.cpp | UTF-8 | 2,610 | 3.5625 | 4 | [] | no_license | #include <stdio.h>
#include <algorithm>
using namespace std;
struct node
{
int element;
node *parent;
int depth;
node *left_child;
node *right_child;
node(int e=0,node *p=NULL):element(e),parent(p),depth(1),left_child(NULL),right_child(NULL){}
};
inline int get_depth(node *p)
{
return p==NULL?0:p->depth;
}
node* left_rotation(node *p)
{
node *q=p->right_child;
q->parent=p->parent;
if(p->parent->left_child==p)
p->parent->left_child=q;
else
p->parent->right_child=q;
p->right_child=q->left_child;
if(q->left_child!=NULL)
q->left_child->parent=p;
q->left_child=p;
p->parent=q;
p->depth=max(get_depth(p->left_child),get_depth(p->right_child))+1;
q->depth=max(get_depth(q->left_child),get_depth(q->right_child))+1;
return q;
}
node* right_rotation(node *p)
{
node *q=p->left_child;
q->parent=p->parent;
if(p->parent->left_child==p)
p->parent->left_child=q;
else
p->parent->right_child=q;
p->left_child=q->right_child;
if(q->right_child!=NULL)
q->right_child->parent=p;
q->right_child=p;
p->parent=q;
p->depth=max(get_depth(p->left_child),get_depth(p->right_child))+1;
q->depth=max(get_depth(q->left_child),get_depth(q->right_child))+1;
return q;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
node *root=new node;
while(n--!=0)
{
int temp;
scanf("%d",&temp);
if(root->left_child==NULL)
root->left_child=new node(temp,root);
else
{
node *p=root->left_child;
while(true)
{
if(p->element<temp)
{
if(p->right_child==NULL)
{
p->right_child=new node(temp,p);
break;
}
else
p=p->right_child;
}
else
{
if(p->left_child==NULL)
{
p->left_child=new node(temp,p);
break;
}
else
p=p->left_child;
}
}
while(true)
{
int left_depth=get_depth(p->left_child);
int right_depth=get_depth(p->right_child);
if(left_depth-right_depth>1)
{
node *q=p->left_child;
if(get_depth(q->left_child)<get_depth(q->right_child))
left_rotation(q);
p=right_rotation(p);
}
else if(right_depth-left_depth>1)
{
node *q=p->right_child;
if(get_depth(q->left_child)>get_depth(q->right_child))
right_rotation(q);
p=left_rotation(p);
}
else
p->depth=max(left_depth,right_depth)+1;
p=p->parent;
if(p==root)
break;
}
}
}
printf("%d\n",root->left_child->element);
}
return 0;
} | true |
05f3618c93fa9fad141adff5f1021dd989ed2600 | C++ | BarbaraWitt/arduino | /aula11/jogoDeCartasArray/jogoDeCartasArray.ino | UTF-8 | 456 | 2.765625 | 3 | [
"Apache-2.0"
] | permissive | /**
* Estudo do Array vetor - Jogo de Cartas
* @author BabbyWitt
*/
void setup() {
Serial.begin (9600);
String faces [] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};
String naipes [] = {"♦","♠","♥","♣"};
randomSeed(analogRead(A0));
int f = random(13);
int n = random(4);
Serial.print (faces [f]);
Serial.println (naipes [n]);
}
void loop() {
// put your main code here, to run repeatedly:
}
| true |
77aa510e4e45c54e1b51db0b40a5ee97ddd354b4 | C++ | m-taku/sotuken | /GameTemplate/Game/graphics/Primitive.cpp | UTF-8 | 1,146 | 2.765625 | 3 | [] | no_license | #include "stdafx.h"
Primitive::Primitive()
{
}
Primitive::~Primitive()
{
Release();
}
void Primitive::Release()
{
m_vertexBuffer.Release();
m_indexBuffer.Release();
}
bool Primitive::Create(
D3D_PRIMITIVE_TOPOLOGY topology,
int numVertex,
int vertexStride,
void* pSrcVertexBuffer,
int numIndex,
IndexBuffer::EnIndexType indexType,
void* pSrcIndexBuffer)
{
Release();
bool result = m_vertexBuffer.Create(numVertex, vertexStride, pSrcVertexBuffer);
if (!result)
{
throw;
return false;
}
result = m_indexBuffer.Create(numIndex, indexType, pSrcIndexBuffer);
if (!result) {
throw;
return false;
}
return true;
}
void Primitive::Draw(ID3D11DeviceContext& rc)
{
UINT offset = 0;
UINT stride = m_vertexBuffer.GetStride();
rc.IASetVertexBuffers(0, 1, &m_vertexBuffer.GetBody(), &stride, &offset);
IndexBuffer::EnIndexType type = m_indexBuffer.GetIndexType();
rc.IASetIndexBuffer(m_indexBuffer.GetBody(),
type == IndexBuffer::enIndexType_16 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT,
0
);
rc.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
rc.DrawIndexed(m_indexBuffer.GetNumIndex(), 0, 0);
} | true |
27eea3c087dc0aed44c1266e2274205c153de91d | C++ | xieyangxu/TryQS | /linear_combiner.cpp | UTF-8 | 2,133 | 2.890625 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <set>
#include <string.h>
#include "linear_combiner.h"
using namespace std;
/*just tool func*/
void boolxor(bool* t,bool* s, long size){
for(long i=0;i<size;++i)
t[i]=(t[i]!=s[i]);
}
/*
randomly choose D_P+1 vectors and use some of them to get a linear combiniation
the func will return an address of a bool-type array
for we will use the function calloc, don't foget to free the array then
*/
bool* linear_combiner(long DR, long DP, long setsize)
{
//printf("linear combining...\n");
bool *t=(bool *)calloc(DR, sizeof(bool));
bool a[D_P+10][D_P]={0};
bool b[D_P+10][D_P+10]={0};
set <int> s;
set<int>::iterator it;
int c=0;
long tt=(Alpha*setsize)-1;
if(tt>DR) tt=DR;
while(s.size()<setsize){
int randnum=rand()%(tt);
s.insert(randnum);
}
for(it=s.begin();it!=s.end();++it,++c){
b[c][c]=1;
memcpy(a[c], m[*it], DP*sizeof(bool));
}
set <int> ss;
for(int i=0;i<DP;++i){
bool flag=0;
int bn=0;
for(int j=0;j<setsize;++j){
if(a[j][i]==0||ss.find(j)!= ss.end())
continue;
if(a[j][i]==1){
if(flag){
boolxor(a[j], a[bn], DP);
boolxor(b[j], b[bn], setsize);
}
else{
flag=1;
bn=j;
ss.insert(j);
}
}
}
}
for(int i=0;i<DP+1;++i){
for(int j=0;j<DP;++j){
if(a[i][j]==1) break;
if(j==DP-1){
for(it=s.begin(),c=0;it!=s.end();++it,++c){
if(b[i][c]){
t[*it]=1;
}
}
return t;
}
}
}
return NULL;
}
void print_combiniation(bool *t, long DR)
{
printf("t = (");
for(int i=0; i<DR; ++i){
if(t[i]){
printf("1 ");
}
else printf("0 ");
}
printf(")\n");
return;
}
| true |
34fcb465918a9773f95b8bd534ec2597e886c2d8 | C++ | epfl-mobots/particle-simu | /src/tools/filesystem.cpp | UTF-8 | 905 | 2.5625 | 3 | [] | no_license | #ifndef SIMU_TOOLS_FILESYSTEM_HPP
#define SIMU_TOOLS_FILESYSTEM_HPP
#include <boost/date_time.hpp>
#include <boost/filesystem.hpp>
namespace simu {
namespace tools {
std::string timestamp()
{
char date[30];
time_t date_time;
time(&date_time);
strftime(date, 30, "%Y-%m-%d_%H_%M_%S", localtime(&date_time));
return std::string(date);
}
boost::filesystem::path create_folder(const std::string folder_name)
{
boost::filesystem::path folder_absolute_path
= boost::filesystem::current_path().string() + "/" + folder_name;
assert(!boost::filesystem::exists(folder_absolute_path));
assert(boost::filesystem::create_directory(folder_absolute_path));
return folder_absolute_path;
}
} // namespace tools
} // namespace simu
#endif
| true |
66d6f57ad72ac387b2c396a2bb0d1805191b8f17 | C++ | Seoui/Cuphead-imitation | /Cuphead/Objects/VenusSeed.h | UTF-8 | 595 | 2.59375 | 3 | [] | no_license | #pragma once
#include "EnemyObject.h"
enum class VENUS_SEED_STATE { Fall, Grow };
class VenusSeed : public EnemyObject
{
public:
VenusSeed(Vector2 _position, Vector2 _scale = Vector2(1, 1));
~VenusSeed() = default;
public:
void Update(Matrix& V, Matrix& P) override;
void Render() override;
public:
void Play(VENUS_SEED_STATE state);
bool IsPlayEnd(VENUS_SEED_STATE state);
void Spawn(Vector2 _position);
void Die();
void Wait();
bool IsLive();
bool IsDead();
Vector2& GrowPosition();
private:
unique_ptr<Animation> seed_anim;
Vector2 grow_pos;
bool b_live;
bool b_dead;
}; | true |
73a30cb8b507755666ed1606f85a7f814eb1ed23 | C++ | dulvinrivindu/HackerRank | /C++/Strings/attribute.cpp | UTF-8 | 1,551 | 3.109375 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <regex>
using namespace std;
struct dict{
string key;
string value;
};
struct tag{
struct tag* parent = NULL;
string name;
vector<dict> attributes;
vector<tag> children;
};
string get_tag(string inString);
vector<dict> get_attributes(string inString);
int main() {
//Reading the input
int N, Q;
//cin >> N >> Q;
cin.ignore();
//Getting the tags to the data structure
vector<tag> tags;
tag* parent = NULL;
for(int read_i = 0; read_i < 1; read_i++){
string testString;
getline(cin, testString);
if(testString[0] != '/'){
if(parent == NULL){
tags.push_back(tag());
parent = &tags[tags.size() - 1];
tags[tags.size() - 1].name = get_tag(testString);
cout << tags[tags.size() - 1].name << endl;
tags[tags.size() - 1].attributes = get_attributes(testString);
}
}
}
return 0;
}
string get_tag(string inString){
smatch m;
regex e("tag\\d*");
regex_search(inString, m, e);
return m[0];
}
vector<dict> get_attributes(string inString){
vector<dict> attributes;
smatch m;
regex e("\\w+\\s=\\s\"\\w+\"");
while (regex_search (inString, m, e)) {
regex e1("\\w+");
regex e2("\"\\w+\"");
smatch m1;
smatch m2;
string s = m[0];
regex_search(s, m1, e1);
regex_search(s, m2, e2);
attributes.push_back(dict());
attributes[attributes.size() - 1].key = m1[0];
attributes[attributes.size() - 1].value = m2[0];
inString = m.suffix().str();
}
return attributes;
}
| true |
c5466dfed3fa6912730973f4db170c2b40b6e347 | C++ | durgesh0187/C-plus-plus-Programming | /Integer_convert_in_string.cpp | UTF-8 | 369 | 3.125 | 3 | [] | no_license | #include<bits/stdc++.h>
#include<sstream>
using namespace std;
int main()
{
int n=2345;
// declear output string stream
ostringstream str1;
// sending integer as a stream into ostringstream
str1<<n;
// declare string variable
string s = str1.str();
// output of the string
cout<<"our new string is : "<<s<<endl;
return 0;
}
| true |
6d0be64c3c062e7be834f8d7ab74b95c6e5fddfb | C++ | Apex5803/hailstorm | /src/Commands/Autonomous_Commands/GearAndBallsRed.cpp | UTF-8 | 1,275 | 2.65625 | 3 | [] | no_license | /*
* GearAndBallsRed.cpp
*
* Created on: Apr 21, 2017
* Author: Apex5803
*/
#include <Commands/Autonomous_Commands/GearAndBallsRed.h>
GearAndBallsRed::GearAndBallsRed() {
// TODO Auto-generated constructor stub
AddSequential(new TankDrive(-.6), 2);
//printf ("Drove toward gearer /n");
AddSequential(new TankDrive(0), .2);
//printf("Stopped /n");
AddParallel(new MoveGearerAuto(), 1);
//printf ("placed gear /n");
AddSequential(new TankDrive(.5), .7);
//printf ("Moved toward intake /n");
AddSequential(new TankDrive(-.75, .75), .8);
//printf ("turned toward boiler");
AddSequential(new TankDrive(.6), 3);
//printf ("Drove toward boiler /n");
AddSequential(new TankDrive(-0.6), 0.25);
//printf ("backed up slightly from boiler /n");
AddSequential(new TankDrive(0), 0.2);
//printf ("stopped moving before shooting /n");
AddParallel(new MoveShooter(8950.), 7);
//printf ("Shooter started /n ");
AddSequential (new FeederOut(), 0.5);
//printf ("Feeder reversed /n ");
AddParallel(new MoveMagiKarpetIn(), 6.5);
//printf ("MagiKarpet moved in /n ");
AddParallel (new MoveIntakeIn(), 6.5);
//printf ("BallCollector Moved /n ");
AddSequential(new FeederIn(), 6.5);
//printf ("Feeder ran in /n ");
}
| true |
42f91aa92064f491532acb6ab576b3dc5f19d32e | C++ | mardrey/Eda031 | /program/server/on_disc_database.cc | UTF-8 | 14,697 | 2.671875 | 3 | [] | no_license | #include "on_disc_database.h"
#include <string>
#include "news_group.h"
#include "article.h"
#include "database.h"
#include <dirent.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include "article.h"
#include <stdio.h>
namespace database{
std::string int_to_string(int i){
std::stringstream ss_convert;
ss_convert<<i;
return (ss_convert.str());
}
int get_id_for_file_or_dir(std::string& name, char del){
std::cout<<"NAME: "<<name<<std::endl;
std::string name_res;
std::stringstream iter_stream(name);
char c;
iter_stream.get(c);
while(c != del){
name_res+=c;
iter_stream.get(c);
}
std::cout<<"CSTRING IS: "<<name_res<<std::endl;
int id = atoi(name_res.c_str());
return id;
}
std::string get_name_for_file_or_dir(std::string& name, char del){
std::string name_res;
std::stringstream iter_stream(name);
char c;
iter_stream.get(c);
int traversed = 1;
for(unsigned int i = traversed; (i < name.size()&&c != del);++i){
// std::cout<<c<<std::endl;
iter_stream.get(c);
traversed++;
}
name_res = name.substr(traversed,name.size()-1);
return name_res;
}
bool delete_file_dir_entry(std::string& path){
std::fstream is_file;
is_file.open(path.c_str());
if(is_file){
if(remove(path.c_str()) != 0){
std::cerr<<"Deletion of file "<<path<<" was unsuccessful"<<std::endl;
is_file.close();
return false;
}else{
is_file.close();
return true;
}
}
std::cout<<path<<" was not a file"<<std::endl;
if(rmdir(path.c_str()) != -1){
return true;
}else{
DIR *root = opendir(path.c_str());
if(root == NULL){
std::cerr<<"could not open directory"<<std::endl;
closedir(root);
return false;
}
struct dirent *entry = readdir(root);
while(entry != NULL){
std::string nome = entry->d_name;
if(nome != "." && nome != ".." && nome != "" && nome[0] != '.'){
std::string name = path + "/" + (nome);
if(!delete_file_dir_entry(name)){
closedir(root);
std::cerr<<"Deletion of "<<(name)<<" was unsuccessful"<<std::endl;
return false;
}
}
entry = readdir(root);
}
closedir(root);
return (rmdir(path.c_str()) != -1);
}
}
article read_article(std::string& path, unsigned int id){
std::ifstream ifs;
ifs.open(path.c_str());
if(!ifs){
std::cerr<<"could not open file"<<std::endl;
std::string f("Fail");
article fail_art(-1,f,f,f);
return fail_art;
}
unsigned int title_l;
ifs>>title_l;
std::string title;
for(unsigned int i = 0; i < title_l; ++i){
char c;
ifs.get(c);
title+=c;
}
unsigned int author_l;
ifs>>author_l;
std::string author;
for(unsigned int i = 0; i < author_l; ++i){
char c;
ifs.get(c);
author+=c;
}
unsigned int content_l;
ifs>>content_l;
std::string content;
for(unsigned int i = 0; i < content_l; ++i){
char c;
ifs.get(c);
content+=c;
}
article art(id,title,author,content);
return art;
}
bool make_dir(std::string name){
int succ = mkdir(name.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
if(succ != 0){
std::cerr<<"Could not create directory "<<name<<std::endl;
return false;
}
return true;
}
unsigned int get_unused_index(std::string index_file_path){
std::ifstream file_exists;
file_exists.open(index_file_path.c_str());
if(!file_exists){
std::ofstream index_file;
index_file.open(index_file_path.c_str(),std::fstream::app);
index_file<<"0\n";
index_file.close();
return 0;
}else{
unsigned int index;
file_exists >> index;
while(!file_exists.eof()){
file_exists >> index;
}
file_exists.close();
index++;
std::ofstream index_file_out;
index_file_out.open(index_file_path.c_str(),std::fstream::app);
index_file_out<<index;
index_file_out<<"\n";
index_file_out.close();
return index;
}
}
on_disc_database::on_disc_database(){
path = "./database";
root = opendir(path.c_str());
if(root == NULL){
int succ = mkdir(path.c_str(), S_IRWXU|S_IRGRP|S_IXGRP);
if(succ != 0){
exit(1);
}
}else{
closedir(root);
}
}
on_disc_database::~on_disc_database(){
closedir(root);
}
int on_disc_database::add_news_group(std::string& name){
root = opendir(path.c_str());
dirent* entry = readdir(root);
while(entry != NULL){
std::string p = entry->d_name;
std::string filename = get_name_for_file_or_dir(p,':');
std::cout<<"P: "<<p<<"FN: "<<filename<<std::endl;
if(name == filename){
closedir(root);
std::cerr<<"Group name already in use"<<std::endl;
return -1;
}
entry = readdir(root);
}
closedir(root);
std::string indices_text = path+"/used_indices.txt";
unsigned int id = get_unused_index(indices_text);
std::ostringstream convert;
convert<<id;
std::string id_str;
id_str = convert.str();
std::string create_dir_name = (path+"/"+id_str+":"+name);
if(make_dir(create_dir_name)){
return 0; //Everything went ok
}
std::cerr<<"could not create directory for news group"<<std::endl;
return -1;
}
std::vector<news_group> on_disc_database::list_news_groups(){
root = opendir(path.c_str());
struct dirent *entry = readdir(root);
std::vector<news_group> groups;
while(entry != NULL){
if(entry->d_type == DT_DIR){
std::string line = entry->d_name;
std::stringstream split_stream(line);
std::string temp_string;
std::string temp_string2;
getline(split_stream,temp_string,':');
getline(split_stream,temp_string2);
if(temp_string != "" && temp_string2 != ""){
news_group ng(temp_string2,atoi(temp_string.c_str()));
groups.push_back(ng);
}
}
entry = readdir(root);
}
closedir(root);
return groups;
}
bool on_disc_database::delete_news_group(int id){
root = opendir(path.c_str());
struct dirent *entry = readdir(root);
while(entry != NULL){
if(entry->d_type == DT_DIR){
std::string line = entry->d_name;
std::stringstream split_stream(line);
std::string temp_string;
std::string temp_string2;
getline(split_stream,temp_string,':');
getline(split_stream,temp_string2);
if(temp_string != "" && temp_string2 != ""){
std::string name = (path + "/" + (entry->d_name));
if(atoi(temp_string.c_str())==id && temp_string != "." && temp_string != ".." && temp_string[0] != '.'){
bool res = delete_file_dir_entry(name);
closedir(root);
return res;
}
}
}
entry = readdir(root);
}
closedir(root);
return false;
}
bool on_disc_database::add_article(int id, std::string& title, std::string& author, std::string& content){
std::stringstream ss1;
std::string d_name;
DIR *dir = opendir(path.c_str());
struct dirent *entry = readdir(dir);
bool found = false;
while(entry!=NULL && !found){
if(entry->d_type == DT_DIR){
d_name = entry->d_name;
std::stringstream split_stream(d_name);
std::string temp_string;
getline(split_stream,temp_string,':');
if(temp_string != "" && temp_string != "." && temp_string != ".." && temp_string[0] != '.'){
int ng_id = atoi(temp_string.c_str());
if(ng_id==id){
found = true;
}
}
}
entry = readdir(dir);
}
if(!found){
std::cerr<<"News group does not exist"<<std::endl;
closedir(dir);
return false;
}
ss1<<path<<"/"<<d_name;
std::string ng_path = ss1.str();
DIR *ng_dir = opendir(ng_path.c_str());
if(ng_dir==NULL){
closedir(dir);
closedir(ng_dir);
std::cerr<<"News group does not exist"<<std::endl;
return false;
}
unsigned int highest = get_unused_index(ng_path+"/used_indices.txt");
std::stringstream ss2;
ss2<<ng_path<<"/"<<highest;
std::string art_path = ss2.str();
std::ofstream ofs;
ofs.open((art_path+":"+title+".art").c_str());
unsigned int title_l = title.size();
unsigned int author_l = author.size();
unsigned int content_l = content.size();
ofs<<title_l<<title<<author_l<<author<<content_l<<content;
ofs.close();
closedir(dir);
closedir(ng_dir);
return true;
}
int on_disc_database::delete_article(int group_id, int article_id){
std::stringstream ss1;
std::string d_name_ng;
std::string d_name_art;
DIR *dir = opendir(path.c_str());
struct dirent *entry = readdir(dir);
bool ng_found = false;
while(entry!=NULL && !ng_found){
std::string nome = entry->d_name;
if(entry->d_type == DT_DIR && nome != ".." && nome != "." && nome[0] != '.'){
d_name_ng = entry->d_name;
std::stringstream split_stream(d_name_ng);
std::string temp_string;
getline(split_stream,temp_string,':');
int ng_id = atoi(temp_string.c_str());
if(ng_id==group_id){
ng_found = true;
}
}
entry = readdir(dir);
}
if(!ng_found){
std::cerr<<"News group does not exist"<<std::endl;
closedir(dir);
return -1;
}
ss1<<path<<"/"<<d_name_ng;
std::string ng_path = ss1.str();
DIR *ng_dir = opendir(ng_path.c_str());
if(ng_dir==NULL){
std::cerr<<"News group does not exist"<<std::endl;
closedir(dir);
closedir(ng_dir);
return -1;
}
struct dirent *entry2;
bool art_found = false;
while(!art_found){
entry2 = readdir(ng_dir);
if(entry2==NULL){
std::cerr<<"Article does not exist"<<std::endl;
closedir(dir);
closedir(ng_dir);
return 1;
}
std::string nome(entry2->d_name);
if(nome!="." && (nome!="..") && nome[0] != '.' && nome != "used_indices.txt"){
d_name_art = entry2->d_name;
std::stringstream split_stream(d_name_art);
std::string temp_string;
getline(split_stream,temp_string,':');
std::cout<<d_name_art<<std::endl;
std::cout<<ng_path<<std::endl;
std::cout<<(ng_path+"/"+d_name_art)<<std::endl;
int art_id = get_id_for_file_or_dir(d_name_art,':');
std::cout<<"found id: "<<art_id<<", wanted id: "<<article_id<<std::endl;
if(art_id==article_id){
art_found = true;
}
}
}
if(!art_found){
std::cerr<<"article was not found"<<std::endl;
closedir(dir);
closedir(ng_dir);
return 1;
}
if(remove((ng_path+"/"+d_name_art).c_str())!=0){
std::cout<<(ng_path+"/"+d_name_art)<<std::endl;
std::cerr<<"article deletion unsuccessful"<<std::endl;
closedir(dir);
closedir(ng_dir);
return 1;
}
closedir(dir);
closedir(ng_dir);
return 0;
}
article on_disc_database::get_article(int group_id, int article_id){
std::string f("Fail");
article fail_art(-1,f,f,f);
std::cout<<"GA0"<<std::endl;
news_group ng2 = get_news_group(group_id);
if(ng2.get_name() == "Fail"){
std::cerr<<"News group does not exist1"<<std::endl;
return fail_art;
}
std::cout<<"GA1"<<std::endl;
std::string i_s;
std::string ng2_name;
i_s = int_to_string(group_id);
ng2_name = ng2.get_name();
std::string d_name_ng;
d_name_ng = (i_s + ":" + ng2_name);
std::string ng_path = path + "/" + d_name_ng;
std::cout<<"path: "<<ng_path<<std::endl;
DIR *ng_dir = opendir(ng_path.c_str());
if(ng_dir==NULL){
std::cerr<<"News group does not exist2"<<std::endl;
closedir(ng_dir);
return fail_art;
}
std::cout<<"GA2"<<std::endl;
struct dirent* entry2;
bool art_found = false;
std::string d_name_art;
while(!art_found){
entry2 = readdir(ng_dir);
if(entry2==NULL){
std::cerr<<"Could not find article"<<std::endl;
closedir(ng_dir);
return fail_art;
}
std::string name = entry2->d_name;
if(name!="." && (name!="..") && (name)[0]!='.' && name != "used_indices.txt"){
d_name_art = name;
std::cout<<d_name_art<<std::endl;
std::stringstream split_stream(d_name_art);
std::string temp_string;
getline(split_stream,temp_string,':');
int art_id = atoi(temp_string.c_str());
if(art_id==article_id){
art_found = true;
}
}
}
std::cout<<"GA3"<<std::endl;
if(!art_found){
std::cerr<<"article was not found"<<std::endl;
if(entry2 != NULL){
}
closedir(ng_dir);
return fail_art;
}
std::cout<<"GA3.5"<<std::endl;
std::cout<<"GA3.56365"<<std::endl;
closedir(ng_dir);
std::cout<<"GA3.6275"<<std::endl;
std::string art_path = (ng_path+"/"+d_name_art);
std::cout<<"GA3.625"<<std::endl;
article art = read_article(art_path,article_id);
std::cout<<"GA3.75"<<std::endl;
if(art.get_id() == -1){
return art;
}
std::cout<<"GA4"<<std::endl;
return art;
}
news_group on_disc_database::get_news_group(int id){
std::string f("Fail");
news_group fail_ng(f,-1);
root = opendir(path.c_str());
dirent *entry = readdir(root);
std::string ng_name;
bool found_ng = false;
while(entry != NULL && !found_ng){
std::string name = entry->d_name;
if(name != "" && name != "." && name != ".." && name[0] != '.' && entry->d_type == DT_DIR){
std::stringstream split_stream(name);
std::string id_string;
getline(split_stream,id_string,':');
int ng_id = atoi(id_string.c_str());
if(ng_id == id){
getline(split_stream,ng_name);
found_ng = true;
}
}
entry = readdir(root);
}
news_group ng(ng_name,id);
if(!found_ng || ng.get_id() == -1){
std::cout<<"could not find news group"<<std::endl;
closedir(root);
return fail_ng;
}
std::stringstream int_con;
int_con<<id;
std::string id_string;
id_string = int_con.str();
std::string ng_path = path+"/"+id_string+":"+ng_name;
closedir(root);
root = opendir(ng_path.c_str());
std::cout<<ng_path<<std::endl;
if(root == NULL){
std::cerr<<"could not open news group"<<std::endl;
closedir(root);
return fail_ng;
}
entry = readdir(root);
while(entry != NULL){
std::string name = entry->d_name;
if(name != "" && name != "." && name != ".." && name[0] != '.' && name != "used_indices.txt"){
std::stringstream ss(name);
std::string temp_string;
getline(ss,temp_string,':');
unsigned int art_id = atoi(temp_string.c_str());
std::string art_path;
art_path = path+"/"+id_string+":"+ng_name+"/"+name;
article art = read_article(art_path, art_id);
if(art.get_id() == -1){
std::cout<<"article is fail"<<std::endl;
closedir(root);
return fail_ng;
}
ng.add_article(art);
}
entry = readdir(root);
}
closedir(root);
return ng;
}
}
| true |
03b602dcc808f7d4395f57f148c48dfd601a4217 | C++ | austinkeil/CTCI | /2-7-b.cpp | UTF-8 | 1,678 | 3.984375 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* NewNode(int data) {
Node* n = new Node();
n->data = data;
n->next = nullptr;
return n;
}
Node* Insert(Node* head, int data) {
Node* temp = NewNode(data);
if (head == nullptr) {
return temp;
}
temp->next = head;
return temp;
}
void Print(Node* head) {
while(head) {
cout << head->data << " at " << head << endl;
head = head->next;
}
}
int main() {
cout << "List 1: \n";
Node* head = NewNode(5);
head = Insert(head, 10);
Node* temp = Insert(head, 17);
head = temp;
head = Insert(head, 7);
head = Insert(head, 2);
head = Insert(head, 21);
head = Insert(head, 13);
cout << "\nList 2:\n";
Node* head2 = NewNode(3);
head2 = Insert(head2, 1);
head2 = Insert(head2, 3);
temp->next = head2;
head2 = temp;
head2 = Insert(head2, 9);
head2 = Insert(head2, 12);
cout <<"\nList1: \n";
Print(head);
cout <<"\nList2: \n";
Print(head2);
Node* p1 = head;
int n1 = 0;
while (p1) {
n1++;
p1 = p1->next;
}
Node* p2 = head2;
int n2 = 0;
while (p2) {
n2++;
p2 = p2->next;
}
if (p1 != p2) {
cout << "NO INTERSECTION!" << endl;
return 0;
}
if (n1 > n2) {
p1 = head;
p2 = head2;
} else {
p1 = head2;
p2 = head;
}
for (int i = 0; i < abs(n1-n2); i++) {
p1 = p1->next;
}
while (p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
cout << "Intersection at: " << p1 << endl;
} | true |
fa6f56a5967c42cd42464326dceb939b5af6692c | C++ | mrnoelle/Chess | /Knight.cpp | UTF-8 | 543 | 2.859375 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<cmath>
#include "Knight.hpp"
using namespace std;
Knight::Knight(string piece_name, string piece_colour): ChessPiece(piece_name, piece_colour)
{
}
Knight::~Knight() {}
bool Knight::validMove(string src, string des, ChessBoard* board)
{
int file_change = abs((int)(des[0]-src[0]));
int rank_change = abs((int)(des[1]-src[1]));
/* move forms an "L"-shape */
if (!((file_change==1 && rank_change==2)||(file_change==2 && rank_change==1)))
return false;
else
return true;
}
| true |
d9504e843e5c29fd4f1662c3c9b92be9e2be4f03 | C++ | skywtchr/pso | /pso/swarm.cpp | UTF-8 | 4,105 | 2.8125 | 3 | [] | no_license | #include "swarm.h"
Swarm::Swarm(ILog &logger,
SwarmConfig &config,
ObjectiveFunction &objectiveFunction) {
_logger = &logger;
_config = &config;
_objectiveFunction = &objectiveFunction;
_isFinished = false;
_iterationCounter = 0;
_configToDelete = nullptr;
}
Swarm::Swarm(ILog &logger, ObjectiveFunction &objectiveFunction)
{
_logger = &logger;
_config = new SwarmConfig(logger);
_configToDelete = _config;
_objectiveFunction = &objectiveFunction;
_isFinished = false;
_iterationCounter = 0;
}
Swarm::~Swarm() {
for (auto var : _vectorsToDelete) {
delete var;
}
delete _configToDelete;
}
void Swarm::SearchFunctionMinimumAsync()
{
_isFinished = false;
auto asynOperation = [] (Swarm* s) {
s->SearchFunctionMinimum();
};
_searchingFuture = std::async(std::launch::async, asynOperation, this);
}
void Swarm::SearchFunctionMinimumSync()
{
_isFinished = false;
SearchFunctionMinimum();
}
std::vector<double> Swarm::GetBestSwarmPosition()
{
return *_bestSwarmPosition;
}
void Swarm::SearchFunctionMinimum()
{
CreateParticles();
FindBestSwarmPositionAndResult();
RunPsoAlgorithm();
_isFinished = true;
}
double Swarm::GetBestSwarmResult()
{
return _bestSwarmResult;
}
int Swarm::GetPercentageProgress()
{
return 100 * _iterationCounter / _config->iterationCount;
}
int Swarm::GetIterationProgress()
{
return _iterationCounter;
}
int Swarm::GetIterationCount()
{
return _config->iterationCount;
}
std::vector<Particle> *Swarm::GetParticles()
{
return &_particles;
}
bool Swarm::IsFinished()
{
return _isFinished;
}
void Swarm::CreateParticles()
{
for(int i = 0; i<_config->particlesCount; i++) {
auto particle = GetNewParticle();
_particles.push_back(particle);
}
}
void Swarm::FindBestSwarmPositionAndResult()
{
_bestSwarmPosition = _particles[0].GetPosition();
_bestSwarmResult = _objectiveFunction->GetResult(*_bestSwarmPosition);
for (auto particle : _particles) {
auto bestParticleResult = particle.GetBestResult();
if (bestParticleResult < _bestSwarmResult) {
_bestSwarmResult = bestParticleResult;
_bestSwarmPosition = particle.GetPosition();
}
}
}
Particle Swarm::GetNewParticle()
{
return Particle(*_logger,
*_config->particleFactors,
_config->velocityLimit,
*_objectiveFunction,
*_config->randomNumbersGenerator,
FixStartPosition(),
FixStartVelocity(),
&_bestSwarmPosition);
}
void Swarm::RunPsoAlgorithm()
{
_logger->LogInfo("PSO algorithm started...");
for (int i=0; i<_config->iterationCount; i++) {
_iterationCounter = i+1;
for (auto particle : _particles) {
particle.Move();
auto bestParticleResult = particle.GetBestResult();
if (bestParticleResult < _bestSwarmResult) {
_bestSwarmResult = bestParticleResult;
_bestSwarmPosition = particle.GetPosition();
}
}
}
_logger->LogInfo("PSO algorithm finished successfully.");
}
std::vector<double>* Swarm::FixStartPosition()
{
std::vector<double>* result = new std::vector<double>();
_vectorsToDelete.push_back(result);
for (int i=0; i<_objectiveFunction->GetVariablesCount(); i++) {
auto startDomain = _config->GetVariableStartDomain(i);
std::uniform_real_distribution<> dist(startDomain.GetLowerLimit(), startDomain.GetUpperLimit());
auto randomValue
= _config->randomNumbersGenerator->GenerateRandomValue(dist);
result->push_back(randomValue);
}
return result;
}
std::vector<double>* Swarm::FixStartVelocity()
{
std::vector<double>* result = new std::vector<double>();
_vectorsToDelete.push_back(result);
for (int i=0; i<_objectiveFunction->GetVariablesCount(); i++) {
result->push_back(0);
}
return result;
}
| true |
af21a7cec17d4af1c6f0513032cef7dae9d511cb | C++ | Drakandes/Portfolio_NicolasPaulBonneau | /Code en C++ de Mage War Online/SkillReinforcement.cpp | ISO-8859-1 | 3,227 | 2.75 | 3 | [
"MIT"
] | permissive | #include "stdafx.h"
#include "SkillReinforcement.h"
SkillReinforcement::SkillReinforcement(int current_language)
{
language = current_language;
if (!texture_icone.loadFromFile("SkillReinforcement.png"))
{
std::cout << "Error while loading SkillReinforcement icone texture" << std::endl;
}
}
SkillReinforcement::~SkillReinforcement()
{
}
void SkillReinforcement::GenerateSkillProjectile(sf::Vector2f &position_player, float player_damage, sf::Vector2f mouse_position, std::shared_ptr<Player> player, int player_id, int skill_level_received, int current_rune)
{
}
sf::Texture SkillReinforcement::ReturnSkillIconeTexture()
{
return texture_icone;
}
float SkillReinforcement::GetSkillCooldown(int skill_level, int class_player)
{
return 0;
}
int SkillReinforcement::GetNumberStringSkillInformation()
{
return number_string_skill_information;
}
sf::String SkillReinforcement::GetStringSkillInformation(int number_string)
{
return string_skill_information[number_string];
}
void SkillReinforcement::ChangeSkillLevel(int skill_level_received, float player_damage, int class_player, int current_rune)
{
skill_level = skill_level_received;
if (class_attribution == class_player)
{
skill_level++;
}
percent_shield = 2 + 1 * (skill_level - 1);
if (language == English_E)
{
string_skill_information[0] = "Reinforcement (passive skill)";
string_skill_information[1] = "Everytime a basic attack hits a target, the player is shielded equal to 2% (+1% per level) of his maximum health.";
}
else
{
string_skill_information[0] = "Renforcement (sort passif)";
string_skill_information[1] = " chaque fois qu'une attaque de base touche une cible, le joueur reoit du bouclier gal 2% (+1% par niveau) de sa vie totale.";
}
}
void SkillReinforcement::DrawSkillHitBox(sf::Vector2f mouse_position, int skill_level, sf::Vector2f position_caster, int class_player, float range_modifier, int current_rune)
{
}
sf::String SkillReinforcement::GetStringRuneBonus(int rune_number)
{
if (language == English_E)
{
switch (rune_number)
{
case FirstRune_E:
return sf::String("Also increase the player's shield capacity by +25%.");
case SecondRune_E:
return sf::String("15% of your armor apply on shield.");
case ThirdRune_E:
return sf::String("Also give +2 (+1 per skill level) armor on hit for 3 seconds.");
}
}
else
{
switch (rune_number)
{
case FirstRune_E:
return sf::String("Augmente aussi la capacit de bouclier du joueur de +25%.");
case SecondRune_E:
return sf::String("15% de votre armure s'applique aussi aux boucliers.");
case ThirdRune_E:
return sf::String("Donne aussi +2 (+1 par niveau de sort) d'armure chaque touche pendant 3 secondes.");
}
}
}
int SkillReinforcement::GetPassiveBonusType()
{
return 0;
}
float SkillReinforcement::GetPassiveBonusValue(int player_level, int class_player, int current_rune)
{
ChangeSkillLevel(player_level, 0, class_player, current_rune);
return percent_shield;
}
float SkillReinforcement::GetPassiveBonusDuration(int player_level, int class_player, int current_rune)
{
return 0;
} | true |
78555f22e2536cc4db02452237d7ebfdb00d6e45 | C++ | rob-DEV/Onyx | /Onyx/src/Platform/OpenGL/OpenGLShader.h | UTF-8 | 1,414 | 2.6875 | 3 | [] | no_license | #ifndef _ONYX_PLATFORM_OPENGL_SHADER_H_
#define _ONYX_PLATFORM_OPENGL_SHADER_H_
#include <Onyx/graphics/Shader.h>
#include <glm/glm.hpp>
typedef unsigned int GLenum;
namespace Onyx {
class OpenGLShader : public Shader {
public:
OpenGLShader(std::string_view filepath);
OpenGLShader(std::string_view name, std::string_view vertexSrc, std::string_view fragmentSrc);
virtual ~OpenGLShader();
virtual void Bind() const;
virtual void Unbind() const;
virtual std::string_view GetName() const override { return m_Name; }
virtual void SetInt(std::string_view name, int value) override;
virtual void SetIntArray(std::string_view name, int* values, uint32_t count) override;
virtual void SetFloat(std::string_view name, float value) override;
virtual void SetFloat2(std::string_view name, const glm::vec2& value) override;
virtual void SetFloat3(std::string_view name, const glm::vec3& value) override;
virtual void SetFloat4(std::string_view name, const glm::vec4& value) override;
void SetMat3(std::string_view name, const glm::mat3& matrix);
void SetMat4(std::string_view name, const glm::mat4& matrix);
private:
std::unordered_map<GLenum, std::string> PreProcess(std::string_view source);
void Compile(const std::unordered_map<GLenum, std::string>& shaderSources);
private:
uint32_t m_RendererID;
std::string m_Name;
};
}
#endif // !_ONYX_PLATFORM_OPENGL_SHADER_H_
| true |
2b5ade57c77401733bcfeb4846166554612efd56 | C++ | matthewcpp/recondite | /src/xml/rXMLDocumentLoader.cpp | UTF-8 | 967 | 2.609375 | 3 | [] | no_license | #include "xml/rXMLDocumentLoader.hpp"
rXMLDocumentLoader::rXMLDocumentLoader(){
m_root = NULL;
}
rXMLDocumentLoader::~rXMLDocumentLoader(){
if (m_root)
delete m_root;
}
rXMLElement* rXMLDocumentLoader::DetachRoot(){
rXMLElement* root = m_root;
m_root = NULL;
return root;
}
void rXMLDocumentLoader::OnStartElement(const rString& elementName, const rXMLAttributeList& attributes){
rXMLElement* parent = m_stack.size() > 0 ? m_stack.top() : 0;
rXMLElement* element = new rXMLElement(parent, elementName);
if (m_stack.size() == 0){
m_root = element;
}
element->AddAttributes(attributes);
m_stack.push(element);
}
void rXMLDocumentLoader::OnEndElement(const rString& elementName){
m_stack.pop();
}
void rXMLDocumentLoader::OnReadCharacters(const rString& data){
rXMLElement* currentElement = m_stack.top();
rString text = currentElement->Text();
if (!text.empty())
text += ' ';
text += data;
currentElement->SetText(text);
}
| true |
75c1e718f210515ea24f734f7a1fc3316e96acc8 | C++ | JinkyuChoi/C-ScrollingGame | /src/Bonus.cpp | UTF-8 | 1,268 | 2.71875 | 3 | [] | no_license | #include "Bonus.h"
#include "Game.h"
Bonus::Bonus()
{
TheTextureManager::Instance()->load("../Assets/textures/bonus.png",
"bonus", TheGame::Instance()->getRenderer());
// measure size by querying the texture
glm::vec2 size = TheTextureManager::Instance()->getTextureSize("bonus");
setWidth(size.x);
setHeight(size.y);
m_reset();
setIsColliding(false);
setType(GameObjectType::BONUS);
setVelocity(glm::vec2(-3.0f, 0.0f));
//TheSoundManager::Instance()->load("../Assets/audio/yay.ogg", "yay", SOUND_SFX);
}
Bonus::~Bonus()
{
}
void Bonus::draw()
{
int xComponent = getPosition().x;
int yComponent = getPosition().y;
TheTextureManager::Instance()->draw("bonus", xComponent, yComponent,
TheGame::Instance()->getRenderer(), 0, 255, true);
}
void Bonus::update()
{
m_move();
m_checkBounds();
}
void Bonus::clean()
{
}
void Bonus::m_reset()
{
const auto randomY = Util::RandomRange(100, Config::SCREEN_HEIGHT - 100);
setPosition(glm::vec2(Config::SCREEN_WIDTH + getWidth(), randomY));
}
void Bonus::m_move()
{
const int xPos = getPosition().x + getVelocity().x;
const int yPos = getPosition().y + getVelocity().y;
setPosition(glm::vec2(xPos, yPos));
}
void Bonus::m_checkBounds()
{
if (getPosition().x < -getWidth())
{
m_reset();
}
}
| true |
015bc8c38fd6608e99e0c2917dad1d5d08992b12 | C++ | Happy-Ferret/WikiAdventure | /WikiAdventure/Source/WA-SDL/SDLMultilineTextObject.h | UTF-8 | 2,516 | 2.578125 | 3 | [
"LicenseRef-scancode-public-domain"
] | permissive |
#ifndef SDLMULTILINETEXTOBJECT_H
#define SDLMULTILINETEXTOBJECT_H
#include "SDLBaseTextObject.h"
#include "SDLDebugTextObject.h"
#include "SDLTextSelectionList.h"
#include "SDLCenterTextObject.h"
/** A ? object */
class CSDLMultilineTextObject: public CSDLTextSelectionList
{
protected:
string m_sFont;
SDL_Color m_stColor;
SDL_Color m_stHoverColor;
int m_iMaxWidth;
// HACKY HACKY HACK!
CSDLMultilineTextObject(
bool bDoNotSetText,
const string& sFontID,
const string& sText = "Hello World",
SDL_Color SColor = stDefColor,
SDL_Color SHoverColor = stDefBGColor,
int iMaxWidth = 600
);
public:
CSDLMultilineTextObject(
const string& sFontID,
const string& sText = "Hello World",
SDL_Color SColor = stDefColor,
SDL_Color SHoverColor = stDefBGColor,
int iMaxWidth = 600
);
virtual ~CSDLMultilineTextObject();
virtual void SetText( const string& sText );
//virtual void GetText() { return CSDLTextSelectionList:: }
virtual void Render( SDL_Surface* pDestSurface );
virtual void MouseMoved( const int& iButton, const int& iX, const int& iY );
virtual void MouseButtonDown( const int& iButton, const int& iX, const int& iY );
virtual void OnMouseEnter();
virtual void OnMouseLeave();
virtual void AddTextLineObject( const string& sText );
};
/** A ? object */
class CSDLMultilineCenterTextObject: public CSDLMultilineTextObject
{
public:
CSDLMultilineCenterTextObject(
const string& sFontID,
const string& sText = "Hello World",
SDL_Color SColor = stDefColor,
SDL_Color SHoverColor = stDefBGColor,
int iMaxWidth = 600
)
: CSDLMultilineTextObject( sFontID, sText, SColor, SHoverColor, iMaxWidth ) {};
virtual ~CSDLMultilineCenterTextObject() {};
//virtual void SetText( const string& sText );
virtual void AddTextLineObject( const string& sText )
{
AddObject( new CSDLCenterTextObject( m_sFont, sText, m_stColor, m_stHoverColor ) );
}
};
/** A ? object */
class CSDLMultilineDebugTextObject: public CSDLMultilineTextObject
{
protected:
SDL_Color m_stBGColor;
SDL_Color m_stBGHoverColor;
public:
CSDLMultilineDebugTextObject(
const string& sFontID,
const string& sText = "Hello World",
SDL_Color SColor = stDefColor,
SDL_Color SBGColor = stDefBGColor,
SDL_Color SHoverColor = stDefBGColor,
SDL_Color SBGHoverColor = stDefColor,
int iMaxWidth = 600
);
virtual ~CSDLMultilineDebugTextObject();
virtual void AddTextLineObject( const string& sText );
};
#endif // SDLMULTILINETEXTOBJECT_H | true |
162339e513c04c3b55a52e171be9be0f65c59aea | C++ | Sparrow116/GameOfLife | /gamewidget.cpp | WINDOWS-1251 | 7,369 | 2.71875 | 3 | [] | no_license | #include <QMessageBox>
#include <QTimer>
#include <QMouseEvent>
#include <QDebug>
#include <QRectF>
#include <QPainter>
#include <qmath.h>
#include "gamewidget.h"
GameWidget::GameWidget(QWidget *parent) :
QWidget(parent),
timer(new QTimer(this)),
generations(-1),
FirstGenSize(40) // ( )
{
timer->setInterval(100); // ( )
ColorCells = "#000"; // ( )
FirstGen = new bool[(FirstGenSize + 2) * (FirstGenSize + 2)];
SecondGen = new bool[(FirstGenSize + 2) * (FirstGenSize + 2)];
connect(timer, SIGNAL(timeout()), this, SLOT(newGeneration()));
memset(FirstGen, false, sizeof(bool)*(FirstGenSize + 2) * (FirstGenSize + 2));
memset(SecondGen, false, sizeof(bool)*(FirstGenSize + 2) * (FirstGenSize + 2));
}
GameWidget::~GameWidget()
{
delete [] FirstGen;
delete [] SecondGen;
}
void GameWidget::startGame(const int &number) //
{
generations = number;
timer->start();
}
void GameWidget::stopGame() //
{
timer->stop();
}
void GameWidget::clear() //
{
for(int k = 1; k <= FirstGenSize; k++) {
for(int j = 1; j <= FirstGenSize; j++) {
FirstGen[k*FirstGenSize + j] = false;
}
}
gameEnds(true);
update();
}
int GameWidget::cellNumber()
{
return FirstGenSize;
}
void GameWidget::setCellNumber(const int &s)
{
FirstGenSize = s;
resetFirstGen();
update();
}
void GameWidget::resetFirstGen()
{
delete [] FirstGen;
delete [] SecondGen;
FirstGen = new bool[(FirstGenSize + 2) * (FirstGenSize + 2)];
SecondGen = new bool[(FirstGenSize + 2) * (FirstGenSize + 2)];
memset(FirstGen, false, sizeof(bool)*(FirstGenSize + 2) * (FirstGenSize + 2));
memset(SecondGen, false, sizeof(bool)*(FirstGenSize + 2) * (FirstGenSize + 2));
}
QString GameWidget::dump()
{
char temp;
QString master = "";
for(int k = 1; k <= FirstGenSize; k++) {
for(int j = 1; j <= FirstGenSize; j++) {
if(FirstGen[k*FirstGenSize + j] == true) {
temp = '*';
} else {
temp = 'o';
}
master.append(temp);
}
master.append("\n");
}
return master;
}
void GameWidget::setDump(const QString &data)
{
int current = 0;
for(int k = 1; k <= FirstGenSize; k++) {
for(int j = 1; j <= FirstGenSize; j++) {
FirstGen[k*FirstGenSize + j] = data[current] == '*';
current++;
}
current++;
}
update();
}
int GameWidget::interval()
{
return timer->interval();
}
void GameWidget::setInterval(int msec)
{
timer->setInterval(msec);
}
bool GameWidget::isAlive(int k, int j)
{
int power = 0;
power += FirstGen[(k+1)*FirstGenSize + j];
power += FirstGen[(k-1)*FirstGenSize + j];
power += FirstGen[k*FirstGenSize + (j+1)];
power += FirstGen[k*FirstGenSize + (j-1)];
power += FirstGen[(k+1)*FirstGenSize + ( j-1)];
power += FirstGen[(k-1)*FirstGenSize + (j+1)];
power += FirstGen[(k-1)*FirstGenSize + (j-1)];
power += FirstGen[(k+1)*FirstGenSize + (j+1)];
if (((FirstGen[k*FirstGenSize + j] == true) && (power == 2)) || (power == 3))
return true;
return false;
}
void GameWidget::newGeneration()
{
if(generations < 0)
generations++;
int notChanged=0;
for(int k=1; k <= FirstGenSize; k++) {
for(int j=1; j <= FirstGenSize; j++) {
SecondGen[k*FirstGenSize + j] = isAlive(k, j);
if(SecondGen[k*FirstGenSize + j] == FirstGen[k*FirstGenSize + j])
notChanged++;
}
}
if(notChanged == FirstGenSize*FirstGenSize) {
QMessageBox::information(this,
tr(" "),
tr("Game Over"),
QMessageBox::Ok);
stopGame();
gameEnds(true);
return;
}
for(int k=1; k <= FirstGenSize; k++) {
for(int j=1; j <= FirstGenSize; j++) {
FirstGen[k*FirstGenSize + j] = SecondGen[k*FirstGenSize + j];
}
}
update();
generations--;
if(generations == 0) {
stopGame();
gameEnds(true);
QMessageBox::information(this,
tr(" "),
tr("Game Over."), //
QMessageBox::Ok,
QMessageBox::Cancel);
}
}
void GameWidget::paintEvent(QPaintEvent *)
{
QPainter p(this);
paintGrid(p);
paintFirstGen(p);
}
void GameWidget::mousePressEvent(QMouseEvent *e)
{
emit environmentChanged(true);
double cellWidth = (double)width()/FirstGenSize;
double cellHeight = (double)height()/FirstGenSize;
int k = floor(e->y()/cellHeight)+1;
int j = floor(e->x()/cellWidth)+1;
FirstGen[k*FirstGenSize + j] = !FirstGen[k*FirstGenSize + j];
update();
}
void GameWidget::mouseMoveEvent(QMouseEvent *e)
{
double cellWidth = (double)width()/FirstGenSize;
double cellHeight = (double)height()/FirstGenSize;
int k = floor(e->y()/cellHeight)+1;
int j = floor(e->x()/cellWidth)+1;
int currentLocation = k*FirstGenSize + j;
if(!FirstGen[currentLocation]){ // ,
FirstGen [currentLocation]= !FirstGen[currentLocation];
update();
}
}
void GameWidget::paintGrid(QPainter &p)
{
QRect borders(0, 0, width()-1, height()-1); //
QColor gridColor = ColorCells; //
gridColor.setAlpha(10); // , ()
p.setPen(gridColor);
double cellWidth = (double)width()/FirstGenSize; // ( )
for(double k = cellWidth; k <= width(); k += cellWidth)
p.drawLine(k, 0, k, height());
double cellHeight = (double)height()/FirstGenSize; // ( )
for(double k = cellHeight; k <= height(); k += cellHeight)
p.drawLine(0, k, width(), k);
p.drawRect(borders);
}
void GameWidget::paintFirstGen(QPainter &p)
{
double cellWidth = (double)width()/FirstGenSize;
double cellHeight = (double)height()/FirstGenSize;
for(int k=1; k <= FirstGenSize; k++) {
for(int j=1; j <= FirstGenSize; j++) {
if(FirstGen[k*FirstGenSize + j] == true) {
qreal left = (qreal)(cellWidth*j-cellWidth); //
qreal top = (qreal)(cellHeight*k-cellHeight); //
QRectF r(left, top, (qreal)cellWidth, (qreal)cellHeight);
p.fillRect(r, QBrush(ColorCells)); //
}
}
}
}
QColor GameWidget::masterColor()
{
return ColorCells;
}
void GameWidget::setMasterColor(const QColor &color)
{
ColorCells = color;
update();
}
| true |
c17f63ee73b8d473f8fd30c68715d2ecee733061 | C++ | nurtiasrahayu/tbfo-interpreter | /14117086_14117067_14117071/interpreter.cpp | UTF-8 | 5,905 | 2.828125 | 3 | [] | no_license | //Irma Safitri (14117067)
//Nurul Fauzia Azizah(14117071)
//Nurtias Rahayu (14117086)
#include <bits/stdc++.h>
using namespace std;
int matrix[19][128];
void setNull() {
matrix[0][32] = 0;
for(int i = 0 ; i < 128 ; i++){
matrix[7][i] = 7;
}
matrix[0][99] = 1;
matrix[1][101] = 2;
matrix[2][116] = 3;
matrix[3][97] = 4;
matrix[4][107] = 5;
matrix[0][67] = 1;
matrix[1][69] = 2;
matrix[2][84] = 3;
matrix[3][65] = 4;
matrix[4][75] = 5;
matrix[5][32] = 6;
matrix[6][32] = 6;
matrix[6][34] = 7;
matrix[6][40]=18;
matrix[6][41]=18;
matrix[6][42]=18;
matrix[6][43]=18;
matrix[6][45]=18;
matrix[6][47]=18;
matrix[6][48]=18;
matrix[6][49]=18;
matrix[6][50]=18;
matrix[6][51]=18;
matrix[6][52]=18;
matrix[6][53]=18;
matrix[6][54]=18;
matrix[6][55]=18;
matrix[6][56]=18;
matrix[6][57]=18;
matrix[18][40]=18;
matrix[18][41]=18;
matrix[18][42]=18;
matrix[18][43]=18;
matrix[18][45]=18;
matrix[18][47]=18;
matrix[18][48]=18;
matrix[18][49]=18;
matrix[18][50]=18;
matrix[18][51]=18;
matrix[18][52]=18;
matrix[18][53]=18;
matrix[18][54]=18;
matrix[18][55]=18;
matrix[18][56]=18;
matrix[18][57]=18;
matrix[18][32]=18;
matrix[18][59]=19;
matrix[7][34]=8;
matrix[8][32]=8;
matrix[8][59]=9;
matrix[0][115]=10;
matrix[10][101]=11;
matrix[11][108]=12;
matrix[12][101]=13;
matrix[13][115]=14;
matrix[14][97]=15;
matrix[15][105]=16;
matrix[16][32]=16;
matrix[16][59]=17;
matrix[0][83]=10;
matrix[10][69]=11;
matrix[11][76]=12;
matrix[12][69]=13;
matrix[13][83]=14;
matrix[14][65]=15;
matrix[15][73]=16;
}
bool operasi(char cek){
return ( cek=='+' || cek=='-' || cek=='*' || cek=='/' || cek=='(' || cek==')' );
}
bool digit(char cek){
return (cek >= '0' && cek <= '9');
}
int perintahoperasi(int x, int y, char z){
if(z=='+'){
return x+y;
}else if(z=='-'){
return x-y;
}else if(z=='*'){
return x*y;
}else{
return x/y;
}
}
int penting(char cek){
switch(cek){
case '+' :
case '-' : return 1;
case '*' :
case '/' : return 2;
case '(' :
case ')' : return 3;
default : return -1;
}
}
int init(string inputan){
stack<int> str;
stack<char> operatorr;
int sementara=0;
int i=0;
while(i<inputan.length()){
char karakter = inputan[i];
if(digit(karakter)){
sementara = (sementara*10) + (int)( karakter - '0');
}else if(operasi(karakter)){
if( karakter=='('){
operatorr.push(karakter);
sementara=0;
}else if(str.empty()){
str.push(sementara);
operatorr.push(karakter);
sementara=0;
}else if(karakter==')'){
str.push(sementara);
while(operatorr.top() != '('){
karakter=operatorr.top();
operatorr.pop();
sementara=str.top();
str.pop();
int pre = str.top();
str.pop();
sementara = perintahoperasi(pre,sementara, karakter);
str.push(sementara);
}
operatorr.pop();
str.pop();
}else{
char prec = operatorr.top();
if(prec=='('){
str.push(sementara);
operatorr.push(karakter);
sementara=0;
}else if(penting(karakter) > penting(prec)){
str.push(sementara);
operatorr.push(karakter);
sementara=0;
}else{
int prevval = str.top();
str.pop();
char prevop = operatorr.top();
operatorr.pop();
prevval=perintahoperasi(prevval,sementara,prevop);
str.push(prevval);
operatorr.push(karakter);
sementara=0;
}
}
}
i++;
}
while(!operatorr.empty()){
int prev = str.top();
str.pop();
char preop = operatorr.top();
operatorr.pop();
sementara = perintahoperasi(prev,sementara,preop);
}
return sementara;
}
bool salah(int states){
if(states < 0){
return true;
}else{
return false;
}
}
bool akhir(int states){
if(states == 9 || states == 17 || 19){
return true;
}else{
return false;
}
}
bool berakhir(int states){
if(states == 17){
return true;
}else{
return false;
}
}
void operasiii(string *x, char y){
*x = *x + y;
}
void kataaa(string *x, char y){
*x = *x + y;
}
void state(string x, bool *selesai){
int i = 0;
int state = 0;
string kata="\0";
string oper="\0";
while(i < x.length() && salah(state) == false){
state = matrix[state][x[i]];
if(state == 7 && x[i] != 34){
kataaa(&kata, x[i]);
}else if(state==18 && x[i] != 59){
operasiii(&oper,x[i]);
}
i++;
}
if(salah(state) == true || akhir(state) == false ){
kata = "\0";
cout << "Kode tidak sesuai dengan peraturan\n";
return;
}else{
if(berakhir(state) == true){
cout << "Terimakasih sudah menggunakan compiler ini";
*selesai = true;
}else if(state==19){
int sementara = init(oper);
cout << "> " << sementara << endl;
}else{
cout << "> " << kata << endl;
}
return;
}
}
void compile(){
string inputan;
bool selesai = false;
while(selesai == false){
cout <<"# ";
getline(cin,inputan);
state(inputan, &selesai);
}
}
void null(int matrix[19][128]){
for(int i = 0 ; i < 19 ; i++){
for(int j = 0 ; j < 128 ; j++){
matrix[i][j] = -1;
}
}
}
int main(){
null(matrix);
setNull();
compile();
return 0;
}
| true |
2125ba27e85965f75b266c18bddaa886c38546ee | C++ | antaires/animation-engine | /src/Math.cpp | UTF-8 | 21,291 | 3.0625 | 3 | [] | no_license | #include "Math.h"
#include <cmath>
#include <iostream>
// macro for matrix mult
#define M4D(aRow, bCol) \
a.v[0 * 4 + aRow] * b.v[bCol * 4 + 0] + \
a.v[1 * 4 + aRow] * b.v[bCol * 4 + 1] + \
a.v[2 * 4 + aRow] * b.v[bCol * 4 + 2] + \
a.v[3 * 4 + aRow] * b.v[bCol * 4 + 3]
// macro for matrix-vector mult
// performs dot product of row against provided column vec
#define M4V4D(mRow, x, y, z, w) \
x * m.v[0 * 4 + mRow] + \
y * m.v[1 * 4 + mRow] + \
z * m.v[2 * 4 + mRow] + \
w * m.v[3 * 4 + mRow]
// macro for transpose
#define M4SWAP(x, y) \
{float t = x; x = y; y = t; }
// macro for inverse of a mat4 to avoid lower order matrices
#define M4_3X3MINOR(x, c0, c1, c2, r0, r1, r2) \
(x[c0*4*r0] * (x[c1*4+r1] * x[c2*4+r2] - x[c1*4+r2] * \
x[c2*4+r1]) - x[c1*4+r0]*(x[c0*4+r1] * x[c2*4+r2] - \
x[c0*4+r2] * x[c2*4+r1]) + x[c2*4+r0]*(x[c0*4+r1] * \
x[c1*4+r2] - x[c0*4+r2] * x[c1*4+r1]))
// **********************//
// //
// vector2 operations //
// //
// **********************//
vec2 operator+(const vec2& a, const vec2& b)
{
return vec2(a.x + b.x, a.y + b.y);
}
vec2 operator-(const vec2& a, const vec2& b)
{
return vec2(a.x - b.x, a.y - b.y);
}
vec2 operator*(const vec2& v, float f)
{
return vec2(v.x * f, v.y * f);
}
float lenSqr(const vec2& v)
{
return (v.x * v.x) + (v.y * v.y);
}
float len(const vec2& v)
{
float lenSq = (v.x * v.x) + (v.y * v.y);
if (lenSq < VEC_EPSILON)
{
return 0.0f;
}
return std::sqrtf(lenSq);
}
void normalize(vec2& v)
{
float lenSq = (v.x * v.x) + (v.y * v.y);
if (lenSq < VEC_EPSILON)
{
return;
}
float invLen = 1.0f / std::sqrtf(lenSq);
v.x *= invLen;
v.y *= invLen;
}
vec2 normalized(const vec2& v)
{
float lenSq = (v.x * v.x) + (v.y * v.y);
if (lenSq < VEC_EPSILON)
{
return v;
}
float invLen = 1.0f / std::sqrtf(lenSq);
return vec2(v.x * invLen, v.y * invLen);
}
// **********************//
// //
// vector3 operations //
// //
// **********************//
vec3 operator+(const vec3& a, const vec3& b)
{
return vec3(a.x + b.x, a.y + b.y, a.z + b.z);
}
vec3 operator-(const vec3& a, const vec3& b)
{
return vec3(a.x - b.x, a.y - b.y, a.z - b.z);
}
// scaling
vec3 operator*(const vec3& v, float f)
{
return vec3(v.x * f, v.y * f, v.z * f);
}
float operator==(const vec3& a, const vec3& b)
{
vec3 diff(a - b);
return lenSqr(diff) < VEC_EPSILON;
}
float operator!=(const vec3& a, const vec3& b)
{
return !(a == b);
}
float dot(const vec3& a, const vec3& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
float lenSqr(const vec3& v)
{
return (v.x * v.x) + (v.y * v.y) + (v.z * v.z);
}
float len(const vec3& v)
{
float lenSq = (v.x * v.x) + (v.y * v.y) + (v.z * v.z);
if (lenSq < VEC_EPSILON)
{
return 0.0f;
}
return std::sqrtf(lenSq);
}
void normalize(vec3& v)
{
float lenSq = (v.x * v.x) + (v.y * v.y) + (v.z * v.z);
if (lenSq < VEC_EPSILON)
{
return;
}
float invLen = 1.0f / std::sqrtf(lenSq);
v.x *= invLen;
v.y *= invLen;
v.z *= invLen;
}
vec3 normalized(const vec3& v)
{
float lenSq = (v.x * v.x) + (v.y * v.y) + (v.z * v.z);
if (lenSq < VEC_EPSILON)
{
return v;
}
float invLen = 1.0f / std::sqrtf(lenSq);
return vec3(v.x * invLen, v.y * invLen, v.z * invLen);
}
float angle(const vec3& a, const vec3& b)
{
float aLenSq = (a.x * a.x) + (a.y * a.y) + (a.z * a.z);
float bLenSq = (b.x * b.x) + (b.y * b.y) + (b.z * b.z);
if (aLenSq < VEC_EPSILON || bLenSq < VEC_EPSILON)
{
return 0.0f;
}
float dot = a.x * b.x + a.y * b.y + a.z * b.z;
acosf(dot / (std::sqrtf(aLenSq) * std::sqrtf(bLenSq)));
}
// project a onto b (get part of a in direction of b)
vec3 project(const vec3& a, const vec3& b)
{
// a dot b divided by len b
float bLen = len(b);
if (bLen < VEC_EPSILON)
{
return vec3();
}
float scale = dot(a, b) / bLen;
return b * scale;
}
vec3 reject(const vec3& a, const vec3& b)
{
vec3 projection = project(a, b);
return a - projection;
}
// bounce reflection, where a 'bounces' off of
// plane and b is the plane's normal
vec3 reflect(const vec3& a, const vec3& b)
{
float bLen = len(b);
if(bLen < VEC_EPSILON)
{
return vec3();
}
float scale = dot(a, b) / bLen;
vec3 projection2 = b * (scale * 2);
return a - projection2;
}
// cross
vec3 operator*(const vec3& a, const vec3& b)
{
return vec3(
a.y * b.z - a.z * b.y
, a.z * b.x - a.x * b.z
, a.x * b.y - a.y * b.x
);
}
vec3 cross(const vec3& a, const vec3& b)
{
return vec3(
a.y * b.z - a.z * b.y
, a.z * b.x - a.x * b.z
, a.x * b.y - a.y * b.x
);
}
vec3 lerp(const vec3& s, const vec3& e, float t)
{
// straight line (so lenght is not constant in relation to t)
// always takes the shortest path from one vec to another
return vec3(
s.x + (e.x - s.x) * t
, s.y + (e.y - s.y) * t
, s.z + (e.z - s.z) * t
);
}
vec3 slerp(const vec3& s, const vec3& e, float t)
{
// arc between two vectors
if (t < 0.01f)
{
return lerp(s, e, t);
}
vec3 from = normalized(s);
vec3 to = normalized(e);
float theta = angle(from, to);
float sin_theta = sinf(theta);
float a = sinf((1.0f - t) * theta) / sin_theta;
float b = sinf(t * theta) / sin_theta;
return from * a + to * b;
}
vec3 nlerp(const vec3& s, const vec3& e, float t)
{
// approximates slerp, but isn't constant velocity
// faster to compute
vec3 linear(
s.x + (e.x - s.x) * t
, s.y + (e.y - s.y) * t
, s.z + (e.z - s.z) * t
);
return normalized(linear);
}
// **********************//
// //
// Matrix operations //
// //
// **********************//
bool operator==(const mat4& a, const mat4& b)
{
for(int i = 0; i < 16; ++i)
{
if (std::fabsf(a.v[i] - b.v[i]) > MAT_EPSILON)
{
return false;
}
}
return true;
}
mat4 operator+(const mat4& a, const mat4& b)
{
return mat4(
a.xx + b.xx, a.xy + b.xy, a.xz + b.xz, a.xw+b.xw
, a.yx + b.yx, a.yy + b.yy, a.yz + b.yz, a.yw+b.yw
, a.zx + b.zx, a.zy + b.zy, a.zz + b.zz, a.zw+b.zw
, a.tx + b.tx, a.ty + b.ty, a.tz + b.tz, a.tw+b.tw
);
}
mat4 operator*(const mat4& m, float f)
{
return mat4(
m.xx * f, m.xy * f, m.xz * f, m.xw * f
, m.yx * f, m.yy * f, m.yz * f, m.yw * f
, m.zx * f, m.zy * f, m.zz * f, m.zw * f
, m.tx * f, m.ty * f, m.tz * f, m.tw * f
);
}
mat4 operator*(const mat4& a, const mat4& b)
{
return mat4(
M4D(0,0), M4D(1,0), M4D(2,0), M4D(3,0)
, M4D(0,1), M4D(1,1), M4D(2,1), M4D(3,1)
, M4D(0,2), M4D(1,2), M4D(2,2), M4D(3,2)
, M4D(0,3), M4D(1,3), M4D(2,3), M4D(3,3)
);
}
vec4 operator*(const mat4& m, const vec4& v)
{
return vec4(
M4V4D(0, v.x, v.y, v.z, v.w)
, M4V4D(1, v.x, v.y, v.z, v.w)
, M4V4D(2, v.x, v.y, v.z, v.w)
, M4V4D(3, v.x, v.y, v.z, v.w)
);
}
vec3 transformVector(const mat4& m, const vec3& v)
{
return vec3(
M4V4D(0, v.x, v.y, v.z, 0.0f)
, M4V4D(1, v.x, v.y, v.z, 0.0f)
, M4V4D(2, v.x, v.y, v.z, 0.0f)
);
}
vec3 transformPoint(const mat4& m, const vec3& v)
{
return vec3(
M4V4D(0, v.x, v.y, v.z, 1.0f)
, M4V4D(1, v.x, v.y, v.z, 1.0f)
, M4V4D(2, v.x, v.y, v.z, 1.0f)
);
}
vec3 transformPoint(const mat4& m, const vec3& v, float& w)
{
// w is a reference to store value for w after execution
float _w = w;
w = M4V4D(3, v.x, v.y, v.z, _w);
return vec3(
M4V4D(0, v.x, v.y, v.z, _w)
, M4V4D(1, v.x, v.y, v.z, _w)
, M4V4D(2, v.x, v.y, v.z, _w)
);
}
// matrix * its inverse = identity
// thus, view matrix that transforms 3d objs to display onscreen
// is inverse of camera position & rotation
// useful to convert between row-major and column-major matrices
void transpose(mat4& m)
{
// flip every element of matrix across its main diagonal
M4SWAP(m.yx, m.xy);
M4SWAP(m.zx, m.xz);
M4SWAP(m.tx, m.xw);
M4SWAP(m.zy, m.yz);
M4SWAP(m.ty, m.yw);
M4SWAP(m.tz, m.zw);
}
mat4 transposed(const mat4& m)
{
return mat4(
m.xx, m.yx, m.zx, m.tx
, m.xy, m.yy, m.yz, m.ty
, m.xz, m.yz, m.zz, m.tz
, m.xw, m.yw, m.zw, m.tw
);
}
// determinant : recursive, always a scalar value, only square matrices
// have a determinant.
// * determinant remains the same if matrix transposed
// * minor of a matrix is determinant of some smaller matrix
// * a matrix of minors is a matrix where every element is the minor of the corresponding
// element from the input matrix
// * cofactor matrix : matrix of minors, where every element is mult by -1 to power of (i+J)
// to form a checkerboard matrix of pos(+) and neg(-) whith positive at top left
// Adjugate matrix = transpose of cofactor matrix
// INVERSE = divide adjugate of a matrix by its determinant
float determinant(const mat4& m)
{
return m.v[0] * M4_3X3MINOR(m.v, 1, 2, 3, 1, 2, 3)
- m.v[4] * M4_3X3MINOR(m.v, 0, 2, 3, 1, 2, 3)
+ m.v[8] * M4_3X3MINOR(m.v, 0, 1, 3, 1, 2, 3)
- m.v[12] * M4_3X3MINOR(m.v, 0, 1, 2, 1, 2, 3);
}
mat4 adjugate(const mat4& m)
{
// cof (M[i,j]) = Minor(M[i,j] * pow(-1, i+j)
mat4 cofactor;
cofactor.v[0] = M4_3X3MINOR(m.v, 1, 2, 3, 1, 2, 3);
cofactor.v[1] = - M4_3X3MINOR(m.v, 1, 2, 3, 0, 2, 3);
cofactor.v[2] = M4_3X3MINOR(m.v, 1, 2, 3, 0, 1, 3);
cofactor.v[3] = - M4_3X3MINOR(m.v, 1, 2, 3, 0, 1, 2);
cofactor.v[4] = - M4_3X3MINOR(m.v, 0, 2, 3, 1, 2, 3);
cofactor.v[5] = M4_3X3MINOR(m.v, 0, 2, 3, 0, 2, 3);
cofactor.v[6] = - M4_3X3MINOR(m.v, 0, 2, 3, 0, 1, 3);
cofactor.v[7] = M4_3X3MINOR(m.v, 0, 2, 3, 0, 1, 2);
cofactor.v[8] = M4_3X3MINOR(m.v, 0, 1, 3, 1, 2, 3);
cofactor.v[9] = - M4_3X3MINOR(m.v, 0, 1, 3, 0, 2, 3);
cofactor.v[10] = M4_3X3MINOR(m.v, 0, 1, 3, 0, 1, 3);
cofactor.v[11] = - M4_3X3MINOR(m.v, 0, 1, 3, 0, 1, 2);
cofactor.v[12] = - M4_3X3MINOR(m.v, 0, 1, 2, 1, 2, 3);
cofactor.v[13] = M4_3X3MINOR(m.v, 0, 1, 2, 0, 2, 3);
cofactor.v[14] = - M4_3X3MINOR(m.v, 0, 1, 2, 0, 1, 3);
cofactor.v[15] = M4_3X3MINOR(m.v, 0, 1, 2, 0, 1, 2);
return transposed(cofactor);
}
mat4 inverse(const mat4& m)
{
float det = determinant(m);
if (det == 0.0f)
{
std::cout<<"\nMatrix determinant is 0";
return mat4();
}
mat4 adj = adjugate(m);
return adj * (1.0f / det);
}
void invert(mat4& m)
{
float det = determinant(m);
if (det == 0.0f)
{
std::cout<<"\nMatrix determinant is 0";
m = mat4();
return;
}
m = adjugate(m) * (1.0f / det);
}
// ***************** //
// camera functions //
// ***************** //
mat4 frustum(float l, float r, float b, float t, float n, float f)
{
if( l == r || t == b || n == f )
{
std::cout<<"\nInvalid frustum";
return mat4();
}
return mat4(
(2.0f * n) / (r - 1), 0, 0, 0
, 0, (2.0f * n) / (t - b), 0, 0
, (r+l)/(r-l), (t+b)/(t-b), (-(f+n))/(f-n), -1
, 0, 0, (-2*f*n) / (f-n), 0
);
}
mat4 perspective(float fov, float aspect, float n, float f)
{
float ymax = n * std::tanf(fov * 3.14159265359f / 360.0f);
float xmax = ymax * aspect;
return frustum(-xmax, xmax, -ymax, ymax, n, f);
}
// for 2d or isometric games
mat4 ortho(float l, float r, float b, float t, float n, float f)
{
if( l == r || t == b || n == f )
{
std::cout<<"\nInvalid ortho";
return mat4();
}
return mat4(
2.0f / (r-l), 0, 0, 0
, 0, 2.0f / (t-b), 0, 0
, 0, 0, -2.0f / (f-n), 0
, -((r+l)/(r-l)), -((t+b)/(t-b)), -((f+n)/(f-n)), 1
);
}
// construct a view matrix
mat4 lookAt(const vec3& position, const vec3& target, const vec3& up)
{
vec3 f = normalized(target - position) * -1.0f;
vec3 r = cross(up, f);
// right handed
if (r == vec3(0, 0, 0))
{
std::cout<<"\nError in lookAt";
return mat4();
}
normalize(r);
vec3 u = normalized(cross(f, r));
// right handed
vec3 t = vec3(
-dot(r, position)
, -dot(u, position)
, -dot(f, position)
);
return mat4(
// transpose upper 3x3 matrix to invert it
r.x, u.x, f.x, 0
, r.y, u.y, f.y, 0
, r.z, u.z, f.z, 0
, t.x, t.y, t.z, 1
);
}
// **********************//
// //
// Quaternions //
// //
// **********************//
quat angleAxis(float angle, const vec3& axis)
{
vec3 norm = normalized(axis);
// divide by 2 to map quat range to sin/cos
// since quat has a period of 720 degrees
// and sin/cos has period of 360 degrees
float s = std::sinf(angle * 0.5f);
return quat(
norm.x * s
, norm.y * s
, norm.z * s
, std::cosf(angle * 0.5f)
);
}
quat fromTo(const vec3& from, const vec3& to)
{
// normalize and makes sure they are not the same vector
vec3 f = normalized(from);
vec3 t = normalized(to);
if (f == t){return quat();}
// check whether vecs are opposite each other
// if yes, most orthogonal axis of FROM vec
// can be used to create pure quaternion
else if (f == t * -1.0f)
{
vec3 ortho = vec3(1, 0, 0);
if (std::fabsf(f.y) < std::fabsf(f.x))
{
ortho = vec3(0, 1, 0);
}
if (std::fabsf(f.z) < std::fabs(f.y) && std::fabs(f.z) < std::fabsf(f.x))
{
ortho = vec3(0, 0, 1);
}
vec3 axis = normalized(cross(f, ortho));
return quat(axis.x, axis.y, axis.z, 0);
}
// create a half vec between FROM and TO vecs
// use cross prod of half vec and starting vec to calc
// axis of rotation and the dot product to find
// angle of rotation
vec3 half = normalized(f + t);
vec3 axis = cross(f, half);
return quat(
axis.x
, axis.y
, axis.z
, dot(f, half)
);
}
vec3 getAxis(const quat& quat)
{
return normalized(vec3(quat.x, quat.y, quat.z));
}
float getAngle(const quat& quat)
{
return 2.0f * std::acosf(quat.w);
}
quat operator+(const quat& a, const quat& b)
{
return quat(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
quat operator-(const quat& a, const quat& b)
{
return quat(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
quat operator*(const quat& a, float b)
{
return quat(a.x * b, a.y * b, a.z * b, a.w * b);
}
quat operator-(const quat& a)
{
return quat(-a.x, -a.y, -a.z, -a.w);
}
// a quaternion and its inverse rotate to the SAME SPOT
// but take different routes
bool operator==(const quat& left, const quat& right)
{
return (std::fabsf(left.x - right.x) <= QUAT_EPSILON
&& std::fabsf(left.y - right.y) <= QUAT_EPSILON
&& std::fabsf(left.z - right.z) <= QUAT_EPSILON
&& std::fabsf(left.w - right.w) <= QUAT_EPSILON);
}
bool operator!=(const quat& a, const quat& b)
{
return !(a==b);
}
bool sameOrientation(const quat& a, const quat& b)
{
return (std::fabsf(a.x - b.x) <= QUAT_EPSILON
&& std::fabsf(a.y - b.y) <= QUAT_EPSILON
&& std::fabsf(a.z - b.z) <= QUAT_EPSILON
&& std::fabsf(a.w - b.w) <= QUAT_EPSILON)
||
(std::fabsf(a.x + b.x) <= QUAT_EPSILON
&& std::fabsf(a.y + b.y) <= QUAT_EPSILON
&& std::fabsf(a.z + b.y) <= QUAT_EPSILON
&& std::fabsf(a.w + b.w) <= QUAT_EPSILON);
}
// like vectors, dot prod. measures how similar 2 quats are
float dot(const quat& a, const quat& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
// like vectors, squared length is same as dot product of quat with itself
// the length of a quat is the square root of the square length
float lenSq(const quat& q)
{
return q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
}
float len(const quat& q)
{
float lenSq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
if (lenSq < QUAT_EPSILON)
{
return 0.0f;
}
return std::sqrtf(lenSq);
}
// unit quaternions have a length of 1
// quats representing a rotation should always be unit quats
void normalize(quat& q)
{
float lenSq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
if (lenSq < QUAT_EPSILON)
{
return;
}
// inverse length
float i_len = 1.0f / std::sqrtf(lenSq);
q.x *= i_len;
q.y *= i_len;
q.z *= i_len;
q.w *= i_len;
}
quat normalized(const quat& q)
{
float lenSq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
if (lenSq < QUAT_EPSILON)
{
return quat();
}
float i_len = 1.0f / std::sqrtf(lenSq);
return quat(q.x * i_len
, q.y * i_len
, q.z * i_len
, q.w * i_len);
}
// inverse of a normalized quat is the conjugate
// the conjugate of a quat flips its axis of rotation
// to check if a quat is normalized: the squared length
// of a normalized quat is ALWAYS == 1
quat conjugate(const quat& q)
{
return quat(
-q.x
, -q.y
, -q.z
, q.w
);
}
// proper quat inverse is the conjugate divdied by
// squared length of the quat
quat inverse(const quat& q)
{
float lenSq = q.x * q.x + q.y * q.y + q.z * q.z + q.w * q.w;
if (lenSq < QUAT_EPSILON)
{
return quat();
}
float recip = 1.0f / lenSq;
return quat(-q.x * recip
, -q.y * recip
, -q.z * recip
, q.w * recip);
}
// mult opperation carried out right to left:
// the right quats rotation is applied first, then the left
quat operator*(const quat& q1, const quat& q2)
{
return quat(
q2.x*q1.w + q2.y*q1.z - q2.z*q1.y + q2.w*q1.x
, -q2.x*q1.z + q2.w*q1.x + q2.z*q1.x + q2.w*q1.y
, q2.x*q1.y - q2.y*q1.x + q2.z*q1.w + q2.w*q1.z
, -q2.x*q1.x - q2.y*q1.y - q2.z*q1.z + q2.w*q1.w
);
}
// to mult a vec & quats, need to turn the vec
// into a PURE quat, which is a quat where w = 0
// and the vec part is normalized
// the mult always yeilds vector that's rotated by the quat
vec3 operator*(const quat& q, const vec3& v)
{
return q.vector * 2.0f * dot(q.vector, v)
+ v * (q.scalar * q.scalar - dot(q.vector, q.vector))
+ cross(q.vector, v) * 2.0f * q.scalar;
}
// interpolation
// quats are a rotation, not an orientation
// every rotation can take long or short arc, with
// short being best usually. to pick shortest,
// neighborhooding is used to place quats in desired neighborhood
// if dot product of quats is +, shorter will be taken
// if -, longer will be taken (so negate 1 of the quats)
// to get shorter :
//if(dot(a,b) < 0.0f) b = -b;
// this is like a lerp, but not because it travels in an arc
// assumes both quats in desired neighborhood
quat mix(const quat& from, const quat& to, float t)
{
return from * (1.0f - t) + to * t;
}
// nlerp is a fast & good approx for spherical interpolation
// assumes both quats in desired neighborhood
quat nlerp(const quat& from, const quat& to, float t)
{
return normalized(from + (to - from) * t);
}
// to adjust angle of a quaternion, raise it to
// desired power. example: to adjust quat to only
// rotate halfway, raise to power of 0.5
// to raise a quat to a power, decompose quat into angle
// and an axis, then angle can be adjusted by power
// and a new quat built from the adjusted angle & axis
quat operator^(const quat& q, float f)
{
float angle = 2.0f * std::acosf(q.scalar);
vec3 axis = normalized(q.vector);
float halfCos = std::cosf(f * angle * 0.5f);
float halfSin = std::sinf(f * angle * 0.5f);
return quat(
axis.x * halfSin
, axis.y * halfSin
, axis.z * halfSin
, halfCos
);
}
// slerp - only use if consistent velocity required
// if back and end quats are close together, use nlerp
// // assumes both quats in desired neighborhood
quat slerp(const quat& start, const quat& end, float t)
{
if(std::fabsf(dot(start, end)) > 1.0f - QUAT_EPSILON)
{
return nlerp(start, end, t);
}
// could use conjugate instead of inverse since
// input vecs to slerp SHOULD BE NORMALIZED
quat delta = inverse(start) * end;
return normalized((delta ^ t) * start);
}
// rotation to lookAt
quat lookRotation(const vec3& direction, const vec3& up)
{
// find orthonormal basis vectors:
// object Forward
vec3 f = normalized(direction);
// desired up
vec3 u = normalized(up);
// right
vec3 r = cross(u, f);
// object up
u = cross(f, r);
// from world forward to object forward
quat worldToObject = fromTo(vec3(0, 0, 1), f);
// what direction is the new object up?
vec3 objectUp = worldToObject * vec3(0, 1, 0);
// from object up to desired up
quat u2u = fromTo(objectUp, u);
// rotate to forward direction first
// then twist to correct up
quat result = worldToObject * u2u;
return normalized(result);
}
// quat to mat4, simply mult world basis vectors
// (x, y, & z world axes) by the quat & store the
// results in the components of the matrix, in which
// 1st column is right vec
// 2nd column is up vec
// 3rd column is forward vec
mat4 quatToMat4(const quat& q)
{
vec3 r = q * vec3(1, 0, 0);
vec3 u = q * vec3(0, 1, 0);
vec3 f = q * vec3(0, 0, 1);
return mat4(
r.x, r.y, r.z, 0
, u.x, u.y, u.z, 0
, f.x, f.y, f.z, 0
, 0 , 0 , 0 , 1
);
}
// a matrix stores both rotation and scale data
// using same components, so need to normalize basis
// vectors and the cross product needs to be used to
// make sure vecs are orthogonal
quat mat4ToQuat(const mat4& m)
{
vec3 up = normalized(vec3(m.up.x, m.up.y, m.up.z));
vec3 forward = normalized(vec3(m.forward.x, m.forward.y, m.forward.z));
vec3 right = cross(up, forward);
up = cross(forward, right);
return lookRotation(forward, up);
}
| true |
1cb2625799c6322fad9384991d73d85c9e78a76b | C++ | Sl-Alex/CppLearn | /L10/bigint/bigint.cpp | UTF-8 | 10,295 | 3.390625 | 3 | [] | no_license | #include "bigint.h"
#include <algorithm>
#include <cstring>
BigInt::BigInt(int val)
{
mDigCnt = mGetLength(val);
mDigits = new int[mDigCnt];
mDigits[0] = 0;
unsigned int pos_val = abs(val);
int i = 0;
while (pos_val != 0)
{
mDigits[i++] = pos_val %10;
pos_val /= 10;
}
mNegative = (val < 0);
}
BigInt::~BigInt()
{
delete[] mDigits;
}
unsigned int BigInt::mGetLength(int val)
{
unsigned int pos_val = abs(val);
unsigned int res = 1;
while (pos_val >= 10)
{
pos_val /= 10;
res++;
}
return res;
}
BigInt::BigInt(const BigInt& val)
{
mDigCnt = val.mDigCnt;
mDigits = new int[mDigCnt];
mNegative = val.mNegative;
memcpy(mDigits, val.mDigits, mDigCnt*sizeof(int));
}
BigInt& BigInt::operator=(const BigInt& rhs)
{
if (this == &rhs) return *this; // handle self assignment
delete[] mDigits;
mDigCnt = rhs.mDigCnt;
mDigits = new int[mDigCnt];
mNegative = rhs.mNegative;
memcpy(mDigits, rhs.mDigits, mDigCnt*sizeof(int));
//assignment operator
return *this;
}
BigInt BigInt::operator+(const BigInt& rhs) const
{
// Calculate maximum number of digits required
unsigned int sz = std::max(mDigCnt, rhs.mDigCnt) + 1;
bool mAddition = !(mNegative ^ rhs.mNegative);
bool mSwapped = false;
BigInt num1;
BigInt num2;
BigInt res = *this;
/*
5 + 10 /// 5 + 10
5 + -10 /// - ( 10 - 5 ) (arguments are swapped)
-5 + 10 /// 10 - 5 (arguments are swapped)
-5 + -10 /// - ( 5 + 10 )
5 + 1 /// 5 + 1 ==> same
5 + -1 /// 5 - 1
-5 + 1 /// - (5 - 1)
-5 + -1 /// - (5 + 1) ==> same
*/
if (mAddition)
res.mNegative = mNegative;
else
{
if (compareArrays(mDigits,rhs.mDigits,mDigCnt,rhs.mDigCnt) > 0)
res.mNegative = mNegative;
else
{
mSwapped = true;
res.mNegative = rhs.mNegative;
}
}
if (mSwapped)
{
num2 = *this;
num1 = rhs;
}
else
{
num1 = *this;
num2 = rhs;
}
int ovl = 0;
// Reserve enough of free memory
res.mRealloc(sz);
// Calculate a sum
for (unsigned int i = 0; i < sz; ++i)
{
int tmp;
if (mAddition)
{
tmp = num1.mGetNumber(i) + num2.mGetNumber(i) + ovl;
}
else
{
tmp = num1.mGetNumber(i) - num2.mGetNumber(i) + ovl;
}
if (tmp < 0)
{
tmp = 10 + tmp;
ovl = - 1;
}
else
{
ovl = tmp / 10;
}
res.mDigits[i] = abs(tmp % 10);
}
// Update negative value
res.mNegative = ((*this).mNegative ^ rhs.mNegative);
// Reduce
res.mReduce();
return res;
}
BigInt BigInt::operator-(const BigInt& rhs) const
{
BigInt num2(rhs);
num2.mNegative = ! num2.mNegative;
return (*this) + num2;
}
BigInt BigInt::operator*(const BigInt& rhs) const
{
int num1cnt = mDigCnt;
int num2cnt = rhs.mDigCnt;
BigInt bigtmp(0);
BigInt sum(0);
int ovl;
int i,j;
// Calculate intermediates
for (i = 0; i < num2cnt; ++i)
{
ovl = 0;
bigtmp.mRealloc(num1cnt);
for (j = 0; j < num1cnt; ++j)
{
int tmp = mGetNumber(j)*rhs.mGetNumber(i) + ovl;
bigtmp.mDigits[j] = tmp % 10;
ovl = tmp / 10;
}
if (ovl)
{
bigtmp.mRealloc(bigtmp.mDigCnt + 1);
bigtmp.mDigits[bigtmp.mDigCnt - 1] = ovl;
}
for (j = 0; j < i; ++j)
{
bigtmp.mAppendRight(0);
}
bigtmp.mReduce();
sum += bigtmp;
bigtmp = 0;
}
// Update negative value
sum.mNegative = ((*this).mNegative ^ rhs.mNegative);
// Reduce
sum.mReduce();
return sum;
}
BigInt BigInt::operator/(const BigInt& rhs) const
{
return full_division((*this), rhs, NULL);
}
BigInt BigInt::operator%(const BigInt& rhs) const
{
BigInt res(0);
full_division((*this), rhs, &res);
return res;
}
void BigInt::mRealloc(unsigned int NewCnt)
{
// Check if it's necessary to reallocate memory
if (mDigCnt == NewCnt) return;
int * newNumbers = new int[NewCnt];
memcpy(newNumbers, mDigits, std::min(NewCnt, mDigCnt)*sizeof(int));
if (NewCnt > mDigCnt)
memset(&newNumbers[mDigCnt], 0, (NewCnt - mDigCnt) * sizeof(int));
mDigCnt = NewCnt;
// Update the pointer
delete[] mDigits;
mDigits = newNumbers;
}
void BigInt::mReduce(void)
{
int amount = 0;
int idx = mDigCnt - 1;
while ((idx > 0) && (mDigits[idx] == 0))
{
amount++;
idx--;
}
mRealloc(mDigCnt - amount);
if ((mDigCnt == 1) && (mDigits[0] == 0))
mNegative = false;
}
void BigInt::mAppendRight(int val)
{
++mDigCnt;
mRealloc(mDigCnt);
for (unsigned int i = mDigCnt - 1; i > 0; --i)
{
mDigits[i] = mDigits[i-1];
}
mDigits[0] = val;
}
int compareArrays(int * arr1, int * arr2, unsigned int sz1, unsigned int sz2)
{
if (sz1 != sz2)
return sz1 - sz2;
unsigned int idx = sz1;
while((arr1[idx - 1] == arr2[idx - 1]) && (idx > 0))
--idx;
if (idx == 0)
return 0;
else
return arr1[idx - 1] - arr2[idx - 1];
}
ostream& operator<<(ostream& os, const BigInt& val)
{
if (val.mNegative)
cout << "-";
for (unsigned int i = val.mDigCnt; i > 0; --i)
os << val.mDigits[i - 1];
return os;
}
BigInt operator-(const BigInt& val)
{
BigInt res(val);
res.mNegative = ! res.mNegative;
return res;
}
BigInt operator+(const BigInt& val)
{
return val;
}
BigInt full_division(const BigInt& lhs, const BigInt& rhs, BigInt * pRemainder)
{
BigInt res(0);
BigInt temp_res(0);
BigInt temp_next(0);
unsigned int cur_idx = lhs.mDigCnt;
// Fill for the very first time
if (rhs.mDigCnt > lhs.mDigCnt)
{
if (pRemainder != NULL)
*pRemainder = rhs;
return res;
}
for (unsigned int i = 0; i < rhs.mDigCnt; i++)
temp_next.mAppendRight(lhs.mDigits[--cur_idx]);
while (true)
{
if (compareArrays(temp_next.mDigits, rhs.mDigits, temp_next.mDigCnt, rhs.mDigCnt) < 0)
{
res.mAppendRight(0);
--cur_idx;
continue;
}
// Search for a good digit
int i;
BigInt last_res(0);
for (i = 1; i < 9; ++i)
{
temp_next.mReduce();
temp_res = rhs * i;
temp_res.mNegative = false;
if (compareArrays(temp_res.mDigits, temp_next.mDigits, temp_res.mDigCnt, temp_next.mDigCnt) > 0)
break;
last_res = temp_res;
}
res.mAppendRight(--i);
// Calculate the difference and add the next digit
temp_next = temp_next - last_res;
if (cur_idx > 0)
temp_next.mAppendRight(lhs.mDigits[--cur_idx]);
else
break;
}
if (pRemainder != NULL)
*pRemainder = temp_next;
res.mReduce();
res.mNegative = lhs.mNegative ^ rhs.mNegative;
return res;
}
BigInt BigInt::operator+=(const BigInt &rhs)
{
*this = (*this) + rhs;
return (*this);
}
BigInt BigInt::operator-=(const BigInt &rhs)
{
*this = (*this) - rhs;
return (*this);
}
BigInt BigInt::operator*=(const BigInt &rhs)
{
*this = (*this) * rhs;
return (*this);
}
BigInt BigInt::operator/=(const BigInt &rhs)
{
*this = (*this) / rhs;
return (*this);
}
BigInt operator+(const int &lhs, const BigInt &rhs)
{
BigInt tmp(lhs);
return tmp + rhs;
}
BigInt operator-(const int &lhs, const BigInt &rhs)
{
BigInt tmp(lhs);
return tmp - rhs;
}
BigInt operator*(const int &lhs, const BigInt &rhs)
{
BigInt tmp(lhs);
return tmp * rhs;
}
BigInt operator/(const int &lhs, const BigInt &rhs)
{
BigInt tmp(lhs);
return tmp / rhs;
}
bool BigInt::isConvertable(ConvType c)
{
bool isPossible = false;
switch(c){
case CONV_CHAR:
break;
case CONV_UCHAR:
break;
case CONV_SHORT:
break;
case CONV_USHORT:
break;
case CONV_INT:
break;
case CONV_UINT:
break;
case CONV_LONG:
break;
case CONV_ULONG:
break;
}
return isPossible;
}
bool BigInt::operator==(const BigInt &rhs) const
{
if (mNegative != rhs.mNegative) return false;
if (compareArrays(mDigits,rhs.mDigits,mDigCnt,rhs.mDigCnt) != 0)
return false;
return true;
}
bool BigInt::operator!=(const BigInt &rhs) const
{
return !((*this) == rhs);
}
bool BigInt::operator> (const BigInt &rhs) const
{
if (mNegative == false)
{
if (rhs.mNegative)
return true;
return (compareArrays(mDigits,rhs.mDigits,mDigCnt,rhs.mDigCnt) > 0);
}
if (rhs.mNegative == false)
return false;
return (compareArrays(mDigits,rhs.mDigits,mDigCnt,rhs.mDigCnt) < 0);
}
bool BigInt::operator< (const BigInt &rhs) const
{
if ((*this) == rhs) return false;
if ((*this) > rhs) return false;
return true;
}
bool BigInt::operator>=(const BigInt &rhs) const
{
return !((*this) < rhs);
}
bool BigInt::operator<=(const BigInt &rhs) const
{
return !((*this) > rhs);
}
BigInt& BigInt::operator++()
{
*this = (*this) + 1;
return *this;
}
BigInt BigInt::operator++(int)
{
BigInt tmp(*this);
*this = (*this) + 1;
return tmp;
}
BigInt& BigInt::operator--()
{
*this = (*this) - 1;
return *this;
}
BigInt BigInt::operator--(int)
{
BigInt tmp(*this);
*this = (*this) - 1;
return tmp;
}
int BigInt::mGetNumber(unsigned int idx) const
{
if (idx < mDigCnt)
return mDigits[idx];
return 0;
}
| true |
9856a62fb8e51fc8e6275f42a9fb00e8d90a0ca3 | C++ | NerdyCrow/OAP-sem1 | /Лаб 5/Lab№5 dop 2/Lab№5 dop 2/torgovlya.cpp | WINDOWS-1251 | 482 | 2.890625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
setlocale(LC_CTYPE, "rus");
float q, p;
int n=0;
float procent = 0.03;
cout << ": ";
cin >> q;
cout << " : ";
cin >> p;
while (p<q)
{
p = p+(p * procent);
n++;
}
cout << " : " << p << std::endl;
cout << " " << n << " ";
return 0;
} | true |
dce552a63e36bd5cede462b081814b89a6cbf03b | C++ | sahil2232/flipster-test | /chef and stones.cpp | UTF-8 | 377 | 2.640625 | 3 | [] | no_license | #include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int t;
cin >> t;
long long int n,k;
while(t--)
{
cin >> n;
cin >> k;
long long int i,a[n],b[n],maxVal=0;
for(i=0;i<n;i++)
cin >> a[i];
for(i=0;i<n;i++)
cin >> b[i];
for(i=0;i<n;i++)
{
if((k/a[i])*b[i]>=maxVal)
maxVal=(k/a[i])*b[i];
}
cout << maxVal << endl;
}
} | true |
e59df4a24e2ea89ae8289c6f37740569e7df4884 | C++ | CoyoteLeo/Cpp | /NTUST Object Oriented Programming Class/Homework/A1001/B10532013.cpp | UTF-8 | 1,306 | 3.59375 | 4 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
void printVector(vector<int> &result)
{
cout << result[0];
for (int i = 1; i < result.size(); ++i)
cout << " " << result[i];
cout << endl;
}
void recursiveCombination(vector<int> &stack, int *arrayPtr, int amount, int choose)
{
if (choose == 1)
{
for (int i = 0; i < amount; i++)
{
stack.push_back(arrayPtr[i]);
printVector(stack);
stack.pop_back();
}
}
else
{
for (int i = 0; i < amount; i++)
{
stack.push_back(arrayPtr[i]);
recursiveCombination(stack, arrayPtr + 1 + i, amount - 1 - i, choose - 1);
stack.pop_back();
}
}
}
void PrintCombination(int *arrayPtr, int amount, int choose)
{
vector<int> stack;
recursiveCombination(stack, arrayPtr, amount, choose);
}
#define ELEMENTS_FOR_COMBINATION 10
#define DLEMENTS_FOR_CHOICE 8
int main(void)
{
int *arrayPtr = new int[ELEMENTS_FOR_COMBINATION]; // Get all elements for combination
for (int i = 0; i < ELEMENTS_FOR_COMBINATION; ++i)
arrayPtr[i] = i + 1;
PrintCombination(arrayPtr, ELEMENTS_FOR_COMBINATION, DLEMENTS_FOR_CHOICE);
if (arrayPtr != NULL)
delete[] arrayPtr;
return 0;
} | true |
e2fbbc43ab22ba61d579c20000c5257c23703508 | C++ | jieshicheng/DataStructures | /BinaryTree_class/binaryTree.hpp | UTF-8 | 2,151 | 3.265625 | 3 | [] | no_license | #ifndef _BINARYTREE_
#define _BINARYTREE_
#include"binaryTreeNode.hpp"
#include<iostream>
using namespace std;
template<typename T> class binaryTree{
public:
virtual ~binaryTree() { }
virtual bool empty() const =0;
virtual int size() const =0;
virtual void preOrder(void (*)(binaryTreeNode<T> *)) =0;
virtual void inOrder(void (*)(binaryTreeNode<T> *)) =0;
virtual void postOrder(void (*)(binaryTreeNode<T> *)) =0;
};
//********************************************************************
template<typename T> class linkedBinaryTree : public binaryTree<T>{
typedef void (*Visit)(binaryTreeNode<T> *);
public:
//construct function
linkedBinaryTree() : root(nullptr),treeSize(0) { }
~linkedBinaryTree() { erase(); }
//ADT
bool empty() const { return treeSize == 0; }
int size() const { return treeSize; }
void preOrder(void (*theVisit)(binaryTreeNode<T> *))
{ visit = theVisit; preOrder(root); }
void inOrder(void (*theVisit)(binaryTreeNode<T> *))
{ visit = theVisit; inOrder(root); }
void postOrder(void (*theVisit)(binaryTreeNode<T> *))
{ visit = theVisit; postOrder(root); }
void erase()
{
postOrder(dispose);
root = NULL;
treeSize = 0;
}
private:
binaryTreeNode<T> *root;
int treeSize;
static Visit visit;
static void preOrder(binaryTreeNode<T> *);
static void inOrder(binaryTreeNode<T> *);
static void postOrder(binaryTreeNode<T> *);
static void dispose(binaryTreeNode<T> *t) { delete t; }
};
template<typename T>
typename linkedBinaryTree<T>::visit = NULL;
#endif
template<typename T>
void linkedBinaryTree<T>::preOrder(binaryTreeNode<T> *theRoot)
{
if( theRoot != NULL ){
linkedBinaryTree<T>::visit(theRoot);
preOrder(theRoot->left);
preOrder(theRoot->right);
}
}
template<typename T>
void linkedBinaryTree<T>::inOrder(binaryTreeNode<T> *theRoot)
{
if( theRoot != NULL ){
linkedBinaryTree<T>::visit(theRoot);
inOrder(theRoot->left);
inOrder(theRoot->right);
}
}
template<typename T>
void linkedBinaryTree<T>::postOrder(binaryTreeNode<T> *theRoot)
{
if( theRoot != NULL ){
linkedBinaryTree<T>::visit(theRoot);
postOrder(theRoot->left);
postOrder(theRoot->right);
}
}
| true |
1b60610c2bd0bea9de62c14561729515e49ffcf7 | C++ | wizleysw/backjoon | /9019/solve.cpp | UTF-8 | 1,536 | 2.78125 | 3 | [] | no_license | // https://www.acmicpc.net/problem/9019
// DSLR
// Written in C++ langs
// 2020. 03. 17.
// Wizley
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
long long N;
int A;
int B;
bool VISITED[10001]={0,};
void bfs(){
memset(VISITED, 0, sizeof(VISITED));
queue<pair<int, string>> que;
que.push(make_pair(A, ""));
VISITED[A] = true;
while(!que.empty()){
int cur = que.front().first;
string route = que.front().second;
que.pop();
if(cur == B){
cout << route << "\n";
break;
}
int cur_D = (cur * 2) % 10000;
if(!VISITED[cur_D]){
VISITED[cur_D] = true;
que.push(make_pair(cur_D, route+'D'));
}
int cur_S;
(cur == 0) ? cur_S = 9999 : cur_S = cur-1;
if(!VISITED[cur_S]){
VISITED[cur_S] = true;
que.push(make_pair(cur_S, route+'S'));
}
int cur_L = (cur % 1000) * 10 + (cur / 1000);
if(!VISITED[cur_L]){
VISITED[cur_L] = true;
que.push(make_pair(cur_L, route+'L'));
}
int cur_R = (cur % 10) * 1000 + (cur / 10);
if(!VISITED[cur_R]){
VISITED[cur_R] = true;
que.push(make_pair(cur_R, route+'R'));
}
}
}
int main(){
ios_base :: sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
for(int i=0; i<N; i++){
cin >> A >> B;
bfs();
}
return 0;
}
| true |
803ee14e2002b59b5db8319475383f7eceae701f | C++ | Askir/Wiiteboard | /QuadrangleMorphing.h | UTF-8 | 1,546 | 2.515625 | 3 | [] | no_license | #ifndef QuadrangleMorphing_h
#define QuadrangleMorphing_h
#include "Point.h"
#include "Rectangle.h"
using namespace uschi;
class QuadrangleMorphing {
private:
uschi::Rectangle QuadrangleMorphing::morphableQuadrangle;
uschi::Rectangle QuadrangleMorphing::finalSquare;
std::vector<uschi::Rectangle> QuadrangleMorphing::quadrangleHistory;
double QuadrangleMorphing::deformation(double x);
double QuadrangleMorphing::scaleX(double y);
double QuadrangleMorphing::scaleY(double x);
void QuadrangleMorphing::addQuadrangle(uschi::Rectangle rectangle);
double QuadrangleMorphing::getRotate();
void QuadrangleMorphing::transformation(uschi::Rectangle rectangle);
Point QuadrangleMorphing::pointTransformation(Point point);
void QuadrangleMorphing::rotation(uschi::Rectangle rectangle);
Point QuadrangleMorphing::pointRotation(Point point);
void QuadrangleMorphing::deformation(uschi::Rectangle rectangle);
Point QuadrangleMorphing::pointDeformation(Point point);
void QuadrangleMorphing::normalisation(uschi::Rectangle rectangle);
Point QuadrangleMorphing::pointNormalisation(Point point);
public:
QuadrangleMorphing::QuadrangleMorphing() { };
QuadrangleMorphing::QuadrangleMorphing(uschi::Rectangle quadrangle);
uschi::Rectangle QuadrangleMorphing::getFinalSquare();
void QuadrangleMorphing::setMorphableQuadrangle(uschi::Rectangle quadrangle);
void QuadrangleMorphing::startQuadrangleTransformation();
Point QuadrangleMorphing::startPointTransformation(Point point);
~QuadrangleMorphing() {};
};
#endif | true |
22c637b36e58214befb2921ec08b2151a5ed6f65 | C++ | hsinyinfu/OOP_RPG | /RpgPerson.h | UTF-8 | 1,037 | 2.828125 | 3 | [] | no_license | #ifndef RPGPERSON_H_INCLUDED
#define RPGPERSON_H_INCLUDED
#include "RpgCreature.h"
#include "Monster.h"
class RpgPerson: public RpgCreature{
public:
RpgPerson(std::string _name, int _maxHp, int _strength, int _defence, int _x, int _y, int _crits, int _level, int _experience, int _coin);
virtual ~RpgPerson();
int getX();
int getY();
void setPosition(int x, int y);
void move(int xMove, int yMove);
void setExperience(bool up_down,int value);
bool checkLevelUp();
void levelUp();
virtual void statusUp()=0;
virtual void printStatus()=0;
int getLevel();
int getExperience();
void setRequiredExp();
int getRequiredExp();
virtual void useSkill(char skillNumber,RpgPerson& player, Monster& monster)=0;
virtual void printSkill()=0;
int getCoin();
void setCoin(int _coin);
void recoverHp();
virtual std::string getJob()=0;
protected:
int level;
int experience;
int x;
int y;
int requiredExp;
int coin;
};
#endif // RPGPERSON_H_INCLUDED
| true |
55b00bcb2bf1ac7f5b3d7e3a31681a6cc8359e80 | C++ | samcrow/ColonyServer-v2 | /network/client.cpp | UTF-8 | 297 | 2.578125 | 3 | [] | no_license | #include "client.hpp"
//Init static members
int Client::allocationCount = 0;
Client::Client(QObject *parent) :
QTcpSocket(parent)
{
//Increment the allocation count and assign it as this one's ID
allocationCount++;
id = allocationCount;
}
int Client::getId() {
return id;
}
| true |
82109b9dbaeed23415672deb950e276c7606aa3e | C++ | jabc1/ProgramLearning | /C++/The_C++_Programming_language/string/basic_string.hpp | UTF-8 | 9,006 | 3.71875 | 4 | [] | no_license | /**
basic_string 基础串类
*/
template<class Char_T, class Tr = char_traits<Char_T>, class A = allocator<Char_T> >
class std::basic_string{
public:
// 类型成员
typedef Tr traits_type;
typedef typename Tr::char_type value_type;
typedef A allocator_type;
typedef typename A::size_type size_type;
typedef typename A::difference_type difference_type;
typedef typename A::reference reference;
typedef typename A::const_reference const_reference;
typedef typename A::pointer pointer;
typedef typename A::const_pointer const_pointer;
typedef implementation_defined iterator;
typedef implementation_defined const_iterator;
typedef std::reverse_iterator<iterator> reverse_iterator;
typedef atd::reverse_iterator<const_iterator> const_reverse_iterator;
// 迭代器
iterator begin();
const_iterator begin() const;
iterator end();
const_iterator end() const;
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
reverse_iterator rend();
const_reverse_iterator rend() const;
// 元素访问
const_reference operator[](size_type n) const; // 不带检查的访问
reference operator[](size_type n);
const_reference at(size_type n) const; // 带检查的访问
reference at(size_type n);
// 构造函数 (string不能使用字符或者整数去初始化)
explicit basic_string(const A &a = A());
basic_string(const basic_string &s, size_type pos = 0, size_type n = npos, const A& a = A());
basic_string(const Char_T *p, size_type n, const A &a = A());
basic_string(const Char_T *p, const A &a = A());
basic_string(size_type n, Char_T c, const A &a = A());
template<class In> basic_string(In first, In last, const A &a = A());
~basic_string();
static const size_type npos; // 表示“所有字符”
// 赋值
basic_string &operator=(const basic_string &s);
basic_string &operator=(const Char_T *p);
basic_string &operator=(Char_T c); // 字符不能用于构造函数,但是可以用于赋值
basic_string &assign(const basic_string &);
basic_string &assign(const basic_string &s, size_type pos, size_type n);
basic_string &assign(const Char_T *p, size_type n);
basic_string &assign(const Char_T *p);
basic_string &assign(size_type n, Char_T c);
template<class In> basic_string &assign(In first, In last);
// 到C风格字符串的转换
const Char_T *c_str() const;
const Char_T *data() const;
size_type copy(Char_T *p, size_type n, size_type pos = 0) const;
// 比较函数
int compare(const basic_string &s) const;
int compare(const Char_T *p) const;
int compare(size_type pos, size_type n, const basic_string &s) const;
int compare(size_type pos, size_type n, const basic_string &s, size_type pos2, size_type n2) const;
int compare(size_type pos, size_type n, const Char_T *p, size_type n2 = npos) const;
// 插入
basic_string &operator+=(const basic_string &s);
basic_string &operator+=(const Char_T *p);
basic_string &operator+=(Char_T c);
void push_back(Char_T c);
basic_string &append(const basic_string &s);
basic_string &append(const basic_string &s, size_type pos, size_type n);
basic_string &append(const Char_T *p, size_type n);
basic_string &append(const Char_T *p);
basic_string &append(size_type n, Char_T c);
template<class In> basic_string &append(In first, In last);
// 在(*this)[pos]之前添加字符
basic_string &insert(size_type pos, const basic_string &s);
basic_string &insert(size_type pos, const basic_string &s, size_type pos2, size_type n);
basic_string &insert(size_type pos, const Char_T *p, size_type n);
basic_string &insert(size_type pos, const Char_T *p);
basic_string &insert(size_type pos, size_type n, Char_T c);
// 在p之前添加字符
iterator insert(iterator p, Char_T c);
void insert(iterator p, size_type n, Char_T c);
template<class In> void insert(iterator p, In first, In last);
// 查找子串
size_type find(const basic_string &s, size_type i = 0) const;
size_type find(const Char_T *p, size_type i, size_type n) const;
size_type find(const Char_T *p, size_type i = 0) const;
size_type find(Char_T c, size_type i = 0) const;
size_type rfind(const basic_string &s, size_type i = npos) const;
size_type rfind(const Char_T *p, size_type i, size_type n) const;
size_type rfind(const Char_T *p, size_type i = npos) const;
size_type rfind(Char_T c, size_type i = npos) const;
size_type find_first_of(const basic_string &s, size_type i = 0) const;
size_type find_first_of(const Char_T *p, size_type i, size_type n) const;
size_type find_first_of(const Char_T *p, size_type i = 0) const;
size_type find_first_of(Char_T c, size_type i = 0) const;
size_type find_last_of(const basic_string &s, size_type i = npos) const;
size_type find_last_of(const Char_T *p, size_type i, size_type n) const;
size_type find_last_of(const Char_T *p, size_type i = npos) const;
size_type find_last_of(Char_T c, size_type i = npos) const;
size_type find_first_not_of(const basic_string &s, size_type i = 0) const;
size_type find_first_not_of(const Char_T *p, size_type i, size_type n) const;
size_type find_first_not_of(const Char_T *p, size_type i = 0) const;
size_type find_first_not_of(Char_T c, size_type i = 0) const;
size_type find_last_not_of(const basic_string &s, size_type i = npos) const;
size_type find_last_not_of(const Char_T *p, size_type i, size_type n) const;
size_type find_last_not_of(const Char_T *p, size_type i = npos) const;
size_type find_last_not_of(Char_T c, size_type i = npos) const;
// 替代
basic_string &replace(size_type i, size_type n, const basic_string &s);
basic_string &replace(size_type i, size_type n, const basic_string &s, size_type i2, size_type n2);
basic_string &replace(size_type i, size_type n, const Char_T *p, size_type n2);
basic_string &replace(size_type i, size_type n, const Char_T *p);
basic_string &replace(size_type i, size_type n, size_type n2, Char_T c);
basic_string &replace(iterator i, iterator i2, const basic_string &s);
basic_string &replace(iterator i, iterator i2, const Char_T *p, size_type n);
basic_string &replace(iterator i, iterator i2, const Char_T *p);
basic_string &replace(iterator i, iterator i2, size_type n, Char_T c);
template<class In> basic_string &replace(iterator i, iterator i2, In j, In j2);
// 从串中删除("用空串替换")
basic_string &erase(size_type i = 0; size_type n = npos);
iterator erase(iterator i);
iterator erase(iterator first, iterator last);
// 大小,容量
size_type size() const;
size_type max_size() const;
size_type length() const {
return size();
}
bool empty() const{
return size() == 0;
}
void resize(size_type n, Char_T c);
void resize(size_type n){
resize(n, Char_T());
}
size_type capacity() const;
void reserve(size_type res_arg = 0);
allocator_type get_allocator() const;
};
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
// 比较运算符
template<class Char_T, class Tr, class A>
bool operator==(const basic_string<Char_T, Tr, A> &s1, const basic_string<Char_T, Tr, A> &s2);
template<class Char_T, class Tr, class A>
bool operator==(const Char_T *str, const basic_string<Char_T, Tr, A> &s2);
template<class Char_T, class Tr, class A>
bool operator==(const basic_string<Char_T, Tr, A> &s1, const Char_T *str);
// != > < >= <= 如此类似
// 拼接
template<class Char_T, class Tr, class A>
basic_string<Char_T, Tr, A>
operator+(const basic_string<Char_T, Tr, A> &s, const basic_string<Char_T, Tr, A> &s2);
template<class Char_T, class Tr, class A>
basic_string<Char_T, Tr, A>
operator+(const Char_T *str, const basic_string<Char_T, Tr, A> &s);
template<class Char_T, class Tr, class A>
basic_string<Char_T, Tr, A>
operator+(const basic_string<Char_T, Tr, A> &s, const Char_T *str);
template<class Char_T, class Tr, class A>
basic_string<Char_T, Tr, A>
operator+(Char_T ch, const basic_string<Char_T, Tr, A> &s);
template<class Char_T, class Tr, class A>
basic_string<Char_T, Tr, A>
operator+(const basic_string<Char_T, Tr, A> &s, Char_T ch);
// I/O操作
template<class Char_T, class Tr, class A>
basic_istream<Char_T, Tr> &operator>>(basic_istream<Char_T, Tr) &bis, basic_string<Char_T, Tr, A> &s);
template<class Char_T, class Tr, class A>
basic_ostream<Char_T, Tr> &operator<<(basic_ostream<Char_T, Tr> &bis, const basic_string<Char_T, Tr, A> &s);
template<class Char_T, class Tr, class A>
basic_istream<Char_T, Tr> &getline(basic_istream<Char_T, Tr> &bis, basic_string<Char_T, Tr, A> &s, Char_T eol);
template<class Char_T, class Tr, class A>
basic_istream<Char_T, Tr> &getline(basic_istream<Char_T, Tr> &bis, basic_string<Char_T, Tr, A> &s);
template<class Char_T, class Tr, class A>
void swap(basic_string<Char_T, Tr, A> &s1, basic_string<Char_T, Tr, A> &s2); | true |
3e27c42c9cc20ca2935b41a376f566e9634fdacd | C++ | Molv1659/Hotel_reservation_system | /customerregestrationdlg.cpp | UTF-8 | 1,371 | 2.53125 | 3 | [] | no_license | #include "customerregestrationdlg.h"
#include "ui_customerregestrationdlg.h"
#include<QMessageBox>
extern QHash<QString,Customer*> customerInfo;//customerID
CustomerRegestrationDlg::CustomerRegestrationDlg(QWidget *parent) :
QDialog(parent),
ui(new Ui::CustomerRegestrationDlg)
{
ui->setupUi(this);
this->setWindowTitle("Customer Registration");
}
CustomerRegestrationDlg::~CustomerRegestrationDlg()
{
delete ui;
}
void CustomerRegestrationDlg::on_pushButton_clicked()
{
if(ui->lineEdit->text()!=NULL&&ui->lineEdit_2->text()!=NULL&&ui->lineEdit_3->text()!=NULL)
{
if(customerInfo[ui->lineEdit->text()]!=NULL)
{
QMessageBox::information(NULL, "消息", "该用户名已被注册", QMessageBox::Yes);
}
else
{
Customer*cu=new Customer(ui->lineEdit->text(),ui->lineEdit_2->text(),ui->lineEdit_3->text());
customerInfo[ui->lineEdit->text()]=cu;
QMessageBox::information(NULL, "消息", "注册成功", QMessageBox::Yes);
this->close();
}
}
else
{
QMessageBox::warning(this, tr("警告"),
tr("请将信息填写完整"),
QMessageBox::Yes);
}
}
void CustomerRegestrationDlg::on_pushButton_2_clicked()
{
this->close();
}
| true |
bb25b72b9e2d860b2246c50ddd8fac1e888f04c7 | C++ | ArielOliveira/Opengl2DBasics | /Opengl2DBasics/DiceFace.h | UTF-8 | 739 | 2.796875 | 3 | [] | no_license | #pragma once
#include <vector>
using std::vector;
#include "Square.h"
#include "Circle.h"
using glm::mat4;
class DiceFace : public Object {
private:
const float dicePos[4] = {
.0f, .0f,
-.35f, .35,
};
Square *square;
vector<Circle*>* circles;
void FillDice();
void GenBuffer();
public:
DiceFace(int const& diceNumber, glm::mat4 const& position, glm::mat4 const& rotation, glm::mat4 const& scale);
DiceFace(DiceFace const& face);
~DiceFace();
void Bind();
void Draw(const unsigned int& uniform);
void Translate(glm::vec3 const& translation);
void Scale(glm::vec3 const& _scale);
int diceNumber;
};
| true |
1525ab4748bb28fb37f89f2e1f877f3dc83e2fc2 | C++ | gchlebus/Life-Universalis | /GameEngine/GameEngine/Transform.h | UTF-8 | 4,600 | 3.09375 | 3 | [] | no_license | #pragma once
#include "GlobalHeaders.h"
#define RAD_TO_DEG(rad) (float)((rad)*(180)/(M_PI))
#define DEG_TO_RAD(deg) (float)((deg)*(M_PI)/(180))
class GAMEENGINE_EXPORT Transform
{
public:
//! Default c'tor. Sets local position to (0, 0, 0), local Euler angles to (0, 0, 0) and
//! local scale to (1, 1, 1).
Transform();
//! Sets local position to (0, 0, 0), local Euler angles to (0, 0, 0) and
//! local scale to (1, 1, 1).
void reset();
//! Sets world rotation and world position of the transform.
//! \param forward - Z versor in world coordinates.
//! \param left - X versor in world coordinates.
//! \param pos - World position.
void fromForwardLeftPosition(const Vector3 &forward, const Vector3 &left,
const Vector3 &pos);
//! Makes 'this' transform to be child of 'parent' transform.
void setParent(Transform *parent);
//! Sets local position of the transform to 'pos'.
void setLocalPosition(const Vector3 &pos);
//! \return Local position of the transform.
const Vector3& getLocalPosition() const;
//! Sets world position of the transform to 'pos'.
void setWorldPosition(const Vector3 &pos);
//! \return World position of the transform.
const Vector3 getWorldPosition() const;
//! Moves the transform by 'translationVec'.
void translate(const Vector3 &translationVec);
//! \return Quaternion describing local rotation of the transform.
const Quaternion getLocalQuaternion() const;
//! Sets local rotation of the transform to 'quaternion'.
//! \param quaternion - normalized quaternion defining rotation.
void setLocalQuaternion(const Quaternion &quaternion);
//! \return Quaternion describing world rotation of the transform.
const Quaternion getWorldQuaternion() const;
//! Sets world rotation of the transform to 'quaternion'.
//! \param quaternion - normalized quaternion defining rotation.
void setWorldQuaternion(const Quaternion &quaternion);
//! \return Euler angles in radians defining local rotation of the transform.
const Vector3 getLocalEulerAngles() const;
//! Sets local rotation of the transform according to 'eulerAngles'.
//! \param eulerAngles - Vector containing euler angles around x, y and z in radians.
void setLocalEulerAngles(const Vector3 &eulerAngles);
//! \return Euler angles in radians defining world rotation of the transform.
const Vector3 getWorldEulerAngles() const;
//! Sets world rotation of the transform according to 'eulerAngles'.
//! \param eulerAngles - Vector containing euler angles around x, y and z in radians.
void setWorldEulerAngles(const Vector3 &eulerAngles);
//! Rotates the transform by 'eulerAngles'. Note that the rotation order is ZXY and the
//! rotation axes XYZ are taken from the static frame, i.e. the one before rotation.
void rotate(const Vector3 &eulerAngles);
//! Rotates the transform given axis and angle.
//! \param axis - Normalized vector starting at local coordinate system origin.
//! \param angle - Rotation angle in radians.
void rotate(const Vector3 &axis, float angle);
//! \return Local scale of the transform.
const Vector3 getLocalScale() const;
//! Sets local scale of the transform to 'scale'.
void setLocalScale(const Vector3 &scale);
//! \return Z versor of the transform in world coordinates.
const Vector3 getForwardVersor() const;
//! \return X versor of the transform in world coordinates.
const Vector3 getLeftVersor() const;
//! \return Y versor of the transform in world coordinates.
const Vector3 getUpVersor() const;
//! \return Matrix that transforms a point from world space to local space.
const Matrix4& getWorldToLocalMatrix() const;
//! \return Matrix that transforms a point from local space to world space.
const Matrix4& getLocalToWorldMatrix() const;
private:
void _computeTransformationMatrices() const;
const Vector3 _getParentWorldPosition() const;
const Matrix4 _getParentWorldToLocalMatrix() const;
const Quaternion _convertEulerAnglesToQuaternion(const Vector3 &eulerAngles);
// Local position of the transform.
Vector3 _localPosition;
// Quaternion to store the local rotation of the transform.
Quaternion _localQuaternion;
// Local scale of the transform.
Vector3 _localScale;
//! Flag indicating whether the cached matrices need to be recomputed.
mutable bool _shouldComputeMatrices;
//! Matrix that transforms a point from world space to local space.
mutable Matrix4 _worldToLocalMatrix;
//! Matrix that transforms a point from local space to world space.
mutable Matrix4 _localToWorldMatrix;
//! Parent transform of this transform.
Transform *_parent;
};
| true |
8926bb89b9243dc02a4f4f5f15d9807356ef2a92 | C++ | SidicleyRibeiro/padmec-amr-2.0 | /src/error-analysis/CalculateSmoothGradientNorm_2D.cpp | UTF-8 | 2,978 | 2.765625 | 3 | [] | no_license | /*
* CalculateSmoothGradientNorm.cpp
*
* Created on: 24/04/2012
* Author: rogsoares
*/
#include "ErrorAnalysis_2D.h"
/*
* Calculate smooth gradient Norm (SGN):
* SNG = sum((|gradSw_I|+|gradSw_J|+|gradSw_K|)/3.0)^2
* where sum is for each triangle element with nodes I, J, K.
*/
void ErrorAnalysis_2D::calculate_SmoothedGradientNorm(pMesh theMesh, SimulatorParameters *pSimPar, GeomData* pGCData, FuncPointer_GetGradient getGradient, FIELD field){
double grad_0[3], grad_1[3], grad_2[3], SGN, dot_0, dot_1, dot_2;
int dom_counter, idx, idx0, idx1, idx2, idx0_global, idx1_global, idx2_global;
pEntity face;
dom_counter = 0;
for (SIter_const dom=pSimPar->setDomain_begin(); dom!=pSimPar->setDomain_end();dom++){
SGN = .0;
idx = 0;
FIter fit = M_faceIter (theMesh);
while ( (face = FIter_next(fit)) ){
if(!theMesh->getRefinementDepth(face)){
pGCData->getFace(dom_counter,idx,idx0,idx1,idx2,idx0_global,idx1_global,idx2_global);
getGradient(field,dom_counter,idx0,idx0_global,grad_0);
getGradient(field,dom_counter,idx1,idx1_global,grad_1);
getGradient(field,dom_counter,idx2,idx2_global,grad_2);
dot_0 = inner_product(grad_0,grad_0,2);
dot_1 = inner_product(grad_1,grad_1,2);
dot_2 = inner_product(grad_2,grad_2,2);
SGN += (dot_0 + dot_1 + dot_2)/3.0;
idx++;
}
}
FIter_delete(fit);
// Allow only one loop over elements to calculate error based on saturation field.
// Saturation gradient is not per domain like pressure.
if (field == SATURATION){
break;
}
dom_counter++;
}
setSmoothedGradNorm(sqrt(SGN));
}
void ErrorAnalysis_2D::calculate_SmoothedGradientNorm_Singularity(pMesh theMesh, SimulatorParameters *pSimPar, GeomData* pGCData, FuncPointer_GetGradient getGradient, FIELD field){
double grad_0[3], grad_1[3], grad_2[3], SGN, dot_0, dot_1, dot_2, gradDiff;
int idx, idx0, idx1, idx2, idx0_global, idx1_global, idx2_global, i, dom_counter ;
pEntity face;
gradDiff = .0;
dom_counter = 0;
for (SIter_const dom=pSimPar->setDomain_begin(); dom!=pSimPar->setDomain_end();dom++){
SGN = .0;
idx = 0;
FIter fit = M_faceIter (theMesh);
while ( (face = FIter_next(fit)) ){
if(!theMesh->getRefinementDepth(face) && !this->isSingular(face)){
pGCData->getFace(dom_counter,idx,idx0,idx1,idx2,idx0_global,idx1_global,idx2_global);
getGradient(field,dom_counter,idx0,idx0_global,grad_0);
getGradient(field,dom_counter,idx1,idx1_global,grad_1);
getGradient(field,dom_counter,idx2,idx2_global,grad_2);
dot_0 = inner_product(grad_0,grad_0,2);
dot_1 = inner_product(grad_1,grad_1,2);
dot_2 = inner_product(grad_2,grad_2,2);
SGN += (dot_0 + dot_1 + dot_2)/3.0;
idx++;
}
}
FIter_delete(fit);
// Allow only one loop over elements to calculate error based on saturation field. Saturation gradient is not per domain like pressure.
if (field == SATURATION){
break;
}
dom_counter++;
}
setSmoothedGradNorm_Singularity(sqrt(SGN));
}
| true |
2807bbf3c481ace9a2b41fdb5fc93a27b64b36c9 | C++ | code-abil/DSA | /subset_sum_dp.cpp | UTF-8 | 1,488 | 3.328125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define int long long
// Considering that we call the below function only when we have a soln.
void print_values(int val[],int subset[][100],int i,int j)
{
if(subset[i][j]==0)
{
cout<<"No possible subset\n";
return;
}
if(i==0 || j==0)
return ;
if(subset[i-1][j]==1)
print_values(val,subset,i-1,j);
else
{
cout<<val[i]<<" ";
print_values(val,subset,i-1,j-val[i]);
}
}
main()
{
int sum=11;
int n=5;
int val[]={-1,2,3,7,8,10};
// first element being a dummy.
int subset[100][100];
// Matrix being built is of the form
// col:sum,row:val
// subset[val][sum]
// Corner cases can be : having sum as 0.
// With no values, we can't get any sum.
for(int i=0;i<=sum;i++)
subset[0][i]=0;
// With sum as 0, we can achieve the sum as we build a empty subset
for(int i=0;i<=n;i++)
subset[i][0]=1;
//subset[0][0]=1 (As we can build a empty subset which totals to 0.)
for(int i=1;i<=n;i++)
{
for(int j=1;j<=sum;j++)
{
if(j>=val[i])
subset[i][j]=subset[i-1][j]||subset[i-1][j-val[i]];
else
subset[i][j]=subset[i-1][j];
}
}
for(int i=0;i<=n;i++)
{
for(int j=0;j<=sum;j++)
cout<<subset[i][j]<<" ";
cout<<endl;
}
print_values(val,subset,n,sum);
} | true |
a1c9e14af17665504109341ebc6ba5ce84ae0507 | C++ | Tinsed/8_puzzle | /node.cpp | UTF-8 | 372 | 2.703125 | 3 | [] | no_license | #include <node.h>
Node::Node(){
state = new State(0x23175468,8);
pParentNode = nullptr;
iAction = -1;
iPathCost = 0;
iDepth =0;
}
Node::Node(State* s, Node* parrent, int act, int cost, int depth){
state = s;
pParentNode = parrent;
iAction = act;
iPathCost = cost;
iDepth = depth;
}
Node::~Node(){
if(state!=nullptr)
delete state;
pParentNode = nullptr;
}
| true |
5b2510c28c2d4112ffcc92cf4255397f9591ac13 | C++ | RWang/oklibrary | /Experimentation/Investigations/Cryptography/AdvancedEncryptionStandard/plans/FieldMulInvestigations.hpp | UTF-8 | 8,693 | 2.609375 | 3 | [] | no_license | // Matthew Gwynne, 6.8.2009 (Swansea)
/* Copyright 2009 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary is free software; you can redistribute
it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation and included in this library; either version 3 of the
License, or any later version. */
/*!
\file Experimentation/Investigations/Cryptography/AdvancedEncryptionStandard/plans/FieldMulInvestigations.hpp
\brief On investigations into the AES field multiplications
\todo Connections
<ul>
<li> See Investigations/BooleanFunctions/plans/Permutations.hpp for
general investigations on permutations of {0,1}^n. </li>
</ul>
\todo Number of prime implicates for field multiplications
<ul>
<li> Currently, within the SAT translation, the most powerful representation
of the Field operations used within the AES SAT translation (such as
multiplication by 02, 03 etc within Rijndael's byte field, see
ComputerAlgebra/Cryptology/Lisp/Cryptanalysis/Rijndael/plans/FieldOperationsAnalysis.hpp)
is the canonical translation using new variables (see "dualts_fcl" in
ComputerAlgebra/Satisfiability/Lisp/ClauseSets/Constructions.mac).
</li>
<li> However, the most powerful representation of any boolean function, not
considering size of the translation is always the set of prime implicates.
</li>
<li> In general, the set of prime implicates for a given boolean function is
prohibitively large, such as is the case with the Sbox with > 100000
clauses. </li>
<li> This is not always the case though, as the size and structure of the
set of prime implicates for each of the field multiplication functions must
be checked. </li>
<li> Small set of prime implicates would provide much better representations
than "dualts_fcl" produces, as then there is no problem that the SAT solver
might somehow get "lost" branching or basing it's heuristics on the new
variables, and if the set of prime implicates is small enough, it might
even be smaller than the "dualts_fcl" translation. </li>
<li> Given an integer representation (??? what is an "integer
representation" ? ACTION required from MG), the full CNF representation of
the boolean function for multiplication by a constant factor n in Rijndael's
byte-field, where n is an integer (see XXX), can be generated by:
\verbatim
output_rijnmult_fullcnf_stdname(n);
\endverbatim
and the prime implicates can be generated using:
\verbatim
QuineMcCluskey-n16-O3-DNDEBUG AES_byte_field_mul_full_n.cnf > AES_byte_field_mul_full_n.pi
\endverbatim
and getting the minimum and maximum prime-clause lengths:
USE a general tool here! For example the OKsolver_2002. ACTION required from
MG.
\verbatim
N=2;cat AES_byte_field_mul_full_${N}.pi | while read x; do CLAUSECOUNT=`echo $x | wc -w`; echo `expr $CLAUSECOUNT - 1`; done | sort > AES_byte_field_mul_full_${N}.stats; cat AES_byte_field_mul_full_${N}.stats | head -n 1; cat AES_byte_field_mul_full_${N}.stats | tail -n 1
\endverbatim
</li>
<li> Multiplication by 1: </li>
<li> Multiplication by 2:
<ul>
<li> There are 58 prime implicates for multiplication by 2. </li>
<li> The minimal size of a prime clause is 2. </li>
<li> The maximal size of a prime clause is 4. </li>
<li> This is to be expected (???) as multiplication by 2 is a very simple
operation. </li>
<li> In this case, representing multiplication by 02 by all it's prime
implicates seems the only real solution, given such a small number. </li>
</ul>
</li>
<li> Multiplication by 3:
<ul>
<li> There are 5048 prime implicates for multiplication by 3. </li>
<li> The minimal size of a prime clause is 3. </li>
<li> The maximal size of a prime clause is 9. </li>
</ul>
</li>
<li> Multiplication by 9:
<ul>
<li> There are 7840 prime implicates for multiplication by 9. </li>
<li> The minimal size of a prime clause is 3. </li>
<li> The maximal size of a prime clause is 9. </li>
</ul>
</li>
<li> Multiplication by 11:
<ul>
<li> There are 15008 prime implicates for multiplication by 11. </li>
<li> The minimal size of a prime clause is 4. </li>
<li> The maximal size of a prime clause is 9. </li>
</ul>
</li>
<li> Multiplication by 13:
<ul>
<li> There are 15312 prime implicates for multiplication by 13. </li>
<li> The minimal size of a prime clause is 4. </li>
<li> The maximal size of a prime clause is 9. </li>
</ul>
</li>
<li> Multiplication by 14:
<ul>
<li> There are 14300 prime implicates for multiplication by 14. </li>
<li> The minimal size of a prime clause is 3. </li>
<li> The maximal size of a prime clause is 9. </li>
</ul>
</li>
<li> We need to handle all multiplications; and we need the size (and
number) of minimum CNF representations. </li>
<li> It would be nice here to be able to read the clause-sets into the
Maxima system, where we have statistics_fcl etc. (see "Input and output" in
ComputerAlgebra/Satisfiability/Lisp/ClauseSets/plans/general.hpp). </li>
</ul>
\todo Minimisation of the field operations
<ul>
<li> See "Minimisation" in
OKlib/Satisfiability/FiniteFunctions/plans/general.hpp . </li>
<li> We can use the QCA package, given in
Buildsystem/ExternalSources/SpecialBuilds/plans/R.hpp to compute
the minimum sized CNF or DNF clause-set representation. </li>
<li> This should be possible using the following code:
\verbatim
######## In Maxima #######
generate_full_byteop_tt(byteop) :=
map(
lambda([ce],
append(
int2polyadic_padd(ce[1],2,8),
int2polyadic_padd(ce[2],2,8),
if byteop(ce[1]) = ce[2] then [1] else [0]))
,cartesian_product(setmn(0,255),setmn(0,255)))$
rijn_lookup_mul : lambda([b],
buildq([b],lambda([a], aes_field_mul_data[b,a])))$
mulConstant : 2;
with_stdout(sconcat("RijndaelMul",mulConstant,".tt"), block(
apply(print, endcons("O",create_list(i,i,1,16))),
for tt_line in generate_full_byteop_tt(rijn_lookup_mul(mulConstant)) do
apply(print,tt_line)
))$
######## In R ###########
oklib_load_all()
library(QCA)
mulConstant = 2
mul_tt = read.table(paste("RijndaelMul",mulConstant,".tt",sep=""),header=TRUE)
eqmcc(mul_tt, outcome="O", expl.0=TRUE)
\endverbatim
where mulConstant can be set in each case to one of 2,3 for the
multiplication in the encryption direction, and 9,11,13 or 14 for
the multiplications used when the decryption of MixColumn is
included in the translation. </li>
<li> Even with multiplication by 02, the R/QCA system still runs out of
memory (see "Minimisation" in
OKlib/Satisfiability/FiniteFunctions/plans/general.hpp for details). </li>
<li> Another possibility is to minimise the field multiplications by 02
using the minimum transversal functions present in the Maxima subsystem.
Assuming the prime implicates for multiplication by 02 have been generated
like so:
\verbatim
output_rijnmult_fullcnf_stdname(2);
\endverbatim
in Maxima, and then from the shell
\verbatim
QuineMcCluskey-n16-O3-DNDEBUG AES_byte_field_mul_full_2.cnf > AES_Mul2_PI.cnf
\endverbatim
the following, in Maxima, should produce a set of all minimum
representations
\verbatim
oklib_plain_include("stringproc")$
read_fcs_f(n) := block([fh, line, ll, cs : [], l,b,c],
fh : openr(n),
while stringp(line : readline(fh)) do (
ll : tokens(line),
if length(ll) >= 1 then
if not(first(ll) = "c" or first(ll) = "p") then
cs : cons(setify(rest(map(parse_string,ll),-1)), cs)
),
cs : setify(cs),
return(cs_to_fcs(cs))
)$
Mul2PI : read_fcs("AES_Mul2_PI.cnf")$
MTHG2 : minimum_transversals_bvs_hg(ghg2hg(subsumption_ghg(Mul2[2], rijnmult_fullcnf_fcs(2)[2])))$
\endverbatim
</li>
<li> For multiplication by 02, the above Maxima function returns 102
minimum CNF representations of size 20 in 2190.1490 seconds. </li>
<li> An example of such a minimum representation is:
\verbatim
{{-16,-15,-8},{-16,-13,-6},{-16,6,13},{-16,8,15},{-15,1,8},{-14,7},{-13,1,6},
{-12,-5,-1},{-12,5,16},{-11,4},{-10,3},{-9,2},{-8,1,15},{-7,14},{-6,1,13},
{-5,12,16},{-4,11},{-3,10},{-2,9},{-1,5,12}}
\endverbatim
</li>
<li> Most (90) of the minimum representations contain 8 clauses of size 2,
and 12 clauses of size 3. There are then a further twelve clause-sets
where there are only 8 clause of size 3, but then 4 clauses of size 4.
</li>
<li> MG is currently running experiments with the other field
multiplications. </li>
</ul>
*/
| true |
c344b2a0534816add9c3b1ec0c5a39fb94378eec | C++ | SDG98/Capstone-Graphics | /PizzaBox/Animation/AnimEngine.h | UTF-8 | 725 | 2.71875 | 3 | [] | no_license | #ifndef ANIM_ENGINE_H
#define ANIM_ENGINE_H
#include "Animator.h"
namespace PizzaBox{
class AnimEngine{
public:
static bool Initialize();
static void Destroy();
static void Update(float deltaTime_);
static void RegisterAnimator(Animator* animator_);
static void UnregisterAnimator(Animator* animator_);
//Delete unwanted compiler generated constructors, destructors and assignment operators
AnimEngine() = delete;
AnimEngine(const AnimEngine&) = delete;
AnimEngine(AnimEngine&&) = delete;
AnimEngine& operator=(const AnimEngine&) = delete;
AnimEngine& operator=(AnimEngine&&) = delete;
~AnimEngine() = delete;
private:
static std::vector<Animator*> animators;
};
}
#endif //!ANIM_ENGINE_H | true |
66e470b877b303d75d731fe9bc10805a16484c7f | C++ | ameth64/hs_sfm | /unit_test/sfm_utility/test_similar_transform_estimator.cpp | UTF-8 | 6,384 | 2.65625 | 3 | [] | no_license | #include <iostream>
#include <gtest/gtest.h>
#include "hs_math/random/normal_random_var.hpp"
#include "hs_math/random/uniform_random_var.hpp"
#include "hs_sfm/sfm_utility/similar_transform_estimator.hpp"
namespace
{
template <typename _Scalar>
class TestSimilarTransformEstimator
{
public:
typedef _Scalar Scalar;
typedef int Err;
private:
typedef hs::sfm::SimilarTransformEstimator<Scalar> Estimator;
typedef typename Estimator::Point Point;
typedef typename Estimator::PointContainer PointContainer;
public:
typedef typename Estimator::Rotation Rotation;
typedef typename Estimator::Translate Translate;
public:
TestSimilarTransformEstimator(
size_t number_of_points,
Scalar stddev,
const Rotation& rotation_prior,
const Translate& translate_prior,
Scalar scale_prior)
: number_of_points_(number_of_points),
stddev_(stddev),
rotation_prior_(rotation_prior),
translate_prior_(translate_prior),
scale_prior_(scale_prior) {}
public:
Err Test()
{
Point rel_point_min;
rel_point_min << -1,
-1,
-1;
Point rel_point_max = -rel_point_min;
PointContainer rel_points_true(number_of_points_);
for (size_t i = 0; i < number_of_points_; i++)
{
hs::math::random::UniformRandomVar<Scalar, 3>::Generate(
rel_point_min, rel_point_max, rel_points_true[i]);
}
PointContainer abs_points_true(number_of_points_);
for (size_t i = 0; i < number_of_points_; i++)
{
Point rel_point = rel_points_true[i];
abs_points_true[i] = scale_prior_ * (rotation_prior_ * rel_point) +
translate_prior_;
}
typedef EIGEN_MATRIX(Scalar, 3, 3) PointCovariance;
PointCovariance rel_covariance = PointCovariance::Identity();
PointCovariance abs_covariance = PointCovariance::Identity();
rel_covariance *= stddev_ * stddev_ / scale_prior_ / scale_prior_;
abs_covariance *= stddev_ * stddev_;
PointContainer rel_points_noised = rel_points_true;
PointContainer abs_points_noised = abs_points_true;
for (size_t i = 0; i < number_of_points_; i++)
{
hs::math::random::NormalRandomVar<Scalar, 3>::Generate(
rel_points_true[i], rel_covariance, rel_points_noised[i]);
hs::math::random::NormalRandomVar<Scalar, 3>::Generate(
abs_points_true[i], abs_covariance, abs_points_noised[i]);
}
Rotation rotation_estimate;
Translate translate_estimate;
Scalar scale_estimate;
Estimator estimator;
if (estimator(rel_points_noised, abs_points_noised,
rotation_estimate,
translate_estimate,
scale_estimate) != 0)
{
return -1;
}
PointContainer abs_points_estimate = rel_points_noised;
for (size_t i = 0; i < number_of_points_; i++)
{
Point rel_point = rel_points_noised[i];
abs_points_estimate[i] =
scale_estimate * (rotation_estimate * rel_point) + translate_estimate;
}
Scalar mean_error = Scalar(0);
for (size_t i = 0; i < number_of_points_; i++)
{
Point diff = abs_points_estimate[i] - abs_points_noised[i];
Scalar error = diff.norm();
mean_error += error;
}
mean_error /= Scalar(number_of_points_);
Scalar threshold = stddev_ * 2 + 1;
if (mean_error > threshold)
{
return -1;
}
return 0;
}
private:
size_t number_of_points_;
Scalar stddev_;
Rotation rotation_prior_;
Translate translate_prior_;
Scalar scale_prior_;
};
TEST(TestSimilarTransformEstimator, SimpleTest)
{
typedef double Scalar;
typedef TestSimilarTransformEstimator<Scalar> Tester;
typedef EIGEN_MATRIX(Scalar, 3, 3) Matrix33;
typedef Tester::Rotation Rotation;
typedef Tester::Translate Translate;
size_t number_of_points = 100;
Scalar stddev = 0.5;
Matrix33 rotation_matrix;
rotation_matrix << 0.5399779, -0.8415759, 0.0131819,
0.8411558, 0.5401282, 0.0268019,
-0.0296757, -0.0033843, 0.9995538;
Rotation rotation_prior(rotation_matrix);
Translate translate_prior;
translate_prior << 22.067653670014472,
-115.69362180617838,
488.11969428744248;
Scalar scale_prior = 180.83981053672068;
Tester tester(number_of_points,
stddev,
rotation_prior,
translate_prior,
scale_prior);
ASSERT_EQ(0, tester.Test());
}
TEST(TestSimilarTransformEstimator, PriorTest)
{
typedef double Scalar;
typedef hs::sfm::SimilarTransformEstimator<Scalar> Estimator;
typedef Estimator::Point Point;
typedef Estimator::PointContainer PointContainer;
typedef Estimator::Rotation Rotation;
typedef Estimator::Translate Translate;
PointContainer points_1(4);
PointContainer points_2(4);
points_2[0] << 2614304.862,
404783.446,
116.810;
points_2[1] << 2611325.079,
405029.381,
117.931;
points_2[2] << 2615611.506,
411900.269,
131.823;
points_2[3] << 2611160.858,
413763.796,
108.580;
points_1[0] << 2614108.822,
557851.217,
116.810;
points_1[1] << 2611131.991,
558128.369,
117.931;
points_1[2] << 2615490.009,
564953.528,
131.823;
points_1[3] << 2611059.331,
566863.561,
108.580;
Estimator estimator;
Rotation rotation_similar;
Translate translate_similar;
Scalar scale_similar;
ASSERT_EQ(0, estimator(points_1, points_2,
rotation_similar,
translate_similar,
scale_similar));
for (size_t i = 0; i < 4; i++)
{
Point point_2_estimate = points_1[i];
point_2_estimate = rotation_similar * point_2_estimate;
point_2_estimate = scale_similar * point_2_estimate;
point_2_estimate = point_2_estimate + translate_similar;
Point diff = point_2_estimate - points_2[i];
int bp = 0;
}
}
}
| true |
7137719a65272d701e1ec5787c86817b563ef55b | C++ | sajjadpoores/binary-search | /binary-search.cpp | UTF-8 | 360 | 3.890625 | 4 | [] | no_license | int binary_search(int a[],int x,int low,int high){ // array a must be sorted , x is the integer we are look for , low and high are index
if (low <= high){
int mid = (low + high) / 2;
if (a[mid] == x)
return mid;
else if (a[mid] < x)
binary_search(a, x, mid+1, high);
else
binary_search(a, x, low, mid-1);
}
else
return -1;
} | true |
03b1bf3ec34738106b4e84bd7372e1f542053d39 | C++ | close2/alibvr-examples | /src/adc_sync_3inputs.cpp | UTF-8 | 1,542 | 2.578125 | 3 | [
"MIT"
] | permissive | #define F_CPU 8000000UL
#include <util/delay.h>
#include "ports.h"
#include "adc.h"
// Test program.
// A previous Adc version had problems when reading 3 adc values:
// similar to:
//
// do {
// <in1>::init
// adc_8bit
// <in2>::init
// adc_8bit
// <in3>::init
// adc_8bit
// turn_off
// }
// ⇒ 1st result was a copy of 3rd
typedef PIN_C5 Input1;
typedef PIN_C4 Input2;
typedef PIN_C3 Input3;
// First define the Adc.
// We want a single conversion (default), whenever we start an adc.
// Use the internal 1.1V voltage as reference.
typedef Adc<_adc::Ref::V1_1> AdcV1_1;
// 255 == 1.1V
const uint8_t V0_5 = (255 * 5) / 11;
typedef PIN_D1 Led1;
typedef PIN_D2 Led2;
typedef PIN_D3 Led3;
__attribute__ ((OS_main)) int main(void) {
// put Led pins into output mode.
Led1::DDR = 1;
Led2::DDR = 1;
Led3::DDR = 1;
for (;;) {
// Measure the voltage on Pin Input1.
AdcV1_1::init<Input1>();
AdcV1_1::adc_8bit(); // first read after initialization shouldn't be trusted
auto in1 = AdcV1_1::adc_8bit();
Led1::PORT = (in1 > V0_5);
AdcV1_1::init<Input2>();
AdcV1_1::adc_8bit(); // first read after initialization shouldn't be trusted
auto in2 = AdcV1_1::adc_8bit();
Led2::PORT = (in2 > V0_5);
AdcV1_1::init<Input3>();
AdcV1_1::adc_8bit(); // first read after initialization shouldn't be trusted
auto in3 = AdcV1_1::adc_8bit();
Led3::PORT = (in3 > V0_5);
AdcV1_1::turn_off();
_delay_ms(100);
}
return 0;
}
| true |
951ff89de1c250da5aca44444bba77b3f7305e14 | C++ | Reicher/Rocket-Rampage | /src/model/Model.h | UTF-8 | 938 | 2.703125 | 3 | [
"Unlicense"
] | permissive | #pragma once
#include <memory>
#include "IObservable.h"
#include "IActor.h"
namespace model {
//! Model for the game
class Model : public IObservable
{
public:
Model();
~Model();
//! Initiates the model
void init();
//! Updates the model
//!
//! @param dt seconds elapsed since the last update call.
void update( float dt );
void setThrustOn( bool thrust, int id );
void setBackThrustOn( bool backThrust, int id );
void setLeftThrustOn( bool leftThrust, int id );
void setRightThrustOn( bool rightThrust, int id );
void setCRotOn( bool cRot, int id );
void setCCWRotOn( bool ccwRot, int id );
//! Adds an observer to the model.
//!
//! @param pObserver pointer to the observer to add.
void addObserver( IObserver* pObserver );
//! Notify all observers
//!
//! @param e The event.
void notifyObservers( const Event& e );
private:
class Impl;
std::auto_ptr<Impl> m_apImpl;
};
} // namespace model
| true |
30f42883297250ef74691206d288978a9251d9eb | C++ | Naateri/AED | /polymorphism.cpp | UTF-8 | 7,137 | 3.484375 | 3 | [] | no_license | #include <iostream>
#include <stdlib.h>
#include <time.h>
#include <fstream>
//unsigned long long int can store up to 19 digit numbers
using namespace std;
template <class T>
T* generarArray(unsigned long long size){
srand(time(NULL));
T* ret = new T[size];
T* a = ret;
for(int i = 0; i<size; a++, i++){
*a = T(rand()) % 1000000;
}
return ret;
}
template <class T>
void imprimir(T *a, T *b){
cout << "[";
for(; a < b; a++){
cout << *a << ",";
}
cout << "]" << endl;
}
template <class T>
void swap(T *p, T *q){
T temp;
temp = *p;
*p = *q;
*q = temp;
}
template <class T> class Cocktail{
protected:
//virtual bool mayor(T, T) = 0;
virtual bool cmp(T, T) = 0;
public:
void sort(T *a, T *fin){
T *aux;
aux = a;
bool compro = 1;
T *auxF = fin;
while (compro){
compro = 0;
for(a; a < fin; a++){
if(cmp(*a, *(a+1))){
swap<T>(*a, *(a+1));
compro = 1;
}
}
for(a; fin != aux; fin--){
if(!(cmp(*fin, *(fin-1)))){
swap<T>(*fin, *(fin-1));
compro = 1;
}
}
swap<T>(*a,*fin);
aux++;
a = aux;
auxF--;
fin = auxF;
}
}
};
template <class T>
class MenorCock: public Cocktail<T>{
public:
bool cmp(T a, T b){
return a < b;
}
};
template <class T>
class MayorCock: public Cocktail<T>{
public:
bool cmp(T a, T b){
return a > b;
}
};
template <class T>
void a1000Elem(double &elapsedTime, ofstream &filexd){
int* array1000 = generarArray<int>(1000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array1000, array1000+999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 1000 elementos: " << elapsedTime << endl;
delete array1000;
//delete Csort;
}
template <class T>
void a5kElem(double &elapsedTime, ofstream &filexd){
T* array5k = generarArray<T>(5000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array5k, array5k+4999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 5 000 elementos: " << elapsedTime << endl;
delete array5k;
//delete Csort;
}
template <class T>
void a10kElem(double &elapsedTime, ofstream &filexd){
T* array10k = generarArray<T>(10000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array10k, array10k+9999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 10 000 elementos: " << elapsedTime << endl;
delete array10k;
//delete Csort;
}
template <class T>
void a25kElem(double &elapsedTime, ofstream &filexd){
T* array25k = generarArray<T>(25000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array25k, array25k+24999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 25 000 elementos: " << elapsedTime << endl;
delete array25k;
//delete Csort;
}
template <class T>
void a50kElem(double &elapsedTime, ofstream &filexd){
T* array50k = generarArray<T>(50000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array50k, array50k+49999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 50 000 elementos: " << elapsedTime << endl;
delete array50k;
//delete Csort;
}
template <class T>
void a100kElem(double &elapsedTime, ofstream &filexd){
int* array100k = generarArray<int>(100000);
cout << sizeof(array100k) << endl;
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array100k, array100k+99999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 100 000 elementos: " << elapsedTime << endl;
delete array100k;
//delete Csort;
}
template <class T>
void a250kElem(double &elapsedTime, ofstream &filexd){
T* array250k = generarArray<T>(250000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array250k, array250k+249999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 250 000 elementos: " << elapsedTime << endl;
delete array250k;
//delete Csort;
}
template <class T>
void a500kElem(double &elapsedTime, ofstream &filexd){
T* array500k = generarArray<T>(500000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array500k, array500k+499999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 500 000 elementos: " << elapsedTime << endl;
//delete array500k;
}
template <class T>
void a1MElem(double &elapsedTime, ofstream &filexd){
int* array1M = generarArray<int>(1000000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array1M, array1M+999999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 1 000 000 elementos: " << elapsedTime << endl;
delete array1M;
//delete Csort;
}
template <class T>
void a100MElem(double &elapsedTime, ofstream &filexd){
int* array100M = generarArray<int>(100000000);
clock_t begin = clock();
Cocktail<T> *Csort = new MenorCock<T>;
Csort->sort(array100M, array100M+99999999);
//imprimir<int>(array1000, array1000+999);
clock_t end = clock();
elapsedTime = double(end-begin) / CLOCKS_PER_SEC;
filexd << "Array 100 000 000 elementos: " << elapsedTime << endl;
delete array100M;
delete Csort;
}
int main(int argc, char *argv[]) {
double et, acum = 0;
ofstream file;
file.open("timesPolymorphism.txt");
for(int i = 0; i < 100; i++){
a1000Elem<int>(et, file);
acum += et;
}
cout << "Acabo 1000\n";
file << "Promedio 1000: " << acum/100 << endl;
acum = 0;
for(int i = 0; i < 50; i++){
a5kElem<int>(et, file);
acum += et;
}
cout << "Acabo 5000\n";
file << "Promedio 5000: " << acum/50 << endl;
acum = 0;
for(int i = 0; i < 30; i++){
a10kElem<int>(et, file);
acum += et;
}
cout << "Acabo 10 000\n";
file << "Promedio 10 000: " << acum/30 << endl;
acum = 0;
for(int i = 0; i < 25; i++){
a25kElem<int>(et, file);
acum += et;
}
cout << "Acabo 25 000\n";
file << "Promedio 25 000: " << acum/25 << endl;
acum = 0;
for(int i = 0; i < 15; i++){
a50kElem<int>(et, file);
acum += et;
}
cout << "Acabo 50 000\n";
file << "Promedio 50 000: " << acum/15 << endl;
acum = 0;
for(int i = 0; i < 10; i++){
a100kElem<int>(et, file);
acum += et;
}
cout << "Acabo 100 000\n";
file << "Promedio 100 000: " << acum/10 << endl;
acum = 0;
a250kElem<int>(et, file);
cout << "Acabo 250 000\n";
a500kElem<int>(et, file);
cout << "Acabo 500 000\n";
//for(int i = 0; i < 10; i++){
a1MElem<int>(et, file);
//acum += et;
//}
cout << "Acabo 1 000 000\n";
//file << "Promedio 100 000 000: " << acum/5 << endl;
return 0;
}
| true |
5dff8d5d8597596ead8a6597baf472d6f3588ad1 | C++ | SepehrSalim/MS-Multiprocessor-DB | /C Files/C_PROGS/RAMZ.CPP | UTF-8 | 357 | 3.09375 | 3 | [] | no_license | #include <iostream.h>
#include <string.h>
int sign_on (void)
{
char str [20];
int i = 0;
do {
if (i ++ == 3)
return 0;
cout << "Enter password please : ";
cin >> str;
} while (strcmp (str, "password"));
return 1;
}
void main (void)
{
if (sign_on ())
cout << "Password --> correct\n";
else
cout << "Password --> denied\n";
} | true |
32b27202afc4040512d33092fa5a96cafdab339b | C++ | KedarBiradar/Problem-Solving | /Spoj/PHONELST.cpp | UTF-8 | 1,139 | 3.296875 | 3 | [] | no_license | #include <cstdio>
#include <stdlib.h>
#include <string.h>
struct node
{
bool endNode;
node * child[10];
};
node * newNode()
{
node * n=(node *)malloc(sizeof(node));
n->endNode=false;
for(int i=0;i<10;i++)
n->child[i]=NULL;
return n;
}
bool insert(node *root,char number[])
{
int len=strlen(number);
node *curr=root;
for(int i=0;i<len;i++)
{
if(curr->endNode)
return true;
if(curr->child[number[i]-48])
curr=curr->child[number[i]-48];
else
{
curr->child[number[i]-48]=newNode();
curr=curr->child[number[i]-48];
}
}
curr->endNode=true;
for(int i=0;i<10;i++)
{
if(curr->child[i])
return true;
}
return false;
}
void deleteTree(node * root)
{
for(int i=0;i<10;i++)
{
if(root->child[i])
deleteTree(root->child[i]);
}
delete root;
}
int main()
{
int n,t,i;
scanf("%d",&t);
char number[11];
bool flag;
while(t--)
{
node *root=newNode();
scanf("%d",&n);
flag=false;
for(i=0;i<n;i++)
{
scanf("%s",number);
if(!flag)
{
if(insert(root,number))
flag=true;
}
}
if(!flag)
printf("YES\n");
else
printf("NO\n");
deleteTree(root);
}
return 0;
}
| true |
fafb1f4e6f9d40362a1d41a2ba4c8abeaaa34b27 | C++ | SiddharthaSarma/a20j | /level-1A/problem-33.cpp | UTF-8 | 306 | 2.90625 | 3 | [] | no_license | // http://codeforces.com/contest/766/problem/A
// 766/A. Mahmoud and Longest Uncommon Subsequence
#include<bits/stdc++.h>
using namespace std;
int main() {
string a, b;
cin >> a >> b;
if (a == b) {
cout << -1 << endl;
} else {
cout << max(a.size(), b.size()) << endl;
}
return 0;
}
| true |
ace3cbc0f8e6b731cd783de8eebd957efce291e9 | C++ | findobj/HelloAndroid | /jni/findobj/foundation/SearchNode.cpp | UTF-8 | 1,072 | 3.0625 | 3 | [] | no_license | #include "SearchNode.h"
SearchNode::SearchNode()
{
mData = NULL;
mParent = NULL;
mNext = NULL;
mVisited = false;
mWeight = 1;
}
SearchNode::~SearchNode()
{
if(mData != NULL) {
mData->release();
}
if(mNext != NULL) {
mNext->release();
}
}
void SearchNode::setData(Object *data)
{
Object::assign((Object**)&mData, (Object**)&data);
}
Object* SearchNode::getData()
{
return mData;
}
void SearchNode::setParent(SearchNode *parent)
{
mParent = parent;
}
SearchNode* SearchNode::getParent()
{
return mParent;
}
void SearchNode::setNext(SearchNode *next)
{
mNext = next;
}
SearchNode* SearchNode::getNext()
{
return mNext;
}
void SearchNode::setVisited(bool visited)
{
mVisited = visited;
}
bool SearchNode::isVisited()
{
return mVisited;
}
void SearchNode::setWeight(int weight)
{
mWeight = weight;
}
int SearchNode::getWeight()
{
return mWeight;
}
int SearchNode::getWeightFromParent()
{
return (mWeight + (mParent != NULL ? mParent->getWeightFromParent() : 0));
}
| true |
2a1e7e71c449375f42d73bd953186edfa0b9285e | C++ | Carlosmau97/ProyectoSistemasInteligentes | /PF_Estructura/myLista.cpp | UTF-8 | 1,056 | 3.3125 | 3 | [] | no_license | #include "myLista.h"
myLista::myLista(){
primero=0;
ultimo=0;
}
void myLista::insertarCabezaLista(float entrada){
Nodo_Lista* nuevo;
nuevo = new Nodo_Lista(entrada);
nuevo -> ponerEnlace(primero);
primero = nuevo;
if(ultimo==0)
ultimo=nuevo;
}
void myLista::mostrar(){
Nodo_Lista* aux;
aux=primero;
while(aux != 0){
cout<< aux->datoNodo()<<endl;
aux = aux->enlaceNodo();
}
}
Nodo_Lista* myLista::buscarLista(float destino){
Nodo_Lista* aux;
aux=primero;
while(aux != 0){
if(aux->datoNodo()==destino)
return aux;
aux=aux->enlaceNodo();
}
return 0;
}
void myLista::insertarUltimo(float entrada){
Nodo_Lista* p=primero;
if(p == 0){
insertarCabezaLista(entrada);
return;
}
Nodo_Lista* nuevo = new Nodo_Lista(entrada);
ultimo->ponerEnlace(nuevo);
ultimo=nuevo;
}
void myLista::insertarLista(Nodo_Lista* anterior, float entrada){
Nodo_Lista* nuevo;
nuevo=new Nodo_Lista(entrada);
nuevo->ponerEnlace(anterior->enlaceNodo());
if(anterior->enlaceNodo()==0)
ultimo=nuevo;
anterior->ponerEnlace(nuevo);
}
| true |
4263993fecfe0d6860ccd56b2038afd0ca4e609e | C++ | torres2235/cs100-lab-08-new | /lab-04/add_test.hpp | UTF-8 | 1,411 | 3.078125 | 3 | [] | no_license | #ifndef __ADD_TEST_HPP__
#define __ADD_TEST_HPP__
#include "gtest/gtest.h"
#include "add.hpp"
#include "op.hpp"
/*
TEST(AddTest, AddEvaluateNonZero) {
Base* val1 = new Op(2);
Base* val2 = new Op(2);
Base* test = new Add(val1,val2);
EXPECT_EQ(test->evaluate(), 4);
}
TEST(AddTest, AddEvaluateNegative) {
Base* val1 = new Op(-3);
Base* val2 = new Op(-3);
Base* test = new Add(val1,val2);
EXPECT_EQ(test->evaluate(), -6);
}
TEST(AddTest, AddEvalulateDecimals) {
Base* val1 = new Op(5.4);
Base* val2 = new Op(-3.1);
Base* test = new Add(val1,val2);
EXPECT_DOUBLE_EQ(test->evaluate(), 2.3);
}
TEST(AddTest, AddString) {
Base* val1 = new Op(9);
Base* val2 = new Op(9);
Base* test = new Add(val1,val2);
EXPECT_EQ(test->stringify(), "9+9");
}
TEST(AddTest, AddStringNegative) {
Base* val1 = new Op(4);
Base* val2 = new Op(-2);
Base* test = new Add(val1,val2);
EXPECT_EQ(test->stringify(), "4+-2");
}
*/
/* UNIT TESTS FOR NEW ITERATOR FUNCTIONS */
TEST(AddTest, AddIteratorTest) {
Base* op1 = new Op(1);
Base* op2 = new Op(2);
Base* test = new Add(op1, op2);
Iterator* newIt = test->create_iterator();
EXPECT_EQ(test->get_left(), op1);
EXPECT_EQ(test->get_right(), op2);
EXPECT_EQ(newIt->current(), op1);
newIt->next();
EXPECT_EQ(newIt->current(), op2);
newIt->next();
EXPECT_EQ(newIt->is_done(), true);
}
#endif //__ADD_TEST_HPP__
| true |
2fa1c1ac1e62706a598a1f32bb503d2dc97584bc | C++ | gitwyy/SmartCarV4 | /Src/smartcar/obj/Battery.cpp | UTF-8 | 874 | 2.828125 | 3 | [
"Apache-2.0"
] | permissive | //
// Created by wangyangyang on 2021-04-10.
//
#include "Battery.h"
#include "adc.h"
Battery::Battery(double minVoltage) : minVoltage(minVoltage) {}
Battery::~Battery() {}
void Battery::init() {
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, 50);
}
bool Battery::isLowVoltage() {
return this->currentValue < this->minVoltage;
}
void Battery::measureVoltage() {
if (HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC)) {
double v = HAL_ADC_GetValue(&hadc1) * 3.3 * 11.1 / 4096.0;
if (v > currentValue) {
this->currentValue = v;
}
}
}
void Battery::resetMeasure() {
if (HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC)) {
this->currentValue = HAL_ADC_GetValue(&hadc1) * 3.3 * 11.1 / 4096.0;
}
}
double Battery::getVoltage() {
return this->currentValue;
} | true |
89a186dbdc09fa5989d2372e3cfed136bd74abf9 | C++ | civinx/ACM_Code | /ZUCC_Prob/2016新生选拔赛/E.女装门徒/myprob/test3.cpp | UTF-8 | 1,175 | 2.59375 | 3 | [] | no_license | #include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
struct node {
int hav[3];
int res[3];
} A[1005];
bool vis[1005];
bool check(int id) {
for (int i = 0; i < 3; i++)
if (A[id].hav[i] + A[0].hav[i] < A[id].res[i])
return false;
return true;
}
void del(int id) {
for (int i = 0; i < 3; i++)
A[0].hav[i] += A[id].hav[i];
}
int main() {
int T, n, cnt;
scanf("%d", &T);
for (int _ = 1; _ <= T; _++) {
scanf("%d", &n);
cnt = 0;
for (int j = 0; j < 3; j++)
scanf("%d", &A[0].hav[j]);
for (int i = 1; i <= n; i++) {
for (int j = 0; j < 3; j++)
scanf("%d", &A[i].hav[j]);
for (int j = 0; j < 3; j++)
scanf("%d", &A[i].res[j]);
vis[i] = false;
}
for (int i = 1; i <= n; ) {
if (!vis[i] && check(i)) {
vis[i] = true;
del(i);
cnt++;
i = 1;
continue;
}
i++;
}
printf("Case #%d: %s\n", _, cnt == n ? "Yes" : "No");
}
return 0;
}
| true |
e1fa4fc0584cf266ece10e98a01496c7933aeb93 | C++ | jvff/mestrado-implementacao | /src/test/cpp/LuminanceFilter/RgbImageImplementationTest.cpp | UTF-8 | 2,635 | 2.609375 | 3 | [] | no_license | #include "LuminanceFilterRgbImageImplementationTest.hpp"
using TypeParameters = ::testing::Types<
Aliases<RgbImage<SimpleArrayImage<std::uint64_t> >,
RgbImage<SimpleArrayImage<std::uint64_t> >,
SimpleArrayImage<unsigned char> >,
Aliases<RgbImage<OpenCLImage<std::uint64_t> >,
RgbImage<OpenCLImage<std::uint64_t> >,
OpenCLImage<std::uint64_t> > >;
TYPED_TEST_CASE(LuminanceFilterRgbImageImplementationTest, TypeParameters);
TEST_C(handlesRgbImages) {
using DestinationPixelType = typename DestinationImageType::PixelType;
unsigned int width = 8;
unsigned int height = 8;
FilterType filter;
auto internalImage = createInternalImage(width, height);
auto sourceImage = SourceImageType(internalImage, true);
auto expectedImage = createDestinationImage(width, height);
float pixelFactor = std::numeric_limits<DestinationPixelType>::max();
float channelValues[4] = { 0.f, 0.33f, 0.67f, 1.f };
for (unsigned int x = 0; x < width; ++x) {
for (unsigned int y = 0; y < height; ++y) {
auto tileX = x / 4;
auto tileY = y / 4;
auto tileId = tileX + tileY * 2;
auto xInTile = x % 4;
auto yInTile = y % 4;
float redComponent = channelValues[xInTile];
float greenComponent = channelValues[yInTile];
float blueComponent = channelValues[tileId];
sourceImage.setPixel(x, y, redComponent, greenComponent,
blueComponent);
auto updatedRedComponent =
sourceImage.getRelativeRedComponent(x, y);
auto updatedGreenComponent =
sourceImage.getRelativeGreenComponent(x, y);
auto updatedBlueComponent =
sourceImage.getRelativeBlueComponent(x, y);
float redContribution = 0.2126f * updatedRedComponent;
float greenContribution = 0.7152f * updatedGreenComponent;;
float blueContribution = 0.0722f * updatedBlueComponent;;
float relativeLuminance = 0.f;
relativeLuminance += redContribution;
relativeLuminance += greenContribution;
relativeLuminance += blueContribution;
auto luminanceValue = std::round(relativeLuminance * pixelFactor);
auto expectedValue = convertFloatDestinationValue(luminanceValue);
expectedImage.setPixel(x, y, expectedValue);
}
}
auto resultingImage = filter.apply(sourceImage);
assertThat(resultingImage).isEqualTo(expectedImage);
}
| true |
63f29f6b6a136b865ad277aa50e08ac37f85e001 | C++ | ssh352/ronin | /Algo_Engine/ROM_Handler/Client_Session.cpp | UTF-8 | 1,565 | 2.53125 | 3 | [] | no_license | #include "Connection.hpp"
#include "Client_Session.hpp"
#include <bullseye/bullseye_common.hpp>
#if 0
namespace dart {
Connector::Connector (Client_Session *session)
: session_ (session)
{}
Connection *Connector::make_handler ()
{
Connection *connection = new Connection (session_);
return connection;
}
Client_Session::Client_Session ()
: connect_pending_ (false)
, connector_ (this)
{}
int Client_Session::open (void *) {
if (this->connector_.open () == -1)
ACE_ERROR_RETURN ((LM_ERROR, DART_LOG ("%p\n"), __FUNCTION__), -1);
return (this->connect () ? 0 : -1);
}
bool Client_Session::connect () {
bool result (false);
if (this->connection_ == 0 && connect_pending_ == false) {
ACE_INET_Addr connect_addr (static_cast <u_short> (8008), "ddart-ltc-rom1");
if (this->connector_.connect (connect_addr) == -1)
ACE_ERROR_RETURN ((LM_ERROR, DART_LOG ("%p\n"), __FUNCTION__), false);
connect_pending_ = true;
result = true;
}
return result;
}
void Client_Session::on_new_connection (Connection *new_connection) {
if (this->connection_)
ACE_DEBUG ((LM_DEBUG, DART_LOG ("Logic error! New client connection "
"established when one already exists!\n")));
else {
this->connection (new_connection);
// As a client we will send a Logon immediately upon connecting
this->logon ();
}
}
void Client_Session::on_data_message (ACE_Message_Block*) {
}
}
#endif
| true |
3bd61dd1702db67f1166931ab5467574c68cedbd | C++ | AlexanderGudov/AlgsAndDataStructuresCoursera | /SumOfTwoDigits.cpp | UTF-8 | 566 | 3.40625 | 3 | [] | no_license | //============================================================================
// Name : SumOfTwoDigits.cpp
// Author : Aleksey Kravchuk
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
int main() {
int a{0};
int b{0};
std::cin >> a >> b;
if(a < 0 || a > 9 || b < 0 || b > 9) {
std::cout << "Constraints: 0 ≤ a, b ≤ 9." << std::endl;
return -1;
}
std::cout << a+b << std::endl;
return 0;
}
| true |
d8cbb1b040a0d3391ef26a176d2550e38567c1f0 | C++ | pchat99/Competitive_Programming | /Array_Problems/kth_smallest_element.cpp | UTF-8 | 337 | 2.84375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int kthsmallest(int arr[], int n, int k)
{
sort(arr, arr + n);
return arr[k - 1];
}
int main () {
int n; cin>>n; int k; cin>>k;
int arr[n];
for (int i = 0; i < n; i++) {
cin>>arr[i];
}
n = sizeof(arr)/sizeof(arr[0]);
cout<<kthsmallest(arr, n, k);
return 0;
} | true |
941b4c55e7fabd7561766f5f5b33078c98601121 | C++ | tupieurods/SportProgramming | /CR160/CR160B/main.cpp | UTF-8 | 578 | 2.703125 | 3 | [] | no_license | #include <stdio.h>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <algorithm>
using namespace std;
int main()
{
int n, k;
scanf("%d %d\n", &n, &k);
int absSmallest = INT_MAX;
int sum = 0;
for(int i = 0; i < n; i++)
{
int tmp;
scanf("%d", &tmp);
if((k != 0) && (tmp <= 0))
{
sum += abs(tmp);
k--;
}
else
sum += tmp;
absSmallest = min(absSmallest, abs(tmp));
}
if(k != 0)
{
if(k % 2 == 1)
sum -= 2 * absSmallest;
}
printf("%d", sum);
return 0;
}
| true |
83742d4b8203c558d3a6af2a13e86db41efa566d | C++ | grishavanika/task | /src/rename_me/include/rename_me/task.h | UTF-8 | 14,154 | 2.65625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <rename_me/custom_task.h>
#include <rename_me/detail/cpp_20.h>
#include <rename_me/detail/internal_task.h>
#include <rename_me/detail/function_task_base.h>
#include <type_traits>
#include <cassert>
namespace nn
{
class Scheduler;
template<typename>
struct is_task;
template<typename>
struct task_from_expected;
template<typename T = void, typename E = void>
class Task
{
private:
// Reference counting is needed to handle ownership
// of task internals for _on_finish()_ implementation.
// Without on_finish() API, it's enough to have raw pointer
// with custom management of lifetime thru Scheduler
// (of course this is true only if Task is move-only.
// If copy semantic will be enabled, ref. counted-like pointer
// is needed in any case)
using InternalTask = detail::RefCountPtr<detail::InternalTask<T, E>>;
template<typename OtherT, typename OtherE>
friend class Task;
public:
using value_type = T;
using error_type = E;
using value = expected<T, E>;
public:
template<typename CustomTask, typename... Args>
static
typename std::enable_if<IsCustomTask<CustomTask, T, E>::value, Task>::type
make(Scheduler& scheduler, Args&&... args);
explicit Task();
~Task();
Task(Task&& rhs) noexcept;
Task& operator=(Task&& rhs) noexcept;
Task(const Task& rhs) = delete;
Task& operator=(const Task& rhs) = delete;
// Because of on_finish() API, we need to accept `const Task& task`
// to avoid situations when someones std::move(task) to internal storage and,
// hence, ending up with, possibly, 2 Tasks intances that refer to same
// InternalTask. This also avoids ability to call task.on_finish() inside
// on_finish() callback.
// Because of this decision, getters of values of the task should be const,
// but return non-const reference so client can get value.
//
// Note: the behavior is undefined if get*():
// 1. is called before task't finish
// 2. value from expected<> is moved more than once
// 3. value from expected<> is read & moved from different threads
// (effect of 2nd case)
expected<T, E>& get() const &;
expected<T, E>& get() &;
expected<T, E> get() &&;
expected<T, E> get_once() const;
// Thread-safe
void try_cancel();
bool is_canceled() const;
Status status() const;
bool is_in_progress() const;
bool is_finished() const;
bool is_failed() const;
bool is_successful() const;
Scheduler& scheduler() const;
// Let's R = f(*this). If R is:
// 1. Task<U, O> then returns Task<U, O>.
// Returned task will reflect state of returned from functor task.
// 2. expected<U, O> then returns Task<U, O>.
// Returned task will reflect status and value of returned
// from functor expected<> (e.g., will be failed if expected contains error).
// 3. U (some type that is not Task<> or expected<>)
// then returns Task<U, void> with immediate success status.
//
// #TODO: accept Args... so caller can pass valid
// INVOKE()-able expression, like:
// struct InvokeLike { void call(const Task<>&) {} };
// InvokeLike callback;
// task.on_finish(&InvokeLike::call, callback)
template<typename F>
detail::FunctionTaskReturnT<F, const Task<T, E>&>
on_finish(Scheduler& scheduler, F&& f);
// Same as on_finish(), but functor does not need to accept
// Task<> instance (e.g., caller discards it and _knows_ that)
template<typename F>
detail::FunctionTaskReturnT<F>
on_finish(Scheduler& scheduler, F&& f);
// Executes on_finish() with this task's scheduler
template<typename F>
auto on_finish(F&& f)
-> decltype(on_finish(
std::declval<Scheduler&>(), std::forward<F>(f)));
// Alias for on_finish()
template<typename F>
auto then(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)));
// Executes then() with this task's scheduler
template<typename F>
auto then(F&& f)
-> decltype(then(
std::declval<Scheduler&>(), std::forward<F>(f)));
template<typename F>
auto on_fail(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)));
// Executes on_fail() with this task's scheduler
template<typename F>
auto on_fail(F&& f)
-> decltype(on_fail(
std::declval<Scheduler&>(), std::forward<F>(f)));
template<typename F>
auto on_success(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)));
// Executes on_success() with this task's scheduler
template<typename F>
auto on_success(F&& f)
-> decltype(on_success(
std::declval<Scheduler&>(), std::forward<F>(f)));
template<typename F>
auto on_cancel(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)));
// Executes on_cancel() with this task's scheduler
template<typename F>
auto on_cancel(F&& f)
-> decltype(on_cancel(
std::declval<Scheduler&>(), std::forward<F>(f)));
bool is_valid() const;
private:
explicit Task(InternalTask task);
template<typename F, typename CallPredicate
, typename ReturnWithTaskArg = detail::FunctionTaskReturn<F, const Task<T, E>&>
, typename ReturnWithoutTaskArg = detail::FunctionTaskReturn<F>>
auto on_finish_impl(Scheduler& scheduler, F&& f, CallPredicate p);
template<typename F>
static decltype(auto) invoke(std::false_type, F& f, const Task&);
template<typename F>
static decltype(auto) invoke(std::true_type, F& f, const Task& self);
void remove();
private:
InternalTask task_;
};
} // namespace nn
#include <rename_me/scheduler.h>
#include <rename_me/detail/internal_task.h>
#include <rename_me/detail/config.h>
#include <rename_me/detail/ebo_storage.h>
#include <utility>
namespace nn
{
template<typename T, typename E>
/*explicit*/ Task<T, E>::Task(InternalTask task)
: task_(std::move(task))
{
}
template<typename T, typename E>
template<typename CustomTask, typename... Args>
/*static*/
typename std::enable_if<IsCustomTask<CustomTask, T, E>::value, Task<T, E>>::type
Task<T, E>::make(Scheduler& scheduler, Args&&... args)
{
using FullTask = detail::InternalCustomTask<T, E, CustomTask>;
auto full_task = detail::RefCountPtr<FullTask>::make(
scheduler, std::forward<Args>(args)...);
if (full_task->status() == Status::InProgress)
{
scheduler.post(full_task.template to_base<detail::TaskBase>());
}
return Task(full_task.template to_base<typename InternalTask::type>());
}
template<typename T, typename E>
/*explicit*/ Task<T, E>::Task()
: task_()
{
}
template<typename T, typename E>
bool Task<T, E>::is_valid() const
{
return task_.operator bool();
}
template<typename T, typename E>
Task<T, E>::~Task()
{
remove();
}
template<typename T, typename E>
void Task<T, E>::remove()
{
task_ = nullptr;
}
template<typename T, typename E>
Task<T, E>::Task(Task&& rhs) noexcept
: task_(rhs.task_)
{
rhs.task_ = nullptr;
}
template<typename T, typename E>
Task<T, E>& Task<T, E>::operator=(Task&& rhs) noexcept
{
if (this != &rhs)
{
remove();
std::swap(task_, rhs.task_);
}
return *this;
}
template<typename T, typename E>
Status Task<T, E>::status() const
{
assert(task_);
return task_->status();
}
template<typename T, typename E>
bool Task<T, E>::is_in_progress() const
{
return (status() == Status::InProgress);
}
template<typename T, typename E>
bool Task<T, E>::is_finished() const
{
return (status() != Status::InProgress);
}
template<typename T, typename E>
bool Task<T, E>::is_canceled() const
{
assert(task_);
return (status() == Status::Canceled);
}
template<typename T, typename E>
bool Task<T, E>::is_failed() const
{
const Status s = status();
return (s == Status::Failed)
|| (s == Status::Canceled);
}
template<typename T, typename E>
bool Task<T, E>::is_successful() const
{
return (status() == Status::Successful);
}
template<typename T, typename E>
Scheduler& Task<T, E>::scheduler() const
{
assert(task_);
return task_->scheduler();
}
template<typename T, typename E>
void Task<T, E>::try_cancel()
{
assert(task_);
task_->cancel();
}
template<typename T, typename E>
expected<T, E>& Task<T, E>::get() const &
{
assert(task_);
return task_->get_data();
}
template<typename T, typename E>
expected<T, E>& Task<T, E>::get() &
{
assert(task_);
return task_->get_data();
}
template<typename T, typename E>
expected<T, E> Task<T, E>::get() &&
{
assert(task_);
return std::move(task_->get_data());
}
template<typename T, typename E>
expected<T, E> Task<T, E>::get_once() const
{
assert(task_);
return std::move(task_->get_data());
}
template<typename T, typename E>
template<typename F>
/*static*/ decltype(auto) Task<T, E>::invoke(std::false_type, F& f, const Task&)
{
return std::move(f)();
}
template<typename T, typename E>
template<typename F>
/*static*/ decltype(auto) Task<T, E>::invoke(std::true_type, F& f, const Task& self)
{
return std::move(f)(self);
}
template<typename T, typename E>
template<typename F, typename CallPredicate
, typename ReturnWithTaskArg
, typename ReturnWithoutTaskArg>
auto Task<T, E>::on_finish_impl(Scheduler& scheduler, F&& f, CallPredicate p)
{
using HasTaskArg = typename ReturnWithTaskArg::is_valid;
using Function = detail::remove_cvref_t<F>;
using FunctionTaskReturn = std::conditional_t<
HasTaskArg::value
, ReturnWithTaskArg
, ReturnWithoutTaskArg>;
using ReturnTask = typename FunctionTaskReturn::type;
struct NN_EBO_CLASS Invoker
: private detail::EboStorage<Function>
, private CallPredicate
{
using Callable = detail::EboStorage<Function>;
explicit Invoker(Function f, CallPredicate p, const InternalTask& t)
: Callable(std::move(f))
, CallPredicate(std::move(p))
, task(t)
{
}
decltype(auto) invoke()
{
Function& f = static_cast<Callable&>(*this).get();
return Task::invoke(HasTaskArg(), f, Task(task));
}
bool can_invoke()
{
auto& call_if = static_cast<CallPredicate&>(*this);
return std::move(call_if)(Task(task));
}
bool wait() const
{
return (task->status() == Status::InProgress);
}
InternalTask task;
};
using FinishTask = detail::FunctionTask<FunctionTaskReturn, Invoker>;
assert(task_);
return ReturnTask::template make<FinishTask>(scheduler
, Invoker(std::forward<F>(f), std::move(p), task_));
}
template<typename T, typename E>
template<typename F>
detail::FunctionTaskReturnT<F, const Task<T, E>&>
Task<T, E>::on_finish(Scheduler& scheduler, F&& f)
{
return on_finish_impl(scheduler, std::forward<F>(f)
, [](const Task& self)
{
// Invoke callback in any case
(void)self;
return true;
});
}
template<typename T, typename E>
template<typename F>
detail::FunctionTaskReturnT<F>
Task<T, E>::on_finish(Scheduler& scheduler, F&& f)
{
return on_finish_impl(scheduler, std::forward<F>(f)
, [](const Task&) { return true; });
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::on_finish(F&& f)
-> decltype(on_finish(
std::declval<Scheduler&>(), std::forward<F>(f)))
{
assert(task_);
return on_finish(task_->scheduler(), std::forward<F>(f));
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::then(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)))
{
return on_finish(scheduler, std::forward<F>(f));
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::then(F&& f)
-> decltype(then(
std::declval<Scheduler&>(), std::forward<F>(f)))
{
return then(task_->scheduler(), std::forward<F>(f));
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::on_fail(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)))
{
return on_finish_impl(scheduler, std::forward<F>(f)
, [](const Task& self)
{
return self.is_failed();
});
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::on_fail(F&& f)
-> decltype(on_fail(
std::declval<Scheduler&>(), std::forward<F>(f)))
{
assert(task_);
return on_fail(task_->scheduler(), std::forward<F>(f));
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::on_success(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)))
{
return on_finish_impl(scheduler, std::forward<F>(f)
, [](const Task& self)
{
return self.is_successful();
});
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::on_success(F&& f)
-> decltype(on_success(
std::declval<Scheduler&>(), std::forward<F>(f)))
{
assert(task_);
return on_success(task_->scheduler(), std::forward<F>(f));
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::on_cancel(Scheduler& scheduler, F&& f)
-> decltype(on_finish(scheduler, std::forward<F>(f)))
{
return on_finish_impl(scheduler, std::forward<F>(f)
, [](const Task& self)
{
return self.is_canceled();
});
}
template<typename T, typename E>
template<typename F>
auto Task<T, E>::on_cancel(F&& f)
-> decltype(on_cancel(
std::declval<Scheduler&>(), std::forward<F>(f)))
{
assert(task_);
return on_cancel(task_->scheduler(), std::forward<F>(f));
}
template<typename>
struct is_task : std::false_type { };
template<typename T, typename E>
struct is_task<Task<T, E>> : std::true_type { };
template<typename T, typename E>
struct task_from_expected<expected<T, E>>
{
using type = Task<T, E>;
};
} // namespace nn
| true |
037e330533a9aa3066c01f1b1dd54cdf599aa54d | C++ | csce-315-501-f/project-1 | /tests/RelationTest.cpp | UTF-8 | 4,587 | 3.15625 | 3 | [] | no_license | #include "RelationTest.h"
/**************************************************
* Object Initialization Tests
**************************************************/
bool RelationTest::initTest() {
Relation relation;
return typeid(relation) == typeid(Relation);
}
bool RelationTest::addAttributeTest() {
Relation relation;
bool newAddition = relation.addAttribute("testAttribute","integer",0) == true;
bool repeatAddition = relation.addAttribute("testAttribute","integer",0) == false;
return newAddition && repeatAddition;
}
bool RelationTest::addRowTest() {
Relation relation;
relation.addAttribute("testIntegerAttribute","integer",0);
relation.addAttribute("testIntegerAttribute2","integer",0);
vector<string> testRow;
testRow.push_back("19");
testRow.push_back("11");
bool success = relation.addRow(testRow) != -1;
return success;
}
bool RelationTest::getRowTest() {
Relation relation;
relation.addAttribute("testIntegerAttribute","integer",0);
relation.addAttribute("testIntegerAttribute2","integer",0);
vector<string> testRow;
testRow.push_back("19");
testRow.push_back("11");
relation.addRow(testRow);
vector<string> row = relation.getRow(0);
bool success = row[0] == "19" && row[1] == "11";
return success;
}
bool RelationTest::getRowsWhereTest() {
Relation relation;
relation.addAttribute("testIntegerAttribute","integer",0);
relation.addAttribute("testIntegerAttribute2","integer",0);
vector<string> testRow;
testRow.push_back("19");
testRow.push_back("11");
relation.addRow(testRow);
vector< vector<string> > rows = relation.getRowsWhere("testIntegerAttribute2","11");
return rows[0][0] == "19" && rows[0][1] == "11";
}
bool RelationTest::removeValueTest() {
Relation relation;
relation.addAttribute("testIntegerAttribute","integer",0);
relation.addAttribute("testIntegerAttribute2","integer",0);
vector<string> testRow;
testRow.push_back("19");
testRow.push_back("11");
int insertedKey = relation.addRow(testRow) ;
relation.removeRow(insertedKey);
vector< vector<string> > rows = relation.getRowsWhere("testIntegerAttribute2","11");
return rows.empty();
}
bool RelationTest::updateAttributeValueTest() {
Relation relation;
relation.addAttribute("testIntegerAttribute","integer",0);
vector<string> testRow;
testRow.push_back("19");
int insertedKey = relation.addRow(testRow);
relation.updateAttributeValue(insertedKey,"testIntegerAttribute","8");
vector<string> row = relation.getRow(insertedKey);
bool success = "8" == row[0];
return success;
}
bool RelationTest::renameAttributeTest() {
Relation relation;
relation.addAttribute("testIntegerAttribute","integer",0);
bool successAddAttribute = relation.attributeExists("testIntegerAttribute");
bool successRenameAttribute = relation.renameAttribute("testIntegerAttribute","renamedIntegerAttribute");
return successAddAttribute && successRenameAttribute;
}
bool RelationTest::getAllRowsTest() {
Relation relation;
relation.addAttribute("testIntegerAttribute","integer",0);
relation.addAttribute("testIntegerAttribute2","integer",0);
vector<string> testRow;
testRow.push_back("19");
testRow.push_back("11");
relation.addRow(testRow);
vector< vector<string> > rows = relation.getAllRows();
return rows[0] == testRow;
}
/**************************************************
* Function to run all tests
**************************************************/
void RelationTest::runAll() {
cout << "**************************" << '\n'
<< "* Testing Relation Class *" << '\n'
<< "**************************" << endl;
cout << "initTest: " << (initTest()?"Passed":"Failed") << endl;
cout << "addAttributeTest: " << (addAttributeTest()?"Passed":"Failed") << endl;
cout << "addRowTest: " << (addRowTest()?"Passed":"Failed") << endl;
cout << "getRowTest: " << (getRowTest()?"Passed":"Failed") << endl;
cout << "getRowsWhereTest: " << (getRowsWhereTest()?"Passed":"Failed") << endl;
cout << "removeValueTest: " << (removeValueTest()?"Passed":"Failed") << endl;
cout << "updateAttributeValueTest: " << (updateAttributeValueTest()?"Passed":"Failed") << endl;
cout << "renameAttributeTest: " << (renameAttributeTest()?"Passed":"Failed") << endl;
cout << "getAllRowsTest: " << (getAllRowsTest()?"Passed":"Failed") << endl;
}
| true |
ed23f0d609d7841cb13d24d4b16e4355e1b95d01 | C++ | Deadshot96/Cpp-code | /Sorting/tempQuick.cpp | UTF-8 | 5,930 | 3.65625 | 4 | [] | no_license | # include <iostream>
# include <vector>
using namespace std;
template <typename Comparable>
void PrintArray(vector <Comparable>);
template <typename Comparable>
void quickSort(vector<Comparable> &);
template <typename Comparable>
void quickSort(vector<Comparable> &, size_t, size_t);
template <typename Comparable>
const Comparable & median3(vector <Comparable> &, size_t, size_t);
template <typename Comparable>
void Swap(vector<Comparable> &, size_t, size_t);
template <typename Iterator>
void quickSort(const Iterator &, const Iterator &);
template <typename Iterator, typename Comparator>
void quickSort(const Iterator &, const Iterator &, Comparator);
template <typename Iterator, typename Comparator>
void __quickSort(const Iterator &, const Iterator &, Comparator);
template <typename Comparable>
void insertionSort(vector<Comparable> &, size_t, size_t);
template <typename Iterator, typename Comparator>
void insertionSort(const Iterator &, const Iterator &, Comparator);
template <typename Iterator, typename Comparator>
const Iterator partition(const Iterator &, const Iterator &, Comparator);
template <typename Iterator>
void PrintArray(const Iterator &, const Iterator&);
int main()
{
vector<int> arr{20, 15, 49, 3, 44, 10, 20, 1, 12, 40, 78, 84, 39, 11, 23, 15,
43, 17, 32, 12, 61, 86, 43, 76, 73, 35, 65, 45, 55, 42, 78, 58, 82, 0, 94, 81};
int size = arr.size();
cout << "Hello, World!\n";
cout << "Size of array: " << size << endl;
// Calling the Function
quickSort(arr.begin(), arr.end());
// quickSort(arr.begin(), arr.end(), less<int> {});
PrintArray(arr);
return 0;
}
template<typename Comparable>
void PrintArray(vector<Comparable> arr){
cout << "Printing Array: \n";
for (Comparable a: arr)
{
cout << a << "\t";
}
cout << "\n";
}
template <typename Iterator>
void PrintArray(const Iterator & begin, const Iterator & end){
cout << "Array: ";
for (Iterator i = begin; i <= end; i++)
{
cout << *i << "\t";
}
cout << endl;
}
template <typename Comparable>
void Swap(vector <Comparable> & a, size_t i, size_t j){
Comparable tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
template <typename Comparable>
void insertionSort(vector<Comparable> & a, size_t left, size_t right){
for (size_t i = left + 1; i <= right; i++)
{
Comparable tmp = std::move(a[i]);
size_t j = i;
while (j > left && a[j - 1] >= tmp){
a[j] = std::move(a[j - 1]);
j--;
}
a[j] = std::move(tmp);
}
}
template <typename Comparable>
void quickSort(vector<Comparable> & a){
quickSort(a, 0, a.size() - 1);
}
template <typename Comparable>
const Comparable & median3(vector<Comparable> & a, size_t left, size_t right){
/**
* Return median of left, center, and right.
* Order these and hide the pivot.
* We hide pivot at right - 1 because the element at right is
* already greater than the pivot so it doesn't violate the partitioning
*/
size_t center = left + (right - left) / 2;
if (a[center] < a[left])
Swap(a, left, center);
if (a[right] < a[left])
Swap(a, right, left);
if (a[right] < a[center])
Swap(a, right, center);
// Place pivot at right - 1 index
Swap(a, center, right - 1);
return a[right - 1];
}
template <typename Comparable>
void quickSort(vector<Comparable> & a, size_t left, size_t right){
/**
* Internal quicksort method that makes recursive calls.
* Uses median-of-three partitioning and a cutoff of 10.
* a is an array of Comparable items.
* left is the left-most index of the subarray.
* right is the right-most index of the subarray.
*/
if (left + 10 <= right){
const Comparable & pivot = median3(a, left, right);
size_t i = left, j = right - 1;
while (true){
while (a[++i] < pivot);
while (pivot < a[--j]);
if (i < j)
Swap(a, i, j);
else
break;
}
Swap(a, i, right - 1);
quickSort(a, left, i - 1);
quickSort(a, i + 1, right);
}
else{
insertionSort(a, left ,right);
}
}
template <typename Iterator, typename Comparator>
void insertionSort(const Iterator & begin, const Iterator & end, Comparator lessThan){
// if (begin == end)
// return;
for (Iterator ptr = begin + 1; ptr != end; ptr++)
{
auto tmp = std::move(*ptr);
Iterator j = ptr;
while (j > begin && lessThan(tmp, *(j - 1))){
*j = std::move(*(j - 1));
j--;
}
*j = std::move(tmp);
}
}
template <typename Iterator>
void quickSort(const Iterator & begin, const Iterator & end){
__quickSort(begin, end - 1, less<decltype (*begin)>{});
}
template <typename Iterator, typename Comparator>
void quickSort(const Iterator & begin, const Iterator & end, Comparator lessThan){
__quickSort(begin, end - 1, lessThan);
}
template <typename Iterator, typename Comparator>
const Iterator partition(const Iterator & begin, const Iterator & end, Comparator lessThan){
Iterator i = begin, j = begin;
auto pivot = std::move(*end);
for (j = begin; j <= end; j++){
if (lessThan(*j, pivot)){
std::swap(*i, *j);
i++;
}
if (!lessThan(*j, pivot) && !lessThan(pivot, *j)){
std::swap(*i, *j);
i++;
}
}
return i - 1;
}
template <typename Iterator, typename Comparator>
void __quickSort(const Iterator & begin, const Iterator & end, Comparator lessThan){
if (begin >= end)
return;
const Iterator partitionIdx = partition(begin, end, lessThan);
__quickSort(begin, partitionIdx - 1, lessThan);
__quickSort(partitionIdx + 1, end, lessThan);
} | true |
9f61858637a681dafe1dba24909cdf0d9ae6d982 | C++ | yasushi-saito/libmustache | /src/mustache.cpp | UTF-8 | 1,231 | 2.609375 | 3 | [
"MIT"
] | permissive |
#include <stdio.h>
#include "mustache.hpp"
const char * mustache_version() {
return MUSTACHE_PACKAGE_VERSION;
}
int mustache_version_int() {
int maj = 0, min = 0, rev = 0;
sscanf(MUSTACHE_PACKAGE_VERSION, "%d.%d.%d", &maj, &min, &rev);
return (rev + (100 * min) + (10000 * maj));
}
namespace mustache {
void Mustache::tokenize(std::string * tmpl, Node * root)
{
tokenizer.tokenize(tmpl, root);
}
void Mustache::render(Node * node, Data * data, Node::Partials * partials, std::string * output)
{
renderer.init(node, data, partials, output);
renderer.render();
}
//! Compile a node
void Mustache::compile(Node * node, uint8_t ** codes, size_t * length)
{
std::vector<uint8_t> * vector = compiler.compile(node);
Compiler::vectorToBuffer(vector, codes, length);
}
//! Compile a node (with partials)
void Mustache::compile(Node * node, Node::Partials * partials, uint8_t ** codes, size_t * length)
{
std::vector<uint8_t> * vector = compiler.compile(node, partials);
Compiler::vectorToBuffer(vector, codes, length);
}
//! Execute the VM
void Mustache::execute(uint8_t * codes, int length, Data * data, std::string * output)
{
vm.execute(codes, length, data, output);
}
} // namespace Mustache
| true |
3ead2364d77655cf696f1fc40af4ed24e91ffd43 | C++ | Cod3lta/SchoolboyBattleQt | /schoolBoyBattle/keyinputs.cpp | UTF-8 | 2,976 | 2.859375 | 3 | [] | no_license | /*
* Description : Cette classe ne crée qu’un seul objet.
* Son utilité est de pouvoir capturer les événements du clavier
* au même endroit avant de les envoyer aux objets Player correspondants.
* Version : 1.0.0
* Date : 25.01.2021
* Auteurs : Prétat Valentin, Badel Kevin et Margueron Yasmine
*/
#include "keyinputs.h"
#include <QGraphicsItem>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QApplication>
#include <QKeyEvent>
#include <QRectF>
#include <QDebug>
KeyInputs::KeyInputs(int focusedPlayerId, QGraphicsObject *parent)
: QGraphicsObject(parent)
{
setFlag(QGraphicsItem::ItemIsFocusable, true);
setPlayerKeys(focusedPlayerId);
}
void KeyInputs::keyPress(QKeyEvent * event) {
int key = event->key();
if(playersKeys.contains(key)) {
int playerId = playersKeys.value(key).at(0);
int playerMove = playersKeys.value(key).at(1);
emit playerKeyToggle(
playerId,
playerMove,
true
);
}
}
void KeyInputs::keyRelease(QKeyEvent *event) {
int key = event->key();
if(playersKeys.contains(key)) {
int playerId = playersKeys.value(key).at(0);
int playerMove = playersKeys.value(key).at(1);
emit playerKeyToggle(
playerId,
playerMove,
false
);
}
}
/**
* Déplacements joueurs.
*/
void KeyInputs::setPlayerKeys(int focusedPlayerId) {
if(focusedPlayerId == -1)
focusedPlayerId = 0;
// La clé à presser, {l'id du joueur, la direction}
playersKeys.insert(Qt::Key_W, {focusedPlayerId, up});
playersKeys.insert(Qt::Key_A, {focusedPlayerId, left});
playersKeys.insert(Qt::Key_S, {focusedPlayerId, down});
playersKeys.insert(Qt::Key_D, {focusedPlayerId, right});
if(focusedPlayerId == 0) {
// Si l'id du 1er joueur n'est pas un socketDescriptor
playersKeys.insert(Qt::Key_Up, {1, up});
playersKeys.insert(Qt::Key_Left, {1, left});
playersKeys.insert(Qt::Key_Down, {1, down});
playersKeys.insert(Qt::Key_Right, {1, right});
}
}
// OVERRIDE REQUIRED
/**
* Dessine le contenu de l'article en coordonnées locales.
*/
void KeyInputs::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
Q_UNUSED(painter)
Q_UNUSED(option)
Q_UNUSED(widget)
}
/**
* Retourne les limites extérieures de l'élément sous forme de rectangle.
* Appelé par QGraphicsView pour déterminer quelles régions doivent être redessinées.
*/
QRectF KeyInputs::boundingRect() const {
return QRectF(0, 0, 0, 0);
}
/**
* Détection de collisions.
*/
QPainterPath KeyInputs::shape() const {
QPainterPath path;
path.addEllipse(boundingRect());
return path;
}
| true |
b949c8bbab7c8e5677285e9a07d8e39d6b2ae543 | C++ | jvdbroeck/plugins-siemens-nx | /AddTemperatureLoads/main.cpp | UTF-8 | 3,035 | 2.59375 | 3 | [] | no_license | /* This plugin adds temperature loads to multiple nodes (based on node ID) in an existing simulation.
The temperature data is to be supplied by an external file (1) as described below.
(1) file 'data.csv' in the same directory as the sim/prt files
Format:
0,<t0>,<t1>,...,<tN>
<node0>,<T0>,<T1>,...,<TN>
<node1>,<T0>,<T1>,...,<TN>
...
The first line lists the time step values (tX), in seconds.
The following lines list the node ID (first value), followed by the temperature values for each time step (Tx), in Celcius.
For each node, the following is added to the simulation:
(1) field, "Temperature(xxx)", where 'xxx' is a unique identifier
independent variable: time (seconds)
dependent variable: temperature (Celcius)
(2) load, "Temperature(xxx)", where 'xxx' is a unique identifier
*/
#include "MyNXSupportLib.h"
using namespace NXOpen;
using namespace std;
/* entry point */
extern DllExport void ufusr( char *parm, int *returnCode, int rlen )
{
static int load_index = 0;
static int table_index = 0;
MyNXSupportLib::Init();
MyNXSupportLib::AssumePart();
MyNXSupportLib::AssumeSimulation();
MyNXSupportLib::AssumeSolution();
/* (in)dependent variables */
auto vIndependent = vector<Fields::FieldVariable *>(1, MyNXSupportLib::GetTimeVariableX());
auto vDependent = vector<Fields::FieldVariable *>(1, MyNXSupportLib::GetVariableY("temperature", "Temperature", MyNXSupportLib::GetUnit("Celcius")));
/* open up the input file */
ifstream infile(MyNXSupportLib::FullFilePath("data.csv"));
assert(infile.is_open());
/* read first line as time data */
vector<int> times = MyNXSupportLib::ReadIntData(infile);
/* add load data for each node in the model */
while (!infile.eof()) {
/* read one line from the file and put the data in an array */
vector<int> data = MyNXSupportLib::ReadIntData(infile);
if (data.size() == 0) continue;
/* construct the node data array */
vector<double> node_data;
for (size_t i = 1; i < data.size(); i++) {
node_data.push_back(times[i]);
node_data.push_back(data[i]);
}
/* create temperature load */
string name = MyNXSupportLib::StringConcat("Temperature(", load_index, ")");
/* ... data table */
Fields::FieldTable *table = MyNXSupportLib::CreateFieldTable(name, table_index, vIndependent, vDependent, node_data);
/* ... target node/element */
int node_id = data[0];
MyNXSupportLib::CreateAndAddLoad("tempLoad", name, table_index+1,
MyNXSupportLib::GetNodeObject(node_id), "temperature", table);
load_index++;
}
}
/* Unload Handler
** This function specifies when to unload your application from Unigraphics.
** If your application registers a callback (from a MenuScript item or a
** User Defined Object for example), this function MUST return
** "Session::LibraryUnloadOptionImmediately". */
extern "C" DllExport int ufusr_ask_unload()
{
return (int)Session::LibraryUnloadOptionImmediately;
}
| true |
3778c44cc77fc37c7c794611f740c477b41263c6 | C++ | Jakstor/C-programs | /Jollygame.cpp | UTF-8 | 840 | 2.625 | 3 | [] | no_license | #include<stdio.h>
#include<math.h>
int main()
{
int i,a[100],b[100],j,n,temp;
int flag=0;
int ans=0;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n-1;i++)
{
b[i]=abs(a[i]-a[i+1]);
}
for(i = 0 ;i <n-1;i++)
{
printf("%d ",b[i]);
}
printf("\n");
// n=n-1;
for(i=0;i<n-1;i++)
{
for(j=1;j<n-i-1;j++)
{
if(b[j-1]>b[j])
{
// printf("%d ",b[j-1]);
// printf("%d ",b[j]);
// printf("\n");
temp=b[j];
b[j]=b[j-1];
b[j-1]=temp;
}
}
}
for(i = 0 ;i <n-1;i++)
{
printf("%d ",b[i]);
}
printf("\n");
if(b[0]==1)
{
for(i=0;i<n-1-1;i++)
{
if(abs(b[i]-b[i+1])!=1)
{
flag=1;
}
}
}
else
{
ans = 1;
printf("Not Jolly");
}
if(flag==1 && ans == 0)
{
printf("Not Jolly");
}
else if(ans == 0)
{
printf("Jolly");
}
return(0);
}
| true |
b10cb20e3fc771761d5566144241c2001f2584fc | C++ | Zhanzo/opengl-game-engine | /src/resource_manager.hpp | UTF-8 | 3,052 | 2.84375 | 3 | [] | no_license | #pragma once
#define STB_IMAGE_IMPLEMENTATION
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <glad/glad.h>
#include <stb_image.h>
#include "shader.hpp"
#include "texture.hpp"
class ResourceManager {
public:
ResourceManager() { }
Shader loadShader(const std::string& name, const std::string& vertexShaderFile, const std::string& fragmentShaderFile, const std::string& geometryShaderFile = "")
{
m_shaders[name] = loadShaderFromFile(vertexShaderFile, fragmentShaderFile, geometryShaderFile);
return m_shaders[name];
}
Shader getShader(const std::string& name)
{
return m_shaders[name];
}
Texture2D loadTexture(const std::string& file, bool hasAlpha, const std::string& name)
{
m_textures[name] = loadTextureFromFile(file, hasAlpha);
return m_textures[name];
}
Texture2D getTexture(const std::string& name) const { return m_textures.at(name); }
void clear()
{
for (auto& it : m_shaders)
it.second.deleteShader();
for (auto& it : m_textures)
it.second.deleteTexture();
}
private:
std::map<std::string, Shader> m_shaders;
std::map<std::string, Texture2D> m_textures;
Shader loadShaderFromFile(const std::string& vShaderFile, const std::string& fShaderFile, const std::string& gShaderFile)
{
std::string vertexCode, fragmentCode, geometryCode;
try {
std::ifstream vertexShaderFile { vShaderFile };
std::ifstream fragmentShaderFile { fShaderFile };
std::stringstream vertexShaderStream, fragmentShaderStream;
vertexShaderStream << vertexShaderFile.rdbuf();
fragmentShaderStream << fragmentShaderFile.rdbuf();
vertexShaderFile.close();
fragmentShaderFile.close();
vertexCode = vertexShaderStream.str();
fragmentCode = fragmentShaderStream.str();
if (gShaderFile != "") {
std::ifstream geometryShaderFile(gShaderFile);
std::stringstream geometryShaderStream;
geometryShaderStream << geometryShaderFile.rdbuf();
geometryShaderFile.close();
geometryCode = geometryShaderStream.str();
}
} catch (std::exception e) {
std::cerr << "ERROR::SHADER::Failed to read shader files" << std::endl;
}
Shader shader;
shader.compile(vertexCode, fragmentCode, geometryCode);
return shader;
}
Texture2D loadTextureFromFile(const std::string& file, bool hasAlpha)
{
Texture2D texture;
if (hasAlpha) {
texture.setInternalFormat(GL_RGBA);
texture.setImageFormat(GL_RGBA);
}
// laod image
int width, height, nrChannels;
unsigned char* data { stbi_load(file.c_str(), &width, &height, &nrChannels, 0) };
texture.generate(width, height, data);
stbi_image_free(data);
return texture;
}
};
| true |
3b0124af7517193dfc36eaa2d502426846ca9716 | C++ | ParagDrunkenMonster/PanduEngine | /Pandu/Utils/PANDUFlag.h | UTF-8 | 878 | 2.890625 | 3 | [] | no_license | /********************************************************************
filename: PANDUFlag
author: Parag Moni Boro
purpose: Game Engine created for learning
*********************************************************************/
#ifndef __PANDUFlag_h__
#define __PANDUFlag_h__
namespace Pandu
{
template <typename T> class Flag
{
private:
T m_Flags;
public:
inline Flag() : m_Flags(0){}
inline Flag(T _flag) : m_Flags(_flag){}
inline Flag(const Flag& _flag) : m_Flags(_flag.m_Flags){}
inline ~Flag(){}
inline void SetFlag( T _flag ) { m_Flags = m_Flags | _flag; }
inline void ClearFlag( T _flag ) { m_Flags = m_Flags & ~_flag; }
inline bool CheckFlag( T _flag ) const { return ((m_Flags & _flag) == _flag); }
inline void ResetFlag() { m_Flags = 0; }
};
typedef Flag<unsigned int> TFlag32;
}
#endif //__PANDUFlag_h__ | true |
4841f6471aaa7aea2b61ef2d8739dbb641c98be1 | C++ | cmuparlay/PAM | /examples/tpch/queries/monoid.h | UTF-8 | 1,815 | 3.71875 | 4 | [
"MIT"
] | permissive | #pragma once
#include <limits>
#include <tuple>
#include <array>
// Definition of various monoids
// each consists of:
// T : type of the values
// static T identity() : returns identity for the monoid
// static T add(T, T) : adds two elements, must be associative
template <class TT>
struct Add {
using T = TT;
static T identity() {return (T) 0;}
static T add(T a, T b) {return a + b;}
};
template <class TT>
struct Max {
using T = TT;
static T identity() {
return (T) numeric_limits<T>::min();}
static T add(T a, T b) {return std::max(a,b);}
};
template <class TT>
struct Min {
using T = TT;
static T identity() {
return (T) numeric_limits<T>::max();}
static T add(T a, T b) {return std::min(a,b);}
};
template <class A1, class A2>
struct Add_Pair {
using T = pair<typename A1::T, typename A2::T>;
static T identity() {return T(A1::identity(), A2::identity());}
static T add(T a, T b) {
return T(A1::add(a.first,b.first), A2::add(a.second,b.second));}
};
template <class AT>
struct Add_Array {
using S = tuple_size<AT>;
using T = array<typename AT::value_type, S::value>;
static T identity() {
T r;
for (size_t i=0; i < S::value; i++)
r[i] = 0;
return r;
}
static T add(T a, T b) {
T r;
for (size_t i=0; i < S::value; i++)
r[i] = a[i] + b[i];
return r;
}
};
template <class AT>
struct Add_Nested_Array {
using T = AT;
using S = tuple_size<T>;
using SS = tuple_size<typename AT::value_type>;
static T identity() {
T r;
for (size_t i=0; i < S::value; i++)
for (size_t j=0; j < SS::value; j++) r[i][j] = 0;
return r;
}
static T add(T a, T b) {
T r;
for (size_t i=0; i < S::value; i++)
for (size_t j=0; j < SS::value; j++)
r[i][j] = a[i][j] + b[i][j];
return r;
}
};
| true |
6127403aea03dcb8dafb3cdfa43133d6c45aa60e | C++ | dominichofer/ReversiPerftCUDA | /Core/BitBoard.h | UTF-8 | 6,382 | 2.75 | 3 | [] | no_license | #pragma once
#include <intrin.h>
#include <cassert>
#include <cstdint>
#include "Bit.h"
enum class Field : uint8_t
{
A1, B1, C1, D1, E1, F1, G1, H1,
A2, B2, C2, D2, E2, F2, G2, H2,
A3, B3, C3, D3, E3, F3, G3, H3,
A4, B4, C4, D4, E4, F4, G4, H4,
A5, B5, C5, D5, E5, F5, G5, H5,
A6, B6, C6, D6, E6, F6, G6, H6,
A7, B7, C7, D7, E7, F7, G7, H7,
A8, B8, C8, D8, E8, F8, G8, H8,
invalid
};
// An 8x8 board of binary integers.
class BitBoard
{
uint64_t b{};
public:
constexpr BitBoard() noexcept = default;
CUDA_CALLABLE constexpr BitBoard(uint64_t b) noexcept : b(b) {}
CUDA_CALLABLE constexpr explicit BitBoard(Field f) noexcept : BitBoard(1ULL << static_cast<uint8>(f)) {}
static constexpr BitBoard Bit(int x, int y) noexcept { return 1ULL << (x + y * 8); }
static constexpr BitBoard HorizontalLine(int i) noexcept { return 0xFFULL << (i * 8); }
static constexpr BitBoard VerticalLine(int i) noexcept { return 0x0101010101010101ULL << i; }
static constexpr BitBoard UpperDiagonalLine(int i) noexcept { return 0x8040201008040201ULL << (i * 8); }
static constexpr BitBoard LowerDiagonalLine(int i) noexcept { return 0x8040201008040201ULL >> (i * 8); }
static constexpr BitBoard UpperCodiagonalLine(int i) noexcept { return 0x0102040810204080ULL << (i * 8); }
static constexpr BitBoard LowerCodiagonalLine(int i) noexcept { return 0x0102040810204080ULL >> (i * 8); }
static constexpr BitBoard DiagonalLine(int i) noexcept { return (i > 0) ? UpperDiagonalLine(i) : LowerDiagonalLine(-i); }
static constexpr BitBoard CodiagonalLine(int i) noexcept { return (i > 0) ? UpperCodiagonalLine(i) : LowerCodiagonalLine(-i); }
static constexpr BitBoard Corners() noexcept { return 0x8100000000000081ULL; }
static constexpr BitBoard Edges() noexcept { return 0xFF818181818181FFULL; }
static constexpr BitBoard LeftHalf() noexcept { return 0xF0F0F0F0F0F0F0F0ULL; }
static constexpr BitBoard RightHalf() noexcept { return 0x0F0F0F0F0F0F0F0FULL; }
static constexpr BitBoard UpperHalf() noexcept { return 0xFFFFFFFF00000000ULL; }
static constexpr BitBoard LowerHalf() noexcept { return 0x00000000FFFFFFFFULL; }
static constexpr BitBoard StrictlyLeftUpper() noexcept { return 0xFEFCF8F0E0C08000ULL; }
static constexpr BitBoard StrictlyLeftLower() noexcept { return 0x0080C0E0F0F8FCFEULL; }
static constexpr BitBoard StrictlyRighUppert() noexcept { return 0x7F3F1F0F07030100ULL; }
static constexpr BitBoard StrictlyRighLowert() noexcept { return 0x000103070F1F3F7FULL; }
CUDA_CALLABLE constexpr operator uint64_t() const noexcept { return b; }
CUDA_CALLABLE constexpr BitBoard operator~() const noexcept { return ~b; }
BitBoard& operator&=(const BitBoard& o) noexcept { b &= o.b; return *this; }
BitBoard& operator|=(const BitBoard& o) noexcept { b |= o.b; return *this; }
BitBoard& operator^=(const BitBoard& o) noexcept { b ^= o.b; return *this; }
BitBoard& operator&=(uint64_t o) noexcept { b &= o; return *this; }
BitBoard& operator|=(uint64_t o) noexcept { b |= o; return *this; }
BitBoard& operator^=(uint64_t o) noexcept { b ^= o; return *this; }
friend CUDA_CALLABLE constexpr BitBoard operator&(const BitBoard& l, const BitBoard& r) noexcept { return l.b & r.b; }
friend CUDA_CALLABLE constexpr BitBoard operator|(const BitBoard& l, const BitBoard& r) noexcept { return l.b | r.b; }
friend CUDA_CALLABLE constexpr BitBoard operator^(const BitBoard& l, const BitBoard& r) noexcept { return l.b ^ r.b; }
friend CUDA_CALLABLE constexpr BitBoard operator&(uint64_t l, const BitBoard& r) noexcept { return l & r.b; }
friend CUDA_CALLABLE constexpr BitBoard operator|(uint64_t l, const BitBoard& r) noexcept { return l | r.b; }
friend CUDA_CALLABLE constexpr BitBoard operator^(uint64_t l, const BitBoard& r) noexcept { return l ^ r.b; }
friend CUDA_CALLABLE constexpr BitBoard operator&(const BitBoard& l, uint64_t r) noexcept { return l.b & r; }
friend CUDA_CALLABLE constexpr BitBoard operator|(const BitBoard& l, uint64_t r) noexcept { return l.b | r; }
friend CUDA_CALLABLE constexpr BitBoard operator^(const BitBoard& l, uint64_t r) noexcept { return l.b ^ r; }
//[[nodiscard]] constexpr auto operator<=>(const BitBoard&) const noexcept = default;
[[nodiscard]] CUDA_CALLABLE constexpr bool operator==(const BitBoard& o) const noexcept { return b == o.b; }
[[nodiscard]] CUDA_CALLABLE constexpr bool operator!=(const BitBoard& o) const noexcept { return b != o.b; }
[[nodiscard]] bool Get(Field f) const noexcept { return b & (1ULL << static_cast<uint8>(f)); }
[[nodiscard]] bool Get(int x, int y) const noexcept { return b & (1ULL << (x + 8 * y)); }
constexpr void Set(Field f) noexcept { b |= 1ULL << static_cast<uint8>(f); }
constexpr void Set(int x, int y) noexcept { b |= 1ULL << (x + 8 * y); }
void Clear(Field f) noexcept { b &= ~(1ULL << static_cast<uint8>(f)); }
void Clear(int x, int y) noexcept { b &= ~(1ULL << (x + 8 * y)); }
[[nodiscard]] CUDA_CALLABLE constexpr bool empty() const noexcept { return b == 0; }
[[nodiscard]] CUDA_CALLABLE Field FirstSet() const noexcept { return static_cast<Field>(std::countr_zero(b)); }
CUDA_CALLABLE void ClearFirstSet() noexcept { RemoveLSB(b); }
void FlipCodiagonal() noexcept;
void FlipDiagonal() noexcept;
void FlipHorizontal() noexcept;
void FlipVertical() noexcept;
};
[[nodiscard]] BitBoard FlipCodiagonal(BitBoard) noexcept;
[[nodiscard]] BitBoard FlipDiagonal(BitBoard) noexcept;
[[nodiscard]] BitBoard FlipHorizontal(BitBoard) noexcept;
[[nodiscard]] BitBoard FlipVertical(BitBoard) noexcept;
CUDA_CALLABLE inline int countl_zero(const BitBoard& b) noexcept { return std::countl_zero(static_cast<uint64_t>(b)); }
CUDA_CALLABLE inline int countl_one(const BitBoard& b) noexcept { return std::countl_one(static_cast<uint64_t>(b)); }
CUDA_CALLABLE inline int countr_zero(const BitBoard& b) noexcept { return std::countr_zero(static_cast<uint64_t>(b)); }
CUDA_CALLABLE inline int countr_one(const BitBoard& b) noexcept { return std::countr_one(static_cast<uint64_t>(b)); }
CUDA_CALLABLE inline int popcount(const BitBoard& b) noexcept { return std::popcount(static_cast<uint64_t>(b)); }
constexpr BitBoard operator""_BitBoard(const char* c, std::size_t size)
{
assert(size == 120);
BitBoard bb;
for (int y = 0; y < 8; y++)
for (int x = 0; x < 8; x++)
{
char symbol = c[119 - 15 * y - 2 * x];
if (symbol != '-')
bb.Set(x, y);
}
return bb;
}
| true |
eb48e9621bae287e7176009837d389d88748e0f0 | C++ | knight-erraunt/TSP_solver | /tsp_solver.cpp | UTF-8 | 1,914 | 2.859375 | 3 | [] | no_license | #include "tsp_solver.h"
// inversed comparison operator as we want the cheapest to be first
bool operator<(const search_state & a, const search_state & b) {
return a.exp_cost > b.exp_cost;
}
tsp_solver::tsp_solver(const point_vector & npoints) :
n(npoints.size()),
points(npoints),
current_best(std::numeric_limits<ldouble>::max())
{}
/*
* returns a vector of numbers representing
* which should each point be in the cycle
*/
std::vector<lint> tsp_solver::solve() {
std::priority_queue< search_state > for_search;
std::vector<lint> visited(n, NOT_VISITED);
visited[0] = 0;
for_search.push( search_state(visited, 0, 0, 0) );
while(!for_search.empty()) {
search_state A = for_search.top(), B;
for_search.pop();
if(std::all_of(A.visit_order.begin(), A.visit_order.end(),
[](lint a){return a != NOT_VISITED;})) {
if(current_best > A.cost + cost(0, A.current)) {
current_best = A.cost + cost(0, A.current);
best_order = A.visit_order;
}
continue;
}
for(lint i=1; i<A.visit_order.size(); i++)
if(A.visit_order[i] == NOT_VISITED) {
ldouble expected_cost = A.cost + cost(A.current, i) + heuristics(points, A, i);
if(expected_cost < current_best) {
B = A;
B.visit_order[i] = A.visit_order[A.current] + 1;
B.current = i;
B.cost = A.cost + cost(A.current, i);
B.exp_cost = expected_cost;
for_search.push(B);
}
}
}
return best_order;
}
ldouble tsp_solver::cost(lint curret_node, lint next_node) const {
return dist(points[curret_node], points[next_node]);
}
ldouble tsp_solver::path_len() const {
return current_best;
}
| true |
163be27e712677142bbaedf8c18bd6f492fbc0aa | C++ | chayao2015/c-coco2dx-code- | /function2.cpp | UTF-8 | 2,376 | 3.890625 | 4 | [] | no_license | /*
按照c++ primer第四版 201页 7.22节的说法
普通形参 无法影响实参本身,执行swap时,酯交换了其实参的局部副本,传递给swap的实参本身的值并没有修改
按照此书说法给形参添加了&引用 可以修改
引用类型无法修改const对象 也就是不能通过const对象进行调用
*/
#include<iostream>
using namespace std;
void swt(int &v1,int &v2);
void test(int v1,int v2);
void swp(int &a);
void printValues(const int ia[10]);
const string &manip(string &s);
char &get_val( string &str,string::size_type ix);
int main()
{
int j=10;
int h=20;
swap(j,h);//晕 原来c++自带一个这么函数啊 我晕
cout<<"c++ 自带的一个函数swap \n "<<"原来的J的值是10现在为:"<<j<<"原来的H的值为20,现在值为:"<<h<<endl;
swt(j,h);
cout<<"这个是自己定义的函数swt形参&int\n" <<"原来的J的值是10现在为:"<<j<<"原来的H的值为20,现在值为:"<<h<<endl;
test(j,h);
cout<<"这个是未添加的引用\n"<<"原来的J的值是10现在为:"<<j<<"原来的H的值为20,现在值为:"<<h<<endl;
const int c=99;
// swp(c);
swp(j);
cout<<"原来j的值为10,现在的值为:" <<j<<endl;
int jb=0;
int jh[]={1,2,3};
printValues(&jb);//其实这个操作已经造成数组越界访问了
cout<<"***************************************************************** "<<endl;
printValues(jh);
string ff("天下无敌");
manip(ff);
cout<<manip(ff)<<endl;
string s("a value");
cout<<s<<endl;
get_val(s,2)='f';//其实这个函数的意思是将第几位替换为A
cout<<s<<endl;
return 0;
}
char &get_val( string &str,string::size_type ix)
{
return str[ix];
}
const string &manip( string &s)
{
const string &ret=s;
cout<<ret<<endl;
return ret;
}
void printValues(const int ia[2])
{
for(size_t i=0;i!=10;++i)
{
cout<<"这个是printValues:"<<ia[i]<<endl;
}
}
void swt(int &v1,int &v2)
{
v1=888;
v2=999;
}
void test(int v1,int v2)
{
int tmp=v2;
v2=v1;
v1=tmp;
}
void swp(int &b)
{
b=90;
}
| true |
a5d94320bb3e1979db3b3e823f265e8f3096bd51 | C++ | pmann84/chip8_emulator | /chip8-emulator/chip8/cpu.h | UTF-8 | 1,807 | 2.78125 | 3 | [] | no_license | #pragma once
#include "opcode_executions.h"
#include "constants.h"
#include "opcode.h"
#include "clock.h"
#include "keyboard.h"
#include <array>
namespace chip8
{
class cpu
{
public:
cpu();
// Convenience functions for opcode implementation
void set_program_counter(program_counter_t ctr);
const program_counter_t get_program_counter() const;
void increment_program_counter(program_counter_t increment_amount);
void store_program_counter_in_stack();
void set_program_counter_from_stack();
void set_index_register(index_register_t idx_reg);
index_register_t get_index_register() const;
byte_t get_register(byte_t index) const;
void set_register(byte_t index, byte_t value);
bool is_key_in_register_pressed(byte_t index, const keyboard& keys);
bool check_for_key_press(byte_t reg_idx, const keyboard& keys);
byte_t get_delay_timer() const;
void set_delay_timer(byte_t value);
byte_t get_sound_timer() const;
void set_sound_timer(byte_t value);
void cycle_delay_timer();
void cycle_sound_timer();
void clear();
private:
void clear_registers();
void clear_stack();
void reset_counters();
private:
byte_t m_registers[16]; // 15 Registers + 16th for carry flag
index_register_t m_idx_register = 0; // Index register
uint16_t m_stack[16]; // program stack
stack_ptr_t m_stack_ptr = 0;
program_counter_t m_program_ctr = CHIP8_MEMORY_START; // Program counter that can range from 0x000 -> 0xFFF (0-4095)
byte_t m_delay_timer = 0;
byte_t m_sound_timer = 0;
};
} | true |
2aa2856a1967b0783aa6edd4d7d3bf5635cdd554 | C++ | Maurya-Grover/Competitive_Coding | /Hackerrank/Algorithms/Implementation/strange_counter/strange_counter.cpp | UTF-8 | 512 | 2.640625 | 3 | [] | no_license | #include <bits/stdc++.h>
#define newline cout << "\n"
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
long long int t, currentTop = 3;
cin >> t;
// find max value for given time that is just greater than given time
// along with update diff between top and currTime until top is less than current top
while (t > currentTop)
{
t = t - currentTop;
currentTop = currentTop * 2;
}
cout << currentTop + 1 - t;
return 0;
} | true |
0b658b42fa5e399c841667b7d997de5fdfbd70f6 | C++ | nuchyobitva/sem3_lab3 | /main.cpp | UTF-8 | 1,903 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <chrono>
#include <cmath>
#define MAS_LEN 262144
#define WARM_NUM 100
#define NUM_CYCLE 10
using namespace std;
int main(int argc, const char * argv[]) {
int l = 0;
auto begin = chrono::steady_clock::now();
auto end = chrono::steady_clock::now();
auto elapsed_ms = chrono::duration_cast< chrono::milliseconds>(end - begin);
for (int SizeNum = 0; SizeNum < 5; ++SizeNum) {
if (SizeNum == 4) l = MAS_LEN * 12;
else l = MAS_LEN*(int)pow(2, SizeNum);
int* array = new int[l];
cout << " " << l / MAS_LEN << "Mb -> " ;
for (int j = 0; j < WARM_NUM; ++j) { // "Разогрев"
for (size_t i = 0; i < l; ++i) {
array[i] = 1;
}
}
cout << "Warm Success" << endl<<endl;
begin = chrono::steady_clock::now(); // Forward direction
for (int j = 0; j <NUM_CYCLE; ++j) {
for (size_t i = 0; i < l; ++i) {
array[i] = 1;
}
}
end = chrono::steady_clock::now();
elapsed_ms = chrono::duration_cast< chrono::milliseconds>(end - begin);
cout << "Forward direction time " << elapsed_ms.count() << " ms" << '\n';
// Reverse Diresction
begin = chrono::steady_clock::now();
for (int j = 0; j <NUM_CYCLE; ++j) {
for (size_t i = l - 1; i > 0; --i) {
array[i] = 1;
}
}
end = chrono::steady_clock::now();
elapsed_ms = chrono::duration_cast< chrono::milliseconds>(end - begin);
cout << "Reversed direction time " << elapsed_ms.count() << " ms" << '\n';
begin = chrono::steady_clock::now(); // Random direction
for (int j = 0; j < NUM_CYCLE; ++j) {
for (size_t i = 0; i < l; ++i) {
int t = (int)(rand() % (l));
array[t] = 1;
}
}
end = chrono::steady_clock::now();
elapsed_ms = chrono::duration_cast< chrono::milliseconds>(end - begin);
cout << "Randomly chosen time " << elapsed_ms.count() << " ms" << '\n';
delete[] array;
}
cin.get();
return 0;
}
| true |
2d6e5f575df74ebbee42af6263a32cc912e69e8e | C++ | 99002554/CPP_PROJECT_ENHANCED | /Hotel_Booking/Client.h | UTF-8 | 2,498 | 3.234375 | 3 | [] | no_license | #ifndef CLIENT_H
#define CLIENT_H
using namespace std;
class Client
{
public:
static int Client_Id_count;
int cost_count;
//using csv file to store & check the user data
virtual void check()
{ //Here searching if a client has his / her account
fstream fin;
fin.open("client.csv", ios::in);
double Client_phone,phone,count = 0;
cout << endl<<"Enter the phone number of the client to display details: ";
cin >> Client_phone;
//using vector to get a line at a time
vector<string> row;
string line, word;
while (fin >> line)
{
row.clear();
stringstream s(line);
while (getline(s,word,','))
{
row.push_back(word);
}
phone = atoi(row[2].c_str());
if (Client_phone == phone)
{
count = 1;
//printing the client data
cout << "\n\t\t\tClient ID: " << row[0] << "\n";
cout << "\t\t\tName: " << row[1] << "\n";
cout << "\t\t\tPhone No: " << row[2] << "\n";
cout << "\t\t\tAddress: " << row[3] << "\n";
cout << "\t\t\tNID: " << row[4] << "\n";
break;
}
}
//if the client isn't registered
if (count == 0)
{
cout << "Client is not registered with the Hotel. Please register the client details\n";
update();
}
}
virtual int update()
{
fstream fout; //open file to append new client data
fout.open("client.csv", ios::out | ios::app);
int Client_id; //getting the client informations
string Client_name;
string Client_phone_no;
string Client_address;
cout<<"\nEnter Client ID:";cin>>Client_id;
cout<<endl<<"Enter Client Name:";cin>>Client_name;
cout<<endl<<"Enter Client Phone No:";cin>>Client_phone_no;
cout<<endl<<"Enter Client Address:";cin>>Client_address;
fout << Client_id << "," //printing the client details in csv file
<< Client_name << ","
<< Client_phone_no << ","
<< Client_address << " " ;
fout.close();
}
};
#endif // CLIENT_H
| true |
3e3d6f0ad030d64c2751944ade2472c4c5c9b084 | C++ | Feroz455/The-CPP-Standard-Template-Library-STL | /STL Vectors/back.cpp | UTF-8 | 534 | 3.34375 | 3 | [] | no_license | /*
Cpp_STL_Reference
VECTOR
program back
TYPE & back();
const TYPE & back() const;
*/
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//main begin
int main()
{
vector<int> v;
for(int i = 0; i < 5; i++)
{
v.push_back(i);
}
cout << "The first elements is " << v.front() << " and the last elements is " << v.back() << endl;
getchar();
return 0;
}
//main end
///Program end
/*
output
The first elements is 0 and the last elements is 4
*/
| true |