0.229322185518176 probably
I wouldn't call this basic though.
[sp]I used 1/(some trigonometric function(60°/2)), the law of cosines and a formula for inscribed circles in a specific figure, but there's probably a better way.[/sp]
[editline]Edited:[/editline]
I made a mistake, it's actually exactly a third.
[sp]My first hunch was correct, think triangles :)[/sp]
SO I am using visual studio 2012 Ultimate and I am running into an issue when trying to compile a project with multiple files and I don't know why I am getting these errors:
1>------ Build started: Project: lab2, Configuration: Debug Win32 ------
1> Node.cpp
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.cpp(13): error C2995: 'Node<ItemType>::Node(void)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.h(17) : see declaration of 'Node<ItemType>::Node'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.cpp(18): error C2995: 'Node<ItemType>::Node(const ItemType &)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.h(18) : see declaration of 'Node<ItemType>::Node'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.cpp(24): error C2995: 'Node<ItemType>::Node(const ItemType &,Node<ItemType> *)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.h(19) : see declaration of 'Node<ItemType>::Node'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.cpp(30): error C2995: 'void Node<ItemType>::setItem(const ItemType &)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.h(20) : see declaration of 'Node<ItemType>::setItem'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.cpp(36): error C2995: 'void Node<ItemType>::setNext(Node<ItemType> *)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.h(21) : see declaration of 'Node<ItemType>::setNext'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.cpp(42): error C2995: 'ItemType Node<ItemType>::getItem(void) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.h(22) : see declaration of 'Node<ItemType>::getItem'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.cpp(48): error C2995: 'Node<ItemType> *Node<ItemType>::getNext(void) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\node.h(23) : see declaration of 'Node<ItemType>::getNext'
1> LinkedBag.cpp
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(14): error C2995: 'LinkedBag<ItemType>::LinkedBag(void)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(25) : see declaration of 'LinkedBag<ItemType>::LinkedBag'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(54): error C2995: 'LinkedBag<ItemType>::LinkedBag(const LinkedBag<ItemType> &)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(26) : see declaration of 'LinkedBag<ItemType>::LinkedBag'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(60): error C2995: 'LinkedBag<ItemType>::~LinkedBag(void)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(27) : see declaration of 'LinkedBag<ItemType>::~LinkedBag'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(66): error C2995: 'bool LinkedBag<ItemType>::isEmpty(void) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(29) : see declaration of 'LinkedBag<ItemType>::isEmpty'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(72): error C2995: 'int LinkedBag<ItemType>::getCurrentSize(void) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(28) : see declaration of 'LinkedBag<ItemType>::getCurrentSize'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(88): error C2995: 'bool LinkedBag<ItemType>::add(const ItemType &)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(30) : see declaration of 'LinkedBag<ItemType>::add'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(104): error C2995: 'std::vector<ItemType> LinkedBag<ItemType>::toVector(void) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(35) : see declaration of 'LinkedBag<ItemType>::toVector'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(129): error C2995: 'bool LinkedBag<ItemType>::remove(const ItemType &)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(31) : see declaration of 'LinkedBag<ItemType>::remove'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(148): error C2995: 'void LinkedBag<ItemType>::clear(void)' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(32) : see declaration of 'LinkedBag<ItemType>::clear'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(168): error C2995: 'int LinkedBag<ItemType>::getFrequencyOf(const ItemType &) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(34) : see declaration of 'LinkedBag<ItemType>::getFrequencyOf'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(174): error C2995: 'bool LinkedBag<ItemType>::contains(const ItemType &) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(33) : see declaration of 'LinkedBag<ItemType>::contains'
1>c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.cpp(225): error C2995: 'Node<ItemType> *LinkedBag<ItemType>::getPointerTo(const ItemType &) const' : function template has already been defined
1> c:\users\omive_000\documents\visual studio 2012\projects\lab2\lab2\linkedbag.h(22) : see declaration of 'LinkedBag<ItemType>::getPointerTo'
1> Generating Code...
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Here are myis my main, headers, and other cpp files:
[CODE]// Created by Tony Chern 9/4/2013
// Sample code for lab2.cpp
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include "LinkedBag.h"
using namespace std;
void showMenu();
int checkMenuInput(char[]);
void displayBag(LinkedBag<string>& );
int main()
{
int choice;
string str;
LinkedBag<string> bag;
cout << "Starting the bag with 6 items." << endl;
string items[] = {"one", "two", "three", "four", "five", "one"};
cout << "Add 6 items to the bag: " << endl;
for (int i = 0; i < 6; i++)
{
bag.add(items[i]);
} // end for
do
{
showMenu(); //display menu
cin >> choice; //store user's choice
//make sure user types in valid menu choice
while (choice < 1 || choice > 6)
{
cout << "Please enter a valid menu choice: ";
cin >> choice;
}
if (choice != 6) //if user doesn't want to quit program
{
switch (choice)
{
case 1: //insert item
break;
case 2: //delete item
break;
case 3: //append item
cout << "Item name: ";
cin >> str;
bag.add(str);
break;
case 4: //print list
displayBag(bag);
break;
case 5: //reverse list
break;
}
}
} while(choice != 6);
return 0;
} // end main
// to display the test menu
void showMenu()
{
cout << "\n"
<< "1. Insert item\n"
<< "2. Delete item\n"
<< "3. Append item\n"
<< "4. Print list\n"
<< "5. Reverse list\n"
<< "6. Quit\n"
<< "Enter your choice: ";
}
// to validate the user input to menu.
int checkMenuInput(char input[])
{
int flag = 0; //0 if valid input, 1 if not
for (int i = 0; i < strlen(input); i++)
{
if((isdigit(input[i]) == 0) && (input[i] != '.'))
{
flag = 1;
}
}
return flag;
}
void displayBag(LinkedBag<string>& bag)
{
cout << "The bag contains " << bag.getCurrentSize()
<< " items:" << endl;
vector<string> bagItems = bag.toVector();
int numberOfEntries = (int) bagItems.size();
for (int i = 0; i < numberOfEntries; i++)
{
cout << bagItems[i] << " ";
} // end for
cout << endl;
} // end displayBag[/CODE]
[CODE]// Created by Frank M. Carrano and Tim Henry.
// Copyright (c) 2013 __Pearson Education__. All rights reserved.
/** Listing 1-1.
@file BagInterface.h */
#ifndef BAG_INTERFACE
#define BAG_INTERFACE
#include <vector>
using namespace std;
template<class ItemType>
class BagInterface
{
public:
/** Gets the current number of entries in this bag.
@return The integer number of entries currently in the bag. */
virtual int getCurrentSize() const = 0;
/** Sees whether this bag is empty.
@return True if the bag is empty, or false if not. */
virtual bool isEmpty() const = 0;
/** Adds a new entry to this bag.
@post If successful, newEntry is stored in the bag and
the count of items in the bag has increased by 1.
@param newEntry The object to be added as a new entry.
@return True if addition was successful, or false if not. */
virtual bool add(const ItemType& newEntry) = 0;
/** Removes one occurrence of a given entry from this bag,
if possible.
@post If successful, anEntry has been removed from the bag
and the count of items in the bag has decreased by 1.
@param anEntry The entry to be removed.
@return True if removal was successful, or false if not. */
virtual bool remove(const ItemType& anEntry) = 0;
/** Removes all entries from this bag.
@post Bag contains no items, and the count of items is 0. */
virtual void clear() = 0;
/** Counts the number of times a given entry appears in bag.
@param anEntry The entry to be counted.
@return The number of times anEntry appears in the bag. */
virtual int getFrequencyOf(const ItemType& anEntry) const = 0;
/** Tests whether this bag contains a given entry.
@param anEntry The entry to locate.
@return True if bag contains anEntry, or false otherwise. */
virtual bool contains(const ItemType& anEntry) const = 0;
/** Empties and then f ills a given vector with all entries that
are in this bag.
@return A vector containing all the entries in the bag. */
virtual vector<ItemType> toVector() const = 0;
}; // end BagInterface
#endif[/CODE]
[CODE]// Created by Frank M. Carrano and Tim Henry.
// Copyright (c) 2013 __Pearson Education__. All rights reserved.
/** ADT bag: Link-based implementation.
@file LinkedBag.h
Listing 4-3 */
#ifndef LINKED_BAG
#define LINKED_BAG
#include "BagInterface.h"
#include "Node.h"
template<class ItemType>
class LinkedBag : public BagInterface<ItemType>
{
private:
Node<ItemType>* headPtr; // Pointer to first node
int itemCount; // Current count of bag items
// Returns either a pointer to the node containing a given entry
// or the null pointer if the entry is not in the bag.
Node<ItemType>* getPointerTo(const ItemType& target) const;
public:
LinkedBag();
LinkedBag(const LinkedBag<ItemType>& aBag); // Copy constructor
virtual ~LinkedBag(); // Destructor should be virtual
int getCurrentSize() const;
bool isEmpty() const;
bool add(const ItemType& newEntry);
bool remove(const ItemType& anEntry);
void clear();
bool contains(const ItemType& anEntry) const;
int getFrequencyOf(const ItemType& anEntry) const;
vector<ItemType> toVector() const;
}; // end LinkedBag
#include "LinkedBag.cpp"
#endif[/CODE]
[CODE]// Created by Frank M. Carrano and Tim Henry.
// Copyright (c) 2013 __Pearson Education__. All rights reserved.
/** ADT bag: Link-based implementation.
@file LinkedBag.cpp */
#include "LinkedBag.h"
#include "Node.h"
#include <cstddef>
template<class ItemType>
LinkedBag<ItemType>::LinkedBag() : headPtr(nullptr), itemCount(0)
{
} // end default constructor
template<class ItemType>
LinkedBag<ItemType>::LinkedBag(const LinkedBag<ItemType>& aBag)
{
itemCount = aBag.itemCount;
Node<ItemType>* origChainPtr = aBag.headPtr; // Points to nodes in original chain
if (origChainPtr == nullptr)
headPtr = nullptr; // Original bag is empty
else
{
// Copy first node
headPtr = new Node<ItemType>();
headPtr->setItem(origChainPtr->getItem());
// Copy remaining nodes
Node<ItemType>* newChainPtr = headPtr; // Points to last node in new chain
origChainPtr = origChainPtr->getNext(); // Advance original-chain pointer
while (origChainPtr != nullptr)
{
// Get next item from original chain
ItemType nextItem = origChainPtr->getItem();
// Create a new node containing the next item
Node<ItemType>* newNodePtr = new Node<ItemType>(nextItem);
// Link new node to end of new chain
newChainPtr->setNext(newNodePtr);
// Advance pointer to new last node
newChainPtr = newChainPtr->getNext();
// Advance original-chain pointer
origChainPtr = origChainPtr->getNext();
} // end while
newChainPtr->setNext(nullptr); // Flag end of chain
} // end if
} // end copy constructor
template<class ItemType>
LinkedBag<ItemType>::~LinkedBag()
{
clear();
} // end destructor
template<class ItemType>
bool LinkedBag<ItemType>::isEmpty() const
{
return itemCount == 0;
} // end isEmpty
template<class ItemType>
int LinkedBag<ItemType>::getCurrentSize() const
{
return itemCount;
} // end getCurrentSize
template<class ItemType>
bool LinkedBag<ItemType>::add(const ItemType& newEntry)
{
// Add to beginning of chain: new node references rest of chain;
// (headPtr is null if chain is empty)
Node<ItemType>* nextNodePtr = new Node<ItemType>();
nextNodePtr->setItem(newEntry);
nextNodePtr->setNext(headPtr); // New node points to chain
// Node<ItemType>* nextNodePtr = new Node<ItemType>(newEntry, headPtr); // alternate code
headPtr = nextNodePtr; // New node is now first node
itemCount++;
return true;
} // end add
template<class ItemType>
vector<ItemType> LinkedBag<ItemType>::toVector() const
{
vector<ItemType> bagContents;
Node<ItemType>* curPtr = headPtr;
int counter = 0;
while ((curPtr != nullptr) && (counter < itemCount))
{
bagContents.push_back(curPtr->getItem());
curPtr = curPtr->getNext();
counter++;
} // end while
return bagContents;
} // end toVector
template<class ItemType>
bool LinkedBag<ItemType>::remove(const ItemType& anEntry)
{
Node<ItemType>* entryNodePtr = getPointerTo(anEntry);
bool canRemoveItem = !isEmpty() && (entryNodePtr != nullptr);
if (canRemoveItem)
{
// Copy data from first node to located node
entryNodePtr->setItem(headPtr->getItem());
// Delete first node
Node<ItemType>* nodeToDeletePtr = headPtr;
headPtr = headPtr->getNext();
// Return node to the system
nodeToDeletePtr->setNext(nullptr);
delete nodeToDeletePtr;
nodeToDeletePtr = nullptr;
itemCount--;
} // end if
return canRemoveItem;
} // end remove
template<class ItemType>
void LinkedBag<ItemType>::clear()
{
Node<ItemType>* nodeToDeletePtr = headPtr;
while (headPtr != nullptr)
{
headPtr = headPtr->getNext();
// Return node to the system
nodeToDeletePtr->setNext(nullptr);
delete nodeToDeletePtr;
nodeToDeletePtr = headPtr;
} // end while
// headPtr is nullptr; nodeToDeletePtr is nullptr
itemCount = 0;
} // end clear
template<class ItemType>
int LinkedBag<ItemType>::getFrequencyOf(const ItemType& anEntry) const
{
int frequency = 0;
int counter = 0;
Node<ItemType>* curPtr = headPtr;
while ((curPtr != nullptr) && (counter < itemCount))
{
if (anEntry == curPtr->getItem())
{
frequency++;
} // end if
counter++;
curPtr = curPtr->getNext();
} // end while
return frequency;
} // end getFrequencyOf
template<class ItemType>
bool LinkedBag<ItemType>::contains(const ItemType& anEntry) const
{
return (getPointerTo(anEntry) != nullptr);
} // end contains
/* ALTERNATE 1
template<class ItemType>
bool LinkedBag<ItemType>::contains(const ItemType& anEntry) const
{
return getFrequencyOf(anEntry) > 0;
}
*/
/* ALTERNATE 2
template<class ItemType>
bool LinkedBag<ItemType>::contains(const ItemType& anEntry) const
{
bool found = false;
Node<ItemType>* curPtr = headPtr;
int i = 0;
while (!found && (curPtr != nullptr) && (i < itemCount))
{
if (anEntry == curPtr-<getItem())
{
found = true;
}
else
{
i++;
curPtr = curPtr->getNext();
} // end if
} // end while
return found;
} // end contains
*/
// private
// Returns either a pointer to the node containing a given entry
// or the null pointer if the entry is not in the bag.
template<class ItemType>
Node<ItemType>* LinkedBag<ItemType>::getPointerTo(const ItemType& anEntry) const
{
bool found = false;
Node<ItemType>* curPtr = headPtr;
while (!found && (curPtr != nullptr))
{
if (anEntry == curPtr->getItem())
found = true;
else
curPtr = curPtr->getNext();
} // end while
return curPtr;
} // end getPointerTo
[/CODE]
[CODE]// Created by Frank M. Carrano and Tim Henry.
// Copyright (c) 2013 __Pearson Education__. All rights reserved.
/** @file Node.h
Listing 4-1 */
#ifndef NODE
#define NODE
template<class ItemType>
class Node
{
private:
ItemType item; // A data item
Node<ItemType>* next; // Pointer to next node
public:
Node();
Node(const ItemType& anItem);
Node(const ItemType& anItem, Node<ItemType>* nextNodePtr);
void setItem(const ItemType& anItem);
void setNext(Node<ItemType>* nextNodePtr);
ItemType getItem() const ;
Node<ItemType>* getNext() const ;
}; // end Node
#include "Node.cpp"
#endif[/CODE]
[CODE]// Created by Frank M. Carrano and Tim Henry.
// Copyright (c) 2013 __Pearson Education__. All rights reserved.
/** @file Node.cpp
Listing 4-2 */
#include "Node.h"
#include <cstddef>
template<class ItemType>
Node<ItemType>::Node() : next(nullptr)
{
} // end default constructor
template<class ItemType>
Node<ItemType>::Node(const ItemType& anItem) : item(anItem), next(nullptr)
{
} // end constructor
template<class ItemType>
Node<ItemType>::Node(const ItemType& anItem, Node<ItemType>* nextNodePtr) :
item(anItem), next(nextNodePtr)
{
} // end constructor
template<class ItemType>
void Node<ItemType>::setItem(const ItemType& anItem)
{
item = anItem;
} // end setItem
template<class ItemType>
void Node<ItemType>::setNext(Node<ItemType>* nextNodePtr)
{
next = nextNodePtr;
} // end setNext
template<class ItemType>
ItemType Node<ItemType>::getItem() const
{
return item;
} // end getItem
template<class ItemType>
Node<ItemType>* Node<ItemType>::getNext() const
{
return next;
} // end getNext
[/CODE]
Don't put the cpp files as part of the build.
You might be able to select that by right-clicking on the file in the project and looking to a setting there.
Alternatively you can give them a different extension, so VS won't recognize them as a C++ implementation file (although I guess highlighting would also break). This is the usual approach, extensions I've seen for this are .ipp (might not be consistent if you don't also use .hpp), .inl (my preference), .tmpl (I like .inl more, because I can also use it for non-template stuff inlining, while the name .tmpl implies templates). To not break highlighting (if VS does not recognize these), maybe you could choose _impl.h.
I have two ways to run my thread in C#.
[code]
(class constructor)
Thread t = new Thread(new ThreadStart(method));
(some method)
t.Start()
[/code]
and
[code]
(some method)
Thread t = new Thread(new ThreadStart(method));
t.Start();
[/code]
I've been told the second way is bad because it creates a new thread each time, though it does just what I want. The first one however, can run the thread only once so is doing
[code]
(variables)
Thread t;
(some method)
t = new Thread(new ThreadStart(method));
t.Start()
[/code]
good or bad? I don't have much experience with C#'s threading.
You could use Task.Run(method), that has the same effect but uses the thread pool instead so it's more lightweight.
I could be problematic if you run a lot of very long-running tasks that way though.
I'm stuck at adding awesomium into vs.
I've followed the steps to configure the project settings (adding to linker etc) but i cannot add #include Awesomium/Webcore.h> to my main.cpp without vs complaining it cannot find the source file (No intellisense either).
PS: Ive given up on gtk+ and webkit, i tried to build webkit for a day with missing files all day long.
Edit:
Fixed it by using absolute paths, what did i do wrong in using a enviromental path?
I used $(AWE_DIR)include before like in the 'getting started' article and it didn't work.
Can anyone give me a hand at translating [URL="http://advsys.net/ken/voxlap/groufst2.bas"]this Qbasic code[/URL] to C or pseudocode?
I've always wanted to make a basic voxel rendering engine, being inspired by [url="http://advsys.net/ken/"]Ken Silverman[/url] and [url="http://advsys.net/ken/voxlap.htm"]his voxlap engine[/url]. (That's also his snippet)
[editline]a[/editline]
No need to anymore, thanks whoever tried.
This isn't something i'm stuck on, but I feel like it's something I can do better.
I'm using PHP and in my code i'm getting elements from the URL and concatenating them into a string in an array format (e.g. "['var1']['var2']") so that I can then eval that (e.g. eval('echo $Variable' . $Items . ";"); to find the value of those in a preset array.
The actual usage is that the user makes a request for "site.com/var1/var2" and then those parameters get put into the string (in array format) so that I can get their value from the $URL array. I'm evaling in order to get the value from the array (since the array string is a string) and I feel that there's a better way to do it.
That brings me onto my second question, if i'm removing all of these ("'", "`", "$", "&", "(", ")", "{", "}", "[", "]", "?", ";", '"', "%") from the eval'd string, is it safe?
[QUOTE=Dorkslayz;42099738]if i'm removing all of these ("'", "`", "$", "&", "(", ")", "{", "}", "[", "]", "?", ";", '"', "%") from the eval'd string, is it safe?[/QUOTE]
Probably not.
In reality you can't do a safe eval query unless it involves no user input whatsoever.
[editline]6th September 2013[/editline]
Basically, if you're using eval, [I]you're probably doing something wrong[/I].
[QUOTE=Dorkslayz;42099738]This isn't something i'm stuck on, but I feel like it's something I can do better.
I'm using PHP and in my code i'm getting elements from the URL and concatenating them into a string in an array format (e.g. "['var1']['var2']") so that I can then eval that (e.g. eval('echo $Variable' . $Items . ";"); to find the value of those in a preset array.
The actual usage is that the user makes a request for "site.com/var1/var2" and then those parameters get put into the string (in array format) so that I can get their value from the $URL array. I'm evaling in order to get the value from the array (since the array string is a string) and I feel that there's a better way to do it.
That brings me onto my second question, if i'm removing all of these ("'", "`", "$", "&", "(", ")", "{", "}", "[", "]", "?", ";", '"', "%") from the eval'd string, is it safe?[/QUOTE]
I think it's a little unclear on what are you trying to achieve, could you please try elaborating further? You might as well just post some example code. What does the URL array consist of?
Also, it appears to me like you for some reason only know the variable's name [ eval('echo $Variable') ]. You don't need to eval for that - just do it like this:
[code]
$foo = 5;
...
$varName = "foo";
echo $$varName;
[/code]
[IMG]http://i.imgur.com/fyAvYoh.png[/IMG]
Sorry if I misunderstood. As I probably have.
Why can't you just use "[URL="http://php.net/manual/en/function.explode.php"]explode[/URL]" or a string split function to get the values?
General C# inquiry here. What would be the most efficient approach to implementing new "Readers" using interfaces and classes?
This is what I do so far. First, there's a master "Spooler" class, which has some basic functions to store offset, size, just stuff like that. It also allows to create a view accessor sing MemoryMappedFile. It's a sealed "base" class, which is what the other little "Readers" need to be attached to. Here's a [B]partial[/B] bit of code from the only reader I have so far:
[code]
public class ChunkSpooler : ISpooler, IDisposable
{
protected Spooler _mainSpooler;
protected struct DataStruct
{
public uint Magic;
public uint Offset;
public byte Unk1;
public byte StrLen;
public byte Unk2;
public byte Unk3;
public uint Size;
}
DataStruct Data;
// Required
public void ReadData()
{
this._mainSpooler.ReadSpoolerData<DataStruct>(ref this.Data);
}
public ChunkSpooler(SpoolableFileStream file, Spooler parent, uint offset, uint size)
{
this._mainSpooler = new Spooler(file, parent, offset, size);
this.ReadData();
}
}
[/code]
The "ISpooler" interface is just a simple interface that requires every ISpooler contain ReadData().
Next I have a generic extension that will read the DataStruct from each reader. I had to resort to marshaling in order to get it to read structures correctly.
[code]
namespace DSC.IO
{
public static class SpoolerExtensions
{
public static void ReadSpoolerData<T>(this Spooler spooler, ref T dataStruct) where T : struct
{
byte[] buffer = new byte[Marshal.SizeOf(typeof(T))];
using (MemoryMappedViewAccessor f = spooler.FileStream.CreateSpoolerView(spooler))
{
f.ReadArray<byte>(0, buffer, 0, buffer.Length);
}
GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
T tmp = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
handle.Free();
dataStruct = tmp;
}
}
}
[/code]
Again, this works just fine. It can be called like this:
[code]
using (SpoolableFileStream ChunkFile = new SpoolableFileStream(@"C:\Program Files (x86)\Atari\DRIV3R\Vehicles\miami.vvs", "SPL01"))
{
Console.WriteLine(ChunkFile.Filename);
Console.WriteLine(ChunkFile.Name);
ChunkSpooler MySpooler = new ChunkSpooler(ChunkFile, null, 0x1010, 10);
Console.WriteLine(MySpooler.ToString());
}
[/code]
Should I continue doing things like this or is there something I should do differently? I'm trying to make a clean set of tools that have plugin-like capabilities. It should be a piece of cake to add in new file formats that are not understood yet. Hence why I created this "Spooler" interface to manage the chunk files in the Driver games. There's other structures that may look like this:
[code]
struct AnotherStruct
{
uint ASMagic;
}
struct DataStruct
{
uint Magic;
uint Something;
uint Something2;
uint Something3;
AnotherStruct moreData;
}
[/code]
I have no encountered the need for these type of structures yet. But after 3 rewrites of my chunk loader, maybe 4th (didn't count), I'm tired of fixing major functions over and over again. I just want to get it right. So if anyone has resources for Marshaling or any personal advice for me, that'd be great. Hopefully before I blow my computer up somehow :v:
Oh yeah, here's the only useful article I found on structs: [url]http://www.developerfusion.com/article/84519/mastering-structs-in-c/[/url]
Can someone explain the difference between WinForms and WPF? I've heard WPF is better, and supports .NET, which is why I'd like to know if using WPF over WinForms is good or not.
[QUOTE=Funley;42106647]Can someone explain the difference between WinForms and WPF? I've heard WPF is better, and supports .NET, which is why I'd like to know if using WPF over WinForms is good or not.[/QUOTE]
[I].NET[/I] supports both, as they are both accessible through the framework's libraries. Mono only supports WinForms.
WPF is a lot more flexible, there are not much limits on how you can format and composite data with XAML alone.
[QUOTE=Tamschi;42106683][I].NET[/I] supports both, as they are both accessible through the framework's libraries. Mono only supports WinForms.
WPF is a lot more flexible, there are not much limits on how you can format and composite data with XAML alone.[/QUOTE]
Nice :)
[QUOTE=khuba;42102362]I think it's a little unclear on what are you trying to achieve, could you please try elaborating further? You might as well just post some example code. What does the URL array consist of?
Also, it appears to me like you for some reason only know the variable's name [ eval('echo $Variable') ]. You don't need to eval for that - just do it like this:
[code]
$foo = 5;
...
$varName = "foo";
echo $$varName;
[/code]
[IMG]http://i.imgur.com/fyAvYoh.png[/IMG]
Sorry if I misunderstood. As I probably have.[/QUOTE]
Your solution looks very interesting, but I don't know how I can apply it to my code.
Okay, so.
User makes request to page.php?URL=page/index
Script gets the URL parameter and explodes it into an array (called URLSections)
URLSections is now an array with "page" and "index" inside of it
I need to look in the Routes array for page "index" inside of the "page" group.
So, I escape URLSections which contains the sections of the URL.
For each of the items in URLSections, I inject the value inside the string "['$Value']"
Then inside of an eval statement, I concatenate the string "$Routes" to the CurrentPath (more on this in the next steps) and then add the newly created string ("['$Value']") on the end and then check if it exists (if it doesn't exist, a variable is set to true which indicates that the script needs to go to the default entry within that group, so the default entry in the page group if index doesn't exist).
If it exists, then concatenate it onto the CurrentPath variable.
(Rinse and repeat for each member of the URLSections array)
Then I check if the value of the CurrentPath in the Routes array is an array, and if so go to the default.
Finally, I eval the value of the CurrentPath in the Routes array.
(The current path would look like "['page']['index']")
I would've posted a code example, but it might of been a bit hard to understand since i've got a bad habit of not commenting my code.
[editline]7th September 2013[/editline]
[QUOTE=eternalflamez;42103688]Why can't you just use "[URL="http://php.net/manual/en/function.explode.php"]explode[/URL]" or a string split function to get the values?[/QUOTE]
Ditto.
Wait so why do you need eval for this
Can anyone see what is up with my C# MergeSort?
[CODE]using System;
namespace MergeSort
{
class Program
{
static void Main(string[] args)
{
int[] input = { 1, 3, 33, 456, 3, 34, 3, 56, 3, 65, 3, 3, 76, 4, 5, 6, 7, 8, 45, 46, 44, 3};
int[] output = MergeSort(input, 0, (input.Length));
Console.WriteLine("Test output for mergesort:");
foreach (int t in output)
{
Console.Write(t.ToString() + ", ");
}
Console.ReadLine();
}
public static int[] Merge(int[] InputArray, int LowerBounds, int MidPoint, int UpperBounds)
{
int LeftTotal = MidPoint - LowerBounds;
int RightTotal = UpperBounds - MidPoint;
int[] LeftArray = new int[LeftTotal + 1];
int[] RightArray = new int[RightTotal + 1];
for (int i = 0; i < LeftTotal; ++i )
{
LeftArray[i] = InputArray[LowerBounds + i];
}
for (int j = 0; j < RightTotal; ++j)
{
RightArray[j] = InputArray[MidPoint + j];
}
LeftArray[LeftTotal] = int.MaxValue;
RightArray[RightTotal] = int.MaxValue;
int LeftCounter = 0, RightCounter = 0;
for (int k = LowerBounds; k < UpperBounds; ++k)
{
if (LeftArray[LeftCounter] < RightArray[RightCounter])
{
InputArray[k] = LeftArray[LeftCounter];
++LeftCounter;
}
else
{
InputArray[k] = RightArray[RightCounter];
++RightCounter;
}
}
return InputArray;
}
public static int[] MergeSort(int[] InputArray, int LowerBounds, int UpperBounds)
{
if (LowerBounds < UpperBounds)
{
int MidPoint = (LowerBounds + UpperBounds) / 2;
InputArray = MergeSort(InputArray, LowerBounds, MidPoint);
InputArray = MergeSort(InputArray, MidPoint + 1, UpperBounds);
InputArray = Merge(InputArray, LowerBounds, MidPoint, UpperBounds);
return InputArray;
}
else
{
return InputArray;
}
}
}
}[/CODE]
[QUOTE=Banana Lord.;42108582]Wait so why do you need eval for this[/QUOTE]
Because the value that needs to be found in the array is a string - "['page']['index']".
[QUOTE=Dorkslayz;42109026]Because the value that needs to be found in the array is a string - "['page']['index']".[/QUOTE]
I'm still not getting this. If you can do whatever by executing arbitrary PHP code based on user input why can't you just do it without the potential to let visitors run PHP
[QUOTE=Banana Lord.;42109770]I'm still not getting this. If you can do whatever by executing arbitrary PHP code based on user input why can't you just do it without the potential to let visitors run PHP[/QUOTE]
Because I was having trouble converting that string into essentially, code.
However, I think I may of found a solution.
[QUOTE=Dorkslayz;42110043]Because I was having trouble converting that string into essentially, code.
However, I think I may of found a solution.[/QUOTE]
I don't understand why are you using eval either.
I thought this would do the trick?
[code]
$array = array(
"key" => array(
"subkey" => "value"
)
);
$first = "key";
$second = "subkey";
echo $array[$first][$second];
[/code]
[QUOTE=khuba;42111321]I don't understand why are you using eval either.
I thought this would do the trick?
[code]
$array = array(
"key" => array(
"subkey" => "value"
)
);
$first = "key";
$second = "subkey";
echo $array[$first][$second];
[/code][/QUOTE]
There could be more that one item, e.g. "key/subkey/subkey", which is why I can't just limit it to two factors.
[QUOTE=Dorkslayz;42111430]There could be more that one item, e.g. "key/subkey/subkey", which is why I can't just limit it to two factors.[/QUOTE]
There's a simple solution for that, too.
[code]
$source = array(
"key" => array(
"subkey" => array(
"subsubkey" => array(
"page" => "mysterious value"
)
)
)
);
function extractOrFail($sourceArray, $inputArray) {
$last = $sourceArray;
foreach ($inputArray as $inputValue) {
if (!isset($last[$inputValue])) {
return false; // There is no such a sub-key for this array, the input array/link is invalid.
}
$last = $last[$inputValue]; // We must go deeper.
}
return $last;
}
var_dump(extractOrFail($source, array("key", "subkey", "subsubkey", "page")));
var_dump(extractOrFail($source, array("key", "icecream", "subsubkey", "page")));
[/code]
Output:
[code]
string(16) "mysterious value"
bool(false)
[/code]
Update:
I'm trying the solution that khuba suggested earlier, but i'm running into issues.
I'm running this code (where $Value is the element of the url, such as account, or index).
[code]
$RoutePath = '$Routes' . $CurrentPath . "['$Value']";
var_dump($$RoutePath);
[/code]
The issue is that the var_dump is only outputting null and i'm getting the error "Undefined variable: $Routes['account']".
When I try to var_dump $Routes['account'] normally, it works fine.
[QUOTE=Dorkslayz;42111596]Update:
I'm trying the solution that khuba suggested earlier, but i'm running into issues.
I'm running this code (where $Value is the element of the url, such as account, or index).
[code]
$RoutePath = '$Routes' . $CurrentPath . "['$Value']";
var_dump($$RoutePath);
[/code]
The issue is that the var_dump is only outputting null and i'm getting the error "Undefined variable: $Routes['account']".
When I try to var_dump $Routes['account'] normally, it works fine.[/QUOTE]
I didn't check if you can use array indexes in combination with $$ but it wouldn't really make any sense at all if you could. The indexing operator is separate of the variable's name, therefore PHP correctly informs you that there is no variable with such a name. Just fetch the array object first and apply the indexer to that one instead:
[code]
$Value = "account";
$CurrentPath = "";
$Routes = array(
"account" => 123
);
$ArrayName = 'Routes' . $CurrentPath;
$ArrayObject = $$ArrayName; // PHP will throw up an error if you try to apply [$Value] directly to the double-dollared ArrayName, you need to do it this way
var_dump($ArrayObject[$Value]);
[/code]
[QUOTE=khuba;42111674]I didn't check if you can use array indexes in combination with $$ but it doesn't really make sense. The indexing operator is separate of the variable's name, therefore it correctly informs you that there is no variable with such a name. Just fetch the array object and apply the indexer to that one instead:
[code]
$Value = "account";
$CurrentPath = "";
$Routes = array(
"account" => 123
);
$ArrayName = 'Routes' . $CurrentPath;
$ArrayObject = $$ArrayName; // PHP will throw up an error if you try to apply [$Value] directly to the double-dollared ArrayName, you need to do it this way
var_dump($ArrayObject[$Value]);
[/code][/QUOTE]
Okay, so i'm doing this now.
[code]
$RoutesPath = '$Routes' . $CurrentPath;
$RouteObject = $$RoutePath;
var_dump($RouteObject['account']);
[/code]
and i'm still getting the error.
If I can't get this to work then i'll use the other solution you posted, but doing it this way would fit in with my current code better.
[QUOTE=Dorkslayz;42111734]Okay, so i'm doing this now.
[code]
$RoutesPath = '$Routes' . $CurrentPath;
$RouteObject = $$RoutePath;
var_dump($RouteObject['account']);
[/code]
and i'm still getting the error.
If I can't get this to work then i'll use the other solution you posted, but doing it this way would fit in with my current code better.[/QUOTE]
Typo. Change $$RoutePath to $$RoutesPath :v:
[QUOTE=khuba;42111751]Typo. Change $$RoutePath to $$RoutesPath :v:[/QUOTE]
Fixed, but still getting errors i'm afraid.
[code]
Notice: Undefined variable: $Routes
[/code]
[QUOTE=Dorkslayz;42111781]Fixed, but still getting errors i'm afraid.
[code]
Notice: Undefined variable: $Routes
[/code][/QUOTE]
Forgot to mention you don't put the leading dollar sign in. Just the name itself without the $.
Sorry, you need to Log In to post a reply to this thread.