Recent Entries 10
- pattern minor 112d agoUsing events together with interfaces in VBAIntroduction Because of the limitation of VBA in using events in interfaces I was searching for a kind of workaround. For sure I also read this which also provides an approach, but I was searching for an easier way. I ended up with the following solution. The idea behind Instead of defining the events directly in an interface - because it is not possible to use them in an implementing class in VBA - I use an additional 'event' class, where all necessary events will be placed in, and which will be injected into the interface implementing classes. Naming of the event class I'm aware of that this class is not really used as an interface, but it only should be used with the regarding interface. So I named it also with an `I` prefix. Another benefit of this is that it will be listed beneath the regarding interface. Circular references The worker object is provided with the event on purpose. As long as it is used in the event handler with care, that means, it should not be stored anywhere else, there shouldn't be any risk regarding circular references. The interfaces IWorker ``` Option Explicit Public Property Set Events(ByRef value As IWorkerEvents) End Property Public Sub Work() End Sub ``` IWorkerEvents ``` Option Explicit Public Event Notify(ByRef worker As IWorker, message As String) Public Sub Notify(ByRef worker As IWorker, message As String) RaiseEvent Notify(worker, message) End Sub ``` The implementations Worker1 ``` Option Explicit Implements IWorker Private Type TWorker Events As IWorkerEvents End Type Private this As TWorker Private Property Set IWorker_Events(RHS As IWorkerEvents) Set this.Events = RHS End Property Private Sub IWorker_Work() Debug.Print "Worker 1 works hard." Notify "is working..." End Sub Sub Notify(ByVal message As String) If Not this.Events Is Nothing Then this.Events.Notify Me, message End If End Sub ``` Worker2 ``` Option Explicit Implements IWorker Private Type TWorker
- debug minor 112d agoTrie implementation for a data structure library in CI'm implementing a trie structure for a library, as an exercise in data structures. Details The tree structure is represented as a doubly chained tree. A struct `trie` represents a node of the trie, and contains the following: - `key` is the character represented by the node. Since keys are expected to be `\0`-terminated strings, a node with a key value of `\0` is a leaf node. - `sibling` is the next sibling of the node. - `child` is the first child of the node. - `val` at a leaf node is the value associated with the key string that terminates at that node. This is expected to be `NULL` on internal nodes. The following methods are implemented: - `trie_init` initialises and returns a trie. - `trie_insert` inserts value `val` into trie `t` with key `k`. - `trie_finsert` makes a copy of the first `size` bytes after `val` to some `new_val`, then adds `new_val` to trie `t` with key `k`. If there is already a value associated with `k`, a destructor function `f` is called on the old value before it is overwritten. - `trie_remove` removes the value associated with key `k` from trie `t`. - `trie_fremove` calls `f` on the value associated with key `k` in trie `t` before removing it. - `trie_seek` searches trie `t` for a value associated with key `k`. Returns it if it is found, returns `NULL` otherwise. - `trie_match` searches trie `t` for all values associated with keys that have prefix `k`, and appends them to a vector `v` in alphabetic order (for instance, doing `trie_match(t, “te”, v)` on the trie in the example as it appears just before it is destroyed will add `”TWO”` and `”EIGHT”` to `v`, in that order.) - `trie_list` is just shorthand for `trie_match(t, “”, v)` and appends all the elements in `t` to `v`. - `trie_dump` prints the structure of the trie. - `trie_dumps` prints the structure of the trie, and also prints the values interpreting them as pointers to `\0`-terminated strings. - `trie_free` destroys a trie. - `trie_ffree` calls `f`
- pattern minor 112d agoFetching files or directories in a given directoryThis is a self-teaching implementation to get files for a given directory in order to simplify `os.Walk` in Go (avoid to pass a func for recursively walking across the files and directories). I'm pretty new to the language and feel there is already something wrong with the way the structure ""implements"" the interface. I feel that it should not be by value but rather by reference in order to avoid redundant copies, should it? ``` package main import ( "os" "fmt" "path/filepath" "time" ) type FileDetail interface { Path() string Info() os.FileInfo } type fileDetail struct{ path string info os.FileInfo } func (detail fileDetail) Path() string { return detail.path } func (detail *ileDetail) Info() os.FileInfo { return detail.info } func GetFiles(path string) []FileDetail { var details []FileDetail walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error { if err != nil { return err } if !fileInfo.IsDir() { var detail FileDetail = fileDetail{path: filePath, info: fileInfo} details = append(details, detail) } return nil } filepath.Walk(path, walkFunc) return details } func GetDirectories(path string) []FileDetail { var details []FileDetail walkFunc := func (filePath string, fileInfo os.FileInfo, err error) error { if err != nil { return err } if fileInfo.IsDir() { var detail FileDetail = fileDetail{path: filePath, info: fileInfo} details = append(details, detail) } return nil } filepath.Walk(path, walkFunc) return details } func main() { sandBoxDirectory := "F:/Perforce/eperret/XLC/R6Code/framework/source/scimitar/onlinemodule/Sandbox" time.Now() files := GetFiles(sandBoxDirectory) for index, file := range files { fileInfo := file.Info() fmt.Println(index, file.Path())
- pattern minor 112d agoA simple program which returns specific value from arrayAfter researching for an hour regarding SOLID Principles, I tried to do it myself. Please note that most of these codes were from the ideas of others. I created a simple program which returns specific value from array, depends on what you choose. ``` public interface IArrayPerformer { int GetAnswer(int[]arr); } public class HighestNumber : IArrayPerformer { public int GetAnswer(int[] arr){ //return highest number } } public class LowestNumber : IArrayPerformer { public int GetAnswer(int[] arr) { //return lowest number } } public class MiddleNumber : IArrayPerformer { public int GetAnswer(int[]arr) { // return middle number } } public class HighestPrimeNumber : IArrayPerformer { public int GetAnswer(int[] arr) { // return highest prime number } } public class LowestPrimeNumber : IArrayPerformer { int GetAnswer(int[] arr) { // return lowest prime number } } ``` Then, I created a class and enum which only purpose is to choose what action to be done in arrays.. ``` class ActionChooser { public IArrayPerformer imath(MathAction mathAction) { IArrayPerformer getMath = null; switch(mathAction) { case MathAction.HighestNumber: getMath = new HighestNumber(); break; case MathAction.LowestNumber: getMath = new LowestNumber(); break; case MathAction.MiddleNumber: getMath = new MiddleNumber(); break; case MathAction.LowestPrimeNumber: getMath = new LowestPrimeNumber(); break; case MathAction.HighestPrimeNumber: getMath = new HighestPrimeNumber(); break; } return getMath; } } public enum MathAction { LowestNumber = 1, HighestNumber = 2, MiddleNumber = 3, LowestPrimeNumber = 4, HighestPrimeNumber = 5 } ``` Lastly, I created a class for making it all possible
- pattern minor 112d agoClasses representing items in an RPG gameI wrote a little program in C# that contains classes representing Items in RPG game. I wanted to have access to all inherited classes parameters from list contains parent Item class instances, so this is my code: ``` using System; using System.Collections.Generic; public interface SpecialObject { int GetIntParameter { get; } } public interface ElementalsObject { int[] GetElementalsParameters { get; } } public class Item { private string _name; private int _cost; public string name { get { return _name; } } public int cost { get { return _cost; } } public Item(string name, int cost) { _name = name; _cost = cost; } } public class Weapon : Item, SpecialObject, ElementalsObject { private int dmgs; private int[] elementalsDmgs; public int GetIntParameter { get { return dmgs; } } public int[] GetElementalsParameters { get { return elementalsDmgs; } } public Weapon(string name, int cost, int dmgs, int[] elementalsDmgs = null) : base(name, cost) { if (elementalsDmgs != null) this.elementalsDmgs = elementalsDmgs; else this.elementalsDmgs = new int[] { 0, 0, 0, 0 }; this.dmgs = dmgs; } } public class Armor : Item, SpecialObject, ElementalsObject { private int armorPts; private int[] elementalsArmorPts; public int GetIntParameter { get { return armorPts; } } public int[] GetElementalsParameters { get { return elementalsArmorPts; } } public Armor(string name, int cost, int armorPts, int[] elementalsArmorPts = null) : base(name, cost) { if (elementalsArmorPts != null) this.elementalsArmorPts = elementalsArmorPts; else this.elementalsArmorPts = new int[] { 0, 0, 0, 0 }; this.armorPts = armorPts; } } public class Food : Item, SpecialObjec
- pattern minor 112d agoGenerating RPG Characters (Objects)I am a beginner Java programmer. I have just finished up an assignment and would appreciate some advice and/or constructive criticism on my program. I am trying to ensure I do not advance my knowledge using bad practices. For context, I have the assignment details, followed by the full code below: Part 1: Write an abstract Human class that implements the Human interface above. You’ll need to include the interface in your project. Part 2: Implement the Knight and Wizard classes. Part 3: Write a test program called LastNameWorld, which: - Declares 4 Humans - Instantiates a Knight - Instantiates a Wizard and moves it - Clones the Knight and changes its name - Checks if the Knight clone is not equal to the original Knight, and if so: moves the clone - Clones the Wizard - Checks if the Wizard clone is equal to the original Wizard, and if so: moves the clone - Prints the total number of Humans living in this World - Prints a description (toString) of all Humans to the console Part 4: Add a third Human (e.g. Archer, King, Queen, Paladin, etc) type class to your simulation. This class must contain an equals and a clone method. Add code to your test harness to fully test your new class. Main Class ``` public class BakosWorld { public static void main(String[] args) { // Declare 4 humans Human[] humans = new Human[4]; // Create original knight and wizard, then move wizard humans[0] = new Knight("Rob", 36, 100, 6.1, 50, 50, "Grey Wind"); humans[1] = new Wizard("Gandalf", 32, 80, 5.11, 25, 25, 50); humans[1].move(45, 45); // Creating a new knight, that is a clone of the first knight humans[2] = ((Knight) humans[0]).clone(); // Checks to see if the two knights are NOT equal if (((Knight) humans[0]).equals(((Knight) humans[2])) == false) { humans[2].move(85, 85); } // Creating a new wizard, that is a clon
- pattern minor 112d agoGenerating 50 Random ShapesI am a beginner Java programmer. I have just finished up an assignment and would appreciate some advice and/or constructive criticism on my program. For context, I have the assignment details, followed by the full code below: The Shape interface is as follows: ``` public interface Shape { public double area(); public double perimeter(); public double getXPos(); public double getYPos(); public void move(double xLoc, double yLoc); public String toString(); } ``` An AbstractShape has the following attributes: - xPos - yPos An AbstractShape has the following behaviour: - move(x,y) - getXPos - getYPos - toString A Circle adds the following attributes: - radius A Circle adds the following behaviour: - area - perimeter - equals(Circle) - clone - updated toString A Rectangle adds the following attributes: - height - width A Rectangle adds the following behaviour: - area - perimeter - equals(Rectangle) - clone - updated toString Also include constructors in your classes. Write a test harness which generates 50 random Shapes, stores them in an array, then prints them out. Main Class: RandomShapes ``` public class RandomShapes { public static void main(String[] args) { // Creating the random variables double randX, randY, randRadius, randWidth, randHeight; // Array to store AbstractShapes AbstractShape[] shapes = new AbstractShape[50]; for (int i = 0; i < shapes.length; i++) { // Random number between 1-2 to decide rectangle, or circle int circleOrRect = (int) (Math.random() * 2 + 1); // Creating 6 random numbers randX = (int) ((Math.random() * 100) + 1); randY = (int) ((Math.random() * 100) + 1); randRadius = (int) ((Math.random() * 10
- pattern minor 112d agoAutomatic IEqualityComparer<T>There are APIs like the `Except` extension that require the `IEqualityComparer` to work. I find it's too much work for such a simple task to implement an interface so I thought why not automate it. I implemented this interface in a reusable fashion so that I can use it with any value and any number of properties. ``` internal class AutoEqualityComparer : IEqualityComparer { public AutoEqualityComparer(IEnumerable> selectors) { Selectors = selectors; } private IEnumerable> Selectors { get; } public bool Equals(T left, T right) { return !ReferenceEquals(left, null) && !ReferenceEquals(right, null) && Selectors.All(selector => selector(left).Equals(selector(right))); } public int GetHashCode(T obj) { unchecked { return Selectors .Select(selector => selector(obj).GetHashCode()) .Aggregate(17, (hashCode, subHashCode) => hashCode * 31 + subHashCode); } } } ``` I then build a new extension which also can accept any number of selectors to compare: ``` internal static class Enumerable { public static IEnumerable Except( this IEnumerable first, IEnumerable second, params Func[] compare) { var mec = new AutoEqualityComparer(compare); return first.Except(second, mec); } } ``` Example: Select all properties of an exception that are not in the base exception: ``` var exceptionProperties = typeof(ArgumentException) .GetProperties() .Except(typeof(Exception).GetProperties(), x => x.Name); // result: ParamName is the only property ```
- pattern minor 112d agoAnimals, inheritance and interfacesI am trying to fully understand interfaces and abstract classes in Java and from what I understood, I created a sample console application. Is there an error in the design or is this basically what interfaces and abstract classes are? Animals.java (interface): ``` interface Animals { void callSound(); int run(); } ``` Feline.java (abstract class): ``` abstract class Feline implements Animals { @Override public void callSound() { System.out.println("roar"); } } ``` Canine.java (abstract class): ``` abstract class Canine implements Animals { @Override public void callSound() { System.out.println("howl"); } } ``` Lion.java (class): ``` class Lion extends Feline { @Override public void callSound() { super.callSound(); } @Override public int run() { return 40; } } ``` Cat.java (class): ``` class Cat extends Feline { @Override public void callSound() { System.out.println("meow"); } @Override public int run() { return 30; } } ``` Wolf.java (class): ``` class Wolf extends Canine { @Override public void callSound() { super.callSound(); } @Override public int run() { return 20; } } ``` Dog.java (class): ``` class Dog extends Canine { @Override public void callSound() { System.out.println("woof"); super.callSound(); } @Override public int run() { return 10; } } ``` Main.java: ``` public class Main { public static void main(String[] args) { Animals[] animals = new Animals[4]; animals[0] = new Cat(); animals[1] = new Dog(); animals[2] = new Wolf(); animals[3] = new Lion(); for (int i = 0; i < animals.length; i++) { animals[i].callSound(); } } } ```
- pattern minor 112d agoAn ordered set in C#I need a generic data structure that ensures that its elements are unique. C# has `HashSet`, great! As it turns out, the elements have to stay in the order in which they were added, too. This sounds more like `List`. I tried to create my own: ``` using System.Collections; using System.Collections.Generic; namespace Collections.Generic { public class HashSetList : IList { private List _list; private HashSet _set; public HashSetList() { _list = new List(); _set = new HashSet(); } public int IndexOf(T item) { return _list.IndexOf(item); } public void Insert(int index, T item) { if (_set.Add(item)) { _list.Insert(index, item); } } public void RemoveAt(int index) { _set.Remove(_list[index]); _list.RemoveAt(index); } public T this[int index] { get { return _list[index]; } set { if (_set.Add(value)) { _list[index] = value; }; } } public void Add(T item) { if (_set.Add(item)) { _list.Add(item); } } public void Clear() { _list.Clear(); _set.Clear(); } public bool Contains(T item) { return _set.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public int Count { get { return _list.Count; } } public bool IsReadOnly { get { return false; } } public bool