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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
27d789b45eefb2871c84b9cecd9a93e261cf0000 | C++ | yashkapoor007/geeksforgeeks | /linkedList_29.cpp | UTF-8 | 1,450 | 3.453125 | 3 | [] | no_license |
#include<set>
Node *removeDuplicates(Node *root)
{
unordered_set<int> s;
Node* current=root;
Node* prev=NULL;
while(current)
{
if(s.find(current->val)!=s.end())
{
prev->next=current->next;
delete current;
}
else
{
s.insert(current->val);
prev=current;
}
current=current->next;
}
return root;
// your code goes here
}
void intersection(Node **head1, Node **head2,Node **head3)
{
if(*head1==NULL||*head2==NULL)
{
*head3=NULL;
return;
}
*head1=removeDuplicates(*head1);
*head2=removeDuplicates(*head2);
unordered_set<int> s;
while((*head1))
{
s.insert((*head1)->val);
(*head1)=(*head1)->next;
}
Node* tail;
while((*head2))
{
if(s.find((*head2)->val)!=s.end())
{
if(*head3==NULL)
{
Node* newnode=(Node*)malloc(sizeof(Node));
newnode->val=(*head2)->val;
newnode->next=NULL;
*head3=newnode;
tail=newnode;
}
else
{
Node* temp=*head3;
Node* newnode=(Node*)malloc(sizeof(Node));
newnode->val=(*head2)->val;
newnode->next=NULL;
tail->next=newnode;
tail=tail->next;
}
}
(*head2)=(*head2)->next;
}
// Your Code Here
}
| true |
e5098e9b501e53c1edec222a0b0906889f7c7757 | C++ | etsangsplk/burgerlib | /source/windows/brcriticalsectionwindows.cpp | UTF-8 | 7,569 | 2.703125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"Zlib"
] | permissive | /***************************************
Class to handle critical sections
Copyright (c) 1995-2017 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brcriticalsection.h"
#if defined(BURGER_WINDOWS)
#include "brassert.h"
#include "bratomic.h"
// InitializeCriticalSectionAndSpinCount() is minimum XP
#if !defined(_WIN32_WINNT)
#define _WIN32_WINNT 0x0501 // Windows XP
#endif
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
/***************************************
Initialize the spin count to 1000 since this
class is usually used for quick data locks
***************************************/
Burger::CriticalSection::CriticalSection()
{
// Safety switch to verify the declaration in brwindowstypes.h matches the real thing
BURGER_STATIC_ASSERT(sizeof(CRITICAL_SECTION)==sizeof(BurgerCRITICAL_SECTION));
InitializeCriticalSectionAndSpinCount(reinterpret_cast<CRITICAL_SECTION *>(&m_Lock),1000);
}
Burger::CriticalSection::~CriticalSection()
{
DeleteCriticalSection(reinterpret_cast<CRITICAL_SECTION *>(&m_Lock));
}
/***************************************
Lock the CriticalSection
***************************************/
void Burger::CriticalSection::Lock(void)
{
EnterCriticalSection(reinterpret_cast<CRITICAL_SECTION *>(&m_Lock));
}
/***************************************
Try to lock the CriticalSection
***************************************/
Word Burger::CriticalSection::TryLock(void)
{
return static_cast<Word>(TryEnterCriticalSection(reinterpret_cast<CRITICAL_SECTION *>(&m_Lock)));
}
/***************************************
Unlock the CriticalSection
***************************************/
void Burger::CriticalSection::Unlock(void)
{
LeaveCriticalSection(reinterpret_cast<CRITICAL_SECTION *>(&m_Lock));
}
/***************************************
Initialize the semaphore
***************************************/
Burger::Semaphore::Semaphore(Word32 uCount) :
m_uCount(uCount)
{
// Get the maximum semaphores
Word32 uMax = uCount+32768U;
// Did it wrap (Overflow?)
if (uMax<uCount) {
// Use max
uMax = BURGER_MAXUINT;
}
m_pSemaphore = CreateSemaphoreW(nullptr,static_cast<LONG>(uCount),static_cast<LONG>(uMax), nullptr);
}
/***************************************
Release the semaphore
***************************************/
Burger::Semaphore::~Semaphore()
{
HANDLE hSemaphore = m_pSemaphore;
if (hSemaphore) {
CloseHandle(hSemaphore);
m_pSemaphore = nullptr;
}
m_uCount = 0;
}
/***************************************
Attempt to acquire the semaphore
***************************************/
Word BURGER_API Burger::Semaphore::TryAcquire(Word uMilliseconds)
{
// Assume failure
Word uResult = 10;
HANDLE hSemaphore = m_pSemaphore;
if (hSemaphore) {
DWORD dwMilliseconds;
#if INFINITE==BURGER_MAXUINT
dwMilliseconds = static_cast<DWORD>(uMilliseconds);
#else
if (uMilliseconds==BURGER_MAXUINT) {
dwMilliseconds = INFINITE;
} else {
dwMilliseconds = static_cast<DWORD>(uMilliseconds);
}
#endif
// Acquire a lock
DWORD uWait = WaitForSingleObject(hSemaphore,dwMilliseconds);
if (uWait==WAIT_OBJECT_0) {
// Got the lock. Decrement the count
AtomicPreDecrement(&m_uCount);
uResult = 0;
} else if (uWait==WAIT_TIMEOUT) {
// Timeout gets a special error
uResult = 1;
}
}
return uResult;
}
/***************************************
Release the semaphore
***************************************/
Word BURGER_API Burger::Semaphore::Release(void)
{
Word uResult = 10;
HANDLE hSemaphore = m_pSemaphore;
if (hSemaphore) {
// Release the count immediately, because it's
// possible that another thread, waiting for this semaphore,
// can execute before the call to ReleaseSemaphore()
// returns
AtomicPreIncrement(&m_uCount);
if (ReleaseSemaphore(hSemaphore,1, nullptr)==FALSE) {
// Error!!! Undo the AtomicPreIncrement()
AtomicPreDecrement(&m_uCount);
} else {
// A-Okay!
uResult = 0;
}
}
return uResult;
}
/***************************************
This code fragment calls the Run function that has
permission to access the members
***************************************/
static DWORD WINAPI Dispatcher(LPVOID pThis)
{
Burger::Thread::Run(pThis);
return 0;
}
/***************************************
Initialize a thread to a dormant state
***************************************/
Burger::Thread::Thread() :
m_pFunction(nullptr),
m_pData(nullptr),
m_pSemaphore(nullptr),
m_pThreadHandle(nullptr),
m_uThreadID(0),
m_uResult(BURGER_MAXUINT)
{
}
/***************************************
Initialize a thread and begin execution
***************************************/
Burger::Thread::Thread(FunctionPtr pThread,void *pData) :
m_pFunction(nullptr),
m_pData(nullptr),
m_pSemaphore(nullptr),
m_pThreadHandle(nullptr),
m_uThreadID(0),
m_uResult(BURGER_MAXUINT)
{
Start(pThread,pData);
}
/***************************************
Release resources
***************************************/
Burger::Thread::~Thread()
{
Kill();
}
/***************************************
Launch a new thread if one isn't already started
***************************************/
Word BURGER_API Burger::Thread::Start(FunctionPtr pFunction,void *pData)
{
Word uResult = 10;
if (!m_pThreadHandle) {
m_pFunction = pFunction;
m_pData = pData;
// Use this temporary semaphore to force synchronization
Semaphore Temp(0);
m_pSemaphore = &Temp;
DWORD uID;
// Start the thread
HANDLE hThread = CreateThread(nullptr,0,Dispatcher,this,0,&uID);
if (hThread) {
// Ensure these are set up
m_uThreadID = uID;
m_pThreadHandle = hThread;
// Wait until the thread has started
Temp.Acquire();
// Kill the dangling pointer
m_pSemaphore = nullptr;
// All good!
uResult = 0;
}
}
return uResult;
}
/***************************************
Wait until the thread has completed execution
***************************************/
Word BURGER_API Burger::Thread::Wait(void)
{
Word uResult = 10;
if (m_pThreadHandle) {
// Wait until the thread completes execution
DWORD uError = WaitForSingleObject(m_pThreadHandle,INFINITE);
// Close it down!
CloseHandle(m_pThreadHandle);
// Allow restarting
m_uThreadID = 0;
m_pThreadHandle = nullptr;
// Shutdown fine?
if (uError==WAIT_OBJECT_0) {
uResult = 0;
} else if (uError==WAIT_TIMEOUT) {
uResult = 1; // Timeout!
}
}
return uResult;
}
/***************************************
Invoke the nuclear option to kill a thread
NOT RECOMMENDED!
***************************************/
Word BURGER_API Burger::Thread::Kill(void)
{
Word uResult = 0;
if (m_pThreadHandle) {
if (!TerminateThread(m_pThreadHandle,BURGER_MAXUINT)) {
uResult = 10; // Error??
} else {
// Release everything
uResult = Wait();
}
}
return uResult;
}
/***************************************
Synchronize and then execute the thread and save
the result if any
***************************************/
void BURGER_API Burger::Thread::Run(void *pThis)
{
Thread *pThread = static_cast<Thread *>(pThis);
pThread->m_uThreadID = GetCurrentThreadId();
pThread->m_pSemaphore->Release();
pThread->m_uResult = pThread->m_pFunction(pThread->m_pData);
}
#endif
| true |
ea989acf3759833abc91429d3c7af00c11ac4f55 | C++ | kdwhan/2015-1.DataStructure | /lab_05_Circular_Queue/main.cpp | UTF-8 | 750 | 3.078125 | 3 | [] | no_license |
#include "lab005.h"
#include "lab.hpp"
template <class T>
Queue<T>::Queue(int queueCapacity) : capacity(queueCapacity)
{
if(capacity < 1) throw "Queue capacity must be > 0";
queue = new T[capacity];
front = rear = 0;
}
int main()
{
Queue<int> q(7);
while(1)
{
cerr << "Queueop > " << endl;
char command[256];
cin >> command;
if(strcmp (command, "quit") == 0)
break;
cout << endl << command << " ";
try {
if(strcmp (command, "push") == 0)
{
int item;
cin >> item;
cout << item << endl;
q.Push(item);
}
else if(strcmp (command, "pop") == 0)
{
cout << endl;
q.Pop();
}
} catch (const char *e) {
cout << "Error " << e << endl;
}
q.Show();
q.Internal();
}
return 1;
}
| true |
b5cbf661002916f9c2bcb5e78600927d6b72cd1d | C++ | wickedZone/ED-2020 | /cpp/08_operador_asignacion/Test3.cpp | UTF-8 | 586 | 2.78125 | 3 | [] | no_license | /*
* ---------------------------------------------------
* ESTRUCTURAS DE DATOS
* ---------------------------------------------------
* Manuel Montenegro Montes
* Facultad de Informática
* Universidad Complutense de Madrid
* ---------------------------------------------------
*/
/*
* Pruebas con la clase Persona y el operador de asignación.
*/
#include "Persona.h"
int main() {
Persona p1("Lucía", 15, 3, 1979);
std::cout << "p1 = " << p1 << std::endl;
p1 = p1;
std::cout << "p1 = " << p1 << std::endl;
return 0;
}
| true |
1abe0c483cfac7383137a38e83ca46de0fe3f4a0 | C++ | quadmotor/Superpixel_QEM | /Superpixel_QEM/processing.cpp | UTF-8 | 8,396 | 2.5625 | 3 | [] | no_license | #include "processing.h"
#include "optimizer.h"
#include "partition.h"
#include <fstream>
#include <unordered_map>
using namespace std;
using namespace cv;
extern Image input_image;
extern Optimizer * optimizer;
extern Partition* tess;
extern int nClusters;
extern int * valid_mapping;
extern string init_mesh_name;
PostProcessor::PostProcessor()
{
}
void PostProcessor::cleanClusters()
{
vector<bool> pixel_visited = vector<bool>(input_image.width * input_image.height, false);
for (int i=0; i<nClusters; i++)
{
int cluster_id = valid_mapping[i];
vector<PixelIdx> flooding_pixels;
vector<set<PixelIdx>> sub_clusters;
vector<set<int>> sub_cluster_neighbors;
set<PixelIdx> remain_components = tess->clusters[cluster_id];
int ncluster = 0;
set<PixelIdx> new_cluster;
set<int> new_cluster_neighbors;
//separate each connected components as a sub-cluster
while (!remain_components.empty())
{
ncluster++;
flooding_pixels.clear();
PixelIdx starting_face = *(remain_components.begin());
flooding_pixels.push_back(starting_face);
remain_components.erase(starting_face);
pixel_visited[starting_face] = true;
new_cluster.clear();
new_cluster_neighbors.clear();
new_cluster.insert(starting_face);
//find the new cluster by flooding
while(!flooding_pixels.empty())
{
vector<int>::iterator it = flooding_pixels.begin();
int p_id = *it;
flooding_pixels.erase(it);
vector<int> neighbor_pixels = input_image.pixel_neighbors[p_id];
for (vector<int>::iterator f_it = neighbor_pixels.begin(); f_it != neighbor_pixels.end(); f_it++)
{
PixelIdx neighbor_face = *f_it;
//the neighbors in the set should be marked as connected
set<PixelIdx>::iterator cluster_neighbor_it = remain_components.find(neighbor_face);
if ( cluster_neighbor_it != remain_components.end())
{
if ( !pixel_visited[*cluster_neighbor_it] )
{
flooding_pixels.push_back(*cluster_neighbor_it);
pixel_visited[*cluster_neighbor_it] = true;
new_cluster.insert(*cluster_neighbor_it);
remain_components.erase(cluster_neighbor_it);
}
}
new_cluster_neighbors.insert(tess->cluster_belong[neighbor_face]);
}
}
sub_clusters.push_back(new_cluster);
new_cluster_neighbors.erase(cluster_id);
sub_cluster_neighbors.push_back(new_cluster_neighbors);
}
int largest_component_id = 0;
int largest_size = sub_clusters[0].size();
for (int j=0; j< ncluster; j++)
{
if (sub_clusters[j].size() > largest_size)
{
largest_component_id = j;
largest_size = sub_clusters[j].size();
}
}
////hold the largest connected component as a cluster
////update the cluster, covariance matrix, set the centroid as the node pos
////keep clusters with more than 3 neighboring clusters
//if (sub_cluster_neighbors[largest_component_id].size() >= 3)
//kepp clusters that contains more than 30 pixels, and the number of clusters may be less than the user desired.
if (sub_clusters[largest_component_id].size() >= 30)
{
tess->clusters[cluster_id] = sub_clusters[largest_component_id];
Covariance cov = Covariance();
for(set<PixelIdx>::iterator f_it = sub_clusters[largest_component_id].begin(); f_it != sub_clusters[largest_component_id].end(); f_it++)
{
cov += optimizer->init_covariance(*f_it);
pixel_visited[*f_it] = false;
}
optimizer->covariance(cluster_id) = cov;
}
else
{
largest_component_id = -1;
tess->clusters[cluster_id].clear();
optimizer->covariance(cluster_id) = Covariance();
}
//merge other connected components
for (int component_id =0; component_id < ncluster; component_id ++)
{
if (component_id != largest_component_id)
{
Covariance cov_i = Covariance();
for(set<PixelIdx>::iterator f_it = sub_clusters[component_id].begin(); f_it != sub_clusters[component_id].end(); f_it++)
{
cov_i += optimizer->init_covariance(*f_it);
}
int cluster_closest = *(sub_cluster_neighbors[component_id].begin());
double energy_increased_smallest = 1e20;
//merge with its neighbors
Covariance cov_j;
Covariance C;
for (set<int>::iterator cluster_it = sub_cluster_neighbors[component_id].begin(); cluster_it != sub_cluster_neighbors[component_id].end(); cluster_it++)
{
cov_j=optimizer->covariance(*cluster_it);
C=cov_i; C+=cov_j;
double energy_increased = C.energy() - cov_i.energy() - cov_j.energy();
//assert(energy_increased >= 0);
if (energy_increased < energy_increased_smallest)
{
cluster_closest = *cluster_it;
energy_increased_smallest = energy_increased;
}
}
//update the cluster, covariance matrix, set the centroid as the node pos
for(set<PixelIdx>::iterator f_it = sub_clusters[component_id].begin(); f_it != sub_clusters[component_id].end(); f_it++)
{
tess->clusters[cluster_closest].insert(*f_it);
tess->cluster_belong[*f_it] = cluster_closest;
pixel_visited[*f_it] = false;
}
optimizer->covariance(cluster_closest) += cov_i;
}
}
}
delete [] valid_mapping;
valid_mapping = new int[nClusters];
nClusters = 0;
int n_domain = 0;
for(PixelIdx j=0; j<tess->size; j++)
{
if (tess->clusters[j].size() != 0)
{
valid_mapping[nClusters] = j;
nClusters ++;
}
}
}
void PostProcessor::save_results(string sp_folder, string par_folder, string file_name)
{
save_superpixels(sp_folder, file_name);
//save_partition_img(par_folder, file_name);
save_partition_txt(par_folder, file_name);
}
void PostProcessor::save_superpixels(string sp_folder, string file_name)
{
int boundary_width = 1;
Mat superpixel_mat = input_image.img.clone();
//IplImage* super_pixel = cvCreateImage( cvGetSize(input_image.img), input_image.img->depth, 3 );
for(int i=0; i< superpixel_mat.rows; i++)
{
uchar* ptr1 = superpixel_mat.ptr<uchar>(i);
//uchar* ptr1 = (uchar*)(super_pixel->imageData + i*super_pixel->widthStep );
//uchar* ptr2 = (uchar*)(input_image.img->imageData + i*input_image.img->widthStep );
for (int j=0; j< superpixel_mat.cols; j++)
{
set<int> neighbor_clusters;
for (int m = i-boundary_width; m < i+boundary_width; m++)
{
for (int n = j-boundary_width; n < j+boundary_width; n++)
{
if(m < 0 || m >= superpixel_mat.rows || n < 0 || n >= superpixel_mat.cols)
neighbor_clusters.insert(-1);
else
neighbor_clusters.insert(tess->cluster_belong[m * superpixel_mat.cols + n]);
}
}
if(neighbor_clusters.size() == 1)
{
/*ptr1[3*j] = ptr2[3*j];
ptr1[3*j+1] = ptr2[3*j+1];
ptr1[3*j+2] = ptr2[3*j+2];*/
}
else
{
ptr1[3*j] = 0;
ptr1[3*j+1] = 0;
ptr1[3*j+2] = 0;
}
}
}
string save_name = sp_folder + "\\" + file_name + ".png";
cout << "save superpixel to " << save_name.c_str() << endl;
imwrite(save_name, superpixel_mat);
/*cvSaveImage(save_name.c_str(), super_pixel);
cvReleaseImage(&super_pixel);*/
}
void PostProcessor::save_partition_img(string par_folder, string file_name)
{
Mat partition_mat = Mat::zeros(input_image.img.size(), input_image.img.type());
//IplImage *img = cvCreateImage( cvGetSize(input_image.img), input_image.img->depth, 3 );
int pixel_id = 0;
for(int i=0; i< partition_mat.rows; i++)
{
//uchar* ptr = (uchar*)(img->imageData + i*img->widthStep );
uchar* ptr = partition_mat.ptr<uchar>(i);
for (int j=0; j< partition_mat.cols; j++)
{
int cluster_id = tess->cluster_belong[pixel_id];
ptr[3*j + 2] = 255 * tess->red[cluster_id];
ptr[3*j] = 255 * tess->blue[cluster_id];
ptr[3*j + 1] = 255 * tess->green[cluster_id];
pixel_id++;
}
}
string save_name = par_folder + "\\" + file_name + "_partition.png";
imwrite(save_name, partition_mat);
/*cvSaveImage(save_name.c_str(), img);
cvReleaseImage(&img);*/
}
void PostProcessor::save_partition_txt(string par_folder, string file_name)
{
unordered_map<int, int> cluster_mapping;
for (int i = 0; i < nClusters; i++)
cluster_mapping[valid_mapping[i]] = i;
string save_name = par_folder + "\\" + file_name + ".txt";
ofstream of(save_name);
for(int i = 0; i < input_image.height; i++)
{
for (int j = 0; j < input_image.width; j++)
{
int pixel_id = i * input_image.width + j;
int cluster_id = tess->cluster_belong[pixel_id];
of << (cluster_mapping[cluster_id] + 1) << '\t';
}
of << '\n';
}
of.close();
} | true |
63e4502e536602b3a5557bbf15c3afe2e5ac89bf | C++ | SpartanJ/eepp | /src/eepp/system/platform/win/threadimpl.cpp | UTF-8 | 1,327 | 2.71875 | 3 | [
"MIT"
] | permissive | #include <eepp/core/debug.hpp>
#include <eepp/system/platform/win/threadimpl.hpp>
#include <eepp/system/thread.hpp>
#include <iostream>
namespace EE { namespace System { namespace Platform {
#if EE_PLATFORM == EE_PLATFORM_WIN
UintPtr ThreadImpl::getCurrentThreadId() {
return ( UintPtr )::GetCurrentThreadId();
}
ThreadImpl::ThreadImpl( Thread* owner ) {
mThread = reinterpret_cast<HANDLE>(
_beginthreadex( NULL, 0, &ThreadImpl::entryPoint, owner, 0, &mThreadId ) );
if ( !mThread )
std::cerr << "Failed to create thread" << std::endl;
}
ThreadImpl::~ThreadImpl() {
if ( mThread ) {
CloseHandle( mThread );
}
}
void ThreadImpl::wait() {
if ( mThread ) { // Wait for the thread to finish, no timeout
eeASSERT( mThreadId != getCurrentThreadId() ); // A thread cannot wait for itself!
WaitForSingleObject( mThread, INFINITE );
}
}
void ThreadImpl::terminate() {
if ( mThread ) {
TerminateThread( mThread, 0 );
}
}
UintPtr ThreadImpl::getId() {
return (UintPtr)mThreadId;
}
unsigned int __stdcall ThreadImpl::entryPoint( void* userData ) {
// The Thread instance is stored in the user data
Thread* owner = static_cast<Thread*>( userData );
// Forward to the owner
owner->run();
// Optional, but it is cleaner
_endthreadex( 0 );
return 0;
}
#endif
}}} // namespace EE::System::Platform
| true |
2b74cc8749718c41ef3be14fa16d5fa90278e260 | C++ | der3318/fs-snapshotcmp | /ColorPrinter.h | UTF-8 | 392 | 2.8125 | 3 | [] | no_license | #pragma once
#include <string>
namespace Der3318FileSystemComparison
{
enum class ConsoleColor
{
Black = 0,
White = 15,
Blue = 1,
Green = 2,
Red = 4,
Yellow = 14
};
class ColorPrinter
{
public:
static void Print(std::string msg, ConsoleColor foreground, ConsoleColor background);
};
} | true |
73556c5ad2fb92b2234dce060a91d829ec701378 | C++ | Zahidsqldba07/competitive-programming-2 | /algorithm/bfs.cpp | UTF-8 | 1,605 | 3.046875 | 3 | [
"MIT"
] | permissive | #include "iostream"
#include "stdio.h"
#include "stdlib.h"
#include "string"
#include "string.h"
#include "algorithm"
#include "math.h"
#include "vector"
#include "queue"
#include "stack"
#include "deque"
using namespace std;
typedef pair<int, int> ii;
typedef vector<int> vi;
typedef vector<ii> vii;
const int inf = 1e9;
#define DFS_WHITE -1 // unvisited
#define DFS_BLACK 1 // visited
vector<vii> AdjList;
int V, E, u, v, w;
void graphUndirected(){
scanf("%d %d", &V, &E);
AdjList.assign(V + 4, vii());
for (int i = 0; i < E; i++) {
scanf("%d %d %d", &u, &v,&w);
AdjList[u].push_back(ii(v, w));
AdjList[v].push_back(ii(u, w));
}
}
int s;
void bfs(int s){
vi d(V+4, inf); d[s] = 0; // distance to source is 0 (default)
queue<int> q; q.push(s); // start from source
int layer = -1; // for our output printing purpose
while (!q.empty()) {
int u = q.front(); q.pop(); // queue: layer by layer!
if (d[u] != layer) printf("\n Layer %d: ", d[u]);
layer = d[u];
printf(" visit %d ", u);
for (int j = 0; j < (int)AdjList[u].size(); j++) {
ii v = AdjList[u][j]; // for each neighbors of u
if (d[v.first] == inf) {
d[v.first] = d[u] + 1; // v unvisited + reachable
q.push(v.first); // enqueue v for next step
}
}
}
}
int main(){
printf("Standard BFS Demo (the input graph must be UNDIRECTED)\n");
graphUndirected();
s = 5; bfs(s);
printf("\n");
return 0;
}
| true |
4f70084e1a5446df1ff9b1ab9bf22af7fddc9a69 | C++ | alelevinas/Inventario | /Common/common_AreaDeVision.cpp | UTF-8 | 2,305 | 2.765625 | 3 | [] | no_license | /*
* common_AreaDeVision.cpp
*
* Created on: Jun 9, 2015
* Author: leandro
*/
#include "common_AreaDeVision.h"
using common::Producto;
namespace common {
unsigned long int AreaDeVision::proximoID;
AreaDeVision::AreaDeVision(unsigned long int id,const std::string& ubicacion, const std::string& tipoDeCapturador, std::list<Producto*>* productosDetectados):ubicacion(ubicacion),tipoDeCapturador(tipoDeCapturador),productosDetectados(productosDetectados),id(id){
//llevo la cuenta de cual id sera el proximo
if (AreaDeVision::proximoID<= id)
AreaDeVision::proximoID=++id;
}
AreaDeVision::AreaDeVision(std::string ubicacion, std::string tipoDeCapturador):ubicacion(ubicacion),tipoDeCapturador(tipoDeCapturador),productosDetectados(new std::list<Producto*>()),id(AreaDeVision::proximoID++){}
AreaDeVision::~AreaDeVision() {
liberarRecursosProductos();
}
void AreaDeVision::liberarRecursosProductos(){
for (std::list<Producto*>::const_iterator it= productosDetectados->begin(); it != productosDetectados->end();++it)
delete (*it);
delete productosDetectados;
}
const std::string& AreaDeVision::getUbicacion() const{
return ubicacion;
}
const std::string& AreaDeVision::getTipoDeCapturador() const{
return tipoDeCapturador;
}
void AreaDeVision::setUbicacion(const std::string& ubicacion){
this->ubicacion=ubicacion;
}
void AreaDeVision::setTipoDeCapturador(const std::string& tipoDeCapturador){
this->tipoDeCapturador=tipoDeCapturador;
}
const unsigned long int AreaDeVision::getId() const{
return id;
}
const std::list<Producto*>* const AreaDeVision::getProductosDetectados() const{
return productosDetectados;
}
void AreaDeVision::actualizarDeteccion(std::list<Producto*>* productosDetectados) {
liberarRecursosProductos();
this->productosDetectados=productosDetectados;
}
std::list<Producto*>::const_iterator AreaDeVision::eliminarProductoDetectado(const unsigned long int idProductoAEliminar){
for (std::list<Producto*>::iterator it= productosDetectados->begin(); it != productosDetectados->end();++it){
delete (*it);
std::list<Producto*>::iterator iteradorARetornar = productosDetectados->erase(it);
return iteradorARetornar;
}
return productosDetectados->end();
}
void AreaDeVision::inicializarCuentaId(){
proximoID=0;
}
} /* namespace common */
| true |
072e3df878a61e21e76262fb527985fa40704faf | C++ | chiahsun/problem_solving | /Algospot/JLIS/solve1.cc | UTF-8 | 2,013 | 2.75 | 3 | [] | no_license | #include <cstdio>
#include <vector>
#include <algorithm>
const bool debug = !true;
const int M = 100+5;
int A[M], B[M];
int merge_list(const std::vector<int> & v1, int sz1, const std::vector<int> & v2, int sz2) {
std::vector<int> v;
int size = 0, last = -(1 << 29);
for (int pos1 = 0, pos2 = 0; pos1 < sz1 or pos2 < sz2;) {
int cur;
if (pos2 >= sz2 or (pos1 < sz1 and v1[pos1] <= v2[pos2])) {
cur = v1[pos1]; ++pos1;
} else {
cur = v2[pos2]; ++pos2;
}
if (cur != last) {
++size;
last = cur;
if (debug) {
v.push_back(cur);
}
}
}
if (debug) {
printf("lis : ");
for (auto x : v)
printf("%d ", x);
printf("\n");
}
return size;
}
int update_lis(int x, std::vector<int> & lis) {
auto it = std::lower_bound(lis.begin(), lis.end(), x);
size_t sz;
if (it == lis.end()) {
lis.push_back(x);
sz = lis.size();
} else if (*it != x) {
*it = x;
sz = it - lis.begin() + 1;
} else {
sz = it - lis.begin() + 1;
}
return sz;
}
int main() {
int nCase, N1, N2;
scanf("%d", &nCase);
while (nCase--) {
scanf("%d%d", &N1, &N2);
for (int i = 0; i < N1; ++i) scanf("%d", A+i);
for (int i = 0; i < N2; ++i) scanf("%d", B+i);
#if 0
for (int i = 0; i < N1; ++i) printf("%d ", A[i]); printf("\n");
for (int i = 0; i < N2; ++i) printf("%d ", B[i]); printf("\n");
#endif
int jlis_size = 0;
std::vector<int> lis1;
for (int i = 0; i < N1; ++i) {
int sz1 = update_lis(A[i], lis1);
std::vector<int> lis2;
for (int k = 0; k < N2; ++k) {
int sz2 = update_lis(B[k], lis2);
jlis_size = std::max(jlis_size, merge_list(lis1, sz1, lis2, sz2));
}
}
printf("%d\n", jlis_size);
}
return 0;
}
| true |
1bd4e6d6c6b0609540198ac00a4b7067d0c144d3 | C++ | cos18/baekjoon | /10973.cpp | UTF-8 | 480 | 2.71875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
ios_base :: sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
vector<int> v;
int N, tmp;
cin >> N;
for(int i=0; i<N; i++){
cin >> tmp;
v.push_back(tmp);
}
bool h = prev_permutation(v.begin(),v.end());
if(h){
for(int i=0; i<N; i++){
cout << v[i] << " ";
}
} else cout << -1;
return 0;
} | true |
e44159f5ec2ea5d030894be31358c12dcdf81ba4 | C++ | corwinjoy/database-template-library | /example/StoredProc.h | UTF-8 | 2,257 | 2.703125 | 3 | [
"LicenseRef-scancode-other-permissive"
] | permissive | // stored proc examples
#ifndef _STORED_PROC_H
#define _STORED_PROC_H
#include "example_core.h"
#if 0
class StoredProcBCA {
public:
void operator()(BoundIOs &cols, variant_row &row)
{
cols[0] >> row._int();
cols[1] >> row._string();
cols[2] >> row._string();
cols.BindVariantRow(row);
}
};
#endif
class GetEmployeeDetailsBCA {
public:
void operator()(BoundIOs &cols, variant_row &row)
{
cols[0] << row._int();
cols[1] >> row._string();
cols[2] >> row._string();
cols[3] >> row._double();
cols[4] >> row._timestamp();
cols.BindVariantRow(row);
}
};
#if 0
PROCEDURE GetEmployeeDetails(
i_emID IN employee.em_id%TYPE,
o_FirstName OUT employee.em_first_name%TYPE,
o_LastName OUT employee.em_last_name%TYPE,
o_Salary OUT employee.em_salary%TYPE,
o_StartDate OUT employee.em_start_date%TYPE)
#endif
void StoredProcRead();
class ProcBCA {
public:
void operator()(BoundIOs &cols, variant_row &row)
{
cols["INT_VALUE"] >> row._int();
cols["STRING_VALUE"] >> row._string();
cols.BindVariantRow(row);
}
};
class ProcParams {
public:
long long_criteria;
};
class ProcBPA {
public:
void operator()(BoundIOs &cols, ProcParams &row)
{
cols[0] << row.long_criteria;
}
};
// Read the contents of a table and print the resulting rows
// *** you must have Oracle ODBC driver version 8.1.5.3.0 for this to work ***
void StoredProcRead2();
// stuff for StoredProcRead3()
class EmptyDataObj
{
};
class ProcOutBCA
{
public:
void operator()(BoundIOs &boundIOs, EmptyDataObj &rowbuf)
{
}
};
class ProcOutParams {
public:
long long_criteria;
int numRecords;
friend ostream &operator<<(ostream &o, const ProcOutParams ¶ms)
{
cout << "ProcOutParams(" << params.long_criteria << ", " << params.numRecords << ")";
return o;
}
};
class ProcOutBPA {
public:
void operator()(BoundIOs &cols, ProcOutParams ¶ms)
{
cols[0] << params.long_criteria;
cols[1] >> params.numRecords;
}
};
// simply does a select count(*) from db_example where example_long = 22
// version that will test output params
// *** you must have Oracle ODBC driver version 8.1.5.3.0 for this to work ***
void StoredProcRead3();
void StoredProcReadTestParm();
#endif
| true |
15a86311e497255b7c3e165f25bd38038baaf5f2 | C++ | kashyapiitd/AlgorithmAndDataStructure | /insertionSortAnalysis.cpp | UTF-8 | 2,025 | 3.390625 | 3 | [] | no_license | #include <vector>
#include <string>
#include <algorithm>
#include <utility>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define MAX_ELEMENTS 10000000
void computeNPasses(vector<int>& input){
int nPasses = 0;
for (int i = 0; i < input.size();i++){
int sample = input[i];
int j = i+1;
while(j < input.size()){
if (input[j] < sample){
nPasses++;
}
j++;
}
}
cout<<nPasses<<endl;
}
unsigned long long int getBitSum(vector<int>& bit,int idx){
int idx1 = idx;
unsigned long long int sum = 0;
while(idx > 0){
sum+=bit[idx];
idx1 -= (idx & -idx);
idx = idx1;
}
return sum;
}
void updateBit(vector<int>& bit,int idx, int value){
int idx1 = idx;
while(idx < bit.size()){
bit[idx]+=value;
idx1 += (idx & -idx);
idx = idx1;
}
}
void computeNPassesBIT(vector<int>& input){
vector<int> bit(MAX_ELEMENTS+1,0);
// Start from the last element in the input array.
// and check how many elements smaller then the current
// element already exists.
unsigned long long int nPasses = 0;
for (int i = input.size() -1; i >= 0; i--){
// Get the number of elements smaller then the current element.
unsigned long long int temp = getBitSum(bit,input[i]-1);
//cout << temp <<endl;
nPasses+=temp;
// Update the BIT with a 1 in the position denoted by the current element.
updateBit(bit,input[i],1);
}
//cout<<nPasses<<endl;
}
int main(){
int nSets;
cin >> nSets;
vector<vector<int> > ar(nSets);
for (int i = 0; i < nSets; i++){
int nElements;
cin >> nElements;
ar[i].resize(nElements);
for (int j = 0; j < nElements; j++){
cin >> ar[i][j];
}
}
for(int i = 0; i < nSets; i++){
//computeNPasses(ar[i]);
computeNPassesBIT(ar[i]);
}
return 0;
}
| true |
12cf8186ebaac85a277fede923e1cfdef98ba27b | C++ | TobiasSchulte/VADS---Dynamischer-De-Bruijn-Graph | /src/Helpers.cpp | UTF-8 | 447 | 2.984375 | 3 | [] | no_license | void itoa(int n, char s[])
{
int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
}
void output(char *str){
if(DEBUG_OUTPUT)
std::cout << str << '\n';
} | true |
e238dae96c00acd842f544cec650c8f7d9703ba1 | C++ | Monster88Ra/RayTracer | /trunk/RayTracer/RayTracer/include/math/Vector2.h | UTF-8 | 4,777 | 3.671875 | 4 | [
"MIT"
] | permissive | #pragma once
#include <cstdint>
#include <cmath>
#include <iostream>
#include <stdexcept>
/*****************************
* Class of the 2D vector.
******************************/
template <typename T>
class Vector2
{
public:
Vector2();
Vector2(T X);
Vector2(T X, T Y);
~Vector2();
template<typename U>
Vector2<T>& operator *= (const U &scalar);
Vector2<T>& operator += (const Vector2<T> &rhs);
Vector2<T>& operator -= (const Vector2<T> &rhs);
template<typename U>
Vector2<T>& operator /= (const U &scalar);
bool operator == (const Vector2<T> &rhs) const;
bool operator != (const Vector2<T> &rhs) const;
T& operator[] (std::size_t index);
const T& operator[] (std::size_t index) const;
void Normalize();
float Length();
// square of length
float LengthSquare();
Vector2<T> Reflect(const Vector2<T> &normal) const;
static T Dot(const Vector2<T> &lhs, const Vector2<T> &rhs);
friend std::ostream& operator << (const std::ostream &os, const Vector2<T> &vec)
{
os << "[" << "X: " << x << "Y: " << y << "]";
return os;
}
public:
T x;
T y;
};
// c++ 11
using Vector2i = Vector2<int32_t>;
using Vector2f = Vector2<float>;
/*****************************
* Inlined Member Functions
******************************/
template <typename T>
Vector2<T>::Vector2():
x(0), y(0)
{
}
template <typename T>
Vector2<T>::Vector2(T X) :
x(X), y(X)
{
}
template <typename T>
Vector2<T>::Vector2(T X, T Y) :
x(X), y(Y)
{
}
template <typename T>
Vector2<T>::~Vector2()
{
}
template <typename T>
template<typename U>
inline Vector2<T>& Vector2<T>::operator *= (const U &scalar)
{
x *= scalar;
y *= scalar;
return *this;
}
template <typename T>
inline Vector2<T>& Vector2<T>::operator += (const Vector2<T> &rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}
template <typename T>
inline Vector2<T>& Vector2<T>::operator -= (const Vector2<T> &rhs)
{
x -= rhs.x;
y -= rhs.y;
return *this
}
template <typename T>
template <typename U>
inline Vector2<T>& Vector2<T>::operator /= (const U &scalar)
{
x /= scalar;
y /= scalar;
return *this;
}
template <typename T>
inline bool Vector2<T>::operator== (const Vector2<T> &rhs) const
{
return (x == rhs.x && y == rhs.y);
}
template <typename T>
inline bool Vector2<T>::operator!=(const Vector2<T> &rhs) const
{
return (x != rhs.x || y != rhs.y);
}
template <typename T>
T& Vector2<T>::operator[] (std::size_t index)
{
switch (index)
{
case 0:
return x;
case 1:
return y;
default:
throw std::out_of_range("Vector2 subscript out of range.");
}
}
template <typename T>
const inline T& Vector2<T>::operator[] (std::size_t index) const
{
switch (index)
{
case 0:
return x;
case 1:
return y;
default:
throw std::out_of_range("Vector2 subscript out of range.");
}
}
template <typename T>
inline float Vector2<T>::LengthSquare()
{
return x*x + y*y;
}
template <typename T>
inline float Vector2<T>::Length()
{
return std::sqrt(x*x + y*y);
}
template <typename T>
inline void Vector2<T>::Normalize()
{
/*
T nor2 = LengthSquare();
if (nor2 > 0)
{
T invNor = 1 / sqrt(nor2);
x *= invNor;
y *= invNor;
}
*/
*this/ Length;
}
/*
template <typename T>
void Vector2<T>::Print()
{
std::cout << "X:" << x << " " << "Y:" << y;
}
*/
template <typename T>
inline T Vector2<T>::Dot(const Vector2<T> &lhs,const Vector2<T> &rhs)
{
return lhs.x * rhs.x + lhs.y * rhs.y;
}
/*****************************
* Non-member Functions
******************************/
template <typename T>
inline Vector2<T> operator + (const Vector2<T> &lhs, const Vector2<T> &rhs)
{
return Vector2<T>(lhs.x + rhs.x, lhs.y + rhs.y);
}
template <typename T>
inline Vector2<T> operator - (const Vector2<T> &lhs, const Vector2<T> &rhs)
{
return Vector2<T>(lhs.x - rhs.x, lhs.y - rhs.y);
}
template <typename T>
inline Vector2<T> operator - (const Vector2<T> &lhs)
{
return Vector2<T>(-lhs.x, -lhs.y);
}
template <typename T,typename U>
inline Vector2<T> operator * (const Vector2<T> &vec, const U &scalar)
{
return Vector2<T>(vec.x * scalar, vec.y * scalar);
}
template <typename T, typename U>
inline Vector2<T> operator * (const U &scalar, const Vector2<T> &vec)
{
return Vector2<T>(vec.x * scalar, vec.y * scalar);
}
template <typename T, typename U>
inline Vector2<T> operator / (const Vector2<T> &vec, const U &scalar)
{
return Vector2<T>(vec.x / scalar, vec.y / scalar);
}
template <typename T, typename U>
inline Vector2<T> operator / (const U &scalar, const Vector2<T> &vec)
{
return Vector2<T>(scalar/vec.x , scalar/vec.y );
}
| true |
6af4c5157872dc602a15cc9ea6c5ce2adeb7914c | C++ | alanlyyy/CPP_Primer_Elementary | /ch9/Date.cpp | UTF-8 | 2,461 | 3.71875 | 4 | [] | no_license | #include <string>
#include <iostream>
#include <vector>
struct Date {
Date(std::string s) {
//format 1: January 1 1900 , currently handles format 1
//format 2: 1/1/1900
//format 3: Jan 1, 1900
int start = 0;
int current = start;
std::vector<std::string> months_abrv = { "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sept", "Oct" ,"Nov", "Dec" };
int date_tracker = 0;
while (current != s.size()){
if (isspace(s[current])) {
//current - start is length of substring between white space
std::string substring = s.substr(start, current-start);
std::cout << s << " "<< substring << " " << start << " " << current << std::endl;
//must be a integer if size of substring > 2
if (substring.size() > 2) {
for (auto m = 0; m != months_abrv.size(); m++) {
if (substring.find(months_abrv[m]) != std::string::npos) {
month = m + 1;
}
}
}
else {
day = stoi(s.substr(start, current));
}
//start marks the place of the last white space
start = current+1;
}
if (s[current] == '/' || s[current] == '-') {
//for format month/day/year and month-day-year
++date_tracker;//trackes the number of '/' and '-' marks, 1 == month, 2== day
//current - start is length of substring between white space
std::string substring = s.substr(start, current - start);
//must be a integer if size of substring > 2
if (date_tracker == 1) {
if (substring.size() > 2) {
for (auto m = 0; m != months_abrv.size(); m++) {
if (substring.find(months_abrv[m]) != std::string::npos) {
month = m + 1;
}
}
}
else {
month = stoi(substring);
}
}
else{
day = stoi(substring);
}
//start marks the place of the last white space
start = current+1;
}
current++;
}
year = stoi(s.substr(start, current));
}
unsigned year;
unsigned month;
unsigned day;
};
int main() {
Date D1 = Date("Nov 21 2020");
Date D2 = Date("11/21/2020");
Date D3 = Date("11-21-2020");
Date D4 = Date("November 21 2020");
Date D5 = Date("Nov-21-2020");
std::cout << D1.month << " " << D1.day << " " << D1.year << std::endl;
std::cout << D2.month << " " << D2.day << " " << D2.year << std::endl;
std::cout << D3.month << " " << D3.day << " " << D3.year << std::endl;
std::cout << D4.month << " " << D4.day << " " << D4.year << std::endl;
std::cout << D5.month << " " << D5.day << " " << D5.year << std::endl;
return 0;
} | true |
5d6516343e80d48151818e9b3211aaff9175a562 | C++ | saadjaliawala/c-practices | /switch/main.cpp | UTF-8 | 348 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int age = 16;
switch (age){
case 16:
cout << "a" << endl;
break;
case 17:
cout << "b" << endl;
break;
case 18:
cout << "c" << endl;
break;
case 19:
cout << "d" << endl;
break;
default :
cout << "you got nithing" << endl;
}
}
| true |
f0502a1a9ae27c9feb1610531808c3d9297c80ce | C++ | amanpratapsingh9/Data_Structures_Coding_Ninjas | /Graphs-1/Adjaceny_List_vector.cpp | UTF-8 | 758 | 3.25 | 3 | [] | no_license | #include<iostream>
#include<string>
#include<string>
#include<bits/stdc++.h>
using namespace std;
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void printGraph(vector<int> adj[], int V)
{
for(int i=0;i<V;i++)
{
cout << "Adjaceny List for vertex " << i << " is " << endl;
cout << "Head";
for(int j=0;j<adj[i].size();j++)
cout << " -> " << adj[i][j] ;
cout << endl << endl;
}
}
int main()
{
int V = 5; //no. of vertices
vector<int> *adj = new vector<int>[V];
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
printGraph(adj, V);
return 0;
return 0 ;
}
| true |
9662053f4fce8f7fbd612efe95f9ff268e70e5c0 | C++ | lineCode/acl | /includes/acl/core/memory.h | UTF-8 | 10,992 | 2.75 | 3 | [
"MIT"
] | permissive | #pragma once
////////////////////////////////////////////////////////////////////////////////
// The MIT License (MIT)
//
// Copyright (c) 2017 Nicholas Frechette & Animation Compression Library contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#include "acl/core/error.h"
#include <malloc.h>
#include <stdint.h>
#include <type_traits>
#include <limits>
#include <memory>
namespace acl
{
constexpr bool is_power_of_two(size_t input)
{
return input != 0 && (input & (input - 1)) == 0;
}
template<typename Type>
constexpr bool is_alignment_valid(size_t alignment)
{
return is_power_of_two(alignment) && alignment >= alignof(Type);
}
//////////////////////////////////////////////////////////////////////////
class Allocator
{
public:
static constexpr size_t DEFAULT_ALIGNMENT = 16;
Allocator() {}
virtual ~Allocator() {}
Allocator(const Allocator&) = delete;
Allocator& operator=(const Allocator&) = delete;
virtual void* allocate(size_t size, size_t alignment = DEFAULT_ALIGNMENT)
{
return _aligned_malloc(size, alignment);
}
virtual void deallocate(void* ptr, size_t size)
{
if (ptr == nullptr)
return;
_aligned_free(ptr);
}
};
template<typename AllocatedType, typename... Args>
AllocatedType* allocate_type(Allocator& allocator, Args&&... args)
{
AllocatedType* ptr = reinterpret_cast<AllocatedType*>(allocator.allocate(sizeof(AllocatedType), alignof(AllocatedType)));
if (std::is_trivially_default_constructible<AllocatedType>::value)
return ptr;
return new(ptr) AllocatedType(std::forward<Args>(args)...);
}
template<typename AllocatedType, typename... Args>
AllocatedType* allocate_type(Allocator& allocator, size_t alignment, Args&&... args)
{
ACL_ENSURE(is_alignment_valid<AllocatedType>(alignment), "Invalid alignment: %u. Expected a power of two at least equal to %u", alignment, alignof(AllocatedType));
AllocatedType* ptr = reinterpret_cast<AllocatedType*>(allocator.allocate(sizeof(AllocatedType), alignment));
if (std::is_trivially_default_constructible<AllocatedType>::value)
return ptr;
return new(ptr) AllocatedType(std::forward<Args>(args)...);
}
template<typename AllocatedType>
void deallocate_type(Allocator& allocator, AllocatedType* ptr)
{
if (ptr == nullptr)
return;
if (!std::is_trivially_destructible<AllocatedType>::value)
ptr->~AllocatedType();
allocator.deallocate(ptr, sizeof(AllocatedType));
}
template<typename AllocatedType, typename... Args>
AllocatedType* allocate_type_array(Allocator& allocator, size_t num_elements, Args&&... args)
{
AllocatedType* ptr = reinterpret_cast<AllocatedType*>(allocator.allocate(sizeof(AllocatedType) * num_elements, alignof(AllocatedType)));
if (std::is_trivially_default_constructible<AllocatedType>::value)
return ptr;
for (size_t element_index = 0; element_index < num_elements; ++element_index)
new(&ptr[element_index]) AllocatedType(std::forward<Args>(args)...);
return ptr;
}
template<typename AllocatedType, typename... Args>
AllocatedType* allocate_type_array(Allocator& allocator, size_t num_elements, size_t alignment, Args&&... args)
{
ACL_ENSURE(is_alignment_valid<AllocatedType>(alignment), "Invalid alignment: %u. Expected a power of two at least equal to %u", alignment, alignof(AllocatedType));
AllocatedType* ptr = reinterpret_cast<AllocatedType*>(allocator.allocate(sizeof(AllocatedType) * num_elements, alignment));
if (std::is_trivially_default_constructible<AllocatedType>::value)
return ptr;
for (size_t element_index = 0; element_index < num_elements; ++element_index)
new(&ptr[element_index]) AllocatedType(std::forward<Args>(args)...);
return ptr;
}
template<typename AllocatedType>
void deallocate_type_array(Allocator& allocator, AllocatedType* elements, size_t num_elements)
{
if (elements == nullptr)
return;
if (!std::is_trivially_destructible<AllocatedType>::value)
{
for (size_t element_index = 0; element_index < num_elements; ++element_index)
elements[element_index].~AllocatedType();
}
allocator.deallocate(elements, sizeof(AllocatedType) * num_elements);
}
//////////////////////////////////////////////////////////////////////////
template<typename AllocatedType>
class Deleter
{
public:
Deleter() : m_allocator(nullptr) {}
Deleter(Allocator& allocator) : m_allocator(&allocator) {}
Deleter(const Deleter& deleter) : m_allocator(deleter.m_allocator) {}
void operator()(AllocatedType* ptr)
{
if (ptr == nullptr)
return;
if (!std::is_trivially_destructible<AllocatedType>::value)
ptr->~AllocatedType();
m_allocator->deallocate(ptr, sizeof(AllocatedType));
}
private:
Allocator* m_allocator;
};
template<typename AllocatedType, typename... Args>
std::unique_ptr<AllocatedType, Deleter<AllocatedType>> make_unique(Allocator& allocator, Args&&... args)
{
return std::unique_ptr<AllocatedType, Deleter<AllocatedType>>(
allocate_type<AllocatedType>(allocator, std::forward<Args>(args)...),
Deleter<AllocatedType>(allocator));
}
template<typename AllocatedType, typename... Args>
std::unique_ptr<AllocatedType, Deleter<AllocatedType>> make_unique(Allocator& allocator, size_t alignment, Args&&... args)
{
return std::unique_ptr<AllocatedType, Deleter<AllocatedType>>(
allocate_type<AllocatedType>(allocator, alignment, std::forward<Args>(args)...),
Deleter<AllocatedType>(allocator));
}
template<typename AllocatedType, typename... Args>
std::unique_ptr<AllocatedType, Deleter<AllocatedType>> make_unique_array(Allocator& allocator, size_t num_elements, Args&&... args)
{
return std::unique_ptr<AllocatedType, Deleter<AllocatedType>>(
allocate_type_array<AllocatedType>(allocator, num_elements, std::forward<Args>(args)...),
Deleter<AllocatedType>(allocator));
}
template<typename AllocatedType, typename... Args>
std::unique_ptr<AllocatedType, Deleter<AllocatedType>> make_unique_array(Allocator& allocator, size_t num_elements, size_t alignment, Args&&... args)
{
return std::unique_ptr<AllocatedType, Deleter<AllocatedType>>(
allocate_type_array<AllocatedType>(allocator, num_elements, alignment, std::forward<Args>(args)...),
Deleter<AllocatedType>(allocator));
}
//////////////////////////////////////////////////////////////////////////
template<typename PtrType>
constexpr bool is_aligned_to(PtrType* value, size_t alignment)
{
return (reinterpret_cast<uintptr_t>(value) & (alignment - 1)) == 0;
}
template<typename IntegralType>
constexpr bool is_aligned_to(IntegralType value, size_t alignment)
{
return (static_cast<size_t>(value) & (alignment - 1)) == 0;
}
template<typename PtrType>
constexpr bool is_aligned(PtrType* value)
{
return is_aligned_to(value, alignof(PtrType));
}
template<typename PtrType>
constexpr PtrType* align_to(PtrType* value, size_t alignment)
{
return reinterpret_cast<PtrType*>((reinterpret_cast<uintptr_t>(value) + (alignment - 1)) & ~(alignment - 1));
}
template<typename IntegralType>
constexpr IntegralType align_to(IntegralType value, size_t alignment)
{
return static_cast<IntegralType>((static_cast<size_t>(value) + (alignment - 1)) & ~(alignment - 1));
}
template<typename DestPtrType, typename SrcPtrType>
inline DestPtrType* safe_ptr_cast(SrcPtrType* input)
{
ACL_ENSURE(is_aligned_to(input, alignof(DestPtrType)), "reinterpret_cast would result in an unaligned pointer");
return reinterpret_cast<DestPtrType*>(input);
}
template<typename DestPtrType, typename SrcIntegralType>
inline DestPtrType* safe_ptr_cast(SrcIntegralType input)
{
ACL_ENSURE(is_aligned_to(input, alignof(DestPtrType)), "reinterpret_cast would result in an unaligned pointer");
return reinterpret_cast<DestPtrType*>(input);
}
template<typename DestIntegralType, typename SrcIntegralType>
inline DestIntegralType safe_static_cast(SrcIntegralType input)
{
ACL_ENSURE(input >= std::numeric_limits<DestIntegralType>::min() && input <= std::numeric_limits<DestIntegralType>::max(), "static_cast would result in truncation");
return static_cast<DestIntegralType>(input);
}
template<typename OutputPtrType, typename InputPtrType, typename OffsetType>
constexpr OutputPtrType* add_offset_to_ptr(InputPtrType* ptr, OffsetType offset)
{
return safe_ptr_cast<OutputPtrType>(reinterpret_cast<uintptr_t>(ptr) + offset);
}
//////////////////////////////////////////////////////////////////////////
struct InvalidPtrOffset {};
template<typename DataType, typename OffsetType>
class PtrOffset
{
public:
constexpr PtrOffset() : m_value(0) {}
constexpr PtrOffset(size_t value) : m_value(safe_static_cast<OffsetType>(value)) {}
constexpr PtrOffset(InvalidPtrOffset) : m_value(std::numeric_limits<OffsetType>::max()) {}
template<typename BaseType>
constexpr DataType* add_to(BaseType* ptr) const
{
ACL_ENSURE(is_valid(), "Invalid PtrOffset!");
return add_offset_to_ptr<DataType>(ptr, m_value);
}
template<typename BaseType>
constexpr const DataType* add_to(const BaseType* ptr) const
{
ACL_ENSURE(is_valid(), "Invalid PtrOffset!");
return add_offset_to_ptr<const DataType>(ptr, m_value);
}
template<typename BaseType>
constexpr DataType* safe_add_to(BaseType* ptr) const
{
return is_valid() ? add_offset_to_ptr<DataType>(ptr, m_value) : nullptr;
}
template<typename BaseType>
constexpr const DataType* safe_add_to(const BaseType* ptr) const
{
return is_valid() ? add_offset_to_ptr<DataType>(ptr, m_value) : nullptr;
}
constexpr operator OffsetType() const { return m_value; }
constexpr bool is_valid() const { return m_value != std::numeric_limits<OffsetType>::max(); }
private:
OffsetType m_value;
};
template<typename DataType>
using PtrOffset16 = PtrOffset<DataType, uint16_t>;
template<typename DataType>
using PtrOffset32 = PtrOffset<DataType, uint32_t>;
}
| true |
a199ca50691519bdb0544eed67f33a421e6b170c | C++ | breakds/monster-avengers | /cpp/utils/jewels_query.h | UTF-8 | 13,302 | 2.59375 | 3 | [
"MIT"
] | permissive | #ifndef _MONSTER_AVENGERS_UTILS_JEWELS_QUERY_
#define _MONSTER_AVENGERS_UTILS_JEWELS_QUERY_
#include <array>
#include <vector>
#include <utility>
#include <unordered_set>
#include <unordered_map>
#include "dataset/dataset.h"
#include "utils/filter.h"
#include "utils/signature.h"
namespace monster_avengers {
using dataset::Data;
class SlotClient {
public:
const static int MAX_ONES = 24;
const static int MAX_TWOS = 8;
const static int MAX_THREES = 8;
SlotClient(const std::vector<int> &skill_ids,
const std::vector<Effect> &effects,
const JewelFilter &filter)
: jewel_keys_() {
bool valid = false;
for (int i = 0; i < Data::jewels().size(); ++i) {
const Jewel &jewel = Data::jewel(i);
if (filter.Validate(i)) {
Signature key = Signature(jewel, skill_ids,
effects, &valid);
if (valid) {
jewel_keys_[jewel.slots].insert(key);
}
}
}
buffer_[0].insert(Signature());
fixed_buffer_[1][0].insert(Signature());
fixed_buffer_[2][0].insert(Signature());
fixed_buffer_[3][0].insert(Signature());
}
SlotClient(const std::vector<Effect> &effects,
const JewelFilter &filter)
: SlotClient(SkillIdsFromEffects(effects), effects, filter) {}
SlotClient(int skill_id,
const std::vector<Effect> &effects,
const JewelFilter &filter)
: SlotClient(std::vector<int>({skill_id}),
effects, filter) {}
inline const std::unordered_set<Signature> &Query(Signature input) {
int i(0), j(0), k(0);
sig::KeySlots(input, &i, &j, &k);
return Calculate(i, j, k, input.BodySlotSum(), input.multiplier());
}
inline const std::unordered_set<Signature> &Query(int i,
int j,
int k,
int extra,
int multiplier) {
return Calculate(i, j, k, extra, multiplier);
}
// Use the hole aligment from stuffed to stuff the original hole
// aligment, and get the residual hole alignment.
static void GetResidual(const Signature &original,
const Signature &stuffed,
int *i, int *j, int *k, int *extra) {
sig::KeySlots(original, i, j, k);
int one(0), two(0), three(0);
sig::KeySlots(stuffed, &one, &two, &three);
// Handle 3 slots
*k -= three;
// Handle 2 slots
if (two <= *j) {
*j -= two;
} else {
two -= *j;
*j = 0;
*k -= two;
*i += two;
}
if (one <= *i) {
*i -= one;
} else {
one -= *i;
*i = 0;
if (one <= ((*j) << 1)) {
*j -= ((one + 1) >> 1);
if (1 & one) {
*i = 1;
}
} else {
one -= (*j << 1);
*j = 0;
*k -= ((one + 2) / 3);
int remain = one % 3;
if (1 == remain) {
(*j)++;
} else if (2 == remain) {
(*i)++;
}
}
}
// Handle Extra:
*extra = original.BodySlotSum() - stuffed.BodySlotSum();
}
// This is only for unit test purpose.
std::unordered_set<Signature> DFS(int i, int j, int k) {
std::array<std::vector<Signature>, 4> jewels;
for (int slots = 1; slots <= 3; ++slots) {
for (const Signature &key : jewel_keys_[slots]) {
jewels[slots].push_back(key);
}
}
std::unordered_set<Signature> result;
DFS(i, j, k, 3, 0, Signature(), jewels, &result);
return result;
}
private:
std::vector<int> SkillIdsFromEffects(const std::vector<Effect> &effects) {
std::vector<int> skill_ids;
for (const Effect &effect : effects) {
skill_ids.push_back(effect.id);
}
return skill_ids;
}
inline void SetProduct(const std::unordered_set<Signature> &a,
const std::unordered_set<Signature> &b,
std::unordered_set<Signature> *c) {
for (const Signature &key_a : a) {
for (const Signature &key_b : b) {
c->insert(key_a + key_b);
}
}
}
inline void SetUnion(const std::unordered_set<Signature> &input,
std::unordered_set<Signature> *base) {
for (const Signature &key : input) {
base->insert(key);
}
}
const std::unordered_set<Signature> &CalculateFixed(int slots, int i) {
if (!fixed_buffer_[slots][i].empty()) {
return fixed_buffer_[slots][i];
}
SetProduct(CalculateFixed(slots, i - 1),
jewel_keys_[slots],
&fixed_buffer_[slots][i]);
return fixed_buffer_[slots][i];
}
const std::unordered_set<Signature> &Calculate(int i) {
if (!buffer_[i].empty()) {
return buffer_[i];
}
buffer_[i] = CalculateFixed(1, i);
SetUnion(Calculate(i - 1),
&buffer_[i]);
return buffer_[i];
}
const std::unordered_set<Signature> &Calculate(int i, int j) {
int index = j * MAX_ONES + i;
if (!buffer_[index].empty()) {
return buffer_[index];
}
if (0 == j) {
return Calculate(i);
}
SetProduct(Calculate(i),
CalculateFixed(2, j),
&buffer_[index]);
SetUnion(Calculate(i + 2, j - 1),
&buffer_[index]);
return buffer_[index];
}
const std::unordered_set<Signature> &Calculate(int i, int j, int k) {
int index = (k * MAX_TWOS + j) * MAX_ONES + i;
if (!buffer_[index].empty()) {
return buffer_[index];
}
if (0 == j && 0 == k) {
return Calculate(i);
}
if (0 == k) {
return Calculate(i, j);
}
SetProduct(Calculate(i, j), CalculateFixed(3, k),
&buffer_[index]);
SetUnion(Calculate(i + 1, j + 1, k - 1),
&buffer_[index]);
return buffer_[index];
}
const std::unordered_set<Signature> &Calculate(int i, int j, int k,
int extra, int multiplier) {
const std::unordered_set<Signature> &base_answer = Calculate(i, j, k);
if (2 > multiplier || 0 == extra) {
return base_answer;
}
int index = ((((multiplier -1) * 3 + (extra - 1)) * MAX_THREES + k) * MAX_TWOS
+ j) * MAX_ONES + i;
if (!buffer_[index].empty()) {
return buffer_[index];
}
const std::unordered_set<Signature> &extension =
1 == extra ? Calculate(1, 0, 0) :
(2 == extra ? Calculate(0, 1, 0) : Calculate(0, 0, 1));
std::unordered_set<Signature> transformed;
for (Signature key : extension) {
key.BodyRefactor(multiplier);
transformed.insert(key);
}
SetProduct(base_answer, transformed, &buffer_[index]);
return buffer_[index];
}
void DFS(int i, int j, int k, int slots, int id, Signature key,
const std::array<std::vector<Signature>, 4> &jewels,
std::unordered_set<Signature> *result) {
result->insert(key);
if (0 == i + j + k) {
return;
}
int p = slots;
int q = id;
do {
if (1 == p) {
if (0 < i) {
DFS(i - 1, j, k, p, q,
key + jewels[p][q],
jewels, result);
} else if (0 < j) {
DFS(i + 1, j - 1, k, p, q,
key + jewels[p][q],
jewels, result);
} else {
DFS(i, j + 1, k - 1, p, q,
key + jewels[p][q],
jewels, result);
}
} else if (2 == p) {
if (0 < j) {
DFS(i, j - 1, k, p, q,
key + jewels[p][q],
jewels, result);
} else if (0 < k) {
DFS(i + 1, j, k - 1, p, q,
key + jewels[p][q],
jewels, result);
}
} else if (3 == p) {
if (0 < k) {
DFS(i, j, k - 1, p, q,
key + jewels[p][q],
jewels, result);
}
}
q++;
if (jewels[p].size() <= q) {
p--;
q = 0;
}
} while (p > 0);
}
std::array<std::unordered_set<Signature>, 4> jewel_keys_;
std::array<std::array<std::unordered_set<Signature>,
MAX_ONES>, 4> fixed_buffer_;
std::array<std::unordered_set<Signature>,
MAX_ONES * MAX_TWOS * MAX_THREES * 3 * 5> buffer_;
};
class JewelSolver {
public:
typedef std::pair<std::unordered_map<int, int>,
std::unordered_map<int, int> > JewelPlan;
JewelSolver(const std::vector<Effect> &effects,
const JewelFilter &filter)
: jewel_keys_() {
bool valid = false;
std::vector<int> skill_ids;
for (const Effect &effect : effects) {
skill_ids.push_back(effect.id);
}
for (int i = 0; i < Data::jewels().size(); ++i) {
if (filter.Validate(i)) {
const Jewel &jewel = Data::jewel(i);
Signature key = Signature(jewel, skill_ids, effects, &valid);
if (valid) {
jewel_keys_[jewel.slots].push_back(key);
jewel_ids_[jewel.slots].push_back(i);
}
}
}
}
JewelPlan Solve(Signature key, int multiplier) const {
Signature target = sig::InverseKey(key);
int i(0), j(0), k(0);
sig::KeySlots(key, &i, &j, &k);
std::vector<int> ids;
std::vector<int> body_ids;
if (multiplier > 1) {
int a(0), b(0), c(0);
key.BodySlots(&a, &b, &c);
std::vector<SearchCriteria> criterias;
criterias.push_back({1, i, 1});
criterias.push_back({2, j, 1});
criterias.push_back({3, k, 1});
criterias.push_back({1, a, multiplier});
criterias.push_back({2, b, multiplier});
criterias.push_back({3, c, multiplier});
CHECK(Search(criterias,
5, // top
0, // criteria_id
0, // jewel_id
target, &ids, &body_ids));
} else {
CHECK(Search({{1, i, 1}, {2, j, 1}, {3, k, 1}},
2, // top
0, // criteria_id
0, // jewel_id
target, &ids, &body_ids));
}
JewelPlan result;
for (int id : ids) {
auto it = result.first.find(id);
if (result.first.end() != it) {
it->second++;
} else {
result.first[id] = 1;
}
}
for (int id : body_ids) {
auto it = result.second.find(id);
if (result.second.end() != it) {
it->second++;
} else {
result.second[id] = 1;
}
}
return result;
}
private:
struct SearchCriteria {
int slots;
int num;
int multiplier;
};
bool Search(const std::vector<SearchCriteria> &targets,
int top, int criteria_id, int jewel_id,
Signature key,
std::vector<int> *ids,
std::vector<int> *body_ids) const {
if (-1 == top) return key.IsZero();
if (criteria_id >= targets[top].num) {
return Search(targets, top - 1, 0, 0, key, ids, body_ids);
}
const int &slots = targets[top].slots;
const int &multiplier = targets[top].multiplier;
for (int seq = jewel_id; seq < jewel_ids_[slots].size(); ++seq) {
Signature jewel_key = jewel_keys_[slots][seq];
if (multiplier > 1) {
body_ids->push_back(jewel_ids_[slots][seq]);
jewel_key *= multiplier;
} else {
ids->push_back(jewel_ids_[slots][seq]);
}
if (Search(targets, top, criteria_id + 1, seq,
key | jewel_key, ids, body_ids)) {
return true;
}
if (multiplier > 1) {
body_ids->pop_back();
} else {
ids->pop_back();
}
}
return false;
}
std::array<std::vector<Signature>, 4> jewel_keys_;
std::array<std::vector<int>, 4> jewel_ids_;
};
class JewelAssigner {
public:
JewelAssigner(const Arsenal *arsenal)
: slots_part_(), slots_jewel_(),
arsenal_(arsenal), slots_(3) {}
inline void AddPart(int part, int id) {
const Armor &armor = (*arsenal_)[id];
slots_part_[armor.slots].push_back(part);
}
inline void AddJewel(int id, int quantity) {
const Jewel &jewel = Data::jewel(id);
for (int i = 0; i < quantity; ++i) {
slots_jewel_[jewel.slots].push_back(id);
}
}
inline bool Pop(int *part, int *jewel_id) {
// Default return value for jewel_id. This happens when there is
// no next assignment.
while (slots_ > 0 && slots_jewel_[slots_].empty()) {
slots_--;
}
if (0 < slots_) {
for (int used_slots = slots_; used_slots < 4; ++used_slots) {
if (slots_part_[used_slots].empty()) continue;
*part = slots_part_[used_slots].back();
*jewel_id = slots_jewel_[slots_].back();
slots_part_[used_slots].pop_back();
slots_jewel_[slots_].pop_back();
if (used_slots > slots_) {
slots_part_[used_slots - slots_].push_back(*part);
}
return true;
}
}
return false;
}
private:
std::array<std::vector<int>, 4> slots_part_;
std::array<std::vector<int>, 4> slots_jewel_;
const Arsenal *arsenal_;
int slots_;
};
} // namespace monster_avengers
#endif // _MONSTER_AVENGERS_UTILS_JEWELS_QUERY_
| true |
491ac5ce32771c7c5a4dd04329249cd565690c38 | C++ | zchambers3/CST-201 | /Week 2/Final Submission CLC/RemoveNodeDBL.cpp | UTF-8 | 1,499 | 3.78125 | 4 | [] | no_license | /*
* RemoveNode.cpp
*
* Created on: Mar 18, 2018
* Author: Caleb Miller
*/
#include <stdio.h>
#include <tchar.h>#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
struct Node {
int data;
struct Node *next;
struct Node *prev;
};
void deleteNode(struct Node **head_node, struct Node *del_node) {
if (*head_node == NULL || del_node == NULL)
return;
if (*head_node == del_node)
*head_node = del_node->next;
if (del_node->next != NULL)
del_node->next->prev = del_node->prev;
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
free(del_node);
return;
}
void push(struct Node** head_node, int new_data) {
//allocating node
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_node);
if ((*head_node) != NULL)
(*head_node)->prev = new_node;
(*head_node) = new_node;
}
void printList(struct Node *node) {
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}
int main() {
struct Node* head = NULL;
push(&head, 10);
push(&head, 20);
push(&head, 53);
push(&head, 79);
push(&head, 32);
cout << "Original Doubly Linked List Is: " << endl;
printList(head);
deleteNode(&head, head);
deleteNode(&head, head->next);
cout << "\nLinked List After Deletion at Head and Middle of List: " << endl;
printList(head);
}
| true |
ac82036cec0f24eb38a717a98df306007d1f153d | C++ | gazdik/l2-mitm-attack | /pcap.cpp | UTF-8 | 2,580 | 2.515625 | 3 | [] | no_license | /**
* Author: Peter Gazdík <xgazdi03(at)stud.fit.vutbr.cz>
*
* Date: 15/04/17
*/
#include "pcap.h"
#include <stdexcept>
#include <iostream>
using namespace std;
namespace pds
{
pcap::pcap(const char *interface, int timeout, bool promisc) :
_interface { interface }
{
init(timeout, promisc);
}
pcap::~pcap()
{
pcap_close(_handle);
}
int pcap::sendpacket(const void *buf, size_t size)
{
return pcap_inject(_handle, buf, size);
}
void pcap::init(int timeout, bool promisc)
{
_handle = pcap_create(_interface.c_str(), _errbuf);
pcap_set_promisc(_handle, promisc);
pcap_set_timeout(_handle, 200);
if (_handle == nullptr) {
cerr << "PCAP: Couldn't open device " << _interface
<< ". Try to run the program as root." << endl;
throw runtime_error("pcap_init");
}
if (pcap_activate(_handle) != 0) {
cerr << "PCAP Activate failed: " << pcap_geterr(_handle) << endl;
throw runtime_error("pcap_init");
}
if (pcap_datalink(_handle) != DLT_EN10MB) {
cerr << "The device doesn't provide Ethernet headers - not supported"
<< endl;
throw runtime_error("pcap_init");
}
if (pcap_lookupnet(_interface.c_str(), &_net, &_mask, _errbuf)) {
_net = 0;
_mask = 0;
}
}
void pcap::setFilter(const char *filter)
{
struct bpf_program fp;
if (pcap_compile(_handle, &fp, filter, true, _net) != 0) {
cerr << "Couldn't parse filter " << filter << ": "
<< pcap_geterr(_handle) << endl;
throw runtime_error("pcap_compile");
}
if (pcap_setfilter(_handle, &fp) != 0) {
cerr << "Couldn't set filter " << filter << ": "
<< pcap_geterr(_handle) << endl;
throw runtime_error("pcap_setfilter");
}
}
void
pcap::staticProcessPacket(u_char *instancePtr, const struct pcap_pkthdr *pkthdr,
const u_char *packet)
{
pcap *instance = (pcap *) instancePtr;
instance->processPacket(pkthdr, packet);
}
void pcap::processPacket(const struct pcap_pkthdr *pkthdr, const u_char *packet)
{
if (_callback) {
_callback(pkthdr, packet);
}
}
void pcap::dispatch(std::function<void(const struct pcap_pkthdr *,
const u_char *)> callback)
{
_callback = callback;
pcap_dispatch(_handle, -1, pcap::staticProcessPacket, (u_char *)this);
}
void pcap::breakloop()
{
pcap_breakloop(_handle);
}
void pcap::setNonBlock(bool nonblock)
{
pcap_setnonblock(_handle, nonblock, _errbuf);
}
} // namespace pds | true |
fd359f656552597510e50a0d79c8e53c40578578 | C++ | kizza/sensor | /lib/internet/internet.cpp | UTF-8 | 449 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | #include "WiFi.h"
#include "internet.h"
#include "promise.h"
std::function<Context (Context)> initWiFi(const char* ssid, const char* password) {
delay(10);
Serial.printf("Connecting to %s..", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.printf(" connected with %s\n", WiFi.localIP().toString().c_str());
return continuation();
}
| true |
587c9c04e614be00787eb6d4cebc81f9a4496090 | C++ | liubincodelife/DataStructureTasks | /T01_01_ArrayStack/ArrayStack.cpp | UTF-8 | 887 | 3.640625 | 4 | [
"Apache-2.0"
] | permissive | #include <iostream>
#include "ArrayStack.hpp"
using namespace std;
int main(int argc, char** argv)
{
ArrayStack<int> arrayStack(10);
cout << "push data into stack:" << endl;
for (int i = 1; i <= 10; i++)
{
arrayStack.push(i);
cout << i << " ";
}
cout << endl;
if (arrayStack.isEmpty())
cout << "The stack is empty!!! " << endl;
else
cout << "The stack is not empty!!! " << endl;
if (arrayStack.isFull())
cout << "The stack is full!!! " << endl;
else
cout << "The stack is not full!!! " << endl;
cout << "pop data out to stack:" << endl;
size_t stackSize = arrayStack.getSize();
for (int i = 0; i < stackSize; i++)
{
int retValue = arrayStack.top();
arrayStack.pop();
cout << retValue << " ";
}
cout << endl;
getchar();
return 0;
} | true |
06b4e59b68cc352c585e369836be263b546cb6a8 | C++ | george-hinkel/MICE_TeamA | /scoop.cpp | UTF-8 | 460 | 2.734375 | 3 | [] | no_license | #include <sstream>
#include "scoop.h"
Scoop::Scoop(std::string name,std::string description,double wholesale_cost,double retail_price,int initial_stock,std::string image_file_path) : Item(name,description,wholesale_cost,retail_price,initial_stock,image_file_path){
_type="scoop";
}
std::string Scoop::to_string(){
std::string t=" ";
std::stringstream ss;
ss << Item::to_string() << std::endl;
ss << t << _description;
return ss.str();
}
| true |
b13c838ea7dd5757fe42e49743bb1fae3d075aae | C++ | sophialundstrom/3D-Project | /Project/Random.h | UTF-8 | 413 | 3.03125 | 3 | [] | no_license | #pragma once
#include <random>
struct Random
{
static float Real(float min, float max)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<float> value(min, max);
return value(mt);
}
static int Integer(int min, int max)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_int_distribution<int> value(min, max);
return value(mt);
}
}; | true |
616207bdda24a89be2f7c9845ebc32b2682a4584 | C++ | ha-k-pg-mori/ProductionShooting | /Shooting/Src/Player.cpp | UTF-8 | 2,247 | 2.53125 | 3 | [] | no_license | #include "Player.h"
#include "InputManager.h"
#include "Definition.h"
#include "../Src/Manager/BulletManager.h"
Player::Player()
{
Player::Pos = Vec2(100.0f, 200.0f);
Player::Speed = 2.0f;
Player::AnimationFrameCounter = 0;
Player::AnimationId = 0;
Player::counter = 0;
}
Player::~Player()
{
}
void Player::Init(Vec2 init_pos)
{
Pos = init_pos;
}
void Player::Update()
{
BulletManager* p_BulletManager = BulletManager::GetInstance();
InputManager* pInputMng = InputManager::GetInstance();
if (pInputMng->IsOn(KeyType_Up))
{
Pos.Y -= Speed;
}
if (pInputMng->IsOn(KeyType_Down))
{
Pos.Y += Speed;
}
if (pInputMng->IsOn(KeyType_Left))
{
Pos.X -= Speed;
}
if (pInputMng->IsOn(KeyType_Right))
{
Pos.X += Speed;
}
if (pInputMng->IsPush(KeyType_Shoot))
{
p_BulletManager->CreateBullet(Vec2(Pos.X + 35.0f, Pos.Y + 28.0f));
}
if (Pos.X < 0.0f)
{
Pos.X = 0.0f;
}
if (Pos.Y < 0.0f)
{
Pos.Y = 0.0f;
}
if (Pos.X > 600.0f)
{
Pos.X = 600.0f;
}
if (Pos.Y > 420.0f)
{
Pos.Y = 420.0f;
}
if (AnimationFrameCounter % 4 == 0)
{
AnimationFrameCounter = 0;
AnimationId++;
if (AnimationId % 3 == 0)
{
AnimationId = 0;
}
}
}
void Player::Draw()
{
//DrawGraph(Pos.X, Pos.Y, Robot, FALSE);
int MosyonList[]
{
LoadGraph("image/Robot_idle 1.PNG"),
LoadGraph("image/Robot_idle 2.PNG"),
LoadGraph("image/Robot_idle 3.PNG"),
};
DrawGraph(Pos.X, Pos.Y, MosyonList[AnimationId],TRUE);
}
//Player* Player::number(int Counter)
//{
// /*counter = Counter;
// InputManager* pInputMng = InputManager::GetInstance();
// if (pInputMng->IsPush(KeyType_Counter))
// {
// counter += 1;
// }*/
//}
Player* Player::m_pInstance = nullptr;
// ���̂����
void Player::CreateInstance()
{
// null�`�F�b�N����邱�ƂŁA�Q��ڈȍ~�͍���Ȃ�
if (m_pInstance == nullptr)
{
m_pInstance = new Player();
}
}
// ���̂�j�������
void Player::DestroyInstance()
{
delete m_pInstance;
m_pInstance = nullptr;
}
// ���̂����邩��m�F�����
bool Player::IsNull()
{
return (m_pInstance == nullptr);
}
// ���̂�擾�����
Player* Player::GetInstance()
{
return m_pInstance;
} | true |
6e4642e0a6abcb3aa50e4f4c717e41131ff8be1d | C++ | ecorman/WiiWhiteboard | /Warper.cpp | UTF-8 | 7,953 | 2.75 | 3 | [
"Unlicense"
] | permissive | // Warper.cpp
// Implements the Warper class representing the engine that turns Wiimote coords into screen coords, based on calibration
#include "Globals.h"
#include "Warper.h"
#include "Calibration.h"
static const Warper::Matrix::Number EPS = static_cast<Warper::Matrix::Number>(0.00001);
////////////////////////////////////////////////////////////////////////////////
// Warper::Matrix:
bool Warper::Matrix::squareToQuad(
Number a_DstX1, Number a_DstY1,
Number a_DstX2, Number a_DstY2,
Number a_DstX3, Number a_DstY3,
Number a_DstX4, Number a_DstY4
)
{
Number ax = a_DstX1 - a_DstX2 + a_DstX3 - a_DstX4;
Number ay = a_DstY1 - a_DstY2 + a_DstY3 - a_DstY4;
if ((std::abs(ax) < EPS) && (std::abs(ay) < EPS))
{
// afine transform
m_Matrix[0][0] = a_DstX2 - a_DstX1;
m_Matrix[0][1] = a_DstY2 - a_DstY1;
m_Matrix[0][2] = 0;
m_Matrix[1][0] = a_DstX3 - a_DstX2;
m_Matrix[1][1] = a_DstY3 - a_DstY2;
m_Matrix[1][2] = 0;
m_Matrix[2][0] = a_DstX1;
m_Matrix[2][1] = a_DstY1;
m_Matrix[2][2] = 1;
}
else
{
Number ax1 = a_DstX2 - a_DstX3;
Number ax2 = a_DstX4 - a_DstX3;
Number ay1 = a_DstY2 - a_DstY3;
Number ay2 = a_DstY4 - a_DstY3;
// Sub-determinants
Number gtop = ax * ay2 - ax2 * ay;
Number htop = ax1 * ay - ax * ay1;
Number bottom = ax1 * ay2 - ax2 * ay1;
if (std::abs(bottom) < EPS)
{
return false;
}
Number g = gtop / bottom;
Number h = htop / bottom;
m_Matrix[0][0] = a_DstX2 - a_DstX1 + g * a_DstX2;
m_Matrix[1][0] = a_DstX4 - a_DstX1 + h * a_DstX4;
m_Matrix[2][0] = a_DstX1;
m_Matrix[0][1] = a_DstY2 - a_DstY1 + g * a_DstY2;
m_Matrix[1][1] = a_DstY4 - a_DstY1 + h * a_DstY4;
m_Matrix[2][1] = a_DstY1;
m_Matrix[0][2] = g;
m_Matrix[1][2] = h;
m_Matrix[2][2] = 1;
}
return true;
}
bool Warper::Matrix::quadToSquare(
Number a_SrcX1, Number a_SrcY1,
Number a_SrcX2, Number a_SrcY2,
Number a_SrcX3, Number a_SrcY3,
Number a_SrcX4, Number a_SrcY4
)
{
// Compute the Square-to-Quad transform and invert it:
if (!squareToQuad(a_SrcX1, a_SrcY1, a_SrcX2, a_SrcY2, a_SrcX3, a_SrcY3, a_SrcX4, a_SrcY4))
{
return false;
}
if (!invert())
{
return false;
}
return true;
}
bool Warper::Matrix::invert()
{
Number det = determinant();
if (std::abs(det) < EPS)
{
return false;
}
Number h11 = m_Matrix[1][1] * m_Matrix[2][2] - m_Matrix[1][2] * m_Matrix[2][1];
Number h21 = m_Matrix[1][2] * m_Matrix[2][0] - m_Matrix[1][0] * m_Matrix[2][2];
Number h31 = m_Matrix[1][0] * m_Matrix[2][1] - m_Matrix[1][1] * m_Matrix[2][0];
Number h12 = m_Matrix[0][2] * m_Matrix[2][1] - m_Matrix[0][1] * m_Matrix[2][2];
Number h22 = m_Matrix[0][0] * m_Matrix[2][2] - m_Matrix[0][2] * m_Matrix[2][0];
Number h32 = m_Matrix[0][1] * m_Matrix[2][0] - m_Matrix[0][0] * m_Matrix[2][1];
Number h13 = m_Matrix[0][1] * m_Matrix[1][2] - m_Matrix[0][2] * m_Matrix[1][1];
Number h23 = m_Matrix[0][2] * m_Matrix[1][0] - m_Matrix[0][0] * m_Matrix[1][2];
Number h33 = m_Matrix[0][0] * m_Matrix[1][1] - m_Matrix[0][1] * m_Matrix[1][0];
m_Matrix[0][0] = h11 / det;
m_Matrix[1][0] = h21 / det;
m_Matrix[2][0] = h31 / det;
m_Matrix[0][1] = h12 / det;
m_Matrix[1][1] = h22 / det;
m_Matrix[2][1] = h32 / det;
m_Matrix[0][2] = h13 / det;
m_Matrix[1][2] = h23 / det;
m_Matrix[2][2] = h33 / det;
return true;
}
Warper::Matrix::Number Warper::Matrix::determinant() const
{
return (
m_Matrix[0][0] * (m_Matrix[2][2] * m_Matrix[1][1] - m_Matrix[2][1] * m_Matrix[1][2]) -
m_Matrix[1][0] * (m_Matrix[2][2] * m_Matrix[0][1] - m_Matrix[2][1] * m_Matrix[0][2]) +
m_Matrix[2][0] * (m_Matrix[1][2] * m_Matrix[0][1] - m_Matrix[1][1] * m_Matrix[0][2])
);
}
void Warper::Matrix::multiplyBy(const Warper::Matrix & a_Other)
{
Number m11 = m_Matrix[0][0] * a_Other.m_Matrix[0][0] + m_Matrix[0][1] * a_Other.m_Matrix[1][0] + m_Matrix[0][2] * a_Other.m_Matrix[2][0];
Number m12 = m_Matrix[0][0] * a_Other.m_Matrix[0][1] + m_Matrix[0][1] * a_Other.m_Matrix[1][1] + m_Matrix[0][2] * a_Other.m_Matrix[2][1];
Number m13 = m_Matrix[0][0] * a_Other.m_Matrix[0][2] + m_Matrix[0][1] * a_Other.m_Matrix[1][2] + m_Matrix[0][2] * a_Other.m_Matrix[2][2];
Number m21 = m_Matrix[1][0] * a_Other.m_Matrix[0][0] + m_Matrix[1][1] * a_Other.m_Matrix[1][0] + m_Matrix[1][2] * a_Other.m_Matrix[2][0];
Number m22 = m_Matrix[1][0] * a_Other.m_Matrix[0][1] + m_Matrix[1][1] * a_Other.m_Matrix[1][1] + m_Matrix[1][2] * a_Other.m_Matrix[2][1];
Number m23 = m_Matrix[1][0] * a_Other.m_Matrix[0][2] + m_Matrix[1][1] * a_Other.m_Matrix[1][2] + m_Matrix[1][2] * a_Other.m_Matrix[2][2];
Number m31 = m_Matrix[2][0] * a_Other.m_Matrix[0][0] + m_Matrix[2][1] * a_Other.m_Matrix[1][0] + m_Matrix[2][2] * a_Other.m_Matrix[2][0];
Number m32 = m_Matrix[2][0] * a_Other.m_Matrix[0][1] + m_Matrix[2][1] * a_Other.m_Matrix[1][1] + m_Matrix[2][2] * a_Other.m_Matrix[2][1];
Number m33 = m_Matrix[2][0] * a_Other.m_Matrix[0][2] + m_Matrix[2][1] * a_Other.m_Matrix[1][2] + m_Matrix[2][2] * a_Other.m_Matrix[2][2];
m_Matrix[0][0] = m11;
m_Matrix[1][0] = m21;
m_Matrix[2][0] = m31;
m_Matrix[0][1] = m12;
m_Matrix[1][1] = m22;
m_Matrix[2][1] = m32;
m_Matrix[0][2] = m13;
m_Matrix[1][2] = m23;
m_Matrix[2][2] = m33;
}
POINT Warper::Matrix::project(POINT a_Src) const
{
auto res = project(static_cast<Number>(a_Src.x), static_cast<Number>(a_Src.y));
return
{
static_cast<LONG>(res.first),
static_cast<LONG>(res.second)
};
}
std::pair<Warper::Matrix::Number, Warper::Matrix::Number> Warper::Matrix::project(Number a_X, Number a_Y) const
{
Number nx = m_Matrix[0][0] * a_X + m_Matrix[1][0] * a_Y + m_Matrix[2][0];
Number ny = m_Matrix[0][1] * a_X + m_Matrix[1][1] * a_Y + m_Matrix[2][1];
Number w = m_Matrix[0][2] * a_X + m_Matrix[1][2] * a_Y + m_Matrix[2][2];
if (w < EPS)
{
w = EPS;
}
return std::make_pair(nx / w, ny / w);
}
////////////////////////////////////////////////////////////////////////////////
// Warper:
Warper::Warper()
{
// Nothing needed yet
}
void Warper::setCalibration(const Calibration & a_Calibration)
{
m_Matrices.clear();
for (const auto & mapping: a_Calibration.getMappings())
{
if (!mapping.second.isUsable())
{
continue;
}
auto & matrix = m_Matrices[mapping.first];
// Project from Wiimote coords to screen coords via a unit square:
const auto & points = mapping.second.m_Points;
matrix.quadToSquare(
static_cast<Matrix::Number>(points[0].m_WiimoteX), static_cast<Matrix::Number>(points[0].m_WiimoteY),
static_cast<Matrix::Number>(points[1].m_WiimoteX), static_cast<Matrix::Number>(points[1].m_WiimoteY),
static_cast<Matrix::Number>(points[2].m_WiimoteX), static_cast<Matrix::Number>(points[2].m_WiimoteY),
static_cast<Matrix::Number>(points[3].m_WiimoteX), static_cast<Matrix::Number>(points[3].m_WiimoteY)
);
Matrix helper;
helper.squareToQuad(
static_cast<Matrix::Number>(points[0].m_ScreenX), static_cast<Matrix::Number>(points[0].m_ScreenY),
static_cast<Matrix::Number>(points[1].m_ScreenX), static_cast<Matrix::Number>(points[1].m_ScreenY),
static_cast<Matrix::Number>(points[2].m_ScreenX), static_cast<Matrix::Number>(points[2].m_ScreenY),
static_cast<Matrix::Number>(points[3].m_ScreenX), static_cast<Matrix::Number>(points[3].m_ScreenY)
);
matrix.multiplyBy(helper);
} // for mapping - a_Calibration[]
}
std::vector<const Wiimote *> Warper::getWarpableWiimotes() const
{
std::vector<const Wiimote *> res;
for (const auto & w: m_Matrices)
{
res.push_back(w.first);
}
return res;
}
POINT Warper::warp(Wiimote & a_Wiimote, POINT a_WiimotePoint) const
{
const auto itr = m_Matrices.find(&a_Wiimote);
assert(itr != m_Matrices.end());
auto res = itr->second.project(static_cast<Matrix::Number>(a_WiimotePoint.x), static_cast<Matrix::Number>(a_WiimotePoint.y));
return
{
static_cast<LONG>(std::floor(res.first + static_cast<Matrix::Number>(0.5))),
static_cast<LONG>(std::floor(res.second + static_cast<Matrix::Number>(0.5)))
};
}
| true |
c5d52b434e0d22785a34b67f10f4463c4fbd4742 | C++ | heegyubaek/algorithm | /sort/recursive.cpp | UTF-8 | 321 | 3.234375 | 3 | [] | no_license | #include <iostream>
using namespace std;
void printA(int n, int i)
{
if(i == 7)
{
return ;
}
int a = n;
while(a!=0)
{
cout << i;
a--;
}
cout << endl;
return printA(n,i+1);
}
int main()
{
int n = 0;
cin >> n;
cout << "input value is "<< n << endl;
int i = 1;
printA(n, i);
return -1;
}
| true |
ba99ba7128d171e272175c93e506b2daf5378816 | C++ | ljjj/PlayGround | /LeetCode/76. Minimum Window Substring.cpp | UTF-8 | 2,260 | 3.078125 | 3 | [] | no_license | class Solution {
public:
string minWindow(string s, string t) {
// build hash map for last positions of characters in T, each character key maps to a value of deque
unordered_map<char, deque<int>> last_pos;
for (const auto & c : t) {
if (last_pos.find(c) != last_pos.end()) last_pos[c].push_back(-1);
else last_pos.emplace(c, deque<int>{-1});
}
// build hash map to indicate the remaining characters in T that have not been found
unordered_map<char, int> found;
for (auto it = last_pos.begin(); it != last_pos.end(); it++) found.emplace(it->first, it->second.size());
// build a list of found positions in S of all characters in T
vector<bool> found_pos(s.size(), false);
string window = ""; // result window
int j = -1; // position of the earliest character in S that matches T so that s[j:i+1] is a window
bool all_found = false; // all characters in T have been found in S
for (int i = 0; i < s.size(); i++) {
if (last_pos.find(s[i]) != last_pos.end()) { // the character is in T
// update found status
if (j == -1) j = i;
if (!all_found && found.find(s[i]) != found.end()) {
found[s[i]] -= 1;
if (!found[s[i]]) found.erase(s[i]);
if (found.empty()) {
all_found = true;
window = s.substr(j, i+1-j);
}
}
// update new last positions of s[i]
int last = last_pos[s[i]].front();
last_pos[s[i]].pop_front();
last_pos[s[i]].push_back(i);
// update found positions
found_pos[i] = true;
if (last >= 0) // guaranteed found[last] == True
found_pos[last] = false;
if (j == last) { // update window
while (!found_pos[j]) j++;
if (all_found && window.size() > i+1-j) window = s.substr(j, i+1-j);
}
}
}
return window;
}
}; | true |
9ea0a7513004160f68ee0e917a39a19ba5c2c162 | C++ | charliemmao/Intranet | /include/php/java/chkgoods.inc | UTF-8 | 2,639 | 2.59375 | 3 | [] | no_license | <html>
<script language=javascript>
function chkgoods() {
var msg;
var i,j,target;
msg = itembyitem();
if (msg != "") {
alert("Please check following field(s) for item 0:\n\n" + msg + "\n\nCheck and resubmit.");
return false;
}
for (i=1; i<100; i++) {
target = document.all("name" + i.toString());
if (target != null) {
//alert("name" + i.toString() + "=" + target.value);
if (target.value) {
msg = checkbyitem(i);
if (msg != "") {
alert("Please check following field(s) for item " + i + ":\n\n" + msg + "\n\nCheck and resubmit.");
return false;
}
}
} else {
break;
}
}
return confirm("Are you sure you want to add the goods to system?\n\nRemember no modification is allowed afterwards.");
}
function checkbyitem(i) {
var msg="";
var tmp, tmpempty, regexp, target;
target = document.all("name" + i.toString());
if (target != null) {
tmp = target.value;
}
tmpempty = chkempty(tmp);
//alert(tmp);
if (tmpempty == "") {
msg = "Product Name:\tempty\n";
//alert(msg);
}
target = document.all("description" + i.toString());
if (target != null) {
tmp = target.value;
}
tmpempty = chkempty(tmp);
//alert(tmp);
if (tmpempty == "") {
msg = msg + "Description:\tempty\n";
//alert(msg);
}
target = document.all("price" + i.toString());
if (target != null) {
tmp = target.value;
}
tmpempty = chkmoney(tmp);
//alert(tmp);
if (tmpempty == "-1") {
msg = msg + "Price:\t(" + tmp + ") wrong format (0.00).\n";
} else {
target.value = tmpempty;
}
//name, description, supid, product_code
target = document.all("supid" + i.toString());
if (target != null) {
tmp = target.value;
}
tmp = document.goodslistman.supid.value;
if (tmp == "-1") {
msg = msg + "Supplier:\t\tempty\n";
}
return msg;
}
function itembyitem() {
var msg="";
var tmp, tmpempty, regexp;
tmp = document.goodslistman.name.value;
tmpempty = chkempty(tmp);
//alert(tmp);
if (tmpempty == "") {
msg = "Product Name:\tempty\n";
//alert(msg);
}
tmp = document.goodslistman.description.value;
tmpempty = chkempty(tmp);
//alert(tmp);
if (tmpempty == "") {
msg = msg + "Description:\tempty\n";
//alert(msg);
}
tmp = document.goodslistman.price.value;
tmpempty = chkmoney(tmp);
//alert(tmp);
if (tmpempty == "-1") {
msg = msg + "Price:\t(" + tmp + ") wrong format (0.00).\n";
} else {
document.goodslistman.price.value = tmpempty;
}
//name, description, supid, product_code
tmp = document.goodslistman.supid.value;
//alert(tmp);
if (tmp == "-1") {
msg = msg + "Supplier:\t\tempty\n";
//alert(msg);
}
return msg;
}
</script>
</html>
| true |
b7525d4fb2b9d353a8e99d05bc4a1339182b7b8a | C++ | VladislavSchastnyi/lab13.11.17 | /1.cpp | UTF-8 | 430 | 2.984375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int n, m;
cout << "Vvedite razmer massiva" << endl;
cin >> n;
if (n <= 0) {
cout << "error" << endl;
return 1;
}
cout << "" << endl;
int *a = new int [n];
for (m = 0; m < n; m++) {
cin >> a[m];
}
for (m = 0; m < n / 2 ; m++) {
swap(a[m], a[n - m -1]);
}
for (m = 0; m < n; m++) {
cout << a[m] << endl;
}
}
| true |
13af8a4c236307c7f1bbe2cc1372198151a71127 | C++ | prop-cc/prop-cc | /include/AD/contain/nsqarray.h | UTF-8 | 3,731 | 2.921875 | 3 | [
"BSD-2-Clause"
] | permissive | //////////////////////////////////////////////////////////////////////////////
// NOTICE:
//
// ADLib, Prop and their related set of tools and documentation are in the
// public domain. The author(s) of this software reserve no copyrights on
// the source code and any code generated using the tools. You are encouraged
// to use ADLib and Prop to develop software, in both academic and commercial
// settings, and are free to incorporate any part of ADLib and Prop into
// your programs.
//
// Although you are under no obligation to do so, we strongly recommend that
// you give away all software developed using our tools.
//
// We also ask that credit be given to us when ADLib and/or Prop are used in
// your programs, and that this notice be preserved intact in all the source
// code.
//
// This software is still under development and we welcome any suggestions
// and help from the users.
//
// Allen Leung
// 1994
//////////////////////////////////////////////////////////////////////////////
#ifndef n_dimensional_square_arrays_h
#define n_dimensional_square_arrays_h
///////////////////////////////////////////////////////////////////////
// NSqArray<T> is a very simple n-dimension array indexed by natural
// numbers that have the same bounds on each dimension.
///////////////////////////////////////////////////////////////////////
template <class T>
class NSqArray
{
NSqArray(const NSqArray&); // no copying constructor
void operator = (const NSqArray&); // no assignment
int n; // dimension
int capacities; // actual capacities of each dimension
T * table; // the table in one dimensional form
public:
const int Max_dimensions = 256;
NSqArray() : n(0), capacities(0), table(0)
{}
~NSqArray()
{
delete [] table;
}
void create( int N, int bounds);
int dimensions() const
{
return n;
}
int capacity() const
{
return capacites;
}
operator T* () const
{
return table;
}
T& operator [] (const int indices[]) const // indexing
{
register int i, offset;
for (offset = indices[0], i = 1; i < dimensions(); i++)
offset = indices[i] + offset * capacities;
return table[offset];
};
void grow(int size); // growth
};
///////////////////////////////////////////////////////////////////////
// Template methods
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Create a new table
///////////////////////////////////////////////////////////////////////
template <class T>
void NSqArray<T>::create( int N, int bounds)
{
n = N;
capacites = bounds;
int total = 1;
for (int i = 0; i < N; i++)
total *= bounds;
table = new T [total];
}
///////////////////////////////////////////////////////////////////////
// Growth in one dimension
///////////////////////////////////////////////////////////////////////
template <class T>
void NSqArray<T>::grow(int size)
{
if (size > capacities)
{
int new_size, old_size, i;
int diffs[Max_dimensions];
int indices[Max_dimensions];
for (i = 0, old_size = capacities, new_size = size; i < n; i++)
{
diffs[i] = new_size - old_size;
new_size *= size;
old_size *= capacities;
indices[i] = 0;
}
T * new_table = new T [new_size];
register T * p = table, * q = new_table;
do
{
*q++ = *p++;
for (i = n - 1; i >= 0; i--)
{
if (++indices[i] < capacities)
break;
q += diffs[i];
indices[i] = 0;
}
}
while (i >= 0);
delete [] table;
table = new_table;
capacities = size;
}
}
#endif
| true |
15cbae90129fbfa5e97aeb559ab720049254ede6 | C++ | dkoguciuk/thin_drivers | /thin_xsens/mtsdk/xcommunication/include/serialinterface.h | UTF-8 | 2,571 | 2.578125 | 3 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | #ifndef SERIALINTERFACE_H
#define SERIALINTERFACE_H
#include "streaminterface.h"
#include <xsens/xsplatform.h>
#include <xsens/xsmessage.h>
#include <xsens/xsbaud.h>
#include <xsens/xscontrolline.h>
struct XsPortInfo;
//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////// SerialInterface /////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
/*! \brief The low-level serial communication class.
*/
class SerialInterface : public StreamInterface {
private:
XSENS_DISABLE_COPY(SerialInterface)
XsFileHandle* rx_log;
XsFileHandle* tx_log;
protected:
//! The baudrate that was last set to be used by the port
XsBaudRate m_baudrate;
//! The time at which an operation will end in ms, used by several functions.
uint32_t m_endTime;
//! The last result of an operation
mutable XsResultValue m_lastResult;
//! The opened COM port nr
uint16_t m_port;
//! The name of the open serial port
char m_portname[32];
/*! The default timeout value to use during blocking operations.
A value of 0 means that all operations become non-blocking.
*/
uint32_t m_timeout;
#ifdef _WIN32
XsIoHandle m_handle; //!< The serial port handle, also indicates if the port is open or not.
#else
termios m_commState; //!< Stored settings about the serial port
int32_t m_handle; //!< The serial port handle, also indicates if the port is open or not.
#endif
public:
SerialInterface();
virtual ~SerialInterface();
// Function overrides
XsResultValue close (void);
XsResultValue closeLive(void);
XsResultValue flushData (void);
bool isOpen (void) const;
XsResultValue getLastResult(void) const;
XsResultValue writeData (const XsByteArray& data, XsSize* written = 0);
XsResultValue readData(XsSize maxLength, XsByteArray& data);
void cancelIo(void) const;
// Other functions
XsResultValue escape(XsControlLine mask, XsControlLine state);
XsBaudRate getBaudrate(void) const;
XsIoHandle getHandle(void) const;
uint16_t getPortNumber (void) const;
void getPortName(XsString& portname) const;
uint32_t getTimeout (void) const;
XsResultValue open ( const XsPortInfo& portInfo, uint32_t readBufSize = XS_DEFAULT_READ_BUFFER_SIZE, uint32_t writeBufSize = XS_DEFAULT_WRITE_BUFFER_SIZE);
XsResultValue setTimeout (uint32_t ms);
XsResultValue waitForData (XsSize maxLength, XsByteArray& data);
};
#endif // file guard
| true |
301998ee75f1b29d451632eefe018c3317a1490e | C++ | Inx3x/Bomberman | /Bomberman/Item.cpp | BIG5 | 1,309 | 2.671875 | 3 | [] | no_license | #include "Item.h"
#include "DoubleBuffer.h"
Item::Item()
{
}
Item::~Item()
{
}
void Item::Initialize()
{
switch (rand()%4)
{
case BOMBPOWERUP:
Texture[0] = (char*)"";
Texture[1] = (char*)"++BP++";
Texture[2] = (char*)"";
ItemList = BOMBPOWERUP;
break;
case BOMBPOWERDOWN:
Texture[0] = (char*)"";
Texture[1] = (char*)"--BP--";
Texture[2] = (char*)"";
ItemList = BOMBPOWERDOWN;
break;
case BOMBCAPACITYUP:
Texture[0] = (char*)"";
Texture[1] = (char*)"++BC++";
Texture[2] = (char*)"";
ItemList = BOMBCAPACITYUP;
break;
case BOMBCAPACITYDOWN:
Texture[0] = (char*)"";
Texture[1] = (char*)"--BC--";
Texture[2] = (char*)"";
ItemList = BOMBCAPACITYDOWN;
break;
}
Color = WHITE;
TransInfo.Position = Vector3(0, 0);
TransInfo.Scale = Vector3((float)strlen(Texture[0]), 3.0f);
Active = false;
Key = ITEM;
}
void Item::Update()
{
if (Time + 1000 < GetTickCount64()) {
if (Color == WHITE) Color = LIGHTWHITE;
else Color = WHITE;
Time = GetTickCount64();
}
}
void Item::Render()
{
for (int i = 0; i < 3; i++) {
DoubleBuffer::GetInstance()->WriteBuffer(
int(TransInfo.Position.x),
int(TransInfo.Position.y + i),
Texture[i],
Color
);
}
}
void Item::Release()
{
} | true |
638d5c1a5fb5e3d4d1fe887ecf7fdc2e292bbde5 | C++ | liqiang1304/leetcode | /median_of_two_sorted_arrays.cpp | UTF-8 | 957 | 3.25 | 3 | [] | no_license | #include <iostream>
using namespace std;
class Solution{
public:
double method(int A[], int m, int B[], int n){
int total = m + n;
if(total&1){
return find_kth(A,m,B,n,total/2+1);
}else{
return (find_kth(A, m, B, n, total/2) + find_kth(A, m, B, n, total/2+1))/2.0;
}
}
int find_kth(int A[], int m, int B[], int n, int k){
if(m == 0) return B[k-1];
if(m > n) return find_kth(B, n, A, m, k);
if(k==1) return (A[0]>B[0])?B[0]:A[0];
int ia = (k/2>m)?m:k/2, ib = k - ia;
if(A[ia-1]<B[ib-1]){
return find_kth(A+ia, m-ia, B, n, k-ia);
}else if(A[ia-1]>B[ib-1]){
return find_kth(A, m, B+ib, n-ib, k-ib);
}else{
return A[ia-1];
}
}
};
int main(){
int m;
cin >> m;
int A[100],B[100];
for(int i=0; i<m; ++i){
cin >> A[i];
}
int n;
cin >> n;
for(int i=0; i<n; ++i){
cin >> B[i];
}
Solution *so = new Solution();
cout << so->method(A, m, B, n) << endl;
}
| true |
29b955041bb74734e2b43047515fa6df31b6fdaf | C++ | ghostincircuit/leetcode | /n_queens.cpp | UTF-8 | 1,746 | 2.921875 | 3 | [
"BSD-2-Clause"
] | permissive | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
vector<int> pos;
int lim;
vector<vector<string> > ret;
void helper(int level) {
if (level == lim) {
vector<string> vs(lim, string(lim, '.'));
for (auto i = 0; i < lim; i++) {
vs[i][pos[i]] = 'Q';
}
ret.push_back(vs);
return;
}
vector<int> possible(lim, 0);
for (auto i = 0; i < level; i++) {
int p = pos[i];
possible[p] = 1;
int left = p - (level - i);
int right = p + (level - i);
if (left >= 0)
possible[left] = 1;
if (right < lim)
possible[right] = 1;
}
for (auto i = 0; i < lim; i++) {
if (possible[i] == 0) {
pos.push_back(i);
helper(level+1);
pos.pop_back();
}
}
}
vector<vector<string> > solveNQueens(int n) {
lim = n;
helper(0);
return ret;
}
};
int main()
{
Solution s;
auto ret = s.solveNQueens(8);
for (auto& i: ret) {
for (auto& j: i)
cout << j << endl;
cout << "------------------------" << endl;
}
return 0;
}
| true |
5dafbe3ab1710c700c0858495ffa471dff8050ad | C++ | Jereq/PongOut | /PongOut_Server/ComLib/Chat.cpp | UTF-8 | 1,135 | 2.796875 | 3 | [] | no_license | #include "stdafx.h"
#include "Chat.h"
Chat::Chat(void) : msgBase(msgBase::MsgType::CHAT)
{
}
Chat::~Chat(void)
{
}
void Chat::setMsg( std::string _msg, unsigned int _id, std::string _userName)
{
id = _id;
msg = _msg;
user = _userName;
msgHeader.length = msg.length() + user.length() + (sizeof(std::uint16_t) * 2) + sizeof(unsigned int);
}
std::vector<char> Chat::getData()
{
std::vector<char> res;
std::back_insert_iterator<std::vector<char>> iter(res);
pack(msgHeader, iter);
pack(user, iter);
pack(id, iter);
pack(msg, iter);
return res;
}
msgBase::ptr Chat::interpretPacket( const std::deque<char>& _buffer )
{
Chat::ptr cp = Chat::ptr(new Chat());
std::deque<char>::const_iterator it = _buffer.cbegin();
it = unpack(cp->msgHeader, it);
it = unpack(cp->user, it);
it = unpack(cp->id, it);
it = unpack(cp->msg, it);
return cp;
}
std::string Chat::getMsg()
{
return msg;
}
unsigned int Chat::getUserID()
{
return id;
}
void Chat::setUserID(unsigned int _id )
{
id = _id;
}
void Chat::setUserName( const std::string& _userName )
{
user = _userName;
}
std::string Chat::getUserName()
{
return user;
}
| true |
9ab3126bd5a03f18771fb2b21f3ae2def057b9bd | C++ | piochelepiotr/minecraftClone | /src/toolbox/mousepicker.h | UTF-8 | 1,149 | 2.671875 | 3 | [] | no_license | #ifndef MOUSEPICKER_H
#define MOUSEPICKER_H
#include <glm/glm.hpp>
#include "entities/camera.h"
#include "world/world.h"
#define MAX_DISTANCE_BLOCK 30
class MousePicker
{
public:
MousePicker(Camera *camera, World *world, glm::mat4 const& projectionMatrix, double windowX, double windowY);
glm::vec3 currentRay() const;
void update();
void updateWindowSize(double windowX, double windowY);
bool getAimedBlock(int & x, int & y, int & z);
double placeInFront(double x_s, double y_s, double z_s, glm::vec3 const& dir);
private:
double getNextBlock(double & x_i, double & y_i, double & z_i, glm::vec3 const& dir,
int & x, int & y, int & z);
glm::vec4 toEyeCoord(glm::vec4 const& clipCoord);
void createViewMatrix();
void computeMouseRay();
glm::vec2 getNormalizedCoord(double x, double y);
glm::vec3 toWorldCoord(glm::vec4 const& eyeCoord);
glm::vec3 m_currentRay;
glm::mat4 m_invertProjectionMatrix;
glm::mat4 m_viewMatrix;
Camera *m_camera;
World *m_world;
glm::mat4 m_projectionMatrix;
double m_windowX;
double m_windowY;
};
#endif // MOUSEPICKER_H
| true |
d1a1e3e2548c4bb6e69f0a2a5746a322aecb63f9 | C++ | Bo-Xinmin/Computational-Grid | /Curvebase.h | UTF-8 | 750 | 2.734375 | 3 | [] | no_license | // SF2565; Program Construction in C++ for Scientific Computing
// Jonathan Ridenour & Martin Björnmalm
// Project 3
#ifndef CURVEBASE
#define CURVEBASE
class Curvebase{
friend int main();
protected:
//starting point
double a;
//ending point
double b;
//displacement from origo
double m;
//arc length
double length;
virtual double xp(double p)=0;
virtual double yp(double p)=0;
virtual double dxp(double p)=0;
virtual double dyp(double p)=0;
virtual double func(double)=0;
public:
Curvebase();
Curvebase(const Curvebase& C);
~Curvebase();
double x(double s);
double y(double s);
double integrate(double a, double b);
double I(double, double);
double II(double, double);
};
#endif | true |
ebf343207728ac537e0757efc992510b915f6648 | C++ | jpike/GalacticEggSnatchers | /GalacticEggSnatchers/src/Objects/EasterEgg.h | UTF-8 | 3,321 | 3.109375 | 3 | [
"Zlib"
] | permissive | #pragma once
#include <cstdint>
#include <memory>
#include <SFML/Graphics.hpp>
#include "Graphics/IRenderable.h"
#include "Objects/IGameObject.h"
#include "Physics/Collisions/ICollidable.h"
namespace OBJECTS
{
////////////////////////////////////////////////////////
/// @brief An Easter egg. Easter eggs are intended to be stationary objects that
/// are protected by Easter bunnies. Aliens attempt to abduct Easter eggs.
///
/// @todo Remove the copy constructor and assignment operator if they aren't needed.
////////////////////////////////////////////////////////
class EasterEgg : public IGameObject, public GRAPHICS::IRenderable, public PHYSICS::COLLISIONS::ICollidable
{
public:
static const uint8_t DEFAULT_HEALTH; ///< The default amount of health for an egg.
/// @brief Constructor. Resources provided via the constructor
/// may be modified by this object during its lifetime.
/// @param sprite - The graphical sprite for this egg.
explicit EasterEgg(const std::shared_ptr<sf::Sprite>& sprite);
/// @brief Copy constructor.
/// @param[in] eggToCopy - The egg to copy.
EasterEgg(const EasterEgg& eggToCopy);
/// @brief Destructor.
virtual ~EasterEgg();
/// @brief Assignment operator.
/// @param[in] rhsEgg - The egg on the right-hand side of the operator.
/// @return This egg with data copied from the provided egg.
EasterEgg& operator= (const EasterEgg& rhsEgg);
/// @copydoc IGameObject::Update(const sf::Time& elapsedTime)
virtual void Update(const sf::Time& elapsedTime);
/// @copydoc IRenderable::Render(sf::RenderTarget& renderTarget)
virtual void Render(sf::RenderTarget& renderTarget);
/// @copydoc ICollidable::GetBoundingRectangle() const
virtual sf::FloatRect GetBoundingRectangle() const;
/// @copydoc ICollidable::SetTopPosition(const float topPositionInPixels)
virtual void SetTopPosition(const float topPositionInPixels);
/// @copydoc ICollidable::SetBottomPosition(const float bottomPositionInPixels)
virtual void SetBottomPosition(const float bottomPositionInPixels);
/// @copydoc ICollidable::SetLeftPosition(const float leftPositionInPixels)
virtual void SetLeftPosition(const float leftPositionInPixels);
/// @copydoc ICollidable::SetRightPosition(const float rightPositionInPixels)
virtual void SetRightPosition(float rightPositionInPixels);
/// @copydoc ICollidable::OnWorldBoundaryCollide()
/// @brief Does nothing for the egg.
virtual void OnWorldBoundaryCollide();
/// @brief Gets the egg's current health.
/// @return The egg's health.
uint8_t GetHealth() const;
/// @brief Causes the egg to lose a unit of health.
void LoseHealth();
private:
/// @brief Helper method for copying.
/// @param[in] eggToCopy - The egg to copy.
void Copy(const EasterEgg& eggToCopy);
uint8_t m_health; ///< The current health of the egg.
std::shared_ptr<sf::Sprite> m_sprite; ///< The egg's graphical sprite.
};
} | true |
7a80180f3e6750fc90cea95a8447d6752c2cfbde | C++ | wojtekblack/KrakJamCandy | /KrakJam2013/main.cpp | UTF-8 | 1,617 | 2.703125 | 3 | [] | no_license | #include "pch.hpp"
#include "SampleScreen.hpp"
#include "MenuScreen.hpp"
#include "GameScreen.hpp"
sf::RenderWindow window;
ScreenManager screenManager;
MenuScreen menuScreen;
GameScreen gameScreen;
const float ONE_SIXTIETH = 1.0f / 60.0f;
int main(void)
{
screenManager.AddScreen(menuScreen);
screenManager.AddScreen(gameScreen);
screenManager.SetCurrentScreen(gameScreen);
screenManager.Load();
screenManager.Init();
window.create(sf::VideoMode(800, 600, 32), "SFML Framework", sf::Style::Titlebar | sf::Style::Close);
window.setVerticalSyncEnabled(true);
sf::Clock clock;
float dt = 0.0f;
float lastUpdateTime = clock.getElapsedTime().asSeconds();
float accumulator = 0.0f;
const float MAX_ACCUMULATED_TIME = 1.0f;
while (window.isOpen())
{
dt = clock.getElapsedTime().asSeconds() - lastUpdateTime;
lastUpdateTime += dt;
dt = std::max(0.0f, dt);
accumulator += dt;
accumulator = Clamp(accumulator, 0.0f, MAX_ACCUMULATED_TIME);
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
window.close();
}
else
{
screenManager.HandleEvent(event);
}
}
while (accumulator > ONE_SIXTIETH)
{
screenManager.Update();
accumulator -= ONE_SIXTIETH;
}
window.clear(sf::Color(0, 0, 0));
screenManager.Render();
window.display();
}
screenManager.Unload();
return EXIT_SUCCESS;
} | true |
170c9239d2b57ad1e8f546d7652ed1ff970f2db5 | C++ | alemontejolp/shipgame | /Cabeceras/Nave_Enemiga.hpp | UTF-8 | 1,715 | 2.6875 | 3 | [] | no_license | #ifndef NAVE_ENEMIGA_HPP
#define NAVE_ENEMIGA_HPP
#include "../Cabeceras/Naves.hpp"
class Nave_Enemiga : public Naves{
public:
Nave_Enemiga(void){}
Nave_Enemiga(int _vidas, int _x, int _y);
~Nave_Enemiga(void){}
//Métodos.
void inicializar(int, int, int);
/*
*Hace la funcion del constructor.
*/
void mover(int, int);
/*
*Sobreescribe el método mover de la clase base.
*/
void re_posicionar(void);
/*
*Cambia de pos a la nave.
*/
int eleccion_aleatoria(void);
/*
*Genera una número entero al azar
*para distintos propósitos. Del 1 al 10.
*/
void disparar(void);
/*
*Decide si se dispara o no.
*/
void disparando(void);
/*
*Ejecutará una animación en la que disára
*asteriscos. xD
*/
void pintar_nave(void)const;
/*
*Dibujará la nave en el lugar que indican
*las coordenadas del objeto.
*/
void borrar_nave(void)const;
/*
*Pintará espacios en lugar de astericos
*para desaparecer la nave en las coordenadas
*del objeto.
*/
void destruir_nave(void);
/*
*Inicia la animación de destruccion de la
*nave en cuestión.
*/
void revisar_estado_nave(Naves*); ///Nuevo.
/*
*Hace algo si la nave sufre cambios.
*-Reduce vida si es golpeada.
*/
void andando(void);
/*
*Junta varios metodos para que la nave
*interactue.
*/
void movimiento(void);
/*
*Decide a que velocidad se mueve la nave.
*/
private:
bool destruyendose;
bool _disparando;
int num_aleatorio;
int fase_explosion;
};
#include "../Codigo_Fuente/Nave_Enemiga.cpp"
#endif // NAVE_ENEMIGA_HPP
| true |
f048dd6ba435853237a1b55102d2d4838ae67ffb | C++ | sanuguladurgaprasad/Codes | /templates/deque front.cpp | UTF-8 | 375 | 3.03125 | 3 | [] | no_license | // deque::front
#include <iostream>
#include <deque>
using namespace std;
int main ()
{char t;
deque<int> mydeque;
mydeque.push_front(77);
mydeque.push_front(17);
mydeque.push_back(16);
mydeque.push_back(43);
mydeque.front() -= mydeque.back();
cout<<"mydeque is now \n" ;
for(int i=0;i<mydeque.size();i++)
cout << mydeque.at(i) << endl;
cin>>t;
return 0;
}
| true |
4bae7e23f9b795af9905c63caf0cea8b5a103458 | C++ | zhsrl/PP1 | /week10/G2/4.cpp | UTF-8 | 248 | 2.796875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> v;
v.push_back(5);
v.push_back(7);
v.push_back(2);
v.push_back(10);
v.empty() <=> v.size() == 0
cout << v.empty() << " " << v.size();
return 0;
} | true |
f0ad243693aa1bdea615b20c77e7a9da15ff0cf1 | C++ | lovenery/Algorithmics | /UVa/11039-Building-designing.cpp | UTF-8 | 2,922 | 3.53125 | 4 | [] | no_license | // UVa 11039 - Building designing
// 更聰明的方法 : http://blog.csdn.net/yucan1219/article/details/23655173
#include <iostream>
#include <algorithm>
using namespace std;
void building(int *b, int length) {
// splice to two array
int *blue = new int[length];
int *red = new int[length];
int num_blue = 0, num_red = 0;
for (int i = 0; i < length; i++)
{
if (b[i] > 0)
{
blue[num_blue++] = b[i];
}
else if (b[i] < 0)
{
red[num_red++] = b[i];
}
}
// sort
sort(blue, blue + num_blue);
reverse(blue, blue + num_blue); // 8,7,6,5...
sort(red, red + num_red); // -8,-7,-6...
// result of the building
int *result = new int[length + 1];
result[0] = 1000000;
int ans1, ans2;
// ans1, blue first
int index_blue = 0, index_red = 0;
int i = 0;
while (1)
{
// blue[index_blue] < result[i]
while (blue[index_blue] >= abs(result[i]) && index_blue < num_blue)
{
index_blue++;
}
if (blue[index_blue] < abs(result[i]) && index_blue < num_blue)
{
result[++i] = blue[index_blue++];
}
else
{
break;
}
// abs(red[index_red]) < result[i]
while (abs(red[index_red]) >= result[i] && index_red < num_red)
{
index_red++;
}
if (abs(red[index_red]) < result[i] && index_red < num_red)
{
result[++i] = red[index_red++];
}
else
{
break;
}
}
ans1 = i;
// ans2, red first
index_blue = 0, index_red = 0;
i = 0;
while (1)
{
// abs(red[index_red]) < result[i]
while (abs(red[index_red]) >= result[i] && index_red < num_red)
{
index_red++;
}
if (abs(red[index_red]) < result[i] && index_red < num_red)
{
result[++i] = red[index_red++];
}
else
{
break;
}
// blue[index_blue] < result[i]
while (blue[index_blue] >= abs(result[i]) && index_blue < num_blue)
{
index_blue++;
}
if (blue[index_blue] < abs(result[i]) && index_blue < num_blue)
{
result[++i] = blue[index_blue++];
}
else
{
break;
}
}
ans2 = i;
// output real ans
if (ans1 > ans2)
{
cout << ans1 << endl;
}
else
{
cout << ans2 << endl;
}
}
int main()
{
int times;
cin >> times;
for (int i = 0; i < times; i++)
{
int num_build;
cin >> num_build;
int *build = new int[num_build];
for (int i = 0; i < num_build; i++)
{
cin >> build[i];
}
building(build, num_build);
}
system("pause");
return 0;
}
| true |
978516ad957f7e791b1be923b0c9aeffc42a87fc | C++ | keserasera77/Bonberman | /Bomberman/Bomberman/State.h | SHIFT_JIS | 1,099 | 2.71875 | 3 | [] | no_license | #pragma once
namespace Sequence {
namespace Game {
class Parent;
}
}
class Player;
class Image;
class Object;
class Bomb;
template<class T> class Array2D {
public:
Array2D() : mArray(0),mWidth(0),mHeight(0){}
~Array2D() {
delete[] mArray;
mArray = 0;
}
void setSize(int width, int height) {
mWidth = width;
mHeight = height;
mArray = new T[width * height];
}
T& operator()(int x, int y) {
return mArray[y * mWidth + x];
}
const T& operator()(int x, int y) const {
return mArray[y * mWidth + x];
}
private:
T* mArray;
int mWidth;
int mHeight;
};
class State {
public:
State(Sequence::Game::Parent* parent);
~State();
void update(Sequence::Game::Parent* parent);
void drawStage() const;
void drawPlayers() const;
void moveEnemys();
//1P̂
bool failureCheck();
bool clearCheck();
void fireEnemys();
//2P̂
int resultCheck();
private:
void setSize(int width, int height);
int mStageWidth;
int mStageHeight;
Image* mImage; //摜f[^
Array2D<Object> mObjects;
Player* mPlayer1;
Player* mPlayer2;
Player** mEnemys;
int mNumOfEnemy;
};
| true |
71d4d96374b6435de4e0a10ad5fec89a9695ff5e | C++ | spencerwooo/exp2-process-control | /Linux/ChildProcess.cpp | UTF-8 | 225 | 2.9375 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <unistd.h>
using namespace std;
int main(int argc, char const *argv[])
{
char name[10] = "武上博";
cout << "Hi, my name is " << name << endl;
// 延时三秒
sleep(3);
return 0;
}
| true |
485197b930825842287cae0b2529a719ecc0a84f | C++ | dwmize98/Public_Work | /Artificial_Intelligence/Resolution_Refutation/resolution.cpp | UTF-8 | 3,297 | 2.984375 | 3 | [] | no_license | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <queue>
#include "parser.hpp"
#include "helpers.cpp"
using namespace std;
//overload operator for priority queue
bool operator<(const ResPair& a, const ResPair& b) {
return a.score > b.score;
}
bool resolution(vector<Expr*> kb, Expr* q) {
Expr * negated_q = negate_expr(q);
kb.push_back(negated_q);
for (int i = 0; i < kb.size(); i++) {
if (validateClause(kb.at(i)) == false) {
return false;
}
}
priority_queue<ResPair> clauses;
for (int i = 0; i < kb.size(); i++) {
for (int j = i + 1; j < kb.size(); j++) {
if (resolvable(kb.at(i), kb.at(j))) {
//unit-clause heuristic
int score = kb.at(i)->sub.size() == 2 || kb.at(j)->sub.size() == 2 ? 1 : kb.at(i)->sub.size() + kb.at(j)->sub.size();
ResPair pair(i, j, score);
clauses.push(pair);
}
}
}
int iter = -1;
while (!clauses.empty() && iter < 10000) {
iter++;
cout << "iteration=" << iter << ", " << "clauses=" << clauses.size() << endl;
ResPair curr = clauses.top();
clauses.pop();
vector<string> props = matching_propositions(kb.at(curr.i), kb.at(curr.j));
cout << "resolving clauses " << curr.i << " and " << curr.j << ": " << kb.at(curr.i)->toString() << ", " << kb.at(curr.j)->toString() << endl;
for (int i = 0; i < props.size(); i++) {
Expr * resolvent = resolve(kb.at(curr.i), kb.at(curr.j), props.at(i));
cout << "resolvent = " << resolvent->toString() << endl;
if (resolvent->sub.size() == 1) {
return true;
}
if (!validateClause(resolvent)) {
cout << endl << endl;
continue;
}
bool keep_going = true;
for (int j = 0; j < kb.size(); j++) {
if (Eq(resolvent, kb.at(j))) {
keep_going = false;
}
}
if (!keep_going) {
cout << endl << endl;
continue;
}
for (int j = 0; j < kb.size(); j++) {
if (resolvable(resolvent, kb.at(j))) {
int updated_score = resolvent->sub.size() == 2 or kb.at(j)->sub.size() == 2 ? 1 : resolvent->sub.size() + kb.at(j)->sub.size();
ResPair pair(kb.size(), j, updated_score);
clauses.push(pair);
}
}
kb.push_back(resolvent);
cout << kb.size() - 1 << ". " << kb.back()->toString() << endl << endl;
}
}
return false;
}
int main(int argc, char **argv) {
try {
Expr* q = parse((string)(argv[argc - 1]));
string filename = (string)(argv[argc - 2]);
vector<Expr *> KB = load_kb(filename);
if (resolution(KB, q)) {
cout << "Success! Derived empty clause, so " << q->toString() << " is entailed" << endl;
}
else {
cout << "Sorry, no solution could be found" << endl;
}
} catch (runtime_error& e) {
cout << e.what() << endl;
}
return 0;
}
| true |
56c1e37299c61262fbc68256b4a351f55b74df07 | C++ | link852258/INF3105TP2 | /tableau.h | UTF-8 | 5,854 | 3.703125 | 4 | [] | no_license | /* Squelette pour classe générique Tableau<T>.
* Lab3 -- Tableau dynamique générique
* UQAM / Département d'informatique
* INF3105 - Structures de données et algorithmes
* http://ericbeaudry.uqam.ca/INF3105/lab3/
*/
#if !defined(_TABLEAU___H_)
#define _TABLEAU___H_
#include <assert.h>
template <class T>
class Tableau{
public:
Tableau(int capacite_initiale=4);
Tableau(const Tableau<T>&);
~Tableau();
// Ajouter un element à la fin
void ajouter(const T& element);
// Vider le tableau
void vider();
// Retourne le nombre d'éléments dans le tableau
int taille() const;
// Insère element à position index. Les éléments à partir de index sont décalés d'une position.
void inserer(const T& element, int index=0);
// Enlève l'element à position index. Les éléments après index sont décalés d'une position.
void enlever(int index=0);
// Enlève le dernier éléments.
void enlever_dernier();
// Cherche et retourne la position de l'élément. Si non trouvé, retourne -1.
int chercher(const T& element);
const T& operator[] (int index) const;
T& operator[] (int index);
bool operator == (const Tableau<T>& autre) const;
Tableau<T>& operator = (const Tableau<T>& autre);
Tableau<T>& operator += (const Tableau<T>& autre);
Tableau<T> operator + (const Tableau<T>& autre) const;
void trier();
private:
T* elements;
int nbElements;
int capacite;
};
// ---------- Définitions -------------
template <class T>
Tableau<T>::Tableau(int capacite_)
{
capacite = capacite_;
nbElements = 0;
elements = new T[capacite];
}
template <class T>
Tableau<T>::Tableau(const Tableau& autre)
{
nbElements = autre.nbElements;
capacite = autre.capacite;
elements = new T[capacite];
for(int i = 0; i < nbElements; i++){
elements[i] = autre.elements[i];
}
}
template <class T>
Tableau<T>::~Tableau()
{
delete[] elements;
elements = nullptr;
}
template <class T>
int Tableau<T>::taille() const
{
return nbElements;
}
template <class T>
void Tableau<T>::ajouter(const T& item)
{
if(nbElements >= capacite){
capacite *= 2;
T* temp = new T[capacite];
for(int i = 0; i < nbElements; i++){
temp[i] = elements[i];
}
delete[] elements;
elements = temp;
}
elements[nbElements++] = item;
}
template <class T>
void Tableau<T>::inserer(const T& element, int index)
{
if(nbElements >= capacite){
capacite *= 2;
T* temp = new T[capacite];
for(int i = 0; i < nbElements; i++){
temp[i] = elements[i];
}
delete[] elements;
elements = temp;
}
nbElements++;
for(int i = nbElements; i > index; i--){
elements[i] = elements[i-1];
}
elements[index] = element;
}
template <class T>
void Tableau<T>::enlever(int index)
{
nbElements--;
for(int i = 0; i < nbElements; i++){
if(i >= index){
elements[i] = elements[i+1];
}
}
}
template <class T>
void Tableau<T>::enlever_dernier()
{
nbElements--;
}
template <class T>
int Tableau<T>::chercher(const T& element)
{
for(int i = 0; i < nbElements; i++){
if(elements[i] == element)
return i;
}
return -1;
}
template <class T>
void Tableau<T>::vider()
{
nbElements = 0;
}
template <class T>
const T& Tableau<T>::operator[] (int index) const
{
assert(index < nbElements);
return elements[index];
}
template <class T>
T& Tableau<T>::operator[] (int index)
{
assert(index < nbElements);
return elements[index];
}
template <class T>
Tableau<T>& Tableau<T>::operator = (const Tableau<T>& autre)
{
if(elements != autre.elements){
nbElements = autre.nbElements;
capacite = autre.capacite;
delete[] elements;
elements = new T[capacite];
for(int i = 0; i < nbElements; i++){
elements[i] = autre.elements[i];
}
}
return *this;
}
template <class T>
bool Tableau<T>::operator == (const Tableau<T>& autre) const
{
if(nbElements != autre.nbElements) return false;
if(elements == autre.elements) return true;
for(int i = 0; i < nbElements; i++){
if(elements[i] != autre.elements[i]) return false;
}
return true;
}
template <class T>
Tableau<T>& Tableau<T>::operator += (const Tableau<T>& autre)
{
int tempNbElements = nbElements + autre.nbElements;
while(capacite < tempNbElements){
capacite *= 2;
}
T* temp = new T[capacite];
for(int i = 0; i < nbElements; i++){
temp[i] = elements[i];
}
for(int i = nbElements; i < autre.nbElements + nbElements; i++){
temp[i] = autre.elements[i - nbElements];
}
delete[] elements;
elements = temp;
nbElements += autre.nbElements;
return *this;
}
template <class T>
Tableau<T> Tableau<T>::operator + (const Tableau<T>& autre) const
{
Tableau temp;
for(int i = 0; i < nbElements; i++){
temp.ajouter(elements[i]);
}
for(int i = 0; i < autre.nbElements; i++){
temp.ajouter(autre.elements[i]);
}
return temp;
}
template <class T>
void Tableau<T>::trier ()
{
T temp;
int i = 0;
int j = 0;
int nbPlusPetit = 0;
for(i = 0; i < nbElements; i++){
temp = elements[i];
nbPlusPetit = i;
for(j = i; j < nbElements; j++){
if(temp >= elements[j]){
temp = elements[j];
nbPlusPetit = j;
}
}
elements[nbPlusPetit] = elements[i];
elements[i] = temp;
}
}
#endif //define _TABLEAU___H_
| true |
f2a5a0e30c87ed0b0a8aaa899b20df6cacdcbcaa | C++ | gzachv/IntroToC | /p2/SortedList.cpp | UTF-8 | 4,257 | 3.59375 | 4 | [] | no_license | /*******************************************************************************
Author: Gustavo Zach Vargas
CS Login: gustavo
Pair Partner: <name of your pair programming partner (if applicable)>
CS Login: <your partner's login name>
Credits: <name of anyone (other than your pair programming partner) who
helped you write your program>
Course: CS 368, Fall 2013
Assignment: Programming Assignment 2
*******************************************************************************/
#include <iostream>
#include "Student.h"
#include "SortedList.h"
using namespace std;
/*
* SortedList implemented class
*
* A SortedList is an ordered collection of Students. The Students are ordered
* from lowest numbered student ID to highest numbered student ID.
*/
// Constructs an empty list.
SortedList::SortedList(){
head = NULL;
}
// If a student with the same ID is not already in the list, inserts
// the given student into the list in the appropriate place and returns
// true. If there is already a student in the list with the same ID
// then the list is not changed and false is returned.
bool SortedList::insert(Student *s){
//if the list is empty, place the student at the top of the list
if(head == NULL){
head = new Listnode();
head->student = s;
head->next = NULL;
return true;
}
Listnode* curr = head; //current node in execution
Listnode* prev = NULL; //node previous to curr in iteration through list
//if the student is smaller than the head
if(s->getID() < curr->student->getID()){
head = new Listnode();
head->student = s;
head->next = curr;
return true;
}
else{
while(curr != NULL){
//if a student with the same id is already in the list, do not add
if(s->getID() == curr->student->getID()){
cout << "The student entered is already in the list. "
"NO INSERT OCCURED";
return false;
}
//if the student to be added is in middle of list
else if(s->getID() < curr->student->getID()){
prev->next = new Listnode();
prev = prev->next;
prev->student = s;
prev->next = curr;
return true;
}
//check if end of list has been reached
else if(curr->next == NULL){
curr->next = new Listnode();
curr = curr->next;
curr->student = s;
curr->next = NULL;
return true;
}
//increment iterating pointers
prev = curr;
curr = curr->next;
}
}
return false;
}
// Searches the list for a student with the given student ID. If the
// student is found, it is returned; if it is not found, NULL is returned.
Student* SortedList::find(int studentID){
Listnode* curr = head;
if(curr == NULL){
return NULL;
}
while(curr != NULL){
if(curr->student->getID() == studentID){
return curr->student;
}
curr = curr->next;
}
return NULL;
}
// Searches the list for a student with the given student ID. If the
// student is found, the student is removed from the list and returned;
// if no student is found with the given ID, NULL is returned.
// Note that the Student is NOT deleted - it is returned - however,
// the removed list node should be deleted.
Student* SortedList::remove(int studentID){
Listnode* curr = head;
Listnode* prev = head;
Listnode* temp = NULL;
Student* ret;
//if the node to be removed is at the top of the list
if(head->student->getID() == studentID){
head = curr->next;
ret = curr->student;
delete curr;
curr = NULL;
return ret;
}
while(curr != NULL){
if(curr->student->getID() == studentID){
//if list node to be removed is at the end of the list
if(curr->next == NULL){
ret = curr->student;
prev->next = NULL;
delete curr;
curr = NULL;
return ret;
}
//list node to be removed is in the middle of list
else{
temp = prev->next;
prev->next = curr->next;
delete temp;
temp = NULL;
return curr->student;
}
}
//increment pointers
prev = curr;
curr = curr->next;
}
return NULL;
}
// Prints out the list of students to standard output. The students are
// printed in order of student ID (from smallest to largest), one per line
void SortedList::print() const{
Listnode* tmp = head;
while(tmp != NULL){
tmp->student->print();
tmp = tmp->next;
}
}
| true |
dfaa601077c47cfbc4adc81b2af9d30525bd9e81 | C++ | cuiy0006/THE-C-PROGRAMMING-LANGUAGE | /C5/5-5/str_op.cc | UTF-8 | 701 | 3 | 3 | [] | no_license | #include "str_op.h"
#include "stdio.h"
char *strncpy_p(char *dest, const char *src, size_t n){
for(size_t i = 0; i < n && *src; ++i){
*dest++ = *src++;
}
*dest = '\0';
return dest;
}
char *strncat_p(char *dest, const char *src, size_t n){
while (*dest){
++dest;
}
for(size_t i = 0; i < n && *src; ++i){
*dest++ = *src++;
}
*dest = '\0';
return dest;
}
int strncmp_p(const char *str1, const char *str2, size_t n){
size_t i = 0;
while(true){
if(*str1 != *str2)
break;
if(i == n - 1 || *str1 == '\0')
return 0;
++i;
++str1;
++str2;
}
return *str1 - *str2;
} | true |
054832853e2c6d506da78c2fc97d287ea1d64fd9 | C++ | MartiHui/GSDAM_Fichaje_Plantilla | /Admin_Fichaje_Plantilla/source/actionjson.cpp | UTF-8 | 5,173 | 2.625 | 3 | [] | no_license | #include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QDebug>
#include "actionjson.h"
ActionJson::ActionJson(QString json) {
m_json = QJsonDocument::fromJson(json.toUtf8());
setActionType();
}
void ActionJson::setActionType() {
QJsonValue action = m_json.object()["action"];
if (action != QJsonValue::Undefined) {
QString actionStr = action.toString();
if (actionStr == "CONNECTION") {
m_actionType = ActionType::CONNECTION;
} else if (actionStr == "REGISTROS_INFO") {
m_actionType = ActionType::REGISTROS_INFO;
} else if (actionStr == "UPDATE") {
m_actionType = ActionType::UPDATE;
} else if (actionStr == "EMPLEADOS_INFO") {
m_actionType = ActionType::EMPLEADOS_INFO;
} else if (actionStr == "NEW_EMPLEADO") {
m_actionType = ActionType::NEW_EMPLEADO;
}
} else {
m_actionType = ActionType::INVALID;
}
}
ActionType ActionJson::getActionType() {
return m_actionType;
}
bool ActionJson::getRegistrosInfo(QVector<Registro> *registros) {
bool validJson{true};
if (m_json.object()["registros"].isArray()) {
QJsonArray registrosArray = m_json.object()["registros"].toArray();
for (int i = 0; i < registrosArray.count(); i++) {
// Si esta posicion tiene un Objeto
if (registrosArray.at(i).type() == QJsonValue::Object) {
QJsonObject registro = registrosArray.at(i).toObject();
// Si tiene todos los campos que esperamos
if (registro["empleado_id"] != QJsonValue::Undefined &&
registro["empleado_nombre"] != QJsonValue::Undefined &&
registro["empleado_apellido"] != QJsonValue::Undefined &&
registro["es_entrada"] != QJsonValue::Undefined &&
registro["fecha"] != QJsonValue::Undefined) {
registros->push_back(Registro{registro["empleado_id"].toInt(),
registro["empleado_nombre"].toString(),
registro["empleado_apellido"].toString(),
registro["es_entrada"].toBool(),
registro["fecha"].toString()});
} else {
validJson = false;
break;
}
} else {
validJson = false;
break;
}
}
} else {
validJson = false;
}
return validJson;
}
bool ActionJson::getEmpleadosInfo(QVector<QMap<QString, QString> > *empleados) {
bool validJson{true};
if (m_json.object()["empleados"].isArray()) {
QJsonArray empleadosArray = m_json.object()["empleados"].toArray();
for (int i = 0; i < empleadosArray.count(); i++) {
if (empleadosArray.at(i).type() == QJsonValue::Object) {
QJsonObject empleadoObject = empleadosArray.at(i).toObject();
QMap<QString, QString> empleado;
empleado["id"] = empleadoObject["id"].toString();
empleado["nombre"] = empleadoObject["nombre"].toString();
empleado["apellido"] = empleadoObject["apellido"].toString();
empleados->append(empleado);
} else {
validJson = false;
break;
}
}
} else {
validJson = false;
}
return validJson;
}
bool ActionJson::connectAdminSuccessful() {
QJsonValue value = m_json.object()["result"];
bool result{false};
if (value.type() == QJsonValue::Bool) {
result = value.toBool();
}
return result;
}
QString ActionJson::askRegistrosInfo() {
QJsonObject ask;
ask.insert("action", QJsonValue("REGISTROS_INFO"));
return QJsonDocument(ask).toJson();
}
QString ActionJson::connectAdmin(QString name, QString password) {
QJsonObject ask;
ask.insert("action", QJsonValue("ADMIN_CONNECT"));
ask.insert("username", QJsonValue(name));
ask.insert("password", QJsonValue(password));
return QJsonDocument(ask).toJson();
}
QString ActionJson::askEmpleadosInfo() {
QJsonObject ask;
ask.insert("action", QJsonValue("EMPLEADOS_INFO"));
return QJsonDocument(ask).toJson();
}
QString ActionJson::newEmpleado(QString nombre, QString apellido) {
QJsonObject ask;
ask.insert("action", QJsonValue("NEW_EMPLEADO"));
ask.insert("nombre", QJsonValue(nombre));
ask.insert("apellido", QJsonValue(apellido));
return QJsonDocument(ask).toJson();
}
QString ActionJson::deleteEmpleado(QString empleadoId) {
QJsonObject ask;
ask.insert("action", QJsonValue("DELETE_EMPLEADO"));
ask.insert("data", QJsonValue(empleadoId));
return QJsonDocument(ask).toJson();
}
QPair<QString, QString> ActionJson::getNewEmpleadoData() {
QPair<QString, QString> data;
data.first = m_json.object()["eanCode"].toString();
data.second = m_json.object()["password"].toString();
return data;
}
| true |
183d0eafb2994a0bd4ae6cbe16ea621f6a1497ad | C++ | r03er7/algorithms | /[Code] algorytmika praktyczna/Programy_bez_komentarzy/programy_bez_komentarzy/covertree.cpp | UTF-8 | 1,952 | 2.515625 | 3 | [] | no_license | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
typedef vector<int> VI;
typedef long long LL;
#define FOR(x, b, e) for(int x = b; x <= (e); ++x)
#define FORD(x, b, e) for(int x = b; x >= (e); --x)
#define REP(x, n) for(int x = 0; x < (n); ++x)
#define VAR(v, n) __typeof(n) v = (n)
#define ALL(c) (c).begin(), (c).end()
#define SIZE(x) ((int)(x).size())
#define FOREACH(i, c) for(VAR(i, (c).begin()); i != (c).end(); ++i)
#define PB push_back
#define ST first
#define ND second
struct CoverTree {
#define nr (wp + wk + 1) >> 1
int *el, *ma, s, p, k, il;
CoverTree(int size) {
el = new int[s = 1 << (size + 1)];
ma = new int[s];
REP(x, s) el[x] = ma[x] = 0;
}
~CoverTree() {
delete[] el;
delete[] ma;
}
void Mark(int wp, int wk, int g) {
if(k<=wp || p>=wk) return;
if(p<=wp && k>=wk) el[g] += il; else {
Mark(wp, nr, 2 * g);
Mark(nr, wk, 2 * g + 1);
}
ma[g] = el[g] > 0 ? wk - wp :
(wk - 1 == wp ? 0 : ma[2 * g] + ma[2 * g + 1]);
}
void Add(int p1, int k1, int i1) {
p = p1;
k = k1;
il = i1;
Mark(0, s / 2, 1);
}
int F(int wp, int wk, int g) {
if (wp >= k || wk <= p) return 0;
if (el[g] > 0) return min(k, wk) - max(p, wp);
if (p <= wp && wk <= k) return ma[g];
return wp == wk - 1 ? 0 : F(wp, nr, 2 * g) + F(nr, wk, 2 * g + 1);
}
int Find(int p1, int k1) {
p = p1;
k = k1;
return F(0, s / 2, 1);
}
};
int main() {
int w1, w2, w3;
CoverTree tree(4);
while(cin >> w1 >> w2 >> w3) {
if (w1 == 0) {
tree.Add(w2, w3, 1);
cout << "Dodanie odcinka [" << w2 << "," << w3 << "]" << endl;
} else if (w1 == 1) {
tree.Add(w2, w3, -1);
cout << "Usuniecie odcinka [" << w2 << "," << w3 << "]" << endl;
} else
cout << "Pokrycie odcinka [" << w2 << "," << w3 <<
"] = " << tree.Find(w2, w3) << endl;
}
return 0;
}
| true |
d6cd55460aa4d18794bcdac3e4166e7da17ca001 | C++ | ndzik/coinwalletoverview | /src/walletfactory.cpp | UTF-8 | 892 | 2.734375 | 3 | [
"MIT"
] | permissive | #include "walletfactory.hpp"
namespace cwo {
Walletfactory Walletfactory::url(std::string url)
{
_url = url;
return *this;
}
Walletfactory Walletfactory::address(std::string address)
{
_address = address;
return *this;
}
Walletfactory Walletfactory::cryptotype(CRYPTOTYPE t)
{
_cryptotype = t;
return *this;
}
Wallet* Walletfactory::build()
{
switch(_cryptotype) {
case ETH:
return new EtherWallet(_address, _url);
reset();
break;
case VET:
return new VechainWallet(_address, _url);
reset();
break;
case BTC:
return new BitcoinWallet(_address, _url);
reset();
break;
default:
reset();
return NULL;
}
}
void Walletfactory::reset()
{
_url = "127.0.0.1";
_address = "0xdeadbeef";
_cryptotype = BTC;
}
};
| true |
f48f80ae244d6713c4f6973a0f6bfe0ae291d099 | C++ | rahulsharma9898/math-problem-solver | /project1.cpp | UTF-8 | 15,008 | 3.890625 | 4 | [] | no_license | #include <iostream>
#include <cmath>
using namespace std;
int main()
{
double pie = 3.14;
std::cout << "\nEnter 1 if question is related to Circle." << std::endl;
std::cout << "Enter 2 if question is related to Square." << std::endl;
std::cout << "Enter 3 if question is related to Triangle." << std::endl;
std::cout << "Enter 4 if question is related to Rectangle." << std::endl;
int shape;
std::cout << "\nEnter the above value to continue: ";
cin >> shape;
switch (shape)
{
//***************************** CIRCLE *********************************//
case 1:
std::cout << "\n\n******************** CIRCLE *******************\n"
<< std::endl;
std::cout << "\n Enter 1 if question is related to Radius and Diameter." << std::endl;
std::cout << " Enter 2 if question is related to Circumference of the Circle." << std::endl;
std::cout << " Enter 3 if question is related to Area of Circle." << std::endl;
std::cout << " Enter 4 if question is related to Length of Arc." << std::endl;
std::cout << " Enter 5 if question is related to Area of Sector.\n"
<< std::endl;
int circle;
std::cout << "Enter the above value:";
cin >> circle;
//************************** 1 Radius and Diameter *****************************//
if (circle == 1)
{
std::cout << "\nRadius and Diameter:-\n"
<< std::endl;
std::cout << "Enter 1 to find Radius of a Circle." << std::endl;
std::cout << "Enter 2 to find Diameter of a Circle.\n"
<< std::endl;
int rd;
std::cout << "Enter the above value:";
cin >> rd;
if (rd == 1)
{
std::cout << "\n To find: Radius = ?" << std::endl;
double rdd;
std::cout << "Diameter = ";
cin >> rdd;
double rdrsum = rdd / 2;
cout<<"\nSoln:-\n"<<endl;
cout<<"d/2 = r ........(formula)"<<endl;
cout<<rdd<<"/2 = r"<<endl;
cout<<rdrsum<<endl;
std::cout << "\nAns :- Radius of circle is " << rdrsum << std::endl;
std::cout << "\n"
<< std::endl;
}
else if (rd == 2)
{
std::cout << "\n To find: Diameter = ? " << std::endl;
double ddd;
std::cout << "Radius = ";
cin >> ddd;
double rddsum = ddd * 2;
cout<<"\nSoln:-\n"<<endl;
cout<<"r * 2 = d .........(formula)"<<endl;
cout<<ddd<<" * 2 = d"<<endl;
cout<<rddsum<<" = d"<<endl;
std::cout << "\nAns :- Diameter of Circle is " << rddsum << std::endl;
std::cout << "\n"
<< std::endl;
}
else
{
std::cout << "\n******************** EROR! *******************\n"
<< std::endl;
std::cout << "You have entered wrong value." << std::endl;
std::cout << "Please enter above value.\n"
<< std::endl;
}
}
//************************** 2 Circumference of Circle *****************************//
else if (circle == 2)
{
std::cout << "\nCircumference of Circle:-\n"
<< std::endl;
std::cout << "Enter 1 to find Circumference of the Circle." << std::endl;
std::cout << "Enter 2 to find Radius of circle if Circumference is given." << std::endl;
int cc;
std::cout << "\nEnter the above value : ";
cin >> cc;
if (cc == 1)
{
std::cout << "\nTo find: Circumference = ? \n"
<< std::endl;
cout<<"Given:-"<<endl;
double rcc;
std::cout << "Radius = ";
cin >> rcc;
cout<<"Soln:-\n"<<endl;
double rccsum = 2 * pie * rcc;
cout<<"circumfernce of circle = 2 pie r .......(formula)"<<endl;
cout<<"circumfernce = 2 * 3.14 * "<<rcc<<endl;
cout<<"circumference = "<<rccsum<<endl;
std::cout << "\nAns :- Circumference of the Circle is " << rccsum << std::endl;
std::cout << "\n"
<< std::endl;
}
else if (cc == 2)
{
std::cout << "\nTo find: Radius = ? " << std::endl;
double dcc;
std::cout << "\nCircumference = ";
cin >> dcc;
double dccsum = dcc / (2 * pie);
std::cout << "\nAns :- Radius of the circle is " << dccsum << std::endl;
std::cout << "\n"
<< std::endl;
}
else
{
std::cout << "\n******************** EROR! *******************\n"
<< std::endl;
std::cout << "You have entered wrong value." << std::endl;
std::cout << "Please enter above value.\n"
<< std::endl;
}
}
//************************** 3 Area of the Circle *****************************//
else if (circle == 3)
{
std::cout << "\nArea of the Circle:-\n"
<< std::endl;
std::cout << "\nEnter 1 to find Area of Circle." << std::endl;
std::cout << "Enter 2 to find Radius if Area of Circle is given." << std::endl;
int ac;
std::cout << "\nEnter the above value : ";
cin >> ac;
if (ac == 1)
{
std::cout << "\nTo find: Area of circle = ? \n"
<< std::endl;
double rac;
std::cout << "Radius = ";
cin >> rac;
double racsum = pie * (rac * rac);
std::cout << "\nAns :- Area of circle is " << racsum << std::endl;
std::cout << "\n"
<< std::endl;
}
else if (ac == 2)
{
std::cout << "\nTo find: Radius = ? \n"
<< std::endl;
double dac;
std::cout << "Area of circle = ";
cin >> dac;
double dacsum = dac / pie;
double sdac = sqrt(dacsum);
std::cout << "\nAns :- Radius of circle is " << sdac << std::endl;
std::cout << "\n"
<< std::endl;
}
else
{
std::cout << "\n******************** EROR! *******************\n"
<< std::endl;
std::cout << "You have entered wrong value." << std::endl;
std::cout << "Please enter above value.\n"
<< std::endl;
}
}
//************************** 4 Length of an Arc *****************************//
else if (circle == 4)
{
std::cout << "\nLength of an Arc:-\n"
<< std::endl;
std::cout << "Enetr 1 to find Length of Arc." << std::endl;
std::cout << "Enter 2 to find radius if length of arc is given." << std::endl;
std::cout << "Enter 3 to find Theta.\n"
<< std::endl;
int la;
std::cout << "Enter the above value:";
cin >> la;
std::cout << "\n"
<< std::endl;
if (la == 1)
{
std::cout << "To find: Length of Arc = ? \n"
<< std::endl;
double latheta;
std::cout << "Enter the given theta: ";
cin >> latheta;
double laradius;
std::cout << "\nEnter the value of radius:";
cin >> laradius;
std::cout << "\n"
<< std::endl;
double larsum = (latheta / 360) * 2 * pie * laradius;
std::cout << "Ans :- Length of Arc is " << larsum << std::endl;
std::cout << "\n"
<< std::endl;
}
else if (la == 2)
{
std::cout << "\nTo find: Radius = ? \n"
<< std::endl;
double latheta1;
std::cout << "Enter the given 0:";
cin >> latheta1;
double arclength;
std::cout << "\nEnter the length of arc:";
cin >> arclength;
double arcsum = (arclength * 360) / (2 * pie * latheta1);
std::cout << "\n Ans :- Radius of Circle is " << arcsum << std::endl;
std::cout << "\n"
<< std::endl;
}
else if (la == 3)
{
std::cout << "\nTo find: Theta = ?" << std::endl;
std::cout << "\nEnter the value of Radius:";
double laradius2;
cin >> laradius2;
std::cout << "\nEnter the Length of Arc:";
double arclength2;
cin >> arclength2;
double thethasum = (arclength2 * 360) / (2 * pie * laradius2);
std::cout << "\nAns :- Theta is " << thethasum << std::endl;
std::cout << "\n"
<< std::endl;
}
else
{
std::cout << "\n******************** EROR! *******************\n"
<< std::endl;
std::cout << "You have entered wrong value." << std::endl;
std::cout << "Please enter above value.\n"
<< std::endl;
}
}
//************************** 5 Area of Sector *****************************//
else if (circle == 5)
{
std::cout << "\nArea of Sector:-\n"
<< std::endl;
std::cout << "Enter 1 to find Area of Sector." << std::endl;
std::cout << "Enter 2 to find Radius." << std::endl;
std::cout << "Enter 3 to find Theta.\n"
<< std::endl;
int as;
std::cout << "Enter the above value:";
cin >> as;
if (as == 1)
{
std::cout << "\nTo find: Area of sector = ?" << std::endl;
std::cout << "\nEnter the given Theta:";
double asthetha1;
cin >> asthetha1;
std::cout << "\nEnter the given Radius:";
double asradius1;
cin >> asradius1;
double assum1 = (asthetha1 / 360) * pie * (asradius1 * asradius1);
std::cout << "\nAns :- Area of Sector is " << assum1 << std::endl;
std::cout << "\n"
<< std::endl;
}
else if (as == 2)
{
std::cout << "\nTo find: Radius = ?\n"
<< std::endl;
std::cout << "Enter the given Theta:";
double asthetha2;
cin >> asthetha2;
std::cout << "\nEnter the Area of Sector:";
double asas1;
cin >> asas1;
double asrsum = (asas1 * 360) / (asthetha2 * pie);
double asrsum1 = sqrt(asrsum);
std::cout << "\nAns :- Radius is " << asrsum1 << std::endl;
std::cout << "\n"
<< std::endl;
}
else if (as == 3)
{
std::cout << "\nTo find: Theta = ? " << std::endl;
std::cout << "\nEnter the radius = ";
double asradius3;
cin >> asradius3;
std::cout << "\nEnter the Area of Sector = ";
double asarea;
cin >> asarea;
double assum3 = (asarea * 360) / (pie * asradius3 * asradius3);
std::cout << "\nAns :- Theta is " << assum3 << std::endl;
std::cout << "\n"
<< std::endl;
}
else
{
std::cout << "\n******************** EROR! *******************\n"
<< std::endl;
std::cout << "You have entered wrong value." << std::endl;
std::cout << "Please enter above value.\n"
<< std::endl;
}
}
//************************** Eror *****************************//
else
{
std::cout << "\n******************** EROR! *******************\n"
<< std::endl;
std::cout << "You have entered wrong value." << std::endl;
std::cout << "Please enter above value.\n"
<< std::endl;
}
break;
//***************************** SQUARE *********************************//
case 2:
std::cout << "\n******************** SQUARE *******************\n"
<< std::endl;
break;
//***************************** TRIANGLE *********************************//
case 3:
std::cout << "\n******************** TRIANGLE *******************\n"
<< std::endl;
break;
//***************************** RECTANGLE *********************************//
case 4:
std::cout << "\n******************** RECTANGLE *******************\n"
<< std::endl;
break;
//***************************** EROR *********************************//
default:
std::cout << "\n******************** EROR! *******************\n"
<< std::endl;
std::cout << "You have entered wrong value." << std::endl;
std::cout << "Please enter above value.\n"
<< std::endl;
break;
}
return 0;
}
| true |
80d1a461ea68b502fa3d2e4274f30dd6921bdfae | C++ | sarthakm1011/c_plus_plus | /LRU_cache_implementation.cpp | UTF-8 | 1,189 | 3.609375 | 4 | [] | no_license | // STL container is used as double ended queue to store the cache
// keys from descending time of reference from front to back and set
// container to check the presence of the key. But to fetch the address
// of the key using find it takes O(N) time. This can be optimized by storing
// reference to each key in hash map.
#include <iostream>
using namespace std;
class LRUCache
{
// Store keys of cache
list<int> dq;
// stores reference of keys in cache
unordered_map<int, list<int>::iterator> ma;
// maximum capacity of cache
int csize;
public:
LRUCache(int);
void refer(int);
void display();
};
LRUCache::LRUCache(int n)
{
csize = n;
}
// Refer key x in the LRUCache
void LRUCache::refer(int x) {
// not present in cache
if (ma.find() == ma.end())
{
if (dq.size() = csize)
{
int last = dq.back();
dq.pop_back();
ma.erase(last);
}
}
else { dq.erase(ma[x]); }
}
void LRUCache::display()
{
for (auto it=dq.begin(); it != dq.end(); it++)
cout << (*it) << " ";
cout << end;
}
// Driver to program test above functions
int main() {
LRUCache ca(4);
ca.refer(1);
ca.refer(2);
ca.refer(3);
ca.refer(1);
ca.display();
return 0;
}
| true |
84c2efc85d6f4a13b1bfc0f968a82d5101428dee | C++ | srcpls/gala.go | /core/board/group/ group.cpp | UTF-8 | 1,946 | 3.546875 | 4 | [] | no_license | //
// gala.go
// group.cpp
//
#include "group.hpp"
group::group(int color)
{
this->color=color;
numofcoordinates=0;
}
group::~group()
{
}
void group::addcoordinate(coordinate c)
{
std::cout<<"when addcoordinate, coordinate c: i:"<<c.i<<" j:"<<c.j<<std::endl;
std::cout<<"when addcoordinate, numofcoordinates before"<<numofcoordinates<<std::endl;
numofcoordinates++;
coordinates.push_back(c);
std::cout<<"when addcoordinate, numofcoordinates after"<<numofcoordinates<<std::endl;
}
void group::minuscoordinate(int index)
{
numofcoordinates--;
coordinates.erase(coordinates.begin()+index);
}
void group::makenilcoordinates()
{
coordinates.clear();
numofcoordinates=0;
}
coordinate group::retrievecoordinate(int index)
{
return coordinates[index];
}
int group::retrievenumofcoordinates()
{
return numofcoordinates;
}
int group::retrievecolor()
{
return color;
}
int group::hascoordinate(coordinate c)
{
std::cout<<"number of coordinates hascoordinate"<<numofcoordinates<<std::endl;
for(int i=0;i<this->numofcoordinates;i++)
{
std::cout<<"checking comparison between coordinate i: "<<coordinates[i].i<<" j: "<<coordinates[i].j<<std::endl;
std::cout<<"and coordinate given: i: "<<c.i<<" j: "<<c.j<<std::endl;
if(coordinates[i]==c)
{
std::cout<<"found. returning index : "<<i<<std::endl;
return i;
}
}
std::cout<<"not found. returning -1"<<std::endl;
return -1;
}
bool group::operator==(const group &g2)
{
for(int i=0;i<numofcoordinates;i++)
{
if(this->coordinates[i]!=g2.coordinates[i])
{
return false;
}
}
return true;
}
bool group::operator-=(const group &g2)
{
for(int i=0;i<g2.numofcoordinates;i++)
{
if(this->hascoordinate(g2.coordinates[i])==-1)
{
return false;
}
}
return true;
}
| true |
4e04b4805c8280468cdbc103fe0b0a64f3b2d618 | C++ | mmason930/kinslayer-mud | /src/threaded_jobs.cpp | UTF-8 | 2,758 | 2.859375 | 3 | [] | no_license | /********************************************************************
* threaded_jobs.cpp - Implements the ThreadedJobsManager class *
* This file is responsible for handling various jobs *
* which require multithreading. *
* Added by Galnor in April of 2010 (Sortak@gmail.com) *
* *
********************************************************************/
#include "threaded_jobs.h"
ThreadedJobManager* ThreadedJobManager::pSelf = NULL;
ThreadedJobManager::ThreadedJobManager()
{
//...
}
ThreadedJobManager::~ThreadedJobManager()
{
//...
}
/***
*
* get( void ) - Singleton accessor. Allocates if it doesn't exist.
* ~~~Galnor 04/17/2010
**/
ThreadedJobManager& ThreadedJobManager::get()
{
if( !pSelf ) pSelf = new ThreadedJobManager();
return *pSelf;
}
/***
*
* free( void ) - Frees up any memory used by this class, and kills all existing jobs in the queue.
* ~~~Galnor 04/17/2010
**/
void ThreadedJobManager::free()
{
delete pSelf;
while( lJobs.empty() == false ) {
delete lJobs.front();
lJobs.pop_front();
}
while( lFinishedJobs.empty() == false ) {
delete lFinishedJobs.front();
lFinishedJobs.pop_front();
}
pSelf = NULL;
}
/***
*
* addJob( Job* ) - Appends a Job to the lJobs list and begins processing it in a new thread.
*
* ~~~Galnor 04/17/2010
**/
void ThreadedJobManager::addJob( Job *job )
{
{//Lock
std::lock_guard<std::mutex> m(jobsMutex);
lJobs.push_back( job );
}//Release
std::thread thread( &ThreadedJobManager::runJob, this, job );
thread.detach();
}
/***
*
* runJob( Job* ) - Thread entry point for the job's routine. This will process the performRoutine()
* method for the Job class, remove from the lJobs list, and add to lFinishedJobs once it
* completes its processing.
* ~~~Galnor 04/17/2010
**/
void ThreadedJobManager::runJob( Job *job )
{
job->performRoutine();
{//Lock
std::lock_guard<std::mutex> m(jobsMutex);
this->lJobs.remove( job );
}//Release
{//Lock
std::lock_guard<std::mutex> m(finishedJobsMutex);
this->lFinishedJobs.push_back( job );
}//Release
}
/***
*
* cycleThroughFinishedJobs( void ) - Cycles through all completed jobs, and runs the
* respective Job::performPostRoutine method for each of them.
* ~~~Galnor 04/17/2010
**/
void ThreadedJobManager::cycleThroughFinishedJobs()
{
{//Lock
std::lock_guard<std::mutex> m(finishedJobsMutex);
for(std::list< Job* >::iterator fjIter = lFinishedJobs.begin();fjIter != lFinishedJobs.end();++fjIter)
{
(*fjIter)->performPostJobRoutine();
delete (*fjIter);
}
lFinishedJobs.clear();
}//Release
}
| true |
315e8355d0c80b01514d116c977a1ed0c90fd836 | C++ | HelloGit2309/Codelines-1 | /Tasks/TASK 1/solution.cpp | UTF-8 | 1,363 | 3.125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const long long int mod = (1<<64);
const int p=22;
//takes a string and returns a vector which containts the hash values
//v[0] = hash(substr(0,1))
//v[1] = hash(substr(0,2))
//v[2] = hash(substr(0,3)) .... and so on
vector <long long int> computeHash(char *str)
{
vector <long long int> hash_values(strlen(str));
long long int pp=1;
for(int i=0;i<strlen(str);i++)
{
hash_values[i] = (hash_values[i-1] + (str[i]-'a')*pp)%mod;
pp = (pp * p)%mod;
}
return hash_values;
}
long long int binpow(long long int a,long long int b,long long int m)
{
long long int res=1;
while(b>0)
{
if(b&1)
res=(res*a)%m;
a=(a*a)%m;
b>>=1;
}
return res;
}
int main()
{
char *str;cin>>str;
vector <long long int> hash_prefix = computeHash(str);
vector <long long int> hash_suffix(strlen(str));
for(long long int i=strlen(str)-1;i>=0;i--)
{
hash_suffix[strlen(str)-i] = ((hash_prefix[i] - hash_prefix[i-1]) * binpow(binpow(p,i,mod),mod-2,mod))%mod;
}
map <long long int,long long int> m_prefix;
map <long long int,long long int> m_suffix;
for(int i=0;i<strlen(str);i++)
{
m_prefix[hash_prefix[i]]++;
m_prefix[hash_suffix[i]]++;
}
int ans=0;
for(auto it:m_prefix)
{
long long int f1=it.second;
long long int f2=m_suffix[it.first];
ans = f1 * f2;
}
cout<<ans;
}
| true |
e0e8984d467ee3c7bea3465e884c2a904688d35c | C++ | ruudstaal/myproject | /Project/befc/mio/cards/AI/DMS202.hpp | UTF-8 | 3,426 | 2.5625 | 3 | [] | no_license | /**
********************************************************************************
* @file DMS202.hpp
* @author Patrick
* @version $Revision: 000 $
* @date $LastChangeDate: Jan 7, 2014 9:50:58 AM 11:00:00 $
*
* @brief Implementation of strain gauge module DMS202
*
********************************************************************************
* COPYRIGHT BY BACHMANN ELECTRONIC GmbH 2015
*******************************************************************************/
#ifndef DMS202_HPP_
#define DMS202_HPP_
/**********************************************************************
* system includes
**********************************************************************/
/**********************************************************************
* project includes
**********************************************************************/
#include "../../common/base/BasicAnalogModule.hpp"
/**
* @brief Strain Gauge Module DMS202
*
* Channels : 2
*
*
*/
class DMS202: public BasicAnalogModule
{
public:
/**
* Offset Values for both Channels
*/
typedef enum
{
OFFSET_0, // Offset 0
OFFSET_1, // Offset 1 mV
OFFSET_2, // Offset 2 mV
OFFSET_3, // Offset 3 mV
OFFSET_4, // Offset 4 mV
OFFSET_5, // Offset 5 mV
OFFSET_6, // Offset 6 mV
OFFSET_7, // Offset 7 mV
OFFSET_8 // Offset 8 mV
} EOffset_t;
/**
* Constructor
*
* @throws a MIOexception when card does not match class
*/
DMS202();
/**
* Constructor
*
* @param ui32CardNumber - configured Cardnumber
*
* @throws a MIOexception when card does not match class
*/
explicit DMS202(UINT32 ui32CardNumber);
/**
* Destructor
*/
virtual ~DMS202();
/**
* set Offset to Measured Signal
*
* @param ui8Channel - selected channel (1,2)
* @param Value - Offset 1-8 mV
* @param b8Save - optional, TRUE = Store Value on Module \n
* optional, FALSE = Value is lost after Reboot
*
* @throws a MIOexception when writing to card fails,
* or a MIOexception if pointer to card is invalid,
* or a MIOexception if parameter is invalid
*/
VOID setOffset(UINT8 ui8Channel, DMS202::EOffset_t Value, BOOL8 b8Save = FALSE);
/**
* read actual Peakvalue
*
* @param ui8Channel - selected channel (1,2)
* @param b8Reset - TRUE = set Value to zero after read
* - FALSE = just read value
*
* @return actual peak Value
*/
SINT32 getPeak(UINT8 ui8Channel, BOOL8 b8Reset = FALSE);
/**
* set offset to Zero
* This method can need a few seconds to execute!
* Offset Value from setOffset(..) will be deleted
*
* @param ui8Channel - selected channel (1,2)
* @param b8Save - optional, TRUE = Store Value on Module
* optional, FALSE = Value is lost after Reboot
*
* @throws a MIOexception when writing to card fails,
* or a MIOexception if pointer to card is invalid,
*/
VOID setZero(UINT8 ui8Channel, BOOL8 b8Save = FALSE);
protected:
/**
* get Type of Module
* see BasicIoModule::TYPE_xxxxx
*
* @returns > 0 - Type
*/
SINT32 getTypeId(VOID)
{
return BasicIoModule::TYPE_DMS202;
}
};
#endif /** DMS202_HPP_ */
| true |
e3d27eeee9733f7ecfc3c4e5c57c757d9d234d7b | C++ | ccdxc/logSurvey | /data/crawl/squid/new_hunk_4211.cpp | UTF-8 | 2,530 | 3.203125 | 3 | [] | no_license | * Configuration option parsing code
*/
/**
* Parse wccp2_return_method and wccp2_forwarding_method options
* they can be '1' aka 'gre' or '2' aka 'l2'
* repesenting the integer numeric of the same.
*/
void
parse_wccp2_method(int *method)
{
char *t;
/* Snarf the method */
if ((t = strtok(NULL, w_space)) == NULL) {
debugs(80, DBG_CRITICAL, "wccp2_*_method: missing setting.");
self_destruct();
}
/* update configuration if its valid */
if (strcmp(t, "gre") == 0 || strcmp(t, "1") == 0) {
*method = WCCP2_METHOD_GRE;
} else if (strcmp(t, "l2") == 0 || strcmp(t, "2") == 0) {
*method = WCCP2_METHOD_L2;
} else {
debugs(80, DBG_CRITICAL, "wccp2_*_method: unknown setting, got " << t );
self_destruct();
}
}
void
dump_wccp2_method(StoreEntry * e, const char *label, int v)
{
switch(v)
{
case WCCP2_METHOD_GRE:
storeAppendPrintf(e, "%s gre\n", label);
break;
case WCCP2_METHOD_L2:
storeAppendPrintf(e, "%s l2\n", label);
break;
default:
debugs(80, DBG_CRITICAL, "FATAL: WCCPv2 configured method (" << v << ") is not valid.");
self_destruct();
}
}
void
free_wccp2_method(int *v)
{ }
/**
* Parse wccp2_assignment_method option
* they can be '1' aka 'hash' or '2' aka 'mask'
* repesenting the integer numeric of the same.
*/
void
parse_wccp2_amethod(int *method)
{
char *t;
/* Snarf the method */
if ((t = strtok(NULL, w_space)) == NULL) {
debugs(80, DBG_CRITICAL, "wccp2_assignment_method: missing setting.");
self_destruct();
}
/* update configuration if its valid */
if (strcmp(t, "hash") == 0 || strcmp(t, "1") == 0) {
*method = WCCP2_ASSIGNMENT_METHOD_HASH;
} else if (strcmp(t, "mask") == 0 || strcmp(t, "2") == 0) {
*method = WCCP2_ASSIGNMENT_METHOD_MASK;
} else {
debugs(80, DBG_CRITICAL, "wccp2_assignment_method: unknown setting, got " << t );
self_destruct();
}
}
void
dump_wccp2_amethod(StoreEntry * e, const char *label, int v)
{
switch(v)
{
case WCCP2_ASSIGNMENT_METHOD_HASH:
storeAppendPrintf(e, "%s hash\n", label);
break;
case WCCP2_ASSIGNMENT_METHOD_MASK:
storeAppendPrintf(e, "%s mask\n", label);
break;
default:
debugs(80, DBG_CRITICAL, "FATAL: WCCPv2 configured " << label << " (" << v << ") is not valid.");
self_destruct();
}
}
void
free_wccp2_amethod(int *v)
{ }
/*
* Format:
* | true |
fa6cd66d3cd8d0ef0f2c0c58622eebc620cab348 | C++ | tmtlab/vapaee.io-source | /contracts/vapaeetokens/vapaeetokens.core.hpp | UTF-8 | 12,972 | 2.765625 | 3 | [
"MIT"
] | permissive | #pragma once
#include <vapaee/token/common.hpp>
using namespace eosio;
namespace vapaee {
namespace token {
class core {
name _self;
public:
core():_self(vapaee::token::contract){}
inline name get_self()const { return vapaee::token::contract; }
// TOKEN --------------------------------------------------------------------------------------------
void action_create_token(name owner, asset maximum_supply) {
PRINT("vapaee::token::core::action_create_token()\n");
PRINT(" owner: ", owner.to_string(), "\n");
PRINT(" maximum_supply: ", maximum_supply.to_string(), "\n");
require_auth( owner );
auto sym = maximum_supply.symbol;
check( sym.is_valid(), "invalid symbol name" );
check( maximum_supply.is_valid(), "invalid supply");
check( maximum_supply.amount > 0, "max-supply must be positive");
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
check( existing == statstable.end(), "token with symbol already exists" );
statstable.emplace( owner, [&]( auto& s ) {
s.supply.symbol = maximum_supply.symbol;
s.max_supply = maximum_supply;
s.issuer = owner;
});
PRINT("vapaee::token::core::action_create_token() ...\n");
}
void action_add_token_issuer( name app, const symbol_code& sym_code, name ram_payer ) {
PRINT("vapaee::token::core::action_add_token_issuer()\n");
PRINT(" app: ", app.to_string(), "\n");
PRINT(" sym_code: ", sym_code.to_string(), "\n");
stats statstable( _self, sym_code.raw() );
auto token_itr = statstable.find( sym_code.raw() );
check( token_itr != statstable.end(), "token with symbol not exists" );
require_auth ( token_itr->issuer );
issuers issuerstable(get_self(), sym_code.raw() );
auto issuer_itr = issuerstable.find( app.value );
check( issuer_itr == issuerstable.end(), "issuer already registered" );
issuerstable.emplace( ram_payer, [&]( auto& a ){
a.issuer = app;
});
PRINT("vapaee::token::core::action_add_token_issuer() ...\n");
}
void action_remove_token_issuer( name app, const symbol_code& sym_code ) {
PRINT("vapaee::token::core::action_remove_token_issuer()\n");
PRINT(" app: ", app.to_string(), "\n");
PRINT(" sym_code: ", sym_code.to_string(), "\n");
stats statstable( _self, sym_code.raw() );
auto token_itr = statstable.find( sym_code.raw() );
check( token_itr != statstable.end(), "token with symbol not exists" );
require_auth ( token_itr->issuer );
issuers issuerstable(get_self(), sym_code.raw() );
auto issuer_itr = issuerstable.find( app.value );
check( issuer_itr != issuerstable.end(), "issuer is not registered" );
issuerstable.erase( *issuer_itr );
PRINT("vapaee::token::core::action_remove_token_issuer() ...\n");
}
void action_issue( name to, const asset& quantity, string memo ) {
PRINT("vapaee::token::core::action_issue()\n");
PRINT(" to: ", to.to_string(), "\n");
PRINT(" quantity: ", quantity.to_string(), "\n");
PRINT(" memo: ", memo.c_str(), "\n");
// check on symbol
auto sym = quantity.symbol;
check( sym.is_valid(), "invalid symbol name" );
check( memo.size() <= 256, "memo has more than 256 bytes" );
// check token existance
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
check( existing != statstable.end(), "token with symbol does not exist, create token before issue" );
const auto& st = *existing;
// getting currency's acosiated app contract account
// vapaee::bgbox::apps apps_table(vapaee::bgbox::contract, vapaee::bgbox::contract.value);
// auto app = apps_table.get(st.app, "app not found");
// name appcontract = app.contract;
// PRINT(" appid: ", std::to_string((int) st.app), "\n");
// PRINT(" appcontract: ", appcontract.to_string(), "\n");
// check authorization (issuer of appcontract)
name everyone = "everyone"_n;
name issuer = st.issuer;
issuers issuerstable(get_self(), sym.code().raw() );
for (auto issuer_itr = issuerstable.begin(); issuer_itr != issuerstable.end(); issuer_itr++) {
// auto issuer_app = apps_table.get(st.issuers[i], (string("app ") + std::to_string((int)st.issuers[i]) + " not found in bgbox::apps").c_str());
name issuer_app = issuer_itr->issuer;
// if "everyone" is in issuers list then everyone is allowed to issue because this is a fake token
if (has_auth(issuer_app) || issuer_app == everyone) {
issuer = issuer_app;
PRINT(" issuer_app: ", issuer.to_string(), "\n");
}
}
if (issuer != everyone) {
// we need sirius issuer signature
PRINT( "require_auth( issuer )", issuer.to_string(), "\n");
require_auth( issuer );
} else {
// for fake token, everyone can issue. No need for signature
issuer = st.issuer;
}
check( quantity.is_valid(), "invalid quantity" );
check( quantity.amount > 0, "must issue positive quantity" );
check( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
check( quantity.amount <= st.max_supply.amount - st.supply.amount, "quantity exceeds available supply");
// update current supply
statstable.modify( st, same_payer, [&]( auto& s ) {
s.supply += quantity;
});
// update contract balance silently
add_balance( get_self(), quantity, get_self() );
// if target user is not the contract then send an inline action
if( to != get_self() ) {
action(
permission_level{get_self(),"active"_n},
get_self(),
"transfer"_n,
std::make_tuple(get_self(), to, quantity, memo)
).send();
}
PRINT("vapaee::token::core::action_issue() ...\n");
}
void action_burn(name owner, asset quantity, string memo ) {
PRINT("vapaee::token::core::action_retire()\n");
PRINT(" quantity: ", quantity.to_string(), "\n");
PRINT(" memo: ", memo.c_str(), "\n");
auto sym = quantity.symbol;
check( sym.is_valid(), "invalid symbol name" );
check( memo.size() <= 256, "memo has more than 256 bytes" );
stats statstable( _self, sym.code().raw() );
auto existing = statstable.find( sym.code().raw() );
check( existing != statstable.end(), "token with symbol does not exist" );
const auto& st = *existing;
require_auth( owner );
check( quantity.is_valid(), "invalid quantity" );
check( quantity.amount > 0, "must retire positive quantity" );
check( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
statstable.modify( st, same_payer, [&]( auto& s ) {
s.supply -= quantity;
});
sub_balance( owner, quantity );
PRINT("vapaee::token::core::action_retire() ...\n");
}
void action_transfer(name from, name to, asset quantity, string memo) {
PRINT("vapaee::token::core::action_transfer()\n");
PRINT(" from: ", from.to_string(), "\n");
PRINT(" to: ", to.to_string(), "\n");
PRINT(" quantity: ", quantity.to_string(), "\n");
PRINT(" memo: ", memo.c_str(), "\n");
check( from != to, "cannot transfer to self" );
check( is_account( to ), "to account does not exist");
auto sym = quantity.symbol.code();
stats statstable( _self, sym.raw() );
const auto& st = statstable.get( sym.raw() );
require_recipient( from );
require_recipient( to );
check( quantity.is_valid(), "invalid quantity" );
check( quantity.amount > 0, "must transfer positive quantity" );
check( quantity.symbol == st.supply.symbol, "symbol precision mismatch" );
check( memo.size() <= 256, "memo has more than 256 bytes" );
auto ram_payer = has_auth( to ) ? to : from;
sub_balance( from, quantity );
add_balance( to, quantity, ram_payer );
PRINT("vapaee::token::core::action_transfer() ...\n");
}
void sub_balance( name owner, asset value ) {
PRINT("vapaee::token::core::action_sub_balance()\n");
PRINT(" owner: ", owner.to_string(), "\n");
PRINT(" value: ", value.to_string(), "\n");
accounts from_acnts( _self, owner.value );
const auto& from = from_acnts.get( value.symbol.code().raw(), "no balance object found" );
check( from.balance.amount >= value.amount, "overdrawn balance" );
int64_t amount;
from_acnts.modify( from, owner, [&]( auto& a ) {
a.balance.amount -= value.amount;
amount = a.balance.amount;
});
if (amount == 0) {
action(
permission_level{get_self(),"active"_n},
get_self(),
"close"_n,
std::make_tuple(owner, value.symbol)
).send();
}
PRINT("vapaee::token::core::action_sub_balance() ...\n");
}
void add_balance( name owner, asset value, name ram_payer ) {
PRINT("vapaee::token::core::action_add_balance()\n");
PRINT(" owner: ", owner.to_string(), "\n");
PRINT(" value: ", value.to_string(), "\n");
PRINT(" ram_payer: ", ram_payer.to_string(), "\n");
accounts to_acnts( _self, owner.value );
auto to = to_acnts.find( value.symbol.code().raw() );
if( to == to_acnts.end() ) {
to_acnts.emplace( ram_payer, [&]( auto& a ){
a.balance = value;
});
} else {
to_acnts.modify( to, same_payer, [&]( auto& a ) {
a.balance += value;
});
}
PRINT("vapaee::token::core::action_add_balance() ...\n");
}
void action_open( name owner, const symbol& symbol, name ram_payer ) {
PRINT("vapaee::token::core::action_open()\n");
PRINT(" owner: ", owner.to_string(), "\n");
PRINT(" symbol: ", symbol.code().to_string(), "\n");
PRINT(" ram_payer: ", ram_payer.to_string(), "\n");
require_auth( ram_payer );
auto sym_code_raw = symbol.code().raw();
stats statstable( _self, sym_code_raw );
const auto& st = statstable.get( sym_code_raw, "symbol does not exist" );
check( st.supply.symbol == symbol, "symbol precision mismatch" );
accounts acnts( _self, owner.value );
auto it = acnts.find( sym_code_raw );
if( it == acnts.end() ) {
acnts.emplace( ram_payer, [&]( auto& a ){
a.balance = asset{0, symbol};
});
}
PRINT("vapaee::token::core::action_open() ...\n");
}
void action_close( name owner, const symbol& symbol ) {
PRINT("vapaee::token::core::action_close()\n");
PRINT(" owner: ", owner.to_string(), "\n");
PRINT(" symbol: ", symbol.code().to_string(), "\n");
if (!has_auth(get_self())) {
require_auth( owner );
}
accounts acnts( _self, owner.value );
auto it = acnts.find( symbol.code().raw() );
check( it != acnts.end(), "Balance row already deleted or never existed. Action won't have any effect." );
check( it->balance.amount == 0, "Cannot close because the balance is not zero." );
acnts.erase( it );
PRINT("vapaee::token::core::action_close() ...\n");
}
}; // class
}; // namespace
}; // namespace | true |
435264414e8760c65bd5e2de4768503f1f82ca4f | C++ | GamesTrap/LearnCPP | /MathVector/src/Vector.h | UTF-8 | 2,069 | 3.59375 | 4 | [
"MIT"
] | permissive | #pragma once
#include <stdexcept>
#include <initializer_list>
template<typename T>
class Vector
{
public:
explicit Vector(std::size_t amount = 1);
Vector(std::size_t amount, T value);
Vector(std::initializer_list<T>);
Vector(const Vector<T>& v);
virtual ~Vector()
{
delete[] m_start;
}
auto size() const { return m_amount; }
void changeSize(std::size_t);
T& operator[](std::size_t index)
{
if (index >= m_amount)
throw std::out_of_range("Index exceeded!");
return m_start[index];
}
const T& operator[](std::size_t index) const
{
if (index >= m_amount)
throw std::out_of_range("Index exceeded!");
return m_start[index];
}
Vector<T>& operator=(Vector<T>);
void swap(Vector<T>& v) noexcept;
T* begin() { return m_start; }
T* end() { return m_start + m_amount; }
const T* begin() const { return m_start; }
const T* end() const { return m_start + m_amount; }
private:
std::size_t m_amount;
T* m_start;
};
template<typename T>
Vector<T>::Vector(std::size_t amount)
: m_amount{amount}, m_start{new T[amount]}
{
}
template <typename T>
Vector<T>::Vector(std::size_t amount, T value)
: Vector(amount)
{
for (std::size_t i = 0; i < m_amount; ++i)
m_start[i] = value;
}
template<typename T>
Vector<T>::Vector(std::initializer_list<T> list)
: Vector(list.size())
{
std::copy(list.begin(), list.end(), m_start);
}
template<typename T>
Vector<T>::Vector(const Vector<T>& v)
: Vector(v.m_amount)
{
for (std::size_t i = 0; i < m_amount; ++i)
m_start[i] = v.m_start[i];
}
template <typename T>
void Vector<T>::swap(Vector<T>& v) noexcept
{
std::swap(m_amount, v.m_amount);
std::swap(m_start, v.m_start);
}
template <typename T>
Vector<T>& Vector<T>::operator=(Vector<T> v)
{
swap(v);
return *this;
}
template <typename T>
void Vector<T>::changeSize(std::size_t newSize)
{
T* pTemp{ new T[newSize] };
const std::size_t smallerNumber{ newSize > m_amount ? m_amount : newSize };
for (std::size_t i = 0; i < smallerNumber; ++i)
pTemp[i] = m_start[i];
delete[] m_start;
m_start = pTemp;
m_amount = newSize;
}
| true |
9348fe881bd1e2d531b0ba00f37755639fee110f | C++ | bs-eagle/bs-eagle | /bs_bos_core_base/include/vector_assign.h | UTF-8 | 979 | 2.8125 | 3 | [] | no_license | /**
* \file
* \brief spec for vectors assign
* \author Sergey Miryanov
* \date 02.03.2009
* */
#ifndef BS_VECTOR_ASSIGN_H_
#define BS_VECTOR_ASSIGN_H_
#include "force_inline.h"
namespace blue_sky {
template <typename item_t, size_t size, typename val_t>
BS_FORCE_INLINE void
assign (boost::array <item_t, size> &array, const val_t &val)
{
memset (&array[0], val, sizeof (item_t) * size);
}
template <typename item_t, typename val_t>
BS_FORCE_INLINE void
assign (shared_vector <item_t> &array, const val_t &val)
{
size_t size = array.size ();
if (size)
memset (&array[0], val, sizeof (item_t) * array.size ());
}
template <typename item_t, typename val_t, typename size_type>
BS_FORCE_INLINE void
assign (shared_vector <item_t> &array, size_type size, const val_t &val)
{
array.resize (size);
assign (array, val);
}
} // namespace blue_sky
#endif // #ifndef BS_VECTOR_ASSIGN_H_
| true |
e1e2dae05ae1e4a7c0a7f7c8763cb235453a9416 | C++ | scissor-project/open-scissor | /docker/d-streamon-master/d-streamon/streamon/lib/fc/StructTemplate.cpp | UTF-8 | 810 | 2.5625 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | #include "StructTemplate.h"
namespace IPFIX {
void StructTemplate::add(const InfoElement* ie, size_t offset) {
// Add IE to maps
add_inner(ie);
// Calculate offset if necessary
if (!offset) {
if (offsets_.empty()) {
offset = 0;
} else if (ie->len() == kVarlen) {
offset = offsets_.back() + sizeof(VarlenField);
} else {
offset = offsets_.back() + ie->len();
}
}
// Check offset monotonity invariant
if (!offsets_.empty() && offset < offsets_.back()) {
throw IETypeError("Cannot add IE with negative offset");
}
// Add offset to offset table
offsets_.push_back(offset);
// calculate minlen
size_t ielen = ie->len();
if (ielen == kVarlen) ielen = sizeof(VarlenField);
if ((offset + ielen) > minlen_) minlen_ = offset + ielen;
}
} | true |
efd6a8b19b6963aa94269aed1de94b5a8c8d70d8 | C++ | XZeusJ/Leetcode | /59.spiral-matrix-ii.cpp | UTF-8 | 1,221 | 3.421875 | 3 | [] | no_license | /*
* @lc app=leetcode id=59 lang=cpp
*
* [59] Spiral Matrix II
*
* https://leetcode.com/problems/spiral-matrix-ii/description/
*
* algorithms
* Medium (48.85%)
* Likes: 730
* Dislikes: 98
* Total Accepted: 168.9K
* Total Submissions: 332.9K
* Testcase Example: '3'
*
* Given a positive integer n, generate a square matrix filled with elements
* from 1 to n^2 in spiral order.
*
* Example:
*
*
* Input: 3
* Output:
* [
* [ 1, 2, 3 ],
* [ 8, 9, 4 ],
* [ 7, 6, 5 ]
* ]
*
*
*/
// @lc code=start
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
int l = 0, r = n - 1, u = 0, d = n - 1;
vector<vector<int>> res(n, vector<int>(n));
int num = 1, tar = n * n;
while (num <= tar) {
for (int i = l; i <= r; i++) res[u][i] = num++; // left to right.
u++;
for (int i = u; i <= d; i++) res[i][r] = num++; // top to bottom.
r--;
for (int i = r; i >= l; i--) res[d][i] = num++; // right to left.
d--;
for (int i = d; i >= u; i--) res[i][l] = num++; // bottom to top.
l++;
}
return res;
}
};
// @lc code=end
| true |
a5adbafc27fc16bda355404f8bd177a22761448f | C++ | wtrnash/LeetCode | /cpp/141环形链表/141环形链表.cpp | UTF-8 | 1,321 | 3.65625 | 4 | [] | no_license | /*
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。
示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。
进阶:
你能用 O(1)(即,常量)内存解决此问题吗?
*/
//解答:用hashmap做,将遇到的节点放入hashmap,判断当前节点是否曾遇到
#include <iostream>
#include <unordered_set>
using namespace std;
/**
* Definition for singly-linked list.
*/ struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> hash;
while(head)
{
if(hash.find(head) != hash.end())
return true;
hash.insert(head);
head = head->next;
}
return false;
}
}; | true |
01b9efe042d40e327c0068900de687b8b9b48e2e | C++ | UelitonFreitas/ComputerVision | /BoW/BoW.h | UTF-8 | 8,671 | 2.671875 | 3 | [] | no_license | #ifndef __BOW_H
#define __BOW_H
#include <opencv/cv.h>
#include <opencv/cxcore.h>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/nonfree/nonfree.hpp>
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/ml/ml.hpp"
#include <stdlib.h>
using namespace cv;
using namespace std;
class BoW{
private:
int dictionarySize; //BoW dictionary size.
BOWKMeansTrainer* bowTrainer; //Bow Trainer.
Mat dictionary; //BoW dictionary.
BOWImgDescriptorExtractor *bowDE; //BoW image descriptor. For testing.
vector<Mat>* trainImages; //Vector of images.
vector<Mat> trainDescriptors; //Vector of keypoints descriptors.
vector< vector<KeyPoint> > trainKeyPoints; //Vector of keypoints of each image.
vector<string>* imagesClass;
vector<Mat>* testImages; //Vector of test images.
vector<Mat> testDescriptors; //Vector of test Descriptors;
vector< vector<KeyPoint> > testKeyPoints; //Vector fo test Keypoints;
vector<Mat> imageAttributes;
Ptr<FeatureDetector> featureDetector; //Default: Surf
Ptr<DescriptorExtractor> descriptorExtractor;
Ptr<DescriptorMatcher> descriptorMatcher;
string detectorType; //Default SURF.
string descriptorType; //Default SURF.
string matcherType; //Default FLANN
float hessianThreshold; //Theshold, the larger value, less keypoints.
string tag;
char fileName[100]; //Name of dictionary to be saved;
public:
BoW(string detectorType = "SURF", string descriptorType = "SURF",string matcherType = "FlannBased",float hessianThreshold = 0.1,int dicSize = 64){
this->detectorType = detectorType;
this->descriptorType =descriptorType;
this->matcherType = matcherType;
this->hessianThreshold =hessianThreshold;
this->dictionarySize = dicSize;
TermCriteria tc(CV_TERMCRIT_ITER,100,0.001);
int retries=1;
int flags=KMEANS_PP_CENTERS;
this->createDetectorDescriptorMatcher();
this->bowTrainer = new BOWKMeansTrainer(this->dictionarySize, tc, retries, flags );
this->bowDE = new BOWImgDescriptorExtractor(this->descriptorExtractor,this->descriptorMatcher);
this->tag = "Bag Of Words: ";
}
void runTraining(){
if(this->trainImages != NULL and this->imagesClass != NULL){
this->trainFeaturesDetect();
this->trainKeyPointsDescriptors();
this->createVocabulary();
this->setVocabularyOnImageDescriptor();
this->saveDictionary();
this->createImagesAttributes();
}
else{
cout << endl<< this->tag << "You have to load train imagens and class names.";
}
}
void createImageAttribute(Mat& image){
vector<KeyPoint> keyPoints;
Mat bowDescriptor;
this->featureDetector->detect(image,keyPoints);
this->bowDE->compute(image,keyPoints,bowDescriptor);
this->imageAttributes.push_back(bowDescriptor);
}
void setVocabularyOnImageDescriptor(){
this->bowDE->setVocabulary(this->dictionary);
}
void createImagesAttributes(){
//this->setVocabulary();
cout << endl << this->tag << "Creating images Attributes..." << endl;
for(int i = 0; i < this->trainImages->size() ; i++){
this->createImageAttribute( this->trainImages->at(i));
}
cout << "Complete!!" << endl;
}
void loadTrainImages(vector<Mat>& images,vector<string>& imagesClass){
cout << endl << this->tag << "Loading images..." << endl;
this->trainImages = new vector<Mat>(images);
this->imagesClass = new vector<string>(imagesClass);
cout << "Complete!!!" << endl;
}
void trainFeaturesDetect(){
cout << endl << this->tag << "Detecting keypoints of " << this->trainImages->size() << " images." << endl;
this->featureDetector->detect(*(this->trainImages),this->trainKeyPoints);
cout << "Complete!!!" << endl;
}
void trainKeyPointsDescriptors(){
cout << endl << this->tag << "Describing Key Points...." << endl;
this->descriptorExtractor->compute(*(this->trainImages),this->trainKeyPoints,this->trainDescriptors);
cout << "Complete!!!" << endl;
}
void createVocabulary(){
cout << endl << this->tag << "Creating vocabulary...." << endl;
for(size_t i = 0 ; i < this->trainDescriptors.size(); i++){
Mat descriptor = this->trainDescriptors[i];
for(int j = 0; j < descriptor.rows; j++){
this->bowTrainer->add(descriptor.row(j));
}
}
cout << this->tag << "Appliyng k-means..." << endl;
this->dictionary = this->bowTrainer->cluster();
cout << this->tag << "Dictionary created with size " << this->dictionarySize << endl;
}
void loadDictionary(string fileName){
//this->fileName = fileName;
FileStorage file(fileName, FileStorage::READ);
if(file.isOpened()){
cout << tag << "Loading Dictionary with size: " << this->dictionarySize << " ...." <<endl;;
file["dictionary"] >> this->dictionary;
setVocabularyOnImageDescriptor();
}
else
cout << this->tag << "Cannot load the dictionary file." << endl;
}
void saveDictionary(){
cout << tag << "Saving Dictionary with size: " << this->dictionarySize << " ...." <<endl;
sprintf(this->fileName,"Dictionary-%02d.xml",this->dictionarySize);
FileStorage file(this->fileName, FileStorage::WRITE);
if(file.isOpened()){
file << "dictionary" << this->dictionary;
cout << tag << "Dictionary saved!! " << endl;
}
else
cout << "Can create dictionary file!!" << endl;
}
bool createDetectorDescriptorMatcher(){
initModule_nonfree();
this->featureDetector = FeatureDetector::create(detectorType);
this->descriptorExtractor = DescriptorExtractor::create(descriptorType);
this->descriptorMatcher = DescriptorMatcher::create(matcherType);
//shows the parameters of a given algorithm
//printParams(this->featureDetector);
this->featureDetector->set("hessianThreshold", this->hessianThreshold);
}
vector<vector<KeyPoint> >& getTrainKeyPoints(){
return this->trainKeyPoints;
}
/*
vector<Mat>& getImagesAttributes(){
return this->imageAttributes;
}
*/
// TESTAR PARA IMPLEMENTAR PADRÃO DE COMUNICAÇÃO
vector<vector<float> >& getImagesAttributes(){
int numberOfImages = this->imageAttributes.size();
vector<vector<float> >* features = new vector<vector<float> >(numberOfImages,vector<float>(this->dictionarySize));
for(int i = 0; i < numberOfImages; i++){
Mat row = this->imageAttributes[i].row(0);
for(int k = 0 ; k < row.cols; k++){
(features->at(i)).at(k) = (float)row.data[k];
}
}
return *features;
}
vector<float>& getImagesAttributesOfTestImage(){
vector<float>* feature = new vector<float>(this->dictionarySize);
Mat row = this->imageAttributes[0].row(0);
for(int k = 0 ; k < row.cols; k++){
feature->at(k) = (float)row.data[k];
}
return *feature;
}
string& getArffFileName(){
char c[200];
sprintf(c,"BoW_Dictionary_%02d.arff",this->dictionarySize);
return *(new string(c));
}
/*
Mat& getImagesAttributesOfTestImage(){
return this->imageAttributes[0];
}
*/
};
#endif
| true |
2de96948c6b302c2c2b7848cb35ba3bf096d799a | C++ | TeamLaw/SFML-V1.0 | /Main_Screen.cpp | UTF-8 | 1,050 | 2.796875 | 3 | [] | no_license | #include "TowerCrawl.h"
#include "Entities.h"
#include "Environment.h"
#include "screens.h"
screen_Main::screen_Main(void)
{
alpha_max = 3 * 255;
alpha_div = 3;
playing = false;
}
int screen_Main::Run(sf::RenderWindow &win)
{
// Start game loop
while (win.isOpen())
{
// Process events
sf::Event Event;
while (win.pollEvent(Event))
{
// Close window : exit
if (Event.type == sf::Event::Closed)
win.close();
// A key has been pressed
if (Event.type == sf::Event::KeyPressed)
{
// Escape key : exit
if (Event.key.code == sf::Keyboard::Escape)
win.close();
}
}
win.clear();
player.input();
win.draw(*player.getCurrentRoom());
if (player.getCurrentRoom()->getEnemy()->getHealth())
{
player.getCurrentRoom()->getEnemy()->followPlayer();
win.draw(*player.getCurrentRoom()->getEnemy());
}
for (auto& r : player.getCurrentRoom()->getDoors()) win.draw(r.second.second);
win.draw(player);
win.display();
}
return EXIT_SUCCESS;
} | true |
6cc458ea76ef0e5c66a0b2d46b736ef046a8a5b9 | C++ | LybaFatimaNasir/DSA | /Binary Search.cpp | UTF-8 | 1,193 | 3.625 | 4 | [] | no_license | #include<iostream>
using namespace std;
const int SIZE = 5;
int BinarySearch(int *Arr, int elem, int low, int high);
int binarySearch(int *Arr, int elem, int low, int high);
int main()
{
//int size =5;
// << " Enter the size of array : " << endl;
//cin >> size;
int arr[SIZE];
int n ,BS;
cout << " Enter elements of arrayin sorted order :" << endl;
for (int i = 1; i <= SIZE; ++i)
{
cin >> arr[i];
}
cout << " Enter the element you want to find " << endl;
cin >> n;
BS=BinarySearch(arr, n, 0, SIZE);
if (BS ==-1)
{
cout << " Element not found !" << endl;
}
else
cout << " The elemnt " << n << " found at " << BS << endl;
system("pause");
return 0;
}
int BinarySearch(int *Arr, int elem, int low,int high)
{
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (elem == Arr[mid])
return mid;
if (elem < Arr[mid])
return binarySearch(Arr, elem, low, mid - 1);
else
return binarySearch(Arr, elem, mid + 1, high);
}
int binarySearch(int *Arr, int index, int low, int high)
{
for (int i = low; i < high; ++i)
{
if (Arr[i] == index)
{
return i;
}
}
} | true |
2351a8856ffdbd62e319fc304f4006d6a0d3226d | C++ | Ravino/ccpp | /Ivan/Ostrouhova/middleSq.cpp | UTF-8 | 984 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include <string>
int convertStrNumber (const char *fio) {
int f = (int) fio [0];
int i = (int) fio [1];
int o = (int) fio [2];
std:: string strNumber = "";
strNumber = strNumber + std:: to_string (f);
strNumber = strNumber + std:: to_string (i);
strNumber = strNumber + std:: to_string (o);
int number = stoi (strNumber);
return number;
}
long SQ (int number) {
long result = number * number;
return result;
}
int selectMiddleSQ (long numberSQ) {
std:: string strNumberSQ = std:: to_string (numberSQ);
char charMiddleNumberSQ [2] = {strNumberSQ [2], strNumberSQ [3]};
std:: string strMiddleNumberSQ = (const char*) charMiddleNumberSQ;
int result = stoi (strMiddleNumberSQ);
return result;
}
int main () {
int fio = convertStrNumber ("FRT");
long numberSQ = SQ (fio);
int middleNumberSQ = selectMiddleSQ (numberSQ);
std:: cout << "\n" << middleNumberSQ << "\n";
return 0;
}
| true |
0649e25ab7a92eb09bddf7e01e6440afca4b2fc9 | C++ | Nekhlyudov/algorithm | /leetcode/basic/395.cpp | UTF-8 | 798 | 2.578125 | 3 | [] | no_license | class Solution {
public:
int dfs(string &s,int l,int r,int k){
int mp[26];memset(mp,0,sizeof(mp));
for(int i=l;i<r;i++){
mp[s[i]-'a']++;
}
int spil=-1;
for(int i=0;i<26;i++){
if(mp[i]>0&&mp[i]<k){spil=i;break;}
}
if(spil==-1)return r-l;
int ll=l;
int ans=0;
while(ll<r){
while(ll<r&&s[ll]==('a'+spil)){
ll++;
}
if(ll==r)break;
int start=ll;
while(ll<r&&s[ll]!=(spil+'a')){
ll++;
}
ans=max(dfs(s,start,ll,k),ans);
}
return ans;
}
int longestSubstring(string s, int k) {
return dfs(s,0,(int)s.length(),k);
}
};
| true |
0be25e3858c6e69335ec67ef5775f18fcaa9318e | C++ | AritonV10/Exercises | /UVT/Fibo.cpp | UTF-8 | 474 | 3.28125 | 3 | [] | no_license | #include <iostream>
void fib_swap(int& a, int& b, int& c){
c = a + b; a = b; b = c;
}
bool func(const int* n, const int* _p){
int a = 0, b = 1, c = 0;
for(int i = 0; i <= *n; i++){
fib_swap(a, b, c);
if(c == *_p)
return true;
}
return false;
}
int main(){
int x = 30, f = 34;
int* _p = &x;
int* p_ = &f;
if(func(_p, p_))
std::cout<<"Is part of fibo";
else
std::cout<<"Not part of fibo";
}
| true |
5ced4faecb438e14980aadfdf3fb2ce85777c4b6 | C++ | gbrlas/AVSP | /CodeJamCrawler/dataset/09_17779_46.cpp | UTF-8 | 1,256 | 2.78125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
using namespace std;
typedef unsigned long ulong;
int numCases;
int d[10];
int main (int argc, char * const argv[])
{
if ( argc != 2 ) return -1;
ifstream fileIn(argv[1], ifstream::in);
if ( fileIn.good() == false ) return -1;
fileIn >> numCases;
for ( int caseIndex = 0; caseIndex < numCases; caseIndex++ )
{
cout << "Case #" << caseIndex + 1 << ": ";
char s[64];
fileIn >> s;
memset(d, 0, 10 * sizeof(int));
int slen = strlen(s);
for ( int i = 0; i < slen; i++ )
{
d[s[i] - '0']++;
}
bool largest = true;
for ( int i = 0; i < slen - 1; i++ )
{
if ( s[i] < s[i+1] )
{
largest = false;
break;
}
}
if ( largest )
{
int d2[10];
memcpy(d2, d, sizeof(int) * 10);
char small[64];
char * psmall = small;
int i = 1;
while ( d2[i] == 0 )
{
i++;
}
*psmall = i + '0';
psmall++;
d2[i]--;
d2[0]++;
for ( int j = 0; j < 10; j++ )
{
while ( d2[j] > 0 )
{
*psmall = j + '0';
psmall++;
d2[j]--;
}
}
*psmall = 0;
cout << small;
} else
{
//cout << "here";
next_permutation(s, s + slen);
cout << s;
}
cout << endl;
}
fileIn.close();
return 0;
}
| true |
185711184017a0ba608092d96d85b411e41efd5a | C++ | SeungHyeokJeon/image_processing | /163337_14_1/thresholding.cpp | UTF-8 | 1,674 | 3.125 | 3 | [] | no_license | #include "opencv2/opencv.hpp"
using namespace cv;
#include <iostream>
using namespace std;
int main()
{
int threshold_value = 127; //처음 추정치 T
int lowsum = 0, highsum = 0, lowcount = 0, highcount = 0;
int u1 = 0, u2 = 0;
Mat src, dst;
src = imread("image.jpg", IMREAD_GRAYSCALE);
cout << "threshold value : " << threshold_value << endl;
while (1)
{
for (int i = 0; i < src.rows; i++)
{
for (int j = 0; j < src.cols; j++)
{ //임계치를 기준으로 임계치보다 아래 화소면 low, 높으면 high로 구분
if (src.at<uchar>(i, j) < threshold_value)
{
lowsum += src.at<uchar>(i, j);
lowcount++;
}
else
{
highsum += src.at<uchar>(i, j);
highcount++;
}
}
}
//평균 임계값 u1과 u2가 더이상 변하지 않으면 빠져나옴
if (lowsum / lowcount == u1 && highsum / highcount == u2)
break;
else //그 외에는 새로운 임계값을 설정함
{
u1 = lowsum / lowcount;
u2 = highsum / highcount;
threshold_value = (u1 + u2) / 2.0f;
cout << "threshold value : " << threshold_value << endl;
lowsum = lowcount = highsum = highcount = 0;
}
}
threshold(src, dst, threshold_value, 255, THRESH_BINARY);
imshow("Original", src);
imshow("Thresholding", dst);
while (1)
{
int key = waitKey();
if (key == 'q')
return 0;
}
} | true |
fe7b971f1fd853a27141b66407bd0b573b4e80f3 | C++ | unWyse/cplusplus-samples | /09 - ShapesHierarchy/09 - ShapesHierarchy/Trapezoid.cpp | UTF-8 | 453 | 2.953125 | 3 | [
"MIT"
] | permissive | //Kyle Wyse
//22 March 2018
//8th: p 532 #12.8; Class Inheritance:
//TRAPEZOID
//This class includes a construtor for a trapezoid object which takes
//as parameters two Points and two lengths. It then calls the constructor
//from its superclass: Quadrilateral.
#include "Trapezoid.h"
Trapezoid::Trapezoid(Point p1, Point p2, int len1, int len2)
: Quadrilateral(p1, p2, Point(p2.getX()+len2, p2.getY()), Point(p1.getX()+len1, p1.getY())) { } | true |
74875bdfeeb3e9088ad158d4ddfd7451159269c8 | C++ | joelnb/nsis | /NSIS/tags/v212/Source/ShConstants.cpp | UTF-8 | 1,614 | 2.90625 | 3 | [] | no_license | #include "ShConstants.h"
ConstantsStringList::ConstantsStringList()
{
index = 0;
}
int ConstantsStringList::add(const char *name, int value1, int value2)
{
int pos=SortedStringListND<struct constantstring>::add(name);
if (pos == -1) return -1;
((struct constantstring*)gr.get())[pos].index = index;
((struct constantstring*)gr.get())[pos].pos = pos;
((struct constantstring*)gr.get())[pos].value1 = value1;
((struct constantstring*)gr.get())[pos].value2 = value2;
int temp = index;
index++;
return temp;
}
int ConstantsStringList::get(char *name, int n_chars /*= -1*/)
{
int v=SortedStringListND<struct constantstring>::find(name, n_chars);
if (v==-1) return -1;
return (((struct constantstring*)gr.get())[v].index);
}
int ConstantsStringList::getnum()
{
return index;
}
int ConstantsStringList::get_value1(int idx)
{
int pos=get_internal_idx(idx);
if (pos==-1) return -1;
return (((struct constantstring*)gr.get())[pos].value1);
}
int ConstantsStringList::get_value2(int idx)
{
int pos=get_internal_idx(idx);
if (pos==-1) return -1;
return (((struct constantstring*)gr.get())[pos].value2);
}
char* ConstantsStringList::idx2name(int idx)
{
int pos=get_internal_idx(idx);
if (pos==-1) return NULL;
struct constantstring *data=(struct constantstring *)gr.get();
return ((char*)strings.get() + data[pos].name);
}
int ConstantsStringList::get_internal_idx(int idx)
{
struct constantstring *data=(struct constantstring *)gr.get();
for (int i = 0; i < index; i++)
{
if (data[i].index == idx)
{
return i;
}
}
return -1;
}
| true |
b0ca8df01973b4295dc9afa3448d8c33eb4f1745 | C++ | shyamelc/Coding-PC | /Non Competetion/Matrix Chain Multiplication/main.cpp | UTF-8 | 868 | 2.921875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int n,i,j;
cin>>n;
int arr[n+1];
for(int i=1; i<=n; i++)
cin>>arr[i];
int matrix[n+1][n+1];
for(i=1; i<=n; i++)
for(j=1;j<=n; j++)
if(i==j)
matrix[i][j] = 0;
else
matrix[i][j] = 65000;
for(i=1; i<=n; i++)
for(j=i+1;j<=n; j++)
if(j-i==1)
{
matrix[i][j] = arr[i]*arr[i+1]*arr[i+2];
}
else
for(int k=i; k<j; k++)
{
cout<<i<<" "<<k<<" "<<j<<" "<<matrix[i][k]<<" "<<matrix[k+1][j]<<" "<<arr[i-1]*arr[k]*arr[j]<<endl;
int q = matrix[i][k] + matrix[k+1][j] + arr[i-1]*arr[k]*arr[j];
matrix[i][j] = min(matrix[i][j],q);
}
cout<<matrix[1][n];
return 0;
}
| true |
7499b99c13bc6f7031357db2406df4a9c6227674 | C++ | cies96035/CPP_programs | /UVA/已通過/uva11332.cpp | UTF-8 | 266 | 2.59375 | 3 | [] | no_license | #include<iostream>
using namespace std;
int N;
int f(int num)
{
int s=0;
while(num)
{
s+=num%10;
num/=10;
}
if(s>9)
return f(s);
return s;
}
int main()
{
cin.tie(0);
ios_base::sync_with_stdio(0);
while(cin>>N&&N)
cout<<f(N)<<'\n';
return 0;
}
| true |
4d88be479137eb53ed90fde4495d566ec7c92573 | C++ | diwadd/sport | /cf_even_odd_game.cpp | UTF-8 | 1,833 | 3.171875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
typedef unsigned long long int ulli;
typedef long double ld;
void left_just(string &s, int n, char c = ' ') {
while(s.length() < n) {
s = c + s;
}
}
template<typename T> void print_vector(vector<T> &vec) {
int n = vec.size();
for(int i = 0; i < n; i++) {
if(i == n - 1)
cout << vec[i];
else
cout << vec[i] << " ";
}
cout << "\n";
}
template<typename T> void print_matrix(vector<vector<T>> &mat) {
for(int i = 0; i < mat.size(); i++) {
print_vector(mat[i]);
}
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int T;
cin >> T;
for(int t = 0; t < T; t++) {
int N;
cin >> N;
vector<lli> a_vec(N, 0);
lli odd = 0;
lli even = 0;
for(int i = 0; i < N; i++) {
cin >> a_vec[i];
if(a_vec[i] % 2 == 0)
even++;
else
odd++;
}
sort(a_vec.rbegin(), a_vec.rend());
// print_vector(a_vec);
bool a_move = true;
lli score = 0;
for(int i = 0; i < N; i++) {
if(a_vec[i] % 2 == 0) {
if(a_move == true) {
score += a_vec[i];
a_move = false;
} else {
a_move = true;
}
} else {
if(a_move == false) {
score -= a_vec[i];
a_move = true;
} else {
a_move = false;
}
}
}
if(score > 0)
cout << "Alice\n";
else if (score == 0)
cout << "Tie\n";
else
cout << "Bob\n";
}
} | true |
81e6ccb1cece73da7e6eeedcb21c964ba33e3c60 | C++ | calmofthestorm/blif-verifier | /truthtable.cc | UTF-8 | 3,604 | 2.78125 | 3 | [] | no_license | #include "truthtable.h"
#include <cassert>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stack>
#include <string>
#include <unordered_map>
#include <vector>
#include "tokenizer.h"
using std::istream;
using std::istringstream;
using std::ostream;
using std::string;
using std::vector;
using std::unordered_set;
using std::unordered_map;
namespace blifverifier {
TruthTable::TruthTable()
: mKind(TTKind::INPUT) { }
bool TruthTable::isValidTTEntry(const string& line, int num_entries) {
if (num_entries != static_cast<int>(line.size())) {
return false;
}
for (const auto& c : line) {
if (c != TOKENS::ZERO && c != TOKENS::ONE && c != TOKENS::NC) {
return false;
}
}
return true;
}
TruthTable::TruthTable(Tokenizer::LineTokenReader& reader,
vector<int>&& inputs, TTKind kind)
: mInputs(inputs), mKind(kind) {
// Parse the truth table.
// Keep reading logic lines until we hit something else, and push it back.
while (reader.isGood()) {
auto tokens = reader.readLine();
// TODO: clean this.
if (tokens.size() == 1 && inputs.size() == 0 &&
(tokens[0][0] == TOKENS::ZERO || tokens[0][0] == TOKENS::ONE ||
tokens[0][0] == TOKENS::NC)) {
TruthTableEntry tte("", tokens[0][0]);
addEntry(tte);
} else if (tokens.size() == 2 &&
isValidTTEntry(tokens[0], inputs.size()) &&
tokens[0].size() == inputs.size() && tokens[1].size() == 1 &&
(tokens[1][0] == TOKENS::ZERO || tokens[1][0] == TOKENS::ONE ||
tokens[1][0] == TOKENS::NC)) {
// Is a valid logic line.
TruthTableEntry tte(tokens[0], tokens[1][0]);
addEntry(tte);
} else {
// Read a non-TT line. Push it back and finish.
reader.putBack(std::move(tokens));
return;
}
}
// should never get here.
assert(false);
}
TruthTableEntry::TruthTableEntry(const std::string& inputs, char output)
: mInputs(inputs), mOutput(output) { }
char TruthTableEntry::getOutput() const {
return mOutput;
}
// TODO: if BLIF truthtable contains a contradiction it will be resolved
// silently as true. This should raise an error as the file is illegal.
void TruthTableEntry::generateCode(
ostream& out,
const vector<int>& input_names,
const unordered_map<int, string>& nicknames) const {
out << "(";
for (decltype(mInputs)::size_type i = 0; i < mInputs.size(); ++i) {
if (mInputs[i] != TOKENS::NC) {
if (mInputs[i] == TOKENS::ZERO) {
out << "~";
}
// Abort if key not present.
out << nicknames.find(input_names[i])->second << " & ";
}
}
out << " -1)";
}
void TruthTable::generateCode(
int name, ostream& out,
const unordered_map<int, string>& nicknames) const {
if (mKind != TruthTable::TTKind::INPUT) {
if (mKind == TruthTable::TTKind::NORMAL) {
out << "size_t ";
}
// Abort if key not present.
out << nicknames.find(name)->second << " = ";
out << "(";
for (const auto& entry : mEntries) {
if (entry.getOutput() == TOKENS::ONE) {
entry.generateCode(out, mInputs, nicknames);
out << " | ";
}
}
out << " 0); // strategy: naive\n";
}
}
void TruthTable::addInput(int input) {
assert(mKind != TTKind::INPUT);
mInputs.push_back(input);
}
void TruthTable::addEntry(const TruthTableEntry& entry) {
assert(mKind != TTKind::INPUT);
mEntries.push_back(entry);
}
const vector<int>& TruthTable::getInputs() const {
return mInputs;
}
} // namespace blifverifier
| true |
5884cef7e9b6a585378e88bf28814418f1a929e8 | C++ | chenyangchenyang/ptcx | /decode.cpp | UTF-8 | 8,415 | 2.640625 | 3 | [
"BSD-2-Clause"
] | permissive |
#include "ptcx_internal.h"
void read_control_values(stream *input, PTCX_PIXEL_RANGE *range, const PTCX_FILE_HEADER &header)
{
if (BASE_PARAM_CHECK)
{
if (!input || input->is_empty())
{
base_post_error(BASE_ERROR_INVALIDARG);
}
}
switch (header.quant_control_bits)
{
case 16:
{
uint16 min_value = 0;
uint16 max_value = 0;
input->read_data(&min_value, 2);
input->read_data(&max_value, 2);
range->min_value[0] = ((min_value) & 0x1F) * 8;
range->min_value[1] = ((min_value >> 5) & 0x3F) * 4;
range->min_value[2] = ((min_value >> 11) & 0x1F) * 8;
range->max_value[0] = ((max_value) & 0x1F) * 8;
range->max_value[1] = ((max_value >> 5) & 0x3F) * 4;
range->max_value[2] = ((max_value >> 11) & 0x1F) * 8;
} break;
default: base_post_error(BASE_ERROR_EXECUTION_FAILURE);
};
}
status read_macroblock_table(stream *input, const PTCX_FILE_HEADER &header, std::vector<uint8> *output)
{
uint32 table_byte_size = (header.image_width / header.block_width) *
(header.image_height / header.block_height);
table_byte_size = (table_byte_size >> 2);
output->resize(table_byte_size);
if (table_byte_size != output->size())
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
if (base_failed(input->read_data(&((*output)[0]), table_byte_size)))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
return BASE_SUCCESS;
}
uint8 query_macroblock_shift(uint8 *input, uint32 x, uint32 width_in_blocks, uint32 y)
{
// The byte we must access is uiBlockIndex / 4, and the bits within that byte are defined by
// ( bits >> ( 2 * ( uiBlockIndex % 4 ) ) ) & 0x3.
uint32 block_index = y * width_in_blocks + x;
uint32 byte_index = block_index >> 2;
uint32 bit_data = 0;
bit_data = input[byte_index];
return (bit_data >> ((block_index % 4) << 1)) & 0x3;
}
status read_macroblock(stream *input, const PTCX_FILE_HEADER &header, uint32 start_x, uint32 start_y, image *output)
{
uint32 quant_step_count = 1 << header.quant_step_bits;
uint32 quant_step_mask = quant_step_count - 1;
uint8 quant_look_aside = 0;
VN_PTCX_PIXEL_RANGE range = {{255, 255, 255}, {0, 0, 0}};
// Read our control values from the stream, using the number of bits defined
// by our pandax file header structure.
read_control_values(input, &range, header);
int16 min_value[3] = {range.min_value[0], range.min_value[1], range.min_value[2]};
int16 max_value[3] = {range.max_value[0], range.max_value[1], range.max_value[2]};
int16 range_delta[3] = {max_value[0] - min_value[0], max_value[1] - min_value[1], max_value[2] - min_value[2]};
// Read our quantization table out to the image, using the number of bits (and
// thus steps) as defined by our ptcx file header structure.
for (uint32 subj = 0; subj < header.block_height; subj++)
for (uint32 subi = 0; subi < header.block_width; subi++)
{
uint32 linear_sub_index = subi + subj * header.block_width;
uint8 *dest_pixel = output->query_data() + output->query_block_offset(start_x + subi, start_y + subj);
// If we have an empty byte of data in our look aside buffer, read one in.
if (0 == ((header.quant_step_bits * linear_sub_index) % 8))
{
if (base_failed(input->read_data(&quant_look_aside, 1)))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
}
// Now we must simply pull a new quantization table value from our list. Note that
// we always remove from the least significant bits in order to ensure proper ordering
// with respect to the quantization operation.
uint32 step_value = (quant_look_aside & quant_step_mask);
quant_look_aside >>= header.quant_step_bits;
dest_pixel[0] = min_value[0] + range_delta[0] / quant_step_mask * step_value;
dest_pixel[1] = min_value[1] + range_delta[1] / quant_step_mask * step_value;
dest_pixel[2] = min_value[2] + range_delta[2] / quant_step_mask * step_value;
}
return BASE_SUCCESS;
}
status inverse_quantize(stream *input, const PTCX_FILE_HEADER &header, image *output)
{
std::vector<uint8> macroblock_table;
PTCX_FILE_HEADER temp_header = header;
// At the start of our file, just after our header, we have a quantization map that indicates a
// per-macro-block block shift. Each entry in our map is two bits, and we have one set of these
// bits for each macro block (defined as the block width * height in our header).
if (base_failed(read_macroblock_table(input, header, ¯oblock_table)))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
// Dequantize the data and place in our output buffer
for (uint32 j = 0; j < output->query_height(); j += header.block_height)
for (uint32 i = 0; i < output->query_width(); i += header.block_width)
{
// Query our micro-block size and proceed to decompress each micro-block
// within our larger macro-block. We grab our two bits and divide the
// supplied macroblock dimensions by that amount (down to a minimum of two).
uint8 macro_scale_bits = \
query_macroblock_shift(¯oblock_table[0], i / header.block_width,
header.image_width / header.block_width, j / header.block_height );
temp_header.block_width = header.block_width >> macro_scale_bits;
temp_header.block_height = header.block_height >> macro_scale_bits;
if (temp_header.block_width < 2) temp_header.block_width = 2;
if (temp_header.block_height < 2) temp_header.block_height = 2;
for (uint32 micro_j = 0; micro_j < (header.block_height / temp_header.block_height); micro_j++)
for (uint32 micro_i = 0; micro_i < (header.block_width / temp_header.block_width); micro_i++)
{
uint32 adjusted_i = i + micro_i * temp_header.block_width;
uint32 adjusted_j = j + micro_j * temp_header.block_height;
if (base_failed(read_macroblock(input, temp_header, adjusted_i, adjusted_j, output)))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
#if PTCX_SHOW_BLOCK_MAP
// Write out the block shift for the current microblock.
for (uint32 subj = 0; subj < temp_header.block_height; subj++)
for (uint32 subi = 0; subi < temp_header.block_width; subi++)
{
uint8 *dest_pixel = output->query_data() + output->query_block_offset(adjusted_i + subi, adjusted_j + subj);
dest_pixel[0] = (128 + macro_scale_bits * 32);
dest_pixel[1] = (64 + macro_scale_bits * 32);
dest_pixel[2] = (64 + macro_scale_bits * 32);
}
#endif
}
}
return BASE_SUCCESS;
}
status load_ptcx(stream *input, image *output)
{
uint32 bytes_read = 0;
PTCX_FILE_HEADER pxh = {0};
if (BASE_PARAM_CHECK)
{
if (!input || !output || input->is_empty())
{
return BASE_ERROR_INVALIDARG;
}
}
if (base_failed(input->read_data(&pxh, sizeof(PTCX_FILE_HEADER), &bytes_read)))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
if (bytes_read != sizeof(PTCX_FILE_HEADER))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
// Verify the integrity of our file
if (PTCX_MAGIC_VALUE != pxh.magic || sizeof(PTCX_FILE_HEADER) != pxh.header_size)
{
return base_post_error(BASE_ERROR_INVALID_RESOURCE);
}
if (2 != pxh.version)
{
return base_post_error( BASE_ERROR_INVALID_RESOURCE );
}
// Create our image as an RGB8 source.
if (base_failed(create_image(IGN_IMAGE_FORMAT_R8G8B8, pxh.image_width, pxh.image_height, output)))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
// Dequantize our image blob based on the header data.
if (base_failed(inverse_quantize(input, pxh, output)))
{
return base_post_error(BASE_ERROR_EXECUTION_FAILURE);
}
return BASE_SUCCESS;
}
| true |
2a84b32da9cf5550dede6b7212965b5a212150c9 | C++ | muris/projects | /InMemoryDatabase/AppManager.cpp | UTF-8 | 3,181 | 3.75 | 4 | [] | no_license | #include <stdio.h>
#include "RecordManager.h"
void Output(struct data *p);
int main()
{
printf("******************************************\n");
printf("* Record Manager Application *\n");
printf("* Xinyi He *\n");
printf("******************************************\n");
char c;
do
{
printf("\n");
printf("a. Open database\n");
printf("b. Get first record\n");
printf("c. Get next record \n");
printf("d. Get previous record\n");
printf("e. Get Nth record\n");
printf("f. Insert record\n");
printf("g. Bulk insert records in file\n");
printf("h. Delete record\n");
printf("i. Update record\n");
printf("j. Find record with first attribute value\n");
printf("k. Show catalog file\n");
printf("l. Get first page\n");
printf("m. Get next page\n");
printf("n. Show buf stats\n");
printf("o. Commit changes\n");
printf("p. Exit\n");
printf("Please press letter to choose an action.\n");
c = getchar();
fflush(stdin);
char filename[100];
switch (c)
{
//a. Open database
case 'a':
{
printf("Please input the database name (don't include extension): ");
gets(filename);
OpenStore(filename);
break;
}
//b. Get first record
case 'b':
{
Output(FirstRec());
break;
}
//c. Get next record
case 'c':
{
Output(NextRec());
break;
}
//d. Get previous record
case 'd':
{
Output(PriorRec());
break;
}
//e. Get Nth record
case 'e':
{
printf("\nInput N: ");
int n;
scanf("%d", &n);
Output(NRec(n));
fflush(stdin);
break;
}
//f. Insert record
case 'f':
{
printf("\nInput a comma-delimited Record:\n");
char statement[100];
scanf("%s", &statement);
fflush(stdin);
InsertRec(statement);
break;
}
//g. Bulk insert records in file
case 'g':
{
printf("\nInput the filename(include extension): ");
char file[100];
scanf("%s", &file);
InsertRecFromFile(file);
fflush(stdin);
break;
}
//h. Delete record
case 'h':
{
DeleteRec();
break;
}
//i. Update record
case 'i':
{
printf("\nInput a comma-delimited Record:\n");
char statement[100];
scanf("%s", &statement);
fflush(stdin);
UpdateRec(statement);
break;
}
//j. Find record with first attribute value
case 'j':
{
printf("\nInput value:\n");
char statement[100];
scanf("%s", &statement);
fflush(stdin);
SearchRec(statement);
break;
}
//k. Show catalog file
case 'k':
{
DisplyCatFile(filename);
break;
}
//l. Get first page
case 'l':
{
GetPage(0);
break;
}
//m. Get next page
case 'm':
{
GetPage(1);
break;
}
//n. Show buf stats
case 'n':
{
ShowBuf();
break;
}
//o. Commit changes
case 'o':
{
Commit(filename);
break;
}
//p. Exit
case 'p':
{
CloseStore(filename);
}
};
}while(c != 'p');
return 0;
}
void Output(struct data *p)
{
struct data *temp = p;
while (temp != NULL)
{
printf("%s\t", temp->record);
temp = temp->nextcolumndata;
}
printf("\n");
} | true |
adfa18d505eee4c5a88665591b83a0df9110028b | C++ | Rexagon/methodist | /app/models/CoursesListModel.cpp | UTF-8 | 1,824 | 3.296875 | 3 | [] | no_license | #include "CoursesListModel.h"
CoursesListModel::CoursesListModel(QObject* parent) :
QAbstractListModel(parent)
{
}
CoursesListModel::~CoursesListModel()
{
m_courses.clear();
}
void CoursesListModel::update()
{
std::stable_sort(m_courses.begin(), m_courses.end(), [](const std::unique_ptr<Course>& a, const std::unique_ptr<Course>& b) {
return a->getName() < b->getName();
});
emit layoutChanged();
}
int CoursesListModel::rowCount(const QModelIndex& parent) const
{
return m_courses.size();
}
QVariant CoursesListModel::data(const QModelIndex& index, int role) const
{
if (role == Qt::DisplayRole && index.row() < m_courses.size()) {
Course* course = m_courses[index.row()].get();
return course->getName();
}
return QVariant();
}
void CoursesListModel::addCourse(std::unique_ptr<Course> course)
{
m_courses.push_back(std::move(course));
update();
}
void CoursesListModel::removeCourse(const Course* course)
{
for (auto it = m_courses.begin(); it != m_courses.end(); ++it) {
if (it->get() == course) {
m_courses.erase(it);
update();
return;
}
}
}
void CoursesListModel::removeCourse(size_t n)
{
if (n < m_courses.size()) {
m_courses.erase(m_courses.begin() + n);
update();
}
}
Course* CoursesListModel::getCourse(size_t n) const
{
if (n < m_courses.size()) {
return m_courses[n].get();
}
return nullptr;
}
int CoursesListModel::getCourseIndex(const Course* course)
{
for (size_t i = 0; i < m_courses.size(); ++i) {
if (m_courses[i].get() == course) {
return static_cast<int>(i);
}
}
return -1;
}
size_t CoursesListModel::getCourseCount() const
{
return m_courses.size();
}
| true |
a2e4d12df1086d00cf3d3b1e3220e37de24a36b2 | C++ | nsubiron/mess-engine | /source/mess/engine/PlayerCredentials.h | UTF-8 | 792 | 3.046875 | 3 | [
"MIT"
] | permissive | #pragma once
#include "mess/NonCopyable.h"
#include "mess/engine/PlayerId.h"
#include <mutex>
#include <string>
namespace mess {
namespace engine {
class PlayerCredentials : private NonCopyable {
public:
PlayerCredentials(PlayerId id, std::string username)
: _id(id),
_username(std::move(username)) {}
PlayerId player_id() const {
return _id;
}
std::string username() const {
std::lock_guard<std::mutex> lock(_mutex);
return _username;
}
void ChangeUsername(std::string username) {
std::lock_guard<std::mutex> lock(_mutex);
_username = std::move(username);
}
private:
mutable std::mutex _mutex;
const PlayerId _id;
std::string _username;
};
} // namespace engine
} // namespace mess
| true |
bd62ecaaf5ca06b3d4ed82da69d04f79488050c4 | C++ | jinkyongpark/practicealgorithm | /Code/swea_홈방범서비스v2.cpp | UTF-8 | 1,413 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include<algorithm>
using namespace std;
const int MAX = 30;
int T, d,w,k,ans;
int film[MAX][MAX], tmpfilm[MAX][MAX];
pair<int,int> cell[MAX];
int drugcnt;
void performanceCheck() {
for (int r = 0; r < d; r++)
for (int c = 0; c < w; c++)
tmpfilm[r][c] = film[r][c];
for (int i = 0; i < drugcnt; i++) {
int rownum = cell[i].first, medicine = cell[i].second;
for (int c = 0; c < w; c++)
tmpfilm[rownum][c] = medicine;
}
for (int c = 0; c < w; c++) {
int point = tmpfilm[0][c];
int cnt = 1;
for (int r = 1; r < d; r++) {
if (point == tmpfilm[r][c]) {
cnt++;
if (cnt >= k) break;
}
else {
point = tmpfilm[r][c];
cnt = 1;
}
}
if (cnt < k) return;
}
ans = min(ans, drugcnt);
}
void insertDrug(int idx,int sidx ) {
if (ans < k) return;
if (idx >= drugcnt) {
performanceCheck();
return;
}
for (int i = sidx; i < d; i++) {
cell[idx] = make_pair(i,0); //이렇게 체크말고 약 투입하고 RECOVER하는게 더 좋다.
insertDrug(idx + 1, i + 1);
cell[idx] = make_pair(i,1);
insertDrug(idx + 1, i + 1);
}
}
int main() {
cin >> T;
for (int t = 1; t <= T; t++) {
cin >> d>>w>>k;
for (int r = 0; r < d; r++)
for (int c = 0; c < w; c++)
cin >> film[r][c];
ans = k;
for (drugcnt= 0; drugcnt < k; drugcnt++) {
insertDrug(0,0);
if (ans < k) break;
}
cout << "#" << t << " " << ans << endl;
}
return 0;
}
| true |
6be23181f207991aab20d17c3e99143fb37d4d67 | C++ | pfaltynek/advent-of-code-2018-cpp | /day22/main.cpp | UTF-8 | 6,802 | 2.625 | 3 | [] | no_license | #include "./../common/aoc.hpp"
#include "./../common/coord.hpp"
#include <queue>
#include <regex>
#define TEST 1
const std::regex depth_regex("^depth: (\\d+)$");
const std::regex target_regex("^target: (\\d+),(\\d+)$");
typedef enum AREA_TYPE { rocky = 0, wet = 1, narrow = 2 } area_type_t;
typedef enum TOOL_TYPE { torch = 1, climbing_gear = 2, neither = 0 } tool_type_t;
typedef struct PATH_INFO {
coord_str coord;
int32_t time;
tool_type_t tool;
} path_info_str;
class AoC2018_day22 : public AoC {
protected:
bool init(const std::vector<std::string> lines);
bool part1();
bool part2();
void tests();
int32_t get_aoc_day();
int32_t get_aoc_year();
private:
int32_t get_risk_level();
int32_t find_path();
int64_t get_geologic_index(int32_t x, int32_t y);
int64_t get_geologic_index(coord_str coord);
int32_t get_erosion_level(int64_t geo_idx);
area_type_t get_area_type(int32_t erosion_lvl);
std::vector<path_info_str> get_next_steps(path_info_str from);
int32_t depth_;
coord_str target_;
std::map<coord_str, int64_t> cache_;
std::map<coord_str, area_type_t> map_;
std::map<coord_str, std::vector<path_info_str>> step_cache_;
};
bool AoC2018_day22::init(const std::vector<std::string> lines) {
std::smatch sm;
if (lines.size() < 2) {
std::cout << "Incomplete input data" << std::endl;
return false;
}
if (std::regex_match(lines[0], sm, depth_regex)) {
depth_ = stoi(sm.str(1));
} else {
std::cout << "Invalid input - missing depth data" << std::endl;
return false;
}
if (std::regex_match(lines[1], sm, target_regex)) {
target_.x = stoi(sm.str(1));
target_.y = stoi(sm.str(2));
} else {
std::cout << "Invalid input - missing target data" << std::endl;
return false;
}
return true;
}
int64_t AoC2018_day22::get_geologic_index(int32_t x, int32_t y) {
if ((x == target_.x) && (y == target_.y)) {
return 0;
}
if (x == 0) {
return y * 48271;
}
if (y == 0) {
return x * 16807;
}
return cache_[coord_str(x, y - 1)] * cache_[coord_str(x - 1, y)];
}
int64_t AoC2018_day22::get_geologic_index(coord_str coord) {
return get_geologic_index(coord.x, coord.y);
}
int32_t AoC2018_day22::get_erosion_level(int64_t geo_idx) {
return (geo_idx + depth_) % 20183;
}
area_type_t AoC2018_day22::get_area_type(int32_t erosion_lvl) {
return static_cast<area_type_t>(erosion_lvl % 3);
}
int32_t AoC2018_day22::get_risk_level() {
int32_t result = 0, size, el;
std::map<coord_str, int64_t> cache;
coord_str pt;
int64_t gi;
area_type_t at;
cache_.clear();
cache.clear();
cache_[coord_str(0, 0)] = get_erosion_level(0);
result += get_area_type(get_erosion_level(get_geologic_index(0, 0)));
size = target_.x + target_.y;
size = size * 11 / 10;
for (int32_t i = 1; i <= size; ++i) {
for (int32_t j = 0; j <= i; j++) {
pt = {j, i - j};
gi = get_geologic_index(pt);
el = get_erosion_level(gi);
cache[pt] = el;
at = get_area_type(el);
map_[pt] = at;
if ((pt.x <= target_.x) && (pt.y <= target_.y)) {
result += at;
}
}
cache.swap(cache_);
cache.clear();
}
cache_.clear();
return result;
}
std::vector<path_info_str> AoC2018_day22::get_next_steps(const path_info_str from) {
std::vector<path_info_str> result = {};
path_info_str next;
std::vector<coord_str> adjacents = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
std::string direction = "DRLU";
for (uint32_t i = 0; i < adjacents.size(); i++) {
next = from;
next.coord = next.coord + adjacents[i];
if (!map_.count(next.coord)) {
continue;
}
next.time++;
switch (map_[next.coord]) {
case rocky:
switch (next.tool) {
case torch:
case climbing_gear:
result.push_back(next);
break;
case neither:
break;
}
break;
case wet:
switch (next.tool) {
case neither:
case climbing_gear:
result.push_back(next);
break;
case torch:
break;
}
break;
case narrow:
switch (next.tool) {
case torch:
case neither:
result.push_back(next);
break;
case climbing_gear:
break;
}
break;
}
}
next = from;
next.time += 7;
switch (map_[from.coord]) {
case rocky:
switch (from.tool) {
case torch:
next.tool = climbing_gear;
result.push_back(next);
break;
case climbing_gear:
next.tool = torch;
result.push_back(next);
break;
case neither:
break;
}
break;
case wet:
switch (from.tool) {
case neither:
next.tool = climbing_gear;
result.push_back(next);
break;
case climbing_gear:
next.tool = neither;
result.push_back(next);
break;
case torch:
break;
}
break;
case narrow:
switch (from.tool) {
case torch:
next.tool = neither;
result.push_back(next);
break;
case neither:
next.tool = torch;
result.push_back(next);
break;
case climbing_gear:
break;
}
break;
}
step_cache_[from.coord] = result;
return result;
}
int32_t AoC2018_day22::find_path() {
std::map<coord_str, std::map<tool_type_t, int32_t>> history = {};
std::queue<path_info_str> q = {};
path_info_str pi, npi;
coord_str pt = {};
int32_t result = INT32_MAX;
std::vector<path_info_str> next;
std::vector<std::string> paths = {};
history[pt][torch] = 0;
history[pt][neither] = 0;
history[pt][climbing_gear] = 0;
pi.coord = pt;
pi.time = 0;
pi.tool = torch;
q.emplace(pi);
while (!q.empty()) {
pi = q.front();
q.pop();
next = get_next_steps(pi);
for (uint32_t i = 0; i < next.size(); i++) {
if ((next[i].coord == target_) && (next[i].tool == torch)) {
if (result > next[i].time) {
result = next[i].time;
}
continue;
}
if (next[i].time > result) {
continue;
}
if (history.count(next[i].coord)) {
if (history[next[i].coord].count(next[i].tool)) {
if (next[i].time < history[next[i].coord][next[i].tool]) {
history[next[i].coord][next[i].tool] = next[i].time;
q.emplace(next[i]);
}
} else {
history[next[i].coord][next[i].tool] = next[i].time;
q.emplace(next[i]);
}
} else {
history[next[i].coord][next[i].tool] = next[i].time;
q.emplace(next[i]);
}
}
}
return result;
}
int32_t AoC2018_day22::get_aoc_day() {
return 22;
}
int32_t AoC2018_day22::get_aoc_year() {
return 2018;
}
void AoC2018_day22::tests() {
#if TEST
init({"depth: 510", "target: 10,10"});
part1(); // 114
part2(); // 45
#endif
}
bool AoC2018_day22::part1() {
int32_t result1;
result1 = get_risk_level();
result1_ = std::to_string(result1);
return true;
}
bool AoC2018_day22::part2() {
int32_t result2;
result2 = find_path();
result2_ = std::to_string(result2);
return true;
}
int main(void) {
AoC2018_day22 day22;
return day22.main_execution();
}
| true |
2c9d9a21eeba512a8e9dbe359bd31fc525fd6460 | C++ | liinumaria/habitare2017 | /habitare2017.ino | UTF-8 | 8,332 | 2.640625 | 3 | [] | no_license | #include <SPI.h> // SPI library
#include <SdFat.h> // SDFat Library
#include <SFEMP3Shield.h> // Mp3 Shield Library
SdFat sd; // Create object to handle SD functions
SFEMP3Shield MP3player; // Create Mp3 library object
// These variables are used in the MP3 initialization to set up
// some stereo options:
const uint8_t VOLUME = 10; // MP3 Player volume 0=max, 255=lowest (off)
const uint8_t SILENT = 254; // MP3 Player volume 0=max, 255=lowest (off)
const uint16_t monoMode = 1; // Mono setting 0=off, 3=max
// Pins
const int ledPin = 5;
const int pirPins[] = {A0, A1, A2, A3};
const int PIR_SENSOR_COUNT = 4;
const int MOVEMENT_THRESHOLD = 1; // How many pirPins need to be HIGH to signal movement
// States
const int STATE_OFF = 0;
const int STATE_STARTING = 1;
const int STATE_ON = 2;
const int STATE_STOPPING = 3;
const unsigned long STARTING_TIMEOUT = 10 * 1000LU; // Duration of STARTING state: 10 seconds
const unsigned long ON_TIMEOUT = 5 * 60 * 1000LU; // Max duration of ON state: 5 minutes
const unsigned long NO_MOVEMENT_TIMEOUT = 1*60*1000LU; // ON state ends in this time if no movement: 1 minute
const unsigned long STOPPING_TIMEOUT = 15 * 1000LU; // Duration of STOPPING state: 15 seconds
const unsigned long CALIBRATION_TIME = 30 * 1000LU; // Time to wait in the beginning
int state = STATE_OFF;
int subState = 0;
unsigned long stateStartTime = 0;
unsigned long elapsed = 0;
unsigned long lastMovementSeenAt = 0;
int currentTrack = 1;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
pinMode(ledPin, OUTPUT);
for (int i=0; i < PIR_SENSOR_COUNT; i++) {
pinMode(pirPins[i], INPUT);
}
Serial.println("Initializing SD card and MP3 player...");
initSD(); // Initialize the SD card
initMP3Player(); // Initialize the MP3 Shield
// PIR calibration period
for (int i=0; i<CALIBRATION_TIME; i+=1000) {
leds((i/1000 % 2) * 255);
delay(1000);
}
}
// initSD() initializes the SD card and checks for an error.
void initSD()
{
//Initialize the SdCard.
if(!sd.begin(SD_SEL, SPI_FULL_SPEED)) // was: SPI_HALF_SPEED
sd.initErrorHalt();
if(!sd.chdir("/"))
sd.errorHalt("sd.chdir");
}
// initMP3Player() sets up all of the initialization for the
// MP3 Player Shield. It runs the begin() function, checks
// for errors, applies a patch if found, and sets the volume/
// stero mode.
void initMP3Player()
{
uint8_t result = MP3player.begin(); // init the mp3 player shield
if(result != 0 && result != 6) // check result, see readme for error codes.
{
Serial.print("Error calling MP3player.begin(): ");
Serial.println(result);
}
MP3player.setVolume(VOLUME, VOLUME);
MP3player.setMonoMode(monoMode);
}
boolean isMovement() {
int count = 0;
for (int i=0; i < PIR_SENSOR_COUNT; i++) {
if (digitalRead(pirPins[i]) == HIGH) {
Serial.print(pirPins[i]);
Serial.print(", ");
count++;
}
}
if (count > 0) {
Serial.println("");
}
return count >= MOVEMENT_THRESHOLD;
}
boolean movementReported = false;
void loop() {
boolean movement = isMovement();
unsigned long now = millis();
elapsed = now - stateStartTime;
if (movement) {
lastMovementSeenAt = now;
// Wait for no movement before printing the message again
if (!movementReported) {
Serial.println("Movement!");
movementReported = true;
}
} else if (movementReported) {
movementReported = false;
}
// State transitions
if (state == STATE_OFF && movement) {
setState(STATE_STARTING, now);
} else if (state == STATE_STARTING && elapsed > STARTING_TIMEOUT) {
// Little silent period before going full ON
MP3player.stopTrack();
leds(0);
delay(2000);
now = millis();
toTrack(3);
setState(STATE_ON, now);
startAnimation(VOLUME, VOLUME, 0, 255, 5000, now);
lastMovementSeenAt = now;
} else if (state == STATE_ON && (elapsed > ON_TIMEOUT || now - lastMovementSeenAt > NO_MOVEMENT_TIMEOUT)) {
if (now - lastMovementSeenAt > NO_MOVEMENT_TIMEOUT) {
Serial.println("No movement seen in a while, stopping...");
} else {
Serial.println("Reached timeout for ON state, stopping...");
}
setState(STATE_STOPPING, now);
} else if (state == STATE_STOPPING && elapsed > STOPPING_TIMEOUT) {
toTrack(1);
setState(STATE_OFF, now);
}
// LED effects
if (state == STATE_OFF) {
toTrack(1);
if (subState == 0 && isAnimationFinished(now)) {
startAnimation(VOLUME, VOLUME, 0, 0, random(15 * 1000), now);
subState = 1;
} else if (subState == 1 && isAnimationFinished(now)) {
int power = random(10, 127);
startAnimation(VOLUME, VOLUME, power, power, random(50, 200), now);
subState = 0;
}
} else if (state == STATE_STARTING) {
if (subState == 0) {
// Fade out sound
startAnimation(VOLUME, SILENT, 0, 0, 2000, now);
subState = 1;
} else if (subState == 1 && isAnimationFinished(now)) {
// Silence a few seconds
MP3player.stopTrack();
toTrack(2);
delay(500);
now = millis();
subState = 2;
} else if (subState == 2 && isAnimationFinished(now)) {
double at = ((double) elapsed) / STARTING_TIMEOUT;
int maxTime = 2000 - (int)(at*2000);
startAnimation(SILENT, SILENT, 0, 0, random(maxTime), now);
subState = 3;
} else if (subState == 3 && isAnimationFinished(now)) {
startAnimation(VOLUME, VOLUME, 255, 255, random(50, 200), now);
subState = 2;
}
} else if (state == STATE_ON) {
toTrack(3);
// Make sure the leds are set to full power in the end of animation
if (isAnimationFinished(now)) {
leds(255);
}
} else if (state == STATE_STOPPING) {
if (subState == 0 && isAnimationFinished(now)) {
double at = ((double) elapsed) / STARTING_TIMEOUT;
int maxTime = 3000 - (int)(at*3000);
startAnimation(VOLUME, VOLUME, 255, 255, random(maxTime), now);
subState = 1;
} else if (subState == 1 && isAnimationFinished(now)) {
startAnimation(VOLUME, VOLUME, 0, 0, random(50, 200), now);
subState = 0;
}
}
animate(now);
}
void setState(int newState, unsigned long now) {
state = newState;
subState = 0;
stateStartTime = now;
elapsed = 0;
stopAnimation();
}
void toTrack(int number) {
if (currentTrack != number || !MP3player.isPlaying()) {
MP3player.stopTrack();
/* Use the playTrack function to play a numbered track: */
currentTrack = number;
uint8_t result = MP3player.playTrack(currentTrack);
if (result == 0) // playTrack() returns 0 on success
{
Serial.print("Playing track ");
Serial.println(currentTrack);
}
else // Otherwise there's an error, check the code
{
Serial.print("Error playing track: ");
Serial.println(result);
}
}
}
void leds(int amount) {
analogWrite(ledPin, amount);
digitalWrite(LED_BUILTIN, amount > 127 ? 1 : 0);
}
// State variables for the animation
unsigned long animationStartTime = 0;
unsigned long animationEndTime = 0;
unsigned long animationDuration = 0;
int animationVolumeStart;
int animationVolumeDelta;
int animationLedStart;
int animationLedDelta;
void startAnimation(int volumeStart, int volumeEnd, int ledStart, int ledEnd, unsigned long duration, unsigned long startTime) {
animationVolumeStart = volumeStart;
animationVolumeDelta = volumeEnd - volumeStart;
animationLedStart = ledStart;
animationLedDelta = ledEnd - ledStart;
animationDuration = duration;
animationStartTime = startTime;
animationEndTime = startTime + duration;
}
void stopAnimation() {
animationEndTime = 0;
}
void animate(unsigned long now) {
if (!isAnimationFinished(now)) {
double atRatio = ((double)(now - animationStartTime))/(double)animationDuration;
int vol = animationVolumeStart + (int)(atRatio * animationVolumeDelta);
int light = animationLedStart + (int)(atRatio * animationLedDelta);
MP3player.setVolume(vol, vol);
leds(light);
/*
Serial.print("Animation is at ");
Serial.print(atRatio);
Serial.print(", volume: ");
Serial.print(vol);
Serial.print(", leds: ");
Serial.println(light);
*/
}
}
boolean isAnimationFinished(unsigned long now) {
return now > animationEndTime;
}
| true |
8c3dc1a1df64dcc04b19ce7cdc810b78172ec039 | C++ | yuan95/Projects | /appTest/stl/remove_copy.cpp | UTF-8 | 471 | 3.640625 | 4 | [] | no_license | // remove_copy example
#include<iostream> // std::cout
#include<algorithm> // std::remove_copy
#include<vector> // std::vector
int main(){
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> myvector(8);
std::remove_copy(myints, myints+8, myvector.begin(), 20);
std::cout << "myvector contains:";
for(std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << std::endl;
return 0;
}
| true |
8c5eeaaf785967f6a995c62d228a52794ca90d9c | C++ | jschmidt42/stingray-html5 | /stingray_sdk/plugin_foundation/stream.h | UTF-8 | 3,265 | 3.25 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include "array.h"
#include <string.h>
namespace stingray_plugin_foundation {
// Functions for treating a Array<char> or a char * as a memory stream that can be written to
// and read from.
namespace stream {
// Packs the data in t to the stream.
template <class T> void pack(char *&v, const T &t)
{
memmove(v, &t, sizeof(T));
v += sizeof(T);
}
// Packs the data in t to the stream, resizing it if necessary.
template <class T> void pack(Array<char> &v, const T &t)
{
v.resize(v.size() + sizeof(T));
memmove(&v[0] + v.size() - sizeof(T), &t, sizeof(T));
}
// Patches already packed data at the specified location.
template <class T> void patch(char *&v, const T &t)
{
memmove(v, &t, sizeof(T));
v += sizeof(T);
}
// Patches already packed data at the specified offset.
template <class T> void patch(Array<char> &v, unsigned &offset, const T &t)
{
memmove(&v[0] + offset, &t, sizeof(T));
offset += sizeof(T);
}
// Packs `count` bytes from `p` to the stream.
inline void pack_bytes(char *&v, const void *p, unsigned count)
{
memmove(v, p, count);
v += count;
}
// Packs `count` bytes from `p` to the stream, resizing it if necessary.
inline void pack_bytes(Array<char> &v, const void *p, unsigned count)
{
v.resize(v.size() + count);
memmove(&v[0] + v.size() - count, p, count);
}
// Packs `count` zero bytes to the stream.
inline void pack_zeroes(char *&v, unsigned count)
{
memset(v, 0, count);
v += count;
}
// Packs `count` zero bytes to the stream, resizing it if necessary.
inline void pack_zeroes(Array<char> &v, unsigned count)
{
v.resize(v.size() + count);
memset(&v[0] + v.size() - count, 0, count);
}
// Aligns the stream to the specified alignment.
inline void pack_align(Array<char> &v, unsigned align) {
while (v.size() % align != 0)
v.push_back(0);
}
// Unpacks an object of type T from the stream and returns it. The stream
// pointer is advanced to the next object. Note that since this operation
// only casts the pointer, it can have alignment problems if objects in the
// stream are not aligned. To unpack potentially unaligned objects, use the
// call unpack(stream, t) instead.
template <class T> const T &unpack(const char *&stream)
{
const T* t = (const T *)stream;
stream += sizeof(T);
return *t;
}
template <class T> T &unpack(char *&stream)
{
T* t = (T *)stream;
stream += sizeof(T);
return *t;
}
// Unpacks an object of type T from the stream into the varaible t.
template <class T> void unpack(const char *&stream, T &t)
{
memmove(&t, stream, sizeof(T));
stream += sizeof(T);
}
template <class T> void unpack(char *&stream, T &t)
{
memmove(&t, stream, sizeof(T));
stream += sizeof(T);
}
// Unpacks count raw bytes from the stream into `p` and returns them.
// The stream pionter is advanced to beyond the bytes.
inline void unpack_bytes(char *&stream, void *p, unsigned count)
{
memmove(p, stream, count);
stream += count;
}
// Aligns the stream to the specified alignment.
inline void unpack_align(char *&stream, unsigned align)
{
unsigned skip = (align - (uintptr_t)stream % align) % align;
stream += skip;
}
} // namespace stream
} // namespace stingray_plugin_foundation
| true |
14a8041e49c4271bacf1a67c4447b7233cd1f253 | C++ | Evalir/Algorithms | /Problems/Local19/a.cpp | UTF-8 | 902 | 2.6875 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <set>
#include <map>
#include <queue>
using namespace std;
// DONT USE SCANF !!!!!!!!
int n, l;
string s;
string pattern;
vector<vector<int>> adj(1010);
long long ans = 0;
void selectNode(int u, int p, int curpos) {
if (s[u] != pattern[curpos])
return;
if (curpos == (l - 1)) {
ans++;
return;
}
for(auto &v : adj[u]) {
if (v != p)
selectNode(v, u, curpos + 1);
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> l;
cin >> s >> pattern;
for(int u = 0; u < n - 1; u++) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for(int i = 0; i < n; i++) {
selectNode(i, -1, 0);
}
cout << ans << endl;
return 0;
}
| true |
88b8d00861d4ae6d0cb28af6265a25632ba2fbb3 | C++ | shahidul-brur/OnlineJudge-Solution | /UVa/11483.cpp | UTF-8 | 797 | 2.59375 | 3 | [] | no_license | //Accepted
#include <stdio.h>
#include<string.h>
int main()
{
freopen("11483.txt", "r", stdin);
int n, i, c=1, len, j;
char input[110];
while(scanf("%d\n",&n) && n!=0)
{
printf("Case %d:\n",c);
printf("#include<string.h>\n#include<stdio.h>\nint main()\n{\n");
for(i=1;i<=n;i++)
{
gets(input);
len=strlen(input);
printf("printf(\"");
for(j=0;j<len;j++)
{
if(input[j]=='"' || input[j]=='\\')
{
printf("\\");
}
printf("%c",input[j]);
}
printf("\\n\");");
printf("\n");
}
printf("printf(\"\\n\");\nreturn 0;\n}\n");
c++;
}
return 0;
}
| true |
eceb84d38ccad44ea050bf426fb5f45c360ac137 | C++ | semerdzhiev/oop-2020-21 | /cs-2-practical/14-virtual-destructors-and-exercise/virtual-destructors/main.cpp | UTF-8 | 805 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <vector>
class Base
{
public:
Base() { std::cout << "Base: Constructor\n"; }
virtual ~Base() { std::cout << "Base: Destructor\n"; }
virtual void test() { std::cout << "base\n"; }
};
class Derived : public Base
{
int *arr;
public:
Derived()
{
arr = new int[5];
std::cout << "Derived: Constructor\n";
}
~Derived()
{
delete[] arr;
std::cout << "Derived: Destructor\n";
}
void test() { std::cout << "der\n"; }
};
int main()
{
Base *base = new Base();
delete base;
std::cout << "---------------------\n";
Derived *derived = new Derived();
delete derived;
std::cout << "---------------------\n";
Base *poly = new Derived();
poly->test();
delete poly;
return 0;
} | true |
a032a5339b0fcc56e548cc243b13cc0d9a33357b | C++ | JasonLin6086/leetcode | /MergeTwoSortedLists/solution.cpp | UTF-8 | 1,279 | 3.46875 | 3 | [
"MIT"
] | permissive | /*
* solution.cpp
*
* Created on: Sep 14, 2016
* Author: jason
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int x) : data(x), next(NULL) {}
};
class Solution {
public:
Node* Merge (Node* head1, Node* head2) {
Node* dummy = new Node(0);
Node* current = dummy;
while (head1 && head2) {
if (head1->data < head2->data) {
current->next = head1;
head1 = head1->next;
} else {
current->next = head2;
head2 = head2->next;
}
current = current->next;
}
if (head1) {
current->next = head1;
}
if (head2) {
current->next = head2;
}
return dummy->next;
}
};
int main()
{
Node* l1 = new Node(0);
l1->next = new Node(2);
l1->next->next = new Node(4);
Node* l2 = new Node(2);
l2->next = new Node(3);
l2->next->next = new Node(5);
Solution s;
Node * result = s.Merge(l1, l2);
while (result != NULL) {
cout<<result->data<<(result->next ? "," : "");
result = result->next;
}
cout<<endl;
}
| true |
117f8047313de34e4a92caf8324308504f53da6c | C++ | Hengle/HFSM2 | /include/hfsm2/detail/shared/bit_array.hpp | UTF-8 | 2,803 | 2.546875 | 3 | [
"MIT"
] | permissive | #pragma once
namespace hfsm2 {
namespace detail {
////////////////////////////////////////////////////////////////////////////////
struct Units {
ShortIndex unit;
ShortIndex width;
};
//------------------------------------------------------------------------------
template <typename TIndex, ShortIndex NCapacity>
class BitArray final {
public:
using Index = TIndex;
using Unit = unsigned char;
static constexpr Index CAPACITY = NCapacity;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class Bits {
template <typename, ShortIndex>
friend class BitArray;
private:
HFSM_INLINE explicit Bits(Unit* const storage,
const Index width)
: _storage{storage}
, _width{width}
{}
public:
HFSM_INLINE explicit operator bool() const;
HFSM_INLINE void clear();
template <ShortIndex NIndex>
HFSM_INLINE bool get() const;
template <ShortIndex NIndex>
HFSM_INLINE void set();
template <ShortIndex NIndex>
HFSM_INLINE void reset();
HFSM_INLINE bool get (const Index index) const;
HFSM_INLINE void set (const Index index);
HFSM_INLINE void reset(const Index index);
private:
Unit* const _storage;
const Index _width;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class ConstBits {
template <typename, ShortIndex>
friend class BitArray;
private:
HFSM_INLINE explicit ConstBits(const Unit* const storage,
const Index width)
: _storage{storage}
, _width{width}
{}
public:
HFSM_INLINE explicit operator bool() const;
template <ShortIndex NIndex>
HFSM_INLINE bool get() const;
HFSM_INLINE bool get(const Index index) const;
private:
const Unit* const _storage;
const Index _width;
};
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
public:
BitArray() {
clear();
}
HFSM_INLINE void clear();
template <ShortIndex NIndex>
HFSM_INLINE bool get() const;
template <ShortIndex NIndex>
HFSM_INLINE void set();
template <ShortIndex NIndex>
HFSM_INLINE void reset();
HFSM_INLINE bool get (const Index index) const;
HFSM_INLINE void set (const Index index);
HFSM_INLINE void reset(const Index index);
template <ShortIndex NUnit, ShortIndex NWidth>
HFSM_INLINE Bits bits();
template <ShortIndex NUnit, ShortIndex NWidth>
HFSM_INLINE ConstBits bits() const;
HFSM_INLINE Bits bits(const Units& units);
HFSM_INLINE ConstBits bits(const Units& units) const;
private:
Unit _storage[CAPACITY];
};
//------------------------------------------------------------------------------
template <typename TIndex>
class BitArray<TIndex, 0> final {
public:
HFSM_INLINE void clear() {}
};
////////////////////////////////////////////////////////////////////////////////
}
}
#include "bit_array.inl"
| true |
2c5e0f42ca9430d6420e278720ecceae6fddb777 | C++ | sicaaa/wtd-2017 | /arduino/wtd_2017_red_thermochromatic.ino | UTF-8 | 4,692 | 2.515625 | 3 | [
"MIT"
] | permissive | /*
ESP8266 MQTT example for controlling thermochromatic material.
(c) 2017 Team R.E.D. @ Cybus WTD Hackathon
This sketch demonstrates the capabilities of the pubsub library in combination
with the ESP8266 board/library and some simple control logic to ensure appropriate
behaviour of thermochromatic material.
To handle the hackathon use case with thermochromatic textiles appropriately
we need to trigger the "on" signal once (heat-up) and reset (cool-down)
immediately for some seconds to avoid unwanted physical effects and
to be able to cool down the thermochromatic material as fast as possible.
This needs to be created non-blocking, so we use simple duration checks
and accept another "on"-state only after the time required to cool down.
It connects to an MQTT server then:
- publishes the "connnection state" to a topic every every two seconds
- subscribes to a device-specific alert topic accepting 1 or 0 for an active or disabled alert state.
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Parameters for Wifi and MQTT Broker
const char* ssid = "..."; // WLAN-SSID
const char* password = "..."; // WLAN Passwort
const char* mqtt_server = "..."; // IP des MQTT-Servers
const char* mqtt_username = "...";
const char* mqtt_password = "...";
const String topicPrefix = "io/cybus/energie-campus/red/";
// Parameters for device control
const String deviceId = "0324"; //String(random(0xffff), HEX);
const long delaySignalCheck = 3000;
const long delayOnState = 2000;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
bool acceptNewSignals = false;
long lastSignalCheck = 0;
long lastOnSignalCheck = 0;
char lastSignal = '0';
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
// Trigger state switch in main loop if a 1 was received as first character
lastSignal = (char)payload[0];
if (lastSignal != '0') {
lastSignal = '1'; // normalize to '1', if values != '0' are set
}
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str(), "wtd17.red.thermo", "thermored")) {
Serial.println("connected");
// Once connected, publish an state sginal...
String connectStatusTopic = topicPrefix;
connectStatusTopic.concat(deviceId);
connectStatusTopic.concat("/connected");
client.publish(connectStatusTopic.c_str(), "smart device connected.");
// subscribe to an alert topic to control the smart device
String alertTopic = topicPrefix;
alertTopic.concat(deviceId);
alertTopic.concat("/alert");
client.subscribe(alertTopic.c_str());
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(D2, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastOnSignalCheck > delaySignalCheck) {
acceptNewSignals = true;
}
if (now - lastSignalCheck > delayOnState) {
lastSignalCheck = now;
if (acceptNewSignals == false || lastSignal == '0') {
digitalWrite(D2, LOW);
} else if (acceptNewSignals == true && lastSignal == '1') {
// signal 1, start delay
lastOnSignalCheck = now;
acceptNewSignals = false;
digitalWrite(D2, HIGH); // reset this after 1 second at the latest
}
}
if (now - lastMsg > 2000) {
lastMsg = now;
++value;
snprintf (msg, 75, "smart device connected #%ld", value);
Serial.print("Publish message: ");
Serial.println(msg);
}
}
| true |
473c92ef9bba157be99d7a3492d9bd70283ef2c0 | C++ | fmadrid/LeetCode | /LongestSubstringWithoutRepeatingCharacters/main.cpp | UTF-8 | 1,180 | 3.125 | 3 | [] | no_license | #include <string>
#include <cstring>
#include<iostream>
#include <algorithm>
#include<vector>
#include<map>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int len = s.length();
vector<char> cArr(len);
for(int i = 0; i < len; i++)
cArr[i] = s[i];
vector<int> lastSeen(26, -1);
int score = 0;
for(int i = 0; i < len; i++) {
char c = cArr[i];
cout << "Checking: " << c << "\n";
if(lastSeen[c - 'a'] == -1) {
cout << c << " never seen.\n";
score++;
lastSeen[c - 'a'] = i;
} else {
cout << c << " last seen at " << lastSeen[c-'a'] << "\n";;
lastSeen[c-'a'] = i;
cout << "\tLastSeen: ";
for(int n : lastSeen)
cout << n << " ";
for(int j = 0; j < 26; j++) {
if(lastSeen[j] == -1) score = i;
else score = (score >= i - lastSeen[j]) ? score : i - lastSeen[j];
}
}
cout << "Current Score: " << score << "\n\n";
}
return score;
}
};
int main() {
Solution s;
string str = "abcabcbb";
cout << s.lengthOfLongestSubstring(str);
return 0;
} | true |
5712fdcbace35c376b9da9b11aadf620d2afdd94 | C++ | alexandraback/datacollection | /solutions_5751500831719424_1/C++/alikhtarov/a.cpp | UTF-8 | 1,368 | 3.109375 | 3 | [] | no_license | #include <cassert>
#include <iostream>
#include <unordered_set>
#include <vector>
using namespace std;
using vi = vector<int>;
using vvi = vector<vi>;
vi count(const string& s) {
vi out;
size_t i = 0, j = 0;
while (i < s.size()) {
while (j < s.size() && s[j] == s[i]) ++j;
out.push_back(j - i);
i = j;
}
return out;
}
string canon(const string& s) {
string out;
size_t i = 0, j = 0;
while (i < s.size()) {
out.push_back(s[i]);
while (j < s.size() && s[j] == s[i]) ++j;
i = j;
}
return out;
}
int solve(const vi& v) {
int best = 1000000;
for (auto t : v) {
int sol = 0;
for (auto x : v) {
sol += abs(x - t);
}
best = min(best, sol);
}
return best;
}
int main() {
int ncases;
cin >> ncases;
for (int ncase = 1; ncase <= ncases; ++ncase) {
int n;
cin >> n;
vvi sv;
unordered_set<string> sc;
string s;
for (int i = 0; i < n && cin >> s; ++i) {
sv.push_back(count(s));
sc.insert(canon(s));
}
cout << "Case #" << ncase << ": ";
if (sc.size() > 1) {
cout << "Fegla Won" << endl;
} else {
int ans = 0;
for (size_t i = 0; i < sv[0].size(); ++i) {
vi v;
for (size_t j = 0; j < sv.size(); ++j) {
assert(i < sv[j].size());
v.push_back(sv[j][i]);
}
ans += solve(v);
}
cout << ans << endl;
}
}
}
| true |
40e2a2b71755bf14f0bb01c808ac1c3622ebe2f0 | C++ | RITIK627/codeforces | /Optimal Point on a Line.cpp | UTF-8 | 569 | 2.703125 | 3 | [] | no_license | #include<iostream>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
long long dis(long long a[], long long n,long long k){
long long i,sum=0;
for(i=0;i<n;i++){
sum += abs(a[i]-k);
}
return sum;
}
int main(){
long long n,i,one,two;
cin>>n;
long long a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
one = dis(a,n,a[n/2]);
two = dis(a,n,a[(n/2)-1]);
if(n%2==0){
if(one>=two){
cout<<a[(n/2)-1];
}
else{
cout<<a[n/2];
}
}
else{
cout<<a[n/2];
}
return 0;
}
| true |