text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
#include "modules/accessibility/acctree/AccessibilityTreeNode.h"
#include "modules/accessibility/AccessibleDocument.h"
#include "modules/accessibility/acctree/AccessibilityTreeLabelNode.h"
AccessibilityTreeNode::AccessibilityTreeNode(AccessibilityTreeNode* parent, AccessibleDocument* document)
: m_parent(parent)
, m_document(m_parent ? m_parent->GetDocument() : document)
, m_label(NULL)
{
OP_ASSERT(m_document);
if (m_parent)
m_parent->AddChild(this);
}
AccessibilityTreeNode::~AccessibilityTreeNode()
{
DeleteAllChildren();
if (m_parent)
m_parent->RemoveChild(this);
if (m_label)
m_label->RemoveControl(this);
}
void AccessibilityTreeNode::SetBounds(const OpRect& bounds)
{
m_bounds = bounds;
}
OP_STATUS AccessibilityTreeNode::GetBounds(OpRect& bounds) const
{
if (!m_bounds.IsEmpty())
bounds = m_bounds;
else if (m_children.GetCount())
{
OpRect sub_bounds;
int i, count = m_children.GetCount();
for (i=0; i<count; i++)
{
if (OpStatus::IsSuccess(m_children.Get(i)->GetBounds(sub_bounds)))
{
bounds.UnionWith(sub_bounds);
}
}
}
return OpStatus::OK;
}
BOOL AccessibilityTreeNode::HitTest(const OpPoint& pt) const
{
if (m_bounds.Contains(pt))
return TRUE;
else
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
if (m_children.Get(i)->HitTest(pt))
return TRUE;
}
}
return FALSE;
}
BOOL AccessibilityTreeNode::Focused() const
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
if (m_children.Get(i)->Focused())
return TRUE;
}
return FALSE;
}
BOOL AccessibilityTreeNode::ClickSelf()
{
return FALSE;
}
OP_STATUS AccessibilityTreeNode::GetText(OpString& str) const
{
str.Empty();
return OpStatus::OK;
}
BOOL AccessibilityTreeNode::Compare(const AccessibilityTreeNode* node) const
{
if (node == this)
return true;
OpRect my_bounds, other_bounds;
if (NodeType() == node->NodeType())
{
GetBounds(my_bounds);
if (!my_bounds.IsEmpty())
{
node->GetBounds(other_bounds);
if (my_bounds.Equals(other_bounds))
{
OpString my_text, other_text;
GetText(my_text);
if (my_text.Length())
{
node->GetText(other_text);
if (my_text == other_text)
{
return TRUE;
}
}
}
}
}
// OK, bound/text comparison failed. Try to see if this might be a form container.
if (m_children.GetCount() == 1)
{
if (node->GetChildrenCount() == 1)
{
if (m_children.Get(0)->Compare(node->GetChild(0)))
{
return TRUE;
}
}
}
return FALSE;
}
void AccessibilityTreeNode::Merge(AccessibilityTreeNode* node)
{
int i = 0, j = 0;
AccessibilityTreeNode* my_child = m_children.Get(i);
AccessibilityTreeNode* your_child = node->m_children.Get(j);
while (my_child || your_child)
{
if (my_child && !your_child)
{
OP_DELETE(my_child);
my_child = m_children.Get(i);
}
else if (your_child && !my_child)
{
your_child->Reparent(this);
your_child = node->m_children.Get(j);
}
else
{
if (my_child->Compare(your_child))
{
my_child->Merge(your_child);
i++;
j++;
}
else
{
int j2 = j+1;
your_child = node->m_children.Get(j2);
while (your_child)
{
if (my_child->Compare(your_child))
{
int diff = j2 - j;
my_child->Merge(your_child);
for (int k = 0; k < diff; k++)
node->m_children.Remove(j)->Reparent(this, i + k);
j++;
i+= 1+diff;
break;
}
j2++;
your_child = node->m_children.Get(j2);
}
if (!your_child)
{
OP_DELETE(my_child);
}
}
my_child = m_children.Get(i);
your_child = node->m_children.Get(j);
}
}
OpRect bounds;
node->GetBounds(bounds);
if (!m_bounds.Equals(bounds))
{
BOOL moved = (bounds.x != m_bounds.x) || (bounds.y != m_bounds.y);
BOOL resized = (bounds.width != m_bounds.width) || (bounds.height != m_bounds.height);
SetBounds(bounds);
BoundsChanged(moved, resized);
}
}
void AccessibilityTreeNode::ParsingDone()
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
m_children.Get(i)->ParsingDone();
}
}
void AccessibilityTreeNode::OnFocus() const
{
OpAccessibleItem* ext = GetAccessibleObject();
if (ext)
{
ext->AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateFocused));
}
}
void AccessibilityTreeNode::OnBlur() const
{
OpAccessibleItem* ext = GetAccessibleObject();
if (ext)
{
ext->AccessibilitySendEvent(Accessibility::Event(Accessibility::kAccessibilityStateFocused));
}
}
void AccessibilityTreeNode::OnReorder() const
{
}
void AccessibilityTreeNode::UnreferenceHTMLElement(const HTML_Element* helm)
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
m_children.Get(i)->UnreferenceHTMLElement(helm);
}
}
void AccessibilityTreeNode::UnreferenceWidget(const OpWidget* widget)
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
m_children.Get(i)->UnreferenceWidget(widget);
}
}
AccessibilityTreeNode* AccessibilityTreeNode::FindElement(HTML_Element* helm)
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
AccessibilityTreeNode* elem = m_children.Get(i)->FindElement(helm);
if (elem)
return elem;
}
return NULL;
}
AccessibilityTreeNode::TreeNodeType AccessibilityTreeNode::NodeType() const
{
return TREE_NODE_TYPE_UNKNOWN;
}
void AccessibilityTreeNode::BoundsChanged(BOOL moved, BOOL resized)
{
}
int AccessibilityTreeNode::GetChildrenCount() const
{
return m_children.GetCount();
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetChild(int i) const
{
return m_children.Get(i);
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetChildAt(const OpPoint& pt) const
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
AccessibilityTreeNode* child = m_children.Get(i);
if (child->HitTest(pt))
return child;
}
return NULL;
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetFocusedChild() const
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
AccessibilityTreeNode* child = m_children.Get(i);
if (child->Focused())
return child;
}
return NULL;
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetNextSibling() const
{
if (m_parent)
return m_parent->GetChildAfter(this);
else
return NULL;
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetPrevSibling() const
{
if (m_parent)
return m_parent->GetChildBefore(this);
else
return NULL;
}
void AccessibilityTreeNode::AddChild(AccessibilityTreeNode* child, int index)
{
if (index < 0 || index > int(m_children.GetCount()))
m_children.Add(child);
else
m_children.Insert(index, child);
OnReorder();
}
void AccessibilityTreeNode::RemoveChild(AccessibilityTreeNode* child)
{
m_children.RemoveByItem(child);
OnReorder();
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetParent() const
{
return m_parent;
}
void AccessibilityTreeNode::Reparent(AccessibilityTreeNode* parent, int index)
{
if (parent != m_parent)
{
if (m_parent)
m_parent->RemoveChild(this);
m_parent = parent;
if (m_parent)
m_parent->AddChild(this, index);
}
}
AccessibleDocument* AccessibilityTreeNode::GetDocument() const
{
return m_document;
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetChildBefore(const AccessibilityTreeNode* node) const
{
int i, count = m_children.GetCount();
AccessibilityTreeNode* prev_node = NULL;
for (i = 0; i < count; i++)
{
AccessibilityTreeNode* child = m_children.Get(i);
if (child == node)
return prev_node;
prev_node = child;
}
return NULL;
}
const AccessibilityTreeNode* AccessibilityTreeNode::GetChildAfter(const AccessibilityTreeNode* node) const
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
if (node == m_children.Get(i))
{
return m_children.Get(i + 1);
}
}
return NULL;
}
const AccessibilityTreeNode* AccessibilityTreeNode::FindItemByID(const uni_char* name) const
{
int i, count = m_children.GetCount();
const AccessibilityTreeNode* node;
for (i = 0; i < count; i++)
{
node = m_children.Get(i)->FindItemByID(name);
if (node)
{
return node;
}
}
return NULL;
}
void AccessibilityTreeNode::SetLabel(AccessibilityTreeLabelNode* label) const
{
if (m_label)
m_label->RemoveControl(this);
m_label = label;
}
void AccessibilityTreeNode::DeleteAllChildren()
{
UINT c;
while ((c = m_children.GetCount()) > 0)
OP_DELETE(m_children.Get(c - 1));
}
OP_STATUS AccessibilityTreeNode::GetLinks(OpVector<AccessibilityTreeURLNode>& links)
{
int i, count = m_children.GetCount();
for (i = 0; i < count; i++)
{
m_children.Get(i)->GetLinks(links);
}
return OpStatus::OK;
}
#endif // ACCESSIBILITY_EXTENSION_SUPPORT
|
#include<iostream>
#include<cstdio>
#include<map>
#include<set>
#include<vector>
#include<stack>
#include<queue>
#include<string>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int a[210],f[210][210][210];
int pow(int k) {
return k*k;
}
int dfs(int l,int r,int k) {
if (f[l][r][k]) return f[l][r][k];
if (l > r) return 0;
int p = l;
for (int i = r;i > l; i--)
if (a[i] != a[i-1]) {
p = i;
break;
}
f[l][r][k] = dfs(l,p-1,0) + pow(k + r-p+1);
for (int i = p-1;i > l; i--)
if (a[i] != a[i-1] && a[i-1] == a[r])
f[l][r][k] = max(f[l][r][k],dfs(l,i-1,k+r-p+1) + dfs(i,p-1,0));
//cout << l << " " << r << " " << k << " " << f[l][r][k] << endl;
return f[l][r][k];
}
int main()
{
int t,ca;
scanf("%d",&t);
for (int ca = 1;ca <= t; ca++) {
int n;
memset(f,0,sizeof(f));
scanf("%d",&n);
for (int i = 1;i <= n; i++)
scanf("%d",&a[i]);
printf("Case %d: %d\n",ca,dfs(1,n,0));
}
return 0;
}
|
// Copyright (c) 2011-2017 The Cryptonote developers
// Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs
// Copyright (c) 2018-2023 Conceal Network & Conceal Devs
//
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <cstdint>
#include <list>
#include <memory>
#include <system_error>
#include <utility>
#include <vector>
#include <CryptoNote.h>
#include "CryptoNoteCore/Difficulty.h"
#include "CryptoNoteCore/MessageQueue.h"
#include "CryptoNoteCore/BlockchainMessages.h"
namespace cn {
struct COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_request;
struct COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response;
struct NOTIFY_RESPONSE_GET_OBJECTS_request;
struct NOTIFY_REQUEST_GET_OBJECTS_request;
class Currency;
class IBlock;
class ICoreObserver;
struct Block;
struct block_verification_context;
struct BlockFullInfo;
struct BlockShortInfo;
struct core_stat_info;
struct i_cryptonote_protocol;
struct Transaction;
struct MultisignatureInput;
struct KeyInput;
struct TransactionPrefixInfo;
struct tx_verification_context;
class ICore {
public:
virtual ~ICore() {}
virtual const Currency& currency() const = 0;
virtual bool addObserver(ICoreObserver* observer) = 0;
virtual bool removeObserver(ICoreObserver* observer) = 0;
virtual bool saveBlockchain() = 0;
virtual bool have_block(const crypto::Hash& id) = 0;
virtual std::vector<crypto::Hash> buildSparseChain() = 0;
virtual std::vector<crypto::Hash> buildSparseChain(const crypto::Hash& startBlockId) = 0;
virtual bool get_stat_info(cn::core_stat_info& st_inf) = 0;
virtual bool on_idle() = 0;
virtual void pause_mining() = 0;
virtual void update_block_template_and_resume_mining() = 0;
virtual bool handle_incoming_block_blob(const cn::BinaryArray& block_blob, cn::block_verification_context& bvc, bool control_miner, bool relay_block) = 0;
virtual bool handle_incoming_block(const Block& b, block_verification_context& bvc, bool control_miner, bool relay_block) = 0;
virtual bool handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS_request& arg, NOTIFY_RESPONSE_GET_OBJECTS_request& rsp) = 0; //Deprecated. Should be removed with CryptoNoteProtocolHandler.
virtual void on_synchronized() = 0;
virtual size_t addChain(const std::vector<const IBlock*>& chain) = 0;
virtual void get_blockchain_top(uint32_t& height, crypto::Hash& top_id) = 0;
virtual std::vector<crypto::Hash> findBlockchainSupplement(const std::vector<crypto::Hash>& remoteBlockIds, size_t maxCount,
uint32_t& totalBlockCount, uint32_t& startBlockIndex) = 0;
virtual bool get_random_outs_for_amounts(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response& res) = 0;
virtual bool get_tx_outputs_gindexs(const crypto::Hash& tx_id, std::vector<uint32_t>& indexs) = 0;
virtual bool getOutByMSigGIndex(uint64_t amount, uint64_t gindex, MultisignatureOutput& out) = 0;
virtual i_cryptonote_protocol* get_protocol() = 0;
virtual bool handle_incoming_tx(const BinaryArray& tx_blob, tx_verification_context& tvc, bool keeped_by_block) = 0; //Deprecated. Should be removed with CryptoNoteProtocolHandler.
virtual std::vector<Transaction> getPoolTransactions() = 0;
virtual bool getPoolTransaction(const crypto::Hash &tx_hash, Transaction &transaction) = 0;
virtual bool getPoolChanges(const crypto::Hash& tailBlockId, const std::vector<crypto::Hash>& knownTxsIds,
std::vector<Transaction>& addedTxs, std::vector<crypto::Hash>& deletedTxsIds) = 0;
virtual bool getPoolChangesLite(const crypto::Hash& tailBlockId, const std::vector<crypto::Hash>& knownTxsIds,
std::vector<TransactionPrefixInfo>& addedTxs, std::vector<crypto::Hash>& deletedTxsIds) = 0;
virtual void getPoolChanges(const std::vector<crypto::Hash>& knownTxsIds, std::vector<Transaction>& addedTxs,
std::vector<crypto::Hash>& deletedTxsIds) = 0;
virtual bool queryBlocks(const std::vector<crypto::Hash>& block_ids, uint64_t timestamp,
uint32_t& start_height, uint32_t& current_height, uint32_t& full_offset, std::vector<BlockFullInfo>& entries) = 0;
virtual bool queryBlocksLite(const std::vector<crypto::Hash>& block_ids, uint64_t timestamp,
uint32_t& start_height, uint32_t& current_height, uint32_t& full_offset, std::vector<BlockShortInfo>& entries) = 0;
virtual crypto::Hash getBlockIdByHeight(uint32_t height) = 0;
virtual bool getBlockByHash(const crypto::Hash &h, Block &blk) = 0;
virtual bool getBlockHeight(const crypto::Hash& blockId, uint32_t& blockHeight) = 0;
virtual void getTransactions(const std::vector<crypto::Hash>& txs_ids, std::list<Transaction>& txs, std::list<crypto::Hash>& missed_txs, bool checkTxPool = false) = 0;
virtual bool getTransactionsWithOutputGlobalIndexes(const std::vector<crypto::Hash>& txs_ids, std::list<crypto::Hash>& missed_txs, std::vector<std::pair<Transaction, std::vector<uint32_t>>>& txs) = 0;
virtual bool getBackwardBlocksSizes(uint32_t fromHeight, std::vector<size_t>& sizes, size_t count) = 0;
virtual bool getBlockSize(const crypto::Hash& hash, size_t& size) = 0;
virtual bool getAlreadyGeneratedCoins(const crypto::Hash& hash, uint64_t& generatedCoins) = 0;
virtual bool getBlockReward(size_t medianSize, size_t currentBlockSize, uint64_t alreadyGeneratedCoins, uint64_t fee, uint32_t height,
uint64_t& reward, int64_t& emissionChange) = 0;
virtual bool scanOutputkeysForIndices(const KeyInput& txInToKey, std::list<std::pair<crypto::Hash, size_t>>& outputReferences) = 0;
virtual bool getBlockDifficulty(uint32_t height, difficulty_type& difficulty) = 0;
virtual bool getBlockTimestamp(uint32_t height, uint64_t ×tamp) = 0;
virtual bool getBlockContainingTx(const crypto::Hash& txId, crypto::Hash& blockId, uint32_t& blockHeight) = 0;
virtual bool getMultisigOutputReference(const MultisignatureInput& txInMultisig, std::pair<crypto::Hash, size_t>& outputReference) = 0;
virtual bool getTransaction(const crypto::Hash &id, Transaction &tx, bool checkTxPool = false) = 0;
virtual bool getGeneratedTransactionsNumber(uint32_t height, uint64_t& generatedTransactions) = 0;
virtual bool getOrphanBlocksByHeight(uint32_t height, std::vector<Block>& blocks) = 0;
virtual bool getBlocksByTimestamp(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t blocksNumberLimit, std::vector<Block>& blocks, uint32_t& blocksNumberWithinTimestamps) = 0;
virtual bool getPoolTransactionsByTimestamp(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<Transaction>& transactions, uint64_t& transactionsNumberWithinTimestamps) = 0;
virtual bool getTransactionsByPaymentId(const crypto::Hash& paymentId, std::vector<Transaction>& transactions) = 0;
virtual std::unique_ptr<IBlock> getBlock(const crypto::Hash& blocksId) = 0;
virtual bool handleIncomingTransaction(const Transaction& tx, const crypto::Hash& txHash, size_t blobSize, tx_verification_context& tvc, bool keptByBlock, uint32_t height) = 0;
virtual std::error_code executeLocked(const std::function<std::error_code()>& func) = 0;
virtual bool addMessageQueue(MessageQueue<BlockchainMessage>& messageQueue) = 0;
virtual bool removeMessageQueue(MessageQueue<BlockchainMessage>& messageQueue) = 0;
};
} //namespace cn
|
#include <cstdio>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
const int N = 111111;
vector<int> g[N];
int color[N], was[N], maxcol;
void dfs(int x) {
bool can[3] = {1, 1, 1};
was[x] = 1;
for (int i = 0; i < (int)g[x].size(); ++i) {
if (was[g[x][i]]) {
can[color[g[x][i]]] = 0;
}
}
color[x] = 0;
while (!can[color[x]]) ++color[x];
if (color[x] > maxcol) maxcol = color[x];
for (int i = 0; i < (int)g[x].size(); ++i) {
if (!was[g[x][i]]) {
dfs(g[x][i]);
}
}
}
int main() {
freopen("coloring.in", "r", stdin);
freopen("coloring.out", "w", stdout);
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) {
int k, x;
scanf("%d%d", &k, &x);
for (int j = 1; j < k; ++j) {
int y;
scanf("%d", &y);
g[x].push_back(y);
g[y].push_back(x);
x = y;
}
}
dfs(1);
printf("%d\n", maxcol + 1);
for (int i = 1; i <= n; ++i)
printf("%d ", color[i] + 1);
printf("\n") ;
return 0;
}
|
#include "..\..\01-Shared\Elysium.Graphics\GameHost.hpp"
Elysium::Graphics::Platform::GameHost::GameHost(Game* Game)
: Elysium::Core::Object(),
Elysium::Graphics::Platform::IGameHost(),
_Game(Game), _GameCanvas(GameWindow())
{
}
Elysium::Graphics::Platform::GameHost::~GameHost()
{
}
Elysium::Graphics::Platform::GameWindow * Elysium::Graphics::Platform::GameHost::GetGameCanvas()
{
return &_GameCanvas;
}
void Elysium::Graphics::Platform::GameHost::Run()
{
_GameCanvas.Show();
while (!_GameCanvas._ShouldExit)
{
_GameCanvas.ProcessInput();
_Game->Draw();
// call some game-class method to run the game-loop
}
}
void Elysium::Graphics::Platform::GameHost::Exit()
{
_GameCanvas.Close();
}
|
#include "Sample.h"
Sample::Sample() {
samples = NULL;
diskSamples = NULL;
hemisphereSamples2D = NULL;
hemisphereSamples3D = NULL;
numberOfSamples = 4;
numberOfHemisphereSamples = 4;
e = 2.718281828459;
roomDepth = 100;
ambientAmountToShade = 0;
}
void Sample::setRoomDepth(double room) {
roomDepth = room;
}
void Sample::setAmbientAmountToShade(double a) {
ambientAmountToShade = a;
}
void Sample::setE(double e) {
this->e = e;
}
void Sample::setNumberOfHemisphereSamples(unsigned int size) {
numberOfHemisphereSamples = size;
}
void Sample::setNumberOfSamples(unsigned int size) {
numberOfSamples = size;
try {
samples = new Point_2D[size];
diskSamples = new Point_2D[size];
}
catch (...) {
throw exception("Error in Sample.setNumberOfSamples()");
}
}
void Sample::initializeHemisphereSamples() {
try {
hemisphereSamples2D = new Point_2D[numberOfHemisphereSamples];
hemisphereSamples3D = new Vector[numberOfHemisphereSamples];
}
catch (...) {
cleanup();
throw exception("Error in Sample.setNumberOfSamples()");
}
}
void Sample::cleanup() {
delete[] samples;
delete[] diskSamples;
delete[] hemisphereSamples2D;
delete[] hemisphereSamples3D;
}
Sample::~Sample() {
delete[] samples;
delete[] diskSamples;
delete[]hemisphereSamples2D;
delete[] hemisphereSamples3D;
}
|
#include <Adafruit_NeoPixel.h>
#include "CatchFire.h"
CatchFire::CatchFire(void) { }
void CatchFire::reset(variables_t *vars) {
vars->progress = 0;
vars->time = 0;
vars->isSparking = true;
vars->isPausing = true;
vars->toQuit = false;
vars->lastTime = millis();
}
void CatchFire::loop(variables_t *vars) {
int i;
// Serial.println("burn");
if((vars->isSparking == true) && (millis()>vars->lastTime+(160-(vars->time*3)))) {
// Serial.println("eeeee");
vars->lastTime = millis();
if(vars->isPausing == true) {
for (i = 0; i < vars->color_len; i++) {//draw
vars->color[i]=Adafruit_NeoPixel::Color(0,0,0);
}
vars->isPausing = false;
// Serial.println("pause");
}else{
for (i = 0; i < vars->color_len; i++) {//draw
if(rand()%(8-(vars->time/2)) == 0) {
vars->color[i]=Adafruit_NeoPixel::Color(255,255,255);
}
}
vars->time++;
if(vars->time > 14) {
vars->isSparking = false;
vars->time = 0;
}
vars->isPausing = true;
}
}else if((vars->isSparking == false) && (millis()>vars->lastTime+160)){
// Serial.println("made it!");
vars->lastTime = millis();
int j;
int div = 21-vars->time;
vars->progress += 1;
if(vars->progress > vars->color_len) {
vars->progress = 0;
}
for (i = 0; i < vars->color_len; i++) {//draw
vars->color[i] = Animation::getColor(rand()%9, div, vars->isCopper);
// Adafruit_NeoPixel::Color(COLOR_PALLET_R[], COLOR_PALLET_G[rand()%9]/div, 0);
}
/* for (i = 0; i < vars->color_len/3; i++) {//draw
vars->color[i] = strip.Color(vars->colorPalletR[rand()%3]/div, vars->colorPalletG[rand()%3]/div, 0);
j = i + vars->progress;
if(j >= vars->color_len) {
j -= vars->color_len;
}
vars->color[j]=vars->color[i]);
}*/
// Serial.println("endraw!");
vars->time++;
if(vars->time >= 20) {
vars->toQuit = true;
}
// Serial.println("todelay!");
}
}
|
#include "Human.hpp"
#include "utils.hpp"
#include <cmath>
#include <iomanip>
#include <iostream>
bool operator>(sf::Vector2f a, sf::Vector2f b) {
return sqrt(pow(a.x, 2) + pow(a.y, 2)) > sqrt(pow(b.x, 2) + pow(b.y, 2));
}
sf::Vector2f operator*(float k, sf::Vector2f a) {
return sf::Vector2f(k * a.x, k * a.y);
}
Human::Human() {
mStatus = Status::Vulnerable;
mFatalityRate = Conf::NORMAL_FATALITY_RATE;
mInfectionDur = Conf::INFECTION_DUR;
mPos = sf::Vector2f(gRandom((int)Conf::MAX_WIDTH),
gRandom((int)Conf::MAX_HEIGHT));
mVel = sf::Vector2f(0, 0);
mHome = mPos;
mWaypoint = sf::Vector2f(-1, -1);
mID = ++sGetCount();
mShape.setPosition(mPos);
mShape.setRadius(3.f);
mShape.setFillColor(Conf::getColorFromMap(mStatus));
mWay.setFillColor(sf::Color::Blue);
mWay.setSize(sf::Vector2f(10, 10));
mWay.setPosition(mWaypoint);
}
Human::~Human() { sGetCount()--; }
int &Human::sGetCount() {
static int sID = 0;
return sID;
}
void Human::mRenderHuman(sf::RenderWindow &pWindow) {
pWindow.draw(mShape);
// pWindow.draw(mWay);
}
void Human::mMove(float timePerFrame) {
if(mStatus != Status::Dead){
sf::Vector2f pos2target = mWaypoint - mPos;
float mag = sqrt(pow(pos2target.x, 2) + pow(pos2target.y, 2));
mVel.x = (100 * pos2target.x / (mag));
mVel.y = (100 * pos2target.y / (mag));
if (pos2target > 0.2 * mVel) {
mPos += timePerFrame * mVel;
if (mPos.x < 0) {
mPos.x += Conf::MAX_WIDTH;
}
if (mPos.x > Conf::MAX_WIDTH) {
mPos.x -= Conf::MAX_WIDTH;
}
if (mPos.y < 0) {
mPos.y += Conf::MAX_HEIGHT;
}
if (mPos.y > Conf::MAX_HEIGHT) {
mPos.y -= Conf::MAX_HEIGHT;
}
// std::cout<<mID<<std::fixed<<std::setprecision(2)<<timePerFrame<<"\t"<<(mPos
// - mWaypoint).x << "\t"<< (mPos - mWaypoint).y<<std::endl;
} else if(mWaypoint == mHome) {
setWaypoint(sf::Vector2f(gRandom((int)Conf::MAX_WIDTH),
gRandom((int)Conf::MAX_HEIGHT)));
} else{
mWaypoint = mHome;
}
mWay.setPosition(mWaypoint);
}
if(mStatus == Status::Infected){
if(mInfectionDur <= 0){
if(gChance(mFatalityRate))
{
setStatus(Status::Dead);
// std::cout<<mID<<" is Dead."<<"\n";
}
else{
setStatus(Status::Immune);
// std::cout<<mID<<" is Immune."<<"\n";
}
}
else{
mInfectionDur -= 60*timePerFrame;
}
}
mShape.setPosition(mPos);
}
void Human::setStatus(enum Status status) {
mStatus = status;
mShape.setFillColor(Conf::getColorFromMap(mStatus));
}
void Human::setFatalityRate(float rate) { mFatalityRate = rate; }
void Human::setWaypoint(sf::Vector2f &&v) { mWaypoint = v; }
|
#ifndef PYTHIA_WRAPPER_H
#define PYTHIA_WRAPPER_H
#include "simpleLogger.h"
#include "Pythia8/Pythia.h"
#include "workflow.h"
#include <sstream>
#include <unistd.h>
#include "predefine.h"
using namespace Pythia8;
class HQGenerator{
public:
HQGenerator(std::string f_pythia, std::string f_trento,
int iev, double pTHL, double pTHH, double _Q0);
void Generate(std::vector<particle> & plist, int Neve, double ycut);
private:
double pL, pH, Q0, sigma0;
Pythia pythia;
std::string f_pythia;
TransverPositionSampler TRENToSampler;
};
HQGenerator::HQGenerator(std::string f_p, std::string f_trento, int iev, double pTHL, double pTHH, double _Q0):
pL(pTHL), pH(pTHH),f_pythia(f_p),TRENToSampler(f_trento, iev)
{
Q0 = _Q0;
// read pythia settings
pythia.readFile(f_pythia);
// suppress output
pythia.readString("Print:quiet = off");
pythia.readString("SoftQCD:all = off");
pythia.readString("PromptPhoton:all=off");
pythia.readString("WeakSingleBoson:all=off");
pythia.readString("WeakDoubleBoson:all=off");
pythia.readString("SpaceShower:QEDshowerByQ=off");
pythia.readString("TimeShower:QEDshowerByQ = off");
pythia.readString("Init:showProcesses = off");
pythia.readString("Init:showMultipartonInteractions = off");
pythia.readString("Init:showChangedSettings = off");
pythia.readString("Init:showChangedParticleData = off");
pythia.readString("Next:numberCount = 1000");
pythia.readString("Next:numberShowInfo = 0");
pythia.readString("Next:numberShowProcess = 0");
pythia.readString("Next:numberShowEvent = 0");
int processid = getpid();
std::ostringstream s1, s2, s3, s4;
s1 << "PhaseSpace:pTHatMin = " << pTHL;
s2 << "PhaseSpace:pTHatMax = " << pTHH;
s3 << "Random:seed = " << processid;
s4 << "TimeShower:pTmin = " << Q0;
std::cout<< s4.str();
pythia.readString(s1.str());
pythia.readString(s2.str());
pythia.readString(s3.str());
pythia.readString(s4.str());
// Init
pythia.init();
for (int i=0; i<1000; i++) pythia.next();
sigma0 = pythia.info.sigmaGen();
}
void reference_pmu(int i, double & tau, Event & event){
auto p = event[i];
int im1 = p.mother1();
int im2 = p.mother2();
if (im1==im2 && im2 > 0){
// simply recoil effect, go on
reference_pmu(im1, tau, event);
}
if (im1==0 && im2 ==0) {
return;
}
if (im1>0 && im2==0){
// radiation
auto P = event[im1];
auto k = event[P.daughter1()];
auto q = event[P.daughter2()];
fourvec Pmu{P.e(), P.px(), P.py(), P.pz()};
fourvec kmu{k.e(), k.px(), k.py(), k.pz()};
fourvec qmu{q.e(), q.px(), q.py(), q.pz()};
double xk = kmu.t()/(kmu.t()+qmu.t());
double xq = 1.-xk;
double Mk2 = k.m()*k.m();
double Mq2 = q.m()*q.m();
double MP2 = P.m()*P.m();
double kT2 = measure_perp(kmu+qmu, kmu).pabs2();
double tauf = 2*xq*xk*(kmu.t()+qmu.t())/(kT2 + xq*Mk2 + xk*Mq2 - xk*xq*MP2);
if (p.e() > 0.5*(kmu.t()+qmu.t())){
reference_pmu(im1, tau, event);
}
else {
tau += tauf;
reference_pmu(im1, tau, event);
}
}
if (im1 != im2 && im1 > 0 && im2 > 0){
return;
}
}
void HQGenerator::Generate(std::vector<particle> & plist, int Neve, double ycut){
double x0, y0;
int Ncharm = 0, Nbottom = 0;
plist.clear();
for(int Ntot=0; Ntot<Neve; Ntot++){
if (Ntot%1000==0) LOG_INFO << "Ncharm = " << Ncharm << ", Nbottom = " << Nbottom;
TRENToSampler.SampleXY(y0, x0);
pythia.next();
double weight = pythia.info.sigmaGen()/Neve;
for (size_t i = 0; i < pythia.event.size(); ++i) {
auto p = pythia.event[i];
bool triggered = ((p.idAbs() == 5) || (p.idAbs() == 4))
&& p.isFinal() && (std::abs(p.y())< ycut);
if (triggered) {
double t0 = 0.;
reference_pmu(i, t0, pythia.event);
if (p.idAbs() == 4) Ncharm ++;
if (p.idAbs() == 5) Nbottom ++;
for(int iphi=0; iphi<8; iphi++){
double phi = iphi*2*M_PI/8;
double cos = std::cos(phi), sin = std::sin(phi);
fourvec p0{p.e(), p.px()*cos-p.py()*sin,
p.px()*sin+p.py()*cos, p.pz()};
particle _p;
_p.pid = p.idAbs();
_p.mass = std::abs(p.m());
_p.x0 = fourvec{0,x0,y0,0};
_p.tau_i = t0;
_p.x = _p.x0;
_p.Q0 = Q0;
_p.Q00 = Q0;
_p.p0 = p0;
_p.col = p.col();
_p.acol = p.acol();
_p.p = _p.p0;
_p.weight = weight/8;
_p.is_virtual = false;
_p.T0 = 0.;
_p.Tf = 0.;
_p.mfp0 = 0.;
_p.vcell.resize(3);
_p.vcell[0] = 0.;
_p.vcell[1] = 0.;
_p.vcell[2] = 0.;
_p.radlist.clear();
_p.charged = p.isCharged();
plist.push_back(_p);
}
}
}
}
//double normW = 0.5*pythia.info.sigmaGen()/pythia.info.weightSum();
//for (auto & p : plist) p.weight *= normW;
//LOG_INFO << "norm = " << normW;
}
#endif
|
// Copyright (c) 2019 The NavCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DAOCONSULTATIONCREATE_H
#define DAOCONSULTATIONCREATE_H
#include "consensus/dao.h"
#include "main.h"
#include "navcoinlistwidget.h"
#include "walletmodel.h"
#include <QCheckBox>
#include <QDialog>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <QRadioButton>
#include <QSpinBox>
#include <QVBoxLayout>
class DaoConsultationCreate : public QDialog
{
Q_OBJECT
public:
DaoConsultationCreate(QWidget *parent);
DaoConsultationCreate(QWidget *parent, QString title, int consensuspos);
void setModel(WalletModel *model);
private:
WalletModel *model;
QVBoxLayout* layout;
QLineEdit* questionInput;
QRadioButton* answerIsNumbersBtn;
QRadioButton* answerIsFromListBtn;
QSpinBox* minBox;
QSpinBox* maxBox;
QLabel* minLbl;
QLabel* maxLbl;
QLabel *warningLbl;
NavCoinListWidget* listWidget;
QCheckBox* moreAnswersBox;
int cpos;
QString title;
void showWarning(QString text);
private Q_SLOTS:
void onCreate();
void onCreateConsensus();
void onRange(bool fChecked);
void onList(bool fChecked);
};
#endif // DAOCONSULTATIONCREATE_H
|
#include "game.hpp"
#include <algorithm>
#include <memory>
#include <utility>
#include "game_object_visitor.hpp"
#include "stats.hpp"
sgfx::rle_image const& resource_manager::rle(std::string const& path)
{
auto i = rle_images_.find(path);
if (i != rle_images_.end())
return i->second;
rle_images_.emplace(make_pair(path, sgfx::load_rle(path)));
return rle(path);
}
game::game() : wnd_{640, 480, "Space!"}
{
}
stats game::run()
{
stats stats;
while (wnd_.handle_events() && !wnd_.should_close())
{
using namespace std::chrono;
auto const now = high_resolution_clock::now();
leftover_time += duration_cast<milliseconds>(now - last_time);
last_time = now;
while (leftover_time >= step_time)
{
{
perf_timer timer{stats.collider};
collision_mgr_.handle_collisions();
}
for (std::size_t i = 0; i < objs_.size(); ++i)
{
perf_timer timer{stats.updates};
auto const obj_state = game_object_updater::update(game_proxy{this}, step_time, *objs_[i]);
if (obj_state == game_object::status::dead)
{
std::swap(objs_[i], objs_.back());
objs_.pop_back();
--i;
}
}
leftover_time -= step_time;
}
std::for_each(begin(objs_), end(objs_), [&](auto& obj) {
perf_timer timer{stats.draws};
game_object_drawer::draw(wnd_, *obj);
});
{
perf_timer timer{stats.render};
wnd_.show();
}
}
std::cout << "stats: " << stats << std::endl;
return stats;
}
void game::spawn(std::unique_ptr<game_object> new_obj)
{
objs_.push_back(std::move(new_obj));
}
|
//Phoenix_RK
/*
https://leetcode.com/problems/delete-node-in-a-bst/
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove.
If the node is found, delete the node.
Follow up: Can you solve it with time complexity O(height of tree)?
Input: root = [5,3,6,2,4,null,7], key = 3
Output: [5,4,6,2,null,null,7]
Explanation: Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the above BST.
Please notice that another valid answer is [5,2,6,null,4,null,7] and it's also accepted.
Input: root = [5,3,6,2,4,null,7], key = 0
Output: [5,3,6,2,4,null,7]
Explanation: The tree does not contain a node with value = 0.
Example 3:
Input: root = [], key = 0
Output: []
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* minValue(TreeNode* root)
{
if(!root)
return root;
while(root->left)
root=root->left;
return root;
}
TreeNode* deleteNode(TreeNode* root, int key) {
if(!root)
return root;
if(root->val<key)
root->right=deleteNode(root->right,key);
else if(root->val>key)
root->left=deleteNode(root->left,key);
else
{
if(!root->left)
{
TreeNode* temp = root->right;
delete root;
return temp;
}
else if(!root->right)
{
TreeNode* temp = root->left;
delete root;
return temp;
}
else
{
TreeNode* temp=minValue(root->right);
root->val=temp->val;
root->right=deleteNode(root->right,temp->val);
}
}
return root;
}
};
|
#include "Configuration.h"
#include <map>
#include <stdlib.h>
using json = nlohmann::json;
Configuration::Configuration(std::string fname)
{
ifs.open(fname);
jsons.assign(std::istreambuf_iterator<char>(ifs) , std::istreambuf_iterator<char>());
j = json::parse(jsons);
}
Configuration::~Configuration()
{
ifs.close();
}
void Configuration::Reload()
{
jsons.assign(std::istreambuf_iterator<char>(ifs) , std::istreambuf_iterator<char>());
j = json::parse(jsons);
}
|
#include <iostream>
#include <forward_list>
using namespace std;
struct incorrect_k_value {};
/*
* Runs O(n)
*
*/
int kth_to_last(forward_list<int> flist, int k) {
if (k <= 0) {
throw incorrect_k_value {};
}
auto i = flist.begin();
int pos = 0;
while ((i != flist.end()) && (pos < k)) {
i++;
pos++;
}
if (pos < k) {
throw incorrect_k_value {};
}
auto kth_iterator = flist.begin();
while (i != flist.end()) {
i++;
kth_iterator++;
}
return *kth_iterator;
}
void run_kth_to_last(forward_list<int> flist, int k) {
try {
int kth = kth_to_last(flist, k);
cout << "Kth to last element: " << kth << endl;
} catch(incorrect_k_value) {
cout << "Invalid k value" << endl;
}
}
int main() {
run_kth_to_last({}, 2);
run_kth_to_last({1, 2, 3, 4, 5, 6, 7}, 0);
run_kth_to_last({1, 2, 3, 4, 5, 6, 7}, 1);
run_kth_to_last({1, 2, 3, 4, 5, 6, 7}, 2);
run_kth_to_last({1, 2, 3, 4, 5, 6, 7}, 7);
run_kth_to_last({1, 2, 3, 4, 5, 6, 7}, 10);
}
|
#include "stdafx.h"
#include "QuizView.h"
namespace qp
{
CQuizView::CQuizView()
{
}
CQuizView::~CQuizView()
{
}
}
|
#ifndef RECOGNITION_HH_
#define RECOGNITION_HH_
#include <list>
#include <string>
/** Data structure for morphemes. */
struct Morpheme
{
unsigned long time; //!< Starting frame of the morpheme.
unsigned long duration; //!< Duration of the morpheme.
std::string data; //!< The morpheme.
};
/** Container type for morphemes. */
typedef std::list<Morpheme> MorphemeList;
/** Data structure containing a morpheme lists both for recognized part and
* hypothesis part. Recognitions are passed as a message to parse function.
* Also this class stores the information about the status of the recognizer.
* The status information should be read some other way, but this was simple
* and good enough, and didn't force major changes to the recognizer.
* This class system is a bit messy, sorry. Did not have time to plan it
* properly.
* TODO: Poista lock ja unlock funktiot. Huolehdi lukoista luokan sisรคllรค.
* Palauta vain kopioita luokan dataan, ei suoria viittauksia. Olisiko
* tรคllaisissa muutoksissa jรคrkeรค..(??)
* */
class RecognizerStatus
{
public:
enum RecognitionStatus { READY, RECOGNIZING, RESETTING };
enum AdaptationStatus { NONE, ADAPTING, ADAPTED };
/** Constant telling how many (recognition) frames in second. */
static const unsigned int frames_per_second;
/** If word based recognition or not */
static bool words;
/** Constructs the object. */
RecognizerStatus();
/** Destructs the object. */
~RecognizerStatus();
/** Call when the recognizer has been reseted. Note, this doesn't reset the
* recognition data, it just affects the status. */
void reset_recognition();
/** Call when M_READY message is received from the recognizer. */
void set_ready();
/** Call if any M_RECOG message is received from the recognizer. */
void received_recognition();
/** \return Returns the status of the recognizer. */
RecognitionStatus get_recognition_status() const;
/** Call when recognition with adaptation is started. */
void start_adapting();
/** Call when adaptation is reseted. */
void reset_adaptation();
/** Call when adaptation is cancelled (from state ADAPTING) */
void cancel_adaptation();
/** Call when M_RECOG_END is received. */
void recognition_end();
/** \return The adaptation status of the recognizer. */
AdaptationStatus get_adaptation_status() const;
/**
* Takes a recognition message as a parameter and updates recognized text
* and hypothesis according to that.
* \param message Formatted string containing the information: starting
* and ending frames for every morpheme and separation of
* hypothesis and recognition by * .
* Valid format examples:
* "100 jou 112 lu * 128 on 140 jo 151"
* "120 sana 135"
* "101"
* "* 120 hypo 151 teesi 174"
* */
void parse(const std::string &message);
/** Function returns when no other thread has lock on. You can use lock
* function if you want to synchronize threads.
*
* NOTE: A bit stupid to have locks here: what does this data structure
* know about threads. Maybe there's a better way to do this? */
inline void lock();
/** Releases the lock for this thread. */
inline void unlock();
/** \return List of morphemes considered as hypothesis. */
inline const MorphemeList& get_hypothesis() const;
/** \return List of morphemes considered recognized. */
inline const MorphemeList& get_recognized() const;
/** \return The last frame of the whole recognition and hypothesis. */
inline unsigned long get_recognition_frame() const;
/** \return Recognized and hypothesis morphemes as a text. */
std::string get_recognition_text() const;
/** Clears all morphemes and recognition frame. */
void reset();
/** message_result(true) has been called */
bool m_message_result_true_called;
protected:
/** Writes morpheme into the string.
* \param str Writes morphemes into this string.
* \param morphemes Morphemes to write. */
inline static void append_morphemes(std::string &str,
const MorphemeList &morphemes);
/** Copies the morpheme to the data string. Changes "<w> to " " and
* "</s>" to ".". Ignores "<s>" to "".
* \param data Destination of the copy.
* \param morpheme Source of the copy. */
static void write_morpheme_data(std::string &data,
const std::string &morpheme);
private:
MorphemeList m_hypothesis; //!< List of hypothesis morphemes.
MorphemeList m_recognized; //!< List of recognized morphemes.
unsigned long m_recognition_frame; //!< Frame set by user.
pthread_mutex_t m_lock; //!< Lock for users of this class.
RecognitionStatus m_recognition_status;
AdaptationStatus m_adaptation_status;
bool m_was_adapting_when_reseted;
};
void
RecognizerStatus::lock()
{
pthread_mutex_lock(&this->m_lock);
}
void
RecognizerStatus::unlock()
{
pthread_mutex_unlock(&this->m_lock);
}
const MorphemeList&
RecognizerStatus::get_hypothesis() const
{
return this->m_hypothesis;
}
const MorphemeList&
RecognizerStatus::get_recognized() const
{
return this->m_recognized;
}
unsigned long
RecognizerStatus::get_recognition_frame() const
{
return this->m_recognition_frame;
}
void
RecognizerStatus::append_morphemes(std::string &str, const MorphemeList &morphemes)
{
for (MorphemeList::const_iterator iter = morphemes.begin();
iter != morphemes.end();
iter++) {
str.append(iter->data);
}
}
#endif /*RECOGNITION_HH_*/
|
/* -*- 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.
*/
#ifndef HTMLEXPORTER_H
#define HTMLEXPORTER_H
#include "modules/util/opfile/opfile.h"
#include "modules/util/adt/opvector.h"
class HTMLExporter
{
public:
OP_STATUS Open(const uni_char *file_name, int width, int height, const char *name = NULL)
{
int i;
RETURN_IF_ERROR(html_file.Construct(file_name));
RETURN_IF_ERROR(html_file.Open(OPFILE_WRITE));
Printf("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
"<html>\n"
"<head>\n");
if (name != NULL)
Printf("<title>%s</title>\n", name);
else Printf("<title></title>\n");
Printf("<style type=\"text/css\">\n"
" table { border-collapse: collapse; }\n");
if (width != 0 && height != 0)
Printf(" td { width: %ipx; height: %ipx; font-size: 1px; line-height: 1px; }\n", width, height);
for (i = 0; i < (int)text_color.GetCount(); ++i)
Printf(" .c_%s { background: %s; }\n", text_color.Get(i)->name, text_color.Get(i)->color);
for (i = 0; i < (int)number_color.GetCount(); ++i)
Printf(" .class_%u { background: %s; }\n", number_color.Get(i)->number, number_color.Get(i)->color);
Printf(" .un_0 { background: white; }\n"
" .un_1 { background: black; }\n"
" .un_2 { background: red; }\n"
" .un_3 { background: green; }\n"
" .un_4 { background: blue; }\n"
" .un_5 { background: yellow; }\n"
"</style>\n"
"</head>\n"
"<body>\n"
"<table>\n"
"<tr>\n");
return OpStatus::OK;
}
void Close(void)
{
Printf("</tr>\n"
"</table>\n"
"</body>\n"
"</html>\n");
html_file.Close();
}
OP_STATUS SetClass(const char *name, const char *color)
{
TextColor *c;
if ((c = OP_NEW(TextColor, ())) == NULL)
return OpStatus::ERR_NO_MEMORY;
op_strncpy(c->name, name, sizeof(c->name));
op_strncpy(c->color, color, sizeof(c->color));
c->color[sizeof(c->color) - 1] = 0;
text_color.Add(c);
return OpStatus::OK;
}
OP_STATUS SetClass(unsigned int number, const char *color)
{
NumberColor *c;
if ((c = OP_NEW(NumberColor, ())) == NULL)
return OpStatus::ERR_NO_MEMORY;
c->number = number;
op_strncpy(c->color, color, sizeof(c->color));
c->color[sizeof(c->color) - 1] = 0;
number_color.Add(c);
return OpStatus::OK;
}
void Add(const char *name, const char *value = "")
{
int i;
if (name == NULL)
{
Printf("\t<td></td>\n");
return;
}
for (i = 0; i < (int)text_color.GetCount(); ++i)
if (op_strncmp(name, text_color.Get(i)->name, sizeof(text_color.Get(i)->name)) == 0)
{
Printf("\t<td class=\"c_%s\">%s</td>\n", name, value);
return;
}
Printf("\t<td class=\"un_%i\">%s</td>\n", name[0] % 6, value);
}
void Add(unsigned int number, const char *value = "")
{
int i;
for (i = 0; i < (int)number_color.GetCount(); ++i)
if (number_color.Get(i)->number == number)
{
Printf("\t<td class=\"class_%u\">%s</td>\n", number, value);
return;
}
Printf("\t<td class=\"un_%i\">%s</td>\n", number % 6, value);
}
void NewLine(void)
{
Printf("</tr>\n</table>\n<table>\n<tr>\n");
}
void Label(const char *value)
{
Printf("\t<th>%s: </th>\n", value);
}
void Label(int value)
{
Printf("\t<th>%.03i: </th>\n", value);
}
protected:
// OpFile::Print was buggy
void Printf(const char *format, ...)
{
va_list arglist;
va_start(arglist, format);
char buffer[256]; /* ARRAY OK 2010-09-24 roarl */
int count = op_vsnprintf(buffer, 255, format, arglist);
buffer[255] = 0;
if (count > 0)
html_file.Write(buffer, count);
va_end(arglist);
}
struct TextColor
{
char name[32]; /* ARRAY OK 2010-09-24 roarl */
char color[32]; /* ARRAY OK 2010-09-24 roarl */
};
struct NumberColor
{
unsigned int number;
char color[32]; /* ARRAY OK 2010-09-24 roarl */
};
OpAutoVector<TextColor> text_color;
OpAutoVector<NumberColor> number_color;
OpFile html_file;
};
#endif // HTMLEXPORTER_H
|
//
// this code writes a SALT ini file to the primary FRAM_SETTINGS section of fram (0x0100-0x0FFF) and writes a
// second, backup copy, to the backup FRAM_SETTINGS_2 section (0x1100-0x1FFF)
//
// This version of ini loader reads an ini file from the uSD flash
//
#include <Systronix_MB85RC256V.h>
#include <SALT_settings.h>
#include <SALT_FETs.h>
#include <SALT.h>
#include <SALT_utilities.h>
#include <SALT_JX.h>
#include <SPI.h>
#include <SdFat.h>
#include <DS1307RTC.h>
#include <Systronix_i2c_common.h>
#include <Systronix_NTP.h>
#include "ini_loader.h" // not exactly a shared file but is the same file as used for ini_loader.ino
Systronix_i2c_common i2c_common;
Systronix_MB85RC256V fram;
Systronix_NTP ntp;
SALT_settings settings;
SALT_utilities utils;
SALT_FETs FETs; // to turn of lights fans, alarm
SALT_JX coreJ2; // to turn off heat pads, lamps, drawer locks
SALT_JX coreJ3;
SALT_JX coreJ4;
SdFat SD;
SdFile file;
//---------------------------< D E F I N E S >----------------------------------------------------------------
#define END_OF_FILE 0xE0FF
#define SYSTEM 0xDF
#define USERS 0xEF
#define STOP 0
#define START 1
#define TIMING 0xFFFFFFFF
//---------------------------< P A G E S C O P E V A R I A B L E S >--------------------------------------
char rx_buf [8192];
char out_buf [8192];
char ln_buf [256];
//uint16_t err_cnt = 0;
uint16_t total_errs = 0;
uint16_t warn_cnt = 0;
char pins[USERS_MAX_NUM+1][6] = {"", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""};
time_t manufacture_date = 0; // not a 'setting' but is stored in fram control block 2
uint16_t habitat_rev = 0xFFFF; // not a 'setting' but is stored in fram control block 2
uint16_t store = 0xFFFF; // not a 'setting' but is stored in fram control block 2
//---------------------------< C O M M O N _ F U N C T I O N S >----------------------------------------------
//
// apparently must be a .h file; compiler can't find the same file in the same location if it has a .inl extension
//
// Functions in the common file are shared with ini_loader
//
#include "ini_loaders_common.h"
//---------------------------< F I L E _ G E T _ C H A R S >--------------------------------------------------
//
// Fetches characters from a selected file in uSD and writes them into rx_buf. CRLF ('\r\n') is converted to LF
// ('\n'). Returns the number of characters received. If the function receives enough characters to fill the
// allotted space in fram then something is not right; null terminates the buffer and returns the number of
// characters received.
//
uint16_t file_get_chars (char* rx_ptr)
{
uint16_t char_cnt = 0;
char c; // temp holding variable
while (file.available()) // while stuff to get
{
c = file.read(); // read and save the byte
if (EOL_MARKER == c)
{
char_cnt++; // tally
*rx_ptr++ = c; // save and bump the pointer
*rx_ptr = EOF_MARKER; // add end-of-file whether we need to or not
*(rx_ptr+1) = '\0'; // null terminate whether we need to or not
if (0 == (char_cnt % 2))
Serial.print ("."); // show that we're received a line
continue;
}
else if ('\r' == c) // carriage return
{
char_cnt ++; // tally
continue; // but don't save; we only want the newline as a line marker
}
else
{
char_cnt++; // tally
*rx_ptr++ = c; // save and bump the pointer
*rx_ptr = EOF_MARKER; // add end-of-file whether we need to or not
*(rx_ptr+1) = '\0'; // null terminate whether we need to or not
}
if (8191 <= char_cnt) // rcvd too many chars? not a SALT ini file?
{
*rx_ptr = '\0'; // null terminate rx_buf
return char_cnt;
}
}
return char_cnt;
}
//---------------------------< S E T U P >--------------------------------------------------------------------
void setup()
{
pinMode(4, INPUT_PULLUP); // not used on salt
// make sure all spi chip selects inactive
pinMode (FLASH_CS_PIN, INPUT_PULLUP); // SALT FLASH_CS(L)
pinMode (T_CS_PIN, INPUT_PULLUP); // SALT T_CS(L)
pinMode (ETH_CS_PIN, INPUT_PULLUP); // SALT ETH_CS(L)
pinMode (DISP_CS_PIN, INPUT_PULLUP); // SALT DISP_CS(L)
pinMode (uSD_DETECT, INPUT_PULLUP); // so we know if a uSD is in the socket
delay(1);
pinMode(PERIPH_RST, OUTPUT);
pinMode (ETHER_RST, OUTPUT);
digitalWrite(PERIPH_RST, LOW); // resets asserted
digitalWrite(ETHER_RST, LOW);
delay(1);
digitalWrite(PERIPH_RST, HIGH); // resets released
digitalWrite(ETHER_RST, HIGH);
delay(1); // time for WIZ850io to reset
Serial.begin(115200); // usb; could be any value
while((!Serial) && (millis()<10000)); // wait until serial monitor is open or timeout
Serial1.begin(9600); // UI habitat A LCD and keypad
while((!Serial1) && (millis()<10000)); // wait until serial port is open or timeout
Serial2.begin(9600); // UI habitat B LCD and keypad
while((!Serial2) && (millis()<10000)); // wait until serial port is open or timeout
Serial.printf ("NAP utility: ini loader SD\nBuild %s %s\r\n", __TIME__, __DATE__);
// These functions have a bug in TD 1.29 see forum post by KurtE...
// ...https://forum.pjrc.com/threads/32502-Serial2-Alternate-pins-26-and-31
Serial2.setRX (26);
Serial2.setTX (31);
Serial1.printf ("r\r"); // 'r' initialize display so we can have a sign-on message
Serial2.printf ("r\r");
delay(50);
// 0123456789ABCDEF0123456789ABCDEF
Serial1.printf ("dNAP utility: ini loader SD \r");
Serial2.printf ("dNAP utility: ini loader SD \r");
FETs.setup (I2C_FET); // constructor for SALT_FETs, and PCA9557
FETs.begin ();
FETs.init (); // lights, fans, and alarms all off
coreJ2.setup (I2C_J2); // heat pads, lamps, drawer locks all off
coreJ3.setup (I2C_J3);
coreJ4.setup (I2C_J4);
coreJ2.begin ();
coreJ3.begin ();
coreJ4.begin ();
coreJ2.init ();
coreJ3.init ();
coreJ4.init ();
coreJ2.JX_data.outdata.as_u32_word = 0; // all drawers unlocked
coreJ2.update();
coreJ3.JX_data.outdata.as_u32_word = 0; // heatlamps and heat pads off
coreJ3.update();
coreJ4.JX_data.outdata.as_u32_word = 0; // heatlamps and heat pads off
coreJ4.update();
fram.setup (0x50);
fram.begin (); // join i2c as master
fram.init();
if (!fram.error.exists)
{
Serial.printf ("fatal error: cannot communicate with fram\r\n");
Serial.printf ("loader stopped; reset to restart\r\n"); // give up and enter an endless
while(1); // loop
}
}
//---------------------------< L O O P >----------------------------------------------------------------------
//
//
//
char file_list [100][64]; // a 1 indexed array of file names; file_list[0] not used
void loop()
{
uint16_t crc = 0xFFFF;
uint16_t rcvd_count;
time_t elapsed_time;
uint8_t ret_val;
uint8_t c = 0;
uint8_t heading = 0;
uint8_t file_count; // indexer into file_list; a 1-indexed array; file_list[0] not used
char* rx_ptr = rx_buf; // point to start of rx_buf
char* out_ptr = out_buf; // point to start of out_buf
memset (out_buf, EOF_MARKER, sizeof(out_buf)); // fill out_buf with end-of-file markers
for (uint8_t i=1; i<=USERS_MAX_NUM; i++) // loop through pins array and reset them to zero length
pins[i][0] = '\0';
if (digitalRead (uSD_DETECT))
{
Serial.printf ("insert uSD\r\n");
while (digitalRead (uSD_DETECT)); // hang here while uSD not installed
delay (50); // installed, now wait a bit for things to settle
}
Serial.printf ("uSD installed\r\n");
if (!SD.begin(uSD_CS_PIN, SPI_HALF_SPEED))
{
Serial.printf ("\r\nerror initializing uSD; cs: %d; half-speed mode\r\n", uSD_CS_PIN);
SD.initErrorHalt("loader stopped; reset to restart\r\n");
while (1);
}
Serial.printf ("monitor must send newline\nchoose ini file to load:\r\n");
file_count = 0;
SD.vwd()->rewind(); // rewind to start of virtual working directory
while (file.openNext(SD.vwd(), O_READ)) // open next file for reading
{
if (!file.isFile()) // files only
{
file.close (); // close this directory
continue; // from the top
}
file_count++; // bump to next file list location
file.getName (file_list[file_count], 32); // get and save the file name
ret_val = strlen (file_list[file_count]) - 4; // make an index to the last four characters of the file name
if (strcasecmp(&file_list[file_count][ret_val], ".ini")) // if last four characters are not ".ini"
{
file_count--; // not a .ini file so recover this spot in the list
file.close(); // close the file
continue; // from the top
}
// Serial.printf ("\n%d ", file.fileSize()); // is this of any value? Get it but don't list a file with length 0?
Serial.printf (" [%2d] %-32s ", file_count, file_list[file_count]); // print menu item, file name, file date
file.printModifyDateTime(&Serial); // and time/date TODO: must we use this? is there no better way to get file date and time?
Serial.printf ("\r\n"); // terminate the menu
file.close(); //
if (99 <= file_count) // only list 99 files
break;
}
if (0 == file_count)
{
Serial.printf ("\r\nno .ini files found on uSD card.\r\nloader stopped; reset to restart");
while (1); // hang it up
}
while (1)
{
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
Serial.printf ("SALT/loader> "); // print the SALT prompt and accept serial input
ret_val = 0;
while (1)
{
if (Serial.available()) // wait for input
{
c = Serial.read(); // get whatever is there
if (!isdigit(c))
break;
c -= '0'; // make binary
if (!c && !ret_val)
continue; // ignore leading zeros
ret_val *= 10; // make room for new digit
ret_val += c; // add the new digit
}
}
if ('\n' == c) // newline ends entry
{
if (ret_val && (ret_val <= file_count)) // entry must be within range of 1 to file_count
{
Serial.printf ("%d\r\n", ret_val); // valid entry, terminate the prompt
if (file.open (file_list[ret_val]))
{
Serial.printf ("\r\nreading %s\r\n", file_list[ret_val]);
ret_val = 0xFF;
}
else
Serial.printf ("\r\nfile %s did not open\r\n", file_list[ret_val]);
break;
}
else
Serial.printf ("invalid choice: %d\n", ret_val);
}
else
Serial.printf ("illegal character: %c\n", c);
ret_val = 0; // non-digit character that is not a new line; restart
}
Serial.printf ("\r\nreading\r\n");
stopwatch (START);
rcvd_count = file_get_chars (rx_buf);
file.close();
elapsed_time = stopwatch (STOP); // capture the time
Serial.printf ("\r\nread %d characters in %dms\r\n", rcvd_count, elapsed_time);
settings.line_num = 0; // reset to count lines taken from rx_buf
Serial.printf ("\r\nchecking\r\n");
stopwatch (START); // reset
rx_ptr = rx_buf; // initialize
while (rx_ptr)
{
rx_ptr = array_get_line (ln_buf, rx_ptr); // returns null pointer when no more characters in buffer
if (!rx_ptr)
break;
if (EOF_MARKER == *ln_buf) // when we find the end-of-file-marker
{
*out_ptr = *ln_buf; // add it to out_buf
break; // done reading rx_buf
}
settings.line_num ++; // tally
if (('\r' == *ln_buf) || (EOL_MARKER == *ln_buf)) // do these here so we have source line numbers for error messages
continue; // cr or lf; we don't save newlines in fram
strcpy (ln_buf, settings.trim (ln_buf)); // trim leading white space
if ('#' == *ln_buf) // first non-whitespace character is '#'?
continue; // comment; we don't save comments in fram
if (strstr (ln_buf, "#")) // find '#' anywhere in the line
{
settings.err_msg ((char *)"misplaced comment"); // misplaced; comment must be on separate lines
total_errs++; // prevent writing to fram
continue; // back to get next line
}
ret_val = normalize_kv_pair (ln_buf); // if kv pair: trim, spaces to underscores; if heading: returns heading define; else returns error
if (ret_val) // if an error or a heading (otherwise returns SUCCESS)
{
if (INI_ERROR == ret_val) // not a heading, missing assignment operator
settings.err_msg ((char *)"not key/value pair");
else // found a new heading
{
heading = ret_val; // so remember which heading we found
out_ptr = array_add_line (out_ptr, ln_buf); // copy to out_buf; reset pointer to eof marker
}
continue; // get the next line
}
if (SYSTEM == heading) // validate the various settings according to their headings
check_ini_system (ln_buf);
else if (HABITAT_A == heading)
check_ini_habitat_A (ln_buf);
else if (HABITAT_B == heading)
check_ini_habitat_B (ln_buf);
else if (HABITAT_EC == heading)
check_ini_habitat_EC (ln_buf);
else if (USERS == heading)
check_ini_users (ln_buf);
}
if ('\0' == *system_config) // these are the required key/value pairs; emit error messages if these have not been modified
{
Serial.printf ("ERROR: required config missing\n");
total_errs++;
}
if (0xFFFF == store)
{
Serial.printf ("ERROR: required store missing\n");
total_errs++;
}
if (0 == manufacture_date)
{
Serial.printf ("ERROR: required manuf date missing\n");
total_errs++;
}
check_min_req_users (); // there must be at minimum 1 each leader, service, & it tech user except when there is a factory user
elapsed_time = stopwatch (STOP); // capture the time
// Serial.printf ("\nchecked %d lines in %dms; ", settings.line_num, elapsed_time);
if (total_errs) // if there have been any errors
{
Serial.printf ("\n###############################################\n");
Serial.printf ("##\n");
Serial.printf ("##\t%d error(s); %d warning(s);\n", total_errs, warn_cnt);
Serial.printf ("##\tconfiguration not written.\r\n");
Serial.printf ("##\tloader stopped; reset to restart\n");
Serial.printf ("##\n");
Serial.printf ("###############################################\n");
while (1);
}
else
Serial.printf ("0 error(s); %d warning(s).\r\n", warn_cnt);
if (warn_cnt && !total_errs) // warnings but no errors
{
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (!utils.get_user_yes_no ((char*)"loader", (char*)"ignore warnings and write settings to fram?", false)) // default answer no
{
total_errs = warn_cnt; // spoof to prevent writing fram
Serial.printf ("\n\nabandoned\r\n");
}
}
if (!total_errs) // if there have been errors, no writing fram
{
write_settings_to_out_buf (out_buf); // write settings to the output buffer
if (!write_test(PRIMARY))
{
Serial.printf ("unable to write to fram primary. loader stopped; reset to restart. check write protect jumper\n");
while(1);
}
Serial.printf ("\n");
erase_settings (PRIMARY); // erase any existing setting from both the primary
if (!settings.is_settings_empty (PRIMARY))
{
Serial.printf ("\tprimary settings area did not erase. loader stopped; reset to restart\r\n");
utils.fram_hex_dump (0);
while(1);
}
if (!write_test(BACKUP))
{
Serial.printf ("unable to write to fram backup. loader stopped; reset to restart. check write protect jumper\n");
while(1);
}
erase_settings (BACKUP); // and backup areas
if (!settings.is_settings_empty (BACKUP))
{
Serial.printf ("\tbackup settings area did not erase. loader stopped; reset to restart\r\n");
while(1);
}
write_settings (PRIMARY, out_buf); // write new settings to both the primary
write_settings (BACKUP, out_buf); // and backup areas
/* debug - see note at bottom of file
settings.get_crc_fram (&crc, 0x0400, FRAM_SETTINGS_END);
Serial.printf ("start: 0x%.4X; end: 0x%.4X; crc: 0x%4X\n", 0x0400, FRAM_SETTINGS_END, crc);
*/
// crc primary
// stopwatch (START);
crc = get_crc_array ((uint8_t*)out_buf); // calculate the crc across the entire buffer
if (set_fram_crc (PRIMARY, crc))
{
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (utils.get_user_yes_no ((char*)"loader", (char*)"crc match failure. dump settings from fram?", true)) // default answer yes
utils.fram_hex_dump (0);
Serial.printf ("\r\ncrc match failure. loader stopped; reset to restart\r\n"); // give up an enter and endless
while(1); // loop
}
// elapsed_time = stopwatch (STOP);
// Serial.printf ("\r\ncrc value (0x%.4X) calculated and written to fram in %dms", crc, elapsed_time);
Serial.printf ("primary crc: 0x%.4X\n", crc);
// crc backup
// stopwatch (START);
crc = get_crc_array ((uint8_t*)out_buf); // calculate the crc across the entire buffer
if (set_fram_crc (BACKUP, crc))
{
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (utils.get_user_yes_no ((char*)"loader", (char*)"backup crc match failure. dump backup settings from fram?", true)) // default answer yes
utils.fram_hex_dump (1000);
Serial.printf ("\r\nbackup crc match failure. loader stopped; reset to restart\r\n"); // give up an enter and endless
while(1); // loop
}
// elapsed_time = stopwatch (STOP);
// Serial.printf ("\r\nbackup crc value (0x%.4X) calculated and written to fram in %dms", crc, elapsed_time);
Serial.printf ("backup crc: 0x%.4X\n", crc);
set_fram_manuf_date ();
set_fram_habitat_rev ();
set_fram_store ();
//--
Serial.printf("\r\n\r\nfram settings write complete\r\n\r\n");
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (utils.get_user_yes_no ((char*)"loader", (char*)"dump settings from fram?", true)) // default answer yes
{
// settings.dump_settings (); // dump the settings to the monitor
utils.fram_hex_dump (0);
}
Serial.printf ("\r\n\ndone\r\n");
}
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (utils.get_user_yes_no ((char*)"loader", (char*)"dump fram log memory?", true)) // default answer yes
utils.fram_hex_dump (FRAM_LOG_START);
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (utils.get_user_yes_no ((char*)"loader", (char*)"initialize fram log memory?", false)) // default answer no
{
Serial.printf ("\r\ninitializing fram log memory\r\n");
stopwatch (START); // reset
utils.fram_fill (EOF_MARKER, FRAM_LOG_START, (FRAM_LOG_END - FRAM_LOG_START + 1));
elapsed_time = stopwatch (STOP); // capture the time
Serial.printf ("\r\nerased %d fram bytes in %dms\r\n", FRAM_LOG_END - FRAM_LOG_START + 1, elapsed_time);
}
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (utils.get_user_yes_no ((char*)"loader", (char*)"set SALT clock?", true)) // default answer yes
{
if (SUCCESS == ntp.setup(POOL))
clock_set ();
else
Serial.printf ("ntp.setup() failed; clock not set\n");
}
Serial.printf ("\r\nloader stopped; reset to restart\r\n"); // give up and enter an endless
while(1); // loop forever
/* disabled; we don't have code to reset the settings in ini_loader.h to their original values after the values
have been modified by a file load. Without complete reset, the default values are not restored for the next
file. The problem showed itself when loading one file, looping back to load another, looping back to reload
the first file. The first and third loads should have had exactly the same crc value but did not. Repeatedly
loading the first file over itself does not produce different crc values. Comparing fram images after the
first and third loads show that they are indeed different between addresses 0400 and 0500. This was located by
setting the crc calculator start address to 0x0800 (1st & 3rd crc same), 0x0400 (different), 0x0600 (same),
0x0500 (same), and back to 0x0400 (different).
Some ini keys do not have assigned values in the first file (b2bwec.ini), but do in the second (b2bwec_ship.ini).
going back to the first file the blank keys assume the 'default' values which are really just the leftovers from
the second file load.
while (Serial.available())
ret_val = Serial.read(); // if anything in the Serial input, get rid of it
if (!utils.get_user_yes_no ((char*)"loader", (char*)"load another file", false)) // default answer no
{
Serial.printf ("\r\nloader stopped; reset to restart\r\n"); // give up and enter an endless
while(1); // loop
}
memset (rx_buf, '\0', sizeof(rx_buf)); // clear rx_buf to zeros
for (uint8_t i=0; i<=USERS_MAX_NUM; i++)
{
user[i].name[0] = '\0'; // make sure that the user list is reset
user[i].pin[0] = '\0';
user[i].rights[0] = '\0';
}
total_errs = 0; // reset these so they aren't misleading
warn_cnt = 0;
*/ }
|
#pragma once
#include "ray.h"
class Camera {
public:
__device__ Camera() = default;
__device__ Camera(const glm::vec3& _origin, const glm::vec3& _lower_left) :
origin(_origin), lower_left(_lower_left)
{
int width = abs(2 * lower_left.x);
horizontal = glm::vec3(width, 0, 0);
int height = abs(2 * lower_left.y);
vertical = glm::vec3(0, height, 0);
}
__device__ ~Camera() = default;
__device__ Ray Camera::get_ray(float u, float v)
{
return Ray(origin, lower_left + u * horizontal + v * vertical);
}
public:
glm::vec3 origin, lower_left;
glm::vec3 horizontal, vertical;
};
|
#include <bits/stdc++.h>
using namespace std;
ofstream fout ("notlast.out");
ifstream fin ("notlast.in");
#define For(x) for(int i = 0; i < x; i++)
#define For2(x) for(int j = 0; j < x; j++)
#define Forv(vector) for(auto& i : vector)
int main(){
int n;
fin>>n;
vector<string> cows= {"Bessie", "Elsie", "Daisy", "Gertie", "Annabelle", "Maggie", "Henrietta"};
vector<pair<int,string> > ls;
Forv(cows){
pair<int,string> p(0,i);
ls.push_back(p);
}
For(n){
string s;
int t;
fin >> s>>t;
if (s == cows[0])
ls[0].first += t;
else if (s == cows[1])
ls[1].first+=t;
else if (s == cows[2])
ls[2].first+=t;
else if (s == "Gertie")
ls[3].first+=t;
else if (s == "Annabelle")
ls[4].first+=t;
else if (s == "Maggie")
ls[5].first+=t;
else
ls[6].first+=t;
}
sort(ls.begin(),ls.end());
int minm = ls[0].first;
int index = 0;
while(ls.size()>0 and ls[index].first == minm){
ls.erase(ls.begin());
}
if(1<ls.size() and ls[index].first == ls[index+1].first){
fout<<"Tie\n";
}
else if(ls.size()==0){
fout<<"Tie\n";
}
else{
fout<<ls[0].second<<"\n";
}
}
|
/*
* Copyright [2017] <Bonn-Rhein-Sieg University>
*
* Author: Torsten Jandt
*
*/
#include <mir_planner_executor/actions/perceive/perceive_action.h>
PerceiveAction::PerceiveAction() : client_("/perceive_location_server") {
//client_.waitForServer();
}
bool PerceiveAction::run(std::string& robot, std::string& location) {
mir_yb_action_msgs::PerceiveLocationGoal goal;
goal.location = location;
actionlib::SimpleClientGoalState state = client_.sendGoalAndWait(goal, ros::Duration(150.0), ros::Duration(5.0));
if (state != actionlib::SimpleClientGoalState::StateEnum::SUCCEEDED) {
return false;
}
auto res = client_.getResult();
return res->success;
}
|
#ifndef CLUBE_H
#define CLUBE_H
#include<iostream>
#include<string.h>
using namespace std;
class Clube
{
string nome;
int pontos,vitorias,saldo,gols;
public:
Clube();
};
#endif
|
// Created on: 1994-09-15
// Created by: Bruno DUMORTIER
// Copyright (c) 1994-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 _ProjLib_ProjectOnSurface_HeaderFile
#define _ProjLib_ProjectOnSurface_HeaderFile
#include <Adaptor3d_Surface.hxx>
class Geom_BSplineCurve;
//! Project a curve on a surface. The result ( a 3D
//! Curve) will be an approximation
class ProjLib_ProjectOnSurface
{
public:
DEFINE_STANDARD_ALLOC
//! Create an empty projector.
Standard_EXPORT ProjLib_ProjectOnSurface();
//! Create a projector normally to the surface <S>.
Standard_EXPORT ProjLib_ProjectOnSurface(const Handle(Adaptor3d_Surface)& S);
Standard_EXPORT virtual ~ProjLib_ProjectOnSurface();
//! Set the Surface to <S>.
//! To compute the projection, you have to Load the Curve.
Standard_EXPORT void Load (const Handle(Adaptor3d_Surface)& S);
//! Compute the projection of the curve <C> on the Surface.
Standard_EXPORT void Load (const Handle(Adaptor3d_Curve)& C, const Standard_Real Tolerance);
Standard_Boolean IsDone() const { return myIsDone; }
Standard_EXPORT Handle(Geom_BSplineCurve) BSpline() const;
private:
Handle(Adaptor3d_Curve) myCurve;
Handle(Adaptor3d_Surface) mySurface;
Standard_Real myTolerance;
Standard_Boolean myIsDone;
Handle(Geom_BSplineCurve) myResult;
};
#endif // _ProjLib_ProjectOnSurface_HeaderFile
|
#pragma once
#include "proto/data_mail.pb.h"
using namespace std;
namespace pd = proto::data;
namespace nora {
namespace scene {
pd::mail mail_new_mail(uint64_t role, uint32_t pttid, const pd::dynamic_data& dynamic_data, const pd::event_array& extra_events);
pd::mail mail_new_mail(uint64_t role, const string& title, const string& content, const pd::dynamic_data& dynamic_data, const pd::event_array& events);
}
}
|
#pragma once
#include <memory>
#include <vector>
#include <map>
#include <windows.h>
#include <d2d1_2.h>
#include <dwrite_2.h>
#include "util.h"
#include "view.h"
#include "bitmap.h"
#include "board_screen.h"
COM_MAKE_PTR(ID2D1HwndRenderTarget);
COM_MAKE_PTR(ID2D1Factory);
COM_MAKE_PTR(IDWriteFactory);
COM_MAKE_PTR(IDWriteTextFormat);
struct render_target {
virtual void draw_line(D2D1::ColorF color, point<pixel> start, point<pixel> end) = 0;
virtual void draw_rect(D2D1::ColorF color, frame<pixel> frame) = 0;
virtual void draw_text(D2D1::ColorF color, frame<pixel> frame, std::wstring const &text) = 0;
virtual void draw_bitmap(bound_bitmap &bitmap, point<pixel> origin) = 0;
virtual void draw_bitmap(bitmap &bitmap, point<pixel> origin) = 0;
};
struct viewport_render_target : public render_target {
render_target ⌖
point<pixel> inset;
frame<pixel> my_frame;
viewport_render_target(render_target &t) : target(t) {}
void draw_line(D2D1::ColorF color, point<pixel> start, point<pixel> end);
void draw_rect(D2D1::ColorF color, frame<pixel> frame);
void draw_text(D2D1::ColorF color, frame<pixel> frame, std::wstring const &text);
void draw_bitmap(bound_bitmap &bitmap, point<pixel> origin);
void draw_bitmap(bitmap &bitmap, point<pixel> origin);
};
class d2d_render_target : public render_target {
ID2D1HwndRenderTargetPtr render_target_ptr;
IDWriteTextFormatPtr text_format;
std::map<bitmap*, bound_bitmap> cache;
public:
d2d_render_target(ID2D1HwndRenderTargetPtr, IDWriteTextFormatPtr);
void draw_line(D2D1::ColorF color, point<pixel> start, point<pixel> end);
void draw_rect(D2D1::ColorF color, frame<pixel> frame);
void draw_text(D2D1::ColorF color, frame<pixel> frame, std::wstring const &text);
void draw_bitmap(bound_bitmap &bitmap, point<pixel> origin);
void draw_bitmap(bitmap &bitmap, point<pixel> origin);
};
class main_window {
static LRESULT CALLBACK window_proc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam);
ID2D1FactoryPtr d2d_factory;
IDWriteFactoryPtr dwrite_factory;
std::vector<std::shared_ptr<view>> views;
std::unique_ptr<render_target> target;
HWND hwnd;
public:
ID2D1HwndRenderTargetPtr render_target;
IDWriteTextFormatPtr text_format;
boost::optional<view&> screen;
static void register_window();
main_window();
void show();
void update();
void add_view(std::shared_ptr<view>);
HWND handle() { return hwnd; }
// Dispatched
LRESULT resize(UINT32 width, UINT32 height);
LRESULT display_changed();
LRESULT paint();
LRESULT destroy();
LRESULT clicked(mouse_button, POINTS point);
};
|
#include "Writefile.h"
#include <iostream>
std::string Writefile::execute(std::string & text) {
std::ofstream fout(outputFile);
if (!fout) {
//colorMessages::RedError(" Can't open file " + outputFile + "!");
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hConsole, 12); // Red Color
std::cout << "[Error]:";
SetConsoleTextAttribute(hConsole, 15); // White Color
std::cout << " Can't open file " << outputFile << "!" << std::endl;
exit(0);
}
fout << text;
std::string result = "";
return result;
}
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int even = 0;
int num;
for(int i = 0; i < 5; i++)
{
cin>>num;
if(num % 2 == 0)
{
even ++;
}
}
cout<<even<<" valores pares\n";
return 0;
}
|
#include "stdafx.h"
bool Core::OnInit()
{
if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
return false;
}
moving = false;
lastMoved = false;
mainWindow = SDL_CreateWindow("Core Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1136, 640, SDL_WINDOW_SHOWN);
mainRenderer = SDL_CreateRenderer(mainWindow, -1, SDL_RENDERER_ACCELERATED);
srand((unsigned)time(NULL));
cDAT assets;
char* buffer;
assets.Read("assets.dat");
/*
std::ifstream infile("assets.txt");
std::string a;
while (infile >> a)
{
buffer = assets.GetFile(a);
}
*/
buffer = assets.GetFile("background.png");
SDL_RWops *rw = SDL_RWFromMem(buffer, assets.GetFileSize("background.png"));
loadingSurface = IMG_Load_RW(rw, 1);
background = SDL_CreateTextureFromSurface(mainRenderer, loadingSurface);
buffer = assets.GetFile("grid.png");
rw = SDL_RWFromMem(buffer, assets.GetFileSize("grid.png"));
loadingSurface = IMG_Load_RW(rw, 1);
tableD.x = 15;
tableD.y = 20;
tableD.h = loadingSurface->h;
tableD.w = loadingSurface->w;
tableSizeX = loadingSurface->w;
tableSizeY = loadingSurface->h;
table = SDL_CreateTextureFromSurface(mainRenderer, loadingSurface);
buffer = assets.GetFile("pont.png");
rw = SDL_RWFromMem(buffer, assets.GetFileSize("pont.png"));
loadingSurface = IMG_Load_RW(rw, 1);
pointsD.x = 15;
pointsD.y = 580;
pointsD.h = loadingSurface->h;
pointsD.w = loadingSurface->w;
points = SDL_CreateTextureFromSurface(mainRenderer, loadingSurface);
buffer = assets.GetFile("timer.png");
rw = SDL_RWFromMem(buffer, assets.GetFileSize("timer.png"));
loadingSurface = IMG_Load_RW(rw, 1);
timerD.x = 820;
timerD.y = 21;
timerD.h = loadingSurface->h;
timerD.w = loadingSurface->w;
timer = SDL_CreateTextureFromSurface(mainRenderer, loadingSurface);
buffer = assets.GetFile("cs01.png");
rw = SDL_RWFromMem(buffer, assets.GetFileSize("cs01.png"));
loadingSurface = IMG_Load_RW(rw, 1);
girlD.x = 800;
girlD.y = 10;
girlD.h = loadingSurface->h;
girlD.w = loadingSurface->w;
girl = SDL_CreateTextureFromSurface(mainRenderer, loadingSurface);
std::stringstream buff;
for (int i = 0; i < 10; i++)
{
buff << "i" << (i+1) << ".png";
buffer = assets.GetFile(buff.str());
buffer = assets.GetFile(buff.str());
rw = SDL_RWFromMem(buffer, assets.GetFileSize(buff.str()));
loadingSurface = IMG_Load_RW(rw, 1);
buff.str(std::string());
runeTex[i] = SDL_CreateTextureFromSurface(mainRenderer, loadingSurface);
}
runeSizeX = loadingSurface->w;
runeSizeY = loadingSurface->h;
for (int i = 0; i < 45; i++)
{
runes[i] = rand() % 10;
runePos[i].x = 15 + 10 + ((i % 9) * (runeSizeX - 25)); // table start position + 10
runePos[i].y = 20 + 10 + ((i / 9) * (runeSizeY + 2));
runePos[i].w = runeSizeX;
runePos[i].h = runeSizeY;
movingRunePos[i].x = 0;
movingRunePos[i].y = 0;
movingRunePos[i].w = runeSizeX;
movingRunePos[i].h = runeSizeY;
if (i % 2 == ((i / 9) % 2 == 0 ? 1 : 0)) // cserรฉlgetjรผk soronkรฉnt, hogy melyik oszlopot kell sรผllyeszteni
{
runePos[i].y += runeSizeY / 2;
}
}
/* mezลk:
120 szรฉles
100 magas
25-25 kรฉt oldalt az รกtfedรฉs
10 px fentrลl a szรผnet
10 px balrรณl a szรผnet
itt kezdลdik az elsล mezล
minden kรถvetkezล szรฉlessรฉg-15 ben kezd
minden pรกros egy magassรกgban
minden pรกratlan magassรกg/2-ben
9x5 = 45
0. item: 0. sor 0. oszlop
i % 9 = oszlop
i / 9 = sor
x:
minden sor elso tagja 0+10px
a tobbi (i-1)->width - 12.5
y:
elso sor: 10px
tobbi: sor*(i->height)
if i % 2 = 1 then height/2
i = 13, mit tudunk?
13 / 9 = 1. sor
13 % 9 = 5. oszlop (4-1)
*/
return true;
}
void Core::OnEvent(SDL_Event* event)
{
if(event->type == SDL_QUIT) {
running = false;
}
else if(event->type == SDL_MOUSEBUTTONDOWN)
{
//std::cout << "Current event type: MOUSE_BUTTON_DOWN \n";
// std::cout << event->button.x << ", " << event->button.y << "\n";
// std::cout << GetClickedRune(event->button.x, event->button.y) << "\n";
StartDrag(GetClickedRune(event->button.x, event->button.y));
}
else if(event->type == SDL_MOUSEBUTTONUP)
{
//std::cout << "Current event type: MOUSE_BUTTON_UP \n";
EndDrag(GetClickedRune(event->button.x, event->button.y));
}
else if(event->type == SDL_MOUSEMOTION)
{
// std::cout << "Current event type: MOUSE_MOTION \n";
}
}
void Core::OnLoop()
{
}
void Core::OnRender()
{
SDL_RenderCopy(mainRenderer, background, NULL, NULL);
SDL_RenderCopy(mainRenderer, table, NULL, &tableD);
SDL_RenderCopy(mainRenderer, points, NULL, &pointsD);
SDL_RenderCopy(mainRenderer, timer, NULL, &timerD);
SDL_RenderCopy(mainRenderer, girl, NULL, &girlD);
for (int i = 0; i < 45; i++)
{
if (runes[i] == -1) continue;
if (runeTargetSteps[i] >= 0)
{
moving = true;
lastMoved = true;
//std::cout << "Moving " << i << " at " << movingRunePos[i].x << " and " << movingRunePos[i].y << " from " << runePos[i].x << " and " << runePos[i].y << "\n";
movingRunePos[i].x += runeTargetX[i];
movingRunePos[i].y += runeTargetY[i];
runeTargetSteps[i] -= 1;
SDL_RenderCopy(mainRenderer, runeTex[runes[i]], NULL, &movingRunePos[i]);
}
else
{
SDL_RenderCopy(mainRenderer, runeTex[runes[i]], NULL, &runePos[i]);
}
}
if (moving != lastMoved) AnimationReady();
lastMoved = moving;
moving = false;
SDL_RenderPresent(mainRenderer);
}
void Core::OnCleanup()
{
/*
set all surface and other pointers to NULL
*/
SDL_DestroyRenderer(mainRenderer);
SDL_DestroyWindow(mainWindow);
SDL_Quit();
}
Core::Core()
{
running = true;
}
int Core::OnExecute() {
if(OnInit() == false) {
return -1;
}
float frameRate = 60;
float ticksToSkip = 1000 / frameRate;
int lastTick = SDL_GetTicks();
int tickCount = 0;
SDL_Event Event;
while(running) {
while(SDL_PollEvent(&Event)) {
OnEvent(&Event);
}
// frame-rate control
tickCount = SDL_GetTicks();
if (tickCount - lastTick < ticksToSkip) continue;
lastTick = tickCount;
OnLoop();
OnRender();
SDL_Delay(1);
}
OnCleanup();
return 0;
}
bool Core::CheckMatches(int index)
{
std::cout <<"Checking for matchis at " << index << ", value: " << runes[index] << "\n";
for (int i = 0; i < 45; i++)
{
std::cout << i << ": " << runes[i] << ", ";
}
std::cout << "\n";
bool result = false;
int matches = 0;
// fรผggลleges csekk felfelรฉ
if (index >= 9 && runes[index] == runes[index - 9]) // nem a legfelsล sorban van
{
std::cout << "Match found in kulso " << index << " and index - 9\n";
matches++;
clearRunes.push_back(index - 9);
if (index >= 9 * 2 && runes[index] == runes[index - (9 * 2)]) // nem is az elsลben
{
std::cout << "Match found in belso " << index << " and index - 9 * 2\n";
matches++;
clearRunes.push_back(index - 9 * 2);
}
}
// fรผggลleges csekk lefelรฉ
if (index < 9 * 4 && runes[index] == runes[index + 9])
{
std::cout << "Match found in kulso " << index << " and index + 9\n";
matches++;
clearRunes.push_back(index + 9);
if (index < 9 * 3 && runes[index] == runes[index + (9 * 2)])
{
std::cout << "Match found in belso " << index << " and index + 9 * 2\n";
matches++;
clearRunes.push_back(index + 9 * 2);
}
}
// csekk found !
if (matches >= 2)
{
// collapse animation clearRunes รถsszes elemรฉt eltรผntetjรผk รฉs score-ozunk
clearRunes.push_back(index);
ClearMatchedRunes();
result = true;
}
if (startIndex % 2 == ((startIndex / 9) % 2 == 0 ? 1 : 0))
{
// ha letolt kis runรกt csekkolunk
matches = 0;
clearRunes.clear();
// nem a jobb szรฉlรฉn van
if ((index % 9 < 8) && runes[index] == runes[index + 1])
{
std::cout << "Match found in kulso " << index << " and index + 1\n";
matches++;
clearRunes.push_back(index + 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 < 7) && index >= 9 && runes[index] == runes[index - 9 + 2])
{
std::cout << "Match found in belso " << index << " and index - 9 + 2\n";
matches++;
clearRunes.push_back(index - 9 + 2);
}
}
// nem a bal szรฉlรฉn van
if (index < 9 * 4 && (index % 9 > 0) && runes[index] == runes[index + 9 - 1])
{
std::cout << "Match found in kulso " << index << " and index + 9 - 1\n";
matches++;
clearRunes.push_back(index + 9 - 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 > 1) && runes[index] == runes[index + 9 - 2])
{
std::cout << "Match found in belso " << index << " and index + 9 - 2\n";
matches++;
clearRunes.push_back(index + 9 - 2);
}
}
// csekk found !
if (matches >= 2)
{
// collapse animation clearRunes รถsszes elemรฉt eltรผntetjรผk รฉs score-ozunk
clearRunes.push_back(index);
ClearMatchedRunes();
result = true;
}
// masik atlot is megnezzuk
matches = 0;
clearRunes.clear();
// nem a jobb szรฉlรฉn van
if (index < 9 * 4 && (index % 9 < 8) && runes[index] == runes[index + 9 + 1])
{
std::cout << "Match found in kulso " << index << " and index + 9 + 1\n";
matches++;
clearRunes.push_back(index + 9 + 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 < 7) && runes[index] == runes[index + 9 + 2])
{
std::cout << "Match found in belso " << index << " and index + 9 + 2\n";
matches++;
clearRunes.push_back(index + 9 + 2);
}
}
// nem a bal szรฉlรฉn van
if ((index % 9 > 0) && runes[index] == runes[index - 1])
{
std::cout << "Match found in kulso " << index << " and index - 1\n";
matches++;
clearRunes.push_back(index - 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 > 1) && index >= 9 && runes[index] == runes[index - 9 - 2])
{
std::cout << "Match found in belso " << index << " and index - 9 - 2\n";
matches++;
clearRunes.push_back(index - 9 - 2);
}
}
// csekk found !
if (matches >= 2)
{
// collapse animation clearRunes รถsszes elemรฉt eltรผntetjรผk รฉs score-ozunk
clearRunes.push_back(index);
ClearMatchedRunes();
result = true;
}
}
else
{
// ha letolt kis runรกt csekkolunk
matches = 0;
clearRunes.clear();
// nem a jobb szรฉlรฉn van
if (index >= 9 && (index % 9 < 8) && runes[index] == runes[index - 9 + 1])
{
std::cout << "Match found in kulso " << index << " and index - 9 + 1\n";
matches++;
clearRunes.push_back(index - 9 + 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 < 7) && runes[index] == runes[index - 9 + 2])
{
std::cout << "Match found in belso " << index << " and index - 9 + 2\n";
matches++;
clearRunes.push_back(index - 9 + 2);
}
}
// nem a bal szรฉlรฉn van
if ((index % 9 > 0) && runes[index] == runes[index - 1])
{
std::cout << "Match found in kulso " << index << " and index - 1\n";
matches++;
clearRunes.push_back(index - 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 > 1) && index < 9 * 4 && runes[index] == runes[index + 9 - 2])
{
std::cout << "Match found in belso " << index << " and index + 9 - 2\n";
matches++;
clearRunes.push_back(index + 9 - 2);
}
}
// csekk found !
if (matches >= 2)
{
// collapse animation clearRunes รถsszes elemรฉt eltรผntetjรผk รฉs score-ozunk
clearRunes.push_back(index);
ClearMatchedRunes();
result = true;
}
// masik atlo
matches = 0;
clearRunes.clear();
// nem a jobb szรฉlรฉn van
if (index >= 9 && (index % 9 > 0) && runes[index] == runes[index - 9 - 1])
{
std::cout << "Match found in kulso " << index << " and index - 9 - 1\n";
matches++;
clearRunes.push_back(index - 9 - 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 > 1) && runes[index] == runes[index - 9 - 2])
{
std::cout << "Match found in belso " << index << " and index - 9 - 2\n";
matches++;
clearRunes.push_back(index - 9 - 2);
}
}
// nem a bal szรฉlรฉn van
if ((index % 9 < 8) && runes[index] == runes[index + 1])
{
std::cout << "Match found in kulso " << index << " and index + 1\n";
matches++;
clearRunes.push_back(index + 1);
// รฉs nem is eggyel a szรฉle elลtt
if ((index % 9 < 7) && index < 9 * 4 && runes[index] == runes[index + 9 + 2])
{
std::cout << "Match found in belso " << index << " and index + 9 + 2\n";
matches++;
clearRunes.push_back(index + 9 + 2);
}
}
// csekk found !
if (matches >= 2)
{
// collapse animation clearRunes รถsszes elemรฉt eltรผntetjรผk รฉs score-ozunk
//clearRunes.clear();
clearRunes.push_back(index);
ClearMatchedRunes();
result = true;
}
}
std::cout << "Match found: " << result << "\n";
return result;
}
void Core::MoveRune(int source, int dest)
{
runes[dest] = runes[source];
}
int Core::GetClickedRune(int mouseX, int mouseY)
{
int clicked;
int column = (mouseX - 15 - 10) / (runeSizeX - 25);
int row = ((mouseY - 20 - 10) - (column % 2 == 0 ? 0 : runeSizeY / 2)) / (runeSizeY);
//std::cout << row << " and " << column << "\n";
clicked = (row * 9) + (column);
return clicked;
}
void Core::StartDrag(int index)
{
if (index < 45 || index >= 0)
{
startIndex = index;
}
}
void Core::EndDrag(int index)
{
if (startIndex == -1) return;
if (index < 45 || index >= 0)
{
endIndex = index;
}
//std::cout << "Start: " << startIndex << ", end: " << endIndex << "\n";
if (startIndex + 9 == endIndex || startIndex - 9 == endIndex || startIndex + 1 == endIndex || startIndex - 1 == endIndex
|| ((startIndex % 2 == ((startIndex / 9) % 2 == 0 ? 1 : 0)) && (startIndex + 9 + 1 == endIndex || startIndex + 9 - 1 == endIndex))
|| ((startIndex % 2 == ((startIndex / 9) % 2 == 0 ? 0 : 1)) && (startIndex - 9 + 1 == endIndex || startIndex - 9 - 1 == endIndex))
)
{
animationState = 1;
//SetRuneTarget(endIndex, runePos[startIndex].x, runePos[startIndex].y, runePos[endIndex].x, runePos[endIndex].y, 10);
//SetRuneTarget(startIndex, runePos[endIndex].x, runePos[endIndex].y, runePos[startIndex].x, runePos[startIndex].y, 10);
//std::cout << "Changing " << startIndex << " (" << runes[startIndex] << ") to " << endIndex << " (" << runes[endIndex] << ")\n";
int tempVal = runes[startIndex];
runes[startIndex] = runes[endIndex];
runes[endIndex] = tempVal;
FlipRunes(endIndex, startIndex, 60);
//std::cout << "After Changing " << startIndex << " (" << runes[startIndex] << ") to " << endIndex << " (" << runes[endIndex] << ")\n";
match1 = CheckMatches(startIndex);
match2 = CheckMatches(endIndex);
}
}
void Core::MatchResults()
{
if (match1 == match2 && match2 == false)
{
std::cout <<"MatchResults false\n";
//SetRuneTarget(endIndex, runePos[startIndex].x, runePos[startIndex].y, runePos[endIndex].x, runePos[endIndex].y, 10);
//SetRuneTarget(startIndex, runePos[endIndex].x, runePos[endIndex].y, runePos[startIndex].x, runePos[startIndex].y, 10);
int tempVal = runes[startIndex];
runes[startIndex] = runes[endIndex];
runes[endIndex] = tempVal;
FlipRunes(startIndex, endIndex, 60);
animationState = 3;
}
else
{
std::cout <<"MatchResults true\n";
animationState = 2;
MoveRunes();
}
startIndex = -1;
endIndex = -1;
};
void Core::ClearMatchedRunes()
{
for (int i = clearRunes.size(); i > 0; i--)
{
runes[clearRunes.at(i-1)] = -1;
clearRunes.pop_back();
}
}
void Core::MoveRunes()
{
for (int i = 44; i >= 0; i--)
{
if (runes[i] == -1)
{
int index = FindNextRune(i);
if (index != -1)
{
runes[i] = runes[index];
runes[index] = -1;
SetRuneTarget(i, runePos[index].x, runePos[index].y, runePos[i].x, runePos[i].y, 50);//(i - index) / 9 * 1
}
}
}
for (int i = 0; i < 9; i++)
{
if (runes[i] == -1)
{
int spawn = 1;
for (int j = 4; j >= 0; j--)
{
if (runes[i + (j * 9)] == -1)
{
SpawnRunes(i + j * 9, spawn);
spawn++;
std::cout << "Spawning new block to column " << i % 9 << ", index: " << (i + j * 9) << "\n";
}
}
//SpawnRunes(i, spawn);
std::cout << "Spawning " << spawn << " new blocks to column " << i % 9 << "\n";
}
}
}
int Core::FindNextRune(int index)
{
if (index >= 9)
{
if (runes[index - 9] == -1)
{
return FindNextRune(index - 9);
}
else
{
//index = FindNextRune(index - 9);
return (index - 9);
}
}
return -1;
}
void Core::SpawnRunes(int index, int count)
{
runes[index] = rand() % 10;
int dist = (runePos[index].y / runeSizeY) + 1;
int startPos = 20 + 10 - runeSizeY * count;
if (index % 2 == ((index / 9) % 2 == 0 ? 1 : 0))
{
startPos += runeSizeY / 2;
}
SetRuneTarget(index, runePos[index].x, startPos, runePos[index].x, runePos[index].y, 50 * count);
}
void Core::SetRuneTarget(int index, int startX, int startY, int targetX, int targetY, int speed)
{
std::cout << "Moving " << index << " to " << targetX << ", " << targetY << " from " << startX << ", " << startY << "\n";
//speed = 1 esetรฉn azt tudom, hogy 60 frame alatt tesz meg 1 sizeY-t vagy sizeX-t => speed = 60
// ha speed = 0.5 akkor => 30
//(runeSizeY / 50) = 1;
//runeTargetX[index] = (speed == 60 ? 0 : (targetX - startX) / speed);
runeTargetX[index] = 0;
//runeTargetY[index] = (speed == 60 ? 2 : (targetY - startY) / speed);
runeTargetY[index] = 2;
movingRunePos[index].x = startX;
movingRunePos[index].y = startY;
//runeTargetSteps[index] = (speed == 60 ? ((targetY - startY) / runeSizeY) * 50 : speed);
runeTargetSteps[index] = speed;
}
void Core::FlipRunes(int index1, int index2, int speed)
{
runeTargetX[index1] = (runePos[index2].x - runePos[index1].x) / speed;
runeTargetY[index1] = (runePos[index2].y - runePos[index1].y) / speed;
movingRunePos[index1].x = runePos[index1].x;
movingRunePos[index1].y = runePos[index1].y;
runeTargetSteps[index1] = speed;
runeTargetX[index2] = (runePos[index1].x - runePos[index2].x) / speed;
runeTargetY[index2] = (runePos[index1].y - runePos[index2].y) / speed;
movingRunePos[index2].x = runePos[index2].x;
movingRunePos[index2].y = runePos[index2].y;
runeTargetSteps[index2] = speed;
}
void Core::AnimationReady()
{
std::cout <<"Ready: " << animationState << "\n";
switch (animationState)
{
case 1:
MatchResults();
break;
}
}
|
//*-- Author : Stephen Wood 20-Apr-2012
//////////////////////////////////////////////////////////////////////////
//
// THcHallCSpectrometer
//
// A standard Hall C spectrometer.
// Contains no standard detectors,
// May add hodoscope
//
// The usual name of this object is either "H", "S", or "P"
// for HMS, SOS, or suPerHMS respectively
//
// Defines the functions FindVertices() and TrackCalc(), which are common
// to both the LeftHRS and the RightHRS.
//
// Special configurations of the HRS (e.g. more detectors, different
// detectors) can be supported in on e of three ways:
//
// 1. Use the AddDetector() method to include a new detector
// in this apparatus. The detector will be decoded properly,
// and its variables will be available for cuts and histograms.
// Its processing methods will also be called by the generic Reconstruct()
// algorithm implemented in THaSpectrometer::Reconstruct() and should
// be correctly handled if the detector class follows the standard
// interface design.
//
// 2. Write a derived class that creates the detector in the
// constructor. Write a new Reconstruct() method or extend the existing
// one if necessary.
//
// 3. Write a new class inheriting from THaSpectrometer, using this
// class as an example. This is appropriate if your HRS
// configuration has fewer or different detectors than the
// standard HRS. (It might not be sensible to provide a RemoveDetector()
// method since Reconstruct() relies on the presence of the
// standard detectors to some extent.)
//
// For timing calculations, S1 is treated as the scintillator at the
// 'reference distance', corresponding to the pathlength correction
// matrix.
//
//////////////////////////////////////////////////////////////////////////
#include "THcHallCSpectrometer.h"
#include "THaTrackingDetector.h"
#include "THaTrack.h"
#include "THaTrackProj.h"
#include "THaTriggerTime.h"
#include "TMath.h"
#include "TList.h"
#include "TList.h"
#include "TMath.h"
#ifdef WITH_DEBUG
#include <iostream>
#endif
using namespace std;
//_____________________________________________________________________________
THcHallCSpectrometer::THcHallCSpectrometer( const char* name, const char* description ) :
THaSpectrometer( name, description )
{
// Constructor. Defines the standard detectors for the HRS.
// AddDetector( new THaTriggerTime("trg","Trigger-based time offset"));
//sc_ref = static_cast<THaScintillator*>(GetDetector("s1"));
SetTrSorting(kFALSE);
}
//_____________________________________________________________________________
THcHallCSpectrometer::~THcHallCSpectrometer()
{
// Destructor
}
//_____________________________________________________________________________
Bool_t THcHallCSpectrometer::SetTrSorting( Bool_t set )
{
if( set )
fProperties |= kSortTracks;
else
fProperties &= ~kSortTracks;
return set;
}
//_____________________________________________________________________________
Bool_t THcHallCSpectrometer::GetTrSorting() const
{
return ((fProperties & kSortTracks) != 0);
}
//_____________________________________________________________________________
Int_t THcHallCSpectrometer::FindVertices( TClonesArray& tracks )
{
// Reconstruct target coordinates for all tracks found in the focal plane.
TIter nextTrack( fTrackingDetectors );
nextTrack.Reset();
while( THaTrackingDetector* theTrackDetector =
static_cast<THaTrackingDetector*>( nextTrack() )) {
#ifdef WITH_DEBUG
if( fDebug>1 ) cout << "Call FineTrack() for "
<< theTrackDetector->GetName() << "... ";
#endif
theTrackDetector->FindVertices( tracks );
#ifdef WITH_DEBUG
if( fDebug>1 ) cout << "done.\n";
#endif
}
// If enabled, sort the tracks by chi2/ndof
if( GetTrSorting() )
fTracks->Sort();
// Find the "Golden Track".
if( GetNTracks() > 0 ) {
// Select first track in the array. If there is more than one track
// and track sorting is enabled, then this is the best fit track
// (smallest chi2/ndof). Otherwise, it is the track with the best
// geometrical match (smallest residuals) between the U/V clusters
// in the upper and lower VDCs (old behavior).
//
// Chi2/dof is a well-defined quantity, and the track selected in this
// way is immediately physically meaningful. The geometrical match
// criterion is mathematically less well defined and not usually used
// in track reconstruction. Hence, chi2 sortiing is preferable, albeit
// obviously slower.
fGoldenTrack = static_cast<THaTrack*>( fTracks->At(0) );
fTrkIfo = *fGoldenTrack;
fTrk = fGoldenTrack;
} else
fGoldenTrack = NULL;
return 0;
}
//_____________________________________________________________________________
Int_t THcHallCSpectrometer::TrackCalc()
{
// Additioal track calculations. At present, we only calculate beta here.
return TrackTimes( fTracks );
}
//_____________________________________________________________________________
Int_t THcHallCSpectrometer::TrackTimes( TClonesArray* Tracks ) {
// Do the actual track-timing (beta) calculation.
// Use multiple scintillators to average together and get "best" time at S1.
//
// To be useful, a meaningful timing resolution should be assigned
// to each Scintillator object (part of the database).
if ( !Tracks ) return -1;
THaTrack *track=0;
Int_t ntrack = GetNTracks();
// linear regression to: t = t0 + pathl/(beta*c)
// where t0 is the time of the track at the reference plane (sc_ref).
// t0 and beta are solved for.
//
#if 0
for ( Int_t i=0; i < ntrack; i++ ) {
track = static_cast<THaTrack*>(Tracks->At(i));
THaTrackProj* tr_ref = static_cast<THaTrackProj*>
(sc_ref->GetTrackHits()->At(i));
Double_t pathlref = tr_ref->GetPathLen();
Double_t wgt_sum=0.,wx2=0.,wx=0.,wxy=0.,wy=0.;
Int_t ncnt=0;
// linear regression to get beta and time at ref.
TIter nextSc( fNonTrackingDetectors );
THaNonTrackingDetector *det;
while ( ( det = static_cast<THaNonTrackingDetector*>(nextSc()) ) ) {
THaScintillator *sc = dynamic_cast<THaScintillator*>(det);
if ( !sc ) continue;
const THaTrackProj *trh = static_cast<THaTrackProj*>(sc->GetTrackHits()->At(i));
Int_t pad = trh->GetChannel();
if (pad<0) continue;
Double_t pathl = (trh->GetPathLen()-pathlref);
Double_t time = (sc->GetTimes())[pad];
Double_t wgt = (sc->GetTuncer())[pad];
if (pathl>.5*kBig || time>.5*kBig) continue;
if (wgt>0) wgt = 1./(wgt*wgt);
else continue;
wgt_sum += wgt;
wx2 += wgt*pathl*pathl;
wx += wgt*pathl;
wxy += wgt*pathl*time;
wy += wgt*time;
ncnt++;
}
Double_t beta = kBig;
Double_t dbeta = kBig;
Double_t time = kBig;
Double_t dt = kBig;
Double_t delta = wgt_sum*wx2-wx*wx;
if (delta != 0.) {
time = (wx2*wy-wx*wxy)/delta;
dt = TMath::Sqrt(wx2/delta);
Double_t invbeta = (wgt_sum*wxy-wx*wy)/delta;
if (invbeta != 0.) {
#if ROOT_VERSION_CODE >= ROOT_VERSION(3,4,0)
Double_t c = TMath::C();
#else
Double_t c = 2.99792458e8;
#endif
beta = 1./(c*invbeta);
dbeta = TMath::Sqrt(wgt_sum/delta)/(c*invbeta*invbeta);
}
}
track->SetBeta(beta);
track->SetdBeta(dbeta);
track->SetTime(time);
track->SetdTime(dt);
}
#endif
return 0;
}
//_____________________________________________________________________________
ClassImp(THcHallCSpectrometer)
|
#include <iostream>
#include <conio.h>
#include <stdio.h>
#define MAX 100
using namespace std;
short checkUnique1(char input[],int n)
{
int hashTable[300]={0},i;
for(i=0;i<n;i++)
{
if(hashTable[input[i]]==0)
hashTable[input[i]]++;
else return 0;
}
return 1;
}
short checkUnique2(char input[],int n)
{
char c;
int i,j;
for(i=0;i<n;i++)
{
c=input[i];
for(j=i+1;j<n;j++)
{
if(c==input[j])
return 0;
}
}
return 1;
}
int main()
{
char input[MAX];
int n,i;
cout<<"Enter a string: ";
cin.getline(input,MAX);
for(n=0;input[n]!=0;n++);
n++;
if(checkUnique1(input,n))
cout<<"String contains unique characters!"<<endl;
else cout<<"String does not contain unique characters!"<<endl;
}
|
#ifndef _EUI_ANIMATION_HELPER__H__
#define _EUI_ANIMATION_HELPER__H__
#include <vector>
namespace UiLib {
class IAnimationCallback
{
public:
virtual void OnFrame() = 0;
};
class CAnimation
{
#pragma pack(1) // turn byte alignment on
enum GIFBlockTypes
{
BLOCK_UNKNOWN,
BLOCK_APPEXT,
BLOCK_COMMEXT,
BLOCK_CONTROLEXT,
BLOCK_PLAINTEXT,
BLOCK_IMAGE,
BLOCK_TRAILER
};
enum ControlExtValues // graphic control extension packed field values
{
GCX_PACKED_DISPOSAL, // disposal method
GCX_PACKED_USERINPUT,
GCX_PACKED_TRANSPCOLOR
};
enum LSDPackedValues // logical screen descriptor packed field values
{
LSD_PACKED_GLOBALCT,
LSD_PACKED_CRESOLUTION,
LSD_PACKED_SORT,
LSD_PACKED_GLOBALCTSIZE
};
enum IDPackedValues // image descriptor packed field values
{
ID_PACKED_LOCALCT,
ID_PACKED_INTERLACE,
ID_PACKED_SORT,
ID_PACKED_LOCALCTSIZE
};
struct TGIFHeader // GIF header
{
char m_cSignature[3]; // Signature - Identifies the GIF Data Stream
// This field contains the fixed value 'GIF'
char m_cVersion[3]; // Version number. May be one of the following:
// "87a" or "89a"
};
struct TGIFLSDescriptor // Logical Screen Descriptor
{
WORD m_wWidth; // 2 bytes. Logical screen width
WORD m_wHeight; // 2 bytes. Logical screen height
unsigned char m_cPacked; // packed field
unsigned char m_cBkIndex; // 1 byte. Background color index
unsigned char m_cPixelAspect; // 1 byte. Pixel aspect ratio
inline int GetPackedValue(enum LSDPackedValues Value);
};
struct TGIFAppExtension // application extension block
{
unsigned char m_cExtIntroducer; // extension introducer (0x21)
unsigned char m_cExtLabel; // app. extension label (0xFF)
unsigned char m_cBlockSize; // fixed value of 11
char m_cAppIdentifier[8]; // application identifier
char m_cAppAuth[3]; // application authentication code
};
struct TGIFControlExt // graphic control extension block
{
unsigned char m_cExtIntroducer; // extension introducer (0x21)
unsigned char m_cControlLabel; // control extension label (0xF9)
unsigned char m_cBlockSize; // fixed value of 4
unsigned char m_cPacked; // packed field
WORD m_wDelayTime; // delay time
unsigned char m_cTColorIndex; // transparent color index
unsigned char m_cBlockTerm; // block terminator (0x00)
inline int GetPackedValue(enum ControlExtValues Value);
};
struct TGIFCommentExt // comment extension block
{
unsigned char m_cExtIntroducer; // extension introducer (0x21)
unsigned char m_cCommentLabel; // comment extension label (0xFE)
};
struct TGIFPlainTextExt // plain text extension block
{
unsigned char m_cExtIntroducer; // extension introducer (0x21)
unsigned char m_cPlainTextLabel; // text extension label (0x01)
unsigned char m_cBlockSize; // fixed value of 12
WORD m_wLeftPos; // text grid left position
WORD m_wTopPos; // text grid top position
WORD m_wGridWidth; // text grid width
WORD m_wGridHeight; // text grid height
unsigned char m_cCellWidth; // character cell width
unsigned char m_cCellHeight; // character cell height
unsigned char m_cFgColor; // text foreground color index
unsigned char m_cBkColor; // text background color index
};
struct TGIFImageDescriptor // image descriptor block
{
unsigned char m_cImageSeparator; // image separator byte (0x2C)
WORD m_wLeftPos; // image left position
WORD m_wTopPos; // image top position
WORD m_wWidth; // image width
WORD m_wHeight; // image height
unsigned char m_cPacked; // packed field
inline int GetPackedValue(enum IDPackedValues Value);
};
#pragma pack() // turn byte alignment off
struct TFrame // structure that keeps a single frame info
{
TImageInfo* m_pImage; // pointer to one frame image
SIZE m_frameSize;
SIZE m_frameOffset;
UINT m_nDelay; // delay (in 1/100s of a second)
UINT m_nDisposal; // disposal method
};
typedef std::vector<TFrame> VTFRAME;
public:
CAnimation(IAnimationCallback* pCallback);
~CAnimation();
const TImageInfo* GetCurImage();
// loads a picture from a file or a program resource
const TImageInfo* LoadGIF(LPCTSTR bitmap, LPCTSTR type = NULL, DWORD mask = 0);
// loads a picture from a memory block (allocated by malloc)
// Warning: this function DOES NOT free the memory, pointed to by pData
const TImageInfo* LoadGIF(const LPBYTE pData, DWORD dwSize, DWORD mask = 0);
SIZE GetSize() const;
int GetFrameCount() const;
COLORREF GetBkColor() const;
bool Play(); // play the animation (just change m_nCurrFrame)
void Stop(); // stops animation
void UnLoad(); // stops animation plus releases all resources
bool IsPlaying() const;
protected:
int GetNextBlockLen() const;
BOOL SkipNextBlock();
BOOL SkipNextGraphicBlock();
void ResetDataPointer();
enum GIFBlockTypes GetNextBlock() const;
UINT GetSubBlocksLen(UINT nStartingOffset) const;
// create a single-frame GIF from one of frames, and put in a memeory block (allocated by malloc)
// Warning: we should free the memeory block, pointed to by return value
LPBYTE GetNextGraphicBlock(UINT* pBlockLen, UINT* pDelay, SIZE* pBlockSize, SIZE* pBlockOffset, UINT* pDisposal);
#ifdef GIF_TRACING
void EnumGIFBlocks();
void WriteDataOnDisk(CString szFileName, HGLOBAL hData, DWORD dwSize);
#endif // GIF_TRACING
private:
unsigned char* m_pRawData; // ่งฃๆๆถ็จไบๆๅญๅจ็ปๆไปถๆฐๆฎ ่งฃๆ็ปๆๅ้็ฝฎๆ ๆ
UINT m_nDataSize; // GIFๆไปถๅคงๅฐ
TGIFHeader* m_pGIFHeader; // GIFๆไปถๅคด
TGIFLSDescriptor* m_pGIFLSDescriptor; // ้ป่พๅฑๅนๆ ่ฏ็ฌฆ
UINT m_nGlobalCTSize; // ๅ
จๅฑ้ข่ฒๅ่กจๅคงๅฐ
SIZE m_PictureSize; // ๅพๅๅฐบๅฏธ
COLORREF m_clrBackground; // ่ๆฏ่ฒ
volatile long m_nCurrFrame; // ๅฝๅๅธง็ดขๅผๅผ
UINT m_nCurrOffset; // ๅ่ฏปๅๅ็งป้
VTFRAME* m_pvFrames; // ๅธงๆฐ็ป
HANDLE m_hThread;
HANDLE m_hDrawEvent; // ็ปๅพไบไปถ ไปฃ่กจๅฝๅๅธงๅทฒ็ป่ขซ่ฏปๅ็จไบ็ปๅถ ๏ผ้ฒๆญข็ฑไบๆธฒๆ้ๅบฆๆ
ข่ๅฏผ่ด่ทณๅธง๏ผ
volatile bool m_bExitThread;
IAnimationCallback* m_pCallback;
DWORD ThreadAnimation();
static DWORD __stdcall _ThreadAnimation(LPVOID pParam);
};
class CDuiAniHelper : public IAnimationCallback
{
public:
virtual ~CDuiAniHelper();
/**
* ็ปๅพๅฝๆฐ็ๅขๅผบ็ ๆฟไปฃๅๆCControlUI::DrawImage ๅ CRenderEngine::DrawImageStringๅฝๆฐ
* Note: ่ขซPaintXXImage่ฐ็จ
*/
bool DrawImageEx(HDC hDC, CPaintManagerUI* pManager, const RECT& rc, const RECT& rcPaint,
LPCTSTR pStrImage, LPCTSTR pStrModify = NULL);
/**
* ็ปๅพๅฝๆฐ็ๅขๅผบ็ ๆฟไปฃๅๆUiLib::DrawImageๅฝๆฐ
* Note: ๅ
ๆฌๅคๆญๆไปถ็ฑปๅใๅๅงๅ่ฏปๅGIFๅ
ๅฎน็ญ
*/
bool DrawAniImage(HDC hDC, CPaintManagerUI* pManager, const RECT& rc, const RECT& rcPaint, const CDuiString& sImageName, \
const CDuiString& sImageResType, RECT rcItem, RECT rcBmpPart, RECT rcCorner, DWORD dwMask, BYTE bFade, \
bool bHole, bool bTiledX, bool bTiledY);
protected:
const TImageInfo* GetAniImage(LPCTSTR bitmap);
const TImageInfo* AddAniImage(HDC hDC, LPCTSTR bitmap, LPCTSTR type = NULL, DWORD mask = 0);
protected:
CStdStringPtrMap m_mAniHash;
};
} // namespace EUILib
#endif
|
#pragma once
#include"Entity.h"
#include"Chamber.h"
#include"Player.h"
#include"Enemy.h"
#include<vector>
#include<string>
class Floor
{
private:
static Floor *f;
Player *p;
std::vector<std::string> defaultMap;
std::vector<std::string> map;
std::vector<Chamber*> chamberList;
int level;
Entity *stair;
Floor();
~Floor();
void randomizeObjectLocation(int &x, int &y, Chamber *&c);
void spawnPlayer();
void spawnStairs();
void generatePotion(int potionIndex);
void generateDragonHoard();
void generateGoldPile();
void generateEnemy(int enemyIndex);
void generateFloor();
std::string commandIntepreter();
public:
static Floor* getInstance();
static void resetInstance();
Player* getPlayer();
void setPlayer(Player *p);
int getLevel();
void initMap(std::vector<std::string> map);
std::vector<std::string>& getMap();
void restoreMapFromCoordinate(int x, int y);
Character* getEnemyFromCoordinate(int x, int y);
Potion* getPotionFromCoordinate(int x, int y);
Treasure* getTreasureFromCoordinate(int x, int y);
void outputFloor();
void initFloor();
void update();
};
|
#include <iostream>
#define N 100
int powOf(int a)
{
for (int i = 2; i*i <= a; i++) {
if (a % i == 0) {
int pow = 0, temp = a;
for (; temp % i == 0; temp /= i, pow++);
if (temp == 1)
return pow;
}
}
return 1;
}
int main()
{
int overlap[6+1] = {0};
bool used[6*N+1] = {0};
for (int pow = 1; pow < 6+1; pow++) {
for (int b = 2*pow; b <= N*pow; b += pow) {
if (used[b]) overlap[pow]++;
used[b] = 1;
}
}
int sum = 0;
for (int a = 2; a <= N; a++)
sum += N - 1 - overlap[powOf(a)];
std::cout << sum << "\n";
}
|
/*
NOTE:
make the variables unique for each file by perhaps parsing in the file name.
malkovich malkovich malkovich malkovich malkovich
malkovich malkovich
malkovich malkovich malkovich malkovich malkovich
malkovich malkovich
malkovich malkovich malkovich
malkovich malkovich malkovich malkovich
*/
#include "createSolver.h"
#define BUFMAX 256
string conditions[] = {"<",">","=","#","$","!"};
string manips[] = {"+","-","*","/"};
void whileFound(ofstream *out, ifstream *input, int *num_of_lines, string *filestring);
//keeping track of all the variables used for while loops so that
//they don't step on each other
int numWhileVars;
int maxWhileVars;
//pther variable uses (ifs?)
int numVars;
int boardWidth = 9;
int boardHeight = 9;
int maxInt = 10;
void createSolver::sCreate(string file, int seedUp)
{
//initialize random seed
srand(time(NULL) + seedUp);
numWhileVars = 0;
maxWhileVars = -1;
numVars = 0;
ofstream out(file.c_str());
if(! out.good()){
cout <<"error creating pop member: "<<file<<"\n";
exit(-6);
}
//make 100 requests for lines
for (int i=0; i<100; i++)
{
out << getLine();
}
out.close();
}
//get "a line"
string createSolver::getLine(){
//output string
std:stringstream out;
//randomly select a line
switch(rand()%3){
//ifs and picksqs
case 0:
case 1:
out << getOther();
break;
//while loop
case 2:
out << getWhile();
break;
}
//cout << out.str();
return out.str();
}
string createSolver::getWhile(){
//output string
std:stringstream out;
//determining if it is a < and increment or > and decrement
int con = rand()%2;
//initial value of the loopiong variable
int val = rand()%maxInt;
//target value for the looping value
int val2 = rand()%maxInt;
//less than and increment
if(con){
//take care of loops with nowhere to go
if(val == 0)
val = 1;
//make sure the target value is in the correct direction
if(val <= val2)
val2 = val-1;
} else if(!con){
//take care of loops with nowhere to go
if(val == maxInt-1)
val = maxInt-2;
//make sure the target value is in the correct direction
if(val >= val2)
val2 = val+1;
}
//Mark the beginning of the while loop
out << "#while\n";
if(numWhileVars>maxWhileVars){
//initialize looping variabl
out << "int wvar" << numWhileVars << "=" << val << endl;
//open the while loop
out << "while wvar" << numWhileVars << conditions[con] << val2 << endl;
//set the loop to update each pass through
out << "update wvar" << numWhileVars << "=wvar" << numWhileVars << manips[con] << "1\n";
//mark the variable as used so no one edits it
numWhileVars++;
maxWhileVars++;
}
else{
//initialize looping variabl
out << "update wvar" << numWhileVars << "=" << val << endl;
//open the while loop
out << "while wvar" << numWhileVars << conditions[con] << val2 << endl;
//set the loop to update each pass through
out << "update wvar" << numWhileVars << "=wvar" << numWhileVars << manips[con] << "1\n";
//mark the variable as used so no one edits it
numWhileVars++;
}
//call for a new "line" inside the loop
out << getLine();
//end the loop
out << "ewhile\n";
out << "#ewhile\n";
numWhileVars--;
return out.str();
//cout << out.str();
//return "temp";
}
string createSolver::getOther(){
//output string
std:stringstream out;
//temp variable to hold random variables throughout
int var;
//keep track of decision of "<" vs ">"
int con;
//pick a square
if(rand()%3){
out <<"#picsq selection\n";
out << "picsq ";
//if no loops are chilling about, make it all random
if(numWhileVars==0){
out << rand()%boardWidth << "," << rand()%boardHeight << endl;
} else {
//pick a random number within the bounds of the while numbers
//for the x coordinate
var = rand()%(numWhileVars+1);
//if outside, make it random
if(var == numWhileVars || var >= boardWidth)
out << rand()%boardWidth << ",";
//otherwise make it be the while variable number
else
out << "wvar" << var << ",";
//pick a random number within the bounds of the while numbers
//for the y coordinate
var = rand()%(numWhileVars+1);
//if outside, make it random
if(var == numWhileVars || var >= boardHeight)
out << rand()%boardHeight << endl;
//otherwise make it be the while variable number
else
out << "wvar" << var << endl;
}
}
//if statement
else
{
//choose to either be "<" or ">"
con = rand()%2;
//half the time poll for a square's contents for comparison
if(rand()%2){
//find out the value of a square
out << "getsq ";
//if there is a loop variable alive
if(numWhileVars)
{
//get a random loop variable
var = rand()%(numWhileVars);
//if beyond the range of loop variables, make it random
if(var == numWhileVars-1 || var >= boardWidth)
out << rand()%boardWidth << ",";
//otherwise grab the loop variable
else
out << "wvar" << var << ",";
//get a random loop variable
var = rand()%(numWhileVars);
//if beyond the range of loop variables, make it random
// if(var == numWhileVars-1 || var >= boardHeight)
out << rand()%boardHeight << endl;
//otherwise grab the loop variable
// else
// out << "wvar" << var << endl;
//grab the square variable and store
out << "int var" << (numVars) << "=GSRETURN" << endl;
//out << "int var" << (numVars) << "=4" << endl;
//check conditions ("<" and ">")
out << "if var" << (numVars) << conditions[con];
//get a random loop variable
var = rand()%(numWhileVars);
//if beyond the range of loop variables, make it random
if(var == numWhileVars-1)
out << rand()%maxInt << endl;
//otherwise grab the loop variable
else
out << "wvar" << var << endl;
//if no loop variables do some random shit
} else {
out << rand()%boardWidth << ",";
out << rand()%boardHeight << endl;
//out << "int var" << (numVars) << "=4" << endl;
out << "if var" << (numVars) << conditions[con];
out << rand()%maxInt << endl;
}
//up the var count so the next line can't mess with it
numVars++;
out << getLine();
//half the time there's an else
if(rand()%2)
{
out << "else\n";
out << getLine();
}
out << "eif\n";
//numVars--;
//half the time there's no polling for a square's contents
} else {
//if loop vars
if(numWhileVars)
{
//randomly select var for first loopvar
var = rand()%numWhileVars;
out << "if wvar" << var << conditions[con];
//pick a random num for comparison
var = rand()%(numWhileVars+1);
//if beyond upper limit, set random number
if(var == numWhileVars)
out << rand()%maxInt << endl;
//otherwise make it be the loop variable
else
out << "wvar" << var << endl;
out << getLine();
//half the time there's an else
if(rand()%2)
{
out << "else\n";
out << getLine();
}
out << "eif\n";
}
}
}
return out.str();
}
void createSolver::combine_best(vector<string> selected_files, mssv vars, int cur_gen){
int num_of_lines = 0;
stringstream out;
int next_gen = cur_gen+1;
srand(time(0));
int rand_file1 = rand()%selected_files.size();
int rand_file2 = rand()%selected_files.size();
//In case the random numbers are equal, redo
while(rand_file1 == rand_file2 && selected_files.size() > 1){
rand_file2 = rand()%selected_files.size();
}
for(int i = 0; i < vars.population; i++){
char file1[BUFMAX], file2[BUFMAX], newfile[BUFMAX];
char buf1[BUFMAX], buf2[BUFMAX];
ifstream input1(selected_files.at(rand_file1).c_str());
ifstream input2(selected_files.at(rand_file2).c_str());
_itoa_s(next_gen,buf1,10, 10);
_itoa_s(i,buf2,10, 10);
sprintf(newfile, "%s\\%s%s%s\\%s%s%s", vars.test_dir.c_str(), vars.test_dir.c_str(), "_gen_", buf1, "population_", buf2, ".mss", " ");
ofstream out(newfile);
if(!input1.good() || !input2.good() || !out.good()){
cout <<"error creating pop member: "<<file1<< "/" <<file2<< "\n";
exit(-10);
}
char file1buf[BUFMAX], file2buf[BUFMAX];
while(!input1.eof() && !input2.eof()){
int random = rand()%2;
input1.getline(file1buf, BUFMAX);
input2.getline(file2buf, BUFMAX);
switch(random){
case 0:
if(file1buf[0] == '#'){
if(strcmp(file1buf, "#picsq selection") == 0){
out << file1buf << "\n";
input1.getline(file1buf, BUFMAX);
out << file1buf << "\n";
num_of_lines += 2;
skipSection(&input2);
}else if(strcmp(file1buf, "#while") == 0){
whileFound(&out, &input1, &num_of_lines, file1buf);
skipSection(&input2);
}
}
break;
case 1:
if(file2buf[0] == '#'){
if(strcmp(file2buf, "#picsq selection") == 0){
out << file2buf << "\n";
input2.getline(file2buf, BUFMAX);
out << file2buf << "\n";
skipSection(&input1);
}else if(strcmp(file2buf, "#while") == 0){
whileFound(&out, &input1, &num_of_lines, file2buf);
skipSection(&input1);
}
}
break;
}//end switch
}//end while
input1.close();
input2.close();
out.close();
}//end for
}
void createSolver::whileFound(ofstream *out, ifstream *input, int *num_of_lines, char *filestring){
int while_count = 1;
(*out) << filestring << "\n";
while(strcmp(filestring, "#ewhile") != 0 && while_count >= 1 && !(input->eof())){
(*input).getline(filestring, BUFMAX);
(*num_of_lines)++;
if(strcmp(filestring, "#while") == 0){
while_count++;
}else if(strcmp(filestring, "#ewhile") == 0){
while_count--;
}
(*out) << filestring << "\n";
}
}
void createSolver::skipSection(ifstream *input){
int while_count = 0;
char skip[256];
(*input).getline(skip, BUFMAX);
if(skip[0] == '#'){
if(strcmp(skip, "#while") == 0){
while_count++;
while(strcmp(skip, "#ewhile") && while_count > 1){
(*input).getline(skip, BUFMAX);
if(strcmp(skip, "#while") == 0){
while_count++;
}else if(strcmp(skip, "#ewhile") == 0){
while_count--;
}
}
}else if(strcmp(skip, "#picsq selection") == 0){
(*input).getline(skip, BUFMAX);
}
}
}
|
๏ปฟ#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int N, M;
int nResult;
vector<int> v;
void DFS(int Index, int Cnt, int Sum)
{
if (3 == Cnt && M >= Sum)
{
nResult = max(Sum, nResult);
return;
}
if (3 < Cnt || Index >= N || M < Sum)
{
return;
}
DFS(Index + 1, Cnt + 1, Sum + v[Index]);
DFS(Index + 1, Cnt, Sum);
}
int main(void)
{
cin >> N >> M;
v = vector<int>(N, 0);
for (int i = 0; i < N; i++)
{
cin >> v[i];
}
DFS(0, 0, 0);
cout << nResult << endl;
return 0;
}
|
#include <iostream>
#include "MapAnalyzer.h"
using namespace sc2;
MapAnalyzer::MapAnalyzer()
{
}
void MapAnalyzer::AnalyzeMap(const ObservationInterface* obs)
{
std::cout << "beginning of the map analysis" << std::endl;
const ObservationInterface* observation = obs;
Units all_neutrals = observation->GetUnits(Unit::Alliance::Neutral); // get all neutral features on the map.
std::vector<const Unit*> all_vespenes = {}; // All vespene units.
std::vector<const Unit*> all_minerals = {}; // All mineral units.
std::cout << "Number of all neutral units : " << all_neutrals.size() << std::endl;
for (const auto& unit : all_neutrals) { // Loop to find all ressources
if (unit->unit_type == UNIT_TYPEID::NEUTRAL_VESPENEGEYSER ||
unit->unit_type == UNIT_TYPEID::NEUTRAL_PURIFIERVESPENEGEYSER ||
unit->unit_type == UNIT_TYPEID::NEUTRAL_PROTOSSVESPENEGEYSER ||
unit->unit_type == UNIT_TYPEID::NEUTRAL_RICHVESPENEGEYSER ||
unit->unit_type == UNIT_TYPEID::NEUTRAL_SHAKURASVESPENEGEYSER)
all_vespenes.push_back(unit);
else {
if (unit->unit_type == UNIT_TYPEID::NEUTRAL_MINERALFIELD ||
unit->unit_type == UNIT_TYPEID::NEUTRAL_MINERALFIELD750 ||
unit->unit_type == UNIT_TYPEID::NEUTRAL_RICHMINERALFIELD ||
unit->unit_type == UNIT_TYPEID::NEUTRAL_RICHMINERALFIELD750) {
all_minerals.push_back(unit);
}
}
}
std::cout << all_vespenes.size() << " " << all_minerals.size() << std::endl;
Point3D start_location = observation->GetStartLocation();
BaseDescriptor start_base = BaseDescriptor();
start_base.position_center = start_location;
std::vector<const Unit*> old_vespenes = all_vespenes;
std::vector<const Unit*> old_minerals = all_minerals;
all_vespenes = {};
all_minerals = {};
while (old_vespenes.size() > 0) {
const Unit* vespene = old_vespenes.back();
old_vespenes.pop_back();
Point3D difference = vespene->pos - start_location;
if (abs(difference.x) < 10 && abs(difference.y) < 10 && abs(difference.z) < 10) {
start_base.gas.push_back(vespene);
}
else
all_vespenes.push_back(vespene);
}
while (old_minerals.size() > 0) {
const Unit* mineral = old_minerals.back();
old_minerals.pop_back();
Point3D difference = mineral->pos - start_location;
if (abs(difference.x) < BASE_SIZE && abs(difference.y) < BASE_SIZE && abs(difference.z) < BASE_SIZE) {
start_base.minerals.push_back(mineral);
}
else {
all_minerals.push_back(mineral);
}
}
std::cout << all_vespenes.size() << " " << all_minerals.size() << std::endl;
start_base.iD = 1;
start_base.occupation = Unit::Alliance::Self;
bases.push_back(start_base);
int newID = 2;
// Now, we look at the other bases on the map.
while (all_minerals.size() > 0) {
BaseDescriptor newBase = BaseDescriptor();
Point3D ressourceCenter = Point3D(0,0,0);
float m_left = std::numeric_limits<float>::max();
float m_right = std::numeric_limits<float>::min();
float m_top = std::numeric_limits<float>::min();
float m_bottom = std::numeric_limits<float>::max();
newBase.iD = newID;
newID++;
newBase.position_center = all_minerals.back()->pos; // We initialize the position of the new base as one of the minerals.
old_minerals = all_minerals;
old_vespenes = all_vespenes;
all_minerals = {};
all_vespenes = {};
const Unit* top_mineral = nullptr; // initialization to find the most top and bottom mineral fields.
const Unit* bottom_mineral = nullptr;
float top,bottom;
top = std::numeric_limits<float>::min();
bottom = std::numeric_limits<float>::max();
while (old_minerals.size() > 0) {
const Unit* mineral = old_minerals.back();
old_minerals.pop_back();
Point3D difference = mineral->pos - newBase.position_center;
if (abs(difference.x) < BASE_SIZE && abs(difference.y) < BASE_SIZE && abs(difference.z) < BASE_SIZE) {
m_top = std::max(m_top, mineral->pos.y);
m_bottom = std::min(m_bottom, mineral->pos.y);
m_right = std::max(m_right, mineral->pos.x);
m_left = std::min(m_left, mineral->pos.x);
newBase.minerals.push_back(mineral);
ressourceCenter = ressourceCenter + mineral->pos;
}
else {
all_minerals.push_back(mineral);
}
}
while (old_vespenes.size() > 0) {
const Unit* vespene = old_vespenes.back();
old_vespenes.pop_back();
Point3D difference = vespene->pos - newBase.position_center;
if (abs(difference.x) < BASE_SIZE && abs(difference.y) < BASE_SIZE && abs(difference.z) < BASE_SIZE) {
newBase.gas.push_back(vespene);
ressourceCenter = ressourceCenter + vespene->pos;
m_top = std::max(m_top, vespene->pos.y);
m_bottom = std::min(m_bottom, vespene->pos.y);
m_right = std::max(m_right, vespene->pos.x);
m_left = std::min(m_left, vespene->pos.x);
}
else {
all_vespenes.push_back(vespene);
}
}
ressourceCenter = ressourceCenter / ((float)newBase.minerals.size() + (float)newBase.gas.size());
/*newBase.position_center.x = (m_left + (m_right - m_left)) / 2;
newBase.position_center.y = (m_bottom + (m_top - m_bottom)) / 2;*/
std::cout << newBase.iD << " " << newBase.position_center.x << " " << newBase.position_center.y << std::endl;
newBase.occupation = Unit::Alliance::Neutral;
bases.push_back(newBase);
}
}
void MapAnalyzer::PrintDebugInfo(DebugInterface* debug)
{
for (const BaseDescriptor base : bases) {
std::string position_string = std::to_string(base.position_center.x) + "," + std::to_string(base.position_center.y);
debug->DebugBoxOut(base.position_center - (2*ones), base.position_center + (2*ones));
debug->DebugTextOut("Base #"+std::to_string(base.iD), base.position_center);
for (const Unit* vespene : base.gas) {
position_string = std::to_string(vespene->pos.x) + "," + std::to_string(vespene->pos.y);
debug->DebugBoxOut(vespene->pos - ones, vespene->pos + ones);
debug->DebugTextOut(position_string, vespene->pos);
}
for (const Unit* mineral : base.minerals) {
position_string = std::to_string(mineral->pos.x) + "," + std::to_string(mineral->pos.y);
debug->DebugBoxOut(mineral->pos - ones, mineral->pos + ones);
debug->DebugTextOut(position_string, mineral->pos);
}
}
}
BaseDescriptor MapAnalyzer::ClosestUnoccupiedBase(Point3D position)
{
BaseDescriptor ret;
std::cout << "Finding closest base now" << std::endl;
float distance = std::numeric_limits<float>::max();
for (auto base : bases) {
if (base.occupation == Unit::Alliance::Neutral) {
float distance_to_base = pow(base.position_center.x - position.x, 2) + pow(base.position_center.y - position.y, 2);
if (distance_to_base < distance) {
ret = base;
distance = distance_to_base;
}
}
}
return ret;
}
MapAnalyzer::~MapAnalyzer()
{
}
|
// Registry.h: interface for the CRegistry class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_REGISTRY_H__08F26279_A63D_11D3_B73D_0050DA34A2BA__INCLUDED_)
#define AFX_REGISTRY_H__08F26279_A63D_11D3_B73D_0050DA34A2BA__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "Crypt.h"
class CRegistry
{
public:
CRegistry(HKEY hKey = HKEY_CURRENT_USER);
virtual ~CRegistry();
BOOL Open(HKEY hKey, LPCTSTR lpszPath, const REGSAM& dwMask = KEY_ALL_ACCESS);
BOOL Open(LPCTSTR lpszPath, const REGSAM& dwMask = KEY_ALL_ACCESS);
void Close();
BOOL VerifyKey(LPCTSTR lpszPath, const BOOL& bOpen = FALSE, const REGSAM& dwMask = KEY_ALL_ACCESS);
BOOL VerifyKey(HKEY hKey, LPCTSTR lpszPath, const BOOL& bOpen = FALSE, const REGSAM& dwMask = KEY_ALL_ACCESS);
BOOL VerifyValue(LPCTSTR lpszValue);
BOOL VerifyValue(HKEY hKey, LPCTSTR lpszValue);
BOOL CreateKey(HKEY hKey, LPCTSTR lpszPath, const BOOL& bOpen = FALSE, const DWORD& dwOptions = REG_OPTION_NON_VOLATILE, const REGSAM& dwMask = KEY_ALL_ACCESS);
BOOL CreateKey(LPCTSTR lpszPath, const BOOL& bOpen = FALSE, const DWORD& dwOptions = REG_OPTION_NON_VOLATILE, const REGSAM& dwMask = KEY_ALL_ACCESS);
BOOL DeleteKey(HKEY hKey, LPCTSTR lpszPath);
BOOL DeleteKey(LPCTSTR lpszPath);
BOOL DeleteValue(HKEY hKey, LPCTSTR lpszValue);
BOOL DeleteValue(LPCTSTR lpszValue);
BOOL WriteString(LPCTSTR lpszKey, LPCTSTR lpszData);
BOOL WriteDWORD(LPCTSTR lpszKey, const DWORD& dwData);
BOOL WriteWnd(LPCTSTR lpszKey, CWnd* pWnd);
BOOL WriteObj(LPCTSTR lpszKey, CObject& object, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5);
BOOL ReadString(LPCTSTR lpszKey, CString& sData);
BOOL ReadDWORD(LPCTSTR lpszKey, DWORD& dwData);
BOOL ReadWnd(LPCTSTR lpszKey, CWnd* pWnd);
BOOL ReadObj(LPCTSTR lpszKey, CObject& object, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5);
protected:
BOOL Encrypt(BYTE*& pByte, DWORD& dwSize, LPCTSTR lpszPassword, const CCrypt::Algorithm& eAlgorithm);
BOOL Decrypt(BYTE*& pByte, DWORD& dwSize, LPCTSTR lpszPassword, const CCrypt::Algorithm& eAlgorithm);
protected:
HKEY m_hKey;
CString m_sPath;
public:
// *** Templates ***
template<class T>
AFX_INLINE BOOL WriteRaw(LPCTSTR lpszKey, const T& type, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5)
{
ASSERT(lpszKey);
CMemFile file;
CArchive ar(&file, CArchive::store);
ar.Write(&type, sizeof(T));
ar.Close();
DWORD dwSize = file.GetLength();
#ifdef _DEBUG
if (dwSize > 2048)
TRACE1("CRegistry::WriteType - Object size = %d (> 2048) better use a file !\n", dwSize);
#endif
BYTE* pByte = file.Detach();
if (lpszPassword)
if (!Encrypt(pByte, dwSize, lpszPassword, eAlgorithm))
return FALSE;
LONG lResult = RegSetValueEx(m_hKey, lpszKey, NULL, REG_BINARY, pByte, dwSize);
if (pByte)
free(pByte);
if(lResult == ERROR_SUCCESS)
return TRUE;
return FALSE;
}
template<class T>
AFX_INLINE BOOL ReadRaw(LPCTSTR lpszKey, T& type, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5)
{
ASSERT(lpszKey);
DWORD dwType = -1;
DWORD dwSize = -1;
BYTE* pByte = NULL;
LONG lResult = RegQueryValueEx(m_hKey, lpszKey, NULL, &dwType, pByte, &dwSize);
if (lResult == ERROR_SUCCESS && dwType == REG_BINARY)
pByte = new BYTE[dwSize];
lResult = RegQueryValueEx(m_hKey, lpszKey, NULL, &dwType, pByte, &dwSize);
if (lResult == ERROR_SUCCESS && dwType == REG_BINARY)
{
if (lpszPassword)
if (!Decrypt(pByte, dwSize, lpszPassword, eAlgorithm))
return FALSE;
CMemFile file(pByte, dwSize);
CArchive ar(&file, CArchive::load);
ar.Read(&type, dwSize);
ar.Close();
file.Close();
delete pByte;
return TRUE;
}
delete pByte;
return FALSE;
}
template<class T>
AFX_INLINE BOOL WriteType(LPCTSTR lpszKey, const T& type, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5)
{
ASSERT(lpszKey);
CMemFile file;
CArchive ar(&file, CArchive::store);
ar << type;
ar.Close();
DWORD dwSize = file.GetLength();
#ifdef _DEBUG
if (dwSize > 2048)
TRACE1("CRegistry::WriteType - Object size = %d (> 2048) better use a file !\n", dwSize);
#endif
BYTE* pByte = file.Detach();
if (lpszPassword)
if (!Encrypt(pByte, dwSize, lpszPassword, eAlgorithm))
return FALSE;
LONG lResult = RegSetValueEx(m_hKey, lpszKey, NULL, REG_BINARY, pByte, dwSize);
if (pByte)
free(pByte);
if(lResult == ERROR_SUCCESS)
return TRUE;
return FALSE;
}
template<class T>
AFX_INLINE BOOL ReadType(LPCTSTR lpszKey, T& type, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5)
{
ASSERT(lpszKey);
DWORD dwType = -1;
DWORD dwSize = -1;
BYTE* pByte = NULL;
LONG lResult = RegQueryValueEx(m_hKey, lpszKey, NULL, &dwType, pByte, &dwSize);
if (lResult == ERROR_SUCCESS && dwType == REG_BINARY)
pByte = new BYTE[dwSize];
lResult = RegQueryValueEx(m_hKey, lpszKey, NULL, &dwType, pByte, &dwSize);
if (lResult == ERROR_SUCCESS && dwType == REG_BINARY)
{
if (lpszPassword)
if (!Decrypt(pByte, dwSize, lpszPassword, eAlgorithm))
return FALSE;
CMemFile file(pByte, dwSize);
CArchive ar(&file, CArchive::load);
ar >> type;
ar.Close();
file.Close();
delete pByte;
return TRUE;
}
delete pByte;
return FALSE;
}
template<class T>
AFX_INLINE BOOL WriteDynObj(LPCTSTR lpszKey, const T* pObject, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5)
{
ASSERT(m_hKey);
ASSERT(lpszKey);
CMemFile file;
CArchive ar(&file, CArchive::store);
ar << pObject;
ar.Close();
DWORD dwSize = file.GetLength();
#ifdef _DEBUG
if (dwSize > 2048)
TRACE2("CRegistry::WriteDynObj - Object[%s] size = %d (> 2048) better use a file !\n",
pObject->GetRuntimeClass()->m_lpszClassName,
dwSize);
#endif
BYTE* pByte = file.Detach();
if (lpszPassword)
if (!Encrypt(pByte, dwSize, lpszPassword, eAlgorithm))
return FALSE;
LONG lResult = RegSetValueEx(m_hKey, lpszKey, NULL, REG_BINARY, pByte, dwSize);
if (pByte)
free(pByte);
if(lResult == ERROR_SUCCESS)
return TRUE;
return FALSE;
}
template<class T>
AFX_INLINE BOOL ReadDynObj(LPCTSTR lpszKey, T*& pObject, LPCTSTR lpszPassword = NULL, const CCrypt::Algorithm& eAlgorithm = CCrypt::Algorithm::eMD5)
{
ASSERT(m_hKey);
ASSERT(lpszKey);
DWORD dwType = -1;
DWORD dwSize = -1;
BYTE* pByte = NULL;
LONG lResult = RegQueryValueEx(m_hKey, lpszKey, NULL, &dwType, pByte, &dwSize);
if (lResult == ERROR_SUCCESS && dwType == REG_BINARY)
pByte = new BYTE[dwSize];
lResult = RegQueryValueEx(m_hKey, lpszKey, NULL, &dwType, pByte, &dwSize);
if (lResult == ERROR_SUCCESS && dwType == REG_BINARY)
{
if (lpszPassword)
if (!Decrypt(pByte, dwSize, lpszPassword, eAlgorithm))
return FALSE;
CMemFile file(pByte, dwSize);
CArchive ar(&file, CArchive::load);
ar >> pObject;
ar.Close();
file.Close();
delete pByte;
return TRUE;
}
delete pByte;
return FALSE;
}
};
#endif // !defined(AFX_REGISTRY_H__08F26279_A63D_11D3_B73D_0050DA34A2BA__INCLUDED_)
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* psmaas - Patricia Aas Oct 2005
*/
#include "core/pch.h"
#include "adjunct/quick/models/DesktopHistoryModel.h"
#include "adjunct/quick/Application.h"
#include "adjunct/quick/hotlist/HotlistManager.h"
#include "adjunct/quick/models/HistoryAutocompleteModel.h"
#include "adjunct/desktop_util/sessions/SessionAutoSaveManager.h"
#include "adjunct/desktop_util/string/stringutils.h"
#include "adjunct/desktop_util/file_utils/filenameutils.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/util/winutils.h"
#include "modules/search_engine/VisitedSearch.h"
#include "adjunct/quick/windows/DocumentDesktopWindow.h"
#include "adjunct/quick/WindowCommanderProxy.h"
#include "modules/debug/debug.h"
/*___________________________________________________________________________*/
/* HISTORY MODEL */
/*___________________________________________________________________________*/
/***********************************************************************************
** Init - static factory method to ensure proper initialisation of the sigleton
** history model.
**
**
** @return
***********************************************************************************/
OP_STATUS DesktopHistoryModel::Init()
{
HistoryModelTimeFolder** timefolders = OP_NEWA(HistoryModelTimeFolder*, NUM_TIME_PERIODS);
if(!timefolders)
return OpStatus::ERR_NO_MEMORY;
// initialize the array so if it fails later, it won't crash in the destructor
op_memset(timefolders, 0, sizeof(*timefolders) * NUM_TIME_PERIODS);
OpHistoryModel* model = g_globalHistory;
if(!model)
return OpStatus::ERR;
INT32 i;
for(i = 0; i < NUM_TIME_PERIODS; i++)
{
timefolders[i] = OP_NEW(HistoryModelTimeFolder, (model->GetTimeFolder((TimePeriod)i)));
if(!(timefolders[i]))
break;
}
if(i < NUM_TIME_PERIODS)
{
//Out of memory - delete folders
for(INT32 j = 0; j < i; j++)
OP_DELETE(timefolders[j]);
OP_DELETEA(timefolders);
return OpStatus::ERR_NO_MEMORY;
}
m_model = model;
m_timefolders = timefolders;
m_model->AddListener(this);
INT32 mode = g_pcui->GetIntegerPref(PrefsCollectionUI::HistoryViewStyle);
m_mode = (mode >= 0 && mode < NUM_MODES) ? (History_Mode) mode : TIME_MODE;
SetSortListener(this);
OP_ASSERT(OpStatus::IsSuccess(g_favicon_manager->AddListener(this)));
m_CoreValid = TRUE;
m_bookmark_model = (g_hotlist_manager) ? g_hotlist_manager->GetBookmarksModel() : 0;
if(m_CoreValid && m_bookmark_model)
{
m_bookmark_model->AddModelListener(this);
// History is created _after_ hotlist parsing,
// so we need to force add of all bookmarks
AddBookmarks();
}
g_application->GetDesktopWindowCollection().AddListener(this);
return OpStatus::OK;
}
/***********************************************************************************
** HistoryModel - Constructor
**
** @param
**
**
***********************************************************************************/
DesktopHistoryModel::DesktopHistoryModel()
: m_model(0),
m_timefolders(0)
{
}
/***********************************************************************************
**
** AddBookmarks
**
** DesktopHistoryModel is created _after_ parsing of bookmarks is finished,
** so the notifications about items added won't reach DesktopHistoryModel,
** therefore this function is needed to add the bookmarks
**
***********************************************************************************/
void DesktopHistoryModel::AddBookmarks()
{
OpVector<Bookmark> items;
m_bookmark_model->GetBookmarkItemList(items);
for(UINT32 i = 0; i < items.GetCount(); i++)
{
Bookmark * item = items.Get(i);
AddBookmark(item);
AddBookmarkNick(item->GetShortName(), item);
}
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
OP_STATUS DesktopHistoryModel::AddBookmarkNick(const OpStringC & nick, Bookmark * item)
{
if(item && item->IsBookmark())
{
if(m_CoreValid)
{
HistoryPage * core_bookmark_item = AddBookmark(item);
if(!core_bookmark_item)
return OpStatus::ERR;
if(nick.IsEmpty())
return OpStatus::OK;
return m_model->AddBookmarkNick(nick, *core_bookmark_item);
}
}
return OpStatus::ERR;
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryPage * DesktopHistoryModel::AddBookmark(Bookmark * item)
{
if(item && item->IsBookmark())
{
if(m_CoreValid)
{
OpString url, display_url;
url.Set(item->GetUrl()); //Try the url itself
if (item->GetHasDisplayUrl())
display_url.Set(item->GetDisplayUrl());
if(url.IsEmpty())
{
return NULL;
}
if(!m_model->IsAcceptable(url.CStr()))
{
url.Set(item->GetResolvedUrl()); //If it doesn't work try the resolved url
}
if(m_model->IsAcceptable(url.CStr()))
{
OpStringC name = item->GetName();
OpStringC shortname = item->GetShortName();
OpString title;
if(name.CStr())
{
title.Set(name.CStr());
title.Append(" ");
}
if(shortname.CStr())
{
title.Append("(");
title.Append(shortname.CStr());
title.Append(")");
}
if(title.IsEmpty())
title.Set(url.CStr());
HistoryPage * history_item = 0, *dummy_item = 0;
OP_ASSERT(url.HasContent());
OP_STATUS status = m_model->AddBookmark(url.CStr(), title.CStr(), history_item);
// Also mark the display url as bookmarked if any, to prevent it appearing in history
// result when searching(it's already searched as a bookmark)
if (display_url.HasContent())
OpStatus::Ignore(m_model->AddBookmark(display_url.CStr(), title.CStr(), dummy_item));
if (OpStatus::IsSuccess(status) && history_item)
{
item->SetHistoryItem(history_item);
}
return (HistoryPage *) history_item;
}
}
}
return NULL;
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::RemoveBookmark(Bookmark * item)
{
if(item)
{
HistoryPage* core_item = item->GetHistoryItem();
if (core_item)
{
// Do not listen to the history item any more
core_item->RemoveListener(item);
// Get the address of the history item
OpString address;
core_item->GetAddress(address);
// Only RemoveBookmark from core history if no more bookmarks listen to this item.
BOOL last_bookmark = FALSE;
OpVector<HistoryItem::Listener> result;
if(OpStatus::IsSuccess(core_item->GetListenersByType(OpTypedObject::BOOKMARK_TYPE, result)))
last_bookmark = (result.GetCount() == 0);
if(last_bookmark)
{
m_model->RemoveBookmark(address.CStr());
}
// Remove referance to history item
item->SetHistoryItem(NULL);
}
}
}
/***********************************************************************************
** HistoryModel - Destructor
**
**
**
**
***********************************************************************************/
DesktopHistoryModel::~DesktopHistoryModel()
{
// Delete items that are not in the ui :
while(m_deletable_items.GetCount())
{
HistoryModelPage * item = m_deletable_items.Remove(0);
if(!item->IsInHistory())
{
DeleteItem(item, TRUE);
}
}
// Delete items in the ui :
ClearModel();
if(m_timefolders)
{
for(INT32 i = 0; i < NUM_TIME_PERIODS; i++)
{
if(m_timefolders[i])
{
m_timefolders[i]->Remove();
OP_DELETE(m_timefolders[i]);
}
}
OP_DELETEA(m_timefolders);
}
if(m_CoreValid && m_model) m_model->RemoveListener(this);
if(g_favicon_manager)
{
OP_ASSERT(OpStatus::IsSuccess(g_favicon_manager->RemoveListener(this)));
}
m_model = 0;
m_CoreValid = FALSE;
g_pcui->WriteIntegerL(PrefsCollectionUI::HistoryViewStyle, m_mode);
g_application->GetDesktopWindowCollection().RemoveListener(this);
if (m_bookmark_model)
m_bookmark_model->RemoveModelListener(this);
}
/***********************************************************************************
** ChangeMode
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::ChangeMode(INT32 mode)
{
if(mode == TIME_MODE ||
mode == SERVER_MODE ||
#ifdef HISTORY_BOOKMARK_VIEW
mode == BOOKMARK_MODE ||
#endif // HISTORY_BOOKMARK_VIEW
mode == OLD_MODE)
{
GenericTreeModel::ModelLock lock(this);
CleanUp();
m_mode = (DesktopHistoryModel::History_Mode) mode;
m_initialized = FALSE;
switch(m_mode)
{
case TIME_MODE : MakeTimeVector(); break;
case SERVER_MODE : MakeServerVector(); break;
case OLD_MODE : MakeOldVector(); break;
#ifdef HISTORY_BOOKMARK_VIEW
case BOOKMARK_MODE : MakeBookmarkVector(); break;
#endif // HISTORY_BOOKMARK_VIEW
}
m_initialized = TRUE;
}
}
/***********************************************************************************
** CleanUp
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::CleanUp()
{
for(INT32 i = 0; i < GetCount(); i++)
{
HistoryModelItem* item = GetItemByIndex(i);
if(item->GetType() == OpTypedObject::FOLDER_TYPE)
{
HistoryModelFolder* folder = (HistoryModelFolder*) item;
if(folder->GetFolderType() == PREFIX_FOLDER)
{
folder->Remove(FALSE);
OP_DELETE(folder);
i--;
}
}
}
RemoveAll();
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnHotlistItemAdded(HotlistModelItem* item)
{
if(item->IsBookmark() && !item->GetIsInsideTrashFolder())
{
Bookmark * bookmark_item = (Bookmark *) item;
AddBookmark(bookmark_item);
AddBookmarkNick(bookmark_item->GetShortName(), bookmark_item);
}
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnHotlistItemChanged(HotlistModelItem* item, BOOL moved_as_child, UINT32 changed_flag)
{
if(item->IsBookmark() && !item->GetIsInsideTrashFolder())
{
Bookmark * bookmark_item = static_cast<Bookmark*>(item);
if(changed_flag & HotlistModel::FLAG_NICK)
{
AddBookmarkNick(bookmark_item->GetShortName(), bookmark_item);
}
else if(changed_flag & HotlistModel::FLAG_NAME || changed_flag & HotlistModel::FLAG_URL)
{
g_hotlist_manager->RemoveBookmarkFromHistory(item);
OnHotlistItemAdded(item);
}
}
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnHotlistItemRemoved(HotlistModelItem* item, BOOL removed_as_child)
{
if(item->IsBookmark() && !item->GetIsInsideTrashFolder())
{
Bookmark * bookmark_item = (Bookmark *) item;
RemoveBookmark(bookmark_item);
}
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnHotlistItemTrashed(HotlistModelItem* item)
{
if(item->IsBookmark())
{
Bookmark * bookmark_item = (Bookmark *) item;
RemoveBookmark(bookmark_item);
}
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnHotlistItemUnTrashed(HotlistModelItem* item)
{
if(item->IsBookmark() && !item->GetIsInsideTrashFolder())
{
Bookmark * bookmark_item = (Bookmark *) item;
AddBookmark(bookmark_item);
AddBookmarkNick(bookmark_item->GetShortName(), bookmark_item);
}
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnFavIconAdded(const uni_char* document_url,
const uni_char* image_path)
{
if (!document_url) return;
HistoryModelPage* item = GetItemByUrl(document_url);
if(item)
{
item->UpdateSimpleItem();
item->Change( TRUE );
}
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnFavIconsRemoved()
{
// TODO : what to do?
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryModelPage* DesktopHistoryModel::GetItemByDesktopWindow(DesktopWindow* window)
{
if(!window || window->GetType() != OpTypedObject::WINDOW_TYPE_DOCUMENT)
return NULL;
DocumentDesktopWindow* document_window = static_cast<DocumentDesktopWindow*>(window);
URL url = WindowCommanderProxy::GetMovedToURL(document_window->GetWindowCommander());
OpString url_string;
RETURN_VALUE_IF_ERROR(url.GetAttribute(URL::KUniName_With_Fragment_Username, url_string, FALSE), NULL);
return GetItemByUrl(url_string.CStr());
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnDesktopWindowAdded(DesktopWindow* window)
{
HistoryModelPage* item = GetItemByDesktopWindow(window);
if(item)
item->SetOpen(TRUE);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnDesktopWindowRemoved(DesktopWindow* window)
{
HistoryModelPage* item = GetItemByDesktopWindow(window);
if(item)
item->SetOpen(FALSE);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnDocumentWindowUrlAltered(DocumentDesktopWindow* document_window,
const OpStringC& url)
{
HistoryModelPage* old_item = GetItemByDesktopWindow(document_window);
if(old_item)
old_item->SetOpen(FALSE);
HistoryModelPage* new_item = GetItemByUrl(url);
if(new_item)
new_item->SetOpen(TRUE);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryModelPage* DesktopHistoryModel::GetPage(HistoryPage* core_item)
{
HistoryModelPage* item = static_cast<HistoryModelPage*>(GetListener(core_item));
#ifdef DEBUG
//Item should have listener
BOOL listener_status_valid =
(item ||
core_item->IsBookmarked() ||
core_item->IsOperaPage() ||
core_item->IsNick());
OP_ASSERT(listener_status_valid);
#endif
if(item)
return item;
item = OP_NEW(HistoryModelPage, (core_item));
if (!item)
return NULL;
if (!item->GetSimpleItem() || // OOM during construction
OpStatus::IsError(m_deletable_items.Add(item)))
{
OP_DELETE(item);
return NULL;
}
return item;
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryItem::Listener* DesktopHistoryModel::GetListener(HistoryItem* core_item)
{
if(!core_item)
return 0;
return core_item->GetListenerByType(core_item->GetType());
}
/***********************************************************************************
** OnItemAdded
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::OnItemAdded(HistoryPage* core_item, BOOL save_session)
{
HistoryItem::Listener* listener = GetListener(core_item);
HistoryModelPage* item = 0;
if(!listener)
{
item = OP_NEW(HistoryModelPage, (core_item));
if (!item)
return;
if (!item->GetSimpleItem()) // OOM during construction
{
OP_DELETE(item);
return;
}
}
else
{
item = (HistoryModelPage*) listener;
item->UpdateSimpleItem();
}
HistoryModelSiteFolder* site = item->GetSiteFolder();
if(m_mode == OLD_MODE)
{
if(!item->GetModel())
AddItem_To_OldVector(item, TRUE);
}
else if(m_mode == TIME_MODE)
{
if(!item->GetModel())
AddItem_To_TimeVector(item);
}
else if(m_mode == SERVER_MODE)
{
if(!site->GetModel())
AddSorted(site);
if(!item->GetModel())
{
INT32 site_ind = GetIndexByItem(site);
AddSorted(item, site_ind);
}
}
if (save_session)
if (g_session_auto_save_manager)
g_session_auto_save_manager->SaveCurrentSession();
if(item->m_moving)
{
item->m_old_parent_id = 0;
item->m_moving = FALSE;
}
}
/* ------------------ HistoryModel::Listener interface ------------------------*/
/***********************************************************************************
** OnItemRemoving - implementing the HistoryModel::Listener interface
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::OnItemRemoving(HistoryItem* core_item)
{
HistoryItem::Listener* listener = GetListener(core_item);
if(!listener)
return;
DeleteItem((HistoryModelItem*) listener, FALSE);
}
/***********************************************************************************
** OnItemDeleting - implementing the HistoryModel::Listener interface
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::OnItemDeleting(HistoryItem* core_item)
{
HistoryItem::Listener* listener = GetListener(core_item);
if(!listener)
return;
DeleteItem((HistoryModelItem*) listener, TRUE);
}
/***********************************************************************************
** OnItemMoving - implementing the HistoryModel::Listener interface
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::OnItemMoving(HistoryItem* core_item)
{
HistoryItem::Listener* listener = GetListener(core_item);
if(!listener)
return;
HistoryModelItem* item = (HistoryModelItem*) listener;
if(!item)
return;
HistoryModelItem* folder = item->GetParentItem();
if(folder) item->m_old_parent_id = folder->GetID();
item->m_moving = TRUE;
BOOL remove_item = TRUE;
/*
Time:
If this is time mode and this item is in a today folder and is
the last child in this folder - do not remove it - since this
will result in the folder being closed.
Server:
If this is the last child of this folder - do not remove it -
since this will result in the folder being closed
*/
if(m_mode == TIME_MODE)
{
HistoryModelSiteFolder * site = item->GetSiteFolder();
if(site) //Should always be true
{
HistoryModelSiteSubFolder * today = site->GetSubFolder(TODAY);
if(today && folder && today == folder && folder->GetChildCount() == 1)
{
remove_item = FALSE;
}
}
}
else if(m_mode == SERVER_MODE)
{
if(folder && folder->GetChildCount() == 1)
{
remove_item = FALSE;
}
}
if(remove_item)
Remove(item);
if(m_mode == TIME_MODE && folder && folder->GetChildCount() == 0)
folder->Remove();
}
/***********************************************************************************
** OnModelChanging - implementing the HistoryModel::Listener interface
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnModelChanging()
{
CleanUp();
}
/***********************************************************************************
** OnModelChanged - implementing the HistoryModel::Listener interface
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnModelChanged()
{
ChangeMode(GetMode());
}
/***********************************************************************************
** OnModelDeleted - implementing the HistoryModel::Listener interface
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::OnModelDeleted()
{
ClearModel();
m_model = 0;
m_CoreValid = FALSE;
}
/* --------------------------------------------------------------------------------*/
/***********************************************************************************
** DeleteItem
**
** @param
**
**
*********************************************************************************/
void DesktopHistoryModel::DeleteItem(HistoryModelItem* item, BOOL deleteParent)
{
HistoryModelSiteFolder* parent = 0;
HistoryModelItem* folder = item->GetParentItem();
if(item->GetType() == OpTypedObject::HISTORY_ELEMENT_TYPE)
parent = item->GetSiteFolder(FALSE);
Remove(item);
if(item->IsDeletable())
{
if(item->GetType() == OpTypedObject::HISTORY_ELEMENT_TYPE)
{
m_deletable_items.RemoveByItem((HistoryModelPage*) item);
}
BroadcastHistoryModelItemDestroyed(item);
OP_DELETE(item);
}
if(parent && deleteParent && parent->IsEmpty())
DeleteItem((HistoryModelSiteFolder*) parent, FALSE);
if(m_mode == TIME_MODE && folder && folder->GetChildCount() == 0)
folder->Remove();
}
/***********************************************************************************
** Delete
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::Delete(HistoryModelItem* item)
{
if(m_CoreValid)
m_model->Delete(item->GetCoreItem());
}
/***********************************************************************************
** Remove
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::Remove(HistoryModelItem* item)
{
if(item->GetType() == OpTypedObject::FOLDER_TYPE)
RemoveFolder((HistoryModelFolder *) item);
else if(item->GetType() == OpTypedObject::HISTORY_ELEMENT_TYPE)
RemoveItem(item);
}
/***********************************************************************************
** RemoveFolder
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::RemoveFolder(HistoryModelFolder* folder)
{
if(!folder->IsSticky())
folder->Remove(FALSE);
}
/***********************************************************************************
** RemoveItem
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::RemoveItem(HistoryModelItem* item)
{
if(item->GetType() == OpTypedObject::HISTORY_ELEMENT_TYPE)
{
item->Remove();
}
}
/***********************************************************************************
** ClearModel
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::ClearModel()
{
//If the model contains sticky folders they have to be removed
if(m_mode == TIME_MODE)
{
for(INT32 i = 0; i < NUM_TIME_PERIODS; i++)
{
m_timefolders[i]->Remove(FALSE);
}
}
for(INT32 i = 0; i < GetCount(); i++)
{
HistoryModelItem* item = GetItemByIndex(i);
if(item->GetType() == OpTypedObject::FOLDER_TYPE)
{
HistoryModelFolder* folder = (HistoryModelFolder*) item;
if(folder->GetFolderType() == PREFIX_FOLDER)
{
folder->Remove(FALSE);
OP_DELETE(folder);
i--;
}
}
}
while(GetCount())
{
HistoryModelItem* item = GetItemByIndex(0);
DeleteItem(item, TRUE);
}
}
/***********************************************************************************
** FindItem
**
** @param
**
** @return
***********************************************************************************/
HistoryModelItem* DesktopHistoryModel::FindItem(INT32 id)
{
return GetItemByID(id);
}
/***********************************************************************************
** GetItemByUrl
**
** @param
**
** @return
***********************************************************************************/
HistoryModelPage* DesktopHistoryModel::GetItemByUrl(const OpStringC & search_url,
BOOL do_guessing)
{
if(search_url.IsEmpty())
return 0;
if(m_CoreValid)
{
HistoryModelPage * page = LookupUrl(search_url);
if(page)
{
// Do exact search first
return page;
}
else if(do_guessing)
{
// Append a slash and try again
OpString tmp;
tmp.AppendFormat(UNI_L("%s/"), search_url.CStr());
return LookupUrl(tmp);
}
}
return 0;
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
HistoryModelPage* DesktopHistoryModel::LookupUrl(const OpStringC & search_url)
{
if(m_CoreValid)
{
if(m_model->IsAcceptable(search_url.CStr()))
{
HistoryPage* core_item = 0;
m_model->GetItem(search_url, core_item);
if(core_item)
{
HistoryItem::Listener* listener = GetListener(core_item);
return (HistoryModelPage*) listener;
}
}
}
return 0;
}
/***********************************************************************************
** SearchContent
**
** @param search_text - the text to search for
** @param items - the items that matched the search text
** @param content_text - the array of the matched text matches the above items item for item
**
***********************************************************************************/
// OP_STATUS DesktopHistoryModel::SearchContent(const OpStringC & search_text,
// OpVector<OpString> & words,
// OpVector<HistoryModelItem> & items,
// OpVector<OpString> & content_text)
// {
// RETURN_IF_ERROR(g_visited_search->Search(search_text.CStr(),
// VisitedSearch::RankSort,
// 500,
// UNI_L("<b>"),
// UNI_L("</b>"),
// 16,
// this));
// return OpStatus::OK;
// }
/***********************************************************************************
** MergeSort (copied and modified from optreemodel)
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::MergeSort(UINTPTR* array, UINTPTR* temp_array, INT32 left, INT32 right)
{
if (left < right)
{
INT32 center = (left + right) / 2;
MergeSort(array, temp_array, left, center);
MergeSort(array, temp_array, center + 1, right);
Merge(array, temp_array, left, center + 1, right);
}
}
/***********************************************************************************
** Merge
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::Merge(UINTPTR* array, UINTPTR* temp_array, INT32 left, INT32 right, INT32 right_end)
{
INT32 left_end = right - 1;
INT32 temp_pos = left;
INT32 count = right_end - left + 1;
while (left <= left_end && right <= right_end)
{
HistoryModelPage* left_item = (HistoryModelPage*) array[left];
HistoryModelPage* right_item = (HistoryModelPage*) array[right];
temp_array[temp_pos++] = ComparePopularity(left_item, right_item) <= 0 ?
array[left++] :
array[right++];
}
while (left <= left_end)
{
temp_array[temp_pos++] = array[left++];
}
while (right <= right_end)
{
temp_array[temp_pos++] = array[right++];
}
for (INT32 i = 0; i < count; i++, right_end--)
{
array[right_end] = temp_array[right_end];
}
}
/***********************************************************************************
** ComparePopularity
**
** @param
**
** @return
***********************************************************************************/
INT32 DesktopHistoryModel::ComparePopularity(HistoryModelPage* item_1, HistoryModelPage* item_2)
{
if(item_1->GetAverageInterval() < item_2->GetAverageInterval())
return -1;
if(item_1->GetAverageInterval() > item_2->GetAverageInterval())
return 1;
return 0;
}
/***********************************************************************************
** GetTopItems
**
** @param
**
** @return OpStatus::OK (or OpStatus::ERR_NO_MEMORY)
***********************************************************************************/
OP_STATUS DesktopHistoryModel::GetTopItems(OpVector<HistoryModelPage> &itemVector, INT32 num_items)
{
if(m_CoreValid)
{
INT32 table_count = m_model->GetCount();
UINTPTR* sort_array = OP_NEWA(UINTPTR, table_count * 2);
if (!sort_array)
return OpStatus::ERR_NO_MEMORY;
UINTPTR* temp_array = sort_array + table_count;
HistoryPage* core_item = 0;
INT32 i;
for(i = 0; i < table_count; i++)
{
core_item = m_model->GetItemAtPosition(i);
sort_array[i] = 0;
if(core_item)
{
HistoryItem::Listener* listener = GetListener(core_item);
HistoryModelPage* item;
if(!listener)
{
item = OP_NEW(HistoryModelPage, (core_item));
if (!item)
break;
if (!item->GetSimpleItem()) // OOM during construction
{
OP_DELETE(item);
break;
}
}
else
{
item = (HistoryModelPage*) listener;
}
sort_array[i] = (UINTPTR) item;
}
else
break;
}
//Number of items retrieved should be equal the number of items in the model
OP_ASSERT(i == table_count);
MergeSort(sort_array, temp_array, 0, table_count - 1);
for(INT32 j = 0, index = 0; j < num_items && index < i; index++)
{
HistoryModelPage* item = (HistoryModelPage*) sort_array[index];
if(item->GetAverageInterval() >= 0)
{
itemVector.Add(item);
j++;
}
}
OP_DELETEA(sort_array);
}
return OpStatus::OK;
}
OP_STATUS DesktopHistoryModel::GetSimpleItems(const OpStringC& search_text, OpVector<HistoryAutocompleteModelItem> &itemVector)
{
OpVector<HistoryPage> result;
RETURN_IF_ERROR(g_globalHistory->GetItems(search_text.CStr(), result));
HistoryModelPage* page = 0;
for(UINT i = 0; i < result.GetCount(); i++)
{
HistoryPage* history_page = result.Get(i);
page = GetPage(history_page);
if(!history_page || !page)
break;
// This is the display url, it is handled elsewhere.
if(history_page->IsBookmarked() && !history_page->GetListenerByType(OpTypedObject::BOOKMARK_TYPE))
continue;
HistoryAutocompleteModelItem* item = page->GetSimpleItem();
if (history_page->IsBookmarked() || history_page->IsNick())
{
item->SetSearchType(HistoryAutocompleteModelItem::BOOKMARK);
RETURN_IF_ERROR(itemVector.Add(item));
}
else
{
item->SetSearchType(PageBasedAutocompleteItem::HISTORY);
RETURN_IF_ERROR(itemVector.Add(item));
}
}
return OpStatus::OK;
}
OP_STATUS DesktopHistoryModel::GetOperaPages(const OpStringC& search_page, OpVector<PageBasedAutocompleteItem>& opera_pages)
{
OpString whole_string;
RETURN_IF_ERROR(whole_string.Set("opera:"));
RETURN_IF_ERROR(whole_string.Append(search_page));
OpVector<HistoryPage> items;
RETURN_IF_ERROR(g_globalHistory->GetItems(whole_string.CStr(), items));
for(UINT i = 0; i < items.GetCount(); ++i)
{
HistoryPage* history_page = items.Get(i);
HistoryModelPage* page = GetPage(history_page);
if (page && history_page->IsOperaPage())
{
RETURN_IF_ERROR(opera_pages.Add(page->GetSimpleItem()));
}
}
return OpStatus::OK;
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::DeleteAllItems()
{
if(m_CoreValid)
{
m_model->DeleteAllItems();
m_model->Save(TRUE);
if(g_url_api)
{
URL history_url = g_url_api->GetURL("opera:history");
history_url.Unload();
}
}
}
/***********************************************************************************
** Save
**
**
**
** @return OpStatus::OK (or result of core history Save())
***********************************************************************************/
OP_STATUS DesktopHistoryModel::Save(BOOL force)
{
if(m_CoreValid)
{
return m_model->Save(force);
}
return OpStatus::OK;
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
BOOL DesktopHistoryModel::IsLocalFileURL(const OpStringC & url, OpString & stripped)
{
if(m_CoreValid)
{
return m_model->IsLocalFileURL(url, stripped);
}
return FALSE;
}
/***********************************************************************************
** OnCompareItems
**
** @param
**
** @return
***********************************************************************************/
INT32 DesktopHistoryModel::OnCompareItems(OpTreeModel* tree_model,
OpTreeModelItem* item0,
OpTreeModelItem* item1)
{
if(item0->GetType() != OpTypedObject::FOLDER_TYPE ||
item1->GetType() != OpTypedObject::FOLDER_TYPE )
return 0;
HistoryModelItem *folder0 = static_cast<HistoryModelItem*>(item0);
HistoryModelItem *folder1 = static_cast<HistoryModelItem*>(item1);
return uni_stricmp(folder0->GetTitle().CStr(), folder1->GetTitle().CStr());
}
/***********************************************************************************
** GetTimeFolder
**
** @param
**
** @return
***********************************************************************************/
HistoryModelTimeFolder* DesktopHistoryModel::GetTimeFolder(TimePeriod period)
{
return m_timefolders[period];
}
/***********************************************************************************
** AddItem_To_TimeVector
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::AddItem_To_TimeVector(HistoryModelPage* item)
{
HistoryModelSiteFolder* site = item->GetSiteFolder();
//Item must have site
OP_ASSERT(site);
if(!site)
return;
//Site must be a folder
OP_ASSERT(site->GetType() == OpTypedObject::FOLDER_TYPE);
if(site->GetType() != OpTypedObject::FOLDER_TYPE)
return;
time_t now = g_timecache->CurrentTime();
time_t acc = item->GetAccessed();
time_t elapsed = now - acc;
time_t today_sec = m_model->SecondsSinceMidnight();
time_t yesterday_sec = today_sec + 24*60*60;
time_t last_week_sec = yesterday_sec + 7*24*60*60;
time_t last_month_sec = last_week_sec + 28*24*60*60;
TimePeriod period;
if (elapsed < today_sec) //Since midnight
{
period = TODAY;
}
else if (elapsed < yesterday_sec) //Yesterday
{
period = YESTERDAY;
}
else if (elapsed < last_week_sec) //The week before yesterday
{
period = WEEK;
}
else if (elapsed < last_month_sec) //Last 4 weeks before last week
{
period = MONTH;
}
else //Older
{
period = OLDER;
}
HistoryModelSiteSubFolder* subfolder = site->GetSubFolder(period);
if (subfolder) // GetSubFolder returns NULL on OOM
{
if(!subfolder->GetModel())
{
INT32 index = GetIndexByItem(GetTimeFolder(period));
AddSorted(subfolder, index);
}
subfolder->AddChildFirst(item);
}
}
/***********************************************************************************
** AddItem_To_OldVector
**
** @param
**
**
***********************************************************************************/
void DesktopHistoryModel::AddItem_To_OldVector(HistoryModelPage* item, BOOL first)
{
BOOL test = FALSE;
if(test)
{
time_t now = g_timecache->CurrentTime();
time_t acc = item->GetAccessed();
time_t elapsed = now - acc;
time_t today_sec = m_model->SecondsSinceMidnight();
time_t yesterday_sec = today_sec + 86400;
time_t last_week_sec = yesterday_sec + 604800;
time_t last_month_sec = last_week_sec + 2419200;
if (elapsed < today_sec) //Since midnight
{
if(first)
GetTimeFolder(TODAY)->AddChildFirst(item);
else
GetTimeFolder(TODAY)->AddChildLast(item);
}
else if (elapsed < yesterday_sec) //Yesterday
{
GetTimeFolder(YESTERDAY)->AddChildLast(item);
}
else if (elapsed < last_week_sec) //The week before yesterday
{
GetTimeFolder(WEEK)->AddChildLast(item);
}
else if (elapsed < last_month_sec) //Last 4 weeks before last week
{
GetTimeFolder(MONTH)->AddChildLast(item);
}
else //Older
{
GetTimeFolder(OLDER)->AddChildLast(item);
}
}
else
AddFirst(item);
}
/***********************************************************************************
** MakeTimeVector
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::MakeTimeVector()
{
if(m_CoreValid)
{
HistoryPage* core_item = 0;
HistoryModelPage* item = 0;
AddLast(GetTimeFolder(TODAY));
AddLast(GetTimeFolder(YESTERDAY));
AddLast(GetTimeFolder(WEEK));
AddLast(GetTimeFolder(MONTH));
AddLast(GetTimeFolder(OLDER));
INT32 i;
for(i = 0; i < m_model->GetCount(); i++)
{
core_item = m_model->GetItemAtPosition(i);
if(core_item)
{
HistoryItem::Listener* listener = GetListener(core_item);
if(!listener)
{
item = OP_NEW(HistoryModelPage, (core_item));
if (!item)
continue;
if (!item->GetSimpleItem()) // OOM during construction
{
OP_DELETE(item);
continue;
}
}
else
{
item = (HistoryModelPage*) listener;
}
item->UpdateSimpleItem();
AddItem_To_TimeVector(item);
}
else
break;
}
}
}
/***********************************************************************************
** MakeServerVector
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::MakeServerVector()
{
if(m_CoreValid)
{
HistoryPage* core_item = 0;
OpVector<HistoryPage> loc_vector;
HistoryModelPage* item = 0;
m_model->GetHistoryItems(loc_vector);
for(UINT32 j = 0; j < loc_vector.GetCount(); j++)
{
core_item = (HistoryPage*) loc_vector.Get(j);
if(core_item->GetType() == OpTypedObject::HISTORY_ELEMENT_TYPE)
{
HistoryItem::Listener* listener = GetListener(core_item);
if(!listener)
{
item = OP_NEW(HistoryModelPage, (core_item));
if (!item)
continue;
if (!item->GetSimpleItem()) // OOM during construction
{
OP_DELETE(item);
continue;
}
}
else
{
item = (HistoryModelPage*) listener;
}
HistoryModelSiteFolder * folder = item->GetSiteFolder();
OP_ASSERT(folder); // All items should have a site folder
if(!folder) // Recovery
continue;
if(!folder->GetModel())
{
AddLast(folder);
}
item->UpdateSimpleItem();
folder->AddChildLast(item);
}
}
}
}
#ifdef HISTORY_BOOKMARK_VIEW
/***********************************************************************************
** MakeBookmarkVector
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::MakeBookmarkVector()
{
if(m_CoreValid)
{
HistoryPage* core_item = 0;
OpVector<HistoryPage> loc_vector;
HistoryModelPage* item = 0;
m_model->GetBookmarkItems(loc_vector);
for(UINT32 j = 0; j < loc_vector.GetCount(); j++)
{
core_item = (HistoryPage*) loc_vector.Get(j);
if(core_item->GetType() == OpTypedObject::HISTORY_ELEMENT_TYPE)
{
HistoryItem::Listener* listener = GetListener(core_item);
if(!listener)
{
item = OP_NEW(HistoryModelPage, (core_item));
if (!item)
continue;
if (!item->GetSimpleItem()) // OOM during construction
{
OP_DELETE(item);
continue;
}
}
else
{
item = (HistoryModelPage*) listener;
}
HistoryModelSiteFolder * folder = item->GetSiteFolder();
OP_ASSERT(folder); // All items should have a site folder
if(!folder) // Recovery
continue;
if(!folder->GetModel())
{
AddLast(folder);
}
item->UpdateSimpleItem();
folder->AddChildLast(item);
}
}
}
}
#endif //HISTORY_BOOKMARK_VIEW
/***********************************************************************************
** MakeOldVector
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::MakeOldVector()
{
if(m_CoreValid)
{
HistoryModelPage * item = 0;
HistoryPage * core_item = 0;
for(INT32 i = 0; i < m_model->GetCount(); i++)
{
core_item = (HistoryPage*) m_model->GetItemAtPosition(i);
HistoryItem::Listener* listener = GetListener(core_item);
if(!listener)
{
item = OP_NEW(HistoryModelPage, (core_item));
if (!item)
continue;
if (!item->GetSimpleItem()) // OOM during construction
{
OP_DELETE(item);
continue;
}
}
else
{
item = (HistoryModelPage*) listener;
}
if(item)
{
item->UpdateSimpleItem();
AddLast(item);
}
else
break;
}
}
}
/* ------------------ OpTreeModel interface ---------------------------------------*/
/***********************************************************************************
** GetColumnData - Implementing the OpTreeModel interface
**
** @param column_data
**
** @return OP_STATUS
***********************************************************************************/
OP_STATUS DesktopHistoryModel::GetColumnData(ColumnData* column_data)
{
Str::LocaleString str_id = Str::NOT_A_STRING;
switch(column_data->column)
{
case 0: str_id = Str::DI_ID_HLFILEPROP_FNAME_LABEL; break;
case 1: str_id = Str::DI_ID_EDITURL_URLLABEL; break;
case 2: str_id = Str::DI_IDLABEL_HL_LASTVISITED; break;
case 3: str_id = Str::S_POPULARITY; break;
default:
return OpStatus::ERR;
}
return g_languageManager->GetString(str_id, column_data->text);
}
#ifdef ACCESSIBILITY_EXTENSION_SUPPORT
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
OP_STATUS DesktopHistoryModel::GetTypeString(OpString& type_string)
{
return g_languageManager->GetString(Str::M_VIEW_HOTLIST_MENU_HISTORY, type_string);
}
#endif
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
OP_STATUS DesktopHistoryModel::AddDesktopHistoryModelListener(DesktopHistoryModelListener* listener)
{
RETURN_IF_ERROR(m_listeners.Add(listener));
return OpStatus::OK;
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
OP_STATUS DesktopHistoryModel::RemoveDesktopHistoryModelListener(DesktopHistoryModelListener* listener)
{
return m_listeners.Remove(listener);
}
/***********************************************************************************
**
**
**
**
**
***********************************************************************************/
void DesktopHistoryModel::BroadcastHistoryModelItemDestroyed(HistoryModelItem* item)
{
for (OpListenersIterator iterator(m_listeners); m_listeners.HasNext(iterator);)
{
m_listeners.GetNext(iterator)->OnDesktopHistoryModelItemDeleted(item);
}
}
|
#include <math.h>
#include <array>
#include <deque>
#include <iostream>
#include <limits.h>
#include "Neighbor.h"
using namespace std;
// Constructors
Neighbor::Neighbor() : GrowArray() {};
Neighbor::Neighbor(int i) : GrowArray(i) {};
Neighbor::Neighbor(int i, int j) : GrowArray(i, j) {};
// Destructor
Neighbor::~Neighbor() {};
// Generator
void Neighbor::GeneratePeriodic() {
// If it's a left or right shift
if ((lrshift != 0) && (udshift == 0)) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < array[i].size(); ++j) {
if (j + lrshift < 0) {
array[i][j] = array[i].size() + j + lrshift;
} else {
array[i][j] = (j + lrshift) % array[i].size();
}
}
}
}
else if ((lrshift == 0) && (udshift != 0)) { // Note: For right now, I'm not sure if this works with anything but a +/- 1 for udshift
// Also note: in its current form, a column with only one element will become its own neighbor. Not sure if I care, but worth noting
if (array.size() != 1){
for (int i = 0; i < rows; ++ i) {
for (int j = 0; j < array[i].size(); ++j) {
// unsigned int multiplier = 1;
int idx2test = i + udshift;
if (checkExist(idx2test, j) == true) { //if it's a valid array point
array[i][j] = idx2test;
} else {
while (checkExist(idx2test, j) == false) {
if (idx2test < 0) { // circles back to bottom row of the array
idx2test = rows - 1;
// multiplier = 1;
}
else if (idx2test > rows - 1) { // circles back to 0th row of array
idx2test = idx2test % rows;
// multiplier = 1;
} else {
// multiplier = multiplier + 1;
idx2test = idx2test + udshift;
}
}
array[i][j] = idx2test;
}
}
}
}
else {
for (int i = 0; i < rows; ++ i) {
for (int j = 0; j < cols; ++j) {
array[i][j] = 0;
}
}
}
}
else if ((lrshift == 0) && (udshift == 0)) {
cout << "Need to define a shift for Neighbors" << endl;
} else {
cout << "Error: Only one directional shift supported at this time" << endl;
}
}
void Neighbor::Generate_Old() {
for (short int i=0; i < rows; ++i){
for (short int j=0; j < array[i].size(); ++j){
if ((lrshift != 0) && (udshift == 0)) {
if (j + lrshift < 0) {
array[i][j] = cols + j + lrshift;
} else {
array[i][j] = (j + lrshift) % cols;
}
} else if ((lrshift == 0) && (udshift != 0)) {
if (i + udshift < 0) {
array[i][j] = rows + i + udshift;
} else {
array[i][j] = (i + udshift) % rows;
}
} else if ((lrshift == 0) && (udshift == 0)) {
cout << "Need to define a shift for Neighbors" << endl;
} else {
cout << "Error: Only one directional shift supported at this time" << endl;
}
}
}
}
// Zero-Flux Boundary Condition Generator
void Neighbor::GenerateZFBC_Old() {
for (short int i=0; i < rows; ++i){
for (short int j=0; j < cols; ++j){
if ((lrshift != 0) && (udshift == 0)) {
if ((i + lrshift < 0) | (i + lrshift > rows - 1)) {
array[i][j] = USHRT_MAX;
} else {
array[i][j] = i + lrshift;
}
} else if ((lrshift == 0) && (udshift != 0)) {
if ((j + udshift < 0) | (j + udshift > cols - 1)) {
array[i][j] = USHRT_MAX;
} else {
array[i][j] = j + udshift;
}
} else if ((lrshift == 0) && (udshift == 0)) {
cout << "Need to define a shift for Neighbors" << endl;
} else {
cout << "Error: Only one directional shift supported at this time" << endl;
}
}
}
}
// New ZFBC Generator (to work with nonconstant column size)
void Neighbor::GenerateZFBC() {
//First, if it's a left-right shift
if ((lrshift != 0) && (udshift == 0)) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < array[i].size(); ++j) {
if ((j + lrshift < 0) | (j + lrshift > array[i].size() - 1)) {
array[i][j] = SHRT_MAX;
} else {
array[i][j] = j + lrshift;
}
}
}
}
else if ((lrshift == 0) && (udshift != 0)) {
for (int i = 0; i < rows; ++i) {
int idx2test = i + udshift;
for (int j = 0; j < array[i].size(); ++j) {
if ((idx2test < 0) | (idx2test > rows -1)) {
array[i][j] = SHRT_MAX;
}
else if (checkExist(idx2test, j) == true) {
array[i][j] = idx2test;
}
else {
array[i][j] = SHRT_MAX;
}
}
}
}
}
void Neighbor::pickGenerator(){
if (boundaryCondition == "Periodic") {
GeneratePeriodic();
}
else if (boundaryCondition == "ZeroFlux") {
GenerateZFBC();
}
else {
cout << "Error in Boundary Condition Choice" << endl;
}
}
//Growth functions //Note: extend shouldn't do anything, just there as placeholder to match form of parent function (necessary to override)
void Neighbor::grow1D(bool extend) {
//Add one space to each row
int numRows = array.size();
for (int i =0; i < numRows; ++i){
array[i].push_back(0);
}
cols = cols+1;
// if (cols != array[0].size()){
// cout << "Error in column indexing" << endl;
// }
//Re-generate new values
pickGenerator();
}
void Neighbor::grow2DSquare(bool vertextend, bool horizextend) {
// Add new rows to top and bottom
deque<unsigned short> newRow(cols, 0);
array.push_front(newRow);
array.push_back(newRow);
rows = rows + 2;
// Adds new columns on sides
for (int j = 0; j < rows; ++j) {
array[j].push_front(0);
array[j].push_back(0);
}
cols = cols + 2;
// Re-generate new values
pickGenerator();
// Error-check
if (rows != array.size()){
cout << "Error in row indexing" << endl;
}
// if (cols != array.front().size()){
// cout << "Error in column indexing" << endl;
// }
}
void Neighbor::grow2Rows(bool vertextend) {
deque<unsigned short> newRow(cols, 0);
array.push_front(newRow);
array.push_back(newRow);
rows = rows + 2;
pickGenerator();
if (rows != array.size()) {
cout << "Error in row indexing" << endl;
}
}
void Neighbor::grow2Cols(bool horizextend) {
for (int j = 0; j < rows; ++j) {
array[j].push_front(0);
array[j].push_back(0);
}
cols = cols + 2;
pickGenerator();
// if (cols != array[0].size()) {
// cout << "Error in column indexing" << endl;
// }
}
void Neighbor::grow2DBasic(bool vertextend, bool horizextend) {
//Add a new row
deque<unsigned short> newRow;
for (unsigned short k = 0; k < cols; ++k) {
newRow.push_back(0);
}
array.push_back(newRow);
rows = rows + 1;
//Add new column
for (int i = 0; i < rows; ++i){
array[i].push_back(0);
}
cols = cols + 1;
if (array.size() != rows){
throw invalid_argument("Error: row definition incorrect");
}
if (array[rows - 1].size() != cols){
throw invalid_argument("Error: column definition incorrect");
}
// Re-generate values (for rectangular array)
pickGenerator();
}
void Neighbor::grow1ColBack(bool horizextend) {
for (int j = 0; j < rows; ++j) {
array[j].push_back(0);
}
cols = cols + 1;
pickGenerator();
// if (cols != array[0].size()) {
// throw invalid_argument("Error in column indexing");
// }
}
void Neighbor::grow1ColFront(bool horizextend) {
for (int j = 0; j < rows; ++j) {
array[j].push_front(0);
}
cols = cols + 1;
pickGenerator();
}
void Neighbor::growTrap(bool vertextend, bool horizextend) {
//First, add a column to the left
for (unsigned short i = 0; i < rows; ++i) {
array[i].push_front(0);
}
//Then, add new rows
deque<unsigned short> newDeque(1, 0);
array.push_front(newDeque);
array.push_back(newDeque);
//Update indices
rows = rows + 2;
cols = cols + 1;
pickGenerator();
if (rows != array.size()) {
cout << "Error in row indexing" << endl;
}
}
// Switch between two different types of growth
void Neighbor::growthSwitcher(bool vertextend, bool horizextend) {
growthCounter = growthCounter + 1;
if (growthCounter != ratio) {
grow1ColFront(false);
} else {
growTrap(false, false);
growthCounter = 0;
}
}
|
/*
* File: maildrops.h
* Author: Wouter Van Rossem
*
*/
#ifndef _MAILDROPS_H
#define _MAILDROPS_H
#include <dvthread/thread.h>
#include <map>
#include <string>
#include <utility>
#include <string>
#include <sstream>
#include "maildrop.h"
#include "player.h"
/** The Maildrops class manages the different maildrops
*/
class Maildrops
{
public:
/** Constructor for Maildrops
* @param folder_path String representing the folder where
* the maildrops are located
*/
Maildrops (std::string folder_path);
/** Destructor for Maildrops
* Deletes all the maildrops in the map
*/
virtual ~Maildrops ();
/* Type of pair from name of the maildrop to the corresponding maildrop */
typedef std::pair<std::string, Maildrop*> Pair;
/* Type of map from name of the maildrop to the corresponding maildrop */
typedef std::map<std::string, Maildrop*> Map;
/** Find the maildrop of the given player
* @param player Player who's maildrop we need to find
* @return The maildrop of the player
*/
Maildrop* find_maildrop (const Player* player) const;
/** Add a maildrop for the player
* The name of the player will be used to find the path to the maildrop
* @param player Player who's maildrop we need to create
* @return A bool indicating if the operation succeeded
*/
bool new_maildrop (const Player* player);
/** Remove the maildrop of the player
* @param player Player who's maildrop we need to delete
*/
void remove_maildrop (const Player* player);
private:
/* Private copy constructor */
Maildrops (const Maildrops& orig);
/** Collection of maildrops
* Key = name of the maildrop
* Value = the maildrop
*/
Map _maildrops;
/* String indicating the path to the maildrops */
std::string _folder_path;
};
#endif /* _MAILDROPS_H */
|
//
// main.cpp
// 1100
//
// Created by Pedro Neves Alvarez on 7/10/17.
// Copyright ยฉ 2017 Pedro Neves Alvarez. All rights reserved.
//
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <vector>
using namespace std;
map<string,vector<string> > graph;
map<string, bool> visited;
map<string, int> distances;
queue<string> q;
void create_chess_graph() {
int i, j;
string letters = "-abcdefgh";
string numbers = "-12345678";
string li, nj;
for (i = 1; i <= 8; i++) {
for (j = 1; j <= 8; j++) {
li = letters[i];
nj = numbers[j];
if (i + 2 <= 8 && j + 1 <= 8) {
graph[li + nj].push_back(
letters.substr(i + 2, 1) + numbers.substr(j + 1, 1));
}
if (i + 2 <= 8 && j - 1 >= 1) {
graph[li + nj].push_back(
letters.substr(i + 2, 1) + numbers.substr(j - 1, 1));
}
if (i - 2 >= 1 && j + 1 <= 8) {
graph[li + nj].push_back(
letters.substr(i - 2, 1) + numbers.substr(j + 1, 1));
}
if (i - 2 >= 1 && j - 1 >= 1) {
graph[li + nj].push_back(
letters.substr(i - 2, 1) + numbers.substr(j - 1, 1));
}
if (i + 1 <= 8 && j + 2 <= 8) {
graph[li + nj].push_back(
letters.substr(i + 1, 1) + numbers.substr(j + 2, 1));
}
if (i + 1 <= 8 && j - 2 >= 1) {
graph[li + nj].push_back(
letters.substr(i + 1, 1) + numbers.substr(j - 2, 1));
}
if (i - 1 >= 1 && j + 2 <= 8) {
graph[li + nj].push_back(
letters.substr(i - 1, 1) + numbers.substr(j + 2, 1));
}
if (i - 1 >= 1 && j - 2 >= 1) {
graph[li + nj].push_back(
letters.substr(i - 1, 1) + numbers.substr(j - 2, 1));
}
}
}
}
void unvisit() {
int i, j;
string letters = "-abcdefgh";
string numbers = "-12345678";
string li, nj;
for (i = 1; i <= 8; i++) {
for (j = 1; j <= 8; j++) {
li = letters[i];
nj = numbers[j];
visited[li + nj] = false;
}
}
}
int bfs(string start, string goal) {
vector<string>::iterator it;
unvisit();
visited[start] = true;
q.push(start);
distances[start] = 0;
while (!q.empty()) {
std::string current = q.front();
q.pop();
for (it = graph[current].begin(); it != graph[current].end(); it++) {
if (!visited[*it]) {
visited[*it] = true;
q.push(*it);
distances[*it] = distances[current] + 1;
}
}
}
return distances[goal];
}
int main() {
string from, to;
create_chess_graph();
while (std::cin >> from >> to) {
cout << "To get from " << from;
cout << " to " << to << " takes " << bfs(from, to);
cout << " knight moves." << endl;
distances.clear();
}
return 0;
}
|
#include "llvm/Pass.h"
#include "llvm/IR/Function.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/InstIterator.h"
#include <unordered_map>
#include <string>
using namespace llvm;
namespace{
struct countInstrPass:public FunctionPass {
static char ID;
countInstrPass() : FunctionPass(ID) {}
bool runOnFunction(Function &F) override {
std::unordered_map <std::string,int> dic;
for(inst_iterator I=inst_begin(F),End=inst_end(F);I!=End;I++){
std::string instrName=I->getOpcodeName();
if(dic.find(instrName)==dic.end()){
dic[instrName]=1;
}else{
dic[instrName]=dic[instrName]+1;
}
}
std::unordered_map<std::string,int>::iterator itr;
for(itr=dic.begin();itr!=dic.end();itr++){
errs()<<itr->first<<'\t'<<itr->second<<'\n';
}
return false;
}
};
}
char countInstrPass::ID = 0;
static RegisterPass<countInstrPass> X("cse231-csi", "Developed to statically count the number of instructions", false /* Only looks at CFG */, false /* Analysis Pass */);
|
class Solution{
public:
vector<string> AllPossibleStrings(string s){
// only gravity will pull me down
// Power Set
int n=s.size();
vector<string> res(pow(2,n)-1);
for(int i=1; i<pow(2,n); i++) {
int x = i, idx=0, l=32;
while(l--) {
if(x&1)
res[i-1] += s[idx];
idx++;
x = x>>1;
}
}
sort(res.begin(), res.end());
return res;
}
};
|
#pragma once
#ifndef _LEAGUEITEMDATABASE_H
#define _LEAGUEITEMDATABASE_H
#include "common.h"
#include "LeagueItemData.h"
#include "opencv2/core.hpp"
/*
* Contains mapping of the item ID to the item data.
* It also contains the mapping of the location on the database image to the item ID.
*/
class LeagueItemDatabase {
public:
static std::shared_ptr<const LeagueItemDatabase> Get();
~LeagueItemDatabase();
cv::Mat GetDatabaseImage() const { return mDatabaseImage; }
// Retrieves a constant pointer to database
const std::map<std::string, PtrLeagueItemData>* GetDatabase() const { return &mData; }
PtrLeagueItemData GetItem(int x, int y) const;
private:
// Load in the database file to creating the mapping of item ID to item data -- also loads in the image as well
void LoadItemDatabase(std::string& dir, std::string& fileName);
// Load in the database IMAGE to create the mapping of image location to string ID.
void LoadItemDatabaseImage();
// Utility function to make our database image. This concatenates all the images into a
// giant image (it tries to make it as square as possible).
cv::Mat CreateDatabaseImage(std::string& dir);
// Database (Two Parts)
// Part 1 - From ID to Item Data
// Part 2 - From Image Location to ID
// Why? Because we use template matching to find the item and therefore will have a match at some point in the image and we want
// to translate that point into the right item.
std::map<std::string, PtrLeagueItemData> mData;
// How to use? When we get a pixel location like x: 100 y: 100, then we want to translate that to the 'image coordinate' which for a 10x10 item image
// would be x:10 , y:10. Then we translate that into a single index (y * x_width + x) to index into mLocationData. Easy!
std::vector<std::string> mLocationData;
// Database Image.
cv::Mat mDatabaseImage;
int numImageDim;
LeagueItemDatabase();
const std::string ItemDataSection = "Items";
const std::string DataDirectoryName = "ItemDataDirectory";
const std::string DatabaseFilenameName = "ItemDatabaseFilename";
const std::string DatabaseImageFilenameName = "ItemDatabaseImageFilename";
const std::string ImageDirectoryName = "ImageDirectory";
};
#endif
|
/*
The MIT License (MIT)
Copyright (c) 2014 nightblizard
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "Session.h"
Session::Session(const Poco::Net::StreamSocket& socket) :
TCPServerConnection(socket)
{
}
void Session::run()
{
std::cout << "New connection from: " << socket().peerAddress().host().toString() << std::endl;
bool isOpen = true;
Poco::Timespan timeout(10, 0);
unsigned char incommingBuffer[1000];
while (isOpen)
{
if (socket().poll(timeout, Poco::Net::Socket::SELECT_READ) == false)
std::cout << "TIMEOUT!" << std::endl;
else
{
std::cout << "RX EVENT!!! --->";
int numBytes = 0;
try
{
numBytes = socket().receiveBytes(incommingBuffer, sizeof(incommingBuffer));
} catch (Poco::Exception& exc)
{
std::cerr << "Network error: " << exc.displayText() << std::endl;
_alive = false;
isOpen = false;
}
if (numBytes == 0)
{
std::cout << "Client closes connection!" << std::endl;
_alive = false;
isOpen = false;
} else
{
std::cout << "Receiving numBytes: " << numBytes << std::endl;
char* name = ((char*)(incommingBuffer + 4));
std::cout << name << std::endl;
}
}
}
std::cout << "Connection finished!" << std::endl;
}
|
#include <Adafruit_NeoPixel.h>
#include "Glowing.h"
Glowing::Glowing(void) { }
void Glowing::reset(variables_t *vars) {
vars->lastTime = 0;
vars->isPausing = false;
}
void Glowing::loop(variables_t *vars) {
int k = millis()*10 % 127;
int i;
if(vars->lastTime > k) {
if(vars->isPausing) {
vars->isPausing = false;
}else{
vars->isPausing = true;
}
}
vars->lastTime = k;
if(vars->defColInPallet) { //red
for (i = 0; i < vars->color_len; i++) {//draw
if(vars->isPausing) {
vars->color[i] = Adafruit_NeoPixel::Color(0,127-k,0);
}else{
vars->color[i] = Adafruit_NeoPixel::Color(0,k,0);
}
}
}else{//blue alliance
for (i = 0; i < vars->color_len; i++) {//draw
if(vars->isPausing) {
vars->color[i] = Adafruit_NeoPixel::Color(0,0,127-k);
}else{
vars->color[i] = Adafruit_NeoPixel::Color(0,0,k);
}
}
}
}
|
๏ปฟ#pragma once
#include <wrl/client.h>
#include <d3d11_1.h>
#include <d2d1_1.h>
#include <d2d1effects.h>
#include <dwrite_1.h>
#include <wincodec.h>
#include <DirectXMath.h>
#include <agile.h>
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml::Controls;
namespace OpenGraphicsLibrary
{
[Windows::Foundation::Metadata::WebHostHidden]
public ref class Graphics sealed
{
public:
Graphics();
bool Initialize(CoreWindow^ window, SwapChainBackgroundPanel^ panel, float dpi);
void UpdateTextPosition(Windows::Foundation::Point deltaTextPosition);
bool UpdateForWindowSizeChange();
bool SetDpi(float dpi);
bool ValidateDevice();
void Update(float timeTotal, float timeDelta);
bool Render();
bool Present();
private:
bool CreateDeviceIndependentResources();
bool CreateDeviceResources();
bool CreateWindowSizeDependentResources();
float ConvertDipsToPixels(float dips);
bool HandleDeviceLost();
bool SetDisplayOrientation();
protected private:
Platform::Agile<Windows::UI::Core::CoreWindow> m_window;
Windows::UI::Xaml::Controls::SwapChainBackgroundPanel^ m_panel;
Microsoft::WRL::ComPtr<IDWriteFactory1> m_dwriteFactory;
Microsoft::WRL::ComPtr<IWICImagingFactory2> m_wicFactory;
Microsoft::WRL::ComPtr<ID3D11Device1> m_d3dDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext1> m_d3dContext;
Microsoft::WRL::ComPtr<IDXGISwapChain1> m_swapChain;
Microsoft::WRL::ComPtr<ID3D11RenderTargetView> m_d3dRenderTargetView;
Microsoft::WRL::ComPtr<ID2D1Factory1> m_d2dFactory;
Microsoft::WRL::ComPtr<ID2D1Device> m_d2dDevice;
Microsoft::WRL::ComPtr<ID2D1DeviceContext> m_d2dContext;
Microsoft::WRL::ComPtr<ID2D1Bitmap1> m_d2dTargetBitmap;
Microsoft::WRL::ComPtr<ID3D11DepthStencilView> m_d3dDepthStencilView;
D3D_FEATURE_LEVEL m_d3dFeatureLevel;
Windows::Foundation::Size m_d3dRenderTargetSize;
Windows::Foundation::Rect m_windowBounds;
float m_dpi;
Windows::Graphics::Display::DisplayOrientations m_orientation;
D2D1::Matrix3x2F m_orientationTransform2D;
DirectX::XMFLOAT4X4 m_orientationTransform3D;
Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> m_blackBrush;
Microsoft::WRL::ComPtr<IDWriteTextFormat> m_textFormat;
Microsoft::WRL::ComPtr<IDWriteTextLayout> m_textLayout;
DWRITE_TEXT_METRICS m_textMetrics;
Windows::Foundation::Point m_textPosition;
int m_backgroundColorIndex;
int m_nWidth;
int m_nHeight;
HWND m_hWnd;
HDC m_hDC;
HGLRC m_hGLRC;
};
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2012 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 QUICK_WIDGET_H
#define QUICK_WIDGET_H
#include "adjunct/desktop_util/adt/typedobject.h"
#include "adjunct/quick_toolkit/widgets/WidgetSizes.h"
#include "modules/widgets/OpWidget.h"
class QuickWidgetContainer;
/** @brief An object that can be used by layouters
* The QuickWidget interface includes all functions necessary for the
* layouters to do their business.
*
* The size of a widget as determined by a layouter is calculated by taking
* these values into account:
* - Minimum size: Widget should never be smaller than this size.
* eg. a single-line text label should always be big enough to fit its text.
*
* - Nominal size: A good initial size for a widget
* Often equal to the minimum size, but doesn't have to be. This can be used
* to determine the initial size to use when creating a window to fit
* widgets in.
*
* - Preferred size: If possible, the widget should be this big (also called
* maximum size). Can be Infinity or Fill (see above). If the preferred
* size is equal to the minimum size, the widget has a fixed size (size
* never changes).
* eg. a single-line text label has a fixed size, but a text input field can
* grow to make input easier.
*
* - Margins: If the widget is placed next to another widget, at least this
* distance should be maintained between the widgets.
* eg. a radio button on MacOS X should leave 6 pixels above and below it.
*
* Current layouters that will respect these values include QuickGrid and
* QuickStackLayout. Each layouter is a QuickWidget itself, so that it can
* be included in complex layouts, to create for example a 3x2 grid with a
* horizontal stack in each cell.
*
* == Is an OpWidget needed to make a QuickWidget?
* No. An OpWidget is needed when there is something to be painted onto the
* screen or when interaction with a widget is necessary. Most layouting
* widgets don't need to do that. If it's not necessary, try avoiding using
* an OpWidget, since it takes a lot of memory and includes a lot of
* functionality.
*
* == How to make a QuickWidget from an OpWidget?
* Use the predefined widgets in QuickWidgetDecls.h, or create your own
* QuickOpWidgetWrapper if necessary. Simple widgets can be wrapped using
* QuickWrap().
*/
class QuickWidget : public TypedObject
{
IMPLEMENT_TYPEDOBJECT(TypedObject);
public:
QuickWidget();
virtual ~QuickWidget() {}
/** @return Minimum width at which the widget is still usable, in pixels
*/
unsigned GetMinimumWidth();
/** @param width Width for which minimum height is required, or WidgetSizes::UseDefault
* @return Minimum height at which the widget is still usable, in pixels
*/
unsigned GetMinimumHeight(unsigned width = WidgetSizes::UseDefault);
/** @return Nominal width for this widget, can be used as initial size
*
* GetMinimumWidth <= GetNominalWidth() can be assumed
*/
unsigned GetNominalWidth();
/** @param width Width for which nominal height is required, or WidgetSizes::UseDefault
* @return Nominal height for this widget, can be used as initial size
*
* GetMinimumHeight <= GetNominalHeight() can be assumed
*/
unsigned GetNominalHeight(unsigned width = WidgetSizes::UseDefault);
/** @return Width that widget would need if infinite width was available, in pixels
* or WidgetSizes::Infinity / WidgetSizes::Fill
*
* GetNominalWidth() <= GetPreferredWidth() can be assumed
*/
unsigned GetPreferredWidth();
/** @param width Width for which preferred height is required, or WidgetSizes::UseDefault
* @return Height that widget would need if infinite height was available, in pixels
* or WidgetSizes::Infinity / WidgetSizes::Fill
*
* GetNominalHeight() <= GetPreferredHeight() can be assumed
*/
unsigned GetPreferredHeight(unsigned width = WidgetSizes::UseDefault);
/** @return Margins this widget requires on its sides
*/
WidgetSizes::Margins GetMargins();
/** @param minimum_width Desired minimum width in pixels, or WidgetSizes::UseDefault
*/
void SetMinimumWidth(unsigned minimum_width) { SetIfChanged(m_minimum_width, minimum_width); }
/** @param minimum_height Desired minimum height in pixels, or WidgetSizes::UseDefault
*/
void SetMinimumHeight(unsigned minimum_height) { SetIfChanged(m_minimum_height, minimum_height); }
/** @param nominal_width Desired nominal width in pixels, or WidgetSizes::UseDefault
*/
void SetNominalWidth(unsigned nominal_width) { SetIfChanged(m_nominal_width, nominal_width); }
/** @param nominal_height Desired nominal height in pixels, or WidgetSizes::UseDefault
*/
void SetNominalHeight(unsigned nominal_height) { SetIfChanged(m_nominal_height, nominal_height); }
/** @param preferred_width Desired preferred width in pixels, or
* WidgetSizes::UseDefault, WidgetSizes::Fill or WidgetSizes::Infinity
*/
void SetPreferredWidth(unsigned preferred_width) { SetIfChanged(m_preferred_width, preferred_width); }
/** @param preferred_height Desired preferred height in pixels, or
* WidgetSizes::UseDefault, WidgetSizes::Fill or WidgetSizes::Infinity
*/
void SetPreferredHeight(unsigned preferred_height) { SetIfChanged(m_preferred_height, preferred_height); }
/** @param fixed_width Desired fixed width in pixels
*/
void SetFixedWidth(unsigned fixed_width) { SetMinimumWidth(fixed_width); SetNominalWidth(fixed_width); SetPreferredWidth(fixed_width); }
/** @param fixed_height Desired fixed height in pixels
*/
void SetFixedHeight(unsigned fixed_height) { SetMinimumHeight(fixed_height); SetNominalHeight(fixed_height); SetPreferredHeight(fixed_height); }
/** Set margins needed on sides of widget
* @param margins List with desired margins, or WidgetSizes::UseDefault
*/
void SetMargins(const WidgetSizes::Margins& margins) { SetIfChanged(m_margins, margins); }
/** Set container for this widget
*/
virtual void SetContainer(QuickWidgetContainer* container) { m_container = container; }
/** Get container for this widget
*/
QuickWidgetContainer* GetContainer() const { return m_container; }
/** @return Whether widget has height that depends on width
* @note Using this will make your layout slower. Use widgets that
* have this property with care.
*/
virtual BOOL HeightDependsOnWidth() = 0;
/** Layout this widget in a given rectangle
* @param rect Rectangle in which widget should be layed out
*/
virtual OP_STATUS Layout(const OpRect& rect) = 0;
/** Layout this widget in a given rectangle within a container rectangle
*
* Call this version of Layout() from a QuickWidgetContainer to lay out
* contained widgets. It will account for UI direction automatically.
*
* @param rect Rectangle in which widget should be layed out
* @param container_rect Rectangle of the container the widget is in
*/
OP_STATUS Layout(const OpRect& rect, const OpRect& container_rect);
/** Set an OpWidget that should be the parent of this widget
* If your widget can be represented as an OpWidget,
* @param parent The OpWidget that serves as a parent to this object, or
* NULL to reset the parent
*/
virtual void SetParentOpWidget(OpWidget* parent) = 0;
/** Show widget */
virtual void Show() = 0;
/** Hide widget */
virtual void Hide() = 0;
/** @return Whether widget is currently visible */
virtual BOOL IsVisible() = 0;
/** Set whether widget should be enabled (can receive input events)
* @param enabled Whether widget should be enabled
*/
virtual void SetEnabled(BOOL enabled) = 0;
/** Set Z-order of widget */
virtual void SetZ(OpWidget::Z z) {}
protected:
// See explanation above about these measurements
virtual unsigned GetDefaultMinimumWidth() = 0;
virtual unsigned GetDefaultMinimumHeight(unsigned width) = 0;
virtual unsigned GetDefaultNominalWidth() = 0;
virtual unsigned GetDefaultNominalHeight(unsigned width) = 0;
virtual unsigned GetDefaultPreferredWidth() = 0;
virtual unsigned GetDefaultPreferredHeight(unsigned width) = 0;
virtual void GetDefaultMargins(WidgetSizes::Margins& margins) = 0;
void BroadcastContentsChanged();
private:
template<class T>
void SetIfChanged(T& property, T value) { if (property != value) { property = value; BroadcastContentsChanged(); } }
unsigned m_minimum_width;
unsigned m_minimum_height;
unsigned m_nominal_width;
unsigned m_nominal_height;
unsigned m_preferred_width;
unsigned m_preferred_height;
WidgetSizes::Margins m_margins;
QuickWidgetContainer* m_container;
};
#endif // QUICK_WIDGET_H
|
#include "libshared_and_static.h"
#ifndef MY_CUSTOM_CONTENT_ADDED
# error "MY_CUSTOM_CONTENT_ADDED not defined!"
#endif
int libshared_and_static::Class::method() const
{
return 0;
}
int libshared_and_static::Class::method_exported() const
{
return 0;
}
int libshared_and_static::Class::method_deprecated() const
{
return 0;
}
int libshared_and_static::Class::method_deprecated_exported() const
{
return 0;
}
int libshared_and_static::Class::method_excluded() const
{
return 0;
}
int const libshared_and_static::Class::data = 1;
int const libshared_and_static::Class::data_exported = 1;
int const libshared_and_static::Class::data_excluded = 1;
int libshared_and_static::ExportedClass::method() const
{
return 0;
}
int libshared_and_static::ExportedClass::method_deprecated() const
{
return 0;
}
int libshared_and_static::ExportedClass::method_excluded() const
{
return 0;
}
int const libshared_and_static::ExportedClass::data = 1;
int const libshared_and_static::ExportedClass::data_excluded = 1;
int libshared_and_static::ExcludedClass::method() const
{
return 0;
}
int libshared_and_static::ExcludedClass::method_exported() const
{
return 0;
}
int libshared_and_static::ExcludedClass::method_deprecated() const
{
return 0;
}
int libshared_and_static::ExcludedClass::method_deprecated_exported() const
{
return 0;
}
int libshared_and_static::ExcludedClass::method_excluded() const
{
return 0;
}
int const libshared_and_static::ExcludedClass::data = 1;
int const libshared_and_static::ExcludedClass::data_exported = 1;
int const libshared_and_static::ExcludedClass::data_excluded = 1;
int libshared_and_static::function()
{
return 0;
}
int libshared_and_static::function_exported()
{
return 0;
}
int libshared_and_static::function_deprecated()
{
return 0;
}
int libshared_and_static::function_deprecated_exported()
{
return 0;
}
int libshared_and_static::function_excluded()
{
return 0;
}
int const libshared_and_static::data = 1;
int const libshared_and_static::data_exported = 1;
int const libshared_and_static::data_excluded = 1;
void use_int(int)
{
}
|
#include "waittingdlg.h"
#include <QLabel>
#include <QMovie>
#include <QBoxLayout>
CWaittingDlg::CWaittingDlg(QWidget *parent)
: QDialog(parent, Qt::ToolTip), m_pLabMovie(NULL), m_pLabTips(NULL)
{
_initCtrls();
m_pMovie->start();
}
CWaittingDlg::~CWaittingDlg()
{
m_pMovie->stop();
delete m_pMovie;
delete m_pLabMovie;
delete m_pLabTips;
}
void CWaittingDlg::_initCtrls()
{
m_pLabMovie = new QLabel(this);
m_pLabMovie->setAlignment(Qt::AlignCenter);
m_pLabTips = new QLabel("่ฏท็ญๅพ
", this);
m_pLabTips->setAlignment(Qt::AlignCenter);
m_pMovie = new QMovie(":/new/prefix1/res/wait.gif");
m_pLabMovie->setMovie(m_pMovie);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(m_pLabMovie,7);
mainLayout->addWidget(m_pLabTips,3);
setLayout(mainLayout);
}
void CWaittingDlg::on_show_tips(const QString &tips)
{
m_pLabTips->setText(tips);
}
|
#pragma once
#include "../engine/core/Game.h"
#include "../engine/components/model/Mesh.h"
#include "../engine/components/model/Model.h"
#include "../engine/components/model/Material.h"
#include "../engine/scenegraph/Node.h"
#include "../engine/texture/Texture.h"
#include "../engine/shader/Shader.h"
class TestGame : public Game {
public:
TestGame() {}
void init();
void update(float delta);
void render();
private:
Node* cubeNodeTest;
Node* cubeNodeTest2;
Node* cubeNodeTest3;
};
|
/* ***** BEGIN LICENSE BLOCK *****
* FW4SPL - Copyright (C) IRCAD, 2009-2010.
* Distributed under the terms of the GNU Lesser General Public License (LGPL) as
* published by the Free Software Foundation.
* ****** END LICENSE BLOCK ****** */
#include <stdio.h> /* for printf */
#include <stdint.h>
#include <stdlib.h> /* for exit */
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sstream>
#include <iterator>
#include <exception>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/convenience.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/foreach.hpp>
#include <fwCore/base.hpp>
#include <fwTools/Factory.hpp>
#include <fwTools/dateAndTime.hpp>
#include <fwTools/fromIsoExtendedString.hpp>
#include <fwData/PatientDB.hpp>
#include <fwData/Patient.hpp>
#include <fwData/Study.hpp>
#include <fwData/Acquisition.hpp>
#include <fwData/Image.hpp>
#include <vtkImageWriter.h>
#include <vtkGDCMImageReader.h>
#include <vtkImageData.h>
#include <vtkStringArray.h>
#include <vtkImageChangeInformation.h>
#include <vtkMedicalImageProperties.h>
#include <vtkImageMapToColors.h>
#include <vtkSmartPointer.h>
#include <gdcmImageHelper.h>
#include <gdcmIPPSorter.h>
#include <gdcmFilename.h>
#include <gdcmTesting.h>
#include <gdcmSystem.h>
#include <gdcmTrace.h>
#include <gdcmDirectory.h>
#include <gdcmScanner.h>
#include <gdcmReader.h>
#include <gdcmIPPSorter.h>
#include <gdcmFilenameGenerator.h>
#include <gdcmAttribute.h>
#include <gdcmFile.h>
#include <vtkIO/vtk.hpp>
#include <vtkIO/helper/ProgressVtkToFw.hpp>
#include "vtkGdcmIO/DicomPatientDBReader.hpp"
#include "vtkGdcmIO/helper/GdcmHelper.hpp"
#ifndef vtkFloatingPointType
#define vtkFloatingPointType float
#endif
// Sort image using Instance Number:
bool mysort(gdcm::DataSet const & ds1, gdcm::DataSet const & ds2 )
{
gdcm::Attribute<0x0020,0x0013> at1; // Instance Number
at1.Set( ds1 );
gdcm::Attribute<0x0020,0x0013> at2;
at2.Set( ds2 );
return at1 < at2;
}
namespace vtkGdcmIO
{
//------------------------------------------------------------------------------
DicomPatientDBReader::DicomPatientDBReader() :
::fwData::location::enableFolder< IObjectReader >(this),
::fwData::location::enableMultiFiles< IObjectReader >(this)
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
DicomPatientDBReader::~DicomPatientDBReader()
{
SLM_TRACE_FUNC();
}
//------------------------------------------------------------------------------
::fwData::PatientDB::sptr DicomPatientDBReader::createPatientDB( const ::boost::filesystem::path dicomDir )
{
SLM_TRACE_FUNC();
::fwData::PatientDB::sptr patientDB = this->getConcreteObject();
std::vector<std::string> filenames;
::vtkGdcmIO::helper::DicomSearch::searchRecursivelyFiles(dicomDir, filenames);
this->addPatients( patientDB , filenames);
return patientDB;
}
//------------------------------------------------------------------------------
void DicomPatientDBReader::addPatients( ::fwData::PatientDB::sptr patientDB, std::vector<std::string> filenames)
{
//gdcm::Trace::SetDebug( 1 );
//gdcm::Trace::SetWarning( 1 );
//gdcm::Trace::SetError( 1 );
gdcm::Scanner scanner;
const gdcm::Tag t1(0x0020,0x000d); // Study Instance UID
const gdcm::Tag t2(0x0020,0x000e); // Series Instance UID
const gdcm::Tag t3(0x0020,0x0011); // Series Number
const gdcm::Tag t4(0x0020,0x0032); // Image Position (Patient)
const gdcm::Tag t5(0x0020,0x0037); //
const gdcm::Tag t6(0x0020,0x0052); //
const gdcm::Tag t7(0x0018,0x0024); // Sequence Name
const gdcm::Tag t8(0x0018,0x0050); // Slice Thickness
const gdcm::Tag t9(0x0028,0x0010); // Rows
const gdcm::Tag t10(0x0028,0x0011); // Columns
const gdcm::Tag t11(0x0008,0x0021); //
const gdcm::Tag t12(0x0008,0x0030); // Study Time
const gdcm::Tag t13(0x0008,0x0031); // Series Time
const gdcm::Tag t14(0x0008,0x0032); // Acquisition Time
const gdcm::Tag imageTypeTag(0x0008,0x0008); // ImageType
scanner.AddTag( t1 );
scanner.AddTag( t2 );
scanner.AddTag( t3 );
scanner.AddTag( t4 );
scanner.AddTag( t5 );
scanner.AddTag( t6 );
scanner.AddTag( t7 );
scanner.AddTag( t8 );
scanner.AddTag( t9 );
scanner.AddTag( t10 );
scanner.AddTag( t11 );
scanner.AddTag( t12 );
scanner.AddTag( t13 );
scanner.AddTag( t14 );
scanner.AddTag(imageTypeTag);
//const gdcm::Tag &reftag = t2;
::fwData::Patient::sptr patient;
::fwData::Study::sptr study;
try
{
std::string seriesInstanceUID("");
std::string studyInstanceUID("");
bool b = scanner.Scan( filenames );
if( !b )
{
SLM_ERROR("Scanner failed");
return ;
}
gdcm::Directory::FilenamesType keys = scanner.GetKeys();
gdcm::Directory::FilenamesType::const_iterator it = keys.begin();
std::map< std::string, std::vector< std::string > > mapSeries;
int secondaryCaptureCounter = 0;
for(; it != keys.end() /*&& i < 2*/; ++it)
{
const char *filename = it->c_str();
assert( scanner.IsKey( filename ) );
const char *value1 = scanner.GetValue( filename, t2);
const char *value2 = scanner.GetValue( filename, t14);
if (value1)
{
std::string stdValue = value1;
if (value2)
{
stdValue += value2;
}
if(scanner.GetValue(filename, imageTypeTag))
{
// Treatment of secondary capture dicom file.
std::string imageType(scanner.GetValue(filename, imageTypeTag));
std::string::size_type idx = imageType.find("DERIVED\\SECONDARY");
if( idx != std::string::npos)
{
std::string::size_type endIdx = imageType.find_first_not_of("DERIVED\\SECONDARY");
std::string optionalInfo = imageType.substr(endIdx);
std::ostringstream indice;
if(!optionalInfo.empty())
{
indice << optionalInfo;
}
else
{
// Tag as Secondary Capture
indice << "_SC_" << secondaryCaptureCounter;
secondaryCaptureCounter++;
}
stdValue += indice.str();
}
}
mapSeries[stdValue.c_str()].push_back(filename);
}
else
{
OSLM_ERROR ( "Error in vtkGdcmIO : No serie name found in : " << filename );
}
}
std::map< std::string, std::vector< std::string > >::iterator iter = mapSeries.begin();
std::map< std::string, std::vector< std::string > >::iterator iterEnd = mapSeries.end();
while (iter != iterEnd)
{
OSLM_TRACE ( " first : " << iter->first );
if ( iter->second.size() != 0 )
{
OSLM_TRACE ( " second : " << *(iter->second.begin()) );
vtkSmartPointer< vtkStringArray > files = vtkSmartPointer< vtkStringArray >::New();
vtkSmartPointer< vtkGDCMImageReader > reader = vtkSmartPointer< vtkGDCMImageReader >::New();
reader->FileLowerLeftOn();
gdcm::IPPSorter s;
s.SetComputeZSpacing( true );
s.SetZSpacingTolerance( 1e-3 );
b = s.Sort( iter->second );
double zspacing = 0;
int nbSorter = 0;
files->Initialize();
std::vector< std::string > listOfFiles = iter->second;
if( !b )
{
SLM_WARN ( "Failed to sort:" );
std::vector< std::string >::const_iterator it = iter->second.begin();
for( ; it != iter->second.end(); ++it)
{
const std::string &f = *it;
files->InsertNextValue( f.c_str() );
}
}
else
{
SLM_TRACE ( "Success to sort" );
zspacing = s.GetZSpacing();
if (!zspacing && s.GetFilenames().size() > 1)
{
SLM_TRACE ( "New sort (more soft)" );
const std::vector<std::string> & sorted = s.GetFilenames();
if (!sorted.empty())
{
gdcm::Reader localReader1;
gdcm::Reader localReader2;
const std::string &f1 = *(sorted.begin());
const std::string &f2 = *(sorted.begin() + 1);
OSLM_TRACE ( "Search spacing in : " << f1.c_str());
OSLM_TRACE ( "Search spacing in : " << f2.c_str());
localReader1.SetFileName( f1.c_str() );
localReader2.SetFileName( f2.c_str() );
if( localReader1.Read() && localReader2.Read() )
{
std::vector<double> vOrigin1 = gdcm::ImageHelper::GetOriginValue(localReader1.GetFile());
std::vector<double> vOrigin2 = gdcm::ImageHelper::GetOriginValue(localReader2.GetFile());
zspacing = vOrigin2[2] - vOrigin1[2];
OSLM_TRACE ( "Found z-spacing:" << zspacing << " from : << " << vOrigin2[2] << " | " << vOrigin1[2]);
}
else
{
OSLM_ERROR ( "Cannot read :" << f1 << " or : " << f2 );
}
}
if (!zspacing)
{
OSLM_DEBUG ( "Failed to find z-spacing:" << s.GetZSpacing());
}
else
{
nbSorter = 2;
OSLM_DEBUG ( "Re-Sort and fix z-spacing:" << s.GetZSpacing());
}
}
else
{
nbSorter = 1;
OSLM_TRACE ( "Found z-spacing:" << s.GetZSpacing());
}
const std::vector<std::string> & sorted = s.GetFilenames(); //FIXME
std::vector< std::string >::const_iterator it = sorted.begin();
for( ; it != sorted.end(); ++it)
{
const std::string &f = *it;
files->InsertNextValue( f.c_str() );
}
}
// Get the serie instance UID.
const std::vector<std::string> & filesList = iter->second;
seriesInstanceUID="";
studyInstanceUID="";
if(!filesList.empty())
{
const std::string &file = *(filesList.begin());
seriesInstanceUID.assign(scanner.GetValue( file.c_str(), t2));
studyInstanceUID.assign(scanner.GetValue( file.c_str(), t1));
}
::fwData::Image::NewSptr pDataImage;
bool res = false;
if (files->GetNumberOfValues() > 0)
{
try
{
SLM_TRACE ( "Read all files" );
reader->SetFileNames( files );
// Memory management
// Clean memory if possible
// Reserve 1 image (to allow a copy) 512 * 512 * size Z * sizeof(signed short)
//bool bMem = xxx->reserveMemory( 512 * 512 * files->GetNumberOfValues() * 2 );
bool bMem = true;
if ( bMem )
{
//add progress observation
::vtkIO::Progressor progress(reader, this->getSptr(), "Serie " + iter->first);
reader->Update();
try
{
::vtkIO::fromVTKImage(reader->GetOutput(), pDataImage);
res = true;
}
catch(std::exception &e)
{
OSLM_ERROR("VTKImage to fwData::Image failed "<<e.what());
}
}
}
catch (std::exception &e)
{
OSLM_ERROR ( "Error during conversion : " << e.what() );
}
catch (...)
{
OSLM_ERROR ( "Error during conversion" );
}
}
if (res)
{
// Read medical info
vtkMedicalImageProperties * medprop = reader->GetMedicalImageProperties();
std::string nameStr = medprop->GetPatientName(); //"0010|0010"
std::string sexStr = medprop->GetPatientSex(); //"0010|0040"
bool sex = (sexStr[0] == 'F')?false:true;
std::string modality = medprop->GetModality(); //"0008|0060"
// std::string zone = (std::string(medprop->GetStudyDescription()) + " - ") + medprop->GetSeriesDescription(); //"0008|1030"
std::string serieDescription = medprop->GetSeriesDescription();
std::string zone = std::string(medprop->GetStudyDescription()) ; //"0008|1030"
std::string studyID = std::string(medprop->GetStudyID()); // "0020,0010"
std::string studyTime = std::string(medprop->GetStudyTime());
std::string studyDate = std::string(medprop->GetStudyDate());
std::string studyDescription = std::string(medprop->GetStudyDescription());
std::string patientID = medprop->GetPatientID();//"0010|0020"
std::string birthdateStr= medprop->GetPatientBirthDate(); //"0010|0030"
::boost::posix_time::ptime birthdate = ::fwTools::strToBoostDateAndTime(birthdateStr);
std::string hospital = medprop->GetInstitutionName(); //"0008|0080"
std::string acqDateStr = medprop->GetAcquisitionDate(); //"0008|0022"
std::string acqTimeStr = medprop->GetAcquisitionTime(); //"0008|0032"
::boost::posix_time::ptime acqDate = ::fwTools::strToBoostDateAndTime(acqDateStr,acqTimeStr);
//std::string spacing = "0028|0030"
double thickness = medprop->GetSliceThicknessAsDouble();//"0018|0050"
//std::string interSliceStr= "0018|0088"
//std::vector<double> vRescale = gdcm::ImageHelper::GetRescaleInterceptSlopeValue(localReader.GetFile());
double center=0.0;
double width=0.0;
if (medprop->GetNumberOfWindowLevelPresets())//FIXME : Multiple preset !!!
medprop->GetNthWindowLevelPreset(0,&width,¢er); //0028|1050,1051
::boost::algorithm::trim(patientID);
::boost::algorithm::trim(hospital);
::boost::algorithm::trim(zone);
::boost::algorithm::trim(nameStr);
// remove accent
nameStr = ::fwTools::toStringWithoutAccent(nameStr);
modality = ::fwTools::toStringWithoutAccent(modality);
zone = ::fwTools::toStringWithoutAccent(zone);
serieDescription = ::fwTools::toStringWithoutAccent(serieDescription);
patientID = ::fwTools::toStringWithoutAccent(patientID);
hospital = ::fwTools::toStringWithoutAccent(hospital);
::fwData::Acquisition::NewSptr acq;
// Check the existence of the the study and the patient.
bool bIsNewStudy =false;
bool bIsNewPatient =false;
if(patientDB->getNumberOfPatients() !=0 )
{
//Looking for an existing patient.
BOOST_FOREACH(patient, patientDB->getPatients())
{
std::string id = patient->getIDDicom();
if (patientID == id)
{
// Looking for an existing study
bool studyExists = false;
BOOST_FOREACH(study, patient->getStudies())
{
if(study->getUID() == studyInstanceUID)
{
studyExists = true;
break;
}
}
if (!studyExists)
{
study = ::fwData::Study::New();
bIsNewStudy = true;
}
break;
}
else
{
bIsNewPatient = true;
patient = ::fwData::Patient::New();
study = ::fwData::Study::New();
}
}
}
else
{
bIsNewStudy = true;
bIsNewPatient = true;
patient = ::fwData::Patient::New();
study = ::fwData::Study::New();
}
// Image must be in 3D
if(pDataImage->getNumberOfDimensions() == 2)
{
::fwData::Image::SizeType imgSize(3);
std::copy(pDataImage->getSize().begin(), pDataImage->getSize().end(), imgSize.begin());
imgSize[2] = 1;
pDataImage->setSize(imgSize);
::fwData::Image::SpacingType imgSpacing(3);
std::copy(pDataImage->getSpacing().begin(), pDataImage->getSpacing().end(), imgSpacing.begin());
imgSpacing[2] = 1;
pDataImage->setSpacing(imgSpacing);
::fwData::Image::OriginType imgOrigin(3);
std::copy(pDataImage->getOrigin().begin(), pDataImage->getOrigin().end(), imgOrigin.begin());
imgOrigin[2] = 1;
pDataImage->setOrigin(imgOrigin);
width = 4096;
}
::fwData::Image::SpacingType vPixelSpacing = pDataImage->getSpacing();
if (zspacing > 0)
{
vPixelSpacing[2] = zspacing;
}
pDataImage->setSpacing(vPixelSpacing);
// Name & firstname
std::string name = "";
std::string firstname = "";
this->extractIdentity(nameStr, name, firstname);
// Set field
pDataImage->setWindowCenter(center);
pDataImage->setWindowWidth(width);
// Not managed by fwData::Image new API
// pDataImage->setRescaleIntercept(/*rescale*/0.0);
acq->setUID(seriesInstanceUID);
acq->setCRefCreationDate(acqDate);
acq->setDescription(serieDescription);
acq->setSliceThickness(thickness);
acq->setBitsPerPixel(pDataImage->getType().sizeOf()*8);
acq->setUnsignedFlag(!pDataImage->getType().isSigned());
// acq->setAxe(medprop->GetOrientationType(0));
// Keep the path and file name fo the Dicom file associated with acquisition.
std::vector< std::string >::const_iterator itrOnfiles = iter->second.begin();
for( ; itrOnfiles != iter->second.end(); ++itrOnfiles)
{
acq->addDicomFileUrl(*itrOnfiles);
}
//acq->setCRefImageType(imageTypeStr);
if (bIsNewStudy)
{
study->setCRefModality(modality);
study->setCRefHospital(hospital);
study->setCRefAcquisitionZone(zone);
study->setUID(studyInstanceUID);
study->setTime(studyTime);
study->setDate(studyDate);
study->setDescription(studyDescription);
}
if(bIsNewPatient)
{
patient->setCRefFirstname(firstname);
patient->setCRefName(name);
patient->setCRefIDDicom(patientID);
patient->setCRefBirthdate(birthdate);
patient->setCRefIsMale(sex);
} //--
acq->setImage(pDataImage);
study->addAcquisition(acq);
if (bIsNewStudy)
{
patient->addStudy(study);
}
if(bIsNewPatient)
{
patientDB->addPatient( patient );
}
} // if res == true
} // if nb files > 0
iter++;
} // While all data
} // try
catch (std::exception& e)
{
OSLM_ERROR ( "Try with another reader or retry with this reader on a specific subfolder : " << e.what() );
std::vector< std::string >::const_iterator it = filenames.begin();
for( ; it != filenames.end(); ++it)
{
OSLM_ERROR ("file error : " << *it );
}
}
}
//------------------------------------------------------------------------------
void DicomPatientDBReader::extractIdentity(const std::string patientName, std::string& name, std::string& firstname)
{
name = "";
firstname = "";
std::string::size_type sizeBase = std::string::npos;
std::string::size_type sizeIndex = patientName.find('^');
if (sizeIndex == sizeBase)
{
name = patientName;
firstname = "";
assert( name.length() == patientName.length() );
}
else
{
name = patientName.substr(0, sizeIndex);
firstname = patientName.substr(sizeIndex+1, patientName.size());
assert( name.length() + firstname.length() + 1 == patientName.length() );
}
}
//------------------------------------------------------------------------------
void DicomPatientDBReader::read()
{
SLM_TRACE_FUNC();
::fwData::PatientDB::sptr patientDB = this->getConcreteObject();
std::vector<std::string> filenames;
if(::fwData::location::have < ::fwData::location::Folder, ::fwDataIO::reader::IObjectReader > (this))
{
::vtkGdcmIO::helper::DicomSearch::searchRecursivelyFiles(this->getFolder(), filenames);
}
else if(::fwData::location::have < ::fwData::location::MultiFiles, ::fwDataIO::reader::IObjectReader > (this))
{
BOOST_FOREACH(::boost::filesystem::path file, this->getFiles())
{
filenames.push_back(file.string());
}
}
this->addPatients( patientDB , filenames);
}
} //namespace vtkGdcmIO
|
#pragma once
#ifndef __MEMORYHEADER_H_
#define __MEMORYHEADER_H_
#include "MACROS.h"
namespace PPSHUAI{
namespace SystemKernel{
__inline static
BOOL ReadProcessMemoryData(HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpData, SIZE_T stSize, SIZE_T * pstNumberOfBytesRead)
{
return ReadProcessMemory(hProcess, lpBaseAddress, lpData, stSize, pstNumberOfBytesRead);
}
__inline static
BOOL WriteProcessMemoryData(HANDLE hProcess, LPVOID lpBaseAddress, LPVOID lpData, SIZE_T stSize, SIZE_T * pstNumberOfBytesWtitten)
{
return WriteProcessMemory(hProcess, lpBaseAddress, lpData, stSize, pstNumberOfBytesWtitten);
}
__inline static
BOOL ReadProcessMemoryData(HANDLE hProcess, std::map<SIZE_T, std::string> * pssmap, std::map<SIZE_T, BOOL> * psbmap = NULL)
{
BOOL bResult = FALSE;
SIZE_T stNumberOfBytesRead = 0;
CHAR czData[MAXWORD + 1] = { 0 };
std::map<SIZE_T, std::string>::iterator itEnd;
std::map<SIZE_T, std::string>::iterator itIdx;
itEnd = pssmap->end();
itIdx = pssmap->begin();
for (; itIdx != itEnd; itIdx++)
{
if (psbmap)
{
psbmap->at(itIdx->first) = FALSE;
}
stNumberOfBytesRead = 0;
bResult = ReadProcessMemory(hProcess, (LPCVOID)itIdx->first, czData, sizeof(czData) * sizeof(CHAR), &stNumberOfBytesRead);
if (bResult || stNumberOfBytesRead)
{
itIdx->second = czData;
memset(czData, 0, sizeof(czData) * sizeof(CHAR));
if (psbmap)
{
psbmap->at(itIdx->first) = TRUE;
}
}
}
return bResult;
}
__inline static
BOOL WriteProcessMemoryData(HANDLE hProcess, std::map<SIZE_T, std::string> * pssmap, std::map<SIZE_T, BOOL> * psbmap = NULL)
{
BOOL bResult = FALSE;
SIZE_T stNumberOfBytesWritten = 0;
std::map<SIZE_T, std::string>::iterator itEnd;
std::map<SIZE_T, std::string>::iterator itIdx;
itEnd = pssmap->end();
itIdx = pssmap->begin();
for (; itIdx != itEnd; itIdx++)
{
if (psbmap)
{
psbmap->at(itIdx->first) = FALSE;
}
stNumberOfBytesWritten = 0;
bResult = WriteProcessMemory(hProcess, (LPVOID)itIdx->first, itIdx->second.c_str(), itIdx->second.length(), &stNumberOfBytesWritten);
if (bResult || stNumberOfBytesWritten)
{
if (psbmap)
{
psbmap->at(itIdx->first) = TRUE;
}
}
}
return bResult;
}
__inline static
BOOL ModifyProcessMemoryVirtualProtect(HANDLE hProcess, LPVOID lpBaseAddress, SIZE_T stRegionSize, DWORD dwNewProtect, DWORD * pdwOldProtect)
{
return VirtualProtectEx(hProcess, (LPVOID)lpBaseAddress, stRegionSize, dwNewProtect, pdwOldProtect);
}
__inline static
void GetProcessMemoryPageList(std::map<SIZE_T, MEMORY_BASIC_INFORMATION> * pmbimap, HANDLE hProcess)
{
DWORD dwPID = 0;
SIZE_T stResultSize = 0;
LPVOID lpMemoryAddress = NULL;
LPVOID lpMemoryAddressMIN = NULL;
LPVOID lpMemoryAddressMAX = NULL;
SYSTEM_INFO siSystemInfo = { 0 };
MEMORY_BASIC_INFORMATION mbiMemoryBuffer = { 0 };
// Get maximum address range from system info.
GetNativeSystemInformation(&siSystemInfo);
lpMemoryAddressMIN = siSystemInfo.lpMinimumApplicationAddress;
lpMemoryAddressMAX = siSystemInfo.lpMaximumApplicationAddress;
lpMemoryAddress = lpMemoryAddressMIN;
// Walk process addresses.
while (lpMemoryAddress < lpMemoryAddressMAX)
{
// Query next region of memory in the process.
stResultSize = VirtualQueryEx(hProcess, lpMemoryAddress, &mbiMemoryBuffer, sizeof(MEMORY_BASIC_INFORMATION));
if (stResultSize != sizeof(MEMORY_BASIC_INFORMATION))
{
break;
}
pmbimap->insert(std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::value_type((SIZE_T)mbiMemoryBuffer.BaseAddress, mbiMemoryBuffer));
// increment lpMemoryAddress to next region of memory.
lpMemoryAddress = (LPVOID)((SIZE_T)mbiMemoryBuffer.BaseAddress + (SIZE_T)mbiMemoryBuffer.RegionSize);
}
}
__inline static
void SearchProcessMemoryPageList(std::map<SIZE_T, SIZE_T> * pssmap,
std::map<SIZE_T, MEMORY_BASIC_INFORMATION> * pmbimap,
const VOID * pvData, SIZE_T stSize, HANDLE hProcess)
{
#ifndef _PART_DATA_SIZE_
#define _PART_DATA_SIZE_ 0x800000 // 8M
#endif //_PART_DATA_SIZE_
BYTE * pbData = NULL;
CHAR * pcbData = NULL;
SIZE_T stDataHead = 0;
SIZE_T stDataSize = 0;
SIZE_T stReadSize = 0;
SIZE_T stSearchPos = 0;
SIZE_T stNumberOfBytesRead = 0;
std::string strMemoryBuffer = ("");
SIZE_T stUnitSize = _PART_DATA_SIZE_;
std::string strFindData((CHAR *)pvData, stSize);
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itEnd;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itIdx;
itEnd = pmbimap->end();
itIdx = pmbimap->begin();
//็ณ่ฏทไปฃ็ ็ๅ
ๅญๅบ
pbData = (BYTE *)malloc(stUnitSize * sizeof(BYTE));
if (pbData)
{
strMemoryBuffer.assign((CHAR *)pbData, stUnitSize * sizeof(BYTE));
pcbData = (CHAR *)strMemoryBuffer.c_str();
for (; itIdx != itEnd; itIdx++)
{
stDataHead = 0;
stDataSize = itIdx->second.RegionSize;
while (stDataHead < stDataSize)
{
stNumberOfBytesRead = 0;
stReadSize = (((itIdx->second.RegionSize - stDataHead) > stUnitSize) ? stUnitSize : (itIdx->second.RegionSize - stDataHead));
if (ReadProcessMemory(hProcess, (BYTE *)itIdx->second.BaseAddress + stDataHead, (LPVOID)pcbData, stReadSize, &stNumberOfBytesRead))
{
// Method One
// String find and search
stSearchPos = 0;
while ((stSearchPos = strMemoryBuffer.find(strFindData, stSearchPos)) != std::string::npos)
{
pssmap->insert(std::map<SIZE_T, SIZE_T>::value_type((SIZE_T)itIdx->second.BaseAddress + stSearchPos, (SIZE_T)itIdx->second.BaseAddress));
stSearchPos += stSize;
}
stDataHead += ((stNumberOfBytesRead <= stDataSize) ? stNumberOfBytesRead : (stNumberOfBytesRead - stSize < 0) ? stSize : (stNumberOfBytesRead - stSize));
memset(pcbData, 0, stUnitSize * sizeof(BYTE));
}
else
{
// Read failure
break;
}
}
}
free(pbData);
pbData = NULL;
}
#ifdef _PART_DATA_SIZE_
#undef _PART_DATA_SIZE_
#endif //_PART_DATA_SIZE_
}
__inline static
void SearchProcessMemoryPageList(std::map<SIZE_T, SIZE_T> * pssmap, const VOID * pvData, SIZE_T stSize, const _TCHAR * ptProcessName)
{
HANDLE hProcess = NULL;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION> mbimap;
hProcess = InitProcessHandle(ptProcessName);
if (hProcess)
{
GetProcessMemoryPageList(&mbimap, hProcess);
SearchProcessMemoryPageList(pssmap, &mbimap, pvData, stSize, hProcess);
ExitProcessHandle(&hProcess);
}
}
__inline static
void SearchProcessMemoryPageListEx(std::map<SIZE_T, SIZE_T> * pssmap,
std::map<SIZE_T, MEMORY_BASIC_INFORMATION> * pmbimap,
const VOID * pvData, SIZE_T stSize, HANDLE hProcess)
{
#ifndef _PART_DATA_SIZE_
#define _PART_DATA_SIZE_ 0x800000 // 8M
#endif //_PART_DATA_SIZE_
DWORD dwPID = 0;
BYTE * pbData = NULL;
LPVOID lpData = NULL;
SIZE_T stDataHead = 0;
SIZE_T stDataSize = 0;
SIZE_T stReadSize = 0;
SIZE_T stSearchPos = 0;
SIZE_T stNumberOfBytesRead = 0;
SIZE_T stUnitSize = _PART_DATA_SIZE_;
std::string strFindData((CHAR *)pvData, stSize);
std::string strMemoryBuffer(stUnitSize, ('\x00'));
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itEnd;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itIdx;
itEnd = pmbimap->end();
itIdx = pmbimap->begin();
if (strMemoryBuffer.size() > 0)
{
pbData = (BYTE *)strMemoryBuffer.c_str();
//็ณ่ฏทไปฃ็ ็ๅ
ๅญๅบ
for (; itIdx != itEnd; itIdx++)
{
stDataHead = 0;
stDataSize = itIdx->second.RegionSize;
while (stDataHead < stDataSize)
{
stNumberOfBytesRead = 0;
stReadSize = (((itIdx->second.RegionSize - stDataHead) > stUnitSize) ? stUnitSize : (itIdx->second.RegionSize - stDataHead));
if (ReadProcessMemory(hProcess, (BYTE *)itIdx->second.BaseAddress + stDataHead, (LPVOID)pbData, stReadSize, &stNumberOfBytesRead))
{
stSearchPos = 0;
while ((stSearchPos = strMemoryBuffer.find(strFindData, stSearchPos)) != std::string::npos)
{
pssmap->insert(std::map<SIZE_T, SIZE_T>::value_type((SIZE_T)itIdx->second.BaseAddress + stSearchPos, (SIZE_T)itIdx->second.BaseAddress));
stSearchPos += stSize;
}
stDataHead += ((stNumberOfBytesRead <= stDataSize) ? stNumberOfBytesRead : (stNumberOfBytesRead - stSize < 0) ? stNumberOfBytesRead : (stNumberOfBytesRead - stSize));
memset(pbData, 0, stUnitSize * sizeof(BYTE));
}
else
{
// Read failure
break;
}
}
}
}
#ifdef _PART_DATA_SIZE_
#undef _PART_DATA_SIZE_
#endif //_PART_DATA_SIZE_
}
__inline static
void SearchProcessMemoryPageListEx(std::map<SIZE_T, SIZE_T> * pssmap, const VOID * pvData, SIZE_T stSize, const _TCHAR * ptProcessName)
{
HANDLE hProcess = NULL;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION> mbimap;
hProcess = InitProcessHandle(ptProcessName);
if (hProcess)
{
GetProcessMemoryPageList(&mbimap, hProcess);
SearchProcessMemoryPageListEx(pssmap, &mbimap, pvData, stSize, hProcess);
ExitProcessHandle(&hProcess);
}
}
__inline static
void PrintMemoryBasicInformation(MEMORY_BASIC_INFORMATION * pmbi)
{
if (pmbi)
{
if ((pmbi->AllocationBase != pmbi->BaseAddress)
&& (pmbi->State != MEM_FREE))
{
#if !defined(_WIN64) && !defined(WIN64)
_tprintf(_T(" 0x%08lX 0x%08lX "),
#else
_tprintf(_T(" 0x%016llX 0x%016llX "),
#endif
pmbi->BaseAddress,
pmbi->RegionSize);
}
else
{
#if !defined(_WIN64) && !defined(WIN64)
_tprintf(_T(" 0x%08lX 0x%08lX "),
#else
_tprintf(_T(" 0x%016llX 0x%016llX "),
#endif
pmbi->BaseAddress,
pmbi->RegionSize);
}
_tprintf(_T("\t"));
switch (pmbi->State)
{
case MEM_COMMIT:
_tprintf(_T("MEM_COMMIT "));
break;
case MEM_RESERVE:
_tprintf(_T("MEM_FREE "));
break;
case MEM_RELEASE:
_tprintf(_T("MEM_RESERVE"));
break;
default:
_tprintf(_T("-----------"));
break;
}
_tprintf(_T("\t"));
switch (pmbi->Type)
{
case MEM_IMAGE:
_tprintf(_T("MEM_IMAGE "));
break;
case MEM_MAPPED:
_tprintf(_T("MEM_MAPPED "));
break;
case MEM_PRIVATE:
_tprintf(_T("MEM_PRIVATE"));
break;
default:
_tprintf(_T("-----------"));
break;
}
_tprintf(_T("\t"));
switch (pmbi->AllocationProtect)
{
case PAGE_READONLY:
_tprintf(_T("PAGE_READONLY "));
break;
case PAGE_READWRITE:
_tprintf(_T("PAGE_READWRITE "));
break;
case PAGE_WRITECOPY:
_tprintf(_T("PAGE_WRITECOPY "));
break;
case PAGE_EXECUTE:
_tprintf(_T("PAGE_EXECUTE "));
break;
case PAGE_EXECUTE_READ:
_tprintf(_T("PAGE_EXECUTE_READ "));
break;
case PAGE_EXECUTE_READWRITE:
_tprintf(_T("PAGE_EXECUTE_READWRITE"));
break;
case PAGE_EXECUTE_WRITECOPY:
_tprintf(_T("PAGE_EXECUTE_WRITECOPY"));
break;
case PAGE_GUARD:
_tprintf(_T("PAGE_GUARD "));
break;
case PAGE_NOACCESS:
_tprintf(_T("PAGE_NOACCESS "));
break;
case PAGE_NOCACHE:
_tprintf(_T("PAGE_NOCACHE "));
break;
default:
_tprintf(_T("----------------------"));
break;
}
_tprintf(_T("\r\n"));
}
}
__inline static
void PrintProcessMemoryPages(std::map<SIZE_T, MEMORY_BASIC_INFORMATION> * pmbimap)
{
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itEnd;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itIdx;
if (pmbimap)
{
itEnd = pmbimap->end();
itIdx = pmbimap->begin();
for (; itIdx != itEnd; itIdx++)
{
PrintMemoryBasicInformation(&itIdx->second);
}
}
}
__inline static
void PrintProcessMemoryPages(const _TCHAR * ptProcessName)
{
HANDLE hProcess = NULL;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION> mbimap;
hProcess = InitProcessHandle(ptProcessName);
if (hProcess)
{
GetProcessMemoryPageList(&mbimap, hProcess);
PrintProcessMemoryPages(&mbimap);
ExitProcessHandle(&hProcess);
}
}
// ๅ
ๅญๆฐๆฎๆ ๅฐๅๅงๅ
__inline static
HANDLE MapMemoryInitialize(BYTE ** ppbData, ULARGE_INTEGER * puiSize, std::map<SIZE_T, SIZE_T> * prsssmap, std::map<SIZE_T, MEMORY_BASIC_INFORMATION> * psmbimap, HANDLE hProcess, LPCTSTR lpMapName = _T("__MAP_MAP__"))
{
START_TIMER_TICKS(DEBUG);
SYSTEM_INFO si = { 0 };
SIZE_T stPlaceIndex = 0;
HANDLE hFileMapping = NULL;
SIZE_T stNumberOfBytesRead = 0;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itEnd;
std::map<SIZE_T, MEMORY_BASIC_INFORMATION>::iterator itIdx;
// Get memory map assign size
PPSHUAI::SystemKernel::GetNativeSystemInformation(&si);
// Calculate map size
itEnd = psmbimap->end();
itIdx = psmbimap->begin();
for (; itIdx != itEnd; itIdx++)
{
if (((itIdx->second.AllocationProtect & PAGE_READONLY) == PAGE_READONLY) ||
((itIdx->second.AllocationProtect & PAGE_READWRITE) == PAGE_READWRITE) ||
((itIdx->second.AllocationProtect & PAGE_WRITECOPY) == PAGE_WRITECOPY) ||
((itIdx->second.AllocationProtect & PAGE_EXECUTE_READ) == PAGE_EXECUTE_READ) ||
((itIdx->second.AllocationProtect & PAGE_EXECUTE_READWRITE) == PAGE_EXECUTE_READWRITE) ||
((itIdx->second.AllocationProtect & PAGE_EXECUTE_WRITECOPY) == PAGE_EXECUTE_WRITECOPY))
{
puiSize->QuadPart += itIdx->second.RegionSize;
}
}
// Assign address size
puiSize->QuadPart += puiSize->QuadPart % si.dwAllocationGranularity;
// Create memory map
hFileMapping = PPSHUAI::FilePath::MapCreate((LPVOID *)ppbData, lpMapName, puiSize);
if (hFileMapping)
{
itEnd = psmbimap->end();
itIdx = psmbimap->begin();
for (; itIdx != itEnd; itIdx++)
{
if (ReadProcessMemory(hProcess, (LPCVOID)itIdx->first, (*ppbData) + stPlaceIndex, itIdx->second.RegionSize, &stNumberOfBytesRead))
{
if (prsssmap)
{
prsssmap->insert(std::map<SIZE_T, SIZE_T>::value_type((SIZE_T)stPlaceIndex, itIdx->first));
}
stPlaceIndex += stNumberOfBytesRead;
}
}
}
CLOSE_TIMER_TICKS(DEBUG);
return hFileMapping;
}
// ๅ
ๅญๆ็ดขๆฐๆฎ
__inline static
SIZE_T MapMemorySearchString(std::map<SIZE_T, SIZE_T> * pssmap, LPVOID lpData, ULARGE_INTEGER * puiSize, LPVOID lpFindData, SIZE_T stFindSize)
{
START_TIMER_TICKS(DEBUG);
std::string::size_type stPlaceIndex = 0;
std::string strFindData((CONST CHAR *)lpFindData, stFindSize);
std::string strMemoryBuffer((CHAR *)(lpData), puiSize->QuadPart);
while ((stPlaceIndex = strMemoryBuffer.find(strFindData, stPlaceIndex)) != std::string::npos)
{
pssmap->insert(std::map<SIZE_T, SIZE_T>::value_type((SIZE_T)stPlaceIndex, (SIZE_T)stPlaceIndex));
stPlaceIndex += strFindData.length();
}
CLOSE_TIMER_TICKS(DEBUG);
return 0;
}
//็ธๅฏนๅ
ๅญๆ ๅฐๅฐๅ=>>็ปๅฏน่ฟ็จๅ
ๅญๅฐๅ
__inline static
SIZE_T MapMemoryRelativeTransferAbsolute(std::map<SIZE_T, SIZE_T> * psssmap, std::map<SIZE_T, SIZE_T> * prssmap, std::map<SIZE_T, SIZE_T> * prvassmap, std::map<SIZE_T, MEMORY_BASIC_INFORMATION> * psmbimap)
{
std::map<SIZE_T, SIZE_T>::iterator itEnd;
std::map<SIZE_T, SIZE_T>::iterator itIdx;
std::map<SIZE_T, SIZE_T>::iterator itRSEnd;
std::map<SIZE_T, SIZE_T>::iterator itRSIdx;
// ็ธๅฏนๅ
ๅญๆ ๅฐๅฐๅๅ่กจ
itEnd = prssmap->end();
itIdx = prssmap->begin();
for (; itIdx != itEnd; itIdx++)
{
// ่พ
ๅฉๅ
ๅญ็ดขๅผๆ ๅฐๅฐๅๅ่กจ
itRSEnd = prvassmap->end();
itRSIdx = prvassmap->begin();
for (; itRSIdx != itRSEnd; itRSIdx++)
{
if ((SIZE_T)itIdx->first >= itRSIdx->first &&
(SIZE_T)itIdx->first < (itRSIdx->first + psmbimap->at(itRSIdx->second).RegionSize))
{
break;
}
}
if (itRSIdx != itRSEnd)
{
psssmap->insert(std::map<SIZE_T, SIZE_T>::value_type((SIZE_T)psmbimap->at(itRSIdx->second).BaseAddress + (itIdx->first - itRSIdx->first), (SIZE_T)psmbimap->at(itRSIdx->second).RegionSize));
}
}
return 0;
}
// ๅ
ๅญๆ ๅฐ่ตๆบ้ๆพ
__inline static
void MapMemoryExitialize(HANDLE * phFileMapping, LPVOID * pbData)
{
PPSHUAI::FilePath::MapRelease(phFileMapping, pbData);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//ๆณจๅ
ฅDLLๅฐ่ฟ็จ่ฟ็จ(ไฝฟ็จCreateRemoteThread)
__inline BOOL InjectDllToRemoteProcess(const _TCHAR* lpDllName, const _TCHAR* lpPid, const _TCHAR* lpProcName)
{
PROCESS_INFORMATION pi = { 0 };
if ((ElevatePrivileges() == FALSE) || (UNDOCAPI::InitUnDocumentApis() == FALSE))
{
return FALSE;
}
if (_tcsstr(lpProcName, _T("\\")) || _tcsstr(lpProcName, _T("/")))
{
StartupProgram(lpProcName, _T(""), NULL, &pi);
}
if (pi.dwProcessId <= 0)
{
if (NULL == lpPid || 0 == _tcslen(lpPid))
{
if (NULL != lpProcName && 0 != _tcslen(lpProcName))
{
if (pi.dwProcessId = GetProcessIdByProcessName(lpProcName))
{
return FALSE;
}
}
else
{
return FALSE;
}
}
else
{
pi.dwProcessId = _ttoi(lpPid);
}
}
//ๆ นๆฎPidๅพๅฐ่ฟ็จๅฅๆ(ๆณจๆๅฟ
้กปๆ้)
HANDLE hRemoteProcess = NULL;
hRemoteProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pi.dwProcessId);
//hRemoteProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_SUSPEND_RESUME, FALSE, stPid);
if (!hRemoteProcess && INVALID_HANDLE_VALUE == hRemoteProcess)
{
return FALSE;
}
//ๆ่ตท่ฟ็จ
FUNC_PROC(ZwSuspendProcess)(hRemoteProcess);
//่ฎก็ฎDLL่ทฏๅพๅ้่ฆ็ๅ
ๅญ็ฉบ้ด
SIZE_T stSize = (1 + _tcslen(lpDllName)) * sizeof(_TCHAR);
//ไฝฟ็จVirtualAllocExๅฝๆฐๅจ่ฟ็จ่ฟ็จ็ๅ
ๅญๅฐๅ็ฉบ้ดๅ้
DLLๆไปถๅ็ผๅฒๅบ,ๆๅ่ฟๅๅ้
ๅ
ๅญ็้ฆๅฐๅ.
LPVOID lpRemoteBuff = VirtualAllocEx(hRemoteProcess, NULL, stSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (NULL == lpRemoteBuff)
{
CloseHandle(hRemoteProcess);
return FALSE;
}
//ไฝฟ็จWriteProcessMemoryๅฝๆฐๅฐDLL็่ทฏๅพๅๅคๅถๅฐ่ฟ็จ่ฟ็จ็ๅ
ๅญ็ฉบ้ด,ๆๅ่ฟๅTRUE.
SIZE_T stHasWrite = 0;
BOOL bRet = WriteProcessMemory(hRemoteProcess, lpRemoteBuff, lpDllName, stSize, &stHasWrite);
if (!bRet || stHasWrite != stSize)
{
VirtualFreeEx(hRemoteProcess, lpRemoteBuff, stSize, MEM_DECOMMIT | MEM_RELEASE);
CloseHandle(hRemoteProcess);
return FALSE;
}
//ๅๅปบไธไธชๅจๅ
ถๅฎ่ฟ็จๅฐๅ็ฉบ้ดไธญ่ฟ่ก็็บฟ็จ(ไน็งฐ:ๅๅปบ่ฟ็จ็บฟ็จ),ๆๅ่ฟๅๆฐ็บฟ็จๅฅๆ.
//ๆณจๆ:่ฟ็จๅฅๆๅฟ
้กปๅ
ทๅคPROCESS_CREATE_THREAD, PROCESS_QUERY_INFORMATION, PROCESS_VM_OPERATION, PROCESS_VM_WRITE,ๅPROCESS_VM_READ่ฎฟ้ฎๆ้
DWORD dwRemoteThread = 0;
LPTHREAD_START_ROUTINE pfnLoadLibrary = (LPTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(_T("Kernel32")), "LoadLibraryA");
HANDLE hRemoteThread = CreateRemoteThread(hRemoteProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pfnLoadLibrary, lpRemoteBuff, 0, &dwRemoteThread);
if (INVALID_HANDLE_VALUE == hRemoteThread)
{
VirtualFreeEx(hRemoteProcess, lpRemoteBuff, stSize, MEM_DECOMMIT | MEM_RELEASE);
CloseHandle(hRemoteProcess);
return FALSE;
}
//ๆณจๅ
ฅๆๅ้ๆพๅฅๆ
WaitForSingleObject(hRemoteThread, INFINITE);
FUNC_PROC(ZwResumeProcess)(hRemoteProcess);
CloseHandle(hRemoteThread);
CloseHandle(hRemoteProcess);
return TRUE;
}
//ไฝฟ็จ็บฏๆฑ็ผๅฎ็ฐ่ฟ็จ่ฟ็จๆณจๅ
ฅ
__inline BOOL InjectDll(DWORD dwProcessId, DWORD dwThreadId, const _TCHAR * ptzDllName)
{
BOOL bResult = FALSE;
FARPROC farproc = NULL;
CONTEXT context = { 0 };
LPVOID lpCodeBase = NULL;
SIZE_T stCodeSize = USN_PAGE_SIZE;
SIZE_T stNumberOfBytesWritten = 0;
SIZE_T dwCurrentEipAddress = 0;
DWORD dwIndexOffsetPosition = 0;
CHAR szCodeData[USN_PAGE_SIZE] = { 0 };
CHAR szCode0[] = ("\x60\xE8\x00\x00\x00\x00\x58\x83\xC0\x13\x50\xB8");
CHAR szCode1[] = ("\xFF\xD0\x61\x68");
CHAR szCode2[] = ("\xC3");
//ๆ นๆฎPidๅพๅฐ่ฟ็จๅฅๆ(ๆณจๆๅฟ
้กปๆ้)
HANDLE hRemoteProcess = NULL;
HANDLE hRemoteThread = NULL;
ULONG ulPreviousSuspendCount = 0;
if ((ElevatePrivileges() == FALSE) || (UNDOCAPI::InitUnDocumentApis() == FALSE))
{
return FALSE;
}
hRemoteProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwProcessId);
//hRemoteProcess = OpenProcess(PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_SUSPEND_RESUME, FALSE, stPid);
if (!hRemoteProcess && INVALID_HANDLE_VALUE == hRemoteProcess)
{
return FALSE;
}
hRemoteThread = OpenThread(THREAD_ALL_ACCESS, FALSE, dwThreadId);
//hRemoteProcess = OpenThread(THREAD_TERMINATE | THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SET_INFORMATION |THREAD_SET_THREAD_TOKEN | THREAD_IMPERSONATE | THREAD_DIRECT_IMPERSONATION | THREAD_QUERY_INFORMATION | THREAD_SUSPEND_RESUME, FALSE, stPid);
if (!hRemoteThread && INVALID_HANDLE_VALUE == hRemoteThread)
{
return FALSE;
}
//ๆ่ตท่ฟ็จ
FUNC_PROC(ZwSuspendProcess)(hRemoteProcess);
//ๆ่ตท็บฟ็จ
FUNC_PROC(ZwSuspendThread)(hRemoteThread, &ulPreviousSuspendCount);
//ๅจ่ฟ็จ่ฟ็จๅ้
ๅฏๆง่ก่ฏปๅๆจกๅ
lpCodeBase = VirtualAllocEx(hRemoteProcess, lpCodeBase, stCodeSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
//่ฎพ็ฝฎ็บฟ็จไธไธๆ็ๆ ่ฏ
context.ContextFlags = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS;
//่ทๅ็บฟ็จไธไธๆ
FUNC_PROC(ZwGetContextThread)(hRemoteThread, &context);
#if !defined(WIN64) && !defined(_WIN64)
//่ทๅ่ฟ็จ่ฟ็จ็ๅฝๅๆง่กๅฐๅ
dwCurrentEipAddress = context.Eip;
//่ฎพ็ฝฎ่ฟ็จ่ฟ็จ็ไธไธๆง่กๅฐๅ
context.Eip = (DWORD)lpCodeBase;
#else
//่ทๅ่ฟ็จ่ฟ็จ็ๅฝๅๆง่กๅฐๅ
dwCurrentEipAddress = context.Rip;
//่ฎพ็ฝฎ่ฟ็จ่ฟ็จ็ไธไธๆง่กๅฐๅ
context.Rip = (SIZE_T)lpCodeBase;
#endif
//่ทๅLoadLibraryA็ๅฝๆฐๅฐๅ
farproc = GetProcAddress(GetModuleHandle(_T("KERNEL32.DLL")), ("LoadLibraryA"));
///////////////////////////////////////////////////////////////////////////////////
// ๆฐๆฎๅ
// CodeData ๏ผ
// { 96, 232, 0, 0, 0, 0, 88, 131, 192, 19, 80, 184 } / "\x60\xE8\x00\x00\x00\x00\x58\x83\xC0\x13\x50\xB8"
// { LoadLibraryAๅฝๆฐๅฐๅ }
// { 255, 208, 97, 104 } / "\xFF\xD0\x61\x68"
// { Eipๅฐๅ }
// { 195 } / "\xC3"
// { Dll่ทฏๅพ };
memcpy(szCodeData + dwIndexOffsetPosition, szCode0, sizeof(szCode0) - 1);
dwIndexOffsetPosition += sizeof(szCode0) - 1;
memcpy(szCodeData + dwIndexOffsetPosition, &farproc, sizeof(farproc));
dwIndexOffsetPosition += sizeof(farproc);
memcpy(szCodeData + dwIndexOffsetPosition, szCode1, sizeof(szCode1) - 1);
dwIndexOffsetPosition += sizeof(szCode1) - 1;
memcpy(szCodeData + dwIndexOffsetPosition, &dwCurrentEipAddress, sizeof(dwCurrentEipAddress));
dwIndexOffsetPosition += sizeof(dwCurrentEipAddress);
memcpy(szCodeData + dwIndexOffsetPosition, szCode2, sizeof(szCode2) - 1);
dwIndexOffsetPosition += sizeof(szCode2) - 1;
memcpy(szCodeData + dwIndexOffsetPosition, Convert::TToA(ptzDllName).c_str(), Convert::TToA(ptzDllName).length());
dwIndexOffsetPosition += Convert::TToA(ptzDllName).length();
//ๅๅ
ฅ่ฟ็จ่ฟ็จๅฏๆง่ก่ฏปๅๆจกๅ
WriteProcessMemory(hRemoteProcess, lpCodeBase, szCodeData, dwIndexOffsetPosition, &stNumberOfBytesWritten);
//่ฎพ็ฝฎ็บฟ็จไธไธๆ
FUNC_PROC(ZwSetContextThread)(hRemoteThread, &context);
//ๆขๅค็บฟ็จ
FUNC_PROC(ZwResumeThread)(hRemoteThread, &ulPreviousSuspendCount);
//ๆขๅค่ฟ็จ
FUNC_PROC(ZwResumeProcess)(hRemoteProcess);
//้ๆพๅจ่ฟ็จ่ฟ็จๅ้
็ๅฏๆง่ก่ฏปๅๆจกๅ
//VirtualFreeEx(hRemoteProcess, lpCodeBase, stCodeSize, MEM_DECOMMIT | MEM_RELEASE);
return bResult;
}
}
}
#endif //__MEMORYHEADER_H_
|
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
if(nums.empty()) return 0;
map<int,int> M;
int maxLen = 1;
for(int i=0; i<nums.size(); ++i){
if(M.find(nums[i]) != M.end()) continue;
M[nums[i]] = 1;
if(M.find(nums[i] - 1) != M.end()){
maxLen = max(maxLen,merge(M,nums[i]-1,nums[i]));
}
if(M.find(nums[i] + 1) != M.end()){
maxLen = max(maxLen,merge(M,nums[i],nums[i] + 1));
}
}
return maxLen;
}
int merge(map<int,int> &M,int less,int more){
int leftNum = less - M[less] + 1;//รรณรยฉ
int rightNum = more + M[more] - 1;//รรรยฉ
int len = rightNum - leftNum + 1;
M[leftNum] = len;
M[rightNum] = len;
return len;
}
};
|
#include"Tests.h"
#include"RepoTemplate.h"
#include"Service.h"
#include"UI.h"
#include"TestFile.h"
int main() {
cout << "start" << endl;
Tests test;
test.testDomain();
test.testRepoTemplate();
//test.testService();
//########repo file tests################
TestRepositoryFile testf;
testf.testLoadFromFile();
testf.testAddElem();
testf.testFindElem();
testf.testDelElem();
testf.testGetAll();
testf.testUpdateElem();
testf.testElemAtPos();
testf.testSize();
cout << "succes" << endl;
//RepositoryTemplate<Car> rep;
RepositoryFile<Car> repo("Elem.txt");
Service serv(repo);
UI ui(serv);
ui.showUI();
return 0;
}
|
//#include "Sensor.h"
//#define DEBUG_RAIN 1
const unsigned long int RAINFALL_COUNT_PERIOD = 20 * 1000l; // Update rainfall every 20 seconds
volatile int rainfall_count = 0; // Incremented in the interrupt function
// Tipping Bucket Rainfall Sensor
RainfallSensor::RainfallSensor( const String& id, const int& pin ) : Sensor(id), d_pin(pin)
{
}
void RainfallSensor::setup() {
pinMode(d_pin, INPUT_PULLUP);
attachInterrupt( digitalPinToInterrupt(d_pin), rainfallUpdate, FALLING );
d_update_time = millis();
}
void RainfallSensor::resetAccumulation() {
d_accumulated_rainfall = 0.0;
}
void RainfallSensor::update(bool) {
unsigned long int elapsed_time = millis() - d_update_time;
if ( elapsed_time > RAINFALL_COUNT_PERIOD ) {
detachInterrupt(digitalPinToInterrupt(d_pin));
d_accumulated_rainfall += 0.2794 * (float)rainfall_count; // Each switch closure is 0.2794mm
#ifdef DEBUG_RAIN
Serial.print("Updating rainfall - count = ");
Serial.print(rainfall_count );
Serial.print(" accumulated rainfall (mm) = ");
Serial.println( d_accumulated_rainfall );
#endif
rainfall_count = 0;
attachInterrupt( digitalPinToInterrupt(d_pin), rainfallUpdate, FALLING );
d_update_time += RAINFALL_COUNT_PERIOD;
}
}
float RainfallSensor::getValue() {
return d_accumulated_rainfall;
}
void RainfallSensor::rainfallUpdate()
{
rainfall_count++;
}
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** FlatSiteBuilder is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#include "defaultthemeeditor.h"
#include "flatbutton.h"
#include "mainwindow.h"
#include <QLineEdit>
#include <QStatusBar>
#include <QGridLayout>
#include <QLabel>
#include <QHBoxLayout>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>
#include <QFile>
DefaultThemeEditor::DefaultThemeEditor()
{
m_hidePoweredBy = new QCheckBox("Hide powered by FlatSiteBuilder in footer");
m_titleLabel->setText("Default Theme Settings");
QVBoxLayout *vbox = new QVBoxLayout();
vbox->addStretch();
m_layout->addWidget(m_hidePoweredBy, 1, 0, 1, 3);
m_layout->addWidget(new QLabel(""), 2, 0);
m_layout->addWidget(new QLabel("Looks a bit empty here, right?"), 3, 0, 1, 3);
m_layout->addWidget(new QLabel("This is just a sample theme editor."), 4, 0, 1, 3);
m_layout->addWidget(new QLabel("To give theme creators an overview of what is possible."), 5, 0, 1, 3);
m_layout->addLayout(vbox, 6, 0); // for stretching only
connect(m_hidePoweredBy, SIGNAL(stateChanged(int)), this, SLOT(showPoweredChanged()));
}
void DefaultThemeEditor::showPoweredChanged()
{
if(m_isHidePoweredByEnabled != m_hidePoweredBy->isChecked())
contentChanged("show powered by changed");
}
void DefaultThemeEditor::load()
{
// set default values in case load failes
m_isHidePoweredByEnabled = false;
QFile theme(m_filename);
if (!theme.open(QIODevice::ReadOnly))
{
m_win->statusBar()->showMessage("Unable to open " + m_filename);
return;
}
QXmlStreamReader xml(&theme);
if(xml.readNextStartElement())
{
if(xml.name() == "Settings")
{
m_isHidePoweredByEnabled = xml.attributes().value("hidePoweredBy").toString() == "true";
m_hidePoweredBy->setChecked(m_isHidePoweredByEnabled);
}
}
theme.close();
}
void DefaultThemeEditor::save()
{
QFile file(m_filename);
if(!file.open(QFile::WriteOnly))
{
m_win->statusBar()->showMessage("Unable to open file " + m_filename);
return;
}
QXmlStreamWriter xml(&file);
xml.setAutoFormatting(true);
xml.writeStartDocument();
xml.writeStartElement("Settings");
xml.writeAttribute("hidePoweredBy", (m_hidePoweredBy->isChecked() ? "true" : "false"));
xml.writeEndElement();
xml.writeEndDocument();
file.close();
m_win->statusBar()->showMessage("Theme settings have been saved.");
}
QVariantMap DefaultThemeEditor::themeVars()
{
load();
QVariantMap vars;
vars["hidePoweredBy"] = m_isHidePoweredByEnabled;
return vars;
}
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rep1(i, n) for(int i = 1; i <= (int)(n); i++)
#define showmap(is, js, x) {rep(i, is){rep(j, js){cout << x[i][j] << " ";}cout << endl;}}
#define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;}
#define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;}
typedef long long ll;
typedef pair<int, int> P;
typedef pair<ll, ll> llP;
ll gcd(int x, int y){ return y?gcd(y, x%y):x;}
ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);}
template<class T> inline bool chmax(T& a, T b) {if (a < b) {a = b; return true;} return false;}
template<class T> inline bool chmin(T& a, T b) {if (a > b) {a = b; return true;} return false;}
int main()
{
int h, w, m;
cin >> h >> w >> m;
set<P> targ;
vector<int> H(h), W(w);
rep(i, m){
P tmp;
cin >> tmp.first >> tmp.second;
tmp.first--;
tmp.second--;
targ.insert(tmp);
H[tmp.first]++;
W[tmp.second]++;
}
int hmax = 0;
int wmax = 0;
rep(i, h) chmax(hmax, H[i]);
rep(i, w) chmax(wmax, W[i]);
vector<int> Hmax, Wmax;
rep(i, h) if (H[i] == hmax) Hmax.push_back(i);
rep(i, w) if (W[i] == wmax) Wmax.push_back(i);
// show(Hmax);
// show(Wmax);
rep(i, Hmax.size())rep(j, Wmax.size()){
if (targ.find(make_pair(Hmax[i], Wmax[j])) == targ.end()){
cout << hmax+wmax << endl;
return 0;
}
}
cout << hmax+wmax -1 << endl;
}
|
/***
* Copyright (C) 2016 Luca Weihs
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SymRC_IntegratedMinor
#define SymRC_IntegratedMinor
#include "NaiveUStatistics.h"
#include "EmpiricalDistribution.h"
class SubsetMinorPartition {
private:
arma::uvec inds0;
arma::uvec inds1;
arma::uvec allInds;
arma::uvec intersection;
arma::uvec complement;
arma::uvec counts;
arma::uvec symmetricDiff;
arma::uvec inds0Unique;
arma::uvec inds1Unique;
public:
SubsetMinorPartition(int dim, arma::uvec leftInds, arma::uvec rightInds);
const arma::uvec& getAllInds() const;
const arma::uvec& getNonUniqueLeftInds() const;
const arma::uvec& getNonUniqueRightInds() const;
const arma::uvec& getUniqueLeftInds() const;
const arma::uvec& getUniqueRightInds() const;
const arma::uvec& getIntersection() const;
const arma::uvec& getCounts() const;
const arma::uvec& getComplement() const;
const arma::uvec& getSymmetricDiff() const;
};
class IntegratedMinorKernelEvaluator : public KernelEvaluator {
private:
static const int ord = 5;
SubsetMinorPartition xPart;
SubsetMinorPartition yPart;
arma::umat perms;
bool minorIndicator(const arma::vec& v0, const arma::vec& v1,
const arma::vec& v2, const arma::vec& v3,
const SubsetMinorPartition& part) const;
bool weightIndicator(const arma::mat& V, const SubsetMinorPartition& part) const;
public:
IntegratedMinorKernelEvaluator(int xDim, int yDim,
arma::uvec xInds0, arma::uvec xInds1,
arma::uvec yInds0, arma::uvec yInds1);
int order() const;
double eval(const arma::mat& X, const arma::mat& Y) const;
};
class IntegratedMinorEvaluator {
private:
SubsetMinorPartition xPart;
SubsetMinorPartition yPart;
std::vector<double> minLower;
int xDim;
int yDim;
bool xIndsEq;
bool yIndsEq;
double countGreaterInX(const std::vector<double> point,
const arma::uvec& xGreaterInds,
const EmpiricalDistribution& ed) const;
double countGreaterInY(const std::vector<double> point,
const arma::uvec& yGreaterInds,
const EmpiricalDistribution& ed) const;
double countGreaterInXY(const std::vector<double> point,
const arma::uvec& xGreaterInds,
const arma::uvec& yGreaterInds,
const EmpiricalDistribution& ed) const;
public:
IntegratedMinorEvaluator(int xDim, int yDim,
arma::uvec xInds0, arma::uvec xInds1,
arma::uvec yInds0, arma::uvec yInds1);
double eval(const arma::mat& X, const arma::mat& Y) const;
};
#endif
|
#include <iostream>
#include <vector>
#include <algorithm>
const std::vector<std::size_t> GetPrimes(std::size_t min, std::size_t max)
{
if (max <= 1)
{
return {};
}
std::vector<bool> check(max + 1, true);
for (std::size_t i = 2; i * i <= max; ++i)
{
if (check[i])
{
for (std::size_t j = i * i; j <= max; j += i)
{
check[j] = false;
}
}
}
std::vector<std::size_t> result;
for (std::size_t i = 2; i <= max; ++i)
{
if (check[i] && i >= min)
{
result.push_back(i);
}
}
return result;
}
int main()
{
std::ios_base::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int a, b;
std::cin >> a >> b;
std::vector<std::size_t> result = GetPrimes(a, b);
std::for_each(result.begin(), result.end(), [](std::size_t c){std::cout << c << '\n';});
return 0;
}
|
#include<iostream>
using namespace std;
int countingValleys(int steps, string path) {
int seal = 0;
int valley = 0;
for(int i=0; i<steps; i++){
if(path[i]=='D'){
seal--;
} else if(path[i]=='U'){
seal++;
}
if(path[i] == 'U'&&seal==0){
valley++;
}
}
return valley;
}
|
#include <iostream>
using namespace std;
#define MAX 100000
#define NIL -1
struct Node { int parent, left, right; };
struct Node T[MAX];
int D[MAX];
// int getDepth(int u){
// d = 0;
// while(T[u].parent != NIL){
// u = T[u].parent;
// d++;
// }
// return d;
// }
void setDepth(int u, int p){
D[u] = p;
if(T[u].right != NIL){
setDepth(T[u].right, p);
}
if(T[u].left != NIL){
setDepth(T[u].left, p+1);
}
}
void print(int n){
bool isFirst;
for(int i=0; i<n; i++){
cout << "node " << i << ": ";
cout << "parent = " << T[i].parent << ", ";
cout << "depth = " << D[i] << ", ";
if(T[i].parent == NIL) cout << "root, ";
else if(T[i].left == NIL) cout << "leaf, ";
else cout << "internal node, ";
cout << "[";
int c = T[i].left;
isFirst = true;
while(c != NIL){
if(!isFirst) cout << ", ";
isFirst = false;
cout << c;
c = T[c].right;
}
cout << "]" << endl;
}
return;
}
int main(void){
int n, id, k, c, left, root;
cin >> n;
for(int i=0; i<n; i++){
T[i].parent = T[i].left = T[i].right = -1;
}
for(int i=0; i<n; i++){
cin >> id >> k;
for(int j=0; j<k; j++){
cin >> c;
T[c].parent = id;
if(j) T[left].right = c;
else T[id].left = c;
left = c;
}
}
for(int i=0; i<n; i++){
if(T[i].parent == NIL) root = i;
}
setDepth(root, 0);
print(n);
return 0;
}
|
#include <map>
#include <vector>
#include <string>
#include "rsdgMission.h"
using namespace std;
pair<int, int> getLoc(map<string,pair<int,int>>&,string);
void addLoc(map<string,pair<int,int>>&,string, int, int);
|
// Created on: 2001-09-26
// Created by: Michael KLOKOV
// Copyright (c) 2001-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 _IntTools_MarkedRangeSet_HeaderFile
#define _IntTools_MarkedRangeSet_HeaderFile
#include <IntTools_CArray1OfReal.hxx>
#include <TColStd_SequenceOfReal.hxx>
#include <TColStd_SequenceOfInteger.hxx>
class IntTools_Range;
//! class MarkedRangeSet provides continuous set of ranges marked with flags
class IntTools_MarkedRangeSet
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT IntTools_MarkedRangeSet();
//! build set of ranges which consists of one range with
//! boundary values theFirstBoundary and theLastBoundary
Standard_EXPORT IntTools_MarkedRangeSet(const Standard_Real theFirstBoundary, const Standard_Real theLastBoundary, const Standard_Integer theInitFlag);
//! Build set of ranges based on the array of progressive sorted values
//!
//! Warning:
//! The constructor do not check if the values of array are not sorted
//! It should be checked before function invocation
Standard_EXPORT IntTools_MarkedRangeSet(const TColStd_Array1OfReal& theSortedArray, const Standard_Integer theInitFlag);
//! build set of ranges which consists of one range with
//! boundary values theFirstBoundary and theLastBoundary
Standard_EXPORT void SetBoundaries (const Standard_Real theFirstBoundary, const Standard_Real theLastBoundary, const Standard_Integer theInitFlag);
//! Build set of ranges based on the array of progressive sorted values
//!
//! Warning:
//! The function do not check if the values of array are not sorted
//! It should be checked before function invocation
Standard_EXPORT void SetRanges (const TColStd_Array1OfReal& theSortedArray, const Standard_Integer theInitFlag);
//! Inserts a new range marked with flag theFlag
//! It replace the existing ranges or parts of ranges
//! and their flags.
//! Returns True if the range is inside the initial boundaries,
//! otherwise or in case of some error returns False
Standard_EXPORT Standard_Boolean InsertRange (const Standard_Real theFirstBoundary, const Standard_Real theLastBoundary, const Standard_Integer theFlag);
//! Inserts a new range marked with flag theFlag
//! It replace the existing ranges or parts of ranges
//! and their flags.
//! Returns True if the range is inside the initial boundaries,
//! otherwise or in case of some error returns False
Standard_EXPORT Standard_Boolean InsertRange (const IntTools_Range& theRange, const Standard_Integer theFlag);
//! Inserts a new range marked with flag theFlag
//! It replace the existing ranges or parts of ranges
//! and their flags.
//! The index theIndex is a position where the range will be inserted.
//! Returns True if the range is inside the initial boundaries,
//! otherwise or in case of some error returns False
Standard_EXPORT Standard_Boolean InsertRange (const Standard_Real theFirstBoundary, const Standard_Real theLastBoundary, const Standard_Integer theFlag, const Standard_Integer theIndex);
//! Inserts a new range marked with flag theFlag
//! It replace the existing ranges or parts of ranges
//! and their flags.
//! The index theIndex is a position where the range will be inserted.
//! Returns True if the range is inside the initial boundaries,
//! otherwise or in case of some error returns False
Standard_EXPORT Standard_Boolean InsertRange (const IntTools_Range& theRange, const Standard_Integer theFlag, const Standard_Integer theIndex);
//! Set flag theFlag for range with index theIndex
Standard_EXPORT void SetFlag (const Standard_Integer theIndex, const Standard_Integer theFlag);
//! Returns flag of the range with index theIndex
Standard_EXPORT Standard_Integer Flag (const Standard_Integer theIndex) const;
//! Returns index of range which contains theValue.
//! If theValue do not belong any range returns 0.
Standard_EXPORT Standard_Integer GetIndex (const Standard_Real theValue) const;
Standard_EXPORT const TColStd_SequenceOfInteger& GetIndices (const Standard_Real theValue);
//! Returns index of range which contains theValue
//! If theValue do not belong any range returns 0.
//! If UseLower is Standard_True then lower boundary of the range
//! can be equal to theValue, otherwise upper boundary of the range
//! can be equal to theValue.
Standard_EXPORT Standard_Integer GetIndex (const Standard_Real theValue, const Standard_Boolean UseLower) const;
//! Returns number of ranges
Standard_Integer Length() const { return myRangeNumber; }
//! Returns the range with index theIndex.
//! the Index can be from 1 to Length()
Standard_EXPORT IntTools_Range Range (const Standard_Integer theIndex) const;
private:
TColStd_SequenceOfReal myRangeSetStorer;
Standard_Integer myRangeNumber;
TColStd_SequenceOfInteger myFlags;
TColStd_SequenceOfInteger myFoundIndices;
};
#endif // _IntTools_MarkedRangeSet_HeaderFile
|
๏ปฟ
#include "ar.Base.h"
namespace ar
{
}
|
#pragma once
#include "afxcmn.h"
#include "ClistCtrlEx.h"
// MyDelayDlg ๅฏน่ฏๆก
class MyDelayDlg : public CDialogEx
{
DECLARE_DYNAMIC(MyDelayDlg)
public:
MyDelayDlg(CWnd* pParent = NULL); // ๆ ๅๆ้ ๅฝๆฐ
virtual ~MyDelayDlg();
// ๅฏน่ฏๆกๆฐๆฎ
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_DELAYTAB_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV ๆฏๆ
DECLARE_MESSAGE_MAP()
public:
ClistCtrlEx m_List_Delay_Dll;
ClistCtrlEx m_List_Delay_Funcition;
virtual BOOL OnInitDialog();
afx_msg void OnClickList1(NMHDR *pNMHDR, LRESULT *pResult);
};
|
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
long int aVeryBigSum(int n, int ar_size, long int* ar) {
long long int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+ar[i];
}
return sum;
}
int main() {
int n;
scanf("%i", &n);
long int *ar = malloc(sizeof(long int) * n);
for(int ar_i = 0; ar_i < n; ar_i++){
scanf("%li",&ar[ar_i]);
}
long int result = aVeryBigSum(n, n, ar);
printf("%ld\n", result);
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
**
** Copyright (C) 2005 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** THIS FILE IS AUTO-GENERATED BY A SCRIPT. DO NOT EDIT THIS FILE DIRECTLY!
*/
#include "core/pch.h"
#ifdef SVG_SUPPORT
#include "modules/svg/src/svgpch.h"
#include "modules/svg/src/SVGInternalEnum.h"
#include "modules/svg/src/SVGInternalEnumTables.h"
#include "modules/svg/src/SVGManagerImpl.h"
#include "modules/style/css_all_values.h"
#include "modules/display/cursor.h"
#ifdef _DEBUG
CONST_ARRAY(g_svg_enum_type_strings, char*)
CONST_ENTRY("SVGENUM_UNKNOWN"),
CONST_ENTRY("SVGENUM_SPREAD_METHOD_TYPE"),
CONST_ENTRY("SVGENUM_UNITS_TYPE"),
CONST_ENTRY("SVGENUM_TRANSFORM_TYPE"),
CONST_ENTRY("SVGENUM_ATTRIBUTE_TYPE"),
CONST_ENTRY("SVGENUM_CALCMODE"),
CONST_ENTRY("SVGENUM_VISIBILITY"),
CONST_ENTRY("SVGENUM_ANIMATEFILLTYPE"),
CONST_ENTRY("SVGENUM_ADDITIVE"),
CONST_ENTRY("SVGENUM_ACCUMULATE"),
CONST_ENTRY("SVGENUM_FILL_RULE"),
CONST_ENTRY("SVGENUM_STROKE_LINECAP"),
CONST_ENTRY("SVGENUM_STROKE_LINEJOIN"),
CONST_ENTRY("SVGENUM_DISPLAY"),
CONST_ENTRY("SVGENUM_ZOOM_AND_PAN"),
CONST_ENTRY("SVGENUM_FONT_WEIGHT"),
CONST_ENTRY("SVGENUM_FONT_STYLE"),
CONST_ENTRY("SVGENUM_TEXT_ANCHOR"),
CONST_ENTRY("SVGENUM_FONT_VARIANT"),
CONST_ENTRY("SVGENUM_RESTART"),
CONST_ENTRY("SVGENUM_REQUIREDFEATURES"),
CONST_ENTRY("SVGENUM_POINTER_EVENTS"),
CONST_ENTRY("SVGENUM_METHOD"),
#ifdef SVG_SUPPORT_FILTERS
CONST_ENTRY("SVGENUM_STITCHTILES"),
CONST_ENTRY("SVGENUM_DISPLACEMENTSELECTOR"),
CONST_ENTRY("SVGENUM_CONVOLVEEDGEMODE"),
CONST_ENTRY("SVGENUM_COMPOSITEOPERATOR"),
CONST_ENTRY("SVGENUM_MORPHOLOGYOPERATOR"),
CONST_ENTRY("SVGENUM_BLENDMODE"),
CONST_ENTRY("SVGENUM_TURBULENCETYPE"),
CONST_ENTRY("SVGENUM_COLORMATRIXTYPE"),
CONST_ENTRY("SVGENUM_FUNCTYPE"),
#endif // SVG_SUPPORT_FILTERS
CONST_ENTRY("SVGENUM_BOOLEAN"),
CONST_ENTRY("SVGENUM_LENGTHADJUST"),
CONST_ENTRY("SVGENUM_TEXTDECORATION"),
CONST_ENTRY("SVGENUM_SPACING"),
CONST_ENTRY("SVGENUM_CURSOR"),
CONST_ENTRY("SVGENUM_OVERFLOW"),
CONST_ENTRY("SVGENUM_UNICODE_BIDI"),
CONST_ENTRY("SVGENUM_WRITING_MODE"),
CONST_ENTRY("SVGENUM_ALIGNMENT_BASELINE"),
CONST_ENTRY("SVGENUM_DOMINANT_BASELINE"),
CONST_ENTRY("SVGENUM_ARABIC_FORM"),
CONST_ENTRY("SVGENUM_DIRECTION"),
CONST_ENTRY("SVGENUM_IMAGE_RENDERING"),
CONST_ENTRY("SVGENUM_MARKER_UNITS"),
CONST_ENTRY("SVGENUM_TEXT_RENDERING"),
CONST_ENTRY("SVGENUM_COLOR_INTERPOLATION"),
CONST_ENTRY("SVGENUM_FOCUSABLE"),
CONST_ENTRY("SVGENUM_VECTOR_EFFECT"),
CONST_ENTRY("SVGENUM_FOCUSHIGHLIGHT"),
CONST_ENTRY("SVGENUM_INITIALVISIBILITY"),
CONST_ENTRY("SVGENUM_TRANSFORMBEHAVIOR"),
CONST_ENTRY("SVGENUM_OVERLAY"),
CONST_ENTRY("SVGENUM_DISPLAY_ALIGN"),
CONST_ENTRY("SVGENUM_EDITABLE"),
CONST_ENTRY("SVGENUM_TEXT_ALIGN"),
CONST_ENTRY("SVGENUM_TEXT_OVERFLOW"),
CONST_ENTRY("SVGENUM_AUTO"),
CONST_ENTRY("SVGENUM_SYNCBEHAVIOR"),
CONST_ENTRY("SVGENUM_NONE"),
CONST_ENTRY("SVGENUM_SHAPE_RENDERING"),
CONST_ENTRY("SVGENUM_BUFFERED_RENDERING"),
CONST_ENTRY("SVGENUM_TIMELINEBEGIN")
CONST_END(g_svg_enum_type_strings)
CONST_ARRAY(g_svg_enum_name_strings, char*)
CONST_ENTRY("SVGSPREAD_PAD"),
CONST_ENTRY("SVGSPREAD_REFLECT"),
CONST_ENTRY("SVGSPREAD_REPEAT"),
CONST_ENTRY("SVGUNITS_USERSPACEONUSE"),
CONST_ENTRY("SVGUNITS_OBJECTBBOX"),
CONST_ENTRY("SVGTRANSFORM_MATRIX"),
CONST_ENTRY("SVGTRANSFORM_TRANSLATE"),
CONST_ENTRY("SVGTRANSFORM_ROTATE"),
CONST_ENTRY("SVGTRANSFORM_SCALE"),
CONST_ENTRY("SVGTRANSFORM_SKEWX"),
CONST_ENTRY("SVGTRANSFORM_SKEWY"),
CONST_ENTRY("SVGATTRIBUTE_CSS"),
CONST_ENTRY("SVGATTRIBUTE_XML"),
CONST_ENTRY("SVGATTRIBUTE_AUTO"),
CONST_ENTRY("SVGCALCMODE_DISCRETE"),
CONST_ENTRY("SVGCALCMODE_LINEAR"),
CONST_ENTRY("SVGCALCMODE_SPLINE"),
CONST_ENTRY("SVGCALCMODE_PACED"),
CONST_ENTRY("SVGVISIBILITY_VISIBLE"),
CONST_ENTRY("SVGVISIBILITY_HIDDEN"),
CONST_ENTRY("SVGVISIBILITY_COLLAPSE"),
CONST_ENTRY("SVGANIMATEFILL_FREEZE"),
CONST_ENTRY("SVGANIMATEFILL_REMOVE"),
CONST_ENTRY("SVGADDITIVE_REPLACE"),
CONST_ENTRY("SVGADDITIVE_SUM"),
CONST_ENTRY("SVGACCUMULATE_NONE"),
CONST_ENTRY("SVGACCUMULATE_SUM"),
CONST_ENTRY("SVGFILL_EVEN_ODD"),
CONST_ENTRY("SVGFILL_NON_ZERO"),
CONST_ENTRY("SVGCAP_BUTT"),
CONST_ENTRY("SVGCAP_ROUND"),
CONST_ENTRY("SVGCAP_SQUARE"),
CONST_ENTRY("SVGJOIN_MITER"),
CONST_ENTRY("SVGJOIN_ROUND"),
CONST_ENTRY("SVGJOIN_BEVEL"),
CONST_ENTRY("SVGDISPLAY_INLINE"),
CONST_ENTRY("SVGDISPLAY_BLOCK"),
CONST_ENTRY("SVGDISPLAY_LISTITEM"),
CONST_ENTRY("SVGDISPLAY_RUNIN"),
CONST_ENTRY("SVGDISPLAY_COMPACT"),
CONST_ENTRY("SVGDISPLAY_MARKER"),
CONST_ENTRY("SVGDISPLAY_TABLE"),
CONST_ENTRY("SVGDISPLAY_INLINETABLE"),
CONST_ENTRY("SVGDISPLAY_TABLEROWGROUP"),
CONST_ENTRY("SVGDISPLAY_TABLEHEADERGROUP"),
CONST_ENTRY("SVGDISPLAY_TABLEFOOTERGROUP"),
CONST_ENTRY("SVGDISPLAY_TABLEROW"),
CONST_ENTRY("SVGDISPLAY_TABLECOLUMNGROUP"),
CONST_ENTRY("SVGDISPLAY_TABLECOLUMN"),
CONST_ENTRY("SVGDISPLAY_TABLECELL"),
CONST_ENTRY("SVGDISPLAY_TABLECAPTION"),
CONST_ENTRY("SVGDISPLAY_NONE"),
CONST_ENTRY("SVGZOOMANDPAN_DISABLE"),
CONST_ENTRY("SVGZOOMANDPAN_MAGNIFY"),
CONST_ENTRY("SVGFONTWEIGHT_NORMAL"),
CONST_ENTRY("SVGFONTWEIGHT_BOLD"),
CONST_ENTRY("SVGFONTWEIGHT_BOLDER"),
CONST_ENTRY("SVGFONTWEIGHT_LIGHTER"),
CONST_ENTRY("SVGFONTWEIGHT_100"),
CONST_ENTRY("SVGFONTWEIGHT_200"),
CONST_ENTRY("SVGFONTWEIGHT_300"),
CONST_ENTRY("SVGFONTWEIGHT_400"),
CONST_ENTRY("SVGFONTWEIGHT_500"),
CONST_ENTRY("SVGFONTWEIGHT_600"),
CONST_ENTRY("SVGFONTWEIGHT_700"),
CONST_ENTRY("SVGFONTWEIGHT_800"),
CONST_ENTRY("SVGFONTWEIGHT_900"),
CONST_ENTRY("SVGFONTSTYLE_NORMAL"),
CONST_ENTRY("SVGFONTSTYLE_ITALIC"),
CONST_ENTRY("SVGFONTSTYLE_OBLIQUE"),
CONST_ENTRY("SVGTEXTANCHOR_START"),
CONST_ENTRY("SVGTEXTANCHOR_MIDDLE"),
CONST_ENTRY("SVGTEXTANCHOR_END"),
CONST_ENTRY("SVGFONTVARIANT_NORMAL"),
CONST_ENTRY("SVGFONTVARIANT_SMALLCAPS"),
CONST_ENTRY("SVGRESTART_ALWAYS"),
CONST_ENTRY("SVGRESTART_WHENNOTACTIVE"),
CONST_ENTRY("SVGRESTART_NEVER"),
CONST_ENTRY("SVGRESTART_UNKNOWN"),
CONST_ENTRY("SVGFEATURE_SVG"),
CONST_ENTRY("SVGFEATURE_SVGDOM"),
CONST_ENTRY("SVGFEATURE_SVGSTATIC"),
CONST_ENTRY("SVGFEATURE_SVGDOMSTATIC"),
CONST_ENTRY("SVGFEATURE_SVGANIMATION"),
CONST_ENTRY("SVGFEATURE_SVGDOMANIMATION"),
CONST_ENTRY("SVGFEATURE_SVGDYNAMIC"),
CONST_ENTRY("SVGFEATURE_SVGDOMDYNAMIC"),
CONST_ENTRY("SVGFEATURE_COREATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_STRUCTURE"),
CONST_ENTRY("SVGFEATURE_CONTAINERATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_CONDITIONALPROCESSING"),
CONST_ENTRY("SVGFEATURE_IMAGE"),
CONST_ENTRY("SVGFEATURE_STYLE"),
CONST_ENTRY("SVGFEATURE_VIEWPORTATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_SHAPE"),
CONST_ENTRY("SVGFEATURE_TEXT"),
CONST_ENTRY("SVGFEATURE_PAINTATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_OPACITYATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_GRAPHICSATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_MARKER"),
CONST_ENTRY("SVGFEATURE_COLORPROFILE"),
CONST_ENTRY("SVGFEATURE_GRADIENT"),
CONST_ENTRY("SVGFEATURE_PATTERN"),
CONST_ENTRY("SVGFEATURE_CLIP"),
CONST_ENTRY("SVGFEATURE_MASK"),
CONST_ENTRY("SVGFEATURE_FILTER"),
CONST_ENTRY("SVGFEATURE_DOCUMENTEVENTSATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_GRAPHICALEVENTSATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_ANIMATIONEVENTSATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_CURSOR"),
CONST_ENTRY("SVGFEATURE_HYPERLINKING"),
CONST_ENTRY("SVGFEATURE_XLINKATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_EXTERNALRESOURCESREQUIRED"),
CONST_ENTRY("SVGFEATURE_VIEW"),
CONST_ENTRY("SVGFEATURE_SCRIPT"),
CONST_ENTRY("SVGFEATURE_ANIMATION"),
CONST_ENTRY("SVGFEATURE_FONT"),
CONST_ENTRY("SVGFEATURE_EXTENSIBILITY"),
CONST_ENTRY("SVGFEATURE_TINY_BASE"),
CONST_ENTRY("SVGFEATURE_TINY_INTERACTIVITY"),
CONST_ENTRY("SVGFEATURE_TINY_ALL"),
CONST_ENTRY("SVGFEATURE_BASIC_ALL"),
CONST_ENTRY("SVGFEATURE_BASIC_BASE"),
CONST_ENTRY("SVGFEATURE_BASIC_CLIP"),
CONST_ENTRY("SVGFEATURE_BASIC_CSS"),
CONST_ENTRY("SVGFEATURE_BASIC_DOMCORE"),
CONST_ENTRY("SVGFEATURE_BASIC_DOMEXTENDED"),
CONST_ENTRY("SVGFEATURE_BASIC_FILTER"),
CONST_ENTRY("SVGFEATURE_BASIC_FONT"),
CONST_ENTRY("SVGFEATURE_BASIC_GRAPHICSATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_BASIC_INTERACTIVITY"),
CONST_ENTRY("SVGFEATURE_BASIC_PAINTATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_BASIC_STRUCTURE"),
CONST_ENTRY("SVGFEATURE_BASIC_TEXT"),
CONST_ENTRY("SVGFEATURE_1_0"),
CONST_ENTRY("SVGFEATURE_1_0_STATIC"),
CONST_ENTRY("SVGFEATURE_1_0_DYNAMIC"),
CONST_ENTRY("SVGFEATURE_1_0_ANIMATION"),
CONST_ENTRY("SVGFEATURE_1_0_ALL"),
CONST_ENTRY("SVGFEATURE_1_0_DOM"),
CONST_ENTRY("SVGFEATURE_1_0_DOM_STATIC"),
CONST_ENTRY("SVGFEATURE_1_0_DOM_DYNAMIC"),
CONST_ENTRY("SVGFEATURE_1_0_DOM_ANIMATION"),
CONST_ENTRY("SVGFEATURE_1_0_DOM_ALL"),
CONST_ENTRY("SVGFEATURE_1_2_SVGSTATIC"),
CONST_ENTRY("SVGFEATURE_1_2_SVGSTATICDOM"),
CONST_ENTRY("SVGFEATURE_1_2_SVGANIMATED"),
CONST_ENTRY("SVGFEATURE_1_2_SVGINTERACTIVE"),
CONST_ENTRY("SVGFEATURE_1_2_SVGALL"),
CONST_ENTRY("SVGFEATURE_1_2_CORE_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_NAVIGATION_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_STRUCTURE"),
CONST_ENTRY("SVGFEATURE_1_2_CONDITIONAL_PROCESSING"),
CONST_ENTRY("SVGFEATURE_1_2_CONDITIONAL_PROCESSING_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_IMAGE"),
CONST_ENTRY("SVGFEATURE_1_2_PREFETCH"),
CONST_ENTRY("SVGFEATURE_1_2_DISCARD"),
CONST_ENTRY("SVGFEATURE_1_2_SHAPE"),
CONST_ENTRY("SVGFEATURE_1_2_TEXT"),
CONST_ENTRY("SVGFEATURE_1_2_PAINT_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_OPACITY_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_GRAPHICS_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_GRADIENT"),
CONST_ENTRY("SVGFEATURE_1_2_SOLID_COLOR"),
CONST_ENTRY("SVGFEATURE_1_2_HYPERLINKING"),
CONST_ENTRY("SVGFEATURE_1_2_XLINK_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_EXTERNALRESOURCESREQUIRED"),
CONST_ENTRY("SVGFEATURE_1_2_SCRIPTING"),
CONST_ENTRY("SVGFEATURE_1_2_HANDLER"),
CONST_ENTRY("SVGFEATURE_1_2_LISTENER"),
CONST_ENTRY("SVGFEATURE_1_2_TIMEDANIMATION"),
CONST_ENTRY("SVGFEATURE_1_2_ANIMATION"),
CONST_ENTRY("SVGFEATURE_1_2_AUDIO"),
CONST_ENTRY("SVGFEATURE_1_2_VIDEO"),
CONST_ENTRY("SVGFEATURE_1_2_FONT"),
CONST_ENTRY("SVGFEATURE_1_2_EXTENSIBILITY"),
CONST_ENTRY("SVGFEATURE_1_2_MEDIA_ATTRIBUTE"),
CONST_ENTRY("SVGFEATURE_1_2_TEXTFLOW"),
CONST_ENTRY("SVGFEATURE_1_2_TRANSFORMEDVIDEO"),
CONST_ENTRY("SVGFEATURE_1_2_COMPOSEDVIDEO"),
CONST_ENTRY("SVGFEATURE_1_2_EDITABLE_ATTRIBUTE"),
CONST_ENTRY("SVGPOINTEREVENTS_VISIBLEPAINTED"),
CONST_ENTRY("SVGPOINTEREVENTS_VISIBLEFILL"),
CONST_ENTRY("SVGPOINTEREVENTS_VISIBLESTROKE"),
CONST_ENTRY("SVGPOINTEREVENTS_VISIBLE"),
CONST_ENTRY("SVGPOINTEREVENTS_PAINTED"),
CONST_ENTRY("SVGPOINTEREVENTS_FILL"),
CONST_ENTRY("SVGPOINTEREVENTS_STROKE"),
CONST_ENTRY("SVGPOINTEREVENTS_ALL"),
CONST_ENTRY("SVGPOINTEREVENTS_NONE"),
CONST_ENTRY("SVGPOINTEREVENTS_BOUNDINGBOX"),
CONST_ENTRY("SVGMETHOD_ALIGN"),
CONST_ENTRY("SVGMETHOD_STRETCH"),
#ifdef SVG_SUPPORT_FILTERS
CONST_ENTRY("SVGSTITCH_STITCH"),
CONST_ENTRY("SVGSTITCH_NOSTITCH"),
CONST_ENTRY("SVGDISPLACEMENT_R"),
CONST_ENTRY("SVGDISPLACEMENT_G"),
CONST_ENTRY("SVGDISPLACEMENT_B"),
CONST_ENTRY("SVGDISPLACEMENT_A"),
CONST_ENTRY("SVGCONVOLVEEDGEMODE_DUPLICATE"),
CONST_ENTRY("SVGCONVOLVEEDGEMODE_WRAP"),
CONST_ENTRY("SVGCONVOLVEEDGEMODE_NONE"),
CONST_ENTRY("SVGCOMPOSITEOPERATOR_OVER"),
CONST_ENTRY("SVGCOMPOSITEOPERATOR_IN"),
CONST_ENTRY("SVGCOMPOSITEOPERATOR_OUT"),
CONST_ENTRY("SVGCOMPOSITEOPERATOR_ATOP"),
CONST_ENTRY("SVGCOMPOSITEOPERATOR_XOR"),
CONST_ENTRY("SVGCOMPOSITEOPERATOR_ARITHMETIC"),
CONST_ENTRY("SVGMORPHOPERATOR_ERODE"),
CONST_ENTRY("SVGMORPHOPERATOR_DILATE"),
CONST_ENTRY("SVGBLENDMODE_NORMAL"),
CONST_ENTRY("SVGBLENDMODE_MULTIPLY"),
CONST_ENTRY("SVGBLENDMODE_SCREEN"),
CONST_ENTRY("SVGBLENDMODE_DARKEN"),
CONST_ENTRY("SVGBLENDMODE_LIGHTEN"),
CONST_ENTRY("SVGTURBULENCE_FRACTALNOISE"),
CONST_ENTRY("SVGTURBULENCE_TURBULENCE"),
CONST_ENTRY("SVGCOLORMATRIX_MATRIX"),
CONST_ENTRY("SVGCOLORMATRIX_SATURATE"),
CONST_ENTRY("SVGCOLORMATRIX_HUEROTATE"),
CONST_ENTRY("SVGCOLORMATRIX_LUMINANCETOALPHA"),
CONST_ENTRY("SVGFUNC_IDENTITY"),
CONST_ENTRY("SVGFUNC_TABLE"),
CONST_ENTRY("SVGFUNC_DISCRETE"),
CONST_ENTRY("SVGFUNC_LINEAR"),
CONST_ENTRY("SVGFUNC_GAMMA"),
#endif // SVG_SUPPORT_FILTERS
CONST_ENTRY("FALSE"),
CONST_ENTRY("TRUE"),
CONST_ENTRY("SVGLENADJUST_SPACING"),
CONST_ENTRY("SVGLENADJUST_SPACINGANDGLYPHS"),
CONST_ENTRY("SVGTEXTDECORATION_NONE"),
CONST_ENTRY("SVGTEXTDECORATION_UNDERLINE"),
CONST_ENTRY("SVGTEXTDECORATION_OVERLINE"),
CONST_ENTRY("SVGTEXTDECORATION_LINETHROUGH"),
CONST_ENTRY("SVGTEXTDECORATION_BLINK"),
CONST_ENTRY("SVGSPACING_AUTO"),
CONST_ENTRY("SVGSPACING_EXACT"),
CONST_ENTRY("CURSOR_URI"),
CONST_ENTRY("CURSOR_CROSSHAIR"),
CONST_ENTRY("CURSOR_DEFAULT_ARROW"),
CONST_ENTRY("CURSOR_CUR_POINTER"),
CONST_ENTRY("CURSOR_MOVE"),
CONST_ENTRY("CURSOR_E_RESIZE"),
CONST_ENTRY("CURSOR_NE_RESIZE"),
CONST_ENTRY("CURSOR_NW_RESIZE"),
CONST_ENTRY("CURSOR_N_RESIZE"),
CONST_ENTRY("CURSOR_SE_RESIZE"),
CONST_ENTRY("CURSOR_SW_RESIZE"),
CONST_ENTRY("CURSOR_S_RESIZE"),
CONST_ENTRY("CURSOR_W_RESIZE"),
CONST_ENTRY("CURSOR_TEXT"),
CONST_ENTRY("CURSOR_WAIT"),
CONST_ENTRY("CURSOR_HELP"),
CONST_ENTRY("CSS_VALUE_visible"),
CONST_ENTRY("CSS_VALUE_hidden"),
CONST_ENTRY("CSS_VALUE_scroll"),
CONST_ENTRY("CSS_VALUE_auto"),
CONST_ENTRY("CSS_VALUE_normal"),
CONST_ENTRY("CSS_VALUE_embed"),
CONST_ENTRY("CSS_VALUE_bidi_override"),
CONST_ENTRY("SVGWRITINGMODE_LR_TB"),
CONST_ENTRY("SVGWRITINGMODE_RL_TB"),
CONST_ENTRY("SVGWRITINGMODE_TB_RL"),
CONST_ENTRY("SVGWRITINGMODE_LR"),
CONST_ENTRY("SVGWRITINGMODE_RL"),
CONST_ENTRY("SVGWRITINGMODE_TB"),
CONST_ENTRY("SVGALIGNMENTBASELINE_AUTO"),
CONST_ENTRY("SVGALIGNMENTBASELINE_BASELINE"),
CONST_ENTRY("SVGALIGNMENTBASELINE_BEFORE_EDGE"),
CONST_ENTRY("SVGALIGNMENTBASELINE_TEXT_BEFORE_EDGE"),
CONST_ENTRY("SVGALIGNMENTBASELINE_MIDDLE"),
CONST_ENTRY("SVGALIGNMENTBASELINE_CENTRAL"),
CONST_ENTRY("SVGALIGNMENTBASELINE_AFTER_EDGE"),
CONST_ENTRY("SVGALIGNMENTBASELINE_TEXT_AFTER_EDGE"),
CONST_ENTRY("SVGALIGNMENTBASELINE_IDEOGRAPHIC"),
CONST_ENTRY("SVGALIGNMENTBASELINE_ALPHABETIC"),
CONST_ENTRY("SVGALIGNMENTBASELINE_HANGING"),
CONST_ENTRY("SVGALIGNMENTBASELINE_MATHEMATICAL"),
CONST_ENTRY("SVGDOMINANTBASELINE_AUTO"),
CONST_ENTRY("SVGDOMINANTBASELINE_USE_SCRIPT"),
CONST_ENTRY("SVGDOMINANTBASELINE_NO_CHANGE"),
CONST_ENTRY("SVGDOMINANTBASELINE_RESET_SIZE"),
CONST_ENTRY("SVGDOMINANTBASELINE_IDEOGRAPHIC"),
CONST_ENTRY("SVGDOMINANTBASELINE_ALPHABETIC"),
CONST_ENTRY("SVGDOMINANTBASELINE_HANGING"),
CONST_ENTRY("SVGDOMINANTBASELINE_MATHEMATICAL"),
CONST_ENTRY("SVGDOMINANTBASELINE_CENTRAL"),
CONST_ENTRY("SVGDOMINANTBASELINE_MIDDLE"),
CONST_ENTRY("SVGDOMINANTBASELINE_TEXT_AFTER_EDGE"),
CONST_ENTRY("SVGDOMINANTBASELINE_TEXT_BEFORE_EDGE"),
CONST_ENTRY("SVGARABICFORM_INITIAL"),
CONST_ENTRY("SVGARABICFORM_MEDIAL"),
CONST_ENTRY("SVGARABICFORM_TERMINAL"),
CONST_ENTRY("SVGARABICFORM_ISOLATED"),
CONST_ENTRY("CSS_VALUE_ltr"),
CONST_ENTRY("CSS_VALUE_rtl"),
CONST_ENTRY("SVGIMAGERENDERING_AUTO"),
CONST_ENTRY("SVGIMAGERENDERING_OPTIMIZESPEED"),
CONST_ENTRY("SVGIMAGERENDERING_OPTIMIZEQUALITY"),
CONST_ENTRY("SVGMARKERUNITS_STROKEWIDTH"),
CONST_ENTRY("SVGMARKERUNITS_USERSPACEONUSE"),
CONST_ENTRY("SVGTEXTRENDERING_AUTO"),
CONST_ENTRY("SVGTEXTRENDERING_OPTIMIZESPEED"),
CONST_ENTRY("SVGTEXTRENDERING_OPTIMIZELEGIBILITY"),
CONST_ENTRY("SVGTEXTRENDERING_GEOMETRICPRECISION"),
CONST_ENTRY("SVGCOLORINTERPOLATION_AUTO"),
CONST_ENTRY("SVGCOLORINTERPOLATION_SRGB"),
CONST_ENTRY("SVGCOLORINTERPOLATION_LINEARRGB"),
CONST_ENTRY("SVGFOCUSABLE_TRUE"),
CONST_ENTRY("SVGFOCUSABLE_FALSE"),
CONST_ENTRY("SVGFOCUSABLE_AUTO"),
CONST_ENTRY("SVGVECTOREFFECT_NONE"),
CONST_ENTRY("SVGVECTOREFFECT_NON_SCALING_STROKE"),
CONST_ENTRY("SVGFOCUSHIGHLIGHT_NONE"),
CONST_ENTRY("SVGFOCUSHIGHLIGHT_AUTO"),
CONST_ENTRY("SVGINITIALVISIBILITY_WHENSTARTED"),
CONST_ENTRY("SVGINITIALVISIBILITY_ALWAYS"),
CONST_ENTRY("SVGTRANSFORMBEHAVIOR_GEOMETRIC"),
CONST_ENTRY("SVGTRANSFORMBEHAVIOR_PINNED"),
CONST_ENTRY("SVGTRANSFORMBEHAVIOR_PINNED90"),
CONST_ENTRY("SVGTRANSFORMBEHAVIOR_PINNED180"),
CONST_ENTRY("SVGTRANSFORMBEHAVIOR_PINNED270"),
CONST_ENTRY("SVGOVERLAY_TOP"),
CONST_ENTRY("SVGOVERLAY_NONE"),
CONST_ENTRY("SVGDISPLAYALIGN_AUTO"),
CONST_ENTRY("SVGDISPLAYALIGN_BEFORE"),
CONST_ENTRY("SVGDISPLAYALIGN_CENTER"),
CONST_ENTRY("SVGDISPLAYALIGN_AFTER"),
CONST_ENTRY("SVGEDITABLE_NONE"),
CONST_ENTRY("SVGEDITABLE_SIMPLE"),
CONST_ENTRY("CSS_VALUE_start"),
CONST_ENTRY("CSS_VALUE_center"),
CONST_ENTRY("CSS_VALUE_end"),
CONST_ENTRY("CSS_VALUE_clip"),
CONST_ENTRY("CSS_VALUE_ellipsis"),
CONST_ENTRY("SVGAUTO_AUTO"),
CONST_ENTRY("SVGSYNCBEHAVIOR_CANSLIP"),
CONST_ENTRY("SVGSYNCBEHAVIOR_LOCKED"),
CONST_ENTRY("SVGSYNCBEHAVIOR_INDEPENDENT"),
CONST_ENTRY("SVGSYNCBEHAVIOR_DEFAULT"),
CONST_ENTRY("SVGSYNCBEHAVIOR_INHERIT"),
CONST_ENTRY("SVGSNAPSHOTTIME_NONE"),
CONST_ENTRY("SVGSHAPERENDERING_AUTO"),
CONST_ENTRY("SVGSHAPERENDERING_OPTIMIZESPEED"),
CONST_ENTRY("SVGSHAPERENDERING_CRISPEDGES"),
CONST_ENTRY("SVGSHAPERENDERING_GEOMETRICPRECISION"),
CONST_ENTRY("SVGBUFFEREDRENDERING_AUTO"),
CONST_ENTRY("SVGBUFFEREDRENDERING_STATIC"),
CONST_ENTRY("SVGBUFFEREDRENDERING_DYNAMIC"),
CONST_ENTRY("SVGTIMELINEBEGIN_ONLOAD"),
CONST_ENTRY("SVGTIMELINEBEGIN_ONSTART")
CONST_END(g_svg_enum_name_strings)
#endif // _DEBUG
const int svg_enum_lookup[] = {
-1,
SVG_ENUM_IDX_SVGENUM_SPREAD_METHOD_TYPE,
SVG_ENUM_IDX_SVGENUM_UNITS_TYPE,
SVG_ENUM_IDX_SVGENUM_TRANSFORM_TYPE,
SVG_ENUM_IDX_SVGENUM_ATTRIBUTE_TYPE,
SVG_ENUM_IDX_SVGENUM_CALCMODE,
SVG_ENUM_IDX_SVGENUM_VISIBILITY,
SVG_ENUM_IDX_SVGENUM_ANIMATEFILLTYPE,
SVG_ENUM_IDX_SVGENUM_ADDITIVE,
SVG_ENUM_IDX_SVGENUM_ACCUMULATE,
SVG_ENUM_IDX_SVGENUM_FILL_RULE,
SVG_ENUM_IDX_SVGENUM_STROKE_LINECAP,
SVG_ENUM_IDX_SVGENUM_STROKE_LINEJOIN,
SVG_ENUM_IDX_SVGENUM_DISPLAY,
SVG_ENUM_IDX_SVGENUM_ZOOM_AND_PAN,
SVG_ENUM_IDX_SVGENUM_FONT_WEIGHT,
SVG_ENUM_IDX_SVGENUM_FONT_STYLE,
SVG_ENUM_IDX_SVGENUM_TEXT_ANCHOR,
SVG_ENUM_IDX_SVGENUM_FONT_VARIANT,
SVG_ENUM_IDX_SVGENUM_RESTART,
SVG_ENUM_IDX_SVGENUM_REQUIREDFEATURES,
SVG_ENUM_IDX_SVGENUM_POINTER_EVENTS,
SVG_ENUM_IDX_SVGENUM_METHOD,
#ifdef SVG_SUPPORT_FILTERS
SVG_ENUM_IDX_SVGENUM_STITCHTILES,
SVG_ENUM_IDX_SVGENUM_DISPLACEMENTSELECTOR,
SVG_ENUM_IDX_SVGENUM_CONVOLVEEDGEMODE,
SVG_ENUM_IDX_SVGENUM_COMPOSITEOPERATOR,
SVG_ENUM_IDX_SVGENUM_MORPHOLOGYOPERATOR,
SVG_ENUM_IDX_SVGENUM_BLENDMODE,
SVG_ENUM_IDX_SVGENUM_TURBULENCETYPE,
SVG_ENUM_IDX_SVGENUM_COLORMATRIXTYPE,
SVG_ENUM_IDX_SVGENUM_FUNCTYPE,
#endif // SVG_SUPPORT_FILTERS
SVG_ENUM_IDX_SVGENUM_BOOLEAN,
SVG_ENUM_IDX_SVGENUM_LENGTHADJUST,
SVG_ENUM_IDX_SVGENUM_TEXTDECORATION,
SVG_ENUM_IDX_SVGENUM_SPACING,
SVG_ENUM_IDX_SVGENUM_CURSOR,
SVG_ENUM_IDX_SVGENUM_OVERFLOW,
SVG_ENUM_IDX_SVGENUM_UNICODE_BIDI,
SVG_ENUM_IDX_SVGENUM_WRITING_MODE,
SVG_ENUM_IDX_SVGENUM_ALIGNMENT_BASELINE,
SVG_ENUM_IDX_SVGENUM_DOMINANT_BASELINE,
SVG_ENUM_IDX_SVGENUM_ARABIC_FORM,
SVG_ENUM_IDX_SVGENUM_DIRECTION,
SVG_ENUM_IDX_SVGENUM_IMAGE_RENDERING,
SVG_ENUM_IDX_SVGENUM_MARKER_UNITS,
SVG_ENUM_IDX_SVGENUM_TEXT_RENDERING,
SVG_ENUM_IDX_SVGENUM_COLOR_INTERPOLATION,
SVG_ENUM_IDX_SVGENUM_FOCUSABLE,
SVG_ENUM_IDX_SVGENUM_VECTOR_EFFECT,
SVG_ENUM_IDX_SVGENUM_FOCUSHIGHLIGHT,
SVG_ENUM_IDX_SVGENUM_INITIALVISIBILITY,
SVG_ENUM_IDX_SVGENUM_TRANSFORMBEHAVIOR,
SVG_ENUM_IDX_SVGENUM_OVERLAY,
SVG_ENUM_IDX_SVGENUM_DISPLAY_ALIGN,
SVG_ENUM_IDX_SVGENUM_EDITABLE,
SVG_ENUM_IDX_SVGENUM_TEXT_ALIGN,
SVG_ENUM_IDX_SVGENUM_TEXT_OVERFLOW,
SVG_ENUM_IDX_SVGENUM_AUTO,
SVG_ENUM_IDX_SVGENUM_SYNCBEHAVIOR,
SVG_ENUM_IDX_SVGENUM_NONE,
SVG_ENUM_IDX_SVGENUM_SHAPE_RENDERING,
SVG_ENUM_IDX_SVGENUM_BUFFERED_RENDERING,
SVG_ENUM_IDX_SVGENUM_TIMELINEBEGIN,
};
SVG_ENUMS_START
SVG_ENUMS_ENTRY(SVGENUM_SPREAD_METHOD_TYPE, SVGSPREAD_PAD, "pad", 3)
SVG_ENUMS_ENTRY(SVGENUM_SPREAD_METHOD_TYPE, SVGSPREAD_REFLECT, "reflect", 7)
SVG_ENUMS_ENTRY(SVGENUM_SPREAD_METHOD_TYPE, SVGSPREAD_REPEAT, "repeat", 6)
SVG_ENUMS_ENTRY(SVGENUM_UNITS_TYPE, SVGUNITS_USERSPACEONUSE, "userSpaceOnUse", 14)
SVG_ENUMS_ENTRY(SVGENUM_UNITS_TYPE, SVGUNITS_OBJECTBBOX, "objectBoundingBox", 17)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORM_TYPE, SVGTRANSFORM_MATRIX, "matrix", 6)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORM_TYPE, SVGTRANSFORM_TRANSLATE, "translate", 9)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORM_TYPE, SVGTRANSFORM_ROTATE, "rotate", 6)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORM_TYPE, SVGTRANSFORM_SCALE, "scale", 5)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORM_TYPE, SVGTRANSFORM_SKEWX, "skewX", 5)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORM_TYPE, SVGTRANSFORM_SKEWY, "skewY", 5)
SVG_ENUMS_ENTRY(SVGENUM_ATTRIBUTE_TYPE, SVGATTRIBUTE_CSS, "CSS", 3)
SVG_ENUMS_ENTRY(SVGENUM_ATTRIBUTE_TYPE, SVGATTRIBUTE_XML, "XML", 3)
SVG_ENUMS_ENTRY(SVGENUM_ATTRIBUTE_TYPE, SVGATTRIBUTE_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_CALCMODE, SVGCALCMODE_DISCRETE, "discrete", 8)
SVG_ENUMS_ENTRY(SVGENUM_CALCMODE, SVGCALCMODE_LINEAR, "linear", 6)
SVG_ENUMS_ENTRY(SVGENUM_CALCMODE, SVGCALCMODE_SPLINE, "spline", 6)
SVG_ENUMS_ENTRY(SVGENUM_CALCMODE, SVGCALCMODE_PACED, "paced", 5)
SVG_ENUMS_ENTRY(SVGENUM_VISIBILITY, SVGVISIBILITY_VISIBLE, "visible", 7)
SVG_ENUMS_ENTRY(SVGENUM_VISIBILITY, SVGVISIBILITY_HIDDEN, "hidden", 6)
SVG_ENUMS_ENTRY(SVGENUM_VISIBILITY, SVGVISIBILITY_COLLAPSE, "collapse", 8)
SVG_ENUMS_ENTRY(SVGENUM_ANIMATEFILLTYPE, SVGANIMATEFILL_FREEZE, "freeze", 6)
SVG_ENUMS_ENTRY(SVGENUM_ANIMATEFILLTYPE, SVGANIMATEFILL_REMOVE, "remove", 6)
SVG_ENUMS_ENTRY(SVGENUM_ADDITIVE, SVGADDITIVE_REPLACE, "replace", 7)
SVG_ENUMS_ENTRY(SVGENUM_ADDITIVE, SVGADDITIVE_SUM, "sum", 3)
SVG_ENUMS_ENTRY(SVGENUM_ACCUMULATE, SVGACCUMULATE_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_ACCUMULATE, SVGACCUMULATE_SUM, "sum", 3)
SVG_ENUMS_ENTRY(SVGENUM_FILL_RULE, SVGFILL_EVEN_ODD, "evenodd", 7)
SVG_ENUMS_ENTRY(SVGENUM_FILL_RULE, SVGFILL_NON_ZERO, "nonzero", 7)
SVG_ENUMS_ENTRY(SVGENUM_STROKE_LINECAP, SVGCAP_BUTT, "butt", 4)
SVG_ENUMS_ENTRY(SVGENUM_STROKE_LINECAP, SVGCAP_ROUND, "round", 5)
SVG_ENUMS_ENTRY(SVGENUM_STROKE_LINECAP, SVGCAP_SQUARE, "square", 6)
SVG_ENUMS_ENTRY(SVGENUM_STROKE_LINEJOIN, SVGJOIN_MITER, "miter", 5)
SVG_ENUMS_ENTRY(SVGENUM_STROKE_LINEJOIN, SVGJOIN_ROUND, "round", 5)
SVG_ENUMS_ENTRY(SVGENUM_STROKE_LINEJOIN, SVGJOIN_BEVEL, "bevel", 5)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_INLINE, "inline", 6)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_BLOCK, "block", 5)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_LISTITEM, "list-item", 9)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_RUNIN, "run-in", 6)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_COMPACT, "compact", 7)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_MARKER, "marker", 6)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLE, "table", 5)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_INLINETABLE, "inline-table", 12)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLEROWGROUP, "table-row-group", 15)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLEHEADERGROUP, "table-header-group", 18)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLEFOOTERGROUP, "table-footer-group", 18)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLEROW, "table-row", 9)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLECOLUMNGROUP, "table-column-group", 18)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLECOLUMN, "table-column", 12)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLECELL, "table-cell", 10)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_TABLECAPTION, "table-caption", 13)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY, SVGDISPLAY_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_ZOOM_AND_PAN, SVGZOOMANDPAN_DISABLE, "disable", 7)
SVG_ENUMS_ENTRY(SVGENUM_ZOOM_AND_PAN, SVGZOOMANDPAN_MAGNIFY, "magnify", 7)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_NORMAL, "normal", 6)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_BOLD, "bold", 4)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_BOLDER, "bolder", 6)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_LIGHTER, "lighter", 7)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_100, "100", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_200, "200", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_300, "300", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_400, "400", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_500, "500", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_600, "600", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_700, "700", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_800, "800", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_WEIGHT, SVGFONTWEIGHT_900, "900", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_STYLE, SVGFONTSTYLE_NORMAL, "normal", 6)
SVG_ENUMS_ENTRY(SVGENUM_FONT_STYLE, SVGFONTSTYLE_ITALIC, "italic", 6)
SVG_ENUMS_ENTRY(SVGENUM_FONT_STYLE, SVGFONTSTYLE_OBLIQUE, "oblique", 7)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_ANCHOR, SVGTEXTANCHOR_START, "start", 5)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_ANCHOR, SVGTEXTANCHOR_MIDDLE, "middle", 6)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_ANCHOR, SVGTEXTANCHOR_END, "end", 3)
SVG_ENUMS_ENTRY(SVGENUM_FONT_VARIANT, SVGFONTVARIANT_NORMAL, "normal", 6)
SVG_ENUMS_ENTRY(SVGENUM_FONT_VARIANT, SVGFONTVARIANT_SMALLCAPS, "small-caps", 10)
SVG_ENUMS_ENTRY(SVGENUM_RESTART, SVGRESTART_ALWAYS, "always", 6)
SVG_ENUMS_ENTRY(SVGENUM_RESTART, SVGRESTART_WHENNOTACTIVE, "whenNotActive", 13)
SVG_ENUMS_ENTRY(SVGENUM_RESTART, SVGRESTART_NEVER, "never", 5)
SVG_ENUMS_ENTRY(SVGENUM_RESTART, SVGRESTART_UNKNOWN, "unknown", 7)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVG, "http://www.w3.org/TR/SVG11/feature#SVG", 38)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVGDOM, "http://www.w3.org/TR/SVG11/feature#SVGDOM", 41)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVGSTATIC, "http://www.w3.org/TR/SVG11/feature#SVG-static", 45)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVGDOMSTATIC, "http://www.w3.org/TR/SVG11/feature#SVGDOM-static", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVGANIMATION, "http://www.w3.org/TR/SVG11/feature#SVG-animation", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVGDOMANIMATION, "http://www.w3.org/TR/SVG11/feature#SVGDOM-animation", 51)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVGDYNAMIC, "http://www.w3.org/TR/SVG11/feature#SVG-dynamic", 46)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SVGDOMDYNAMIC, "http://www.w3.org/TR/SVG11/feature#SVGDOM-dynamic", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_COREATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#CoreAttribute", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_STRUCTURE, "http://www.w3.org/TR/SVG11/feature#Structure", 44)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_CONTAINERATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#ContainerAttribute", 53)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_CONDITIONALPROCESSING, "http://www.w3.org/TR/SVG11/feature#ConditionalProcessing", 56)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_IMAGE, "http://www.w3.org/TR/SVG11/feature#Image", 40)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_STYLE, "http://www.w3.org/TR/SVG11/feature#Style", 40)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_VIEWPORTATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#ViewportAttribute", 52)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SHAPE, "http://www.w3.org/TR/SVG11/feature#Shape", 40)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_TEXT, "http://www.w3.org/TR/SVG11/feature#Text", 39)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_PAINTATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#PaintAttribute", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_OPACITYATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#OpacityAttribute", 51)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_GRAPHICSATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#GraphicsAttribute", 52)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_MARKER, "http://www.w3.org/TR/SVG11/feature#Marker", 41)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_COLORPROFILE, "http://www.w3.org/TR/SVG11/feature#ColorProfile", 47)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_GRADIENT, "http://www.w3.org/TR/SVG11/feature#Gradient", 43)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_PATTERN, "http://www.w3.org/TR/SVG11/feature#Pattern", 42)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_CLIP, "http://www.w3.org/TR/SVG11/feature#Clip", 39)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_MASK, "http://www.w3.org/TR/SVG11/feature#Mask", 39)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_FILTER, "http://www.w3.org/TR/SVG11/feature#Filter", 41)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_DOCUMENTEVENTSATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#DocumentEventsAttribute", 58)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_GRAPHICALEVENTSATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#GraphicalEventsAttribute", 59)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_ANIMATIONEVENTSATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#AnimationEventsAttribute", 59)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_CURSOR, "http://www.w3.org/TR/SVG11/feature#Cursor", 41)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_HYPERLINKING, "http://www.w3.org/TR/SVG11/feature#Hyperlinking", 47)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_XLINKATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#XlinkAttribute", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_EXTERNALRESOURCESREQUIRED, "http://www.w3.org/TR/SVG11/feature#ExternalResourcesRequired", 60)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_VIEW, "http://www.w3.org/TR/SVG11/feature#View", 39)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_SCRIPT, "http://www.w3.org/TR/SVG11/feature#Script", 41)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_ANIMATION, "http://www.w3.org/TR/SVG11/feature#Animation", 44)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_FONT, "http://www.w3.org/TR/SVG11/feature#Font", 39)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_EXTENSIBILITY, "http://www.w3.org/TR/SVG11/feature#Extensibility", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_TINY_BASE, "http://www.w3.org/TR/SVG11/feature#base", 39)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_TINY_INTERACTIVITY, "http://www.w3.org/TR/SVG11/feature#interactivity", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_TINY_ALL, "http://www.w3.org/TR/SVG11/feature#all", 38)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_ALL, "http://www.w3.org/TR/SVGMobile/Basic/feature#all", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_BASE, "http://www.w3.org/TR/SVGMobile/Basic/feature#base", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_CLIP, "http://www.w3.org/TR/SVG11/feature#BasicClip", 44)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_CSS, "http://www.w3.org/TR/SVGMobile/Basic/feature#css", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_DOMCORE, "http://www.w3.org/TR/SVGMobile/Basic/feature#SVGBasicDomCore", 60)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_DOMEXTENDED, "http://www.w3.org/TR/SVGMobile/Basic/feature#SVGBasicDomExtended", 64)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_FILTER, "http://www.w3.org/TR/SVG11/feature#BasicFilter", 46)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_FONT, "http://www.w3.org/TR/SVG11/feature#BasicFont", 44)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_GRAPHICSATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#BasicGraphicsAttribute", 57)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_INTERACTIVITY, "http://www.w3.org/TR/SVGMobile/Basic/feature#interactivity", 58)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_PAINTATTRIBUTE, "http://www.w3.org/TR/SVG11/feature#BasicPaintAttribute", 54)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_STRUCTURE, "http://www.w3.org/TR/SVG11/feature#BasicStructure", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_BASIC_TEXT, "http://www.w3.org/TR/SVG11/feature#BasicText", 44)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0, "org.w3c.svg", 11)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_STATIC, "org.w3c.svg.static", 18)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_DYNAMIC, "org.w3c.svg.dynamic", 19)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_ANIMATION, "org.w3c.svg.animation", 21)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_ALL, "org.w3c.svg.all", 15)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_DOM, "org.w3c.dom.svg", 15)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_DOM_STATIC, "org.w3c.dom.svg.static", 22)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_DOM_DYNAMIC, "org.w3c.dom.svg.dynamic", 23)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_DOM_ANIMATION, "org.w3c.dom.svg.animation", 25)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_0_DOM_ALL, "org.w3c.dom.svg.all", 19)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SVGSTATIC, "http://www.w3.org/Graphics/SVG/feature/1.2/#SVG-static", 54)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SVGSTATICDOM, "http://www.w3.org/Graphics/SVG/feature/1.2/#SVG-static-DOM", 58)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SVGANIMATED, "http://www.w3.org/Graphics/SVG/feature/1.2/#SVG-animated", 56)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SVGINTERACTIVE, "http://www.w3.org/Graphics/SVG/feature/1.2/#SVG-interactive", 59)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SVGALL, "http://www.w3.org/Graphics/SVG/feature/1.2/#SVG-all", 51)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_CORE_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#CoreAttribute", 57)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_NAVIGATION_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#NavigationAttribute", 63)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_STRUCTURE, "http://www.w3.org/Graphics/SVG/feature/1.2/#Structure", 53)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_CONDITIONAL_PROCESSING, "http://www.w3.org/Graphics/SVG/feature/1.2/#ConditionalProcessing", 65)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_CONDITIONAL_PROCESSING_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#ConditionalProcessingAttribute", 74)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_IMAGE, "http://www.w3.org/Graphics/SVG/feature/1.2/#Image", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_PREFETCH, "http://www.w3.org/Graphics/SVG/feature/1.2/#Prefetch", 52)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_DISCARD, "http://www.w3.org/Graphics/SVG/feature/1.2/#Discard", 51)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SHAPE, "http://www.w3.org/Graphics/SVG/feature/1.2/#Shape", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_TEXT, "http://www.w3.org/Graphics/SVG/feature/1.2/#Text", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_PAINT_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#PaintAttribute", 58)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_OPACITY_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#OpacityAttribute", 60)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_GRAPHICS_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#GraphicsAttribute", 61)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_GRADIENT, "http://www.w3.org/Graphics/SVG/feature/1.2/#Gradient", 52)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SOLID_COLOR, "http://www.w3.org/Graphics/SVG/feature/1.2/#SolidColor", 54)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_HYPERLINKING, "http://www.w3.org/Graphics/SVG/feature/1.2/#Hyperlinking", 56)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_XLINK_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#XlinkAttribute", 58)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_EXTERNALRESOURCESREQUIRED, "http://www.w3.org/Graphics/SVG/feature/1.2/#ExternalResourcesRequired", 69)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_SCRIPTING, "http://www.w3.org/Graphics/SVG/feature/1.2/#Scripting", 53)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_HANDLER, "http://www.w3.org/Graphics/SVG/feature/1.2/#Handler", 51)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_LISTENER, "http://www.w3.org/Graphics/SVG/feature/1.2/#Listener", 52)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_TIMEDANIMATION, "http://www.w3.org/Graphics/SVG/feature/1.2/#TimedAnimation", 58)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_ANIMATION, "http://www.w3.org/Graphics/SVG/feature/1.2/#Animation", 53)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_AUDIO, "http://www.w3.org/Graphics/SVG/feature/1.2/#Audio", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_VIDEO, "http://www.w3.org/Graphics/SVG/feature/1.2/#Video", 49)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_FONT, "http://www.w3.org/Graphics/SVG/feature/1.2/#Font", 48)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_EXTENSIBILITY, "http://www.w3.org/Graphics/SVG/feature/1.2/#Extensibility", 57)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_MEDIA_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#MediaAttribute", 58)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_TEXTFLOW, "http://www.w3.org/Graphics/SVG/feature/1.2/#TextFlow", 52)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_TRANSFORMEDVIDEO, "http://www.w3.org/Graphics/SVG/feature/1.2/#TransformedVideo", 60)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_COMPOSEDVIDEO, "http://www.w3.org/Graphics/SVG/feature/1.2/#ComposedVideo", 57)
SVG_ENUMS_ENTRY(SVGENUM_REQUIREDFEATURES, SVGFEATURE_1_2_EDITABLE_ATTRIBUTE, "http://www.w3.org/Graphics/SVG/feature/1.2/#EditableTextAttribute", 65)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_VISIBLEPAINTED, "visiblePainted", 14)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_VISIBLEFILL, "visibleFill", 11)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_VISIBLESTROKE, "visibleStroke", 13)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_VISIBLE, "visible", 7)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_PAINTED, "painted", 7)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_FILL, "fill", 4)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_STROKE, "stroke", 6)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_ALL, "all", 3)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_POINTER_EVENTS, SVGPOINTEREVENTS_BOUNDINGBOX, "boundingBox", 11)
SVG_ENUMS_ENTRY(SVGENUM_METHOD, SVGMETHOD_ALIGN, "align", 5)
SVG_ENUMS_ENTRY(SVGENUM_METHOD, SVGMETHOD_STRETCH, "stretch", 7)
#ifdef SVG_SUPPORT_FILTERS
SVG_ENUMS_ENTRY(SVGENUM_STITCHTILES, SVGSTITCH_STITCH, "stitch", 6)
SVG_ENUMS_ENTRY(SVGENUM_STITCHTILES, SVGSTITCH_NOSTITCH, "noStitch", 8)
SVG_ENUMS_ENTRY(SVGENUM_DISPLACEMENTSELECTOR, SVGDISPLACEMENT_R, "R", 1)
SVG_ENUMS_ENTRY(SVGENUM_DISPLACEMENTSELECTOR, SVGDISPLACEMENT_G, "G", 1)
SVG_ENUMS_ENTRY(SVGENUM_DISPLACEMENTSELECTOR, SVGDISPLACEMENT_B, "B", 1)
SVG_ENUMS_ENTRY(SVGENUM_DISPLACEMENTSELECTOR, SVGDISPLACEMENT_A, "A", 1)
SVG_ENUMS_ENTRY(SVGENUM_CONVOLVEEDGEMODE, SVGCONVOLVEEDGEMODE_DUPLICATE, "duplicate", 9)
SVG_ENUMS_ENTRY(SVGENUM_CONVOLVEEDGEMODE, SVGCONVOLVEEDGEMODE_WRAP, "wrap", 4)
SVG_ENUMS_ENTRY(SVGENUM_CONVOLVEEDGEMODE, SVGCONVOLVEEDGEMODE_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_COMPOSITEOPERATOR, SVGCOMPOSITEOPERATOR_OVER, "over", 4)
SVG_ENUMS_ENTRY(SVGENUM_COMPOSITEOPERATOR, SVGCOMPOSITEOPERATOR_IN, "in", 2)
SVG_ENUMS_ENTRY(SVGENUM_COMPOSITEOPERATOR, SVGCOMPOSITEOPERATOR_OUT, "out", 3)
SVG_ENUMS_ENTRY(SVGENUM_COMPOSITEOPERATOR, SVGCOMPOSITEOPERATOR_ATOP, "atop", 4)
SVG_ENUMS_ENTRY(SVGENUM_COMPOSITEOPERATOR, SVGCOMPOSITEOPERATOR_XOR, "xor", 3)
SVG_ENUMS_ENTRY(SVGENUM_COMPOSITEOPERATOR, SVGCOMPOSITEOPERATOR_ARITHMETIC, "arithmetic", 10)
SVG_ENUMS_ENTRY(SVGENUM_MORPHOLOGYOPERATOR, SVGMORPHOPERATOR_ERODE, "erode", 5)
SVG_ENUMS_ENTRY(SVGENUM_MORPHOLOGYOPERATOR, SVGMORPHOPERATOR_DILATE, "dilate", 6)
SVG_ENUMS_ENTRY(SVGENUM_BLENDMODE, SVGBLENDMODE_NORMAL, "normal", 6)
SVG_ENUMS_ENTRY(SVGENUM_BLENDMODE, SVGBLENDMODE_MULTIPLY, "multiply", 8)
SVG_ENUMS_ENTRY(SVGENUM_BLENDMODE, SVGBLENDMODE_SCREEN, "screen", 6)
SVG_ENUMS_ENTRY(SVGENUM_BLENDMODE, SVGBLENDMODE_DARKEN, "darken", 6)
SVG_ENUMS_ENTRY(SVGENUM_BLENDMODE, SVGBLENDMODE_LIGHTEN, "lighten", 7)
SVG_ENUMS_ENTRY(SVGENUM_TURBULENCETYPE, SVGTURBULENCE_FRACTALNOISE, "fractalNoise", 12)
SVG_ENUMS_ENTRY(SVGENUM_TURBULENCETYPE, SVGTURBULENCE_TURBULENCE, "turbulence", 10)
SVG_ENUMS_ENTRY(SVGENUM_COLORMATRIXTYPE, SVGCOLORMATRIX_MATRIX, "matrix", 6)
SVG_ENUMS_ENTRY(SVGENUM_COLORMATRIXTYPE, SVGCOLORMATRIX_SATURATE, "saturate", 8)
SVG_ENUMS_ENTRY(SVGENUM_COLORMATRIXTYPE, SVGCOLORMATRIX_HUEROTATE, "hueRotate", 9)
SVG_ENUMS_ENTRY(SVGENUM_COLORMATRIXTYPE, SVGCOLORMATRIX_LUMINANCETOALPHA, "luminanceToAlpha", 16)
SVG_ENUMS_ENTRY(SVGENUM_FUNCTYPE, SVGFUNC_IDENTITY, "identity", 8)
SVG_ENUMS_ENTRY(SVGENUM_FUNCTYPE, SVGFUNC_TABLE, "table", 5)
SVG_ENUMS_ENTRY(SVGENUM_FUNCTYPE, SVGFUNC_DISCRETE, "discrete", 8)
SVG_ENUMS_ENTRY(SVGENUM_FUNCTYPE, SVGFUNC_LINEAR, "linear", 6)
SVG_ENUMS_ENTRY(SVGENUM_FUNCTYPE, SVGFUNC_GAMMA, "gamma", 5)
#endif // SVG_SUPPORT_FILTERS
SVG_ENUMS_ENTRY(SVGENUM_BOOLEAN, FALSE, "false", 5)
SVG_ENUMS_ENTRY(SVGENUM_BOOLEAN, TRUE, "true", 4)
SVG_ENUMS_ENTRY(SVGENUM_LENGTHADJUST, SVGLENADJUST_SPACING, "spacing", 7)
SVG_ENUMS_ENTRY(SVGENUM_LENGTHADJUST, SVGLENADJUST_SPACINGANDGLYPHS, "spacingAndGlyphs", 16)
SVG_ENUMS_ENTRY(SVGENUM_TEXTDECORATION, SVGTEXTDECORATION_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_TEXTDECORATION, SVGTEXTDECORATION_UNDERLINE, "underline", 9)
SVG_ENUMS_ENTRY(SVGENUM_TEXTDECORATION, SVGTEXTDECORATION_OVERLINE, "overline", 8)
SVG_ENUMS_ENTRY(SVGENUM_TEXTDECORATION, SVGTEXTDECORATION_LINETHROUGH, "line-through", 12)
SVG_ENUMS_ENTRY(SVGENUM_TEXTDECORATION, SVGTEXTDECORATION_BLINK, "blink", 5)
SVG_ENUMS_ENTRY(SVGENUM_SPACING, SVGSPACING_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_SPACING, SVGSPACING_EXACT, "exact", 5)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_URI, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_CROSSHAIR, "crosshair", 9)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_DEFAULT_ARROW, "default", 7)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_CUR_POINTER, "pointer", 7)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_MOVE, "move", 4)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_E_RESIZE, "e-resize", 8)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_NE_RESIZE, "ne-resize", 9)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_NW_RESIZE, "nw-resize", 9)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_N_RESIZE, "n-resize", 8)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_SE_RESIZE, "se-resize", 9)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_SW_RESIZE, "sw-resize", 9)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_S_RESIZE, "s-resize", 8)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_W_RESIZE, "w-resize", 8)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_TEXT, "text", 4)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_WAIT, "wait", 4)
SVG_ENUMS_ENTRY(SVGENUM_CURSOR, CURSOR_HELP, "help", 4)
SVG_ENUMS_ENTRY(SVGENUM_OVERFLOW, CSS_VALUE_visible, "visible", 7)
SVG_ENUMS_ENTRY(SVGENUM_OVERFLOW, CSS_VALUE_hidden, "hidden", 6)
SVG_ENUMS_ENTRY(SVGENUM_OVERFLOW, CSS_VALUE_scroll, "scroll", 6)
SVG_ENUMS_ENTRY(SVGENUM_OVERFLOW, CSS_VALUE_auto, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_UNICODE_BIDI, CSS_VALUE_normal, "normal", 6)
SVG_ENUMS_ENTRY(SVGENUM_UNICODE_BIDI, CSS_VALUE_embed, "embed", 5)
SVG_ENUMS_ENTRY(SVGENUM_UNICODE_BIDI, CSS_VALUE_bidi_override, "bidi-override", 13)
SVG_ENUMS_ENTRY(SVGENUM_WRITING_MODE, SVGWRITINGMODE_LR_TB, "lr-tb", 5)
SVG_ENUMS_ENTRY(SVGENUM_WRITING_MODE, SVGWRITINGMODE_RL_TB, "rl-tb", 5)
SVG_ENUMS_ENTRY(SVGENUM_WRITING_MODE, SVGWRITINGMODE_TB_RL, "tb-rl", 5)
SVG_ENUMS_ENTRY(SVGENUM_WRITING_MODE, SVGWRITINGMODE_LR, "lr", 2)
SVG_ENUMS_ENTRY(SVGENUM_WRITING_MODE, SVGWRITINGMODE_RL, "rl", 2)
SVG_ENUMS_ENTRY(SVGENUM_WRITING_MODE, SVGWRITINGMODE_TB, "tb", 2)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_BASELINE, "baseline", 8)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_BEFORE_EDGE, "before-edge", 11)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_TEXT_BEFORE_EDGE, "text-before-edge", 16)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_MIDDLE, "middle", 6)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_CENTRAL, "central", 7)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_AFTER_EDGE, "after-edge", 10)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_TEXT_AFTER_EDGE, "text-after-edge", 15)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_IDEOGRAPHIC, "ideographic", 11)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_ALPHABETIC, "alphabetic", 10)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_HANGING, "hanging", 7)
SVG_ENUMS_ENTRY(SVGENUM_ALIGNMENT_BASELINE, SVGALIGNMENTBASELINE_MATHEMATICAL, "mathematical", 12)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_USE_SCRIPT, "use-script", 10)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_NO_CHANGE, "no-change", 9)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_RESET_SIZE, "reset-size", 10)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_IDEOGRAPHIC, "ideographic", 11)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_ALPHABETIC, "alphabetic", 10)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_HANGING, "hanging", 7)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_MATHEMATICAL, "mathematical", 12)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_CENTRAL, "central", 7)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_MIDDLE, "middle", 6)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_TEXT_AFTER_EDGE, "text-after-edge", 15)
SVG_ENUMS_ENTRY(SVGENUM_DOMINANT_BASELINE, SVGDOMINANTBASELINE_TEXT_BEFORE_EDGE, "text-before-edge", 16)
SVG_ENUMS_ENTRY(SVGENUM_ARABIC_FORM, SVGARABICFORM_INITIAL, "initial", 7)
SVG_ENUMS_ENTRY(SVGENUM_ARABIC_FORM, SVGARABICFORM_MEDIAL, "medial", 6)
SVG_ENUMS_ENTRY(SVGENUM_ARABIC_FORM, SVGARABICFORM_TERMINAL, "terminal", 8)
SVG_ENUMS_ENTRY(SVGENUM_ARABIC_FORM, SVGARABICFORM_ISOLATED, "isolated", 8)
SVG_ENUMS_ENTRY(SVGENUM_DIRECTION, CSS_VALUE_ltr, "ltr", 3)
SVG_ENUMS_ENTRY(SVGENUM_DIRECTION, CSS_VALUE_rtl, "rtl", 3)
SVG_ENUMS_ENTRY(SVGENUM_IMAGE_RENDERING, SVGIMAGERENDERING_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_IMAGE_RENDERING, SVGIMAGERENDERING_OPTIMIZESPEED, "optimizeSpeed", 13)
SVG_ENUMS_ENTRY(SVGENUM_IMAGE_RENDERING, SVGIMAGERENDERING_OPTIMIZEQUALITY, "optimizeQuality", 15)
SVG_ENUMS_ENTRY(SVGENUM_MARKER_UNITS, SVGMARKERUNITS_STROKEWIDTH, "strokeWidth", 11)
SVG_ENUMS_ENTRY(SVGENUM_MARKER_UNITS, SVGMARKERUNITS_USERSPACEONUSE, "userSpaceOnUse", 14)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_RENDERING, SVGTEXTRENDERING_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_RENDERING, SVGTEXTRENDERING_OPTIMIZESPEED, "optimizeSpeed", 13)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_RENDERING, SVGTEXTRENDERING_OPTIMIZELEGIBILITY, "optimizeLegibility", 18)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_RENDERING, SVGTEXTRENDERING_GEOMETRICPRECISION, "geometricPrecision", 18)
SVG_ENUMS_ENTRY(SVGENUM_COLOR_INTERPOLATION, SVGCOLORINTERPOLATION_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_COLOR_INTERPOLATION, SVGCOLORINTERPOLATION_SRGB, "sRGB", 4)
SVG_ENUMS_ENTRY(SVGENUM_COLOR_INTERPOLATION, SVGCOLORINTERPOLATION_LINEARRGB, "linearRGB", 9)
SVG_ENUMS_ENTRY(SVGENUM_FOCUSABLE, SVGFOCUSABLE_TRUE, "true", 4)
SVG_ENUMS_ENTRY(SVGENUM_FOCUSABLE, SVGFOCUSABLE_FALSE, "false", 5)
SVG_ENUMS_ENTRY(SVGENUM_FOCUSABLE, SVGFOCUSABLE_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_VECTOR_EFFECT, SVGVECTOREFFECT_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_VECTOR_EFFECT, SVGVECTOREFFECT_NON_SCALING_STROKE, "non-scaling-stroke", 18)
SVG_ENUMS_ENTRY(SVGENUM_FOCUSHIGHLIGHT, SVGFOCUSHIGHLIGHT_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_FOCUSHIGHLIGHT, SVGFOCUSHIGHLIGHT_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_INITIALVISIBILITY, SVGINITIALVISIBILITY_WHENSTARTED, "whenStarted", 11)
SVG_ENUMS_ENTRY(SVGENUM_INITIALVISIBILITY, SVGINITIALVISIBILITY_ALWAYS, "always", 6)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORMBEHAVIOR, SVGTRANSFORMBEHAVIOR_GEOMETRIC, "geometric", 9)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORMBEHAVIOR, SVGTRANSFORMBEHAVIOR_PINNED, "pinned", 6)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORMBEHAVIOR, SVGTRANSFORMBEHAVIOR_PINNED90, "pinned90", 8)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORMBEHAVIOR, SVGTRANSFORMBEHAVIOR_PINNED180, "pinned180", 9)
SVG_ENUMS_ENTRY(SVGENUM_TRANSFORMBEHAVIOR, SVGTRANSFORMBEHAVIOR_PINNED270, "pinned270", 9)
SVG_ENUMS_ENTRY(SVGENUM_OVERLAY, SVGOVERLAY_TOP, "top", 3)
SVG_ENUMS_ENTRY(SVGENUM_OVERLAY, SVGOVERLAY_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY_ALIGN, SVGDISPLAYALIGN_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY_ALIGN, SVGDISPLAYALIGN_BEFORE, "before", 6)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY_ALIGN, SVGDISPLAYALIGN_CENTER, "center", 6)
SVG_ENUMS_ENTRY(SVGENUM_DISPLAY_ALIGN, SVGDISPLAYALIGN_AFTER, "after", 5)
SVG_ENUMS_ENTRY(SVGENUM_EDITABLE, SVGEDITABLE_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_EDITABLE, SVGEDITABLE_SIMPLE, "simple", 6)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_ALIGN, CSS_VALUE_start, "start", 5)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_ALIGN, CSS_VALUE_center, "center", 6)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_ALIGN, CSS_VALUE_end, "end", 3)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_OVERFLOW, CSS_VALUE_clip, "clip", 4)
SVG_ENUMS_ENTRY(SVGENUM_TEXT_OVERFLOW, CSS_VALUE_ellipsis, "ellipsis", 8)
SVG_ENUMS_ENTRY(SVGENUM_AUTO, SVGAUTO_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_SYNCBEHAVIOR, SVGSYNCBEHAVIOR_CANSLIP, "canSlip", 7)
SVG_ENUMS_ENTRY(SVGENUM_SYNCBEHAVIOR, SVGSYNCBEHAVIOR_LOCKED, "locked", 6)
SVG_ENUMS_ENTRY(SVGENUM_SYNCBEHAVIOR, SVGSYNCBEHAVIOR_INDEPENDENT, "independent", 11)
SVG_ENUMS_ENTRY(SVGENUM_SYNCBEHAVIOR, SVGSYNCBEHAVIOR_DEFAULT, "default", 7)
SVG_ENUMS_ENTRY(SVGENUM_SYNCBEHAVIOR, SVGSYNCBEHAVIOR_INHERIT, "inherit", 7)
SVG_ENUMS_ENTRY(SVGENUM_NONE, SVGSNAPSHOTTIME_NONE, "none", 4)
SVG_ENUMS_ENTRY(SVGENUM_SHAPE_RENDERING, SVGSHAPERENDERING_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_SHAPE_RENDERING, SVGSHAPERENDERING_OPTIMIZESPEED, "optimizeSpeed", 13)
SVG_ENUMS_ENTRY(SVGENUM_SHAPE_RENDERING, SVGSHAPERENDERING_CRISPEDGES, "crispEdges", 10)
SVG_ENUMS_ENTRY(SVGENUM_SHAPE_RENDERING, SVGSHAPERENDERING_GEOMETRICPRECISION, "geometricPrecision", 18)
SVG_ENUMS_ENTRY(SVGENUM_BUFFERED_RENDERING, SVGBUFFEREDRENDERING_AUTO, "auto", 4)
SVG_ENUMS_ENTRY(SVGENUM_BUFFERED_RENDERING, SVGBUFFEREDRENDERING_STATIC, "static", 6)
SVG_ENUMS_ENTRY(SVGENUM_BUFFERED_RENDERING, SVGBUFFEREDRENDERING_DYNAMIC, "dynamic", 7)
SVG_ENUMS_ENTRY(SVGENUM_TIMELINEBEGIN, SVGTIMELINEBEGIN_ONLOAD, "onLoad", 6)
SVG_ENUMS_ENTRY(SVGENUM_TIMELINEBEGIN, SVGTIMELINEBEGIN_ONSTART, "onStart", 7)
SVG_ENUMS_END
#endif // SVG_SUPPORT
|
#include <iostream>
#include <cmath>
using namespace std;
int main() {
float G = 6.67e-11;
float M = 9.982e12;
float R = 2650;
float Vesc = sqrt((2.0*G*M)/(R));
//cout << "Escape Velocity is: " << Vesc << endl;
float jumpV = 0.;
cout << "What was the Jump Velocity?: ";
cin >> jumpV;
if(jumpV < Vesc) {
//You didn't escape.
cout << "You weren't able to escape the asteroid's gravity" << endl;
}
else {
//calculate mass for the case where you wouldn't escape
float m = (pow(jumpV, 2) * R)/(2*G);
cout << "You escaped! But if the mass of the satellite had been " << m << "kg you wouldn't have." << endl;
}
return 0;
}
|
#pragma once
namespace Hourglass
{
class WaypointAgent;
class Separation;
}
class Chase : public Hourglass::IAction
{
public:
void LoadFromXML(tinyxml2::XMLElement* data);
bool IsRunningChild() const { return false; }
void Init(Hourglass::Entity* entity);
IBehavior::Result Update(Hourglass::Entity* entity);
IBehavior* MakeCopy() const;
private:
StrID m_Run;
float m_AnimSpeed;
uint32_t m_Pursuit : 1;
StrID m_TargetTag;
hg::Entity* m_Target;
hg::Motor* m_Motor;
hg::Separation* m_Separation;
float m_Speed;
float m_StopDistance;
hg::WaypointAgent* m_WaypointAgent;
float m_Timer;
float m_RepathFreq;
};
|
// poj 1330
#include <iostream>
#include <fstream>
#include <sstream>
#include <utility>
#include <vector>
#include <list>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>
#include <functional>
#include <numeric>
#include <bitset>
#include <complex>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <climits>
using namespace std;
#define ft(i,a,b) for (int i=(a);i<=(b);++i)
#define fdt(i,a,b) for (int i=(a);i>=b;--i)
#define feach(arr,i) for(vector<pii>::itr i=(arr.begin());i!=(arr.end());++i)
#define fsubset(subset,set) for (int subset=set&(set-1);subset;subset=(subset-1)&set)
#define fl(x,y) memset((x),char(y),sizeof(x))
#define clr(x) fl(x,char(0))
#define pb push_back
#define mp make_pair
#define x first
#define y second
#define sz(x) (int((x).size()))
#define all(x) (x).begin(),(x).end()
#define srt(x) sort(all(x))
#define uniq(x) srt(x),(x).erase(unique(all(x)),x.end());
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define pr pair
#define que queue
#define prq priority_queue
#define itr iterator
#define sf scanf
#define pf printf
#define pdb(prcs,x) printf("%."#prcs"f",(abs(x)<1e-##prcs)?0.0:x)
#define input(in) freopen(in,"r",stdin)
#define output(out) freopen(out,"w",stdout)
#define lowbit(i) (i&(-i))
typedef long long int LL;
typedef pr<int,int> pii;
typedef pr<LL,LL> pll;
typedef pr<double,double> pdd;
typedef pr<string,int> psi;
typedef map<int,int> mii;
typedef map<string,int> msi;
typedef map<char,int> mci;
typedef que<int> qi;
typedef prq<int> pqi;
typedef vector<int> veci;
typedef vector<bool> vecb;
typedef vector<string> vecs;
typedef vector<double> vecdb;
const int oo=(~0u)>>1;
const LL lloo=(~0ull)>>1;
const int INF = 0x7f7f7f7f;
const double dboo=1e+20;
const double eps=1e-8;
const double pi=acos(-1.0);
const int MOD=1000000007;
const int MAXN =11111;
int t;
int N;
vector<int> maps[MAXN];
const int SecMax=20;
struct Lcatype
{
int Dep[MAXN*3];
int Fir[MAXN*3];
int DFS[MAXN*3];
bool vis[MAXN];
int Dp;
int f[MAXN*3][21];//mul 3 for dfs sequence has 3*cnt of maxns
int Sec[SecMax];
void dfs(int num,int dep){
vis[num]=1;
Dep[++Dp]=dep;
DFS[Dp]=num;
Fir[num]=Dp;
for(vector<int>::itr i = maps[num].begin();i!=maps[num].end();++i)
{
int &to = *i;
if(!vis[to])
{
dfs(to,dep+1);
Dep[++Dp]=dep;
DFS[Dp]=num;
}
}
}
int Closed(int now){
for(int i=0;i<=SecMax;i++)
{
if(Sec[i+1]>=now)
return i;
}
}
void init(int treehead){
clr(vis);
Dp = 0;
dfs(treehead,0);//dfs
for(int i=1;i<=Dp;i++)
f[i][0]=i;
Sec[0]=1;
for(int i=1;i<SecMax;i++)
Sec[i]=(1<<i);
int K=Closed(Dp);
for(int i=1;i<=K;i++)
for(int j=1;j<=Dp-Sec[i]+1;j++)
{
if(Dep[f[j][i-1]]<Dep[f[j+Sec[i-1]][i-1]])
f[j][i]=f[j][i-1];
else
f[j][i]=f[j+Sec[i-1]][i-1];
}
}
int lca(int a,int b){
if(Fir[a]>Fir[b])
swap(a,b);
int i=Closed(Fir[b]-Fir[a]+1);
if(Dep[f[Fir[a]][i]]<Dep[f[Fir[b]-Sec[i]+1][i]])
return DFS[f[Fir[a]][i]];
else
return DFS[f[Fir[b]-Sec[i]+1][i]];
}
};
Lcatype lca;
int a,b;
bool showed[MAXN];
int main(int argc, char *argv[])
{
sf("%d",&t);
while(t--)
{
sf("%d",&N);
ft(i,1,N-1)
sf("%d%d",&a,&b),maps[a].pb(b),maps[b].pb(a),showed[b] = 1;
ft(i,1,N)
if(!showed[i])
lca.init(i);
sf("%d%d",&a,&b);
cout << lca.lca(a,b) << "\n";
clr(showed);
ft(i,1,N)
maps[i].clear();
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2012 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_UTIL_TESTS_OPFILEMOCK_H
#define MODULES_UTIL_TESTS_OPFILEMOCK_H
#ifdef SELFTEST
#include "modules/util/opfile/opfile.h"
#include "modules/hardcore/base/opstatus.h"
#include "modules/opdata/OpData.h"
/** A mock implementation of OpFile for testing classes that
* use this interface.
*
* May be incomplete, feel free to implement more faked/mocked methods.
**/
class OpFileMock : public OpFile
{
public:
OpFileMock() :
openCalls(0), openLastMode(0), openReturn(OpStatus::OK),
isOpenReturn(TRUE),
closeCalls(0), closeReturn(OpStatus::OK),
writeCalls(0), writeLastData(), writeLastLen(0), writeReturn(OpStatus::OK),
isWritableReturn(TRUE)
{}
virtual OP_STATUS Open(int mode)
{
openCalls++;
openLastMode = mode;
return openReturn;
}
virtual BOOL IsOpen() const
{
return isOpenReturn;
}
virtual OP_STATUS Close()
{
closeCalls++;
isOpenReturn = FALSE;
return closeReturn;
}
virtual OP_STATUS Write(const void* data, OpFileLength len)
{
writeCalls++;
RETURN_IF_ERROR(writeLastData.SetCopyData((char*) data, static_cast<size_t>(len)));
writeLastLen = len;
return writeReturn;
}
virtual BOOL IsWritable() const
{
return isWritableReturn;
}
void reset()
{
openCalls = 0;
openLastMode = 0;
openReturn = OpStatus::OK;
isOpenReturn = TRUE;
closeCalls = 0;
closeReturn = OpStatus::OK;
writeCalls = 0;
writeLastData.Clear();
writeLastLen = 0;
writeReturn = OpStatus::OK;
isWritableReturn = TRUE;
}
int openCalls;
int openLastMode;
OP_STATUS openReturn;
BOOL isOpenReturn;
int closeCalls;
OP_STATUS closeReturn;
int writeCalls;
OpData writeLastData;
OpFileLength writeLastLen;
OP_STATUS writeReturn;
BOOL isWritableReturn;
};
#endif // SELFTEST
#endif // MODULES_UTIL_TESTS_OPFILEMOCK_H
|
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int stops = 0;
int in = 0,out = 0,max = 0,total = 0;
cin >> stops;
while(stops--){
//cin >> in >> out;
cin >> out >> in;
total += in-out;
if(total > max){
max = total;
}
}
cout << max<<"\n";
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#if defined(SELFTEST)
#include "modules/network_selftest/matchurl.h"
#include "modules/locale/oplanguagemanager.h"
void MatchWithURL_Tester::MatchURLLoader::OnAllDocumentsFinished()
{
parent->MatchURLs_Loaded();
}
OP_STATUS MatchWithURL_Tester::Construct(URL &a_url, URL &ref, URL &match_base, URL &mtch_url, BOOL unique)
{
if(a_url.IsEmpty() || match_url.IsEmpty() || a_url == match_url)
return OpStatus::ERR;
URL_DocSelfTest_Item::Construct(a_url, ref, unique);
match_url = mtch_url;
if(match_url.IsEmpty())
return OpStatus::ERR;
match_url_use = match_url;
return url.IsValid() ? OpStatus::OK : OpStatus::ERR;
}
OP_STATUS MatchWithURL_Tester::Construct(const OpStringC8 &source_url, URL &ref, URL &match_base, const OpStringC8 &mtch_url, BOOL unique)
{
if(source_url.IsEmpty())
return OpStatus::ERR;
URL a_url;
URL empty;
a_url = g_url_api->GetURL(empty,source_url,unique);
if(a_url.IsEmpty())
return OpStatus::ERR;
URL_DocSelfTest_Item::Construct(a_url, ref, unique);
match_url = g_url_api->GetURL(match_base, mtch_url, unique);
if(match_url.IsEmpty() || a_url == match_url)
return OpStatus::ERR;
match_url_use = match_url;
return url.IsValid() ? OpStatus::OK : OpStatus::ERR;
}
OP_STATUS MatchWithURL_Tester::Construct(const OpStringC &source_url, URL &ref, URL &match_base, const OpStringC &mtch_url, BOOL unique)
{
if(source_url.IsEmpty())
return OpStatus::ERR;
URL a_url;
URL empty;
a_url = g_url_api->GetURL(empty,source_url,unique);
if(a_url.IsEmpty())
return OpStatus::ERR;
URL_DocSelfTest_Item::Construct(a_url, ref, unique);
match_url = g_url_api->GetURL(match_base, mtch_url, unique);
if(match_url.IsEmpty() || a_url == match_url)
return OpStatus::ERR;
match_url_use = match_url;
return url.IsValid() ? OpStatus::OK : OpStatus::ERR;
}
BOOL MatchWithURL_Tester::Verify_function(URL_DocSelfTest_Event event, Str::LocaleString status_code)
{
switch(event)
{
case URLDocST_Event_Data_Received:
{
URLStatus status = (URLStatus) url.GetAttribute(URL::KLoadStatus, TRUE);
if(status == URL_LOADED)
{
URL_LoadPolicy policy(FALSE, URL_Load_Normal);
URL empty;
OP_STATUS op_err= loader.LoadDocument(match_url, empty, policy);
if(OpStatus::IsError(op_err))
{
ReportFailure("Loading match item failed.");
return FALSE;
}
return TRUE;
}
else if(status != URL_LOADING)
{
ReportFailure("Some kind of loading failure %d.", status);
return FALSE;
}
}
break;
default:
return URL_DocSelfTest_Item::Verify_function(event, status_code);
}
return TRUE;
}
void MatchWithURL_Tester::MatchURLs_Loaded()
{
Verify_function((CompareURLAndURL(this, url, match_url) ? URLDocST_Event_LoadingFinished : URLDocST_Event_LoadingFailed));
}
#endif // SELFTEST
|
//
// Created by mikcy on 15. 6. 7.
//
#include "KillTimerTask.h"
void Timer::KillTimerTask::task() {
kill(_target, SIGKILL);
}
|
#include "ItemTableModel.hpp"
#include <glog/logging.h>
#include <envire_core/items/ItemMetadata.hpp>
using namespace envire::core;
namespace envire { namespace viz {
ItemTableModel::ItemTableModel(QObject* parent): QAbstractTableModel(parent),
numColumns(4)
{}
void ItemTableModel::addItem(envire::core::ItemBase::Ptr item)
{
{
beginInsertRows(QModelIndex(), items.size(), items.size());
items.push_back(item);
endInsertRows();
}
}
void ItemTableModel::clear()
{
if(items.size() > 0)
{
beginRemoveRows(QModelIndex(), 0, items.size()-1);
items.clear();
endRemoveRows();
}
}
int ItemTableModel::columnCount(const QModelIndex& parent) const
{
return numColumns;
}
int ItemTableModel::rowCount(const QModelIndex& parent) const
{
return items.size();
}
QVariant ItemTableModel::data(const QModelIndex& index, int role) const
{
const int row = index.row();
const int col = index.column();
if(row >= int(items.size()))
{
LOG(ERROR) << "ItemTableModel: row index out of range: " << row;
return QVariant();
}
if(col >= numColumns)
{
LOG(ERROR) << "ItemTableModel: column index out of range: " << col;
return QVariant();
}
if (role == Qt::DisplayRole)
{
const ItemBase::Ptr item = items[row];
switch(col)
{
case 0: //uuid
return QVariant(QString::fromStdString(item->getIDString()));
case 1: //type
return QVariant(QString::fromStdString(item->getClassName()));
case 2: //raw type
{
std::string rawType("Unknown Type");
try
{
//this fails if the type was not properly loaded using the plugin system
rawType = ItemMetadataMapping::getMetadata(*(item->getTypeInfo())).embeddedTypename;
}
catch(const std::out_of_range& ex){}
return QVariant(QString::fromStdString(rawType));
}
case 3: //timestamp
return QVariant(QString::fromStdString(item->getTime().toString()));
default:
LOG(ERROR) << "ItemTableModel: unknown column: " << col;
return QVariant();
}
}
return QVariant();
}
QVariant ItemTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
{
switch (section)
{
case 0:
return tr("UUID");
case 1:
return tr("Class Name");
case 2:
return tr("Raw Type");
case 3:
return tr("Timestamp");
default:
return QVariant();
}
}
return QVariant();
}
envire::core::ItemBase::Ptr ItemTableModel::getItem(const QModelIndex& index) const
{
const int row = index.row();
assert(row < items.size());
return items[row];
}
}}
|
#pragma once
#include "Core/Core.h"
namespace Rocket
{
struct WindowProps
{
String Title;
int32_t Width;
int32_t Height;
WindowProps(const String& title = "Rocket Engine",
uint32_t width = 1280,
uint32_t height = 720)
: Title(title), Width(width), Height(height) {}
};
// Interface representing a desktop system based Window
Interface Window
{
public:
Window(WindowProps prop) : m_Props(prop) {}
virtual ~Window() = default;
virtual void Initialize() = 0;
virtual void Finalize() = 0;
void SetWidth(uint32_t w) { m_Props.Width = w; }
void SetHeight(uint32_t h) { m_Props.Height = h; }
uint32_t GetWidth() const { return m_Props.Width; }
uint32_t GetHeight() const { return m_Props.Height; }
virtual void* GetNativeWindow() const = 0;
static Ref<Window> Create(const WindowProps &props = WindowProps());
protected:
WindowProps m_Props;
};
}
|
#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <list>
#include <sstream>
#include <sys/ioctl.h>
#include <stdio.h>
#include <unistd.h>
#include <algorithm>
#include <vector>
#include <istream>
#include <iterator>
#include "colors.h"
#include <pthread.h>
#include "Adb.h"
#define VERSION "1.3"
using namespace std;
#define MAX_BUFFER_LENGTH 2000
#define MIN_LINE_LEN 10
#define PID_LEN 6
#define TAG_LEN 20
#define MSG_OFFSET 33
#define ARG_TAG "-t"
#define ARG_LOGLEVEL "-i"
#define ARG_EXCLUDE "-e"
#define ARG_FINDWORDS "-f"
#define ARG_DEVICE "-d"
#define ARG_PROCESS "-p"
#define ARG_HELP "--help"
#define ARG_VERSION "--version"
struct Message
{
int level;
int pid;
string tag;
string message;
};
struct CmdOptions
{
int loglevel;
string deviceId;
string deviceName;
string tags;
int pid;
list<string> findwords;
list<string> ignoreWords;
};
map<string, string> argMap;
map<std::string, int> mpTagList;
CmdOptions cmd;
int color = 1;
pthread_t pidThread_t;
bool ProcessMessageLine(const char* line, int length, Message* msg);
bool ProcessMessageLineNewAPI(const char* line, int length, Message* msg);
char GetLogLevel(int level);
void PrintOutput(Message* msg, int maxMsgLen);
void ProcessCmdOptions();
bool DoHighlight(const char* msg);
void SetLogColor(int level);
int GetTagColor(string tag);
void PrintVersion();
void PrintHelp();
bool IgnoreTag(const char* tag);
void setDevice();
int getSdkVersion();
int getPid(string strName);
void* PidMonitorThread(void* param);
vector<string> &split(const string &s, char delim, vector<string> &elems);
std::vector<std::string> split(std::string const &input);
string getDeviceProperty(string deviceId, string property);
int main(int argc, char* argv[])
{
if (argc == 2 && (strcmp(argv[1], ARG_VERSION) == 0))
{
PrintVersion();
return 0;
}
if (argc == 2 && (strcmp(argv[1], ARG_HELP) == 0))
{
PrintHelp();
return 0;
}
if (argc > 1)
{
//Process command line options
string argType = "";
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
argType = string(argv[i], 2);
if (!(argType == ARG_DEVICE || argType == ARG_TAG || argType == ARG_FINDWORDS ||
argType == ARG_LOGLEVEL || argType == ARG_EXCLUDE || argType == ARG_PROCESS))
{
//invalid argument
PrintHelp();
return 0;
}
}
else
{
//cout << argType << endl;
if (argMap.find(argType) == argMap.end())
{
//not found. new arg
argMap.insert(make_pair(argType, string(argv[i])));
}
else
{
//found. append to string
string str = " " + string(argv[i]);
argMap.at(argType).append(str);
}
//specialization for findwords
if (argType == ARG_FINDWORDS)
cmd.findwords.push_back(string(argv[i]));
//specialization for ignore words
if (argType == ARG_EXCLUDE)
cmd.ignoreWords.push_back(string(argv[i]));
}
}
ProcessCmdOptions();
}
if(cmd.deviceId.length() == 0)
setDevice();
int sdk = getSdkVersion();
//printf("sdk version: %i\n", sdk);
printf("selected device: %s, SDK: %i\n", cmd.deviceId.c_str(), sdk);
char szLine[MAX_BUFFER_LENGTH] = "";
Message msg;
struct winsize termSize;
ioctl(STDOUT_FILENO, TIOCGWINSZ, &termSize);
int maxMsgLen = termSize.ws_col - (PID_LEN + TAG_LEN + 8);
if (maxMsgLen < 50)
{
cout << "terminal width not enough..." << endl;
return 0;
}
string command = ADB" logcat";
if (cmd.deviceId.length() > 0)
command = ADB" -s " + cmd.deviceId + " logcat";
if (cmd.tags.length() > 0)
command += " -s " + cmd.tags;
cout << "command: " << command << endl;
//command = "./test.logcat"; //debug only
FILE* fp = popen(command.c_str(), "r");
if (NULL != fp)
{
while (fgets(szLine, MAX_BUFFER_LENGTH, fp))
{
bool print = false;
if(sdk > 22)
print = ProcessMessageLineNewAPI(szLine, sizeof(szLine), &msg);
else
print = ProcessMessageLine(szLine, sizeof(szLine), &msg);
if(print)
PrintOutput(&msg, maxMsgLen);
}
fclose(fp);
}
else
printf("Command Error!\n");
return 0;
}
bool ProcessMessageLine(const char* line, int length, Message* msg)
{
if (strnlen(line, length) < MIN_LINE_LEN)
{
msg->level = -1;
return false;
}
//process Log Level
if (line[0] == 'V') msg->level = 0;
else if (line[0] == 'I') msg->level = 1;
else if (line[0] == 'D') msg->level = 2;
else if (line[0] == 'W') msg->level = 3;
else if (line[0] == 'E') msg->level = 4;
else msg->level = -1;
//do not use strtok on the original string. it changes it.
const char* firstBracket = strchr(line, '(');
const char* secondBracket = strchr(line, ')');
const char* tagStart = line + 2;
//Process TAG
if (firstBracket != NULL && secondBracket != NULL && tagStart != NULL)
{
msg->tag = string(tagStart, (firstBracket - tagStart));
if(msg->tag.length() > (TAG_LEN - 1))
msg->tag.erase(TAG_LEN, std::string::npos); //delimit to 20 chars
}
else
msg->tag = "**unknown";
//Process PID
if (firstBracket != NULL && secondBracket != NULL)
{
msg->pid = atoi(string(firstBracket + 1, ((secondBracket - 1) - firstBracket)).c_str());
}
else
msg->pid = -1;
//ignore based on pid
if((cmd.pid != 0 && cmd.pid != msg->pid) || cmd.pid == -1)
return false;
//Process Message
if (secondBracket != NULL)
{
msg->message = string(secondBracket + 3);
}
return true;
}
char GetLogLevel(int level)
{
switch (level)
{
case 0: return 'V';
case 1: return 'I';
case 2: return 'D';
case 3: return 'W';
case 4: return 'E';
default: return 'X';
}
}
int GetLogLevelInt(char level)
{
switch (level)
{
case 'v':
case 'V': return 0;
case 'i':
case 'I': return 1;
case 'd':
case 'D': return 2;
case 'w':
case 'W': return 3;
case 'e':
case 'E': return 4;
default: return -1;
}
}
void PrintOutput(Message* msg, int maxMsgLen)
{
if (msg->level >= cmd.loglevel && !IgnoreTag(msg->tag.c_str()))
{
printf(ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET);
//Print PID
printf(ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET);
printf("%*i ", PID_LEN, msg->pid); //white background, black text
printf(ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET);
//Print TAG
printf(ANSI_TEXT_COLOR_RESET);
colors::SetBackColor(GetTagColor(msg->tag));
printf("%*s ", TAG_LEN, msg->tag.c_str());
printf(ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET " ");
//Print Log Level
SetLogColor(msg->level);
printf(" %c ", GetLogLevel(msg->level));
printf(ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET" ");
msg->message.erase(msg->message.length() - 1);
int msgLen = msg->message.length();
bool bHighlight = false;
if (!cmd.findwords.empty())
bHighlight = DoHighlight(msg->message.c_str());
else
bHighlight = false;
if (msgLen > maxMsgLen)
{
//Need to break message to multiple lines
int num = msgLen / maxMsgLen;
if (num*maxMsgLen < msgLen) num = num + 1;
for (int i = 0; i < num; i++)
{
if (i == 0)
{
if (bHighlight)
printf(ANSI_BACK_COLOR_WHITE ANSI_TEXT_COLOR_BLACK"%s" ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET"\n", msg->message.substr(0, maxMsgLen).c_str());
else
printf("%s\n", msg->message.substr(0, maxMsgLen).c_str());
}
else
{
if (bHighlight)
printf("%*s"ANSI_BACK_COLOR_WHITE ANSI_TEXT_COLOR_BLACK"%s"ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET"\n", MSG_OFFSET, "", msg->message.substr(i*maxMsgLen, maxMsgLen).c_str());
else
printf("%*s%s\n", MSG_OFFSET, "", msg->message.substr(i*maxMsgLen, maxMsgLen).c_str());
}
}
}
else
{
if (bHighlight)
printf(ANSI_BACK_COLOR_WHITE ANSI_TEXT_COLOR_BLACK"%s"ANSI_BACK_COLOR_RESET ANSI_TEXT_COLOR_RESET"\n", msg->message.c_str());
else
printf("%s\n", msg->message.c_str());
}
}
}
void ProcessCmdOptions()
{
if(argMap.find(ARG_DEVICE) != argMap.end()) cmd.deviceId = argMap.at(ARG_DEVICE);
if (argMap.find(ARG_LOGLEVEL) != argMap.end())cmd.loglevel = GetLogLevelInt(argMap.at(ARG_LOGLEVEL).c_str()[0]);
if (argMap.find(ARG_TAG) != argMap.end())cmd.tags = argMap.at(ARG_TAG);
if(argMap.find(ARG_PROCESS) != argMap.end())
{
if(cmd.deviceId.length() == 0)
setDevice();
cmd.pid = getPid(argMap.at(ARG_PROCESS));
pthread_create(&pidThread_t, NULL, PidMonitorThread, NULL);
}
}
void* PidMonitorThread(void* param)
{
while(1)
{
//cout<<"in thread. checking pid"<<endl;
if(argMap.find(ARG_PROCESS) != argMap.end())
{
int pid = getPid(argMap.at(ARG_PROCESS));
if(pid != cmd.pid && pid != 0)
{
//cout << "setting new pid: "<<pid <<endl;
cmd.pid = pid;
}
}
sleep(1);
}
return NULL;
}
bool DoHighlight(const char* msg)
{
for (std::list<string>::iterator itr = cmd.findwords.begin(); itr != cmd.findwords.end(); itr++)
{
if (NULL != (strstr(msg, (*itr).c_str())))
return true;
}
return false;
}
bool IgnoreTag(const char* tag)
{
bool bRet = false;
bool bUseWildcard = false;
//cout << "usewl: " << bUseWildcard << endl;
if (tag != NULL)
{
for (std::list<string>::iterator itr = cmd.ignoreWords.begin(); itr != cmd.ignoreWords.end(); itr++)
{
if (itr->find('*') == itr->size()-1) bUseWildcard = true;
if (bUseWildcard)
{
if (NULL != (strstr(tag, itr->substr(0, itr->size() - 1).c_str())))
bRet = true;
}
else
{
if (strncmp(tag, itr->c_str(), TAG_LEN) == 0)
{
bRet = true;
}
}
}
}
return bRet;
}
void SetLogColor(int level)
{
printf(ANSI_TEXT_COLOR_BLACK);
switch (level)
{
case 0: printf(ANSI_BACK_COLOR_WHITE);
break;
case 1: printf(ANSI_BACK_COLOR_GREEN);
break;
case 2: printf(ANSI_BACK_COLOR_BLUE);
break;
case 3: printf(ANSI_BACK_COLOR_YELLOW);
break;
case 4: printf(ANSI_BACK_COLOR_RED);
break;
}
}
int GetTagColor(string tag)
{
if (mpTagList.find(tag) == mpTagList.end())
{
mpTagList.insert(std::make_pair(tag, color++));
if (color == 8)
{
color = 1;
return 7;
}
else return color;
}
else
{
//have tag. return its color
return mpTagList[tag];
}
}
void PrintVersion()
{
cout << "ADB logcat version "VERSION"\n" << endl;
}
void PrintHelp()
{
cout << "ADB logcat v"VERSION << endl;
cout << "Usage:" << endl;
cout << ARG_TAG" : select tags" << endl;
cout << ARG_DEVICE" : select device" << endl;
cout << ARG_FINDWORDS" : highlight given words" << endl;
cout << ARG_LOGLEVEL" : set minimum log level (D - debug, E - error, I - info, V - verbose, W - warning)" << endl;
cout << ARG_EXCLUDE" : exclude tags by wildcard" << endl;
cout << ARG_PROCESS" : filter by process name" << endl;
cout << ARG_VERSION" : show program version" << endl;
cout << ARG_HELP" : show this help section" << endl;
cout << "Example usage: logcat -d DEVICE_NAME -t TAG1 TAG2 TAG3 -l D -f word1 word2 \"word3 word4\"" << endl;
cout << "\t\tlogcat -e TAG1 TAG*" << endl;
cout << "\t\tlogcat -p com.android.phone" << endl;
}
void setDevice()
{
char szLine[MAX_BUFFER_LENGTH] = "";
vector<string> vDevices;
vector<string> vDeviceNames;
vDevices.clear();
FILE* fp = popen(ADB" devices", "r");
int iCount = 0;
if (NULL != fp)
{
while (fgets(szLine, MAX_BUFFER_LENGTH, fp))
{
if(iCount > 0)
{
char* c = strchr(szLine, '\t');
int len = c - szLine;
if(len > 0 && len < 100)
{
string device = string(szLine, len);
vDevices.push_back(device);
string brand = getDeviceProperty(device, "ro.product.brand");
string name = getDeviceProperty(device, "ro.product.model");
string release = getDeviceProperty(device, "ro.build.version.release");
string sdkInt = getDeviceProperty(device, "ro.build.version.sdk");
//printf("%s %s (Android %s, API %s)\n", brand.c_str(), name.c_str(), release.c_str(), sdkInt.c_str());
vDeviceNames.push_back(brand + " " + name + " (Android " + release + ", API " + sdkInt + ")");
}
}
iCount++;
memset(szLine, 0, MAX_BUFFER_LENGTH);
}
fclose(fp);
}
else
{
printf("Command Error! Could not get available devices\n");
exit(0);
}
unsigned int selected = 0;
bool validSelection = false;
while(!validSelection)
{
if(vDevices.size() > 1)
{
printf("Please select device:\n");
for(unsigned int i=0; i<vDevices.size(); i++)
{
printf("\t%i: %s\n", i+1, /*vDevices[i].c_str(),*/ vDeviceNames[i].c_str());
}
scanf("%i", &selected);
selected--;
validSelection = true;
if(selected < 0 || selected > vDevices.size())
{
printf("invalid device selection\n");
validSelection = false;
}
}
else
{
validSelection = true;
selected = 0;
}
}
cmd.deviceId = vDevices[selected];
}
int getSdkVersion()
{
string command = ADB" -s " + cmd.deviceId + " shell getprop ro.build.version.sdk";
//printf("command: %s\n", command.c_str());
FILE* fp = popen(command.c_str(), "r");
char number[10] = "";
int sdk = 0;
if(fp != NULL)
{
fgets(number, sizeof(number), fp);
sdk = atoi(number);
}
fclose(fp);
return sdk;
}
string getDeviceProperty(string deviceId, string property)
{
string command = ADB" -s " + deviceId + " shell getprop " + property;
FILE* fp = popen(command.c_str(), "r");
char val[100] = "";
if(fp != NULL)
{
fgets(val, sizeof(val), fp);
}
if(val[0] > 96)
val[0] = val[0] - 32;
string str(val);
str.erase(std::remove(str.begin(), str.end(), '\n'), str.end());
str.erase(std::remove(str.begin(), str.end(), '\r'), str.end());
fclose(fp);
return str;
}
std::vector<std::string> split(std::string const &input)
{
std::istringstream buffer(input);
std::vector<std::string> ret;
std::copy(std::istream_iterator<std::string>(buffer),
std::istream_iterator<std::string>(),
std::back_inserter(ret));
return ret;
}
int getPid(string strName)
{
string command = ADB" -s " + cmd.deviceId + " shell ps";
FILE* fp = popen(command.c_str(), "r");
char pname[1024] = "";
int pid = -1;
if(fp != NULL)
{
while(fgets(pname, sizeof(pname), fp))
{
vector<string> line = split(string(pname));
if(line.size() > 1)
{
string pname = line.back();
if(pname.size() > strName.size() && pname.find(strName, 0) != string::npos)
{
pid = atoi(line[1].c_str());
//cout<<"partial match on pname: "<<pname<<endl;
}
if(pname == strName)
{
pid = atoi(line[1].c_str());
//cout<<"found PID for : "<<pname<<endl;
break;
}
}
}
}
fclose(fp);
return pid;
}
vector<string> &split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
bool ProcessMessageLineNewAPI(const char *line, int length, Message *msg)
{
if (strnlen(line, length) < MIN_LINE_LEN)
{
msg->level = -1;
return false;
}
//NOTE: do not use strtok on the original string. it changes it.
vector<string> tokens;
vector<string>& results = split(string(line), ' ', tokens);
int iCount = 0;
for(unsigned int i=0; i<results.size(); i++)
{
//printf("results[%i]: %s\n", i, results[i].c_str());
if(results[i].length() > 0)
{
switch(iCount)
{
case 2:
msg->pid = atoi(results[i].c_str());
break;
case 4:
//process Log Level
if (results[i] == "V") msg->level = 0;
else if (results[i] == "I") msg->level = 1;
else if (results[i] == "D") msg->level = 2;
else if (results[i] == "W") msg->level = 3;
else if (results[i] == "E") msg->level = 4;
else msg->level = -1;
break;
case 5:
msg->tag = results[i];
if(msg->tag.length() > (TAG_LEN - 1))
msg->tag.erase(TAG_LEN, std::string::npos); //delimit to 20 chars
break;
}
iCount++;
}
}
//PID based filtering
if((cmd.pid != 0 && cmd.pid != msg->pid) || cmd.pid == -1)
return false;
const char* message = strchr(line+20, ':');
if(message == NULL)
msg->message = "null";
else msg->message = string(message+2);
if(msg->tag.size() > 1 && msg->tag.at(msg->tag.size()-1) == ':')
{
msg->tag = msg->tag.substr(0, msg->tag.size()-1);
}
return true;
}
|
//
// File: Seg7LED.h
// Author: Andy Shepherd
// email: seg7led@bytecode.co.uk
// License: Public Domain
//
#ifndef SEG7LED_H
#define SEG7LED_H
#include <arduino.h>
#include "CLedBuf.h"
#define CHAR_0 ((byte) 0b1111110)
#define CHAR_1 ((byte) 0b0110000)
#define CHAR_2 ((byte) 0b1101101)
#define CHAR_3 ((byte) 0b1111001)
#define CHAR_4 ((byte) 0b0110011)
#define CHAR_5 ((byte) 0b1011011)
#define CHAR_6 ((byte) 0b1011111)
#define CHAR_7 ((byte) 0b1110000)
#define CHAR_8 ((byte) 0b1111111)
#define CHAR_9 ((byte) 0b1111011)
#define CHAR_A ((byte) 0b1110111)
#define CHAR_b ((byte) 0b0011111)
#define CHAR_C ((byte) 0b1001110)
#define CHAR_d ((byte) 0b0111101)
#define CHAR_E ((byte) 0b1001111)
#define CHAR_F ((byte) 0b1000111)
#define CHAR_c ((byte) 0b0001101)
#define CHAR_e ((byte) 0b1101111)
#define CHAR_g ((byte) 0b1111011)
#define CHAR_h ((byte) 0b0010111)
#define CHAR_I ((byte) 0b0110000)
#define CHAR_i ((byte) 0b0010000)
#define CHAR_J ((byte) 0b0111000)
#define CHAR_L ((byte) 0b0001110)
#define CHAR_n ((byte) 0b0010101)
#define CHAR_o ((byte) 0b0011101)
#define CHAR_O ((byte) 0b1111110)
#define CHAR_P ((byte) 0b1100111)
#define CHAR_q ((byte) 0b1110011)
#define CHAR_r ((byte) 0b0000101)
#define CHAR_S ((byte) 0b1011011)
#define CHAR_t ((byte) 0b0001111)
#define CHAR_U ((byte) 0b0111110)
#define CHAR_u ((byte) 0b0011100)
#define CHAR_X ((byte) 0b0110111)
#define CHAR_Y ((byte) 0b0111011)
#define CHAR_Z ((byte) 0b1101101)
#define CHAR_MINUS ((byte) 0b0000001)
#define CHAR_OPEN_BRACKET ((byte) 0b1001110)
#define CHAR_CLOSE_BRACKET ((byte) 0b1111000)
#define CHAR_DP ((byte) 0b10000000)
#define CHAR_BLANK ((byte) 0b00000000)
#define CHAR_UNDERSCORE ((byte) 0b0001000)
#define CHAR_EQUALS ((byte) 0b0001001)
#define CHAR_ALL ((byte) 0b11111111)
#define SEG_A ((byte) 0b1000000)
#define SEG_B ((byte) 0b0100000)
#define SEG_C ((byte) 0b0010000)
#define SEG_D ((byte) 0b0001000)
#define SEG_E ((byte) 0b0000100)
#define SEG_F ((byte) 0b0000010)
#define SEG_G ((byte) 0b0000001)
class Seg7LED
{
public:
Seg7LED( int aPinLatch, int aPinRTS, int aPinData, int aPinCTS );
bool printFloat( double f );
bool printInt( int aVal );
bool print4LEDChars( char * aStr );
bool printNumericString( char * aStr );
void floatToLEDBuf(double number, uint8_t decimal_places, CLEDBuf & LEDBuf );
/*
bool setting( char setting );
bool DPSetPos( int aPos );
bool DPClearPos( int aPos );
bool DPClearAll();
*/
private:
bool print8BitChar( char aCh );
int m_pinLatch;
int m_pinRTS;
int m_pinData;
int m_pinCTS;
int m_DPPos;
};
#endif // SEG7LED_H
|
#include "tipoqueue.h"
#include <cstddef>
TipoQueue::TipoQueue()
{
//ctor
this->start = NULL;
this->end = NULL;
}
TipoQueue::~TipoQueue()
{
//dtor
this->free();
}
Tipo* TipoQueue::retrieve()
{
if (!start)
return NULL;
Tipo* value = start->getTipo();
TipoNode* aux = start;
start = start->getNext();
delete aux;
if (!start)
end = NULL;
return value;
}
void TipoQueue::add(Tipo* tipo)
{
TipoNode* newTipoNode = new TipoNode(tipo);
if (!start)
{
start = end = newTipoNode;
return;
}
end->setNext(newTipoNode);
end = newTipoNode;
}
TipoNode* TipoQueue::getStart()
{
return start;
}
void TipoQueue::setStart(TipoNode* start)
{
this->start = start;
}
TipoNode* TipoQueue::getEnd()
{
return end;
}
void TipoQueue::setEnd(TipoNode* end)
{
this->end = end;
}
void TipoQueue::free()
{
while (TipoNode* aux = start)
{
start = start->getNext();
delete aux;
}
}
void TipoQueue::show()
{
TipoNode* aux = start;
while (aux)
{
aux->show();
cout << endl;
aux = aux->getNext();
}
cout << endl << endl;
}
|
#include "WordsParser.h"
namespace WordCounter {
WordsParser::WordsParser() {
Words = new map<string, pair<int64_t, float>>();
}
WordsParser::~WordsParser() {
delete Words;
}
void WordsParser::AddWord(string word) {
WordsAmount++;
map<string, pair<int64_t, float>>::iterator it = Words->find(word);
if (it != Words->end()) {
it->second.first++;
} else {
Words->insert(it, TableRow(word, pair<int64_t, float>(1, 0)));
}
}
void WordsParser::AddLine(string line) {
string word = "";
for (auto x : line) {
if (!((x <= 'Z' && x >= 'A') || (x <= 'z' && x >= 'a') || (x <= '9' && x >= '0'))) {
AddWord(word);
word = "";
} else {
word += x;
}
}
if(word != "") AddWord(word);
}
std::vector<TableRow> WordsParser::MapToSortedVector() {
UpdateFreq();
Comparator compFunctor = [](TableRow const & elem1, TableRow const & elem2) {
if (elem2.second.second == elem1.second.second) return elem2.first[0] > elem1.first[0];
return elem2.second.second < elem1.second.second;
};
vector <TableRow> WordsVector(Words->begin(), Words->end());
return WordsVector;
}
void WordsParser::VectorToCSV(vector<TableRow> set, string file) {
ofstream output(file);
if (!output) {
cerr << "Can't open file " << file << endl;
return;
}
for (auto element : set) {
output << element.first << ", " << element.second.first << ", " << element.second.second << "\n";
}
output.close();
}
void WordsParser::UpdateFreq() {
for (auto it = Words->begin(); it != Words->end(); ++it) {
it->second.second = (float)it->second.first / (float)WordsAmount;
}
}
}
|
#include<iostream>
using namespace std;
int main()
{
int arr[100],n,i,j;
int flag=0; int sum;
cout<<"Enter length of array\n";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"Enter elements\n";
cin>>arr[i];
cout<<endl;
}
for(i=0;i<n;i++)
{
sum=0;
for(j=i;j<n;j++)
{
sum+=arr[j];
if(sum==0)
{
flag++;
}
}
}
cout<<"Sub arrays having sum=0: "<<flag;
return 0;
}
|
/*
DIGITAL SENSOR CHECK FOR 3 DIGITAL SENSORS
Connect the + on the sensor board to +5V on the Arduino
Connect the - on the sensor board to GND on the Arduino
Connect the R on the board to Digital Pin 2 on the Arduino
Connect the P on the board to Digital Pin 3 on the Arduino
Connect the X on the board to Digital Pin 4 on the Arduino
*/
/*
Define the Pins on which the sensors are attached
Reed Sensor R is attached to Digital Pin 2 on Arduino
Power Sensor P is attached to Digital Pin 3 on Arduino
PIR Sensor X is attached to Digital Pin 4 on Arduino
*/
int reedPin= 2;
int powerPin= 3;
int pirPin= 4;
/* Global Varibales to store the reed status value */
boolean reedStatus;
/* Global Varibales to store the power status value */
boolean powerStatus;
/* Global Varibales to store the pir status value */
boolean pirStatus;
/*
This function is called only once in lifetime
Will be called again when the RED RESET button is pressed on the Arduino
*/
void setup()
{
// Setup the connection speed to Serial Monitor and Arduino Board
// 9600 bits of data per second
Serial.begin(9600);
// Pin 2 defined for taking INPUT
pinMode(reedPin, INPUT);
// Pin 3 defined for taking INPUT
pinMode(powerPin, INPUT);
// Pin 4 defined for taking INPUT
pinMode(pirPin, INPUT);
// Print the output on the Serial Monitor
Serial.println("DIGITAL SENSOR CHECK FOR 3 DIGITAL SENSORS");
}
/*
This function is called in a loop again and again by Arduino infinitely
untill the RED RESET button is not pressed
*/
void loop()
{
// Call the function to get the power status and store in our global variable
reedStatus = getReedStatus(reedPin);
powerStatus = getPowerStatus(powerPin);
pirStatus = getPirStatus(pirPin);
// Print the output on the Serial Monitor
Serial.println("");
Serial.println("******************************");
Serial.print("Gate Status = ");
if(reedStatus == true)
Serial.println("OPEN");
if(reedStatus == false)
Serial.println("CLOSE");
Serial.print("Power Status = ");
if(powerStatus == true)
Serial.println("ON");
if(powerStatus == false)
Serial.println("OFF");
Serial.print("Person Status = ");
if(pirStatus == true)
Serial.println("YES");
if(pirStatus == false)
Serial.println("NO");
Serial.println("******************************");
Serial.println("");
// Delay of 1 sec to take the sensor value again
delay(1000);
}
/*********** Digital Read function*********/
boolean getReedStatus(int reedPin)
{
return (boolean)digitalRead(reedPin);
}
boolean getPowerStatus(int powerPin)
{
return (boolean)digitalRead(powerPin);
}
boolean getPirStatus(int pirPin)
{
return (boolean)digitalRead(pirPin);
}
|
#include "kompute/Tensor.hpp"
#include "kompute/operations/OpTensorSyncLocal.hpp"
namespace kp {
OpTensorSyncLocal::OpTensorSyncLocal()
{
SPDLOG_DEBUG("Kompute OpTensorSyncLocal constructor base");
}
OpTensorSyncLocal::OpTensorSyncLocal(
std::shared_ptr<vk::PhysicalDevice> physicalDevice,
std::shared_ptr<vk::Device> device,
std::shared_ptr<vk::CommandBuffer> commandBuffer,
std::vector<std::shared_ptr<Tensor>> tensors)
: OpBase(physicalDevice, device, commandBuffer, tensors)
{
SPDLOG_DEBUG("Kompute OpTensorSyncLocal constructor with params");
}
OpTensorSyncLocal::~OpTensorSyncLocal()
{
SPDLOG_DEBUG("Kompute OpTensorSyncLocal destructor started");
}
void
OpTensorSyncLocal::init()
{
SPDLOG_DEBUG("Kompute OpTensorSyncLocal init called");
if (this->mTensors.size() < 1) {
throw std::runtime_error(
"Kompute OpTensorSyncLocal called with less than 1 tensor");
}
for (std::shared_ptr<Tensor> tensor : this->mTensors) {
if (!tensor->isInit()) {
throw std::runtime_error(
"Kompute OpTensorSyncLocal: Tensor has not been initialized");
}
if (tensor->tensorType() == Tensor::TensorTypes::eStorage) {
SPDLOG_WARN(
"Kompute OpTensorSyncLocal tensor parameter is of type "
"TensorTypes::eStorage and hence cannot be used to receive or "
"pass data.");
}
}
}
void
OpTensorSyncLocal::record()
{
SPDLOG_DEBUG("Kompute OpTensorSyncLocal record called");
for (size_t i = 0; i < this->mTensors.size(); i++) {
if (this->mTensors[i]->tensorType() == Tensor::TensorTypes::eDevice) {
this->mTensors[i]->recordCopyFromDeviceToStaging(
this->mCommandBuffer, true);
}
}
}
void
OpTensorSyncLocal::preEval()
{
SPDLOG_DEBUG("Kompute OpTensorSyncLocal preEval called");
}
void
OpTensorSyncLocal::postEval()
{
SPDLOG_DEBUG("Kompute OpTensorSyncLocal postEval called");
SPDLOG_DEBUG("Kompute OpTensorSyncLocal mapping data into tensor local");
for (size_t i = 0; i < this->mTensors.size(); i++) {
if (this->mTensors[i]->tensorType() != Tensor::TensorTypes::eStorage) {
this->mTensors[i]->mapDataFromHostMemory();
}
}
}
}
|
#ifndef __MYTEAPOT_H__
#define __MYTEAPOT_H__
class MyTeapot
{
D3DXVECTOR3 m_vPos;
D3DXVECTOR3 m_vRot;
D3DXVECTOR3 m_vScale;
D3DXMATRIX m_mTM;
D3DXMATRIX m_mScale, m_mRot, m_mTrans;
D3DMATERIAL9 m_Mtrl;
LPD3DXMESH m_pTeapot;
LPDIRECT3DTEXTURE9 m_envTexture;
public:
void InitTeapot(void);
void UpdateTeapot(float dTime);
void RenderTeapot(int LState);
void ReleaseTeapot(void);
public:
MyTeapot(void);
virtual ~MyTeapot(void);
};
#endif
|
/*
* This file is part of the GROMACS molecular simulation package.
*
* Copyright (c) 2011,2012,2013,2014,2015, by the GROMACS development team, led by
* Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
* and including many others, as listed in the AUTHORS file in the
* top-level source directory and at http://www.gromacs.org.
*
* GROMACS is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* GROMACS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with GROMACS; if not, see
* http://www.gnu.org/licenses, or write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* If you want to redistribute modifications to GROMACS, please
* consider that scientific software is very special. Version
* control is crucial - bugs must be traceable. We will be happy to
* consider code for inclusion in the official distribution, but
* derived work must not be called official GROMACS. Details are found
* in the README & COPYING files - if they are missing, get the
* official version at http://www.gromacs.org.
*
* To help us fund GROMACS development, we humbly ask that you cite
* the research papers on the package. Check out http://www.gromacs.org.
*/
#include <string>
#include <vector>
#include <iostream>
#include <cmath>
#include <cstring>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <iterator>
#include <algorithm>
#include <gromacs/trajectoryanalysis.h>
using namespace gmx;
/*! \brief
* Template class to serve as a basis for user analysis tools.
*/
class AnalysisTemplate : public TrajectoryAnalysisModule
{
public:
AnalysisTemplate();
virtual void initOptions(IOptionsContainer *options,
TrajectoryAnalysisSettings *settings);
virtual void initAnalysis(const TrajectoryAnalysisSettings &settings,
const TopologyInformation &top);
virtual void analyzeFrame(int frnr, const t_trxframe &fr, t_pbc *pbc,
TrajectoryAnalysisModuleData *pdata);
virtual void finishAnalysis(int nframes);
virtual void writeOutput();
// Adding new variables
std::vector<double> frame_number;
std::vector<double> frame_time;
std::vector<double> msdt;
std::vector<std::vector<double>> coord_sol_x;
std::vector<std::vector<double>> coord_sol_y;
std::vector<std::vector<double>> coord_sol_z;
std::vector<double> atom_count;
double zmax_i=10, zmin_i=-10;
double zmax,zmin,comz;
double boxx,boxy,boxz;
double dis[4],pos_x,pos_y,pos_z;
double** msd_pos;
double** init_pos;
double* msd_time;
int* msd_index;
int atom_num;
double d_time = 0;
int d_frame = 0;
int timeflag=1;
double fr_time_start;
int n_start=10;
std::vector<double> dym_ele{std::vector<double>(8,0)};
std::vector<std::vector<std::vector<std::vector<double> > > > record_dym;
std::vector<std::vector<double> > record_dym_i;
std::vector<std::vector<std::vector<double> > > runoutofnames;
std::vector<std::vector<double> > dym_i; //write outp ut
std::vector<double> dym_i1{std::vector<double>(8,0)} ; //write outp ut
std::vector<int> count;
int nf=0;
int ille_a=0;
private:
class ModuleData;
std::string fnMSD_="msd_code";
double cutoff_;
Selection basesel_;
Selection sel_;
AnalysisNeighborhood nb_;
AnalysisData data_;
AnalysisDataAverageModulePointer avem_;
// Adding the pointer about data points
AnalysisDataPlotSettings plotSettings_;
};
AnalysisTemplate::AnalysisTemplate()
: cutoff_(0.0)
{
registerAnalysisDataset(&data_, "avedist");
}
void
AnalysisTemplate::initOptions(IOptionsContainer *options,
TrajectoryAnalysisSettings *settings)
{
static const char *const desc[] = {
"This is a template for writing your own analysis tools for",
"GROMACS. The advantage of using GROMACS for this is that you",
"have access to all information in the topology, and your",
"program will be able to handle all types of coordinates and",
"trajectory files supported by GROMACS. In addition,",
"you get a lot of functionality for free from the trajectory",
"analysis library, including support for flexible dynamic",
"selections. Go ahead an try it![PAR]",
"To get started with implementing your own analysis program,",
"follow the instructions in the README file provided.",
"This template implements a simple analysis programs that calculates",
"average distances from a reference group to one or more",
"analysis groups."
};
settings->setHelpText(desc);
options->addOption(FileNameOption("o")
.filetype(eftPlot).outputFile()
.store(&fnMSD_).defaultBasename("avedist")
.description("Average distances from reference group"));
options->addOption(SelectionOption("Base")
.store(&basesel_).required()
.description("Base group to calculate distances from"));
options->addOption(SelectionOption("select")
.store(&sel_).required()
.description("Groups to calculate MSD(OW) for"));
options->addOption(DoubleOption("cutoff").store(&cutoff_)
.description("Cutoff for distance calculation (0 = no cutoff)"));
options->addOption(DoubleOption("maxz").store(&zmax_i)
.description("Max z for plane with respect to the base"));
options->addOption(DoubleOption("minz").store(&zmin_i)
.description("Min z for plane with respect to the base"));
settings->setFlag(TrajectoryAnalysisSettings::efRequireTop);
}
void
AnalysisTemplate::initAnalysis(const TrajectoryAnalysisSettings &settings,
const TopologyInformation & /*top*/)
{
nb_.setCutoff(cutoff_);
data_.setColumnCount(0, 1);
avem_.reset(new AnalysisDataAverageModule());
data_.addModule(avem_);
std::cout << "You have picked:"<<basesel_.name()<<"as your base"<<std::endl;
std::cout<< "You have picked:"<<sel_.name()<<"as your group for MSD calculation"<<std::endl;
if (!fnMSD_.empty())
{
AnalysisDataPlotModulePointer plotm(
new AnalysisDataPlotModule(settings.plotSettings()));
plotm->setFileName(fnMSD_);
plotm->setTitle("MSD vs Time");
plotm->setXAxisIsTime();
plotm->setYLabel("MSD");
data_.addModule(plotm);
}
atom_num=sel_.atomCount();
msd_index=new int [atom_num]();
for (int i=0; i<atom_num;i++)
{
msd_index[i]=0;
record_dym.push_back(runoutofnames);
}
std::cout << "Total number of atoms processed is:" << atom_num <<std::endl;
}
void
AnalysisTemplate::analyzeFrame(int frnr, const t_trxframe &fr, t_pbc *pbc,
TrajectoryAnalysisModuleData *pdata)
{
AnalysisDataHandle dh = pdata->dataHandle(data_);
const Selection &sel = pdata->parallelSelection(sel_);
const Selection &basesel = pdata->parallelSelection(basesel_);
AnalysisNeighborhoodSearch nbsearch = nb_.initSearch(pbc, sel);
//dh.startFrame(frnr, fr.time);
int nr_base=basesel.posCount();
int nr_sel=sel.posCount();
std::vector<double> coord_frame_x;
std::vector<double> coord_frame_y;
std::vector<double> coord_frame_z;
int atom_count_frame=0;
if(timeflag==1)
{
timeflag=0;
fr_time_start=fr.time;
}
dym_i1[0]=fr.time-fr_time_start;
dym_i.push_back(dym_i1);
boxx=fr.box[0][0];
boxy=fr.box[1][1];
boxz=fr.box[2][2];
comz = 0;
for (int i = 0; i < nr_base; ++i)
{
SelectionPosition p = basesel.position(i);
pos_z=p.x()[2];
//std::cout<<"Atom:"<<i<<" Position:"<<pos_z<<std::endl;
if(pos_z<0 || pos_z>=boxz)
{
pos_z=pos_z-boxz*floor(pos_z/boxz);
}
comz+=pos_z;
}
//std::cout<<" Before:"<<comz<<std::endl;
comz /=nr_base;
//std::cout<<" After:"<<comz<<std::endl;
zmax=comz+zmax_i;
zmin=comz+zmin_i;
//std::cout<<"Zmin:"<<zmin<<" Zmax:"<<zmax<<std::endl;
double pos_x_sel,pos_y_sel,pos_z_sel;
for(int i=0;i<nr_sel;i++)
{
SelectionPosition p = sel.position(i);
pos_x_sel=p.x()[0];
pos_y_sel=p.x()[1];
pos_z_sel=p.x()[2];
dym_ele[0]=frnr;
dym_ele[1]=fr.time;
dym_ele[2]=p.x()[0];
dym_ele[3]=p.x()[1];
dym_ele[4]=p.x()[2];
if(pos_z_sel<0 || pos_z_sel>=boxz)
{
pos_z_sel=pos_z_sel-boxz*floor(pos_z_sel/boxz);
}
if (pos_z_sel<=zmax && pos_z_sel>=zmin)
{
coord_frame_x.push_back(dym_ele[2]);
coord_frame_y.push_back(dym_ele[3]);
coord_frame_z.push_back(dym_ele[4]);
atom_count_frame++;
}
else
{
coord_frame_x.push_back(-1000.0);
coord_frame_y.push_back(-1000.0);
coord_frame_z.push_back(-1000.0);
}
}
coord_sol_x.push_back(coord_frame_x);
coord_sol_y.push_back(coord_frame_y);
coord_sol_z.push_back(coord_frame_z);
frame_time.push_back(fr.time);
atom_count.push_back(atom_count_frame);
std::cout<<"No. of atoms in domain in frame at:"<< fr.time<< " are:"<<atom_count_frame<<" out of "<<coord_frame_z.size()<<std::endl;
}
void
AnalysisTemplate::finishAnalysis(int nframes)
{
std::vector<double> msd_x(nframes,0.0);
std::vector<double> msd_y(nframes,0.0);
std::vector<double> msd_z(nframes,0.0);
std::vector<double> norm(nframes,0.0);
std::vector<double> atom_count(nframes,0.0);
for(int i=0;i<nframes;i++)
{
//if (i%int(nframes/10)==0)
//{
std::cerr<<i<<" out of"<<nframes<<" frames processed"<< std::endl;
//}
for (int j=1;j<(nframes-i);j++)
{
for (int k=0;k<atom_num;k++)
{
if (coord_sol_z[i+j][k]!= -1000.0 && coord_sol_z[i][k]!=-1000.0 && coord_sol_z[i+j-1][k] != -1000.0)
{
atom_count[i]++;
msd_x[j] += (coord_sol_x[j+i][k]-coord_sol_x[i][k])*(coord_sol_x[j+i][k]-coord_sol_x[i][k]);
msd_y[j] += (coord_sol_y[j+i][k]-coord_sol_y[i][k])*(coord_sol_y[j+i][k]-coord_sol_y[i][k]);
msd_z[j] += (coord_sol_z[j+i][k]-coord_sol_z[i][k])*(coord_sol_z[j+i][k]-coord_sol_z[i][k]);
norm[j]++;
}
}
}
//std::cout<<"Atom count: "<<atom_count[i]<<std::endl;
}
norm[0]=1;
for(int k = 0; k < nframes; ++k)
{
std::cout << "Norm:" << norm[k] <<std::endl;
msd_x[k] /= norm[k];
msd_y[k] /= norm[k];
msd_z[k] /= norm[k];
msdt.push_back(msd_x[k] + msd_y[k] + msd_z[k]);
}
}
void
AnalysisTemplate::writeOutput()
{
// We print out the average of the mean distances for each group.
std::string filename2;
filename2 =fnMSD_.c_str();
FILE * myfile2;
myfile2 = fopen(filename2.c_str(), "a");
fprintf (myfile2,"%s\n", "@ time difference MSD_x MSD_y MSD_xyz" );
for (int i=0; i<msdt.size(); i++)
{
fprintf (myfile2, "%12.3f%14.5f\n",frame_time[i],msdt[i]);
}
fclose(myfile2);
}
/*! \brief
* The main function for the analysis template.
*/
int
main(int argc, char *argv[])
{
return gmx::TrajectoryAnalysisCommandLineRunner::runAsMain<AnalysisTemplate>(argc, argv);
}
|
//
// Created by Nikita Kruk on 25.11.17.
//
#ifndef SPRAPPROXIMATEBAYESIANCOMPUTATION_DEFINITIONS_HPP
#define SPRAPPROXIMATEBAYESIANCOMPUTATION_DEFINITIONS_HPP
//#define MPI_PARALLELIZATION
//#define BCS_CLUSTER
typedef double Real;
const int kS = 4; // number of state variables <-> (x,y,v_x,v_y)
const int kSe = 8; // number of extended state variables <-> (x,y,v_x,v_y,area,slope,width,height)
const Real kMicroMetersPerPixel = 0.0639;
const Real kSecondsPerImage = 1e-3;
const Real kMetersPerMicroMeter = 1e-6;
#endif //SPRAPPROXIMATEBAYESIANCOMPUTATION_DEFINITIONS_HPP
|
// https://oj.leetcode.com/problems/integer-to-roman/
// Reference:
// http://fisherlei.blogspot.com/2012/12/leetcode-integer-to-roman.html
class Solution {
public:
string intToRoman(int num) {
char symbol[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
string ret;
int base = 1000;
for (int i = 6; i >= 0; i = i - 2) {
int digit = num / base;
if (digit != 0) {
if (digit <= 3) {
ret.append(digit, symbol[i]);
} else if (digit == 4) {
ret.append(1, symbol[i]);
ret.append(1, symbol[i+1]);
} else if (digit == 5) {
ret.append(1, symbol[i+1]);
} else if (digit <= 8) {
ret.append(1, symbol[i+1]);
ret.append(digit - 5, symbol[i]);
} else if (digit == 9) {
ret.append(1, symbol[i]);
ret.append(1, symbol[i+2]);
}
}
num = num % base;
base = base / 10;
}
return ret;
}
};
|
//
// Created by laureano on 08/11/19.
//
#ifndef AEDA_PROJETO_TIME_H
#define AEDA_PROJETO_TIME_H
#include <sstream>
#include <string>
#include <vector>
#include "utilitarios.h"
using namespace std;
class Time {
int hora;
int minutos;
int segundos;
public:
Time();
Time(int hora, int minutos, int segundos);
int getHora() const;
void setHora(int hora);
int getMinutos() const;
void setMinutos(int minutos);
int getSegundos() const;
void setSegundos(int segundos);
//-------------------------------
bool valid();
void setTime(int hora, int minutos, int segundos);
void setTimeString(string linha);//set Time throw a string
string getTimeString(); //???
//bool verifyTime(string time); verifica a func de cima.
//other methods
//static string returnTime(Time time); //Displays the date in a string
friend ostream &operator<<(ostream &out,const Time &time); //output operator
bool operator==(Time &t); // comparison operators
bool operator!=(const Time &t);
bool operator>(const Time &t);
bool operator<(const Time &t);
string returnTime(Time &time);
//------------------------------//
Time operator-(Time &t);
Time operator+(const Time &t1);
};
#endif //AEDA_PROJETO_TIME_H
|
// Copyright (c) 2015, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
//
// This file is part of Caliper.
// Written by David Boehme, boehme3@llnl.gov.
// LLNL-CODE-678900
// All rights reserved.
//
// For details, see https://github.com/scalability-llnl/Caliper.
// Please also see the LICENSE file for our additional BSD notice.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this list of
// conditions and the disclaimer below.
// * Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the disclaimer (as noted below) in the documentation and/or other materials
// provided with the distribution.
// * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse
// or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/// @file Variant.cpp
/// Variant datatype implementation
#include "Variant.h"
#include "c-util/vlenc.h"
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <iterator>
#include <map>
#include <sstream>
#include <vector>
using namespace cali;
using namespace std;
namespace
{
struct Histogram {
const int nbins;
std::vector<int> bins;
void update(int i) {
int bin = 0;
for (bin = 0; bin < nbins-1 && i > 2*bin; ++bin)
;
++bins[bin];
}
void print() const {
int bound = 0;
for (int val : bins)
std::cerr << 2*bound++ << ": " << val << ", ";
}
};
}
Variant::Variant(cali_attr_type type, const void* data, std::size_t size)
: m_type { type }, m_size { size }
{
switch (m_type) {
case CALI_TYPE_INV:
break;
case CALI_TYPE_USR:
case CALI_TYPE_STRING:
m_value.ptr = data;
break;
case CALI_TYPE_INT:
m_value.v_int = *static_cast<const int64_t*>(data);
break;
case CALI_TYPE_ADDR:
case CALI_TYPE_UINT:
m_value.v_uint = *static_cast<const uint64_t*>(data);
break;
case CALI_TYPE_DOUBLE:
m_value.v_double = *static_cast<const double*>(data);
break;
case CALI_TYPE_BOOL:
m_value.v_bool = *static_cast<const bool*>(data);
break;
case CALI_TYPE_TYPE:
m_value.v_type = *static_cast<const cali_attr_type*>(data);
break;
}
}
const void*
Variant::data() const
{
switch (m_type) {
case CALI_TYPE_USR:
case CALI_TYPE_STRING:
return m_value.ptr;
break;
case CALI_TYPE_INT:
return &m_value.v_int;
break;
case CALI_TYPE_ADDR:
case CALI_TYPE_UINT:
return &m_value.v_uint;
break;
case CALI_TYPE_DOUBLE:
return &m_value.v_double;
break;
case CALI_TYPE_BOOL:
return &m_value.v_bool;
break;
case CALI_TYPE_TYPE:
return &m_value.v_type;
break;
default:
break;
}
return nullptr;
}
cali_id_t
Variant::to_id(bool* okptr) const
{
bool ok = false;
cali_id_t id = to_uint(&ok);
if (okptr)
*okptr = ok;
return ok ? id : CALI_INV_ID;
}
cali_id_t
Variant::to_id(bool* okptr)
{
bool ok = false;
cali_id_t id = to_uint(&ok);
if (okptr)
*okptr = ok;
return ok ? id : CALI_INV_ID;
}
bool
Variant::to_bool(bool* okptr) const
{
bool ok = false;
bool b = m_value.v_bool;
cali_attr_type type = m_type;
if (m_type == CALI_TYPE_INV && !m_string.empty()) {
// try string
{
string lower;
std::transform(m_string.obj().begin(), m_string.obj().end(), back_inserter(lower), ::tolower);
if (lower == "true" || lower == "t") {
ok = true;
b = true;
} else if (lower == "false" || lower == "f") {
ok = true;
b = false;
}
}
// try numeral
if (!ok) {
istringstream is(m_string.obj());
is >> b;
ok = !is.fail();
}
if (ok)
type = CALI_TYPE_BOOL;
}
ok = (type == CALI_TYPE_BOOL || type == CALI_TYPE_INT || type == CALI_TYPE_UINT);
if (okptr)
*okptr = ok;
switch (type) {
case CALI_TYPE_BOOL:
return b;
case CALI_TYPE_INT:
return m_value.v_int != 0;
case CALI_TYPE_UINT:
return m_value.v_uint != 0;
default:
break;
}
return false;
}
bool
Variant::to_bool(bool* okptr)
{
bool ok = false;
bool b = const_cast<const Variant*>(this)->to_bool(&ok);
if (m_type == CALI_TYPE_INV && ok) {
m_type = CALI_TYPE_BOOL;
m_size = sizeof(bool);
m_value.v_int = b;
}
if (okptr)
*okptr = ok;
return b;
}
int
Variant::to_int(bool* okptr) const
{
int i = static_cast<int>(m_value.v_int);
cali_attr_type type = m_type;
if (m_type == CALI_TYPE_INV && !m_string.empty()) {
istringstream is(m_string.obj());
is >> i;
if (is)
type = CALI_TYPE_INT;
}
bool ok = (type == CALI_TYPE_INT);
if (okptr)
*okptr = ok;
return ok ? i : 0;
}
int
Variant::to_int(bool* okptr)
{
bool ok = false;
int i = const_cast<const Variant*>(this)->to_int(&ok);
if (m_type == CALI_TYPE_INV && ok) {
m_type = CALI_TYPE_INT;
m_size = sizeof(int64_t);
m_value.v_int = i;
}
if (okptr)
*okptr = ok;
return i;
}
uint64_t
Variant::to_uint(bool* okptr) const
{
uint64_t uint = m_value.v_uint;
cali_attr_type type = m_type;
if (m_type == CALI_TYPE_INV && !m_string.empty()) {
istringstream is(m_string.obj());
is >> uint;
if (is)
type = CALI_TYPE_UINT;
}
bool ok = (type == CALI_TYPE_UINT);
if (okptr)
*okptr = ok;
return ok ? uint : 0;
}
uint64_t
Variant::to_uint(bool* okptr)
{
bool ok = false;
uint64_t uint = const_cast<const Variant*>(this)->to_uint(&ok);
if (m_type == CALI_TYPE_INV && ok) {
m_type = CALI_TYPE_UINT;
m_size = sizeof(uint64_t);
m_value.v_uint = uint;
}
if (okptr)
*okptr = ok;
return uint;
}
double
Variant::to_double(bool* okptr) const
{
double d = m_value.v_double;
cali_attr_type type = m_type;
if (type == CALI_TYPE_INV && !m_string.empty()) {
istringstream is(m_string.obj());
is >> d;
if (is)
type = CALI_TYPE_DOUBLE;
}
bool ok = (type == CALI_TYPE_DOUBLE || type == CALI_TYPE_INT || type == CALI_TYPE_UINT);
if (okptr)
*okptr = ok;
switch (type) {
case CALI_TYPE_DOUBLE:
return d;
case CALI_TYPE_INT:
return m_value.v_int;
case CALI_TYPE_UINT:
return m_value.v_uint;
default:
return 0;
}
}
double
Variant::to_double(bool* okptr)
{
bool ok = false;
double d = const_cast<const Variant*>(this)->to_double(&ok);
if (m_type == CALI_TYPE_INV && ok) {
m_type = CALI_TYPE_DOUBLE;
m_size = sizeof(double);
m_value.v_double = d;
}
if (okptr)
*okptr = ok;
return d;
}
cali_attr_type
Variant::to_attr_type(bool* okptr) const
{
cali_attr_type ret = m_value.v_type;
cali_attr_type type = m_type;
if (m_type == CALI_TYPE_INV && !m_string.empty()) {
ret = cali_string2type(m_string.obj().c_str());
if (ret != CALI_TYPE_INV)
type = CALI_TYPE_TYPE;
}
bool ok = (type == CALI_TYPE_TYPE);
if (okptr)
*okptr = ok;
return ok ? ret : CALI_TYPE_INV;
}
cali_attr_type
Variant::to_attr_type(bool* okptr)
{
bool ok = false;
cali_attr_type t = const_cast<const Variant*>(this)->to_attr_type(&ok);
if (m_type == CALI_TYPE_INV && ok) {
m_type = CALI_TYPE_TYPE;
m_size = sizeof(cali_attr_type);
m_value.v_type = t;
}
if (okptr)
*okptr = ok;
return t;
}
std::string
Variant::to_string() const
{
if (!m_string.empty())
return m_string.obj();
string ret;
switch (m_type) {
case CALI_TYPE_INV:
break;
case CALI_TYPE_USR:
{
ostringstream os;
copy(static_cast<const unsigned char*>(m_value.ptr), static_cast<const unsigned char*>(m_value.ptr) + m_size,
ostream_iterator<unsigned>(os << std::hex << setw(2) << setfill('0'), ":"));
ret = os.str();
}
break;
case CALI_TYPE_INT:
ret = std::to_string(m_value.v_int);
break;
case CALI_TYPE_UINT:
ret = std::to_string(m_value.v_uint);
break;
case CALI_TYPE_STRING:
{
const char* str = static_cast<const char*>(m_value.ptr);
std::size_t len = m_size;
if (len && str[len-1] == 0)
--len;
ret.assign(str, len);
}
break;
case CALI_TYPE_ADDR:
{
ostringstream os;
os << std::hex << m_value.v_uint;
ret = os.str();
}
break;
case CALI_TYPE_DOUBLE:
ret = std::to_string(m_value.v_double);
break;
case CALI_TYPE_BOOL:
ret = m_value.v_bool ? "true" : "false";
break;
case CALI_TYPE_TYPE:
{
ret = cali_type2string(m_value.v_type);
}
break;
}
return ret;
}
size_t
Variant::pack(unsigned char* buf) const
{
size_t nbytes = 0;
nbytes += vlenc_u64(static_cast<uint64_t>(m_type), buf);
switch (m_type) {
case CALI_TYPE_INV:
break;
case CALI_TYPE_USR:
case CALI_TYPE_STRING:
nbytes += vlenc_u64(m_size, buf+nbytes);
default:
nbytes += vlenc_u64(m_value.v_uint, buf+nbytes);
break;
}
return nbytes;
}
Variant
Variant::unpack(const unsigned char* buf, size_t* inc, bool *ok)
{
size_t p = 0;
Variant v;
uint64_t u_type = vldec_u64(buf, &p);
if (u_type > CALI_MAXTYPE) {
if (ok)
*ok = false;
return v;
}
v.m_type = static_cast<cali_attr_type>(u_type);
switch (v.m_type) {
case CALI_TYPE_INV:
break;
case CALI_TYPE_USR:
case CALI_TYPE_STRING:
v.m_size = static_cast<size_t>(vldec_u64(buf+p, &p));
default:
v.m_value.v_uint = vldec_u64(buf+p, &p);
}
if (inc)
*inc += p;
return v;
}
Variant
Variant::concretize(cali_attr_type type, bool *ok) const
{
Variant ret;
if (m_type == type && m_type != CALI_TYPE_INV) {
if (ok)
*ok = true;
return *this;
}
switch (type) {
case CALI_TYPE_INV:
case CALI_TYPE_USR:
case CALI_TYPE_STRING:
// can't concretize this without knowing where to alloc memory
if (ok)
*ok = false;
break;
case CALI_TYPE_ADDR:
case CALI_TYPE_INT:
{
int64_t u = to_int(ok);
if (ok)
ret = Variant(type, &u, sizeof(int64_t));
}
break;
case CALI_TYPE_UINT:
{
uint64_t u = to_uint(ok);
if (ok)
ret = Variant(type, &u, sizeof(uint64_t));
}
break;
case CALI_TYPE_DOUBLE:
ret = Variant(to_double(ok));
break;
case CALI_TYPE_BOOL:
ret = Variant(to_bool(ok));
break;
case CALI_TYPE_TYPE:
ret = Variant(to_attr_type(ok));
break;
};
return ret;
}
bool cali::operator == (const Variant& lhs, const Variant& rhs)
{
if (lhs.m_type == CALI_TYPE_INV && rhs.m_type == CALI_TYPE_INV)
return lhs.m_string == rhs.m_string;
if (lhs.m_type == CALI_TYPE_INV || rhs.m_type == CALI_TYPE_INV)
return lhs.to_string() == rhs.to_string();
if (lhs.m_type != rhs.m_type)
return false;
switch (lhs.m_type) {
case CALI_TYPE_STRING:
case CALI_TYPE_USR:
if (lhs.m_size == rhs.m_size) {
if (lhs.m_value.ptr == rhs.m_value.ptr)
return true;
else
return 0 == memcmp(lhs.m_value.ptr, rhs.m_value.ptr, lhs.m_size);
}
return false;
case CALI_TYPE_BOOL:
return lhs.m_value.v_bool == rhs.m_value.v_bool;
case CALI_TYPE_TYPE:
return lhs.m_value.v_type == rhs.m_value.v_type;
case CALI_TYPE_DOUBLE:
return lhs.m_value.v_double == rhs.m_value.v_double;
default:
return lhs.m_value.v_uint == rhs.m_value.v_uint;
}
}
bool cali::operator < (const Variant& lhs, const Variant& rhs)
{
if (lhs.m_type == CALI_TYPE_INV || rhs.m_type == CALI_TYPE_INV)
return lhs.to_string() < rhs.to_string();
if (lhs.m_type != rhs.m_type)
return lhs.m_type < rhs.m_type;
switch (lhs.m_type) {
case CALI_TYPE_STRING:
return strncmp(static_cast<const char*>(lhs.m_value.ptr),
static_cast<const char*>(rhs.m_value.ptr), std::min(lhs.m_size, rhs.m_size)) < 0;
case CALI_TYPE_USR:
return memcmp(lhs.m_value.ptr, rhs.m_value.ptr, std::min(lhs.m_size, rhs.m_size)) < 0;
case CALI_TYPE_BOOL:
return lhs.m_value.v_bool < rhs.m_value.v_bool;
case CALI_TYPE_TYPE:
return lhs.m_value.v_type < rhs.m_value.v_type;
case CALI_TYPE_DOUBLE:
return lhs.m_value.v_double < rhs.m_value.v_double;
case CALI_TYPE_INT:
return lhs.m_value.v_int < rhs.m_value.v_int;
default:
return lhs.m_value.v_uint < rhs.m_value.v_uint;
}
}
ostream& cali::operator << (ostream& os, const Variant& v)
{
os << v.to_string();
return os;
}
|
#include<bits/stdc++.h>
using namespace std;
struct node{
int to,cap,rev;
};
vector<node> e[3000];
bool used[3000];
int s=0,t=2999,n,m,ans;
inline void ins(int u,int v,int c){
e[u].push_back((node){v,c,e[v].size()});
e[v].push_back((node){u,0,e[u].size()-1});
}
void readit(){
scanf("%d%d",&n,&m);
for (int i=1;i<=m;i++){
int u,v;
scanf("%d%d",&u,&v);
ins(u,v+n,1);
}
for (int i=1;i<=n;i++){
ins(s,i,1);
ins(i+n,t,1);
}
}
void writeit(){
printf("%d\n",ans);
}
int dfs(int v,int t,int f){
if (v==t) return f;
used[v]=1;
for (int i=0;i<e[v].size();i++){
node &evi=e[v][i];
if (!used[evi.to]&&evi.cap>0){
int c=dfs(evi.to,t,min(f,evi.cap));
if (c>0){
evi.cap-=c;
e[evi.to][evi.rev].cap+=c;
return c;
}
}
}
return 0;
}
int max_flow(int s,int t){
int flow=0;
for (;;){
memset(used,0,sizeof(used));
int f=dfs(s,t,10000000);
if (f==0) return flow;
flow+=f;
}
}
void work(){
ans=n-max_flow(s,t);
}
int main(){
readit();
work();
writeit();
return 0;
}
|
//
// EPITECH PROJECT, 2018
// zappy
// File description:
// Menu.cpp
//
#include "Menu.hpp"
Menu::Menu()
{
}
Menu::Menu(ImageManager *img, ButtonManager *btn, ServPanel *srv,
SoundManager *snd, StaticTextManager *txt, CheckBoxManager *bx,
Table *tl, ListBox *lstB, ScrollBar *scrllB)
{
_img = img;
_btn = btn;
_srv = srv;
_snd = snd;
_txt = txt;
_bx = bx;
_tbl = tl;
_lstBx = lstB;
_scrllBr = scrllB;
isMenuOpen = false;
isOptionsOpen = false;
isCreditsOpen = false;
isServerLaunch = false;
needToExit = false;
start = true;
idSkyBox = 0;
_serverHandler = nullptr;
}
Menu::~Menu()
{
}
void Menu::isButtonPressed()
{
_btn->isButtonPressed(this);
}
void Menu::test(int id)
{
std::cout << "Button " << id << " is testing\n";
}
void Menu::show_timer()
{
if (start) {
_img->setVisible(true, TIMER_PANEL);
_txt->setVisible(true, TIMER_TEXT_1);
_txt->setVisible(true, TIMER_TEXT_2);
_scrllBr->setVisible(true);
}
}
void Menu::hide_timer()
{
_img->setVisible(false, TIMER_PANEL);
_txt->setVisible(false, TIMER_TEXT_1);
_txt->setVisible(false, TIMER_TEXT_2);
_scrllBr->setVisible(false);
}
void Menu::show_table()
{
if (start) {
_tbl->setVisible(true);
_img->setVisible(true, TABLE_PANEL);
}
}
void Menu::hide_table()
{
_tbl->setVisible(false);
_img->setVisible(false, TABLE_PANEL);
}
void Menu::show_listBox()
{
if (start) {
_lstBx->setVisible(true);
_img->setVisible(true, LISTBOX_PANEL);
}
}
void Menu::hide_listBox()
{
_lstBx->setVisible(false);
_img->setVisible(false, LISTBOX_PANEL);
}
void Menu::menu_open()
{
/* FOR CYRIL
show_inventory();
hide_inventory();
update_inventory({"12", "13", "20", "31", "42", "20", "12"}); */
if (!isMenuOpen && !isOptionsOpen && !isCreditsOpen) {
isMenuOpen = true;
_btn->setVisible(true, MENU_BTN_OPTIONS);
_btn->setVisible(true, MENU_BTN_CREDITS);
_btn->setVisible(true, MENU_BTN_EXIT);
_btn->setVisible(true, MENU_BTN_CANCEL_MENU);
_img->setVisible(true, MENU_PANEL);
_img->setVisible(true, MENU_HEADER);
_img->setVisible(true, MENU_MENU_TEXT);
} else {
options_cancel();
credits_cancel();
menu_cancel();
}
std::cout << "Menu open\n";
}
void Menu::menu_cancel()
{
if (isMenuOpen && !isOptionsOpen && !isCreditsOpen) {
isMenuOpen = false;
_btn->setVisible(false, MENU_BTN_OPTIONS);
_btn->setVisible(false, MENU_BTN_CREDITS);
_btn->setVisible(false, MENU_BTN_EXIT);
_btn->setVisible(false, MENU_BTN_CANCEL_MENU);
_img->setVisible(false, MENU_PANEL);
_img->setVisible(false, MENU_HEADER);
_img->setVisible(false, MENU_MENU_TEXT);
}
std::cout << "Menu cancel\n";
}
void Menu::options_cancel()
{
if (isMenuOpen && isOptionsOpen && !isCreditsOpen) {
isOptionsOpen = false;
_btn->setVisible(false, MENU_BTN_CANCEL_OPTIONS);
_btn->setVisible(true, MENU_BTN_OPTIONS);
_btn->setVisible(true, MENU_BTN_CREDITS);
_btn->setVisible(true, MENU_BTN_EXIT);
_btn->setVisible(true, MENU_BTN_CANCEL_MENU);
_img->setVisible(false, MENU_OPTIONS_TEXT);
_img->setVisible(true, MENU_MENU_TEXT);
_bx->setVisible(false, MENU_OPTIONS_CHECKBOX_TIMER);
_bx->setVisible(false, MENU_OPTIONS_CHECKBOX_TABLE);
_bx->setVisible(false, MENU_OPTIONS_CHECKBOX_LISTBOX);
_bx->setVisible(false, MENU_OPTIONS_CHECKBOX_MUSIC);
_txt->setVisible(false, MENU_OPTIONS_TEXT_TABLE);
_txt->setVisible(false, MENU_OPTIONS_TEXT_TIMER);
_txt->setVisible(false, MENU_OPTIONS_TEXT_MUSIC);
_txt->setVisible(false, MENU_OPTIONS_TEXT_LISTBOX);
_bx->isCheck(this, MENU_OPTIONS_CHECKBOX_TIMER);
_bx->isCheck(this, MENU_OPTIONS_CHECKBOX_LISTBOX);
_bx->isCheck(this, MENU_OPTIONS_CHECKBOX_MUSIC);
_bx->isCheck(this, MENU_OPTIONS_CHECKBOX_TABLE);
}
std::cout << "Options cancel\n";
}
void Menu::options_open()
{
if (isMenuOpen && !isOptionsOpen && !isCreditsOpen) {
isOptionsOpen = true;
_btn->setVisible(false, MENU_BTN_OPTIONS);
_btn->setVisible(false, MENU_BTN_CREDITS);
_btn->setVisible(false, MENU_BTN_EXIT);
_btn->setVisible(false, MENU_BTN_CANCEL_MENU);
_btn->setVisible(true, MENU_BTN_CANCEL_OPTIONS);
_img->setVisible(false, MENU_MENU_TEXT);
_img->setVisible(true, MENU_OPTIONS_TEXT);
_txt->setVisible(true, MENU_OPTIONS_TEXT_TABLE);
_txt->setVisible(true, MENU_OPTIONS_TEXT_TIMER);
_txt->setVisible(true, MENU_OPTIONS_TEXT_MUSIC);
_txt->setVisible(true, MENU_OPTIONS_TEXT_LISTBOX);
_bx->setVisible(true, MENU_OPTIONS_CHECKBOX_LISTBOX);
_bx->setVisible(true, MENU_OPTIONS_CHECKBOX_TIMER);
_bx->setVisible(true, MENU_OPTIONS_CHECKBOX_TABLE);
_bx->setVisible(true, MENU_OPTIONS_CHECKBOX_MUSIC);
}
std::cout << "Options open\n";
}
void Menu::credits_cancel()
{
if (isMenuOpen && !isOptionsOpen && isCreditsOpen) {
isCreditsOpen = false;
_btn->setVisible(false, MENU_BTN_CANCEL_CREDITS);
_btn->setVisible(true, MENU_BTN_OPTIONS);
_btn->setVisible(true, MENU_BTN_CREDITS);
_btn->setVisible(true, MENU_BTN_EXIT);
_btn->setVisible(true, MENU_BTN_CANCEL_MENU);
_img->setVisible(false, MENU_CREDITS_TEXT);
_img->setVisible(true, MENU_MENU_TEXT);
_img->setVisible(false, MENU_CREDITS_IMG);
}
std::cout << "Credits cancel\n";
}
void Menu::credits_open()
{
if (isMenuOpen && !isOptionsOpen && !isCreditsOpen) {
isCreditsOpen = true;
_btn->setVisible(false, MENU_BTN_OPTIONS);
_btn->setVisible(false, MENU_BTN_CREDITS);
_btn->setVisible(false, MENU_BTN_EXIT);
_btn->setVisible(false, MENU_BTN_CANCEL_MENU);
_btn->setVisible(true, MENU_BTN_CANCEL_CREDITS);
_img->setVisible(false, MENU_MENU_TEXT);
_img->setVisible(true, MENU_CREDITS_TEXT);
_img->setVisible(true, MENU_CREDITS_IMG);
}
std::cout << "Credits open\n";
}
void Menu::server_open()
{
start = false;
isMenuOpen = false;
isOptionsOpen = false;
isCreditsOpen = false;
isServerLaunch = false;
_btn->setVisible(false, ADD_TEAM1);
_btn->setVisible(false, ADD_TEAM2);
_btn->setVisible(false, ADD_TEAM3);
_btn->setVisible(false, ADD_TEAM4);
_btn->setVisible(false, LAUNCH_GAME);
_img->setVisible(true, MENU_SRV_PANEL);
_btn->setVisible(true, SRV_FIRST_OK);
_srv->setVisible(true, EditBox::PORT);
_srv->setVisible(true, EditBox::WIDTH);
_srv->setVisible(true, EditBox::HEIGHT);
_srv->setVisible(true, EditBox::CLIENT);
_srv->setVisible(true, EditBox::FREQ);
_srv->setVisible(true, EditBox::TEAM);
}
void Menu::server_first_ok()
{
_btn->setVisible(false, SRV_FIRST_OK);
_srv->setVisible(false, EditBox::PORT);
_srv->setVisible(false, EditBox::WIDTH);
_srv->setVisible(false, EditBox::HEIGHT);
_srv->setVisible(false, EditBox::CLIENT);
_srv->setVisible(false, EditBox::FREQ);
_srv->setVisible(false, EditBox::TEAM);
_srv->setString(EditBox::PORT);
_srv->setString(EditBox::WIDTH);
_srv->setString(EditBox::HEIGHT);
_srv->setString(EditBox::CLIENT);
_srv->setString(EditBox::FREQ);
_srv->setString(EditBox::TEAM);
std::wcout << "PORT : [" << _srv->port << "]\n";
std::wcout << "WIDTH : [" << _srv->width << "]\n";
std::wcout << "HEIGHT : [" << _srv->height << "]\n";
std::wcout << "CLIENT : [" << _srv->client << "]\n";
std::wcout << "FREQ : [" << _srv->freq << "]\n";
std::wcout << "TEAM : [" << _srv->team << "]\n";
_srv->srvClient->setNbTeam(_srv->team);
_btn->setVisible(true, SRV_SECOND_OK);
_srv->setVisible(true, EditBox::NAME1);
if (_srv->srvClient->getNbTeam() >= 2)
_srv->setVisible(true, EditBox::NAME2);
if (_srv->srvClient->getNbTeam() >= 3)
_srv->setVisible(true, EditBox::NAME3);
if (_srv->srvClient->getNbTeam() >= 4)
_srv->setVisible(true, EditBox::NAME4);
}
void Menu::server_second_ok()
{
_srv->setString(EditBox::NAME1);
if (_srv->srvClient->getNbTeam() >= 2) {
_srv->setString(EditBox::NAME2);
}
if (_srv->srvClient->getNbTeam() >= 3) {
_srv->setString(EditBox::NAME3);
}
if (_srv->srvClient->getNbTeam() >= 4) {
_srv->setString(EditBox::NAME4);
}
_btn->setVisible(false, SRV_SECOND_OK);
_img->setVisible(false, MENU_SRV_PANEL);
_srv->setVisible(false, EditBox::NAME1);
_srv->setVisible(false, EditBox::NAME2);
_srv->setVisible(false, EditBox::NAME3);
_srv->setVisible(false, EditBox::NAME4);
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM1),
ADD_TEAM1);
if (_srv->srvClient->getNbTeam() >= 2) {
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM2),
ADD_TEAM2);
}
if (_srv->srvClient->getNbTeam() >= 3) {
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM3),
ADD_TEAM3);
}
if (_srv->srvClient->getNbTeam() >= 4) {
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM4),
ADD_TEAM4);
}
_serverHandler = std::make_shared<ServerHandler>();
auto port = atoi(wchar_to_string(_srv->port).c_str());
auto width = atoi(wchar_to_string(_srv->width).c_str());
auto height = atoi(wchar_to_string(_srv->height).c_str());
auto client = atoi(wchar_to_string(_srv->client).c_str());
auto freq = atoi(wchar_to_string(_srv->freq).c_str());
auto vec = _srv->srvClient->getVectorTeam();
std::cout << "Starting server to port " << port << std::endl;
bool started = _serverHandler->startServer(width, height, port, vec, client, freq);
if (!started)
{
std::cout << "Failed to start server" << std::endl;
server_open();
}
else
{
std::cout << "Server listening to port " << port << std::endl;
isServerLaunch = true;
_btn->setVisible(true, LAUNCH_GAME);
_btn->setVisible(true, ADD_TEAM1);
if (_srv->srvClient->getNbTeam() >= 2) {
_btn->setVisible(true, ADD_TEAM2);
}
if (_srv->srvClient->getNbTeam() >= 3) {
_btn->setVisible(true, ADD_TEAM3);
}
if (_srv->srvClient->getNbTeam() >= 4) {
_btn->setVisible(true, ADD_TEAM4);
}
}
start = true;
/* EXECUTE SERVER */
}
void Menu::add_team1()
{
_srv->srvClient->addPlayer(SrvClient::TEAM1);
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM1),
ADD_TEAM1);
}
void Menu::add_team2()
{
_srv->srvClient->addPlayer(SrvClient::TEAM2);
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM2),
ADD_TEAM2);
}
void Menu::add_team3()
{
_srv->srvClient->addPlayer(SrvClient::TEAM3);
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM3),
ADD_TEAM3);
}
void Menu::add_team4()
{
_srv->srvClient->addPlayer(SrvClient::TEAM4);
_btn->setText(_srv->srvClient->updateClient(SrvClient::TEAM4),
ADD_TEAM4);
}
void Menu::hide_inventory()
{
_img->setVisible(false, INVENTORY_PANEL);
_img->setVisible(false, INV_IMG_1);
_img->setVisible(false, INV_IMG_2);
_img->setVisible(false, INV_IMG_3);
_img->setVisible(false, INV_IMG_4);
_img->setVisible(false, INV_IMG_5);
_img->setVisible(false, INV_IMG_6);
_img->setVisible(false, INV_IMG_7);
_txt->setVisible(false, INV_VALUE_1);
_txt->setVisible(false, INV_VALUE_2);
_txt->setVisible(false, INV_VALUE_3);
_txt->setVisible(false, INV_VALUE_4);
_txt->setVisible(false, INV_VALUE_5);
_txt->setVisible(false, INV_VALUE_6);
_txt->setVisible(false, INV_VALUE_7);
}
void Menu::show_inventory()
{
_img->setVisible(true, INVENTORY_PANEL);
_img->setVisible(true, INV_IMG_1);
_img->setVisible(true, INV_IMG_2);
_img->setVisible(true, INV_IMG_3);
_img->setVisible(true, INV_IMG_4);
_img->setVisible(true, INV_IMG_5);
_img->setVisible(true, INV_IMG_6);
_img->setVisible(true, INV_IMG_7);
_txt->setVisible(true, INV_VALUE_1);
_txt->setVisible(true, INV_VALUE_2);
_txt->setVisible(true, INV_VALUE_3);
_txt->setVisible(true, INV_VALUE_4);
_txt->setVisible(true, INV_VALUE_5);
_txt->setVisible(true, INV_VALUE_6);
_txt->setVisible(true, INV_VALUE_7);
}
void Menu::update_inventory(std::vector<std::string> string)
{
int count = 0;
for (std::vector<std::string>::iterator it = string.begin();
it != string.end(); ++it) {
if (count == 0) {
_txt->setText((*it).c_str(), INV_VALUE_1);
} else if (count == 1) {
_txt->setText((*it).c_str(), INV_VALUE_2);
} else if (count == 2) {
_txt->setText((*it).c_str(), INV_VALUE_3);
} else if (count == 3) {
_txt->setText((*it).c_str(), INV_VALUE_4);
} else if (count == 4) {
_txt->setText((*it).c_str(), INV_VALUE_5);
} else if (count == 5) {
_txt->setText((*it).c_str(), INV_VALUE_6);
} else if (count == 6) {
_txt->setText((*it).c_str(), INV_VALUE_7);
}
count += 1;
}
}
void Menu::launch_game()
{
_btn->setVisible(false, ADD_TEAM1);
_btn->setVisible(false, ADD_TEAM2);
_btn->setVisible(false, ADD_TEAM3);
_btn->setVisible(false, ADD_TEAM4);
_btn->setVisible(false, LAUNCH_GAME);
for(size_t i = 0; i < _srv->srvClient->team.size(); i++) {
auto nbLaunch = _srv->srvClient->nb[i];
auto str = wchar_to_string(_srv->srvClient->team[i]);
_serverHandler->addAi(str, nbLaunch);
}
/* EXECUTE ALL IA */
}
void Menu::next_song()
{
_snd->playNextMusic();
std::cout << "Next music !" << "\n";
}
void Menu::exit()
{
needToExit = true;
std::cout << "Exit\n";
}
int Menu::getPort() const
{
return atoi(wchar_to_string(_srv->port).c_str());
}
bool Menu::getExit() const
{
return needToExit;
}
std::shared_ptr<ServerHandler> Menu::getServerHandler(void) const noexcept
{
return _serverHandler;
}
void Menu::nextSkyBox()
{
++idSkyBox;
}
|
//============================================================================
// Name : stack.cpp
// Author :
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
class Stack
{
int a[5];
int top;
public:
void push(int);
void pop();
void display();
void topofstack();
Stack()
{
top=-1;
}
};
void Stack::push(int x){
if(top==4)
{cout<<"stack overflow";
}
else
{
top++;
a[top]=x;
}
}
void Stack::pop()
{
if(top==-1)
{cout<<"Stack underflow";
}
else
top--;
}
void Stack::display()
{
cout<<"The current stack is\n";
for(int i=0;i>=top;i--)
{
cout<<a[i]<<"\n";
}
}
void Stack::topofstack()
{
cout<<"The element on top of the stack is:";
cout<<a[top];
}
int main() {
Stack s;
cout << "Stack:" << endl;
//s.push(67);
//s.push(56);
//s.push(34);
//s.push(78);
//s.display();
//s.pop();
//s.display();
//s.pop();
//s.display();
//s.topofstack();
//s.pop();
//s.display();
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- */
#include "core/pch.h"
#include "modules/libgogi/mde.h"
#ifdef MDE_SUPPORT_MOUSE
void MDE_Screen::ReleaseMouseCapture()
{
if (m_captured_input)
{
// OnMouseLeave() below can trigger a re-enter (example: DSK-318237)
MDE_View *captured_input = m_captured_input;
m_captured_input = 0;
MDE_View *target = GetViewAt(m_mouse_x, m_mouse_y, true);
if (target != captured_input)
captured_input->OnMouseLeave();
captured_input->OnMouseCaptureRelease();
}
}
MDE_View *MDE_View::GetViewAt(int x, int y, bool include_children)
{
MDE_View *tmp = m_first_child;
MDE_View *last_match = NULL;
while(tmp)
{
if (tmp->m_is_visible && tmp->GetHitStatus(x - tmp->m_rect.x, y - tmp->m_rect.y))
{
if (include_children)
{
last_match = tmp->GetViewAt(x - tmp->m_rect.x, y - tmp->m_rect.y, include_children);
if (!last_match)
last_match = tmp;
}
else
last_match = tmp;
}
tmp = tmp->m_next;
}
return last_match;
}
bool MDE_View::GetHitStatus(int x, int y)
{
if (m_custom_overlap_region.num_rects)
{
if (!MDE_RectContains(m_rect, x + m_rect.x, y + m_rect.y))
return false;
for (int i = 0; i < m_custom_overlap_region.num_rects; i++)
{
if (MDE_RectContains(m_custom_overlap_region.rects[i], x, y))
return false;
}
return true;
}
return MDE_RectContains(m_rect, x + m_rect.x, y + m_rect.y);
}
void MDE_View::TrigMouseDown(int x, int y, int button, int clicks, ShiftKeyState keystate)
{
m_screen->m_mouse_x = x;
m_screen->m_mouse_y = y;
if (!m_screen->m_captured_input)
{
m_screen->m_captured_input = GetViewAt(x, y, true);
m_screen->m_captured_button = button;
// don't allow double clicks where clicks stem from
// different views - see CORE-28158
if (g_mde_last_captured_input != m_screen->m_captured_input && clicks > 1)
clicks = 1;
g_mde_last_captured_input = m_screen->m_captured_input;
}
if (m_screen->m_captured_input)
{
m_screen->m_captured_input->ConvertFromScreen(x, y);
m_screen->m_captured_input->OnMouseDown(x, y, button, clicks, keystate);
}
}
void MDE_View::TrigMouseUp(int x, int y, int button, ShiftKeyState keystate)
{
m_screen->m_mouse_x = x;
m_screen->m_mouse_y = y;
MDE_View *target = m_screen->m_captured_input ? m_screen->m_captured_input : GetViewAt(x, y, true);
if (target)
{
target->ConvertFromScreen(x, y);
target->OnMouseUp(x, y, button, keystate);
if (button == m_screen->m_captured_button)
m_screen->ReleaseMouseCapture();
}
}
void MDE_View::TrigMouseMove(int x, int y, ShiftKeyState keystate)
{
MDE_View *old_target = GetViewAt(m_screen->m_mouse_x, m_screen->m_mouse_y, true);
m_screen->m_mouse_x = x;
m_screen->m_mouse_y = y;
ConvertToScreen(m_screen->m_mouse_x, m_screen->m_mouse_y);
MDE_View *target = m_screen->m_captured_input ? m_screen->m_captured_input : GetViewAt(x, y, true);
if (old_target && old_target != target && !m_screen->m_captured_input)
{
old_target->OnMouseLeave();
// Just in case the above call caused target to be deleted.
target = m_screen->m_captured_input ? m_screen->m_captured_input : GetViewAt(x, y, true);
}
if (target)
{
int tx = m_screen->m_mouse_x;
int ty = m_screen->m_mouse_y;
target->ConvertFromScreen(tx, ty);
target->OnMouseMove(tx, ty, keystate);
}
}
void MDE_View::TrigMouseWheel(int x, int y, int delta, bool vertical, ShiftKeyState keystate)
{
MDE_View *target = m_screen->m_captured_input ? m_screen->m_captured_input : GetViewAt(x, y, true);
if (target)
{
while(target && !target->OnMouseWheel(delta, vertical, keystate))
target = target->m_parent;
}
}
void MDE_View::OnMouseDown(int x, int y, int button, int clicks, ShiftKeyState keystate) { }
void MDE_View::OnMouseUp(int x, int y, int button, ShiftKeyState keystate) { }
void MDE_View::OnMouseMove(int x, int y, ShiftKeyState keystate) { }
void MDE_View::OnMouseLeave() { }
bool MDE_View::OnMouseWheel(int delta, bool vertical, ShiftKeyState keystate) { return false; }
void MDE_View::OnMouseCaptureRelease() { }
#endif // MDE_SUPPORT_MOUSE
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** FlatSiteBuilder is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#include "dashboard.h"
#include "flatbutton.h"
#include <QGridLayout>
#include <QLabel>
#include <QTest>
#include <QPushButton>
#include <QTextBrowser>
#include <QScrollArea>
#include <QDesktopServices>
#include <QFileDialog>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
Dashboard::Dashboard(Site *site, QString defaultPath)
{
m_site = site;
m_defaultPath = defaultPath;
QVBoxLayout *vbox = new QVBoxLayout();
QGridLayout *layout = new QGridLayout();
QLabel *title = new QLabel();
title->setText("Dashboard");
QFont fnt = title->font();
fnt.setPointSize(20);
fnt.setBold(true);
title->setFont(fnt);
m_browser = new QTextBrowser();
m_browser->setOpenLinks(false);
m_loadButton = new FlatButton(":/images/load_normal.png", ":/images/load_hover.png", ":/images/load_pressed.png");
m_loadButton->setToolTip("Load an existing website project");
m_createButton = new FlatButton(":/images/create_normal.png", ":/images/create_hover.png", ":/images/create_pressed.png");
m_createButton->setToolTip("Create a new website project");
m_publishButton = new FlatButton(":/images/publish_normal.png", ":/images/publish_hover.png", ":/images/publish_pressed.png");
m_publishButton->setToolTip("Upload the website to your web space provider");
m_previewButton = new FlatButton(":/images/preview_normal.png", ":/images/preview_hover.png", ":/images/preview_pressed.png");
m_previewButton->setToolTip("Load the website in your browser locally");
m_buildButton = new FlatButton(":/images/build_normal.png", ":/images/build_hover.png", ":/images/build_pressed.png");
m_buildButton->setToolTip("Build the website");
m_info = new QLabel();
if(m_site && !m_site->title().isEmpty())
m_info->setText(m_site->title() + " loaded...");
else
m_info->setText("No site loaded yet...");
QWidget *space = new QWidget();
QWidget *space2 = new QWidget();
QWidget *space3 = new QWidget();
space->setMinimumHeight(30);
space2->setMinimumHeight(30);
space3->setMinimumHeight(30);
layout->addWidget(title, 0, 0, 1, 3);
layout->addWidget(m_info, 1, 0, 1, 3);
layout->addWidget(space, 2, 0);
layout->addWidget(m_loadButton, 3, 0, 1, 1, Qt::AlignCenter);
layout->addWidget(m_createButton, 3, 1, 1, 1, Qt::AlignCenter);
layout->addWidget(m_publishButton, 3, 2, 1, 1, Qt::AlignCenter);
layout->addWidget(space2, 4, 0);
layout->addWidget(m_previewButton, 5, 0, 1, 1, Qt::AlignCenter);
layout->addWidget(m_buildButton, 5, 1, 1, 1, Qt::AlignCenter);
vbox->addLayout(layout);
vbox->addSpacing(40);
vbox->addWidget(m_browser);
setLayout(vbox);
connect(m_loadButton, SIGNAL(clicked()), this, SLOT(loadClicked()));
connect(m_createButton, SIGNAL(clicked()), this, SLOT(createClicked()));
connect(m_publishButton, SIGNAL(clicked()), this, SLOT(publishClicked()));
connect(m_previewButton, SIGNAL(clicked()), this, SLOT(previewClicked()));
connect(m_buildButton, SIGNAL(clicked()), this, SLOT(buildClicked()));
QNetworkAccessManager * manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(fileIsReady(QNetworkReply*)));
manager->get(QNetworkRequest(QUrl("https://artanidos.github.io/FlatSiteBuilder/news.html")));
}
void Dashboard::fileIsReady( QNetworkReply *reply)
{
m_browser->setHtml(reply->readAll());
connect(m_browser, SIGNAL(anchorClicked(QUrl)), this, SLOT(anchorClicked(QUrl)));
}
void Dashboard::anchorClicked(QUrl url)
{
QDesktopServices::openUrl(url);
}
void Dashboard::loadClicked()
{
QString fileName;
QFileDialog *dialog = new QFileDialog();
dialog->setFileMode(QFileDialog::AnyFile);
dialog->setNameFilter(tr("FlatSiteBuilder (*.xml);;All (*)"));
dialog->setWindowTitle(tr("Load Site"));
dialog->setOption(QFileDialog::DontUseNativeDialog, true);
dialog->setAcceptMode(QFileDialog::AcceptOpen);
dialog->setDirectory(m_defaultPath);
if(dialog->exec())
fileName = dialog->selectedFiles().first();
delete dialog;
if (fileName.isEmpty())
return;
emit loadSite(fileName);
}
void Dashboard::createClicked()
{
emit createSite();
}
void Dashboard::buildClicked()
{
emit buildSite();
}
void Dashboard::publishClicked()
{
emit publishSite();
}
void Dashboard::previewClicked()
{
emit previewSite(NULL);
}
void Dashboard::siteLoaded(Site *site)
{
m_site = site;
if(m_site->title().isEmpty())
m_info->setText("No site loaded yet...");
else
m_info->setText(m_site->title() + " loaded...");
}
|
/***************************************************************************************************
mathutils.h
math-related constants and utilities
by David Ramos
***************************************************************************************************/
#pragma once
// TODO: review if/when I get the VS2015 libs to make template typedefs and have constexpr instead of preprocessor macros
#define PI 3.14159265358979323846f
#define METERS 1.0f
#define SECONDS 1.0f
#define TO_RADIANS(deg) (deg * PI/180.0f)
#define TO_DEGREES(rad) (rad * 180.0f/PI)
#define HALF 0.5f
#define EPSILON 1e-5f
#define INVALID_INTERSECT_RESULT FLT_MAX
//----------------------------------------------------------------------------
inline bool IsSimilar(float lhs, float rhs, float epsilon = EPSILON)
{
return fabsf(lhs - rhs) < epsilon;
}
//----------------------------------------------------------------------------
template <typename T>
int Sign(const T& val)
{
return (T(0) < val) - (val < T(0));
}
|
#include<bits/stdc++.h>
using namespace std;
map<string,int> mp;
map<int,string> mp1;
void init() {
mp["1m"]=1,mp["2m"]=2,mp["3m"]=3,mp["4m"]=4,mp["5m"]=5;
mp["6m"]=6,mp["7m"]=7,mp["8m"]=8,mp["9m"]=9;
mp["1s"]=10,mp["2s"]=11,mp["3s"]=12,mp["4s"]=13,mp["5s"]=14;
mp["6s"]=15,mp["7s"]=16,mp["8s"]=17,mp["9s"]=18;
mp["1p"]=19,mp["2p"]=20,mp["3p"]=21,mp["4p"]=22,mp["5p"]=23;
mp["6p"]=24,mp["7p"]=25,mp["8p"]=26,mp["9p"]=27;
mp["1c"]=28,mp["2c"]=29,mp["3c"]=30,mp["4c"]=31,mp["5c"]=32;
mp["6c"]=33,mp["7c"]=34;
for(auto it=mp.begin(); it!=mp.end(); it++) {
mp1[it->second]=it->first;
}
}
int shisanyao[20]= {1,9,19,27,10,18,28,29,30,31,32,33,34};
int cnt[40];
int tc[40];
int a[20];
int ans=0;
vector<int> tiles;
bool judge1();
bool judge(int x) {
memset(tc,0,sizeof(tc));
tc[x]++;
int cnt_pair=0;
for(int i=1; i<=34; i++) {
tc[i]+=cnt[i];
if(tc[i]>4)
return false;
if(tc[i]==2)
cnt_pair++;
}
if(cnt_pair==7) {
return true;
}
if(cnt_pair==1) {
bool flag=true;
int tcnt=0;
for(int j=0; j<13; j++) {
if(tc[shisanyao[j]]==1)
continue;
if(tc[shisanyao[j]]>2||tc[shisanyao[j]]==0) {
flag=false;
break;
}
if(tc[shisanyao[j]]==2) {
tcnt++;
}
}
// cout<<tcnt<<" tcnt\n";
if(tcnt==1&&flag) {
return true;
}
}
for(int i=1; i<=34; i++) {
if(tc[i]>=2) {
tc[i]-=2;
if(judge1())
return true;
tc[i]+=2;
}
}
return false;
}
bool judge1() {
int ttc[40];
for(int i=1; i<=34; i++) {
ttc[i]=tc[i];
}
int tcnt=0;
for(int i=1; i<=34; i++) {
if(ttc[i]>=3) {
tcnt++;
ttc[i]-=3;
}
while(true) {
if(ttc[i]>0&&i<=25&&i!=8&&i!=9&&i!=17&&i!=18) {
if(ttc[i+1]>0&&ttc[i+2]>0) {
ttc[i]--;
ttc[i+1]--;
ttc[i+2]--;
tcnt++;
}else
break;
}else
break;
}
}
if(tcnt==4)
return true;
return false;
}
int main() {
init();
int T;
cin>>T;
while(T--) {
ans=0;
tiles.clear();
memset(cnt,0,sizeof(cnt));
memset(a,0,sizeof(a));
string s;
for(int i=0; i<13; i++) {
cin>>s;
cnt[mp[s]]++;
}
for(int i=1; i<=34; i++) {
if(judge(i)) {
ans++;
tiles.push_back(i);
}
}
if(ans==0) {
cout<<"Nooten\n";
continue;
}
cout<<ans;
for(int i=0; i<tiles.size(); i++) {
cout<<" "<<mp1[tiles[i]];
}
cout<<"\n";
}
return 0;
}
|
/*
Petar 'PetarV' Velickovic
Algorithm: Graham Scan
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <list>
#include <string>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <complex>
#define MAX_N 100001
#define INF 987654321
using namespace std;
typedef long long lld;
struct Point
{
double X, Y;
Point()
{
this->X = this->Y = 0;
}
Point(double x, double y)
{
this->X = x;
this->Y = y;
}
};
int n;
Point P[MAX_N];
Point R;
//Grahamov algoritam za nalazenje konveksnog omotaca datog skupa 2D tacaka
//Slozenost: O(N log N)
inline bool cmp(Point A, Point B)
{
return atan2(A.Y-R.Y,A.X-R.X) < atan2(B.Y-R.Y,B.X-R.X);
}
inline double CCW(Point a, Point b, Point c)
{
return ((b.X - a.X) * (c.Y - a.Y) - (b.Y - a.Y) * (c.X - a.X));
}
inline int GrahamScan(vector<Point> &cH)
{
int min_id = 1;
for (int i=2;i<=n;i++)
{
if (P[i].Y < P[min_id].Y || (P[i].Y == P[min_id].Y && P[i].X < P[min_id].X))
{
min_id = i;
}
}
swap(P[1], P[min_id]);
R = P[1];
sort(P+2, P+n+1, cmp);
P[0] = P[n];
int HullSize = 1;
for (int i=2;i<=n;i++)
{
while (CCW(P[HullSize-1], P[HullSize], P[i]) <= 0)
{
if (HullSize > 1) HullSize--;
else if (i == n) break;
else i++;
}
swap(P[++HullSize], P[i]);
}
for (int i=1;i<=HullSize;i++) cH.push_back(P[i]);
return HullSize;
}
int main()
{
n = 4;
P[1] = Point(4, 8);
P[2] = Point(4, 12);
P[3] = Point(5, 9.3);
P[4] = Point(7, 8);
vector<Point> cH;
int m = GrahamScan(cH);
printf("Hull size: %d\n",m);
for (int i=0;i<m;i++)
{
printf("%lf %lf\n",cH[i].X, cH[i].Y);
}
return 0;
}
|
#include "GnMeshPCH.h"
#include "GnLayerMain.h"
GnLayerMain::GnLayerMain() : mpBackground(NULL)
{
}
bool GnLayerMain::CreateBackgroundFromFile(const gchar* fileName)
{
if( mpBackground )
{
removeChild( mpBackground, true );
}
GnReal2DMesh* mesh = CCSprite::spriteWithFile( fileName );
if( mesh == NULL )
return false;
mesh->setAnchorPoint( CCPointMake(0,0) );
mpBackground = new GnLayerBackground();
mpBackground->addChild( mesh, 0 );
mpBackground->autorelease();
addChild( mpBackground );
return true;
}
|
// 1.15(์) Day 3
// ๊ณผ์ : ๋ฐ๋ณต๋ฌธ๊ณผ ์กฐ๊ฑด๋ฌธ, rand()๋ฅผ ์ด์ฉํ ๊ฐ์ ๋ฐ์ ๋ณด ๊ฒ์
// ์งํ ๋ฐฉ์
// ํ๋ ์ด์ด 2๋ช
1๋ช
์ ๋, ํ๋ช
์ ์ปดํจํฐ
// ๊ฐ์(0), ๋ฐ์(1), ๋ณด(2)
// ๋๋ ํ๋ ์ ํ
// ์ด 5๋ฒ ํ๋ ์ด
// ๋งค ํ๋ ์ด๋ง๋ค ๋๊ฐ ์ด๋ป๊ฒ ์ด๊ฒผ๋ค. ๋ผ๋ ๋ฌธ๊ตฌ ์ถ๋ ฅ
// ex) ์ฌ์ฉ์๊ฐ ๊ฐ์๋ก ์ปดํจํฐ๋ฅผ ์ด๊ฒผ๋ค
// ์ต์ข
์ ์ผ๋ก ์ด๊ธด ํ์, ์ง ํ์, ๋น๊ธด ํ์ ์ถ๋ ฅ
// ์นดํ์ ์ค์ท์ฐ์ด์ ์ฌ๋ฆฌ๊ธฐ
#include <iostream>
#include <time.h>
using namespace std;
void makeCover(int star) {
for (int i = 0; i < star; i++) {
cout << "*";
}
cout << endl;
}
void main()
{
int star = 49;
bool isSelect = false;
int player;
makeCover(star);
cout << "*\t\t๊ฐ์ ๋ฐ์ ๋ณด ๊ฒ์\t\t*" << endl;
makeCover(star);
while (isSelect == false) {
cout << "๊ฐ์ ๋ฐ์ ๋ณด ์ค ํ๋๋ฅผ ์
๋ ฅํ์ธ์" << endl;
cout << "์ซ์ํค ๊ฐ์(0), ๋ฐ์(1), ๋ณด(2)" << endl;
cout << "์
๋ ฅ : ";
cin >> player;
cout << endl;
switch (player) {
case 0:
cout << "[๊ฐ์(0)]๋ฅผ ์
๋ ฅ ํ์
จ์ต๋๋ค." << endl;
isSelect = true;
break;
case 1:
cout << "[๋ฐ์(1)]๋ฅผ ์
๋ ฅ ํ์
จ์ต๋๋ค." << endl;
isSelect = true;
break;
case 2:
cout << "[๋ณด(2)]๋ฅผ ์
๋ ฅ ํ์
จ์ต๋๋ค." << endl;
isSelect = true;
break;
default:
cout << "์๋ชป ์
๋ ฅํ์
จ์ต๋๋ค. ๋ค์ ์
๋ ฅํ์ธ์" << endl;
cout << "์
๋ ฅํ์ ์ซ์๋ " << player << "์
๋๋ค." << endl;
break;
}
}
cout << endl;
makeCover(star);
cout << "*\t\t๊ฒ์์ ์์ํฉ๋๋ค.\t\t*" << endl;
makeCover(star);
srand(time(NULL));
// ํ๋ ์ด ํ์
int num = 5;
int win, lose, draw;
win = lose = draw = 0;
for (int i = 0; i < num; i++) {
cout << i + 1 << "๋ฒ์งธ ๊ฒ์" << endl;
// ์ปดํจํฐ ์ํ
int com = rand() % 3;
cout << "\t์ปดํจํฐ๋ ";
switch (com) {
case 0:
cout << "๊ฐ์(0)๋ฅผ ๋์ต๋๋ค." << endl;
break;
case 1:
cout << "๋ฐ์(1)๋ฅผ ๋์ต๋๋ค." << endl;
break;
case 2:
cout << "๋ณด(2)๋ฅผ ๋์ต๋๋ค." << endl;
break;
}
cout << "\t๋น์ ์... ";
// draw
if (com == player) {
cout << "๋น๊ฒผ์ต๋๋ค." << endl;
draw++;
}
// player win
// ์ปด ๋ณด(2), ํ๋ ์ด์ด ๊ฐ์(2)์ผ ๋ ์ ์ซ์ ํด ๋ ์ด๊น
else if (com < player || (com == 2 && player == 0)) {
cout << "์ด๊ฒผ์ต๋๋ค." << endl;
win++;
}
// lose
else {
cout << "์ก์ต๋๋ค." << endl;
lose++;
}
}
makeCover(star);
cout << "*\t\t๊ฒ์ ๊ฒฐ๊ณผ\t\t\t*" << endl;
cout << "*\t\t" << win << "์น, " << lose << "ํจ, " << draw << "๋ฌด" << "\t\t\t*" << endl;
makeCover(star);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.