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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
c4841ec9969c5efe7a342de5256696d001e694b2 | C++ | valnmv/vbackup | /src/zlib_intf.cpp | UTF-8 | 3,601 | 2.71875 | 3 | [] | no_license | #include "pch.h"
#include "zlib_intf.h"
#include "zlib.h"
#include <vector>
#include <assert.h>
#include <stdio.h>
/* Compress from file source to file dest until EOF on source.
def() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_STREAM_ERROR if an invalid compression
level is supplied, Z_VERSION_ERROR if the version of zlib.h and the
version of the library linked do not match, or Z_ERRNO if there is
an error reading or writing the files. */
int deflate(int compressionLevel, std::vector<uint8_t> &inbuf, std::vector<uint8_t> &outbuf)
{
int ret, flush;
unsigned have;
z_stream strm;
/* allocate deflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
ret = deflateInit(&strm, compressionLevel);
if (ret != Z_OK)
return ret;
strm.avail_in = static_cast<uInt>(inbuf.size());
//flush = last ? Z_FINISH : Z_NO_FLUSH;
flush = Z_FINISH;
strm.next_in = &inbuf[0];
std::size_t prev_out_size = 0;
outbuf.resize(CHUNK);
strm.next_out = &outbuf[0];
do {
strm.avail_out = CHUNK;
ret = deflate(&strm, flush); /* no bad return value */
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
have = CHUNK - strm.avail_out;
if (strm.avail_out == 0)
{
prev_out_size += CHUNK;
outbuf.resize(prev_out_size + CHUNK);
strm.next_out = &outbuf[prev_out_size];
}
} while (strm.avail_out == 0);
assert(strm.avail_in == 0); /* all input will be used */
outbuf.resize(prev_out_size + have);
/* clean up and return */
(void)deflateEnd(&strm);
return Z_OK;
}
/* Decompress from file source to file dest until stream ends or EOF.
inf() returns Z_OK on success, Z_MEM_ERROR if memory could not be
allocated for processing, Z_DATA_ERROR if the deflate data is
invalid or incomplete, Z_VERSION_ERROR if the version of zlib.h and
the version of the library linked do not match, or Z_ERRNO if there
is an error reading or writing the files. */
int inflate(const std::vector<uint8_t> &inbuf, std::vector<uint8_t> &outbuf)
{
int ret;
unsigned have;
z_stream strm;
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit(&strm);
if (ret != Z_OK)
return ret;
do {
strm.avail_in = static_cast<uInt>(inbuf.size());
if (strm.avail_in == 0)
break;
strm.next_in = const_cast<Byte*>(&inbuf[0]);
do {
strm.avail_out = CHUNK;
strm.next_out = &outbuf[0];
ret = inflate(&strm, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR); /* state not clobbered */
switch (ret) {
case Z_NEED_DICT:
ret = Z_DATA_ERROR; /* and fall through */
case Z_DATA_ERROR:
case Z_MEM_ERROR:
(void)inflateEnd(&strm);
return ret;
}
have = CHUNK - strm.avail_out;
// TODO handle output buffer flush?
} while (strm.avail_out == 0);
/* done when inflate() says it's done */
} while (ret != Z_STREAM_END);
/* clean up and return */
(void)inflateEnd(&strm);
return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
}
/* report a zlib or i/o error */
void zerr(int ret)
{
fputs("zlib: ", stderr);
switch (ret) {
case Z_ERRNO:
if (ferror(stdin))
fputs("error reading stdin\n", stderr);
if (ferror(stdout))
fputs("error writing stdout\n", stderr);
break;
case Z_STREAM_ERROR:
fputs("invalid compression level\n", stderr);
break;
case Z_DATA_ERROR:
fputs("invalid or incomplete deflate data\n", stderr);
break;
case Z_MEM_ERROR:
fputs("out of memory\n", stderr);
break;
case Z_VERSION_ERROR:
fputs("zlib version mismatch!\n", stderr);
}
}
| true |
5b30b9fe025833805df7cd35b01144c29825d65d | C++ | 23ksw10/LeetCode | /algorithm/1493_Longest_Subarray_of_1's_After Deleting_One_Element/solution.cpp | UTF-8 | 547 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include<string>
#include <algorithm>
using namespace std;
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int l = 0;
int r = 0;
int delete_count = 0;
int ans = 0;
for (int i = 0; i < nums.size(); i++) {
if (delete_count) {
if (nums[i])r++;
else {
ans = max(ans, l + r);
l = r;
r = 0;
}
}
else {
if (nums[i])l++;
else {
delete_count = 1;
}
}
}
ans = max(ans, l + r);
if (!delete_count)ans--;
return ans;
}
}; | true |
0f69bb943dbcb0965fc25d56499794d9835b6461 | C++ | masato-sso/AtCoderProblems | /ABC001_100/ABC009/B.cpp | UTF-8 | 628 | 2.75 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<stdio.h>
#include<bits/stdc++.h>
#include<map>
#include<vector>
using namespace std;
int main(){
int N;
cin>>N;
vector<int>A(N,0);
for(int i=0;i<N;i++){
cin>>A[i];
}
int first_max=-1;
int second_max=-1;
for(int i=0;i<N;i++){
if(A[i]>first_max){
second_max=first_max;
first_max=A[i];
}
else{
if(A[i]==first_max){
continue;
}
if(A[i]>second_max){
second_max=A[i];
}
}
}
cout<<second_max<<endl;
} | true |
d442067909136348d9c8b8fce51420fb6f7af641 | C++ | DeadBlasoul/os | /lab6/slave/src/main.cpp | UTF-8 | 4,388 | 2.859375 | 3 | [] | no_license | //
// Hello World client in C++
// Connects REQ socket to tcp://localhost:5555
// Sends "Hello" to server, expects "World" back
//
#include <zmq.hpp>
#include <string>
#include <iostream>
#include <sstream>
#include <Windows.h>
#undef interface
#include <utility/commandline.hpp>
#include <network/response.hpp>
#include <network/topology.hpp>
#include "interface.hpp"
auto main(int const argc, char const* argv[]) -> int try
{
using namespace utility;
if (argc != 3)
{
throw std::invalid_argument{"Incorrect number of arguments"};
}
std::cout
<< "[#] New node created with the following parameters:" << std::endl
<< " path : " << argv[0] << std::endl
<< " address : " << argv[1] << std::endl
<< " id : " << argv[2] << std::endl;
//
// As we start program via CreateProcess it's doesn't receive argv[0] as path to program which started.
// Following it argv[0] will be an address, argv[1] will be an unique id.
//
auto const* address = argv[1];
auto const id = std::stoll(argv[2]);
//
// Prepare our context and socket
//
auto context = zmq::context_t{1};
auto engine = network::topology::tree::engine{context};
auto interface = executable::interface{engine, id};
auto socket = zmq::socket_t{context, ZMQ_REP};
socket.bind(address);
auto send_response = [&socket](network::response const& response) -> void
{
auto serialized_response = zmq::message_t{response.size()};
response.serialize_to(serialized_response);
socket.send(serialized_response, zmq::send_flags::dontwait);
std::cout << "[v] Response : [" << response.code_to_string() << "] " << response.message << std::endl;
};
while (not interface.kill_requested())
{
//
// Receive request
//
auto serialized_request = zmq::message_t{256};
auto const result = socket.recv(serialized_request, zmq::recv_flags::none);
serialized_request.rebuild(*result);
//
// Process request
//
try
{
auto request = network::request{};
request.deserialize_from(serialized_request);
std::cout << std::endl;
std::cout << "[^] Request : [" << request.code_to_string() << "] " << request.message << std::endl;
if (request.type == network::request::type::envelope)
{
//
// Send 'ok' back immediately on envelope request
//
send_response({.error = network::error::ok});
continue;
}
auto request_stream = std::stringstream{request.message};
auto target_id = std::int64_t{};
if (not (request_stream >> target_id))
{
throw std::invalid_argument{"invalid target id"};
}
auto response = network::response{};
if (target_id == id || target_id == network::topology::any_node)
{
auto command = std::string{};
for (auto line = std::string{}; std::getline(request_stream, line);)
{
command += line + "\n";
}
response = interface.execute(command);
}
else
{
response = engine.ask_every_until_response(target_id, request.message);
}
//
// Send response
//
send_response(response);
}
catch (std::runtime_error const& e)
{
send_response({
.error = network::error::internal_error,
.message = e.what(),
});
}
catch (std::invalid_argument const& e)
{
send_response({
.error = network::error::bad_request,
.message = e.what(),
});
}
catch (std::exception const& e)
{
send_response({
.error = network::error::internal_error,
.message = e.what(),
});
}
}
}
catch (std::exception& e)
{
std::cerr << "PANIC: " << e.what() << std::endl;
#undef max
zmq_sleep(std::numeric_limits<int>::max());
}
| true |
f251c3bc44608023f255b76dcab82a0434647bca | C++ | KalahariKanga/ooImages | /printExpression.cpp | UTF-8 | 579 | 3.078125 | 3 | [] | no_license | #include "printExpression.h"
#include "Array.h"
printExpression::printExpression()
{
noArguments = 1;
optimisable = 0;
}
printExpression::~printExpression()
{
}
Variable printExpression::evaluate()
{
auto result = arguments[0]->getResult();
if (result.isType<Real>())
{
float value = *result.get<Real>();
std::cout << value << std::endl;
}
if (result.isType<Array>())
{
auto arr = result.get<Array>();
std::cout << "[ ";
for (int c = 0; c < arr->size(); c++)
std::cout << *arr->get(c).get<Real>() << " ";
std::cout << "]\n";
}
return Variable();
} | true |
8c6d766063c90f97c9e1bfb4db7f34d79646df29 | C++ | muneebGH/oop-misc-cpp | /tic-tac-toe-class-implementation/TicTacToe.cpp | UTF-8 | 1,404 | 3.453125 | 3 | [] | no_license | #include"TicTacToe.h"
void TicTacToe::gamePlay()
{
GameBoard GB;
char symbolA, symbolB,pos;
bool check;
do
{
cout << "enter the character for player 1 : ";
cin >> symbolA;
check = GB.isValidPosition(symbolA);
} while (check);
do
{
cout << "enter the character for player 2 : ";
cin >> symbolB;
check = GB.isValidPosition(symbolA);
}
while (check);
system("cls");
PlayerTurn PT = FIRST_PLAYER;
GB.setGameStatus(IN_PROGRESS);
GB.displayBoard();
do
{
cout << "enter the position for player " << PT << " : ";
cin >> pos;
GB.markBoard(pos, symbolA);
GB.displayBoard();
int movesCount = GB.getValidMovesCount();
if (movesCount== 9)
{
GB.setGameStatus(DRAW);
}
else if (GB.isWin())
{
GB.setGameStatus(WIN);
}
if (GB.getGameStatus() == IN_PROGRESS)
{
PT = SECOND_PLAYER;
cout << "enter the position for player " << PT << " :";
cin >> pos;
GB.markBoard(pos, symbolB);
GB.displayBoard();
int movesCount = GB.getValidMovesCount();
if (movesCount== 9)
{
GB.setGameStatus(DRAW);
}
else if (GB.isWin())
{
GB.setGameStatus(WIN);
}
}
}
while (GB.getGameStatus() == IN_PROGRESS);
if (GB.getGameStatus() == WIN)
{
cout << " player " << PT << " have won " << endl;
}
else
{
cout << "draw have occurred " << endl;
}
} | true |
9210735f3bf6a420834e6be507ca0239700c76f5 | C++ | vbirds/Bex | /Bex/src/Bex/stream/serialization/text_oarchive.hpp | UTF-8 | 4,203 | 2.75 | 3 | [] | no_license | #ifndef __BEX_STREAM_SERIALIZATION_TEXT_OARCHIVE__
#define __BEX_STREAM_SERIALIZATION_TEXT_OARCHIVE__
#include "base_serializer.hpp"
#include <boost/lexical_cast.hpp>
//////////////////////////////////////////////////////////////////////////
/// 文本式序列化 out
namespace Bex { namespace serialization
{
class text_oarchive
: public base_serializer<text_oarchive>
, public text_base
, public output_archive_base
{
friend class base_serializer<text_oarchive>;
std::streambuf& buf_;
std::streamsize acc_;
int deep_;
public:
explicit text_oarchive(std::streambuf& sb)
: buf_(sb), acc_(0), deep_(0)
{
}
explicit text_oarchive(std::ostream& os)
: buf_(*os.rdbuf()), acc_(0), deep_(0)
{
}
template <typename T>
inline text_oarchive & operator&(T const& t)
{
return (*this << t);
}
template <typename T>
inline text_oarchive & operator<<(T const& t)
{
save(t);
return (*this);
}
template <typename T>
inline bool save(T const& t)
{
if (!good()) return false;
int deep = deep_++;
if (!do_save(const_cast<T&>(t)))
{
state_ = archive_state::error;
-- deep_;
return false;
}
else
{
if (!deep)
acc_ = 0;
-- deep_;
return true;
}
}
// @Todo: 改为private.
public:
using base_serializer<text_oarchive>::do_save;
inline bool do_save(char const* buffer, std::size_t size)
{
std::streamsize ls = buf_.sputn(buffer, size);
acc_ += ls;
return (ls == size);
}
inline bool do_save(text_wrapper<char> & wrapper)
{
char & ch = wrapper.data();
std::streamsize ls = buf_.sputn(&ch, 1);
acc_ += ls;
return (ls == 1);
}
template <typename T>
inline bool do_save(text_wrapper<T> & wrapper)
{
BOOST_STATIC_ASSERT( (boost::is_arithmetic<T>::value) );
std::string buffer;
try {
buffer = boost::lexical_cast<std::string>(wrapper.data()) + " ";
} catch (...) { return false; }
std::streamsize ls = buf_.sputn(buffer.c_str(), buffer.length());
acc_ += ls;
return (ls == buffer.length());
}
};
//////////////////////////////////////////////////////////////////////////
/// text_save
template <typename T>
bool text_save(T const& t, std::ostream& os)
{
boost::io::ios_flags_saver saver(os);
os.unsetf(std::ios_base::skipws);
text_oarchive bo(os);
bo & t;
return bo.good() ? true : (bo.clear(), false);
}
template <typename T>
bool text_save(T const& t, std::streambuf& osb)
{
text_oarchive bo(osb);
bo & t;
return bo.good() ? true : (bo.clear(), false);
}
template <typename T>
std::size_t text_save(T const& t, char * buffer, std::size_t size)
{
static_streambuf osb(buffer, size);
text_oarchive bo(osb);
bo & t;
return bo.good() ? osb.size() : (bo.clear(), 0);
}
/// 数据持久化专用接口
template <typename T, typename ... Args>
FORCE_INLINE auto text_save_persistence(T const& t, Args && ... args) -> decltype(text_save(t, std::forward<Args>(args)...))
{
static_assert(has_serialize<T>::value, "The persistence data mustbe has serialize function.");
static_assert(has_version<T>::value, "The persistence data mustbe has version.");
return text_save(t, std::forward<Args>(args)...);
}
} //namespace serialization
namespace {
using serialization::text_oarchive;
using serialization::text_save;
using serialization::text_save_persistence;
} //namespace
} //namespace Bex
#endif //__BEX_STREAM_SERIALIZATION_TEXT_OARCHIVE__ | true |
a0004784a1e83440c082eddaa848629429e5307a | C++ | sarahkittyy/bullet-heck | /src/Application.cpp | UTF-8 | 860 | 2.953125 | 3 | [
"MIT"
] | permissive | #include "Application.hpp"
Application::Application()
: mWindow(sf::VideoMode(800, 600), "Bullet Heck"),
mResources(),
mAppState(&mWindow, &mResources, new States::Menu())
{
}
int Application::run()
{
sf::Clock appClock; //The application time manager.
while (mWindow.isOpen()) //App loop
{
//Poll events
sf::Event event;
while (mWindow.pollEvent(event))
{
switch (event.type)
{
default:
break;
case sf::Event::Closed:
mWindow.close();
break;
}
}
//Time elapsed since last frame.
float msElapsed = appClock.restart().asSeconds() * 1000.f;
//Update the app state.
mAppState.update(msElapsed);
//Clear the window
mWindow.clear(mAppState.getState()->getBackgroundColor());
//Draw the app state.
mWindow.draw(mAppState);
//Display the drawn-to window
mWindow.display();
}
return 0;
} | true |
f498583a41c3c360a6dc420b280a9bf13e8a572a | C++ | clatisus/ACM-ICPC-Team-Archive | /zhongzihao-personal/Atcoder/grand005/C.cpp | UTF-8 | 514 | 2.65625 | 3 | [] | no_license | #include<bits/stdc++.h>
const int N = 110;
int cnt[N];
void no(){
puts("Impossible");
exit(0);
}
int main(){
int n;
scanf("%d", &n);
int min = INT_MAX, max = 0;
for (int i = 0, x; i < n; ++ i){
scanf("%d", &x);
++ cnt[x];
min = std::min(min, x);
max = std::max(max, x);
}
if (cnt[min] < 1 || cnt[min] > 2) no();
if (cnt[min] == 1 && max != 2 * min || cnt[min] == 2 && max != 2 * min - 1) no();
for (int i = min + 1; i <= max; ++ i){
if (cnt[i] < 2) no();
}
puts("Possible");
return 0;
}
| true |
77c23dea35b2a572c5b5bd1554a19466dd048e8e | C++ | mayankagg9722/Placement-Preparation | /leetcode/**nthDigit.cpp | UTF-8 | 1,087 | 3.46875 | 3 | [] | no_license | /*
400. Nth Digit
Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
Note:
n is positive and will fit within the range of a 32-bit signed integer (n < 231).
Example 1:
Input:
3
Output:
3
Example 2:
Input:
11
Output:
0
Explanation:
The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10.
*/
class Solution {
public:
int findNthDigit(int n) {
// string s="";
// int i=1;
// while(s.length()<n){
// s+=to_string(i++);
// }
// return s[n-1]-'0';
if(n<=9){
return n;
}
int i=1;
long int s=0;
long int ten=1;
int t;
while(true){
t=s;
s+=i*(9*ten);
ten=ten*10;
if(s>n){
break;
}
i++;
}
t=t+1;
long int rem = (n-t)%i;
long int no = ((n-t)/i)+pow(10,(i-1));
string str = to_string(no);
cout<<str;
return str[rem]-'0';
}
}; | true |
4cab56c976e67e5f4f69a257c4ca14d394bb8611 | C++ | dogguts/Transcendence | /Alchemy/Kernel/Math.cpp | UTF-8 | 3,844 | 3.09375 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | // Math.cpp
//
// Integer math package
#include "Kernel.h"
#include <math.h>
#define m ((unsigned long)2147483647)
#define q ((unsigned long)44488)
#define a ((unsigned int)48271)
#define r ((unsigned int)3399)
DWORD g_Seed = 0;
int mathNearestPowerOf2 (int x)
// mathNearestPowerOf2
//
// Returns the largest power of 2 that is <= x
// NOTE: This doesn't work for very large integers because we overflow
// iResult.
{
int iResult;
iResult = 1;
while (x > 0)
{
x = x >> 1;
iResult = iResult << 1;
}
return iResult >> 1;
}
int mathPower (int x, int n)
// mathPower
//
// Returns x raised to the nth power
{
if (x == 1)
return 1;
else if (n > 0)
{
int iResult = 1;
while (n)
{
if (n & 1)
{
iResult = iResult * x;
n = n - 1;
}
else
{
x = x * x;
n = n / 2;
}
}
return iResult;
}
else if (n == 0)
return 1;
else
return 0;
}
DWORD mathRandom (void)
// mathRandom
//
// Returns a random 31-bit number: 0 to 2^31-1 (2147483647)
//
// Based on code written by William S. England (Oct 1988) based
// on:
//
// Stephen K. Park and Keith W. Miller. RANDOM NUMBER GENERATORS:
// GOOD ONES ARE HARD TO FIND. Communications of the ACM,
// New York, NY.,October 1988 p.1192
{
// Seed it
if (g_Seed == 0)
{
g_Seed = MAKELONG(rand() % 0x10000, rand() % 0x10000);
g_Seed *= ::GetTickCount();
}
// Random
int lo, hi, test;
hi = g_Seed / q;
lo = g_Seed % q;
test = a * lo - r * hi;
if (test > 0)
g_Seed = test;
else
g_Seed = test + m;
// Done
return g_Seed;
}
int mathRandom (int iFrom, int iTo)
// mathRandom
//
// Returns a random number between iFrom and iTo (inclusive)
{
int iRandom;
int iRange = Absolute(iTo - iFrom) + 1;
if (iRange > RAND_MAX)
iRandom = ((10000 * rand()) + (rand() % 10000)) % iRange;
else
iRandom = rand() % iRange;
return iRandom + iFrom;
}
double mathRandomMinusOneToOne (void)
{
DWORD dwValue = mathRandom();
if (dwValue % 2)
return ((dwValue >> 1) / 1073741824.0);
else
return ((dwValue >> 1) / -1073741824.0);
}
double mathRandomGaussian (void)
// mathRandomGaussian
//
// Returns a random number with Gaussian distribution. The mean value is 0.0
// and the standard deviation is 1.0.
//
// Uses the polar form of the Box-Muller transformation.
//
// See: http://www.taygeta.com/random/gaussian.html
{
double x1, x2, w;
do
{
x1 = mathRandomMinusOneToOne();
x2 = mathRandomMinusOneToOne();
w = x1 * x1 + x2 * x2;
}
while (w >= 1.0);
w = sqrt((-2.0 * log(w)) / w);
return x1 * w;
}
int mathRound (double x)
// mathRound
//
// Round to the nearest integer.
// Based on: http://ldesoras.free.fr/doc/articles/rounding_en.pdf
{
const float round_to_nearest = 0.5f;
int i;
#ifndef __GNUC__
__asm
{
fld x
fadd st, st (0)
fadd round_to_nearest
fistp i
sar i, 1
}
#else
//i = floor(x + round_to_nearest); //fallback alternative
__asm__ __volatile__ (
"fadd %%st\n\t"
"fadd %%st(1)\n\t"
"fistpl %0\n\t"
"sarl $1, %0\n"
: "=m"(i) : "u"(round_to_nearest), "t"(x) : "st"
);
#endif
return (i);
}
int mathSeededRandom (int iSeed, int iFrom, int iTo)
// mathSeededRandom
//
// Returns a random number between iFrom and iTo (inclusive)
// The same random number is returned for any given value of iSeed
{
#define rand_with_seed() (((dwSeed = dwSeed * 214013L + 2531011L) >> 16) & 0x7fff)
DWORD dwSeed = (DWORD)iSeed;
int iRandom;
int iRange = Absolute(iTo - iFrom) + 1;
if (iRange > RAND_MAX)
iRandom = ((10000 * rand_with_seed()) + (rand_with_seed() % 10000)) % iRange;
else
iRandom = rand_with_seed() % iRange;
return iRandom + iFrom;
#undef rand_with_seed
}
int mathSqrt (int x)
// mathSqrt
//
// Returns the square root of x
{
// For now we use a floating point method
#ifndef LATER
return (int)sqrt((double)x);
#endif
}
| true |
17b6e83b2a5f74c380b51556daf201d81afc376a | C++ | janhancic/CHIC | /lib/arrayset/arrayset.h | UTF-8 | 586 | 2.90625 | 3 | [
"MIT"
] | permissive | #include <stdlib.h>
#include <stdio.h>
#ifndef __arrayset_h
#define __arrayset_h
#define DEFAULT_SIZE 10
class ArraySet {
private:
void **_arr;
int _num_elements;
int _size;
int _index_of(void *elem);
public:
ArraySet() : ArraySet(DEFAULT_SIZE) {}
ArraySet(int initial_size);
void add(void *elem);
bool remove(void *elem);
bool remove(int index);
void* find(void *elem);
void* get(int idx);
int size();
int count();
~ArraySet();
};
#endif
| true |
d9aad5f8863f65f9039ddc3d0897da879fcbc8dc | C++ | dsr373/phase-locked-loops | /Arduino/serial_test/serial_test.ino | UTF-8 | 595 | 2.734375 | 3 | [] | no_license | // var declarations
//int pin = 9;
int ledpin = 13;
String message = "";
String reply = "";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
// pinMode(pin, OUTPUT);
pinMode(ledpin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
if(Serial.available()) {
message = Serial.readString();
if(message == "on") {
digitalWrite(ledpin, HIGH);
reply = "pin 13 turned on";
}
else if(message = "off") {
digitalWrite(ledpin, LOW);
reply = "pin 13 turned off";
}
Serial.println(reply);
}
}
| true |
d44fc09dad0a3cbd9f99498d089e68f694099d77 | C++ | 4solo/leetcode | /25 Reverse Nodes in k-Group.cpp | UTF-8 | 843 | 3.34375 | 3 | [] | no_license | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
int newk=k;
ListNode* current=head;
ListNode* temp;
if(head==NULL) return head;
while(current&&newk>0)
{
current=current->next;
newk--;
}
if(newk>0)
{
return head;
}
else
{
ListNode* prev=reverseKGroup(current,k);
while(head&&k)
{
temp=head;
head=head->next;
temp->next=prev;
prev=temp;
k--;
}
return prev;
}
}
}; | true |
b7bbca010b873e617af7e8721e8138c9c1068f63 | C++ | iiwolf/Competitive | /HackerRank.cpp | UTF-8 | 3,246 | 3.375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
bool checkNext(string s, int digitSize, int i, int increaseFactor){
cout << "STARTING INFO: " << s << " - " << digitSize << " - " << i << endl;
int location = i*digitSize;
cout << "Giving a location of " << location << endl;
//went through the whole string without not being beautiful
if(location >= s.size() - 1){
return true;
}
string number = s.substr(i*digitSize - increaseFactor,digitSize);
cout << "Looking at " << number;
int n = stoi(number);
int nx = n + 1;
string nextNumber = to_string(nx);
int newDigitSize = nextNumber.size();
if(newDigitSize > digitSize){
increaseFactor += 1;
}
i++;
location = newDigitSize*i - increaseFactor; //takes care if same or increasing by 1
string actualNext = s.substr(location,newDigitSize);
digitSize = newDigitSize;
cout << ". Next number should be " << nextNumber << "\n";
cout << "Next number actually is " << actualNext << endl;
if(actualNext == nextNumber){
cout << "Yes!\n";
i++;
if(checkNext(s, digitSize, i, increaseFactor)){
return true;
}
}
cout << "No...\n";
return false;
}
int main(){
int q;
cin >> q;
for(int a0 = 0; a0 < q; a0++){
string s;
cin >> s;
cout << "--Considering new number: " << s << "\n\n";
bool continueLoop = true;
int size = s.size();
if(size == 1){
cout << "NO\n";
continue;
}
for(int digitSize = 1; digitSize <= size/2 + 1; digitSize++){
//take in number, convert it to int, find next, convert back to string
string number = s.substr(0,digitSize);
int n = stoi(number);
int nx = n + 1;
string nextNumber = to_string(nx);
int newDigitSize = nextNumber.size(); //update incase 99-->100, etc.
int increaseFactor = 0;
if(newDigitSize > digitSize){
increaseFactor += 1;
}
//actual next number in string
string actualNext = s.substr(digitSize,newDigitSize);
cout << "Looking at " << number << ". Next should be " << nextNumber << "\n";
cout << "Actual next string number is " << actualNext << endl;
if(nextNumber == actualNext){
cout << "Found possible match with a digit size of " << digitSize << endl;
if(digitSize + newDigitSize == size){
cout << "YES" << number << endl;
continueLoop = false;
}
else if(checkNext(s, newDigitSize, 1, increaseFactor)){
cout << "YES " << number << endl;
continueLoop = false;;
}
}
if(!continueLoop){break;}
else{
cout << "No match found yet. New digitSize " << (digitSize + 1)<< endl;
}
}
// your code goes here
}
return 0;
}
| true |
f068221d2c7f6512815f5261827fdae4820b2c59 | C++ | Skyway666/Assignment-1--2D-Platformer | /Dev_class5_handout/Motor2D/j1Collisions.h | UTF-8 | 1,515 | 2.671875 | 3 | [] | no_license | #ifndef __j1COLLISIONS_H__
#define __j1COLLISIONS_H__
#define MAX_COLLIDERS 10000
#include "j1Module.h"
#include "p2Log.h"
#include "SDL/include/SDL.h"
#include "SDL_image/include/SDL_image.h"
#pragma comment( lib, "SDL_image/libx86/SDL2_image.lib" )
enum COLLIDER_TYPE
{
COLLIDER_NONE = -1,
COLLIDER_WALL,
COLLIDER_BONE,
COLLIDER_DEADLY,
COLLIDER_PLAYER,
COLLIDER_MAX,
};
struct Collider
{
SDL_Rect rect;
bool to_delete = false;
COLLIDER_TYPE type;
Collider(SDL_Rect rectangle, COLLIDER_TYPE type) :
rect(rectangle),
type(type)
{}
void SetPos(int x, int y)
{
rect.x = x;
rect.y = y;
}
void SetSize(int w, int h)
{
rect.w = w;
rect.h = h;
}
bool CheckCollision(const SDL_Rect& r) const;
bool WillCollideLeft(const SDL_Rect& r, int distance) const;
bool WillCollideRight(const SDL_Rect& r, int distance) const;
bool WillCollideGround(const SDL_Rect& r, int distance) const;
bool WillCollideTop(const SDL_Rect& r, int distance) const;
};
class j1Collisions : public j1Module
{
public:
j1Collisions();
~j1Collisions();
bool Update(float dt);
bool PreUpdate();
bool CleanUp();
void Erase_Non_Player_Colliders();
bool WillCollideAfterSlide(const SDL_Rect& r, int distance) const; //checks if any rectangle would be colliding with the ceiling
Collider* AddCollider(SDL_Rect rect, COLLIDER_TYPE type);
void DebugDraw();
private:
Collider* colliders[MAX_COLLIDERS];
bool matrix[COLLIDER_MAX][COLLIDER_MAX];
bool debug = false;
};
#endif // __j1COLLISIONS_H__ | true |
cd411102fd6f7ff255b0518952deb9f34a234daf | C++ | colin016/smart | /src/handle/test/smartdll/dll_if.cpp | UTF-8 | 3,159 | 2.625 | 3 | [] | no_license | #include <stdio.h>
#include "dll.h"
class dllib *dllinf;
//动态库接口函数
int init(struct task_user *head, int (*callback)(int type, void* msg))
{
int i;
DBG("enter init( )......\n");
//构造动态库的任务信息定义
dllinf = new dllib; //本模块
dllinf->setcb(callback);
dllinf->setstatus(DLL_INITED);
if(head)
i = dllinf->settask(head); //如果携带有用户定义的任务设置,则进行设置
else
i = 1;
return i;
}
int query(int type)
{
int i, ret = 0;
DBG("enter query( )......\n");
DBG("type =%d\n", type);
switch(type)
{
case 0:
ret = DLL_VERSION;
break;
case 1:
if(dllinf->getstatus() < DLL_RUNNING)
ret = 0;
else
ret = 1;
break;
case 2:
if(dllinf == NULL)
ret = 0;
else if(dllinf->getstatus() == DLL_INITED)
{
ret = sizeof(dllib);
for(i=0; i<TASK_SUM; i++)
ret += dllinf->gettask(i)->getsize();
}
break;
case 3:
if(dllinf==NULL || dllinf->getstatus() == DLL_ERROR)
ret = 0;
else
ret = dllinf->gettasknum();
break;
case 4:
if(dllinf->getstatus() >= DLL_INITED)
{
task *p;
for(i=0; i<TASK_SUM; i++)
{
p = dllinf->gettask(i);
ret += p->getnum();
}
}
else
ret = 0;
case 5:
ret = dllinf->getstatus();
break;
default:
ret = -1;
break;
}
return ret;
}
//最重要的控制接口
int control(int type, void *in, void *out)
{
int i, ret = 0;
DBG("enter control( )......\n");
if(dllinf == NULL) //如果还没有初始化的话
return -1;
switch(type)
{
case 0:
ret = TASK_SUM;
break;
case 1:
for(i=0; i<TASK_SUM; i++)
{
dllinf->gettask(i)->gettaskinf((struct task_tip *)out+i);
}
break;
case 2:
i = *((int *)in);
ret = dllinf->gettask(i)->getarraynum(0);
break;
case 3:
{
int n = *((int *)in);
dllinf->gettask(n)->getparainf((struct para_tip *)out);
}
break;
case 4:
i = *((int *)in);
ret = dllinf->gettask(i)->getarraynum(1);
break;
case 5:
{
int n = *((int *)in);
dllinf->gettask(n)->getctlinf((struct ctl_inf *)out);
}
break;
case 6:
if(dllinf->getstatus() == DLL_RUNNING)
{
ret = dllinf->stop();
if(ret == 0)
dllinf->setstatus(DLL_PAUSE);
else
dllinf->setstatus(DLL_ERROR);
}
break;
case 7:
ret = dllinf->settask((struct task_user *)in); //如果携带有用户定义的任务设置,则进行设置
break;
case 8:
ret = dllinf->modtask((struct task_user *)in); //如果携带有用户定义的任务设置,则进行设置
break;
case 9:
ret = dllinf->deltask(*((int *)in));
break;
case 10:
{
int force;
if(in == NULL)
force = 0;
else
force = (*(int *)in);
if(force == 0 && dllinf->getstatus() >= 0)
dllinf->start(false);
else
dllinf->start(true);
}
break;
case 11: //获取动态库id和版本
{
struct dll_ver *p = (struct dll_ver *)out;
p->name = (char *)DLL_ID;
p->version = DLL_VERSION;
}
break;
default:
ret = -1;
break;
}
return ret;
}
int closedll(void)
{
DBG("enter close( )......\n");
delete dllinf;
return 0;
}
| true |
edeb48e8a65aaf4815ee648d114ca8caac33f760 | C++ | G-GFFD/Cendric2 | /src/FileIO/MapReader.cpp | UTF-8 | 21,820 | 2.515625 | 3 | [] | no_license | #include "FileIO/MapReader.h"
#ifndef XMLCheckResult
#define XMLCheckResult(result) if (result != XML_SUCCESS) {g_logger->logError("MapReader", "XML file could not be read, error: " + std::to_string(static_cast<int>(result))); return false; }
#endif
using namespace std;
MapReader::MapReader()
{
}
MapReader::~MapReader()
{
}
bool MapReader::checkData(MapData& data) const
{
if (data.mapSize.x == 0 || data.mapSize.y == 0)
{
g_logger->logError("MapReader", "Error in map data : map size not set / invalid");
return false;
}
if (data.tileSize.x == 0 || data.tileSize.y == 0)
{
g_logger->logError("MapReader", "Error in map data : tile size not set / invalid");
return false;
}
if (data.name.empty())
{
g_logger->logError("MapReader", "Error in map data : map name not set / empty");
return false;
}
if (data.tileSetPath.empty())
{
g_logger->logError("MapReader", "Error in map data : tileset path not set / empty");
return false;
}
if (data.backgroundLayers.empty())
{
g_logger->logError("MapReader", "Error in map data : no background layers set");
return false;
}
for (int i = 0; i < data.backgroundLayers.size(); i++)
{
if (data.backgroundLayers[i].empty())
{
g_logger->logError("MapReader", "Error in map data : background layer " + std::to_string(i) + std::string(" empty"));
return false;
}
if (data.backgroundLayers[i].size() != data.mapSize.x * data.mapSize.y)
{
g_logger->logError("MapReader", "Error in map data : background layer " + std::to_string(i) + std::string(" has not correct size (map size)"));
return false;
}
}
for (int i = 0; i < data.foregroundLayers.size(); i++)
{
if (data.foregroundLayers[i].empty())
{
g_logger->logError("MapReader", "Error in map data : foreground layer " + std::to_string(i) + std::string(" empty"));
return false;
}
if (data.foregroundLayers[i].size() != data.mapSize.x * data.mapSize.y)
{
g_logger->logError("MapReader", "Error in map data : foreground layer " + std::to_string(i) + std::string(" has not correct size (map size)"));
return false;
}
}
for (auto it : data.mapExits)
{
if (it.mapExitRect.left < 0.0 || it.mapExitRect.top < 0.0 || it.mapExitRect.left >= data.mapSize.x * data.tileSize.x || it.mapExitRect.top >= data.mapSize.y * data.tileSize.y)
{
g_logger->logError("MapReader", "Error in map data : a map exit rect is out of range for this map.");
return false;
}
if (it.levelID.empty())
{
g_logger->logError("MapReader", "Error in map data : map exit level id is empty.");
return false;
}
if (it.levelSpawnPoint.x < 0.f || it.levelSpawnPoint.y < 0.f)
{
g_logger->logError("MapReader", "Error in map data : lmap exit level spawn point is negative.");
return false;
}
}
for (auto it : data.npcs)
{
if (it.id.empty())
{
g_logger->logError("MapReader", "Error in map data : a map npc has no id.");
return false;
}
if (it.objectID == -1)
{
g_logger->logError("MapReader", "Error in map data : a map npc has no object id.");
return false;
}
}
if (data.collidableTiles.empty())
{
g_logger->logError("MapReader", "Error in map data : collidable layer is empty");
return false;
}
if (data.collidableTiles.size() != data.mapSize.x * data.mapSize.y)
{
g_logger->logError("MapReader", "Error in map data : collidable layer has not correct size (map size)");
return false;
}
return true;
}
bool MapReader::readMapExits(XMLElement* objectgroup, MapData& data) const
{
XMLElement* object = objectgroup->FirstChildElement("object");
while (object != nullptr)
{
int x;
XMLError result = object->QueryIntAttribute("x", &x);
XMLCheckResult(result);
int y;
result = object->QueryIntAttribute("y", &y);
XMLCheckResult(result);
int width;
result = object->QueryIntAttribute("width", &width);
XMLCheckResult(result);
int height;
result = object->QueryIntAttribute("height", &height);
XMLCheckResult(result);
MapExitBean bean;
bean.mapExitRect = sf::FloatRect(static_cast<float>(x), static_cast<float>(y), static_cast<float>(width), static_cast<float>(height));
bean.levelID = "";
bean.levelSpawnPoint.x = -1.f;
bean.levelSpawnPoint.y = -1.f;
// map spawn point for level exit
XMLElement* properties = object->FirstChildElement("properties");
if (properties == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no objectgroup->object->properties attribute found for level exit.");
return false;
}
XMLElement* _property = properties->FirstChildElement("property");
while (_property != nullptr)
{
const char* textAttr = nullptr;
textAttr = _property->Attribute("name");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no objectgroup->object->properties->property->name attribute found for level exit.");
return false;
}
std::string name = textAttr;
if (name.compare("level id") == 0)
{
textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no objectgroup->object->properties->property->value attribute found for level exit map id.");
return false;
}
bean.levelID = textAttr;
}
else if (name.compare("x") == 0)
{
XMLError result = _property->QueryIntAttribute("value", &x);
XMLCheckResult(result);
bean.levelSpawnPoint.x = static_cast<float>(x);
}
else if (name.compare("y") == 0)
{
XMLError result = _property->QueryIntAttribute("value", &y);
XMLCheckResult(result);
bean.levelSpawnPoint.y = static_cast<float>(y);
}
else
{
g_logger->logError("MapReader", "XML file could not be read, unknown objectgroup->object->properties->property->name attribute found for level exit.");
return false;
}
_property = _property->NextSiblingElement("property");
}
data.mapExits.push_back(bean);
object = object->NextSiblingElement("object");
}
return true;
}
bool MapReader::readLights(XMLElement* objectgroup, MapData& data) const
{
XMLElement* object = objectgroup->FirstChildElement("object");
while (object != nullptr)
{
int x;
XMLError result = object->QueryIntAttribute("x", &x);
XMLCheckResult(result);
int y;
result = object->QueryIntAttribute("y", &y);
XMLCheckResult(result);
int width;
result = object->QueryIntAttribute("width", &width);
XMLCheckResult(result);
int height;
result = object->QueryIntAttribute("height", &height);
XMLCheckResult(result);
LightBean bean;
bean.radius.x = width / 2.f;
bean.radius.y = height / 2.f;
bean.center.x = x + bean.radius.x;
bean.center.y = y + bean.radius.y;
// brightness for light bean
XMLElement* properties = object->FirstChildElement("properties");
if (properties != nullptr)
{
XMLElement* _property = properties->FirstChildElement("property");
while (_property != nullptr)
{
const char* textAttr = nullptr;
textAttr = _property->Attribute("name");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no objectgroup->object->properties->property->name attribute found for light bean.");
return false;
}
std::string name = textAttr;
if (name.compare("brightness") == 0)
{
float brightness;
result = _property->QueryFloatAttribute("value", &brightness);
XMLCheckResult(result);
if (brightness < 0.f || brightness > 1.f)
{
brightness = 1.f;
g_logger->logWarning("MapReader", "Brightness must be between 0 and 1. It was " + std::to_string(brightness) + ", it is now 1");
}
bean.brightness = brightness;
}
else
{
g_logger->logError("MapReader", "XML file could not be read, unknown objectgroup->object->properties->property->name attribute found for light bean.");
return false;
}
_property = _property->NextSiblingElement("property");
}
}
data.lights.push_back(bean);
object = object->NextSiblingElement("object");
}
return true;
}
bool MapReader::readObjects(XMLElement* map, MapData& data) const
{
XMLElement* objectgroup = map->FirstChildElement("objectgroup");
const char* textAttr;
while (objectgroup != nullptr)
{
textAttr = nullptr;
textAttr = objectgroup->Attribute("name");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no objectgroup->name attribute found.");
return false;
}
std::string name = textAttr;
if (name.find("mapexits") != std::string::npos)
{
if (!readMapExits(objectgroup, data)) return false;
}
else if (name.find("npc") != std::string::npos)
{
if (!readNPCs(objectgroup, data)) return false;
}
else if (name.find("light") != std::string::npos)
{
if (!readLights(objectgroup, data)) return false;
}
else
{
g_logger->logError("MapReader", "Objectgroup with unknown name found in level.");
return false;
}
objectgroup = objectgroup->NextSiblingElement("objectgroup");
}
return true;
}
bool MapReader::readNPCs(XMLElement* objectgroup, MapData& data) const
{
XMLElement* object = objectgroup->FirstChildElement("object");
while (object != nullptr)
{
int id;
XMLError result = object->QueryIntAttribute("id", &id);
XMLCheckResult(result);
int x;
result = object->QueryIntAttribute("x", &x);
XMLCheckResult(result);
int y;
result = object->QueryIntAttribute("y", &y);
XMLCheckResult(result);
NPCBean npc = DEFAULT_NPC;
npc.objectID = id;
npc.position.x = static_cast<float>(x);
npc.position.y = static_cast<float>(y);
// npc properties
XMLElement* properties = object->FirstChildElement("properties");
if (properties != nullptr)
{
XMLElement* _property = properties->FirstChildElement("property");
while (_property != nullptr)
{
const char* textAttr = nullptr;
textAttr = _property->Attribute("name");
if (textAttr == nullptr)
{
g_logger->logError("LevelReader", "XML file could not be read, no objectgroup->object->properties->property->name attribute found.");
return false;
}
std::string attrText = textAttr;
if (attrText.compare("active") == 0)
{
int active;
result = _property->QueryIntAttribute("value", &active);
XMLCheckResult(result);
npc.talksActive = (active != 0);
}
else if (attrText.compare("id") == 0)
{
textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("LevelReader", "XML file could not be read, no objectgroup->object->properties->property->value attribute found.");
return false;
}
npc.id = textAttr;
}
else if (attrText.compare("dialogueid") == 0)
{
textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("LevelReader", "XML file could not be read, no objectgroup->object->properties->property->value attribute found.");
return false;
}
npc.dialogueID = textAttr;
}
else if (attrText.compare("spritetexture") == 0)
{
textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("LevelReader", "XML file could not be read, no objectgroup->object->properties->property->value attribute found.");
return false;
}
std::string tex = textAttr;
size_t pos = 0;
if ((pos = tex.find(",")) == std::string::npos) return false;
npc.texturePosition.left = std::stoi(tex.substr(0, pos));
tex.erase(0, pos + 1);
npc.texturePosition.top = std::stoi(tex);
}
else if (attrText.compare("dialoguetexture") == 0)
{
textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("LevelReader", "XML file could not be read, no objectgroup->object->properties->property->value attribute found.");
return false;
}
std::string tex = textAttr;
size_t pos = 0;
if ((pos = tex.find(",")) == std::string::npos) return false;
npc.dialogueTexturePositon.left = std::stoi(tex.substr(0, pos));
tex.erase(0, pos + 1);
npc.dialogueTexturePositon.top = std::stoi(tex);
}
else if (attrText.compare("boundingbox") == 0)
{
textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("LevelReader", "XML file could not be read, no objectgroup->object->properties->property->value attribute found.");
return false;
}
std::string bb = textAttr;
size_t pos = 0;
if ((pos = bb.find(",")) == std::string::npos) return false;
npc.boundingBox.left = static_cast<float>(std::stoi(bb.substr(0, pos)));
bb.erase(0, pos + 1);
if ((pos = bb.find(",")) == std::string::npos) return false;
npc.boundingBox.top = static_cast<float>(std::stoi(bb.substr(0, pos)));
bb.erase(0, pos + 1);
if ((pos = bb.find(",")) == std::string::npos) return false;
npc.boundingBox.width = static_cast<float>(std::stoi(bb.substr(0, pos)));
bb.erase(0, pos + 1);
npc.boundingBox.height = static_cast<float>(std::stoi(bb));
}
_property = _property->NextSiblingElement("property");
}
}
data.npcs.push_back(npc);
object = object->NextSiblingElement("object");
}
return true;
}
bool MapReader::readBackgroundTileLayer(const std::string& layer, MapData& data) const
{
std::string layerData = layer;
size_t pos = 0;
std::vector<int> backgroundLayer;
while ((pos = layerData.find(",")) != std::string::npos) {
backgroundLayer.push_back(std::stoi(layerData.substr(0, pos)));
layerData.erase(0, pos + 1);
}
backgroundLayer.push_back(std::stoi(layerData));
data.backgroundLayers.push_back(backgroundLayer);
return true;
}
bool MapReader::readCollidableLayer(const std::string& layer, MapData& data) const
{
std::string layerData = layer;
size_t pos = 0;
std::vector<bool> collidableLayer;
while ((pos = layerData.find(",")) != std::string::npos) {
collidableLayer.push_back(std::stoi(layerData.substr(0, pos)) != 0);
layerData.erase(0, pos + 1);
}
collidableLayer.push_back(std::stoi(layerData) != 0);
data.collidableTiles = collidableLayer;
return true;
}
bool MapReader::readForegroundTileLayer(const std::string& layer, MapData& data) const
{
std::string layerData = layer;
size_t pos = 0;
std::vector<int> foregroundLayer;
while ((pos = layerData.find(",")) != std::string::npos) {
foregroundLayer.push_back(std::stoi(layerData.substr(0, pos)));
layerData.erase(0, pos + 1);
}
foregroundLayer.push_back(std::stoi(layerData));
data.foregroundLayers.push_back(foregroundLayer);
return true;
}
bool MapReader::readLayers(XMLElement* map, MapData& data) const
{
XMLElement* layer = map->FirstChildElement("layer");
const char* textAttr;
while (layer != nullptr)
{
textAttr = nullptr;
textAttr = layer->Attribute("name");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no layer->name attribute found.");
return false;
}
std::string name = textAttr;
XMLElement* layerDataNode = layer->FirstChildElement("data");
if (layerDataNode == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no layer->data found.");
return false;
}
std::string layerData = layerDataNode->GetText();
if (name.find("BG") != std::string::npos || name.find("bg") != std::string::npos)
{
if (!readBackgroundTileLayer(layerData, data)) return false;
}
else if (name.find("FG") != std::string::npos || name.find("fg") != std::string::npos)
{
if (!readForegroundTileLayer(layerData, data)) return false;
}
else if (name.find("collidable") != std::string::npos)
{
if (!readCollidableLayer(layerData, data)) return false;
}
else
{
g_logger->logError("MapReader", "Layer with unknown name found in map.");
return false;
}
layer = layer->NextSiblingElement("layer");
}
return true;
}
bool MapReader::readMap(const char* fileName, MapData& data)
{
XMLDocument xmlDoc;
XMLError result = xmlDoc.LoadFile(fileName);
XMLCheckResult(result);
XMLElement* map = xmlDoc.FirstChildElement("map");
if (map == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no map node found.");
return false;
}
if (!readMapProperties(map, data)) return false;
if (!readLayers(map, data)) return false;
if (!readObjects(map, data)) return false;
updateData(data);
if (!checkData(data)) return false;
return true;
}
bool MapReader::readMapName(XMLElement* _property, MapData& data) const
{
// we've found the property "name"
const char* textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no value attribute found (map->properties->property->name=name).");
return false;
}
data.name = textAttr;
return true;
}
bool MapReader::readTilesetPath(XMLElement* _property, MapData& data) const
{
// we've found the property "tilesetpath"
const char* textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no value attribute found (map->properties->property->name=tilesetpath).");
return false;
}
data.tileSetPath = textAttr;
return true;
}
bool MapReader::readMusicPath(XMLElement* _property, MapData& data) const
{
// we've found the property "musicpath"
const char* textAttr = nullptr;
textAttr = _property->Attribute("value");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no value attribute found (map->properties->property->name=musicpath).");
return false;
}
data.musicPath = textAttr;
return true;
}
bool MapReader::readDimming(XMLElement* _property, MapData& data) const
{
// we've found the property "dimming"
float dimming = 0.f;
XMLError result = _property->QueryFloatAttribute("value", &dimming);
XMLCheckResult(result);
if (dimming < 0.0f || dimming > 1.0f)
{
g_logger->logError("LevelReader", "XML file could not be read, dimming value not allowed (only [0,1]).");
return false;
}
data.dimming = dimming;
return true;
}
bool MapReader::readMapProperties(XMLElement* map, MapData& data) const
{
// check if renderorder is correct
const char* textAttr = nullptr;
textAttr = map->Attribute("renderorder");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no renderorder attribute found.");
return false;
}
std::string renderorder = textAttr;
if (renderorder.compare("right-down") != 0)
{
g_logger->logError("MapReader", "XML file could not be read, renderorder is not \"right-down\".");
return false;
}
// check if orientation is correct
textAttr = nullptr;
textAttr = map->Attribute("orientation");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no orientation attribute found.");
return false;
}
std::string orientation = textAttr;
if (orientation.compare("orthogonal") != 0)
{
g_logger->logError("MapReader", "XML file could not be read, renderorder is not \"orthogonal\".");
return false;
}
// read map width and height
XMLError result = map->QueryIntAttribute("width", &data.mapSize.x);
XMLCheckResult(result);
result = map->QueryIntAttribute("height", &data.mapSize.y);
XMLCheckResult(result);
// read tile size
result = map->QueryIntAttribute("tilewidth", &data.tileSize.x);
XMLCheckResult(result);
result = map->QueryIntAttribute("tileheight", &data.tileSize.y);
XMLCheckResult(result);
// read level properties
XMLElement* properties = map->FirstChildElement("properties");
if (properties == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no properties node found.");
return false;
}
XMLElement* _property = properties->FirstChildElement("property");
while (_property != nullptr)
{
textAttr = nullptr;
textAttr = _property->Attribute("name");
if (textAttr == nullptr)
{
g_logger->logError("MapReader", "XML file could not be read, no property->name attribute found.");
return false;
}
std::string name = textAttr;
if (name.compare("name") == 0)
{
if (!readMapName(_property, data)) return false;
}
else if (name.compare("tilesetpath") == 0)
{
if (!readTilesetPath(_property, data)) return false;
}
else if (name.compare("musicpath") == 0)
{
if (!readMusicPath(_property, data)) return false;
}
else if (name.compare("dimming") == 0)
{
if (!readDimming(_property, data)) return false;
}
else
{
g_logger->logError("MapReader", "XML file could not be read, unknown name attribute found in properties (map->properties->property->name).");
return false;
}
_property = _property->NextSiblingElement("property");
}
return true;
}
void MapReader::updateData(MapData& data) const
{
int x = 0;
int y = 0;
vector<bool> xLine;
// calculate collidable tiles
for (std::vector<bool>::iterator it = data.collidableTiles.begin(); it != data.collidableTiles.end(); ++it) {
xLine.push_back((*it));
if (x + 1 >= data.mapSize.x)
{
x = 0;
y++;
data.collidableTileRects.push_back(xLine); // push back creates a copy of that vector.
xLine.clear();
}
else
{
x++;
}
}
// calculate map rect
data.mapRect.left = 0;
data.mapRect.top = 0;
data.mapRect.height = static_cast<float>(data.tileSize.y * data.mapSize.y);
data.mapRect.width = static_cast<float>(data.tileSize.x * data.mapSize.x);
for (auto& it : data.npcs)
{
// why? why does tiled that to our objects?
it.position.y -= data.tileSize.y;
}
} | true |
33cfaf241489e6294963c4e27d3838fd2c9d9062 | C++ | 1148583946/AutoEngine | /AutoEngine/RunTime/Includes/Math/Matrix3x3.cpp | UTF-8 | 2,722 | 2.75 | 3 | [] | no_license | #include "Matrix3x3.h"
MATH_BEGIN
Matrix3x3::Matrix3x3(const Matrix4x4 & other)
{
m_Data[0] = other.m_Data[0];
m_Data[1] = other.m_Data[1];
m_Data[2] = other.m_Data[2];
m_Data[3] = other.m_Data[4];
m_Data[4] = other.m_Data[5];
m_Data[5] = other.m_Data[6];
m_Data[6] = other.m_Data[8];
m_Data[7] = other.m_Data[9];
m_Data[8] = other.m_Data[10];
}
Matrix3x3& Matrix3x3::SetZero()
{
Get(0, 0) = 0.0f; Get(0, 1) = 0.0f; Get(0, 2) = 0.0f;
Get(1, 0) = 0.0f; Get(1, 1) = 0.0f; Get(1, 2) = 0.0f;
Get(2, 0) = 0.0f; Get(2, 1) = 0.0f; Get(2, 2) = 0.0f;
return *this;
}
Matrix3x3& Matrix3x3::SetIdentity()
{
Get(0, 0) = 1.0f; Get(0, 1) = 0.0f; Get(0, 2) = 0.0f;
Get(1, 0) = 0.0f; Get(1, 1) = 1.0f; Get(1, 2) = 0.0f;
Get(2, 0) = 0.0f; Get(2, 1) = 0.0f; Get(2, 2) = 1.0f;
return *this;
}
Matrix3x3 & Matrix3x3::SetOrthoNormalBasis(const Vector3 & inX, const Vector3 & inY, const Vector3 & inZ)
{
Get(0, 0) = inX[0]; Get(0, 1) = inY[0]; Get(0, 2) = inZ[0];
Get(1, 0) = inX[1]; Get(1, 1) = inY[1]; Get(1, 2) = inZ[1];
Get(2, 0) = inX[2]; Get(2, 1) = inY[2]; Get(2, 2) = inZ[2];
return *this;
}
Matrix3x3 & Matrix3x3::SetOrthoNormalBasisInverse(const Vector3 & inX, const Vector3 & inY, const Vector3 & inZ)
{
Get(0, 0) = inX[0]; Get(1, 0) = inY[0]; Get(2, 0) = inZ[0];
Get(0, 1) = inX[1]; Get(1, 1) = inY[1]; Get(2, 1) = inZ[1];
Get(0, 2) = inX[2]; Get(1, 2) = inY[2]; Get(2, 2) = inZ[2];
return *this;
}
Matrix3x3 & Matrix3x3::operator=(const Matrix4x4 & other)
{
m_Data[0] = other.m_Data[0];
m_Data[1] = other.m_Data[1];
m_Data[2] = other.m_Data[2];
m_Data[3] = other.m_Data[4];
m_Data[4] = other.m_Data[5];
m_Data[5] = other.m_Data[6];
m_Data[6] = other.m_Data[8];
m_Data[7] = other.m_Data[9];
m_Data[8] = other.m_Data[10];
return *this;
}
Matrix3x3& Matrix3x3::operator *= (float f)
{
for (int i = 0; i < 9; i++)
m_Data[i] *= f;
return *this;
}
Matrix3x3& Matrix3x3::operator *= (const Matrix3x3& inM)
{
int i;
for (i = 0; i < 3; i++)
{
float v[3] = { Get(i, 0), Get(i, 1), Get(i, 2) };
Get(i, 0) = v[0] * inM.Get(0, 0) + v[1] * inM.Get(1, 0) + v[2] * inM.Get(2, 0);
Get(i, 1) = v[0] * inM.Get(0, 1) + v[1] * inM.Get(1, 1) + v[2] * inM.Get(2, 1);
Get(i, 2) = v[0] * inM.Get(0, 2) + v[1] * inM.Get(1, 2) + v[2] * inM.Get(2, 2);
}
return *this;
}
Matrix3x3& Matrix3x3::operator *= (const Matrix4x4& inM)
{
int i;
for (i = 0; i < 3; i++)
{
float v[3] = { Get(i, 0), Get(i, 1), Get(i, 2) };
Get(i, 0) = v[0] * inM.Get(0, 0) + v[1] * inM.Get(1, 0) + v[2] * inM.Get(2, 0);
Get(i, 1) = v[0] * inM.Get(0, 1) + v[1] * inM.Get(1, 1) + v[2] * inM.Get(2, 1);
Get(i, 2) = v[0] * inM.Get(0, 2) + v[1] * inM.Get(1, 2) + v[2] * inM.Get(2, 2);
}
return *this;
}
MATH_END
| true |
9ab0d25ab841e6911e590b58f0891f5cf1a7d02a | C++ | Argons/LeetCode | /Combination_Sum_II.cpp | UTF-8 | 1,518 | 3.453125 | 3 | [] | no_license | // Given a collection of candidate numbers (C) and a target number (T),
// find all unique combinations in C where the candidate numbers sums to T.
// Each number in C may only be used once in the combination.
// Note:
// All numbers (including target) will be positive integers.
// Elements in a combination (a1, a2, … , ak) must be in non-descending order.
// The solution set must not contain duplicate combinations.
// For example, given candidate set 10,1,2,7,6,1,5 and target 8,
// A solution set is:
// [1, 7]
// [1, 2, 5]
// [2, 6]
// [1, 1, 6]
class Solution {
public:
void sumSets(vector<int> &num, int start, int target,
vector<vector<int> > &result, vector<int> &item) {
if (target == 0) {
result.push_back(item);
return;
}
if (target < 0 || start >= num.size())
return;
item.push_back(num[start]);
sumSets(num, start+1, target-num[start], result, item);
item.pop_back();
while (num[start+1] == num[start])
// if num[start] is invalid, the same num after shall pass as well.
start++;
sumSets(num, start+1, target, result, item);
}
vector<vector<int> > combinationSum2(vector<int> &num, int target)
{
vector<vector<int> > result;
if (num.empty())
return result;
vector<int> item;
sort(num.begin(), num.end());
sumSets(num, 0, target, result, item);
return result;
}
};
| true |
e988cd42f52b2e51cc2c9fddb5f3e03050b861c3 | C++ | chiba-lab/measure-project-mac | /Coordinates.h | UTF-8 | 276 | 2.765625 | 3 | [] | no_license | #pragma once
class Coordinates
{
public:
Coordinates();
Coordinates(int new_x, int new_y);
~Coordinates();
int get_x();
int get_y();
void set_x(int new_x);
void set_y(int new_y);
void set_coords(int new_x, int new_y);
private:
int x;
int y;
};
| true |
597fce76cdda2d29dcf2c9471131a0bb8c5d0cf2 | C++ | verri/uatlib | /test/simple.cpp | UTF-8 | 3,292 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <limits>
#include <stdexcept>
#include <uat/simulation.hpp>
#include <cool/indices.hpp>
#include <jules/array/array.hpp>
#include <jules/base/random.hpp>
#include <random>
#include <variant>
using namespace uat;
class my_agent
{
public:
explicit my_agent(mission_t mission) : mission_{std::move(mission)} {}
auto bid_phase(uint_t t, bid_fn bid, permit_public_status_fn status, int seed)
{
using namespace permit_public_status;
// otherwise, it tries to buy in the next time
if (std::holds_alternative<available>(status(mission_.from, t + 1)) &&
std::holds_alternative<available>(status(mission_.to, t + 2))) {
// note: in a real simulation there would exist intermediate regions
std::mt19937 gen(seed);
const auto price = 1.0 + jules::canon_sample(gen);
bid(mission_.from, t + 1, price);
bid(mission_.to, t + 2, price);
remaining_ = 2;
}
}
auto on_bought(const region&, uint_t, value_t) { --remaining_; }
auto stop(uint_t, int) { return remaining_ == 0; }
private:
mission_t mission_;
uint_t remaining_ = std::numeric_limits<uint_t>::max();
};
// unidimensional space with 10 regions
class my_region
{
public:
explicit my_region(std::size_t pos) : pos_{pos} {}
auto hash() const -> std::size_t { return pos_; }
auto adjacent_regions() const -> std::vector<region>
{
if (pos_ == 0)
return {my_region{pos_ + 1}};
if (pos_ == 9)
return {my_region{pos_ - 1}};
return {my_region{pos_ - 1}, my_region{pos_ + 1}};
}
auto operator==(const my_region& other) const { return pos_ == other.pos_; }
auto distance(const my_region& other) const { return pos_ > other.pos_ ? pos_ - other.pos_ : other.pos_ - pos_; }
private:
std::size_t pos_;
};
class my_airspace
{
public:
auto random_mission(int seed) const -> mission_t
{
std::mt19937 gen(seed);
const auto from = jules::uniform_index_sample(9u, gen);
const auto to = from + 1;
return {my_region{from}, my_region{to}};
}
void iterate(region_fn callback) const
{
for (const auto i : cool::indices(std::size_t{10}))
if (!callback(my_region{i}))
return;
}
};
using atraits = agent_traits<my_agent>;
static_assert(atraits::has_mb_bid_phase);
static_assert(!atraits::has_mb_ask_phase);
static_assert(atraits::has_mb_on_bought);
static_assert(!atraits::has_mb_on_sold);
int main()
{
static constexpr auto n = 100u;
static constexpr auto lambda = 10u;
auto factory = [](uint_t t, const airspace& airspace, int seed) -> std::vector<agent> {
if (t >= n)
return {};
std::mt19937 gen(seed);
std::vector<agent> result;
result.reserve(lambda);
for ([[maybe_unused]] const auto _ : cool::indices(lambda))
result.push_back(my_agent(airspace.random_mission(gen())));
return result;
};
jules::vector<value_t> cost(n * lambda);
simulation_opts_t opts;
opts.trade_callback = [&](trade_info_t info) {
if (info.from != no_owner)
cost[info.from] -= info.value;
cost[info.to] += info.value;
};
simulate(factory, my_airspace{}, 17, opts);
const auto [mean, sd] = jules::meansd(cost);
fmt::print("Average cost: {} ± {}\n", mean, sd);
fmt::print("Cost range: {}, {}\n", jules::min(cost), jules::max(cost));
}
| true |
ec4798c8cae99536906bdd6180b8429eaeb79dc1 | C++ | DogeCoding/Algorithm | /LeetCode/69.cpp | UTF-8 | 466 | 2.515625 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <math.h>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <vector>
#include <stack>
#include <queue>
#include <unordered_map>
using namespace std;
int mySqrt(int x) {
if (x == 0) return 0;
double last=0;
double res=1;
while(res!=last) {
last=res;
res=(res+x/res)/2;
}
return int(res);
}
int main(int argc, char const *argv[]) {
return 0;
} | true |
548247a9b8aad8c3d56d3fbabbaba6029c766277 | C++ | ClickHouse/ClickHouse | /src/Common/Throttler.h | UTF-8 | 2,860 | 2.875 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <Common/Throttler_fwd.h>
#include <Common/ProfileEvents.h>
#include <mutex>
#include <memory>
#include <base/sleep.h>
#include <base/types.h>
#include <atomic>
namespace DB
{
/** Allows you to limit the speed of something (in tokens per second) using sleep.
* Implemented using Token Bucket Throttling algorithm.
* Also allows you to set a limit on the maximum number of tokens. If exceeded, an exception will be thrown.
*/
class Throttler
{
public:
static const size_t default_burst_seconds = 1;
Throttler(size_t max_speed_, size_t max_burst_, const std::shared_ptr<Throttler> & parent_ = nullptr)
: max_speed(max_speed_), max_burst(max_burst_), limit_exceeded_exception_message(""), tokens(max_burst), parent(parent_) {}
explicit Throttler(size_t max_speed_, const std::shared_ptr<Throttler> & parent_ = nullptr);
Throttler(size_t max_speed_, size_t max_burst_, size_t limit_, const char * limit_exceeded_exception_message_,
const std::shared_ptr<Throttler> & parent_ = nullptr)
: max_speed(max_speed_), max_burst(max_burst_), limit(limit_), limit_exceeded_exception_message(limit_exceeded_exception_message_), tokens(max_burst), parent(parent_) {}
Throttler(size_t max_speed_, size_t limit_, const char * limit_exceeded_exception_message_,
const std::shared_ptr<Throttler> & parent_ = nullptr);
/// Use `amount` tokens, sleeps if required or throws exception on limit overflow.
/// Returns duration of sleep in nanoseconds (to distinguish sleeping on different kinds of throttlers for metrics)
UInt64 add(size_t amount);
UInt64 add(size_t amount, ProfileEvents::Event event_amount, ProfileEvents::Event event_sleep_us)
{
UInt64 sleep_ns = add(amount);
ProfileEvents::increment(event_amount, amount);
ProfileEvents::increment(event_sleep_us, sleep_ns / 1000UL);
return sleep_ns;
}
/// Not thread safe
void setParent(const std::shared_ptr<Throttler> & parent_)
{
parent = parent_;
}
/// Reset all throttlers internal stats
void reset();
/// Is throttler already accumulated some sleep time and throttling.
bool isThrottling() const;
private:
size_t count{0};
const size_t max_speed{0}; /// in tokens per second.
const size_t max_burst{0}; /// in tokens.
const UInt64 limit{0}; /// 0 - not limited.
const char * limit_exceeded_exception_message = nullptr;
std::mutex mutex;
std::atomic<UInt64> accumulated_sleep{0}; // Accumulated sleep time over all waiting threads
double tokens{0}; /// Amount of tokens available in token bucket. Updated in `add` method.
UInt64 prev_ns{0}; /// Previous `add` call time (in nanoseconds).
/// Used to implement a hierarchy of throttlers
std::shared_ptr<Throttler> parent;
};
}
| true |
1f88f1051846c6ec2a576d63becf2a2f8dfec880 | C++ | Plypy/Lifestyle | /Rqoj/roundnumber.cpp | GB18030 | 1,369 | 2.953125 | 3 | [] | no_license | // ͳһ
// Ʊʾ0ĸ1ĸĸ
//
#include <iostream>
#include <cstdlib>
using namespace std;
typedef unsigned long long ull;
class Problem
{
private:
static const int MAXN = 35;
ull st, ed;
ull f[MAXN][MAXN];
public:
void init()
{
f[0][0] = 1;
for (int i = 1; i < MAXN; ++i)
{
f[i][0] = 1;
for (int j = 1; j <= i; ++j)
f[i][j] = f[i-1][j-1]+f[i-1][j];
}
}
ull get(ull num)
{
ull dig = 0;
for (ull t = num; t>0; t>>=1)
++dig;
ull ret = 1;
for (int i = dig-1; i>0; --i)
for (int j = 0; j+j+2 <= i; ++j)
ret += f[i-1][j];
ull ct = 0;
for (int i = dig-1; i>=0; --i)
{
if (num & (1ULL<<i))
{
if (ct>0)
{
for (int j = 1; j <= i && j+ct+j+ct <= dig; ++j)
ret += f[i][j];
}
++ct;
if (ct+ct>dig)
break;
++ret;
}
}
return ret;
}
int run()
{
init();
cin >> st >> ed;
cout << get(ed)-get(st-1) << endl;
return 0;
}
} prob;
int main()
{
return prob.run();
}
| true |
55cdf231de89888b55be80513de0e8c374872ee3 | C++ | lulyon/poj-archive | /emperorlu/1256/3092220_WA.cc | UTF-8 | 664 | 2.890625 | 3 | [
"BSD-3-Clause"
] | permissive | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cctype>
using namespace std;
int transfer(char c)
{
if(c<='Z'&&c>='A')
return (c-'A')*2;
else if(c<='z'&&c>='a')
return (c-'A')*2+1;
}
int cmp(char a,char b)
{
int c,d;
c=transfer(a);
d=transfer(b);
return c<b;
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
char s[20],d[20];
scanf("%s",s);
int len=strlen(s);
sort(s,s+len,cmp);
do
{
strcpy(d,s);
printf("%s\n",d);
}
while(next_permutation(s,s+len)&&strcmp(d,s));
}
return 0;
}
| true |
8877bfef61111fc2e3d375c738c1beeb0fc35e0d | C++ | capnemo/distributed-sort | /incl/worker.h | UTF-8 | 1,090 | 2.796875 | 3 | [] | no_license | /***************************************************************************************
FILENAME: worker.h
DESCRIPTION:
Class to run a subTask in an independent thread.
Supervised by an instance of threadPool.
NOTES:
Cannot be copy constructed and cannot be assigned.
***************************************************************************************/
#ifndef WORKER_H
#define WORKER_H
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include "localTypes.h"
class worker {
public:
worker() {}
void addTask(subTask& nextTask);
bool getResult(struct subTask& res);
bool ready();
void terminate();
worker(const worker&) = delete;
worker& operator = (const worker&) = delete;
~worker() = default;
private:
void threadFunc();
private:
std::queue<struct subTask> taskQ;
std::queue<struct subTask> resultsQ;
bool finish = false;
std::thread* exTh = 0;
std::mutex runMtx;
std::condition_variable condVar;
const uint32_t maxInQ = 1;
};
#endif /* WORKER_H */
| true |
aad92c1f67a8c2ce88c05d7c22b54fb8e8ce8329 | C++ | Lord-Aman/GFG | /Programming Languages/SimpleCPP/Name.cpp | UTF-8 | 1,044 | 2.53125 | 3 | [] | no_license | #include <simplecpp>
main_program{
turtleSim();
// A
left(60); wait(0.2);
forward(20); wait(0.2);
repeat(3){
forward(20);
right(120);
wait(0.2);
}
right(60);
penUp();
forward(20);
penDown();
right(60);
forward(20);
// M
penUp();
left(60); wait(0.2);
forward(20);
penDown();
left(90); wait(0.2);
forward(20);
right(135); wait(0.2);
forward(8);
left(90); wait(0.2);
forward(8);
right(135); wait(0.2);
forward(20);
//A
left(90);
penUp();
forward(20);
penDown();
// A
left(60); wait(0.2);
forward(20); wait(0.2);
repeat(3){
forward(20);
right(120);
wait(0.2);
}
right(60);
penUp();
forward(20);
penDown();
right(60);
forward(20);
penUp();
left(60); wait(0.2);
forward(20);
penDown();
left(90);
forward(20);
right(135); wait(0.2);
forward(20);
left(135);
forward(20);
wait(5);
}
| true |
dc3519c7f5d9576794d4fb4d13c3a20f0178b490 | C++ | mcetting/Advanced-Programming-in-C- | /Assignment4/TurnIn/shape.cpp | UTF-8 | 7,444 | 2.546875 | 3 | [] | no_license | // $Id: shape.cpp,v 1.1 2015-07-16 16:47:51-07 - - $
/*
* Name: Michael Ettinger
* ID: mcetting : 1559249
* Email:mcetting@ucsc.edu
* Date: 3/5/2018
*/
#include <typeinfo>
#include <unordered_map>
#include <cmath>
using namespace std;
#include "shape.h"
#include "graphics.h"
#include "util.h"
GLubyte borderColor[3];
GLfloat line_width = 1;
text* zero_to_nine[10];
static unordered_map<void *, string> fontname{
{GLUT_BITMAP_8_BY_13, "Fixed-8x13"},
{GLUT_BITMAP_9_BY_15, "Fixed-9x15"},
{GLUT_BITMAP_HELVETICA_10, "Helvetica-10"},
{GLUT_BITMAP_HELVETICA_12, "Helvetica-12"},
{GLUT_BITMAP_HELVETICA_18, "Helvetica-18"},
{GLUT_BITMAP_TIMES_ROMAN_10, "Times-Roman-10"},
{GLUT_BITMAP_TIMES_ROMAN_24, "Times-Roman-24"},
};
unordered_map<string, void *> fontcode{
{"Fixed-8x13", GLUT_BITMAP_8_BY_13},
{"Fixed-9x15", GLUT_BITMAP_9_BY_15},
{"Helvetica-10", GLUT_BITMAP_HELVETICA_10},
{"Helvetica-12", GLUT_BITMAP_HELVETICA_12},
{"Helvetica-18", GLUT_BITMAP_HELVETICA_18},
{"Times-Roman-10", GLUT_BITMAP_TIMES_ROMAN_10},
{"Times-Roman-24", GLUT_BITMAP_TIMES_ROMAN_24},
};
ostream &operator<<(ostream &out, const vertex &where)
{
out << "(" << where.xpos << "," << where.ypos << ")";
return out;
}
shape::shape()
{
DEBUGF('c', this);
}
text::text(void *glut_bitmap_font, const string &textdata) : glut_bitmap_font(glut_bitmap_font), textdata(textdata)
{
DEBUGF('c', this);
}
ellipse::ellipse(GLfloat width, GLfloat height) : dimension({width, height})
{
DEBUGF('c', this);
}
circle::circle(GLfloat diameter) : ellipse(diameter, diameter)
{
DEBUGF('c', this);
}
polygon::polygon(const vertex_list &vertices) : vertices(vertices)
{
DEBUGF('c', this);
}
rectangle::rectangle(GLfloat width, GLfloat height) : polygon({{-width / 2, height / 2}, {width / 2, height / 2}, {width / 2, -height / 2}, {-width / 2, -height / 2}})
{
DEBUGF('c', this << "(" << width << "," << height << ")");
}
diamond::diamond(GLfloat width, GLfloat height) : polygon({{-width / 2, 0}, {0, height / 2}, {width / 2, 0}, {0, -height / 2}})
{
DEBUGF('c', this << "(" << width << "," << height << ")");
}
triangle::triangle(const vertex_list &v) : polygon(v)
{
}
equilateral::equilateral(GLfloat width) : triangle({{-width / 2, -width / 2}, {0, width / 2}, {width / 2, -width / 2}})
{
DEBUGF('c', this);
}
square::square(GLfloat width) : rectangle(width, width)
{
DEBUGF('c', this);
}
void text::draw(const vertex ¢er, const rgbcolor &color) const
{
DEBUGF('d', this << "(" << center << "," << color << ")");
glColor3ubv(color.ubvec);
glRasterPos2f(center.xpos, center.ypos);
auto u_str = reinterpret_cast<const GLubyte *>(this->textdata.c_str());
glutBitmapString(this->glut_bitmap_font, u_str);
if (this->my_ID == window::selected)
{
// draw a rectangle
string s = this->textdata;
auto x = reinterpret_cast<const GLubyte*> (s.c_str());
size_t width = glutBitmapLength (this->glut_bitmap_font, x);
int height = int(glutBitmapHeight (this->glut_bitmap_font));
rectangle r(width, height);
vertex_list vertices;
vertex v;
v.xpos = 0;
v.ypos = -height / 2;
vertices.push_back(v);
v.xpos = width;
v.ypos = -height / 2;
vertices.push_back(v);
v.xpos = width;
v.ypos = height;
vertices.push_back(v);
v.xpos = 0;
v.ypos = height;
vertices.push_back(v);
// border
glLineWidth(line_width);
glBegin(GL_LINE_LOOP);
glEnable(GL_LINE_SMOOTH);
glColor3ubv(borderColor);
for (unsigned int i = 0; i < 4; ++i)
{
glVertex2f(vertices[i].xpos + center.xpos, vertices[i].ypos + center.ypos);
}
glEnd();
}
}
void ellipse::draw(const vertex ¢er, const rgbcolor &color) const
{
DEBUGF('d', this << "(" << center << "," << color << ")");
// draw the ellipse to the screen?
// the dimensions are saved as part of the object
glBegin(GL_POLYGON);
glEnable(GL_LINE_SMOOTH);
glColor3ubv(color.ubvec);
float scale = 1.0;
const float delta = 2 * M_PI / 32;
float width = this->dimension.xpos / 3 * scale;
float height = this->dimension.ypos / 3 * scale;
for (float theta = 0; theta < 2 * M_PI; theta += delta)
{
float xpos = width * cos(theta) + center.xpos;
float ypos = height * sin(theta) + center.ypos;
glVertex2f(xpos, ypos);
}
glEnd();
if (this->my_ID == window::selected)
{
glLineWidth(line_width);
glBegin(GL_LINE_LOOP);
glEnable(GL_LINE_SMOOTH);
glColor3ubv(borderColor);
float scale = 1.0;
const float delta = 2 * M_PI / 32;
float width = this->dimension.xpos / 3 * scale;
float height = this->dimension.ypos / 3 * scale;
for (float theta = 0; theta < 2 * M_PI; theta += delta)
{
float xpos = width * cos(theta) + center.xpos;
float ypos = height * sin(theta) + center.ypos;
glVertex2f(xpos, ypos);
}
glEnd();
}
if (this->my_ID < 10)
{
rgbcolor gbr;
gbr.ubvec[0] = 255;
gbr.ubvec[1] = 255;
gbr.ubvec[2] = 255;
string s = "0";
auto x = reinterpret_cast<const GLubyte*> (s.c_str());
size_t width = glutBitmapLength (fontcode.find("Times-Roman-24")->second, x);
size_t height = glutBitmapHeight (fontcode.find("Times-Roman-24")->second);
vertex temp;
temp.xpos = center.xpos - width / 2;
temp.ypos = center.ypos - height / 2;
zero_to_nine[this->my_ID]->draw(temp, gbr);
}
}
void polygon::draw(const vertex ¢er, const rgbcolor &color) const
{
DEBUGF('d', this << "(" << center << "," << color << ")");
glBegin(GL_POLYGON);
glEnable(GL_LINE_SMOOTH);
glColor3ubv(color.ubvec);
for (unsigned int i = 0; i < this->vertices.size(); ++i)
{
glVertex2f(this->vertices[i].xpos + center.xpos, this->vertices[i].ypos + center.ypos);
}
glEnd();
if (this->my_ID == window::selected)
{
// border
glLineWidth(line_width);
glBegin(GL_LINE_LOOP);
glEnable(GL_LINE_SMOOTH);
glColor3ubv(borderColor);
for (unsigned int i = 0; i < this->vertices.size(); ++i)
{
glVertex2f(this->vertices[i].xpos + center.xpos, this->vertices[i].ypos + center.ypos);
}
glEnd();
}
if (this->my_ID < 10)
{
rgbcolor gbr;
gbr.ubvec[0] = 255;
gbr.ubvec[1] = 255;
gbr.ubvec[2] = 255;
string s = "0";
auto x = reinterpret_cast<const GLubyte*> (s.c_str());
size_t width = glutBitmapLength (fontcode.find("Times-Roman-24")->second, x);
size_t height = glutBitmapHeight (fontcode.find("Times-Roman-24")->second);
vertex temp;
temp.xpos = center.xpos - width / 2;
temp.ypos = center.ypos - height / 2;
zero_to_nine[this->my_ID]->draw(temp, gbr);
}
}
void shape::show(ostream &out) const
{
out << this << "->" << demangle(*this) << ": ";
}
void text::show(ostream &out) const
{
shape::show(out);
out << glut_bitmap_font << "(" << fontname[glut_bitmap_font]
<< ") \"" << textdata << "\"";
}
void ellipse::show(ostream &out) const
{
shape::show(out);
out << "{" << dimension << "}";
}
void polygon::show(ostream &out) const
{
shape::show(out);
out << "{" << vertices << "}";
}
ostream &operator<<(ostream &out, const shape &obj)
{
obj.show(out);
return out;
}
| true |
6975ac46d5638844518c0038b706550bf16f88b7 | C++ | Ngiong/tcframe | /include/tcframe/spec/core/StyleConfig.hpp | UTF-8 | 1,871 | 3.09375 | 3 | [
"MIT"
] | permissive | #pragma once
#include <tuple>
#include <utility>
using std::move;
using std::tie;
namespace tcframe {
enum class EvaluationStyle {
BATCH,
INTERACTIVE
};
struct StyleConfig {
friend class StyleConfigBuilder;
public:
static const EvaluationStyle DEFAULT_EVALUATION_STYLE = EvaluationStyle::BATCH;
static const bool DEFAULT_NEEDS_OUTPUT = true;
static const bool DEFAULT_NEEDS_CUSTOM_SCORER = false;
private:
EvaluationStyle evaluationStyle_;
bool needsCustomScorer_;
bool needsOutput_;
public:
EvaluationStyle evaluationStyle() const {
return evaluationStyle_;
}
bool needsCustomScorer() const {
return needsCustomScorer_;
}
bool needsOutput() const {
return needsOutput_;
}
bool operator==(const StyleConfig& o) const {
return tie(evaluationStyle_, needsCustomScorer_, needsOutput_)
== tie(o.evaluationStyle_, o.needsCustomScorer_, o.needsOutput_);
}
};
class StyleConfigBuilder {
private:
StyleConfig subject_;
public:
StyleConfigBuilder() {
subject_.evaluationStyle_ = StyleConfig::DEFAULT_EVALUATION_STYLE;
subject_.needsOutput_ = StyleConfig::DEFAULT_NEEDS_OUTPUT;
subject_.needsCustomScorer_ = StyleConfig::DEFAULT_NEEDS_CUSTOM_SCORER;
}
StyleConfigBuilder& BatchEvaluator() {
subject_.evaluationStyle_ = EvaluationStyle::BATCH;
return *this;
}
StyleConfigBuilder& InteractiveEvaluator() {
subject_.evaluationStyle_ = EvaluationStyle::INTERACTIVE;
return *this;
}
StyleConfigBuilder& CustomScorer() {
subject_.needsCustomScorer_ = true;
return *this;
}
StyleConfigBuilder& NoOutput() {
subject_.needsOutput_ = false;
return *this;
}
StyleConfig build() {
return move(subject_);
}
};
}
| true |
d6d21dd02705e7e17503ac05661b16024bebbca7 | C++ | OperDoc/Problems | /trains/#2/A.cpp | UTF-8 | 345 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main() {
int T;
cin >> T;
for(int t = 0; t < T; t++) {
int n, a, b, c, d;
cin >> n >> a >> b >> c >> d;
if(n + 1 <= 2 * (a + b + c + d)) {
cout << "Yes\n";
} else {
cout << "No\n";
}
}
return 0;
} | true |
200bcd1d287b7151d7aac78c7d6dff5627e5a2fc | C++ | Rishis3D/ElasticImplicitSkinning | /include/ScalarField/fieldfunction.h | UTF-8 | 1,526 | 2.609375 | 3 | [] | no_license | #ifndef FIELDFUNCTION_H
#define FIELDFUNCTION_H
#include <glm/glm.hpp>
#include "Hrbf/hrbf_core.h"
#include "Hrbf/hrbf_phi_funcs.h"
#include "ScalarField/field1d.h"
typedef HRBF_fit<float, 3, Rbf_pow3<float> > DistanceField;
class FieldFunction
{
public:
FieldFunction(glm::mat4 _transform = glm::mat4(1.0f));
~FieldFunction();
void Fit(const std::vector<glm::vec3>& points,
const std::vector<glm::vec3>& normals,
const float _r = 1.0f);
/// @brief Method to precompute field values and store them in m_field attribute.
void PrecomputeField();
void SetR(const float _r);
void SetTransform(glm::mat4 _transform);
float Eval(const glm::vec3& x);
float EvalDist(const glm::vec3& x);
glm::vec3 Grad(const glm::vec3& x);
private:
/// @brief Method to remap distance field values to a compactly supported field function [0:1]
/// @param float _distValue value we need to remap to be between [0:1]
/// @return float field value between [0:1]
float Remap(float _df);
glm::vec3 TransformSpace(glm::vec3 _x);
/// @brief Attribute used for remapping distance field to compactly supported field function.
float r;
/// @brief
glm::mat4 m_transform;
/// @brief an HRBF distance field generator
DistanceField m_distanceField;
/// @brief A field object to store precomputed field value,
/// improves performance to interpolate values than compute them.
Field1D m_field;
};
#endif // FIELDFUNCTION_H
| true |
9feaa485e59672c8aea821b877a54b6e225278ee | C++ | sakshamaggarwal/LEETCODE | /Q165.cpp | UTF-8 | 780 | 2.84375 | 3 | [] | no_license | class Solution {
public:
int compareVersion(string version1, string version2) {
int n1=version1.size();
int n2=version2.size();
long int i=0,j=0,a=0,b=0;
while((i<n1)||(j<n2))
{
a=0,b=0;
while((version1[i]!='.')&&(i<n1))
{
a=a*10+(version1[i]-'0');
i++;
}
while((version2[j]!='.')&&(j<n2))
{
b=b*10+(version2[j]-'0');
j++;
}
if(a>b)
return 1;
else if(b>a)
return -1;
if(i<n1)
i++;
if(j<n2)
j++;
}
return 0;
}
};
| true |
e520eebc6b4cb898152203ecc435c3981f23986a | C++ | abagali1/ascent | /src/common/StateFieldRegistry.cpp | UTF-8 | 940 | 3.046875 | 3 | [] | no_license | #include "StateFieldRegistry.hpp"
ReadableStateFieldBase* StateFieldRegistry::find_readable_field(const std::string& name) const{
for(ReadableStateFieldBase* r: this->readable_fields){
if(r->get_name() == name)
return r;
}
return nullptr;
}
WriteableStateFieldBase* StateFieldRegistry::find_writeable_field(const std::string& name) const{
for(WriteableStateFieldBase* w: this->writeable_fields){
if(w->get_name() == name)
return w;
}
return nullptr;
}
bool StateFieldRegistry::add_readable_field(ReadableStateFieldBase* field){
if(find_readable_field(field->get_name()))
return false;
this->readable_fields.push_back(field);
return true;
}
bool StateFieldRegistry::add_writeable_field(WriteableStateFieldBase* field){
if(find_writeable_field(field->get_name()))
return false;
this->writeable_fields.push_back(field);
return true;
}
| true |
72166ebb1e468416404472da84033a89f0c7a41f | C++ | JulianSchroden/InputDevices | /src/Encoder.cpp | UTF-8 | 1,854 | 2.515625 | 3 | [
"MIT"
] | permissive | /**
* Copyright (c) 2019 Julian Schroden. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for
* full license information.
*/
#include <InputDevices/Encoder.h>
using namespace std::chrono;
using namespace SimpleGPIO;
namespace InputDevices
{
Encoder::Encoder(DigitalInputPin encoderAPin, DigitalInputPin encoderBPin)
: encoderAPin_(std::move(encoderAPin))
, encoderBPin_(std::move(encoderBPin))
, lastEncoderPulse_(steady_clock::now())
{
}
void Encoder::onScroll(std::function<void(int)> callback)
{
onScrollCallback_ = callback;
}
void Encoder::update()
{
int currentScrollOffset = 0;
encoderAPin_.poll(
[¤tScrollOffset, this](PinEvent event, DigitalPinState state) {
auto bState = encoderBPin_.state();
if (event == PinEvent::Rise)
{
if (bState == DigitalPinState::High)
{
currentScrollOffset = -1;
}
else
{
currentScrollOffset = 1;
}
}
});
if (currentScrollOffset)
{
steady_clock::time_point currentEncoderPulse = steady_clock::now();
if ((currentEncoderPulse - lastEncoderPulse_) < debounceTime)
{
return;
}
// check if direction changed
if ((currentScrollOffset < 0 && lastScrollOfset_ > 0) ||
(currentScrollOffset > 0 && lastScrollOfset_ < 0))
{
if ((currentEncoderPulse - lastEncoderPulse_) < directionDebounceTime)
{
return;
}
}
onScroll(currentScrollOffset);
lastEncoderPulse_ = currentEncoderPulse;
lastScrollOfset_ = currentScrollOffset;
}
}
void Encoder::onScroll(int distance)
{
if (onScrollCallback_) onScrollCallback_(distance);
}
} // namespace InputDevices | true |
a475e710f374f0902bc5244b124f03a7adbffe4b | C++ | namrataparekar/Complex-Numbers | /Complex.h | UTF-8 | 874 | 2.828125 | 3 | [] | no_license |
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
class Complex{
private:
int r;
int i;
public:
Complex();
Complex(int, int);
void setComplex(int, int);
int getReal() const;
int getImg() const;
/*Operator overloading*/
friend std::ostream& operator << (std::ostream&, const Complex&);
friend std::istream& operator >> (std::istream&, Complex&);
friend Complex operator + (const Complex&, const Complex&);
friend Complex operator - (const Complex&, const Complex&);
friend Complex operator * (const Complex&, const Complex&);
friend Complex operator / (const Complex&, const Complex&);
void operator ~ ();
void operator * ();
void operator = (const Complex&);
void operator = (int);
void display(std::ostream&) const;
};
#endif //COMPLEX_H
| true |
96ebf4c8f4a4c80a387a49e54c0260abe8cd9bbf | C++ | GDxU/mini-fifa | /BackgroundObject.hpp | UTF-8 | 1,277 | 2.671875 | 3 | [] | no_license | #pragma once
#include "Camera.hpp"
#include "Shader.hpp"
#include "ShaderProgram.hpp"
#include "ShaderAttrib.hpp"
#include "Texture.hpp"
#include "Tuple.hpp"
struct BackgroundObject {
gl::ShaderProgram<
gl::VertexShader,
gl::FragmentShader
> program;
gl::VertexArray vao;
gl::Attrib<GL_ARRAY_BUFFER, gl::AttribType::VEC2> attrVertex;
using ShaderAttrib = decltype(attrVertex);
using ShaderProgram = decltype(program);
BackgroundObject():
program({"shaders/bg.vert", "shaders/bg.frag"}),
attrVertex("vertex")
{}
void init() {
ShaderAttrib::init(attrVertex);
attrVertex.allocate<GL_STREAM_DRAW>(6, std::vector<float>{
-1,-1, 1,-1, 1,1,
1,1, -1,1, -1,-1,
});
gl::VertexArray::init(vao);
gl::VertexArray::bind(vao);
vao.enable(attrVertex);
vao.set_access(attrVertex, 0, 0);
gl::VertexArray::unbind();
ShaderProgram::init(program, vao, {"attrVertex"});
}
void display(Camera &cam) {
ShaderProgram::use(program);
gl::VertexArray::bind(vao);
glDrawArrays(GL_TRIANGLES, 0, 6); GLERROR
gl::VertexArray::unbind();
ShaderProgram::unuse();
}
void clear() {
ShaderAttrib::clear(attrVertex);
gl::VertexArray::clear(vao);
ShaderProgram::clear(program);
}
};
| true |
15091a098b899654240fc6ff39de5e0fd0b3ba1a | C++ | Ryeoryeon/Algorithm_study | /ryeoryeon/Baekjoon/15988:1,2,3 더하기 3/main.cpp | UTF-8 | 1,107 | 3.171875 | 3 | [] | no_license | //
// main.cpp
// 1, 2, 3 더하기 (3)
//
// Created by 이영현 on 2021/07/03.
// Copyright © 2021 이영현. All rights reserved.
//
#include <iostream>
using namespace std;
int dividedNum;
int tempSaveFinal = 3; // 마지막으로 저장된 수
unsigned long long int divideMemo[1000001] = {0, };
void divideFunc(int num)
{
if(divideMemo[num] != 0) // 이미 저장되어있는 경우, 바로 출력
cout<<divideMemo[num] % 1000000009<<'\n'; // 개행 빼먹지 말자 ^^..
else
{
for(int i = tempSaveFinal + 1; i <= num;++i)
{
divideMemo[i] = (divideMemo[i - 1] + divideMemo[i - 2] + divideMemo[i - 3]);
divideMemo[i] %= 1000000009;
}
tempSaveFinal = num;
cout<<divideMemo[num] % 1000000009 <<'\n';
}
}
int main(int argc, const char * argv[]) {
int testCase;
cin>>testCase;
divideMemo[1] = 1;
divideMemo[2] = 2;
divideMemo[3] = 4;
for(int i = 0; i < testCase; ++i)
{
cin>>dividedNum;
divideFunc(dividedNum);
}
return 0;
}
| true |
63030097c14afd99faa1d601b6bb164bd0596487 | C++ | mortennobel/kick | /src/kick/math/ray.h | UTF-8 | 884 | 2.78125 | 3 | [] | no_license | //
// ray.h
// KickCPP
//
// Created by Morten Nobel-Jørgensen on 18/12/13.
// Copyright (c) 2013 Morten Nobel-Joergensen. All rights reserved.
//
#pragma once
#include "glm/glm.hpp"
namespace kick {
class Ray {
public:
Ray();
Ray(glm::vec3 origin, glm::vec3 direction);
bool closestPoints(Ray otherRay, glm::vec3& outPoint1, glm::vec3& outPoint2) const;
glm::vec3 closestPoint(glm::vec3 point) const;
bool intersectTriangle(glm::vec3 v0, glm::vec3 v1, glm::vec3 v2, glm::vec3 &intersectionPoint, bool clampBackIntersections = true) const;
glm::vec3 const &origin() const;
void setOrigin(glm::vec3 const &origin);
glm::vec3 const &direction() const;
void setDirection(glm::vec3 const &direction);
glm::vec3 point(float offset) const;
private:
glm::vec3 mOrigin;
glm::vec3 mDirection;
};
} | true |
340407ff368e5d9b839c6961cf0c1b6d112e1d72 | C++ | R-penguins/ICPC-Live-Archive-Solutions | /7952gen.cpp | UTF-8 | 546 | 2.546875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
int main()
{
default_random_engine e(time(0));
uniform_int_distribution<int> nGen(1, 2000);
uniform_int_distribution<long long> numGen(10000000000000000, 1000000000000000000);
for (int i = 0; i < 100; ++i)
{
int n = nGen(e);
cout << n << "\n";
while (n--)
{
long long x1 = numGen(e);
uniform_int_distribution<long long> numGen2(x1, 1000000000000000000);
cout << x1 << " " << numGen2(e) << "\n";
}
}
} | true |
b7da5168035085647e7963a33fc215a2a00fe642 | C++ | HarrisonHesslink/Harrisons-College-Programs | /tempchanger.cpp | UTF-8 | 1,993 | 4.0625 | 4 | [] | no_license | /*
Program: Change temp from either C to F or F to C
Author: Harrison Hesslink
Date: Jan 9, 2019
Description: Made this in class from the "program" design example.
*/
#include <iostream>
#include <string>
double convertToF(double temp){
return (temp * 1.8)+ 32;
}
double convertToC(double temp){
return (temp - 32) * 1.8;
}
double convertCToK(double temp){
return (temp + 273.15);
}
double convertFToK(double temp){
return convertToC(temp) + 273.15;
}
double convertKToC(double temp){
return (temp - 273.15);
}
double convertKToF(double temp){
return convertToF(temp + 273.15);
}
int main()
{
std::string temp;
std::string type;
std::string type2;
std::cout << "Enter Temp: ";
getline (std::cin, temp);
std::cout << "Enter Type (C or F or K): ";
getline (std::cin, type);
std::cout << "Enter Return Type (C or F or K): ";
getline (std::cin, type2);
if(type == "C"){
if(type2 == "F"){
double convertedTemp = convertToF(std::stoi(temp));
std::cout << "Converted Temp (F): " << convertedTemp << "F";
}else if(type2 == "K"){
double convertedTemp = convertCToK(std::stoi(temp));
std::cout << "Converted Temp (K): " << convertedTemp << "K";
}
}else if(type == "F"){
if(type2 == "C"){
double convertedTemp = convertToC(std::stoi(temp));
std::cout << "Converted Temp (C): " << convertedTemp << "C";
}else if(type2 == "K"){
double convertedTemp = convertFToK(std::stoi(temp));
std::cout << "Converted Temp (K): " << convertedTemp << "K";
}
}else if(type == "K"){
if(type2 == "F"){
double convertedTemp = convertKToF(std::stoi(temp));
std::cout << "Converted Temp (F): " << convertedTemp << "F";
}else if(type2 == "F"){
double convertedTemp = convertKToC(std::stoi(temp));
std::cout << "Converted Temp (C): " << convertedTemp << "C";
}
}else{
std::cout << "Not supported Temp Type";
}
return 0;
}
| true |
cc48cbbd467f6d66f22b04f25b63baadf36e6faa | C++ | dramenti/jayscript | /jaytools.cpp | UTF-8 | 5,724 | 3.265625 | 3 | [] | no_license | #include "globals.h"
#include<string>
#include<exception>
#include<cstdlib>
#include<iostream>
#include "jaytools.h"
#define ASCII_SHIFT 48
//48 to 57 inclusive is the range of digits in ASCII
bool is_num(std::string s)
{
int i = 0;
if (s.at(i) == '-' && s.size() > 1) i++;
int first_char = (int)s.at(i);
if (first_char >= 48 && first_char <= 57) //check if is a digit
{
return true;
}
return false; //not a digit
}
bool is_var_int(std::string s)
{
if (var_ints.count(s))
{
return true;
}
return false; //not in map
}
bool is_var_string(std::string s)
{
if (var_strings.count(s))
{
return true;
}
return false;
}
int convert_string_to_int(std::string s)
{
int converted = 0; //will contain the final integer representation of s
int size = s.size();
int multiplier = 1; //goes up by factor of 10 every time
int dig; //stores each character, which is a digit
int endpoint = 0;
int negativizer = 1;
if (s.at(0) == '-') //deals with negative numbers
{
endpoint = 1;
negativizer = -1;
}
for (int i = size-1; i >= endpoint; i--)
{
dig = (int)s.at(i)-ASCII_SHIFT;
converted += dig*multiplier;
multiplier *= 10;
}
return (converted*negativizer);
}
std::string convert_int_to_string(int num)
{
if (num == 0) return "0";
std::string str_int;
if (num < 0)
{
str_int = "-"; //dat negative sign tho
num *= -1;
}
else
{
str_int = "";
}
//at this point, num contains a positive integer
int divider = 1;
while (num/divider > 0)
{
divider *= 10;
}
divider /= 10; //when while loop breaks, divider will be too big, go back to last "good run"
//std::cout << "in convert_int_to_string, number of digits, or divider value is " << divider << std::endl;
int next_digit;
//digit stripper
while (divider >= 1)
{
next_digit = num/divider;
str_int += (char)(next_digit+ASCII_SHIFT);
num = num-divider*next_digit;
divider /= 10;
}
//std::cout << "in convert_int_to_string, final string representation is " << str_int << std::endl;
return str_int;
}
bool is_OpChar(char c)
{
switch(c)
{
case '+':
return true;
break;
case '-':
return true;
break;
case '*':
return true;
break;
case '/':
return true;
break;
case '%':
return true;
break;
case '=':
return true;
break;
case '<':
return true;
break;
case '>':
return true;
break;
case '!':
return true;
break;
default:
return false;
break;
}
}
bool in_int_range(int x)
{
return (x >= 48 && x <= 57);
}
bool in_upcase_range(int x)
{
return (x >= 65 && x <= 90);
}
bool in_lowcase_range(int x)
{
return (x >= 97 && x <= 122);
}
//unicode [48, 57]U[65,90]U[97, 122]
bool is_IdentifierChar(char c)
{
int ic = (int)c;
if (in_int_range(ic) || in_upcase_range(ic) || in_lowcase_range(ic))
{
return true;
}
return false;
}
bool is_Valid_Identifier(std::string id)
{
//int ids = id.size(); //size of potential identifier
int c1 = (int)(id.at(0)); //used to check if starts with digit
//if c1 is a digit, return false: cannot start with a digit
if (in_int_range(c1)) //if is int, return false
{
return false;
}
//else, check all of chars... if all chars are id chars, return true
unsigned index = 0;
while (index < id.size())
{
if (!is_IdentifierChar(id.at(index)))
{
return false;
}
index++;
}
return true;
}
void trim_tail(std::string& s)
{
int index = s.size()-1;
while (index >= 0)
{
if (s.at(index) == ' ' || s.at(index) == '\t')
{
index--;
}
else
{
break;
}
}
//loop has broken: index is now location of last nonspace character
//the substring from 0 to index is our final result
//substring argument is (0, length)
//length = index+1
s = s.substr(0, index+1);
}
//returns whether the line begins with lvl number of tabs or soft tabs
bool begins_with_tab(const std::string& s, int lvl)
{
const std::string SOFT = " "; //FOUR SPACES AKA SOFT TAB
const char HARD = '\t'; //TABSPACE
try
{
bool yesbegin = false;
int k = 0;
while (k < lvl)
{
yesbegin = true; //so far it looks ok...
if (s.at(k) != HARD) //not a hard tab...
{
yesbegin = false; //so false for now
break; //exit
}
k++;
}
if (yesbegin) return yesbegin; //if we didn't break, return true
//now do soft check
k = 0;
while (k < lvl)
{
yesbegin = true;
if (s.substr(4*k, 4) != SOFT)
{
yesbegin = false;
break;
}
k++;
}
return yesbegin;
}
catch (std::exception& e)
{
return false;
}
}
void decomment(std::string& s)
{
//removes everything after, and including, the # character
//in other words, # is the inline comment character
char comment_character = '#';
unsigned i = 0;
while (i < s.size() && s.at(i) != comment_character)
{
i++;
}
s = s.substr(0, i);
} | true |
43f3c76bd4a8260bbcd801f59baa1e505fa3cafe | C++ | AAAmer91/Evaluator_Stack | /Stack_Class.h | UTF-8 | 392 | 3.5 | 4 | [] | no_license | // A class to represent a stack
#include <iostream>
#include <string>
struct node
{
int data;
struct node *next;
};
// Creating a class STACK
class stack
{
struct node *ptop;
public:
stack() // constructor
{
ptop = NULL;
}
void push(int data); // to insert an element
int pop(); // to delete an element
int top(); // to show the stack
int isEmpty();
}; | true |
61883dbb8b4572d6af0fbb00679a542782de9b37 | C++ | anagorko/zpk2015 | /grupa3/monikao/p2/duz.cpp | UTF-8 | 1,252 | 3.296875 | 3 | [] | no_license | #include <iostream>
using namespace std;
void porownaj(int s1, int s2, string znak, bool &prawda, bool &koniec)
{
if(s1 > s2){
koniec = true;
if(znak == ">" || znak == ">=" || znak == "!=")
prawda = true;
else
prawda = false;
}
if(s1 < s2){
koniec = true;
if(znak == "<" || znak == "<=" || znak == "!=")
prawda = true;
else
prawda = false;
}
}
int main() {
string liczba1;
string liczba2;
string znak;
bool koniec = false;
bool prawda;
cin >> liczba1;
cin >> znak;
cin >> liczba2;
int l1 = liczba1.length();
int l2 = liczba2.length();
int i = 0;
if( l1 != l2){
porownaj(l1, l2, znak, prawda, koniec);
}
else{
while(i < l1 & !koniec){
int s1 = liczba1[i] - 48;
int s2 = liczba2[i] - 48;
porownaj(s1, s2, znak, prawda, koniec);
i++;
}
if(!koniec & (znak == "<=" || znak == ">=" || znak == "=="))
prawda = true;
}
if(prawda)
cout << "TAK" << endl;
else
cout << "NIE" << endl;
}
| true |
1eb8a261475cab8abf3e18b720188cde621c4fcf | C++ | fwsGonzo/LiveUpdate | /liveupdate.hpp | UTF-8 | 8,481 | 2.953125 | 3 | [] | no_license | /**
* Master thesis
* by Alf-Andre Walla 2016-2017
*
**/
#pragma once
#ifndef LIVEUPDATE_HEADER_HPP
#define LIVEUPDATE_HEADER_HPP
#include <net/tcp/connection.hpp>
#include <delegate>
#include <string>
#include <vector>
struct storage_entry;
struct storage_header;
namespace liu
{
struct Storage;
struct Restore;
typedef std::vector<char> buffer_t;
/**
* The beginning and the end of the LiveUpdate process is the begin() and resume() functions.
* begin() is called with a provided fixed memory location for where to store all serialized data,
* and after an update is_resumable, with the same fixed memory location, will return true.
* resume() can then be called with this same location, and it will call handlers for each @id it finds,
* unless no such handler is registered, in which case it just calls the default handler which is passed
* to the call to resume(). The call to resume returns true if everything went well.
**/
struct LiveUpdate
{
// The buffer_t parameter is the update blob (the new kernel) and can be null.
// If the parameter is null, you can assume that it's currently not a live update.
typedef delegate<void(Storage&, const buffer_t*)> storage_func;
typedef delegate<void(Restore&)> resume_func;
// Start a live update process, storing all user-defined data
// at @location, which can then be resumed by the future service after update
static void begin(void* location, buffer_t blob, storage_func = nullptr);
// In the event that LiveUpdate::begin() fails,
// call this function in the C++ exception handler:
static void restore_environment();
// Only store user data, as if there was a live update process
// Throws exception if process or sanity checks fail
static size_t store(void* location, storage_func);
// Returns true if there is stored data from before at @location.
// It performs an extensive validation process to make sure the data is
// complete and consistent
static bool is_resumable(void* location);
// Register a user-defined handler for what to do with @id from storage
static void on_resume(uint16_t id, resume_func custom_handler);
// Attempt to restore existing stored entries from fixed location.
// Returns false if there was nothing there. or if the process failed
// to be sure that only failure can return false, use is_resumable first
static bool resume(void* location, resume_func default_handler);
// When explicitly resuming from heap, heap overrun checks are disabled
static bool resume_from_heap(void* location, resume_func default_handler);
// Retrieve the recorded length, in bytes, of a valid storage area
// Throws std::runtime_error when something bad happens
// Never returns zero
static size_t stored_data_length(void* location);
// Set location of known good blob to rollback to if something happens
static void set_rollback_blob(const void*, size_t) noexcept;
// Returns true if a backup rollback blob has been set
static bool has_rollback_blob() noexcept;
// Immediately start a rollback, not saving any state other than
// performing a soft-reset to reduce downtime to a minimum
// Never returns, and upon failure intentionally hard-resets the OS
static void rollback_now(const char* reason);
};
////////////////////////////////////////////////////////////////////////////////
// IMPORTANT:
// Calls to resume can fail even if is_resumable validates everything correctly.
// this is because when the user restores all the saved data, it could grow into
// the storage area used by liveupdate, if enough data is stored, and corrupt it.
// All failures are of type std::runtime_error. Make sure to give VM enough RAM!
////////////////////////////////////////////////////////////////////////////////
/**
* The Storage object is passed to the user from the handler given to the
* call to begin(), starting the liveupdate process. When the handler is
* called the system is ready to serialize data into the given @location.
* By using the various add_* functions, the user stores data with @uid
* as a marker to be able to recognize the object when restoring data.
* IDs don't have to have specific values, and the user is free to use any value.
*
* When using the add() function, the type cannot be verified on the other side,
* simply because type_info isn't guaranteed to work across updates. A new update
* could have been compiled with a different compiler.
*
**/
struct Storage
{
typedef net::tcp::Connection_ptr Connection_ptr;
typedef uint16_t uid;
template <typename T>
inline void add(uid, const T& type);
// storing as int saves some storage space compared to all the other types
void add_int (uid, int value);
void add_string(uid, const std::string&);
void add_buffer(uid, const buffer_t&);
void add_buffer(uid, const void*, size_t length);
// store vectors of PODs or std::string
template <typename T>
inline void add_vector(uid, const std::vector<T>& vector);
// store a TCP connection
void add_connection(uid, Connection_ptr);
Storage(storage_header& sh) : hdr(sh) {}
void add_vector (uid, const void*, size_t count, size_t element_size);
void add_string_vector (uid, const std::vector<std::string>&);
// markers are used to delineate the end of variable-length structures
void put_marker(uid);
private:
storage_header& hdr;
};
/**
* A Restore object is given to the user by restore handlers,
* during the resume() process. The user should know what type
* each id is, and call the correct as_* function. The object
* will still be validated, and an error is thrown if there was
* a type mismatch in most cases.
*
* It's possible to restore many objects from the same handler by
* using go_next(). In that way, a user can restore complicated objects
* completely without leaving the handler. go_next() will throw if there
* is no next object to go to.
*
**/
struct Restore
{
typedef net::tcp::Connection_ptr Connection_ptr;
bool is_end() const noexcept;
bool is_int() const noexcept;
bool is_marker() const noexcept;
int as_int() const;
std::string as_string() const;
buffer_t as_buffer() const;
Connection_ptr as_tcp_connection(net::TCP&) const;
template <typename S>
inline const S& as_type() const;
template <typename T>
inline std::vector<T> as_vector() const;
int16_t get_type() const noexcept;
uint16_t get_id() const noexcept;
int length() const noexcept;
const void* data() const noexcept;
uint16_t next_id() const noexcept;
// go to the next storage entry
void go_next();
// go *past* the first marker found (or end reached)
// if a marker is found, the markers id is returned
// if the end is reached, 0 is returned
uint16_t pop_marker();
// go *past* the first marker found (or end reached)
// if a marker is found, verify that @id matches
// if the end is reached, @id is not used
void pop_marker(uint16_t id);
// cancel and exit state restoration process
// NOTE: resume() will still return true
void cancel(); // pseudo: "while (!is_end()) go_next()"
// NOTE:
// it is safe to immediately use is_end() after any call to:
// go_next(), pop_marker(), pop_marker(uint16_t), cancel()
Restore(storage_entry*& ptr) : ent(ptr) {}
Restore(const Restore&);
private:
const void* get_segment(size_t, size_t&) const;
std::vector<std::string> rebuild_string_vector() const;
storage_entry*& ent;
};
/// various inline functions
template <typename S>
inline const S& Restore::as_type() const {
if (sizeof(S) != length()) {
throw std::runtime_error("Mismatching length for id " + std::to_string(get_id()));
}
return *reinterpret_cast<const S*> (data());
}
template <typename T>
inline std::vector<T> Restore::as_vector() const
{
size_t count = 0;
auto* first = (T*) get_segment(sizeof(T), count);
return std::vector<T> (first, first + count);
}
template <>
inline std::vector<std::string> Restore::as_vector() const
{
return rebuild_string_vector();
}
template <typename T>
inline void Storage::add(uid id, const T& thing)
{
add_buffer(id, &thing, sizeof(T));
}
template <typename T>
inline void Storage::add_vector(uid id, const std::vector<T>& vector)
{
add_vector(id, vector.data(), vector.size(), sizeof(T));
}
template <>
inline void Storage::add_vector(uid id, const std::vector<std::string>& vector)
{
add_string_vector(id, vector);
}
} // liu
#endif
| true |
b898db66a3fde84d6a2f4e43c5014c3fcaf2d2c2 | C++ | TakuyaKimura/Leetcode | /136 Single Number/136.cpp | UTF-8 | 777 | 3.546875 | 4 | [] | no_license | /*
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
*/
#include <unordered_set>
using namespace std;
// O(1) space, bit manipulation
class Solution2 {
public:
int singleNumber(vector<int>& nums) {
int x = 0;
for (auto num : nums)
x ^= num;
return x;
}
};
// O(n) extra space
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_set<int> set;
for (auto& num : nums)
if (set.find(num) == set.end())
set.insert(num);
else
set.erase(num);
return *set.begin();
}
}; | true |
741e5aa0b1f2abe002cb00442c83b736ee217f20 | C++ | ydykid/leetcode_cpp | /2021m9/17.2.minOperations.cpp | UTF-8 | 551 | 3 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
int minOperations(vector<string>& logs) {
int ans = 0;
for (int i=0; i<logs.size(); i++) {
if (logs[i][0]=='.'&&logs[i][1]=='.') {
if (ans>0){ans--;}
}else if (logs[i][0]!='.'){
ans++;
}
}
return ans;
}
};
int main() {
vector<string> qs1 = vector<string>();
qs1.push_back("d1/");
qs1.push_back("d2/");
Solution sol = Solution();
printf("ans:%d\n", sol.minOperations(qs1));
return 0;
} | true |
be6d664e143bd0994553df394a2f05eb970914ac | C++ | marcelsan/PathTracer | /src/light.h | UTF-8 | 1,212 | 2.953125 | 3 | [] | no_license | #ifndef LIGHT_H
#define LIGHT_H
#include <glm/glm.hpp>
#include "color.h"
using namespace glm;
namespace PathTrace {
class Object;
class Light
{
public:
Light(bool d = false, float ip = 1.0f, Object* o = nullptr) : directional(d), ip(ip), obj(o) { }
virtual ~Light() = default;
bool directional;
float ip;
Object* object() const { return obj; }
virtual vec3 direction() const = 0;
virtual color emissionColor() const = 0;
virtual vec3 samplePosition() const;
private:
Object* obj;
};
class SingleColorLight : public Light
{
private:
color cl;
public:
SingleColorLight(Object* o = nullptr, color c = {}, float ip = 1.0f)
: Light(false, ip, o)
, cl(c)
{ }
vec3 direction() const { return {}; }
virtual ~SingleColorLight() = default;
protected:
color emissionColor() const override { return cl; }
};
class DirectionalLight : public Light
{
public:
DirectionalLight(vec3 d, float ip)
: Light(true, ip)
, dir(d)
{ }
vec3 dir;
vec3 samplePosition() const { return {}; }
vec3 direction() const { return dir; }
color emissionColor() const override { return {1.0f, 1.0f, 1.0f}; }
};
}
#endif | true |
11ccf92a37cca9a6a048080c0e906f28d6b22971 | C++ | electro1rage/OJProblemsCodes | /Problem Storage/Dynamic Programming/Masks/2013-2014_neerc_Moscow_B_BlackList.cpp | UTF-8 | 1,466 | 2.78125 | 3 | [] | no_license | /*
reality, be rent!
synapse, break!
Van!shment Th!s World !!
*/
#include <bits/stdc++.h>
using namespace std;
#define EQL 0
#define LESS 1
#define MORE 2
const int MN = 22;
char s[MN];
int a[MN], ans[MN];
int memo[MN][1 << 16][3];
string d = "0123456789ABCDEF";
int get_cmp(int a, int b, int cmp) {
if (cmp != EQL) return cmp;
if (a > b) return LESS;
if (a == b) return EQL;
return MORE;
}
bool get_next(int i, int mask, int cmp) {
if (cmp == LESS) return false;
if (i == MN) return cmp == MORE;
int &ret = memo[i][mask][cmp], j;
if (ret == -1) {
ret = false;
for (j = 0; j < 16; ++j) {
if ((mask >> j) & 1) continue;
if (get_next(i + 1, mask | (1 << j), get_cmp(a[i], j, cmp))) return ret = true;
}
}
return ret;
}
void get_ans(int i, int mask, int cmp) {
if (i == MN) return ;
int j;
for (j = 0; j < 16; ++j) {
if ((mask >> j) & 1) continue;
if (get_next(i + 1, mask | (1 << j), get_cmp(a[i], j, cmp))) {
ans[i] = j;
get_ans(i + 1, mask | (1 << j), get_cmp(a[i], j, cmp));
return ;
}
}
}
int get_num(char c) {
int i;
for (i = 0; i < 16; ++i) if (d[i] == c) return i;
}
int main() {
scanf("%s", s);
int n = strlen(s), i, j;
for (i = n - 1, j = MN - 1; i >= 0; --i, --j) a[j] = get_num(s[i]);
for (i = MN - n; i >= 0; --i) {
memset(memo, -1, sizeof memo);
if (get_next(i, 0, EQL)) {
get_ans(i, 0, EQL);
for (j = i; j < MN; ++j) cout << d[ans[j]];cout << endl;
return 0;
}
}
return 0;
}
| true |
0fb58c32350986f359cb0d0c013cb0f8fa0db7bf | C++ | hdhyy/thrust_offer | /src/test36.hpp | UTF-8 | 1,273 | 3.296875 | 3 | [
"MIT"
] | permissive | #include <bits/stdc++.h>
using namespace std;
/**
* 输入两个链表,找出它们的第一个公共结点。
*
**/
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution
{
public:
ListNode *FindFirstCommonNode(ListNode *pHead1, ListNode *pHead2)
{
int len1 = 0, len2 = 0;
auto np1 = pHead1, np2 = pHead2;
if(np1 == nullptr || np2 == nullptr)
return nullptr;
while (np1 != nullptr)
{
np1 = np1->next;
++len1;
}
while (np2 != nullptr)
{
np2 = np2->next;
++len2;
}
int x = abs(len1 - len2);
np1 = pHead1;
np2 = pHead2;
if(len1 > len2)
{
for (int i = 0; i < x; i++)
{
np1 = np1->next;
}
}
else if(len1 < len2)
{
for (int i = 0; i < x; i++)
{
np2 = np2->next;
}
}
while (np1 != np2 && np1 != nullptr && np2 != nullptr)
{
np1 = np1->next;
np2 = np2->next;
}
return (np1 == nullptr || np2 == nullptr) ? nullptr : np1;
}
}; | true |
c533441dc54a502d0b60a9b7b2df42a1f7fb746c | C++ | DanylAnikushyn/pseudo3d_game | /weapon_manager.cpp | UTF-8 | 1,105 | 2.875 | 3 | [] | no_license | #include "weapon_manager.h"
#include "appconfig.h"
std::vector<std::string> WeaponManager::pathes_to_weapons = {
"textures/weapon.png"
};
WeaponManager* WeaponManager::instance = nullptr;
WeaponManager::WeaponManager(SDL_Renderer* renderer)
{
for (int i = 0; i < pathes_to_weapons.size(); ++i)
{
weapons.push_back(IMG_LoadTexture(renderer, pathes_to_weapons.at(i).c_str())); // can be error, nullptr will be pushed into vector
}
}
WeaponManager::~WeaponManager()
{
for (int i = 0; i < pathes_to_weapons.size(); ++i)
{
SDL_DestroyTexture(weapons.at(i));
}
}
WeaponManager* WeaponManager::get(SDL_Renderer *renderer)
{
if (!instance)
{
instance = new WeaponManager(renderer);
}
return instance;
}
void WeaponManager::destroy()
{
delete instance;
instance = nullptr;
}
void WeaponManager::drawWeapon(SDL_Renderer* renderer, WeaponType type) const
{
SDL_Rect from;
from.w = 1157; from.h = 495; from.x = 0; from.y = 0;
SDL_Rect to;
to.w = 900; to.h = 400; to.x = 300; to.y = AppConfig::windows_rect.h - to.h + 100;
SDL_RenderCopy(renderer, weapons.at((int)type), &from, &to);
} | true |
1b3558da523b04ddf2954e1ec2dc3a9d4e3b9771 | C++ | JeffersonLab/QwAnalysis | /Tracking/src/QwHitContainer.cc | UTF-8 | 3,288 | 2.71875 | 3 | [] | no_license | #include "QwHitContainer.h"
ClassImp(QwHitContainer)
#include <boost/bind.hpp>
static struct logical_not_s{
bool operator()(bool a){return !a;};
} logical_not_;
// Iterator methods to obtain subsets of QwHitContainer elements - rakitha (08/2008)
QwHitContainer::iterator QwHitContainer::GetStartOfHits (
EQwRegionID region,
EQwDetectorPackage package,
EQwDirectionID direction)
{
return find_if (begin(), end(),
boost::bind(&QwHit::DirMatches, _1,
boost::ref(region),
boost::ref(package),
boost::ref(direction)));
}
QwHitContainer::iterator QwHitContainer::GetEndOfHits (
EQwRegionID region,
EQwDetectorPackage package,
EQwDirectionID direction)
{
iterator first = GetStartOfHits(region, package, direction);
return find_if (first, end(),
boost::bind<bool>(logical_not_,
boost::bind(&QwHit::DirMatches, _1,
boost::ref(region),
boost::ref(package),
boost::ref(direction))));
}
QwHitContainer::iterator QwHitContainer::GetStartOfHits1 (
EQwRegionID region,
EQwDetectorPackage package,
Int_t plane)
{
return find_if (begin(), end(),
boost::bind(&QwHit::PlaneMatches, _1,
boost::ref(region),
boost::ref(package),
boost::ref(plane)));
}
QwHitContainer::iterator QwHitContainer::GetEndOfHits1 (
EQwRegionID region,
EQwDetectorPackage package,
Int_t plane)
{
iterator first = GetStartOfHits1(region, package, plane);
return find_if (first, end(),
boost::bind<bool>(logical_not_,
boost::bind(&QwHit::PlaneMatches, _1,
boost::ref(region),
boost::ref(package),
boost::ref(plane))));
}
void QwHitContainer::GetSubList_Dir(EQwRegionID region, EQwDetectorPackage package, EQwDirectionID direction, std::vector<QwHit> & sublist) {
iterator p;
for (p=GetStartOfHits(region,package,direction);p !=GetEndOfHits(region,package,direction);p++){
sublist.push_back(*p);
}
}
void QwHitContainer::GetSubList_Plane(EQwRegionID region, EQwDetectorPackage package, Int_t plane, std::vector<QwHit> & sublist) {
iterator p;
for (p=GetStartOfHits1(region,package,plane);p !=GetEndOfHits1(region,package,plane);p++){
sublist.push_back(*p);
}
}
// Return the sublist of hits only in specified package, region, and detector plane
QwHitContainer* QwHitContainer::GetSubList_Plane (EQwRegionID region, EQwDetectorPackage package, Int_t plane) {
QwHitContainer* sublist = new QwHitContainer;
for (iterator hit = begin(); hit != end(); hit++)
if (hit->PlaneMatches(region, package, plane))
sublist->push_back(*hit);
return sublist;
}
// Return the sublist of hits only in specified package, region, and detector plane
QwHitContainer* QwHitContainer::GetSubList_Dir (EQwRegionID region, EQwDetectorPackage package, EQwDirectionID dir) {
QwHitContainer* sublist = new QwHitContainer;
for (iterator hit = begin(); hit != end(); hit++)
if (hit->DirMatches(region, package, dir))
sublist->push_back(*hit);
return sublist;
}
void QwHitContainer::Print (const Option_t* option) const
{
if (! this) return;
std::cout << *this << std::endl;
}
std::ostream& operator<< (std::ostream& stream, const QwHitContainer& hitlist)
{
for (QwHitContainer::const_iterator hit = hitlist.begin(); hit != hitlist.end(); hit++)
stream << *hit << std::endl;
return stream;
}
| true |
df351b87227d8cb48f79481a2468dfec2b1f10c0 | C++ | daria-kulikova/base-data-structures | /labs/tests/dynamic_array_test.cpp | UTF-8 | 2,763 | 3.84375 | 4 | [] | no_license | #include <dynamic_array/dynamic_array.h>
#include <exception>
#include <iostream>
#include <sstream>
int main() {
DynamicArray a_def;
std::cout << "Let's create default array. Array is " << a_def << std::endl;
std::cout << "Size is " << a_def.Size() << std::endl;
std::cout << "Let's try to create array0 where size = -2. -> " << std::endl;
try {
DynamicArray a0(-2);
}
catch(const std::length_error& exp) {
std::cout << exp.what() << std::endl;
}
DynamicArray a1(2);
std::cout << "Let's create array1 where size = 2. Array1 is " << a1
<< std::endl;
int val1(1);
int val2(2);
int val3(3);
a1[0] = val1;
a1[1] = val2;
std::cout << "Let's do a1[0] = " << val1 << ", a1[1] = " << val2
<< ". Array1 is " << a1 << std::endl;
a1.PushBack(val3);
std::cout << "Let's push " << val3 << ". " << "Array is " << a1 << std::endl;
std::cout << "Size is " << a1.Size() << std::endl;
std::cout << std::endl;
DynamicArray a2(a1);
std::cout << "Let's create copy of array1. Array2 is " << a2 << std::endl;
std::cout << "Size is " << a2.Size() << std::endl;
a2.PopBack();
std::cout << "Let's pop. Array is " << a2 << std::endl;
std::cout << "Size is " << a2.Size() << std::endl;
std::cout << "a2[0] is " << a2[0] << std::endl;
try {
std::cout << "Let's try to get a2[4] -> ";
std::cout << a2[4] << std::endl;
}
catch(const std::out_of_range& exp) {
std::cout << exp.what() << std::endl;
}
std::cout << std::endl;
DynamicArray a3;
std::cout << "Array3 is " << a3 << std::endl;
a3 = a1;
std::cout << "Let's do array3 = array1. Array3 is " << a3 << std::endl;
std::cout << "Size is " << a3.Size() << std::endl;
a3.Resize(2);
std::cout << "Let's do Resize(2) to array3. Array3 is " << a3 << std::endl;
std::cout << "Size is " << a3.Size() << std::endl;
std::cout << std::endl;
a3.PushBack(5);
a2.PushBack(3);
std::cout << "Let's check operators ==, != :" << std::endl;
std::cout << a2 << " == " << a1 << " -> " << (a2 == a1) << "; "
<< a2 << " == " << a3 << " -> " << (a2 == a3) << std::endl;
std::cout << a2 << " != " << a1 << " -> " << (a2 != a1) << "; "
<< a2 << " != " << a3 << " -> " << (a2 != a3) << std::endl;
std::cout << std::endl;
a2[2] = 4;
std::cout << "A1 = " << a1 << std::endl;
std::cout << "A2 = " << a2 << std::endl;
std::cout << "A3 = " << a3 << std::endl;
std::cout << "Let's try to do A1 = A1 -> " << std::endl;
a1 = a1;
std::cout << "A1 = " << a1 << std::endl;
std::cout << "Let's try to do A1 = A2 = A3 -> " << std::endl;
a1 = a2 = a3;
std::cout << "A1 = " << a1 << std::endl;
std::cout << "A2 = " << a2 << std::endl;
std::cout << "A3 = " << a3 << std::endl;
return 0;
}
| true |
7a8698b0b198c08b8f9128a60d8875c261949e60 | C++ | 740299743/cppTest | /cppTest/main.cpp | UTF-8 | 2,116 | 3.5625 | 4 | [] | no_license | //
// main.cpp
// cppTest
//
// Created by pactera on 2/9/15.
// Copyright (c) 2015 pactera. All rights reserved.
//
#include <iostream>
#include <vector>
using namespace std;
class MyClass
{
public:
int x;
int y;
void foo()
{
cout<<"x + y = "<<x+y<<endl;
}
private:
float z;
void bar();
};
class Foo
{
public:
int x;
};
void changeValue(Foo& foo)
{
foo.x = 5;
}
class Player
{
void play();
public:
void foo()
{
cout<<"player---foo"<<endl;
}
};
class Manager
{
void manage();
public:
void foo()
{
cout<<"manager---foo"<<endl;
}
};
class PlayerManager:public Player,public Manager
{
};
class DoubleInt
{
public:
int x;
int y;
DoubleInt(int x,int y):x(x),y(y){}
DoubleInt operator+(const DoubleInt & rhs);
DoubleInt operator+(const int rhs);
};
DoubleInt DoubleInt::operator+(const DoubleInt &rhs)
{
return DoubleInt(x + rhs.x, y + rhs.y);
}
DoubleInt DoubleInt::operator+(const int rhs)
{
return DoubleInt(x + rhs, y + rhs);
}
template <typename T>
void selfSwap(T &a, T &b)
{
T temp = a;
a = b;
b = temp;
}
template <typename T>
class Triplet
{
private:
T a,b,c;
public:
Triplet(T a,T b,T c):a(a),b(b),c(c)
{
};
T getA()
{
return a;
}
T getB()
{
return b;
}
T getC()
{
return c;
}
};
template <typename TA, typename TB,typename TC>
class Triplet2
{
private:
TA a;
TB b;
TC c;
public:
Triplet2(TA a,TB b,TC c):a(a),b(b),c(c)
{
};
TA getA()
{
return a;
}
TB getB()
{
return b;
}
TC getC()
{
return c;
}
};
int main(int argc, const char * argv[])
{
Triplet2<int, float, string> mixedTriplet(1,3.141,"Hello World!");
cout<<"The c parameters = "<<mixedTriplet.getC()<<endl;
/*vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
*/
return 0;
}
| true |
6ca9282a1f53774dab64ad0e2496cae83c7ed223 | C++ | osmanuss/Programming | /Practice/25/C++/25/25/25.cpp | UTF-8 | 3,042 | 3.40625 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
std::vector<int> bozoSort(std::vector<int> arr, bool bl = 1)
{
bool check = 1;
while (check)
{
int a = rand() * arr.size() / RAND_MAX;
int b = rand() * arr.size() / RAND_MAX;
int tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
if (bl)
{
bool tmpBool = 1;
for (auto i = arr.begin(); i != arr.end() - 1; i++)
if (*i > * (i + 1))
{
tmpBool = 0;
break;
}
check = !tmpBool;
}
else
{
bool tmpBool = 1;
for (auto i = arr.begin(); i != arr.end() - 1; i++)
if (*i < *(i + 1))
{
tmpBool = 0;
break;
}
check = !tmpBool;
}
}
return arr;
}
std::vector <std::vector<int>> bozoSort(std::vector<std::vector<int>> arr, bool bl = 1)
{
const int m = arr.size();
const int n = arr[0].size();
bool check = 1;
while (check)
{
int rand_1_1 = rand() * n / RAND_MAX;
int rand_1_2 = rand() * m / RAND_MAX;
int rand_2_1 = rand() * n / RAND_MAX;
int rand_2_2 = rand() * m / RAND_MAX;
int tmp = arr[rand_1_2][rand_1_1];
arr[rand_1_2][rand_1_1] = arr[rand_2_2][rand_2_1];
arr[rand_2_2][rand_2_1] = tmp;
if (bl)
{
bool tmpBool = 1;
int previousNumber = arr[0][0];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
if (previousNumber > arr[i][j])
{
tmpBool = 0;
}
previousNumber = arr[i][j];
}
check = !tmpBool;
}
else
{
bool tmpBool = 1;
int previousNumber = arr[0][0];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
{
if (previousNumber < arr[i][j])
{
tmpBool = 0;
}
previousNumber = arr[i][j];
}
check = !tmpBool;
}
}
return arr;
}
std::vector<int> bozoSort(int a, int b, int c, bool bl = 1)
{
std::vector<int> arr;
arr.push_back(a);
arr.push_back(b);
arr.push_back(c);
return bozoSort(arr, bl);
}
void printVector(std::vector<int> vec)
{
for (auto i = vec.begin(); i != vec.end(); i++)
std::cout << *i << ' ';
std::cout << '\n';
}
void printVector(std::vector<std::vector<int>> vec)
{
for (int i = 0; i < vec.size(); i++)
for (int j = 0; j < vec[i].size(); j++)
std::cout << vec[i][j] << ' ';
std::cout << '\n';
}
int main()
{
srand(time(NULL));
int n;
std::cin >> n;
int* arr = new int[n];
for (int i = 0; i < n; i++)
std::cin >> arr[i];
std::vector<int> arr_1(n);
for (int i = 0; i < n; i++) {
arr_1[i] = arr[i];
}
auto arr_1_1 = bozoSort(arr_1);
auto arr_1_2 = bozoSort(arr_1, 0);
printVector(arr_1_1);
printVector(arr_1_2);
int m = sqrt(n);
std::vector<std::vector<int>> arr_2(m, std::vector<int>(m));
int k = 0;
for (int i = 0; i < m; i++)
for (int j = 0; j < m; j++)
arr_2[i][j] = arr[k++];
auto arr_2_1 = bozoSort(arr_2);
auto arr_2_2 = bozoSort(arr_2, 0);
printVector(arr_2_1);
printVector(arr_2_2);
int a = arr[0];
int b = arr[1];
int c = arr[2];
auto arr_3_1 = bozoSort(a, b, c);
auto arr_3_2 = bozoSort(a, b, c, 0);
printVector(arr_3_1);
printVector(arr_3_2);
delete[] arr;
return 0;
} | true |
df1fc112f00efcaf9b369aa6bbaddabb40b5bb0e | C++ | Wildflowerr/data-structures | /graph/SingleChild.cpp | UTF-8 | 329 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <list>
#include "Graph.h"
using namespace std;
template <typename T> //problem 1a
bool singleChild(Graph<T>& g, const T& a) {
list<T> vertic = g.vertices();
for (T v : vertic) {
if (g.containsEdge(v, a)) {
if (g.neighbours(v).size() > 1) return false;
}
}
return true;
} | true |
fc0b4aed4c94e83179a3a8407fd912a74e8d5a6d | C++ | Vikalp19041999/LeetCode-solutions | /Nearest Exit from Entrance in Maze.cpp | UTF-8 | 1,057 | 2.640625 | 3 | [] | no_license | class Solution {
public:
int nearestExit(vector<vector<char>>& maze, vector<int>& e) {
queue<pair<int,int>> q;
q.push({e[0],e[1]});
int moves = 1;
int rows = maze.size();
int cols = maze[0].size();
vector<vector<int>> offsets = {{0,1}, {1,0}, {0,-1}, {-1,0}};
maze[e[0]][e[1]]='+';
while(!q.empty()) {
int l = q.size();
for(int k=0; k<l; k++) {
auto [i,j] = q.front();
q.pop();
for(int l=0;l<4;l++) {
int x = i + offsets[l][0];
int y = j + offsets[l][1];
if(x<0 || y<0 || x>=rows || y>=cols || maze[x][y]=='+') {
continue;
}
if(x==0 || y==0 || x==rows-1 || y==cols-1) {
return moves;
}
maze[x][y] = '+';
q.push({x,y});
}
}
moves++;
}
return -1;
}
}; | true |
e2616992e2f3e5da2d3706dd6a30c2e536e62578 | C++ | YannisLamp/doc-search | /posting_list.h | UTF-8 | 634 | 2.84375 | 3 | [] | no_license | #ifndef SYSPRO_PROJECT_1_POSTINGLIST_H
#define SYSPRO_PROJECT_1_POSTINGLIST_H
#include "posting.h"
/*
* Main PostingList class, a single-linked list
* Works as a head
* It points to a Posting object (the first one)
* To make inserts faster, it also points to the last Posting
* Handles all main tasks of the PostingList
*/
class PostingList {
private:
int node_num;
Posting* first_node_ptr;
Posting* last_node_ptr;
public:
PostingList(int doc_id);
~PostingList();
void insert_doc_id(int doc_id);
int get_node_num();
int search_count(int id);
Posting* get_first_node_ptr();
};
#endif | true |
c8b6f2140dc5e7c2f0e927c97f85ff2e65d54c11 | C++ | irvifa/online-judges | /cheatsheets/Fenwick.cpp | UTF-8 | 290 | 2.828125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
struct Fenwick {
vector<int> f;
Fenwick(int n) : f(n) {}
void update(int k, int v) {
for(k++; k<f.size(); k+= k & -k)
f[k] ^= v;
}
int query(int k) {
int res = 0;
for(k++; k>0; k-= k & -k)
res ^= f[k];
return res;
}
};
| true |
1f11e02db58dc55bae9a58b722206f72108745e8 | C++ | AntanasJurk/Projects | /C++/OpenGL Sphere/Project1/main.cpp | UTF-8 | 4,072 | 2.640625 | 3 | [] | no_license | #include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define X .525731112119133606
#define Z .850650808352039932
int n;
static GLfloat vdata[12][3] = {
{ -X, 0.0, Z }, { X, 0.0, Z }, { -X, 0.0, -Z }, { X, 0.0, -Z },
{ 0.0, Z, X }, { 0.0, Z, -X }, { 0.0, -Z, X }, { 0.0, -Z, -X },
{ Z, X, 0.0 }, { -Z, X, 0.0 }, { Z, -X, 0.0 }, { -Z, -X, 0.0 }
};
static GLuint tindices[20][3] = {
{ 0, 4, 1 }, { 0, 9, 4 }, { 9, 5, 4 }, { 4, 5, 8 }, { 4, 8, 1 },
{ 8, 10, 1 }, { 8, 3, 10 }, { 5, 3, 8 }, { 5, 2, 3 }, { 2, 7, 3 },
{ 7, 10, 3 }, { 7, 6, 10 }, { 7, 11, 6 }, { 11, 0, 6 }, { 0, 1, 6 },
{ 6, 1, 10 }, { 9, 0, 11 }, { 9, 11, 2 }, { 9, 2, 5 }, { 7, 2, 11 } };
GLfloat colors[8][3] = {
{ 0.0, 0.0, 0.0 }, { 1.0, 0.0, 0.0 },
{ 1.0, 1.0, 0.0 }, { 0.0, 1.0, 0.0 },
{ 0.0, 0.0, 1.0 }, { 1.0, 0.0, 1.0 },
{ 1.0, 1.0, 1.0 }, { 0.0, 1.0, 1.0 }
};
void normalize(GLfloat *a) {
GLfloat d = sqrt(a[0] * a[0] + a[1] * a[1] + a[2] * a[2]);
a[0] /= d; a[1] /= d; a[2] /= d;
}
void drawtri(GLfloat *a, GLfloat *b, GLfloat *c, int div, float r) {
if (div <= 0) {
glColor3fv(a);
glNormal3fv(a);
glVertex3f(a[0] * r, a[1] * r, a[2] * r);
glColor3fv(b);
glNormal3fv(b);
glVertex3f(b[0] * r, b[1] * r, b[2] * r);
glColor3fv(c);
glNormal3fv(c);
glVertex3f(c[0] * r, c[1] * r, c[2] * r);
}
else {
GLfloat ab[3], ac[3], bc[3];
for (int i = 0; i<3; i++) {
ab[i] = (a[i] + b[i]) / 2;
ac[i] = (a[i] + c[i]) / 2;
bc[i] = (b[i] + c[i]) / 2;
}
normalize(ab); normalize(ac); normalize(bc);
drawtri(a, ab, ac, div - 1, r);
drawtri(b, bc, ab, div - 1, r);
drawtri(c, ac, bc, div - 1, r);
drawtri(ab, bc, ac, div - 1, r);
}
}
void drawsphere(int ndiv, float radius = 1.0) {
glBegin(GL_TRIANGLES);
for (int i = 0; i<20; i++)
drawtri(vdata[tindices[i][0]], vdata[tindices[i][1]], vdata[tindices[i][2]], ndiv, radius);
glEnd();
}
static GLfloat theta[] = { 0.0, 0.0, 0.0 };
static GLint axis = 0;
/*==========================================================*/
void display(void)
{
/* display callback, clear frame buffer and z buffer,
rotate cube and draw, swap buffers */
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(theta[0], 1.0, 0.0, 0.0); /* x */
glRotatef(theta[1], 0.0, 1.0, 0.0); /* y */
glRotatef(theta[2], 0.0, 0.0, 1.0); /* z */
drawsphere(n);
glFlush();
glutSwapBuffers();
}
/*==========================================================*/
void spinSphere(void)
{
/* Idle callback, rotate cube 0.2 degrees about selected axis */
theta[axis] += 0.2;
if (theta[axis] > 360.0)
theta[axis] -= 360.0;
glutPostRedisplay();
}
/*==========================================================*/
void mouse(int btn, int state, int x, int y)
{
char *sAxis[] = { "X-axis", "Y-axis", "Z-axis" };
/* mouse callback, selects an axis about which to rotate */
if (btn == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
axis = (++axis) % 3;
printf("Rotate about %s\n", sAxis[axis]);
}
}
/*==========================================================*/
void myReshape(int w, int h)
{
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (w <= h)
glOrtho(-2.0, 2.0, -2.0 * (GLfloat)h / (GLfloat)w,
2.0 * (GLfloat)h / (GLfloat)w, -10.0, 10.0);
else
glOrtho(-2.0 * (GLfloat)w / (GLfloat)h,
2.0 * (GLfloat)w / (GLfloat)h, -2.0, 2.0, -10.0, 10.0);
glMatrixMode(GL_MODELVIEW);
}
void key(unsigned char key, int xmouse, int ymouse)
{
switch (key){
case '+':
n++;
break;
case '-':
n--;
break;
default:
break;
}
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
n = 0;
printf("\nPress left mouse button to change rotation axis\n\n");
/* need both double buffering and z buffer */
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutCreateWindow("Color Cube");
glutReshapeFunc(myReshape);
glutDisplayFunc(display);
glutIdleFunc(spinSphere);
glutMouseFunc(mouse);
glutKeyboardFunc(key);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
| true |
651ffae81bf0a30a4216446ec512f75eb571519f | C++ | julie-yc/FlightBookingSystem | /FlightBookingSystem/FlightBookingSystem.cpp | UTF-8 | 4,216 | 3.53125 | 4 | [] | no_license | // FlightBookingSystem.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include "Database.h"
using namespace std;
using namespace FlightBookingSystem;
int displayMenu();
void flightDetailQuery(Database& db);
void getTicketInfo(Database& db);
void addBooking(Database& db);
void addFlight(Database& db);
int main() {
Database flightDB;
while (true) {
try
{
int selection = displayMenu();
switch (selection) {
case 1:
flightDB.displayAllFlights();
break;
case 2:
flightDetailQuery(flightDB);
break;
case 3:
getTicketInfo(flightDB);
break;
case 4:
addBooking(flightDB);
break;
case 5:
addFlight(flightDB);
break;
case 6:
cout << "Exiting the system" << endl;
break;
default:
cerr << "Unknown command. Try again." << endl;
return 1;
}
}
catch (logic_error error)
{
cerr << error.what() << endl;
}
}
return 0;
}
int displayMenu() {
int selection;
cout << endl;
cout << "FlightBookingSystem" << endl;
cout << "------------------------------" << endl;
cout << "1) All flights schedule" << endl;
cout << "2) Flight detail query" << endl;
cout << "3) Your ticket info" << endl;
cout << "4) Reserve a seat" << endl;
cout << "5) Add new flight" << endl;
cout << "6) Exit" << endl;
cout << "------------------------------" << endl;
cin >> selection;
return selection;
}
void flightDetailQuery(Database& db) {
string flightNumber;
cout << "Flight number: " << endl;
cin >> flightNumber;
Flight& flight = db.getFlightInfo(flightNumber);
flight.displayFlightInfo();
}
void getTicketInfo(Database& db) {
string flightNumber;
string passportNumber;
cout << "Flight Number: " << endl;
cin >> flightNumber;
Flight& flight = db.getFlightInfo(flightNumber);
cout << "Passport Number: " << endl;
cin >> passportNumber;
flight.displayTicketInfo(passportNumber);
}
void addBooking(Database& db) {
string flightNumber;
string firstName;
string lastName;
string passportNumber;
int seatNumber;
cout << "Flight Number: " << endl;
cin >> flightNumber;
Flight& flight = db.getFlightInfo(flightNumber);
cout << "First name: " << endl;
cin >> firstName;
cout << "Last name: " << endl;
cin >> lastName;
cout << "Passport Number: " << endl;
cin >> passportNumber;
cout << "Select your seat from 1~" << flight.getSeatsAvailable() << " for your flight" << endl;
cin >> seatNumber;
flight.reserveSeat(seatNumber, firstName, lastName, passportNumber);
cout << "Your have successfully reserved seat " << seatNumber << endl;
}
void addFlight(Database& db) {
string flightNumber;
string departureAirport;
string departureDate;
string departureTime;
string arrivalAirport;
string arrivalDate;
string arrivalTime;
int seatsAvailable;
cout << "Flight Number: " << endl;
cin >> flightNumber;
if (db.isFlightScheduled(flightNumber) == true)
{
throw logic_error("Flight already scheduled.");
}
cout << "Departure Airport: " << endl;
cin >> departureAirport;
cout << "Departure Date: " << endl;
cin >> departureDate;
cout << "Departure Time: " << endl;
cin >> departureTime;
cout << "Arrival Airport: " << endl;
cin >> arrivalAirport;
cout << "Arrival Date: " << endl;
cin >> arrivalDate;
cout << "Arrival Time: " << endl;
cin >> arrivalTime;
cout << "Number of Seats: " << endl;
cin >> seatsAvailable;
db.addFlight(flightNumber, departureAirport, departureDate, departureTime,
arrivalAirport, arrivalDate, arrivalTime, seatsAvailable);
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| true |
7aebdfd40ad78e414baeda5d9418a98f972bc0f6 | C++ | Aznad-Maruf/Algo | /General/shuntingYardAlgorithm.cpp | UTF-8 | 2,363 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
string stInfix, stPostfix;
stack < char > stk;
map < char, int > mp;
double evaluateIt( string st ){
int a_i, b_i, n s = st.size();
stack < char > stk1, stk2;
for( a_i = s-1; a_i>=0; a_i-- ) stk2.push( st[a_i] );
while( !stk2.empty() ){
}
}
void infixToPostfix(){
int a_i, b_i, n, temp, l;
char ch, ch2, cuCH, chT;
l = stInfix.length();
for( a_i=0; a_i<l; a_i++ ){
cuCH = stInfix[a_i];
if( mp[cuCH] == 0 ) stPostfix += cuCH; // is it is not an operator add it to output string.
else{
if( stPostfix)
if( stk.empty() ){
cout<<"Empty"<<endl;
stk.push( cuCH );
}
else{
if( cuCH == '(' ) stk.push( '(' );
else if( cuCH == ')' ){
cout<<"Got"<<endl;
while( !stk.empty() ){
cout<<stk.top()<<endl;
if( stk.top() == '(' ){
stk.pop();
break;
}
else{
stPostfix += stk.top();
stk.pop();
}
}
}
else{
cout<<cuCH<<endl;
if( mp[cuCH] >= mp[stk.top()] ) stk.push( cuCH );
else{
while( !stk.empty() && mp[stk.top()] > mp[cuCH] ){
stPostfix += stk.top();
stk.pop();
}
stk.push(cuCH);
}
cout<<stk.top()<<endl;
}
}
}
cout<<stPostfix<<endl;
}
while( !stk.empty() ){
stPostfix += stk.top();
stk.pop();
}
}
void initializeMap(){
mp['('] = -1;
mp[')'] = -1;
mp['+'] = 1;
mp['-'] = 1;
mp['*'] = 2;
mp['/'] = 2;
}
int main(){
int a_i, b_i, n, temp;
initializeMap();
cin>>stInfix;
stPostfix = "";
infixToPostfix();
cout<<stPostfix<<endl;
cout<<evaluateIt( stPostfix )<<endl;
}
| true |
6a1757abbfe25efcf94fa173a556d59d5644a4a0 | C++ | dreamiond/LeetCode | /leetcode_35.cpp | UTF-8 | 869 | 3.484375 | 3 | [] | no_license | //leetcode35:Search Insert Position
/*
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Example 1:
Input: [1,3,5,6], 5
Output: 2
Example 2:
Input: [1,3,5,6], 2
Output: 1
Example 3:
Input: [1,3,5,6], 7
Output: 4
Example 4:
Input: [1,3,5,6], 0
Output: 0
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_set>
#include <math.h>
using namespace std;
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int low = 0, high = nums.size() - 1, mid = 0;
while (low <= high) {
mid = low + (high - low) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
return low;
}
}; | true |
a685734682a45c064f69cbafc7178a21a226ef48 | C++ | iguessthislldo/cmake-build-extension | /example/src/mymath.h | UTF-8 | 907 | 3.5 | 4 | [
"MIT"
] | permissive | #ifndef MYMATH_H
#define MYMATH_H
#include <vector>
namespace mymath {
/**
* Perform the inner product between two 1D vectors.
*
* @param vector1 The first vector.
* @param vector2 The second vector.
* @throws If the vectors sizes do not match.
* @return The double product of the input vectors.
*/
double dot(const std::vector<double>& vector1,
const std::vector<double>& vector2);
/**
* Normalize a 1D vector.
*
* The normalization operation takes the input vector and divides
* all its element by its norm. The resulting vector is a unit vector,
* i.e. a vector with length 1.
*
* @param input The vector to normalize.
* @return The unit vector computed by normalizing the input.
*/
std::vector<double> normalize(const std::vector<double>& data);
} // namespace mymath
#endif // MYMATH_H
| true |
dd54a15cde50fb2af6ec1a49a4f989951c840793 | C++ | PurbayanNC/Far_Behind | /Codebook/code/Data_Structures/SegmentTree.cpp | UTF-8 | 1,025 | 3.09375 | 3 | [
"MIT"
] | permissive | /*All arrays are 0 indexed. call bld(0,n-1,1)
upd(0,n-1,1,x,y,val) -> increase [x,y] by val
sum(0,n-1,1,x,y) -> sum [x,y]
array of size N -> segment tree of size 4*N*/
ll arr[N],st[N<<2], lz[N<<2];
void ppgt(ll l, ll r,ll id){
if(l==r) return;
ll m=l+r>>1;
lz[id*2]+=lz[id];lz[id<<1|1]+=lz[id];
st[id << 1] += (m - l + 1) * lz[id];
st[id<<1|1]+=(r-m)*lz[id];lz[id] = 0;}
void bld(ll l,ll r,ll id){
if(l==r) { st[id] = arr[l]; return; }
bld(l,l+r>>1,id*2);bld(l+r+1>>1,r,id*2+1);
st[id] = st[ id << 1] + st[id << 1 | 1];}
void upd(ll l,ll r,ll id,ll x,ll y,ll val){
if (l > y || r < x ) return;ppgt(l, r, id);
if (l >= x && r <= y ) {
lz[id]+=val;st[id]+=(r-l+1)*val; return;}
upd(l,l + r >> 1,id << 1, x, y, val);upd((l + r >> 1) + 1,r ,id << 1 | 1,x, y, val);
st[id] = st[id << 1] + st[ id << 1 | 1];}
ll sum(ll l,ll r,ll id,ll x,ll y){
if (l > y || r < x ) return 0;ppgt(l, r, id);
if (l >= x && r <= y ) return st[id];
return sum(l, l + r >> 1,id << 1, x, y) + sum((l + r >> 1 ) + 1,r ,id << 1 | 1,x, y);} | true |
1aef8c3a51c823d64285b70c0d642aaf9ce119a8 | C++ | ChandlorRatcliffe/Computer-Graphics--Group-Project-2 | /CGProject2/ShearYMatrix.cpp | UTF-8 | 1,195 | 3.359375 | 3 | [] | no_license | #include "ShearYMatrix.h"
#include "CompositeMatrix.h"
/**
* ShearYMatrix constructs a homogeneous linear transformation matrix
* intended to shear a 3 vector in the y direction with respect to the x-axis
* by a factor of sy.
*/
ShearYMatrix::ShearYMatrix(float sy) {
this->matrix[0][0] = 1.0;
this->matrix[0][1] = 0.0;
this->matrix[0][2] = 0.0;
this->matrix[1][0] = sy;
this->matrix[1][1] = 1.0;
this->matrix[1][2] = 0.0;
this->matrix[2][0] = 0.0;
this->matrix[2][1] = 0.0;
this->matrix[2][2] = 1.0;
this->type = Type::SHEARY;
}
/**
* ShearYMatrix constructs a homogeneous linear transformation matrix
* intended to shear a 3 vector in the y direction with respect to an
* alternative horizontal line specified by xAxis by a factor of sy.
*/
ShearYMatrix::ShearYMatrix(float sy, float xAxis) {
CompositeMatrix composite = CompositeMatrix();
TranslationMatrix translateLeft = TranslationMatrix(0.0, xAxis);
TranslationMatrix translateRight = TranslationMatrix(0.0, -xAxis);
ShearYMatrix shear = ShearYMatrix(sy);
composite.composeWith(&translateRight);
composite.composeWith(&shear);
composite.composeWith(&translateLeft);
copyFrom(&composite);
} | true |
27c8b11282d68f98aab42354b191d32109cd6737 | C++ | rajkumawat01/CSES-Problem-Set | /2.missing.cpp | UTF-8 | 756 | 3.515625 | 4 | [] | no_license | /*
You are given all numbers between 1,2,…,n except one.
Your task is to find the missing number.
->Input
The first input line contains an integer n.
The second line contains n−1 numbers.
Each number is distinct and between 1 and n (inclusive).
->Output
Print the missing number.
->Constraints
2≤n≤2⋅105
->Example
Input:
5
2 3 1 5
Output:
4
*/
#include <iostream>
using namespace std;
int main()
{
long long int n, n1;
long long int sum;
cin >> n;
sum = n*(n+1);
sum = sum*0.5;
n = n - 1;
for(int i=0; i<n; i++)
{
cin >> n1;
sum = sum - n1;
}
cout << sum;
return 0;
}
| true |
256730bbcb4b62475672b980449a22e611324baa | C++ | ill/illEngine | /Graphics/serial/BitmapFont.cpp | UTF-8 | 15,005 | 2.796875 | 3 | [] | no_license | #include "Graphics/serial/BitmapFont.h"
#include "Graphics/GraphicsBackend.h"
#include "FileSystem/FileSystem.h"
#include "FileSystem/File.h"
#include "Logging/logging.h"
const int32_t HEADER = 0x424D4603; //"BMF" followed by format specifier 3 in big endian form
namespace illGraphics {
glm::vec2 BitmapFont::getPrintDimensions(const char * text) const {
glm::vec2 res(0.0f);
glm::mediump_float maxX = 0;
size_t currPos = 0;
size_t lastChar = strlen(text);
//go through the string and get dimensions of every character
while(text[currPos]) {
size_t stopPos = lastChar;
{
const char * newLineChar = strchr(text + currPos, '\n');
if(newLineChar) {
stopPos = newLineChar - text;
}
}
res = getCharLocation(text, stopPos, currPos, res);
if(res.x > maxX) {
maxX = res.x;
}
if(text[currPos] == '\n') {
currPos++;
res.y += m_lineHeight;
}
}
return glm::vec2(maxX, res.y + m_lineHeight);
}
glm::vec2 BitmapFont::getCharLocation(const char * text, size_t charPos, size_t& currPos, glm::vec2 startLocation) const {
if(m_state != RES_LOADED) {
LOG_FATAL_ERROR("Attempting to get character location of bitmap font when it's not loaded.");
}
while(text[currPos] && currPos < charPos) {
//eat the color code
{
const char * newPos = getColorCode(text + currPos, glm::vec4());
currPos = newPos - text;
}
//parse special characters
switch (text[currPos]) {
case '\n': //newline
startLocation = glm::vec2(0.0f, startLocation.y - getLineHeight());
break;
case ' ': //space
startLocation.x += 5.0f;
break;
case '\t': //tab
startLocation.x += getSpacingHorz() * 4.0f;
break;
default:
startLocation.x += getCharData(text[currPos]).m_advance;
break;
}
currPos++;
}
return startLocation;
}
const char * BitmapFont::getColorCode(const char * text, glm::vec4& destination) {
//TODO: hex digit parsing
enum class ParseState {
BEGIN,
CARAT,
//HEX,
//HEX_DIGITS
} parseState = ParseState::BEGIN;
size_t numReadHex = 0;
const char * currText = text;
while(*currText) {
switch(parseState) {
case ParseState::BEGIN:
if(*currText == '^') {
parseState = ParseState::CARAT;
currText++;
}
/*else if(*currText == '#') {
parseState = ParseState::HEX;
currText++;
}*/
else {
return text;
}
break;
case ParseState::CARAT:
if(*currText == '^') {
//escape
return currText;
}
else if(!isdigit(*currText)) {
//not a digit
return text;
}
else {
//return the right color
switch(*currText) {
case '0': //black
destination = glm::vec4(0.0f, 0.0f, 0.0f, 1.0);
break;
case '1': //red
destination = glm::vec4(1.0f, 0.0f, 0.0f, 1.0);
break;
case '2': //green
destination = glm::vec4(0.0f, 1.0f, 0.0f, 1.0);
break;
case '3': //yellow
destination = glm::vec4(1.0f, 1.0f, 0.0f, 1.0);
break;
case '4': //blue
destination = glm::vec4(0.0f, 0.0f, 1.0f, 1.0);
break;
case '5': //cyan
destination = glm::vec4(0.0f, 1.0f, 1.0f, 1.0);
break;
case '6': //magenta
destination = glm::vec4(1.0f, 0.0f, 1.0f, 1.0);
break;
case '7': //white
destination = glm::vec4(1.0f, 1.0f, 1.0f, 1.0);
break;
case '8': //purple
destination = glm::vec4(0.5f, 0.0f, 0.5f, 1.0);
break;
case '9': //gray
destination = glm::vec4(0.5f, 0.5f, 0.5f, 1.0);
break;
}
return ++currText;
}
break;
/*case ParseState::HEX:
break;*/
}
}
return text;
}
void BitmapFont::unload() {
if(m_state == RES_LOADING) {
LOG_FATAL_ERROR("Attempting to unload bitmap font while it's loading");
}
if(m_state == RES_UNINITIALIZED || m_state == RES_UNLOADED) {
return;
}
m_mesh.unload();
m_pageTextures.clear();
m_kerningPairs.clear();
m_state = RES_UNLOADED;
}
void BitmapFont::reload(GraphicsBackend * backend) {
unload();
m_loader = backend;
m_state = RES_LOADING;
illFileSystem::File * openFile = illFileSystem::fileSystem->openRead(m_loadArgs.m_path.c_str());
/////////////////////////////
//read header
{
uint32_t header;
openFile->readB32(header);
if(header != HEADER) {
LOG_FATAL_ERROR("Font file %s is not a valid Angelcode Bitmap Font Generator binary Version 3 file", m_loadArgs.m_path.c_str());
}
}
unsigned int textureWidth;
unsigned int textureHeight;
/////////////////////////////
//read blocks
while(!openFile->eof()) {
//get block type
uint8_t blockType;
openFile->read8(blockType);
//get block size
uint32_t blockSize;
openFile->readL32(blockSize);
switch(blockType) {
case 1: //info
readInfo(openFile, (size_t) blockSize);
break;
case 2: //common
readCommon(openFile, textureWidth, textureHeight);
break;
case 3: //pages
readPages(openFile, (size_t) blockSize);
break;
case 4: //chars
readChars(openFile, (size_t) blockSize, textureWidth, textureHeight);
break;
case 5: //kerning pairs
readKerningPairs(openFile, (size_t) blockSize);
break;
}
}
delete openFile;
m_state = RES_LOADED;
}
void BitmapFont::readInfo(illFileSystem::File * file, size_t size) {
//skip to the stuff I need
file->seekAhead(7);
//get padding
uint8_t value;
file->read8(value);
m_paddingUp = (glm::mediump_float) value;
file->read8(value);
m_paddingDown = (glm::mediump_float) value;
file->read8(value);
m_paddingLeft = (glm::mediump_float) value;
file->read8(value);
m_paddingRight = (glm::mediump_float) value;
//get spacing
file->read8(value);
m_spacingHorz = (glm::mediump_float) value;
file->read8(value);
m_spacingVert = (glm::mediump_float) value;
//skip the rest of the block
file->seekAhead(size - (7 + 6));
}
void BitmapFont::readCommon(illFileSystem::File * file, unsigned int& textureWidth, unsigned int& textureHeight) {
//read line height
{
uint16_t lineHeight;
file->readL16(lineHeight);
m_lineHeight = (glm::mediump_float) lineHeight;
}
//read line base
{
uint16_t lineBase;
file->readL16(lineBase);
m_lineBase = (glm::mediump_float) lineBase;
}
//read the scale
{
uint16_t scale;
file->readL16(scale);
textureWidth = (unsigned int) scale;
file->readL16(scale);
textureHeight = (unsigned int) scale;
}
//read pages number
{
uint16_t pages;
file->readL16(pages);
m_pageTextures.resize((size_t) pages);
}
//TODO: read the bitfield
file->seekAhead(5);
}
void BitmapFont::readPages(illFileSystem::File * file, size_t size) {
//string length is the same for all file names in this block
size_t pathSize = size / m_pageTextures.size();
char * pathBuffer = new char[pathSize];
//TODO: make the texture path be relative to the path of the font file
TextureLoadArgs loadArgs;
loadArgs.m_wrapS = TextureLoadArgs::Wrap::W_CLAMP_TO_EDGE;
loadArgs.m_wrapT = TextureLoadArgs::Wrap::W_CLAMP_TO_EDGE;
for(unsigned int texture = 0; texture < m_pageTextures.size(); texture++) {
file->read(pathBuffer, pathSize);
loadArgs.m_path.assign(pathBuffer);
m_pageTextures[texture].load(loadArgs, m_loader);
}
delete[] pathBuffer;
}
void BitmapFont::readChars(illFileSystem::File * file, size_t size, unsigned int textureWidth, unsigned int textureHeight) {
memset(m_charData, 0, sizeof(CharData) * NUM_CHARS);
glm::mediump_float texW = 1.0f / textureWidth;
glm::mediump_float texH = 1.0f / textureHeight;
unsigned int numChars = (unsigned int) size / 20;
//create a mesh data object with 2 triangles per character and 4 verteces per character to create quads
m_mesh.unload();
m_mesh.setFrontentDataInternal(new MeshData<>(numChars << 2, numChars << 2, 1, MF_POSITION | MF_TEX_COORD));
uint16_t * indeces = m_mesh.getMeshFrontentData()->getIndices();
{
auto primGroup = m_mesh.getMeshFrontentData()->getPrimitiveGroup(0);
primGroup.m_beginIndex = 0;
primGroup.m_numIndices = m_mesh.getMeshFrontentData()->getNumInd();
primGroup.m_type = MeshData<>::PrimitiveGroup::Type::TRIANGLE_FAN;
}
for(unsigned int currChar = 0; currChar < numChars; currChar++) {
unsigned char character;
//read the character id
{
uint32_t ch;
file->readL32(ch);
assert(ch < NUM_CHARS);
character = (unsigned char) ch;
}
//read the character size data
{
uint16_t val;
file->readL16(val);
glm::mediump_float left = (glm::mediump_float) val * texW;
file->readL16(val);
glm::mediump_float top = 1.0f - (glm::mediump_float) val * texH;
file->readL16(val);
glm::mediump_float width = (glm::mediump_float) val;
file->readL16(val);
glm::mediump_float height = (glm::mediump_float) val;
glm::mediump_float right = left + width * texW;
glm::mediump_float bottom = top - height * texH;
file->readL16(val);
glm::mediump_float xOffset = (glm::mediump_float) (int16_t) val;
file->readL16(val);
glm::mediump_float yOffset = (glm::mediump_float) (int16_t) val;
file->readL16(val);
m_charData[character].m_advance = (glm::mediump_float) (int16_t) val;
/*
A character's mesh looks like this
vtx 3 _____ vtx 2
| /
| /|
| / |
|/ |
vtx 0 /___| vtx 1
*/
//set the character index buffer data
size_t currVert = currChar << 2;
m_charData[character].m_meshIndex = (uint16_t) currVert;
indeces[currVert] = (uint16_t) currVert; //vtx 0
indeces[currVert + 1] = (uint16_t) currVert + 1; //vtx 1
indeces[currVert + 2] = (uint16_t) currVert + 2; //vtx 2
indeces[currVert + 3] = (uint16_t) currVert + 3; //vtx 3
//set the character vertex buffer data
//positions
m_mesh.getMeshFrontentData()->getPosition((uint32_t) currVert) = glm::vec3(xOffset, m_lineHeight - (yOffset + height) - m_lineBase, 0.0f); //vtx 0
m_mesh.getMeshFrontentData()->getPosition((uint32_t) currVert + 1) = glm::vec3(xOffset + width, m_lineHeight - (yOffset + height) - m_lineBase, 0.0f); //vtx 1
m_mesh.getMeshFrontentData()->getPosition((uint32_t) currVert + 2) = glm::vec3(xOffset + width, m_lineHeight - yOffset - m_lineBase, 0.0f); //vtx 2
m_mesh.getMeshFrontentData()->getPosition((uint32_t) currVert + 3) = glm::vec3(xOffset, m_lineHeight - yOffset - m_lineBase, 0.0f); //vtx 3
//tex coords
m_mesh.getMeshFrontentData()->getTexCoord((uint32_t) currVert) = glm::vec2(left, bottom); //vtx 0
m_mesh.getMeshFrontentData()->getTexCoord((uint32_t) currVert + 1) = glm::vec2(right, bottom); //vtx 1
m_mesh.getMeshFrontentData()->getTexCoord((uint32_t) currVert + 2) = glm::vec2(right, top); //vtx 2
m_mesh.getMeshFrontentData()->getTexCoord((uint32_t) currVert + 3) = glm::vec2(left, top); //vtx 3
}
//read the texture page
{
uint8_t page;
file->read8(page);
m_charData[character].m_texturePage = page;
}
//TODO: read the channel
file->seekAhead(1);
}
/*for(unsigned int ind = 0; ind < m_mesh.getMeshFrontentData()->getNumInd(); ind++) {
LOG_DEBUG("ind %u %u", ind, indeces[ind]);
}
for(unsigned int ind = 0; ind < m_mesh.getMeshFrontentData()->getNumVert(); ind++) {
LOG_DEBUG("vert %u %f %f %f", ind, m_mesh.getMeshFrontentData()->getPosition(ind).x, m_mesh.getMeshFrontentData()->getPosition(ind).y, m_mesh.getMeshFrontentData()->getPosition(ind).z);
}
for(unsigned int ind = 0; ind < m_mesh.getMeshFrontentData()->getNumVert(); ind++) {
LOG_DEBUG("tex %u %f %f", ind, m_mesh.getMeshFrontentData()->getTexCoord(ind).x, m_mesh.getMeshFrontentData()->getTexCoord(ind).y);
}*/
m_mesh.frontendBackendTransferInternal(m_loader);
}
void BitmapFont::readKerningPairs(illFileSystem::File * file, size_t size) {
unsigned int numPairs = (unsigned int) size / 10;
for(unsigned int pair = 0; pair < numPairs; pair++) {
uint32_t firstChar;
file->readL32(firstChar);
assert(firstChar < NUM_CHARS);
uint32_t secondChar;
file->readL32(secondChar);
assert(secondChar < NUM_CHARS);
uint16_t amount;
file->readL16(amount);
m_kerningPairs[(char) firstChar][(char) secondChar] = (glm::mediump_float) (int16_t) amount;
}
}
}
| true |
7d8b8e0156a0b6989a82818d057ecf220e713b42 | C++ | ha271923/TestCpp | /testdome/cpp/sum3.cpp | UTF-8 | 1,862 | 4.09375 | 4 | [] | no_license | /*
Question: TestDome - Sum3
Solution by Arash Partow 2014
Design a data structure that can EFFICIENTLY handle two types of
requests: add a list of elements at the end of the internal list, and
answer whether there is a sum of any three consecutive elements in the
internal list equal to the given sum.
For example, a Sum3() creates an empty internal list with no existing
sum3s. addLast({1, 2, 3}) appends elements {1, 2, 3} resulting with
internal list {1, 2, 3} and only one existing sum3 (1+2+3=6).
addLast({4}) appends element 4 resulting with internal list {1, 2, 3,
4} and two existing sum3s (1+2+3=6 and 2+3+4=9).
*/
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <unordered_set>
class Sum3
{
public:
/**
* \brief Adds/appends list of integers at the end of internal list.
*
**/
void addLast(const std::vector<int>& list)
{
std::size_t vs = v_.size();
std::copy(list.begin(), list.end(), std::back_inserter(v_));
if (v_.size() >= 3)
{
for (std::size_t i = std::max<int>(0, vs - 2); i < v_.size() - 2; ++i)
{
sum_map_.insert((v_[i] + v_[i + 1] + v_[i + 2]));
}
}
}
/**
* \brief Returns boolean representing if any three consecutive integers in the internal list have given susum_map.
*
**/
bool containsSum3(int sum)
{
return sum_map_.find(sum) != sum_map_.end();
}
private:
std::vector<int> v_;
std::unordered_set<int> sum_map_;
};
#ifndef RunTests
int main(int argc, const char* argv[])
{
Sum3 s;
std::vector<int> first;
first.push_back(1);
first.push_back(2);
first.push_back(3);
s.addLast(first);
std::cout << s.containsSum3(6) << '\n';
std::cout << s.containsSum3(9) << '\n';
std::vector<int> second;
second.push_back(4);
s.addLast(second);
std::cout << s.containsSum3(9) << '\n';
}
#endif | true |
30e631fefcc2dba935fab53e7739bb35704265d3 | C++ | jaankaup/my_opencl_project | /src/OpenCL/GPU_Device.h | UTF-8 | 6,532 | 2.53125 | 3 | [] | no_license | #ifndef GPU_DEVICE_H
#define GPU_DEVICE_H
//#define __CL_ENABLE_EXCEPTIONS
//#define CL_HPP_TARGET_OPENCL_VERSION 200
#include <vector>
#include <unordered_map>
#include <memory>
#include <GL/glew.h>
//#include <CL/cl2.hpp>
#include <CL/cl.hpp>
#include <CL/cl_gl.h>
#include "../Utils/log.h"
#include "CL_Helper.h"
class CL_Program;
/** A singleton class for represention of a single GPU opencl device. */
class GPU_Device
{
public:
/**
* A method for getting the pointer to the this singleton object.
* @param return The pointer to the GPU_Device instance.
*/
static GPU_Device* getInstance() { static GPU_Device gd; return &gd; }
/**
* The destructor.
*/
~GPU_Device() {};
/**
* Initializes the opencl device and context.
* @param return True if initialization succeed, false otherwise.
*/
bool init();
/**
* A method for getting a pointer for the created context.
* @param return a pointer to the gpu device context of nullptr if these is
* no context.
*/
cl::Context* getContext();
/**
* Copy and move operations are deleted because this is an singleton class.
* */
GPU_Device(const GPU_Device&) = delete;
/**
* Copy and move operations are deleted because this is an singleton class.
* */
GPU_Device(GPU_Device&&) = delete;
/**
* Copy and move operations are deleted because this is an singleton class.
* */
GPU_Device& operator=(const GPU_Device&) = delete;
/** Copy and move operations are deleted because this is an singleton class. */
GPU_Device& operator=(GPU_Device&&) = delete;
/**
* Get pointer to the actual device.
* @param return Pointer to the device.
*/
cl::Device* getDevice();
// /**
// * Get pointer to the cl::CommandQueue. TODO: Remove.
// * @param return Pointer to the cl::CommandQueue.
// */
// cl::CommandQueue* getCommandQueue();
/**
* Get the maximum group size.
* @param return Maximum group size.
*/
size_t getMaxGroupSize() const;
/**
* Get the global dimension.
* @param total_count The number of elements.
* @param return The global dimension.
*/
cl::NDRange getGlobalDim(const int total_count);
/**
* Get the local dimension.
* @param total_count The number of elements.
* @param return The local dimension.
*/
cl::NDRange getLocalDim();
// /**
// * Makes the GPU_Devices CommandQueue to run the kernel. TODO: Remove.
// * @param globalDim The global dimension.
// * @param localDim The local dimension.
// * @param return Did the kernel execution succeed.
// */
// bool runKernel(CL_Program* kernel, cl::NDRange globalDim, cl::NDRange localDim);
cl::Buffer* createBuffer(const std::string& name, size_t size, cl_mem_flags);
cl::ImageGL* createImage(const std::string& name, cl_mem_flags flags, GLenum target, GLuint textureID)
{
cl_int error = 0;
std::unique_ptr<cl::ImageGL> b(new cl::ImageGL(pContext, flags, target, 0, textureID, &error));
if (error != CL_SUCCESS)
{
Log::getDebug().log("GPU_Device::createImage(%,%,%,%)",name,flags,target, textureID);
print_cl_error(error);
return nullptr;
}
pImages[name] = std::move(b);
return pImages[name].get();
}
cl::Program* createProgram(const std::string& name, cl::Program::Sources& sources);
/**
* Create a new resource (gl::CommandQueue).
* @param key A key for getting and deleting the resource.
* @param return A pointer to the created resource or nullptr on
* failure.
*/
template<typename T>
T* create(const std::string& key)
{
assert(pInitialized);
if constexpr (std::is_same<T,cl::CommandQueue>::value) {
cl_int error;
std::unique_ptr<cl::CommandQueue> c(new cl::CommandQueue(pContext, pDevice, 0, &error));
if (error != CL_SUCCESS)
{
Log::getError().log("GPU:Device::create(): Failed to create CommmandQueue.");
Log::getError().log("%",errorcode_toString(error));
return nullptr;
}
pCommandQueues[key] = std::move(c);
return pCommandQueues[key].get();
}
}
/**
* Delete a resource.
* @param key for deleting the resource.
*/
template<typename T>
void del(const std::string& key)
{
assert(pInitialized);
if constexpr (std::is_same<T,cl::CommandQueue>::value) { pCommandQueues.erase(key); }
if constexpr (std::is_same<T,cl::Buffer>::value) { pBuffers.erase(key); }
if constexpr (std::is_same<T,cl::ImageGL>::value) { pImages.erase(key); }
if constexpr (std::is_same<T,cl::Program>::value) { pPrograms.erase(key); }
}
/**
* Get a resource for given key.
* @param key for getting the resource.
* @return A pointer to the resource or nullptr is resource is not found.
*/
template<typename T>
T* get(const std::string& key)
{
assert(pInitialized);
if constexpr (std::is_same<T,cl::CommandQueue>::value) { auto f = pCommandQueues.find(key); if (f != pCommandQueues.end()) return f->second.get(); else return nullptr; }
if constexpr (std::is_same<T,cl::Buffer>::value) { auto f = pBuffers.find(key); if (f != pBuffers.end()) return f->second.get(); else return nullptr; }
if constexpr (std::is_same<T,cl::Program>::value) { auto f = pPrograms.find(key); if (f != pPrograms.end()) return f->second.get(); else return nullptr; }
if constexpr (std::is_same<T,cl::ImageGL>::value) { auto f = pImages.find(key); if (f != pImages.end()) return f->second.get(); else return nullptr; }
}
private:
/** The constructor. */
GPU_Device() {};
std::unordered_map<std::string, std::unique_ptr<cl::Buffer>> pBuffers; /**< cl::Buffers. */
std::unordered_map<std::string, std::unique_ptr<cl::ImageGL>> pImages; /**< cl::ImageGLs. */
std::unordered_map<std::string, std::unique_ptr<cl::CommandQueue>> pCommandQueues; /**< cl::CommandQueues. */
std::unordered_map<std::string, std::unique_ptr<cl::Program>> pPrograms; /**< cl::Programs. */
bool pInitialized = false; /**< Indicates the initialization state. */
cl::Device pDevice; /**< The cl::Device. */
cl::Context pContext; /**< The cl::Context for this device. */
cl::CommandQueue pQueue; /**< The cl::CommandQueue for this device. TODO: remove. */
};
#endif
| true |
044eed2793357a79a52eff45ec3440e4330f3326 | C++ | xcgj/QT_Lesson | /0202InputToSaveToFile/writefile.cpp | UTF-8 | 1,257 | 3.03125 | 3 | [] | no_license | #include "writefile.h"
#include "data.h"
#include <QDebug>
#include <QFile>
#include <QDataStream>
writefile::writefile(QWidget *parent) : QWidget(parent)
{
name = new QLineEdit(this);
name->move(10, 40);
name->setPlaceholderText("请输入姓名");
age = new QLineEdit(this);
age->move(10, 110);
age->setPlaceholderText("请输入姓名");
score = new QLineEdit(this);
score->move(10, 180);
score->setPlaceholderText("请输入姓名");
button = new QPushButton("确定", this);
button->move(100, 240);
//当按钮按下,执行数据保存操作
connect(button, &QPushButton::pressed, this, &writefile::savedata);
//关闭窗口
connect(button, &QPushButton::clicked, this, &writefile::close);
}
void writefile::savedata()
{
//定义结构体,保存数据
DATA d;
d.nam = name->text();
d.ag = age->text().toInt();
d.scor = score->text().toInt();
qDebug() << d.nam;
//打开文件
QFile file("data.info");
file.open(QFile::WriteOnly);
//序列化写入
QDataStream ds(&file);
ds << d.nam << d.ag << d.scor;
//关闭文件
file.close();
qDebug() << "数据保存成功";
}
| true |
b68893bff44ca45690318cbe5807638d3681f692 | C++ | 4LG0R4/amazing-code | /4963/HoduGwaja.cpp | UHC | 1,726 | 3.40625 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
int w, h; // ,
int map[50][50]; // ü
bool visited[50][50]; // ʿ ϱ?
// ü
typedef struct { // ü
int dx, dy; // x, y
}dir;
dir direction[8] = { {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}, {0, -1}, {1, -1} }; //ʺ ð
void VisitIsland(int y, int x) {
if (!map[y][x] || visited[y][x]) return; // 湮 ? ̱ ?(ȵ ư)
visited[y][x] = true; //湮
for (int i = 0; i < 8; i++) {
int newY = y + direction[i].dy; // yǥ
int newX = x + direction[i].dx; // xǥ
if (newX >= 0 && newX < w && newY >= 0 && newY < h) { // ?
VisitIsland(newY, newX); // мغ
}
}
}
int main()
{
while (true) { // ٰ 0 0 ԷµǸ while
int island = 0; //
cin >> w >> h; //
if (w == 0 && h == 0) break;
memset(visited, false, sizeof(visited)); // ϴ ǥ, ʱȭ , ũ
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> map[i][j]; // Է
}
}
// ѹ DZ Է ް island
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (!visited[i][j] && map[i][j]) { // ΰ? && ű Ȱ?
VisitIsland(i, j); // ŭ ѹ
island++; // Ϸ
}
}
}
cout << island << endl; //
}
return 0;
} | true |
224528615aa7148f16a3a8fad6bbfcd0429f5261 | C++ | ly774508966/GameRender3D | /lonely3D/Vector3.h | UTF-8 | 4,748 | 3.21875 | 3 | [] | no_license | #pragma once
#ifndef __Vector3_H__
#define __Vector3_H__
#include "MathTools.h"
class Vector2;
class Vector4;
class Vector3
{
public:
Vector3();
Vector3(float32 _x, float32 _y, float32 _z) :x(_x), y(_y), z(_z) {}
Vector3(const Vector2& inVec);
Vector3(const Vector3& inVec);
Vector3(const Vector4& inVec);
~Vector3();
float32 x, y, z;
Vector3& operator() (Vector2 inVec);
Vector3& operator() (Vector4 inVec);
Vector3& operator =(Vector2 inVec);
Vector3& operator =(Vector4 inVec);
//Vector3& operator=(const Vector2& inVec);
//Vector3& operator=(const Vector4& inVec);
float32 operator[] (int32 index) { if (index == 0)return x; else if (index == 1) return y; else if (index == 2) return z; }
const float32 operator[] (int32 index)const { if (index == 0)return x; else if (index == 1) return y; else if (index == 2) return z; }
Vector3& operator +=(const Vector3 inVec) { x += inVec.x; y += inVec.y; z += inVec.z; return *this; }
Vector3& operator -=(const Vector3 inVec) { x -= inVec.x; y -= inVec.y; z -= inVec.z; return *this; }
Vector3& operator *=(const float32 d) { x *= d; y *= d; z *= d; return *this; }
Vector3& operator /=(const float32 d) { x /= d; y /= d; z /= d; return *this; }
Vector3 operator -() { return Vector3(-x, -y, -z); }
bool operator == (Vector3 inVec) { return x == inVec.x && y == inVec.y && z == inVec.z; }
bool operator !=(Vector3 inVec) { return x != inVec.x || y != inVec.y || z != inVec.z; }
float32 Dot(const Vector3& inVec);
float32 Dot(const Vector4& inVec);
float32 Magnitude();
float32 SqrMagnitude();
void Normalize();
void Set(float32 newX, float32 newY, float32 newZ);
void Set(const Vector4& inVec);
void AddEqual(const Vector4& inVec);
void AddEqual(const Vector3& inVec);
void Clear() { x = 0; y = 0; z = 0;}
static const Vector3 zero() { return Vector3(0, 0, 0); }
static const Vector3 one() { return Vector3(1, 1, 1); }
static const Vector3 forward() { return Vector3(0, 0, 1); }
static const Vector3 back() { return Vector3(0, 0, -1); }
static const Vector3 left() { return Vector3(-1, 0, 0); }
static const Vector3 right() { return Vector3(1, 0, 0); }
static const Vector3 up() { return Vector3(0, 1, 0); }
static const Vector3 down() { return Vector3(0, -1, 0); }
};
inline Vector3::Vector3()
{
x = 0;y = 0;z = 0;
}
inline Vector3::~Vector3() {}
inline Vector3 operator +(const Vector3& a, const Vector3& b)
{
return Vector3(a.x + b.x, a.y + b.y, a.z + b.z);
}
inline Vector3 operator -(const Vector3& a, const Vector3& b)
{
return Vector3(a.x - b.x, a.y - b.y, a.z - b.z);
}
inline Vector3 operator * (float32 t, const Vector3& v)
{
return Vector3(v.x * t, v.y * t, v.z * t);
}
inline Vector3 operator * (const Vector3& v, float32 t)
{
return Vector3(v.x * t, v.y * t, v.z * t);
}
inline Vector3 operator /(const Vector3& v, float32 t)
{
return Vector3(v.x / t, v.y / t, v.z / t);
}
inline bool operator ==(const Vector3& a, const Vector3& b)
{
return (a.x == b.x && a.y == b.y && a.z == b.z);
}
inline bool operator !=(const Vector3& a, const Vector3& b)
{
return (a.x != b.x || a.y != b.y || a.z != b.z);
}
inline Vector3 operator -(const Vector3& a)
{
return Vector3(-a.x, -a.y, -a.z);
}
inline bool operator < (const Vector3& a, const Vector3& b)
{
return a.x < b.x && a.y < b.y&& a.z < b.z;
}
inline bool operator > (const Vector3& a, const Vector3& b)
{
return a.x > b.x && a.y > b.y && a.z > b.z;
}
inline float32 Dot(Vector3 a, Vector3 b)
{
return a.x * b.x + a.y * b.y + a.z * b.z;
}
inline float32 Angle(Vector3 a, Vector3 b)
{
a.Normalize();
b.Normalize();
float32 rad = ACos(Dot(a, b));
return (float32)(rad * RAD_TO_DEG);
}
inline float32 Distance(Vector3 a, Vector3 b)
{
Vector3 dis = a - b;
return dis.Magnitude();
}
inline Vector3 Cross(Vector3 a, Vector3 b)
{
float32 x = a.y * b.z - a.z * b.y;
float32 y = a.z * b.x - a.x * b.z;
float32 z = a.x * b.y - a.y * b.x;
return Vector3(x, y, z);
}
inline Vector3 Lerp(Vector3 form, Vector3 to, float32 t)
{
return (to - form) * t + form;
}
inline Vector3 Max(Vector3 lhs, Vector3 rhs)
{
return Vector3(Max(lhs.x, rhs.x), Max(lhs.y, rhs.y), Max(lhs.z, rhs.z));
}
inline Vector3 Min(Vector3 lhs, Vector3 rhs)
{
return Vector3(Min(lhs.x, rhs.x), Min(lhs.y, rhs.y), Min(lhs.z, rhs.z));
}
inline Vector3 Reflect(Vector3 inDirection, Vector3 inNormal)
{
return inDirection - 2 * (Dot(inDirection, inNormal) * inNormal);
}
inline Vector3 Project(Vector3 vector, Vector3 onNormal)
{
onNormal.Normalize();
return Dot(vector, onNormal) * onNormal;
}
#endif
| true |
10250501518371f2538e960407ef9828dd2ccc2a | C++ | gelatinstudios/Shmetris | /tetrominos.cpp | UTF-8 | 3,768 | 2.734375 | 3 | [] | no_license |
#include <SDL2/SDL.h>
#include "shmetris_math.hpp"
#include "tetrominos.hpp"
const SDL_Point I[] = {{5, -1}, {3, -1}, {4, -1}, {6, -1}};
const SDL_Point O[] = {{4, -2}, {5, -2}, {4, -1}, {5, -1}};
const SDL_Point T[] = {{4, -1}, {3, -1}, {5, -1}, {4, -2}};
const SDL_Point J[] = {{4, -1}, {5, -1}, {3, -1}, {3, -2}};
const SDL_Point L[] = {{4, -1}, {5, -1}, {3, -1}, {5, -2}};
const SDL_Point S[] = {{4, -2}, {5, -2}, {3, -1}, {4, -1}};
const SDL_Point Z[] = {{4, -2}, {3, -2}, {4, -1}, {5, -1}};
const SDL_Point *shapes[] = {I, O, T, J, L, S, Z};
const Uint32 rgba_colors[] = {
[TYPE_I] = 0xFFFFFF00, //light blue
[TYPE_O] = 0xFF00FFFF, //yellow
[TYPE_T] = 0xFFFF00A7, //purple
[TYPE_J] = 0xFFFF0000, //blue
[TYPE_L] = 0xFF0091FF, //orange
[TYPE_S] = 0xFF00FF00, //green
[TYPE_Z] = 0xFF0000FF //red
};
void Bag::shuffle() {
xorshift32_state *const state = &rng_state;
for (Uint8 i = 6; i >= 1; --i) {
const Uint8 j = rng(i, state);
const Uint8 tmp = types[j];
types[j] = types[i];
types[i] = tmp;
}
index = 0;
}
void Tetromino::make_new(Bag &bag) {
type = bag.types[bag.index];
if (bag.index == 6) {
bag.shuffle();
} else ++bag.index;
for (Uint8 i = 0; i < 4; ++i) {
points[i].x = shapes[type][i].x;
points[i].y = shapes[type][i].y;
}
orientation = 0;
}
void Tetromino::move_left(const Uint32 playfield[10*20]) {
for (Uint8 i = 0; i < 4; ++i) {
if (points[i].x - 1 < 0 || playfield[coord_to_index(points[i].x - 1, points[i].y)])
return;
}
for (Uint8 i = 0; i < 4; ++i) {
--points[i].x;
}
}
void Tetromino::move_right(const Uint32 playfield[10*20]) {
for (Uint8 i = 0; i < 4; ++i) {
if (points[i].x + 1 > 9 || playfield[coord_to_index(points[i].x + 1, points[i].y)])
return;
}
for (Uint8 i = 0; i < 4; ++i) {
++points[i].x;
}
}
void Tetromino::rotate_left(const Uint32 playfield[10*20]) {
if (type == TYPE_O) return;
Tetromino result = *this;
result.type = type;
for (Uint8 i = 1; i < 4; ++i) {
const int x = points[0].x - points[i].x;
const int y = points[0].y - points[i].y;
result.points[i].x = points[0].x - y;
result.points[i].y = points[0].y + x;
if(!in_bounds(result.points[i]) || playfield[coord_to_index(result.points[i].x, result.points[i].y)])
return;
}
result.orientation = (orientation - 1 + 4) % 4;
*this = result;
}
void Tetromino::rotate_right(const Uint32 playfield[10*20]) {
if (type == TYPE_O) return;
Tetromino result = *this;
result.type = type;
for (Uint8 i = 1; i < 4; ++i) {
const int x = points[0].x - points[i].x;
const int y = points[0].y - points[i].y;
result.points[i].x = points[0].x + y;
result.points[i].y = points[0].y - x;
if(!in_bounds(result.points[i]) || playfield[coord_to_index(result.points[i].x, result.points[i].y)])
return;
}
result.orientation = (orientation + 1) % 4;
*this = result;
}
void Tetromino::blit_to_playfield(Uint32 playfield[10*20]) {
for (Uint8 i = 0; i < 4; ++i) {
const int n = coord_to_index(points[i].x, points[i].y);
SDL_assert(n > 0);
playfield[n] = rgba_colors[type];
}
}
| true |
8522bd7a9a5d70a985715774f0fee083117f5260 | C++ | huangruikai/ATM | /mian.cpp | UTF-8 | 1,862 | 3.34375 | 3 | [] | no_license | #include <iostream>
using namespace std;
/*用户类*/
class people {
protected:
int account_number;
int password;
public:
people(int n, int m) {
account_number = n;
password = m;
}
int get_account_number(void);
int get_password(void);
private:
int i;
};
int people::get_account_number(void) {
return account_number;
}
int people::get_password(void) {
return password;
}
people obj[2] = {
people(227,123),
people(526,456)
};
/*ATM类*/
class ATM {
protected:
public:
void better();
void cin_account_number_s();
void cin_password_s();
void get_account_number_b(int i);
void get_password_b(int i);
void ATM_function();
void print_message();
private:
int password_b;
int account_number_b;
int password_s;
int account_number_s;
};
void ATM::cin_account_number_s() {
cout << "请输入账号";
cin >> account_number_s;
}
void ATM::cin_password_s() {
cout << "请输入密码";
cin >> password_s;
}
void ATM::get_account_number_b(int i) {
account_number_b = obj[i].get_account_number();
}
void ATM::get_password_b(int i) {
password_b = obj[i].get_password();
}
void ATM::better() {
int i;
for (i = 0; i < 2; i++) {
account_number_b = obj[i].get_account_number();
if (account_number_b == account_number_s) {
password_b = obj[i].get_password();
if (password_b == password_s) {
cout << "登录成功" << "\n";
ATM_function();
}
else cout << "密码错误" << "\n";
}
}
}
void ATM::print_message() {
}
void ATM::ATM_function() {
int function = 0;
cout << "按1查看信息\n";
cout << "按2取款\n";
cout << "按3修改密码\n";
switch (function) {
case 1:
print_message(); break;
}
}
int main() {
ATM atm;
atm.cin_account_number_s();
atm.cin_password_s();
atm.better();
return 0;
}
| true |
c25dbe37de48499b13eb535abff44fb9b857da01 | C++ | A-STAR0/hackerrank-solutions-1 | /Algorithms/Strings/alternating-characters.cpp | UTF-8 | 558 | 2.828125 | 3 | [
"MIT"
] | permissive | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main() {
int t; cin >> t;
vector<string> inputs(t);
for (int i = 0; i < t; i++)
cin >> inputs[i];
for (int i = 0; i < t; i++) {
int charsToDel = 0;
for (int j = 0, n = inputs[i].size() - 1; j < n; j++) {
if (inputs[i][j] == inputs[i][j + 1]) {
charsToDel++;
}
}
cout << charsToDel << endl;
}
return 0;
}
| true |
694bb0b27f5a68e2093d68f8d9715fb7b9faa6bf | C++ | Maxai2/CharArray | /CharArray/CharArray/Source.cpp | UTF-8 | 8,316 | 3.390625 | 3 | [] | no_license | #include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <ctype.h>
#include "Functions.h"
#include "CharLibrary.h"
#define size 255
// const int size = 255;
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
using namespace std;
int main()
{
/*1. Дана строка символов. Заменить в ней все пробелы на табуляции
3. Подсчитать количество слов во введенном предложении.*/
//char *str = new char[size];
//cout << "Text: ";
//cin.getline(str, size);
//int count = 0;
//count = countWord(str) + 1;
//cout << "Count of word: " << count;
//str = spaceToTab(str, size);
//cout << "\nNew text: " << str << endl;
//-------------------------------------------------------------------------------------
/*7. Создать библиотеку следующих функций:
// a. int mystrlen(const char * str); - функция определяет длину строки.
//char *str = new char[size];
//cout << "Text: ";
//cin.getline(str, size);
//int count = 0;
//count = mystrlen(str) - 1;
//cout << "Count of word: " << count << endl;
//-----------------------------------------------------------------------------------------------
/*b. char * mystrcpy (char * str1, const char * str2);
- функция копирует строку str2 в буфер, адресуемый через str1.
Функция возвращает указатель на первую строку str1. */
//cout << "String one: ";
//char *str1 = new char[size];
//cin.getline(str1, size);
//cout << "String two: ";
//char *str2 = new char[size];
//cin.getline(str2, size);
//str1 = mystrcpy(str1, str2);
//cout << "\n\nResult: " << str1 << endl;
//-----------------------------------------------------------------------------------------------
/* c. char * mystrcat (char * str1, const char * str2); - функция
присоединяет строку str2 к строке str1. Функция возвращает
указатель на первую строку str1.*/
//cout << "string one: ";
//char *str1 = new char[size];
//cin.getline(str1, size);
//cout << "string two: ";
//char *str2 = new char[size];
//cin.getline(str2, size);
//str1 = mystrcat(str1, str2);
//cout << "\nstring two + string one: " << str1 << endl;
//-----------------------------------------------------------------------------------------------
/* d. char * mystrchr (char * str, char s); - функция осуществляет
поиск символа s в строке str. Функция возвращает указатель
на первое вхождение символа в строку, в противном случае 0.*/
//char *str = new char[size];
//cout << "String: ";
//cin.getline(str, size);
//cout << "Input the symbol to search: ";
//char s;
//cin >> s;
//if (mystrchr(str, s) != 0)
//{
// str = mystrchr(str, s);
// cout << "\nWe found place at the beginning your symbol: " << str << endl;
//}
//else
// cout << "\nSorry we does not found your symbol in the string(" << endl;
//-----------------------------------------------------------------------------------------------
/* e. char * mystrstr (char * str1, char * str2); - функция
осуществляет поиск подстроки str2 в строке str1. Функция
возвращает указатель на первое вхождение подстроки str2 в
строку str1, в противном случае 0.*/
//cout << "String: ";
//char *str = new char[size];
//cin.getline(str, size);
//cout << "Input similar pharase: ";
//char *phrase = new char[size];
//cin.getline(phrase, size);
//if (mystrstr(str, phrase) != 0)
//{
// str = mystrstr(str, phrase);
// cout << "\nWe found the word in which your phrase meeting: " << str << endl;
//}
//else
// cout << "\nSorry we does not found your phrase in the string(" << endl;
//-----------------------------------------------------------------------------------------------
/* f. int mystrcmp (const char * str1, const char * str2); - функция
сравнивает две строки, и , если строки равны возвращает 0,
если первая строка больше второй, то возвращает 1, иначе -1.*/
//cout << "Input the first string: ";
//char *str1 = new char[size];
//cin.getline(str1, size);
//cout << "Input the second string: ";
//char *str2 = new char[size];
//cin.getline(str2, size);
//cout << endl;
//if (mystrcmp(str1, str2) == -1)
// cout << "The function return us: " << mystrcmp(str1, str2) << ", so that mean the first string is less than the second.";
//else if (mystrcmp(str1, str2) == 0)
// cout << "The function return us: " << mystrcmp(str1, str2) << ", so that mean first string is equal to second.";
//else if (mystrcmp(str1, str2) == 1)
// cout << "The function return us: " << mystrcmp(str1, str2) << ", so that mean the first string is more than the second.";
//cout << endl;
//-----------------------------------------------------------------------------------------------
/* g. int StringToNumber( char * str); - функция конвертирует
строку в число и возвращает это число.*/
//cout << "Text: ";
//char *str = new char[size];
//cin.getline(str, size);
//cout << "Your text in number format from ASCII table is(32 is space): " << StringToNumber(str) << endl;
//-----------------------------------------------------------------------------------------------
/* h. char * NumberToString ( int number); - функция конвертирует
число в строку и возвращает указатель на эту строку.*/
cout << "Symbols: ";
short row = 1, col = 0;
for (int i = 32; i <= 126; i++)
{
SetConsoleCursorPosition(h, { col, row });
if (32 <= i && i <= 47 || 58 <= i && i <= 64 || 91 <= i && i <= 96 || 123 <= i && i <= 126)
{
cout << "\'" << char(i) << "\' - " << i;
row++;
}
if (row == 5 && row != 0)
{
col += 13; row = 1;
}
}
SetConsoleCursorPosition(h, { 0, 6 });
cout << "Numbers: ";
row = 7, col = 0;
for (int i = 48; i <= 57; i++)
{
SetConsoleCursorPosition(h, { col, row });
cout << "\'" << char(i) << "\' - " << i;
row++;
if (row == 9 && row != 0)
{
col += 13; row = 7;
}
}
SetConsoleCursorPosition(h, { 0, 10 });
cout << "Alphabets: ";
row = 11, col = 0;
for (int i = 65; i <= 90; i++)
{
SetConsoleCursorPosition(h, { col, row });
if (i <= 67)
cout << "\'" << char(i) << "\' - " << i << " \'" << char(i + 32) << "\' - " << i + 32 << " |";
else
cout << "\'" << char(i) << "\' - " << i << " \'" << char(i + 32) << "\' - " << i + 32 << " |";
row++;
if (row == 16 && row != 0)
{
col += 20; row = 11;
}
}
SetConsoleCursorPosition(h, { 0, 17 });
cout << "Number: ";
unsigned _int64 num;
cin >> num;
cout << "Your number in text format by ASCII table is(32 is space): " << NumberToString(num) << endl;
//-----------------------------------------------------------------------------------------------
/* i. char * Uppercase (char * str1); - функция преобразует строку
в верхний регистр.*/
//cout << "Text: ";
//char *text = new char(size);
//cin.getline(text, size);
//cout << "Your text in Uppercase format: " << Uppercase(text) << endl;
//-----------------------------------------------------------------------------------------------
/* j. char * Lowercase (char * str1); - функция преобразует строку
в нижний регистр.*/
//cout << "Text: ";
//char *text = new char(size);
//cin.getline(text, size);
//cout << "Your text in Lowercase format: " << Lowercase(text) << endl;
//-----------------------------------------------------------------------------------------------
/* k. char * mystrrev (char * str); - функция реверсирует строку и
возвращает указатель на новую строку.*/
//cout << "Text: ";
//char *text = new char(size);
//cin.getline(text, size);
//cout << "Your text in revers format: " << mystrrev(text) << endl;
} | true |
af7e95bc9298cb0b5a8e81c14818133b7d3a01f5 | C++ | a-colombo/Identikeep | /Plugins/Linux/Mem/Mem.cpp | UTF-8 | 1,830 | 2.734375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include "Utils.h"
#include "multire.h"
#include "Mem.h"
// Logging
#include "plog/Log.h"
#define MEM_INFO_FILE "/proc/meminfo"
bool MEM::Collect(int argc, char *argv[])
{
bool is_ok=true;
LOG_VERBOSE << "Parsing " << this->Name() << " info...";
/* Open /proc/meminfo for reading. This should be perfectly fine on linux */
std::ifstream ifs(MEM_INFO_FILE);
if (ifs.fail()) {
LOG_ERROR << "Could not open " MEM_INFO_FILE;
return false;
}
/* parse all content into cpu_info string, used later for regex matching */
std::string mem_info( (std::istreambuf_iterator<char>(ifs) ),
(std::istreambuf_iterator<char>() ) );
/* == Get Total Memory, kB == */
std::vector<std::string> res = DoRegexMatch(mem_info, "MemTota[l|l ]:[ \t]+([0-9]+)[ \t]*kB");
LOG_DEBUG << "Total memory parsing got " << res.size() << " elements.";
if (res.size() > 0) {
int msize = 0;
/* Only one entry in /proc/meminfo for Total memory,
* try to convert it to int */
try {
if (res.size() == 1) {
msize = std::stoi(res[0]);
} else {
LOG_ERROR << "Invalid number of elements in Total memory: " << res.size() << " elements.";
is_ok = false;
}
} catch (const std::exception &e) { LOG_ERROR << "Error in MEM::Collect:" << e.what(); is_ok = false; }
/* Only add value if valid */
if ( msize > 0 ) {
Item<int> i = Item<int>("memTotal", "kB", match::none, msize);
m_items.integers.push_back(i);
}
} else {
LOG_ERROR << "Could not parse total memory.";
is_ok = false;
}
return is_ok;
};
| true |
c031173a93912902025c5a6cf912c47bcbbadcdf | C++ | XingXingXudong/LeetCodePractice | /11_strings/implement_strstr_28.cpp | UTF-8 | 1,735 | 3.4375 | 3 | [] | no_license | // https://leetcode.com/problems/implement-strstr/
#include <string>
#include <gtest/gtest.h>
void calNext(const std::string& needle, std::vector<int>& next) {
for (int j = 1, p = -1; j < (int)needle.length(); ++j) {
while (p > - 1 && needle[p+1] != needle[j]) {
p = next[p]; // 如果下一位置不同,往前回溯
}
if (needle[p + 1] == needle[j]) {
++p; // 如果下一位置相同,更新相同的最大前缀和最大后缀长
}
next[j] = p;
}
}
int strStr(const std::string& haystack, const std::string& needle) {
int k = -1, n = haystack.length(), p = needle.length();
if (p == 0) {
return 0;
}
auto next = std::vector<int>(p, -1);
calNext(needle, next); // 计算next数组
for (int i = 0; i < n; ++i) {
while (k > -1 && needle[k + 1] != haystack[i]) {
k = next[k]; // 有部分匹配,往前回溯
}
if (needle[k + 1] == haystack[i]) {
++k;
}
if (k == p-1) {
return i - p + 1; // 完成匹配,返回匹配的起始位置
}
}
return -1;
}
TEST(strStr, a) {
std::string haystack = "hello";
std::string needle = "ll";
int output = 2;
EXPECT_EQ(strStr(haystack, needle), output);
}
TEST(strStr, b) {
std::string haystack = "aaaaa";
std::string needle = "bba";
int output = -1;
EXPECT_EQ(strStr(haystack, needle), output);
}
TEST(strStr, c) {
std::string haystack = "";
std::string needle = "";
int output = 0;
EXPECT_EQ(strStr(haystack, needle), output);
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | true |
106346d599b44ac96771616bc82878753be86959 | C++ | Saptarshi-Nag189/Data-Structure-in-C- | /arr_rev_using_stack.cpp | UTF-8 | 302 | 2.984375 | 3 | [] | no_license | #include <iostream>
#include "stack_class.cpp"
using namespace std;
int main()
{
class Stack s;
int arr[]={1,2,3,4,5};
for (int i = 0; i < 5; i++)
{
s.push(arr[i]);
}
for (int i = 0; i < 5; i++)
{
arr[i] = s.pop();
}
return 0;
} | true |
0e2e675605f668fbddb39a5bd0374ad934921951 | C++ | huyquynh2302/Game | /gamedev-intro-tutorials-master/02-Sprite/Enemy1.cpp | UTF-8 | 1,752 | 2.609375 | 3 | [] | no_license | #include "Game.h"
#include "Enemy1.h"
//CEnemy1::CEnemy1(float x, float y, float vx) :CEnemy(x, y)
//{
// this->vx = vx;
//};
//CEnemy1::CEnemy1()
//{
// this->x = ENEMY_X;
// this->y = ENEMY_Y;
// this->vx = ENEMY_WALKING_SPEED;
// this->vy = 0.0f;
//}
void CEnemy1::Update(DWORD dt)
{
CEnemy::GetVX();
CEnemy::Update(dt);
//Ngang
//CEnemy1::SetPosition();
//CEnemy1::SetSpeed();
//x += vx * dt;
//y += vy * dt;
//vx = ENEMY_WALKING_SPEED;
//int BackBufferWidth = CGame::GetInstance()->GetBackBufferWidth();
if (x <= 0 || x >= 290) {
vx = -vx;
if (x <= 0)
{
x = 0;
}
else if (x >= 290)
{
x = (float)(290);
}
}
//Doc
/*y += vx * dt;
int BackBufferHeight = CGame::GetInstance()->GetBackBufferHeight();
if (y <= 0 || y >= BackBufferHeight - ENEMY_HEIGHT) {
vx = -vx;
if (y <= 0)
{
y = 0;
}
else if (y >= BackBufferHeight - ENEMY_HEIGHT)
{
y = (float)(BackBufferHeight - ENEMY_HEIGHT);
}
}*/
}
void CEnemy1::Render()
{
//[RED FLAG][TODO]: Student needs to think about how to associate this animation/asset to Mario!!
//if (vx > 0) ani = CAnimations::GetInstance()->Get(500);
//else ani = CAnimations::GetInstance()->Get(501);
//vector<LPANIMATION> animations;
int ani;
if (vx == 0)
{
if (nx > 0) ani = ENEMY_ANI_IDLE_RIGHT;
else ani = ENEMY_ANI_IDLE_LEFT;
}
else if (vx > 0)
ani = ENEMY_ANI_WALKING_RIGHT;
else ani = ENEMY_ANI_WALKING_LEFT;
animations[ani]->Render(x, y);
}
void CEnemy1::SetState(int state)
{
CEnemy::SetState(state);
switch (state)
{
case ENEMY_STATE_WALKING_RIGHT:
vx = ENEMY_WALKING_SPEED;
nx = 1;
break;
case ENEMY_STATE_WALKING_LEFT:
vx = -ENEMY_WALKING_SPEED;
nx = -1;
break;
case ENEMY_STATE_IDLE:
vx = 0;
break;
}
} | true |
c25b3517dce921c1dc039f185cec80a1c11ab005 | C++ | RajasekharMugada/cpp_programming | /02_template_function.cpp | UTF-8 | 343 | 3.609375 | 4 | [] | no_license | /*
@author: Rajasekhar Mugada
@brief : template function/ generic function
*/
#include <iostream>
using namespace std;
template <class T>
T max_num(T a, T b)
{
if(a > b)
return a;
else
return b;
}
int main()
{
cout << max_num(1, 2) << endl;
cout << max_num(1.0f, 2.5f) << endl;
return 0;
}
| true |
274ee2f4f98bc1cb989823f66b5218fb9232207d | C++ | shunail2029/algorithm | /sort/radix_sort.cpp | UTF-8 | 2,451 | 3.578125 | 4 | [] | no_license | #include <iostream>
#include <new>
#include <typeinfo>
template<class RandomAccessIterator>
void radix_sort(RandomAccessIterator first, RandomAccessIterator last, long long digit = 1) {
if (first == last) {
return;
}
auto val = *first;
using type = decltype(val);
if (typeid(val) != typeid(int) && typeid(val) != typeid(long long)) {
std::cout << "this sort can only be used for integer allay." << std::endl;
return;
}
int len = last - first;
type *zero = new type[len];
type *one = new type[len];
int cnt_zero = 0, cnt_one = 0;
bool finish = true;
for (auto iter = first; iter != last; iter++) {
type tmp = *iter;
if (tmp > digit) {
finish = false;
}
if ((tmp & digit) == 0) {
zero[cnt_zero++] = tmp;
} else {
one[cnt_one++] = tmp;
}
}
int cur = 0;
for (int i=0; i<cnt_zero; i++) {
*(first+cur) = zero[i];
cur++;
}
for (int i=0; i<cnt_one; i++) {
*(first+cur) = one[i];
cur++;
}
delete [] zero;
delete [] one;
if (finish) {
return;
} else {
::radix_sort(first, last, digit << 1);
}
}
template<class RandomAccessIterator>
void radix_sort_greater(RandomAccessIterator first, RandomAccessIterator last, long long digit = 1) {
if (first == last) {
return;
}
auto val = *first;
using type = decltype(val);
if (typeid(val) != typeid(int) && typeid(val) != typeid(long long)) {
std::cout << "this sort can only be used for integer allay." << std::endl;
return;
}
int len = last - first;
type *zero = new type[len];
type *one = new type[len];
int cnt_zero = 0, cnt_one = 0;
bool finish = true;
for (auto iter = first; iter != last; iter++) {
type tmp = *iter;
if (tmp > digit) {
finish = false;
}
if ((tmp & digit) == 0) {
zero[cnt_zero++] = tmp;
} else {
one[cnt_one++] = tmp;
}
}
int cur = 0;
for (int i=0; i<cnt_one; i++) {
*(first+cur) = one[i];
cur++;
}
for (int i=0; i<cnt_zero; i++) {
*(first+cur) = zero[i];
cur++;
}
delete [] zero;
delete [] one;
if (finish) {
return;
} else {
::radix_sort_greater(first, last, digit << 1);
}
}
| true |
800b603c2fa3985ce846fec9204fc58c83605ff9 | C++ | Paul-Kummer/angleDetection | /angleProject/getAngleModule/functions/functions.cpp | UTF-8 | 8,269 | 2.890625 | 3 | [] | no_license | #include "..\prototypes.h"
#include "..\escapi3\escapi.h"
//for purpose of line drawing, the bottom left of the image is (0,0)
//draw x and y are both needed for cases of vertical and horizxontal lines
void makeLine(imageArr& pixArr, float yIntercept, float slope, Pixel lineColor, int lineSize)
{
int yIndex, y, yLineSize, x;
for(int xIndex = 0; xIndex < WIDTH; xIndex++)
{
yIndex = HEIGHT-y;
yLineSize = lineSize + ( ( (abs(slope) /(float)1000) * HEIGHT ) ); //Adjust the marker line for near vertical lines
y = (int)((slope * (float)xIndex) + yIntercept);
if(yIndex > 0 && yIndex < HEIGHT); //Make sure the point is on the image
{
//span the lineSize on the x axis of both sides of the point
for(int aroundX = xIndex-lineSize; aroundX < xIndex+lineSize; aroundX++)
{
//span the lineSize on the y axis of both sides of the point
for(int aroundY = yIndex-yLineSize; aroundY < yIndex+yLineSize; aroundY++)
{
//ensure the pixels to change are on the image plane
if(aroundX > 0 && aroundX < WIDTH && aroundY > 0 && aroundY < HEIGHT)
{
pixArr[aroundY][aroundX] = lineColor; //change the color of pixels on the path of the line
}
}
}
}
}
}
//Method: Line of Best Fit (Least Square Method)
float getAngle (imageArr& pixArr, bool drawLine, bool showStats)
{
float slope, angle, yIntercept, xIntercept;
float ptCount;
float xSum, xAvg, xSqrSum;
float ySum, yAvg, ySqrSum;
float xMinusXAvgTimesYMinusYAvgSum, xMinusXAvgSqrSum;
float yMinusYAvgSqrSum;
std::vector<std::pair<int,int>> pointArray;
//statistical analysis
float yActual, xActual;
float yPredicted, xPredicted;
float residual, residualSquared;
float yMinusYBar, yMinusYBarSquared;
float xRes, xResSqr;
float xMinXBar, xMinXBarSqr;
float rSquared, xRSqr;
float goodnessOfFit, xGOF;
for(float y = 0; y < HEIGHT; y++) //HEIGHT
{
for(float x = 0; x < WIDTH; x++) //WIDTH
{
if(pixArr[y][x].getRed()==0) //all three colors will be 0 for black, so only one needs to be checked
{
int xPos = x, yPos = (HEIGHT - y); // y position has to be adjusted for top down approach
pointArray.push_back(std::make_pair(xPos,yPos));
xSum += x;
ySum += yPos;
xSqrSum += pow(x,2);
ySqrSum += pow(yPos, 2);
ptCount++;
}
}
}
//prevent divide by zero, and set to resonable value if ptCount is zero
xAvg = ptCount>0?xSum/ptCount:0;
yAvg = ptCount>0?ySum/ptCount:1;
//determine the line of best fit for the points
for(int i = 0; i < pointArray.size(); i++)
{
//y=mx+b for horizontal to 45, x=ny+p for vertical
float x = (float)pointArray[i].first, y = (float)pointArray[i].second;
xMinusXAvgTimesYMinusYAvgSum += ((x - xAvg)*(y - yAvg));
xMinusXAvgSqrSum += pow((x - xAvg), 2);
yMinusYAvgSqrSum += pow((y - yAvg), 2);
}
//multiply by -1 because the image is read backwards
//angle = -1*((atan(slope) * 180) / 3.14159265); not accurate when line is close to vertical
angle = atan2(yMinusYAvgSqrSum, xMinusXAvgSqrSum) * 180 / 3.14159265;
//Slope determined using Least Square Method
//if the denominator is zero, the line is vertical and a slope of infinity
slope = xMinusXAvgSqrSum!=0?(xMinusXAvgTimesYMinusYAvgSum / xMinusXAvgSqrSum):100000000;
yIntercept = yAvg - (slope * xAvg);
xIntercept = -yIntercept / -slope;
if(showStats)
{
//[(-inf : -1), (1 : +inf)] slopes over 1 and under -1 should use the x intercept form, vertical lines
//(-1 : 1) slopes under 1 and over -1 should use the y intercept form, horizontal lines
for(int i = 0; i < pointArray.size(); i++)
{
yActual = pointArray[i].second;
xActual = pointArray[i].first;
yPredicted = (slope * xActual) + yIntercept;
xPredicted = (yActual - yIntercept)/slope;
residual += (yActual-yPredicted);
xRes += (xActual-xPredicted);
residualSquared += pow(residual,2);
xResSqr += pow(xRes,2);
yMinusYBar += (yActual-yAvg);
xMinXBar += (xActual-xAvg);
yMinusYBarSquared += pow(yMinusYBar, 2);
xMinXBarSqr += pow(xMinXBar, 2);
}
//R^2 = SSR/SST || 1-SSE/SST || SSR/(SSR+SSE)
rSquared = 1 - (residualSquared/yMinusYBarSquared);
xRSqr = 1 - (xResSqr/xMinXBarSqr);
goodnessOfFit = 100 * rSquared; //y intercept line, close to horizontal
xGOF = 100 * xRSqr; //x intercept line, close to vertical
//Change this to use the formula with the best fit
//printf("Image Width(pixels): %i\n", WIDTH);
//printf("Image Height(pixels): %i\n", HEIGHT);
//printf("y Average: %5.0f\n", yAvg);
//printf("x Average: %5.0f\n", xAvg);
//printf("Sum Squared Regression(SSR): %5.2f\n",residualSquared);
//printf("Total Sum of Squares(SST): %5.2f\n",yMinusYBarSquared);
printf("X Intercept: %.0f\n", xIntercept);
printf("Y Intercept: %.0f\n", yIntercept);
printf("The xLine Fits: %3.0f Percent | R^2: %1.6f\n", xGOF, xRSqr);
printf("The Line Fits: %3.0f Percent | R^2: %1.6f\n", goodnessOfFit, rSquared);
printf("The Slope is: %3.4f\n", slope);
printf("The Angle is: %3.1f\n", angle);
}
//this will add a line of best fit to the bmp created
if(drawLine)
{
//Make Line Should be Changed to use xIntercept form when the line slope is close to +-inf
Pixel lineColor = Pixel(0,255,0); //make the line of best fit green
makeLine(pixArr, yIntercept, slope, lineColor, (int)1);
}
return angle;
};
void toBlackAndWhite(imageArr& pixArr, int maxColorLimit, int trimAmount)
{
for(int y = 0; y < HEIGHT; y++) //HEIGHT
{
for(int x = 0; x < WIDTH; x++) //WIDTH
{
pixArr[y][x];
//when all the colors are the same value, a shade of grey will be produced
int avgColor = ((pixArr[y][x].getRed() + pixArr[y][x].getGreen() + pixArr[y][x].getBlue())/3); // (red + green + blue)/3 = 0-255
avgColor = avgColor<maxColorLimit?0:255; //remove all colors that don't meet the threshold, and make all other color black
if(y > trimAmount && x > trimAmount && y < (HEIGHT-trimAmount) && x < (WIDTH-trimAmount)) //trim off 10 pixels around the border
{
pixArr[y][x].setRGB(avgColor, avgColor, avgColor);
}
else
{
pixArr[y][x].setRGB(255, 255, 255);
}
}
}
};
//this should be its own thread
void captureImages (imageArr bmpPixels, float* angle)
{
char* imageName = (char*)"testImage.bmp";
bool atAngle, setGuard=true;
/* Initialize ESCAPI */
int devices = setupESCAPI();
setCaptureProperty(0,13,3,0); //look in escapi.h for propery values
if (devices == 0)
{
printf("ESCAPI initialization failure or no devices found.\n");
}
struct SimpleCapParams capture;
capture.mWidth = WIDTH;
capture.mHeight = HEIGHT;
capture.mTargetBuf = new int[HEIGHT * WIDTH];
if (initCapture(0, &capture) == 0) //0 is device one
{
printf("Capture failed - device may already be in use.\n");
};
//request a capture
doCapture(0);
while (isCaptureDone(0) == 0)
{
// Wait until capture is done.
};
//each index an int consisting of 4 bytes, alpha(1byte), red(1byte), green(1byte), blue(1byte)
int count = 0;
for(int y = 0; y < HEIGHT; y++) //HEIGHT
{
for(int x = 0; x < WIDTH; x++) //WIDTH
{
//(HEIGHT-y)*WIDTH will give the posision of the row that is being iterated
//(WIDTH-x) will give the current position within the row
bmpPixels[y][x] = Pixel(capture.mTargetBuf[((HEIGHT-y)*WIDTH)+(WIDTH-x)]);
count++;
};
};
//clean up the image and make it black and white
toBlackAndWhite(bmpPixels);
*angle = getAngle(bmpPixels, false, false); //returns the angle and takes input of pixel vector, draw line of best fit, and show statistics of line
//create an image of the current capture and put a line of best fit drawn over it
//makeImage(imageName, bmpPixels); //This will save an image of what was just caputured in bmp format
//pauses between capures, in micro seconds
//usleep(2000000);
deinitCapture(0);
};
float adjustToAngle()
{
float angleToAdjustTo;
std::cout << "What Angle Do You Desire?: ";
std::cin >> angleToAdjustTo;
return angleToAdjustTo;
}; | true |
a642d83852a72fcabbe80af4289a9c9abcb93608 | C++ | seoushi/Mini-Net | /samples/Client/main.cpp | UTF-8 | 1,169 | 3.046875 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | /*
* File: main.cpp
* Author: sean
*
* Created on January 13, 2011, 7:29 PM
*/
#include <iostream>
#include "Connection.hpp"
#include "Message.hpp"
int main(int argc, char** argv)
{
Connection con;
if(!con.connect("127.0.0.1", 7777))
{
std::cout << "could not connect to server, exiting" << std::endl;
return 1;
}
std::string input;
for(;;)
{
// get user message
std::getline(std::cin, input);
if(input == "quit!")
{
break;
}
if(!con.isConnected())
{
std::cout << "disconnected from server: exiting" << std::endl;
}
// send user message
DataBuffer buffer;
Message outMsg;
buffer << input;
outMsg.setData(buffer);
con << outMsg;
// get server response
Message inMsg;
for(;;)
{
if(con >> inMsg)
{
break;
}
}
std::string reply;
inMsg.data() >> reply;
std::cout << "got reply: " << reply << std::endl;
}
return 0;
}
| true |
ca684aaa4fcced25e730117528218b84476ab654 | C++ | EdCornejo/ImitateKRF | /Classes/Towers/BarrackTower.cpp | UTF-8 | 620 | 2.734375 | 3 | [] | no_license | #include "BarrackTower.h"
const float BarrackTower::kBarrackTowerLv1Scope = 150.0f;
const float BarrackTower::kBarrackTowerLv2Scope = 200.0f;
const float BarrackTower::kBarrackTowerLv3Scope = 250.0f;
BarrackTower::BarrackTower(): BaseTower(
TowerType::BARRACK, // type
"Barrack Tower", // name
1, // level
kBarrackTowerLv1Scope, // scope
kBarrackTowerLv2Scope, // next scope
1.0f, // rate
20.0f, // power
20, // upgrade price
10, // selling price
nullptr // target monster
) { }
BarrackTower::~BarrackTower() {
}
bool BarrackTower::init() {
if (!BaseTower::init()) {
return false;
}
return true;
}
| true |
2d73f6448b4b1ba19af10b01ba2ffd1c1800299d | C++ | iCodeIN/code-forces | /427e/main.cpp | UTF-8 | 1,397 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <cstdio>
#include <cstdint>
#include <cstdlib>
#include <cstring>
using namespace std;
#define BUF_LEN 1048576
uint8_t* buf;
uint32_t cur, len;
void fillBuf() {
cur = 0;
len = fread(buf, sizeof(uint8_t), BUF_LEN, stdin);
}
void initBuf() {
buf = (uint8_t*) calloc(BUF_LEN, sizeof(uint8_t));
fillBuf();
}
void destroyBuf() {
free(buf);
buf = 0;
}
int32_t getInt() {
int32_t ret = 0;
int32_t sign = 1;
while (cur < len && buf[cur] != '-' && (buf[cur] < '0' || '9' < buf[cur])) {
if ((++cur) == len) {
fillBuf();
}
}
if (cur < len && buf[cur] == '-') {
sign = -1;
if ((++cur) == len) {
fillBuf();
}
}
while (cur < len && '0' <= buf[cur] && buf[cur] <= '9') {
ret = 10 * ret + buf[cur] - '0';
if ((++cur) == len) {
fillBuf();
}
}
return sign * ret;
}
int main() {
initBuf();
int n = getInt(), m = getInt();
int mid = n / 2;
uint64_t total = 0;
int* criminals = (int*) calloc(n, sizeof(int));
for (int i = 0; i < n; ++i) {
criminals[i] = getInt();
}
for (int i = 0; i < mid; i += m) {
total += criminals[mid] - criminals[i];
}
for (int i = n - 1; mid < i; i -= m) {
total += criminals[i] - criminals[mid];
}
printf("%I64d\n", 2 * total);
return 0;
}
| true |
3c190006219a295a61d2e5d4f0aa810898c8d91f | C++ | naveen-ku/Competitive-Programming | /contests/codechef/8-2020-challange/ac4-w.cpp | UTF-8 | 794 | 2.578125 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void smallestKMP() {
// vector<string> s;
// vector<string> p;
// string input1, input2;
// cin >> input1;
// cin >> input2;
// s.push_back(input1);
// p.push_back(input2);
string s;
string p;
cin >> s;
cin >> p;
map<int, char> sc;
for (int i = 0; i < s.length(); i++) {
sc[i] = s[i];
}
for (int i = 0; i < p.length(); i++) {
for (int j = 0; j < sc.size(); j++) {
if (sc[j] == p[i]) {
sc.erase(j);
break;
}
}
}
for (auto i = sc.begin(); i != sc.end(); i++) {
cout << (*i).second;
}
}
int main() {
int t;
cin >> t;
while (t--) {
smallestKMP();
}
return 0;
} | true |
73bf7ae2cbb1c2ed626277e5dd9f698f8269a517 | C++ | gabrielkoyama/getting_started_with_Cplusplus | /a.cpp | UTF-8 | 1,095 | 3.25 | 3 | [] | no_license | // lista de exercicios http://www.inf.pucrs.br/~pinho/PRGSWB/Exercicios/Introducao/Introducao.html
#include <iostream>
using namespace std;
void ex1(){
int matriz[2][2];
int menor = 0;
//poppulando a matriz
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
cout << "matriz " << i << " " << j << ": ";
cin >> matriz[i][j];
}
}
menor = matriz[0][0];
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
if(menor > matriz[i][j]){
menor = matriz[i][j];
}
}
}
cout << "Menor: " << menor << endl;
}
void ex2(){
float nt1;
float nt2;
float nt3;
float ma;
float me;
cin >> nt1 >> nt2 >> nt3;
me = (nt1 + nt2 + nt3) / 3;
ma = (nt1 + nt2*2 + nt3*3 + me)/7;
if(ma >= 9){
cout << "A";
}
else if(ma >= 7.5 && ma < 9){
cout << "B";
}
else if(ma >= 6 && ma < 7.5){
cout << "C";
}
else if(ma >= 4 && ma < 6){
cout << "D";
}else{
cout << "E";
}
}
void ex3(){
// int n;
// cout << "Escolha um numero";
// cin >> n;
// for(int i = 0; i < n; i++){
// cout << i;
// }
}
int main(){
// ex1();
ex2();
return 0;
} | true |
2700b396c9365544d708717dab91ab954e2c542d | C++ | WojciechMula/random-binary-trees | /cpp/src/random.cpp | UTF-8 | 284 | 2.515625 | 3 | [] | no_license | #include "random.h"
namespace lcg {
static uint32_t state = 0;
const uint32_t a = 1103515245;
const uint32_t c = 12345;
uint32_t init(uint32_t seed) {
const uint32_t prev = state;
state = seed;
return prev;
}
uint32_t next() {
state = a * state + c;
return state;
}
}
| true |
3fa594b652517c9dabcd2dbc9b68b93fd44cc981 | C++ | jwalter229/CS3304 | /HW1_Quad/main.cpp | UTF-8 | 2,723 | 3.6875 | 4 | [] | no_license | #include "Quad.h"
#include <iostream>
#include <string>
using namespace std;
//testing Getters
bool Test_Gets()
{
//Declare Objects
//Passing 1,2,3 as parameters
Quad test(1,2,3);
bool passed = true;
//GetA Test
if(test.GetA() != 1)
{
cout << "Get A failed" << endl;
passed = false;
}
//GetB Test
if(test.GetB() != 2)
{
cout << "Get B failed" << endl;
passed = false;
}
//GetC Test
if(test.GetC() != 3)
{
cout << "Get C failed" << endl;
passed = false;
}
return passed;
}
//Testing x = 2
//for x^2 + 2x + 3 = 11
bool Test_Eval()
{
Quad test(1,2,3);
if(test.Eval(2) != 11)
{
cout << "Evaluate Failed Output. Expected 11." << endl;
return false;
}
return true;
}
//Testing to see how
//many zeros there are
bool Test_Cal_Number_Of_Zeros()
{
bool passed = true;
//Testing for
//no zeros
Quad test1(0,0,5);
if(!test1.Cal_Zero().empty())
{
cout << "Failed Calculate zeros at 0 zeros!" << endl;
passed = false;
}
//Testing the Quad
//for one zero
Quad test2(0,1,1);
{
if(test2.Cal_Zero().size() != 1)
{
cout << "Failed Calculate zeros at 1 zero" << endl;
passed = false;
}
}
//Testing the Quad
//for two zeros
Quad test3(1,0,-4);
{
if(test3.Cal_Zero().size()!=2)
{
cout << "Failed Calculate zeros at 2 zeros" << endl;
passed = false;
}
return passed;
}
}
//Determing the zeros
//of the Quad
bool Test_Cal_Zero()
{
Quad test (1,0,-4);
vector <double> output = test.Cal_Zero();
if(output[0] != 2 && output[0] != -2)
{
return false;
}
if(output[1] != 2 && output[1] != -2)
{
return false;
}
return true;
}
int main(int argc, char **argv)
{
if(Test_Gets() == true)
{
cout << "Passed Test_Gets!" << endl;
}
else
{
cout << "Failed Test_Gets!" << endl;
}
if(Test_Eval() == true)
{
cout << "Passed Test_Eval!" << endl;
}
else
{
cout << "Failed Test_Eval!" << endl;
}
if(Test_Cal_Number_Of_Zeros() == true)
{
cout << "Passed Test_Cal_Number_Of_Zeros!" << endl;
}
else
{
cout << "Failed Test_Cal_Number_Of_Zeros!" << endl;
}
if(Test_Cal_Zero() == true)
{
cout << "Passed Test_Zeros!" << endl;
}
else
{
cout <<"Failed Test_Zeros" << endl;
}
}
| true |
7ef31970e02bd1be6568bf68cb349e7e91ee6b5b | C++ | Azhao1993/Leetcode | /AnswerByCpp/0683_K Empty Slots.cpp | UTF-8 | 1,712 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using namespace std;
/*
683. K 个空花盆
花园里有 N 个花盆,每个花盆里都有一朵花。这 N 朵花会在 N 天内依次开放,每天有且仅有一朵花会开放并且会一直盛开下去。
给定一个数组 flowers 包含从 1 到 N 的数字,每个数字表示在那一天开放的花所在的花盆编号。
例如, flowers[i] = x 表示在第 i 天盛开的花在第 x 个花盆中,i 和 x 都在 1 到 N 的范围内。
给你一个整数 k,请你输出在哪一天恰好有两朵盛开的花,他们中间间隔了 k 朵花并且都没有开放。
如果不存在,输出 -1。
样例 1: 输入: flowers: [1,3,2] k: 1 输出: 2
解释: 在第二天,第一朵和第三朵花都盛开了。
样例 2: 输入: flowers: [1,2,3] k: 1 输出: -1
注释 : 给定的数组范围是 [1, 20000]。
1 <= N <= 20000
1 <= bulbs[i] <= N
bulbs is a permutation of numbers from 1 to N.
0 <= K <= 20000
*/
class Solution {
public:
int kEmptySlots(vector<int>& bulbs, int K) {
int left = 0, right = K+1, len = bulbs.size(), res = 20004;
vector<int> arr(len);
for (int i=0; i<len; i++) arr[bulbs[i] - 1] = i + 1;
for (int i=1; right<len; i++) {
if (i == right) res = min(res, max(arr[left], arr[right]));
if (i == right || arr[i] < max(arr[left], arr[right]))
left = i, right = i + K + 1;
}
return res == 20004 ? -1 : res;
}
};
int main(){
vector<int> arr{6,5,8,9,7,1,10,2,3,4};
int res = Solution().kEmptySlots(arr, 2);
cout << res << endl;
return 0;
} | true |
90c25a5ae78bae371d8994110f480331afcc7a27 | C++ | mallius/CppPrimer | /ch16/1624ex.cpp | UTF-8 | 281 | 3.25 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
template <typename T>
int compare(const T& v1, const T& v2)
{
if(v1 < v2)
return -1;
if(v2 < v1)
return 1;
return 0;
}
int main(void)
{
short si = 1;
int i = 2;
cout << compare(static_cast<int>(si), i) << endl;
return 0;
}
| true |
f0025de6cc2e312eb4fe7a564c127fe8bb6e99bc | C++ | Svengali/cblib | /profiler.h | UTF-8 | 4,778 | 2.59375 | 3 | [
"Zlib"
] | permissive | #pragma once
#include "Base.h"
#include "Timer.h"
#include "cblib_config.h"
/*****************
In-game real-time profiler
Reasonably light-weight when in Disabled mode.
Clients should primarily use the PROFILE macro, like :
void func()
{
PROFILE(func);
... do stuff ...
}
-------------------------------------
Profiler is "frame" based. Even if you're not doing like a frame-based realtime app, you can use the "frame" concept.
Basically a "frame" is one processing block, then Profiler will count things as per-processing block.
For example if you're processing database records, you call Profiler::Frame() for each record and the report will then
give you information in terms of how long per record.
*******************/
// @@ toggle here : ; uses QPC if you don't want TSC
#define PROFILE_TSC // much faster & more accurate, use when possible !
// usually toggle using SetEnabled() ; this compile-time switch turns it off completely
#ifndef CBLIB_PROFILE_ENABLED
#define CBLIB_PROFILE_ENABLED 1
#endif
START_CB
namespace Profiler
{
//-------------------------------------------------------------------------------------------
#ifdef PROFILE_TSC
inline uint64 GetTimer() { return Timer::GetAbsoluteTicks(); }
inline double GetSeconds() { return Timer::rdtscSeconds(); }
inline double TimeToSeconds(uint64 time) { return time * Timer::GetSecondsPerTick(); }
#else
inline uint64 GetTimer() { return Timer::QPC(); }
inline double GetSeconds() { return Timer::GetQPCSeconds(); }
inline double TimeToSeconds(uint64 time) { return time * Timer::GetSecondsPerQPC(); }
#endif
//-------------------------------------------------------------------------------------------
//! default is "Disabled"
// when you call SetEnabled() it doesn't actually start until you call a Frame()
void SetEnabled(const bool yesNo);
bool GetEnabled();
extern bool g_enabled; // ugly variable tunnel for fast checks
//! Push & Pop timer blocks
// (generally don't call directly, use "PROFILE" macro)
void Push(const int index,const char * const name, uint64 time);
void Pop( const int index,const uint64 delta);
int Index(const char * const name);
//! clear the counts
void Reset();
//! let us know when a frame happens
void Frame();
//! FPS queries
/*
float GetInstantFPS();
float GetAveragedFPS(); // over the last some frames
float GetTotalFPS(); // since startup
*/
//-------------------------------------------------------------------------------------------
void WriteRecords(const char * fileName);
void ReadRecords( const char * fileName);
void GetEntry(const int index, uint64 * pTime, int* pCount);
//! Spew it out to a report since the last Reset (you'll usually want to Report and Reset together)
//! dumpAll == false only reports the currently selected branch
//! dumpAll == true dumps all reports known to the profiler (up to some internal limit)
void Report(const bool dumpAll = false);
void SetReportNodes(bool enable);
bool GetReportNodes();
//! for walking the display :
void ViewAscend();
void ViewDescend(int which);
//-------------------------------------------------------------------------------------------
//! Useful class for profiling code. Since this stuff is for profiling
//! everything should be inline.
class AutoTimer
{
public:
__forceinline AutoTimer(int index,const char * name) : m_index(0)
{
if ( g_enabled )
{
m_index = index;
m_startTime = Profiler::GetTimer();
cb::Profiler::Push(index,name,m_startTime);
}
}
__forceinline ~AutoTimer()
{
if ( m_index ) // was enabled at Push time
{
uint64 endTime = Profiler::GetTimer();
Profiler::Pop( m_index, endTime - m_startTime );
}
}
private:
int m_index;
uint64 m_startTime;
};
//-------------------------------------------------------------------------------------------
#pragma pack(push)
#pragma pack(4)
struct ProfileRecord
{
int32 index;
uint64 time;
ProfileRecord() { }
ProfileRecord(int i,uint64 t) : index(i), time(t) { }
};
#pragma pack(pop)
COMPILER_ASSERT( sizeof(ProfileRecord) == 12 );
const ProfileRecord * GetRecords(int * pCount);
const char * GetEntryName(int index);
//-------------------------------------------------------------------------------------------
};
END_CB
#if CBLIB_PROFILE_ENABLED //{
#define PROFILE(Name) \
static int s_index_##Name = cb::Profiler::Index(_Stringize(Name)); \
cb::Profiler::AutoTimer profile_of_##Name(s_index_##Name,_Stringize(Name))
#define PROFILE_FN(Name) \
static int s_index_##Name = cb::Profiler::Index(_Stringize(Name)); \
cb::Profiler::AutoTimer profile_of_##Name(s_index_##Name,_Stringize(Name))
#else //}{
#define PROFILE(Name)
#define PROFILE_FN(Name)
#endif //} FINAL
| true |
dc2c8012b7b8286986dab49a8af95bf7b1dbf301 | C++ | robertgilmartin/Master | /ModuleWindow.cpp | UTF-8 | 1,854 | 2.921875 | 3 | [
"MIT"
] | permissive | #include "Globals.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "MemoryLeaks.h"
ModuleWindow::ModuleWindow()
{
}
// Destructor
ModuleWindow::~ModuleWindow()
{
}
// Called before render is available
bool ModuleWindow::Init()
{
LOG("Init SDL window & surface");
ret = true;
if(SDL_Init(SDL_INIT_VIDEO) < 0)
{
LOG("SDL_VIDEO could not initialize! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
else
{
CreateAWindow();
}
return ret;
}
// Called before quitting
bool ModuleWindow::CleanUp()
{
LOG("Destroying SDL window and quitting all SDL systems");
//Destroy window
if(window != NULL)
{
SDL_DestroyWindow(window);
}
//Quit SDL subsystems
SDL_Quit();
return true;
}
void ModuleWindow::CreateAWindow()
{
//Create window
int width = SCREEN_WIDTH;
int height = SCREEN_HEIGHT;
flags = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
if (FULLSCREEN == true)
{
flags |= SDL_WINDOW_FULLSCREEN;
}
window = SDL_CreateWindow(TITLE, SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, flags);
if (window == NULL)
{
LOG("Window could not be created! SDL_Error: %s\n", SDL_GetError());
ret = false;
}
else
{
//Get window surface
screen_surface = SDL_GetWindowSurface(window);
}
}
void ModuleWindow::WindowConfiguration(SDL_WindowFlags flag, bool state)
{
switch (flag)
{
case SDL_WINDOW_RESIZABLE:
SDL_SetWindowResizable(window, (SDL_bool)state);
break;
case SDL_WINDOW_BORDERLESS:
if (state)
{
SDL_SetWindowBordered(window, SDL_TRUE);
break;
}
else
{
SDL_SetWindowBordered(window, SDL_FALSE);
break;
}
default:
break;
}
}
void ModuleWindow::Brightness(float brightness)
{
SDL_SetWindowBrightness(window, brightness);
}
void ModuleWindow::WidhtHeightResizable(int width, int height)
{
SDL_SetWindowSize(window, width, height);
}
| true |
f8f57d289157902b4856cbddd8e66e8033c13a25 | C++ | lsiddiqsunny/programming-contest | /Code chef Long/December/1.cpp | UTF-8 | 279 | 2.671875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,r;
cin>>n>>r;
while(n--){
int x;
cin>>x;
if(x>=r){
cout<<"Good boi"<<endl;
}
else{
cout<<"Bad boi"<<endl;
}
}
}
| true |
2accd952346aa11f4bff6c6b0ed129a7ba85da42 | C++ | dlufy/SPOJSOLUTION | /SPOJSOLUTION/PIGBANK.cpp | UTF-8 | 624 | 2.625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
#define MAX 1000000000
int main()
{
int t;
cin>>t;
while(t--)
{
int e,f;
cin>>e>>f;
int n;
cin>>n;
vector<pair<int,int> > coin(n+5);
for(int i=0;i<n;i++)
{
int x,y;
cin>>x>>y;
coin[i].first=y;
coin[i].second=x;
}
int dp[f+10];
dp[0]=0;
for(int i=1;i<=f;i++)
{
dp[i]=MAX;
for(int j=0;j<n;j++)
{
if(coin[j].first<=i)
dp[i]=min(dp[i],coin[j].second+dp[i-coin[j].first]);
}
}
if(dp[f-e]!=MAX)
cout<<"The minimum amount of money in the piggy-bank is "<<dp[f-e]<<".\n";
else
cout<<"This is impossible.\n";
}
}
| true |
66b06cdae2ad6f57a1f9209e2f3ed3ffc449319f | C++ | DamianBocanegra/TextAdventure | /test.cpp | UTF-8 | 934 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include "item.h"
#include "inventory.h"
#include "room.h"
using namespace std;
int main()
{
inventory inv;
Room rm = Room("test room", 1,0,0,0,0);
inv.add(item("Potion", 1, 1));
inv.add(item("Elixir", 1, 2));
inv.add(item("Ether", 1, 3));
inv.add(item("Revive", 1, 4));
cout << inv.getItem(0).getName() << endl;
cout << inv.getItem(1).getName() << endl;
cout << inv.getItem(2).getName() << endl;
cout << inv.getItem(3).getName() << endl;
cout << rm.getDescription() << endl;
if(rm.getRoomNumber() == inv.getItem(0).getLocation())
{
cout << rm.getDescription() << " contains the item " << inv.getItem(0).getName() << endl;
}
string str;
getline(cin, str);
if(str.find("go") != string::npos)
{
cout << str << endl;
}
if(str.find("north") != string::npos)
{
cout << "String contains north" << endl;
}
return 0;
}
| true |
9c010ba8baa6bf772ad3d0756d949dad6461253e | C++ | fanll4523/algorithms | /Part13算法竞赛宝典/第一部资源包/附录/字符串数字转整数.cpp | GB18030 | 225 | 2.734375 | 3 | [
"LicenseRef-scancode-mulanpsl-1.0-en",
"MulanPSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | //ַתֵ
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
char s1[50];
int a;
gets(s1);
a=atof(s1);
cout<<a;
}
| true |
84a2c1367d673eb1d7254af0927064b5fa40aacf | C++ | HarVi0/reszta | /main.cpp | UTF-8 | 797 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
float nominal[15]= {50000, 20000, 10000, 5000, 2000, 1000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
float reszta;
int liczba_banknotow, i=0;
cout << "Podaj reszte: ";
cin >> reszta;
reszta = reszta * 100;
while (reszta>0)
{
if (reszta >= nominal[i])
{
liczba_banknotow=reszta / nominal[i];
reszta=reszta-(nominal[i]*liczba_banknotow);
if(liczba_banknotow==1)
{
cout << liczba_banknotow << " raz " << nominal[i]/100 <<" zl." << endl;
}
else
{
cout << liczba_banknotow << " razy " << nominal[i]/100 <<" zl. " << endl;
}
}
i++;
}
return 0;
}
| true |