text
stringlengths 8
6.88M
|
|---|
#include <iostream>
#include <vector>
using namespace std;
int partition(vector<int>& A, int left, int right, int who) {
for (int i=left; i<right; ++i) {
if (A[i] <= who) {
swap(A[i], A[left]);
left ++;
}
}
return left - 1;
}
void quicksort(vector<int>& A, int left, int right) {
if (left >= right) return;
int middle = left + (right - left) / 2;
swap(A[middle], A[left]);
int who = A[left];
int left_temp = left + 1;
for (int i=left_temp; i<right; ++i) {
if (A[i] <= who) {
swap(A[i], A[left_temp]);
left_temp ++;
}
}
int midpoint = left_temp - 1;
static int iter = 0;
cout << "Iteration " << iter << ": ";
for (int i=0; i<A.size(); ++i) {
cout << A[i] << " ";
}
cout << endl;
iter++;
swap(A[left], A[midpoint]);
quicksort(A, left, midpoint);
quicksort(A, midpoint + 1, right);
}
int main ()
{
int elements[] = {1, 12, 2, 2, 2, 6, 20, 22};
vector<int> A(elements, elements + 8);
quicksort(A, 0, A.size());
for (int i=0; i<A.size(); ++i) {
cout << A[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
|
/**
* A simple defragmentation program for a simulated file system.
*/
#include "Kernel.h"
#include "DirectoryEntry.h"
#include "Stat.h"
#include <stdlib.h>
#include <string.h>
#define BUF_SIZE 4096
#define OUTPUT_MODE 0700
int main(int argc, char ** argv)
{
char PROGRAM_NAME[8];
strcpy(PROGRAM_NAME, "defrag");
// initialize the file system simulator kernel
if(Kernel::initialize() == false)
{
cout << "Failed to initialized Kernel" << endl;
Kernel::exit(1);
}
// print a helpful message if no command line arguments are given
if(argc != 1)
{
cout << PROGRAM_NAME << ": usage: " << PROGRAM_NAME << endl;
Kernel::exit( 1 ) ;
}
int status = Kernel::defrag();
if(status == EXIT_FAILURE)
{
cout << "Error in defrag" << endl;
return EXIT_FAILURE;
}
Kernel::exit(0);
}
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup" -*- */
#include "core/pch.h"
#include "modules/ecmascript/carakan/src/es_pch.h"
#include "modules/ecmascript/carakan/src/kernel/es_box.h"
#include "modules/ecmascript/carakan/src/util/es_hash_table.h"
static inline unsigned doubleHash (unsigned key)
{
key = ~key + (key >> 23);
key ^= (key << 12);
key ^= (key >> 7);
key ^= (key << 2);
key ^= (key >> 20);
return key;
}
#define DECLARE() unsigned index = hash, jump = 1 | doubleHash (hash);
#define NEXT() index += jump;
#define TOMB_MARKER 0xFFFFFFFF
#define FREE_MARKER 0xFFFFFFFE
static unsigned ComputeSize(unsigned size)
{
unsigned candidate_size = 4;
while (candidate_size < size)
candidate_size *= 2;
return candidate_size;
}
/* static */
ES_Identifier_Array *ES_Identifier_Array::Make(ES_Context *context, unsigned size, unsigned nused)
{
ES_Identifier_Array *array;
GC_ALLOCATE_WITH_EXTRA(context, array, (size - 1) * sizeof(JString *), ES_Identifier_Array, (array, nused));
return array;
}
/* static */
void ES_Identifier_Array::Initialize(ES_Identifier_Array *array, unsigned nused)
{
array->InitGCTag(GCTAG_ES_Identifier_Array);
array->nused = nused;
}
/* static */
ES_IdentifierCell_Array *ES_IdentifierCell_Array::Make(ES_Context *context, unsigned size)
{
ES_IdentifierCell_Array *array;
GC_ALLOCATE_WITH_EXTRA(context, array, (size - 1) * sizeof(Cell), ES_IdentifierCell_Array, (array, size));
return array;
}
/* static */
void ES_IdentifierCell_Array::Initialize(ES_IdentifierCell_Array *array, unsigned size)
{
array->InitGCTag(GCTAG_ES_IdentifierCell_Array);
array->size = size;
}
/* JString_Hash_List */
/* static */
ES_Identifier_List *ES_Identifier_List::Make(ES_Context *context, unsigned size)
{
ES_Identifier_List *list;
GC_ALLOCATE(context, list, ES_Identifier_List, (list));
ES_CollectorLock gclock(context);
size = ComputeSize(size);
list->indices = ES_Box::Make(context, size * sizeof(unsigned));
list->identifiers = ES_Identifier_Array::Make(context, size);
list->nallocated = size;
unsigned *hashed = reinterpret_cast<unsigned*>(list->indices->Unbox());
JString **identifiers = list->GetIdentifiers();
for (unsigned i = 0; i < list->Allocated(); ++i)
{
hashed[i] = FREE_MARKER;
identifiers[i] = NULL;
}
return list;
}
/* static */ void
ES_Identifier_List::Free(ES_Context *context, ES_Identifier_List *list)
{
ES_Heap *heap = context->heap;
heap->Free(list->indices);
heap->Free(list->identifiers);
heap->Free(list);
}
BOOL ES_Identifier_List::AppendL(ES_Context *context, JString *element, unsigned &position, BOOL hide_existing)
{
OP_ASSERT(element != NULL);
restart:
unsigned hash = element->Hash(), mask = Allocated() - 1;
DECLARE();
unsigned *candidate = NULL;
unsigned *hashed = reinterpret_cast<unsigned*>(indices->Unbox());
JString **keys = GetIdentifiers();
while (TRUE)
{
unsigned &entry = hashed[index & mask];
if (entry == FREE_MARKER)
{
add:
if (4 * Used() >= 3 * Allocated())
{
ResizeL(context);
goto restart;
}
if (!candidate)
candidate = &entry;
*candidate = position = Used();
keys[Used()] = element;
++Used();
return TRUE;
}
else if (!keys[entry])
candidate = &entry;
else if (keys[entry] == element || keys[entry]->Equals(element))
if (hide_existing)
{
/* Use the already existing identifier to ensure that a pointer
comparison is enough to compare them. ResizeL depend on this
fact later. */
element = keys[entry];
candidate = &entry;
goto add;
}
else
{
position = entry;
return FALSE;
}
NEXT();
}
}
void ES_Identifier_List::AppendAtIndexL(ES_Context *context, JString *element, unsigned index, unsigned &position)
{
unsigned *hashed = reinterpret_cast<unsigned *>(indices->Unbox());
JString **keys = GetIdentifiers();
OP_ASSERT(hashed[index] == FREE_MARKER);
if (4 * Used() < 3 * Allocated())
{
hashed[index] = Used();
keys[Used()] = element;
position = Used()++;
}
else
AppendL(context, element, position);
}
BOOL ES_Identifier_List::IndexOf(JString *element, unsigned &i)
{
OP_ASSERT(element != NULL);
unsigned hash = element->Hash(), mask = Allocated() - 1;
DECLARE();
unsigned *hashed = reinterpret_cast<unsigned *>(indices->Unbox());
JString **keys = GetIdentifiers();
while (TRUE)
{
unsigned &entry = hashed[index & mask];
if (entry == FREE_MARKER)
{
i = index & mask;
return FALSE;
}
else if (keys[entry] == element || keys[entry] && keys[entry]->hash == hash && keys[entry]->Equals(element))
{
i = entry;
return TRUE;
}
NEXT();
}
return FALSE;
}
BOOL ES_Identifier_List::Lookup(unsigned index, JString *&element)
{
if (index >= Used())
return FALSE;
element = GetIdentifiers()[index];
return TRUE;
}
JString *ES_Identifier_List::FindOrFindPositionFor(JString *element, unsigned &index)
{
if (IndexOf(element, index))
return GetIdentifiers()[index];
return NULL;
}
static void CopyIdentifiers(JString **target, JString **source, unsigned count)
{
op_memcpy(target, source, count * sizeof(*target));
}
ES_Identifier_List *ES_Identifier_List::CopyL(ES_Context *context)
{
ES_Identifier_List *new_copy = ES_Identifier_List::Make(context, Allocated());
op_memcpy(new_copy->indices->Unbox(), indices->Unbox(), Allocated() * sizeof(unsigned));
CopyIdentifiers(new_copy->GetIdentifiers(), GetIdentifiers(), Used());
new_copy->Used() = Used();
return new_copy;
}
ES_Identifier_List *ES_Identifier_List::CopyL(ES_Context *context, unsigned count)
{
OP_ASSERT(count <= Used());
ES_Identifier_List *new_copy = ES_Identifier_List::Make(context, Allocated());
CopyIdentifiers(new_copy->GetIdentifiers(), GetIdentifiers(), count);
new_copy->Used() = count;
new_copy->Rehash();
return new_copy;
}
/* static */
void ES_Identifier_List::Initialize(ES_Identifier_List *list)
{
list->InitGCTag(GCTAG_ES_Identifier_List);
list->indices = NULL;
list->identifiers = NULL;
}
void ES_Identifier_List::ResizeL(ES_Context *context)
{
unsigned nused = Used();
unsigned new_nallocated = nallocated;
while (4 * nused >= 3 * new_nallocated)
new_nallocated *= 2;
while (4 * nused < new_nallocated)
new_nallocated /= 2;
ES_Box *new_indices = ES_Box::Make(context, new_nallocated * sizeof(unsigned));
ES_CollectorLock gclock(context);
ES_Identifier_Array *new_identifiers = ES_Identifier_Array::Make(context, new_nallocated, Used());
JString **new_idents = new_identifiers->identifiers;
CopyIdentifiers(new_idents, GetIdentifiers(), Used());
unsigned *new_hashed_indices = reinterpret_cast<unsigned *>(new_indices->Unbox());
for (unsigned i = 0; i < new_nallocated; ++i)
new_hashed_indices[i] = FREE_MARKER;
JString **item = new_idents;
for (unsigned added = 0; added < nused; ++added, ++item)
{
// *item == NULL will allow us to handle Remove() in a mutable version
if (*item == NULL)
continue;
unsigned hash = (*item)->Hash(), mask = new_nallocated - 1;
DECLARE();
while (TRUE)
{
unsigned &entry = new_hashed_indices[index & mask];
if (entry == FREE_MARKER || new_idents[entry] == *item)
{
entry = added;
break;
}
NEXT();
}
}
ES_Heap *heap = context->heap;
heap->Free(indices);
heap->Free(identifiers);
indices = new_indices;
identifiers = new_identifiers;
nallocated = new_nallocated;
return;
}
void ES_Identifier_List::Rehash()
{
JString **identifiers = GetIdentifiers(), **item = identifiers;
unsigned nused = Used();
unsigned nallocated = Allocated();
Used() = 0;
unsigned *hashed_indices = reinterpret_cast<unsigned *>(indices->Unbox());
for (unsigned i = 0; i < nallocated; ++i)
hashed_indices[i] = FREE_MARKER;
for (unsigned added = 0; added < nused; ++added, ++item)
{
if (*item == NULL)
continue;
unsigned hash = (*item)->Hash(), mask = nallocated - 1;
DECLARE();
while (TRUE)
{
unsigned &entry = hashed_indices[index & mask];
if (entry == FREE_MARKER)
{
unsigned new_index = Used()++;
entry = new_index;
identifiers[new_index] = *item;
break;
}
OP_ASSERT(identifiers[entry] != *item);
NEXT();
}
}
}
/* ES_Identifier_Mutable_List */
void ES_Identifier_Mutable_List::Remove(unsigned index)
{
OP_ASSERT(index < Used());
JString **identifiers = GetIdentifiers();
identifiers[index] = NULL;
}
void ES_Identifier_Mutable_List::RemoveLast(unsigned remove_index)
{
OP_ASSERT(remove_index == (Used() - 1));
JString **identifiers = GetIdentifiers();
unsigned nallocated = Allocated();
unsigned *hashed_indices = reinterpret_cast<unsigned *>(indices->Unbox());
unsigned hash = identifiers[remove_index]->Hash(), mask = nallocated - 1;
DECLARE();
while (TRUE)
{
unsigned &entry = hashed_indices[index & mask];
if (entry == remove_index)
{
entry = FREE_MARKER;
--Used();
break;
}
NEXT();
}
identifiers[remove_index] = NULL;
}
/* ES_Identifier_Hash_Table */
ES_Identifier_Hash_Table *ES_Identifier_Hash_Table::Make(ES_Context *context, unsigned size)
{
ES_Identifier_Hash_Table *table;
GC_ALLOCATE(context, table, ES_Identifier_Hash_Table, (table));
ES_CollectorLock gclock(context);
size = ComputeSize(size);
table->cells = ES_IdentifierCell_Array::Make(context, size);
op_memset(table->cells->cells, 0, size * sizeof(ES_IdentifierCell_Array::Cell));
#ifdef DEBUG_ENABLE_OPASSERT
for (unsigned i = 0; i < size; ++i)
{
OP_ASSERT(table->cells->cells[i].key == NULL);
}
#endif
return table;
}
void ES_Identifier_Hash_Table::Initialize(ES_Identifier_Hash_Table *table)
{
table->InitGCTag(GCTAG_ES_Identifier_Hash_Table);
table->nused = 0;
table->ndeleted = 0;
table->cells = NULL;
}
/* static */ void
ES_Identifier_Hash_Table::Free(ES_Context *context, ES_Identifier_Hash_Table *table)
{
ES_Heap *heap = context->heap;
heap->Free(table->cells);
heap->Free(table);
}
BOOL ES_Identifier_Hash_Table::AddL(ES_Context *context, JString *key, unsigned value, unsigned key_extra_bits)
{
restart:
unsigned hash = key->Hash(), nallocated = cells->size, mask = nallocated - 1;
ES_HASH_UPDATE(hash, key_extra_bits);
DECLARE();
ES_IdentifierCell_Array::Cell *candidate = 0;
ES_IdentifierCell_Array::Cell *hashed = (ES_IdentifierCell_Array::Cell *) cells->cells;
while (TRUE)
{
ES_IdentifierCell_Array::Cell &entry = hashed[index & mask];
if (entry.key == NULL && entry.value != TOMB_MARKER)
{
if (!candidate)
{
if (4 * (nused + ndeleted) >= 3 * nallocated)
{
ResizeL(context);
goto restart;
}
candidate = &entry;
}
else
{
--ndeleted;
}
++nused;
candidate->key = key;
candidate->value = value;
candidate->key_fragment = key_extra_bits;
return TRUE;
}
else if (entry.key == NULL && entry.value == TOMB_MARKER && !candidate)
candidate = &entry;
else if ((entry.key == key || entry.key->Equals(key)) && entry.key_fragment == key_extra_bits)
return FALSE;
NEXT();
}
}
BOOL ES_Identifier_Hash_Table::Contains(JString *key, unsigned extra_bits)
{
unsigned value;
return Find(key, value, extra_bits);
}
BOOL ES_Identifier_Hash_Table::Find(JString *key, unsigned &value, unsigned key_extra_bits)
{
unsigned hash = key->Hash(), mask = cells->size - 1;
ES_HASH_UPDATE(hash, key_extra_bits);
DECLARE();
ES_IdentifierCell_Array::Cell *hashed = (ES_IdentifierCell_Array::Cell *) cells->cells;
while (TRUE)
{
ES_IdentifierCell_Array::Cell &entry = hashed[index & mask];
if (entry.key == NULL && entry.value != TOMB_MARKER)
return FALSE;
if ((entry.key == key || entry.key->Equals(key)) && entry.key_fragment == key_extra_bits)
{
value = entry.value;
return TRUE;
}
NEXT();
}
return FALSE;
}
BOOL ES_Identifier_Hash_Table::Remove(JString *key, unsigned &value, unsigned key_extra_bits)
{
unsigned hash = key->Hash(), mask = cells->size - 1;
ES_HASH_UPDATE(hash, key_extra_bits);
DECLARE();
ES_IdentifierCell_Array::Cell *hashed = (ES_IdentifierCell_Array::Cell *) cells->cells;
while (TRUE)
{
ES_IdentifierCell_Array::Cell &entry = hashed[index & mask];
if (entry.key == NULL && entry.value != TOMB_MARKER)
return FALSE;
else if ((entry.key == key || entry.key->Equals(key)) && entry.key_fragment == key_extra_bits)
{
value = entry.value;
entry.key = NULL;
entry.value = TOMB_MARKER;
entry.value = 0;
--nused;
++ndeleted;
return TRUE;
}
NEXT();
}
}
BOOL ES_Identifier_Hash_Table::Remove(JString *key, unsigned key_extra_bits)
{
unsigned value;
return Remove(key, value, key_extra_bits);
}
void ES_Identifier_Hash_Table::ResizeL(ES_Context *context)
{
unsigned nallocated = cells->size;
while (4 * nused >= 3 * nallocated)
nallocated *= 2;
while (4 * nused < nallocated)
nallocated /= 2;
ES_IdentifierCell_Array *new_cells = ES_IdentifierCell_Array::Make(context, nallocated);
ES_IdentifierCell_Array::Cell *new_hashed = new_cells->cells;
for (unsigned i = 0; i < nallocated; ++i)
{
new_hashed[i].key = NULL;
new_hashed[i].value = 0;
new_hashed[i].key_fragment = 0;
}
ES_IdentifierCell_Array::Cell *item = cells->cells;
for (unsigned added = 0; added < nused; ++added)
{
while (item->key == NULL)
++item;
unsigned hash = item->key->Hash(), mask = nallocated - 1;
if (item->key_fragment)
ES_HASH_UPDATE(hash, item->key_fragment);
DECLARE();
while (TRUE)
{
ES_IdentifierCell_Array::Cell &entry = new_hashed[index & mask];
if (entry.key == NULL)
{
entry.key = item->key;
entry.value = item->value;
entry.key_fragment = item->key_fragment;
item++;
break;
}
NEXT();
}
}
op_memset(cells->cells, 0, cells->size * sizeof(ES_IdentifierCell_Array::Cell));
cells = new_cells;
ndeleted = 0;
return;
}
ES_Identifier_Hash_Table *ES_Identifier_Hash_Table::CopyL(ES_Context *context)
{
ES_Identifier_Hash_Table *table = ES_Identifier_Hash_Table::Make(context, cells->size);
table->nused = nused;
table->ndeleted = ndeleted;
op_memcpy(table->cells->cells, cells->cells, cells->size * sizeof(ES_IdentifierCell_Array::Cell));
return table;
}
/* ES_Identifier_Boxed_Hash_Table */
ES_Identifier_Boxed_Hash_Table *ES_Identifier_Boxed_Hash_Table::Make(ES_Context *context, unsigned size)
{
ES_Identifier_Boxed_Hash_Table *self;
GC_ALLOCATE(context, self, ES_Identifier_Boxed_Hash_Table, (self));
ES_CollectorLock gclock(context);
size = ComputeSize(size);
self->array = ES_Boxed_Array::Make(context, size, 0);
self->cells = ES_IdentifierCell_Array::Make(context, size);
op_memset(self->cells->cells, 0, size * sizeof(ES_IdentifierCell_Array::Cell));
#ifdef DEBUG_ENABLE_OPASSERT
for (unsigned i = 0; i < size; ++i)
{
OP_ASSERT(self->cells->cells[i].key == NULL);
}
#endif
return self;
}
void ES_Identifier_Boxed_Hash_Table::Initialize(ES_Identifier_Boxed_Hash_Table *table)
{
ES_Identifier_Hash_Table::Initialize(table);
table->ChangeGCTag(GCTAG_ES_Identifier_Boxed_Hash_Table);
}
BOOL ES_Identifier_Boxed_Hash_Table::AddL(ES_Context *context, JString *key, unsigned key_extra_bits, ES_Boxed *value)
{
if (ES_Identifier_Hash_Table::AddL(context, key, array->nused, key_extra_bits))
{
if (!(array->nused < array->nslots))
array = ES_Boxed_Array::Grow(context, array);
ES_Boxed *&storage = array->slots[array->nused++];
storage = value;
return TRUE;
}
return FALSE;
}
BOOL ES_Identifier_Boxed_Hash_Table::Find(JString *key, unsigned key_extra_bits, ES_Boxed *&value)
{
unsigned index;
if (ES_Identifier_Hash_Table::Find(key, index, key_extra_bits))
{
value = array->slots[index];
return TRUE;
}
return FALSE;
}
BOOL ES_Identifier_Boxed_Hash_Table::FindLocation(JString *key, unsigned key_extra_bits, ES_Boxed **&value)
{
unsigned index;
if (ES_Identifier_Hash_Table::Find(key, index, key_extra_bits))
{
value = &array->slots[index];
return TRUE;
}
return FALSE;
}
#undef DECLARE
#undef NEXT
#undef TOMB_MARKER
#undef FREE_MARKER
|
#include "PropSystem.h"
static PropSystem* _propSystem = NULL;
PropInfo::PropInfo(const rapidjson::Value &json)
{
m_propNumber = json["ID"].GetInt();
m_iconNumber = json["Icon"].GetInt();
m_avatarNumber = json["AvatarID"].GetInt();
m_propName = json["Name"].GetString();
m_propType = json["Type"].GetInt();
m_depict = json["Depict"].GetString();
m_levelRequirements = json["Nlevel"].GetInt();
m_attackRequirements = json["Nattack"].GetInt();
m_magicRequirements = json["Nmaige"].GetInt();
m_taoismRequirements = json["Ntaoism"].GetInt();
m_gender = json["Gender"].GetInt();
m_lasting = json["Lasting"].GetInt();
m_weight = json["Weight"].GetInt();
m_specialRequirements = json["Nspecial"].GetInt();
m_coin = json["Coin"].GetInt();
m_accurate = json["Accurate"].GetInt();
m_dodge = json["Dodge"].GetInt();
m_magicDodge = json["Mdodge"].GetInt();
m_defenseMax = json["MaxDefense"].GetInt();
m_defenseMin = json["MinDefense"].GetInt();
m_magicDefenseMax = json["MaxMDefense"].GetInt();
m_magicDefenseMin = json["MinMDefense"].GetInt();
m_attackMax = json["MaxAttack"].GetInt();
m_attackMin = json["MinAttack"].GetInt();
m_magicMax = json["MaxMaige"].GetInt();
m_magicMin = json["MinMaige"].GetInt();
m_taoismMax = json["MaxTaoism"].GetInt();
m_taoismMin = json["MinTaoism"].GetInt();
m_lucky = json["Lucky"].GetInt();
m_SE = json["SE"].GetInt();
m_JS = json["JS"].GetInt();
}
PropInfo::~PropInfo()
{
}
PropSystem* PropSystem::sharePropSystem()
{
if (_propSystem == NULL)
{
_propSystem = new PropSystem();
}
return _propSystem;
}
PropSystem::PropSystem()
{
//CSJson::Reader reader;
//CSJson::Value json;
rapidjson::Document json;
string file = FileUtils::getInstance()->fullPathForFilename("game_data/prop_info.json");
CCString* filePath = CCString::createWithContentsOfFile(file.c_str());
CCAssert(filePath, "file is open fail!");
json.Parse<0>(filePath->getCString());
if (json.HasParseError())
{
log("PropSystem GetParseError %s\n",json.GetParseError());
}
int nArrayCount = json.Size();
for (int i=0; i<nArrayCount; i++)
{
const rapidjson::Value &ArrayJson = json[i];
this->addPropInfo(ArrayJson);
}
}
PropSystem::~PropSystem()
{
map<unsigned int, PropInfo*>::iterator itr;
for (itr=m_propMap.begin(); itr!=m_propMap.end(); itr++)
{
delete itr->second;
m_propMap.erase(itr);
}
_propSystem = NULL;
}
void PropSystem::addPropInfo(const rapidjson::Value &json)
{
PropInfo* _propInfo = new PropInfo(json);
unsigned int key = _propInfo->getPropNumber();
m_propMap[key] = _propInfo;
}
PropInfo* PropSystem::getPropInfo(const unsigned int propID)
{
if (_propSystem == NULL)
{
PropSystem::sharePropSystem();
}
map<unsigned int, PropInfo*>::iterator itr;
itr = _propSystem->m_propMap.find(propID);
if (itr != _propSystem->m_propMap.end())
{
return (*itr).second;
}
return NULL;
}
|
//---------------------------------------------------------------------------
#ifndef shortcutsH
#define shortcutsH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ComCtrls.hpp>
#include <Menus.hpp>
//---------------------------------------------------------------------------
class TShortCutsFrm : public TForm
{
__published: // IDE-managed Components
TListView *ShortCutsListView;
void __fastcall FormClose(TObject *Sender, TCloseAction &Action);
private: // User declarations
public: // User declarations
__fastcall TShortCutsFrm(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TShortCutsFrm *ShortCutsFrm;
//---------------------------------------------------------------------------
#endif
|
#ifndef FILE_IO_H
#define FILE_IO_H
#include "Common.h"
#include "SupportVectorMachine.h"
#include "Feature.h"
#include "Detection.h"
void saveToFile(const std::string &filename, const SupportVectorMachine &svm);
void loadFromFile(const std::string &filename, SupportVectorMachine &svm);
void saveToFile(const std::string &filename, const std::vector<Detection> &dets);
#endif // FILE_IO_H
|
// File: key.cpp
// Written by Joshua Green
#include "shared/fileio/fileio.h"
#include "shared/db/db.h"
#include "shared/str/str.h"
#include <vector>
#include <map>
#include <string>
#include <iostream>
#include <process.h>
#include <windows.h>
using namespace std;
const column TRANS_DATE_COL = column("date", 30);
const column TRANS_TYPE_COL = column("type", 30);
const column TRANS_DESC_COL = column("description", 75);
const column TRANS_AMOUNT_COL = column("amount", 30);
const column TRANS_GRP_NAME_COL = column("name", 50);
const column TRANS_GRP_DESC_COL = column("description", 75);
const string TRANSACTION_MARKER = "<!-- end isLoc or isFdr if statement -->";
const string END_TRANSACTION_MARKER = "<!-- end for loop -->";
map<float, string> pie;
int _argc;
char** _argv;
void glbranch(void*);
struct transaction {
string date, type, raw_description, description;
float amount;
row to_row() const {
return row().add(TRANS_DATE_COL, date).add(TRANS_TYPE_COL, type).add(TRANS_DESC_COL, description).add(TRANS_AMOUNT_COL, ftos(amount));
}
};
transaction get_transaction(fileio&);
string strip_whitespace(const string&);
string format_desc(const string&, int words=3);
int main(int argc, char** argv) {
_argc = argc;
_argv = argv;
fileio data;
database db;
db.initialize("KeyBank");
table* TRANSACTIONS = db.get_table("transactions");
table* TRANSACTION_GROUPS = db.get_table("transaction_groups");
if (TRANSACTIONS == 0) {
cout << "Creating transaction table...";
TRANSACTIONS = db.add_table("transactions");
TRANSACTIONS->add_column(TRANS_DATE_COL);
TRANSACTIONS->add_column(TRANS_TYPE_COL);
TRANSACTIONS->add_column(TRANS_DESC_COL);
TRANSACTIONS->add_column(TRANS_AMOUNT_COL);
cout << " done." << endl;
}
else cout << "Transaction table loaded." << endl;
if (TRANSACTION_GROUPS == 0) {
cout << "Creating transaction-group table...";
TRANSACTION_GROUPS = db.add_table("transaction_groups");
TRANSACTION_GROUPS->add_column(TRANS_GRP_NAME_COL);
TRANSACTION_GROUPS->add_column(TRANS_GRP_DESC_COL);
cout << " done." << endl;
}
else cout << "Transaction-group table loaded." << endl;
string input;
cout << "Load new transactions? (y/n) ";
getline(cin, input);
if (input[0] == 'y' || input[0] == 'Y') {
string filename;
cout << "Filename: ";
getline(cin, filename);
bool define_groups = false;
input.clear();
cout << "Define transactions groups? (y/n) ";
getline(cin, input);
define_groups = (input[0] == 'y' || input[0] == 'Y');
data.open(filename, "r");
if (!data.is_open()) {
cout << "Unable to open \"" << filename << "\"." << endl;
return 1;
}
data.read(-1, END_TRANSACTION_MARKER);
int stop_pos = data.pos()-40;
data.seek(0);
data.read(-1, TRANSACTION_MARKER);
cout << "Loading transactions...";
while (data.pos() < stop_pos) {
transaction t = get_transaction(data);
TRANSACTIONS->add_row(t.to_row());
if (define_groups) {
// if a group is not already defined...
if (TRANSACTION_GROUPS->select(query().where(predicate().add(equalto(TRANS_GRP_DESC_COL, format_desc(t.description))))).size() == 0) {
input.clear();
cout << "\"" << t.raw_description << "\"" << endl;
cout << "Group: " << endl;
getline(cin, input);
TRANSACTION_GROUPS->add_row(row().add(TRANS_GRP_NAME_COL, input).add(TRANS_GRP_DESC_COL, format_desc(t.description)));
}
}
}
cout << " done." << endl << endl;
}
vector<row> results = TRANSACTIONS->select(query().where());
/*cout << "Transactions:" << endl;
for (int i=0;i<results.size();i++) {
results[i].print(TRANSACTIONS);
}*/
float total_expenses = 0.0f, total_credits = 0.0f;
map<string, float> totals;
for (int i=0;i<results.size();i++) {
// search for matching group association:
vector<row> associations = TRANSACTION_GROUPS->select(query().where(predicate().add(equalto(TRANS_GRP_DESC_COL, format_desc(results[i][TRANS_DESC_COL])))));
if (associations.size() > 0) {
if (totals.find(associations[0][TRANS_GRP_NAME_COL]) == totals.end()) totals[associations[0][TRANS_GRP_NAME_COL]] = 0.0f;
totals[associations[0][TRANS_GRP_NAME_COL]] += atof(results[i][TRANS_AMOUNT_COL].c_str());
}
else {
if (totals.find(format_desc(results[i][TRANS_DESC_COL])) == totals.end()) totals[format_desc(results[i][TRANS_DESC_COL])] = 0.0f;
totals[format_desc(results[i][TRANS_DESC_COL])] += atof(results[i][TRANS_AMOUNT_COL].c_str());
}
if (atof(results[i][TRANS_AMOUNT_COL].c_str()) < 0) total_expenses += atof(results[i][TRANS_AMOUNT_COL].c_str());
else total_credits += atof(results[i][TRANS_AMOUNT_COL].c_str());
}
map<string, float>::iterator it = totals.begin();
while (it != totals.end()) {
for (int i=0;i<30;i++) {
if (i < it->first.length()) cout << (it->first)[i];
else cout << " ";
}
cout << ": ";
if (it->second >= 0) cout << " ";
cout << it->second << "\t(";
if (it->second >= 0) cout << floor((it->second/total_credits)*1000.0f + 0.5f)/10.0f << "%)" << endl;
else {
cout << floor((it->second/total_expenses)*1000.0f + 0.5f)/10.0f << "%)" << endl;
pie[fabs(floor((it->second/total_expenses)*1000.0f + 0.5f)/10.0f)/100.0f] = it->first;
}
it++;
}
// ---------------------- OPENGL ---------------------- //
_beginthread(&glbranch, 0, (void*)0);
// -------------------- END OPENGL -------------------- //
input.clear();
cout << "Expand group? (y/n) ";
getline(cin, input);
if (input[0] == 'y' || input[0] == 'Y') {
cout << "Group: ";
input.clear();
getline(cin, input);
vector<row> groups = TRANSACTION_GROUPS->select(query().where(predicate().And(equalto(TRANS_GRP_NAME_COL, input))));
for (int groups_index=0;groups_index< groups.size();groups_index++) {
string group_description = groups[groups_index][TRANS_GRP_DESC_COL];
vector<row> transactions = TRANSACTIONS->select(query().where(predicate().And(equalto(TRANS_DESC_COL, group_description))));
for (int c=0;c<transactions.size();c++) {
cout << " ";
string transaction_description = transactions[c][TRANS_DESC_COL];
float transaction_amount = atof(transactions[c][TRANS_AMOUNT_COL].c_str());
for (int i=0;i<30;i++) {
if (i < transaction_description.length()) cout << transaction_description[i];
else cout << " ";
}
cout << ": ";
if (transaction_amount >= 0) cout << " ";
cout << transaction_amount << "\t(";
if (transaction_amount >= 0) cout << floor((transaction_amount/total_credits)*1000.0f + 0.5f)/10.0f << "%)" << endl;
else cout << floor((transaction_amount/total_expenses)*1000.0f + 0.5f)/10.0f << "%)" << endl;
}
}
}
return 0;
}
transaction get_transaction(fileio& data) {
transaction entry;
string temp;
data.read(-1, " >");
entry.date = strip_whitespace(data.read(-1, "</td>"));
data.read(-1, " >");
entry.type = strip_whitespace(data.read(-1, "</td>"));
data.read(-1, " >");
entry.raw_description = data.read(-1, "</td>");
entry.description = format_desc(entry.raw_description);
data.read(-1, "align=\"right\">");
temp = data.read(-1, "</td>");
if (temp != " ") {
temp.insert(0, string("-"));
entry.amount = atof(temp.c_str());
}
else {
data.read(-1, "align=\"right\">");
temp = data.read(-1, "</td>");
entry.amount = atof(temp.c_str());
}
data.read(-1, "</tr>");
return entry;
}
string strip_whitespace(const string& t) {
string str = t;
int del = 0;
for (int i=0;i<str.length();i++) {
if ( (str[i] == ' ' || str[i] == '\n' || str[i] == '\t' || str[i] == '\r')
&& (i+1 < str.length() && (str[i+1] == ' ' || str[i+1] == '\n' || str[i+1] == '\t' || str[i+1] == '\r'))
) del++;
else {
str.erase(i-del, del);
i-= del;
del = 0;
}
}
for (int i=str.length()-1;i>0;i--) {
if (str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') str.erase(i, 1);
else break;
}
return str;
}
string format_desc(const string& t, int words) {
string str;
int i=0;
while (i < t.length()) {
if (t[i] == ' ') words--;
if (words > 0) {
// is alpha or numeric
if (t[i] == ' ' || (t[i] > 64 && t[i] < 91) || (t[i] > 96 && t[i] < 123)) str += t[i];
}
else break;
i++;
}
return strtolower(strip_whitespace(str));
}
|
#include<cstdio>
#include<cstring>
#include<complex>
#include<cmath>
#include<algorithm>
#define MAXN 263010
#define EPS 1e-8
using namespace std;
typedef complex<double> cp;
const double pi = acos(-1.0);
char s1[MAXN],s2[MAXN];
cp x1[MAXN],x2[MAXN];
cp t1[MAXN],t2[MAXN];
cp x3[MAXN];
int ans[MAXN];
int n,m;
void output(cp arr[], int len)
{
for(int i=0; i<len; i++)
printf("<%lf, %lf> ", arr[i].real(), arr[i].imag());
printf("\n");
}
void init_array(char *s, cp a[], int len, int retlen) //初始化IDF数组
{
for(int i=0; i<len; i++)
a[len-i-1] = cp(s[i]-'0', 0); //1+a0x+a1x^2+...
for(int i=len; i<retlen; i++)
a[i] = cp(0, 0);
}
int rev(int x, int bit)
{
int ret= 0;
while(bit--) {
ret = (ret <<1) | (x & 1);
x >>= 1;
}
return ret;
}
void bit_reverse_copy(cp in[], cp out[], int n, int bitnum)
{
for(int i=0; i<n; i++) {
out[rev(i, bitnum)] = in[i];
}
}
void iterative_fft(cp in[], cp out[], int n, int flip) //flip == 1 or -1
{
cp wm,w,t, u;
int bitnum;
for(bitnum=0; !((1<<bitnum) & n); bitnum++) ;
bit_reverse_copy(in, out, n, bitnum);
for(int m = 2; m<=n; m*=2)
{
wm = cp(cos(2*pi*flip / m), sin(2*pi*flip / m));
for(int k=0; k<n; k+=m)
{
w = cp(1, 0);
for(int j=0; j<m/2; j++)
{
t = w * out[k+j+m/2];
u = out[k+j];
out[k+j] = u + t;
out[k+j+m/2] = u - t;
w = w * wm;
}
}
}
if(flip == -1)
for(int i=0; i<n; i++) out[i] /= n;
}
void trans_back(cp x[], int ans[], int &n)
{
for(int i=0; i<n; i++) ans[i] = x[i].real() + 0.5;
for(int i=0; i<n; i++)
{
ans[i+1] += ans[i] / 10;
ans[i] %= 10;
}
while(n>0 && ans[n-1] == 0) n--;
}
int main()
{
while(scanf("%s%s", s1, s2) != EOF)
{
int l1 = strlen(s1), l2 = strlen(s2);
m = l1 + l2;
for(n =1; n<m; n<<=1) ;
init_array(s1, x1, l1, n);
init_array(s2, x2, l2, n);
iterative_fft(x1, t1, n, 1);// DFT
iterative_fft(x2, t2, n, 1);
for(int i=0; i<n; i++)
x3[i] = t1[i] * t2[i];
iterative_fft(x3, x1, n, -1); //IDFT
fill(ans, ans+n, 0);
trans_back(x1, ans, n); //把IDFT结果转为高精度形式
if(n <= 0) printf("0\n");
else {
for(int i=n-1; i>=0; i--)
printf("%d", ans[i]);
printf("\n");
}
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#ifndef DEFAULT_QUICK_BINDER_H
#define DEFAULT_QUICK_BINDER_H
#include "adjunct/quick_toolkit/bindings/QuickBinder.h"
/**
* A QuickBinder that makes the effects of bindings permanent immediately.
*
* @author Wojciech Dzierzanowski (wdzierzanowski)
*/
class DefaultQuickBinder : public QuickBinder
{
protected:
virtual OP_STATUS OnAddBinding(OpProperty<bool>& property) { return OpStatus::OK; }
virtual OP_STATUS OnAddBinding(OpProperty<OpString>& property) { return OpStatus::OK; }
virtual OP_STATUS OnAddBinding(OpProperty<INT32>& property) { return OpStatus::OK; }
virtual OP_STATUS OnAddBinding(OpProperty<UINT32>& property) { return OpStatus::OK; }
virtual OP_STATUS OnAddBinding(OpProperty<OpTreeModel*>& property) { return OpStatus::OK; }
virtual OP_STATUS OnAddBinding(OpProperty<OpINT32Vector>& property) { return OpStatus::OK; }
virtual OP_STATUS OnAddBinding(PrefUtils::IntegerAccessor& accessor) { return OpStatus::OK; }
virtual OP_STATUS OnAddBinding(PrefUtils::StringAccessor& accessor) { return OpStatus::OK; }
};
#endif // DEFAULT_QUICK_BINDER_H
|
/*
File: WidgetApp.c (Based on BasicRAEL from CarbonSDK)
Demonstrate getting Opera 7.2 up and running as a Widget
from a CFM-based host application.
*/
#ifdef __MACH__
#include <Carbon/Carbon.h>
#else
#include <Carbon.h>
#endif
#include "WidgetApp.h"
#include "OperaControl.h"
#include "WidgetAppEvents.h"
// Globals
WidgetAppEvents *gWidgetAppEvents = NULL;
extern EmBrowserRef gWidgetPointer;
extern EmBrowserInitParameterBlock * params;
Boolean gQuitFlag;
int main(int argc, const char** argv)
{
Initialize();
MakeMenu();
gWidgetAppEvents = new WidgetAppEvents;
if (gWidgetAppEvents)
{
gWidgetAppEvents->InstallCarbonEventHandlers();
gWidgetAppEvents->InstallPeriodicEventHandler(10);
}
RunApplicationEventLoop();
if (gWidgetAppEvents)
{
gWidgetAppEvents->RemoveCarbonEventHandlers();
gWidgetAppEvents->RemovePeriodicEventHandler();
}
// If widget was not destroyed yet, do it now.
if (gWidgetPointer && params->destroyInstance)
DestroyWidget();
/**********************************
** STEP 6: SHUTDOWN THE LIBRARY **
***********************************/
if (params && params->shutdown)
params->shutdown();
return 0;
}
void Initialize()
{
OSErr err;
InitCursor();
err = AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP(QuitAppleEventHandler), 0, false);
if (err != noErr)
ExitToShell();
}
void MakeWindow(WindowRef *outRef)
{ Rect wRect;
WindowRef window;
OSStatus err;
EventHandlerRef ref;
SetRect(&wRect,50,50,600,600);
err = CreateNewWindow(kDocumentWindowClass, kWindowStandardDocumentAttributes,&wRect, &window);
InstallStandardEventHandler(GetWindowEventTarget(window));
gWidgetAppEvents->InstallCarbonWindowHandler(window,&ref);
ShowWindow(window);
*outRef = window;
}
void MakeMenu(void)
{
Handle menuBar;
MenuRef menu;
long response;
OSStatus err = noErr;
menuBar = GetNewMBar(128);
if (menuBar)
{
SetMenuBar(menuBar);
// see if we should modify quit in accordance with the Aqua HI guidelines
err = Gestalt(gestaltMenuMgrAttr, &response);
if ((err == noErr) && (response & gestaltMenuMgrAquaLayoutMask))
{
menu = GetMenuHandle(mFile);
DeleteMenuItem(menu, iQuit);
DeleteMenuItem(menu, iQuitSeperator);
}
DrawMenuBar();
}
else
DebugStr("\p MakeMenu failed");
}
static pascal OSErr QuitAppleEventHandler(const AppleEvent *appleEvt, AppleEvent* reply, long refcon)
{
#pragma unused (appleEvt, reply, refcon)
QuitApplicationEventLoop();
return noErr;
}
void DoAboutBox(void)
{
Alert(kAboutBox, nil); // simple alert dialog box
}
|
#include <iostream>
#include <boost/filesystem.hpp>
#include "lib/StreamSampler/StreamSampler.h"
int main(int argc, char *argv[])
{
const auto sample_sets_count = std::size_t {1};
const auto sample_count = std::size_t {1};
const auto source_dir = argc > 1 ? argv[1] : ".";
if (boost::filesystem::exists(source_dir)) {
StreamSampler::CStreamSamplerWOR_R0<std::string> sampler {sample_sets_count, sample_count};
boost::filesystem::directory_iterator it {source_dir};
for (const auto& p : it) {
sampler.AddElement(std::move(p.path().string()));
}
const auto sample_sets = sampler.GetSampleSets();
assert(sample_sets.size() == sample_sets_count);
assert(sample_sets[0].size() == sample_count);
const auto& sampled_path = sample_sets[0][0];
std::cout << sampled_path << "\n";
return 0;
} else {
std::cout << "directory " << source_dir << " does not exist\n";
return 1;
}
}
|
#pragma once
#include "../entity/entity.h"
#include "../Components/Transform.h"
#include "../Components/Renderer.h"
class duiElement :
public Entity
{
public:
duiElement(void);
virtual ~duiElement(void);
virtual void Init();
virtual void Update();
Transform tf;
Renderer render;
void SetFocus(bool val);
void OnFocus();
void OnClick();
duiElement* topLink;
duiElement* bottomLink;
duiElement* leftLink;
duiElement* rightLink;
private:
bool isFocused;
bool startsWithFocus;
};
|
#include <iostream>
#define validation \
while (std::cin.fail() || 0 >= size) { \
std::cout << "Invalid Value: Try again!" << std::endl; \
std::cin.clear(); \
std::cin.ignore(256,'\n'); \
std::cout << "Enter intager number( > 0): "; \
std::cin >> size; \
}
#define input_elements_of_array \
int size = 0; \
std::cout << "Enter size of array: "; \
std::cin >> size; \
validation; \
int array[size]; \
std::cout << "Enter the elements of the array: "; \
for (int i = 0; i < size; ++i) { \
std::cin >> array[i]; \
validation; \
};
#define find_maximum_element \
int max = array[0]; \
for (int i = 1; i < size; ++i) { \
if (max < array[i]) { \
max = array[i]; } \
};
#define print_maximum_element \
std::cout << "Max value is " << max << std::endl;
int main() {
input_elements_of_array
find_maximum_element
print_maximum_element
return 0;
}
|
#include <iostream.h>
#include <malloc.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
void initiarray( );
void initiones();
void display( float *r);
void solve();
void backloop();
static float *p,*q;
int N;
void main() //利用要求矩阵和单位矩阵一起行变化,当要求矩阵成为单位矩阵时
{ // 单位矩阵变成其逆矩阵
printf("input array size N:");
scanf("%d",&N);
p=(float *)malloc(sizeof(float)*(N*N));
q=(float *)malloc(sizeof(float)*(N*N));
initiarray();
initiones();
display(p);
solve( );
backloop();
display(q);
}
void initiarray( ) //初始化
{
int i,j;
extern N;
printf("initialize array……\ninput array:\n");
for(i=0;i<N;i++)
for(j=0;j<N;j++)
scanf("%f",&p[i*N+j]);
}
void initiones() //形成单位矩阵
{
int i,j;
for(i=0;i<N;i++)
for(j=0;j<N;j++)
{ if(i==j)
q[i*N+j]=1;
else
q[i*N+j]=0;
}
}
void display(float *r ) //显示
{
int i,j;
printf("out put array:\n");
for(i=0;i<N;i++)
{
for(j=0;j<N;j++)
printf("%10.4f",r[i*N+j]);
printf("\n");
}
}
void swap(float *r,int i,int line) //换行
{
int j;
float m;
for(j=0;j<N;j++)
{ m=r[i*N+j];
r[i*N+j]=r[line*N+j];
r[line*N+j]=m;
}
}
void solve() //形成下三角矩阵
{
int i ,j,k,m,line;
float max,temp,savep;
for (i=0;i<N;i++)
{
max=fabs(p[i*N+i]);
temp=p[i*N+i];
line=i;
for (j=i+1;j<N;j++)
{
if(fabs(p[j*N+i])>max) //找出绝对值最大元
{line=j;
max=fabs(p[j*N+i]);
temp=p[j*N+i]; }
}
if(max<=1e-5) //三角矩阵的对角元等于0则无解
{
cout<<"no inverse array\n";
exit(0);}
if(line!=i)
{
swap(p,i,line);
swap(q,i,line);}
for (k=0;k<N;k++)
{
p[i*N+k]/=temp;
q[i*N+k]/=temp;}
for(k=i+1;k<N;k++) //消元,成下三角阵;
{
savep=p[k*N+i];
for( m=0;m<N;m++)
{
q[k*N+m]=q[k*N+m]-q[i*N+m]*savep;
p[k*N+m]=p[k*N+m]-p[i*N+m]*savep;}
}
}
}
void backloop() //回带,形成单位矩阵
{
int i,j,k;
float savep;
for(i=N-1;i>0;i--)
{
for(j=i-1;j>=0;j--)
{
savep=p[j*N+i];
p[j*N+i]=p[j*N+i]-p[i*N+i]*savep;
for(k=0;k<N;k++)
q[j*N+k]=q[j*N+k]-q[i*N+k]*savep;
}
}
}
|
typedef unsigned int addr_t;
#include "guest.h"
#include <stdlib.h>
#include <stdio.h>
//#include "arm_cpu.h"
void guest_print_string(const char* str)
{
FILE* fd = fopen("C:\proc.txt", "a");
fwrite( str, strlen(str) + 1, 1, fd);
fflush(fd);
fclose(fd);
printf("GUEST SAYS: %s\n", str);
}
int guest_abort()
{
ABORT("GUEST Aborted");
return 0;
}
int video_call_guest_guest_print_string(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
HOST_READ_QUEUE(1024);
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t str_out_size = paParms[k-1].u.pointer.size;
char* str = (char*)malloc(str_out_size);
memcpy(str, pchBuf1, str_out_size);
//addr_t str_; // addr_t str_;
//QUEUE_POP(&str_, sizeof (addr_t));
//char* str = NULL;
//size_t str_out_size = 0;
//assert(str_);
//QUEUE_POP(&str_out_size, sizeof (size_t));
//str = (char*)malloc(str_out_size);
//assert(str);
//if ((size_t) read_linear(cpu, str_, str_out_size, str, 1) != str_out_size)
// ABORT("read_linear in function \"guest_print_string\" failed");
guest_print_string(str);
HOST_START_PUSH();
free(str);
HOST_WRITE_QUEUE();
}
int video_call_guest_guest_abort(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: guest_abort\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
int ret_value = guest_abort();
HOST_START_PUSH();
QUEUE_PUSH(&ret_value, sizeof (int));
HOST_WRITE_QUEUE();
}
|
#include<iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int n, cnt=0;
int *col;
bool promissing(int i) {
int k;
bool sw;
k = 1;
sw = true;
while (k < i && sw) {
if (col[i] == col[k] || i - k == abs(col[i] - col[k]))
sw = false;
k++;
}
return sw;
}
void queen(int i) {
int j;
if (promissing(i)) {
if (i == n) {
cnt++;
return;
}
else
for (j = 1; j <= n; j++) {
col[i + 1] = j;
queen(i + 1);
}
}
}
int main(void) {
cin >> n;
col = (int*)malloc(sizeof(int)*n);
queen(0);
cout << cnt;
free(0);
return 0;
}
|
#include "LandruActorVM/Fiber.h"
#include "LandruActorVM/Library.h"
#include "LandruActorVM/VMContext.h"
#include <mutex>
#include <GLFW/glfw3.h>
#define LANDRUGL_EXPORTS
#include "api.h"
using namespace std;
using namespace Landru;
namespace {
struct OnWindowClosed : public OnEventEvaluator
{
explicit OnWindowClosed(GLFWwindow* w, std::shared_ptr<Fiber> f, vector<Instruction> & statements)
: OnEventEvaluator(f, statements)
, window(w) {}
GLFWwindow* window;
};
struct OnWindowResized : public OnEventEvaluator
{
explicit OnWindowResized(GLFWwindow* w, std::shared_ptr<Fiber> f, vector<Instruction> & statements)
: OnEventEvaluator(f, statements)
, window(w) {}
GLFWwindow* window;
static void window_resized(GLFWwindow* w, int width, int height);
};
std::vector<GLFWwindow*> sgWindows;
std::vector<OnWindowClosed> sgOnWindowClosed;
std::vector<OnWindowResized> sgOnWindowResized;
struct PendingResize
{
GLFWwindow * window;
float width, height;
};
std::vector<PendingResize> sgResizes;
void error_callback(int error, const char* description)
{
fprintf(stderr, "Error: %s\n", description);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
bool close = key == GLFW_KEY_ESCAPE || key == (GLFW_KEY_LEFT_ALT|GLFW_KEY_F4) || key == (GLFW_KEY_RIGHT_ALT|GLFW_KEY_F4);
if (close && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
/// @TODO reroute key to landru as a string, like "alt-G" or "alt-g"
}
void OnWindowResized::window_resized(GLFWwindow* w, int width, int height)
{
for (auto & i : sgOnWindowResized) {
if (i.window == w) {
sgResizes.push_back({ w, (float) width, (float) height });
}
}
}
void initGL()
{
static std::once_flag once;
std::call_once(once, []()
{
glfwSetErrorCallback(error_callback);
glfwInit();
sgWindows = std::vector<GLFWwindow*>();
});
}
class GLContext
{
public:
};
RunState createWindow(FnContext& run)
{
string title = run.self->pop<string>();
float height = run.self->pop<float>();
float width = run.self->pop<float>();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
GLFWwindow* window = glfwCreateWindow((int) width, (int) height, title.c_str(), NULL, NULL);
glfwSetKeyCallback(window, key_callback);
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
sgWindows.emplace_back(window);
run.self->push<GLFWwindow*>(window);
return RunState::Continue;
}
RunState windowClosed(FnContext& run)
{
vector<Instruction> instr = run.self->back<vector<Instruction>>(-2);
auto property = run.self->pop<GLFWwindow*>();
run.self->popVar(); // drop the instr
if (property)
sgOnWindowClosed.emplace_back(OnWindowClosed(property, run.vm->fiberPtr(run.self), instr));
return RunState::Continue;
}
RunState windowResized(FnContext& run)
{
vector<Instruction> instr = run.self->back<vector<Instruction>>(-2);
auto property = run.self->pop<GLFWwindow*>();
run.self->popVar(); // drop the instr
if (property) {
glfwSetWindowSizeCallback(property, OnWindowResized::window_resized);
sgOnWindowResized.emplace_back(OnWindowResized(property, run.vm->fiberPtr(run.self), instr));
}
return RunState::Continue;
}
} // anon
extern "C"
LANDRUGL_API
void landru_gl_init(void* vl)
{
initGL();
Landru::Library * lib = reinterpret_cast<Landru::Library*>(vl);
Landru::Library gl_lib("gl");
auto glVtable = unique_ptr<Library::Vtable>(new Library::Vtable("gl"));
glVtable->registerFn("1.0", "createWindow", "ffs", "o", createWindow);
glVtable->registerFn("1.0", "windowClosed", "o", "", windowClosed);
glVtable->registerFn("1.0", "windowResized", "o", "ff", windowResized);
gl_lib.registerVtable(move(glVtable));
gl_lib.registerFactory("context", []()->std::shared_ptr<Wires::TypedData>
{
return std::make_shared<Wires::Data<GLContext>>();
});
gl_lib.registerFactory("window", []()->std::shared_ptr<Wires::TypedData>
{
return std::make_shared<Wires::Data<GLFWwindow*>>(nullptr);
});
lib->libraries.emplace_back(std::move(gl_lib));
}
extern "C"
LANDRUGL_API
RunState landru_gl_update(double now, VMContext* vm)
{
bool cullWindows;
do {
cullWindows = false;
for (auto i = sgWindows.begin(); i != sgWindows.end(); ++i) {
if (glfwWindowShouldClose(*i)) {
for (auto j = sgOnWindowClosed.begin(); j != sgOnWindowClosed.end(); ++j) {
if (j->window == *i) {
FnContext fn(vm, j->fiber(), nullptr);
auto & instr = j->instructions();
fn.run(instr);
}
j = sgOnWindowClosed.erase(j);
if (j == sgOnWindowClosed.end())
break;
}
glfwDestroyWindow(*i);
sgWindows.erase(i);
cullWindows = true;
break;
}
}
} while (cullWindows);
for (auto i : sgResizes) {
for (auto & j : sgOnWindowResized) {
if (j.window == i.window) {
FnContext fn(vm, j.fiber(), nullptr);
j.fiber()->push<float>(i.height);
j.fiber()->push<float>(i.width);
auto & instr = j.instructions();
fn.run(instr);
}
}
}
sgResizes.clear();
for (auto w : sgWindows) {
/// @TODO only render and swap buffers if the window needs redrawing
/// @TODO render here
glfwSwapBuffers(w);
}
glfwPollEvents();
return RunState::Continue;
}
extern "C"
LANDRUGL_API
void landru_gl_finish(void* vl)
{
Landru::Library * lib = reinterpret_cast<Landru::Library*>(vl);
}
extern "C"
LANDRUGL_API
void landru_gl_fiberExpiring(Fiber* f)
{
// called when Fibers are destroyed so that pending items like onWindowsClosed can be removed
}
extern "C"
LANDRUGL_API
void landru_gl_clearContinuations(Fiber* f, int level)
{
// called when continuations must be cleared, for example before executing a goto statement
if (!f)
sgOnWindowClosed.clear();
else
{
for (std::vector<OnWindowClosed>::iterator i = sgOnWindowClosed.begin(); i != sgOnWindowClosed.end(); ++i) {
if (i->fiber() == f) {
i = sgOnWindowClosed.erase(i);
if (i == sgOnWindowClosed.end())
break;
}
}
for (std::vector<OnWindowResized>::iterator i = sgOnWindowResized.begin(); i != sgOnWindowResized.end(); ++i) {
if (i->fiber() == f) {
i = sgOnWindowResized.erase(i);
if (i == sgOnWindowResized.end())
break;
}
}
}
}
extern "C"
LANDRUGL_API
bool landru_gl_pendingContinuations(Fiber * f)
{
return sgOnWindowClosed.size() > 0 || sgOnWindowResized.size() > 0;
}
|
#pragma once
#include "definitions.h"
namespace lm {
int lvl_to_int(lvl);
}
|
#ifndef WORDDISPLAYFORMATTER_H
#define WORDDISPLAYFORMATTER_H
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <set>
using namespace std;
namespace view
{
//
// Formats the given words to the style needed for the output summary
//
class WordDisplayFormatter
{
private:
static const size_t COLUMN_WIDTH = 14;
public:
//
// Formats the words so that only the guessed words are shown and the rest are #
//
// @precondition none
// @postcondition none
//
// @param guessed the guessed words
// @param allWords the total collection of possible words
//
// @return the summary string formatted
//
static const string format(const set<string>* guessed, const set<string>* allWords);
private:
static const string drawWord(const string& word, const set<string>* guessed);
};
}
#endif // WORDDISPLAYFORMATTER_H
|
#pragma once
#ifndef _TABLE_UNIT_H_
#define _TABLE_UNIT_H_
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
enum class UnitType
{
SHIFT, REDUCE, ERROR, ACC
};
class TableUnit
{
private:
//表格单元类型
UnitType type;
//表格值
size_t value;
public:
TableUnit(UnitType type, size_t value);
//解析字符串为分析表action表格单元
static TableUnit identify(string str);
UnitType getType();
char getTypeStr();
size_t getValue();
};
#endif
|
#include <bits/stdc++.h>
#define ALL(x) x.begin(), x.end()
#define MAX 1000010
using namespace std;
typedef long long int LL;
const int MOD = 1000000007;
const double EPS = 0.0000000001;
LL n;
LL p = 9;
int memo[MAX];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
memset(memo, -1, sizeof memo);
memo[0]=memo[1]=memo[2]=memo[3]=memo[4]=memo[5]=memo[6]=memo[7]=0;
memo[8] = 1;
while(cin >> n){
if(n == 0)
break;
if(memo[n] != -1)
cout <<memo[n]<< '\n';
else{
for(;p<= n; ++p){
double test = sqrt((p*p+p)/2.0);
memo[p] = memo[p-1];
if(test == (LL)(test+EPS)){
memo[p]++;
}
}
assert(memo[n] != -1);
cout << memo[n]<< '\n';
}
}
return 0;
}
|
#pragma once
#include <iostream>
#include <string>
#include "FBullCowGame.h"
/*
Console executable that makes use of the bull cow class.
This acts as teh veiew in MVC patter,and is responsible for all user interaction.
For the game logic see the FBullCowGame class
*/
using FText = std::string;
using int32 = int;
void Printintro();
FText GetValidGuess();
void PlayerTurn();
bool AskToPlayAgain();
FBullCowGame BCGame;
int main()
{
bool bPlayAgain = false;
//introduce the player to the game
do {
Printintro();
PlayerTurn();
bPlayAgain = AskToPlayAgain();
} while (bPlayAgain);
return 0;
}
void PlayerTurn()
{
BCGame.Reset();
//Sets the number of player turns
int32 MaxTries = BCGame.GetMaxTries();
while(!BCGame.IsGameWon() && BCGame.GetCurrentTry()<= MaxTries){
//Get the returned guess from player
FText Guess = GetValidGuess(); //TODO make loop check for valid input
// submit valid guess to the game
FBullCowCount BullCowCount = BCGame.SubmitGuess(Guess);
// print the number of bulls and cows
std::cout << "Bulls =" << BullCowCount.Bulls<<std::endl;
std::cout << "Cows =" << BullCowCount.Cows<< std::endl;
std::cout << std::endl;
}
BCGame.PrintGameSummary();
return;
}
bool AskToPlayAgain()
{
std::cout << "Do you want to play again?";
FText Response = "";
std::getline(std::cin, Response);
return (Response[0] == 'Y' || Response[0] == 'y');
}
std::string GetValidGuess()
{
EGuessStatus status = EGuessStatus::Invalid;
do {
int32 CurrentTry = BCGame.GetCurrentTry();
//Get the player Guess
FText Guess = "";
std::cout << "Please enter try:" << CurrentTry << "of" << BCGame.GetMaxTries();
std::getline(std::cin, Guess);
status = BCGame.CheckGuessValidity(Guess);
switch (status) {
case EGuessStatus::Wrong_Length:
std::cout << "Please enter a" << BCGame.GetHiddenWordLength() << "Letter word\n\n";
break;
case EGuessStatus::notIsogram:
std::cout << "Please enter a word with out repeating letters\n\n";
break;
case EGuessStatus::NotLowerCase:
std::cout << "Please put the word in lower case\n\n";
break;
default:
return Guess;
}
std::cout << std::endl;
} while (status != EGuessStatus::ok);
}
void Printintro()
{
//Begin introducing the game
std::cout << "Welcome To Bulls And Cows, a fun word game";
std::cout << "can you guess the " << BCGame.GetHiddenWordLength();
std::cout << "lettter isogram I'm thinking of?" << "\n\n";
return;
}
|
#include "operations.hpp"
float suma(float A, float B)
{
float C = A + B;
return C;
}
float resta(float A, float B)
{
float C = A - B;
return C;
}
float multi(float A, float B)
{
float C = A*B;
return C;
}
float div(float A, float B)
{
float C = A/B;
return C;
}
|
#include <iostream>
#include <iomanip>
#include <map>
using namespace std;
long long primes[1000000];
bool isPrime(long long num, int numprimes) {
for(int i = 0; i < numprimes; i++) {
if (num % primes[i] == 0) {
return false;
}
}
return true;
}
int main() {
int numprimes = 1;
primes[0] = 2;
map<int, bool> primeMap;
int circular = 0;
for (double i = 3; i < 1000000; i++) {
if (isPrime((long long)i, numprimes)) {
primes[numprimes] = i;
primeMap[i] = true;
numprimes++;
}
}
for (int i = 0; i < numprimes; i++) {
if ( primes[i] < 10 ) {
circular++;
} else if (primes[i] < 100) {
int circ = primes[i] / 10;
circ = (primes[i] % 10) * 10 + circ;
if (primeMap.count(circ) > 0 && primeMap.count(primes[i]) > 0) {
circular++;
}
} else if (primes[i] < 1000) {
int circ = primes[i] / 10;
circ = (primes[i] % 10) * 100 + circ;
int circ2 = circ / 10;
circ2 = (circ % 10) * 100 + circ2;
if (primeMap.count(circ2) > 0 && primeMap.count(circ) > 0 &&
primeMap.count(primes[i]) > 0) {
circular++;
}
} else if (primes[i] < 10000) {
int circ = primes[i] / 10;
circ = (primes[i] % 10) * 1000 + circ;
int circ2 = circ / 10;
circ2 = (circ % 10) * 1000 + circ2;
int circ3 = circ2 / 10;
circ3 = (circ2 % 10) * 1000 + circ3;
if (primeMap.count(circ2) > 0 && primeMap.count(circ) > 0 &&
primeMap.count(circ3) > 0 && primeMap.count(primes[i]) > 0) {
circular++;
}
} else if (primes[i] < 100000) {
int circ = primes[i] / 10;
circ = (primes[i] % 10) * 10000 + circ;
int circ2 = circ / 10;
circ2 = (circ % 10) * 10000 + circ2;
int circ3 = circ2 / 10;
circ3 = (circ2 % 10) * 10000 + circ3;
int circ4 = circ3 / 10;
circ4 = (circ3 % 10) * 10000 + circ4;
if (primeMap.count(circ2) > 0 && primeMap.count(circ) > 0 &&
primeMap.count(circ3) > 0 && primeMap.count(primes[i]) > 0 &&
primeMap.count(circ4) > 0) {
circular++;
}
} else if (primes[i] < 1000000) {
int circ = primes[i] / 10;
circ = (primes[i] % 10) * 100000 + circ;
int circ2 = circ / 10;
circ2 = (circ % 10) * 100000 + circ2;
int circ3 = circ2 / 10;
circ3 = (circ2 % 10) * 100000 + circ3;
int circ4 = circ3 / 10;
circ4 = (circ3 % 10) * 100000 + circ4;
int circ5 = circ4 / 10;
circ5 = (circ4 % 10) * 100000 + circ5;
if (primeMap.count(circ2) > 0 && primeMap.count(circ) > 0 &&
primeMap.count(circ3) > 0 && primeMap.count(primes[i]) > 0 &&
primeMap.count(circ4) > 0 && primeMap.count(circ5) > 0) {
circular++;
}
} else {
break;
}
}
cout << "There are " << circular << " circular primes below 1000000." << endl;
}
|
#include "vector.h"
#include <iostream>
struct Complex {
float x,y;
};
int main() {
Vector<int> ints = {1,2,3,4,5};
Vector<Complex> cvals = { {1., 2.}, {3., 4.}};
cvals.push_back({5., 6.});
for (Vector<Complex>::size_type i=0; i<cvals.size(); i++) {
std::cout << "i = " << i << " value.x = " << cvals[i].x
<< " value.y = " << cvals[i].y << std::endl;
}
}
|
/** Underscore
@file /.../Source/Kabuki_SDK-Impl/_App/App.h
@author Cale McCollough
@copyright Copyright 2016 Cale McCollough ©
@license http://www.apache.org/licenses/LICENSE-2.0
*/
#include "App.h"
using namespace _App;
/** */
App::App (int initWidth, int initHeight)
{
if (initWidth < MinWidthOrHeight) initWidth = MinWidthOrHeight;
else if (initWidth > MaxWidth) initWidth = MaxWidth;
if (initHeight < MinWidthOrHeight) initHeight = MinWidthOrHeight;
else if (initHeight > MaxWidth) initHeight = MaxWidth;
}
/** Returns the process ID of this App. */
long App::GetUID { return uID; }
/** Sets the activeWindow to the newIndex. */
int App::ActivateWindow (int newWindowIndex)
{
return windows.Select (newWindowIndex);
}
/** Sets the activeWindow to the newWindow. */
int App::ActivateWindow (Window newWindow)
{
if (newWindow == nullptr)
return -1;
activeWindow = newWindow;
return 0;
}
/** Returns the */
WindowGroup Windows { return windows; }
/** */
int App::Show ()
{
return 0;
}
/** */
int App::Hide ()
{
return 0;
}
/** */
int App::Close ()
{
return 0;
}
/** Returns a link to this application's drawing context. */
_G2D.Cell App::Cell ()
{
return null;
}
/** Draws the graphics on in the Cell canvas g. */
void App::Draw (_G2D.Cell g)
{
}
/** Redraws the screen */
void App::Redraw ()
{
}
/** Returns a text representation of this object. */
string App::ToString ()
{
return "";
}
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
LL solve() {
int n;
vector< vector<pair<char, int> > > gg;
cin >> n;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
vector< pair<char, int> > g;
for (int i = 0; i < s.length(); ++i) {
if (i == 0 || s[i] != s[i - 1]) {
g.push_back(make_pair(s[i], 1));
} else {
++g.back().second;
}
}
gg.push_back(g);
}
for (int i = 1; i < gg.size(); ++i) {
if (gg[i].size() != gg[0].size())
return -1;
for (int j = 0; j < gg[0].size(); ++j)
if (gg[i][j].first != gg[0][j].first)
return -1;
}
LL ans = 0;
for (int i = 0; i < gg[0].size(); ++i) {
vector<int> v;
for (int j = 0; j < gg.size(); ++j) v.push_back(gg[j][i].second);
sort(v.begin(), v.end());
LL subans = 0, submin = 1e18;
for (int cc = 0; cc <= 100; ++cc) {
subans = 0;
for (int j = 0; j < gg.size(); ++j) subans += abs(cc - gg[j][i].second);
submin= min(submin, subans);
}
ans += submin;
}
return ans;
}
int main() {
freopen(".in", "r", stdin);
freopen(".out", "w", stdout);
int T;
cin >> T;
for (int __it = 1; __it <= T; ++__it) {
cout << "Case #" << __it << ": ";
LL t = solve();
if (t == -1)
cout << "Fegla Won";
else
cout << t;
cout << endl;
}
return 0;
}
|
// Created on: 2014-03-17
// Created by: Kirill GAVRILOV
// Copyright (c) 2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef OpenGl_GlCore42_HeaderFile
#define OpenGl_GlCore42_HeaderFile
#include <OpenGl_GlCore41.hxx>
//! OpenGL 4.2 definition.
struct OpenGl_GlCore42 : public OpenGl_GlCore41
{
private:
typedef OpenGl_GlCore41 theBaseClass_t;
public: //! @name GL_ARB_base_instance (added to OpenGL 4.2 core)
using theBaseClass_t::glDrawArraysInstancedBaseInstance;
using theBaseClass_t::glDrawElementsInstancedBaseInstance;
using theBaseClass_t::glDrawElementsInstancedBaseVertexBaseInstance;
public: //! @name GL_ARB_transform_feedback_instanced (added to OpenGL 4.2 core)
using theBaseClass_t::glDrawTransformFeedbackInstanced;
using theBaseClass_t::glDrawTransformFeedbackStreamInstanced;
public: //! @name GL_ARB_internalformat_query (added to OpenGL 4.2 core)
using theBaseClass_t::glGetInternalformativ;
public: //! @name GL_ARB_shader_atomic_counters (added to OpenGL 4.2 core)
using theBaseClass_t::glGetActiveAtomicCounterBufferiv;
public: //! @name GL_ARB_shader_image_load_store (added to OpenGL 4.2 core)
using theBaseClass_t::glBindImageTexture;
using theBaseClass_t::glMemoryBarrier;
public: //! @name GL_ARB_texture_storage (added to OpenGL 4.2 core)
using theBaseClass_t::glTexStorage1D;
using theBaseClass_t::glTexStorage2D;
using theBaseClass_t::glTexStorage3D;
};
#endif // _OpenGl_GlCore42_Header
|
#pragma once
/*****************************************************************
* Copyright (c) Dassault Systemes. All rights reserved. *
* This file is part of FMIKit. See LICENSE.txt in the project *
* root for license information. *
*****************************************************************/
#include "fmi1.h"
#include "FMU.h"
#ifndef _WIN32
#include <dlfcn.h>
#endif
namespace fmikit {
class FMU1 : public FMU {
public:
explicit FMU1(const std::string &guid,
const std::string &modelIdentifier,
const std::string &unzipDirectory,
const std::string &instanceName,
allocateMemoryCallback *allocateMemory,
freeMemoryCallback *freeMemory);
virtual ~FMU1();
double getReal(ValueReference vr) override;
int getInteger(ValueReference vr) override;
bool getBoolean(ValueReference vr) override;
std::string getString(ValueReference vr) override;
void setReal(const ValueReference vr, double value) override;
void setInteger(ValueReference vr, int value) override;
void setBoolean(ValueReference vr, bool value) override;
void setString(ValueReference vr, std::string value) override;
protected:
static FMU1 *s_currentInstance;
static void logFMU1Message(fmi1Component c, fmi1String instanceName, fmi1Status status, fmi1String category, fmi1String message, ...);
fmi1Component m_component ;
fmi1CallbackFunctions m_callbackFunctions;
void assertNoError(fmi1Status status, const char *message);
template<typename T> T* getFunc(const char *functionName, bool required = true) {
std::string procName = modelIdentifier() + "_" + functionName;
# ifdef _WIN32
FARPROC fp = GetProcAddress(m_libraryHandle, procName.c_str());
# else
void *fp = dlsym(m_libraryHandle, procName.c_str());
# endif
if (required && !fp) {
error("Function %s not found in shared library", functionName);
}
return reinterpret_cast<T *>(fp);
}
/* Common functions for FMI 1.0 */
fmi1GetTypesPlatformTYPE *fmi1GetTypesPlatform;
fmi1GetVersionTYPE *fmi1GetVersion;
fmi1GetRealTYPE *fmi1GetReal;
fmi1GetIntegerTYPE *fmi1GetInteger;
fmi1GetBooleanTYPE *fmi1GetBoolean;
fmi1GetStringTYPE *fmi1GetString;
fmi1SetDebugLoggingTYPE *fmi1SetDebugLogging;
fmi1SetRealTYPE *fmi1SetReal;
fmi1SetIntegerTYPE *fmi1SetInteger;
fmi1SetBooleanTYPE *fmi1SetBoolean;
fmi1SetStringTYPE *fmi1SetString;
private:
/* Wrapper functions for SEH */
void getCString(ValueReference vr, char *value);
void setCString(ValueReference vr, const char *value);
};
class FMU1Slave : public FMU1, public Slave {
public:
FMU1Slave(const std::string &guid,
const std::string &modelIdentifier,
const std::string &unzipDirectory,
const std::string &instanceName,
allocateMemoryCallback *allocateMemory = nullptr,
freeMemoryCallback *freeMemory = nullptr);
~FMU1Slave();
void instantiateSlave(const std::string &fmuLocation, double timeout, bool loggingOn);
void initializeSlave(double startTime, bool stopTimeDefined, double stopTime);
void doStep(double h) override;
void setRealInputDerivative(ValueReference vr, int order, double value) override;
private:
/* Wrapper functions for SEH */
void instantiateSlave_(fmi1String instanceName, fmi1String fmuGUID, fmi1String fmuLocation, fmi1String mimeType, fmi1Real timeout, fmi1Boolean visible, fmi1Boolean interactive, fmi1CallbackFunctions functions, fmi1Boolean loggingOn);
void terminateSlave();
void freeSlaveInstance();
/***************************************************
Functions for FMI 1.0 for Co-Simulation
****************************************************/
fmi1InstantiateSlaveTYPE *fmi1InstantiateSlave;
fmi1InitializeSlaveTYPE *fmi1InitializeSlave;
fmi1TerminateSlaveTYPE *fmi1TerminateSlave;
fmi1ResetSlaveTYPE *fmi1ResetSlave;
fmi1FreeSlaveInstanceTYPE *fmi1FreeSlaveInstance;
fmi1GetRealOutputDerivativesTYPE *fmi1GetRealOutputDerivatives;
fmi1SetRealInputDerivativesTYPE *fmi1SetRealInputDerivatives;
fmi1DoStepTYPE *fmi1DoStep;
fmi1CancelStepTYPE *fmi1CancelStep;
fmi1GetStatusTYPE *fmi1GetStatus;
fmi1GetRealStatusTYPE *fmi1GetRealStatus;
fmi1GetIntegerStatusTYPE *fmi1GetIntegerStatus;
fmi1GetBooleanStatusTYPE *fmi1GetBooleanStatus;
fmi1GetStringStatusTYPE *fmi1GetStringStatus;
};
class FMU1Model : public FMU1, public Model {
public:
explicit FMU1Model( const std::string &guid,
const std::string &modelIdentifier,
const std::string &unzipDirectory,
const std::string &instanceName,
allocateMemoryCallback *allocateMemory = nullptr,
freeMemoryCallback *freeMemory = nullptr);
~FMU1Model();
void instantiateModel(bool loggingOn);
void initialize(bool toleranceControlled, double relativeTolerance);
void getContinuousStates(double states[], size_t size) override;
void getNominalContinuousStates(double states[], size_t size) override;
void setContinuousStates(const double states[], size_t size) override;
void getDerivatives(double derivatives[], size_t size) override;
void getEventIndicators(double eventIndicators[], size_t size) override;
void setTime(double time) override;
bool completedIntegratorStep() override;
void eventUpdate();
bool iterationConverged() const { return m_eventInfo.iterationConverged != fmi1False; }
bool stateValueReferencesChanged() const { return m_eventInfo.stateValueReferencesChanged != fmi1False; }
bool stateValuesChanged() const { return m_eventInfo.stateValuesChanged != fmi1False; }
bool terminateSimulation() const { return m_eventInfo.terminateSimulation != fmi1False; }
bool upcomingTimeEvent() const { return m_eventInfo.upcomingTimeEvent != fmi1False; }
double nextEventTime() const override { return m_eventInfo.nextEventTime; }
private:
fmi1EventInfo m_eventInfo;
/* Wrapper functions for SEH */
void instantiateModel_(fmi1String instanceName, fmi1String GUID, fmi1CallbackFunctions functions, fmi1Boolean loggingOn);
void terminate();
void freeModelInstance();
/* Functions for FMI 1.0 for Model Exchange */
fmi1GetModelTypesPlatformTYPE *fmi1GetModelTypesPlatform;
fmi1InstantiateModelTYPE *fmi1InstantiateModel;
fmi1FreeModelInstanceTYPE *fmi1FreeModelInstance;
fmi1SetTimeTYPE *fmi1SetTime;
fmi1SetContinuousStatesTYPE *fmi1SetContinuousStates;
fmi1CompletedIntegratorStepTYPE *fmi1CompletedIntegratorStep;
fmi1InitializeTYPE *fmi1Initialize;
fmi1GetDerivativesTYPE *fmi1GetDerivatives;
fmi1GetEventIndicatorsTYPE *fmi1GetEventIndicators;
fmi1EventUpdateTYPE *fmi1EventUpdate;
fmi1GetContinuousStatesTYPE *fmi1GetContinuousStates;
fmi1GetNominalContinuousStatesTYPE *fmi1GetNominalContinuousStates;
fmi1GetStateValueReferencesTYPE *fmi1GetStateValueReferences;
fmi1TerminateTYPE *fmi1Terminate;
};
}
|
// Created on: 2016-04-07
// Copyright (c) 2016 OPEN CASCADE SAS
// Created by: Oleg AGASHIN
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IMeshData_Model_HeaderFile
#define _IMeshData_Model_HeaderFile
#include <IMeshData_Shape.hxx>
#include <Standard_Type.hxx>
#include <TopoDS_Shape.hxx>
#include <IMeshData_Types.hxx>
class TopoDS_Face;
class TopoDS_Edge;
//! Interface class representing discrete model of a shape.
class IMeshData_Model : public IMeshData_Shape
{
public:
//! Destructor.
virtual ~IMeshData_Model()
{
}
//! Returns maximum size of shape model.
Standard_EXPORT virtual Standard_Real GetMaxSize () const = 0;
DEFINE_STANDARD_RTTIEXT(IMeshData_Model, IMeshData_Shape)
public: //! @name discrete faces
//! Returns number of faces in discrete model.
Standard_EXPORT virtual Standard_Integer FacesNb () const = 0;
//! Adds new face to shape model.
Standard_EXPORT virtual const IMeshData::IFaceHandle& AddFace (const TopoDS_Face& theFace) = 0;
//! Gets model's face with the given index.
Standard_EXPORT virtual const IMeshData::IFaceHandle& GetFace (const Standard_Integer theIndex) const = 0;
public: //! @name discrete edges
//! Returns number of edges in discrete model.
Standard_EXPORT virtual Standard_Integer EdgesNb () const = 0;
//! Adds new edge to shape model.
Standard_EXPORT virtual const IMeshData::IEdgeHandle& AddEdge (const TopoDS_Edge& theEdge) = 0;
//! Gets model's edge with the given index.
Standard_EXPORT virtual const IMeshData::IEdgeHandle& GetEdge (const Standard_Integer theIndex) const = 0;
protected:
//! Constructor.
//! Initializes empty model.
IMeshData_Model (const TopoDS_Shape& theShape)
: IMeshData_Shape(theShape)
{
}
};
#endif
|
#ifndef SRC_CLEANUP_H
#define SRC_CLEANUP_H
/**
* Remove all children from this Trie - this Trie shall become a leaf.
*/
template<class T> void TrieNode<T>::clear()
{
if (!this->hasChildren()) {
return;
}
for (int i = 0; i < children.size(); i++) {
delete children[i];
}
children.clear();
}
/**
* Invoked when this TrieNode is being deleted. At that time, free all of the children as well.
*/
template<class T> TrieNode<T>::~TrieNode()
{
clear();
}
#endif // SRC_CLEANUP_H
|
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
ULL a[222222];
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
int n;
scanf("%d", &n);
ULL tot = ULL(12) * 1000000 * 1000000;
ULL sum = 0;
for (int i = 0; i < n; ++i) {
int x, y, z;
scanf("%d%d%d", &x, &y, &z);
a[i] = (((ULL(x) * 1000000) + y) * 1000000) + z;
sum += a[i];
}
for (int i = 0; i < n; ++i) a[i + n] = a[i] + tot;
sort(a, a + n);
ULL sum1 = 0, sum2 = 0;
ULL ans = 9e18;
int c1 = 0;
for (int i = 0, j = 0; i < n; ++i) {
while (j < n + i && a[j] <= a[i] + tot / 2) {
sum1 += a[j];
sum2 += a[j];
if (j >= n) sum2 -= tot;
++c1;
++j;
}
ans = min(ans, sum1 - a[i] * c1 + tot * (n - c1) - (sum - sum2) + (n - c1) * a[i]);
--c1;
sum1 -= a[i];
sum2 -= a[i];
}
cout << ((ans / 1000000) / 1000000) << " "
<< ((ans / 1000000) % 1000000) << " "
<< (ans % 1000000) << endl;
return 0;
}
|
#ifndef KEYREADER_H
#define KEYREADER_H
#include <QKeyEvent>
class KeyReader
{
public:
KeyReader();
static char _key_pressed;
};
#endif // KEYREADER_H
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "SelfReplicator.h"
// Sets default values
ASelfReplicator::ASelfReplicator()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
staticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>("RootStaticMesh");
rootSceneComponent = CreateDefaultSubobject<USceneComponent>("Root");
RootComponent = rootSceneComponent;
staticMeshComponent->AttachTo(rootSceneComponent);
auto staticMeshAsset = ConstructorHelpers::FObjectFinder<UStaticMesh>(TEXT("StaticMesh'/Engine/BasicShapes/Sphere.Sphere'"));
if (staticMeshAsset.Object != nullptr) {
staticMeshComponent->SetStaticMesh(staticMeshAsset.Object);
}
}
void ASelfReplicator::incrementReplicaCount() {
static int replicaCount = 0;
replicaCount += 1;
GEngine->AddOnScreenDebugMessage(-1, 10, FColor::Red, FString::Printf(TEXT("Repica count: %i"), replicaCount));
if (replicaCount < 20) {
auto actorSpawnLocation = this->GetTargetLocation() + FVector(50 * FMath::FRandRange(-1, 1), 50 * FMath::FRandRange(-1, 1), 50 * FMath::FRandRange(-1, 1));
UWorld* world = this->GetWorld();
world->SpawnActor(ASelfReplicator::StaticClass(), &actorSpawnLocation);
}
}
// Called when the game starts or when spawned
void ASelfReplicator::BeginPlay()
{
Super::BeginPlay();
incrementReplicaCount();
}
// Called every frame
void ASelfReplicator::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
|
//===-- OR1KFixupKinds.h - OR1K Specific Fixup Entries ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_OR1K_OR1KFIXUPKINDS_H
#define LLVM_OR1K_OR1KFIXUPKINDS_H
#include "llvm/MC/MCFixup.h"
namespace llvm {
namespace OR1K {
// Although most of the current fixup types reflect a unique relocation
// one can have multiple fixup types for a given relocation and thus need
// to be uniquely named.
//
// This table *must* be in the save order of
// MCFixupKindInfo Infos[OR1K::NumTargetFixupKinds]
// in OR1KAsmBackend.cpp.
//
enum Fixups {
// Results in R_OR1K_NONE
fixup_OR1K_NONE = FirstTargetFixupKind,
// Results in R_OR1K_32
fixup_OR1K_32,
// Results in R_OR1K_16
fixup_OR1K_16,
// Results in R_OR1K_8
fixup_OR1K_8,
// Results in R_OR1K_LO_16_IN_INSN
fixup_OR1K_LO16_INSN,
// Results in R_OR1K_HI_16_IN_INSN
fixup_OR1K_HI16_INSN,
// Results in R_OR1K_INSN_REL_26
fixup_OR1K_REL26,
// Results in R_OR1K_32_PCREL
fixup_OR1K_PCREL32,
// Results in R_OR1K_16_PCREL
fixup_OR1K_PCREL16,
// Results in R_OR1K_8_PCREL
fixup_OR1K_PCREL8,
// Results in R_OR1K_GOTPC_HI16
fixup_OR1K_GOTPC_HI16,
// Results in R_OR1K_GOTPC_LO16
fixup_OR1K_GOTPC_LO16,
// Results in R_OR1K_GOT16
fixup_OR1K_GOT16,
// Results in R_OR1K_PLT26
fixup_OR1K_PLT26,
// Results in R_OR1K_GOTOFF_HI16
fixup_OR1K_GOTOFF_HI16,
// Results in R_OR1K_GOTOFF_LO16
fixup_OR1K_GOTOFF_LO16,
// Results in R_OR1K_COPY
fixup_OR1K_COPY,
// Results in R_OR1K_GLOB_DAT
fixup_OR1K_GLOB_DAT,
// Results in R_OR1K_JMP_SLOT
fixup_OR1K_JMP_SLOT,
// Results in R_OR1K_RELATIVE
fixup_OR1K_RELATIVE,
// Marker
LastTargetFixupKind,
NumTargetFixupKinds = LastTargetFixupKind - FirstTargetFixupKind
};
} // end namespace OR1K
} // end namespace llvm
#endif
|
class MH60S;
class MH60S_DZ : MH60S {
displayName = "$STR_VEH_NAME_MH60";
vehicleClass = "DayZ Epoch Vehicles";
scope = 2;
crew = "";
typicalCargo[] = {};
class TransportMagazines{};
class TransportWeapons{};
weapons[] = {"CMFlareLauncher"};
magazines[] = {"120Rnd_CMFlareMagazine"};
class Turrets;
class MainTurret;
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
transportMaxWeapons = 20;
transportMaxMagazines = 100;
transportMaxBackpacks = 6;
armor = 35;
damageResistance = 0.00242;
attendant = 0;
transportAmmo = 0;
radartype = 0;
supplyRadius = 2.6;
enableManualFire = 0;
fuelCapacity = 2760;
};
class MH60S_DZE : MH60S_DZ {
class Turrets : Turrets {
class MainTurret : MainTurret {
discreteDistance[] = {100, 200, 300, 400, 500, 600, 700, 800};
discreteDistanceInitIndex = 2;
gunnerCompartments = "Compartment1";
initElev = 5;
initTurn = 80;
body = "mainTurret";
gun = "mainGun";
minElev = -80;
maxElev = 25;
minTurn = 30;
maxTurn = 150;
soundServo[] = {"",0.01,1};
stabilizedInAxes = "StabilizedInAxesNone";
gunBeg = "muzzle_1"; // endpoint of the gun
gunEnd = "chamber_1"; // chamber of the gun
turretInfoType = "RscWeaponZeroing";
weapons[] = {"M240BC_veh"};
magazines[] = {};
gunnerName = $STR_POSITION_CREWCHIEF;
gunnerOpticsModel = "\ca\weapons\optika_empty";
gunnerOutOpticsShowCursor = 1;
gunnerOpticsShowCursor = 1;
gunnerAction = "MH60_Gunner";
gunnerInAction = "MH60_Gunner";
primaryGunner = 1;
class ViewOptics {
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.7;
minFov = 0.25;
maxFov = 1.1;
};
};
class RightDoorGun : MainTurret {
body = "Turret_2";
gun = "Gun_2";
animationSourceBody = "Turret_2";
animationSourceGun = "Gun_2";
weapons[] = {"M240BC_veh_2"};
animationSourceHatch = "";
selectionFireAnim = "zasleh_1";
proxyIndex = 2;
gunnerName = $STR_POSITION_DOORGUNNER;
commanding = -2;
minTurn = -150;
maxTurn = -30;
initTurn = -80;
stabilizedInAxes = "StabilizedInAxesNone";
gunBeg = "muzzle_2"; // endpoint of the gun
gunEnd = "chamber_2"; // chamber of the gun
primaryGunner = 0;
memoryPointGun = "machinegun_2";
memoryPointGunnerOptics = "gunnerview_2";
};
};
class Upgrades
{
ItemHeliAVE[] = {"MH60S_DZE1",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliAVE",1},{"equip_metal_sheet",5},{"ItemScrews",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class MH60S_DZE1: MH60S_DZE
{
displayName = "$STR_VEH_NAME_MH60+";
original = "MH60S_DZE";
armor = 80;
damageResistance = 0.02078;
class Upgrades
{
ItemHeliLRK[] = {"MH60S_DZE2",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliLRK",1},{"PartGeneric",2},{"ItemScrews",1},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class MH60S_DZE2: MH60S_DZE1
{
displayName = "$STR_VEH_NAME_MH60++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportMaxBackpacks = 12;
class Upgrades
{
ItemHeliTNK[] = {"MH60S_DZE3",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliTNK",1},{"PartFueltank",2},{"PartGeneric",2},{"ItemFuelBarrel",1},{"ItemTinBar",1},{"equip_scrapelectronics",1},{"equip_floppywire",1}}};
};
};
class MH60S_DZE3: MH60S_DZE2
{
displayName = "$STR_VEH_NAME_MH60+++";
fuelCapacity = 5800;
};
class UH60M_EP1;
class UH60M_EP1_DZ: UH60M_EP1 {
displayName = "$STR_VEH_NAME_UH60";
vehicleClass = "DayZ Epoch Vehicles";
scope = 2;
crew = "";
typicalCargo[] = {};
class TransportMagazines{};
class TransportWeapons{};
weapons[] = {"CMFlareLauncher"};
magazines[] = {"120Rnd_CMFlareMagazine"};
class Turrets;
class MainTurret;
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
transportMaxWeapons = 20;
transportMaxMagazines = 100;
transportMaxBackpacks = 6;
fuelCapacity = 2760;
radartype = 0;
supplyRadius = 2.6;
};
class UH60M_EP1_DZE: UH60M_EP1_DZ {
enableManualFire = 0;
class Turrets: Turrets {
class MainTurret: MainTurret {
body = "mainTurret";
gun = "mainGun";
minElev = -60;
maxElev = 30;
initElev = 0;
minTurn = -7;
maxTurn = 183;
initTurn = 0;
soundServo[] = {"",0.01,1};
animationSourceHatch = "";
stabilizedInAxes = "StabilizedInAxesNone";
gunBeg = "muzzle_1";
gunEnd = "chamber_1";
weapons[] = {"M134"};
magazines[] = {};
gunnerName = $STR_POSITION_CREWCHIEF;
gunnerOpticsModel = "\ca\weapons\optika_empty";
gunnerOutOpticsShowCursor = 1;
gunnerOpticsShowCursor = 1;
gunnerAction = "UH60M_Gunner_EP1";
gunnerInAction = "UH60M_Gunner_EP1";
commanding = -2;
primaryGunner = 1;
class ViewOptics {
initAngleX = 0;
minAngleX = -30;
maxAngleX = 30;
initAngleY = 0;
minAngleY = -100;
maxAngleY = 100;
initFov = 0.7;
minFov = 0.25;
maxFov = 1.1;
};
gunnerCompartments = "Compartment2";
};
class RightDoorGun: MainTurret {
body = "Turret_2";
gun = "Gun_2";
animationSourceBody = "Turret_2";
animationSourceGun = "Gun_2";
weapons[] = {"M134_2"};
magazines[] = {};
stabilizedInAxes = "StabilizedInAxesNone";
selectionFireAnim = "zasleh_1";
proxyIndex = 2;
gunnerName = $STR_POSITION_DOORGUNNER;
commanding = -3;
minElev = -60;
maxElev = 30;
initElev = 0;
minTurn = -183;
maxTurn = 7;
initTurn = 0;
gunBeg = "muzzle_2";
gunEnd = "chamber_2";
primaryGunner = 0;
memoryPointGun = "machinegun_1";
memoryPointGunnerOptics = "gunnerview_2";
};
};
class Upgrades
{
ItemHeliAVE[] = {"UH60M_EP1_DZE1",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliAVE",1},{"equip_metal_sheet",5},{"ItemScrews",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class UH60M_EP1_DZE1: UH60M_EP1_DZE
{
displayName = "$STR_VEH_NAME_UH60+";
original = "UH60M_EP1_DZE";
armor = 80;
damageResistance = 0.02078;
class Upgrades
{
ItemHeliLRK[] = {"UH60M_EP1_DZE2",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliLRK",1},{"PartGeneric",2},{"ItemScrews",1},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class UH60M_EP1_DZE2: UH60M_EP1_DZE1
{
displayName = "$STR_VEH_NAME_UH60++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportMaxBackpacks = 12;
class Upgrades
{
ItemHeliTNK[] = {"UH60M_EP1_DZE3",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliTNK",1},{"PartFueltank",2},{"PartGeneric",2},{"ItemFuelBarrel",1},{"ItemTinBar",1},{"equip_scrapelectronics",1},{"equip_floppywire",1}}};
};
};
class UH60M_EP1_DZE3: UH60M_EP1_DZE2
{
displayName = "$STR_VEH_NAME_UH60+++";
fuelCapacity = 5800;
};
// Unarmed medevac
class UH60M_MEV_EP1;
class UH60M_MEV_EP1_DZ : UH60M_MEV_EP1 {
displayname = "$STR_VEH_NAME_HH60";
vehicleClass = "DayZ Epoch Vehicles";
scope = 2;
crew = "";
typicalCargo[] = {};
commanderCanSee = 2+16+32;
gunnerCanSee = 2+16+32;
driverCanSee = 2+16+32;
transportMaxWeapons = 20;
transportMaxMagazines = 100;
transportMaxBackpacks = 6;
fuelCapacity = 2760;
class TransportMagazines{};
class TransportWeapons{};
attendant = 0;
radartype = 0;
supplyRadius = 2.6;
class Upgrades
{
ItemHeliAVE[] = {"UH60M_MEV_EP1_DZE1",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliAVE",1},{"equip_metal_sheet",5},{"ItemScrews",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class UH60M_MEV_EP1_DZE1: UH60M_MEV_EP1_DZ
{
displayName = "$STR_VEH_NAME_HH60+";
original = "UH60M_MEV_EP1_DZ";
armor = 80;
damageResistance = 0.02078;
class Upgrades
{
ItemHeliLRK[] = {"UH60M_MEV_EP1_DZE2",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliLRK",1},{"PartGeneric",2},{"ItemScrews",1},{"ItemWoodCrateKit",1},{"ItemGunRackKit",1},{"ItemTinBar",1},{"equip_scrapelectronics",2},{"equip_floppywire",2}}};
};
};
class UH60M_MEV_EP1_DZE2: UH60M_MEV_EP1_DZE1
{
displayName = "$STR_VEH_NAME_HH60++";
transportMaxWeapons = 40;
transportMaxMagazines = 200;
transportMaxBackpacks = 12;
class Upgrades
{
ItemHeliTNK[] = {"UH60M_MEV_EP1_DZE3",{"ItemToolbox","ItemSolder_DZE"},{},{{"ItemHeliTNK",1},{"PartFueltank",2},{"PartGeneric",2},{"ItemFuelBarrel",1},{"ItemTinBar",1},{"equip_scrapelectronics",1},{"equip_floppywire",1}}};
};
};
class UH60M_MEV_EP1_DZE3: UH60M_MEV_EP1_DZE2
{
displayName = "$STR_VEH_NAME_HH60+++";
fuelCapacity = 5800;
};
|
// Created on: 1992-10-20
// Created by: Remi GILET
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Geom2dGcc_Circ2dTanOnRad_HeaderFile
#define _Geom2dGcc_Circ2dTanOnRad_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <TColgp_Array1OfCirc2d.hxx>
#include <GccEnt_Array1OfPosition.hxx>
#include <TColStd_Array1OfInteger.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <GccEnt_Position.hxx>
class Geom2dGcc_QualifiedCurve;
class Geom2dAdaptor_Curve;
class Geom2d_Point;
class GccAna_Circ2dTanOnRad;
class Geom2dGcc_Circ2dTanOnRadGeo;
class gp_Circ2d;
class gp_Pnt2d;
//! This class implements the algorithms used to
//! create a 2d circle tangent to a 2d entity,
//! centered on a 2d entity and with a given radius.
//! More than one argument must be a curve.
//! The arguments of all construction methods are :
//! - The qualified element for the tangency constrains
//! (QualifiedCirc, QualifiedLin, QualifiedCurvPoints).
//! - The Center element (circle, line, curve).
//! - A real Tolerance.
//! Tolerance is only used in the limits cases.
//! For example :
//! We want to create a circle tangent to an OutsideCurv Cu1
//! centered on a line OnLine with a radius Radius and with
//! a tolerance Tolerance.
//! If we did not used Tolerance it is impossible to
//! find a solution in the following case : OnLine is
//! outside Cu1. There is no intersection point between Cu1
//! and OnLine. The distance between the line and the
//! circle is greater than Radius.
//! With Tolerance we will give a solution if the
//! distance between Cu1 and OnLine is lower than or
//! equal Tolerance.
class Geom2dGcc_Circ2dTanOnRad
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs one or more 2D circles of radius Radius,
//! centered on the 2D curve OnCurv and:
//! - tangential to the curve Qualified1
Standard_EXPORT Geom2dGcc_Circ2dTanOnRad(const Geom2dGcc_QualifiedCurve& Qualified1, const Geom2dAdaptor_Curve& OnCurv, const Standard_Real Radius, const Standard_Real Tolerance);
//! Constructs one or more 2D circles of radius Radius,
//! centered on the 2D curve OnCurv and:
//! passing through the point Point1.
//! OnCurv is an adapted curve, i.e. an object which is an
//! interface between:
//! - the services provided by a 2D curve from the package Geom2d,
//! - and those required on the curve by the construction algorithm.
//! Similarly, the qualified curve Qualified1 is created from
//! an adapted curve.
//! Adapted curves are created in the following way:
//! Handle(Geom2d_Curve) myCurveOn = ... ;
//! Geom2dAdaptor_Curve OnCurv ( myCurveOn ) ;
//! The algorithm is then constructed with this object:
//! Handle(Geom2d_Curve) myCurve1 = ...
//! ;
//! Geom2dAdaptor_Curve Adapted1 ( myCurve1 ) ;
//! Geom2dGcc_QualifiedCurve
//! Qualified1 = Geom2dGcc::Outside(Adapted1);
//! Standard_Real Radius = ... , Tolerance = ... ;
//! Geom2dGcc_Circ2dTanOnRad
//! myAlgo ( Qualified1 , OnCurv , Radius , Tolerance ) ;
//! if ( myAlgo.IsDone() )
//! { Standard_Integer Nbr = myAlgo.NbSolutions() ;
//! gp_Circ2d Circ ;
//! for ( Standard_Integer i = 1 ;
//! i <= nbr ; i++ )
//! { Circ = myAlgo.ThisSolution (i) ;
//! ...
//! }
//! }
Standard_EXPORT Geom2dGcc_Circ2dTanOnRad(const Handle(Geom2d_Point)& Point1, const Geom2dAdaptor_Curve& OnCurv, const Standard_Real Radius, const Standard_Real Tolerance);
Standard_EXPORT void Results (const GccAna_Circ2dTanOnRad& Circ);
Standard_EXPORT void Results (const Geom2dGcc_Circ2dTanOnRadGeo& Circ);
//! Returns true if the construction algorithm does not fail
//! (even if it finds no solution).
//! Note: IsDone protects against a failure arising from a
//! more internal intersection algorithm which has reached
//! its numeric limits.
Standard_EXPORT Standard_Boolean IsDone() const;
//! Returns the number of circles, representing solutions
//! computed by this algorithm.
//! Exceptions: StdFail_NotDone if the construction fails.
Standard_EXPORT Standard_Integer NbSolutions() const;
//! Returns the solution number Index and raises OutOfRange
//! exception if Index is greater than the number of solutions.
//! Be careful: the Index is only a way to get all the
//! solutions, but is not associated to these outside the context
//! of the algorithm-object.
//! Exceptions
//! Standard_OutOfRange if Index is less than zero or
//! greater than the number of solutions computed by this algorithm.
//! StdFail_NotDone if the construction fails.
Standard_EXPORT gp_Circ2d ThisSolution (const Standard_Integer Index) const;
//! Returns the qualifier Qualif1 of the tangency argument
//! for the solution of index Index computed by this algorithm.
//! The returned qualifier is:
//! - that specified at the start of construction when the
//! solutions are defined as enclosed, enclosing or
//! outside with respect to the arguments, or
//! - that computed during construction (i.e. enclosed,
//! enclosing or outside) when the solutions are defined
//! as unqualified with respect to the arguments, or
//! - GccEnt_noqualifier if the tangency argument is a point.
//! Exceptions
//! Standard_OutOfRange if Index is less than zero or
//! greater than the number of solutions computed by this algorithm.
//! StdFail_NotDone if the construction fails.
Standard_EXPORT void WhichQualifier (const Standard_Integer Index, GccEnt_Position& Qualif1) const;
//! Returns information about the tangency point between the
//! result number Index and the first argument.
//! ParSol is the intrinsic parameter of the point on the solution curv.
//! ParArg is the intrinsic parameter of the point on the argument curv.
//! PntSol is the tangency point on the solution curv.
//! PntArg is the tangency point on the argument curv.
//! Exceptions
//! Standard_OutOfRange if Index is less than zero or
//! greater than the number of solutions computed by this algorithm.
//! StdFail_NotDone if the construction fails.
Standard_EXPORT void Tangency1 (const Standard_Integer Index, Standard_Real& ParSol, Standard_Real& ParArg, gp_Pnt2d& PntSol) const;
//! Returns the center PntSol on the second argument (i.e.
//! line or circle) of the solution of index Index computed by
//! this algorithm.
//! ParArg is the intrinsic parameter of the point on the argument curv.
//! PntSol is the center point of the solution curv.
//! PntArg is the projection of PntSol on the argument curv.
//! Exceptions:
//! Standard_OutOfRange if Index is less than zero or
//! greater than the number of solutions computed by this algorithm.
//! StdFail_NotDone if the construction fails.
Standard_EXPORT void CenterOn3 (const Standard_Integer Index, Standard_Real& ParArg, gp_Pnt2d& PntSol) const;
//! Returns true if the solution of index Index and the first
//! argument of this algorithm are the same (i.e. there are 2
//! identical circles).
//! If Rarg is the radius of the first argument, Rsol is the
//! radius of the solution and dist is the distance between
//! the two centers, we consider the two circles to be
//! identical if |Rarg - Rsol| and dist are less than
//! or equal to the tolerance criterion given at the time of
//! construction of this algorithm.
//! OutOfRange is raised if Index is greater than the number of solutions.
//! notDone is raised if the construction algorithm did not succeed.
Standard_EXPORT Standard_Boolean IsTheSame1 (const Standard_Integer Index) const;
protected:
private:
Standard_Boolean WellDone;
Standard_Integer NbrSol;
TColgp_Array1OfCirc2d cirsol;
GccEnt_Array1OfPosition qualifier1;
TColStd_Array1OfInteger TheSame1;
TColgp_Array1OfPnt2d pnttg1sol;
TColStd_Array1OfReal par1sol;
TColStd_Array1OfReal pararg1;
TColgp_Array1OfPnt2d pntcen3;
TColStd_Array1OfReal parcen3;
};
#endif // _Geom2dGcc_Circ2dTanOnRad_HeaderFile
|
class G36K_Camo_DZ : G36C
{
model = "z\addons\dayz_communityweapons\g36\g36k_camo.p3d";
picture = "\z\addons\dayz_communityweapons\g36\data\w_g36k_camo_ca.paa";
displayName = $STR_DZ_WPN_G36K_CAMO_NAME;
magazines[] =
{
30Rnd_556x45_G36,
100Rnd_556x45_BetaCMag,
30Rnd_556x45_Stanag,
20Rnd_556x45_Stanag,
60Rnd_556x45_Stanag_Taped
};
//G36 Optic
optics = true;
opticsDisablePeripherialVision = true;
modelOptics = "z\addons\dayz_communityweapons\g36\2dscope_g36.p3d";
opticsPPEffects[]={"OpticsCHAbera1","OpticsBlur2"};
opticsZoomMin=0.083; opticsZoomMax=0.083;
distanceZoomMin=100; distanceZoomMax=100;
dexterity = 1.8;
class Single : Single
{
dispersion = 0.0011;
};
class Burst : Burst
{
dispersion = 0.0011;
};
class FullAuto : FullAuto
{
dispersion = 0.0011;
};
class OpticsModes
{
class Kolimator
{
opticsID = 1;
useModelOptics = false;
opticsFlare = false;
opticsDisablePeripherialVision = false;
opticsZoomMin=0.25;
opticsZoomMax=1.1;
opticsZoomInit=0.5;
distanceZoomMin=100;
distanceZoomMax=100;
memoryPointCamera = "eye";
visionMode[] = {};
opticsPPEffects[]={"OpticsCHAbera1","OpticsBlur1"};
cameraDir = "";
};
class Scope
{
opticsID = 2;
useModelOptics = true;
opticsFlare = true;
opticsDisablePeripherialVision = true;
opticsZoomMin = 0.083;
opticsZoomMax = 0.083;
opticsZoomInit= 0.083;
distanceZoomMin=200;
distanceZoomMax=200;
memoryPointCamera = "opticView";
visionMode[] = {"Normal"};
opticsPPEffects[]={"OpticsCHAbera1","OpticsBlur1"};
cameraDir = "";
};
};
//G36 Optic end
class Attachments
{
Attachment_Sup556 = "G36K_Camo_SD_DZ";
};
};
class G36K_Camo_SD_DZ : G36_C_SD_eotech
{
model = "z\addons\dayz_communityweapons\g36\g36k_camo_sd.p3d";
picture = "\z\addons\dayz_communityweapons\g36\data\w_g36k_camo_sd_ca.paa";
displayName = $STR_DZ_WPN_G36K_CAMO_SD_NAME;
magazines[] =
{
30Rnd_556x45_G36SD,
30Rnd_556x45_StanagSD,
60Rnd_556x45_StanagSD_Taped,
100Rnd_556x45_BetaCMagSD
};
//G36 Optic
optics = true;
opticsDisablePeripherialVision = true;
modelOptics = "z\addons\dayz_communityweapons\g36\2dscope_g36_noflash.p3d";
opticsPPEffects[]={"OpticsCHAbera1","OpticsBlur2"};
opticsZoomMin=0.083; opticsZoomMax=0.083;
distanceZoomMin=100; distanceZoomMax=100;
dexterity = 1.7;
class Single : Single
{
dispersion = 0.0011;
};
class Burst : Burst
{
dispersion = 0.0011;
};
class FullAuto : FullAuto
{
dispersion = 0.0011;
};
class OpticsModes
{
class Kolimator
{
opticsID = 1;
useModelOptics = false;
opticsFlare = false;
opticsDisablePeripherialVision = false;
opticsZoomMin=0.25;
opticsZoomMax=1.1;
opticsZoomInit=0.5;
distanceZoomMin=100;
distanceZoomMax=100;
memoryPointCamera = "eye";
visionMode[] = {};
opticsPPEffects[]={"OpticsCHAbera1","OpticsBlur1"};
cameraDir = "";
};
class Scope
{
opticsID = 2;
useModelOptics = true;
opticsFlare = true;
opticsDisablePeripherialVision = true;
opticsZoomMin = 0.083;
opticsZoomMax = 0.083;
opticsZoomInit= 0.083;
distanceZoomMin=200;
distanceZoomMax=200;
memoryPointCamera = "opticView";
visionMode[] = {"Normal"};
opticsPPEffects[]={"OpticsCHAbera1","OpticsBlur1"};
cameraDir = "";
};
};
//G36 Optic end
class ItemActions
{
class RemoveSuppressor
{
text = $STR_ATTACHMENT_RMVE_Silencer;
script = "; ['Attachment_Sup556',_id,'G36K_Camo_DZ'] call player_removeAttachment";
};
};
};
class G36A_Camo_DZ : G36K_Camo_DZ
{
model = "z\addons\dayz_communityweapons\g36\g36a_camo.p3d";
picture = "\z\addons\dayz_communityweapons\g36\data\w_g36a_camo_ca.paa";
displayName = $STR_DZ_WPN_G36A_CAMO_NAME;
dexterity = 1.66;
class Single : Single
{
dispersion = 0.0007;
};
class Burst : Burst
{
dispersion = 0.0007;
};
class FullAuto : FullAuto
{
dispersion = 0.0007;
};
class Attachments
{
Attachment_Sup556 = "G36A_Camo_SD_DZ";
};
};
class G36A_Camo_SD_DZ : G36K_Camo_SD_DZ
{
model = "z\addons\dayz_communityweapons\g36\g36a_camo_sd";
picture = "\dayz_epoch_c\icons\weapons\G36A_Camo_SD.paa";
displayName = $STR_DZ_WPN_G36A_CAMO_SD_NAME;
class ItemActions
{
class RemoveSuppressor
{
text = $STR_ATTACHMENT_RMVE_Silencer;
script = "; ['Attachment_Sup556',_id,'G36A_Camo_DZ'] call player_removeAttachment";
};
};
};
|
#include "../include/MovePen.h"
|
// IP, ARP, UDP and TCP functions.
// Author: Guido Socher
// Copyright: GPL V2
//
// The TCP implementation uses some size optimisations which are valid
// only if all data can be sent in one single packet. This is however
// not a big limitation for a microcontroller as you will anyhow use
// small web-pages. The web server must send the entire web page in one
// packet. The client "web browser" as implemented here can also receive
// large pages.
//
// 2010-05-20 <jc@wippler.nl>
#include "EtherCard.h"
#include "net.h"
#undef word // arduino nonsense
#define gPB ether.buffer
#define PINGPATTERN 0x42
// Avoid spurious pgmspace warnings - http://forum.jeelabs.net/node/327
// See also http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734
//#undef PROGMEM
//#define PROGMEM __attribute__(( section(".progmem.data") ))
//#undef PSTR
//#define PSTR(s) (__extension__({static prog_char c[] PROGMEM = (s); &c[0];}))
#define TCP_STATE_SENDSYN 1
#define TCP_STATE_SYNSENT 2
#define TCP_STATE_ESTABLISHED 3
#define TCP_STATE_NOTUSED 4
#define TCP_STATE_CLOSING 5
#define TCP_STATE_CLOSED 6
#define SERIAL_PRINT 0
#define TCPCLIENT_SRC_PORT_H (rand() % 32762) << 1 | 0x01 //Source port (MSB) for TCP/IP client connections - hardcode all TCP/IP client connection from ports in range 2816-3071
static uint8_t tcpclient_src_port_l=1; // Source port (LSB) for tcp/ip client connections - increments on each TCP/IP request
static uint8_t tcp_fd; // a file descriptor, will be encoded into the port
static uint8_t tcp_client_state; //TCP connection state: 1=Send SYN, 2=SYN sent awaiting SYN+ACK, 3=Established, 4=Not used, 5=Closing, 6=Closed
static uint8_t tcp_client_port_h; // Destination port (MSB) of TCP/IP client connection
static uint8_t tcp_client_port_l; // Destination port (LSB) of TCP/IP client connection
static uint8_t (*client_tcp_result_cb)(uint8_t,uint8_t,uint16_t,uint16_t); // Pointer to callback function to handle response to current TCP/IP request
static uint16_t (*client_tcp_datafill_cb)(uint8_t); //Pointer to callback function to handle payload data in response to current TCP/IP request
static uint8_t www_fd; // ID of current http request (only one http request at a time - one of the 8 possible concurrent TCP/IP connections)
static void (*icmp_cb)(uint8_t *ip); // Pointer to callback function for ICMP ECHO response handler (triggers when localhost receives ping response (pong))
static uint8_t destmacaddr[ETH_LEN]; // storing both dns server and destination mac addresses, but at different times because both are never needed at same time.
static boolean waiting_for_dns_mac = false; //might be better to use bit flags and bitmask operations for these conditions
static boolean has_dns_mac = false;
static boolean waiting_for_dest_mac = false;
static boolean has_dest_mac = false;
static uint8_t gwmacaddr[ETH_LEN]; // Hardware (MAC) address of gateway router
static uint8_t waitgwmac; // Bitwise flags of gateway router status - see below for states
//Define gateway router ARP statuses
#define WGW_INITIAL_ARP 1 // First request, no answer yet
#define WGW_HAVE_GW_MAC 2 // Have gateway router MAC
#define WGW_REFRESHING 4 // Refreshing but already have gateway MAC
#define WGW_ACCEPT_ARP_REPLY 8 // Accept an ARP reply
static uint16_t tcp_payload_length;
static uint16_t info_data_len; // Length of TCP/IP payload
static uint8_t seqnum = 0xa; // My initial tcp sequence number
static uint8_t result_fd = 123; // Session id of last reply
static const char* result_ptr; // Pointer to TCP/IP data
#define CLIENTMSS 550
#define TCP_DATA_START ((uint16_t)TCP_SRC_PORT_H_P+(gPB[TCP_HEADER_LEN_P]>>4)*4) // Get offset of TCP/IP payload data
const unsigned char arpreqhdr[] PROGMEM = { 0,1,8,0,6,4,0,1 }; // ARP request header
const unsigned char iphdr[] PROGMEM = { 0x45,0,0,0x82,0,0,0x40,0,0x20 }; //IP header
const unsigned char ntpreqhdr[] PROGMEM = { 0xE3,0,4,0xFA,0,1,0,0,0,1 }; //NTP request header
extern const uint8_t allOnes[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; // Used for hardware (MAC) and IP broadcast addresses
static void fill_checksum(uint8_t dest, uint8_t off, uint16_t len,uint8_t type) {
const uint8_t* ptr = gPB + off;
uint32_t sum = type==1 ? IP_PROTO_UDP_V+len-8 :
type==2 ? IP_PROTO_TCP_V+len-8 : 0;
while(len >1) {
sum += (uint16_t) (((uint32_t)*ptr<<8)|*(ptr+1));
ptr+=2;
len-=2;
}
if (len)
sum += ((uint32_t)*ptr)<<8;
while (sum>>16)
sum = (uint16_t) sum + (sum >> 16);
uint16_t ck = ~ (uint16_t) sum;
gPB[dest] = ck>>8;
gPB[dest+1] = ck;
}
static void setMACs (const uint8_t *mac) {
EtherCard::copyMac(gPB + ETH_DST_MAC, mac);
EtherCard::copyMac(gPB + ETH_SRC_MAC, EtherCard::mymac);
}
static void setMACandIPs (const uint8_t *mac, const uint8_t *dst) {
setMACs(mac);
EtherCard::copyIp(gPB + IP_DST_P, dst);
EtherCard::copyIp(gPB + IP_SRC_P, EtherCard::myip);
}
static uint8_t check_ip_message_is_from(const uint8_t *ip) {
return memcmp(gPB + IP_SRC_P, ip, IP_LEN) == 0;
}
static boolean is_lan(const uint8_t source[IP_LEN], const uint8_t destination[IP_LEN]) {
if(source[0] == 0 || destination[0] == 0) {
return false;
}
for(int i = 0; i < IP_LEN; i++)
if((source[i] & EtherCard::netmask[i]) != (destination[i] & EtherCard::netmask[i])) {
return false;
}
return true;
}
static uint8_t eth_type_is_arp_and_my_ip(uint16_t len) {
return len >= 41 && gPB[ETH_TYPE_H_P] == ETHTYPE_ARP_H_V &&
gPB[ETH_TYPE_L_P] == ETHTYPE_ARP_L_V &&
memcmp(gPB + ETH_ARP_DST_IP_P, EtherCard::myip, IP_LEN) == 0;
}
static uint8_t eth_type_is_ip_and_my_ip(uint16_t len) {
return len >= 42 && gPB[ETH_TYPE_H_P] == ETHTYPE_IP_H_V &&
gPB[ETH_TYPE_L_P] == ETHTYPE_IP_L_V &&
gPB[IP_HEADER_LEN_VER_P] == 0x45 &&
(memcmp(gPB + IP_DST_P, EtherCard::myip, IP_LEN) == 0 //not my IP
|| (memcmp(gPB + IP_DST_P, EtherCard::broadcastip, IP_LEN) == 0) //not subnet broadcast
|| (memcmp(gPB + IP_DST_P, allOnes, IP_LEN) == 0)); //not global broadcasts
//!@todo Handle multicast
}
static void fill_ip_hdr_checksum() {
gPB[IP_CHECKSUM_P] = 0;
gPB[IP_CHECKSUM_P+1] = 0;
gPB[IP_FLAGS_P] = 0x40; // don't fragment
gPB[IP_FLAGS_P+1] = 0; // fragment offset
gPB[IP_TTL_P] = 64; // ttl
fill_checksum(IP_CHECKSUM_P, IP_P, IP_HEADER_LEN,0);
}
static void make_eth_ip() {
setMACs(gPB + ETH_SRC_MAC);
EtherCard::copyIp(gPB + IP_DST_P, gPB + IP_SRC_P);
EtherCard::copyIp(gPB + IP_SRC_P, EtherCard::myip);
fill_ip_hdr_checksum();
}
static void step_seq(uint16_t rel_ack_num,uint8_t cp_seq) {
uint8_t i;
uint8_t tseq;
i = 4;
while(i>0) {
rel_ack_num = gPB[TCP_SEQ_H_P+i-1]+rel_ack_num;
tseq = gPB[TCP_SEQACK_H_P+i-1];
gPB[TCP_SEQACK_H_P+i-1] = rel_ack_num;
if (cp_seq)
gPB[TCP_SEQ_H_P+i-1] = tseq;
else
gPB[TCP_SEQ_H_P+i-1] = 0; // some preset value
rel_ack_num = rel_ack_num>>8;
i--;
}
}
static void make_tcphead(uint16_t rel_ack_num,uint8_t cp_seq) {
uint8_t i = gPB[TCP_DST_PORT_H_P];
gPB[TCP_DST_PORT_H_P] = gPB[TCP_SRC_PORT_H_P];
gPB[TCP_SRC_PORT_H_P] = i;
uint8_t j = gPB[TCP_DST_PORT_L_P];
gPB[TCP_DST_PORT_L_P] = gPB[TCP_SRC_PORT_L_P];
gPB[TCP_SRC_PORT_L_P] = j;
step_seq(rel_ack_num,cp_seq);
gPB[TCP_CHECKSUM_H_P] = 0;
gPB[TCP_CHECKSUM_L_P] = 0;
gPB[TCP_HEADER_LEN_P] = 0x50;
}
static void make_arp_answer_from_request() {
setMACs(gPB + ETH_SRC_MAC);
gPB[ETH_ARP_OPCODE_H_P] = ETH_ARP_OPCODE_REPLY_H_V;
gPB[ETH_ARP_OPCODE_L_P] = ETH_ARP_OPCODE_REPLY_L_V;
EtherCard::copyMac(gPB + ETH_ARP_DST_MAC_P, gPB + ETH_ARP_SRC_MAC_P);
EtherCard::copyMac(gPB + ETH_ARP_SRC_MAC_P, EtherCard::mymac);
EtherCard::copyIp(gPB + ETH_ARP_DST_IP_P, gPB + ETH_ARP_SRC_IP_P);
EtherCard::copyIp(gPB + ETH_ARP_SRC_IP_P, EtherCard::myip);
EtherCard::packetSend(42);
}
static void make_echo_reply_from_request(uint16_t len) {
make_eth_ip();
gPB[ICMP_TYPE_P] = ICMP_TYPE_ECHOREPLY_V;
if (gPB[ICMP_CHECKSUM_P] > (0xFF-0x08))
gPB[ICMP_CHECKSUM_P+1]++;
gPB[ICMP_CHECKSUM_P] += 0x08;
EtherCard::packetSend(len);
}
bool EtherCard::tcpconnected() {
return tcp_client_state == TCP_STATE_ESTABLISHED;
}
static void make_tcp_synack_from_syn() {
gPB[IP_TOTLEN_H_P] = 0;
gPB[IP_TOTLEN_L_P] = IP_HEADER_LEN+TCP_HEADER_LEN_PLAIN+4;
make_eth_ip();
gPB[TCP_FLAGS_P] = TCP_FLAGS_SYNACK_V;
make_tcphead(1,0);
gPB[TCP_SEQ_H_P+0] = 0;
gPB[TCP_SEQ_H_P+1] = 0;
gPB[TCP_SEQ_H_P+2] = seqnum;
gPB[TCP_SEQ_H_P+3] = 0;
seqnum += 3;
gPB[TCP_OPTIONS_P] = 2;
gPB[TCP_OPTIONS_P+1] = 4;
gPB[TCP_OPTIONS_P+2] = 0x05;
gPB[TCP_OPTIONS_P+3] = 0x0;
gPB[TCP_HEADER_LEN_P] = 0x60;
gPB[TCP_WIN_SIZE] = 0x5; // 1400=0x578
gPB[TCP_WIN_SIZE+1] = 0x78;
fill_checksum(TCP_CHECKSUM_H_P, IP_SRC_P, 8+TCP_HEADER_LEN_PLAIN+4,2);
EtherCard::packetSend(IP_HEADER_LEN+TCP_HEADER_LEN_PLAIN+4+ETH_HEADER_LEN);
}
uint16_t EtherCard::getTcpPayloadLength() {
int16_t i = (((int16_t)gPB[IP_TOTLEN_H_P])<<8)|gPB[IP_TOTLEN_L_P];
i -= IP_HEADER_LEN;
i -= (gPB[TCP_HEADER_LEN_P]>>4)*4; // generate len in bytes;
if (i<=0)
i = 0;
return (uint16_t)i;
}
static void make_tcp_ack_from_any(int16_t datlentoack,uint8_t addflags) {
gPB[TCP_FLAGS_P] = TCP_FLAGS_ACK_V|addflags;
if (addflags!=TCP_FLAGS_RST_V && datlentoack==0)
datlentoack = 1;
make_tcphead(datlentoack,1); // no options
uint16_t j = IP_HEADER_LEN+TCP_HEADER_LEN_PLAIN;
gPB[IP_TOTLEN_H_P] = j>>8;
gPB[IP_TOTLEN_L_P] = j;
make_eth_ip();
gPB[TCP_WIN_SIZE] = 0x4; // 1024=0x400, 1280=0x500 2048=0x800 768=0x300
gPB[TCP_WIN_SIZE+1] = 0;
fill_checksum(TCP_CHECKSUM_H_P, IP_SRC_P, 8+TCP_HEADER_LEN_PLAIN,2);
EtherCard::packetSend(IP_HEADER_LEN+TCP_HEADER_LEN_PLAIN+ETH_HEADER_LEN);
}
static void make_tcp_ack_with_data_noflags(uint16_t dlen) {
uint16_t j = IP_HEADER_LEN+TCP_HEADER_LEN_PLAIN+dlen;
gPB[IP_TOTLEN_H_P] = j>>8;
gPB[IP_TOTLEN_L_P] = j;
fill_ip_hdr_checksum();
gPB[TCP_CHECKSUM_H_P] = 0;
gPB[TCP_CHECKSUM_L_P] = 0;
fill_checksum(TCP_CHECKSUM_H_P, IP_SRC_P, 8+TCP_HEADER_LEN_PLAIN+dlen,2);
EtherCard::packetSend(IP_HEADER_LEN+TCP_HEADER_LEN_PLAIN+dlen+ETH_HEADER_LEN);
}
static uint32_t getBigEndianLong(byte offs) { //get the sequence number of packets after an ack from GET
return (((unsigned long)gPB[offs]*256+gPB[offs+1])*256+gPB[offs+2])*256+gPB[offs+3];
} //thanks to mstuetz for the missing (unsigned long)
// static void setSequenceNumber(uint32_t seq) {
// gPB[TCP_SEQ_H_P] = (seq & 0xff000000 ) >> 24;
// gPB[TCP_SEQ_H_P+1] = (seq & 0xff0000 ) >> 16;
// gPB[TCP_SEQ_H_P+2] = (seq & 0xff00 ) >> 8;
// gPB[TCP_SEQ_H_P+3] = (seq & 0xff );
// }
uint32_t EtherCard::getSequenceNumber() {
return getBigEndianLong(TCP_SEQ_H_P);
}
void EtherCard::clientIcmpRequest(const uint8_t *destip) {
if(is_lan(EtherCard::myip, destip)) {
setMACandIPs(destmacaddr, destip);
} else {
setMACandIPs(gwmacaddr, destip);
}
gPB[ETH_TYPE_H_P] = ETHTYPE_IP_H_V;
gPB[ETH_TYPE_L_P] = ETHTYPE_IP_L_V;
memcpy_P(gPB + IP_P,iphdr,sizeof iphdr);
gPB[IP_TOTLEN_L_P] = 0x54;
gPB[IP_PROTO_P] = IP_PROTO_ICMP_V;
fill_ip_hdr_checksum();
gPB[ICMP_TYPE_P] = ICMP_TYPE_ECHOREQUEST_V;
gPB[ICMP_TYPE_P+1] = 0; // code
gPB[ICMP_CHECKSUM_H_P] = 0;
gPB[ICMP_CHECKSUM_L_P] = 0;
gPB[ICMP_IDENT_H_P] = 5; // some number
gPB[ICMP_IDENT_L_P] = EtherCard::myip[3]; // last byte of my IP
gPB[ICMP_IDENT_L_P+1] = 0; // seq number, high byte
gPB[ICMP_IDENT_L_P+2] = 1; // seq number, low byte, we send only 1 ping at a time
memset(gPB + ICMP_DATA_P, PINGPATTERN, 56);
fill_checksum(ICMP_CHECKSUM_H_P, ICMP_TYPE_P, 56+8,0);
packetSend(98);
}
// make a arp request
static void client_arp_whohas(uint8_t *ip_we_search) {
setMACs(allOnes);
gPB[ETH_TYPE_H_P] = ETHTYPE_ARP_H_V;
gPB[ETH_TYPE_L_P] = ETHTYPE_ARP_L_V;
memcpy_P(gPB + ETH_ARP_P, arpreqhdr, sizeof arpreqhdr);
memset(gPB + ETH_ARP_DST_MAC_P, 0, ETH_LEN);
EtherCard::copyMac(gPB + ETH_ARP_SRC_MAC_P, EtherCard::mymac);
EtherCard::copyIp(gPB + ETH_ARP_DST_IP_P, ip_we_search);
EtherCard::copyIp(gPB + ETH_ARP_SRC_IP_P, EtherCard::myip);
EtherCard::packetSend(42);
}
uint8_t EtherCard::clientWaitingGw () {
return !(waitgwmac & WGW_HAVE_GW_MAC);
}
static uint8_t client_store_mac(uint8_t *source_ip, uint8_t *mac) {
if (memcmp(gPB + ETH_ARP_SRC_IP_P, source_ip, IP_LEN) != 0)
return 0;
EtherCard::copyMac(mac, gPB + ETH_ARP_SRC_MAC_P);
return 1;
}
// static void client_gw_arp_refresh() {
// if (waitgwmac & WGW_HAVE_GW_MAC)
// waitgwmac |= WGW_REFRESHING;
// }
void EtherCard::setGwIp (const uint8_t *gwipaddr) {
delaycnt = 0; //request gateway ARP lookup
waitgwmac = WGW_INITIAL_ARP; // causes an arp request in the packet loop
copyIp(gwip, gwipaddr);
}
void EtherCard::updateBroadcastAddress()
{
for(uint8_t i=0; i<IP_LEN; i++)
broadcastip[i] = myip[i] | ~netmask[i];
}
static void client_syn(uint8_t srcport,uint8_t dstport_h,uint8_t dstport_l) {
if(is_lan(EtherCard::myip, EtherCard::hisip)) {
setMACandIPs(destmacaddr, EtherCard::hisip);
} else {
setMACandIPs(gwmacaddr, EtherCard::hisip);
}
gPB[ETH_TYPE_H_P] = ETHTYPE_IP_H_V;
gPB[ETH_TYPE_L_P] = ETHTYPE_IP_L_V;
memcpy_P(gPB + IP_P,iphdr,sizeof iphdr);
gPB[IP_TOTLEN_L_P] = 44; // good for syn
gPB[IP_PROTO_P] = IP_PROTO_TCP_V;
fill_ip_hdr_checksum();
gPB[TCP_DST_PORT_H_P] = dstport_h;
gPB[TCP_DST_PORT_L_P] = dstport_l;
gPB[TCP_SRC_PORT_H_P] = TCPCLIENT_SRC_PORT_H;
gPB[TCP_SRC_PORT_L_P] = srcport; // lower 8 bit of src port
memset(gPB + TCP_SEQ_H_P, 0, 8);
gPB[TCP_SEQ_H_P+2] = seqnum;
seqnum += 3;
gPB[TCP_HEADER_LEN_P] = 0x60; // 0x60=24 len: (0x60>>4) * 4
gPB[TCP_FLAGS_P] = TCP_FLAGS_SYN_V;
gPB[TCP_WIN_SIZE] = 0x3; // 1024 = 0x400 768 = 0x300, initial window
gPB[TCP_WIN_SIZE+1] = 0x0;
gPB[TCP_CHECKSUM_H_P] = 0;
gPB[TCP_CHECKSUM_L_P] = 0;
gPB[TCP_CHECKSUM_L_P+1] = 0;
gPB[TCP_CHECKSUM_L_P+2] = 0;
gPB[TCP_OPTIONS_P] = 2;
gPB[TCP_OPTIONS_P+1] = 4;
gPB[TCP_OPTIONS_P+2] = (CLIENTMSS>>8);
gPB[TCP_OPTIONS_P+3] = (uint8_t) CLIENTMSS;
fill_checksum(TCP_CHECKSUM_H_P, IP_SRC_P, 8 +TCP_HEADER_LEN_PLAIN+4,2);
// 4 is the tcp mss option:
EtherCard::packetSend(IP_HEADER_LEN+TCP_HEADER_LEN_PLAIN+ETH_HEADER_LEN+4);
}
uint8_t EtherCard::clientTcpReq (uint8_t (*result_cb)(uint8_t,uint8_t,uint16_t,uint16_t),
uint16_t (*datafill_cb)(uint8_t),uint16_t port) {
client_tcp_result_cb = result_cb;
client_tcp_datafill_cb = datafill_cb;
tcp_client_port_h = port>>8;
tcp_client_port_l = port;
tcp_client_state = TCP_STATE_SENDSYN; // Flag to packetloop to initiate a TCP/IP session by send a syn
tcp_fd = (tcp_fd + 1) & 7;
return tcp_fd;
}
static uint16_t tcp_datafill_cb(uint8_t fd) {
uint16_t len = Stash::length();
Stash::extract(0, len, EtherCard::tcpOffset());
Stash::cleanup();
EtherCard::tcpOffset()[len] = 0;
#if SERIAL_PRINT
Serial.print("REQUEST: ");
Serial.println(len);
Serial.println((char*) EtherCard::tcpOffset());
#endif
result_fd = 123; // bogus value
return len;
}
static uint8_t tcp_result_cb(uint8_t fd, uint8_t status, uint16_t datapos, uint16_t datalen) {
if (status == 0) {
result_fd = fd; // a valid result has been received, remember its session id
result_ptr = (char*) ether.buffer + datapos;
tcp_payload_length = datalen;
// result_ptr[datalen] = 0;
// Serial.printlnf("DATAPOS: %d, DATALEN: %d", datapos, datalen);
// Serial.println(" <<<< ");
// for(uint16_t i=0; i<6*8; i++) {
// // if(i > 0 && i%8 == 0 && i%16!=0) { Serial.println(" ");};
// if(i > 0 && i%8 == 0) { Serial.print("\r\n"); }
// Serial.printf("[0x%02X]", ether.buffer[i]);
// }
// Serial.println("\n\r======");
}
return 1;
}
uint8_t EtherCard::tcpSend () {
// Serial.println("tcpSend");
www_fd = clientTcpReq(&tcp_result_cb, &tcp_datafill_cb, hisport);
return www_fd;
}
boolean EtherCard::tcpClosed() {
return tcp_client_state == TCP_STATE_CLOSED;
}
const char* EtherCard::tcpReply (uint8_t fd, uint16_t& len) {
if (result_fd != fd) {
// Serial.printlnf("result_fd != fd result_fd: %d fd: %d", result_fd, fd);
return 0;
}
result_fd = 123; // set to a bogus value to prevent future match
len = tcp_payload_length;
return result_ptr;
}
void EtherCard::registerPingCallback (void (*callback)(uint8_t *srcip)) {
icmp_cb = callback;
}
uint8_t EtherCard::packetLoopIcmpCheckReply (const uint8_t *ip_monitoredhost) {
return gPB[IP_PROTO_P]==IP_PROTO_ICMP_V &&
gPB[ICMP_TYPE_P]==ICMP_TYPE_ECHOREPLY_V &&
gPB[ICMP_DATA_P]== PINGPATTERN &&
check_ip_message_is_from(ip_monitoredhost);
}
uint16_t EtherCard::accept(const uint16_t port, uint16_t plen) {
uint16_t pos;
if (gPB[TCP_DST_PORT_H_P] == (port >> 8) &&
gPB[TCP_DST_PORT_L_P] == ((uint8_t) port))
{ //Packet targeted at specified port
if (gPB[TCP_FLAGS_P] & TCP_FLAGS_SYN_V)
make_tcp_synack_from_syn(); //send SYN+ACK
else if (gPB[TCP_FLAGS_P] & TCP_FLAGS_ACK_V)
{ //This is an acknowledgement to our SYN+ACK so let's start processing that payload
info_data_len = getTcpPayloadLength();
if (info_data_len > 0)
{ //Got some data
pos = TCP_DATA_START; // TCP_DATA_START is a formula
//!@todo no idea what this check pos<=plen-8 does; changed this to pos<=plen as otw. perfectly valid tcp packets are ignored; still if anybody has any idea please leave a comment
if (pos <= plen)
return pos;
}
else if (gPB[TCP_FLAGS_P] & TCP_FLAGS_FIN_V)
make_tcp_ack_from_any(0,0); //No data so close connection
}
}
return 0;
}
uint16_t EtherCard::packetLoop (uint16_t plen) {
uint16_t len;
if (plen==0) {
//Check every 65536 (no-packet) cycles whether we need to retry ARP request for gateway
if ((waitgwmac & WGW_INITIAL_ARP || waitgwmac & WGW_REFRESHING) &&
delaycnt==0 && isLinkUp()) {
client_arp_whohas(gwip);
waitgwmac |= WGW_ACCEPT_ARP_REPLY;
}
delaycnt++;
#if ETHERCARD_TCPCLIENT
//Initiate TCP/IP session if pending
if (tcp_client_state==TCP_STATE_SENDSYN && (waitgwmac & WGW_HAVE_GW_MAC)) { // send a syn
// Serial.printlnf("connection no: %d", tcpclient_src_port_l);
tcp_client_state = TCP_STATE_SYNSENT;
tcpclient_src_port_l++; // allocate a new port
client_syn(((tcp_fd<<5) | (0x1f & tcpclient_src_port_l)),tcp_client_port_h,tcp_client_port_l);
}
#endif
//!@todo this is trying to find mac only once. Need some timeout to make another call if first one doesn't succeed.
if(is_lan(myip, dnsip) && !has_dns_mac && !waiting_for_dns_mac) {
client_arp_whohas(dnsip);
waiting_for_dns_mac = true;
}
//!@todo this is trying to find mac only once. Need some timeout to make another call if first one doesn't succeed.
if(is_lan(myip, hisip) && !has_dest_mac && !waiting_for_dest_mac) {
client_arp_whohas(hisip);
waiting_for_dest_mac = true;
}
return 0;
}
if (eth_type_is_arp_and_my_ip(plen))
{ //Service ARP request
if (gPB[ETH_ARP_OPCODE_L_P]==ETH_ARP_OPCODE_REQ_L_V)
make_arp_answer_from_request();
if (waitgwmac & WGW_ACCEPT_ARP_REPLY && (gPB[ETH_ARP_OPCODE_L_P]==ETH_ARP_OPCODE_REPLY_L_V) && client_store_mac(gwip, gwmacaddr))
waitgwmac = WGW_HAVE_GW_MAC;
if (!has_dns_mac && waiting_for_dns_mac && client_store_mac(dnsip, destmacaddr)) {
has_dns_mac = true;
waiting_for_dns_mac = false;
}
if (!has_dest_mac && waiting_for_dest_mac && client_store_mac(hisip, destmacaddr)) {
has_dest_mac = true;
waiting_for_dest_mac = false;
}
return 0;
}
if (eth_type_is_ip_and_my_ip(plen)==0)
{ //Not IP so ignoring
//!@todo Add other protocols (and make each optional at compile time)
return 0;
}
#if ETHERCARD_ICMP
if (gPB[IP_PROTO_P]==IP_PROTO_ICMP_V && gPB[ICMP_TYPE_P]==ICMP_TYPE_ECHOREQUEST_V)
{ //Service ICMP echo request (ping)
if (icmp_cb)
(*icmp_cb)(&(gPB[IP_SRC_P]));
make_echo_reply_from_request(plen);
return 0;
}
#endif
#if ETHERCARD_UDPSERVER
if (ether.udpServerListening() && gPB[IP_PROTO_P]==IP_PROTO_UDP_V)
{ //Call UDP server handler (callback) if one is defined for this packet
if(ether.udpServerHasProcessedPacket(plen))
return 0; //An UDP server handler (callback) has processed this packet
}
#endif
if (plen<54 || gPB[IP_PROTO_P]!=IP_PROTO_TCP_V )
return 0; //from here on we are only interested in TCP-packets; these are longer than 54 bytes
#if ETHERCARD_TCPCLIENT
// if (gPB[TCP_DST_PORT_H_P]==TCPCLIENT_SRC_PORT_H)
if (true)
{ //Source port is in range reserved (by EtherCard) for client TCP/IP connections
if (check_ip_message_is_from(hisip)==0)
return 0; //Not current TCP/IP connection (only handle one at a time)
if (gPB[TCP_FLAGS_P] & TCP_FLAGS_RST_V)
{ //TCP reset flagged
if (client_tcp_result_cb)
(*client_tcp_result_cb)((gPB[TCP_DST_PORT_L_P]>>5)&0x7,3,0,0);
tcp_client_state = TCP_STATE_CLOSING;
return 0;
}
len = getTcpPayloadLength();
if (tcp_client_state==TCP_STATE_SYNSENT)
{ //Waiting for SYN-ACK
if ((gPB[TCP_FLAGS_P] & TCP_FLAGS_SYN_V) && (gPB[TCP_FLAGS_P] &TCP_FLAGS_ACK_V))
{ //SYN and ACK flags set so this is an acknowledgement to our SYN
make_tcp_ack_from_any(0,0);
gPB[TCP_FLAGS_P] = TCP_FLAGS_ACK_V|TCP_FLAGS_PUSH_V;
if (client_tcp_datafill_cb)
len = (*client_tcp_datafill_cb)((gPB[TCP_SRC_PORT_L_P]>>5)&0x7);
else
len = 0;
tcp_client_state = TCP_STATE_ESTABLISHED;
make_tcp_ack_with_data_noflags(len);
}
else
{ //Expecting SYN+ACK so reset and resend SYN
// for(uint16_t i =0; i < plen; i++ ) {
// if(i%8 == 0 && i!=0) { Serial.print("\t"); }
// if(i%16 == 0 && i!=0) { Serial.println("\n\r "); }
// Serial.printf("[0x%02X] ", ether.buffer[i]);
// }
tcp_client_state = TCP_STATE_SENDSYN; // retry
len++;
if (gPB[TCP_FLAGS_P] & TCP_FLAGS_ACK_V)
len = 0;
make_tcp_ack_from_any(len,TCP_FLAGS_RST_V);
delay(500000);
}
return 0;
}
if (tcp_client_state==TCP_STATE_ESTABLISHED && len>0)
{ //TCP connection established so read data
if (client_tcp_result_cb) {
uint16_t tcpstart = TCP_DATA_START; // TCP_DATA_START is a formula
uint16_t save_len = len;
if (tcpstart+len>plen)
save_len = plen-tcpstart;
(*client_tcp_result_cb)((gPB[TCP_DST_PORT_L_P]>>5)&0x7,0,tcpstart,save_len); //Call TCP handler (callback) function
if(persist_tcp_connection)
{ //Keep connection alive by sending ACK
make_tcp_ack_from_any(len,TCP_FLAGS_PUSH_V);
}
else
{ //Close connection
make_tcp_ack_from_any(len,TCP_FLAGS_PUSH_V|TCP_FLAGS_FIN_V);
tcp_client_state = TCP_STATE_CLOSED;
}
return 0;
}
}
if (tcp_client_state != TCP_STATE_CLOSING)
{ //
if (gPB[TCP_FLAGS_P] & TCP_FLAGS_FIN_V) {
if(tcp_client_state == TCP_STATE_ESTABLISHED) {
return 0; // In some instances FIN is received *before* DATA. If that is the case, we just return here and keep looking for the data packet
}
make_tcp_ack_from_any(len+1,TCP_FLAGS_PUSH_V|TCP_FLAGS_FIN_V);
tcp_client_state = TCP_STATE_CLOSED; // connection terminated
} else if (len>0) {
make_tcp_ack_from_any(len,0);
}
}
return 0;
}
#endif
#if ETHERCARD_TCPSERVER
//If we are here then this is a TCP/IP packet targeted at us and not related to our client connection so accept
return accept(hisport, plen);
#endif
}
void EtherCard::persistTcpConnection(bool persist) {
persist_tcp_connection = persist;
}
|
#include <Arduino.h>
#include "FSWebServer.h"
#include "WIFI.h"
#include "HTTPinit.h"
#include "max7219display.h"
#include "sensorsBME280.h"
#include "FileConfig.h"
#include "json.h"
extern ESP8266WebServer HTTP;
extern LedControl lc;
extern TickerScheduler ts;
void setup()
{
Serial.begin(115200);
FS_init(); //Запускаем файловую систему
configSetup = readFile("configs.json", 4096); // считали файл configs.json и поместили в переменную "configSetup"
delay(1000);
Serial.println("");
// записываем в "configJson" значение "SSDP" из "configSetup", чтобы применить
// при инициализации SSDP и последующем отображении имени в ярлыке
jsonWrite(configJson, "SSDP", jsonRead(configSetup, "SSDP"));
WIFIinit();
SSDP_init(); //Настраиваем и запускаем SSDP интерфейс
HTTP_init(); // Настраиваем и запускаем HTTP интерфейс
max7219displayInit();
wetherSensor_init(); // инициализация датчика BME280
Charts_init();
}
void loop()
{
ts.update(); // планировщик задач
HTTP.handleClient(); // отслеживает присутствие клиента и доставляет запрошенную HTML-страницу
// Serial.println(" ");
// Serial.print("Huminity: ");
// Serial.println(readDht (0));
// delay(1500);
// Serial.print("Temperature: ");
// Serial.println(readDht (1));
// printTwoNumb(27.6, 5);
// printTwoNumb(readDht (2), 5);
// printSymbolTermo();
// readDht (2);
// ccs811();
delay(1);
}
|
#pragma once
class field
{
private:
char battlefield[10][10];
public:
field();
char getFieldAtPosition(int, int);
void setField(int, int, char);
bool isTaken(int, int);
bool canPlaceShip(int, int, int, int);
void placeShip(int, int, int,int);
};
/*
0 1 2
0 + + +
1 + + +
2 + + +
*/
/*
YYYYYYY
X
X
X
*/
/*
^(1)
<-(4) ->(2)
V(3)
*/
/*
1 - x--
2 - y++
3 - x++
4 - y--
*/
|
#include<cstdio>
#include<iostream>
using namespace std;
int an[22][22][22];
int w(long long a,long long b,long long c)
{
if(a<=0 || b<=0 || c<=0)
return 1;
else
{
if(a>20 || b>20 || c>20)
return an[20][20][20]=w(20,20,20);
if(an[a][b][c]!=0)
return an[a][b][c];
else
{
if(a<b && b<c)
{
return an[a][b][c]=w(a,b,c-1)+w(a,b-1,c-1)-w(a,b-1,c);
}
else
{
return an[a][b][c]=w(a-1,b,c)+w(a-1,b-1,c)+w(a-1,b,c-1)-w(a-1,b-1,c-1);
}
}
}
}
int main()
{
long long a,b,c;
while(1)
{
cin>>a>>b>>c;
if(a==-1 && b==-1 && c==-1)
break;
else
{
cout << "w" << "(" << a << ", "<< b << ", "<< c<< ") = "<< w(a,b,c) << endl;
}
}
}
|
#include"slamBase.h"
PointCloud::Ptr image2PointCloud(cv::Mat &rgb, cv::Mat &depth, CAMERA_INTRINSIC_PARAMETERS)
{
PointCloud::Ptr cloud(new PointCloud);
for(int m=0; m<depth.rows; m++){
for(int n=0; n<dpeth.cols; n++){
ushort d = depth.ptr<ushort>(m)[n];
if(d<=0)
continue;
PointT p;
p.z = double(d) / camera.scale;
p.x = (n - camera.cx) * p.z / camera.fx;
p.y = (m - camera.cy) * p.z / camera.fy;
p.b = rgb.ptr<uchar>(m)[n*3];
p.g = rgb.ptr<uchar>(m)[n*3+1];
p.r = rgb.ptr<uchar>(m)[n*3+2];
cloud->push_back(p);
}
}
cloud->height = 1;
cloud->width = cloud->points.size();
cloud->is_dense = false;
return cloud;
}
Point3f point2dTo3d(cv::Point3f &point, CAMERA_INTRINSIC_PARAMETERS &camera)
{
cv::Point3f p;
p.z = double(point.z) / camera.scale;
p.x = (point.x - camera.cx) * p.z / camera.fx;
p.y = (point.y - camera.cy) * p.z / camera.fy;
return p;
}
void computeKeyPointAndDesp(FRAME &frame, string detector, string descriptor)
{
cv::Ptr<FeatureDetector> _detector;
cv::Ptr<DescriptorExtractor> _descriptor;
_detector = cv::FeatureDetector::create(detector.c_str());
_descriptor = cv::DescriptorExtractor::create(descriptor.c_str());
if(!_detector || !_descriptor){
cerr<<"Unknown detector or descriptor type!"<<detector<<", "<<descriptor<<endl;
return;
}
_detector->detect(frame.rgb, frame.kp);
_descriptor->compute(frame.rgb, frame.kp, frame.desp);
return;
}
RESULT_OF_PNP estimateMotion(FRAME &frame1, FRAME &frame2, CAMERA_INTRINSIC_PARAMETERS &camera)
{
static ParameterReader pd;
vector<cv::DMatch> matches;
cv::BFMatcher matcher;
matcher.match(frame1.desp, frame2.desp, matches);
RESULT_OF_PNP result;
vector<cv::DMatch> goodmatches;
double minDis = 99999.0;
double good_match_threshold = atof(pd.getData("good_match_threshold").s_str());
for(size_t i=0; i<matches.size(); i++){
if(matches[i].distance<minDis)
minDis=matches[i].distance;
}
if(minDis<10)
minDis=10;
for(size_t i=0; i<matches.size(); i++){
if(matches[i].distance<good_match_threshold*minDis)
goodmatches.push_back(matches[i]);
}
if(goodmatches.size()<5){
result.inliers = -1;
return result;
}
vector<cv::Point3f> pts_obj;
vector<cv::Point2f> pts_img;
for(size_t i=0; i<goodmatches.size(); i++){
cv::Point2f p = frame1.kp[goodmatches[i].queryIdx].pt;
ushort d = frame1.depth.ptr<ushort>(int(p.y))[int(p.x)];
if(d==0)
continue;
cv::Point3f pt(p.x, p.y, d);
cv::Point3d pd = point2dTo3d(pt, camera);
pts_obj.push_back(pd);
pts_img.push_back(cv::Point2f(frame2.kp[goodmatches[i].trainIdx].pt));
}
if(pts_obj.size()==0 || pts_img.size()==0){
result.inliers = -1;
return result;
}
double camera_matrix_data[3][3] = {
{camera.fx, 0, camera.cx},
{0, camera.fy, camera.cy},
{0,0,1}
};
cv::Mat cameraMatrix(3,3,CV_64F, camera_matrix_data); //构建相机矩阵
cv::Mat rvec, tvec, inliers;
cv::solvePnPRansac(pts_obj, pts_img, cameraMatrix, cv::Mat(), rvec, tvec, false, 100, 1.0, 100, inliers);
result.rvec = rvec;
result.tvec = tvec;
result.inliers = inliers;
return result;
}
Eigen::Isometry3d cvMat2Eigen(cv::Mat &rvec, cv::Mat &tvec)
{
cv::Mat R;
cv::Rodrigues(rvec, R);
Eigen::Matrix3d r;
for(int i=0; i<3; ++i)
for(int j=0; i<3; ++j)
r(i,j) = R.at<double>(i,j);
Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
Eigen::AngleAxisd angle(r);
T = angle;
T(0,3) = tvec.at<double>(0,0);
T(1,3) = tvec.at<double>(1,0);
T(2,3) = tvec.at<double>(2,0);
return T;
}
PointCloud::Ptr joinPointCloud(PointCloud::Ptr original, FRAME &newFrame, Eigen::Isometry3d T, CAMERA_INTRINSIC_PARAMETERS &camera)
{
PointCloud::Ptr newCloud = image2PointCloud(newFrame.rgb, newFrame.depth, camera);
PointCloud::Ptr output(new PointCloud());
pcl::transformPointCloud(*original, *output, T.matrix());
*newcloud += *output;
static pcl::VoxelGrid<PointT> voxel;
static ParameterReader pd;
double gridsize = atof(pd.getData("voxel_grid").c_str());
voxel.setLeafSize(gridsize, gridsize, gridsize);
voxel.setInputCloud(newCloud);
PointCloud::Ptr tmp(new PointCloud());
voxel.filter(*tmp);
return tmp;
}
|
#pragma once
#include "RaytracingObject.h"
#include "ImageBMP.h"
#include "Camera.h"
#include "Sample.h"
#include "Light.h"
#include "Material.h"
#include "Matte.h"
#include "Phong.h"
#include <vector>
#include "Sphere.h"
#include "Point_2D.h"
#include "Plane.h"
#include "Material.h"
#include "Matte.h"
#include "Phong.h"
#include "Lambertian.h"
#include "AmbientLight.h"
#include "DirectionalLight.h"
#include "RectangleAreaLight.h"
#include "PointLight.h"
#include "Shade.h"
#include "RGB.h"
#include <float.h>
#include <iostream>
#include <ctime>
using namespace std;
class RayTracer {
public:
Camera cam;
ImageBMP bmp;
vector<RaytracingObject*> objects;
Sample sample;
vector<Light*> ambientLight;
vector<Light*> directionalLights;
vector<Light*> pointLights;
vector<Light*> rectangleAreaLights;
RayTracer();
~RayTracer();
Material *createPhongMaterial(double ambientCoefficient, double diffuseCoefficient, double specularCoefficient, double phongExponent);
Material *createMatteMaterial(double ambientCoefficient, double diffuseCoefficient);
void createPlane(Material *mat, vector<RaytracingObject*> &objects, double w, double h, double degreeRotation, double r, double g, double b, double nx, double ny, double nz, double px, double py, double pz, bool checkered, string tag = "none");
void createSphere(Material *mat, vector<RaytracingObject*> &objects, double r, double g, double b, double ox, double oy, double oz, double radius, string tag = "none");
void createRectangleAreaLight(vector<Light*> &light, double originx, double originy, double originz, double width, double height, int samplePointWidth, double radianRotation, double r, double g, double b, double x, double y, double z, double i);
void createDirectionalLight(vector<Light*> &light, double r, double g, double b, double x, double y, double z, double i);
void createAmbientLight(vector<Light*> &light, double r, double g, double b, double i);
void createAreaPointLight(vector<Light*> &light, double radius, int samplePointAmount, double r, double g, double b, double x, double y, double z, double i);
void createImage();
void setupCamera();
void setSamples();
void setupLights();
void createGeometricObjects();
void render();
void saveImage();
};
|
#ifndef ITEM_HPP
#define ITEM_HPP
#include <QObject>
class Item : public QObject
{
Q_OBJECT
public:
Q_SLOT
void go();
};
#endif
|
#include "player.h"
#include <terrain/terrain.h>
#include <utils/timer.h>
#include <info/info.h>
namespace sloth {
void Player::move(Terrain &terrain)
{
checkInputs();
float deltaFrameTime = static_cast<float>(Timer::deltaFrameTime);
increaseRotation(0.0f, m_CurrentTurnSpeed * deltaFrameTime, 0.0f);
float distance = m_CurrentSpeed * deltaFrameTime;
float dx = distance * glm::sin(glm::radians(getRotY()));
float dz = distance * glm::cos(glm::radians(getRotY()));
increasePosition(dx, 0.0f, dz);
m_UpwardSpeed += PLAYER_GRAVITY * deltaFrameTime;
increasePosition(0.0f, m_UpwardSpeed * deltaFrameTime, 0.0f);
float terrainHeight = terrain.getHeightOfTerrain(m_Position.x, m_Position.z);
if (m_Position.y < terrainHeight) {
m_UpwardSpeed = 0;
m_Position.y = terrainHeight;
m_IsInAir = false;
}
}
void Player::jump()
{
if (!m_IsInAir) {
m_UpwardSpeed = PLAYER_JUMP_POWER;
m_IsInAir = true;
}
}
void Player::checkInputs()
{
if (Input::keys[GLFW_KEY_W]) {
m_CurrentSpeed = PLAYER_RUN_SPEED;
}
else if (Input::keys[GLFW_KEY_S]) {
m_CurrentSpeed = -PLAYER_RUN_SPEED;
}
else {
m_CurrentSpeed = 0.0f;
}
if (Input::keys[GLFW_KEY_D]) {
m_CurrentTurnSpeed = -PLAYER_TURN_SPEED;
}
else if (Input::keys[GLFW_KEY_A]) {
m_CurrentTurnSpeed = PLAYER_TURN_SPEED;
}
else {
m_CurrentTurnSpeed = 0.0f;
}
if (Input::keys[GLFW_KEY_SPACE]) {
jump();
}
}
}
|
#include "Inizialize.h"
#ifdef _WIN32
string back_slash = "\\";
#else
string back_slash = "/";
#endif
//const cv::String WINDOW_NAME("Camera video");
cv::String WINDOW_NAME;
int NumMaxFrame = 2;
const int PictureWidth = 60;
const int PictureHeight = 80;
string Time, Data;
int numDir; std::vector<string> dirList;
string path_init_Norm;
string init_path;
extern string cascade_face;
string directoryNorm;
int colNum = (PictureWidth*PictureHeight*50)/10/10; int rowNum = 1;
float theresold;
float meanTotal;
//std::vector<cv::Mat> faces;
std::vector<cv::Mat> faces(NumMaxFrame+1);
//extern cv::VideoCapture camera;
float normWidth, normHeight;
int window_width = 480;
int window_height = 350;
int window_width_laserScreen = 250;
int window_height_laserScreen = 320;
int native_width = 1920;
int native_height = 1080;
int windowSizeWidth;
int windowSizeHeight;
void SetPath(string ¤t_path);
cv::VideoCapture inizialize(int argc, char** argv, string current_path) {
int numDir; std::vector<string> dirList;
SetPath(current_path);
string directoryNorm = "Database_Normalized" + back_slash;
if (thesis::isDirectory(("Database_Normalized" + back_slash + Data + back_slash).c_str()) == 0) {
#ifdef _WIN32
ShowWindow(GetConsoleWindow(), SW_HIDE);
#endif
messageBox("", 4);
myUtils::playSound("click.wav");
exit(-1);
}
//myUtils::system_pause();
if (!myUtils::timeData(Time, Data)) {
#ifdef _WIN32
ShowWindow(GetConsoleWindow(), SW_HIDE);
#endif
messageBox("", 4);
myUtils::playSound("click.wav");
exit(-1);
}
path_init_Norm = current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash;
int numDirNorm;
if (myUtils::numDirectoryList(current_path + back_slash + "Database_Normalized", numDir, dirList) <= 1) {
messageBox("", 4);
myUtils::playSound("click.wav");
exit(-1);
}
else {
cout << "numDir " << numDir << endl;
string toFind = "-2017"; int countList = 0;
for (int i = 0; i < numDir; i++) {
if (dirList[i].length() >= 5 && dirList[i].substr(dirList[i].length() - 5, dirList[i].length()) != toFind) {
countList++;
}
}
if (countList == numDir - 2) { // le prime due solo folder di sistema...
messageBox("", 4);
myUtils::playSound("click.wav");
exit(-1);
}
}
if (!thesis::isDirectory(path_init_Norm)) {
myUtils::DataAdjust(current_path, Data, path_init_Norm);
cout << "Datacrrected: " << Data << endl;
numDirNorm = myUtils::numDirectoryList(path_init_Norm, numDir, dirList);
cout << "numdirnorm: " << numDirNorm << endl;
if (numDirNorm == 0) {
messageBox("", 4);
myUtils::playSound("click.wav");
exit(-1);
}
}
else { // controlla se la cartella cn la dta odierna esiste ma è vuota..
if (myUtils::numFileListInDirectory(path_init_Norm) <= 1) {
messageBox("", 4);
myUtils::playSound("click.wav");
exit(-1);
}
}
/*else
numDirNorm = myUtils::numDirectoryList(path_init_Norm, numDir, dirList);
numDirNorm = numDirNorm - 2;
if (myUtils::numDirectoryList(path_init_Norm, numDir, dirList) == 0) {
messageBox("", 4);
myUtils::playSound("click.wav");
return -1;
}
cout << "numdirnorm: " << numDirNorm << endl;
if (numDirNorm == 0) {
cout << "vxbcbcbc " << path_init_Norm << endl;
messageBox("", 4);
myUtils::playSound("click.wav");
return -1;
}*/
std::ifstream inNorm;
std::vector<float>meanBox;
inNorm.open((path_init_Norm + "meanBox.data").c_str(), ios::in | ios::binary);
meanBox = myUtils::loadVectorKnownSize(inNorm, NumMaxFrame/2);
cout << "<< " << meanBox.size() << endl;
int Total = 0; //float meanTotal;
for (int i = 0; i < meanBox.size();i++) {
cout << "i " << i << ": " << meanBox[i] << endl;
if (meanBox[i] != 0) {
Total = Total + meanBox[i];
}
}
meanTotal = Total/ (NumMaxFrame/2);
cout << "meanTotal: " << meanTotal << endl;
inNorm.close();
LQP_initParam();
//float theresold;
//float theresold_copy;
if (!myUtils::fexists((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info_temp.data").c_str()) && !myUtils::fexists((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info.data").c_str())) {
theresold = FindTheresoldValue();
//theresold_copy = theresold;
FILE *fp; fp = fopen((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info.data").c_str(), "wb");
myUtils::writefloat(theresold, fp);
if (!myUtils::fexists(("Database_Normalized" + back_slash + Data + back_slash + "Info.data"))) {
cout << "ERRORE" << endl;
system("pause");
return -1;
}
fclose(fp);
}
else if (myUtils::fexists((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info_temp.data").c_str())) {
FILE *fp; fp = fopen((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info_temp.data").c_str(), "rb");
float theresold_temp = myUtils::readfloat(fp);
cout << "theresold_temp: "<<theresold_temp << endl;
theresold = FindTheresoldValue(701);
if (theresold < theresold_temp)
theresold = theresold_temp;
//theresold_copy = theresold;
fclose(fp);
fp = fopen((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info.data").c_str(), "wb");
myUtils::writefloat(theresold, fp);
fclose(fp);
thesis::delete_file((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info_temp.data").c_str());
}
else if (myUtils::fexists((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info.data").c_str())) {
FILE *fp; fp = fopen((current_path + back_slash + "Database_Normalized" + back_slash + Data + back_slash + "Info.data").c_str(), "rb");
theresold = myUtils::readfloat(fp);
fclose(fp);
}
cout << "theresold: "<<theresold << endl;
setGeometries();
cv::VideoCapture camera(0);
if (!camera.isOpened()) {
#ifdef _WIN32
messageBox("ERRORE nell'apertura della web-cam!", 1);
myUtils::playSound("click.wav");
exit(-1);
#else
int ret = messageBox("ERRORE nell'apertura della web-cam!", 1);
myUtils::playSound("click.wav");
return -1;
#endif
}
WINDOW_NAME = setFrame_properties("Camera-training");
/*****************************************************************/
// Tutta questa parte serve per settare la grandezza della finestra in cui viene aperta la webcam e centrarla sull schermo
// in relazione alle dim del display su cui viene eseguita. Su Android essendo visualizzata a tutto schermo potrebbe essere totalmente eliminabile...
/*
QRect rec = QApplication::desktop()->screenGeometry();
cv::Size Screen_Rec_size(640, 480);
cv::Size Default_ScreenSize(1920, 1080);
cv::Size Current_ScreenRec_Size;
cout << rec.width() << " " << rec.height() << endl;
if (rec.width() != Default_ScreenSize.width) {
cout << "num 1" << endl;
cout << rec.width() << " " << Default_ScreenSize.width << endl;
cout << "DIV " << ((float)rec.width() / (float)Default_ScreenSize.width) << endl;
float c = (Screen_Rec_size.width*((float)rec.width() / (float)Default_ScreenSize.width));
cout << "c: " << c << endl;
Current_ScreenRec_Size.width = (Screen_Rec_size.width*((float)rec.width() / (float)Default_ScreenSize.width));
//Current_ScreenRec_Size.width = ((int)(c * 100 + .5) / 100.0);
cout << Current_ScreenRec_Size.width << endl;
}
else {
Current_ScreenRec_Size.width = Screen_Rec_size.width;
cout << Current_ScreenRec_Size.width << endl;
}
if (rec.height() != Default_ScreenSize.height) {
Current_ScreenRec_Size.height = Screen_Rec_size.height*((float)rec.height() / (float)Default_ScreenSize.height);
cout << Current_ScreenRec_Size.height << endl;
//meanTotal = meanTotal * ((float)rec.height() / (float)Default_ScreenSize.height);
}
else {
Current_ScreenRec_Size.height = Screen_Rec_size.height;
cout << Current_ScreenRec_Size.height << endl;
}
int height = (rec.height() / 2) - (Current_ScreenRec_Size.height / 2);
int width = (rec.width() / 2) - (Current_ScreenRec_Size.width / 2);
cout << width << " " << height << endl;
camera.set(CV_CAP_PROP_FRAME_WIDTH, Current_ScreenRec_Size.width);
camera.set(CV_CAP_PROP_FRAME_HEIGHT, Current_ScreenRec_Size.height);
cv::moveWindow(WINDOW_NAME, (rec.width() / 2) - (Current_ScreenRec_Size.width / 2), height);
cout << "final dm " << Current_ScreenRec_Size.width << " " << Current_ScreenRec_Size.height << endl;
*/
/*****************************************************************/
return camera;
}
void SetPath(string ¤t_path) {
cascade_face = "resources" + back_slash + "haarcascade_frontalface_default.xml";
char cCurrentPath[FILENAME_MAX];
#ifdef _WIN32
GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));
#else
getcwd(cCurrentPath, sizeof(cCurrentPath));
#endif
current_path = cCurrentPath;
#ifdef _WIN32
init_path = current_path.substr(0, current_path.find_first_of("\\"));
//current_path = current_path + "\\" + "Windows\\System32\\";
#else
init_path = current_path.substr(0, current_path.find_first_of("/"));
#endif
#ifdef _WIN32
//string search_path = init_path + back_slash + "Windows" + back_slash + "System32" + back_slash + "FaceRec_SystemPathDevelopment";
string search_path = init_path + back_slash + "ProgramData" + back_slash + "FaceAuthenticationSystem" + back_slash + "FaceRec_SystemPathDevelopment";
#else
string search_path = init_path + back_slash + "usr" + back_slash + "lib" + back_slash + "x86_64-linux-gnu" + back_slash + "FaceRec_SystemPathDevelopment";
//cout<<"jhgyg "<<myUtils::fexists(search_path)<<endl;
#endif
if (!myUtils::fexists(search_path)) {
if (!myUtils::fexists("resources" + back_slash + "Antispoof" + back_slash + "mappingTable_16pts.txt") || !myUtils::fexists("Database_Normalized" + back_slash + "Theresold" + back_slash + "1a.jpg.bmp") || !myUtils::fexists("resources" + back_slash + "other" + back_slash + "divieto.png") || !myUtils::fexists("resources" + back_slash + "icons" + back_slash + "Recognizer.ico")) {
//cout << "AAAAAAAAAAAAAAAAAAAAAA" << endl;
messageBox("Non risulta effettuato alcun setup! Impossibile continuare!", 5);
//myUtils::playSound("click.wav");
//return false;
exit(-1);
}
}
else {
ifstream readPath; readPath.open(search_path.c_str(), ios::in);
while (std::getline(readPath, current_path)) {
readPath >> current_path;
//cout << current_path << endl;
//system("pause");
}
readPath.close();
if (!thesis::isDirectory(current_path)) {
messageBox("Non risulta effettuato alcun setup! Impossibile continuare!", 5);
//myUtils::playSound("click.wav");
//return false;
exit(-1);
}
else {
//cout << "HERE" << endl;
//current_path = init_path + back_slash + "FR" + back_slash;
_chdir(current_path.c_str());
#ifdef _WIN32
//GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));
//cout << cCurrentPath << endl;
//system("pause");
//cout << current_path << endl;
#else
getcwd(cCurrentPath, sizeof(cCurrentPath));
current_path = cCurrentPath;
//cout << "cuurent path 1: " << current_path << endl;
#endif
}
}
/*********************************************************************/
}
double FindTheresoldValue(int residuals) {
// Read file created before....
#ifdef _WIN32
ifstream file; file.open("Database_Normalized" + back_slash + "list_images_WIN32.txt", ios::in);
#else
ifstream file; file.open("Database_Normalized" + back_slash + "list_images_LINUX.txt", ios::in);
#endif
std::string line;
std::vector<std::string> myLines;
while (std::getline(file, line))
{
myLines.push_back(line);
}
cout << myLines.size() << endl;
file.close();
cv::Mat LAST;// = cv::Mat(rowNum, colNum, CV_64FC1);
std::vector<float>data(myLines.size());
for (int i = residuals; i < myLines.size(); i++) {
cv::Mat img = cv::imread(myLines[i], CV_LOAD_IMAGE_ANYCOLOR);
/*if (!img.data) {
cerr << "error in reading image: " << myLines[i] << endl;
myUtils::system_pause();
exit(-1);
}*/
//resize(img,img,Size(PictureWidth, PictureHeight));
LQP_EXTRACT_noSave(img, LAST);
//LAST.convertTo(LAST, CV_32FC1);
//cv::Mat Data_1 = Data.row(0);
//cv::Mat Data_2 = Data.row(1);
std::vector<double>theta_(NumMaxFrame);
for (int j = 0; j < NumMaxFrame; j++)
theta_[j] = (LAST.dot(faces[j])) / (norm(LAST)*(norm(faces[j])));
//double theta_1 = *std::max_element(theta_.begin(), theta_.end());
data[i] = *std::max_element(std::begin(theta_), std::end(theta_));
//theta_1 = (double)(int(theta_1 * 100000)) / 100000;
//data[i] = theta_1;
//cout << "["<<i<<"]: "<<data[i] << endl;
//string p = to_string(theta_1);
}
double Theresold;
double theta_2 = *std::max_element(std::begin(data), std::end(data));
//cout << "Theta_2: " << theta_2 << endl;
Theresold = theta_2;
//cout << "thweta_1 - theta_2: " << theta_2 - theta_1 << endl;
/*if (theta_1 - theta_2 > 0)
Theresold = theta_1;
else if ((theta_2 - theta_1) > 0.035) {
//cout << "HERE" << endl;
//theta_1 = ((int)(theta_1 * 100 + .5) / 100.0);
Theresold = theta_1 + 0.03;
}
else
Theresold = theta_2 + 0.00001;*/
/*if (ufi_theta_2 > Theresold)
Theresold = ufi_theta_2 + 0.00001;*/
//else
//Theresold = theta_1+ 0.01; // se ho arrotondato per ecesso non sommo nnt...
cout << "Theresold: " << Theresold << endl;
/*
if (theta_1 >= 0.48)
Theresold = theta_1 - 0.02;
else
Theresold = theta_1 - 0.01;
cout << "Theresold: " << Theresold << endl;
*/
/*
if (theta_me - theta_1 >= 0.29)
Theresold = theta_1 + 0.02;
else
Theresold = theta_1 + 0.03;
cout << "Fixed: " << Theresold << endl;
*/
return Theresold;
}
cv::String setFrame_properties(string Title) {
const cv::String WINDOW_NAME(Title);
//WINDOW_NAME=Title;
//cv::namedWindow(WINDOW_NAME, cv::WINDOW_AUTOSIZE);
int width = (normWidth*native_width) / 2 - (window_width / 2);
cv::moveWindow(WINDOW_NAME, width, 0);
return WINDOW_NAME;
}
void setGeometries() {
QRect rec = QApplication::desktop()->screenGeometry();
normWidth = std::round((rec.width() / native_width));
normHeight = std::round((rec.height() / native_height));
windowSizeWidth = normWidth*window_width;
windowSizeHeight = normHeight*window_height;
}
|
class Solution {
public:
int rotatedDigits(int N) {
int result = 0;
vector<int> unpermittedNumbers = {3, 4, 7};
vector<int> rotationNumbers = {2, 5, 6, 9};
for(int i=1;i<=N;i++){
int num = i;
int rotations = 0, unpermitteds = 0;
while(num){
int digit = num % 10;
num /= 10;
if(find(unpermittedNumbers.begin(), unpermittedNumbers.end(), digit) != unpermittedNumbers.end()){
unpermitteds++;
break;
}
if(find(rotationNumbers.begin(), rotationNumbers.end(), digit) != rotationNumbers.end())
rotations++;
}
if(!unpermitteds && rotations > 0)
result++;
}
return result;
}
};
|
/*
SegaCDI - Sega Dreamcast cdi image validator.
MRImage.cpp - Boot image compressor/decompressor.
Sep 26th, 2014
*/
#include "../stdafx.h"
#include "MRImage.h"
namespace Dreamcast
{
bool SaveMRToBMP(const char *pbBuffer, int dwBufferSize, const char *psFileName)
{
// Check if the buffer size is valid.
if (dwBufferSize <= sizeof(MRHeader))
{
// Print error and return false.
printf("ERROR: MR image is invalid!\n");
return false;
}
// Parse the MR image header and check if it is valid.
MRHeader *pHeader = (MRHeader*)pbBuffer;
if (pHeader->wMagic != ByteFlip16(MR_IMAGE_MAGIC))
{
// Print error and return.
printf("ERROR: MR image contains invalid magic!\n");
return false;
}
// Check the size of the MR image.
if (pHeader->dwSize <= sizeof(MRHeader) || dwBufferSize < pHeader->dwSize)
{
// Print error and return.
printf("ERROR: MR image has invalid size!\n");
return false;
}
// Parse the color patlette array.
PaletteColor *pColorPalette = (PaletteColor*)&pbBuffer[sizeof(MRHeader)];
// Create the output file.
DWORD Count = 0;
HANDLE hFile = CreateFile(psFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
// Print error and return.
printf("ERROR: failed to create file %s!\n", psFileName);
return false;
}
// Create a BMP header with the info we have right now.
BMPHeader sBmpHeader = { 0 };
sBmpHeader.wMagic = ByteFlip16(BMP_HEADER_MAGIC);
sBmpHeader.dwFileSize = (pHeader->dwWidth * pHeader->dwHeight * 4) + sizeof(BMPHeader);
sBmpHeader.dwDataOffset = sizeof(BMPHeader);
sBmpHeader.sInfo.dwHeaderSize = sizeof(_BITMAPINFOHEADER);
sBmpHeader.sInfo.dwWidth = pHeader->dwWidth;
sBmpHeader.sInfo.dwHeight = pHeader->dwHeight;
sBmpHeader.sInfo.wColorPlanes = 1;
sBmpHeader.sInfo.wBitsPerPixel = 32;
sBmpHeader.sInfo.dwCompressionMethod = 0;
sBmpHeader.sInfo.dwImageSize = pHeader->dwWidth * pHeader->dwHeight * 4;
sBmpHeader.sInfo.dwHorizontalPpm = 0x120B;
sBmpHeader.sInfo.dwVerticalPpm = 0x120B;
sBmpHeader.sInfo.dwColorsInPalette = 0;
sBmpHeader.sInfo.dwImportantColors = 0;
// Write a 32bbp BMP header.
WriteFile(hFile, &sBmpHeader, sizeof(BMPHeader), &Count, NULL);
// Compute the size of the pixel data.
DWORD dwPixelDataSize = pHeader->dwSize - (sizeof(MRHeader) + pHeader->dwColors * 4);
// Loop through the MR image buffer and decompress it.
int ptr = 0;
BYTE *pbPixelBuffer = (PBYTE)&pbBuffer[pHeader->dwDataOffset];
while (ptr < dwPixelDataSize - 1)
{
int length = 1;
// Read the length marker.
int id = pbPixelBuffer[ptr++];
// Use the block marker to determin the length of the pixel run.
if (id == 0x82)
{
// Read the next byte and determin if the block is greater than 0x100.
if ((pbPixelBuffer[ptr] & 0x80) == 0x80)
{
// The length is greater than 0x100.
length = (pbPixelBuffer[ptr++] & 0x7F) + 0x100;
}
else
{
// The length is greater than 1.
length = id & 0x7F;
}
}
else if (id == 0x81)
{
// The length is less than 0x100.
length = pbPixelBuffer[ptr++];
}
else if ((id & 0x80) == 0x80)
{
// The length is greater than 1.
length = id & 0x7F;
}
else
{
// The block marker is the color index.
ptr--;
}
// Read the palette index from the buffer.
int colorIndex = pbPixelBuffer[ptr++];
if (colorIndex > pHeader->dwColors)
{
// Color index is out of range, print error and return false.
printf("ERROR: color index out of range for boot image!\n");
CloseHandle(hFile);
return false;
}
// Write the color run to the output file.
for (int x = 0; x < length; x++)
WriteFile(hFile, &pColorPalette[colorIndex].Color, 4, &Count, NULL);
}
// Close the output file and return.
CloseHandle(hFile);
return true;
}
bool CreateMRFromBMP(const char *psFileName, char *ppbBuffer, int *pdwBufferSize)
{
// Open the BMP file.
HANDLE hFile = CreateFile(psFileName, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
// Print error and return.
printf("ERROR: failed to open file %s!\n", psFileName);
return false;
}
// Get the size of the file.
int dwFileSize = GetFileSize(hFile, NULL);
// Allocate a buffer for the BMP file.
BYTE *pbBmpBuffer = new BYTE[dwFileSize];
// Read the BMP file into memory.
DWORD Count = 0;
ReadFile(hFile, pbBmpBuffer, dwFileSize, &Count, NULL);
// Close the BMP file.
CloseHandle(hFile);
// Parse the BMP header and check if the magic is valid.
BMPHeader *pBmpHeader = (BMPHeader*)pbBmpBuffer;
if (pBmpHeader->wMagic != ByteFlip16(BMP_HEADER_MAGIC))
{
// Print an error and return.
printf("ERROR: BMP image has invalid magic!\n");
delete[] pbBmpBuffer;
return false;
}
// Check the width and height are within range.
if (pBmpHeader->sInfo.dwWidth > MR_MAX_WIDTH || pBmpHeader->sInfo.dwHeight > MR_MAX_HEIGHT)
{
// Print a warning and try to continue.
printf("WARNING: bmp image has invalid resolution, should be 320x94 or smaller!, continuing anyway...\n");
}
// Check to make sure the bmp image is 32bbp.
if (pBmpHeader->sInfo.wBitsPerPixel != 32)
{
printf("ERROR: bmp image should be 32bbp!\n");
delete[] pbBmpBuffer;
return false;
}
// Allocate a temp working buffer for the MR image.
BYTE *pbMRTempBuffer = new BYTE[pBmpHeader->sInfo.dwWidth * pBmpHeader->sInfo.dwHeight * 4];
memset(pbMRTempBuffer, 0, pBmpHeader->sInfo.dwWidth * pBmpHeader->sInfo.dwHeight * 4);
// Create a MR image header.
MRHeader *pMRHeader = (MRHeader*)pbMRTempBuffer;
pMRHeader->wMagic = ByteFlip16(MR_IMAGE_MAGIC);
pMRHeader->dwWidth = pBmpHeader->sInfo.dwWidth;
pMRHeader->dwHeight = pBmpHeader->sInfo.dwHeight;
// Create the color palette.
int colors = 0;
PaletteColor *pColorPalette = (PaletteColor*)&pbMRTempBuffer[sizeof(MRHeader)];
// Create a pixel buffer for the image data.
BYTE *pbMRPixelData = (BYTE*)&pbMRTempBuffer[sizeof(MRHeader) + (sizeof(PaletteColor) * 128)];
DWORD *pdwBmpPixelData = (DWORD*)&pbBmpBuffer[pBmpHeader->dwDataOffset];
// Loop through the pixel buffer and process each one.
DWORD length = 0;
for (int pos = 0; pos < pBmpHeader->sInfo.dwImageSize; )
{
// Determine the size of the pixel run.
int run = 1;
while ((pdwBmpPixelData[pos] == pdwBmpPixelData[pos + run]) && (run < 0x17f) &&
(pos + run <= pBmpHeader->sInfo.dwImageSize))
{
// Pixel n is the same as the current pixel, so increase the run length by 1.
run++;
}
// Check if this color is in the color palette and if not add it.
int colorIndex = -1;
for (int i = 0; i < colors; i++)
{
// Check if this color matches the current pixel.
if (pdwBmpPixelData[pos] == pColorPalette[i].Color)
{
// Found the color, break the loop.
colorIndex = i;
break;
}
}
// Check if we found the color in the color palette.
if (colorIndex == -1)
{
// We did not find the color in the color palette, see if there is room to add it.
if (colors < 128)
{
// Add the color to the palette.
pColorPalette[colors].Color = pdwBmpPixelData[pos];
colorIndex = colors++;
}
else
{
// The color palette is full, print a warning and continue.
colorIndex = 0;
printf("WARNING: bmp image should have 128 colors or less! continuing anyway...\n");
}
}
// Check the size of the pixel run and create the block accordingly.
if (run > 0xFF)
{
pbMRPixelData[length++] = 0x82;
pbMRPixelData[length++] = 0x80 | (run - 0x100);
pbMRPixelData[length++] = (BYTE)colorIndex;
}
else if (run > 0x7F)
{
pbMRPixelData[length++] = 0x81;
pbMRPixelData[length++] = run;
pbMRPixelData[length++] = (BYTE)colorIndex;
}
else if (run > 1)
{
pbMRPixelData[length++] = 0x80 | run;
pbMRPixelData[length++] = (BYTE)colorIndex;
}
else
{
pbMRPixelData[length++] = (BYTE)colorIndex;
}
// Increase the position by the run length.
pos += run;
}
// Check if the length of the MR image will fit in the IP.BIN file.
if (sizeof(MRHeader) + (sizeof(PaletteColor) * colors) + length > MR_MAX_SIZE)
{
// Delete our bmp buffer and temp mr buffer.
delete[] pbBmpBuffer;
delete[] pbMRTempBuffer;
// Print error and return false.
printf("ERROR: MR image is too large and will corrupt IP.BIN bootstrap!\n");
return false;
}
// Finish creating the MR image header.
pMRHeader->dwSize = sizeof(MRHeader) + (sizeof(PaletteColor) * colors) + length;
pMRHeader->dwDataOffset = sizeof(MRHeader) + (colors * sizeof(PaletteColor));
pMRHeader->dwColors = colors;
// Move the pixel data to directly after the color palette.
memmove(&pbMRTempBuffer[pMRHeader->dwDataOffset], pbMRPixelData, length);
// Check to make sure the output buffer can hold the MR image buffer.
if (*pdwBufferSize < pMRHeader->dwSize)
{
// Delete our bmp buffer and temp mr buffer.
delete[] pbBmpBuffer;
delete[] pbMRTempBuffer;
// Print an error and return false.
printf("ERROR: MR image is too large for buffer!\n");
return false;
}
// Copy the MR image buffer to our new buffer.
memcpy(ppbBuffer, pbMRTempBuffer, pMRHeader->dwSize);
*pdwBufferSize = pMRHeader->dwSize;
// Delete our bmp buffer and temp mr buffer.
delete[] pbBmpBuffer;
delete[] pbMRTempBuffer;
// Done, return true.
return true;
}
};
|
/*****************************************************************************************************************
* File Name : AlternateSplitLL.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\linkedlist\page03\AlternateSplitLL.h
* Created on : Dec 22, 2013 :: 9:34:32 PM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
/************************************************* Main code ******************************************************/
#ifndef ALTERNATESPLITLL_H_
#define ALTERNATESPLITLL_H_
llNode *alternateSplitIterativeNew(llNode *ptr){
if(ptr == NULL){
return NULL;
}
llNode *listOne,*listOneCrawler,*listTwo,*listTwoCrawler,*crawler = ptr;
bool odd = true;
while(crawler != NULL){
if(odd){
if(listOne){
listOne = createNewLLNode(crawler->value);
listOneCrawler = listOne;
}else{
listOneCrawler->next = createNewLLNode(crawler->value);
listOneCrawler = listOneCrawler->next;
}
}else{
if(listTwo){
listTwo = createNewLLNode(crawler->value);
listTwoCrawler = listTwo;
}else{
listTwoCrawler->next = createNewLLNode(crawler->value);
listTwoCrawler = listTwoCrawler->next;
}
}
odd = !odd;
crawler = crawler->next;
}
llNode *lists[] = {listOne,listTwo};
return lists;
}
llNode *alternateSplit(llNode *ptr){
if(ptr == NULL){
return NULL;
}
llNode *lists[];
list[0] = createNewLLNode(ptr->value);
if(ptr->next == NULL){
lists[1] = createNewLLNode(ptr->next->value);
return lists;
}
llNode *temp = alternateSplit(ptr->next->next);
lists[0]->next = temp[0];
lists[1]->next = temp[1];
return lists;
}
llNode *alternateSplitOptimized(llNode *ptr){
if(ptr == NULL){
return NULL;
}
llNode *oddNodeList,*evenNodeList,*oddNodeListCrawler,*evenNodeListCrawler,*crawler = ptr;
bool isOddNode = true;
while(crawler == NULL){
if(isOddNode){
if(oddNodeList == NULL){
oddNodeList = crawler;
oddNodeListCrawler = oddNodeList;
}else{
oddNodeListCrawler->next = crawler;
oddNodeListCrawler = oddNodeListCrawler->next;
}
}else{
if(evenNodeList == NULL){
evenNodeList = crawler;
evenNodeListCrawler = evenNodeList;
}else{
evenNodeListCrawler->next = crawler;
evenNodeListCrawler = evenNodeListCrawler->next;
}
}
ptr = crawler->next;
crawler->next = NULL;
crawler = ptr;
}
llNode *lists[] = {oddNodeList,evenNodeList};
return lists;
}
#endif /* ALTERNATESPLITLL_H_ */
/************************************************* End code *******************************************************/
|
#include <iostream>
using namespace std;
int main() {
int t = 0;
cin >> t;
char c = '\0';
int depth = 0;
c = getchar(); // flush '\n' at first
while (t--) {
depth = 0;
while (1) {
c = getchar();
if (c == '(') {
depth++;
} else if (c == ')') {
depth--;
} else {
break;
}
if (depth < 0) {
while (getchar() != '\n') {} // flush until '\n'
break;
}
}
if (depth == 0) {
cout << "YES" << endl;
} else {
cout << "NO" << endl;
}
}
return 0;
}
|
#include "dirent.h"
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
DIR *dir;
struct dirent *ent;
char arr[] = "C:\\Users\\pgunaraj\\Downloads\\DataR\\";
if ((dir = opendir(arr)) != NULL)
{
while ((ent = readdir(dir)) != NULL) {
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0)
{
strcat(arr, ent->d_name);
printf("%s",arr);
}
}
closedir(dir);
}
else {
/* could not open directory */
perror("");
return EXIT_FAILURE;
}
_getch();
return 0;
}
|
//知识点:分治
/*
By:Luckyblock
分析题意:
将 大矩阵分为四个 等大小矩阵
对左上角的 子矩阵进行处理
注意对 子矩阵的边界进行判断
*/
#include<cstdio>
#include<cctype>
#define ll long long
const int MARX = 1024+10;
//=============================================================
ll n,mul;
bool map[MARX][MARX];
//=============================================================
inline ll read()
{
ll s=1, w=0; char ch=getchar();
for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1;
for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0';
return s*w;
}
void solve(ll x1, ll y1, ll l)
{
for(ll i=x1; i<=(x1+(l-1)/2); i++)//左上角 子矩阵
for(ll j=y1; j<=(y1+(l-1)/2); j++)
map[i][j] = 1;
if(l/2 == 1) return ;//无法继续分割
solve(x1,y1+l/2,l/2);//左下,右上,右下的矩阵
solve(x1+l/2,y1,l/2);
solve(x1+l/2,y1+l/2,l/2);
}
//=============================================================
signed main()
{
n=read(); mul=1<<n;
solve(1,1,mul);
for(ll i=1; i<=mul; putchar('\n'),i++)//输出处理后的矩阵
for(ll j=1; j<=mul; j++)
printf("%d ",map[i][j]?0:1);
}
|
/*
load / save the mesh attributes from file.
*/
#ifndef H_MESH_IO_H
#define H_MESH_IO_H
#include "Common.h"
#include "Mesh.h"
#include <string>
namespace P_RVD
{
enum FileType
{
OBJfile = 0,
PTXfile = 1
};
/*
load the mesh attributes from the file
meshpoints : true -- load a mesh
flase -- load points, just vertices
*/
bool mesh_load(const std::string _filepath, Mesh& _M, bool _meshpoints = true, FileType _filetype = OBJfile);
/*
save the mesh.
*/
}
#endif /* H_MESH_IO_H */
|
#pragma once
#include"Lista.h"
#include"Nodo1.h"
#include"Productos.h"
class Orden
{
//Se utiliza Quicksort para:
//ordenar el tipo de producto
void QuickSortTipo(Lista* lista, int start, int end);
int DivideTipo(Lista* lista, int start, int end);
//Se ordena por cantidad de producto
void QuickSortCantidad(Lista* lista, int start, int end);
int DivideCantidad(Lista* lista, int start, int end);
//ordenar por peso
void QuickSortPeso(Lista* lista, int start, int end);
int DividePeso(Lista* lista, int start, int end);
//Se utiliza bubble para:
//Ordenar por fecha
void BubbleSortFecha(Lista* lista);
void IntercambioProducto(Nodo1* Producto1, Nodo1* Producto2);
};
|
#include "stdafx.h"
#include "BaseApplication.h"
#include "Config.h"
//-------------------------------------------------------------------------------------
BaseApplication::BaseApplication(void)
: mRoot(0),
mCamera(0),
mSceneMgr(0),
mWindow(0),
mCursorWasVisible(false),
mShutDown(false),
mInputManager(0),
mMouse(0),
mKeyboard(0)
{
mGUI = 0;
mPlatform = 0;
}
//-------------------------------------------------------------------------------------
BaseApplication::~BaseApplication(void)
{
if (mGUI)
{
mGUI->shutdown();
delete mGUI;
mGUI = 0;
}
if (mPlatform)
{
mPlatform->shutdown();
delete mPlatform;
mPlatform = 0;
}
//Remove ourself as a Window listener
Ogre::WindowEventUtilities::removeWindowEventListener(mWindow, this);
windowClosed(mWindow);
delete mRoot;
}
//-------------------------------------------------------------------------------------
bool BaseApplication::configure(void)
{
// Show the configuration dialog and initialise the system
// You can skip this and use root.restoreConfig() to load configuration
// settings if you were sure there are valid ones saved in ogre.cfg
// Grab the OpenGL RenderSystem, or exit
if(mRoot->restoreConfig() || mRoot->showConfigDialog())
{
// If returned true, user clicked OK so initialise
// Here we choose to let the system create a default rendering window by passing 'true'
mWindow = mRoot->initialise(true, "Ogre Move Test");
// Let's add a nice window icon
HWND hwnd;
mWindow->getCustomAttribute("WINDOW", (void*)&hwnd);
LONG iconID = (LONG)LoadIcon( GetModuleHandle(0), MAKEINTRESOURCE(IDI_APPICON) );
SetClassLong( hwnd, GCL_HICON, iconID );
return true;
}
else
{
return false;
}
}
//-------------------------------------------------------------------------------------
void BaseApplication::chooseSceneManager(void)
{
// Get the SceneManager, in this case a generic one
mSceneMgr = mRoot->createSceneManager(Ogre::ST_GENERIC);
}
//-------------------------------------------------------------------------------------
void BaseApplication::createCamera(void)
{
// Create the camera
mCamera = mSceneMgr->createCamera("PlayerCam");
// Position it at 500 in Z direction
mCamera->setPosition(g_Cameras[defaultCamera].pos);
mCamera->lookAt(g_Cameras[defaultCamera].lookAt);
mCamera->setNearClipDistance(0.05);
//mCameraMan = new OgreBites::SdkCameraMan(mCamera); // create a default camera controller
}
//-------------------------------------------------------------------------------------
void BaseApplication::createFrameListener(void)
{
Ogre::LogManager::getSingletonPtr()->logMessage("*** Initializing OIS ***");
OIS::ParamList pl;
size_t windowHnd = 0;
std::ostringstream windowHndStr;
mWindow->getCustomAttribute("WINDOW", &windowHnd);
windowHndStr << windowHnd;
pl.insert(std::make_pair(std::string("WINDOW"), windowHndStr.str()));
mInputManager = OIS::InputManager::createInputSystem( pl );
mKeyboard = static_cast<OIS::Keyboard*>(mInputManager->createInputObject( OIS::OISKeyboard, true ));
mMouse = static_cast<OIS::Mouse*>(mInputManager->createInputObject( OIS::OISMouse, true ));
mMouse->setEventCallback(this);
mKeyboard->setEventCallback(this);
//Set initial mouse clipping size
windowResized(mWindow);
//Register as a Window listener
Ogre::WindowEventUtilities::addWindowEventListener(mWindow, this);
mRoot->addFrameListener(this);
}
//-------------------------------------------------------------------------------------
void BaseApplication::destroyScene(void)
{
}
//-------------------------------------------------------------------------------------
void BaseApplication::createViewports(void)
{
// Create one viewport, entire window
Ogre::Viewport* vp = mWindow->addViewport(mCamera);
vp->setBackgroundColour(Ogre::ColourValue(0,0,0));
// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio(
Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
}
//-------------------------------------------------------------------------------------
void BaseApplication::setupResources(void)
{
// Only add the minimally required resource locations to load up SDKTrays and the Ogre head mesh
Ogre::ResourceGroupManager::getSingleton().addResourceLocation("media/packs/pingpong.zip", "Zip", "General");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation("media/fonts", "FileSystem", "General");
Ogre::ResourceGroupManager::getSingleton().addResourceLocation("media/MyGUI_Media", "FileSystem", "General");
}
//-------------------------------------------------------------------------------------
void BaseApplication::createResourceListener(void)
{
}
//-------------------------------------------------------------------------------------
void BaseApplication::loadResources(void)
{
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
//-------------------------------------------------------------------------------------
void BaseApplication::go(void)
{
if (!setup())
return;
mRoot->startRendering();
// clean up
destroyScene();
}
//-------------------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
mRoot = new Ogre::Root("");
// A list of required plugins
Ogre::StringVector required_plugins;
required_plugins.push_back("D3D9 RenderSystem");
required_plugins.push_back("GL RenderSystem");
required_plugins.push_back("Octree & Terrain Scene Manager");
// List of plugins to load
Ogre::StringVector plugins_toLoad;
plugins_toLoad.push_back("RenderSystem_Direct3D9");
plugins_toLoad.push_back("RenderSystem_GL");
plugins_toLoad.push_back("Plugin_OctreeSceneManager");
// Load the OpenGL RenderSystem and the Octree SceneManager plugins
for (Ogre::StringVector::iterator j = plugins_toLoad.begin(); j != plugins_toLoad.end(); j++)
{
#ifdef _DEBUG
mRoot->loadPlugin(*j + Ogre::String("_d"));
#else
mRoot->loadPlugin(*j);
#endif;
}
// Check if the required plugins are installed and ready for use
// If not: exit the application
Ogre::Root::PluginInstanceList ip = mRoot->getInstalledPlugins();
for (Ogre::StringVector::iterator j = required_plugins.begin(); j != required_plugins.end(); j++)
{
bool found = false;
// try to find the required plugin in the current installed plugins
for (Ogre::Root::PluginInstanceList::iterator k = ip.begin(); k != ip.end(); k++)
{
Ogre::String pluginName=(*k)->getName();
if (pluginName == *j)
{
found = true;
break;
}
}
if (!found) // return false because a required plugin is not available
{
return false;
}
}
setupResources();
bool carryOn = configure();
if (!carryOn) return false;
chooseSceneManager();
createCamera();
createViewports();
// Set default mipmap level (NB some APIs ignore this)
Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
// Create any resource listeners (for loading screens)
createResourceListener();
// Load resources
loadResources();
mPlatform = new MyGUI::OgrePlatform();
mPlatform->initialise(mWindow, mSceneMgr); // mWindow is Ogre::RenderWindow*, mSceneManager is Ogre::SceneManager*
mGUI = new MyGUI::Gui();
mGUI->initialise();
createFrameListener();
// Create the scene
createScene();
return true;
};
//-------------------------------------------------------------------------------------
bool BaseApplication::frameRenderingQueued(const Ogre::FrameEvent& evt)
{
if(mWindow->isClosed())
return false;
if(mShutDown)
return false;
//Need to capture/update each device
mKeyboard->capture();
mMouse->capture();
return true;
}
//-------------------------------------------------------------------------------------
bool BaseApplication::keyPressed( const OIS::KeyEvent &arg )
{
if (arg.key == OIS::KC_SYSRQ) // take a screenshot
{
mWindow->writeContentsToTimestampedFile("screenshot", ".jpg");
}
else if (arg.key == OIS::KC_ESCAPE)
{
mShutDown = true;
}
MyGUI::InputManager::getInstance().injectKeyPress(MyGUI::KeyCode::Enum(arg.key), arg.text);
return true;
}
bool BaseApplication::keyReleased( const OIS::KeyEvent &arg )
{
MyGUI::InputManager::getInstance().injectKeyRelease(MyGUI::KeyCode::Enum(arg.key));
return true;
}
bool BaseApplication::mouseMoved( const OIS::MouseEvent &arg )
{
MyGUI::InputManager::getInstance().injectMouseMove(arg.state.X.abs, arg.state.Y.abs, arg.state.Z.abs);
return true;
}
bool BaseApplication::mousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
MyGUI::InputManager::getInstance().injectMousePress(arg.state.X.abs, arg.state.Y.abs, MyGUI::MouseButton::Enum(id));
return true;
}
bool BaseApplication::mouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id )
{
MyGUI::InputManager::getInstance().injectMouseRelease(arg.state.X.abs, arg.state.Y.abs, MyGUI::MouseButton::Enum(id));
return true;
}
//Adjust mouse clipping area
void BaseApplication::windowResized(Ogre::RenderWindow* rw)
{
unsigned int width, height, depth;
int left, top;
rw->getMetrics(width, height, depth, left, top);
const OIS::MouseState &ms = mMouse->getMouseState();
ms.width = width;
ms.height = height;
}
//Unattach OIS before window shutdown (very important under Linux)
void BaseApplication::windowClosed(Ogre::RenderWindow* rw)
{
//Only close for window that created OIS (the main window in these demos)
if( rw == mWindow )
{
if( mInputManager )
{
mInputManager->destroyInputObject( mMouse );
mInputManager->destroyInputObject( mKeyboard );
OIS::InputManager::destroyInputSystem(mInputManager);
mInputManager = 0;
}
}
}
|
#include <iostream>
#include "List.h"
using namespace std;
char** split_string_into_words(char* str, int& words_count);
void add_word_to_array(char**& words, char* new_word, int& words_count);
void main(){
cout << "Hello world!" << endl;
List* lst = new List();
char* str = new char[255];
cout << "Enter string: \n";
cin.getline(str, 255);
int words_count = 0;
char** words = split_string_into_words(str, words_count);
for (int i = 0; i < words_count; i++){
lst->add_item(words[i]);
}
lst->print();
cout << "--------------------" << endl;
lst->remove_common_items();
lst->print();
}
char** split_string_into_words(char* str, int& words_count){
char** words = new char*[words_count];
char* word = strtok(str, ";");
while (word != NULL){
add_word_to_array(words, word, words_count);
word = strtok(NULL, ";");
}
return words;
}
void add_word_to_array(char**& words, char* new_word, int& words_count){
char** added_words = new char*[words_count + 1];
for (int i = 0; i < words_count; i++){
added_words[i] = words[i];
}
added_words[words_count] = new_word;
delete words;
words_count++;
words = added_words;
}
|
/*=================================================================================================
Author: Renato Farias (renatomdf@gmail.com)
Created on: April 13th, 2012
Updated on: June 12th, 2012
About: This is a simple CPU implementation of the Jump Flooding algorithm from the paper "Jump
Flooding in GPU With Applications to Voronoi Diagram and Distance Transform" [Rong 2006]. The
result is a Voronoi diagram generated from a number of seeds which the user provides with mouse
clicks. You can also click on and drag around a seed to reposition it, if that's your thing.
=================================================================================================*/
#ifndef __JFA_H__
#define __JFA_H__
/*=================================================================================================
INCLUDES
=================================================================================================*/
#include "ImgLib.h"
#include "edlines.h"
#include <vector>
#include <fstream>
#include <unordered_map>
typedef vector<Pixel> EdgeChain;
typedef EdgeChain Seeds;
//typedef vector<vector<Pixel> > VecEdgeChains;
typedef unordered_multimap<int, int> VoiPixelMap;
//namespace JFA {
//
// //这里因为命名相同无法编译通过的原因,简单通过设置命名空间来解决,后续需要完善
//
// //using namespace std;
// typedef struct Pixel {
// int x, y;
//
// Pixel(int tx, int ty) {
// x = tx;
// y = ty;
// }
// Pixel() {};
// } Pixel;
//
// typedef std::vector<Pixel> EdgeChain;
//}
// Represents a Pixel with (x,y) coordinates
/*=================================================================================================
FUNCTIONS
=================================================================================================*/
//void ExecuteJumpFlooding(vector<Pixel> Seeds);
void ExecuteJumpFloodingDis(float* flowDisMap, Seeds Seeds, unsigned int xsize, unsigned int ysize);
void ExecuteJumpFloodingVoi(int* VoiMap, const Seeds Seeds, unsigned int xsize, unsigned int ysize);
//EdgeChain VertexOptimization(const EdgeChain constrainedPoints, const EdgeChain cvtSeeds,
// unsigned int xsize, unsigned int ysize, int optTimes, int* distMap);
Seeds VertexOptimization(const Seeds cvtSeeds, unsigned int xsize, unsigned int ysize, int optTimes, float* flowDistMap);
//EdgeChains VertexOptimization(const EdgeChains constrainedPoints, const EdgeChains cvtSeeds,
// unsigned int xsize, unsigned int ysize, int optTimes, float* distMap);
#endif
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef DESKTOP_TAB_H
#define DESKTOP_TAB_H
#include "adjunct/quick_toolkit/windows/DesktopWindow.h"
#include "adjunct/desktop_pi/desktop_file_chooser.h"
class OpFindTextBar;
class DesktopTab
: public DesktopWindow
, public DesktopFileChooserListener
{
public:
DesktopTab();
virtual ~DesktopTab();
// From DesktopFileChooserListener
virtual void OnFileChoosingDone(DesktopFileChooser* chooser, const DesktopFileChooserResult& result);
// From DesktopWindow - this function should return a non-NULL value
virtual OpWindowCommander* GetWindowCommander() = 0;
void ShowFindTextBar(BOOL show = TRUE);
// WidgetListener
virtual BOOL OnContextMenu(OpWidget* widget, INT32 child_index, const OpPoint& menu_point, const OpRect* avoid_rect, BOOL keyboard_invoked);
protected:
/** Save the current document in this window
* @param save_focused_frame Whether to save just the focused frame or the whole document
*/
OP_STATUS SaveDocument(BOOL save_focused_frame);
/** Get a file chooser object
* @param chooser Where to position the chooser
*/
OP_STATUS GetChooser(DesktopFileChooser*& chooser);
/** Get the find text bar
* @return OpFindTextBar*
*/
OpFindTextBar* GetFindTextBar() { return m_search_bar; }
DesktopFileChooserRequest m_request;
private:
BOOL m_save_focused_frame;
#ifdef DEBUG_ENABLE_OPASSERT
int m_waiting_for_filechooser;
#endif
DesktopFileChooser* m_chooser;
static UINT32 s_default_filter;
OpFindTextBar* m_search_bar;
};
#endif // DESKTOP_TAB_H
|
#include<bits/stdc++.h>
using namespace std;
class Fraction{
private:
int numerator;
int denominator;
public:
Fraction(int numerator,int denominator){
this -> numerator = numerator;
this -> denominator = denominator;
}
void simplify(){
int gcd = 1;
int j = min(this -> numerator,this -> denominator);
for(int i=1;i<=j;i++){
if(this -> numerator % i == 0 && this -> denominator % i == 0){
gcd = i;
}
}
this -> numerator = this -> numerator / gcd;
this -> denominator = this -> denominator / gcd;
}
void add(Fraction f2){
int lcm = this -> denominator * f2.denominator;
int x = lcm/this -> denominator;
int y = lcm/f2.denominator;
int num = ((x * this -> numerator) + (y * f2.numerator));
this -> numerator = num;
this -> denominator = lcm;
simplify();
}
void print(){
cout << this -> numerator << "/" << this -> denominator << endl;
}
};
int main(){
Fraction f1(10,2);
Fraction f2(15,4);
cout << "f1 : ";
f1.print();
cout << "f2 : ";
f2.print();
f1.add(f2);
cout << "Sum : ";
f1.print();
return 0;
}
|
#include <mqtt/subscriber/subcallback.h>
void SubCallback::reconnect() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
mqtt::connect_options connOpts;
connOpts.set_keep_alive_interval(20);
connOpts.set_clean_session(true);
try {
cli_.connect(connOpts, nullptr, *this);
} catch (const mqtt::exception &exc) {
std::cerr << "Error: " << exc.what() << std::endl;
exit(1);
}
}
// Re-connection failure
void SubCallback::on_failure(const mqtt::itoken &) {
if (++nretry_ > 5)
exit(1);
reconnect();
}
// Re-connection success
void SubCallback::on_success(const mqtt::itoken &) {
for (unsigned int i = 0; i < subscribers_.size(); i++)
cli_.subscribe(subscribers_[i]->topic(), qos_, nullptr, listener_);
}
void SubCallback::connection_lost(const std::string &cause) {
std::string log_msg = "Mqtt: Connection Lost ";
if (!cause.empty())
log_msg += " cause: " + cause + ". Reconnecting.";
log(log_msg);
nretry_ = 0;
reconnect();
}
void SubCallback::message_arrived(const std::string &topic,
mqtt::message_ptr msg) {
for (unsigned int i = 0; i < subscribers_.size(); i++) {
if (topic == subscribers_[i]->topic()) {
subscribers_[i]->data_buffer->push_back(
XorCipher::decrypt(msg->to_str()));
subscribers_[i]->parse();
// Beware of the race condition.
break;
}
}
}
void SubCallback::delivery_complete(mqtt::idelivery_token_ptr) {}
void SubCallback::addSubscriber(Subscriber *s) { subscribers_.push_back(s); }
|
#include "_pch.h"
#include "MObjCatalog.h"
using namespace wh;
using namespace wh::object_catalog;
//-------------------------------------------------------------------------
//-------------------------------------------------------------------------
MObjCatalog::MObjCatalog(const char option)
:TModelData<rec::CatCfg>(option)
, mPath(new model::MPath)
, mTypeArray(new MTypeArray)
, mFilter(new MFilterArray)
, mFilterCat(new MFilter)
, mAutoLoadObj(new TModelData<bool>)
{
mAutoLoadObj->SetData(false, true);
Insert(mAutoLoadObj);
this->Insert(mPath);
this->Insert(mTypeArray);
this->Insert(mFilter);
// 0
{
FilterData fd;
fd.mConn = fcAND;
fd.mFieldName = "acls.kind";
fd.mOp = foEq;
fd.mVal = wxString::Format("%d", (int)ClsKind::Abstract);
fd.mFieldType = ftLong;
fd.mIsEnabled = false;
auto item = mFilter->CreateItem(fd,true);
mFilter->Insert(item);
}
// 1
mFilter->Insert(
mFilter->CreateItem(
FilterData("0", "acls.id", ftLong, foEq, fcAND, false), true));
// 2
{
FilterData fd;
fd.mConn = fcAND;
fd.mFieldName = "acls.title";
fd.mOp = foLike;
fd.mVal = "";
fd.mFieldType = ftText;
fd.mIsEnabled = false;
auto item = mFilter->CreateItem(fd, true);
mFilter->Insert(item);
}
}
//-------------------------------------------------------------------------
void MObjCatalog::SetCfg(const rec::CatCfg& cfg)
{
this->SetData(cfg);
unsigned long parent_id = cfg.mHideSystemRoot ? 1 : 0;
switch (cfg.mCatType)
{
case rec::catCls:
case rec::catObj:
SetCatFilter(parent_id, true);
break;
default:
SetCatFilter(0, false);
break;
}
}
//-------------------------------------------------------------------------
void MObjCatalog::LoadChilds()
{
mPath->Load();
mTypeArray->Load();
}
//-------------------------------------------------------------------------
bool MObjCatalog::IsObjTree()const
{
const auto& cfg = this->GetData();
return rec::catObj == cfg.mCatType;
}
//-------------------------------------------------------------------------
bool MObjCatalog::IsShowDebug()const
{
const auto& cfg = this->GetData();
return cfg.mShowDebugColumns;
}
//-------------------------------------------------------------------------
bool MObjCatalog::IsObjEnabled()const
{
if (IsAbstractTree())
return false;
const auto& cfg = this->GetData();
return cfg.mEnableObj;
}
//-------------------------------------------------------------------------
void MObjCatalog::ObjEnable(bool enable)
{
auto cfg = this->GetData();
cfg.mEnableObj = enable;
this->SetData(cfg);
}
//-------------------------------------------------------------------------
rec::PathItem MObjCatalog::GetRoot()
{
const auto& cfg = this->GetData();
rec::PathItem root;
std::shared_ptr<MFilter> mfilter;
switch (cfg.mCatType)
{
case rec::catCls:
root.mCls.mId = mFilterCat->GetData().mVal;
case rec::catObj:
root.mObj.mId = mFilterCat->GetData().mVal;
break;
default:break;
}
return root;
}
//-------------------------------------------------------------------------
void MObjCatalog::DoUp()
{
const auto& cfg = this->GetData();
std::shared_ptr<model::MPathItem> pathItem;
unsigned long pid = cfg.mHideSystemRoot ? 1 : 0;
switch (cfg.mCatType)
{
case rec::catCls:
if (mPath->GetChildQty() > 1)
{
pathItem = mPath->at(1);
if (pathItem && !pathItem->GetData().mCls.mId.IsNull())
pid = pathItem->GetData().mCls.mId;
}
SetCatFilter(pid);
Load();
break;
case rec::catObj:
if (mPath->GetChildQty() > 1)
{
pathItem = mPath->at(1);
if (pathItem && !pathItem->GetData().mObj.mId.IsNull())
pid = pathItem->GetData().mObj.mId;
}
SetCatFilter(pid);
Load();
break;
default:break;
}
}
//-------------------------------------------------------------------------
void MObjCatalog::SetFilterClsKind(ClsKind ct, FilterOp fo, bool enable)
{
FilterData fd(wxString::Format("%d", (int)ct)
, "acls.kind", ftLong, fo, fcAND, enable);
mFilter->at(0)->SetData(fd, true);
}
//-------------------------------------------------------------------------
const FilterData& MObjCatalog::GetFilterClsKind()const
{
return mFilter->at(0)->GetData();
};
//-------------------------------------------------------------------------
void MObjCatalog::SetFilterClsId(long id, FilterOp fo, bool enable)
{
FilterData fd(wxString::Format("%d", id)
, "acls.id", ftLong, fo, fcAND, enable);
mFilter->at(1)->SetData(fd, true);
}
//-------------------------------------------------------------------------
const FilterData& MObjCatalog::GetFilterClsId()const
{
return mFilter->at(1)->GetData();
};
//-------------------------------------------------------------------------
bool MObjCatalog::IsAbstractTree()const
{
const auto& filter = mFilter->at(0)->GetData();
if (filter.mIsEnabled)
{
unsigned long val;
if (
filter.mVal.ToCULong(&val))
return ClsKind::Abstract == (ClsKind)val;
}
return false;
}
//-------------------------------------------------------------------------
wxString MObjCatalog::GetFilterCls()const
{
return mFilter->GetSqlString();
}
//-------------------------------------------------------------------------
wxString MObjCatalog::GetFilterObj()const
{
return wxEmptyString;
}
//-------------------------------------------------------------------------
void MObjCatalog::SetCatFilter(long pid, bool enable)
{
const auto& cfg = this->GetData();
const wxString pidStr = wxString::Format("%d", pid);
switch (cfg.mCatType)
{
case rec::catCls:
mFilterCat->SetData(FilterData(pidStr, "acls.pid", ftLong, foEq, fcAND, enable));
break;
case rec::catObj:
mFilterCat->SetData(FilterData(pidStr, "obj.pid", ftLong, foEq, fcAND, enable));
break;
default:
mFilterCat->SetData(FilterData(wxEmptyString, wxEmptyString, ftLong, foEq, fcAND, false));
break;
}
}
//-------------------------------------------------------------------------
wxString MObjCatalog::GetFilterCat()const
{
return mFilterCat->GetData().GetSqlString();
}
//-------------------------------------------------------------------------
void MObjCatalog::Find(const wxString& cls_filter)
{
auto cfilter = std::dynamic_pointer_cast<MFilter>(mFilter->GetChild(2));
auto cfilter_data = cfilter->GetData();
cfilter_data.mVal = cls_filter;
cfilter_data.mIsEnabled = true;
cfilter->SetData(cfilter_data, true);
auto cat_old = mFilterCat->GetData();
wh::FilterData cat_filter = cat_old;
cat_filter.mIsEnabled = false;
mFilterCat->SetData(cat_filter);
Load();
cfilter_data.mIsEnabled = false;
cfilter->SetData(cfilter_data, true);
mFilterCat->SetData(cat_old, true);
}
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "458"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
char symbol;
while( ~scanf("%c",&symbol) ){
if(symbol!='\n')
symbol = symbol - 7;
printf("%c",symbol);
}
return 0;
}
|
#pragma once
#include <vulkan\vulkan.h>
#include <vector>
#include<functional>
#include <glm\glm.hpp>
#include <memory>
#include "VkDeleter.h"
#include "VkRelease.h"
#include "VulkanDebug.h"
#include "Builders\BufferInfoBuilder.h"
#include <Systems\Graphics\IGraphicsPipeline.h>
struct Buffer
{
VkBuffer buffer;
VkBuffer bufferMemory;
};
struct TransferBuffer
{
Buffer stagingBuffer;
Buffer mainBuffer;
uint32_t size;
};
struct ShaderStage
{
ShaderStage(VkShaderStageFlagBits flag, const char * name) : shaderFlag(flag), filename(name) {
}
VkShaderStageFlagBits shaderFlag = VK_SHADER_STAGE_VERTEX_BIT;
const char * filename;
};
class IVulkanGraphicsSystem
{
public:
IVulkanGraphicsSystem()
{
}
virtual ~IVulkanGraphicsSystem() noexcept = default;
virtual void Initialize(
std::function<void(const VkInstance&, VkSurfaceKHR*)> createSurface,
std::function<void(VkDevice)> createGraphicsPipeline,
std::function<void(VkCommandBuffer)> createDrawCommands,
std::function<void()> createVertexBuffers,
glm::vec2 dimensions) = 0;
virtual void Draw() = 0;
virtual void RecreateSwapChain(glm::vec2 dimensions) = 0;
virtual void SetValidationLayers(std::vector<const char *> layers) = 0;
virtual void SetDeviceExtensions(std::vector<const char *> extensions) = 0;
virtual VkShaderModule CreateShaderModule(const char * filename) = 0;
virtual VkPhysicalDevice GetPhysicalDevice() const = 0;
virtual void WaitUntilDeviceIdle() const = 0;
virtual void WaitUntilGraphicsQueueIdle() const = 0;
virtual Buffer CreateBuffer(VkBufferCreateInfo bufferInfo, VkMemoryPropertyFlagBits properties = (VkMemoryPropertyFlagBits)(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) = 0;
virtual VkRenderPass CreateRenderPass() = 0;
virtual VkRenderPass CreateRenderPass(const VkAttachmentDescription & colorAttachment, const VkSubpassDescription & subpassDescription, VkSubpassDependency const & subpassDepdency) = 0;
virtual VkRenderPass CreateRenderPass(VkRenderPassCreateInfo renderPassInfo) = 0;
virtual void SetRenderpass(VkRenderPass renderPass) = 0;
virtual VkRenderPass GetRenderPass() const = 0;
virtual std::vector<VkPipelineShaderStageCreateInfo> CreateShaderStages(const std::vector<ShaderStage> & shaderStages) = 0;
virtual VkPipeline CreateGraphicsPipeline(VkPipelineVertexInputStateCreateInfo vertexInput, const std::vector<VkPipelineShaderStageCreateInfo> & shaderStages) = 0;
virtual VkPipeline CreateGraphicsPipeline(VkPipelineVertexInputStateCreateInfo vertexInput, const std::vector<VkPipelineShaderStageCreateInfo> & shaderStages, VkPipelineLayoutCreateInfo pipelineInfo) = 0;
virtual void SetGraphicsPipeline(VkPipeline pipeline) = 0;
virtual const VRelease<VkDevice> & GetDevice() const = 0;
virtual VkCommandPool GetCommandPool() const = 0;
virtual VkQueue GetGraphicsQueue() const = 0;
virtual VkPipelineLayout GetPipelineLayout() const = 0;
virtual TransferBuffer MapToLocalMemory(uint32_t bufferSize, void * data, VkBufferUsageFlagBits usage = (VkBufferUsageFlagBits)(VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT)) = 0;
virtual void MapToLocalMemory(TransferBuffer buffer, void * data) = 0;
virtual GraphicsPipelineCreator * StartGraphicsPipeline(VkPipelineVertexInputStateCreateInfo vertexInput, const std::vector<VkPipelineShaderStageCreateInfo> & shaderStages) = 0;
};
class VulkanGraphicsSystem : public IVulkanGraphicsSystem
{
public:
VulkanGraphicsSystem() : graphicsPipelineCreator(new GraphicsPipelineCreator())
{
}
~VulkanGraphicsSystem()
{
for (auto buffer : vertexBuffers){
buffer.Release();
}
for (auto shaderModule : shaderModules) {
shaderModule.Release();
}
for (auto memoryBuffer : vertexMemoryBuffers){
memoryBuffer.Release();
}
for (auto renderpass : renderpasses) {
renderpass.Release();
}
vkDestroyPipeline(device, graphicsPipeline, nullptr);
swapChain.Release();
pipelineLayout.Release();
commandPool.Release();
imageAvailableSemaphore.Release();
renderFinishedSemaphore.Release();
for (auto swapChainFrameBuffer : swapChainFramebuffers) {
swapChainFrameBuffer.Release();
}
for (auto swapChainImageView : swapChainImageViews) {
swapChainImageView.Release();
}
graphicsPipelineCreator->Cleanup();
device.Release();
callback.Release();
surface.Release();
instance.Release();
}
void Initialize(
std::function<void(const VkInstance&, VkSurfaceKHR*)> createSurface,
std::function<void(VkDevice)> createGraphicsPipeline,
std::function<void(VkCommandBuffer)> createDrawCommands,
std::function<void()> createVertexBuffers,
glm::vec2 dimensions) override {
initInstance();
this->createGraphicsPipeline = createGraphicsPipeline;
this->createDrawCommands = createDrawCommands;
VulkanDebug::setupDebugCallback(instance, &callback);
width = static_cast<uint32_t>(dimensions.x);
height = static_cast<uint32_t>(dimensions.y);
createSurface(instance, &surface);
pickPhysicalDevice();
createLogicalDevice();
createSwapChain();
createImageViews();
//currentRenderPass = CreateRenderPass();
graphicsPipelineCreator->SetRenderpass(CreateRenderPass());
graphicsPipelineCreator->Initialize(device,swapChainExtent,glm::vec2(width,height));
createGraphicsPipeline(device);
createFramebuffers();
createCommandPool();
createVertexBuffers();
createCommandBuffers();
createSemaphores();
}
virtual GraphicsPipelineCreator * StartGraphicsPipeline(VkPipelineVertexInputStateCreateInfo vertexInput, const std::vector<VkPipelineShaderStageCreateInfo> & shaderStages) override {
return this->graphicsPipelineCreator
->StartGraphicsPipeline(vertexInput, shaderStages);
}
Buffer CreateBuffer(VkBufferCreateInfo bufferInfo, VkMemoryPropertyFlagBits properties = (VkMemoryPropertyFlagBits)(VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)) override {
vertexBuffers.push_back({ device,vkDestroyBuffer });
vkOk(vkCreateBuffer(device, &bufferInfo, nullptr, &vertexBuffers[vertexBuffers.size() - 1]), "Failed to create the vertex buffer");
auto vertexBuffer = vertexBuffers[vertexBuffers.size() - 1];
vertexMemoryBuffers.push_back({ device,vkFreeMemory });
VkMemoryRequirements memoryRequirements;
vkGetBufferMemoryRequirements(device, vertexBuffer, &memoryRequirements);
VkMemoryAllocateInfo allocateInfo = {};
allocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocateInfo.allocationSize = memoryRequirements.size;
allocateInfo.memoryTypeIndex = findMemoryType(memoryRequirements.memoryTypeBits, properties, GetPhysicalDevice());
vkOk(vkAllocateMemory(device, &allocateInfo, nullptr, &vertexMemoryBuffers[vertexMemoryBuffers.size() - 1]), "Failed to allocate vertex buffer memory");
vkBindBufferMemory(device, vertexBuffer, vertexMemoryBuffers[vertexMemoryBuffers.size() - 1], 0);
auto vertexBufferMemory = vertexMemoryBuffers[vertexMemoryBuffers.size() - 1];
return {vertexBuffer, vertexBufferMemory};
}
virtual void MapToLocalMemory(TransferBuffer buffer, void * data) override {
void * newData;
vkMapMemory(device, buffer.stagingBuffer.bufferMemory, 0, buffer.size, 0, &newData);
memcpy(newData, data, (size_t)buffer.size);
vkUnmapMemory(device, buffer.stagingBuffer.bufferMemory);
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = 1;
VkCommandBuffer commandBuffer;
vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
vkBeginCommandBuffer(commandBuffer, &beginInfo);
VkBufferCopy copyRegion = {};
copyRegion.srcOffset = 0;
copyRegion.dstOffset = 0;
copyRegion.size = buffer.size;
vkCmdCopyBuffer(commandBuffer, buffer.stagingBuffer.buffer, buffer.mainBuffer.buffer, 1, ©Region);
vkEndCommandBuffer(commandBuffer);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffer;
vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
WaitUntilGraphicsQueueIdle();
vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
}
virtual VkPipelineLayout GetPipelineLayout() const override{
return graphicsPipelineCreator->GetPipelineLayout();
}
virtual TransferBuffer MapToLocalMemory(uint32_t bufferSize, void * data, VkBufferUsageFlagBits usage = (VkBufferUsageFlagBits)(VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT)) override {
auto stagingBufferInfo = BufferInfoBuilder(bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT)
.Build();
auto stagingBuffer = CreateBuffer(stagingBufferInfo);
/*void * newData;
vkMapMemory(device, stagingBuffer.bufferMemory, 0, stagingBufferInfo.size, 0, &newData);
memcpy(newData, data, (size_t)stagingBufferInfo.size);
vkUnmapMemory(device, stagingBuffer.bufferMemory);*/
auto bufferInfo = BufferInfoBuilder(bufferSize, usage)
.Build();
auto buffer = CreateBuffer(bufferInfo, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
TransferBuffer transferBuffer = {};// {stagingBuffer, vertexBuffer, bufferSize};
transferBuffer.mainBuffer = buffer;
transferBuffer.size = bufferSize;
transferBuffer.stagingBuffer = stagingBuffer;
MapToLocalMemory(transferBuffer,data);
return transferBuffer;
}
virtual VkShaderModule CreateShaderModule(const char * filename) override {
shaderModules.push_back({ device,vkDestroyShaderModule });
vkOk(vkCreateShaderModule(device, &ShaderModuleInfoBuilder(readFile(filename)).Build(), nullptr, &shaderModules[shaderModules.size() - 1]));
return shaderModules[shaderModules.size() - 1];
}
virtual VkCommandPool GetCommandPool() const override{
return commandPool;
}
virtual VkPhysicalDevice GetPhysicalDevice() const {
return physicalDevice;
}
void Draw() {
uint32_t imageIndex;
vkAcquireNextImageKHR(device, swapChain, std::numeric_limits<uint64_t>::max(), imageAvailableSemaphore, VK_NULL_HANDLE, &imageIndex);
VkSubmitInfo submitInfo = {};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = { imageAvailableSemaphore };
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
VkSemaphore signalSemaphores[] = { renderFinishedSemaphore };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
vkOk(vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE), "Failed to submit draw command buffer!");
VkPresentInfoKHR presentInfo = {};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = { swapChain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
auto result = vkQueuePresentKHR(presentQueue, &presentInfo);
if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR) {
RecreateSwapChain(glm::vec2(width,height));
}
else if (result != VK_SUCCESS) {
vkOk(result, "Failed to present swap chain image!");
}
}
void WaitUntilDeviceIdle()const override{
vkDeviceWaitIdle(device);
}
virtual void WaitUntilGraphicsQueueIdle() const override {
vkQueueWaitIdle(graphicsQueue);
}
void SetValidationLayers(std::vector<const char *> layers) override {
validationLayers = std::move(layers);
}
void SetDeviceExtensions(std::vector<const char *> extensions) override{
deviceExtensions = std::move(extensions);
}
void RecreateSwapChain(glm::vec2 dimensions) override{
width = static_cast<uint32_t>(dimensions.x);
height = static_cast<uint32_t>(dimensions.y);
vkDestroyPipeline(device, graphicsPipeline, nullptr);
vkDeviceWaitIdle(device);
createSwapChain();
createImageViews();
CreateRenderPass();
createGraphicsPipeline(device);
createFramebuffers();
createCommandBuffers();
}
void AddGraphicsPipeline()
{
}
virtual const VRelease<VkDevice> & GetDevice() const override {
return device;
}
virtual VkQueue GetGraphicsQueue() const override {
return graphicsQueue;
}
virtual VkRenderPass GetRenderPass() const { return graphicsPipelineCreator->GetRenderPass(); }
virtual VkRenderPass CreateRenderPass(const VkAttachmentDescription & colorAttachment,const VkSubpassDescription & subpassDescription, VkSubpassDependency const & subpassDepdency) override {
auto renderPassInfo = RenderpassInfoBuilder(&colorAttachment, &subpassDescription, &subpassDepdency).Build();
return CreateRenderPass(renderPassInfo);
}
virtual VkRenderPass CreateRenderPass(VkRenderPassCreateInfo renderPassInfo) override {
renderpasses.push_back({ device,vkDestroyRenderPass });
vkOk(vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderpasses[renderpasses.size()-1]), "Failed to create render pass!");
return renderpasses[renderpasses.size() - 1];
}
virtual VkRenderPass CreateRenderPass() override {
auto colorAttachment = AttachmentDescriptionBuilder(swapChainImageFormat).Build();
auto colorAttachmentRef = AttachmentReferenceBuilder().Build();
auto subPass = SubpassDescriptionBuilder(&colorAttachmentRef).Build();
auto subpassDependancy = SubpassDependencyBuilder().Build();
return CreateRenderPass(colorAttachment, subPass, subpassDependancy);
}
virtual VkPipeline CreateGraphicsPipeline(VkPipelineVertexInputStateCreateInfo vertexInput, const std::vector<VkPipelineShaderStageCreateInfo> & shaderStages) override{
auto viewport = ViewportBuilder(static_cast<float>(width), static_cast<float>(height)).Build();
auto scissor = ScissorBuilder(swapChainExtent).Build();
auto pipelineLayoutInfo = PipelineLayoutBuilder().Build();
auto viewportStateInfo = ViewportStateBuilder(&viewport, &scissor).Build();
auto colorBlending = ColorBlendStateBuilder().Build();
return CreateGraphicsPipeline(vertexInput, shaderStages, pipelineLayoutInfo,
viewportStateInfo, colorBlending);
}
virtual VkPipeline CreateGraphicsPipeline(VkPipelineVertexInputStateCreateInfo vertexInput, const std::vector<VkPipelineShaderStageCreateInfo> & shaderStages, VkPipelineLayoutCreateInfo layoutInfo) override{
auto viewport = ViewportBuilder(static_cast<float>(width), static_cast<float>(height)).Build();
auto scissor = ScissorBuilder(swapChainExtent).Build();
auto viewportStateInfo = ViewportStateBuilder(&viewport, &scissor).Build();
auto colorBlending = ColorBlendStateBuilder().Build();
return CreateGraphicsPipeline(vertexInput, shaderStages, layoutInfo,
viewportStateInfo, colorBlending);
}
void SetGraphicsPipeline(VkPipeline pipeline) {
graphicsPipeline = pipeline;
}
std::vector<VkPipelineShaderStageCreateInfo> CreateShaderStages(const std::vector<ShaderStage> & shaderStages) override {
ShaderStageBuilder shaderStageBuilder;
for (auto shaderStage : shaderStages) {
auto module = this->CreateShaderModule(shaderStage.filename);
shaderStageBuilder.AddStage(shaderStage.shaderFlag, module);
}
return shaderStageBuilder.BuildStages();
}
void SetRenderpass(VkRenderPass renderPass) override {
graphicsPipelineCreator->SetRenderpass(renderPass);
}
private:
VkPipeline CreateGraphicsPipeline(
VkPipelineVertexInputStateCreateInfo vertexInput,
const std::vector<VkPipelineShaderStageCreateInfo> & shaderStages,
VkPipelineLayoutCreateInfo pipelineLayoutInfo,
VkPipelineViewportStateCreateInfo viewport,
VkPipelineColorBlendStateCreateInfo colorBlending) {
vkOk(vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout), "Failed to create the pipeline layout!");
graphicsPipelineCreator->SetPipelineLayout(pipelineLayout);
auto rasterizerState = RasterizationStateBuilder()
.WithCounterClockwiseFace()
->WithBackCulling()
->Build();
auto pipelineInfo = GraphicsPipelineBuilder(shaderStages, viewport,
colorBlending, pipelineLayout, this->GetRenderPass())
.WithVertexInputState(vertexInput)
->WithRasterizationState(rasterizerState)
->Build();
auto pipeline = CreateGraphicsPipeline(pipelineInfo);
return pipeline;
}
VkPipeline CreateGraphicsPipeline(VkGraphicsPipelineCreateInfo graphicsCreateInfo) {
VkPipeline pipeline;
vkOk(vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &graphicsCreateInfo, nullptr, &pipeline));
return pipeline;
}
void initInstance() {
if (enableValidationLayers && !VulkanValidation::checkValidationLayerSupport(validationLayers)) {
throw std::runtime_error("validation layers requested, but not available");
}
auto instanceBuilder = InstanceInfoBuilder();
instanceBuilder
.WithApplicationInfo(ApplicationInfoBuilder()
.WithApplicationName("Hello Triangle")->Build());
if (enableValidationLayers) {
instanceBuilder.WithEnabledLayers(validationLayers.size(), validationLayers.data());
}
auto exten = VulkanValidation::getRequiredExtensions();
instanceBuilder.WithEnabledExtensions(exten.size(), exten.data());
auto instanceInfo = instanceBuilder.Build();
vkOk(vkCreateInstance(&instanceInfo, nullptr, &instance), "Failed to create instance!");
}
void createSemaphores() {
VkSemaphoreCreateInfo semaphoreInfo = {};
semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
vkOk(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphore), "Failed to create semaphores!");
vkOk(vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphore), "Failed to create semaphores!");
}
void createCommandBuffers() {
if (commandBuffers.size() > 0) {
vkFreeCommandBuffers(device, commandPool, commandBuffers.size(), commandBuffers.data());
}
commandBuffers.resize(swapChainFramebuffers.size());
VkCommandBufferAllocateInfo allocInfo = {};
allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
allocInfo.commandPool = commandPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = (uint32_t)commandBuffers.size();
vkOk(vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()), "Failed to allocate command buffers");
for (unsigned int i = 0; i < commandBuffers.size(); i++) {
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.flags = VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT;
beginInfo.pInheritanceInfo = nullptr;
vkBeginCommandBuffer(commandBuffers[i], &beginInfo);
VkRenderPassBeginInfo renderPassInfo = {};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = graphicsPipelineCreator->GetRenderPass();
renderPassInfo.framebuffer = swapChainFramebuffers[i];
renderPassInfo.renderArea.offset = { 0,0 };
renderPassInfo.renderArea.extent = swapChainExtent;
VkClearValue clearColor = { 0.0f,0.0f,0.0f,1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(commandBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(commandBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
auto commandBuffer = commandBuffers[i];
createDrawCommands(commandBuffer);
vkCmdEndRenderPass(commandBuffers[i]);
vkOk(vkEndCommandBuffer(commandBuffers[i]), "Failed to record command buffer");
}
}
void createCommandPool() {
QueueFamilyIndicies queueFamilyIndices = findQueueFamilies(physicalDevice, surface);
VkCommandPoolCreateInfo poolInfo = {};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily;
poolInfo.flags = 0;
vkOk(vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool));
}
void createFramebuffers()
{
swapChainFramebuffers.resize(swapChainImageViews.size(), { device, vkDestroyFramebuffer });
for (unsigned int i = 0; i < swapChainImageViews.size(); i++) {
VkImageView attachments[] = { swapChainImageViews[i] };
auto frameBufferInfoBuilder = FrameBufferInfoBuilder(graphicsPipelineCreator->GetRenderPass(), swapChainExtent, attachments, 1);
vkOk(vkCreateFramebuffer(device, &frameBufferInfoBuilder.Build(), nullptr, &swapChainFramebuffers[i]), "Failed to create framebuffer");
}
}
void createImageViews() {
swapChainImageViews.resize(swapChainImages.size(), VRelease<VkImageView>{device, vkDestroyImageView});
for (unsigned int i = 0; i < swapChainImages.size(); i++) {
auto createInfo = SwapchainImageViewInfoBuilder(swapChainImages[i], swapChainImageFormat).Build();
vkOk(vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews[i]), "Failed to create image view");
}
}
void createSwapChain() {
auto createInfo = SwapchainInfoKHRBuilder(physicalDevice, surface, width, height)
.WithOldSwapchain(swapChain)
->Build();
VkSwapchainKHR newSwapchain;
vkOk(vkCreateSwapchainKHR(device, &createInfo, nullptr, &newSwapchain), "Failed to create the swap chain");
*&swapChain = newSwapchain;
vkGetSwapchainImagesKHR(device, swapChain, &createInfo.minImageCount, nullptr);
swapChainImages.resize(createInfo.minImageCount);
vkGetSwapchainImagesKHR(device, swapChain, &createInfo.minImageCount, swapChainImages.data());
swapChainImageFormat = createInfo.imageFormat;
swapChainExtent = createInfo.imageExtent;
}
void pickPhysicalDevice() {
uint32_t deviceCount;
vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
if (deviceCount == 0) {
throw std::runtime_error("failed to find any GPUS with Vulkan support!");
}
std::vector<VkPhysicalDevice> devices(deviceCount);
vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
for (const auto & device : devices) {
if (isDeviceSuitable(device)) {
physicalDevice = device;
break;
}
}
if (physicalDevice == VK_NULL_HANDLE) {
throw std::runtime_error("Failed to find a suitable GPU!");
}
}
bool isDeviceSuitable(VkPhysicalDevice device) {
VkPhysicalDeviceProperties deviceProperties;
VkPhysicalDeviceFeatures deviceFeatures;
vkGetPhysicalDeviceProperties(device, &deviceProperties);
vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
bool extensionsSupported = VulkanValidation::checkDeviceExtensionSupport(device, deviceExtensions);
bool swapChainAdequate = false;
if (extensionsSupported) {
SwapChainSupportDetails swapChainSupport = querySwapChainSupport(device, surface);
swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
}
return deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU &&
deviceFeatures.geometryShader &&
findQueueFamilies(device, surface).isComplete() &&
extensionsSupported &&
swapChainAdequate;
}
void createLogicalDevice() {
QueueFamilyIndicies indices = findQueueFamilies(physicalDevice, surface);
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<int> uniqueQueueFamilies = { indices.graphicsFamily, indices.presentFamily };
float queuePriority = 1.0f;
for (auto queueFamily : uniqueQueueFamilies) {
VkDeviceQueueCreateInfo queueCreateInfo = {};
queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = &queuePriority;
queueCreateInfos.push_back(queueCreateInfo);
}
VkPhysicalDeviceFeatures deviceFeatures = {};
VkDeviceCreateInfo createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
createInfo.pQueueCreateInfos = queueCreateInfos.data();
createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
createInfo.pEnabledFeatures = &deviceFeatures;
createInfo.enabledExtensionCount = deviceExtensions.size();
createInfo.ppEnabledExtensionNames = deviceExtensions.data();
if (enableValidationLayers) {
createInfo.enabledLayerCount = validationLayers.size();
createInfo.ppEnabledLayerNames = validationLayers.data();
}
else {
createInfo.enabledLayerCount = 0;
}
vkOk(vkCreateDevice(physicalDevice, &createInfo, nullptr, &device), "Failed to create logical device");
vkGetDeviceQueue(device, indices.graphicsFamily, 0, &graphicsQueue);
vkGetDeviceQueue(device, indices.presentFamily, 0, &presentQueue);
}
std::function<void(VkDevice)> createGraphicsPipeline;
std::function<void(VkCommandBuffer)> createDrawCommands;
uint32_t width;
uint32_t height;
VRelease<VkInstance> instance{ vkDestroyInstance };
VRelease<VkSurfaceKHR> surface{ instance, vkDestroySurfaceKHR };
VRelease<VkDevice> device{ vkDestroyDevice };
VRelease<VkSwapchainKHR> swapChain{ device, vkDestroySwapchainKHR };
VkPipeline graphicsPipeline;
//VkRenderPass currentRenderPass;
std::vector<VRelease<VkRenderPass>> renderpasses;
VRelease<VkPipelineLayout> pipelineLayout{ device, vkDestroyPipelineLayout };
VRelease<VkCommandPool> commandPool{ device, vkDestroyCommandPool };
VRelease<VkSemaphore> imageAvailableSemaphore{ device, vkDestroySemaphore };
VRelease<VkSemaphore> renderFinishedSemaphore{ device, vkDestroySemaphore };
std::vector<VkCommandBuffer> commandBuffers;
std::vector<VRelease<VkFramebuffer>> swapChainFramebuffers;
std::vector<VRelease<VkImageView>> swapChainImageViews;
std::vector<VRelease<VkBuffer>> vertexBuffers;
std::vector<VRelease<VkBuffer>> vertexMemoryBuffers;
std::vector<VRelease<VkShaderModule>> shaderModules;
std::vector<VkImage> swapChainImages;
VkFormat swapChainImageFormat;
VkExtent2D swapChainExtent;
VkQueue graphicsQueue;
VkQueue presentQueue;
VkPhysicalDevice physicalDevice = VK_NULL_HANDLE;
VRelease<VkDebugReportCallbackEXT> callback{ instance, VulkanDebug::DestroyDebugReportCallbackEXT };
std::vector<const char *> validationLayers;
std::vector<const char *> deviceExtensions;
std::unique_ptr<GraphicsPipelineCreator> graphicsPipelineCreator;
};
|
#include <stdio.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int,int> pairs;
int main(int argc, char *argv[])
{
int t;
scanf("%d",&t);
for(int i = 0;i< t;i++)
{
int n;
scanf("%d",&n);
vector<pairs> kingdoms;
int leftExtreme = 100001;
for(int j = 0;j<n;j++)
{
int l,r;
scanf("%d%d",&l,&r);
kingdoms.push_back(pairs(r,l));
if(leftExtreme > l)
{
leftExtreme = l;
}
}
std::sort(kingdoms.begin(),kingdoms.end());
leftExtreme--;
int count = 0;
for(int k =0;k<n;k++)
{
if(leftExtreme < kingdoms[k].second)
{
count++;
leftExtreme = kingdoms[k].first;
}
}
printf("%d\n",count);
}
return 0;
}
|
//
// Created by tompi on 6/3/18.
//
#ifndef OPENCLDISPATCHER_AGGREGATION_H
#define OPENCLDISPATCHER_AGGREGATION_H
#pragma once
#include "../../data_api.h"
#include "../../kernel_api.h"
#include "../../runtime_api.h"
#include "../../ImportKernelSource.h"
void IndexValue(cl_device_id _DEVICE, uint *_sorted_elements, uint _element_size, uint *_index_arr, uint *_offset_arr,
uint _offset_size, vector<string> _arguments, uint _global_size, uint ITERATOR) ;
/*class Aggregating {
public:
void Aggregate(cl_device_id _DEVICE, int _sorted_elements[], uint _element_size, uint _no_distinct_val);
};/**/
void Aggregate(cl_device_id _DEVICE, uint *_sorted_elements, uint _element_size, uint _global_size, uint ITERATOR) {
double first_primitive_time = 0;
vector<string> arguments;
uint _m_offset_size = _element_size/ITERATOR;
uint *_m_offset_arr = (uint *) calloc((uint)_m_offset_size, sizeof(uint));
uint *_m_index_arr = (uint *) calloc((uint)_element_size, sizeof(uint));
// Call function for calculating Prefix Sum
IndexValue(_DEVICE, _sorted_elements, _element_size, _m_index_arr, _m_offset_arr, _m_offset_size, arguments,
_global_size, ITERATOR);
first_primitive_time = execution_time_ns;
//cout << "1 TIME :: " << first_primitive_time << endl;
// Fetch Offset Value from Buffer
read_data(INDEX_ARR, _DEVICE, _m_index_arr, _element_size);
read_data(OFFSET_ARR, _DEVICE, _m_offset_arr, _m_offset_size);
// Clear data from buffer
clear_data(_DEVICE, arguments);
// Get unique count of elements & Make an array for Result of unique count
uint _m_unique_count = _m_offset_arr[_m_offset_size - 1] + 1;
uint *_m_agg_res = (uint *) calloc((uint)_m_unique_count, sizeof(uint));
// Preparing to calling Kernel
add_data(INDEX_ARR, _m_index_arr, _DEVICE, _element_size);
add_data(OFFSET_ARR, _m_offset_arr, _DEVICE, _m_offset_size);
add_data(RESULTANT_ARR, _m_agg_res, _DEVICE, _m_unique_count);
//lookup_data_buffer();
//Add kernels to the respective devices
string kernel_name = KERNEL_AGGREGATE;
string kernel_src = readKernelFile("../include/primitives/kernel/Aggregate.cl");
// Add the values that you need for defining at Kernel
stringstream _sStream;
_sStream << " -DITERATOR=" << ITERATOR;
//_sStream << "-DARR_SIZE=" << _element_size << " -DITERATOR=" << ITERATOR;
if (!kernel_src.empty()) {
add_kernel(kernel_name, _DEVICE, kernel_src, _sStream.str());
// Pass array of elements
arguments.push_back(INDEX_ARR);
arguments.push_back(OFFSET_ARR);
arguments.push_back(RESULTANT_ARR);
// Pass constant Params
vector<int> param;
execute(_DEVICE, kernel_name, arguments, param, _element_size, _element_size);
//cout << endl << "res" << endl;
//print_data(RESULTANT_ARR, _DEVICE, _m_unique_count);
//cout << "2 TIME :: " << execution_time_ns << endl;
execution_time_ns += first_primitive_time;
//cout << "3 TIME :: " << execution_time_ns << endl;
// Clear data from buffer
clear_data(_DEVICE, arguments);
} else {
cout << "Error in reading kernel source file.\n";
}
}
void IndexValue(cl_device_id _DEVICE, uint *_sorted_elements, uint _element_size, uint *_index_arr, uint *_offset_arr,
uint _offset_size, vector<string> _arguments, uint _global_size, uint ITERATOR) {
// Add data to the respective devices
add_data(ELEMENT_ARR, _sorted_elements, _DEVICE, _element_size);
add_data(INDEX_ARR, _index_arr, _DEVICE, _element_size);
add_data(OFFSET_ARR, _offset_arr, _DEVICE, _offset_size);
//lookup_data_buffer();
//print_data(ELEMENTS, _DEVICE, _element_size);
// Add kernels to the respective devices
string kernel_name = KERNEL_INDEX_VALUE;
string kernel_src = readKernelFile("../include/primitives/kernel/IndexValue.cl");
// Add the values that you need for defining at Kernel
stringstream _sStream;
_sStream << " -DOFFSET_SIZE=" << _offset_size << " -DITERATOR=" << ITERATOR;
//_sStream << "-DARR_SIZE=" << _element_size << " -DOFFSET_SIZE=" << _offset_size << " -DITERATOR=" << ITERATOR;
if (!kernel_src.empty()) {
add_kernel(kernel_name, _DEVICE, kernel_src, _sStream.str());
// Pass array of elements
_arguments.push_back(ELEMENT_ARR);
_arguments.push_back(INDEX_ARR);
_arguments.push_back(OFFSET_ARR);
// Pass constant Params
vector<int> param;
execute(_DEVICE, kernel_name, _arguments, param, _global_size, ITERATOR);
//cout << endl << "index arr" << endl;
//print_data(INDEX_ARR, _DEVICE, _element_size);
//cout << endl << "offset" << endl;
//print_data(OFFSET_ARR, _DEVICE, _offset_size);
} else {
cout << "Error in reading kernel source file.\n";
}
}
#endif //OPENCLDISPATCHER_AGGREGATION_H
|
/**
* Given inorder and postorder traversal of a tree, construct the binary tree.
*
* Note:
* You may assume that duplicates do not exist in the tree.
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// Without using additional data structures
class Solution {
TreeNode *do_build(vector<int> &inorder, int in_start, int in_end, vector<int> &postorder, int po_start, int po_end) {
if (in_end >= inorder.size() || po_end >= postorder.size() || in_start > in_end || po_start > po_end) {
return nullptr;
}
if (in_start == in_end && po_start == po_start) {
return new TreeNode(inorder[in_start]);
}
int rootval = postorder[po_end];
TreeNode *root = new TreeNode(rootval);
// find root val in inorder vector
int idx = -1;
for (int i = in_start; i <= in_end; i++) {
if (inorder[i] == rootval) {
idx = i;
break;
}
}
if (idx == -1) {
// error case: bad inorder array
return nullptr;
}
int leftsize = idx - in_start;
root->left = do_build(inorder, in_start, idx - 1, postorder, po_start, po_start + leftsize - 1);
root->right = do_build(inorder, idx + 1, in_end, postorder, po_start + leftsize, po_end - 1);
return root;
}
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
return do_build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);
}
};
// Use a hashmap to buffer inorder index
class Solution {
unordered_map<int, int> in_index; // <val, index>
TreeNode *do_build(vector<int> &inorder, int root_val, int in_start, int in_end,
vector<int> &postorder, int po_start, int po_end) {
TreeNode *root = new TreeNode(root_val);
int in_root_index = in_index[root_val];
// base case
if (in_start > in_end || po_start > po_end) {
return nullptr;
}
if (in_root_index > in_start) {
int leftsize = in_root_index - in_start;
root->left = do_build(inorder, postorder[po_start + leftsize - 1],
in_start, in_start + leftsize - 1,
postorder, po_start, po_start + leftsize - 1);
}
if (in_root_index < in_end) {
int rightsize = in_end - in_root_index;
root->right = do_build(inorder, postorder[po_end - 1],
in_root_index + 1, in_end,
postorder, po_end - rightsize, po_end - 1);
}
return root;
}
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if (inorder.size() != postorder.size()) {
return nullptr;
}
if (inorder.size() == 0) {
return nullptr;
}
for (int i = 0; i < inorder.size(); i++) {
in_index[inorder[i]] = i;
}
return do_build(inorder, postorder[postorder.size()-1], 0, inorder.size() - 1,
postorder, 0, postorder.size() - 1);
}
};
|
#pragma once
#include <vector>
#include <map>
#include "cs225/PNG.h"
#include "dsets.h"
class SquareMaze{
public:
// constructor
SquareMaze();
~SquareMaze();
bool isEdge(int x, int y, int dir);
// prepare block I
void blockI(int height, int width);
// bfs search returning the distances vector
std::vector<int> bfs ();
// turns address into coordinate
std::pair<int, int> coordinate (int address);
// check if there are any loops
bool loops (int position, int dir);
// check if going on border
bool isBorder (int position, int dir);
// Makes a new SquareMaze of the given height and width
void makeMaze (int width, int height);
// This uses your representation of the maze to determine whether it is possible to travel in the given direction from the square at coordinates (x,y)
bool canTravel (int x, int y, int dir) const;
// Sets whether or not the specified wall exists
void setWall (int x, int y, int dir, bool exists);
// Solves this SquareMaze
std::vector<int> solveMaze ();
// Draws the maze without the solution
cs225::PNG* drawMaze () const;
// This function calls drawMaze, then solveMaze; it modifies the PNG from drawMaze to show the solution vector and the exit
cs225::PNG* drawMazeWithSolution ();
private:
int width_;
int height_;
//std::map<std::pair<int, int>, bool> maze;
//std::vector<int> solution;
DisjointSets disjoint;
std::vector<std::vector<bool>> walls;
};
|
class Solution
{
public:
int setBits(int N)
{
// only gravity will pull me down
// Set Bits
int res=0;
while(N) {
res += (N&1);
N = N>>1;
}
return res;
}
};
|
#include <iostream>
using namespace std;
#define MAX 100
#define INFTY 10000001
#define WHITE 0
#define GRAY 1
#define BLACK 2
#define DEFLT 0 // 初期値
int M[MAX][MAX], d[MAX];
void dijkstra(int n){
int mincost, u, color[n], p[n];
for(int i=0; i<n; i++){
color[i] = WHITE;
d[i] = INFTY;
}
d[DEFLT] = 0;
p[DEFLT] = -1;
while(true){
mincost = INFTY;
for(int i=0; i<n; i++){
if(color[i] != BLACK && d[i] < mincost){
mincost = d[i];
u = i;
}
}
if(mincost == INFTY) break;
color[u] = BLACK;
for(int v=0; v<n; v++){
if(color[v] != BLACK && M[u][v] < INFTY){
if(d[u] + M[u][v] < d[v]){
d[v] = d[u] + M[u][v];
p[v] = u;
color[v] = GRAY;
}
}
}
}
}
int main(void){
int n, u, k, v, c;
cin >> n;
for(u=0; u<MAX; u++){
for(v=0; v<MAX; v++){
M[u][v] = INFTY;
}
}
for(int i=0; i<n; i++){
cin >> u >> k;
for(int j=0; j<k; j++){
cin >> v >> c;
M[u][v] = c;
}
}
dijkstra(n);
for(int i=0; i<n; i++){
cout << i << " " << d[i] << endl;;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "modules/display/vis_dev.h"
#include "modules/dochand/win.h"
#include "modules/forms/piforms.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/viewers/viewers.h"
#include "modules/windowcommander/src/WindowCommander.h"
#include "modules/widgets/OpButton.h"
#include "modules/widgets/OpEdit.h"
#include "modules/widgets/OpFileChooserEdit.h"
#include "modules/locale/locale-enum.h"
#ifdef _FILE_UPLOAD_SUPPORT_
# include "modules/forms/formmanager.h"
# include "modules/formats/argsplit.h"
#ifdef WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
# include "modules/util/opfile/opfile.h"
#endif // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
#endif // _FILE_UPLOAD_SUPPORT_
#ifdef _FILE_UPLOAD_SUPPORT_
/**
* Gathers all matching extensions. Duplicates will occur.
*/
OP_STATUS AppendExtensions(OpAutoVector<OpString> &extensions, const uni_char* mime_type_str, UINT32 len)
{
while (len > 0 && mime_type_str[len-1] == '*')
len--; // remove trailing *
if (len == 0)
return OpStatus::OK;
// Run through the viewers and append file extensions if we match the MIME type.
ChainedHashIterator *viewer_iterator = NULL;
OP_STATUS rc = g_viewers->CreateIterator(viewer_iterator);
if (rc == OpStatus::ERR)
return OpStatus::OK; // no viewers available
RETURN_IF_ERROR(rc);
ANCHOR_PTR(ChainedHashIterator, viewer_iterator);
while (Viewer* viewer = g_viewers->GetNextViewer(viewer_iterator))
{
if (uni_strnicmp(mime_type_str, viewer->GetContentTypeString(), len) == 0)
{
const uni_char* viewer_exts = viewer->GetExtensions();
while (viewer_exts)
{
int viewer_exts_len = 0;
while (viewer_exts[viewer_exts_len] != '\0' &&
viewer_exts[viewer_exts_len] != ',')
{
viewer_exts_len++;
}
if (viewer_exts_len > 0)
{
unsigned int insert_before;
int last_diff = 1;
for (insert_before = 0; insert_before < extensions.GetCount(); ++insert_before)
{
OpString* str = extensions.Get(insert_before);
int this_len = str->Length();
last_diff = uni_strncmp(str->CStr(), viewer_exts, MIN(this_len, viewer_exts_len));
if (last_diff == 0 && viewer_exts_len != this_len)
last_diff = this_len < viewer_exts_len ? -1 : 1;
if (last_diff >= 0)
break;
}
if (last_diff != 0)
{
OpString* str = OP_NEW(OpString, ());
if (!str)
return OpStatus::ERR_NO_MEMORY;
OP_STATUS res;
if (insert_before < extensions.GetCount())
res = extensions.Insert(insert_before, str);
else
res = extensions.Add(str);
if (OpStatus::IsError(res))
{
OP_DELETE(str);
return res;
}
RETURN_IF_ERROR(str->Set(viewer_exts, viewer_exts_len));
}
}
if (viewer_exts[viewer_exts_len] == '\0')
break; // finished with this mime type
viewer_exts += viewer_exts_len + 1;
}
}
}
return OpStatus::OK;
}
#endif // _FILE_UPLOAD_SUPPORT_
static inline WindowCommander* GetWindowCommander(VisualDevice* vis_dev)
{
if (vis_dev)
{
Window* w = vis_dev->GetWindow();
if (w)
return w->GetWindowCommander();
}
return 0;
}
// == OpFileChooserEdit ===========================================================
OP_STATUS OpFileChooserEdit::Construct(OpFileChooserEdit** obj)
{
*obj = OP_NEW(OpFileChooserEdit, ());
if (!*obj)
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsError((*obj)->init_status))
{
OP_DELETE(*obj);
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
OpFileChooserEdit::OpFileChooserEdit()
: button(NULL)
, edit(NULL)
# ifdef _FILE_UPLOAD_SUPPORT_
, m_media_types(NULL)
, m_is_upload(FALSE)
, m_max_no_of_files(1)
, m_callback(NULL)
# endif // _FILE_UPLOAD_SUPPORT_
{
OP_STATUS status;
status = OpEdit::Construct(&edit);
CHECK_STATUS(status);
AddChild(edit, TRUE);
edit->SetForceTextLTR(TRUE);
status = OpButton::Construct(&button);
CHECK_STATUS(status);
AddChild(button, TRUE);
// Center text in button and use TRUE so forms can't change it back again.
button->SetJustify(JUSTIFY_CENTER, TRUE);
// now everybody is supposed to use the GUI for manipulation of paths on web pages
// see OnAdded() for re-enabling it in native UI
edit->SetReadOnly(TRUE);
edit->SetForceAllowClear(TRUE);
# ifdef WIDGETS_FILE_UPLOAD_IMAGE
button->SetText(UNI_L("-"));
button->GetForegroundSkin()->SetImage(UNI_L("File upload"));
button->SetButtonStyle(OpButton::STYLE_IMAGE);
# else // WIDGETS_FILE_UPLOAD_IMAGE
OpString browse;
TRAP(status, g_languageManager->GetStringL(Str::SI_BROWSE_TEXT, browse));
init_status = status;
button->SetText(browse.CStr());
# endif // WIDGETS_FILE_UPLOAD_IMAGE
button->SetListener(this);
edit->SetListener(this);
}
OpFileChooserEdit::~OpFileChooserEdit()
{
# ifdef _FILE_UPLOAD_SUPPORT_
if (m_callback)
m_callback->Closing(this);
OP_DELETE(m_media_types);
# endif // _FILE_UPLOAD_SUPPORT_
}
#ifdef WIDGETS_CLONE_SUPPORT
OP_STATUS OpFileChooserEdit::CreateClone(OpWidget **obj, OpWidget *parent, INT32 font_size, BOOL expanded)
{
*obj = NULL;
OpFileChooserEdit *widget;
RETURN_IF_ERROR(OpFileChooserEdit::Construct(&widget));
parent->AddChild(widget);
if (OpStatus::IsError(widget->CloneProperties(this, font_size)))
{
widget->Remove();
OP_DELETE(widget);
return OpStatus::ERR;
}
*obj = widget;
return OpStatus::OK;
}
#endif // WIDGETS_CLONE_SUPPORT
INT32 OpFileChooserEdit::GetButtonWidth()
{
INT32 button_width = 0;
INT32 button_height = 0;
button->GetRequiredSize(button_width, button_height);
return button_width;
}
void OpFileChooserEdit::OnResize(INT32* new_w, INT32* new_h)
{
INT32 button_width = GetButtonWidth();
int width = *new_w;
int height = *new_h;
int spacing = 2;
int edit_width = width - button_width - spacing;
if (GetRTL())
{
button->SetRect(OpRect(0, 0, button_width, height));
edit->SetRect(OpRect(button_width + spacing, 0, edit_width, height));
}
else
{
edit->SetRect(OpRect(0, 0, edit_width, height));
button->SetRect(OpRect(edit_width + spacing, 0, button_width, height));
}
}
void OpFileChooserEdit::OnFocus(BOOL focus, FOCUS_REASON reason)
{
# ifdef _FILE_UPLOAD_SUPPORT_
// *** SECURITY ***
// This mustn't be changed since it currently prevents the following:
// 1. User pressing key
// 2. Page setting focus to file upload in keydown/up/press handler
// 3. Character appearing in file upload
// By doing the operation above selectively and by restoring focus a page
// can enter any file name if only the user writes those letters.
if (focus)
{
button->SetFocus(reason);
}
# endif // _FILE_UPLOAD_SUPPORT_
}
void OpFileChooserEdit::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect)
{
edit->SetHasCssBackground(HasCssBackgroundImage());
//button->SetHasCssBackground(HasCssBackgroundImage());
edit->SetHasCssBorder(HasCssBorder());
button->SetHasCssBorder(HasCssBorder());
edit->SetPadding(GetPaddingLeft(), GetPaddingTop(), GetPaddingRight(), GetPaddingBottom());
button->SetPadding(GetPaddingLeft(), GetPaddingTop(), GetPaddingRight(), GetPaddingBottom());
// We don't want any style to affect the button
button->UnsetForegroundColor();
button->UnsetBackgroundColor();
}
void OpFileChooserEdit::EndChangeProperties()
{
// propagate background color to edit field
if (!m_color.use_default_background_color)
edit->SetBackgroundColor(m_color.background_color);
}
# ifdef _FILE_UPLOAD_SUPPORT_
OP_STATUS OpFileChooserEdit::SetButtonText(const uni_char* text)
{
return button->SetText(text);
}
OP_STATUS OpFileChooserEdit::SetText(const uni_char* text)
{
#ifdef WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
OpString absolute_path;
RETURN_IF_ERROR(absolute_path.Set(text));
UniParameterList filelist;
RETURN_IF_ERROR(FormManager::ConfigureForFileSplit(filelist, absolute_path));
const uni_char* sep = UNI_L("; %s");
OpString locPaths;
UniParameters* file = filelist.First();
while (file)
{
if (const uni_char* file_name = file->Name())
{
// try to get the localized path
OpFile opfile;
RETURN_IF_ERROR(opfile.Construct(file_name));
// GetLocalizedPath may return OpStatus::ERR for
// non-localizable paths. such errors should not be
// reported, instead absolute path is used.
OpString localizedPath;
OP_STATUS status = opfile.GetLocalizedPath(&localizedPath);
if (OpStatus::IsSuccess(status))
file_name = localizedPath.CStr();
else
RETURN_IF_MEMORY_ERROR(status);
// append path
if (locPaths.HasContent())
status = locPaths.AppendFormat(sep, file_name);
else
status = locPaths.Append(file_name);
RETURN_IF_ERROR(status);
}
file = file->Suc();
}
RETURN_IF_ERROR(edit->SetText(locPaths));
m_path.TakeOver(absolute_path);
return OpStatus::OK;
#else // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
return edit->SetText(text);
#endif //WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
}
INT32 OpFileChooserEdit::GetTextLength()
{
#ifdef WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
return m_path.Length();
#else // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
return edit->GetTextLength();
#endif // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
}
OP_STATUS OpFileChooserEdit::GetText(OpString &str)
{
#ifdef WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
return str.Set(m_path);
#else // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
return edit ? edit->GetText(str) : OpStatus::ERR_NULL_POINTER;
#endif // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
}
void OpFileChooserEdit::GetText(uni_char *buf)
{
#ifdef WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
uni_strcpy(buf, m_path.CStr());
#else // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
edit->GetText(buf, GetTextLength(), 0);
#endif // WIDGETS_HIDE_FILENAMES_IN_FILE_CHOOSER
}
void OpFileChooserEdit::SetIsFileUpload(BOOL is_upload)
{
m_is_upload = is_upload;
SetEnabled(IsEnabled());
}
void OpFileChooserEdit::SetMaxNumberOfFiles(unsigned int max_count)
{
Str::LocaleString id = Str::NOT_A_STRING;
if (max_count > 1)
{
if (m_max_no_of_files <= 1)
{
// Need to change button text
// Set "Add" text on button
id = Str::D_ADD_FILE_BUTTON_TEXT;
}
}
// else we want a multi file widget
else if (m_max_no_of_files > 1)
{
// Need to change button text
// Set "Browse" text on button
id = Str::SI_BROWSE_TEXT;
}
m_max_no_of_files = max_count;
if (id != Str::NOT_A_STRING)
{
OpString label;
if (OpStatus::IsSuccess(g_languageManager->GetString(id, label)))
{
button->SetText(label.CStr());
}
}
}
void OpFileChooserEdit::SetEnabled(BOOL enabled)
{
OpWidget::SetEnabled(enabled);
if (m_is_upload)
{
WindowCommander* wc = GetWindowCommander(GetVisualDevice());
if (wc && !wc->GetFileSelectionListener()->OnRequestPermission(wc))
enabled = FALSE;
if(button)
button->SetEnabled(enabled);
}
}
void OpFileChooserEdit::OnAdded()
{
if (!IsForm())
{
edit->SetReadOnly(FALSE);
}
}
void OpFileChooserEdit::OnChangeWhenLostFocus(OpWidget *widget)
{
if (listener && widget == edit)
listener->OnChange(this, FALSE);
}
void OpFileChooserEdit::OnClick()
{
WindowCommander* wc = GetWindowCommander(GetVisualDevice());
if (!wc || !GetFormObject() || m_callback)
return;
OP_DELETE(m_media_types);
m_media_types = 0;
OpFileChooserEditCallback* callback = OP_NEW(OpFileChooserEditCallback, (this));
if (!callback)
{
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
return;
}
m_callback = callback;
wc->GetFileSelectionListener()->OnUploadFilesRequest(wc, callback);
}
void OpFileChooserEdit::OnGeneratedClick(OpWidget *widget, UINT32 id)
{
if (widget == button)
{
// Called on keypresses or actions
OnClick();
}
}
void OpFileChooserEdit::OnChange(OpWidget *widget, BOOL changed_by_mouse)
{
if (listener && widget == edit)
listener->OnChange(this, changed_by_mouse);
}
void OpFileChooserEdit::OnFilesSelected(const OpVector<OpString> *files)
{
const uni_char quote = '"';
if (files->GetCount() > 1)
{
for (unsigned int i = 0; i < files->GetCount(); i++)
{
if (files->Get(i) && files->Get(i)->HasContent()) // XXX Is this necessary?
{
// Quote the string
OpString quoted_file_name;
if (OpStatus::IsError(quoted_file_name.AppendFormat(UNI_L("\"%s\""), (files->Get(i))->CStr())))
return;
if (m_max_no_of_files > 1)
{
// Append the file
AppendFileName(quoted_file_name.CStr());
}
else if (OpStatus::IsError(SetText(quoted_file_name.CStr())))
{
return;
}
}
}
}
else
{
if( IsInWebForm() )
{
OpString tmp;
RETURN_VOID_IF_ERROR(tmp.Set(files->Get(0)->CStr()));
tmp.Strip();
int length = tmp.Length();
// See if we need to quote the string
if( length > 0 && tmp.CStr()[0] != quote && tmp.CStr()[length-1] != quote )
{
OpString tmp2;
RETURN_VOID_IF_ERROR(tmp2.AppendFormat(UNI_L("\"%s\""), tmp.CStr()));
RETURN_VOID_IF_ERROR(tmp.Set( tmp2.CStr() ));
}
SetText(tmp.CStr());
}
else
{
SetText(files->Get(0)->CStr());
}
}
if (listener)
{
listener->OnChange(this, FALSE);
}
}
void OpFileChooserEdit::AppendFileName(const uni_char* new_file_name)
{
OpString contents;
OP_STATUS status = GetText(contents);
if (OpStatus::IsSuccess(status) && !contents.IsEmpty())
{
status = contents.Append(";"); // file delimiter
if (OpStatus::IsSuccess(status))
{
status = contents.Append(new_file_name);
}
}
else
{
// We didn't get an existing file name
status = contents.Set(new_file_name);
}
if (OpStatus::IsSuccess(status))
{
SetText(contents.CStr());
}
}
OP_STATUS OpFileChooserEdit::InitializeMediaTypes()
{
if (m_media_types)
return OpStatus::OK;
HTML_Element* helm = GetFormObject()->GetHTML_Element();
OP_ASSERT(helm);
const uni_char* accept = helm->GetStringAttr(ATTR_ACCEPT);
m_media_types = OP_NEW(OpAutoVector<OpFileSelectionListener::MediaType>, ());
if (!m_media_types)
return OpStatus::ERR_NO_MEMORY;
if (accept)
{
const uni_char* str = accept;
while (TRUE)
{
int len = 0;
while(str[len] != ',' && str[len] != 0)
len++;
OpFileSelectionListener::MediaType* media_type = OP_NEW(OpFileSelectionListener::MediaType, ());
if (!media_type)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(m_media_types->Add(media_type));
RETURN_IF_ERROR(media_type->media_type.Set(str, len));
// Add the extensions
RETURN_IF_ERROR(AppendExtensions(media_type->file_extensions, str, len));
if (str[len] == '\0')
break;
str += len + 1;
len = 0;
}
}
return OpStatus::OK;
}
const OpFileSelectionListener::MediaType* OpFileChooserEdit::GetMediaType(unsigned int index)
{
if (!m_media_types)
{
OP_STATUS res = InitializeMediaTypes();
if (OpStatus::IsError(res))
{
OP_DELETE(m_media_types);
m_media_types = 0;
g_memory_manager->RaiseCondition(res);
return 0;
}
}
if (index < m_media_types->GetCount())
return m_media_types->Get(index);
else
return 0;
}
unsigned int OpFileChooserEditCallback::GetMaxFileCount()
{
if (m_fc_edit)
return MAX(1, m_fc_edit->m_max_no_of_files);
else
return 1;
}
const uni_char* OpFileChooserEditCallback::GetInitialPath()
{
if (m_fc_edit)
{
if (OpStatus::IsError(m_fc_edit->GetText(m_initial_path)))
return NULL;
return m_initial_path.CStr();
}
else
return NULL;
}
const uni_char* GetAcceptAttribute(HTML_Element * helm)
{
OP_ASSERT(helm);
const uni_char* accept = helm->GetStringAttr(ATTR_ACCEPT);
// If we have an accept attribute on the forms element, that
// will function as a fallback
if (!accept)
{
FramesDocument* frames_doc = NULL; // XXX Must get a real document
HTML_Element* form_elm = FormManager::FindFormElm(frames_doc, helm);
if (form_elm)
{
accept = form_elm->GetStringAttr(ATTR_ACCEPT);
}
}
return accept;
}
const OpFileSelectionListener::MediaType* OpFileChooserEditCallback::GetMediaType(unsigned int index)
{
OpFileSelectionListener::MediaType media_type;
if (m_fc_edit)
return m_fc_edit->GetMediaType(index);
else
return 0;
}
void OpFileChooserEditCallback::OnFilesSelected(const OpAutoVector<OpString>* files)
{
if (files && files->GetCount() > 0)
{
if (m_fc_edit && files->GetCount())
m_fc_edit->OnFilesSelected(files);
}
if (m_fc_edit)
m_fc_edit->ResetFileChooserCallback();
OP_DELETE(this);
}
# endif // _FILE_UPLOAD_SUPPORT_
|
int pirsensor = 0;
void setup(){
pinMode(13, OUTPUT);
pinMode(2, INPUT);
}
void loop(){
pirsensor = digitalRead(2);
if (pirsensor==HIGH){
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,LOW);
}
delay(10);
}
|
#include "stdafx.h"
#include "ThreadPool.h"
#include "Interface.h"
static unsigned int WINAPI ThreadPoolWorkThread(void *Param)
{
((ThreadPool*)Param)->ThreadFunc();
return 0;
}
void ThreadPool::ThreadFunc()
{
UINT threadNumber = ::InterlockedIncrement(&m_threadNum);
Log("ThreadPool the " << threadNumber << "th thread start!");
while (m_bRun)
{
_ThreadElem* oneElem = GetElem();
if (NULL != oneElem)
{
oneElem->callback(oneElem->pParam);
}
Sleep(1);
}
}
_ThreadElem* ThreadPool::GetElem()
{
AUTO_LOCKER(m_csLocker);
if (m_elems.size() == 0) return NULL;
//遍历
DWORD tick = timeGetTime();
for (auto m_elemIt = m_elems.begin(); m_elemIt != m_elems.end();)
{
_ThreadElem* oneElem = *m_elemIt;
if (tick - oneElem->startTime > oneElem->interval)
{
oneElem->startTime = tick;
if (oneElem->runCount == 0 && oneElem->runCount != MAX_THREAD_RUNCOUNT)
{
SAFE_DELETE(oneElem->pParam);
SAFE_DELETE(oneElem);
m_elemIt = m_elems.erase(m_elemIt);
continue;
}
if (oneElem->runCount != MAX_THREAD_RUNCOUNT)
{
--oneElem->runCount;
}
return oneElem;
}
++m_elemIt;
}
return NULL;
}
ThreadPool::ThreadPool()
{
m_bRun = false;
m_threadNum = 0;
}
ThreadPool::~ThreadPool()
{
timeEndPeriod(1);
}
ThreadPool* ThreadPool::instance = NULL;
ThreadPool* ThreadPool::Instance()
{
if (instance == NULL)
{
instance = new ThreadPool();
}
return instance;
}
bool ThreadPool::Init(UINT threadNum)
{
Log("初始化线程池。。。");
int errorCode = 0;
//初始化线程
m_bRun = true;
for (UINT i = 0; i < threadNum; ++i)
{
::_beginthreadex(NULL, 0, ThreadPoolWorkThread, this, 0, 0);
}
//初始化时间控制
timeBeginPeriod(1);
//初始化临界区锁
m_csLocker.init();
return true;
}
bool ThreadPool::AddElem(_ThreadElem* param)
{
if (param->runCount == 0 && param->runCount != MAX_THREAD_RUNCOUNT)
{
Log("ThreadPool param error!");
return false;
}
if (!HasSpace())
{
Log("ThreadPool has not enough space!");
return false;
}
AUTO_LOCKER(m_csLocker);
m_elems.push_back(param);
return true;
}
bool ThreadPool::HasSpace()
{
AUTO_LOCKER(m_csLocker);
if (m_elems.size() < MAX_THREAD_ELEMS)
{
return true;
}
return false;
}
|
#pragma once
#include "Value.h"
class Lexer;
class SymbolTable;
class Proto;
class Func;
class GC;
class Pepper;
class Parser {
Proto *proto;
SymbolTable *syms;
Lexer *lexer;
GC *gc;
Parser(GC *gc, Proto *proto, SymbolTable *syms, Lexer *lexer);
~Parser();
int createUpval(Proto *proto, int protoLevel, Value name, int level, int slot);
int lookupSlot(Value name);
int emitHole();
void emit(unsigned top, int op, int dest, Value a, Value b);
void emitJump(int pos, int op, Value a, int to);
void emitCode(unsigned top, int op, int dest, Value a, Value b);
void patchOrEmitMove(int top, int dest, Value a);
Value codeUnary(int top, int op, Value a);
Value codeBinary(int top, int op, Value a, Value b);
void advance();
void consume(int token);
Value expr(int top);
Value subExpr(int top, int limit);
Value suffixedExpr(int top);
Value arrayExpr(int top);
Value mapExpr(int top);
Value funcExpr(int top);
Value callExpr(int top, Value func, Value self);
void parList();
// returns true if last statement was "return".
bool block();
bool insideBlock();
bool lambdaBody();
bool statList();
// returns true if statement was "return".
bool statement();
void ifStat();
void whileStat();
void forStat();
Proto *parseProto(int *outSlot);
Value mapSpecialConsts(Value a);
static Func *makeFunc(GC *gc, Proto *proto, Value *upsTop, int recSlot);
public:
static Func *parseFunc(GC *gc, SymbolTable *syms, Value *upsTop, const char *text);
static Func *parseStatList(GC *gc, SymbolTable *syms, Value *upsTop, const char *text);
static int parseStatList(GC *gc, Proto *proto, SymbolTable *symbols, const char *text);
static Func *parseInEnv(Pepper *pepper, const char *text, bool isFunc);
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#include "core/pch.h"
#ifdef M2_SUPPORT
#include "adjunct/m2/src/engine/index/indexcontainer.h"
OP_STATUS IndexContainer::AddIndex(index_gid_t id, Index* index)
{
OpAutoVector<Index>& indexes = m_index_types[GetType(id)];
const size_t pos = GetPos(id);
// Make sure there is place for new index
for (unsigned i = indexes.GetCount(); i <= pos; i++)
RETURN_IF_ERROR(indexes.Add(0));
// Now insert the index
Index* existing_index = indexes.Get(pos);
if (existing_index == index)
return OpStatus::OK;
if (existing_index)
{
OP_DELETE(existing_index);
OP_ASSERT(0);
}
else
m_count++;
return indexes.Replace(pos, index);
}
void IndexContainer::DeleteIndex(index_gid_t id)
{
Index* existing_index = GetIndex(id);
if (!existing_index)
return;
OP_DELETE(existing_index);
OpStatus::Ignore(m_index_types[GetType(id)].Replace(GetPos(id), 0));
m_count--;
}
Index* IndexContainer::GetRange(UINT32 range_start, UINT32 range_end, INT32& iterator)
{
if (iterator < 0)
iterator = range_start;
while ((unsigned)iterator < range_end)
{
size_t type = GetType(iterator);
size_t pos = GetPos(iterator);
size_t endpos;
Index* index = 0;
OpAutoVector<Index>& indexes = m_index_types[type];
// if end of range is in current type, don't search past end of range
if (GetType(range_end) == type)
endpos = min(GetPos(range_end), indexes.GetCount());
else
endpos = indexes.GetCount();
// Search for index within current type
while (pos < endpos && !index)
{
index = indexes.Get(pos);
pos++;
}
// Update iterator so that it can be used next time
iterator = pos + type * IndexTypes::ID_SIZE;
if (index)
return index;
// Progress to next type if within range
if (type + 1 <= GetType(range_end))
iterator = (type + 1) * IndexTypes::ID_SIZE;
else
break;
}
return 0;
}
#endif // M2_SUPPORT
|
#include <Tanker/Revocation.hpp>
#include <Tanker/BlockGenerator.hpp>
#include <Tanker/Client.hpp>
#include <Tanker/ContactStore.hpp>
#include <Tanker/Crypto/Crypto.hpp>
#include <Tanker/Crypto/Format/Format.hpp>
#include <Tanker/DeviceKeyStore.hpp>
#include <Tanker/Errors/Errc.hpp>
#include <Tanker/Errors/Exception.hpp>
#include <Tanker/Format/Format.hpp>
#include <Tanker/Trustchain/DeviceId.hpp>
#include <Tanker/Trustchain/UserId.hpp>
#include <Tanker/UserKeyStore.hpp>
#include <cppcodec/base64_rfc4648.hpp>
#include <algorithm>
#include <vector>
using Tanker::Trustchain::UserId;
using namespace Tanker::Trustchain::Actions;
using namespace Tanker::Errors;
namespace Tanker
{
namespace Revocation
{
tc::cotask<void> ensureDeviceIsFromUser(Trustchain::DeviceId const& deviceId,
UserId const& selfUserId,
ContactStore const& contactStore)
{
auto const userId = TC_AWAIT(contactStore.findUserIdByDeviceId(deviceId));
if (!userId || userId != selfUserId)
{
throw formatEx(
Errc::InvalidArgument, TFMT("unknown device: {:s}"), deviceId);
}
}
tc::cotask<User> getUserFromUserId(UserId const& selfUserId,
ContactStore const& contactStore)
{
auto const user = TC_AWAIT(contactStore.findUser(selfUserId));
if (!user)
{
throw formatEx(
Errc::InternalError,
"user associated with given deviceId should be a valid user");
}
if (!user->userKey)
throw formatEx(Errc::InternalError, "user should always have a user key");
TC_RETURN(*user);
}
tc::cotask<Crypto::SealedPrivateEncryptionKey> encryptForPreviousUserKey(
UserKeyStore const& userKeyStore,
User const& user,
Crypto::PublicEncryptionKey const& publicEncryptionKey)
{
auto const previousEncryptionPrivateKey =
TC_AWAIT(userKeyStore.getKeyPair(*user.userKey));
auto const encryptedKeyForPreviousUserKey = Crypto::sealEncrypt(
previousEncryptionPrivateKey.privateKey, publicEncryptionKey);
TC_RETURN(encryptedKeyForPreviousUserKey);
}
tc::cotask<DeviceRevocation::v2::SealedKeysForDevices>
encryptPrivateKeyForDevices(
User const& user,
Trustchain::DeviceId const& deviceId,
Crypto::PrivateEncryptionKey const& encryptionPrivateKey)
{
DeviceRevocation::v2::SealedKeysForDevices userKeys;
for (auto const& device : user.devices)
{
if (device.id != deviceId && device.revokedAtBlkIndex == std::nullopt)
{
Crypto::SealedPrivateEncryptionKey sealedEncryptedKey{Crypto::sealEncrypt(
encryptionPrivateKey, device.publicEncryptionKey)};
userKeys.emplace_back(device.id, sealedEncryptedKey);
}
}
TC_RETURN(userKeys);
}
tc::cotask<void> revokeDevice(Trustchain::DeviceId const& deviceId,
UserId const& userId,
ContactStore const& contactStore,
UserKeyStore const& userKeyStore,
BlockGenerator const& blockGenerator,
std::unique_ptr<Client> const& client)
{
TC_AWAIT(ensureDeviceIsFromUser(deviceId, userId, contactStore));
auto const user = TC_AWAIT(getUserFromUserId(userId, contactStore));
auto const newEncryptionKey = Crypto::makeEncryptionKeyPair();
auto const oldPublicEncryptionKey = *user.userKey;
auto const encryptedKeyForPreviousUserKey =
TC_AWAIT(encryptForPreviousUserKey(
userKeyStore, user, newEncryptionKey.publicKey));
auto const userKeys = TC_AWAIT(
encryptPrivateKeyForDevices(user, deviceId, newEncryptionKey.privateKey));
auto const block =
blockGenerator.revokeDevice2(deviceId,
newEncryptionKey.publicKey,
oldPublicEncryptionKey,
encryptedKeyForPreviousUserKey,
userKeys);
TC_AWAIT(client->pushBlock(block));
}
Crypto::PrivateEncryptionKey decryptPrivateKeyForDevice(
std::unique_ptr<DeviceKeyStore> const& deviceKeyStore,
Crypto::SealedPrivateEncryptionKey const& encryptedPrivateEncryptionKey)
{
auto const deviceEncryptionKeyPair = deviceKeyStore->encryptionKeyPair();
auto const decryptedUserPrivateKey =
Crypto::PrivateEncryptionKey{Crypto::sealDecrypt(
encryptedPrivateEncryptionKey, deviceEncryptionKeyPair)};
return decryptedUserPrivateKey;
}
tc::cotask<void> onOtherDeviceRevocation(
DeviceRevocation const& deviceRevocation,
Entry const& entry,
UserId const& selfUserId,
Trustchain::DeviceId const& deviceId,
ContactStore& contactStore,
std::unique_ptr<DeviceKeyStore> const& deviceKeyStore,
UserKeyStore& userKeyStore)
{
TC_AWAIT(contactStore.revokeDevice(deviceRevocation.deviceId(), entry.index));
if (auto const deviceRevocation2 =
deviceRevocation.get_if<DeviceRevocation2>())
{
auto const userId = TC_AWAIT(
contactStore.findUserIdByDeviceId(deviceRevocation2->deviceId()));
TC_AWAIT(contactStore.rotateContactPublicEncryptionKey(
*userId, deviceRevocation2->publicEncryptionKey()));
assert(userId.has_value() &&
"Device revocation has been verified, userId should exists");
// deviceId is null for the first pass where the device has not been created
if (*userId == selfUserId && !deviceId.is_null())
{
auto const sealedUserKeysForDevices =
deviceRevocation2->sealedUserKeysForDevices();
auto const sealedPrivateUserKey =
std::find_if(sealedUserKeysForDevices.begin(),
sealedUserKeysForDevices.end(),
[deviceId](auto const& encryptedUserKey) {
return encryptedUserKey.first == deviceId;
});
assert(
sealedPrivateUserKey != sealedUserKeysForDevices.end() &&
"Device revocation has been revoked deviceId should belong to user");
auto const decryptedUserPrivateKey = decryptPrivateKeyForDevice(
deviceKeyStore, sealedPrivateUserKey->second);
TC_AWAIT(userKeyStore.putPrivateKey(
deviceRevocation2->publicEncryptionKey(), decryptedUserPrivateKey));
}
}
}
}
}
|
#ifndef _GetPlayInfo_H_
#define _GetPlayInfo_H_
#include "BaseProcess.h"
class GetPlayInfo : public BaseProcess {
public:
GetPlayInfo();
~GetPlayInfo();
virtual int doRequest(CDLSocketHandler *clientHandler, InputPacket *inputPacket, Context *pt);
};
#endif
|
/*
** EPITECH PROJECT, 2021
** Untitled (Workspace)
** File description:
** main
*/
#include <unistd.h>
#include <signal.h>
#include "SystemInfos.hpp"
#include "UserInfos.hpp"
#include "Date.hpp"
#include "CoreInfos.hpp"
#include "NetInfos.hpp"
#include "ModuleManage.hpp"
#include "Itop.hpp"
void updateRam(std::atomic<bool> &is_running);
int main(int ac, char **av)
{
if (ac > 2) {
std::cerr << "Too many arguments" << std::endl;
return 84;
}
std::string launch_type = (std::string)av[1];
if (launch_type.compare("-h") == 0) {
std::cout << "[USAGE] ./MyGKrellm monitor_type" << std::endl
<< "\tmonitor_type = text OR graphical" << std::endl;
return 0;
}
if (launch_type.compare("text") != 0 && launch_type.compare("graphical") != 0) {
std::cerr << "Wrong launch mode detected" << std::endl;
return 84;
}
SystemInfos sys;
UserInfos users;
Date date;
CoreInfos core;
NetInfos net;
std::string new_arg = "";
std::atomic<bool> is_running{true};
std::thread update_time(updateTime, std::ref(is_running));
std::thread update_core(updateCore, std::ref(is_running));
std::thread update_ram(updateRam, std::ref(is_running));
update_time.detach();
update_core.detach();
update_ram.detach();
if (launch_type.compare("text") == 0) {
ModuleManage monitor(sys, date, net, core, users);
monitor.run();
is_running = false;
}
if (launch_type.compare("graphical") == 0) {
Itop monitor;
monitor.run();
is_running = false;
}
return 0;
}
|
#include "ChatRoom.h"
#include <algorithm>
#include "Person.h"
Person* ChatRoom::PersonReference::operator->() const { return &people[index]; }
void ChatRoom::broadcast(const string& origin, const string& message) {
for (auto& p : people)
if (p.name != origin) p.receive(origin, message);
}
ChatRoom::PersonReference ChatRoom::join(Person&& p) {
string join_msg = p.name + " joins the chat";
broadcast("room", join_msg);
p.room = this;
people.emplace_back(p);
return {people, static_cast<unsigned int>(people.size() - 1)};
}
void ChatRoom::message(const string& origin, const string& who, const string& message) {
auto target =
find_if(begin(people), end(people), [&](const Person& p) { return p.name == who; });
if (target != end(people)) {
target->receive(origin, message);
}
}
|
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
//Find the longest subarr with given sum
//IDEA: store the first occurence of every prefix sum.
int longestSubarr(int arr[],int n,int x){
unordered_map<int,int> mp;
int preSum=0,res=0;
for(int i=0;i<n;i++){
preSum+=arr[i];
if(preSum==x){
res=max(res,i+1);
}
else if(mp.find(preSum-x)!=mp.end())
res=max(res,i-mp[preSum-x]);
else if(mp.find(preSum-x)==mp.end()){
mp.insert({preSum,i});
}
}
return res;
}
int main(int argc, char const *argv[])
{
int arr[]={8,3,1,5,-6,6,2,2};
int n=sizeof(arr)/sizeof(arr[0]);
int sum=4;
cout<<": "<<longestSubarr(arr,n,sum);
return 0;
}
|
#include "EnumConverter.h"
#include "Keng/GraphicsCommon/FilteringMode.h"
#include "EverydayTools/Exception/CallAndRethrow.h"
namespace keng::graphics::gpu
{
namespace
{
template<typename From, typename To>
struct EnumFlagConverter
{
EnumFlagConverter(From from_) :
from(from_) {
}
bool HasFlag(From flag) const {
if constexpr (std::is_enum_v<From>) {
return (from & flag) != From::None;
} else {
return (from & flag) != 0;
}
}
void ConvertFlag(From fromFlag, To toFlag) {
if (HasFlag(fromFlag)) {
to |= toFlag;
}
}
From from;
To to = static_cast<To>(0);
};
}
DXGI_FORMAT ConvertTextureFormat(const FragmentFormat& from) {
return CallAndRethrowM + [&] {
switch (from) {
case FragmentFormat::R8_UNORM: return DXGI_FORMAT_R8_UNORM;
case FragmentFormat::R8_G8_B8_A8_UNORM: return DXGI_FORMAT_R8G8B8A8_UNORM;
case FragmentFormat::R24_G8_TYPELESS: return DXGI_FORMAT_R24G8_TYPELESS;
case FragmentFormat::D24_UNORM_S8_UINT: return DXGI_FORMAT_D24_UNORM_S8_UINT;
case FragmentFormat::R24_UNORM_X8_TYPELESS: return DXGI_FORMAT_R24_UNORM_X8_TYPELESS;
default: throw std::runtime_error("This texture format is not implemented here");
}
};
}
FragmentFormat ConvertTextureFormat(const DXGI_FORMAT& from) {
return CallAndRethrowM + [&] {
switch (from) {
case DXGI_FORMAT_R8_UNORM: return FragmentFormat::R8_UNORM;
case DXGI_FORMAT_R8G8B8A8_UNORM: return FragmentFormat::R8_G8_B8_A8_UNORM;
case DXGI_FORMAT_R24G8_TYPELESS: return FragmentFormat::R24_G8_TYPELESS;
case DXGI_FORMAT_D24_UNORM_S8_UINT: return FragmentFormat::D24_UNORM_S8_UINT;
case DXGI_FORMAT_R24_UNORM_X8_TYPELESS: return FragmentFormat::R24_UNORM_X8_TYPELESS;
default: throw std::runtime_error("This texture format is not implemented here");
}
};
}
D3D11_TEXTURE_ADDRESS_MODE ConvertAddressMode(const TextureAddressMode& from) {
return CallAndRethrowM + [&] {
switch (from) {
case TextureAddressMode::Border: return D3D11_TEXTURE_ADDRESS_BORDER;
case TextureAddressMode::Clamp: return D3D11_TEXTURE_ADDRESS_CLAMP;
case TextureAddressMode::Mirror: return D3D11_TEXTURE_ADDRESS_MIRROR;
case TextureAddressMode::Wrap: return D3D11_TEXTURE_ADDRESS_WRAP;
default: throw std::runtime_error("This address mode is not implemented here");
}
};
}
TextureAddressMode ConvertAddressMode(const D3D11_TEXTURE_ADDRESS_MODE& from) {
return CallAndRethrowM + [&] {
switch (from) {
case D3D11_TEXTURE_ADDRESS_BORDER: return TextureAddressMode::Border;
case D3D11_TEXTURE_ADDRESS_CLAMP: return TextureAddressMode::Clamp;
case D3D11_TEXTURE_ADDRESS_MIRROR: return TextureAddressMode::Mirror;
case D3D11_TEXTURE_ADDRESS_WRAP: return TextureAddressMode::Wrap;
default: throw std::runtime_error("This address mode is not implemented here");
}
};
}
D3D11_FILTER ConvertFilteringMode(const FilteringMode& from) {
return CallAndRethrowM + [&] {
switch (from) {
case FilteringMode::Nearest: return D3D11_FILTER_MIN_MAG_MIP_POINT;
case FilteringMode::Bilinear: return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
case FilteringMode::Trilinear: return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
case FilteringMode::Anisotropic: return D3D11_FILTER_ANISOTROPIC;
default: throw std::runtime_error("This filtering mode is not implemented here");
}
};
}
PrimitiveTopology ConvertTopology(const D3D_PRIMITIVE_TOPOLOGY& from) {
return CallAndRethrowM + [&] {
switch (from) {
case D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST: return PrimitiveTopology::TriangleList;
case D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP: return PrimitiveTopology::TriangleStrip;
default: throw std::runtime_error("This topology is not implemented here");
}
};
}
D3D_PRIMITIVE_TOPOLOGY ConvertTopology(const PrimitiveTopology& from) {
return CallAndRethrowM + [&] {
switch (from) {
case PrimitiveTopology::LineList: return D3D10_PRIMITIVE_TOPOLOGY_LINELIST;
case PrimitiveTopology::LineStrip: return D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP;
case PrimitiveTopology::TriangleList: return D3D10_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
case PrimitiveTopology::TriangleStrip: return D3D10_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
default: throw std::runtime_error("This topology is not implemented here");
}
};
}
CpuAccessFlags ConvertCpuAccessFlags(UINT flags) {
return CallAndRethrowM + [&] {
EnumFlagConverter<UINT, CpuAccessFlags> c(flags);
c.ConvertFlag(D3D11_CPU_ACCESS_WRITE, CpuAccessFlags::Write);
c.ConvertFlag(D3D11_CPU_ACCESS_READ, CpuAccessFlags::Read);
static_assert((size_t)CpuAccessFlags::Last == 4, "Changed enumeration? Fix here!");
return c.to;
};
}
UINT ConvertCpuAccessFlags(const CpuAccessFlags& flags) {
return CallAndRethrowM + [&] {
EnumFlagConverter<CpuAccessFlags, UINT> c(flags);
c.ConvertFlag(CpuAccessFlags::Write, D3D11_CPU_ACCESS_WRITE);
c.ConvertFlag(CpuAccessFlags::Read, D3D11_CPU_ACCESS_READ);
static_assert((size_t)CpuAccessFlags::Last == 4, "Changed enumeration? Fix here!");
return c.to;
};
}
UINT ConvertDeviceBufferBindFlags(const DeviceBufferBindFlags& flags) {
return CallAndRethrowM + [&] {
EnumFlagConverter<DeviceBufferBindFlags, UINT> c(flags);
c.ConvertFlag(DeviceBufferBindFlags::VertexBuffer, D3D11_BIND_VERTEX_BUFFER);
c.ConvertFlag(DeviceBufferBindFlags::IndexBuffer, D3D11_BIND_INDEX_BUFFER);
c.ConvertFlag(DeviceBufferBindFlags::ConstantBuffer, D3D11_BIND_CONSTANT_BUFFER);
c.ConvertFlag(DeviceBufferBindFlags::ShaderResource, D3D11_BIND_SHADER_RESOURCE);
c.ConvertFlag(DeviceBufferBindFlags::RenderTarget, D3D11_BIND_RENDER_TARGET);
c.ConvertFlag(DeviceBufferBindFlags::DepthStencil, D3D11_BIND_DEPTH_STENCIL);
c.ConvertFlag(DeviceBufferBindFlags::UnorderedAccess, D3D11_BIND_UNORDERED_ACCESS);
static_assert((size_t)DeviceBufferBindFlags::Last == 129, "Changed enumeration? Fix here!");
return c.to;
};
}
DeviceBufferBindFlags ConvertDeviceBufferBindFlags(UINT flags) {
return CallAndRethrowM + [&] {
EnumFlagConverter<UINT, DeviceBufferBindFlags> c(flags);
c.ConvertFlag(D3D11_BIND_VERTEX_BUFFER, DeviceBufferBindFlags::VertexBuffer);
c.ConvertFlag(D3D11_BIND_INDEX_BUFFER, DeviceBufferBindFlags::IndexBuffer);
c.ConvertFlag(D3D11_BIND_CONSTANT_BUFFER, DeviceBufferBindFlags::ConstantBuffer);
c.ConvertFlag(D3D11_BIND_SHADER_RESOURCE, DeviceBufferBindFlags::ShaderResource);
c.ConvertFlag(D3D11_BIND_RENDER_TARGET, DeviceBufferBindFlags::RenderTarget);
c.ConvertFlag(D3D11_BIND_DEPTH_STENCIL, DeviceBufferBindFlags::DepthStencil);
c.ConvertFlag(D3D11_BIND_UNORDERED_ACCESS, DeviceBufferBindFlags::UnorderedAccess);
static_assert((size_t)DeviceBufferBindFlags::Last == 129, "Changed enumeration? Fix here!");
return c.to;
};
}
D3D11_USAGE ConvertDeviceBufferUsage(const DeviceBufferUsage& flags) {
return CallAndRethrowM + [&] {
switch (flags) {
case DeviceBufferUsage::Default: return D3D11_USAGE_DEFAULT;
case DeviceBufferUsage::Immutable: return D3D11_USAGE_IMMUTABLE;
case DeviceBufferUsage::Dynamic: return D3D11_USAGE_DYNAMIC;
case DeviceBufferUsage::Staging: return D3D11_USAGE_STAGING;
}
static_assert((size_t)DeviceBufferUsage::Last == 4, "Changed enumeration? Fix here!");
throw std::runtime_error("Unknown value or not implemented");
};
}
DeviceBufferUsage ConvertDeviceBufferUsage(D3D11_USAGE flags) {
return CallAndRethrowM + [&] {
switch (flags) {
case D3D11_USAGE_DEFAULT: return DeviceBufferUsage::Default;
case D3D11_USAGE_IMMUTABLE: return DeviceBufferUsage::Immutable;
case D3D11_USAGE_DYNAMIC: return DeviceBufferUsage::Dynamic;
case D3D11_USAGE_STAGING: return DeviceBufferUsage::Staging;
}
static_assert((size_t)DeviceBufferUsage::Last == 4, "Changed enumeration? Fix here!");
throw std::runtime_error("Unknown value or not implemented");
};
}
UINT ConvertDepthStencilClearFlags(const DepthStencilClearFlags& flags) {
return CallAndRethrowM + [&] {
EnumFlagConverter<DepthStencilClearFlags, UINT> c(flags);
c.ConvertFlag(DepthStencilClearFlags::ClearDepth, D3D11_CLEAR_DEPTH);
c.ConvertFlag(DepthStencilClearFlags::ClearStencil, D3D11_CLEAR_STENCIL);
static_assert((size_t)DepthStencilClearFlags::Last == 4, "Changed enumeration? Fix here!");
return c.to;
};
}
DepthStencilClearFlags ConvertDepthStencilClearFlags(UINT flags) {
return CallAndRethrowM + [&] {
EnumFlagConverter<UINT, DepthStencilClearFlags> c(flags);
c.ConvertFlag(D3D11_CLEAR_DEPTH, DepthStencilClearFlags::ClearDepth);
c.ConvertFlag(D3D11_CLEAR_STENCIL, DepthStencilClearFlags::ClearStencil);
static_assert((size_t)DepthStencilClearFlags::Last == 4, "Changed enumeration? Fix here!");
return c.to;
};
}
}
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int t, n, a[100], req, count, idx, curEle;
vector<int> ans;
cin >> t;
while (t--)
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
sort(a, a + n);
req = n / 4;
count = 0;
idx = n - 1;
while (ans.size() != 3 && idx != -1)
{
count = 0;
while (count < req && idx != -1)
{
idx--;
count++;
while (idx != -1 && a[idx] == a[idx + 1])
{
idx--;
count++;
}
}
if (count == req)
{
ans.push_back(a[idx + 1]);
}
else
break;
}
if (ans.size() == 3)
{
for (auto idx = ans.rbegin(); idx != ans.rend(); idx++)
cout << *idx << " ";
}
else
cout << -1;
cout << endl;
ans.clear();
}
}
|
#ifndef WEAPONS_H
#define WEAPONS_H
class Weapons {
public:
Weapons(const char*);
string findWeapon(string);
private:
int readInfo(ifstream&);
string weaps[20];
string weaps_hint[20];
int no_weaps;
};
#endif /*WEAPONS_H*/
|
// Created on: 1991-10-10
// Created by: Jean Claude VAUTHIER
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Convert_HyperbolaToBSplineCurve_HeaderFile
#define _Convert_HyperbolaToBSplineCurve_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Convert_ConicToBSplineCurve.hxx>
class gp_Hypr2d;
//! This algorithm converts a hyperbola into a rational B-spline curve.
//! The hyperbola is an Hypr2d from package gp with the
//! parametrization :
//! P (U) =
//! Loc + (MajorRadius * Cosh(U) * Xdir + MinorRadius * Sinh(U) * Ydir)
//! where Loc is the location point of the hyperbola, Xdir and Ydir are
//! the normalized directions of the local cartesian coordinate system
//! of the hyperbola.
//! KeyWords :
//! Convert, Hyperbola, BSplineCurve, 2D .
class Convert_HyperbolaToBSplineCurve : public Convert_ConicToBSplineCurve
{
public:
DEFINE_STANDARD_ALLOC
//! The hyperbola H is limited between the parametric values U1, U2
//! and the equivalent B-spline curve has the same orientation as the
//! hyperbola.
Standard_EXPORT Convert_HyperbolaToBSplineCurve(const gp_Hypr2d& H, const Standard_Real U1, const Standard_Real U2);
protected:
private:
};
#endif // _Convert_HyperbolaToBSplineCurve_HeaderFile
|
#define GLEW_STATIC
#include "Angel.h"
#include <math.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <stdio.h>
using namespace std;
void
bufferGenerator(struct vec4 polygonPoints[],int polyPoints_size, struct vec4 colorPonts[],int colorPoints_size, struct mat4 , struct mat4);
GLuint program;
void create_object ();
vector<vec4> colors , points ;
vector<vec3> normals;
mat4 transformed_matrix, scaling_matrix, translating_matrix;
float theta[3] = {0.0 , 0.0 , 0.0} , scale_by = 1.0 , translate_by;
float theta_delta = 1 , scale_delta = 0.1 , translate_delta = 0.1;
vector<vec4> vertices , faces;
vec4 location_eye = vec4(0.0 , 0.0 , 3.0 , 0.0) , at_model = vec4(0.0 , 0.0 , 0.0 , 0.0) , up_axis = vec4(0.0 , 1.0 , 0.0 , 0.0);
vec4 normalized_value;
void split(string inText , char space);
vec3 vector1 , centroid_value;
mat4 projection_type , viewing_object;
float minX , minY , minZ , maxX , maxY , maxZ;
float min_values[3] , max_values[3];
void find_min(); void find_max();
float range_value , get_max_value;
void get_range();
float eye_x , eye_y , eye_z, light_x , light_y , light_z , light1_x , light1_y , light1_z;
float angle = 90 , height = 0.0 , radius = 3.0, theta_light = 90, light_height = 0.0, light_radius = 2.0;
float angle_delta = 1 , height_delta = 0.5 , radius_delta = 0.1 , theta_light_delta = 3;
int projection_flag = 1;
int shader_flag = 0;
vec4 material_diffuse = vec4(0.24725, 0.1995, 0.0745, 1.0);
vec4 material_ambience = vec4(0.75164, 0.60648, 0.2264, 1.0);
vec4 material_specular = vec4(1.0, 1.0, 1.0, 1.0);
vec4 light1_diffuse = vec4(0.8 , 0.8 , 0.8 , 0.0);
vec4 light1_ambience = vec4(0.2 , 0.2 , 0.2 , 0.0);
vec4 light1_specular = vec4(1.0, 1.0, 1.0 , 0.0);
vec4 light1_pos = vec4(0.0 , 0.0 , 2.0 , 0.0);
vec4 light_diffuse = vec4(0.8 , 0.8 , 0.8 , 0.0);
vec4 light_ambience = vec4(0.2 , 0.2 , 0.2 , 0.0);
vec4 light_specular = vec4(1.0, 1.0, 1.0 , 0.0);
vec4 light0_pos;
vec4 specular0 = vec4(1.0, 1.0, 1.0 , 0.0);
GLfloat shine = 100.0;
vec4 diffuse1 = light_diffuse * material_diffuse;
vec4 ambient1 = light_ambience * material_ambience;
vec4 specular1 = vec4(1.0, 1.0, 1.0 , 0.0);
void quad( int a, int b, int c )
{
points.push_back(vertices[a]);
points.push_back(vertices[b]);
points.push_back(vertices[c]);
vec3 get_n = normalize(cross((vertices[c] - vertices[a]),(vertices[b] - vertices[a])));
normals[a] += get_n;
normals[b] += get_n;
normals[c] += get_n;
}
void construct_cube () {
for(int i=0 ; i<faces.size() ; i++) {
quad( (int)(faces[i].x-1) , (int)(faces[i].y-1), (int)(faces[i].z-1) );
}
vec4 normal_data;
for(int i=0 ; i<faces.size() ; i++) {
normal_data = normalize(normals[(int)(faces[i].x-1)]);
normal_data.x = abs(normal_data.x);
normal_data.y = abs(normal_data.y);
normal_data.z = abs(normal_data.z);
normal_data.w = 0.0;
colors.push_back(normal_data);
vec4 temporay_var = normals[(int)(faces[i].x-1)];
normal_data = normalize(normals[(int)(faces[i].y-1)]);
normal_data.x = abs(normal_data.x);
normal_data.y = abs(normal_data.y);
normal_data.z = abs(normal_data.z);
normal_data.w = 0.0;
colors.push_back(normal_data);
normal_data = normalize(normals[(int)(faces[i].z-1)]);
normal_data.x = abs(normal_data.x);
normal_data.y = abs(normal_data.y);
normal_data.z = abs(normal_data.z);
normal_data.w = 0.0;
colors.push_back(normal_data);
}
}
void
display()
{
glClearColor(0.0 , 0.0 , 0.0 , 0.0);
glClear( GL_COLOR_BUFFER_BIT| GL_DEPTH_BUFFER_BIT ); // clear the window
eye_x = radius * cos(angle*M_PI/180.0);
eye_y = height;
eye_z = radius * sin(angle*M_PI/180.0);
location_eye = vec4(eye_x , eye_y , eye_z , 1.0);
viewing_object = LookAt(location_eye , at_model , up_axis);
light_x = light_radius * cos(theta_light*M_PI/180.0);
light_y = light_height;
light_z = light_radius * sin(theta_light*M_PI/180.0);
light0_pos = vec4(light_x , light_y , light_z , 1.0);
light1_x = 2.0 * cos(angle*M_PI/180.0);
light1_y = height;
light1_z = 2.0 * sin(angle*M_PI/180.0);
light1_pos = vec4(light1_x , light1_y , light1_z , 0.0);
if(projection_flag == 1)
projection_type = Perspective(82.0 , 1.0 , 0.1 , 15);
else if(projection_flag == 2)
projection_type = Ortho(-1.0 , 1.0 , -1.0 , 1.0 , 0.01 , 10.0);
vec4 colors_vec_value[colors.size()];
vec4 points_vec_value[points.size()];
copy(points.begin(),points.end(),points_vec_value);
copy(colors.begin(),colors.end(),colors_vec_value);
bufferGenerator(points_vec_value , sizeof(points_vec_value) , colors_vec_value , sizeof(colors_vec_value), viewing_object , projection_type);
glDrawArrays( GL_TRIANGLES, 0, points.size() );
glutSwapBuffers();
}
void
init( void )
{
for(int i=0 ; i<vertices.size() ; i++)
normals.push_back(vec3(0.0 , 0.0 , 0.0));
construct_cube();
program = InitShader( "vshader21.glsl",
"fshader21.glsl" );
create_object();
}
void create_object () {
find_max();
find_min();
centroid_value = vec3((minX+maxX)/2 , (minY+maxY)/2 , (minZ+maxZ)/2);
translating_matrix = Translate(vec3(-centroid_value.x , -centroid_value.y , -centroid_value.z));
get_range();
scaling_matrix = Scale(vec3((1.0/range_value) , (1.0/range_value) , (1.0/range_value)));
transformed_matrix = scaling_matrix * translating_matrix ;
for(int i=0 ; i<points.size(); i++)
points[i] = transformed_matrix * points[i];
}
void find_min() {
minX = points[0].x;
minY = points[0].y;
minZ = points[0].z;
for(int i=1 ; i<points.size() ; i++) {
if(points[i].x < minX)
minX = points[i].x;
if(points[i].y < minY)
minY = points[i].y;
if(points[i].z < minZ)
minZ = points[i].z;
}
}
void find_max() {
maxX = points[0].x;
maxY = points[0].y;
maxZ = points[0].z;
for(int i=1 ; i<points.size() ; i++) {
if(points[i].x > maxX)
maxX = points[i].x;
if(points[i].y > maxY)
maxY = points[i].y;
if(points[i].z > maxZ)
maxZ = points[i].z;
}
}
void get_range() {
get_max_value = maxX;
range_value = maxX - minX;
if(maxY > get_max_value && maxY > maxZ){
get_max_value = maxY;
range_value = maxY - minY;
}
if(maxZ > get_max_value && maxZ > maxY) {
get_max_value = maxZ;
range_value = maxZ - minZ;
}
}
void keyboard_function( unsigned char key, int x, int y )
{
switch ( key ) {
case 'q': exit( EXIT_SUCCESS ); break;
case 'x': angle += angle_delta;
if(angle > 360.0)
angle = 0.0;
break;
case 's': angle -= angle_delta;
if(angle < -360.0)
angle = 0.0;
break;
case 'y': height += height_delta;
break;
case 'h': height -= height_delta;
break;
case 'z': radius += radius_delta;
break;
case 'a': radius -= radius_delta;
if(radius < 1.0)
radius = 1.0;
break;
case 'r': angle = 90.0 ; height = 0.0 ; radius = 3.0; projection_flag = 1;
break;
case 'l': theta_light += theta_light_delta;
if(theta_light > 360.0)
theta_light = 0.0;
break;
case 'o': theta_light -= theta_light_delta;
if(theta_light < -360.0)
theta_light = 0.0;
break;
case 'k': light_height += height_delta;
break;
case 'i': light_height -= height_delta;
break;
case 'j': light_radius += radius_delta;
if(light_radius < 1.0)
light_radius = 1.0;
break;
case 'u': light_radius -= radius_delta;
if(light_radius < 1.0)
light_radius = 1.0;
break;
}
glutPostRedisplay();
}
void
bufferGenerator(struct vec4 polygonPoints[],int polyPoints_size, struct vec4 colorPonts[],int colorPoints_size, struct mat4 viewing_object , struct mat4 projection_type) {
GLuint buffer_name_polygon;
glGenBuffers( 1, &buffer_name_polygon );
glBindBuffer( GL_ARRAY_BUFFER, buffer_name_polygon );
glBufferData( GL_ARRAY_BUFFER, polyPoints_size, polygonPoints, GL_STATIC_DRAW );
GLuint loc = glGetAttribLocation( program, "vPosition" );
glEnableVertexAttribArray( loc );
glVertexAttribPointer( loc, 4, GL_FLOAT, GL_FALSE, 0,
BUFFER_OFFSET(0) );
GLuint buffer_name_color;
glGenBuffers( 1, &buffer_name_color );
glBindBuffer( GL_ARRAY_BUFFER, buffer_name_color );
glBufferData( GL_ARRAY_BUFFER, colorPoints_size, colorPonts, GL_STATIC_DRAW );
GLuint loc_color = glGetAttribLocation( program, "vColor" );
glEnableVertexAttribArray( loc_color );
glVertexAttribPointer( loc_color, 4, GL_FLOAT, GL_FALSE, 0,
BUFFER_OFFSET(0) );
GLint uniform_m_transform_vo = glGetUniformLocation(program, "viewing_object");
glUniformMatrix4fv(uniform_m_transform_vo , 1 , GL_TRUE , &viewing_object[0][0]);
GLint uniform_m_transform_pt = glGetUniformLocation(program, "projection_type");
glUniformMatrix4fv(uniform_m_transform_pt , 1 , GL_TRUE , &projection_type[0][0]);
vec4 diffuse0 = light_diffuse * material_diffuse;
vec4 ambient0 = light_ambience * material_ambience;
GLint uniform_ambient = glGetUniformLocation(program, "AmbientProduct");
glUniform4f(uniform_ambient , ambient0.x , ambient0.y , ambient0.z , ambient0.w);
GLint uniform_diffuse = glGetUniformLocation(program, "DiffuseProduct");
glUniform4f(uniform_diffuse , diffuse0.x , diffuse0.y , diffuse0.z , diffuse0.w);
GLint uniform_spec = glGetUniformLocation(program, "SpecularProduct");
glUniform4f(uniform_spec , specular0.x , specular0.y , specular0.z , specular0.w);
light1_pos = viewing_object * light1_pos;
vec4 diffuse1 = light1_diffuse * material_diffuse;
vec4 ambient1 = light1_ambience * material_ambience;
GLint uniform_ambient1 = glGetUniformLocation(program, "AmbientProduct1");
glUniform4f(uniform_ambient1 , ambient1.x , ambient1.y , ambient1.z , ambient1.w);
GLint uniform_diffuse1 = glGetUniformLocation(program, "DiffuseProduct1");
glUniform4f(uniform_diffuse1 , diffuse1.x , diffuse1.y , diffuse1.z , diffuse1.w);
GLint uniform_spec1 = glGetUniformLocation(program, "SpecularProduct1");
glUniform4f(uniform_spec1 , specular1.x , specular1.y , specular1.z , specular1.w);
GLint uniform_shine = glGetUniformLocation(program, "Shininess");
glUniform1f(uniform_shine , shine);
vec4 light_pos = light0_pos;
GLint uniform_light = glGetUniformLocation(program, "LightPosition");
glUniform4f(uniform_light , light_pos.x , light_pos.y , light_pos.z , light_pos.w);
GLint uniform_light1 = glGetUniformLocation(program, "Light1Position");
glUniform4f(uniform_light1 , light1_pos.x , light1_pos.y , light1_pos.z , light1_pos.w);
GLint uniform_eye_loc = glGetUniformLocation(program, "EyePosition");
glUniform3f(uniform_eye_loc , location_eye.x , location_eye.y , location_eye.z);
GLint uniform_shader_flag = glGetUniformLocation(program, "shader_flag");
glUniform1i(uniform_shader_flag , shader_flag);
}
void process_menu_events(int option) {
switch (option) {
case 1: projection_flag = 1;
break;
case 2: projection_flag = 2;
break;
case 3: shader_flag = 0;
break;
case 4: shader_flag = 1;
break;
case 5: light_diffuse = vec4(0.8 , 0.8 , 0.8 , 0.0);
light_ambience = vec4(0.2 , 0.2 , 0.2 , 0.0);
light_specular = vec4(1.0, 1.0, 1.0 , 0.0);
break;
case 6: light_diffuse = vec4(1.0 , 0.4 , 0.6 , 0.0);
light_ambience = vec4(0.2 , 0.2 , 0.2 , 0.0);
light_specular = vec4(1.0, 1.0, 1.0 , 0.0);
break;
case 7: material_diffuse = vec4(0.8, 0.8, 0.8 , 0.0);
material_ambience = vec4(0.5, 0.5, 0.5 , 0.0);
material_specular = vec4(1.0, 1.0, 1.0 , 0.0);
break;
case 8: material_diffuse = vec4(0.24725, 0.1995, 0.0745, 1.0);
material_ambience = vec4(0.75164, 0.60648, 0.2264, 1.0);
material_specular = vec4(1.0, 1.0, 1.0, 1.0);
break;
case 9: material_diffuse = vec4(0.0, 1.0, 1.0 , 0.0);
material_ambience = vec4(0.0, 0.5, 0.5 , 0.0);
material_specular = vec4(1.0, 1.0, 1.0 , 0.0);
break;
}
glutPostRedisplay();
}
void getInput(string input_file) {
string inText;
ifstream reader(input_file.c_str());
if(!reader) {
cout<<"\n Error opening the file";
}
else {
while(!reader.eof()) {
getline(reader,inText);
if(inText[0] == 'v') {
split(inText,' ');
vertices.push_back(vector1);
}
else if(inText[0] == 'f') {
split(inText,' ');
faces.push_back(vector1);
}
}
}
}
void split(string inText , char space)
{
int position = inText.find(space,2);
int i=2;
int iterating_pointer = 0;
float temp[3];
while(iterating_pointer<2)
{
temp[iterating_pointer] = ::atof((inText.substr(i, position)).c_str());
i=++position;
position=inText.find(space,i);
iterating_pointer++;
}
temp[2] = ::atof((inText.substr(i, inText.size())).c_str());
vector1 = vec3(temp[0] , temp[1] , temp[2]);
}
int window_id;
int
main( int argc, char **argv )
{
printf("\n Once the program is up and running : ");
printf("\n The default value is set at Perspective Gouroud and Gold material with white light");
printf("\n To change - Right click of mouse button will show you a drop down menu containing \n Projection Type \n Shading Type \n Light Type \n Material Type");
printf("\n On selecting any one from the menu you will be able to perform the following : ");
printf("\n key press 'x' : Increases the angle to rotate around the object");
printf("\n key press 's' : Decreases the angle to rotate around the object");
printf("\n key press 'y' : Increases the height of the camera");
printf("\n key press 'h' : Decreases the height of the camera");
printf("\n key press 'z' : The camera goes away from the object");
printf("\n key press 'a' : The camera goes near to the object");
printf("\n key press 'l' : Increases the angle to rotate around the object");
printf("\n key press 'o' : Decreases the angle to rotate around the object");
printf("\n key press 'k' : Increases the height of the light");
printf("\n key press 'i' : Decreases the height of the light");
printf("\n key press 'j' : The light goes away from the object");
printf("\n key press 'u' : The light goes near to the object");
printf("\n key press 'r' : Resets to default values");
printf("\n key press 'q' : Quits from output window");
if(argv[1] == NULL)
getInput("bunny.smf");
else
getInput(argv[1]);
glutInit( &argc, argv );
#ifdef __APPLE__
glutInitDisplayMode(GLUT_3_2_CORE_PROFILE | GLUT_RGBA );
#else
glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
#endif
glutInitWindowPosition(100,100);
glutInitWindowSize( 500, 500 );
window_id = glutCreateWindow( "assignment 5" );
#ifndef __APPLE__
GLenum err = glewInit();
if (GLEW_OK != err)
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
#endif
init();
glutKeyboardFunc( keyboard_function );
int window_menu , projection_menu , shading_menu , light_menu , material_menu;
projection_menu = glutCreateMenu(process_menu_events);
glutAddMenuEntry("Perspective",1);
glutAddMenuEntry("Parallel",2);
shading_menu = glutCreateMenu(process_menu_events);
glutAddMenuEntry("Gouraud",3);
glutAddMenuEntry("Phong",4);
light_menu = glutCreateMenu(process_menu_events);
glutAddMenuEntry("White light",5);
glutAddMenuEntry("Colored light",6);
material_menu = glutCreateMenu(process_menu_events);
glutAddMenuEntry("White Shiny",7);
glutAddMenuEntry("Gold",8);
glutAddMenuEntry("Cyan",9);
glutCreateMenu(process_menu_events);
glutAddSubMenu("Projection Type", projection_menu);
glutAddSubMenu("Shading", shading_menu);
glutAddSubMenu("Light", light_menu);
glutAddSubMenu("Material", material_menu);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutDisplayFunc(display);
glEnable(GL_DEPTH_TEST);
glutMainLoop();
return 0;
}
|
#pragma once
#include "../Config.hpp"
#include "../SecureWiper.hpp"
#include "../Array.hpp"
namespace accel::Crypto {
class RC4_ALG {
public:
static constexpr size_t MinKeySizeValue = 1;
static constexpr size_t MaxKeySizeValue = 256;
private:
SecureWiper<Array<uint8_t, 256>> _InitSBoxWiper;
SecureWiper<Array<uint8_t, 256>> _SBoxWiper;
Array<uint8_t, 256> _InitSBox;
mutable Array<uint8_t, 256> _SBox;
ACCEL_FORCEINLINE
void _KeyExpansion() noexcept {
for (size_t i = 0; i < 256; ++i)
_SBox[i] = static_cast<uint8_t>(i);
uint8_t j = 0;
for (size_t i = 0; i < 256; ++i) {
j += _InitSBox[i] + _SBox[i];
std::swap(_SBox[i], _SBox[j]);
}
}
ACCEL_FORCEINLINE
void _EncDecProcess(uint8_t* PtrToText, size_t TextSize) const noexcept {
uint8_t i = 0, j = 0;
for (size_t k = 0; k < TextSize; ++k) {
i += 1;
j += _SBox[i];
uint8_t temp = _SBox[i];
_SBox[i] = _SBox[j];
_SBox[j] = temp;
PtrToText[k] ^= _SBox[(_SBox[i] + _SBox[j]) % 256];
}
}
public:
RC4_ALG() noexcept :
_InitSBoxWiper(_InitSBox),
_SBoxWiper(_SBox) {}
constexpr size_t MinKeySize() const noexcept {
return MinKeySizeValue;
}
constexpr size_t MaxKeySize() const noexcept {
return MaxKeySizeValue;
}
[[nodiscard]]
bool SetKey(const void* PtrToUserKey, size_t UserKeySize) noexcept {
if (MinKeySizeValue <= UserKeySize && UserKeySize <= MaxKeySizeValue) {
auto BytesOfUserKey = reinterpret_cast<const uint8_t*>(PtrToUserKey);
for (size_t i = 0; i < 256; ++i)
_InitSBox[i] = BytesOfUserKey[i % UserKeySize];
_KeyExpansion();
return true;
} else {
return false;
}
}
size_t EncryptStream(void* PtrToPlaintext, size_t TextSize) const noexcept {
_EncDecProcess(reinterpret_cast<uint8_t*>(PtrToPlaintext), TextSize);
return TextSize;
}
size_t DecryptStream(void* PtrToCiphertext, size_t TextSize) const noexcept {
_EncDecProcess(reinterpret_cast<uint8_t*>(PtrToCiphertext), TextSize);
return TextSize;
}
void Reset() noexcept {
_KeyExpansion();
}
void ClearKey() noexcept {
_InitSBox.SecureZero();
_SBox.SecureZero();
}
};
}
|
class Solution {
public:
int maxSubArray(vector<int>& nums) {
if(nums==NULL) return -INT_MAX;
int max=nums[0],curr=nums[0];
for(int i=1;i<nums.size();i++){
if(curr>0){
curr+=nums[i];
}else{
curr=nums[i];
}
max= max(max, curr);
}
return max;
}
};
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <memory.h>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
#include <complex>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define N 555
char s[N][N];
int l[N][N], u[N][N], r[N][N], d[N][N];
int pr[555], prn = 0;
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
for (int i = 2; i < 500; ++i) {
int j = 0;
for (; j < prn; ++j)
if (i % pr[j] == 0)
break;
if (j == prn) {
pr[prn++] = i;
}
}
int T;
scanf("%d\n", &T);
while (T--) {
int n, m, ans = 0;
scanf("%d%d\n", &n, &m);
for (int i = 0; i < n; ++i) gets(s[i]);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (s[i][j] == '^') {
if (i == 0) u[i][j] = 0;else u[i][j] = u[i - 1][j] + 1;
if (j == 0) l[i][j] = 0;else l[i][j] = l[i][j - 1] + 1;
} else
u[i][j] = l[i][j] = -1;
}
}
for (int i = n - 1; i >= 0; --i) {
for (int j = m - 1; j >= 0; --j) {
if (s[i][j] == '^') {
if (i == n - 1) d[i][j] = 0;else d[i][j] = d[i + 1][j] + 1;
if (j == m - 1) r[i][j] = 0;else r[i][j] = r[i][j + 1] + 1;
int t = min(min(r[i][j], l[i][j]), min(d[i][j], u[i][j]));
ans += lower_bound(pr, pr + prn, t + 1) - pr;
} else
d[i][j] = r[i][j] = -1;
}
}
cout << ans << endl;
}
return 0;
}
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
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.
====================================================================*/
#pragma once
// Local includes
#include "IEngineComponent.h"
#include "IVoiceInput.h"
// STL includes
#include <deque>
namespace DX
{
class DeviceResources;
class StepTimer;
}
namespace HoloIntervention
{
namespace Rendering
{
class NotificationRenderer;
}
namespace System
{
class NotificationSystem : public Input::IVoiceInput, public IEngineComponent
{
enum AnimationState
{
SHOWING,
FADING_IN,
FADING_OUT,
HIDDEN
};
struct MessageEntry
{
MessageEntry() {};
MessageEntry(uint64 id, const std::wstring& msg, double duration)
: messageId(id)
, message(msg)
, messageDuration(duration)
{}
uint64 messageId = 0;
std::wstring message = L"";
double messageDuration = 0.0;
};
typedef std::deque<MessageEntry> MessageQueue;
public:
NotificationSystem(Rendering::NotificationRenderer& notificationRenderer);
~NotificationSystem();
// Add a message to the queue to render
uint64 QueueMessage(const std::string& message, double duration = DEFAULT_NOTIFICATION_DURATION_SEC);
uint64 QueueMessage(const std::wstring& message, double duration = DEFAULT_NOTIFICATION_DURATION_SEC);
uint64 QueueMessage(Platform::String^ message, double duration = DEFAULT_NOTIFICATION_DURATION_SEC);
void RemoveMessage(uint64 messageId);
void Initialize(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose);
void Update(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose, const DX::StepTimer& timer);
// Accessors
bool IsShowingNotification() const;
Windows::Foundation::Numerics::float3 GetPosition() const;
Windows::Foundation::Numerics::float3 GetVelocity() const;
// Override the current lerp and force the position
void SetPose(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose);
// IVoiceInput functions
virtual void RegisterVoiceCallbacks(HoloIntervention::Input::VoiceInputCallbackMap& callbackMap);
protected:
void UpdateHologramPosition(Windows::UI::Input::Spatial::SpatialPointerPose^ pointerPose, const DX::StepTimer& timer);
void CalculateWorldMatrix();
void CalculateAlpha(const DX::StepTimer& timer);
void CalculateVelocity(float oneOverDeltaTime);
void GrabNextMessage();
bool IsFading() const;
protected:
// Cached pointer to device resources.
Rendering::NotificationRenderer& m_notificationRenderer;
float m_fadeTime = 0.f;
AnimationState m_animationState = HIDDEN;
Windows::Foundation::Numerics::float3 m_position = { 0.f, 0.f, -2.f };
Windows::Foundation::Numerics::float3 m_lastPosition = { 0.f, 0.f, -2.f };
Windows::Foundation::Numerics::float3 m_velocity = { 0.f, 0.f, 0.f };
Windows::Foundation::Numerics::float4x4 m_worldMatrix;
Windows::Foundation::Numerics::float4 m_hologramColorFadeMultiplier;
MessageQueue m_messages;
std::mutex m_messageQueueMutex;
std::atomic_bool m_hideNotifications;
MessageEntry m_currentMessage;
double m_messageTimeElapsedSec = 0.0f;
uint64 m_nextMessageId = 0;
// Constants relating to behavior of the notification system
static const Windows::Foundation::Numerics::float4 HIDDEN_ALPHA_VALUE;
static const Windows::Foundation::Numerics::float4 SHOWING_ALPHA_VALUE;
static const Windows::Foundation::Numerics::float3 NOTIFICATION_SCREEN_OFFSET;
static const double DEFAULT_NOTIFICATION_DURATION_SEC;
static const double MAXIMUM_REQUESTED_DURATION_SEC;
static const float LERP_RATE;
static const float MAX_FADE_TIME;
static const float NOTIFICATION_DISTANCE_OFFSET;
static const uint32 BLUR_TARGET_WIDTH_PIXEL;
static const uint32 OFFSCREEN_RENDER_TARGET_WIDTH_PIXEL;
};
}
}
|
#ifndef _ROS_sub8_msgs_PathPoint_h
#define _ROS_sub8_msgs_PathPoint_h
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include "ros/msg.h"
#include "geometry_msgs/Point.h"
namespace sub8_msgs
{
class PathPoint : public ros::Msg
{
public:
geometry_msgs::Point position;
float yaw;
PathPoint():
position(),
yaw(0)
{
}
virtual int serialize(unsigned char *outbuffer) const
{
int offset = 0;
offset += this->position.serialize(outbuffer + offset);
offset += serializeAvrFloat64(outbuffer + offset, this->yaw);
return offset;
}
virtual int deserialize(unsigned char *inbuffer)
{
int offset = 0;
offset += this->position.deserialize(inbuffer + offset);
offset += deserializeAvrFloat64(inbuffer + offset, &(this->yaw));
return offset;
}
const char * getType(){ return "sub8_msgs/PathPoint"; };
const char * getMD5(){ return "4cc04ac3ba6c1f0f2caa721fb8f71842"; };
};
}
#endif
|
#ifndef LIGHT_SOURCE_HPP
#define LIGHT_SOURCE_HPP
#include "../include/point.hpp"
#include "../include/color.hpp"
#include <string>
#include <ostream>
class light_source {
public:
light_source();
light_source(std::string const&,math3d::point const&, color const&, color const&);
light_source(const light_source& orig);
virtual~ light_source();
void print_on(std::ostream& str) const;
math3d::point get_pos()const;
color get_la()const;
color get_ld()const;
private:
std::string name_;
math3d::point position_;
color la_;
color ld_;
};
std::ostream& operator<<(std::ostream& str, light_source const& ls);
#endif /* LIGHT_SOURCE_HPP */
|
#include "PageSyncMaster.h"
|
vector<int> solution(int N, vector<int> &P, vector<int> &Q) {
// write your code in C++14 (g++ 6.2.0)
vector<bool> sieve(N+1, 1); // initialize as all 1
vector<int> rec(N+1, 0); // initialize as all 2
sieve[0] = 0; // if prime -> 1
sieve[1] = 0;
int i = 2;
while(i*i <= N) {
if (sieve[i]==1){
int k = i*i;
while (k <= N){
sieve[k]=0;
//if (sieve[k/i]==1) rec[k]++;
//if (k==18) cout << "i = " << i << endl;
k+=i;
}
}
i++;
}
i = 2;
while(i*i <= N) {
if (sieve[i]==1){
int k = i*i;
while (k <= N){
sieve[k]=0;
if (sieve[k/i]==1) rec[k]++;
//if (k==18) cout << "i = " << i << endl;
k+=i;
}
}
i++;
}
//cout << "zz" << endl;
vector<int> acc(N+1, 0);
for (int i = 1; i<N+1 ;i++){
if (rec[i]==1) acc[i]=acc[i-1]+1;
else acc[i]=acc[i-1];
//cout << i << "??" << acc[i] << endl;
}
//cout << "zzz" << endl;
vector<int> ret(Q.size(), 0);
for (size_t i = 0; i<Q.size(); i++){
//cout << Q[i] << ";" << P[i] << endl;
ret[i] = acc[Q[i]]-acc[P[i]-1];
}
//cout << "zzzz" << endl;
return ret;
}
|
#include<iostream>
#include<cstring>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define FORD(i,j) for(i=j;i>=0;i--)
#define MAX(a,b) (a)>(b)?(a):(b)
#define MIN(a,b) (a)<(b)?(a):(b)
using namespace std;
int m,n;
int table[10201][101];
int f[101],p[101];
int take(int value,int index)
{
if(value>m&&m<=1800)return -1000;
if(value>m+200)return -1000;
if(index==n)
{
if(value>m)
{
if(value>2000) return 0;
else return -1000;
}
return 0;
}
if(table[value][index]!=-1)return table[value][index];
return table[value][index]=MAX(f[index]+take(value+p[index],index+1),take(value,index+1));
}
int main()
{
int i,temp1,temp2,ans;
while(cin>>m)
{
memset(table,-1,sizeof table);
cin>>n;
FOR0(i,n)
{
scanf("%d%d",&p[i],&f[i]);
}
ans=take(0,0);
printf("%d\n",ans);
}
}
|
#include "MakeCustomIncludes.h"
int main()
{
return MakeCustomIncludes();
}
|
#include <iostream>
// knapsack
#include "knapsackP.h"
#include "knapsack.h"
// TSP
#include "route.h"
#include "tsp.h"
// real function
#include "real_function.h"
#include "real_vector.h"
#include "island_EA.hpp"
template <typename problem_class, typename solution_class>
void solve_problem(size_t problem_size){
// Create a random problem
problem_class problem(100);
problem.disp();
// Create a solver for the problem
island_EA<problem_class,solution_class> solver(problem);
solver.run();
// Print final statistics
int idx = 1;
for (auto iter = solver.best_solutions_begin(); iter != solver.best_solutions_end(); ++iter) {
std::cout << "Solution " << idx << ": " << std::endl;
(*iter)->s.disp(problem);
std::cout << "Objetive function " << idx << ": " << (*iter)->fx << std::endl;
idx++;
}
};
int main() {
const size_t problem_size = 20;
solve_problem<knapsack_p,knapsack>(problem_size);
solve_problem<real_function,real_vector>(problem_size);
solve_problem<tsp,route>(problem_size);
return 0;
}
|
#include <iostream>
#include "CCSprite.h"
using namespace std;
int main()
{
CCSprite a(1), b(2), c(3);
for (int i = 100; i < 106; i++) {
new CCSprite(i);
}
CCSprite::traverseCCSprite();
return 0;
}
|
//
// Created by 钟奇龙 on 2019-05-12.
//
#include <vector>
#include <iostream>
using namespace std;
void setNumIntoSupport(vector<int> &support,int num,int k){
vector<int> temp(32,0);
int index = 0;
while(num){
temp[index++] = num%k;
num/=k;
}
for(int i=0; i<support.size(); ++i){
support[i] = (support[i] + temp[i])%k;
}
}
int getOnceNum(vector<int> arr,int k){
vector<int> support(32,0);
for(int i=0; i<arr.size(); ++i){
setNumIntoSupport(support,arr[i],k);
}
//将support数组转为10进制数
int res = 0;
for(int i=support.size()-1; i>=0; --i){
res = res * k + support[i];
}
return res;
}
int main(){
vector<int> arr = {1,1,1,4,2,2,4,3,3,3,4,2,5};
cout<<getOnceNum(arr,3)<<endl;
return 0;
}
|
#include <QCoreApplication>
#include <iostream>
class Base
{
public:
virtual const char* getName() { return "Base"; }
};
class Derived: public Base
{
public:
virtual const char* getName() { return "Derived"; }
};
int main()
{
Derived derived;
Base &rBase = derived;
std::cout << "rBase is a " << rBase.getName() << '\n';
}
//int main(int argc, char *argv[])
//{
// QCoreApplication a(argc, argv);
// return a.exec();
//}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.