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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
9f50d68c9d3a02590b2c05d3b11bf258bd6d6e0f | C++ | mourogurt/oage | /src/system/core/Threads/thread_guard.hpp | UTF-8 | 911 | 3.0625 | 3 | [
"MIT"
] | permissive | #ifndef THREAD_GUARD_HPP
#define THREAD_GUARD_HPP
#include <event.hpp>
#include <thread>
/*class thread_guard
{
std::thread t;
std::unique_ptr<EventBase> ev {nullptr};
public:
explicit thread_guard(std::thread&& t_, EventBase&& ev_) noexcept : t(std::move(t_)), ev(&ev_) {}
explicit thread_guard(std::thread&& t_, std::unique_ptr<EventBase>&& ev_) noexcept : t(std::move(t_)), ev(std::move(ev_)) {}
explicit thread_guard(std::thread&& t_) noexcept : t(std::move(t_)) {}
thread_guard(thread_guard const&) = delete;
thread_guard& operator=(thread_guard const&) = delete;
std::thread& operator &() noexcept {
return t;
}
std::thread* operator *() noexcept {
return &t;
}
~thread_guard()
{
if (t.joinable()) {
if (ev != nullptr)
(*ev)();
t.join();
}
}
};*/
#endif // THREAD_GUARD_HPP
| true |
2e3da131ec40c3dd433cf60c9f0db436bacba7ff | C++ | ParkerSD/nlos_rpi | /rpi_files/Documents/wifip2p/driver/p2p_driver/connect.h | UTF-8 | 3,586 | 3 | 3 | [] | no_license | #ifndef CONNECT_HEADER
#define CONNECT_HEADER
#include <string>
/******************** FUNCTION DECLARATIONS ********************/
/**
* Enters the connected state of the program.
* Spawns two threads:
* - Thread 1: Will monitor the connection status of our P2P connection using function: connected_loop()
* - Thread 2: Will open a socket and montior commands from the connected device using function: listen_for_commands() (command_handler.h)
*
* Termination of this function only occurs when the two threads have completed running.
* Currently this only occurs when the device is disconnected from us.
*/
void enter_connected_state();
/**
* Opens a WPA control interface and attempts to register the interface to recieve event messages.
* On success, control_data field will be not null and available for use.
* On failure, control_data field will be null and disposed of. No need to clean up.
* In the case of an attach timeout, this method will attempt to open until it has reached an amount of attempts, MAX_TIMEOUT_ATTEMPTS
* Check for null after calling this function!
*/
void init_and_attach_ctrl();
/**
* Disposes of the WPA control interface as well as terminates all P2P connections
* this driver is responsible for handling.
*/
void dispose_p2p();
/**
* Initializes this program to listen for any signals that an error has occured.
* Ensures the proper disposal of the wpa event listener no matter what happens.
*/
void init_termination_signals();
/**
* Handles ending our p2p service as well as exiting the program on recieving a signal.
* This function should only be called via underlying system methods via registration with the function signal()!
* Function's purpose is to handle cleaning upon any type of program termination.
*/
void signal_callback_handler(int signum);
/**
* Runs a loop which will listen for a P2P-GO-NEG-REQUEST from wpa_ctrl events.
* Upon receiving a connection request, we allow the device to attempt to connect to us using the "virtual push button" connection method.
* control_data MUST be initialized before calling this function for it to work properly!
*/
void connect_loop();
/**
* Runs a loop which will take note of various P2P notifications, such as
*/
void connected_loop();
/**
* Attempts to connect to a device given their mac address.
* This function blocks until a connection has been established, or connection attempt fails.
*/
bool connect_to_device(std::string mac_address);
/**
* Recieves a pending message from wpa_ctrl.
* Returns true or false based on the message successfully being fetched.
*/
bool recieve_message(char* reply_buffer, size_t* reply_len);
/**
* Determines if a wpa_ctrl message is of a message type.
* NOTE: Does not take into account the prefix of each message; adjust PREFIX_LEN to the length of the prefix of your system.
*/
bool is_message_type(char* message, size_t message_len, std::string message_type);
/**
* Fetches the mac address from a P2P-GO-NEG-REQUEST.
* Function is only guarenteed to work when it has been confirmed that this is a P2P-GO-NEG-REQUEST;
* Ensure that it is by using the function is_message_type before using function.
*/
std::string get_mac_from_neg_request(char* message);
/**
* Fetches the name of a group from a P2P-GROUP-STARTED message.
* Function is only guarenteed to work when it has been confirmed that this is a P2P-GROUP-STARTED;
* Ensure that it is by using the function is_message_type before using function.
*/
std::string get_group_name_from_group_started(char* message);
#endif // CONNECT_HEADER
| true |
8d9087e5401a006c7405f340d29c258a10e63129 | C++ | ForPertP/The-Bomberman-Game | /The-Bomberman-Game.cpp | UTF-8 | 1,461 | 3.171875 | 3 | [] | no_license | void detonate(vector<string>& grid, const vector<string>& previous_grid)
{
size_t r{ grid.size() };
size_t c{ grid[0].size() };
for (int i = 0; i < r; ++i)
{
for (int j = 0; j < c; ++j)
{
if (previous_grid[i][j] == 'O')
{
grid[i][j] = '.';
if (i + 1 < r)
grid[i + 1][j] = '.';
if (i - 1 >= 0)
grid[i - 1][j] = '.';
if (j + 1 < c)
grid[i][j + 1] = '.';
if (j - 1 >= 0)
grid[i][j - 1] = '.';
}
}
}
}
vector<string> bomberMan(int n, vector<string> grid)
{
vector<string> initial_grid{ grid };
vector<string> full_of_bombs{ grid };
vector<string> pattern_a;
size_t r{ grid.size() };
size_t c{ grid[0].size() };
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
grid[i][j] = 'O';
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
full_of_bombs[i][j] = 'O';
detonate(grid, initial_grid);
pattern_a = grid;
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j)
grid[i][j] = 'O';
detonate(grid, pattern_a);
int k{ n % 4 };
if (n == 1)
return initial_grid;
if (k == 0 || k == 2)
return full_of_bombs;
else if (k == 3)
return pattern_a;
return grid;
}
| true |
ca7dd66982bc9937d70b06dad7bef2969a4aabf5 | C++ | rxtsolar/finger-game | /server/gs_epoll.h | UTF-8 | 1,428 | 2.75 | 3 | [] | no_license | #ifndef _GS_EPOLL_H_
#define _GS_EPOLL_H_
#include "gs_socket.h"
#include <cstring>
#include <fcntl.h>
#include <sys/epoll.h>
namespace gs {
struct Data {
int fd;
unsigned int len;
char buf[2048];
Data() { }
Data(const char* s, const int l)
{
memcpy(buf, s, l);
}
};
class EpollManager {
public:
EpollManager(int n)
{
fd = epoll_create(1);
if (fd < 0) {
perror("epoll_create");
exit(-1);
}
maxEvents = n;
timeout = -1;
}
int addSocket(int sock)
{
epoll_event e;
e.events = EPOLLIN | EPOLLET;
e.data.fd = sock;
fcntl(sock, F_SETFL, O_NONBLOCK);
return epoll_ctl(fd, EPOLL_CTL_ADD, sock, &e);
}
void modIn(int index)
{
epoll_event e;
e.data.fd = *(int*)events[index].data.ptr;
e.events = EPOLLIN | EPOLLET;
epoll_ctl(fd, EPOLL_CTL_MOD, *(int*)events[index].data.ptr, &e);
}
void modOut(int index, Data* data)
{
epoll_event e;
data->fd = events[index].data.fd;
e.data.ptr = data;
e.events = EPOLLOUT | EPOLLET;
epoll_ctl(fd, EPOLL_CTL_MOD, events[index].data.fd, &e);
}
int wait(void)
{
return epoll_wait(fd, events, maxEvents, timeout);
}
TCPSocket getSocket(int index)
{
return TCPSocket(events[index].data.fd);
}
TCPSocket getSocket(Data* data)
{
return TCPSocket(data->fd);
}
Data* getData(int index)
{
return (Data*)events[index].data.ptr;
}
private:
int fd;
int maxEvents;
int timeout;
epoll_event* events;
};
}
#endif
| true |
3a5c0d20d0ec0bb0632aad2763d0cf610128e490 | C++ | chidaa/Smart-Project | /Smart/jeu.h | UTF-8 | 596 | 2.515625 | 3 | [] | no_license | #ifndef JEU_H
#define JEU_H
#include <QString>
#include <QSqlQuery>
#include <QSqlQueryModel>
class Jeu
{
public:
Jeu();
Jeu(int,QString,int,int);
int get_jeu_id(){return jeu_id;}
QString get_type_jeu(){return type_jeu;}
int get_nombre_tick(){return nbr_tick;}
int get_nombre_enf(){return nbr_enf;}
bool ajouter();
QSqlQueryModel * afficher();
QSqlQueryModel * afficher_trie();
bool supprimer(int);
bool modifier(int);
QSqlQueryModel * recherche(const QString&);
private:
QString type_jeu;
int jeu_id,nbr_tick,nbr_enf;
};
#endif // JEU_H
| true |
a888c180a16bafcf987b4674710edd831fc72adf | C++ | micyril/AIWars | /WebHandler/WebHandler/WebSocketPacket.h | UTF-8 | 757 | 2.671875 | 3 | [] | no_license | #pragma once
#include <Windows.h>
#include <string>
using namespace std;
enum WebSocketMessageType {
TextData = 1,
BinaryData = 2,
AnyData = TextData | BinaryData,
Ping = 4,
Pong = 8,
Close = 16,
UnknownType = 0
};
class WebSocketPacket {
private:
BYTE flags_opcode;
BYTE mask_len;
WORD exlen;
unsigned long long exlen2;
BYTE mask_key[4];
BYTE *data;
public:
WebSocketPacket();
~WebSocketPacket();
// данные из d будут скопированы
void setData(BYTE *d, unsigned long long len);
// просто вернет длину если d == 0
unsigned long long getData(BYTE *d);
void ping();
void pong();
void close();
WebSocketMessageType getType();
void sendTo(SOCKET s);
void recvFrom(SOCKET s);
};
| true |
e244fd19e1a872287ef7a03be79eb6243e32cf5f | C++ | JeissonNaveros16/NaverosJeisson_Ejercicio30 | /EDPelip.cpp | UTF-8 | 1,917 | 3.046875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <cmath>
#include "stdio.h"
void init(double *psi, int n_x);
void print(double *psi, int n_x);
void copy(double *recibe, double *entrega, int n_x);
double evolve(double *psi_new, double *psi_old, double delta_x, int n_x, double m, double p);
void save(double **almacen, double *temporal, int n_x, int t);
int main(int argc, char **argv)
{
double *psi = NULL;
double *psi_past = NULL;
int n_x;
double delta_x;
psi = new double [n_x];
psi_past = new double [n_x];
for(int i = 1; i < 11; i++)
{
n_x=atoi(argv[i+1]);
delta_x = 2.0/n_x;
init(psi, n_x);
double maxCamb = 1.0;
double maxPsi = 0.0;
int nItera = 0;
while(maxCamb > 0.000001)
{
copy(psi_past, psi, n_x);
maxCamb, maxPsi = evolve(psi, psi_past, delta_x, n_x, maxCamb, maxPsi);
nItera++;
}
double epsilon = abs(maxCamb/maxPsi);
std::cout << n_x << " " << nItera << " " << epsilon << " " << psi[n_x/2] << "\n";
}
return 0;
}
double evolve(double *psi_new, double *psi_old, double delta_x, int n_x, double m, double p)
{
int i;
double mx = m;
double px = p;
for(i=1;i<n_x-1;i++)
{
psi_new[i] = 0.5*psi_old[i+1] + 0.5*psi_old[i-1] + delta_x*delta_x/2;
if(psi_new[i]-psi_old[i] > mx)
{
mx = (psi_new[i]-psi_old[i]);
p = psi_old[i];
}
}
return mx, px;
}
void copy(double *recibe, double *entrega, int n_x)
{
int i;
for (i=0;i<n_x;i++)
{
recibe[i] = entrega[i];
}
}
void save(double **almacen, double *temporal, int n_x, int t)
{
int i;
for (i=0;i<n_x;i++)
{
almacen[t][i] = temporal[i];
}
}
void init(double *psi, int n_x)
{
int i;
for(i=0;i<n_x;i++)
{
psi[i] = 0.0;
}
}
void print(double *psi, int n_x)
{
int i;
for(i=0;i<n_x;i++)
{
std::cout << psi[i] << " ";
}
std::cout << "\n";
} | true |
04ba9e59a1cfda4c38ebed8b5304c73abb91fb6a | C++ | KRHero03/CompetitiveCoding | /Codeforces/1379A.cpp | UTF-8 | 2,509 | 2.53125 | 3 | [] | no_license | /*
author: KRHero
IDE: VSCode
*/
#include <bits/stdc++.h>
#define ll long long int
#define ull unsigned long long int
#define MOD 1000000007
#define f(i, a, b) for (int i = a; i < b; i++)
#define fe(i, a, b) for (int i = a; i <= b; i++)
#define fd(i, a, b) for (int i = b; i > a; i--)
#define fde(i, a, b) for (int i = b; i >= a; i--)
#define fastio \
cin.tie(0); \
cout.tie(0); \
ios_base::sync_with_stdio(false);
#define debug(x) cout << '>' << #x << ':' << x << endl;
#define MID(s, e) (s + (e - s) / 2)
#define whilet() \
int t; \
cin >> t; \
while (t--)
#define F first
#define S second
#define mp make_pair
#define epsilon 1e-15
#define pb push_back
#define PI 3.1415926535897932384626433832
using namespace std;
void solve()
{
ll n;
cin >> n;
string s;
cin >> s;
ll cnt = 0;
f(i, 0, n - 6)
{
string temp = s.substr(i, 7);
if (temp == "abacaba")
cnt++;
}
if (cnt >= 2)
{
cout << "No" << endl;
return;
}
if (cnt == 1)
{
cout << "Yes" << endl;
f(i, 0, n)
{
if (s[i] != '?')
cout << s[i];
else
cout << 'z';
}
cout << endl;
return;
}
f(i, 0, n - 6)
{
if ((s[i] == 'a' || s[i] == '?') && (s[i + 1] == 'b' || s[i + 1] == '?') && (s[i + 2] == 'a' || s[i + 2] == '?') && (s[i + 3] == 'c' || s[i + 3] == '?') && (s[i + 4] == 'a' || s[i + 4] == '?') && (s[i + 5] == 'b' || s[i + 5] == '?') && (s[i + 6] == 'a' || s[i + 6] == '?'))
{
string s1 = s;
s1[i] = 'a';
s1[i + 1] = 'b';
s1[i + 2] = 'a';
s1[i + 3] = 'c';
s1[i + 4] = 'a';
s1[i + 5] = 'b';
s1[i + 6] = 'a';
ll pass = 0;
ll cnt1 = 0;
f(j, 0, n - 6)
{
string temp = s1.substr(j, 7);
if (temp == "abacaba")
cnt1++;
}
if (cnt1 == 1)
{
cout << "Yes" << endl;
f(i, 0, n)
{
if (s1[i] == '?')
cout << 'z';
else
cout << s1[i];
}
cout << endl;
return;
}
}
}
cout << "No" << endl;
return;
}
int main()
{
whilet()
{
solve();
}
}
| true |
57cd33ccdb4c24b846aafe938ad1ea6ecc0bbd78 | C++ | Nodmgatall/R | /Rcpp/pir_heidmann-presentation/test/src/RcppExports.cpp | UTF-8 | 1,016 | 2.640625 | 3 | [] | no_license | // This file was generated by Rcpp::compileAttributes
// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
#include <Rcpp.h>
#include <vector>
using namespace Rcpp;
void rcpp_hello_world();
int return_given_value(int value);
std::vector<int> add_lists(std::vector<int> vec1, std::vector<int> vec2);
// rcpp_hello_world
RcppExport SEXP test_rcpp_hello_world() {
BEGIN_RCPP
Rcpp::RObject __result;
__result = 1;
rcpp_hello_world();
return __result;
END_RCPP;
}
// example showing how to paese a number(in this case int)
RcppExport SEXP test_return_given_value(SEXP value) {
BEGIN_RCPP
int a = Rcpp::as<int>(value);
int __result = return_given_value(a);
return Rcpp::wrap(__result);
END_RCPP
}
// example showing how to parse a vector of ints
RcppExport SEXP test_add_lists(SEXP vec1, SEXP vec2) {
BEGIN_RCPP
Rcpp::RObject __result;
__result =
add_lists(Rcpp::as<std::vector<int>>(vec1), Rcpp::as<std::vector<int>>(vec2));
return Rcpp::wrap(__result);
END_RCPP
}
| true |
041f1ccfe6fc58372547dc33eaca18b9ce1fb99c | C++ | AlirezaShamsoshoara/gfpop | /src/Edge.h | UTF-8 | 502 | 2.65625 | 3 | [] | no_license | #ifndef EDGE_H
#define EDGE_H
#include<string>
#include "Rcpp.h"
class Edge
{
public:
Edge();
Edge(double b, int s1 = 0, int s2 = 0, Rcpp::String cstt = "std", double param = 0);
double getBeta() const;
int getState1() const;
int getState2() const;
std::string getConstraint() const;
double getParameter() const;
void show() const;
private:
double beta;
int state1;
int state2;
std::string constraint;
double parameter;
};
#endif // EDGE_H
| true |
dc88e842ed8d547567be804609b6219b5b3fcb93 | C++ | mevoroth/eternal-engine-core | /src/Core/Level.cpp | UTF-8 | 1,210 | 2.671875 | 3 | [] | no_license | #include "Core/Level.hpp"
#include "Core/GameObject.hpp"
namespace Eternal
{
namespace Core
{
Level::Level()
: WorldObject()
{
_GameObjects.reserve(GameObjectsInitialPool);
}
void Level::SetWorld(_In_ World* InWorld)
{
WorldObject::SetWorld(InWorld);
for (uint32_t GameObjectIndex = 0; GameObjectIndex < _GameObjects.size(); ++GameObjectIndex)
_GameObjects[GameObjectIndex]->SetWorld(InWorld);
}
void Level::AddGameObject(_In_ GameObject* InGameObject)
{
_GameObjects.push_back(InGameObject);
InGameObject->SetParent(this);
}
void Level::RemoveGameObject(_In_ GameObject* InGameObject)
{
InGameObject->SetParent(nullptr);
vector<GameObject*>::iterator GameObjectIterator = remove(_GameObjects.begin(), _GameObjects.end(), InGameObject);
}
void Level::Update(_In_ const TimeSecondsT InDeltaSeconds)
{
for (uint32_t GameObjectIndex = 0; GameObjectIndex < _GameObjects.size(); ++GameObjectIndex)
_GameObjects[GameObjectIndex]->Update(InDeltaSeconds);
}
void Level::UpdateDebug()
{
for (uint32_t GameObjectIndex = 0; GameObjectIndex < _GameObjects.size(); ++GameObjectIndex)
_GameObjects[GameObjectIndex]->UpdateDebug();
}
}
}
| true |
4961523b8abfbed5270af7589f26323ee81f630e | C++ | willstudy/LeetCode | /strstr.cpp | UTF-8 | 1,648 | 3.78125 | 4 | [] | no_license | /*
Implement strStr().
Returns the index of the first occurrence of needle in haystack,
or -1 if needle is not part of haystack.
*/
class Solution {
public:
int strStr(string haystack, string needle) {
int size1 = haystack.size();
int size2 = needle.size();
int i, j;
int index = 0;
i = 0;
j = 0;
while( i < size1 && j < size2 )
{
i = index;
while( haystack[i] == needle[j] && j < size2 && i < size1 )
{
i++;
j++;
}
if( j == size2 ) break;
j = 0;
index++;
}
if( j == size2 ) return i - j;
return -1;
}
};
/*
* KMP algorithm
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> generate( string pattern )
{
int size = pattern.size();
int len = 0;
int i;
vector<int> next(size, 0);
for( i = 1, len = 0; i < size; )
{
if( pattern[i] == pattern[len] )
{
next[i++] = ++len;
}
else if( len ) len = next[len-1];
else next[i++] = 0;
}
return next;
}
int strstr( string text, string pattern )
{
int size1 = text.size();
int size2 = pattern.size();
int i, j;
vector<int> next = generate(pattern);
for( i = 0, j = 0; i < size1; )
{
if( text[i] == pattern[j] )
{
i++;
j++;
}
if( j == size2 ) return i - j;
if( i < size1 && text[i] != pattern[j] )
{
if( j ) j = next[j-1];
else i++;
}
}
return -1;
}
int main()
{
string text = "abcdefgabcdabcd";
string pattern = "abcdabcd";
cout << strstr( text, pattern ) << endl;
return 0;
}
| true |
50c4ca5b8cbd077bc3c94b656e21fbf90110da23 | C++ | wangxinalex/LeetCode-1 | /Palindrome Number.cpp | UTF-8 | 510 | 3.21875 | 3 | [] | no_license | class Solution
{
public:
bool isPalindrome(int x)
{
if (x < 0)
{
return false;
}
int digit[12] = {0};
int count = 0;
while (x != 0)
{
digit[count++] = x % 10;
x /= 10;
}
for (int i = 0; i < count / 2; ++i)
{
if (digit[i] != digit[count - 1 - i])
{
return false;
}
}
return true;
}
};
| true |
e89c8cf4d7168dde36636f8ea0c90909c1a3dec7 | C++ | abidon/pbxbuild | /pbxbuild/base_object.hpp | UTF-8 | 442 | 2.625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <memory>
#include <string>
namespace pbx
{
class Project;
class BaseObject
{
std::weak_ptr<pbx::Project> _project;
std::string _uid;
public:
BaseObject(const std::shared_ptr<pbx::Project>& project, const std::string& uid);
virtual ~BaseObject() = 0;
std::weak_ptr<pbx::Project>&
project();
const std::weak_ptr<pbx::Project>&
project() const;
const std::string&
uid() const;
};
}
| true |
2643bebb054cf5d4a3d1eb412d53b185ce19edc5 | C++ | smallsunsun1/Cpp-tools | /libs/simple_thread_pool.cpp | UTF-8 | 1,381 | 2.765625 | 3 | [] | no_license | //
// Created by 孙嘉禾 on 2020/1/22.
//
#include "simple_thread_pool.h"
thread_local WorkStealingThreadPool::Data* WorkStealingThreadPool::local_queue_;
thread_local unsigned WorkStealingThreadPool::index_;
bool WorkStealingThreadPool::PopTaskFromLocalQueue(WorkStealingThreadPool::Task &task) {
if (!local_queue_)
return false;
else {
std::lock_guard<std::mutex> lock_guard(local_queue_->mu_);
if (local_queue_->tasks_.empty())
return false;
task = local_queue_->tasks_.front();
local_queue_->tasks_.pop_front();
queues_[index_]->size_.fetch_sub(1);
return true;
}
}
bool WorkStealingThreadPool::PopTaskFromOtherThreadQueue(WorkStealingThreadPool::Task &task) {
for (unsigned int i = 0; i < queues_.size(); ++i) {
unsigned const index = (index_ + i + 1) % queues_.size();
std::lock_guard<std::mutex> lock_guard(queues_[index]->mu_);
if (!queues_[index]->tasks_.empty()){
task = queues_[index]->tasks_.front();
queues_[index]->tasks_.pop_front();
queues_[index]->size_.fetch_sub(1);
return true;
}
}
return false;
}
void WorkStealingThreadPool::RunTask() {
Task task;
if (PopTaskFromLocalQueue(task)) {
task();
num_jobs_.fetch_sub(1);
} else if (PopTaskFromOtherThreadQueue(task)) {
task();
num_jobs_.fetch_sub(1);
}
else{
std::this_thread::yield();
}
}
| true |
ea1d205ac6106b25b045894f6a3cdc88597394f1 | C++ | OC-MCS/p2finalproject-02-josephkarch1 | /game/textureManager.h | UTF-8 | 5,162 | 3.046875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
using namespace std;
#include <SFML/Graphics.hpp>
using namespace sf;
class textureManager
{
private:
Texture shipTexture; // holds the texture for the ship / russell westbrook
Texture starsTexture; // holds the texture for the stars background / OKC thunder home court
Texture missileTexture; // holds the texture for the missile / cupcake
Texture enemyTexture; // holds the texture for the enemy / level 1 bad guy, kevin durant
Texture enemyTexture2; // holds the texture for the enemy / level 2 bad guy, angry kevin durant
Texture bombTexture; // holds the texture for the enemy bombs / kevin durant attack weapon, the NBA trophy
RectangleShape startButton; // shape of the start button, click and start the game
RectangleShape winButton; // shape of the win button, click and it restarts the game
RectangleShape loseButton; // shape of the lose button, click and it restarts the game
public:
textureManager()
{
// load all the textures that will be used in the program
if (!shipTexture.loadFromFile("ship.png"))
{
cout << "Unable to load ship texture!" << endl;
exit(EXIT_FAILURE);
}
if (!starsTexture.loadFromFile("stars.png"))
{
cout << "Unable to load stars texture!" << endl;
exit(EXIT_FAILURE);
}
if (!missileTexture.loadFromFile("missile.png"))
{
cout << "Unable to load missile texture!" << endl;
exit(EXIT_FAILURE);
}
if (!enemyTexture.loadFromFile("enemy.png"))
{
cout << "Unable to load enemy texture!" << endl;
exit(EXIT_FAILURE);
}
if (!enemyTexture2.loadFromFile("enemy2.png"))
{
cout << "Unable to load enemy texture!" << endl;
exit(EXIT_FAILURE);
}
if (!bombTexture.loadFromFile("bomb.png"))
{
cout << "Unable to load bomb texture!" << endl;
exit(EXIT_FAILURE);
}
// load all the buttons that will be used in the game
Vector2f sqPos1(300, 300);
startButton.setPosition(sqPos1);
startButton.setOutlineColor(Color::White);
startButton.setOutlineThickness(3);
startButton.setSize(Vector2f(200, 100));
startButton.setFillColor(Color::White);
Vector2f sqPos2(300, 300);
winButton.setPosition(sqPos1);
winButton.setOutlineColor(Color::White);
winButton.setOutlineThickness(3);
winButton.setSize(Vector2f(200, 100));
winButton.setFillColor(Color::White);
Vector2f sqPos3(300, 300);
loseButton.setPosition(sqPos1);
loseButton.setOutlineColor(Color::White);
loseButton.setOutlineThickness(3);
loseButton.setSize(Vector2f(200, 100));
loseButton.setFillColor(Color::White);
// load the fonts we will need
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
{
die("couldn't load font");
}
}
//================================================================================
// drawStartButton: draws the start button
// parameters: RenderWindow& win
// return type: void
//================================================================================
void drawStartButton(RenderWindow& win)
{
win.draw(startButton);
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
{
die("couldn't load font");
}
Text startButtonTitle("Click to Start!", font, 24);
startButtonTitle.setPosition(325, 325);
startButtonTitle.setFillColor(sf::Color::Blue);
win.draw(startButtonTitle);
}
//================================================================================
// drawWinButton: draws the win button
// parameters: RenderWindow& win
// return type: void
//================================================================================
void drawWinButton(RenderWindow& win)
{
win.draw(winButton);
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
{
die("couldn't load font");
}
Text winButtonTitle("You Win! Click to Replay!", font, 16);
winButtonTitle.setPosition(325, 325);
winButtonTitle.setFillColor(sf::Color::Blue);
win.draw(winButtonTitle);
}
//================================================================================
// drawLoseButton: draws the lose button
// parameters: RenderWindow& win
// return type: void
//================================================================================
void drawLoseButton(RenderWindow& win)
{
win.draw(loseButton);
Font font;
if (!font.loadFromFile("C:\\Windows\\Fonts\\arial.ttf"))
{
die("couldn't load font");
}
Text loseButtonTitle("You Lose! Click to Replay!", font, 16);
loseButtonTitle.setPosition(325, 325);
loseButtonTitle.setFillColor(sf::Color::Blue);
win.draw(loseButtonTitle);
}
// the following getter functions allow other classes to pull the textures from the texture manager to be used elsewhere
RectangleShape &getStartButton()
{
return startButton;
}
Texture &getShipTexture()
{
return shipTexture;
}
Texture &getStarsTexture()
{
return starsTexture;
}
Texture &getMissileTexture()
{
return missileTexture;
}
Texture &getEnemyTexture()
{
return enemyTexture;
}
Texture &getEnemyTexture2()
{
return enemyTexture2;
}
Texture &getBombTexture()
{
return bombTexture;
}
};
| true |
ded095a5b0c916060d4fe9c871d3ba43c2ab2754 | C++ | Kamil7260/Age_of_War | /src/GameClass/CannonSpawner.hpp | UTF-8 | 900 | 2.78125 | 3 | [] | no_license | #pragma once
#include "../Base/Actor.hpp"
#include <functional>
class CannonSpawner : public base::Actor {
public:
CannonSpawner();
CannonSpawner(const CannonSpawner& source) = default;
CannonSpawner(CannonSpawner&& source) = default;
CannonSpawner& operator=(const CannonSpawner& source) = default;
CannonSpawner& operator=(CannonSpawner&& source) = default;
virtual ~CannonSpawner() = default;
virtual void setTexture(const sf::Texture& tex);
virtual void move(const sf::Vector2f& delta) override;
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const override;
virtual void onUpdate() override;
virtual void setPosition(const sf::Vector2f& pos) override;
virtual void setScale(const sf::Vector2f& sca) override;
virtual void setCallbackOnRelease(const std::function<void()>& callme);
protected:
sf::Sprite m_sprite;
std::function<void()> m_spawnCallback;
}; | true |
332fe04f86ce892dc6a4ad16c4af06f74afd5632 | C++ | Naivedya02/learning101 | /C++HRQ16.cpp | UTF-8 | 3,299 | 3.28125 | 3 | [] | no_license |
#include<bits/stdc++.h>
using namespace std;
class Box{
private:
int length,breadth,height;
public:
void setlength(int l){
length = l;
}
void setbreadth(int b){
breadth = b;
}
void setheight(int h){
height = h;
}
Box(){
setlength(0);
setbreadth(0);
setheight(0);
}
Box(int l, int b, int h){
setlength(l);
setbreadth(b);
setheight(h);
}
Box(const Box &W){
setlength(W.length);
setbreadth(W.breadth);
setheight(W.height);
};
int getLength(){
return length;
}
int getBreadth(){
return breadth;
}
int getHeight(){
return height;
}
long long CalculateVolume(){
return (long long)length*(long long)breadth*height;
}
bool operator<(Box& b){
if(length<b.length) return true;
if(breadth<b.breadth && length==b.length) return true;
if(height<b.height && breadth==b.breadth && length==b.length) return true;
else return false;
}
friend ostream& operator<<(ostream& out, Box& B);
};
ostream& operator<<(ostream& out, Box& B){
out << B.getLength() << " " << B.getBreadth() << " " << B.getHeight();
return out;
}
void check2()
{
int n;
cin>>n;
Box temp;
for(int i=0;i<n;i++)
{
int type;
cin>>type;
if(type ==1)
{
cout<<temp<<endl;
}
if(type == 2)
{
int l,b,h;
cin>>l>>b>>h;
Box NewBox(l,b,h);
temp=NewBox;
cout<<temp<<endl;
}
if(type==3)
{
int l,b,h;
cin>>l>>b>>h;
Box NewBox(l,b,h);
if(NewBox<temp)
{
cout<<"Lesser\n";
}
else
{
cout<<"Greater\n";
}
}
if(type==4)
{
cout<<temp.CalculateVolume()<<endl;
}
if(type==5)
{
Box NewBox(temp);
cout<<NewBox<<endl;
}
}
}
int main()
{
check2();
}
| true |
e7867fb435a0d2a10286bc9c42eefb9d815347f4 | C++ | LuisBarcenas14/Programacion-Competitiva | /Otros/minimax.cpp | UTF-8 | 3,385 | 3.078125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
#define endl '\n'
const int MAX = 10;
bool gano(char c, char tablero[MAX][MAX],int n){
bool horizontal;
for(int i=0; i<n; i++){
horizontal=true;
for(int j=0; horizontal && j<n; j++){
if(tablero[i][j] != c)
horizontal=false;
}
if(horizontal)
return true;
}
bool vertical;
for(int i=0; i<n; i++){
vertical=true;
for(int j=0; vertical && j<n; j++){
if(tablero[j][i] != c)
vertical=false;
}
if(vertical)
return true;
}
bool diagonal1=true,diagonal2=true;
for(int i=0, j=n-1; i<n; i++, j--){
if(tablero[i][i]!=c)
diagonal1=false;
if(tablero[i][j]!=c)
diagonal2=false;
}
return (diagonal1 || diagonal2);
}
bool lleno(int n,char tablero[MAX][MAX]){
for(int i=0; i<n; i++){
for(int j=0; j<n; j++)
if(tablero[i][j]=='_')
return false;
}
return true;
}
int esFin(int n, char tablero[MAX][MAX]){
if(gano('x', tablero, n))
return 1; //cout<<"Gano X"<<endl;
else if(gano('o', tablero, n))
return 2; //cout<<"Gano O"<<endl;
else if(lleno(n, tablero))
return 0; //cout<<"empate"<<endl;
else
return -1;//cout<<"Juego en progreso"<<endl;
}
void dibujarTablero(int n, char tablero[MAX][MAX]){
for(int i=0; i<n; i++){
cout<<tablero[i][0];
for(int j=1; j<n; j++)
cout<<" | "<<tablero[i][j];
cout<<endl;
for(int k=0; k<n; k++)
cout<<"---";
cout<<endl;
}
}
void reiniciar(int n, char tablero[MAX][MAX]){
//tablero={{',',',',','},{',',',',','},{',',',',','}};
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
tablero[i][j]='_';
}
int main(){
int n=3;
char tablero[MAX][MAX];
reiniciar(n, tablero);
//esFin(n,tablero);
bool jugar=true;
int x,y,num,fin=-1;
cout<<"El gato funciona de la siguiente forma:\nEn cada turno debe introducir un número del 1 al "<<n*n;
cout<<" que no haya sido marcado.\nSiendo que la esquina superior izquierda es 1 y la esquina inferior derecha es "<<n*n<<endl;
string s;
while(jugar){
for(int i=0; i<n*n; i++){
cout<<"Introduzca un número de 1 a "<<n*n<<": ";
while(cin>>num){
num--;
y=num%n;
x=num/n;
if(tablero[x][y] == '_')
break;
cout<<"MARCADO teclee otro número: ";
}
if(i%2==0){
tablero[x][y]='x';
}else{
tablero[x][y]='o';
}
//cout<<"hi"<<endl;
fin = esFin(n, tablero);
//cout<<"fin esFin xd"<<endl;
dibujarTablero(n, tablero);
if(fin>=0){
if(fin==0)
cout<<"Empate"<<endl;
else if(fin==1)
cout<<"Gano X"<<endl;
else if(fin==2)
cout<<"Gano O"<<endl;
break;
}
}
cout<<"Desea iniciar una nueva partida? S/N ";
cin>>s;
if(!(s=="s" || s=="S"))
jugar=false;
reiniciar(n, tablero);
}
return 0;
}
| true |
de4800ed0942ef62a87efc77cf62fa74781503cc | C++ | kennethhu418/LeetCode_Practice | /Maximal_Rectangle/Maximal_Rectangle.cpp | GB18030 | 4,247 | 3.25 | 3 | [] | no_license | // Maximal_Rectangle.cpp : ̨Ӧóڵ㡣
//
#include "stdafx.h"
#include <vector>
#include <stack>
#include <assert.h>
using namespace std;
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
vector<vector<int>> verticalLineLengthOfPoints;
int rows = matrix.size();
if (rows == 0) return 0;
int cols = matrix[0].size();
if (cols == 0) return 0;
getVerticalLineLengthOfPoints(matrix, verticalLineLengthOfPoints);
int maxRectArea = 0;
int curRowMaxRectArea = 0;
for (int i = 0; i < rows; i++)
{
curRowMaxRectArea = getMaxRectAreaInHist(verticalLineLengthOfPoints[i]);
if (curRowMaxRectArea > maxRectArea)
maxRectArea = curRowMaxRectArea;
}
return maxRectArea;
}
private:
void getVerticalLineLengthOfPoints(const vector<vector<char> > &matrix, vector<vector<int>>& resultArr)
{
int rows = matrix.size();
if (rows == 0) return;
int cols = matrix[0].size();
if (cols == 0) return;
resultArr.resize(rows);
for (int i = 0; i < rows; i++)
resultArr[i].resize(cols);
for (int i = 0; i < cols; i++)
{
if (matrix[rows - 1][i] == '0')
resultArr[rows - 1][i] = 0;
else
resultArr[rows - 1][i] = 1;
}
for (int i = rows - 2; i >= 0; i--)
{
for (int j = 0; j < cols; j++)
{
if (matrix[i][j] == '0')
resultArr[i][j] = 0;
else
resultArr[i][j] = 1 + resultArr[i + 1][j];
}
}
return;
}
int getMaxRectAreaInHist(vector<int> &height) {
int n = height.size();
if (n == 0)
return 0;
if (n == 1)
return height[0];
/*data stack is to store each height. And the heights stored in the stack
*are in non-decending order from bottom to top*/
stack<int> dataStack;
/*Each element in width stack is corresponding to each height in data stack.
* It records how many consecutive heights in the current height's left
* side are smaller than the current height, so the current width means
* how many width can the current height be extended to the left side
* to form a rectangle.*/
stack<int> widthStack;
int maxRectArea = height[0];
dataStack.push(height[0]);
widthStack.push(1);
int originalLastHeight = height[n - 1];
int curIndex = 1;
bool hasPushedEndData = false;
int curWidth = 0;
int curArea = 0;
while (curIndex < n)
{
assert(!dataStack.empty());
assert(!widthStack.empty());
if (height[curIndex] >= dataStack.top())
{
dataStack.push(height[curIndex]);
widthStack.push(1);
}
else
{
curWidth = 0;
while (!dataStack.empty() && dataStack.top() > height[curIndex])
{
assert(!widthStack.empty());
curWidth += widthStack.top();
curArea = curWidth*dataStack.top();
widthStack.pop();
dataStack.pop();
if (curArea > maxRectArea)
maxRectArea = curArea;
}
dataStack.push(height[curIndex]);
widthStack.push((1 + curWidth));
}
if (!hasPushedEndData && curIndex + 1 == n)
{
height[curIndex] = 0;
hasPushedEndData = true;
continue;
}
curIndex++;
}
height[n - 1] = originalLastHeight;
return maxRectArea;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
vector<char> v;
v.push_back('0');
v.push_back('1');
vector<vector<char>> vv;
vv.push_back(v);
Solution so;
so.maximalRectangle(vv);
return 0;
} | true |
4a9d728f84fbb4979c133c68286ec0a0f7318d46 | C++ | marcphilippebeaujean-abertay/archaic-arena | /sfml_server.h | UTF-8 | 950 | 2.828125 | 3 | [] | no_license | #pragma once
#include "connection_manager.h"
class sfml_server : public connection_manager
{
public:
sfml_server(sf::IpAddress hostAddr, unsigned short serverport, sf::Time blockingTimeval, int nrOfPlayers);
~sfml_server();
// override functions
void update(float& deltaTime) override;
void handleGameStart() override;
void closeConnection() override;
// getters
void tcpServerRecieveMessage(sf::TcpSocket& client);
private:
struct Connection
{
sf::TcpSocket* clientSocket;
bool connected;
};
// define the nr of players that need to connect before a game starts
int playerNr = 1;
// define the maximum nr of players for a game
#define MAX_PLAYERS 4
// listener used to grab TCP connections
sf::TcpListener* tcpListener;
// vector that stores information on the connections made
Connection connectedPlayers[MAX_PLAYERS];
// selector that is used to wait and handle multiple connections
sf::SocketSelector* selector;
};
| true |
71cb540bae7b846605ddde5db0a6936498b6133c | C++ | dsfb/topicosProgramacao | /aula12/src/CadastroPessoas.cpp | UTF-8 | 9,686 | 3.1875 | 3 | [] | no_license | /**
PCS2478 - Tópicos de Programação
CadastroPessoas.cpp
@author 8586861 - Luiz Eduardo Sol (luizedusol@gmail.com)
@author 7576829 - Augusto Ruy Machado (augustormachado@gmail.com)
@version 1.0 2017-10-11
*/
#include "CadastroPessoas.h"
#include <iostream>
using namespace std;
// Construtores da classe CadastroPessoas
CadastroPessoas::CadastroPessoas(){}
CadastroPessoas::CadastroPessoas(string dados){
}
// Destrutor da classe CadastroPessoas
CadastroPessoas::~CadastroPessoas(){
delete &(this->dadosPessoais);
}
// Setters e Getters
vector<string> CadastroPessoas::getDadosPessoais(){
return this->dadosPessoais;
}
/**
Valida uma string de dados de cadastro.
@param dados (string): a string a ser validada
@return true se a string for válida, false caso contrário
*/
bool CadastroPessoas::validarDados(string dados){
if(dados.back() != '\n'){ // String termina em '/n'?
return false;
}
vector<string> resultado;
try { // String é parseável?
resultado = CadastroPessoas::splitDado(dados);
} catch (int e) {
return false;
}
if(resultado.size() != 10){ // String tem 9 campos?
return false;
}
try { // O estado funcional é um inteiro?
std::stoi(resultado[2]);
} catch (int e) {
return false;
}
return true;
}
/**
Adiciona uma string de dados ao array de dados pessoais.
@param dados (string): a string a ser adicionada
@param sobrescrever (bool): true se a adição deve sobrescrever os dados de
um usuário com o mesmo idPessoa
@return true se a string foi adicionada, false caso contrário
@throw caso haja a tentativa de sobrescrever um usuário e o argumento
'sobrescrever' seja false (domain_error)
*/
bool CadastroPessoas::adicionarDadosPessoa(string dados,
bool sobrescrever){
if(CadastroPessoas::validarDados(dados)){
string idPessoa = CadastroPessoas::splitDado(dados)[0];
int indice = CadastroPessoas::getIndicePessoa(idPessoa);
if(indice == -1){ // Pessoa ainda não cadastrada
this->dadosPessoais.push_back(dados);
return true;
} else if(sobrescrever) { // Pessoa já cadastrada, vamos sobrescrever
this->dadosPessoais[indice] = dados;
return true;
}
}
throw std::domain_error("CadastroPessoas::adicionarDadosPessoa: "
"Tentativa de subscricao de pessoa ja cadastrada");
}
/**
Adiciona uma string contendo várias strings de dados ao array de dados
pessoais.
@param dados (string): a string dos dados a serem adicionados
@param sobrescrever (bool): true se a adição deve sobrescrever os dados de
um usuário com o mesmo idPessoa
@return true se todos os dados foram adicionados, false caso contrário
@throw caso sejam passados dados inválidos (invalid_argument)
@throw caso outro cadastro já possua esse ID Pessoa (domain_error)
*/
bool CadastroPessoas::adicionarDadosPessoas(bool sobrescrever){
string dados;
dados = acessoDados.lerTudo(CAD_PESSOAS);
vector<string> linhas;
string linha;
istringstream f(dados);
// Transformando a string de linhas em vetores
while (std::getline(f, linha)) {
linha.push_back('\n');
linhas.push_back(linha);
}
// Validando as linhas
for(unsigned int i = 0; i < linhas.size(); i++){
// A linha é válida?
if(! CadastroPessoas::validarDados(linhas[i])){
throw std::invalid_argument("CadastroPessoas::adicionarDadosPessoas:"
" dados invalidos");
}
string idPessoa = CadastroPessoas::splitDado(linhas[i])[0];
// Caso não possa sobrescrever, já existe algum usuário com esse idPessoa?
if(!sobrescrever && CadastroPessoas::getIndicePessoa(idPessoa) != -1) {
throw std::domain_error("CadastroPessoas::adicionarDadosPessoas:"
" outro cadastro ja possui esse ID Pessoa");
}
}
for(unsigned int i = 0; i < linhas.size(); i++){ // Adicionando as linhas
CadastroPessoas::adicionarDadosPessoa(linhas[i]);
}
return true;
}
/**
Retorna uma string obtida pela concatenação de todos os dados no vetor de
dados pessoais.
@return a string resultante da concatenação de todos os dados contidos no
vetor de dados pessoais
*/
string CadastroPessoas::lerDadosTodasPessoas(){
string resultado;
resultado = acessoDados.ler(CAD_PESSOAS, "", C_IDPESSOA);
return resultado;
}
/**
Retorna uma string com os dados de uma pessoa.
@param idPessoa (string): o id da pessoa a ser buscada
@return a string contendo os dados da pessoa
@throw caso os idPessoa não exista (domain_error)
*/
string CadastroPessoas::lerDadosPessoa(string idPessoa){
int indice = CadastroPessoas::getIndicePessoa(idPessoa);
if(indice == -1){
throw std::domain_error("CadastroPessoas::lerDadosPessoa:"
" ID Pessoa inexistente.");
} else {
return this->dadosPessoais[indice];
}
}
/**
Atualiza os dados de uma pessoa.
@param dados (string): os novos dados a serem atualizados
@return true se a operação foi bem sucedida, false caso contrario
@throw caso sejam passados dados inválidos (invalid_argument)
@throw caso os idPessoa não exista (domain_error)
*/
bool CadastroPessoas::atualizarDadosPessoa(string dados){
if(!CadastroPessoas::validarDados(dados)){
throw std::invalid_argument("CadastroPessoas::atualizarDadosPessoa:"
" dados invalidos");
}
vector<string> resultado = CadastroPessoas::splitDado(dados);
int indice = CadastroPessoas::getIndicePessoa(resultado[0]);
if(indice == -1){
throw std::domain_error("CadastroPessoas::atualizarDadosPessoa:"
" ID Pessoa inexistente.");
}
return CadastroPessoas::adicionarDadosPessoa(dados, true);
}
/**
Retorna um vector de strings contendo os diferentes campos de uma linha de
dados de pessoa.
@param dado (string): o dado a ser processado
@return o vetor de strings contendo os diferentes campos de uma linha de
dados de pessoa
@throw caso o argumento seja inválido (invalid_argument)
*/
vector<string> CadastroPessoas::splitDado(string dado){
vector<string> result;
unsigned int start = 0;
unsigned int i = 1;
while(i < dado.length()-1){
if(dado.at(i) == '|'){
if(start == i){
throw std::invalid_argument("String invalida.");
}
result.push_back(dado.substr(start, i-start));
start = i + 1;
}
i++;
}
return result;
}
/**
Determina o índice do vector dadosPessoais em que está uma linha contendo
os dados de uma determinada pessoa.
@param idPessoa (string): o id da pessoa a ser localizada
@return o índice da string contida no dadosPessoais caso ela exista, -1
caso contrário
*/
int CadastroPessoas::getIndicePessoa(string idPessoa){
for(unsigned int i = 0; i < this->dadosPessoais.size(); i++){
if(CadastroPessoas::splitDado(this->dadosPessoais[i])[0] == idPessoa){
return i;
}
}
return -1;
}
/**
Gera uma linha formatada contendo os dados relativos a uma pessoa.
@param idPessoa (string): o id da pessoa
@param idFuncional (string): o idFuncional da pessoa
@param estadoFuncional (string): o estado funcional da pessoa
@param nome (string): o nome da pessoa
@param profissao (string): a profissão da pessoa
@param endereco (string): o endereco da pessoa
@param funcao (string): a funcao da pessoa
@param cargo (string): o cargo da pessoa
@param faixaSalarial (string): a faixa salarial da pessoa
@param gratificacao (string): a gratificação salarial da pessoa
@return a string formatada contendo os dados da pessoa
*/
string CadastroPessoas::gerarLinha(string idPessoa, string idFuncional,
string estadoFuncional, string nome,
string profissao, string endereco,
string funcao, string cargo,
string faixaSalarial, string gratificacao){
return idPessoa + "|" + idFuncional + "|" + estadoFuncional + "|" + nome +
"|" + profissao + "|" + endereco + "|" + funcao + "|" + cargo + "|" +
faixaSalarial + "|" + gratificacao + "|\n";
}
string CadastroPessoas::lerDadosPessoas(string valorChave, Campos chave)
{
return acessoDados.ler(CAD_PESSOAS, valorChave, chave);
}
string CadastroPessoas::dadosCP()
{
return acessoDados.lerTudo(CAD_PESSOAS);
}
bool CadastroPessoas::atualizarDadosPessoas(string valChave, Campos chave, string novoValor, Campos campo)
{
return acessoDados.atualizar(CAD_PESSOAS, valChave,chave, novoValor,campo);
}
bool CadastroPessoas::inserir(string idPessoal, string idFuncional, string estadoFuncional, string nome, string profissao, string endereco, string funcao, string cargo, string faixaSalarial, string gratificacao)
{
string pessoa = idPessoal + "|" + idFuncional + "|" + estadoFuncional + "|" + nome + "|" + profissao + "|" + endereco + "|" + funcao + "|" + cargo + "|" + faixaSalarial + "|" + gratificacao + "|";
return this->acessoDados.inserir(CAD_PESSOAS,pessoa);
}
bool CadastroPessoas::excluirPessoa(string idPessoal)
{
return this->acessoDados.excluir(CAD_PESSOAS, idPessoal, C_IDPESSOA);
}
| true |
1e18b5aaab0c47c3bf2e059230e2d785a545350b | C++ | oLESHIYka/PdfConsoleParser_QT | /PdfConsoleParser_QT/source/Text/Style/TextStyle.h | WINDOWS-1251 | 6,861 | 3.015625 | 3 | [] | no_license | #pragma once
/*====================================================*\
TextType.h - TextType
\*====================================================*/
#include "../../MaybeType/MaybeType.h"
#include <unordered_map>
#include <functional>
#define ENUMERABLE_STYLE_FIELD_DECLARATION(enumType, fieldName, ...) \
public: \
MaybeType<enumType> fieldName; \
private: \
std::unordered_map<std::string, enumType> fieldName##Map; /*__VA_ARGS__;*/ \
void set_##fieldName##(const std::string& value); \
public: \
bool get_##fieldName##Enum(enumType##& _enum, const std::string& _str) \
{ \
bool res = false; \
auto resEnum = fieldName##Map.find(_str); \
if (res = (resEnum != fieldName##Map.end())) \
{ \
_enum = resEnum->second; \
} \
return res; \
}; \
bool get_##fieldName##Str(const enumType _enum, std::string &_str) \
{ \
bool res = false; \
\
for (auto pair = fieldName##Map.begin(); pair != fieldName##Map.end(); ++pair) \
{ \
if (pair->second == _enum) \
{ \
_str = pair->first; \
res = true; \
} \
} \
\
return res; \
}
#define STYLE_FIELD_DECLARATION(fieldType, fieldName) \
public: \
fieldType fieldName; \
private: \
void set_##fieldName##(const std::string& value);
using uint32 = unsigned int;
struct RGB_color
{
MaybeType<uint32> red
, green
, blue
, alpha;
};
class TextStyle
{
template<typename> friend class MaybeType;
using SetterFunction = void(TextStyle::*)(const std::string&);
std::unordered_map<std::string, SetterFunction> settersMap;
public:
TextStyle();
~TextStyle() {};
enum class FAMILY
{
SERIF = 0
, SANS_SERIF
, CURSIVE
, FANTASY
, MONOSPACE
};
enum class WEIGHT
{
BOLD = 0
, BOLDER
, LIGHTER
, NORMAL
, ONE_HUNDRED = 100
, TWO_HUNDRED = 200
, THREE_HUNDRED = 300
, FOUR_HUNDRED = 400
, FIVE_HUNDRED = 500
, SIX_HUNDRED = 600
, SEVEN_HUNDRED = 700
, EIGHT_HUNDRED = 800
, NINE_HUNDRED = 900
};
enum class STYLE
{
NORMAL = 0
, ITALIC
, OBLIQUE
};
enum class VERTICAL_ALIGN
{
BASELINE = 0
, BOTTOM
, MIDDLE
, SUB
, SUPER
, TEXT_BOTTOM
, TEXT_TOP
, TOP
};
STYLE_FIELD_DECLARATION(MaybeType<uint32>, left )
STYLE_FIELD_DECLARATION(MaybeType<uint32>, top )
STYLE_FIELD_DECLARATION(MaybeType<uint32>, fontSize)
STYLE_FIELD_DECLARATION(RGB_color , color )
ENUMERABLE_STYLE_FIELD_DECLARATION(FAMILY, fontFamily,
{
{ "serif" , FAMILY::SERIF },
{ "sans-serif" , FAMILY::SANS_SERIF},
{ "cursive" , FAMILY::CURSIVE },
{ "fantasy" , FAMILY::FANTASY },
{ "monospace" , FAMILY::MONOSPACE }
}
)
ENUMERABLE_STYLE_FIELD_DECLARATION(WEIGHT, fontWeight,
{
{ "bold" , WEIGHT::BOLD },
{ "bolder" , WEIGHT::BOLDER },
{ "lighter" , WEIGHT::LIGHTER },
{ "normal" , WEIGHT::NORMAL },
{ "100" , WEIGHT::ONE_HUNDRED },
{ "200" , WEIGHT::TWO_HUNDRED },
{ "300" , WEIGHT::THREE_HUNDRED },
{ "400" , WEIGHT::FOUR_HUNDRED },
{ "500" , WEIGHT::FIVE_HUNDRED },
{ "600" , WEIGHT::SIX_HUNDRED },
{ "700" , WEIGHT::SEVEN_HUNDRED },
{ "800" , WEIGHT::EIGHT_HUNDRED },
{ "900" , WEIGHT::NINE_HUNDRED }
}
)
ENUMERABLE_STYLE_FIELD_DECLARATION(STYLE, fontStyle,
{
{ "normal" , STYLE::NORMAL },
{ "italic" , STYLE::ITALIC },
{ "oblique" , STYLE::OBLIQUE }
}
)
ENUMERABLE_STYLE_FIELD_DECLARATION(VERTICAL_ALIGN, verticalAlign,
{
{ "baseline" , VERTICAL_ALIGN::BASELINE },
{ "bottom" , VERTICAL_ALIGN::BOTTOM },
{ "middle" , VERTICAL_ALIGN::MIDDLE },
{ "sub" , VERTICAL_ALIGN::SUB },
{ "super" , VERTICAL_ALIGN::SUPER },
{ "text-bottom", VERTICAL_ALIGN::TEXT_BOTTOM },
{ "text-top" , VERTICAL_ALIGN::TEXT_TOP },
{ "top" , VERTICAL_ALIGN::TOP }
}
)
void concat(const TextStyle& _style);
private:
template<typename type>
void compareFields(MaybeType<type>& _old, const MaybeType<type>& _new);
public:
bool parse(std::string& rule);
public:
std::string print();
}; | true |
38b9da5d9329bed4b485c0d09c05ef1a6afb9a23 | C++ | dorkosaurus/engine | /gvector.h | UTF-8 | 777 | 2.65625 | 3 | [] | no_license | #include <math.h>
#include <sstream>
#include <string>
using namespace std;
#ifndef GVector_H
#define GVector_H
class GVector{
private:
double x,y,z;
double length;
public:
double GetX();
double GetY();
double GetZ();
double GetLength();
GVector Scale(double scalar);
double DotProduct(GVector A);
double SquaredDotProduct();
double Length();
GVector PerpendicularXY();
GVector Add(GVector c);
GVector(double x_length,double y_length, double z_length);
bool Equals(GVector c);
string ToString();
};
#endif
| true |
7dd54b47980c9b1b2240a03f0da70b2b57999c9b | C++ | adamurish/roborebels | /RoboRebels2014/src/org/stlpriory/robotics/I2CFromChiefDelphi.ino | UTF-8 | 4,340 | 3.140625 | 3 | [] | no_license | #include <Wire.h>
byte dataToSend = 0;
unsigned long counter = 0;
byte data2[6] = {11, 12, 13, 14, 15, 16};
void setup()
{
Wire.begin(2); // Start I2C interface (address 2)
Wire.onReceive(i2cReceive); // Receive ISR routine
Wire.onRequest(i2cRequest); // Request (send) ISR routine
Serial.begin(9600);
Serial.println("Starting up!");
}
void loop()
{
delay(10); // 10 milliseond delay
// Increment a counter every loop. Since the ISR may interrupt this code at any time,
// we need to disable interrupts during the increment operation so the ISR can't a
// partially updated value.
noInterrupts();
counter++;
interrupts();
}
// This routine is called by the ISR once a complete transmission is received from the master
void i2cReceive(int count)
{
byte i2cCount; // Loop/Array counter
byte tmp; // temporary byte holder
byte i2cDataR[7]; // 7 Bytes in length as that is the
// maximum that can be sent by the
// cRIO
Serial.println("Data received from cRIO!");
for (i2cCount = 0; i2cCount < count; i2cCount++) // Read data into local buffer
{ // looping through the entire message
tmp = Wire.read();
if (i2cCount < 7) // If more than 7 bytes in length,
i2cDataR[i2cCount] = tmp; // discard remaining data as somthing
} // is wrong.
// the first byte read is typically what is called the register to be read/written. This
// example utilizes it as a "command" either to be executed or the type of data to be returned
// when a "request" is received.
switch (i2cDataR[0]) // Perform action based on command
{
// Command 1: Return the counter value when the "request" occurs
case 1:
dataToSend = 1; // Set a "global" variable for use by
break; // the i2cRequest routine
// Command 2: Update data 2 array with what ever data is sent (if any) and allow this data
// to be returned to the master if it is requested
case 2:
dataToSend = 2; // Communication for i2cRequest
if (i2cCount > 1) // More than just the command byte
memcpy(&data2[0], &i2cDataR[1], i2cCount < 7 ? // Limit the data to copy to 6 max
i2cCount - 1 : 6); // so as to not overflow the array
}
}
// This routine is called when the master requests the slave send data. A full transaction
// typically includes a Receive envent (register to send) followed by a Request event where the
// slave data is actually transmitted to the master.
void i2cRequest()
{
byte i2cDataW[7];
byte length;
Serial.println("Data sent to cRIO!");
// I use the first byte of the data array to send a comfirmation of the information that follows.
// This allows the cRIO a way to check what "message" is being sent from the Arduino and interpret
// it correctly. While this does limit the actual data part of the message to 6 bytes, the extra
// verification, I feel, is worth it.
switch (dataToSend) // variable set in the i2cReceive event
{
// Return the value of the counter
case 1:
i2cDataW[0] = 1;
memcpy(&i2cDataW[1], &counter, 4);
length = 5;
break;
// Return the contents of the cRIO read/write array
case 2:
i2cDataW[0] = 2;
memcpy(&i2cDataW[1], &data2[0], 6);
length = 7;
break;
// Unknown or invalid command. Send an error byte back
default:
i2cDataW[0] = 0xFF;
length = 1;
}
Wire.write((uint8_t *) &i2cDataW[0], length);
}
| true |
c1c048e7dc908618a7707dba11212d0538bded93 | C++ | jg-maon/test | /ListQuickSort/source/Random.inl | UTF-8 | 391 | 2.875 | 3 | [] | no_license |
namespace ns_Random
{
template<typename ValueType> inline ValueType Random::GetRandom(const ValueType& min, const ValueType& max)
{
::std::uniform_real_distribution<ValueType> range(min, max);
return range(m_engine);
}
template<> inline int Random::GetRandom<int>(const int& min, const int& max)
{
std::uniform_int_distribution<> range(min, max);
return range(m_engine);
}
} | true |
82b027ad47dbed40dddbbe114bbbc8f2d748f7be | C++ | niuxu18/logTracker-old | /second/download/CMake/CMake-old-new/CMake-old-new-joern/Kitware_CMake_old_new_old_function_891.cpp | UTF-8 | 4,444 | 2.734375 | 3 | [] | no_license | const void *
__archive_read_filter_ahead(struct archive_read_filter *filter,
size_t min, ssize_t *avail)
{
ssize_t bytes_read;
size_t tocopy;
if (filter->fatal) {
if (avail)
*avail = ARCHIVE_FATAL;
return (NULL);
}
/*
* Keep pulling more data until we can satisfy the request.
*/
for (;;) {
/*
* If we can satisfy from the copy buffer (and the
* copy buffer isn't empty), we're done. In particular,
* note that min == 0 is a perfectly well-defined
* request.
*/
if (filter->avail >= min && filter->avail > 0) {
if (avail != NULL)
*avail = filter->avail;
return (filter->next);
}
/*
* We can satisfy directly from client buffer if everything
* currently in the copy buffer is still in the client buffer.
*/
if (filter->client_total >= filter->client_avail + filter->avail
&& filter->client_avail + filter->avail >= min) {
/* "Roll back" to client buffer. */
filter->client_avail += filter->avail;
filter->client_next -= filter->avail;
/* Copy buffer is now empty. */
filter->avail = 0;
filter->next = filter->buffer;
/* Return data from client buffer. */
if (avail != NULL)
*avail = filter->client_avail;
return (filter->client_next);
}
/* Move data forward in copy buffer if necessary. */
if (filter->next > filter->buffer &&
filter->next + min > filter->buffer + filter->buffer_size) {
if (filter->avail > 0)
memmove(filter->buffer, filter->next, filter->avail);
filter->next = filter->buffer;
}
/* If we've used up the client data, get more. */
if (filter->client_avail <= 0) {
if (filter->end_of_file) {
if (avail != NULL)
*avail = 0;
return (NULL);
}
bytes_read = (filter->read)(filter,
&filter->client_buff);
if (bytes_read < 0) { /* Read error. */
filter->client_total = filter->client_avail = 0;
filter->client_next = filter->client_buff = NULL;
filter->fatal = 1;
if (avail != NULL)
*avail = ARCHIVE_FATAL;
return (NULL);
}
if (bytes_read == 0) { /* Premature end-of-file. */
filter->client_total = filter->client_avail = 0;
filter->client_next = filter->client_buff = NULL;
filter->end_of_file = 1;
/* Return whatever we do have. */
if (avail != NULL)
*avail = filter->avail;
return (NULL);
}
filter->client_total = bytes_read;
filter->client_avail = filter->client_total;
filter->client_next = filter->client_buff;
}
else
{
/*
* We can't satisfy the request from the copy
* buffer or the existing client data, so we
* need to copy more client data over to the
* copy buffer.
*/
/* Ensure the buffer is big enough. */
if (min > filter->buffer_size) {
size_t s, t;
char *p;
/* Double the buffer; watch for overflow. */
s = t = filter->buffer_size;
if (s == 0)
s = min;
while (s < min) {
t *= 2;
if (t <= s) { /* Integer overflow! */
archive_set_error(
&filter->archive->archive,
ENOMEM,
"Unable to allocate copy buffer");
filter->fatal = 1;
if (avail != NULL)
*avail = ARCHIVE_FATAL;
return (NULL);
}
s = t;
}
/* Now s >= min, so allocate a new buffer. */
p = (char *)malloc(s);
if (p == NULL) {
archive_set_error(
&filter->archive->archive,
ENOMEM,
"Unable to allocate copy buffer");
filter->fatal = 1;
if (avail != NULL)
*avail = ARCHIVE_FATAL;
return (NULL);
}
/* Move data into newly-enlarged buffer. */
if (filter->avail > 0)
memmove(p, filter->next, filter->avail);
free(filter->buffer);
filter->next = filter->buffer = p;
filter->buffer_size = s;
}
/* We can add client data to copy buffer. */
/* First estimate: copy to fill rest of buffer. */
tocopy = (filter->buffer + filter->buffer_size)
- (filter->next + filter->avail);
/* Don't waste time buffering more than we need to. */
if (tocopy + filter->avail > min)
tocopy = min - filter->avail;
/* Don't copy more than is available. */
if (tocopy > filter->client_avail)
tocopy = filter->client_avail;
memcpy(filter->next + filter->avail, filter->client_next,
tocopy);
/* Remove this data from client buffer. */
filter->client_next += tocopy;
filter->client_avail -= tocopy;
/* add it to copy buffer. */
filter->avail += tocopy;
}
}
} | true |
9717a1c17ccad1f44a22307eb9b209bc9d58f767 | C++ | pjanotti/signalfx-dotnet-tracing | /shared/src/native-src/string.cpp | UTF-8 | 2,549 | 2.859375 | 3 | [
"MIT",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | #include "string.h"
#ifdef _WIN32
#include <Windows.h>
#define tmp_buffer_size 512
#else
#include "miniutf.hpp"
#endif
namespace shared {
std::string ToString(const std::string& str) { return str; }
std::string ToString(const char* str) { return std::string(str); }
std::string ToString(const uint64_t i) { return std::to_string(i); }
std::string ToString(const WSTRING& wstr) { return ToString(wstr.data(), wstr.size()); }
std::string ToString(const WCHAR* wstr, std::size_t nbChars)
{
#ifdef _WIN32
if (nbChars == 0) return std::string();
char tmpStr[tmp_buffer_size] = {0};
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)nbChars, &tmpStr[0], tmp_buffer_size, NULL, NULL);
if (size_needed < tmp_buffer_size)
{
return std::string(tmpStr, size_needed);
}
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)nbChars, &strTo[0], size_needed, NULL, NULL);
return strTo;
#else
std::u16string ustr(reinterpret_cast<const char16_t*>(wstr), nbChars);
return miniutf::to_utf8(ustr);
#endif
}
WSTRING ToWSTRING(const std::string& str) {
#ifdef _WIN32
if (str.empty()) return std::wstring();
wchar_t tmpStr[tmp_buffer_size] = {0};
int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &tmpStr[0], tmp_buffer_size);
if (size_needed < tmp_buffer_size) {
return std::wstring(tmpStr, size_needed);
}
std::wstring wstrTo(size_needed, 0);
MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);
return wstrTo;
#else
auto ustr = miniutf::to_utf16(str);
return WSTRING(reinterpret_cast<const WCHAR*>(ustr.c_str()));
#endif
}
WSTRING ToWSTRING(const uint64_t i) {
return WSTRING(reinterpret_cast<const WCHAR*>(std::to_wstring(i).c_str()));
}
bool TryParse(WSTRING const& s, int& result) {
if (s.empty())
{
result = 0;
return false;
}
try
{
result = std::stoi(ToString(s));
return true;
}
catch (std::exception const&)
{
}
result = 0;
return false;
}
bool EndsWith(const std::string& str, const std::string& suffix)
{
return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
}
} // namespace trace | true |
b9ed21f046da9ce6c08ded0471256568402382dd | C++ | Wouterdek/raytracer | /raytracer/src/lib/material/environment/ImageMapEnvironment.cpp | UTF-8 | 779 | 2.75 | 3 | [] | no_license | #include "ImageMapEnvironment.h"
#include <utility>
ImageMapEnvironment::ImageMapEnvironment(std::shared_ptr<Texture<float>> environmentMap)
: texture(std::move(environmentMap))
{}
ImageMapEnvironment* ImageMapEnvironment::cloneImpl() const
{
return new ImageMapEnvironment(this->texture);
}
RGB ImageMapEnvironment::getRadiance(const Scene &scene, const Vector3 &direction) const
{
auto latitude = std::asin(direction.y());
auto longtitude = M_PI + std::atan2(direction.z()/std::cos(latitude), direction.x()/std::cos(latitude));
auto x = texture->getWidth() * longtitude/(2.0f*M_PI);
auto y = texture->getHeight() * (1.0f - (((M_PI/2.0f) + latitude)/M_PI));
return this->texture->get(static_cast<int>(x), static_cast<int>(y)) * intensity;
}
| true |
d694026537225fdecf90a091779b8465f9584437 | C++ | MarcusTurnerBSU/LinkedIn-Learning | /CodeLab II/C++ Standard Template Library/The Standard Template Library/sequence-containers.cpp | WINDOWS-1252 | 2,667 | 3.609375 | 4 | [] | no_license | /*
Containers
objects that handle a collection of other objects (elements) implementing a well defined data structure
example: vectors, stacks, queues, maps, pairs
three types of containers - sequence, associative, unordered associative
sequence - storage of data elements - vectors, list, deques, stacks, queues
//further down the page
{ associative - storage of associative pairs implemented as trees - sets, maps, multisets, multimaps
- are implemented with binary trees under the hood, meaning that they can be traversed, iterated in a predictable order
and are relatively fast to read or write.
unordered associative - storage of associative pairs implemented as hash tables - sets, maps, multisets, multimaps
- are implemented with hash tables, even faster on average but have a very bad worse case performance. }
//on associative-containers.cpp
Vector - is a C++ STL implementation of a dynamic size array
supports random access for insertions and deletions of elements
element are stored coniguously in memory
dynamically resizes as needed
there is also 'array' - array container that is statically defined at compile time
You'd use this if you need a fixed size array will all it's elements known in advance.
List - is a C++ STL implementation of a doubly linked list.
does not support random access of elements
elements are not stored contiguously in memory
different performance than a vector
there is also 'forward_list'
Deque(deck) - is a C++ STL implementation of a double-ended queue.
supports push and pop operations on both ends
elements are not all stored contiguously in memory
also serves as a stack or queue
A deque implements the behavior of more modest structures, such as a stack or a queue.
There are container definitions for these two in the C++ STL known as a containter adaptor.
Container Adapters - are interfaces that implement some special functionality on top of a sequence container.
The C++ STL supports the following container adapters - stack, queue, priority queue
Stack implements push and pop operations on one end. Ideal choice for the underlying container is the deque.
Although a vector or list could be used here too.
Queue implements push on one end to enqueue and pop on the other end to dequeue.
This is normally implemented on top of a deque but a list or vector can be used as well.
Priority queue is a data structure that supports the operations of a queue but always dequeues the maximum element.
This is naturally performed by an array based data structure called a heap.
It's underlying container is usually a vector but can also be a deque.
*/ | true |
4f2c8ac6b6d3b7a6ef41a07bfafa8f8a8223d0b5 | C++ | adam-lafontaine/BoostBeast | /Server/source_main.cpp | UTF-8 | 958 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <exception>
#include "server.hpp"
namespace svr = server_async;
// C++17 for constexpr lambdas
auto constexpr send_text =
[](auto const& req) {
svr::send_text(req, "Here is some text");
std::cout << "send_text\n";
};
auto constexpr send_json =
[](auto const& req) {
svr::send_json(req, "[{key: 'k1', value: 'v1'}, {key: 'k2', value: 'v2'}]");
std::cout << "send_json\n";
};
auto constexpr send_file =
[](auto const& req) {
svr::send_file(req, "./index.html");
std::cout << "send_file\n";
};
void build_api() {
svr::add_get("/text", send_text);
svr::add_get("/json", send_json);
svr::add_get("/file", send_file);
}
int main() {
try {
build_api();
auto address = "0.0.0.0";
auto port = 5000;
auto threads = 5;
svr::Server server(address, port, threads);
server.start();
}
catch (std::exception const& e)
{
std::cerr << "Error: " << e.what() << "\n";
return EXIT_FAILURE;
}
} | true |
2c000e543aa4b38ec7937dac0589ab7b3d7f5f56 | C++ | dav991/octotouch | /src/MainActivity.cxx | UTF-8 | 2,844 | 2.578125 | 3 | [] | no_license | #include "MainActivity.h"
MainActivity::MainActivity( Glib::RefPtr< Gtk::Application > app ): window(nullptr)
{
this->app = app;
app->hold();
statusActivity = new StatusActivity(this);
webcamActivity = new WebcamActivity(this);
filesActivity = new FilesActivity(this);
moveActivity = new MoveActivity(this);
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file( Config::i()->getResourcesFolder() + "glade/mainWindow.glade" );
builder->get_widget( "windowMain", window );
builder->get_widget( "lblAppName", lblAppName );
builder->get_widget( "btnStatus", btnStatus );
builder->get_widget( "btnWebcam", btnWebcam );
builder->get_widget( "btnFiles", btnFiles );
builder->get_widget( "btnMove", btnMove );
if( !validWidget( window, "windowMain missing from mainWindow.glade" ) ) return;
if( !validWidget( lblAppName, "lblAppName missing from mainWindow.glade" ) ) return;
if( !validWidget( btnStatus, "btnStatus missing from mainWindow.glade" ) ) return;
if( !validWidget( btnWebcam, "btnWebcam missing from mainWindow.glade" ) ) return;
if( !validWidget( btnFiles, "btnFiles missing from mainWindow.glade" ) ) return;
if( !validWidget( btnMove, "btnMove missing from mainWindow.glade" ) ) return;
window->signal_delete_event().connect( sigc::mem_fun( this, &MainActivity::windowDestroyed ) );
window->set_default_size( Config::i()->getDisplayWidth(), Config::i()->getDisplayHeight() );
lblAppName->set_text( Glib::ustring::compose("%1 %2.%3", lblAppName->get_text(), Octotouch_VERSION_MAJOR, Octotouch_VERSION_MINOR) );
btnStatus->signal_clicked().connect( sigc::mem_fun( this, &MainActivity::statusClicked ) );
btnWebcam->signal_clicked().connect( sigc::mem_fun( this, &MainActivity::webcamClicked ) );
btnFiles->signal_clicked().connect( sigc::mem_fun( this, &MainActivity::filesClicked ) );
btnMove->signal_clicked().connect( sigc::mem_fun( this, &MainActivity::moveClicked ) );
}
void MainActivity::show()
{
window->show();
}
void MainActivity::hide()
{
window->hide();
}
int MainActivity::start()
{
return app->run(*window);
}
void MainActivity::childActivityHidden( Activity *child )
{
this->show();
}
bool MainActivity::windowDestroyed( GdkEventAny* any_event )
{
this->hide();
app->release();
return true;
}
void MainActivity::statusClicked()
{
this->hide();
this->statusActivity->show();
}
void MainActivity::webcamClicked()
{
this->hide();
this->webcamActivity->show();
}
void MainActivity::filesClicked()
{
this->hide();
this->filesActivity->show();
}
void MainActivity::moveClicked()
{
this->hide();
this->moveActivity->show();
}
MainActivity::~MainActivity()
{
delete window;
delete statusActivity;
delete webcamActivity;
delete filesActivity;
}
| true |
02618b9ad1d96848d60913e36339a71b0445f0a4 | C++ | gilbutITbook/080261 | /C204_PPD42NS_미세먼지_센서/01 아두이노 라이브러리/libraries/Steamedu123_Sensor-master/src/C204_Steam_Air_PPD42NS_Dust.cpp | UTF-8 | 2,447 | 2.890625 | 3 | [] | no_license | /*
PPD42NS library
STEMEDU123 license
written by SteamLabs
homepage: http://www.steamedu123.com
naver cafe : https://cafe.naver.com/arduinosensor/book5108749/49
email : steamedu123@gmail.com
*/
#include "C204_Steam_Air_PPD42NS_Dust.h"
#define COUNT_NUM 10
/**
* @함수명 : SteamPPD42NS
* @설명 : 생성자
*/
SteamPPD42NS::SteamPPD42NS(int pin)
{
_ppdPin = pin;
}
/**
* @함수명 : begin
* @설명 : 센서를 초기화 한다.
*/
void SteamPPD42NS::begin()
{
Serial.println("PPD42NS Sensor");
Serial.println("Ready.....");
Serial.println("--------------------------------");
pinMode(_ppdPin, INPUT);
starttime = millis();
// delay(5000);
if (dustDensity == 0)
{
Serial.println("Analysing Sensor");
Serial.println("................");
lowpulseoccupancy = 0;
starttime = millis();
}
cntPM = 0;
}
/**
* @함수명 : read
* @설명 : 센서의 값을 읽어온다
*/
void SteamPPD42NS::read()
{
if (cntPM < COUNT_NUM)
{
getPM();
avrDustDensity += dustDensity;
cntPM++;
}
else
{
avrDustDensity = avrDustDensity / COUNT_NUM;
cntPM = 0;
}
}
/**
* @함수명 : getPM
* @설명 : 센서의 값을 변환한다.
*/
void SteamPPD42NS::getPM()
{
duration = pulseIn(_ppdPin, LOW);
lowpulseoccupancy = lowpulseoccupancy + duration;
if ((millis() - starttime) >= sampletime_ms)
{
ratio = lowpulseoccupancy / (sampletime_ms * 10.0);
concentration = 1.1 * pow(ratio, 3) - 3.8 * pow(ratio, 2) + 520 * ratio + 0.62;
pcsPerCF = concentration * 100;
dustDensity = pcsPerCF / 13000;
}
}
/**
* @함수명 : display
* @설명 : 센서의 값을 출력한다.
*/
void SteamPPD42NS::display()
{
int pm25 = ceil(avrDustDensity);
if (cntPM == 0)
{
Serial.print("PM2.5=> ");
Serial.print(pm25);
Serial.print(" ug/m3 ");
_displayAirCondition(avrDustDensity);
Serial.println(" ");
}
}
/**
* @함수명 : _displayAirCondition_PM25
* @설명 : 미세먼지 PM2.5 상태를 출력한다.
* 좋음(Good) : 0-15
* 보통(Normal) : 16-35
* 나쁨(Bad) : 36-75
* 매우나쁨(Very Bad) :76-
*/
void SteamPPD42NS::_displayAirCondition(unsigned int pm2_5)
{
if (pm2_5 <= 15)
{
Serial.print("Good");
}
else if (pm2_5 <= 35)
{
Serial.print("Normal");
}
else if (pm2_5 <= 75)
{
Serial.print("Bad");
}
else
{
Serial.print("Very Bad");
}
}
| true |
17a245e8110102f7fbe990a7fcad6b68890a1e93 | C++ | MetalBall887/Competitive-Programming | /CodeForces/CF850-D1-B.cpp | UTF-8 | 1,756 | 2.515625 | 3 | [] | no_license | #include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//Let d be our new gcd, x = kd. For each numbers [(k-1)d+1;kd] they either add enough times to become x or get deleted. For this segment it's easy to determine a
//border where it gets more optimal to delete a number rather than increase it to x. For each number i to the right it will cost (x - i)*y, if a[l..r] is the
//number of elements from l to r and s[l..r] is the sum of elements from l to r it will be a[x-k;x]*x*y - b[x-k;x]*y. For each such x try all divisors and
//add correspondent cost to the answer if new gcd is the current divisor of x.
//using namespace __gnu_pbds;
#define N 2000001
using namespace std;
typedef long long ll;
typedef long double ld;
const ll INF = 1e18, MOD = 1e9 + 7, MOD2 = 1e6 + 3;
ll p[N + 1], p2[N + 1], s[N + 1], ans[N + 1], n, x, y;
vector <int> dv[N + 1];
ll sum (int l, int r) {
if (l > r) return 0;
return p[r] - p[l-1];
}
ll sum2 (int l, int r) {
if (l > r) return 0;
return p2[r] - p2[l-1];
}
int main () {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n >> x >> y;
int mx = 0;
for (int i = 0; i < n; i++) {
int a;
cin >> a;
mx = max (mx, a);
s[a]++;
p[a] -= a;
}
for (int i = 1; i <= 2 * mx; i++) {
p2[i] = s[i] + p2[i-1];
p[i] += p[i-1];
}
for (int i = 2; i <= 2 * mx; i++) {
if (!dv[i].empty ()) {
ans[i] = 1e18;
continue;
}
for (int j = i; j <= 2 * mx; j += i) {
dv[j].push_back (i);
}
}
int k = x / y;
for (int i = 2; i <= 2 * mx; i++) {
for (int d : dv[i]) {
int l = i - d + 1, r = i, m = max (l, i - k);
ll c = x * sum2 (l, m - 1) + y * (sum (m, r) + sum2(m, r) * r);
ans[d] += c;
}
}
cout << *min_element (ans + 2, ans + 2 * mx + 1);
}
| true |
6722717e0657d8c14075ea1461c989829bc73f00 | C++ | ahmedibrahim404/CompetitiveProgramming | /CF Contests/Div2_569/A/main.cpp | UTF-8 | 379 | 2.53125 | 3 | [] | no_license | #include <iostream>
#include<math.h>
using namespace std;
typedef long long ll;
int n;
int main(){
scanf("%d", &n);
if(n == 1) return printf("1"), 0;
int a=1;
long long total=0;
for(int i=0;i<n;i++){
total += a;
a+=2;
}
a-=2;
total *= 2;
total -= a;
printf("%lld", total);
return 0;
}
| true |
1095427d83a8f2e666faf1c6301bba317fdd8eef | C++ | kevinlin47/Projects | /Data-Structures/Stack/main.cpp | UTF-8 | 1,269 | 3.890625 | 4 | [] | no_license | #include"stack.h"
#include<time.h>
#include<random>
int main()
{
std::cout<<"Testing all stack methods"<<std::endl;
std::cout<<"\nAdding 20 random numbers into the stack"<<std::endl;
stack testStack;
srand(time(NULL));
for (int i=0;i<20;++i)
{
int randomEntry=rand()%99+1;
testStack.push(randomEntry);
}
std::cout<<"\nDisplaying all the items in the current stack:"<<std::endl;
testStack.printStack();
std::cout<<"\n\nRemoving the last 10 entries from the stack:"<<std::endl;
for (int i=0;i<10;++i)
{
testStack.pop();
}
testStack.printStack();
std::cout<<"\n\nDisplaying number at the top of the current stack:"<<std::endl;
std::cout<<testStack.peek()<<std::endl;
std::cout<<"\n\nDisplaying current number of items in the stack:"<<std::endl;
std::cout<<testStack.currSize()<<std::endl;
std::cout<<"\n\nTesting isEmpty function:"<<std::endl;
std::cout<<testStack.isEmpty()<<std::endl;
std::cout<<"\n\nClearing the stack:"<<std::endl;
testStack.clearStack();
testStack.printStack();
std::cout<<"\n\nCalling isEmpty on cleared stack:"<<std::endl;
std::cout<<testStack.isEmpty()<<std::endl;
}
| true |
91c04ecfa964d67c9d1010a09eede04e03101bdb | C++ | sheharyarak/CS124 | /Lab4/main.hpp | UTF-8 | 443 | 3.125 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
class Term
{
public:
Term *nxt = nullptr;
int coeff;
int exp;
Term(int exp, int coeff);
};
class Polynomial
{
public:
Term *h = nullptr;
Term *t = nullptr;
void addTerm(int coeff, int exp);
void addToStart(Term *newterm);
void addToEnd(Term *newterm);
void addInPlace(Term *newterm);
Polynomial operator+ (Polynomial right);
Polynomial operator* (Polynomial right);
};
| true |
56e77dd3c3819d32419b7366a6f1e34027480660 | C++ | demelue/easy-medium-code-challenges | /C_C++/BST/main.cpp | UTF-8 | 2,867 | 3.28125 | 3 | [] | no_license | #include "bst.h"
vector<int> output;
vector<std::vector<int> > results;
void pre_order_traversal(BstNode* root)
{
if (root == NULL) return;
output.push_back(root->data);
pre_order_traversal(root->left);
pre_order_traversal(root->right);
}
void post_order_traversal(BstNode* root)
{
if (!root) return;
post_order_traversal(root->left);
post_order_traversal(root->right);
output.push_back(root->data);
}
void in_order_traversal(BstNode* root)
{
if (!root) return;
in_order_traversal(root->left);
output.push_back(root->data);
in_order_traversal(root->right);
}
void level_order_traversal(BstNode* root)
{
queue<BstNode*> q;
if (root == NULL) return;
q.push(root);
q.push(NULL);
BstNode *temp;
vector<int> sub_list;
while (!q.empty())
{
temp = q.front();
q.pop();
if (temp == NULL)
{
results.push_back(sub_list);
sub_list.resize(0);
if (q.size() > 0)
{
q.push(NULL);
}
}
else
{
sub_list.push_back(temp->data);
if (temp->left != NULL)
{
q.push(temp->left);
}
if (temp->right != NULL)
{
q.push(temp->right);
}
}
}
}
int main(int argc, char const *argv[]) {
BstNode* root;
root = NULL;
root = InsertNode(root, 12);
root = InsertNode(root, 13);
root = InsertNode(root, 5);
root = InsertNode(root, 4);
root = InsertNode(root, 3);
root = InsertNode(root, 7);
// struct BstNode *root = CreateNode(1);
//
// root->left = CreateNode(2);
// root->right = CreateNode(3);
// root->left->left = CreateNode(4);
// root->left->right = CreateNode(5);
// level_order_traversal(root);
// for (int i = 0; i < results.size(); i++)
// {
// for (int j = 0; j < results[i].size(); j++)
// {
// printf("%d\n", results[i][j]);
// }
// }
// in_order_traversal(root);
// for (int i = 0; i < output.size(); i++)
// {
// printf("%d\n", output[i]);
// }
// BstNode* test_node = CreateNode(15);
// BstNode *output = in_order_successor_v1(root,test_node);
// bool closest_value = false;
//
// if(output)
// {
// printf("In order successor: %d\n", output->data);
// }
// else
// {
// printf("There is no in order successor\n");
// }
// printf("Closest value: %d\n", closest_binary_tree_value(root, 9));
// printf("%d\n", max_path_sum(root,0));
// printf("Find path sum %d\n", find_path_sum(root,28));
// printf("node count: %d\n", count_node(root));
// printf("tree sum %d\n", sum_of_all_nodes(root));
// printf("output version 1: %d\n", Search_v1(root, 9));
// printf("output version 2: %d\n", Search_v2(root, 9));
// printf("Maximum Value: %d\n", findMax(root));
// printf("Minimum Value: %d\n", findMin(root));
// print_in_order(root);
printf("max depth: %d\n", max_depth(root));
return 0;
}
| true |
db323c6831021f3fc23df7736cb529fe9c40afef | C++ | TheIncredibleVee/Classes-and-object | /Answer 5 Objects and classes.cpp | UTF-8 | 1,696 | 3.625 | 4 | [] | no_license | #include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
/*Class*/
class Cloth{
char code[30];
char type[50];
int size;
char material[50];
float price;
void Calc_price();
public:
Cloth();
void getData();
void showData();
};
/*Main Function*/
int main(int argc, char* arv[]){
Cloth *c=new Cloth(); // New pointer to cloth
c->showData(); // Checking that constructor correctly or not
c->getData(); //Change the data
c->showData(); //Check if the data is chnaged or not
return 0;
}
/*Class functions Definations*/
void Cloth::Calc_price(){
if(!strcmpi(material,"cotton")){
if (!strcmpi(type,"trouser"))
price=1500;
else if (!strcmpi(type,"shirt")){
price=1200;
}
else
price=1000;
}
else{
if (!strcmpi(type,"trouser"))
price=0.75*float(1500);
else if (!strcmpi(type,"shirt")){
price=0.75*(1200);
}
else
price=1000;
}
}
Cloth::Cloth(){
strcpy(type,"NOT ASSIGNED");
strcpy(code,"NOT ASSIGNED");
strcpy(material,"NOT ASSIGNED");
price=0;
size=0;
}
void Cloth::getData(){
cout<<"\nEnter the details as follows\n1. Code of the cloth \t";
cin.ignore();
cin.getline(code,30);
cout<<"2. Type of the cloth \t";
cin.getline(type,30);
cout<<"3. Size of the cloth \t";
cin>>size;
cout<<"4. Material of the cloth \t";
cin.ignore();
cin.getline(material,30);
Calc_price();
}
void Cloth::showData(){
printf("The details are as follows\n1. Code of the cloth \t %s \n2. Type of the cloth \t %s \n3. Size of the cloth \t %d \n4.Material of the coth \t %s \n5. Price of the cloth\t %.2f\n", code, type, size, material, price);
}
| true |
061aa0a25799cc57f7f31378ed7f6821505a9e22 | C++ | jcasanella/game_programming | /Learning/source/private/Shader.cpp | UTF-8 | 2,737 | 3.03125 | 3 | [] | no_license | #include "Shader.h"
#include <iostream>
#include <fstream>
#include <cassert>
namespace GameEngine {
const GLuint INVALID_PROGRAM_ID = 0;
Shader::Shader() : m_programId(INVALID_PROGRAM_ID)
{
}
Shader::~Shader()
{
Terminate();
}
void Shader::Terminate()
{
if (m_programId != INVALID_PROGRAM_ID)
{
glDeleteProgram(m_programId);
}
}
GLuint Shader::CompileVertexShader(const char* shaderLocation)
{
const char* VERTEX_SHADER_ERROR = "ERROR::SHADER::VERTEX::COMPILATION_FAILED";
return CompileShader(shaderLocation, VERTEX_SHADER_ERROR, GL_VERTEX_SHADER);
}
GLuint Shader::CompileFragmentShader(const char* shaderLocation)
{
const char* FRAGMENT_SHADER_ERROR = "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED";
return CompileShader(shaderLocation, FRAGMENT_SHADER_ERROR, GL_FRAGMENT_SHADER);
}
GLuint Shader::CompileShaderProgram() const
{
// Link the different shaders
GLuint shaderProgram = glCreateProgram();
assert(shaderProgram != 0);
GLint success;
char infoLog[512];
for (std::vector<GLuint>::const_iterator it = m_shadersId.begin(); it != m_shadersId.end(); ++it) {
glAttachShader(shaderProgram, *it);
}
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADERPROGRAM::LINK_FAILED" << std::endl << infoLog << std::endl;
}
for (std::vector<GLuint>::const_iterator it = m_shadersId.begin(); it != m_shadersId.end(); ++it) {
glDetachShader(shaderProgram, *it);
glDeleteShader(*it);
}
return shaderProgram;
}
GLuint Shader::CompileShader(const char* shaderLocation, const char* errorMessage, const GLenum& shaderType)
{
const char* shaderSource = ReadFile(shaderLocation);
assert(shaderSource != NULL);
GLuint shaderId = glCreateShader(shaderType);
assert(shaderId != 0);
glShaderSource(shaderId, 1, &shaderSource, NULL);
glCompileShader(shaderId);
// Check if vertex shader compilation worked
GLint success;
char infoLog[512];
glGetShaderiv(shaderId, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(shaderId, 512, NULL, infoLog);
std::cout << errorMessage << std::endl << infoLog << std::endl;
}
delete[] shaderSource;
m_shadersId.push_back(shaderId);
return shaderId;
}
const char* Shader::ReadFile(const char* fileName)
{
char* content = NULL;
std::ifstream inData(fileName);
if (inData.is_open()) {
inData.seekg(0, std::ios::end);
size_t fileSize = inData.tellg();
inData.seekg(0);
content = new char[fileSize + 1];
inData.read(content, fileSize);
content[fileSize] = '\0';
}
inData.close();
return content;
}
} | true |
5224885eb838046a908c6c9f58123221e3db5e7d | C++ | Kushagratandon12/Coding-Competition-Problems- | /30Days.cpp | UTF-8 | 2,346 | 3.875 | 4 | [] | no_license | #include<iostream>
#include<conio.h>
#include<set>
#include<unordered_set>
#include<unordered_map>
#include<vector>
using namespace std;
void duplicate_array()
{
//only one repeating element is present
//Sort the array and find the element adajcent to it
//First approach in mind is using set and passing the element in array and check weather it is existing in it or not
vector<int> input{ 1,2,3,5,7 };
set<int> dub_check;
int i = 0, size = input.size();
while (i < size)
{
if (find(dub_check.begin(), dub_check.end(), input[i]) != dub_check.end())
{
dub_check.insert(input[i]);
}
i++;
}
}
void inversion()
{
vector<int> input1{ 2,4,1,3,5 };
int inversion = 0;
for (int i = 0; i < input1.size(); i++)
{
for (int j = 0; j < input1.size(); j++)
{
if (input1[i] > input1[j] && i < j)
{
inversion++;
}
}
}
cout << "Total number of the inversion that can be created form the array " << inversion;
}
//Hash Set
void dublicate()
{
vector<int> arr{ 1,2,3,1 };
unordered_set<int> intSet;
unordered_set<int> duplicate;
for (int i = 0; i < arr.size()-1; i++)
{
// if element is not there then insert that
if (intSet.find(arr[i]) == intSet.end())
intSet.insert(arr[i]);
// if element is already there then insert into
// duplicate set
else
duplicate.insert(arr[i]);
}
unordered_set<int> ::iterator itr;
for (itr = duplicate.begin(); itr != duplicate.end(); itr++)
{
cout << *itr;
}
}
void findLeastNumOfUniqueInts() {
/*
4,3,1,1,3,3,2 and K=3
- unodered map - occurances add in the second order
- if the occurances are 1 only remove those elements and then remove any element
7*/
vector<int> arr{ 5,5,4 };
int k = 1;
unordered_map<int , int> mp;
for (int i = 0; i < arr.size(); i++)
{
mp[arr[i]]++;
}
//remove the elements having only 1 occurances mesured
for (auto x : mp)
{
cout << x.first << " " << x.second;
}
}
void jump_array_55()
{
vector<int> arr{ 3,2,1,2,4,3,6,9,10 };
int pointer = 1;
int last = arr.size() - 1;
while (pointer!= last)
{
int val = arr[pointer];
pointer = pointer + val;
if (pointer > last || arr[pointer] == 0 )
{
cout << "False";
return;
}
}
cout << "True";
}
int main()
{
//duplicate_array();
//inversion();
//findLeastNumOfUniqueInts();
jump_array_55();
return 0;
} | true |
4d3388b90ebd830e92eea5e1be5fdeaaa84441a2 | C++ | m80126colin/Judge | /before2020/UVa_ACM/003 - Volume III/UVa 369(1.5, Combination, Math).cpp | UTF-8 | 555 | 3.125 | 3 | [] | no_license | /**
* @judge UVa
* @id 369
* @tag 1.5, Combination, Math
*/
#include <stdio.h>
#include <iostream>
using namespace std;
int n, m;
long long c(int a, int b)
{
long long ans, i, j, mn, mx;
ans = 1;
mn = min(a - b, b);
mx = max(a - b, b);
for (i = a, j = 1; i > mx; i--)
{
ans *= i;
if (j <= mn)
{
ans /= j;
j++;
}
}
for (; j <= mn; j++)
ans /= j;
return ans;
}
int main()
{
while (scanf("%d%d", &n, &m), (n || m))
printf("%d things taken %d at a time is %lld exactly.\n", n, m, c(n, m));
} | true |
47255b1b914d64ac1159f8c892f84487b68d52e7 | C++ | google/perfetto | /include/perfetto/protozero/static_buffer.h | UTF-8 | 3,449 | 2.515625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef INCLUDE_PERFETTO_PROTOZERO_STATIC_BUFFER_H_
#define INCLUDE_PERFETTO_PROTOZERO_STATIC_BUFFER_H_
#include <memory>
#include <string>
#include <vector>
#include "perfetto/base/export.h"
#include "perfetto/protozero/root_message.h"
#include "perfetto/protozero/scattered_stream_writer.h"
namespace protozero {
class Message;
// A simple implementation of ScatteredStreamWriter::Delegate backed by a
// fixed-size buffer. It doesn't support expansion. The caller needs to ensure
// to never write more than the size of the buffer. Will CHECK() otherwise.
class PERFETTO_EXPORT_COMPONENT StaticBufferDelegate
: public ScatteredStreamWriter::Delegate {
public:
StaticBufferDelegate(uint8_t* buf, size_t len) : range_{buf, buf + len} {}
~StaticBufferDelegate() override;
// ScatteredStreamWriter::Delegate implementation.
ContiguousMemoryRange GetNewBuffer() override;
ContiguousMemoryRange const range_;
bool get_new_buffer_called_once_ = false;
};
// Helper function to create protozero messages backed by a fixed-size buffer
// in one line. You can write:
// protozero::Static<protozero::MyMessage> msg(buf.data(), buf.size());
// msg->set_stuff(...);
// size_t bytes_encoded = msg.Finalize();
template <typename T /* protozero::Message */>
class StaticBuffered {
public:
StaticBuffered(void* buf, size_t len)
: delegate_(reinterpret_cast<uint8_t*>(buf), len), writer_(&delegate_) {
msg_.Reset(&writer_);
}
// This can't be neither copied nor moved because Message hands out pointers
// to itself when creating submessages.
StaticBuffered(const StaticBuffered&) = delete;
StaticBuffered& operator=(const StaticBuffered&) = delete;
StaticBuffered(StaticBuffered&&) = delete;
StaticBuffered& operator=(StaticBuffered&&) = delete;
T* get() { return &msg_; }
T* operator->() { return &msg_; }
// The lack of a size() method is deliberate. It's to prevent that one
// accidentally calls size() before Finalize().
// Returns the number of encoded bytes (<= the size passed in the ctor).
size_t Finalize() {
msg_.Finalize();
return static_cast<size_t>(writer_.write_ptr() - delegate_.range_.begin);
}
private:
StaticBufferDelegate delegate_;
ScatteredStreamWriter writer_;
RootMessage<T> msg_;
};
// Helper function to create stack-based protozero messages in one line.
// You can write:
// protozero::StackBuffered<protozero::MyMessage, 16> msg;
// msg->set_stuff(...);
// size_t bytes_encoded = msg.Finalize();
template <typename T /* protozero::Message */, size_t N>
class StackBuffered : public StaticBuffered<T> {
public:
StackBuffered() : StaticBuffered<T>(&buf_[0], N) {}
private:
uint8_t buf_[N]; // Deliberately not initialized.
};
} // namespace protozero
#endif // INCLUDE_PERFETTO_PROTOZERO_STATIC_BUFFER_H_
| true |
0f5464b82a96fd27078fd75fdcecdede99dec20b | C++ | HopeChanger/homework4 | /PB15000176_PB15000202/hw4.cpp | UTF-8 | 7,656 | 2.671875 | 3 | [] | no_license | #include<FindContours.h>
#define OK 1
#define FAIL 0
#define MAX_LABLE 100000
int *table;
int length;
int Connect_Update(int a, int b) {
int con_a = table[a];
int con_b = table[b];
if (con_a > con_b) {
int temp = con_a;
con_a = con_b;
con_b = temp;
}
for (int i = con_b; i <= length; i++)
{
if (table[i] == con_b) {
table[i] = con_a;
}
}
return min(a, b);
}
int First_Traverse(Mat BinaryImg, Mat &LabelImg) {
if (NULL == BinaryImg.data || NULL == LabelImg.data)
{
cout << "image read failed." << endl;
return FAIL;
}
int width = BinaryImg.cols;
int height = BinaryImg.rows;
int label_width = LabelImg.cols;
int label_height = LabelImg.rows;
if (height != label_height || width != label_width)
{
cout << "image size wrong." << endl;
return FAIL;
}
length = 0;
memset(table, 0, width*height * sizeof(int));
LabelImg.setTo(0);
uchar* binptr = BinaryImg.data;
float* labelptr = (float*)LabelImg.data;
//length += (*binptr & 1);
//table[(*binptr & 1)] = (*binptr & 1);
if (*binptr) //first pixel
{
table[1] = 1;
length = 1;
*labelptr = length;
}
binptr++; labelptr++;
for (int j = 1; j < width; j++) //first row without first pixel
{
switch ((*binptr & 2) + (*(binptr - 1) & 1))
{
case 0: break;
case 1: break;
case 2:
{
length++;
table[length] = length;
*labelptr = length;
break;
}
case 3: *labelptr = *(labelptr - 1);
}
binptr++; labelptr++;
}
for (int i = 1; i < height; i++)
{
switch ((*binptr & 4) + (*(binptr - width) & 2) + (*(binptr - width + 1) & 1))
// 2 1
// 4
{
case 0: break;
case 1: break;
case 2: break;
case 3: break;
case 4:
{
length++;
table[length] = length;
*labelptr = length;
break;
}
case 5:
{
*labelptr = *(labelptr - width + 1);
break;
}
case 6:
case 7:
{
*labelptr = *(labelptr - width);
break;
}
}
labelptr++; binptr++;
for (int j = 1; j < width - 1; j++)
{
switch ((*binptr & 16) + (*(binptr - 1) & 8) + (*(binptr - width - 1) & 4) + (*(binptr - width) & 2) + (*(binptr - width + 1) & 1))
// 4 2 1
// 8 16
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15: break;
case 16:
{
length++;
table[length] = length;
*labelptr = length;
break;
}
case 17:
{
*labelptr = *(labelptr - width + 1);
break;
}
case 18:
case 19:
{
*labelptr = *(labelptr - width);
break;
}
case 20:
{
*labelptr = *(labelptr - width - 1);
break;
}
case 21:
{
*labelptr = Connect_Update(*(labelptr - width - 1), *(labelptr - width + 1));
break;
}
case 22:
case 23:
{
*labelptr = *(labelptr - width - 1);
break;
}
case 24:
{
*labelptr = *(labelptr - 1);
break;
}
case 25:
{
*labelptr = Connect_Update(*(labelptr - 1), *(labelptr - width + 1));
break;
}
case 26:
case 27:
case 28:
{
*labelptr = *(labelptr - 1);
break;
}
case 29:
{
*labelptr = *labelptr = Connect_Update(*(labelptr - 1), *(labelptr - width + 1));
break;
}
case 30:
case 31:
{
*labelptr = *(labelptr - 1);
break;
}
}
labelptr++; binptr++;
}
switch ((*binptr & 8) + (*(binptr - 1) & 4) + (*(binptr - width - 1) & 2) + (*(binptr - width) & 1))
// 2 1
// 4 8
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:break;
case 8:
{
length++;
table[length] = length;
*labelptr = length;
break;
}
case 9:
{
*labelptr = *(labelptr - width);
break;
}
case 10:
case 11:
{
*labelptr = *(labelptr - width - 1);
break;
}
case 12:
case 13:
case 14:
case 15:
{
*labelptr = *(labelptr - 1);
break;
}
}
labelptr++; binptr++;
}
return OK;
}
int Second_Traverse(Mat &LabelImg) {
if (NULL == LabelImg.data)
{
cout << "image read failed." << endl;
return FAIL;
}
float* ptr = (float*)LabelImg.data;
int width = LabelImg.cols;
int height = LabelImg.rows;
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++) {
*ptr = table[(int)*ptr];
ptr++;
}
}
return OK;
}
int ustc_ConnectedComponentLabeling(Mat grayImg, Mat& labelImg)
{
if (NULL == grayImg.data || NULL == labelImg.data)
{
cout << "image read failed." << endl;
return FAIL;
}
int width = grayImg.cols;
int height = grayImg.rows;
int label_width = labelImg.cols;
int label_height = labelImg.rows;
if (height != label_height || width != label_width)
{
cout << "image size wrong." << endl;
return FAIL;
}
Mat BinaryImg(height, width, CV_8UC1);
table = (int*)malloc(width*height * sizeof(int));
length = 0;
int flag = First_Traverse(grayImg, labelImg);
flag = Second_Traverse(labelImg);
return OK;
}
int USTC_Find_Contours(Mat binaryImg, vector < vector < cv::Point >>& contours)
{
int width = binaryImg.cols;
int height = binaryImg.rows;
int TraversedLabel[MAX_LABLE] = { 0 };
int Dirt_x[8] = { -1,-1,-1,0,1,1,1,0 };
int Dirt_y[8] = { -1,0,1,1,1,0,-1,-1 };
// 0 1 2
// 7 x 3
// 6 5 4
Mat labelImg(height, width, CV_32FC1);
ustc_ConnectedComponentLabeling(binaryImg, labelImg); //build a image with label
Mat newImg(height + 2, width + 2, CV_32FC1); //build a new image which has a zero edge
memset(newImg.data, 0, (height + 2)*(width + 2) * sizeof(float));
for (int i = 0;i < height;i++)
{
for (int j = 0;j < width;j++)
{
((float*)newImg.data)[(i + 1) * (width + 2) + j + 1] = ((float*)labelImg.data)[i * width + j];
//cout << ((float*)newImg.data)[(i + 1) * (width + 2) + j + 1] << " ";
}
//cout << endl;
}
width += 2;
height += 2;
//Mat showImg(height - 2, width - 2, CV_8UC1);
float *pointer = newImg.ptr<float>(0);
for (int i = 0;i < width * height;i++)
{
int label = *pointer;
if (label != 0 && TraversedLabel[label] == 0) //first point
{
TraversedLabel[label] = 1;
Point point = Point(i / width - 1, i % width - 1);
vector<cv::Point> edge;
edge.push_back(point);
float *last = NULL;
int lastDirt = -1;
for (int j = 0;j < 8;j++) //second point
{
float *next = pointer + Dirt_x[j] * width + Dirt_y[j];
if (*next == label)
{
last = pointer;
pointer = next;
point.x += Dirt_x[j];
point.y += Dirt_y[j];
edge.push_back(point);
lastDirt = (j + 4) % 8;
break;
}
}
if (lastDirt == -1) //second point not exist
{
*pointer = 0;
continue;
}
float *begin1 = last, *begin2 = pointer;
while(1) //other points
{
for (int j = lastDirt + 1;j < 8;j++)
{
float *next = pointer + Dirt_x[j] * width + Dirt_y[j];
if (*next == label)
{
last = pointer;
pointer = next;
point.x += Dirt_x[j];
point.y += Dirt_y[j];
lastDirt = (j + 4) % 8;
goto NEXT;
}
}
for (int j = 0;j < lastDirt + 1;j++)
{
float *next = pointer + Dirt_x[j] * width + Dirt_y[j];
if (*next == label)
{
last = pointer;
pointer = next;
point.x += Dirt_x[j];
point.y += Dirt_y[j];
lastDirt = (j + 4) % 8;
goto NEXT;
}
}
NEXT:
if (begin1 == last && begin2 == pointer)
break;
else
edge.push_back(point);
}
pointer = begin1;
contours.push_back(edge);
//for (int j = 0;j < edge.size();j++)
//{
// showImg.data[edge[j].x * (width - 2) + edge[j].y] = 255;
//}
}
pointer++;
}
//namedWindow("Edge", 0);
//imshow("Edge", showImg);
//waitKey(1);
return MY_OK;
}
| true |
594d281f2decb60191c2b6983cb1694fe8891ada | C++ | Mustafamemon/SEM_THREE | /DATA STRUCTURE/Ass/K173795 -E MustafaManga/K173795 A2_P2.cpp | UTF-8 | 2,620 | 2.953125 | 3 | [] | no_license | #include<iostream>
#include<string.h>
#include<fstream>
#include<cmath>
#include<stack>
using namespace std;
int i_ans(char ch[])
{
stack <int>s ;
int con=0,ans=0;
for(int i=0;i<strlen(ch);i++)
{
if(ch[i]>='0' && ch[i]<='9')
{
con=(con*10)+(ch[i]-48);
}
else if(ch[i]==' ')
{
if(con!=-1)
s.push(con);
con=0;
}
else if(ch[i]=='/' || ch[i]=='*' || ch[i]=='+' || ch[i]=='-' || ch[i]=='^' || ch[i]=='%')
{
ans=s.top();
s.pop();
con=s.top();
s.pop();
if(ch[i]=='^')
s.push(pow(con,ans));
else if(ch[i]=='%')
s.push(con%ans);
else if(ch[i]=='*')
s.push(ans*con);
else if(ch[i]=='/')
s.push(con/ans);
else if(ch[i]=='+')
s.push(ans+con);
else if(ch[i]=='-')
s.push(con-ans);
con=-1;
}
}
return s.top();
}
int O_precedence(char O)
{
if(O=='^')
return 3;
else if(O == '*' || O == '/' || O == '%')
return 2;
else if(O == '+' || O == '-')
return 1;
else
return -1;
}
void infix_to_postfix(char infix[])
{
fstream fout;
fout.open("output.txt",ios::out | ios::app);
char output[strlen(infix)+strlen(infix)];
stack <char>s;
int k=0;
for(int i=0;i<strlen(infix);i++)
{
if(infix[i]=='(')
{
s.push(infix[i]);
}
else if(infix[i]==')')
{
while(s.top()!='(')
{
output[k]=' ';
k++;
if(s.top()!=')' && s.top()!='(')
{
output[k]=s.top();
k++;
}
s.pop();
}
s.pop();
}
else if((infix[i]>='0' && infix[i]<='9') || (infix[i]>='a' && infix[i]<='z'))
{
output[k]=infix[i];
k++;
}
else if(!s.empty())
{
output[k]=' ';
k++;
again:
if(O_precedence(s.top())<O_precedence(infix[i]))
{
s.push(infix[i]);
}
else
{
output[k]=s.top();
k++;
output[k]=' ';
++k;
s.pop();
if(!s.empty())
goto again;
s.push(infix[i]);
}
}
else
{
output[k]=' ';
k++;
s.push(infix[i]);
}
}
while(!s.empty())
{
output[k]=' ';
k++;
if(s.top()!=')' && s.top()!='(')
{
output[k]=s.top();
k++;
}
s.pop();
}
output[k]='\0';
for(int i=0;i<k;i++)
{
cout<<output[i];
fout<<output[i];
}
if((output[0]>='a' && output[0]<='z'))
cout<<endl<<endl;
else
{
k=i_ans(output);
fout<<endl<<k<<endl;
cout<<endl<<k<<endl<<endl;
}
fout.close();
}
int main()
{
string ch1;
fstream fin;
fin.open("input.txt", ios::in);
if(fin.is_open())
{
while(!fin.eof())
{
fin>>ch1;
char ch[ch1.length()];
for(int i=0;i<ch1.length();i++)
{
ch[i]=ch1[i];
}
ch[ch1.length()]='\0';
infix_to_postfix(ch);
}
}
else
cout<<"File Not Found!";
}
| true |
ad4119cba9b71d2e43b623e2e5bc830387abea5d | C++ | yuzin9712/Alogrithm | /대학생 심화반/BOJ_11404.cpp | UTF-8 | 1,374 | 3.328125 | 3 | [] | no_license | #include <iostream>
#include <vector>
#define INF 1000000001
using namespace std;
int **graph;
int n, m;
void init() {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(i == j) {
graph[i][j] = 0;
} else {
graph[i][j] = INF;
}
}
}
}
void input() {
int x, y, cost;
cin >> n >> m;
graph = (int **)malloc(sizeof(int*) * n);
for(int i = 0; i < n; i++) {
graph[i] = (int *)malloc(sizeof(int) * n);
}
init();
for(int i = 0; i < m; i++) {
cin >> x >> y >> cost;
if(graph[x - 1][y - 1] > cost) {
graph[x - 1][y - 1] = cost;
}
}
}
void FloydWashall() {
for(int middle = 0; middle < n; middle++) {
for(int start = 0; start < n; start++) {
for(int end = 0; end < n; end++) {
if(graph[start][end] > graph[start][middle] + graph[middle][end]) {
graph[start][end] = graph[start][middle] + graph[middle][end];
}
}
}
}
}
int main() {
input();
FloydWashall();
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(graph[i][j] == INF) {
graph[i][j] = 0;
}
cout << graph[i][j] << " ";
}
cout << "\n";
}
} | true |
c440a6a16fabae21f75c7db29608009adafd25cf | C++ | xd23fe39/arduino-basics | /PlatformIO/RelaisDemoV1/src/main.cpp | UTF-8 | 2,026 | 3.109375 | 3 | [] | no_license | #include <Arduino.h>
#define PIN_RELAIS_A 8
// Funktion für Signal-LED-Steuerung
void blink(uint8_t pin, byte repeat, int ms = 200);
/*
Relais 5V/230V Raspberry Pi Modul Channel Relay Arduino
- 5V Relais Modul 1-Kanal
- 5 Volt 1-Kanal-Relais-Schnittstellenkarte
- zur Steuerung von Verbrauchern bis 230 Volt
- Verbrauch 50-60mA.
- Hochstrom-Relais: AC250V 10A; DC30V 10A.
- LED zur Statusanzeige welcher Ausgang aktiv ist
Relais-Module mit Low-Level-Trigger schalten, sobald am Anschluss-PIN
LOW anliegt. Soll bei der Initialisierung des Moduls KEIN Schaltvorgang
ausgelöst werden, muss der Anschluss-PIN auf HIGH gesetzt werden.
*/
void relais_init(uint8_t pin, bool low_level_trigger = false);
void relais_switch(uint8_t pin, int level);
/**
* Arduino SETUP Procedure.
*
*/
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, LOW);
relais_init(PIN_RELAIS_A, true); // LLT-Relais initialisieren (AUS => HIGH)
delay(5000);
relais_switch(PIN_RELAIS_A, LOW); // AN bei LLT-Relais
delay(5000);
relais_switch(PIN_RELAIS_A, HIGH); // AUS bei LLT-Relais
}
/**
* Arduino LOOP Procedure.
*
*/
void loop() {
blink(LED_BUILTIN, 1, 200);
}
/**
* Lässt eine LED an PIN pin repeat-mal blinken.
*/
void blink(uint8_t pin, byte repeat, int ms = 200) {
for (byte i = 0; i < repeat; i++)
{
digitalWrite(pin, HIGH);
delay(ms);
digitalWrite(pin, LOW);
delay(ms);
}
}
/**
* Initialisierung des Relais. Es werden HIGH- und LOW-Level-Trigger
* Relaismodule unterstützt.
*/
void relais_init(uint8_t pin, bool low_level_trigger)
{
// Anschluss-PIN als Ausgang setzen
pinMode(pin, OUTPUT);
// Low-Level-Trigger Module schalten beim Wechsel nach LOW
if (low_level_trigger)
{
relais_switch(pin, HIGH); // AUS
}
else
{
relais_switch(pin, LOW); // AUS
}
}
/**
* Schaltet das Relaimodul an PIN pin auf LEVEL level.
*/
void relais_switch(uint8_t pin, int level)
{
digitalWrite(pin, level);
}
| true |
4b9486453c17a7993cc4e3a480fac3e9c6b6d7e3 | C++ | Iamnvincible/myleetcode | /LinkedList/Solution_83.hpp | UTF-8 | 636 | 3.78125 | 4 | [] | no_license | #ifndef SOLUTION_83
#define SOLUTION_83
/* Given a sorted linked list,
delete all duplicates such that each element appear only once.
在排好序的链表中删除重复元素
记得要释放内存
*/
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
auto cur = head;
while (cur && cur->next) {
if (cur->val == cur->next->val) {
auto temp = cur->next;
cur->next = cur->next->next;
delete temp;
} else {
cur = cur->next;
}
}
return head;
}
};
#endif | true |
b116c6cf9c18b804296e5765abccad6530cf00e9 | C++ | DmitriyKitov/cppcourse | /lw1/cpp1.4/square_equation.cpp | UTF-8 | 638 | 3.5625 | 4 | [] | no_license | #include <cstdio>
#include <cmath>
int main()
{
// 1. prompt user to enter coefficients
std::puts("please enter a, b and c for `ax^2 + bx + c = 0`:");
// 2. read coefficients for equation `ax^2 + bx + c = 0`
float a = 0;
float b = 0;
float c = 0;
std::scanf("%f %f %f", &a, &b, &c);
// 3. solve equation `ax^2 + bx + c = 0`
// solution: `-b ± sqrt(b * b - 4 * 1 * c`
float x1 = (-b + sqrt(b * b - 4 * 1 * c)) / 2 * a;
float x2 = (-b - sqrt(b * b - 4 * 1 * c)) / 2 * a;
std::printf("solution 1: %f\n"
"solution 2: %f\n",
x1, x2);
}
| true |
1fe46b4054fa443a98026e8823f4a4834a009de2 | C++ | DongChengrong/ACM-Program | /UVA/1300-1399/1388.cpp | UTF-8 | 808 | 2.84375 | 3 | [] | no_license | /*
很遗憾没学会刘汝佳的做法,不过我们可以把它们均分最后用二分确定一下大小就好了
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define N 2200
double a[N], b[N];
int main() {
int n,m;
while (scanf("%d%d",&n, &m) == 2) {
double a_cnt = 10000.0 / n;
double b_cnt = 10000.0 / (n + m);
for (int i = 0; i < n; ++i) {
a[i] = i * a_cnt;
}
for (int i = 0; i < n + m; ++i) {
b[i] = i * b_cnt;
}
double ans = 0;
for (int i = 1; i < n; ++i) {
int p = lower_bound(b, b + n + m, a[i]) - b;
ans += min(fabs(b[p - 1] - a[i]), fabs(b[p] - a[i]));
}
printf("%.4f\n",ans);
}
return 0;
}
| true |
8994d6bbe78d07c1429965bc207cf494a0c8669a | C++ | windystrife/UnrealEngine_NVIDIAGameWorks | /Engine/Source/ThirdParty/Perforce/p4api-2015.2/include/p4/filesys.h | UTF-8 | 12,845 | 2.5625 | 3 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | /*
* Copyright 1995, 1996 Perforce Software. All rights reserved.
*
* This file is part of Perforce - the FAST SCM System.
*/
/*
* FileSys.h - OS specific file manipulation
*
* Public classes:
*
* FileSys - a file handle, with all the trimmings
*
* Static Public methods:
*
* FileSys::Create() - create a FileSys, given its file type
* FileSys::CreateTemp() - create, destructor deletes the file
* FileSys::CreateGloablTemp() - Temp, constructor makes a global name
* FileSys::FileExists() - does the passed filepath exist in the file system
* FileSys::Perm() - translate string perm to enum
*
* Public methods:
*
* FileSys::Set() - set file name
* FileSys::Name() - get file name
* FileSys::GetType() - get type previously set
* FileSys::IsTextual() - return if type is one of text types
* FileSys::IsExec() - return if type indicates executable bit set
* FileSys::DoIndirectWrites() - updates should write temp/rename
*
* FileSys::MakeGlobalTemp() - make a temp name in a global directory
* FileSys::MakeLocalTemp() - make a temp name in same dir as file
*
* FileSys::IsDeleteOnClose() - will file be removed on close?
* FileSys::SetDeleteOnClose() - file will be removed
* FileSys::ClearDeleteOnClose() - file won't be removed
*
* FileSys::Perms() - set file permission for close after write
* FileSys::ModTime() - set mod time for close after write
* FileSys::ChmodTime() - use modTime value to change mod time directly
*
* FileSys::Open() - open named file according to mode
* FileSys::Write() - write a block into file
* FileSys::Read() - read a block from file
* FileSys::ReadLine() - read a line into string
* FileSys::ReadWhole() - read whole file into string
* FileSys::Close() - close file description
*
* FileSys::Stat() - return flags if file exists, writable
* FileSys::Truncate() - set file to zero length if it exists
* FileSys::Unlink() - remove single file
*
* FileSys::GetFd() - return underlying int fd, FST_BINARY only
* FileSys::GetSize() - return file size, FST_BINARY,TEXT,ATEXT only
* FileSys::GetOwner() - return the UID of the file owner
* FileSys::GetDiskSpace() - fill in data about filesystem space usage.
* FileSys::Seek() - seek to offset, FST_BINARY,TEXT,ATEXT only
* FileSys::Tell() - file position, FST_BINARY,TEXT,ATEXT only
*
* FileSys::ScanDir() - return a list of directory contents
* FileSys::MkDir() - make a directory for the current file
* FileSys::RmDir() - remove the directory of the current file
* FileSys::Rename() - rename file to target
* FileSys::ReadFile() - open, read whole file into string, close
* FileSys::WriteFile() - open, write whole file from string, close
* FileSys::Chmod() - change permissions
* FileSys::Compare() - compare file against target
* FileSys::Copy - copy one file to another
* FileSys::Digest() - return a fingerprint of the file contents
* FileSys::Chmod2() - copy a file to get ownership and set perms
* FileSys::Fsync() - sync file state to disk
*
* FileSys::CheckType() - look at the file and see if it is binary, etc
*/
# ifdef OS_NT
# define DOUNICODE ( CharSetApi::isUnicode((CharSetApi::CharSet)GetCharSetPriv()) )
# endif
enum FileSysType
{
// Base types
FST_TEXT = 0x0001, // file is text
FST_BINARY = 0x0002, // file is binary
FST_DIRECTORY = 0x0005, // it's a directory
FST_SYMLINK = 0x0006, // it's a symlink
FST_RESOURCE = 0x0007, // Macintosh resource file
FST_SPECIAL = 0x0008, // not a regular file
FST_MISSING = 0x0009, // no file at all
FST_CANTTELL = 0x000A, // can read file to find out
FST_EMPTY = 0x000B, // file is empty
FST_UNICODE = 0x000C, // file is unicode
FST_UTF16 = 0x000E, // stream is utf8 convert to utf16
FST_UTF8 = 0x000F, // stream is utf8, might have BOM handling
FST_MASK = 0x000F, // mask for types
// Compression Modifiers
FST_C_ASIS = 0x0400, // replacing FST_M_COMP
FST_C_GZIP = 0x0800, // for gziped files
FST_C_GUNZIP = 0x0c00, // for compress on client
FST_C_MASK = 0x0c00,
// Modifiers
FST_M_APPEND = 0x0010, // open always append
FST_M_EXCL = 0x0020, // open exclusive create
FST_M_SYNC = 0x0040, // fsync on close
FST_M_EXEC = 0x0100, // file is executable
FST_M_APPLE = 0x0200, // apple single/double encoding
FST_M_COMP = 0x0400, // file is somehow compressed
FST_M_MASK = 0x0ff0, // mask for modifiers
// Line ending types, loosely mapped to LineType
FST_L_LOCAL = 0x0000, // LineTypeLocal
FST_L_LF = 0x1000, // LineTypeRaw
FST_L_CR = 0x2000, // LineTypeCr
FST_L_CRLF = 0x3000, // LineTypeCrLf
FST_L_LFCRLF = 0x4000, // LineTypeLfcrlf
FST_L_MASK = 0xf000, // mask for LineTypes
// Composite types, for filesys.cc
FST_ATEXT = 0x0011, // append-only text
FST_XTEXT = 0x0101, // executable text
FST_RTEXT = 0x1001, // raw text
FST_RXTEXT = 0x1101, // executable raw text
FST_CBINARY = 0x0402, // pre-compressed binary
FST_XBINARY = 0x0102, // executable binary
FST_APPLETEXT = 0x0201, // apple format text
FST_APPLEFILE = 0x0202, // apple format binary
FST_XAPPLEFILE =0x0302, // executable apple format binary
FST_XUNICODE = 0x010C, // executable unicode text
FST_XUTF16 = 0x010E, // stream is utf8 convert to utf16
FST_XUTF8 = 0x010F, // stream is utf8 BOM handling
FST_RCS = 0x1041, // RCS temporary file: raw text, sync on close
FST_GZIP = 0x0802, // file is gzip
FST_GUNZIP = 0x0c02, // stream is gzip
FST_GZIPTEXT = 0x0801, // file is text gzipped
};
enum FileStatFlags {
FSF_EXISTS = 0x01, // file exists
FSF_WRITEABLE = 0x02, // file is user-writable
FSF_DIRECTORY = 0x04, // file is a directory
FSF_SYMLINK = 0x08, // file is symlink
FSF_SPECIAL = 0x10, // file is not regular
FSF_EXECUTABLE = 0x20, // file is executable
FSF_EMPTY = 0x40, // file is empty
FSF_HIDDEN = 0x80 // file is invisible (hidden)
} ;
enum FileSysAttr {
FSA_HIDDEN = 0x01 // file is invisible (hidden)
} ;
enum FileOpenMode {
FOM_READ, // open for reading
FOM_WRITE, // open for writing
FOM_RW // open for write, but don't trunc, allow read
} ;
enum FilePerm {
FPM_RO, // leave file read-only
FPM_RW, // leave file read-write
FPM_ROO, // leave file read-only (owner)
// following two enums are for key file and dir permissions
FPM_RXO, // set file read-execute (owner) NO W
FPM_RWO, // set file read-write (owner) NO X
FPM_RWXO // set file read-write-execute (owner)
} ;
enum LFNModeFlags {
LFN_ENABLED = 0x01,
LFN_UNCPATH = 0x02,
LFN_UTF8 = 0x04,
} ;
class StrArray;
class CharSetCvt;
class MD5;
class StrBuf;
class DateTimeHighPrecision; // for the high-precision modtime calls
class DiskSpaceInfo {
public:
DiskSpaceInfo();
~DiskSpaceInfo();
P4INT64 blockSize;
P4INT64 totalBytes;
P4INT64 usedBytes;
P4INT64 freeBytes;
int pctUsed;
StrBuf *fsType;
} ;
class FileSys {
public:
// Creators
static FileSys *Create( FileSysType type );
static FileSys *CreateTemp( FileSysType type ) {
FileSys *f = Create( type );
f->SetDeleteOnClose();
return f;
}
static FileSys *CreateGlobalTemp( FileSysType type ) {
FileSys *f = Create( type );
f->SetDeleteOnClose();
f->MakeGlobalTemp();
return f;
}
// special temp for simple locking
static FileSys *CreateLock( FileSys *, Error * );
static FilePerm Perm( const char *p );
static bool FileExists( const char *p );
static int BufferSize();
static bool IsRelative( const StrPtr &p );
# ifdef OS_NT
static bool IsUNC( const StrPtr &p );
# endif
virtual void SetBufferSize( size_t ) { }
int IsUnderPath( const StrPtr &path );
static int SymlinksSupported()
# ifdef OS_NT
; // Have to probe the system to decide
# else
# ifdef HAVE_SYMLINKS
{ return 1; }
# else
{ return 0; }
# endif
# endif
// Get/set perms, modtime
void Perms( FilePerm p ) { perms = p; }
void ModTime( StrPtr *u ) { modTime = u->Atoi(); }
void ModTime( time_t t ) { modTime = (int)t; }
time_t GetModTime() { return modTime; }
// Set filesize hint for NT fragmentation avoidance
void SetSizeHint( offL_t l ) { sizeHint = l; }
offL_t GetSizeHint() { return sizeHint; }
// Set advise hint (don't pollute O.S cache with archive content)
virtual void SetCacheHint() { cacheHint = 1; }
// Initialize digest
virtual void SetDigest( MD5 *m );
// Get type info
FileSysType GetType() { return type; }
int IsExec() { return ( type & FST_M_EXEC ); }
int IsTextual() {
return ( type & FST_MASK ) == FST_TEXT ||
( type & FST_MASK ) == FST_UNICODE ||
( type & FST_MASK ) == FST_UTF8 ||
( type & FST_MASK ) == FST_UTF16;
}
int IsUnicode() {
return ( type & FST_MASK ) == FST_UNICODE ||
( type & FST_MASK ) == FST_UTF8 ||
( type & FST_MASK ) == FST_UTF16;
}
int IsSymlink() {
return ( type & FST_MASK ) == FST_SYMLINK;
}
// Read/write file access, provided by derived class
FileSys();
virtual ~FileSys();
# ifdef OS_NT
virtual void SetLFN( const StrPtr &name );
virtual int GetLFN( ) {return LFN;}
# endif
virtual void Set( const StrPtr &name );
virtual void Set( const StrPtr &name, Error *e );
virtual StrPtr *Path() { return &path; }
virtual int DoIndirectWrites();
virtual void Translator( CharSetCvt * );
virtual void Open( FileOpenMode mode, Error *e ) = 0;
virtual void Write( const char *buf, int len, Error *e ) = 0;
virtual int Read( char *buf, int len, Error *e ) = 0;
virtual void Close( Error *e ) = 0;
virtual int Stat() = 0;
virtual int StatModTime() = 0;
virtual void StatModTimeHP(DateTimeHighPrecision *modTime);
virtual void Truncate( Error *e ) = 0;
virtual void Truncate( offL_t offset, Error *e ) = 0;
virtual void Unlink( Error *e = 0 ) = 0;
virtual void Rename( FileSys *target, Error *e ) = 0;
virtual void Chmod( FilePerm perms, Error *e ) = 0;
virtual void ChmodTime( Error *e ) = 0;
virtual void ChmodTimeHP( const DateTimeHighPrecision & /* modTime */, Error * /* e */ ) {};
virtual void SetAttribute( FileSysAttr, Error * ) { };
virtual void Fsync( Error * ) { }
// NB: these for ReadFile only; interface will likely change
virtual bool HasOnlyPerm( FilePerm perms );
virtual int GetFd();
virtual int GetOwner();
virtual offL_t GetSize();
virtual void Seek( offL_t offset, Error * );
virtual offL_t Tell();
// Convenience wrappers for above
void Chmod( Error *e ) { Chmod( perms, e ); }
void Chmod( const char *perms, Error *e )
{ Chmod( Perm( perms ), e ); }
char * Name() { return Path()->Text(); }
void Set( const char *name ) { Set( StrRef( name ) ); }
void Set( const char *name, Error *e )
{ Set( StrRef( name ), e ); }
void Write( const StrPtr &b, Error *e )
{ Write( b.Text(), b.Length(), e ); }
void Write( const StrPtr *b, Error *e )
{ Write( b->Text(), b->Length(), e ); }
// Tempfile support
void MakeGlobalTemp();
virtual void MakeLocalTemp( char *file );
int IsDeleteOnClose() { return isTemp; }
void SetDeleteOnClose() { isTemp = 1; }
void ClearDeleteOnClose() { isTemp = 0; }
// Meta operations
virtual StrArray *ScanDir( Error *e );
virtual void MkDir( const StrPtr &p, Error *e );
void MkDir( Error *e ) { MkDir( path, e ); }
virtual void PurgeDir( const char *p, Error *e );
virtual void RmDir( const StrPtr &p, Error *e );
void RmDir( Error *e = 0 ) { RmDir( path, e ); }
FileSysType CheckType( int scan = -1 );
# if defined ( OS_MACOSX )
FileSysType CheckTypeMac();
# endif
// Type generic operations
virtual int ReadLine( StrBuf *buf, Error *e );
void ReadWhole( StrBuf *buf, Error *e );
// Type generic, whole file operations
void ReadFile( StrBuf *buf, Error *e );
void WriteFile( const StrPtr *buf, Error *e );
int Compare( FileSys *other, Error *e );
void Copy( FileSys *targetFile, FilePerm perms, Error *e );
virtual void Digest( StrBuf *digest, Error *e );
void Chmod2( FilePerm perms, Error *e );
void Chmod2( const char *p, Error *e )
{ Chmod2( Perm( p ), e ); }
void Cleanup();
// Character Set operations
void SetCharSetPriv( int x = 0 ) { charSet = x; }
int GetCharSetPriv() { return charSet; }
void SetContentCharSetPriv( int x = 0 ) { content_charSet = x; }
int GetContentCharSetPriv() { return content_charSet; }
void GetDiskSpace( DiskSpaceInfo *info, Error *e );
void LowerCasePath();
protected:
FileOpenMode mode; // read or write
FilePerm perms; // leave read-only or read-write
int modTime; // stamp file mod date on close
offL_t sizeHint; // how big will the file get ?
StrBuf path;
FileSysType type;
MD5 *checksum; // if verifying file transfer
int cacheHint; // don't pollute cache
# ifdef OS_NT
int LFN;
# endif
private:
void TempName( char *buf );
int isTemp;
int charSet;
int content_charSet;
} ;
| true |
0912b470c23cc98f76ccf0a3222f9ff115ef2c58 | C++ | IgorYunusov/Mega-collection-cpp-1 | /数据结构STL版/第4章/PBiTree.h | GB18030 | 1,616 | 2.984375 | 3 | [] | no_license | //PBiTree.h ָṹĶࣨPBiTreeࣩ
#ifndef _PBITREE_H_
#define _PBITREE_H_
#define BiTNode PBiTNode
#include "BiTree.h"
template<typename T>class PBiTree: public BiTree<T>
{
static void VisitParent(BiTNode<T> &c)
{
if (c.lchild != NULL)
c.lchild->parent = &c;
if (c.rchild != NULL)
c.rchild->parent = &c;
}
public:
void CreateBiTreeFromFile(ifstream &f)
{
BiTree<T>::CreateBiTreeFromFile(f);
OrderTraverse(root, Pre, VisitParent);
root->parent = NULL;
}
bool InsertChild(PBiTNode<T>* &p, bool LR, PBiTree<T> &c)
{
BiTree<T>::InsertChild(p, LR, c);
if (p != NULL) {
if (!LR) {
p->lchild->parent = p;
if (p->lchild->rchild)
p->lchild->rchild->parent = p->lchild;
} else {
p->rchild->parent = p;
if (p->rchild->rchild)
p->rchild->rchild->parent = p->rchild;
}
return true;
}
return false;
}
BiTNode<T>* Parent(BiTNode<T>* p)const
{
return p->parent;
}
bool Sibling(BiTNode<T>* p, BiTNode<T>* &sib, bool &LR)const
{
if (p->parent == NULL)
return false;
if (p->parent->lchild == p) {
sib = p->parent->rchild;
LR = true;
} else {
sib = p->parent->lchild;
LR = false;
}
return sib != NULL;
}
};
#endif
| true |
3785b0113afb745e4018e7cf32e9a216362bd34d | C++ | Sjhunt93/Nes-Emulator | /NES Emulator/Source/Audio/Filter.hpp | UTF-8 | 1,658 | 2.671875 | 3 | [] | no_license | //
// Filter.hpp
// NES Emulator - App
//
// Created by Samuel Hunt on 21/02/2019.
//
#ifndef Filter_hpp
#define Filter_hpp
#include "Audio.h"
class FirstOrderFilter {
public:
float B0;
float B1;
float A1;
float prevX;
float prevY;
float step(float x)
{
float y = B0*x + B1*prevX - A1*prevY;
prevY = y;
prevX = x;
return y;
}
};
class Filter
{
public:
Filter (const float _sampleRate, const float _cutoff)
{
sampleRate = _sampleRate;
cutoff = _cutoff;
}
float step(float x)
{
return coreFilter.step(x);
}
float sampleRate;
float cutoff;
FirstOrderFilter coreFilter;
};
class LowPassFilter : public Filter
{
LowPassFilter (const float _sampleRate, const float _cutoff) : Filter (_sampleRate, _cutoff)
{
float c = sampleRate / M_PI / cutoff;
float a0i = 1.0 / (1.0 + c);
coreFilter.B0 = a0i;
coreFilter.B1 = a0i;
coreFilter.A1 = (1.0 - c) * a0i;
}
};
class HighPassFilter : public Filter
{
HighPassFilter (const float _sampleRate, const float _cutoff) : Filter (_sampleRate, _cutoff)
{
float c = sampleRate / M_PI / cutoff;
float a0i = 1.0 / (1.0 + c);
coreFilter.B0 = c * a0i;
coreFilter.B1 = -c * a0i;
coreFilter.A1 = (1.0 - c) * a0i;
}
};
#if 0
type FilterChain []Filter
func (fc FilterChain) Step(x float32) float32 {
if fc != nil {
for i := range fc {
x = fc[i].Step(x)
}
}
return x
}
#endif
#endif /* Filter_hpp */
| true |
e1415f2a1450dcc339a40d7fcf23c1c350dcd59c | C++ | satellitnorden/Catalyst-Engine | /Engine/Include/Math/General/SpringDampingSystem.h | UTF-8 | 2,029 | 3.234375 | 3 | [] | no_license | #pragma once
//Core.
#include <Core/Essential/CatalystEssential.h>
class SpringDampingSystem final
{
public:
/*
* Returns the current.
*/
FORCE_INLINE NO_DISCARD float32 GetCurrent() const NOEXCEPT
{
return _Current;
}
/*
* Returns the velocity.
*/
FORCE_INLINE NO_DISCARD float32 GetVelocity() const NOEXCEPT
{
return _Velocity;
}
/*
* Sets the current.
*/
FORCE_INLINE void SetCurrent(const float32 value) NOEXCEPT
{
_Current = value;
}
/*
* Returns the desired value.
*/
FORCE_INLINE NO_DISCARD float32 GetDesired() const NOEXCEPT
{
return _Desired;
}
/*
* Sets the desired value.
*/
FORCE_INLINE void SetDesired(const float32 desired) NOEXCEPT
{
_Desired = desired;
}
/*
* Sets the damping coefficient.
*/
FORCE_INLINE void SetDampingCoefficient(const float32 damping_coefficient) NOEXCEPT
{
_DampingCoefficient = damping_coefficient;
}
/*
* Sets the spring constant.
*/
FORCE_INLINE void SetSpringConstant(const float32 spring_constant) NOEXCEPT
{
_SpringConstant = spring_constant;
}
/*
* Sets the velocity.
*/
FORCE_INLINE void SetVelocity(const float32 velocity) NOEXCEPT
{
_Velocity = velocity;
}
/*
* Updates the spring damping system. Returns the current value.
*/
FORCE_INLINE constexpr NO_DISCARD float32 Update(const float32 delta_time) NOEXCEPT
{
//Calculate the difference.
const float32 difference{ _Current - _Desired };
//Calculate the acceleration.
const float32 acceleration{ -difference * _SpringConstant - _DampingCoefficient * _Velocity };
//Update the velocity.
_Velocity += acceleration * delta_time;
//Update the current value.
_Current += _Velocity * delta_time;
//Return the current value.
return _Current;
}
private:
//The current value.
float32 _Current{ 0.0f };
//The desired value.
float32 _Desired{ 0.0f };
//The velocity.
float32 _Velocity{ 0.0f };
//The damping coefficient.
float32 _DampingCoefficient{ 0.0f };
//The spring constant.
float32 _SpringConstant{ 1.0f };
}; | true |
e931a63b879a6e84ba81272e640b04558f6bbe4e | C++ | inge91/AISnake | /screen.cpp | UTF-8 | 210 | 2.515625 | 3 | [] | no_license | #include "screen.h"
bool Screen::handle_input(SDL_Event e, Screen* s)
{
if (e.type == SDL_QUIT)
{
return false;
}
}
void Screen::execute_tick(SDL_Renderer* renderer){
std::cout << "Here" << std::endl;
} | true |
c62b42d2275c2a96758a0d594e6e23d3f9e8e502 | C++ | rmalusa72/cs310-quickhull | /qhull.cpp | UTF-8 | 916 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <cmath>
#include <CGAL/Cartesian_d.h>
#include <CGAL/constructions_d.h>
typedef CGAL::Cartesian_d<double> K;
typedef CGAL::Point_d<K> Point;
typedef CGAL::Vector_d<K> Vector;
typedef CGAL::Segment_d<K> Segment;
typedef CGAL::Hyperplane_d<K> Hyperplane;
typedef K::Squared_distance_d Squared_distance;
typedef K::Orientation_d Orientation;
double point_plane_sqdistance(Hyperplane plane, Point on_plane, Point y){
int dim = plane.dimension();
double origin[dim];
for(int i=0; i<dim; i++){
origin[i] = 0;
}
Point o = Point(dim, origin, &origin[dim]);
Vector a = plane.orthogonal_vector();
Vector yv = y-o;
Vector pv = on_plane-o;
// d = p dot a
double d = pv*a;
// distance = y dot a - d / |a|
double squared_distance = pow(yv*a - d,2.0) / a.squared_length();
return squared_distance;
}
int main()
{
}
| true |
ed9d164a6a695627507e550cdab820d8dbf6cda6 | C++ | CFWLoader/Basic-Algorithm | /Matrix-Chain-Order/main.cpp | UTF-8 | 488 | 2.859375 | 3 | [] | no_license | //
// Created by cfwloader on 9/3/15.
//
#include <iostream>
#include "MatrixChain.h"
using namespace std;
int main(int argc, char* argv[])
{
vector<int> dimension = {3, 6, 9, 12};
MatrixChain matrixChain(dimension);
for (int i = 0; i < matrixChain.getCostMatrix().size(); ++i) {
for (int j = 0; j < matrixChain.getCostMatrix().size(); ++j) {
cout << matrixChain.getCostMatrix()[i][j] << " ";
}
cout << endl;
}
return 0;
}
| true |
4e57009b1e570797363b497276c6a92101ca5fa5 | C++ | shashidhargr111/C-Plus-Plus | /l9.cpp | UTF-8 | 549 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<string.h>
using namespace std;
class STRING
{
char *p;
int len;
public:STRING()
{
}
STRING(char *a)
{
len=strlen(a);
p=new char[len+1];
strcpy(p,a);
}
friend int operator ==(STRING,STRING);
};
int operator ==(STRING x,STRING y)
{
if(strcmp(x.p,y.p)==0)
return 1;
else
return 0;
}
int main()
{
STRING s1,s2;
char str1[10],str2[10];
cout<<"Enter 1st string\n";
cin>>str1;
cout<<"Enter 2nd string\n";
cin>>str2;
s1=str1;
s2=str2;
if(s1==s2)
cout<<"Strings are equal\n";
else
cout<<"Strings are not equal\n";
return 0;
}
| true |
b87271a27db762aab1d5f17340b5ac5b3dd976c0 | C++ | 2ooom/annoyjni | /src/main/cpp/annoyint.h | UTF-8 | 2,421 | 2.53125 | 3 | [] | no_license | #include "annoylib.h"
#include "kissrandom.h"
extern "C" {
long createAngular(int f) {
return (long)new AnnoyIndex<int32_t, float, Angular, Kiss64Random>(f);
}
long createDotProduct(int f) {
return (long)new AnnoyIndex<int32_t, float, DotProduct, Kiss64Random>(f);
}
long createEuclidean(int f) {
return (long)new AnnoyIndex<int32_t, float, Euclidean, Kiss64Random>(f);
}
long createManhattan(int f) {
return (long)new AnnoyIndex<int32_t, float, Manhattan, Kiss64Random>(f);
}
long createHamming(int f) {
return (long)new HammingWrapper<Kiss64Random>(f);
}
void deleteIndex(long ptr) {
delete (AnnoyIndexInterface<int32_t, float> *)ptr;
}
void addItem(long ptr, int32_t item, float *w) {
((AnnoyIndexInterface<int32_t, float> *)ptr)->add_item(item, w);
}
void build(long ptr, int q) {
((AnnoyIndexInterface<int32_t, float> *)ptr)->build(q);
}
bool save(long ptr, char *filename) {
return ((AnnoyIndexInterface<int32_t, float> *)ptr)->save(filename);
}
void unload(long ptr) {
((AnnoyIndexInterface<int32_t, float> *)ptr)->unload();
}
bool load(long ptr, char *filename) {
return ((AnnoyIndexInterface<int32_t, float> *)ptr)->load(filename);
}
float getDistance(long ptr, int32_t i, int32_t j) {
return ((AnnoyIndexInterface<int32_t, float> *)ptr)->get_distance(i, j);
}
void getNnsByItem(long ptr, int32_t item, int n,
int search_k, int32_t *result, float *distances) {
vector<int32_t> resultV;
vector<float> distancesV;
((AnnoyIndexInterface<int32_t, float> *)ptr)->get_nns_by_item(item, n, search_k, &resultV, &distancesV);
std::copy(resultV.begin(), resultV.end(), result);
std::copy(distancesV.begin(), distancesV.end(), distances);
}
void getNnsByVector(long ptr, float *w, int n,
int search_k, int32_t *result, float *distances) {
vector<int32_t> resultV;
vector<float> distancesV;
((AnnoyIndexInterface<int32_t, float> *)ptr)->get_nns_by_vector(w, n, search_k, &resultV, &distancesV);
std::copy(resultV.begin(), resultV.end(), result);
std::copy(distancesV.begin(), distancesV.end(), distances);
}
int getNItems(long ptr) {
return (int)((AnnoyIndexInterface<int32_t, float> *)ptr)->get_n_items();
}
void verbose(long ptr, bool v) {
((AnnoyIndexInterface<int32_t, float> *)ptr)->verbose(v);
}
void getItem(long ptr, int32_t item, float *v) {
((AnnoyIndexInterface<int32_t, float> *)ptr)->get_item(item, v);
}
} | true |
57d5223128637e6bfb5fafbbce167ea13d6124a9 | C++ | capull0/SkyReader | /checksum.cpp | UTF-8 | 8,768 | 3.484375 | 3 | [] | no_license | #include "checksum.h"
/*
data checksums
The checksums are a mess. There are four "types" of checksums:
Type 0: this is a CRC16 checksum of the first 0x1E unsigned chars of sector 0. The checksum itself is stored in block 0x01, offset 0x0E.
Type 1: this is a CRC16 checksum of the data area header. As there are two data areas, there are two of these checksums.
One is at block 0x08, offset 0x0E, and the other is at block 0x24, offset 0x0E.
Type 2: this is a CRC16 checksum of the data area. As there are two data areas, there are two of these checksums.
One is at block 0x08, offset 0x0C, and the other is at block 0x24, offset 0x0C.
Type 3: this is another CRC16 checksum of the data area, except padded with zeroes. As there are two data areas,
there are two of these checksums. One is at block 0x08, offset 0x0A, and the other is at block 0x24, offset 0x0A.
As type 0 is a checksum of a *supposedly* read-only sector, it's not all that important. It's also very straightforward to understand.
The type 1 checksum is a checksum of just one block, the data area header (0x08 and 0x24). As it's also stored WITHIN the
data area header, a default value must be supplied for the checksum before actually calculating it. That value is 0x0005.
The type 2 checksum is actually only a checksum of the first 4 blocks (EXCLUDING the data area header, and the access control blocks).
The type 3 checksum is a checksum of the next 4 blocks (EXCLUDING the data area header, and the access control blocks),
and then 0x0E blocks of zeroes.
Just to re-iterate, the encryption is applied AFTER all this checksum mess is done.
*/
// CCITT CRC Code
// Update the CRC for transmitted and received data using
// the CCITT 16bit algorithm (X^16 + X^12 + X^5 + 1).
unsigned short Checksum::UpdateCcittCrc16(unsigned short crc16, unsigned char data)
{
unsigned short num2 = (unsigned short) (data << 8);
for (unsigned int i = 0; i < 8; i++)
{
int num3;
if ((crc16 ^ num2) > 0x7fff)
{
num3 = 1;
}
else
{
num3 = 0;
}
crc16 = (unsigned short) ((crc16 << 1) ^ (num3 * 0x1021));
num2 = (unsigned short) (num2 << 1);
}
return crc16;
}
unsigned short Checksum::ComputeCcittCrc16(void const* data, unsigned int bytes)
{
unsigned short crc = 0xffff;
unsigned char const* numPtr = (unsigned char const*)data;
for (unsigned int i = 0; i < bytes; i++)
{
crc = UpdateCcittCrc16(crc, *((unsigned char const*) (numPtr + i)));
}
return crc;
}
bool Checksum::getChecksumParameters(int checksumType, unsigned int* checksumOffset, unsigned int* dataOffset, unsigned int* dataLength)
{
switch (checksumType)
{
case 0:
// Type 0 checksum.
*checksumOffset = 0x1E; // The checksum itself is stored in block 0x01, offset 0x0E.
*dataOffset = 0;
*dataLength = 0x1E; // checksum of the first 0x1E unsigned chars of sector 0.
break;
case 1:
// Type 1 checksum.
// Type 1: this is a CRC16 checksum of the data area header. As there are two data areas,
// there are two of these checksums. One is at block 0x08, offset 0x0E, and the other is at block 0x24, offset 0x0E.
*checksumOffset = 0x0E; // Checksum is stored within the data header block.
*dataOffset = 0;
*dataLength = 0x10; // The type 1 checksum is a checksum of just one block, the data area header (blocks 0x08 and 0x24).
break;
case 2:
// Type 2 checksum.
// Type 2: this is a CRC16 checksum of the data area. As there are two data areas, there are two of these checksums.
// One is at block 0x08, offset 0x0C, and the other is at block 0x24, offset 0x0C.
*checksumOffset = 0x0C;
*dataOffset = 0x10;
*dataLength = 0x40; // Checksum of the first 4 blocks (EXCLUDING the data area header, and the access control blocks).
break;
case 3:
// Type 3 checksum.
// Type 3: this is another CRC16 checksum of the data area, except padded with zeroes. As there are two data areas,
// there are two of these checksums. One is at block 0x08, offset 0x0A, and the other is at block 0x24, offset 0x0A.
// The type 3 checksum is a checksum of the next 4 blocks after the type 2 checksum
// (EXCLUDING the data area header, and the access control blocks), and then 0x0E blocks of zeroes.
*checksumOffset = 0x0A;
*dataOffset = 0x50;
*dataLength = 0x40;
break;
default:
return false;
}
return true;
}
bool Checksum::computeChecksum(int type, void const* memoryIn, unsigned short* checksum)
{
unsigned int startBlock;
unsigned int cntBlock;
unsigned int block;
unsigned char const* numPtr = (unsigned char const*)memoryIn;
Crypt crypt;
if ((type == 0) || (type == 1))
{
unsigned int dataLength;
unsigned int dataOffset;
unsigned int checksumOffset;
if (!getChecksumParameters(type, &checksumOffset, &dataOffset, &dataLength))
{
return false;
}
if (type == 1)
{
unsigned char header[0x10];
memcpy(header, (void const*) (numPtr + dataOffset), 0x10);
*(header + 14) = 5;
*(header + 15) = 0;
*checksum = ComputeCcittCrc16((void const*) &header, dataLength);
}
else
{
*checksum = ComputeCcittCrc16((void const*) (numPtr + dataOffset), dataLength);
}
return true;
}
if (type == 2)
{
startBlock = 1;
cntBlock = 4;
}
else if (type == 3)
{
startBlock = 5;
cntBlock = 4;
}
else
{
return false;
}
numPtr += (startBlock * 0x10);
*checksum = 0xffff;
block = startBlock;
while(true)
{
if (block >= (startBlock + cntBlock))
{
if (type != 3)
{
return true;
}
block = startBlock + cntBlock;
break;
}
if (!crypt.IsAccessControlBlock(block))
{
for (unsigned int i = 0; i < 0x10; i++)
{
*checksum = UpdateCcittCrc16(*checksum, *((unsigned char*) (numPtr + i)));
}
}
numPtr += 0x10;
block++;
}
// Pad Type 3 checksum with 0x0E blocks of zeroes
while (block < 0x1c)
{
if (!crypt.IsAccessControlBlock(block))
{
for (unsigned int j = 0; j < 0x10; j++)
{
*checksum = UpdateCcittCrc16(*checksum, 0);
}
}
block++;
}
return true;
}
// validateChecksum
// buffer: pointer to entire decrypted character as single chunk of memory
// type: checksum type
// dataArea: dataArea to validate.
// A value of 0 indicates the first data area starting at 0x08
// A value of 1 indicates the second data area starting at 0x24
// overwrite: if true, replace checksum in buffer with newly computed checksum
//
// returns true if old checksum in buffer matches computed checksum.
bool Checksum::validateChecksum(unsigned char *buffer, int type, int dataArea, bool overwrite)
{
unsigned int checksumOffset;
unsigned int areaSequenceOffset;
unsigned short computedChecksum;
unsigned int dataLength;
unsigned int dataOffset;
unsigned int offset = 0;
unsigned char *ptr;
bool match;
if (!getChecksumParameters(type, &checksumOffset, &dataOffset, &dataLength))
{
return false;
}
if (type != 0)
{
int dataAreaBlock;
if (dataArea == 0)
{
dataAreaBlock = 0x08;
}
else
{
dataAreaBlock = 0x24;
}
offset += (unsigned int) (dataAreaBlock * 0x10);
}
ptr = buffer + offset;
if(overwrite && type == 1) {
// Before computing checksum 1 (and after computing checksum 2 and 3)
// update sequence number.
areaSequenceOffset = 0x09;
ptr[areaSequenceOffset]++; // increment sequence
}
if (!computeChecksum(type, ptr, &computedChecksum))
{
return false;
}
unsigned short oldChecksum = (unsigned short) ((ptr[checksumOffset] & 0xff) | ((ptr[(int) (checksumOffset + 1)] & 0xff) << 8));
match = (oldChecksum == computedChecksum);
if(overwrite) {
// overwrite old value with newly computed checksum
ptr[checksumOffset] = computedChecksum & 0xff;
ptr[checksumOffset+1] = (computedChecksum >> 8) & 0xff;
}
return match;
}
bool Checksum::ValidateAllChecksums(unsigned char *buffer, bool overwrite)
{
bool OK = true;
bool res;
int dataArea;
int type;
// When computing checksums for overwrite, they have to be done in the following order.
// Compute checksum 3 and 2, then increment the area sequence number by 1,
// then compute checksum 1.
//
// In the logic below, the area sequence number is set just prior to computing checksum 1.
for(dataArea = 0; dataArea <= 1; dataArea++) {
for(type = 3; type >=0; type--) {
res = validateChecksum(buffer, type, dataArea, overwrite);
if(!res && !overwrite) {
fprintf(stderr, "Checksum failure for checksum type %d, data area %d", type, dataArea);
}
OK = OK && res;
}
}
return OK;
}
| true |
cbc5cdde29f92f033f311c56995cb8e5f5947dbf | C++ | territo-sci/flare | /src/ShaderProgram.cpp | UTF-8 | 6,372 | 2.75 | 3 | [] | no_license | /*
* Author: Victor Sand (victor.sand@gmail.com)
*
*/
// TODO abstraction of shader binder, maybe a templated ShaderBinder class?
// or string values service
// possibly make a common UniformType class to handle matrices, ints, floats
#include <GL/glew.h>
#ifndef _WIN32
#include <GL/glfw.h>
#else
#include <GL/glfw3.h>
#endif
#include <Utils.h>
#include <ShaderProgram.h>
#include <Texture2D.h>
#include <algorithm>
#include <fstream>
using namespace osp;
ShaderProgram * ShaderProgram::New() {
return new ShaderProgram();
}
ShaderProgram::ShaderProgram()
: vertexShaderSet_(false),
fragmentShaderSet_(false),
programHandle_(0),
vertexSource_(""),
fragmentSource_("") {
}
bool ShaderProgram::CreateShader(ShaderType _type, std::string _fileName) {
// Handle different types
// Save source filenames to enable reloading shaders
std::string typeString;
GLuint type;
switch (_type) {
case ShaderProgram::VERTEX:
type = GL_VERTEX_SHADER;
typeString = "vertex";
vertexSource_ = _fileName;
break;
case ShaderProgram::FRAGMENT:
type = GL_FRAGMENT_SHADER;
typeString = "fragment";
fragmentSource_ = _fileName;
break;
default:
ERROR("Invalid shader type");
return false;
}
INFO("Creating " << typeString << " shader from source file " << _fileName);
// Create shader
unsigned int handle = glCreateShader(type);
if (glIsShader(handle) == GL_FALSE) {
ERROR("Failed to create shader");
CheckGLError("CreateShader()");
return false;
}
// Read shader source
char *source = ReadTextFile(_fileName);
const char *constSource = source;
glShaderSource(handle, 1, &constSource, NULL);
glCompileShader(handle);
int shaderCompiled;
glGetShaderiv(handle, GL_COMPILE_STATUS, &shaderCompiled);
if (shaderCompiled != GL_TRUE) {
ERROR("Shader compilation failed");
CheckGLError("CreateShader()");
PrintLog(handle);
return false;
}
// Save shader handle
shaderHandles_.push_back(handle);
free(source);
if (_type == ShaderProgram::VERTEX) vertexShaderSet_ = true;
else if (_type == ShaderProgram::FRAGMENT) fragmentShaderSet_ = true;
return true;
}
bool ShaderProgram::CreateProgram() {
INFO("Creating shader program");
if (!vertexShaderSet_){
ERROR("Can't create program, vertex shader not set");
return false;
}
if (!fragmentShaderSet_) {
ERROR("Can't create program, fragment shader not set");
return false;
}
// Create new program
programHandle_ = glCreateProgram();
// Attach the shaders
std::vector<unsigned int>::iterator it;
for (it=shaderHandles_.begin(); it!=shaderHandles_.end(); it++)
{
glAttachShader(programHandle_, *it);
}
// Link the program
INFO("Linking shader program");
glLinkProgram(programHandle_);
int programLinked;
glGetProgramiv(programHandle_, GL_LINK_STATUS, &programLinked);
if (programLinked != GL_TRUE) {
ERROR("Program linking failed");
CheckGLError("CreateProgram()");
PrintLog(programHandle_);
return false;
}
return true;
}
bool ShaderProgram::PrintLog(unsigned int _handle) const {
int logLength, maxLength;
// Handle shaders and programs differently
if (glIsShader(_handle)) {
glGetShaderiv(_handle, GL_INFO_LOG_LENGTH, &maxLength);
} else {
glGetProgramiv(_handle, GL_INFO_LOG_LENGTH, &maxLength);
}
std::vector<char> log(maxLength);
if (glIsShader(_handle)) {
glGetShaderInfoLog(_handle, maxLength, &logLength, (GLchar*)&log[0]);
} else {
glGetProgramInfoLog(_handle, maxLength, &logLength, (GLchar*)&log[0]);
}
if (logLength > 0) {
DEBUG(&log[0]);
} else {
ERROR("Log length is not over zero");
return false;
}
return true;
}
char * ShaderProgram::ReadTextFile(std::string _fileName) const
{
FILE * in;
char * content = NULL;
in = fopen(_fileName.c_str(), "r");
if (in != NULL) {
fseek(in, 0, SEEK_END);
int count = ftell(in);
rewind(in);
content = (char *)malloc(sizeof(char)*(count+1));
count = fread(content, sizeof(char), count, in);
content[count] = '\0';
fclose(in);
} else {
ERROR("Could not read file " + _fileName);
}
return content;
}
bool ShaderProgram::BindMatrix4f(std::string _uniform, float * _matrix) {
glUseProgram(programHandle_);
int location = glGetUniformLocation(programHandle_, _uniform.c_str());
if (location == -1) {
ERROR("Uniform " << _uniform << " could not be found");
glUseProgram(0);
return false;
}
glUniformMatrix4fv(location, 1, GL_FALSE, _matrix);
glUseProgram(0);
return CheckGLError("BindMatrix4f()") == GL_NO_ERROR;
}
// TODO see if glUseProgram must be called before glGetUniformLocation
bool ShaderProgram::BindFloat(std::string _uniform, float _value) {
glUseProgram(programHandle_);
int location = glGetUniformLocation(programHandle_, _uniform.c_str());
if (location == -1) {
ERROR("Uniform " << _uniform << " could not be found");
glUseProgram(0);
return false;
}
glUniform1f(location, _value);
glUseProgram(0);
return CheckGLError("BindFloat()") == GL_NO_ERROR;
}
bool ShaderProgram::BindInt(std::string _uniform, int _value) {
glUseProgram(programHandle_);
int location = glGetUniformLocation(programHandle_, _uniform.c_str());
if (location == -1) {
ERROR("Uniform " << _uniform << " could not be found");
glUseProgram(0);
return false;
}
glUniform1i(location, _value);
glUseProgram(0);
return CheckGLError("Bindintf()") == GL_NO_ERROR;
}
unsigned int ShaderProgram::GetAttribLocation(std::string _attrib) const {
return glGetAttribLocation(programHandle_, _attrib.c_str());
}
bool ShaderProgram::Reload() {
if (!vertexShaderSet_ || !fragmentShaderSet_) {
ERROR("Can't reload, shaders not set");
return false;
}
CreateShader(ShaderProgram::VERTEX, vertexSource_);
CreateShader(ShaderProgram::FRAGMENT, fragmentSource_);
CreateProgram();
return true;
}
bool ShaderProgram::DeleteShaders() {
if (!vertexShaderSet_ || !fragmentShaderSet_) {
ERROR("Shader(s) not set, nothing to delete");
return false;
}
for (unsigned int i=0; i<shaderHandles_.size(); i++) {
glDetachShader(programHandle_, shaderHandles_[i]);
glDeleteShader(shaderHandles_[i]);
}
shaderHandles_.clear();
glDeleteProgram(programHandle_);
return true;
}
| true |
f1e28dc401e017c2ae9b3d336db15f9637e219d5 | C++ | narayanr7/HeavenlySword | /code/geometry/Sector2D.h | UTF-8 | 4,103 | 3.0625 | 3 | [] | no_license | /***************************************************************************************************
*
* DESCRIPTION Simple class to encapsulate a sector of a circle in two dimensions.
*
* NOTES
*
***************************************************************************************************/
#ifndef SECTOR2D_H_
#define SECTOR2D_H_
//**************************************************************************************
// Includes files.
//**************************************************************************************
#include "core/Maths.h"
#include "core/boundingvolumes.h"
#include "Circle2D.h"
//**************************************************************************************
// Typedefs.
//**************************************************************************************
//**************************************************************************************
// m_Facing
// ^
// --|--
// | | | <---- supposed to be circular arc :)
// -- | --
// | | |
// \ | / E
// \ | /
// \ | /
// \ | /
// \ | /
// \--|--/ <-|
// \ | / |
// \|/ m_BaseAngle
// v
// m_Apex
//
//
// m_Radius is the distance from m_Apex to point E on the diagram.
//
//**************************************************************************************
class Sector2D
{
public:
//
// Useful functions.
//
// Is (x,y) inside the sector.
inline bool IsInside ( float x, float y ) const;
public:
//
// Return AABB of this sector - N.B. this doesn't give a great bound as it
// only returns the AABB of the enclosing circle.
//
inline void CreateAABB ( CAABB &aabb ) const;
public:
//
// Ctor.
//
Sector2D( float apexX, float apexY, float radius,
float facingX, float facingY, float angle_in_rads )
: m_ApexX ( apexX )
, m_ApexY ( apexY )
, m_Radius ( radius )
, m_FacingX ( facingX )
, m_FacingY ( facingY )
, m_BaseAngle ( angle_in_rads )
, m_CosHalfBaseAngle ( cosf( angle_in_rads / 2.0f ) )
{
ntAssert_p( angle_in_rads <= PI, ("Sectors with base angles of more than 180degs are not supported.") );
float facing_len( sqrtf( m_FacingX*m_FacingX + m_FacingY*m_FacingY ) );
ntError_p( facing_len > 0.0f, ("You must supply a non-zero facing vector.") );
// Normalise our facing direction.
m_FacingX /= facing_len;
m_FacingY /= facing_len;
}
public:
//
// Public data members - explained in comment at top of class.
//
float m_ApexX, m_ApexY;
float m_Radius;
float m_FacingX, m_FacingY;
float m_BaseAngle; // In Radians.
float m_CosHalfBaseAngle;
};
//**************************************************************************************
//
//**************************************************************************************
bool Sector2D::IsInside( float x, float y ) const
{
if ( !Circle2D( m_ApexX, m_ApexY, m_Radius ).IsInside( x, y ) )
{
return false;
}
// The scalar product between our facing direction and a 2d vector
// from our apex to (x,y) will give us the cosine of the angle
// between them, if this angle is greater than our base angle then
// the point is outside the sector.
float dx( x - m_ApexX );
float dy( y - m_ApexY );
float Dlength( sqrtf( dx*dx + dy*dy ) );
static const float DIST_FUDGE = 0.0001f;
if ( Dlength > DIST_FUDGE )
{
dx /= Dlength;
dy /= Dlength;
}
float cos_angle( dx * m_FacingX + dy * m_FacingY );
if ( cos_angle <= m_CosHalfBaseAngle )
{
// If cos_angle <= cos_half_base_angle then angle > half_base_angle.
return false;
}
return true;
}
//**************************************************************************************
//
//**************************************************************************************
void Sector2D::CreateAABB( CAABB &aabb ) const
{
aabb.Min() = CPoint( m_ApexX - m_Radius, 0.0f, m_ApexY - m_Radius );
aabb.Max() = CPoint( m_ApexX + m_Radius, 0.0f, m_ApexY + m_Radius );
}
#endif // !SECTOR2D_H_
| true |
8cbcba0362b01ebe8590860a4e025042cce3d435 | C++ | csyezheng/Cpp-Primer | /ch09/9.27.cpp | UTF-8 | 464 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include <forward_list>
using std::cout;
using std::endl;
using std::forward_list;
int main()
{
forward_list<int> iFwList = { 1, 2, 3, 5, 23, 24 };
auto prev = iFwList.before_begin();
auto curr = iFwList.begin();
while (curr != iFwList.end())
{
if (*curr & 1)
{
curr = iFwList.erase_after(prev);
}
else
{
prev = curr;
++curr;
}
}
for (const auto &elem : iFwList)
cout << elem << " ";
cout << endl;
return 0;
} | true |
7e2999dcf3f7bdee6592c8556bc84dfbd81d1905 | C++ | alex-min/babelroxor | /babel-2014-minett_a/trunk/lib/network.h | UTF-8 | 773 | 2.546875 | 3 | [] | no_license | #ifndef NETWORK_H
#define NETWORK_H
#include <map>
#include "iportablesocket.h"
#include "circularbuffer.h"
#include "islotinterface.h"
#include "crc.h"
#include "singleton.h"
class Network
{
public:
Network(unsigned int readCirbufSize = 4096, unsigned int writeCirbufSize = 4096);
Network(PortableSocket *sock, unsigned int readCirbufSize = 4096, unsigned int writeCirbufSize = 4096);
CircularBuffer *getReadBuffer();
CircularBuffer *getWriteBuffer();
PortableSocket *getSocket();
void setSocket(PortableSocket *sock);
std::string const &getName() const;
void setName(std::string const &);
protected:
std::string _name;
PortableSocket *_socket;
CircularBuffer _readBuf;
CircularBuffer _writeBuf;
};
#endif // NETWORK_H
| true |
901f99f47bc2a143e5cce9eb564fec20f24e6697 | C++ | kenken64/VoiceControlledK-nexCar | /RaspberryPiArduinoControl/raspiMotorControl/raspiMotorControl.ino | UTF-8 | 1,899 | 3.296875 | 3 | [] | no_license | // Arduino Control for Raspberry Pi Voice Controlled Car
// Author: Austin Wilson
#include "MotorDriver.h"
MotorDriver motor;
char ser;
int greenPin = 3;
int redPin = 5;
int bluePin = 6;
#define COMMON_ANODE
void setup(){
pinMode(greenPin, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(bluePin, OUTPUT);
motor.begin();
Serial.begin(9600);
setColor(0, 0, 0);
}
void loop(){
if (Serial.available()) {
ser = Serial.read();
Serial.print(ser);
if(ser == '0' || ser == '1') {
motorDirection(ser);
} else if(ser == '2' || ser == '3' || ser == '4' || ser == '5' || ser == '6') {
carColor(ser);
} else if(ser == '7') {
motorStop();
} else {
}
}
delay(500);
}
void motorDirection(char dir)
{
if(dir == '0') {
motor.speed(0, 100); // set motor0 forward
motor.speed(1, 100); // set motor1 forward
} else if(dir == '1') {
motor.speed(0, -100); // set motor0 backward
motor.speed(1, -100); // set motor1 backward
} else {
Serial.print("Error Reading direction");
}
}
void carColor(char col) {
if(col == '2') {
setColor(0, 255, 0); // set lights to green
} else if(col == '3') {
setColor(255, 0, 0); // set lights to red
} else if(col == '4') {
setColor(0, 0, 255); // set lights to blue
} else if(col == '5') {
setColor(255, 153, 0); // set lights to orange
} else if(col == '6') {
setColor(255, 255, 0); // set lights to yellow
} else {
Serial.print("Error Reading color");
}
}
void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
red = 255 - red;
green = 255 - green;
blue = 255 - blue;
#endif
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
void motorStop()
{
motor.brake(0);
motor.brake(1);
}
| true |
11810b581b7f0dbbc3509d3e48b4ecf0ad618678 | C++ | dvir/homework | /spl/exercises/hw1/sentence.cpp | UTF-8 | 637 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<string> split(char sentence[], int len) {
vector<string> words;
string word = "";
for (size_t i = 0; i < len; i++) {
if (sentence[i] == ' ') {
words.push_back(word);
word = "";
} else {
word = word + sentence[i];
}
}
if (word != "") words.push_back(word);
return words;
}
void printWords(vector<string> words) {
for (size_t i = 0; i < words.size(); i++) {
cout << words[i] << endl;
}
}
int main(int argc, char *argv[]) {
char sentence[15] = "THIS IS SPARTA";
printWords(split(sentence, sizeof(sentence)));
return 0;
}
| true |
45f01129e7fe1022076d1f6746feec1d75a30a37 | C++ | niuxu18/logTracker-old | /second/download/git/gumtree/git_repos_function_2456_git-2.6.5.cpp | UTF-8 | 769 | 2.609375 | 3 | [] | no_license | static struct trailer_item *process_command_line_args(struct string_list *trailers)
{
struct trailer_item *arg_tok_first = NULL;
struct trailer_item *arg_tok_last = NULL;
struct string_list_item *tr;
struct trailer_item *item;
/* Add a trailer item for each configured trailer with a command */
for (item = first_conf_item; item; item = item->next) {
if (item->conf.command) {
struct trailer_item *new = new_trailer_item(item, NULL, NULL);
add_trailer_item(&arg_tok_first, &arg_tok_last, new);
}
}
/* Add a trailer item for each trailer on the command line */
for_each_string_list_item(tr, trailers) {
struct trailer_item *new = create_trailer_item(tr->string);
add_trailer_item(&arg_tok_first, &arg_tok_last, new);
}
return arg_tok_first;
} | true |
7ee9620c7699532f1abeb652e265fbcec12445e8 | C++ | Acytoo/leetcode | /c++/844backspaceString.cc | UTF-8 | 1,006 | 2.671875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <climits>
#include <stack>
#include <algorithm>
#include <cmath>
#include <set>
#include <unordered_map>
#include <list>
#include <unordered_set>
#include <map>
#include <set>
#include <functional>
using namespace std;
static int x = [] () {ios::sync_with_stdio(false); cin.tie(0); return 0;} ();
class Solution {
public:
bool backspaceCompare(string S, string T) {
stack<char> stack_s, stack_t;
for (char c: S)
if (c != '#')
stack_s.push(c);
else if (!stack_s.empty())
stack_s.pop();
for (char c: T)
if (c != '#')
stack_t.push(c);
else if (!stack_t.empty())
stack_t.pop();
if (stack_s.size() != stack_t.size())
return false;
while (!stack_s.empty()) {
if (stack_s.top() != stack_t.top())
return false;
stack_s.pop();
stack_t.pop();
}
return true;
}
};
int main() {
Solution s;
return 0;
}
| true |
5b358f09dbfa4ab9beeb34de2ebd288496b3681d | C++ | dastyk/SE | /SluaghEngine/Test/WindowTest.cpp | UTF-8 | 2,675 | 2.5625 | 3 | [] | no_license | #include "WindowTest.h"
#include <window/IWindow.h>
#include <Graphics/IRenderer.h>
//#include "Utilz/Console.h"
#include <Profiler.h>
#ifdef _DEBUG
#pragma comment(lib, "WindowD.lib")
#pragma comment(lib, "GraphicsD.lib")
#else
#pragma comment(lib, "Window.lib")
#pragma comment(lib, "Graphics.lib")
#endif
//using namespace SE::Window;
using namespace SE::Test;
WindowTest::WindowTest()
{
}
WindowTest::~WindowTest()
{
}
static void KeyCall()
{
// SE::Utilz::Console::Print("Callback called.\n");
}
static void MouseCall(int x, int y)
{
//SE::Utilz::Console::Print("Clicked at %d, %d.\n", x, y);
}
static void MouseMotionCall(int rx, int ry, int x, int y)
{
// SE::Utilz::Console::Print("Moved mouse %d, %d pixels.\n", rx, ry);
}
bool WindowTest::Run(SE::DevConsole::IConsole* console)
{
StartProfile;
//create a window pointer
SE::Window::IWindow* window = Window::CreateNewWindow();
//initiate window (display and input)
window->Initialize();
//bind keys
window->MapActionButton(0, SE::Window::KeyEscape);
window->MapActionButton(1, SE::Window::KeyW);
window->MapActionButton(2, SE::Window::KeyA);
window->MapActionButton(3, SE::Window::KeyD);
window->MapActionButton(1, SE::Window::KeyS);
window->MapActionButton(7, Window::KeyCode::KeyU);
window->MapActionButton(5, Window::KeyCode::MouseLeft);
window->MapActionButton(6, Window::KeyCode::MouseRight);
window->BindKeyPressCallback(2, &KeyCall);
window->BindMouseClickCallback(5, &MouseCall);
window->BindMouseMotionCallback(&MouseMotionCall);
window->MapActionButton(8, SE::Window::KeyO);
bool running = true;
while(running)
{
window->Frame();
if (window->ButtonDown(6))
console->Print("Mouse right down\n");
if (window->ButtonPressed(1))
console->Print("Action button %d pressed\n", 1);
if (window->ButtonPressed(0))
running = false;
if (window->ButtonDown(3))
console->Print("Action button %d down.\n", 3);
if (window->ButtonPressed(4))
console->Print("Action button %d pressed\n", 4);
if (window->ButtonPressed(7))
window->UnbindCallbacks();
if (window->ButtonPressed(8))
{
int x, y;
window->GetMousePos(x, y);
console->Print("Mouse at: %d, %d\n", x, y);
}
}
Graphics::IRenderer* renderer = Graphics::CreateRenderer();
renderer->Initialize({ window->GetHWND() });
uint8_t* fakeTexture = new uint8_t[256 * 256 * 4];
for(int i = 0; i < 256*256*4; i++)
{
fakeTexture[i] = 255;
}
Graphics::TextureDesc td;
td.width = 256;
td.height = 256;
renderer->CreateTexture(fakeTexture, td);
renderer->Shutdown();
window->Shutdown();
delete renderer;
delete window;
delete[] fakeTexture;
ProfileReturnConst(true);
} | true |
5b903a49fa1ba5e77a261cbf077bdf089adce34f | C++ | tedsta/Tetraverse | /include/PlayerDatabase.h | UTF-8 | 795 | 3.03125 | 3 | [] | no_license | #ifndef PLAYERDATABASE_H
#define PLAYERDATABASE_H
#include <string>
#include <vector>
class Engine;
class Entity;
struct Player
{
std::string mName;
std::string mPassword;
int mNetID; // -1 if the player isn't logged in
Entity* mEntity;
};
class PlayerDatabase
{
public:
PlayerDatabase(Engine* engine);
virtual ~PlayerDatabase();
void createPlayer(std::string name, std::string password);
bool validatePlayer(std::string name, std::string password);
bool loginPlayer(std::string name, int netID);
void logoutPlayer(int netID);
Player* findPlayer(std::string name);
Player* findPlayer(int netID);
private:
Engine* mEngine;
std::vector<Player> mPlayers;
};
#endif // PLAYERDATABASE_H
| true |
8a80ca012cc2367a85c283e6b7019fa128c60498 | C++ | iamweiweishi/LeetCode-Problems | /127.cpp | UTF-8 | 1,380 | 2.671875 | 3 | [
"MIT"
] | permissive | class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
if(!wordList.size()) return 0;
queue<string> q;
queue<int> t;
unordered_map<string,bool> visited;
q.push(beginWord);
t.push(1);
visited[beginWord]=true;
int l=beginWord.length(),pos=-1;
for(int i=0;i<wordList.size();i++){
if(endWord.compare(wordList[i])==0){
pos=i;
break;
}
}
if(pos==-1) return 0;
while(q.size()){
string nowWord=q.front();
q.pop();
int nowNum=t.front();
t.pop();
if(nowNum>wordList.size()) return 0;
for(int i=0;i<wordList.size();i++){
int countd=0;
for(int j=0;j<l;j++){
if(wordList[i][j]!=nowWord[j]){
countd++;
if(countd>1) break;
}
}
if(countd==1){
if(i==pos) return nowNum+1;
if(!visited[wordList[i]]){
q.push(wordList[i]);
t.push(nowNum+1);
visited[wordList[i]]=true;
}
}
}
}
return 0;
}
};
| true |
a592b629a9cd2cfdba2eadd0a3b6105b7c73a9d3 | C++ | gayu-thri/Coding | /C/Program15_Books.cpp | UTF-8 | 1,764 | 3.59375 | 4 | [] | no_license | #include<stdio.h>
#include<string.h>
struct date
{
int mon, yr;
};
const date curr={5,2018};
struct book
{
int accno, price;
char title[18];
date pub;
void input()
{
printf("\n Enter the account number : ");
scanf("%d", &accno);
printf("\n Enter the price : ");
scanf("%d", &price);
printf("\n Enter the title : ");
scanf("%s", &title);
printf("\n Enter the month of publication : ");
scanf("%d", &pub.mon);
printf("\n Enter the year of publication : ");
scanf("%d", &pub.yr);
}
void output()
{
printf("\n Account number : ");
printf("%d",accno);
printf("\n Price : ");
printf("%d", price);
printf("\n Title : ");
printf(title);
printf("\n Month of publication : ");
printf("%d", pub.mon);
printf("\n Year of publication : ");
printf("%d", pub.yr);
}
};
int cmp(book a, book b)
{
int flag=0;
if(a.accno!=b.accno)
flag++;
if(a.price!=b.price)
flag++;
if(strcmp(a.title,b.title))
flag++;
if(a.pub.mon!=b.pub.mon)
flag++;
if(a.pub.yr!=b.pub.yr)
flag++;
return(flag);
}
book* search(book a[], book &ele, int &n)
{
book *ptr;
int i;
for(i=0;i<n;i++)
{
if(!cmp(a[i],ele))
ptr=&a[i];
}
return(ptr);
}
void display(book a[], int n)
{
int i;
for(i=0;i<n;i++)
{
if(a[i].pub.yr==curr.yr)
a[i].output();
}
}
int main()
{
book a[108], ele, *ans;
int n, i;
printf("\n Enter number of books required : ");
scanf("%d", &n);
printf("\n Enter the book details : \n");
for(i=0;i<n;i++)
a[i].input();
printf("\n Enter the book to be searched : \n");
ele.input();
ans=search(a,ele,n);
(*ans).output();
printf("\n Books published in this year are : \n");
display(a,n);
return 0;
}
| true |
439a82d0a137bb426c75e17344c6a81f442269ca | C++ | luqian2017/Algorithm | /LintCode/395_Coins-in-a-Line-II/395_Coins-in-a-Line-II-V3.cpp | UTF-8 | 757 | 3.421875 | 3 | [] | no_license | class Solution {
public:
/**
* @param values: a vector of integers
* @return: a boolean which equals to true if the first player will win
*/
bool firstWillWin(vector<int> &values) {
int len = values.size();
if (len < 3) return true;
int sum1 = values[len - 1];
int sum2 = values[len - 1] + values[len - 2];
int dp2 = sum2;
int dp1 = sum1;
for (int i = len - 3; i >= 0; --i) {
int dp = max(sum2 - dp2 + values[i],
sum1 - dp1 + values[i] + values[i + 1]);
dp1 = dp2;
dp2 = dp;
sum1 = sum2;
sum2 += values[i];
}
return sum2 - dp2 < dp2;
}
}; | true |
dbb8bf7053e0a2a1e655f71794f66ed19dce12c8 | C++ | Mouradouchane/HackerRank_ProblemSolving | /HackerRank/SerivceLane.cpp | UTF-8 | 1,149 | 3.296875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// problem : https://www.hackerrank.com/challenges/service-lane/problem
// solution O(n*k) ====================================================
// just normal function for getting min value instead of std::min
int getMin(std::vector<int> &w , int start , int end){ // O(k)
int min = w[start];
for(int h = start ; h <= end ; h += 1){
if(w[h] < min) min = w[h];
}
return min;
}
// hint ==> you have to edit result variable in main()
// and edit serviceLane function to get vector of width & vector of test cases
vector<int> serviceLane(vector<int> w, vector<vector<int>> cs){
std::vector<int> minWidth; // when we store the all min widths in each test case :)
// loop over all test case
for(int i = 0 ; i < cs.size() ; i += 1){ // O(n)
// loop over widths form "cs->start" to "cs->end" & get min widths
// push min width to "minWidth" vector :)
minWidth.push_back( getMin(w,cs[i][0] , cs[i][1]) ); // O(k)
}
// return vector of min widths
return minWidth;
}
// ====================================================================== | true |
8c9c211e95ff48e506aca26151965ad2d0bb564e | C++ | thomasmaters/A2B-Applicatie | /Route.cpp | UTF-8 | 1,352 | 3 | 3 | [] | no_license | #include <string>
#include <vector>
#include <list>
#include <iostream>
#include <assert.h>
#include "Route.hpp"
void Route::inputRoute(Location A, Location B)
{
startPoint = A;
endPoint = B;
}
void Route::calculateRoute()
{
for(auto connectie : RoadNetwork::connectionpieces){
if(connectie->getStartPoint() == startPoint){
routes.push_back(*connectie);
break;
}
}
for(auto connectie : RoadNetwork::connectionpieces){
if(connectie->getEndPoint() == endPoint){
routes.push_back(*connectie);
break;
}
}
std::cout << "Uw route van " << startPoint.getName() << " naar " << endPoint.getName() << ":" << std::endl;
for(auto route : routes){
travelTime += route.getTravelTime();
std::cout << "U pakt het verbindingsstuk :" << route.getStartPoint().getName() << " - " << route.getEndPoint().getName() << " Met een totale reistijd van:" << route.getTravelTime() << " minuten met " << route.getAmountDelays() << " vertragingen." << std::endl ;
}
std::cout << "U bereikt uw bestemming in " << travelTime << " minuten." << std::endl;
}
Route::Route():
travelTime(0),
routes(std::vector<ConnectionPiece>()),
startPoint(),
endPoint()
{
}
Route::Route(const Route& aRoute):
travelTime(aRoute.travelTime),
routes(aRoute.routes),
startPoint(aRoute.startPoint),
endPoint(aRoute.endPoint)
{
}
Route::~Route()
{
}
| true |
b1ec029525430de874a861a789436ba60976befd | C++ | samychen/AndroidOpengl | /photoeditor/jni/beauty/gpuprocess/src/texture_2d.cpp | UTF-8 | 2,251 | 2.578125 | 3 | [] | no_license | #include "texture_2d.h"
#include <android/bitmap.h>
static int toolsavefile(unsigned char* pData, int size, char* name)
{
FILE *pf =fopen(name, "wb");
if(pf != 0){
fwrite(pData, size, 1, pf);
fclose(pf);
return 1;
}
return 0;
}
static int toolloadfile(unsigned char* pData, int size, char* name)
{
FILE *pf =fopen(name, "rb");
if(pf != 0){
fread(pData, size, 1, pf);
fclose(pf);
return 1;
}
return 0;
}
texture_2d::texture_2d(GLvoid* pImg, TInt32 w, TInt32 h, GLint format, TInt32 texturename,GLenum texturetype)
{
mpPixel = pImg;
genTexture(w, h, format, texturename, texturetype);
// checkGlError("glBindTexture");
glTexImage2D(GL_TEXTURE_2D, 0, format, w, h, 0, format, texturetype, pImg);
glBindTexture(GL_TEXTURE_2D, 0);
}
texture_2d::texture_2d():mWidth(0),mHeight(0),mTexturename(0),mColorFormat(0),mTextureId(0){
}
texture_2d::~texture_2d()
{
glDeleteTextures(1, &mTextureId);
}
void texture_2d::genTexture(TInt32 w, TInt32 h, GLint format, TInt32 texturename,GLenum texturetype){
mWidth = w;
mHeight = h;
mTexturename = texturename;
mColorFormat = format;
glGenTextures(1, &mTextureId);
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
// This is necessary for non-power-of-two textures
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
void texture_2d::subImage(GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels){
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexSubImage2D (GL_TEXTURE_2D, 0, xoffset, yoffset, width, height, format, type, pixels);
glBindTexture(GL_TEXTURE_2D, 0);
}
TInt32 texture_2d::getWidth(){
return mWidth;
}
TInt32 texture_2d::getHeight(){
return mHeight;
}
TInt32 texture_2d::getColorFormart(){
return mColorFormat;
}
TInt32 texture_2d::getTexturename(){
return mTexturename;
}
GLuint texture_2d::getTextureId(){
return mTextureId;
}
| true |
3ac6f2fe70aa5864c0bc2d580ec6d53f57abb65e | C++ | Akzwar/ArenstorfModel | /Matrix.cpp | UTF-8 | 7,927 | 3.21875 | 3 | [] | no_license | #include <Matrix.h>
#include <stdarg.h>
#include <QDebug>
TMatrix::TMatrix(int Width, int Height, double *n)//Параметр n- указатель
{ //на одномерный динамический массив
data= new double*[Width]; //Из него созается двумерный массив,
for(int i=0;i<Width;i++) //который заполняется по столбцам, т.е.:
{ //|n[1] n[4] n[7]| |data[1][1] data[2][1] data[3][1]|
data[i]= new double[Height]; //|n[2] n[5] n[8]|=|data[1][2] data[2][2] data[3][2]|
for(int j=0;j<Height;j++) //|n[3] n[6] n[9]| |data[1][3] data[2][3] data[3][3]|
{
data[i][j]=n[i*Height+j];
}
}
this->Height=Height;
this->Width=Width;
}
TMatrix::TMatrix(int Width, int Height)
{
data= new double*[Width];
for(int i=0;i<Width;i++)
{
data[i]= new double[Height];
for(int j=0;j<Height;j++)
{
data[i][j]=0;
}
}
this->Height=Height;
this->Width=Width;
}
TMatrix::~TMatrix()
{
for(int i=0;i<=Width-1;i++)
delete data[i];
}
int TMatrix::getHeight()const
{
return this->Height;
}
int TMatrix::getWidth()const
{
return this->Width;
}
void TMatrix::setElement(int Width, int Height, double Value)
{
this->data[Width][Height]=Value;
}
double TMatrix::getElement(int Width, int Height)
{
return data[Width][Height];
}
void TMatrix::addColumn(TVect *Vect)
{
double **olddata=data;
data= new double*[this->Width+1];
for(int i=0;i<this->Width+1;i++)
{
data[i]= new double[this->Height];
for(int j=0;j<this->Height;j++)
{
if(i!=this->Width)
data[i][j]=olddata[i][j];
else
data[i][j]=Vect->getElement(j);
}
}
this->Width++;
}
void TMatrix::addRow(TVect *Vect)
{
double **olddata=data;
data= new double*[this->Width];
for(int i=0;i<this->Width;i++)
{
data[i]= new double[this->Height+1];
for(int j=0;j<this->Height+1;j++)
{
if(i!=Height)
data[i][j]=olddata[i][j];
else
data[i][j]=Vect->getElement(i);
}
}
this->Height++;
}
TVect* TMatrix::getColumn(int Column)
{
TVect* ResultVect=new TVect(this->getHeight());
for(int i=0;i<this->getHeight();i++)
ResultVect->setElement(i,this->getElement(Column,i));
return ResultVect;
}
TVect* TMatrix::getRow(int Row)
{
TVect* ResultVect=new TVect(this->getWidth());
for(int i=0;i<this->getWidth();i++)
ResultVect->setElement(i,this->getElement(i,Row));
return ResultVect;
}
void TMatrix::setColumn(int Column, TVect *Vect)
{
for(int i=0;i<this->getHeight();i++)
this->setElement(Column, i, Vect->getElement(i));
}
void TMatrix::setRow(int Row, TVect *Vect)
{
for(int i=0;i<this->getWidth();i++)
this->setElement(i, Row, Vect->getElement(i));
}
void TMatrix::ColReverse(int a, int b)
{
TVect* TempVect=this->getColumn(a);
this->setColumn(a,this->getColumn(b));
this->setColumn(b,TempVect);
}
void TMatrix::RowReverse(int a, int b)
{
TVect* TempVect=this->getRow(a);
this->setRow(a,this->getRow(b));
this->setRow(b,TempVect);
}
void TMatrix::RemoveColumn(int Column)
{
double **olddata=data;
data= new double*[this->Width-1];
for(int i=0;i<Column;i++)
{
data[i]= new double[this->Height];
for(int j=0;j<this->Height;j++)
{
data[i][j]=olddata[i][j];
}
}
for(int i=Column+1;i<this->getWidth();i++)
{
data[i-1]= new double[this->Height];
for(int j=0;j<this->Height;j++)
{
data[i-1][j]=olddata[i][j];
}
}
this->Width--;
}
void TMatrix::RemoveRow(int Row)
{
double **olddata=data;
data= new double*[this->Width];
for(int i=0;i<this->Width;i++)
{
data[i]= new double[this->Height-1];
for(int j=0;j<Row;j++)
{
data[i][j]=olddata[i][j];
}
for(int j=Row+1;j<this->getHeight();j++)
{
data[i][j-1]=olddata[i][j];
}
}
this->Height--;
}
TMatrix* TMatrix::Inverse()
{
bool Simmetr=false;
for(int i=0;i<this->getHeight();i++)
for(int j=0;j<this->getHeight();j++)
{
if(this->data[i][j]!=this->data[j][i])
Simmetr=false;
}
TMatrix* ResultMatr;
ResultMatr=new TMatrix(this->getWidth(),this->getHeight());
// if(Simmetr=false)
//{
TVect* CurrColumn=NULL;
ResultMatr->data=this->data;
double *n=new double[this->Width];
for(int i=0; i<this->Width; i++)
{
for(int j=0; j<this->Height; j++)
if(i==j)
n[j]=1;
else
n[j]=0;
ResultMatr->addColumn(new TVect(this->Height,n));
}
for(int i=0; i<ResultMatr->getHeight();i++)
{
fprintf(stderr, "\n");
for(int j=0;j<ResultMatr->getWidth();j++)
fprintf(stderr,"% 6.2f ",ResultMatr->getElement(j,i));
}
fprintf(stderr, "\n");
//////////Получение верхней треугольной матрицы
for(int k=0;k<this->getHeight();k++)
{
int i=0;
int j=k;
bool b=false;
while(i<this->getWidth() && b==false)
{
while(b==false && j<this->getHeight())
{
if(ResultMatr->data[i][j]!=0)
{
CurrColumn=ResultMatr->getColumn(i);
b=true;
}
j++;
}
i++;
j=k;
}
if(CurrColumn->getElement(k)==0)
{
for(int i=1;i<this->getWidth();i++)
if(CurrColumn->getElement(i)!=0)
{
ResultMatr->RowReverse(k,i);
CurrColumn=ResultMatr->getRow(k);
break;
}
}
ResultMatr->setRow(k,*(ResultMatr->getRow(k))*(1/CurrColumn->getElement(k)));
for(int i=k+1;i<this->getHeight();i++)
ResultMatr->setRow(i,
*(ResultMatr->getRow(i))-*(*(ResultMatr->getRow(k))*ResultMatr->getRow(i)->getElement(k)));
for(int i=0; i<ResultMatr->getHeight();i++)
{
fprintf(stderr, "\n");
for(int j=0;j<ResultMatr->getWidth();j++)
fprintf(stderr,"% 6.2f ",ResultMatr->getElement(j,i));
}
fprintf(stderr, "\n");
}
for(int k=2;k<=this->getHeight();k++)
{
for(int i=this->getHeight()-k;i>=0;i--)
ResultMatr->setRow(i,
*(ResultMatr->getRow(i))-*(*(ResultMatr->getRow(this->getHeight()-k+1))*ResultMatr->getRow(i)->getElement(this->getWidth()-k+1)));
}
for(int i=0; i<ResultMatr->getHeight();i++)
{
fprintf(stderr, "\n");
for(int j=0;j<ResultMatr->getWidth();j++)
fprintf(stderr,"% 6.2f ",ResultMatr->getElement(j,i));
}
fprintf(stderr, "\n");
for(int i=0;i<this->Height;i++)
ResultMatr->RemoveColumn(0);
// }
// else
// {
// double buff;
// for(int i=0;i<this->getHeight();i++)
// {
// for(int j=0;j<i;j++)
// {
// buff=this->data[i][j];
// for(int k=0;k<j;k++)
// }
// }
// }
return ResultMatr;
}
| true |
729c001fb383c4812ee9bac453a1ee32baed3b0b | C++ | delor34n/maximization_function-genetic_algorithm | /ga_script.cpp | UTF-8 | 3,719 | 3.09375 | 3 | [] | no_license | /*
* File: ga_script.cpp
* Author: macbook
*
* Created on 4 de julio de 2016, 23:49
*/
#include <iostream>
#include <cstdlib>
#include <bitset>
#include <time.h>
//Tamaño de la poblacion
#define P_LENGTH 5
//Largo del array de cromosomas
#define C_LENGTH 5
//Número máximo de soluciones a encontrar
#define C_MAX 31
/*
* Estructura para cada sujeto de la poblacion
*/
typedef struct {
int sujeto_id;
char cromosomas[C_LENGTH];
unsigned int x;
unsigned int f_x;
}EstructuraPoblacion;
//Función que genera la población inicial
void ini_poblacion(EstructuraPoblacion *poblacion);
//Función para mostrar la población generada
void muestra_poblacion(EstructuraPoblacion *poblacion);
//Función para realizar torneo de selección
void torneo_seleccion(EstructuraPoblacion *poblacion);
//Función que genera los rivales que tendrá cada sujeto
void *genera_rivales(int * rivales);
//Función para dejar con flag -1 al sujeto que corresponde eliminar
void borrar_sujeto(EstructuraPoblacion *sujeto);
//Función para generar los cromosomas que representan una solución (individuo)
void genera_cromosomas(unsigned int x, char *cromosomas);
//Función para determinar el valor de X
unsigned int f_x(unsigned int x);
//Función para generar un número aleatorio
unsigned int ranged_rand(int min, int max);
//Funcion main
int main(int argc, char** argv) {
srand(time(NULL));
EstructuraPoblacion poblacion[P_LENGTH];
ini_poblacion(poblacion);
std::cout << "ANTES DE LA SELECCION" << std::endl;
muestra_poblacion(poblacion);
torneo_seleccion(poblacion);
std::cout << "DESPUES DE LA SELECCION" << std::endl;
muestra_poblacion(poblacion);
return 0;
}
void muestra_poblacion(EstructuraPoblacion *poblacion){
for(int i = 0; i < P_LENGTH; i++){
std::cout << "SUJETO ID >> " << poblacion[i].sujeto_id << std::endl;
std::cout << "X >> " << poblacion[i].x << std::endl;
std::cout << "F(X) >> " << poblacion[i].f_x << std::endl;
std::cout << "CROMOSOMAS >> " << poblacion[i].cromosomas << std::endl;
std::cout << std::endl;
}
std::cout << std::endl;
}
void ini_poblacion(EstructuraPoblacion *poblacion){
for(int i = 0; i < P_LENGTH; i++){
poblacion[i].sujeto_id = i + 1;
poblacion[i].x = ranged_rand(1, C_MAX);
poblacion[i].f_x = f_x(poblacion[i].x);
genera_cromosomas(poblacion[i].x, poblacion[i].cromosomas);
}
}
void torneo_seleccion(EstructuraPoblacion *poblacion){
EstructuraPoblacion seleccion[P_LENGTH];
int * rivales = new (std::nothrow) int[P_LENGTH];
genera_rivales(rivales);
for(int i = 0; i < P_LENGTH; i++){
if(poblacion[i].sujeto_id != -1 && poblacion[rivales[i]].sujeto_id != -1){
if(poblacion[i].f_x > poblacion[rivales[i]].f_x){
seleccion[i] = poblacion[i];
seleccion[i+1] = poblacion[i];
borrar_sujeto(&poblacion[rivales[i]]);
} else {
seleccion[i] = poblacion[rivales[i]];
seleccion[i+1] = poblacion[rivales[i]];
borrar_sujeto(&poblacion[i]);
}
}
}
poblacion = seleccion;
}
void borrar_sujeto(EstructuraPoblacion *sujeto){ sujeto->sujeto_id = -1; }
void *genera_rivales(int * rivales){
for(unsigned int i = 0; i < P_LENGTH; i++){
}
}
void genera_cromosomas(unsigned int x, char *cromosomas){
strlcpy(cromosomas, std::bitset<C_LENGTH>(x).to_string().c_str(), sizeof(cromosomas));
}
unsigned int f_x(unsigned int x){
return x * x;
}
unsigned int ranged_rand(int min, int max){
return min + ((int)(max - min) * (rand() / (RAND_MAX + 1.0)));
} | true |
c0b08c6b89ac94659adba2c87627d1259a579aa1 | C++ | maxkhain/AutonomouseVehicle | /Data_structure/CurrentStatus.h | UTF-8 | 562 | 2.828125 | 3 | [] | no_license | #pragma once
#ifndef _CURRENTSTATUS_H /* Guard against multiple inclusion */
#define _CURRENTSTATUS_H
/**Status
@param <speed>
@param <angle>
*/
class Status {
private:
double angle;
double speed;
public:
Status(double speed, double angle)
{
this->speed = speed;
this->angle = angle;
}
double GetCurrentSpeed();
double GetCurrentAngle();
void SetCurrentStats(double current_speed, double current_angle);
void SetCurrentSpeed(double new_speed);
void SetCurrentAngle(double new_angle);
};
#endif
| true |
ca687d7d1dbda8738a37b31378795d1125f44019 | C++ | kenza-bouzid/PLD-COMP-H4242 | /compiler/code/AST/Expression/ExpressionNeg.cpp | UTF-8 | 599 | 2.71875 | 3 | [
"MIT"
] | permissive | #include "ExpressionNeg.h"
ExpressionNeg::ExpressionNeg(Expression *expr)
{
this->expr = expr;
}
string ExpressionNeg::getIR(BasicBlock **bb)
{
#ifdef DEBUG
cout << "getIR ExpressionNeg starting" << endl;
cout << "Current BasicBlock is : " << *bb << " | addressed at: " << bb << endl;
#endif
string varTempDest = expr->getIR(bb);
IRInstr *instr = new IRInstrNot((*bb),varTempDest);
(*bb)->add_IRInstr(instr);
return varTempDest;
}
Expression *ExpressionNeg::getExpression()
{
return expr;
}
ExpressionNeg::~ExpressionNeg()
{
delete (expr);
} | true |
ed4ad5eac4417078a8945e2faea6b740090ab97c | C++ | jasonblog/note | /c++/code/mybooksources/Chapter01/codes/test_shared_ptr_use_count.cpp | GB18030 | 974 | 3.390625 | 3 | [] | no_license | // test_shared_ptr.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
#include <memory>
class A
{
public:
A()
{
std::cout << "A constructor" << std::endl;
}
~A()
{
std::cout << "A destructor" << std::endl;
}
};
int main()
{
{
//ʼʽ1
std::shared_ptr<A> sp1(new A());
std::cout << "use count: " << sp1.use_count() << std::endl;
//ʼʽ2
std::shared_ptr<A> sp2(sp1);
std::cout << "use count: " << sp1.use_count() << std::endl;
sp2.reset();
std::cout << "use count: " << sp1.use_count() << std::endl;
{
std::shared_ptr<A> sp3 = sp1;
std::cout << "use count: " << sp1.use_count() << std::endl;
}
std::cout << "use count: " << sp1.use_count() << std::endl;
}
return 0;
}
| true |
c9a8099c8380b094c962a1fe27bdab85f90eb410 | C++ | noahklein00/cs5201_hw5 | /kalman.h | UTF-8 | 3,993 | 3.359375 | 3 | [] | no_license | /*! \file
*
* Definitions for the kalman filter derived class. \n
* Programmer: Noah Klein \n
* Class: CS5201 \n
* Assignment: Homework 5 \n
*/
#ifndef KALMAN_H
#define KALMAN_H
#include "filter.h"
#include "nTrix.h"
//! kalman class.
/*!
* This class is a derived filter class that acts as a kalman filter to filter
* a noisy signal from a state given a linear model.
*/
template <typename T>
class kalman: public filter<T>
{
typedef std::initializer_list<std::initializer_list<T>> data;
private:
nTrix<T> m_A; /*!< A nTrix object that stores the information for the
* state transition matrix.
*/
nTrix<T> m_B; /*!< A nTrix object that stores the information for the
* input transition matrix.
*/
nVect<T> m_state; /*!< A nVect object that stores the current state of the
* system.
*/
nTrix<T> m_error; /*!< A nTrix object that stores the information for the
* covariance matrix for the current state.
*/
nTrix<T> m_process_error; /*!< A nTrix object that stores the information
* for the process noise of the system.
*/
nTrix<T> m_measurement_error; /*!< A nTrix object that stores the
* information for the measurement uncertainty
* matrix.
*/
nTrix<T> m_identity; /*!< A nTrix object that stores information for the
* identity matrix.
*/
nTrix<T> m_K; /*!< A nTrix object that stores information for the Kalman
* gain.
*/
public:
/*! \brief Constructor
*
* Description: Parameterized constructor for the kalman derived filter
* class that allows the user to specify all constants and initial member
* variables for the calculations.
* \param A is the constant state transition matrix.
* \param B is the constant input transition matrix.
* \param i_state is the initial state of the modeled system.
* \param P is the initial state of the covariance matrix.
* \param Q is the constant process error matrix.
* \param R is the constant measurement uncertainty matrix.
* \param I is the constant identity matrix in the correct dimensions of the
* system.
* \post A kalman filter is initialized with all the values it needs to
* operate.
* \throw Throws a std::invalid_argument object if any of the defined
* matrices would not hold up for a () operator calculation.
*/
kalman(const data& A, const data& B, const nVect<T>& i_state, const data& P,
const data& Q, const data& R, const data& I);
/*! \brief () operator
*
* Description: () operator overload for the kalman derived filer that steps
* the simulation forward by one time step and calculates the neccessary
* updates for different variables.
* \param measured is the current measured state of the system.
* \param signal is the current PID signal that was sent to the lander
* model.
* \return Returns a nVect<float> that represents the filtered system.
* \pre *, +, -, and = operators must be defined for type T.
* \post The filtered state is returned and the kalman filter is updated
* by one time step.
*/
nVect<float> operator()(const nVect<T>& measured, const float signal);
/*! \brief () operator
*
* Description: () operator overload that matches the virtual function
* defined in the filter class. This does not do anything.
* \param measured is the current state of the system.
* \return Returns a nVect<float> that is the same as the input.
* \post Does nothing.
*/
virtual nVect<float> operator()(nVect<T>& measured);
};
#include "kalman.hpp"
#endif
| true |
e3309f06c5f4fe6894805edd13abc5e31ccfd1b2 | C++ | tekfyl/DataStructures | /BST/main.cc | UTF-8 | 4,756 | 3.53125 | 4 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node* left;
node* right;
};
node* insert(node *root, int value);
void find_bst(node *bst, int e);
void levelOrder(node *root);
int height(node *root);
void inOrder(node *root);
void postOrder(node *root);
void visit(node *root);
void preOrder(node *root);
void topViewLeft(node *root);
void topViewRight(node *root);
void topView(node *root);
void decode_huff(node *root, string s);
int main(){
std::ios_base::sync_with_stdio(false);
int choice;
node *root = new node;
root = NULL;
while(1){
cout<<"-----------------"<<endl;
cout<<"Operations on BST"<<endl;
cout<<"-----------------"<<endl;
cout<<"1.Insert Element "<<endl;
cout << "2.Find Element "<<endl;
//cout<<"2.Delete Element "<<endl;
cout<<"3.Inorder Traversal"<<endl;
cout<<"4.Preorder Traversal"<<endl;
cout<<"5.Postorder Traversal"<<endl;
cout<<"6.Level Order"<<endl;
cout<<"7. Top View"<<endl;
cout<<"8.Height of BST"<<endl;
cout<<"15.Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
cout << "\n\n\n\n";
switch(choice){
case 1:
int value; cin >> value;
root = insert(root, value);
break;
case 2:
int e; cin >> e;
find_bst(root,e);
break;
case 3:
inOrder(root);
break;
case 4:
preOrder(root);
break;
case 5:
postOrder(root);
break;
case 6:
levelOrder(root);
break;
case 7:
topView(root);
break;
case 8:
cout << height(root) << endl;
break;
case 15:
return 0;
break;
default:
cout << "Number not in option" << endl;
}
cout << endl << "Want to Continue? (y/n)" << endl;
char c; cin >> c;
c == 'y' ? 1 : cout << "Quit then!" << endl;
}
return 0;
}
node* insert(node *root, int value) {
if(root == NULL){
node *temp = new node;
temp->data = value;
temp->left = temp->right = NULL;
root = temp;
}
else if(root->data > value){
root->left = insert(root->left, value);
}
else {
root->right = insert(root->right, value);
}
return root;
}
void find_bst(node *bst, int e){
if (bst == NULL) cout << "NOT FOUND\n";
else if (bst->data == e) cout << "Found\n";
else if (bst->data<e) return find_bst(bst->right, e);
else return find_bst(bst->left, e);
}
void levelOrder(node *root) {
queue<node*> q;
node *temp = root;
q.push(temp);
while(!q.empty()){
if(temp->left != NULL){
q.push(temp->left);
}
if(temp->right != NULL){
q.push(temp->right);
}
visit(temp);
q.pop();
temp = q.front();
}
}
int height(node *root) {
return (root == NULL ? -1 : max(height(root->left), height(root->right)) +1);
}
void inOrder(node *root) {
if(root == NULL){
return;
}
inOrder(root->left);
visit(root);
inOrder(root->right);
}
void postOrder(node *root) {
if(root == NULL){
return;
}
postOrder(root->left);
postOrder(root->right);
visit(root);
}
void visit(struct node *root){
cout << root->data << " ";
}
void preOrder(node *root) {
if (root == NULL){
return;
}
visit(root);
preOrder(root->left);
preOrder(root->right);
}
void topViewLeft(node *root){
if(root == NULL){
return;
}
topViewLeft(root->left);
visit(root);
}
void topViewRight(struct node *root){
if(root == NULL){
return;
}
visit(root);
topViewRight(root->right);
}
void topView(node * root) {
if(root == NULL){
return;
}
topViewLeft(root->left);
visit(root);
topViewRight(root->right);
}
node* lca_bst(node *root, int v1,int v2)
{
if(root->data > v1 && root->data > v2) return lca_bst(root->left, v1, v2);
else if(root->data < v1 && root->data < v2) return lca_bst(root->right, v1, v2);
return root;
}
void decode_huff(node * root,string s)
{
node *t = root;
for(auto c:s){
t = (c == '0'? t->left : t->right);
if(t->data){
cout << t->data;
t = root;
}
}
}
| true |
e7ae972178f85a6f8a26763cb0d354a4e5e23918 | C++ | shulincome/Data_Structres-with-c- | /ch02/CH02_01.cpp | GB18030 | 626 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int Score[5]={ 87,66,90,65,70 };
//Score[5], 5ɼ
int count, Total_Score=0;
for (count=0; count < 5; count++) // ִ for ѭȡѧɼ
{
cout<<""<<count+1<<"λѧķ:"<<Score[count]<<endl;
Total_Score+=Score[count]; //жȡܷ
}
cout<<"-------------------------"<<endl;
cout<<"5λѧܷ:"<<Total_Score<<endl;
//ɼܷ
system("pause");
return 0;
}
| true |
73c92ade77a451e2f2ad74cbce8543cb35ef3b11 | C++ | xMonny/Data-Structures-And-Algorithms | /Homeworks/File_Systems/main.cpp | UTF-8 | 2,925 | 3.84375 | 4 | [] | no_license | #include <iostream>
#include <map>
#include <vector>
using namespace std;
struct Directory
{
Directory* parent;
string word;
map<string, Directory*> table;
Directory()
{
this->word = "/";
this->parent = nullptr;
}
};
class Path
{
Directory* root = new Directory();
Directory* current = root;
public:
void make_directory(string directory)
{
map<string, Directory*>::iterator it = current->table.find(directory);
if (it != current->table.end())
{
cout << "Directory already exists" << endl;
return;
}
Directory* new_directory = new Directory();
new_directory->parent = current;
new_directory->word = directory;
current->table.insert(make_pair(directory, new_directory));
}
void change_directory(string directory)
{
if (directory == "..")
{
if (current == root)
{
cout << "No such directory" << endl;
return;
}
current = current->parent;
return;
}
map<string, Directory*>::iterator it = current->table.find(directory);
if (it == current->table.end())
{
cout << "No such directory" << endl;
return;
}
current = it->second;
}
void print_whole_directory()
{
Directory* remember = current;
if (remember != root)
{
vector<string> s;
while (remember != root)
{
s.push_back(remember->word);
remember = remember->parent;
}
for (int i = s.size()-1; i >= 0; i--)
{
cout << "/" << s[i];
}
}
cout << "/" << endl;
}
void print(map<string, Directory*> t, Directory* remember)
{
map<string, Directory*>::iterator it;
for (it = t.begin(); it != t.end(); it++)
{
if (it->second->parent != remember)
{
break;
}
cout << it->first << " ";
print(it->second->table, remember);
}
}
void print()
{
print(current->table, current);
cout << endl;
}
};
int main()
{
int N;
cin >> N;
string expression;
string directory;
Path path;
for (int i = 0; i < N; i++)
{
cin >> expression;
if (expression == "mkdir")
{
cin >> directory;
path.make_directory(directory);
}
if (expression == "cd")
{
cin >> directory;
path.change_directory(directory);
}
if (expression == "ls")
{
path.print();
}
if (expression == "pwd")
{
path.print_whole_directory();
}
}
return 0;
}
| true |
1827225a20bc4a4feb4988115ba1b262eb0b74ea | C++ | dlgkrwns213/algorithm | /수학10 (baekjoon11050 - 이항 계수1) .cpp | UTF-8 | 305 | 3.453125 | 3 | [] | no_license | //기본적인 조합값 구하는 문제
#include <iostream>
using namespace std;
int fac(int big, int small);
int main()
{
int n, k;
cin >> n >> k;
cout << fac(n, n-k+1)/fac(k, 1);
return 0;
}
int fac(int big, int small)
{
int sum = 1;
for(int i=small;i<=big;i++)
sum *= i;
return sum;
}
| true |
b26f836209d9a8a04c569cf5a5d5e35c184ff106 | C++ | overaction/algorithm_problem_solution | /8.16 두니발 박사의 탈옥/8.16 두니발 박사의 탈옥/main.cpp | UHC | 2,022 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <algorithm>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;
int C,N,D,P,T,Q;
int village[51][51], counts[51];
// cache[ ȣ][¥]
double cache[51][101];
/* Ž
double allSearch(vector < int > &path) {
// ¥ ߴٸ
if(path.size() == D+1) {
//
if(path.back() == Q) {
double result = 1.0;
for(int i=0; i+1<path.size(); i++) {
int next = counts[path[i]];
result /= next;
}
return result;
}
else return 0;
}
double ret = 0;
for(int i=0; i<N; i++) {
// Ǿִٸ
if(village[path.back()][i]) {
path.push_back(i);
ret += allSearch(path);
path.pop_back();
}
}
return ret;
}
*/
// ġ ְ ش ¥ Ȯ ȯ
double searching(int now, int day) {
// :
if(day == D) {
if(now == Q) return 1;
else return 0;
}
double &ret = cache[now][day];
if(ret != -1.0) return ret;
ret = 0.0;
for(int i=0; i<N; i++) {
if(village[now][i])
ret += (searching(i,day+1)/counts[now]);
}
return ret;
}
int main()
{
scanf("%d",&C);
for(int c=0; c<C; c++) {
scanf("%d %d %d",&N,&D,&P);
for(int i=0; i<N; i++) {
for(int j=0; j<N; j++) {
scanf("%d",&village[i][j]);
if(village[i][j]) counts[i]++;
}
}
scanf("%d",&T);
for(int i=0; i<T; i++) {
for(int i=0; i<51; i++)
for(int j=0; j<101; j++)
cache[i][j] = -1.0;
scanf("%d",&Q);
printf("%lf ",searching(P,0));
}
printf("\n");
memset(counts,0,sizeof(counts));
}
}
| true |
addb790f394e12c2e25a8c96118fcb9ea7120684 | C++ | peterxie/482p2 | /old_tests/test_unlock_unowned_mutex.cpp | UTF-8 | 623 | 3.1875 | 3 | [] | no_license | #include "thread.h"
#include <iostream>
#include <exception>
using namespace std;
// This tests behavior of a thread unlocking a mutex
// owned by no thread
// Expected output:
// terminate called after throwing an instance of 'std::runtime_error'
// what(): Thread cannot unlock mutex it does not own.
// Aborted
mutex m1;
void parent(void *a)
{
try{
char *id = (char *) a;
m1.unlock();
cout << id << " finishing" << endl;
}
catch (runtime_error &e) {
cout << e.what() << endl;
}
}
int main()
{
cpu::boot(1, (thread_startfunc_t) parent, (void *) "parent thread", false, false, 0);
}
| true |
42e9635627d670f0b4c6a2a1748ad5e5f5a55510 | C++ | weimingtom/tanuki-mo-issyo | /プログラム/Ngllib/src/OpenGL/RendererGL.cpp | SHIFT_JIS | 15,077 | 2.578125 | 3 | [] | no_license | /*******************************************************************************/
/**
* @file RendererGL.cpp.
*
* @brief OpenGL _[NX\[Xt@C.
*
* @date 2008/07/20.
*
* @version 1.00.
*
* @author Kentarou Nishimura.
*/
/******************************************************************************/
#include "Ngl/OpenGL/RendererGL.h"
#include "Ngl/OpenGL/BufferGL.h"
#include "Ngl/OpenGL/VertexDeclarationGL.h"
#include "Ngl/OpenGL/EffectCgGL.h"
#include "Ngl/OpenGL/Texture1DGL.h"
#include "Ngl/OpenGL/Texture2DGL.h"
#include "Ngl/OpenGL/Texture3DGL.h"
#include <cassert>
using namespace Ngl;
using namespace Ngl::OpenGL;
/*=========================================================================*/
/**
* @brief RXgN^
*
* @param[in] Ȃ.
*/
RendererGL::RendererGL():
vertexDeclaration_( 0 ),
indexBuffer_( 0 ),
indexFormat_( toIndexFormat( INDEX_TYPE_USHORT ) ),
indexOffset_( 0 ),
primitiveMode_( toPrimitiveMode( PRIMITIVE_TYPE_TRIANGLE_LIST ) ),
framebufferObject_( 0 )
{
// t[obt@IuWFNg̍쐬
glGenFramebuffersEXT( 1, &framebufferObject_ );
//
initialize();
}
/*=========================================================================*/
/**
* @brief fXgN^
*
* @param[in] Ȃ.
*/
RendererGL::~RendererGL()
{
// Ԃ
clearState();
// t[obt@IuWFNg̍폜
glDeleteFramebuffersEXT( 1, &framebufferObject_ );
}
/*=========================================================================*/
/**
* @brief
*
* @param[in] Ȃ.
* @return Ȃ.
*/
void RendererGL::initialize()
{
// ʃJO̐ݒ
glEnable( GL_CULL_FACE );
glCullFace( GL_BACK );
glFrontFace( GL_CCW );
// fvXobt@1.0ŃNA
glEnable( GL_DEPTH_TEST );
glDepthFunc( GL_LESS );
// At@eXg̐ݒ
glEnable( GL_ALPHA_TEST );
glAlphaFunc( GL_GREATER, 0.0f );
// uhXe[g̐ݒ
glEnable( GL_BLEND );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
// p[XyNeBus
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
}
/*=========================================================================*/
/**
* @brief r[|[g̐ݒ
*
* @param[in] desc r[|[gLqq.
* @return Ȃ.
*/
void RendererGL::setViewport( const ViewportDesc& desc )
{
glViewport( desc.x, desc.y, desc.width, desc.height );
viewport_ = desc;
}
/*=========================================================================*/
/**
* @brief r[|[g̎擾
*
* @param[in] Ȃ.
* @return r[|[gLqq.
*/
const ViewportDesc& RendererGL::getViewport() const
{
return viewport_;
}
/*=========================================================================*/
/**
* @brief J[obt@
*
* @param[in] r NAJ[Ԑ.
* @param[in] g NAJ[ΐ.
* @param[in] b NAJ[.
* @param[in] a NAJ[At@.
* @return Ȃ.
*/
void RendererGL::clearColorBuffer( float r, float g, float b, float a )
{
// NAJ[ݒ肷
glClearColor( r, g, b, a );
// J[obt@̏
glClear( GL_COLOR_BUFFER_BIT );
}
/*=========================================================================*/
/**
* @brief fvXXeVobt@
*
* @param[in] depth fvXobt@邩.
* @param[in] stencil XeVobt@邩.
* @return Ȃ.
*/
void RendererGL::clearDepthStencilBuffer( bool depth, bool stencil )
{
GLbitfield mask = 0;
if( depth ){
mask |= GL_DEPTH_BUFFER_BIT;
}
if( stencil ){
mask |= GL_STENCIL_BUFFER_BIT;
}
glClear( mask );
}
/*=========================================================================*/
/**
* @brief obt@쐬
*
* @param[in] desc obt@Lqq.
* @param[in] data obt@f[^.
* @return 쐬obt@C^[tF[X̃|C^.
*/
IBuffer* RendererGL::createBuffer( const BufferDesc& desc, const void* data )
{
return new BufferGL( desc, data );
}
/*=========================================================================*/
/**
* @brief eNX`쐬
*
* @param[in] desc eNX`Lqq.
* @param[in] data eNX`f[^.
* @return 쐬eNX`C^[tF[X̃|C^.
*/
ITexture* RendererGL::createTexture( const TextureDesc& desc, const void* data )
{
TextureGL* texture = 0;
switch( desc.type ){
case TEXTURE_TYPE_1D:
texture = new Texture1DGL( desc, data );
break;
case TEXTURE_TYPE_2D:
texture = new Texture2DGL( desc, data );
break;
case TEXTURE_TYPE_3D:
texture = new Texture3DGL( desc, data );
break;
case TEXTURE_TYPE_CUBE:
texture = new Texture2DGL( desc, data );
}
return texture;
}
/*=========================================================================*/
/**
* @brief _錾쐬
*
* @param[in] desc _錾Lqq̔z.
* @param[in] numDesc _錾Lqqz̗vf.
* @param[in] inputSignature ̓VOl`Lqq.
* @return 쐬_錾C^[tF[X̃|C^.
*/
IVertexDeclaration* RendererGL::createVertexDeclaration( const VertexDeclarationDesc desc[], unsigned int numDesc, const InputSignatureDesc& inputSignature )
{
(void)inputSignature; // OpenGLł͎gpȂ
return new VertexDeclarationGL( desc, numDesc );
}
/*=========================================================================*/
/**
* @brief GtFNg̍쐬
*
* @param[in] fileName GtFNgt@C.
* @return 쐬GtFNgC^[tF[X̃|C^.
*/
IEffect* RendererGL::createEffect( const char* fileName )
{
return new EffectCgGL( fileName );
}
/*=========================================================================*/
/**
* @brief _錾f[^ݒ
*
* @param[in] layout ݒ肷钸_錾f[^̃|C^.
* @return Ȃ.
*/
void RendererGL::setVertexDeclaration( IVertexDeclaration* layout )
{
vertexDeclaration_ = static_cast< VertexDeclarationGL* >( layout );
}
/*=========================================================================*/
/**
* @brief obt@ݒ
*
* @param[in] stream _Xg[Lqqz.
* @param[in] numStream _Xg[Lqqz̗vf.
* @param[in] offset ItZbgl.
* @return Ȃ.
*/
void RendererGL::setVertexBuffer( const VertexStreamDesc stream[], unsigned int numStream, unsigned int offset )
{
for( unsigned int i=0; i<numStream; ++i ){
vertexStream_[i+offset] = stream[i];
}
}
/*=========================================================================*/
/**
* @brief CfbNXobt@ݒ
*
* @param[in] buffer CfbNXobt@̃|C^.
* @param[in] type _^Cv.
* @param[in] offset ItZbgl.
* @return Ȃ.
*/
void RendererGL::setIndexBuffer( IBuffer* buffer, IndexType type, unsigned int offset )
{
indexBuffer_ = static_cast< BufferGL* >( buffer );
indexFormat_ = toIndexFormat( type );
indexOffset_ = offset;
}
/*=========================================================================*/
/**
* @brief ~bv}bv̍쐬
*
* @param[in] texture ~bv}bv쐬eNX`̃|C^.
* @return Ȃ.
*/
void RendererGL::generateMipmap( ITexture* texture )
{
TextureGL* tex = static_cast< TextureGL* >( texture );
tex->generateMipmap();
}
/*=========================================================================*/
/**
* @brief `悷v~eBuݒ
*
* @param[in] primitive v~eBu^Cv.
* @return Ȃ.
*/
void RendererGL::setPrimitive( PrimitiveType primitive )
{
primitiveMode_ = toPrimitiveMode( primitive );
}
/*=========================================================================*/
/**
* @brief _obt@`
*
* @param[in] numVertex `悷钸_.
* @param[in] start Jn_ԍ.
* @return Ȃ.
*/
void RendererGL::draw( unsigned int numVertex, unsigned int start )
{
// _錾ݒ
vertexDeclaration_->setVertexStream( vertexStream_, start );
// _obt@̕`
glDrawArrays( primitiveMode_, 0, numVertex );
// _obt@Zbg
vertexDeclaration_->resetVertexStream();
}
/*=========================================================================*/
/**
* @brief CfbNXobt@gpĕ`悷
*
* @param[in] numIndices CfbNX.
* @param[in] startIndex JnCfbNXԍ.
* @param[in] startVertex Jn_ԍ
* @return Ȃ.
*/
void RendererGL::drawIndexed( unsigned int numIndices, unsigned int startIndex, unsigned int startVertex )
{
// _obt@ݒ肷
vertexDeclaration_->setVertexStream( vertexStream_, startVertex );
// CfbNXobt@oCh
glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, indexBuffer_->buffer() );
GLubyte* base = 0;
glDrawElements(
primitiveMode_,
numIndices,
indexFormat_.type,
&base[ ( indexOffset_ + startIndex ) * indexFormat_.size ]
);
// CfbNXobt@Zbg
glBindBufferARB( GL_ELEMENT_ARRAY_BUFFER_ARB, 0 );
// _obt@Zbg
vertexDeclaration_->resetVertexStream();
}
/*=========================================================================*/
/**
* @brief eNX`_[^[Qbgɐݒ
*
* @param[in] targets ݒ肷eNX`̔z.
* @param[in] numTargets eNX`z̗vf.
* @param[in] depthStencil fvXXeVobt@ƂĎgpeNX`̃|C^.
* @param[in] index JnCfbNXԍ.
* @return Ȃ.
*/
void RendererGL::setRenderTargets( ITexture* targets[], unsigned int numTargets, ITexture* depthStencil, unsigned int index )
{
// _[^[QbgZbg
resetRenderTargets();
// ݒ肳ĂȂꍇ̓Zbĝ
if( targets == 0 && depthStencil == 0 ){
return;
}
// t[obt@IuWFNg̃oCh
glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, framebufferObject_ );
// fvXXeVobt@̐ݒ
TextureGL* depthStencilBuffer = static_cast< TextureGL* >( depthStencil );
if( depthStencilBuffer != 0 ){
// fvXXeVobt@ɃA^b`
depthStencilBuffer->attachDepthStencil();
}
// _[^[Qbg̐ݒ
GLenum drawBuffers[ RENDER_TARGET_MAX ];
for( GLuint i=0; i<numTargets; ++i ){
// eNX`t[obt@IuWFNgɃA^b`
static_cast< TextureGL* >( targets[i] )->attachFramebuffer( i, index );
// `obt@̐ݒ
drawBuffers[i] = GL_COLOR_ATTACHMENT0_EXT + i;
}
// _[^[Qbg݂邩
if( numTargets > 0 ){
// `obt@̐ݒ
glDrawBuffersARB( numTargets, drawBuffers );
}
else{
// `obt@ւ݂̏Ȃ悤ɂ
glDrawBuffer( GL_NONE );
glReadBuffer( GL_NONE );
}
assert( glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ) == GL_FRAMEBUFFER_COMPLETE_EXT );
}
/*=========================================================================*/
/**
* @brief _[^[QbgZbg
*
* @param[in] Ȃ.
* @return Ȃ.
*/
void RendererGL::resetRenderTargets()
{
glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, framebufferObject_ );
// fvXXeVobt@̃Zbg
glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0 );
glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0 );
// _[^[Qbg̃Zbg
GLint maxDrawBuffer;
glGetIntegerv( GL_MAX_DRAW_BUFFERS, &maxDrawBuffer );
for( GLint i=0; i<maxDrawBuffer; ++i ){
glFramebufferTexture2DEXT( GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT+i, GL_TEXTURE_2D, 0, 0 );
}
// `Eǂݍ݃obt@̃Zbg
glDrawBuffer( GL_COLOR_ATTACHMENT0_EXT );
glReadBuffer( GL_COLOR_ATTACHMENT0_EXT );
// t[obt@IuWFNgZbg
glBindFramebufferEXT( GL_FRAMEBUFFER_EXT, 0 );
}
/*=========================================================================*/
/**
* @brief _[tbV
*
* @param[in] Ȃ.
* @return Ȃ.
*/
void RendererGL::flush()
{
glFlush();
}
/*=========================================================================*/
/**
* @brief _[̏ԂNA
*
* @param[in] Ȃ.
* @return Ȃ.
*/
void RendererGL::clearState()
{
resetRenderTargets();
initialize();
}
/*=========================================================================*/
/**
* @brief CfbNX^Cv̕ϊ
*
* @param[in] format ϊCfbNX^CvtO.
* @return ϊ̃CfbNXtH[}bg\.
*/
const RendererGL::IndexFormat& RendererGL::toIndexFormat( IndexType format )
{
static const RendererGL::IndexFormat indexFormats[] = {
{ GL_UNSIGNED_SHORT, sizeof( GLushort ) },
{ GL_UNSIGNED_INT, sizeof( GLuint ) }
};
return indexFormats[ format ];
}
/*=========================================================================*/
/**
* @brief v~eBu^Cv̕ϊ
*
* @param[in] primitive ϊv~eBu^CvtO.
* @return ϊOpenGLv~eButO.
*/
GLenum RendererGL::toPrimitiveMode( PrimitiveType primitive )
{
static const GLenum primitiveModels[] = {
GL_POINTS, // PRIMITIVE_TYPE_POINTLIST = 0
GL_LINES, // PRIMITIVE_TYPE_LINELIST = 1
GL_LINE_STRIP, // PRIMITIVE_TYPE_LINESTRIP = 2
GL_TRIANGLES, // PRIMITIVE_TYPE_TRIGNALE_LIST = 3
GL_TRIANGLE_STRIP // PRIMITIVE_TYPE_TRIANGLE_STRIP = 4
};
return primitiveModels[ primitive ];
}
/*===== EOF ==================================================================*/ | true |
608934035dac1e4487d755b79233b23bf944bc9d | C++ | Easoncer/swordoffer | /sword_c++/UnionFindSet.cpp | UTF-8 | 2,155 | 3.40625 | 3 | [] | no_license | //
// Created by 李先生 on 2018/9/3.
//
#include <iostream>
#include <vector>
#include <map>
using namespace std;
map<char, int> rootdict; //key: root value: 结点值的数目
map<char, char> parent; //定义某个结点的父结点
void Make_Set(vector<vector<char>> relation)
{
for (int i = 0; i< relation.size(); i++)
{
rootdict[relation[i][0]] = 1;
rootdict[relation[i][1]] = 1;
parent[relation[i][0]] = relation[i][0];
parent[relation[i][1]] = relation[i][1];
}
}
//返回根节点
char findroot(char x)
{
map<char, int>::iterator iter;
iter = rootdict.find(x);
// 发现存在对应key值
if (iter != rootdict.end()) {
return parent[x];
} else {
return findroot(parent[x]);
}
}
void combine(char x, char y)
{
char rootx = findroot(x);
char rooty = findroot(y);
int depx = rootdict[rootx];
int depy = rootdict[rooty];
// 按照深度来进行合并
// 如果第一个树的深度比第二个深度大,将x 并到y树上
if (depx >= depy)
{
parent[rooty] = rootx;
rootdict.erase(rooty);
rootdict[rootx] = depx + depy;
} else{
parent[rootx] = rooty;
rootdict.erase(rootx);
rootdict[rooty] = depx + depy;
}
}
void createTree(vector<vector<char>> relation)
{
for(int i =0 ; i < relation.size(); i++)
{
// 判断根节点是不是一样?
if (findroot(relation[i][0]) != findroot(relation[i][1]))
{
combine(relation[i][0], relation[i][1]);
}
}
}
int main()
{
vector<vector<char>> relation = {{'a','b'},{'a','c'},{'a','d'},{'e','f'},{'f','g'}};
Make_Set(relation);
createTree(relation);
// map<char, int>::iterator iter;
////// for( iter = rootdict.begin(); iter != rootdict.end() ; iter ++ )
////// {
////// cout << findroot(iter->first) <<endl;
////// cout << findroot(iter->second) <<endl;
////// }
for(int i =0 ; i < relation.size(); i++)
{
cout << findroot(relation[i][0]) <<endl;
cout << findroot(relation[i][1]) <<endl;
}
return 0;
} | true |
6572090a454599c38457c38fe5091683dd61b41a | C++ | rlannon/SIN-Language | /link/Linker.cpp | UTF-8 | 13,227 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "Linker.h"
void Linker::get_metadata() {
// iterate through the .sinc files to get the file metadata and ensure they are compatible
// if they aren't, throw an exception
// first, we need to get the wordsize and version of the 0th file; this will be our reference
uint8_t wordsize_compare = this->object_files[0]._wordsize;
uint8_t version_compare = this->object_files[0]._sinvm_version;
// then, iterate through our file vector and compare the word size to the 0th file
// if they match, continue; if they don't, throw an error and die
for (std::vector<SinObjectFile>::iterator file_iter = this->object_files.begin(); file_iter != this->object_files.end(); file_iter++) {
if (file_iter->_wordsize != wordsize_compare) {
throw std::runtime_error("**** Word sizes in all object files must match.");
}
if (file_iter->_sinvm_version != version_compare) {
throw std::runtime_error("**** SINVM Version must be the same between all object files.");
}
}
// now that we know everything matches, set the start address and word size to be used by the linker in creating a .sml file
this->_wordsize = wordsize_compare;
// set our memory location information based on the version of the SIN VM
if (version_compare == 1) {
this->_start_offset = _PRG_BOTTOM;
this->_rs_start = _RS_START;
}
else {
throw std::runtime_error("**** Specified SIN VM version is not currently supported by this toolchain");
}
}
// create a .sml file from all of our objects
void Linker::create_sml_file(std::string file_name) {
// first, update all the memory offsets
size_t current_offset = this->_start_offset; // current offset starts at the start address of VM memory
size_t current_rs_address = this->_rs_start; // the next available address for a @rs directive starts at Linker::_rs_start
// iterate over the whole vector
for (std::vector<SinObjectFile>::iterator file_iter = this->object_files.begin(); file_iter != this->object_files.end(); file_iter++) {
// _text_start holds the start address, from which all control flow addresses in the file are offset
file_iter->_text_start = current_offset;
// add this offset to every "value" field in the symbol table where the symbol class is "D", or "C"
// symbols with class "M" will not be updated; the address defined will remain
for (std::list<AssemblerSymbol>::iterator symbol_iter = file_iter->symbol_table.begin(); symbol_iter != file_iter->symbol_table.end(); symbol_iter++) {
// if our symbol is defined
if ((symbol_iter->symbol_class == D) || (symbol_iter->symbol_class == C)) {
// update the value stored in the symbol table to be the current value plus the offset
symbol_iter->value = symbol_iter->value + current_offset;
}
/*
if the symbol table is "C", we also need to add the offsets from both:
a) the size of the .text section
b) the offset from the /end/ of the .text section
*/
if (symbol_iter->symbol_class == C) {
// iterate through the file's constants list to find the constant's data
std::list<std::tuple<std::string, size_t, std::vector<uint8_t>>>::iterator data_iter = file_iter->data_table.begin();
bool found_constant = false;
while (!found_constant && (data_iter != file_iter->data_table.end())) {
if (std::get<0>(*data_iter) == symbol_iter->name) {
found_constant = true;
}
else {
data_iter++;
}
}
if (found_constant) {
// get the total offset
size_t offset_from_text_end = std::get<1>(*data_iter);
// add the total offset to <1>(symbol_iter), which is the offset for the current symbol in the symbol table; this symbol is class "C"
symbol_iter->value += offset_from_text_end;
}
else {
throw std::runtime_error("Could not find the constant specified in the constants table!");
}
}
// if the symbol class is "R", we need to allocate space in memory for it
if (symbol_iter->symbol_class == R) {
// first, make sure "current_rs_address" is not beyond the memory we are allowed to use; it cannot move beyond the heap
if (current_rs_address >= _RS_END) {
throw std::runtime_error("**** Memory Exception: Global variable limit exceeded.");
}
// if we are still within our bounds
else {
// we will change the value of the symbol to the next available memory address based on "current_rs_address"
symbol_iter->value = current_rs_address;
// update current_rs_address; advance by the size of the symbol (usually one word, but not necessarily)
current_rs_address += symbol_iter->width;
}
}
// the "U" class will be updated later, so ignore it here
}
// update current_offset to add the size of the program just added
current_offset += file_iter->program_data.size();
// we then need to update current_offset to add the size of the .data section, as these will get added onto the program sections at the end
size_t data_section_offset = 0;
for (std::list<std::tuple<std::string, size_t, std::vector<uint8_t>>>::iterator data_it = file_iter->data_table.begin(); data_it != file_iter->data_table.end(); data_it++) {
size_t constant_size = std::get<2>(*data_it).size();
data_section_offset += constant_size;
}
current_offset += data_section_offset;
}
// now that our initial offsets and defined label offsets have been adjusted, we can construct the master symbol table
// first, create the vector to hold the table
std::vector<AssemblerSymbol> master_symbol_table;
// iterate through our object files' symbol tables to add to the master table
for (std::vector<SinObjectFile>::iterator file_iter = this->object_files.begin(); file_iter != this->object_files.end(); file_iter++) {
// only add defined references to the table
// find them by iterating through each symbol table and adding the defined symbols to the master table
for (std::list<AssemblerSymbol>::iterator symbol_iter = file_iter->symbol_table.begin(); symbol_iter != file_iter->symbol_table.end(); symbol_iter++) {
if (symbol_iter->symbol_class == D || symbol_iter->symbol_class == C || symbol_iter->symbol_class == R || symbol_iter->symbol_class == M) {
master_symbol_table.push_back(*symbol_iter);
}
else {
continue;
}
}
}
// now, go through each object file and locate any undefined symbol references
for (std::vector<SinObjectFile>::iterator file_iter = this->object_files.begin(); file_iter != this->object_files.end(); file_iter++) {
// look for undefined symbols
for (std::list<AssemblerSymbol>::iterator symbol_iter = file_iter->symbol_table.begin(); symbol_iter != file_iter->symbol_table.end(); symbol_iter++) {
// if it is a constant, the symbol should now have the proper address
// if it's undefined, a constant, or a reserved macro
if (symbol_iter->symbol_class == U || symbol_iter->symbol_class == C || symbol_iter->symbol_class == R) {
// iterate through the master table and find the symbol referenced
std::vector<AssemblerSymbol>::iterator master_table_iter = master_symbol_table.begin();
bool found = false;
while ((master_table_iter != master_symbol_table.end()) && !found) {
// if the symbol names are the same
if (master_table_iter->name == symbol_iter->name) {
// copy over the value from the master table iterator to our local symbol table
symbol_iter->value = master_table_iter->value;
// update our found variable so we can abort
found = true;
}
else {
// increment the master_symbol_table iterator
master_table_iter++;
}
}
// if the symbol was NOT found in the table
if (!found) {
throw std::runtime_error("**** Symbol table error: Could not find '" + symbol_iter->name + "' in symbol table!");
}
}
else {
continue; // skip defined references
}
}
// now, go through each file individually and update all values pointed to in the relocations table
for (std::vector<SinObjectFile>::iterator file_iter = this->object_files.begin(); file_iter != this->object_files.end(); file_iter++) {
// iterate through the relocation table
for (std::list<RelocationSymbol>::iterator relocation_iter = file_iter->relocation_table.begin(); relocation_iter != file_iter->relocation_table.end(); relocation_iter++) {
// if the symbol is "_NONE", we add the file's offset to the value pointed to by the relocator
if (relocation_iter->name == "_NONE") {
// the start address is the value in the relocation iter
size_t value_start_address = relocation_iter->value;
unsigned int data = 0;
size_t wordsize_bytes = (size_t)file_iter->_wordsize / 8;
// the value to write is located at value_start_address
for (size_t i = 0; i < (wordsize_bytes - 1); i++) {
data += file_iter->program_data[value_start_address + i];
data = data << (i * 8);
}
data += file_iter->program_data[value_start_address + (wordsize_bytes - 1)];
// write the big-endian value to the addresses starting at value_start_address
for (size_t i = wordsize_bytes; i > 0; i--) {
file_iter->program_data[value_start_address + (wordsize_bytes - i)] = data >> ((i - 1) * 8);
}
}
else {
// retrieve "value" from the master symbol table
std::vector<AssemblerSymbol>::iterator master_table_iter = master_symbol_table.begin();
bool found = false;
size_t value = 0;
while ((master_table_iter != master_symbol_table.end()) && !found) {
// if the names are the same
if (master_table_iter->name == relocation_iter->name) {
// get the value
value = master_table_iter->value;
// set the found variable and exit the loop
found = true;
}
else {
master_table_iter++;
}
}
// if we didn't find it, throw an error
if (!found) {
throw std::runtime_error("**** Relocation error: Could not find '" + relocation_iter->name + "' in symbol table!");
}
// finally, write "value" to the relocation table
// get the start address and the number of bytes in our wordsize
size_t value_start_address = relocation_iter->value;
size_t wordsize_bytes = (size_t)file_iter->_wordsize / 8;
for (size_t i = wordsize_bytes; i > 0; i--) {
file_iter->program_data[value_start_address + (wordsize_bytes - i)] = value >> ((i - 1) * 8);
}
}
}
}
}
// Now, we can write all of the program data to a vector of bytes
std::vector<uint8_t> sml_data;
for (std::vector<SinObjectFile>::iterator file_iter = this->object_files.begin(); file_iter != this->object_files.end(); file_iter++) {
// iterate through the program data and push the bytes into sml_data
for (std::vector<uint8_t>::iterator byte_iter = file_iter->program_data.begin(); byte_iter != file_iter->program_data.end(); byte_iter++) {
sml_data.push_back(*byte_iter);
}
// create a vector of uint8_ts from our file to contain all of the .data information
std::vector<uint8_t> data_section;
// iterate through the .data section of the file
for (std::list<std::tuple<std::string, size_t, std::vector<uint8_t>>>::iterator data_table_iter = file_iter->data_table.begin(); data_table_iter != file_iter->data_table.end(); data_table_iter++) {
// iterate through the actual data bytes in the section
for (std::vector<uint8_t>::iterator data_iter = std::get<2>(*data_table_iter).begin(); data_iter != std::get<2>(*data_table_iter).end(); data_iter++) {
// push those bytes onto data_section
data_section.push_back(*data_iter);
}
}
// now, push all of the information from data_section to sml_data; the data section should come at the end of each object
for (std::vector<uint8_t>::iterator data_section_iter = data_section.begin(); data_section_iter != data_section.end(); data_section_iter++) {
sml_data.push_back(*data_section_iter);
}
}
/************************************************************
******************** SML FILE *********************
************************************************************/
// Finally, create a .sml file of our linked program
std::ofstream sml_file;
sml_file.open(file_name + ".sml", std::ios::out | std::ios::binary); // TODO: get a final program name
BinaryIO::writeU8(sml_file, this->object_files[0]._wordsize); // TODO: get a better wordsize deciding algorithm
BinaryIO::writeU32(sml_file, sml_data.size());
// write the byte to the file
for (std::vector<uint8_t>::iterator it = sml_data.begin(); it != sml_data.end(); it++) {
BinaryIO::writeU8(sml_file, *it);
}
sml_file.close();
}
Linker::Linker() {
this->_start_offset = 0; // default to 0
this->_wordsize = 16; // default to 16 bit words
this->_rs_start = _RS_START; // default to "_RS_START" as defined in "VMMemoryMap.h"
}
Linker::Linker(std::vector<SinObjectFile> object_files) : object_files(object_files)
{
this->_start_offset = 0; // default to 0
this->_wordsize = 16; // default to 16 bit words
this->_rs_start = _RS_START; // default to "_RS_START" as defined in "VMMemoryMap.h"
this->get_metadata(); // get our metadata so we can form the sml file; this may overwrite the initial values established above
}
Linker::~Linker()
{
}
| true |
ddb9e3b9a6f8e2ffd6ff902da3a7b0db156f036e | C++ | ngthvan1612/OJCore | /TestModule/HK1/Users/19110342/BAI1.CPP | UTF-8 | 440 | 3.140625 | 3 | [] | no_license | #include<iostream>
using namespace std;
void kt(int x, int y, int &a, int &b)
{
if(x==1&&y==3)
{
a+=3;
}
else if(x==3&&y==1)
b+=3;
if(x==3&&y==2)
{
a+=3;
}
else if(x==2&&y==3)
b+=3;
if(x==2&&y==1)
{
a+=3;
}
else if(x==1&&y==2)
b+=3;
if(x==y)
{
a++;
b++;
}
}
void main()
{
int a=0,b=0,c=0;
int x, y, z, t, u, v;
cin>>x>>y>>z>>t>>u>>v;
kt(x,y,a,b);
kt(z,t,a,c);
kt(u,v,b,c);
cout<<a<<" "<<b<<" "<<c;
} | true |
01b1b483bfde83cb276a52ef4a5c1baae824434c | C++ | clubeccuffs/obi2018 | /uri2783.cc | UTF-8 | 639 | 2.765625 | 3 | [] | no_license | #include <iostream>
#include <set>
#include <vector>
using namespace std;
vector<bool> carimbada;
vector<int> figurinhas;
int main() {
int N, C, M;
cin >> N >> C >> M;
carimbada.assign(N, false);
figurinhas.assign(N, 0);
for(int i = 0; i < C; ++i) {
int x;
cin >> x;
carimbada[x-1] = true;
}
for(int i = 0; i < M; ++i) {
int x;
cin >> x;
figurinhas[x-1]++;
}
int achadas = 0;
for(int i = 0; i < N; ++i) {
if(figurinhas[i] > 0 && carimbada[i]) {
achadas++;
}
}
cout << C - achadas << '\n';
return 0;
}
| true |
4b061b88f8ebd09775292ff5c54ef0fd6bd6d0da | C++ | MarcoLotto/ScaenaFramework | /Graphics/src/BasicForceMeshDeformationTFShader.cpp | UTF-8 | 3,332 | 2.515625 | 3 | [
"MIT"
] | permissive | /**********************************
* SCAENA FRAMEWORK
* Author: Marco Andrés Lotto
* License: MIT - 2016
**********************************/
#include "BasicForceMeshDeformationTFShader.h"
#include "GraphicDevice.h"
#include "WindowConnector.h"
//***PARAMETROS GENERALES*********************************************************************************
#define VSHADER WindowConnector::getBaseApplicationPath() + "Shaders/BasicForceMeshDeformationTFShader.vert"
//********************************************************************************************************
BasicForceMeshDeformationTFShader::BasicForceMeshDeformationTFShader(){
this->forceDirection = vec3(0.0f);
this->forceIntensity = 0.0f;
this->staticStrength = 0.0f;
this->staticPoint = vec3(0.0f);
this->forceIntensityInterpolator = new TimeParameterInterpolator(0.0f, this->forceIntensity, 0);
this->init();
}
BasicForceMeshDeformationTFShader::~BasicForceMeshDeformationTFShader(){
delete this->forceIntensityInterpolator;
}
// Se declaran que VBOs del MeshBuffers se escribiran en el output del transform feedback (se declaran en el transformFeedbackObject)
void BasicForceMeshDeformationTFShader::declareFeedbackInputsAndOutputs(MeshBuffers* meshBuffersInput, MeshBuffers* meshBuffersOutput){
// Me guardo el mesh para despues poder transformar
this->inputMeshBuffers = meshBuffersInput;
// Inicializo (o limpio) el shader para este mesh
this->prepareTransformFeedbackObject();
//Declaro todos los buffers de salida (solo puse uno, podria haber mas)
this->attachVboToTransformFeedback(meshBuffersOutput->getVertexBufferObject());
}
// Se llama para generar la transformacion. Es analogo a draw en los shaders con rasterizador
void BasicForceMeshDeformationTFShader::execute(){
//Activo el programa de shaders
this->use();
//Cargo la direccion e intensidad de la fuerza aplicada
this->setUniform(this->staticPointUniform, this->staticPoint);
this->setUniform(this->staticStrengthUniform, this->staticStrength);
this->setUniform(this->forceDirectionUniform, this->forceDirection);
this->setUniform(this->forceIntensityUniform, this->forceIntensityInterpolator->getCurrentValue());
//Mando a transformar
VertexArrayObject* vao = this->inputMeshBuffers->getVaoObject();
unsigned int vertexCount = this->inputMeshBuffers->getVertexBufferObject()->getBufferDataLenght();
GraphicDevice::getInstance()->transformUsingFeedback(vao, vertexCount, this->transformFeedbackObject);
}
// Inicia el shader de transformacion
void BasicForceMeshDeformationTFShader::init(){
list<string> inputAttributes;
inputAttributes.push_back("VertexPosition");
list<string> outputAttributes;
outputAttributes.push_back("VertexPositionOutput");
this->setVertexShaderName(VSHADER);
this->initialize(&inputAttributes, &outputAttributes, true);
}
void BasicForceMeshDeformationTFShader::setAnimationTime(unsigned int time){
this->forceIntensityInterpolator->setInterpolationTime(time);
this->forceIntensityInterpolator->setPlay();
// Identifico los uniforms a utilizar
this->staticPointUniform = new GLSLUniform("staticPoint", this);
this->staticStrengthUniform = new GLSLUniform("staticStrength", this);
this->forceDirectionUniform = new GLSLUniform("forceDirection", this);
this->forceIntensityUniform = new GLSLUniform("forceIntensity", this);
} | true |
a0a95b56a284699830759f60fbdb0ceeb519d4f7 | C++ | vroussea/piscine_cpp | /D04/ex01/Character.cpp | UTF-8 | 2,910 | 2.921875 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Character.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vroussea <vroussea@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/12 19:46:43 by vroussea #+# #+# */
/* Updated: 2018/01/12 19:46:43 by vroussea ### ########.fr */
/* */
/* ************************************************************************** */
#include "Character.hpp"
Character::Character(void) : _name("Val") {
setWeapon(nullptr);
setAPMax(40);
setAP(this->_apMax);
}
Character::Character(std::string const & name) : _name(name) {
setWeapon(nullptr);
setAPMax(40);
setAP(this->_apMax);
}
Character::Character(Character const &src) {
*this = src;
}
Character::~Character(void) {
}
void Character::recoverAP() {
setAP(this->_ap + 10);
}
void Character::equip(AWeapon * aWeapon) {
setWeapon(aWeapon);
}
void Character::attack(Enemy * enemy) {
if (this->_weapon && this->_ap >= this->_weapon->getAPCost()) {
setAP(this->_ap - this->_weapon->getAPCost());
std::cout << this->getName();
std::cout << " attacks " << enemy->getType();
std::cout << " with a " << this->_weapon->getName() << std::endl;
this->_weapon->attack();
enemy->takeDamage(this->_weapon->getDamage());
if (enemy->getHP() <= 0) {
delete enemy;
}
}
}
std::string const Character::getName() const {
return this->_name;
}
AWeapon *Character::getWeapon() const {
return this->_weapon;
}
int Character::getAP() const {
return this->_ap;
}
int Character::getAPMax() const {
return this->_apMax;
}
void Character::setWeapon(AWeapon * weapon) {
this->_weapon = weapon;
}
void Character::setAP(int ap) {
this->_ap = (ap > this->_apMax ? this->_apMax : ap);
}
void Character::setAPMax(int apMax) {
this->_apMax = apMax;
}
Character &Character::operator=(Character const &) {
return *this;
}
std::ostream &operator<<(std::ostream &o, Character const &i) {
o << i.getName();
o << " has " << i.getAP();
o << " AP and ";
if (i.getWeapon()) {
std::cout << "wields a " << i.getWeapon()->getName() << std::endl;
}
else {
std::cout << "is unarmed" << std::endl;
}
return o;
}
| true |
0c740ed6eb133e77bb31befb696aae3b2107568e | C++ | clchen3667/algorithm-exercise | /heap/mergeToMaxHeap/heap_maker.cpp | UTF-8 | 538 | 3.3125 | 3 | [] | no_license | #include "heap_maker.h"
using namespace std;
void buildMaxHeap(vector<int>& arr, int num) {
for (int i = num/2 -1;i >= 0;i--)
maxHeapify(arr, num, i);
}
void maxHeapify(vector<int>& arr, int n, int idx) {
if (idx >= n)
return;
int l_child = 2 * idx + 1;
int r_child = 2 * idx + 2;
int max;
if (l_child < n && arr[l_child] > arr[idx]) {
max = l_child;
} else {
max = idx;
}
if (r_child < n && arr[r_child] > arr[max]) {
max = r_child;
}
if (max != idx) {
swap(arr[max], arr[idx]);
maxHeapify(arr, n, max);
}
}
| true |
ec94a5b0fcf5dffb51a693ca126d6eb6f3db61d4 | C++ | noeld/cpp | /cpp11/cpp11.cpp | UTF-8 | 1,534 | 2.8125 | 3 | [
"Unlicense"
] | permissive | //clang++ cpp11.cpp -std=c++11 -o cpp11
#include <iostream>
#include <thread>
#include <unistd.h>
#include <mutex>
#include <array>
#include <atomic>
#include <cstdint>
using namespace std;
long long func() {
cout << std::this_thread::get_id() << endl;
sleep(1);
return 7ll;
}
template<typename t> struct countertype {
typedef t type;
// static const size_t bytelength{sizeof(t)};
};
typedef countertype<uint32_t> myct_t;
class mythread : public thread {
public:
using thread::thread;
// using thread::operator=;
~mythread() {
cout << "~mythread" << endl;
}
};
int main (int argc, char const *argv[])
{
cout << "Hardware concurrency: " << thread::hardware_concurrency() << endl;
//auto var = func();
//cout << var << endl;
//cout << typeid(var).name() << endl;
mutex m;
atomic<typename myct_t::type> counter{0};
auto lambda = [&](int max){ for(int i = 0; i < max; ++i) {
++counter;
if (i % 1000 == 0)
{
{
unique_lock<mutex> lock(m);
cout << std::this_thread::get_id() << " " << i << "/" << max << endl;
}
// sleep(1);
}
} };
const size_t n = 32;
array<thread*,n> t;
// thread** t = new thread*[n];
// for (int i = 0; i < n; ++i) {
{
int i{0};
for (auto& c : t) {
c = new thread(lambda, ++i << 12);
}
}
for (auto& c : t) {
c->join();
delete c;
//cout << "(" << myct_t::bytelength;
cout << "(" << sizeof(myct_t::type) << ") Counter: " << counter << endl;
}
/*
for (int i = 0; i < n; ++i) {
t[i]->join();
delete t[i];
}*/
// delete [] t;
return 0;
} | true |
e41c573759496a0530d703a826a3bfea69cbbdaa | C++ | zhaodongzhi/leetcodeSolution | /Best_Time_to_Buy_and_Sell_Stock_IV.cpp | UTF-8 | 707 | 3.0625 | 3 | [] | no_license | class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
if(k >= prices.size()/2)
{
int result = 0;
for(int i=1; i<prices.size(); ++i)
{
result += max(prices[i]-prices[i-1], 0);
}
return result;
}
vector<int> buys(k+1, INT_MIN);
vector<int> sells(k+1, 0);
for(int i=0; i<prices.size(); ++i)
{
int price = prices[i];
for(int j=k; j>0; --j)
{
sells[j] = max(buys[j]+price, sells[j]);
buys[j] = max(sells[j-1]-price, buys[j]);
}
}
return sells[k];
}
};
| true |
39d32db6ff235bd627ac6cecdf0909ad5b6e2b4f | C++ | xry224/newcode | /code/浮点数加法.cpp | GB18030 | 1,890 | 3.546875 | 4 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
#define SIZE 3000
class BigFloat
{
public:
int Integer[SIZE] = { 0 };
int Decimal[SIZE] = { 0 };
BigFloat(string str)
{
int index = str.find(".");
for (int i = index - 1; i >= 0; i--)
{
int off = index - 1 - i;
Integer[SIZE - off - 1] = str[i] - '0';
}
for (int i = index + 1; i < str.length(); i++)
{
Decimal[i - (index + 1)] = str[i] - '0';
}
}
BigFloat()
{
}
void Output()
{
int index;
int i;
for (i = 0; i < SIZE; i++)
{
if (Integer[i] != 0)
{
index = i;
break;
}
}
if (i == SIZE) //ȫ0
{
index = SIZE - 1;
}
int indexD;
for (int j = SIZE - 1; j >= 0; j--)
{
if (Decimal[j] != 0)
{
indexD = j;
break;
}
}
for (int i = index; i < SIZE; i++)
{
cout << Integer[i];
}
cout << ".";
for (int i = 0; i <= indexD; i++)
{
cout << Decimal[i];
}
cout << endl;
}
BigFloat operator + (const BigFloat &b) const
{
BigFloat res = BigFloat();
bool flag = false;//Ƿλ
//С
for (int i = SIZE - 1; i >= 0; i--)
{
res.Decimal[i] += Decimal[i] + b.Decimal[i];
if (res.Decimal[i] >= 10)
{
res.Decimal[i] -= 10;
if (i == 0)
{
flag = true;
}
else
{
res.Decimal[i - 1] ++;
}
}
}
if (flag)
{
res.Integer[SIZE - 1]++;
}
//
for (int i = SIZE - 1; i >= 0; i--)
{
res.Integer[i] += Integer[i] + b.Integer[i];
if (res.Integer[i] >= 10)
{
res.Integer[i] -= 10;
res.Integer[i - 1]++;
}
}
return res;
}
};
int main()
{
string a, b;
while (cin >> a >> b)
{
BigFloat n1 = BigFloat(a);
BigFloat n2 = BigFloat(b);
n1 = n1 + n2;
n1.Output();
}
return 0;
} | true |
0945d91ed0416eed0ef0625eaa97a911a90e9f0b | C++ | gtz12345/gao_tianze | /第四章/salary/main.cpp | UTF-8 | 254 | 3.015625 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
float a;
float b=200;
float c;
while(a!=-1)
{
cout<<"Enter sales in dollars(-1 to end):";
cin>>a;
c=b+a*0.09;
}
cout<<"Salary is :$"<<c<<endl;
}
| true |