Recent Entries 10
- principle minor 112d agoDoodlebug vs. ant population simulationI am looking for a review on one of my homework assignments for this semester. This homework has already been submitted and graded and my final has already been submitted so there is no cheating or conflict of interest in my review request! I would love some advice on how to better manage my class interactions and how to better encapsulate data. The specific area I struggle with is when using parent classes and giving access to only protected assets from child classes. My professor has mentioned on several occasions that it would be much better to keep data private and give access through functions, but how would I initialize those member variables when instantiating an instance of a child class that has private members in the parent class? I understand the idea of encapsulation is to protect data that shouldn't be manipulated by outside programmers or irrelevant classes. I was the sole developer on this project so I understand in this specific example encapsulation may not be paramount, but on a larger project with multiple engineers it would certainly be relevant. Includes ``` #include "stdafx.h" #include #include #include using namespace std; ``` ** Note the coordinates struct just contains an integer xCoordinate and an integer yCoordinate main ``` int main() { //Create environment object containing environment antDoodlebugSimulation; antDoodlebugSimulation.InitializeSimulation(); return 0; } ``` Environment ``` class environment { //friends of environment friend class organism; friend class doodlebug; friend class ant; private: organism * environmentBoard[20][20]; void CreateStartPopulation(); int GenerateRandomStartingLocations(int min, int max); void OutputCurrentEnvironment(); void DoodlebugsAct(); void AntsAct(); void ResetCritterTimeStep(); public: //constructor environment(); //deconstructor ~environment(); //public member functions void Initializ
- pattern minor 112d agoPerlin Noise terrain in Unity3DI've recently had time to devise another program so this time I decided to write the Perlin Noise algorithm in code. I have succeeded and the code works but I can't help but feel that my practices while writing are still not as good as they should be (especially since I'm still pretty new to the topic of programming). Please note that as I am working in Unity I have not separated the class files that I wrote into different source files. The code is comprised of a total of 3 class files: the main MonoBehaviour class named perlin_terrain and the two I have declared - named "Grid" and "Point". ``` using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class perlin_terrain : MonoBehaviour { public Terrain terrain; public int gridResolution = 512; // Will be adjusted to be divisible by the subdivision value. public int gridSubdivision = 4; // Value must be a power of 2. [Range(0, 1)] public float steepness = 0.12f; Grid grid; private static float[,] heights; // Use this for initialization void Start() { if (gridResolution unitPoints = new List(); unitPoints = getUnitPoints(x, y); int n = 0; foreach (Point point in unitPoints) { switch (n) { case 0: value1 = Vector2.Dot(point.GradientVector, distanceVectors[0]); break; case 1: value2 = Vector2.Dot(point.GradientVector, distanceVectors[1]); break; case 2: value3 = Vector2.Dot(point.GradientVector, distanceVectors[2]); break; case 3: value4 = Vector2.Dot(point.GradientVector, distanceVectors[3]); break; } n++; } weighed1 = Mathf.Lerp(value1, value2, fadeValue(pointX)); weighed2 = Mathf.Lerp(val
- pattern minor 112d agoBeginner Python OOP web scraperI started learn OOP in Python. I have OOP basics in Java and apparently I have a problem with thinking in OOP in Python (and using the best functionalities and syntax). I have doubts about my OOP design in web scraping for a local book review page. So the basic idea is scraping information about book with the user reviews for that books. The structure of the Python package: ``` /bookscraper __init__.py book.py comment.py parsers.py ``` parsers.py: ``` from urllib.request import urlopen from bs4 import BeautifulSoup from bookscraper.book import Book from bookscraper.comment import Comment class Parser: def __init__(self, url, name, search_url): self.url = url self.name = name self.search_url = search_url class DatabazeKnih(Parser): PAGE_URL = 'http://www.databazeknih.cz/' NAME = 'Databáze knih' SEARCH_URL = 'search?q={}&hledat=&stranka=search' def __init__(self): super().__init__(DatabazeKnih.PAGE_URL, DatabazeKnih.NAME, DatabazeKnih.SEARCH_URL) def search(self, name): self.search_html = urlopen(DatabazeKnih.PAGE_URL + DatabazeKnih.SEARCH_URL.format(name)) self.book_link = DatabazeKnih.PAGE_URL + self.get_book_link() + '?show=alldesc' return self.get_book_info() def get_book_page(self): return urlopen(self.book_link) def get_book_link(self): soup = BeautifulSoup(self.search_html, 'html.parser') return soup.find(type='book').attrs['href'] @staticmethod def parse_comment(comment): user = comment.find('a').string text = comment.find('p', {'class': 'odtopm new2 justify'}).text date = comment.find('span', {'class': 'pozn_lightest odleft_pet'}).string return user, text, date @staticmethod def get_comments(soup): comments_objects = [] comments = soup.find_all('div', {'class': 'komholdu'}) for comment in comments: user, text, date = DatabazeKnih.parse_com
- 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
- pattern minor 112d agoPython solution to Mars RoverI'm still quite new to Python, but am loving the language (I come from a more strongly-typed language background..). A month or so ago I found the Mars Rover Challenge and attempted to solve it. I quite quickly managed to solve the problem, but in all honesty I can't help but feel like there is a lot of code-smells in my solution. Could I get some help on ways to refactor functions and (if possible) add polymorphism to the classes to make it easier to extend on them? Overall feedback would be great too! main.py ``` #!/usr/bin/env python3 from Rover import Rover, directions from Mars import Mars import re def validate_int(x, y): """ Validate that the two parameters are integers. Re-used multiple times during the execution. """ try: if int(x) >= 0 and int(y) >= 0: return True except Exception as err: print("Only numerical elements. Try again!") return False def validate_rover(x, y, direction): """ Validates a rover to ensure the parameters are correct datatypes(int, int, string). It also controls ensures that the integers are inside the Mars surface and that the supplied direction is a correct direction. """ try: if validate_int(x, y) and direction in directions: return True except ValueError as err: print("Error: {}\n. Please enter two numbers followed by a char either N, E, S or W\nTry again!".format(err)) return False print("You seem to have entered an incorrect Rover.\nPlease enter two numbers followed by a char either N, E, S or W\nTry again!\n") return False def validate_operations(op): """ Uses regex to validate that the supplied string only contains 'M', 'R' and 'L'. Raises a ValueError if incorrect operation(s) have been supplied. """ pattern = re.compile("^[MRL]*$") if pattern.match(op): return True else: raise ValueError("Only values 'L', 'M' or 'R' a
- pattern minor 112d agoFile selection button for Jupyter notebookBackground This is a feature that I have wanted to see in Jupyter notebook for quite some time. I'm sure that others have built similar things but I haven't been able to find them on SO, Github, CodeReview or the rest of the searchable internet. Approach I used `ipywidgets.Button` as a base class and added a traitlet called files. This traitlet receives a list of files as strings from `tkinter.filedialog.askopenfilename`. When the button is clicked the file dialog pops up the user selects files and then can access that list of strings as an attribute/traitlet on the button instance. ``` import traitlets from ipywidgets import widgets from IPython.display import display from tkinter import Tk, filedialog class SelectFilesButton(widgets.Button): """A file widget that leverages tkinter.filedialog.""" def __init__(self): super(SelectFilesButton, self).__init__() # Add the selected_files trait self.add_traits(files=traitlets.traitlets.List()) # Create the button. self.description = "Select Files" self.icon = "square-o" self.style.button_color = "orange" # Set on click behavior. self.on_click(self.select_files) @staticmethod def select_files(b): """Generate instance of tkinter.filedialog. Parameters ---------- b : obj: An instance of ipywidgets.widgets.Button """ # Create Tk root root = Tk() # Hide the main window root.withdraw() # Raise the root to the top of all windows. root.call('wm', 'attributes', '.', '-topmost', True) # List of selected fileswill be set to b.value b.files = filedialog.askopenfilename(multiple=True) b.description = "Files Selected" b.icon = "check-square-o" b.style.button_color = "lightgreen" ``` Example Usage Displaying the button ``` my_button = SelectFilesButton() my_button # This will display the button in t
- pattern minor 112d ago(REALLY) simple neural network programThis is a simple program to create neural networks. It only includes weighting of connections and activation values for the neurons. It doesn't include any learning feature of any kind, and it is really just a first attempt at creating something resembling a neural network. Main.java ``` package uniliniarnetwork; public class Main { public static void main(String[] args) { Neuron inputNode = new Neuron(0,1,"InputNode",1); Neuron hiddenNode_One = new Neuron(0.5f,0.9f,"HiddenNode_One",1); Neuron hiddenNode_Two = new Neuron(0.5f,0.9f,"HiddenNode_Two",1); Neuron hiddenNode_Three = new Neuron(0.5f,0.9f,"HiddenNode_Three",1); Neuron outputNode = new Neuron(0,0.9f,"OutputNode",3); inputNode.connect(hiddenNode_One); inputNode.connect(hiddenNode_Two); inputNode.connect(hiddenNode_Three); hiddenNode_One.connect(outputNode); hiddenNode_Two.connect(outputNode); hiddenNode_Three.connect(outputNode); inputNode.input(1); } } ``` Neuron.java ``` package uniliniarnetwork; import java.util.ArrayList; public class Neuron { private float activationValue, weight; private String neuronName; private ArrayList outputs = new ArrayList(); private float[] inputs; int inputCounter = 0, nInputs; public Neuron(float activationValue, float weight, String neuronName, int nInputs){ this.activationValue = activationValue; this.weight = weight; this.neuronName = neuronName; this.nInputs = nInputs; inputs = new float[nInputs]; } public void connect(Neuron neuron){ outputs.add(neuron); } public void input(float inputValue){ inputs[inputCounter] = inputValue; inputCounter++; if(inputCounter == nInputs){ fire(); } } public void fire(){ float sum = 0; for(int i = 0; i activationValue){ for(int i = 0; i < outputs.size(); i++){ outputs.get(i).input(signal); } } else{ for(int i = 0; i < outputs.size(); i++){ outputs.get(i).input(0);
- snippet minor 112d agoConvert MQTT messages and publish them to Rabbit MQI'm looking for advice on how to find a balance between keeping this code flexible/maintainable, while also keeping it readable. It reads MQTT messages in JSON format from four different topics, converts the JSON into a different JSON format, and publishes it to a common Rabbit message queue. One of the topics, the sensor status topic, has messages in four different formats (four different sensor types publish their status in that topic). In its original form the code is very straightforward and contained in a single class, however the class grows in size for each new sensor or topic added to it. My first decision to improve it was to create two message handler factories, one for the four topics and one for the special sensor topic, but then I thought using only one factory for both was better. The bad thing about the factory is that it must be injected with a lot of arguments in order to perform its duty, which is to pass those arguments to the instantiated message handlers. I don't know how can I improve that. It seems to be a limitation of the Simple Factory "pattern" (not a real pattern though). Two real patterns have also been applied to the code: Template Method (in `ConvertingPublisherHandler`) and Decorator (implemented in `LoggingRabbitPublisher` and used in `ConvertingPublisherHandler`). Regarding Decorator, it is my first time applying it and I'm not sure if it is the best solution to the problem. I wanted to log both the original MQTT message and the converted JSON message in pairs, along with a line separator, so this is what the decorator does. This, however, caused the factory to receive a lot of arguments thus it is not very readable. Regarding Template Method, I'm not sure if it is the most flexible solution to adopt. Firstly because the pattern is not very flexible by itself (it relies on inheritance and also freezes the sequence of methods it calls). Secondly because I took advantage of the common behavior for all messages that is to convert
- pattern minor 112d agoDesigning classes for non-standard arithmeticsThis question is inspired by http://anydice.com - a dice probability calculator web application. Anydice language has three run-time types: a number, a sequence and a die. There is also a number of unary and binary operations defined on these types. Each binary operation can take any type pair (out of the 3) as arguments, there are separate definitions of what each operation does for each possible pair of types. Some operations are not commutative. For simplicity let's consider a single binary operation, which I'll call `OpAccess`, or `@`. My goal is to design a set of classes that represent the run-time values, so that if the access operation is executed on two of such values the correct operation implementation (depending on argument types) is called. The main problem is that at compile time it is not known yet what run-time type a value has, yet, it's required to dispatch the correct operation implementation during the run-time. Let's start with defining the base class for our values: ``` abstract class Primitive { public abstract Primitive OpAccess(Primitive right); } ``` Our value will use itself as the left argument in the `OpAccess`operation and accept the right argument as the parameter. Having this base we can design our value classes as follows: ``` class Number : Primitive { public override Primitive OpAccess(Primitive right) { return OpAccess((dynamic)right); } public Primitive OpAccess(Number right) { Console.WriteLine("Number @ Number"); return null; } public Primitive OpAccess(Sequence right) { Console.WriteLine("Number @ Sequence"); return null; } public Primitive OpAccess(Die right) { Console.WriteLine("Number @ Die"); return null; } } class Sequence : Primitive { public override Primitive OpAccess(Primitive right) { return OpAccess((dynamic)right); } public Primitive OpAccess(Number right) { Console.WriteLine("Sequence @ Number"); return null; } public Primiti
- pattern minor 112d agoOOP implementation of BlackJack in JavaThis code is not done, but still fully functional. But, before I continue I'd really appreciate some input on the code-structure as is. AbstractHand.java ``` package com.tn.deck; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class AbstractHand { protected List hand = new ArrayList<>(); public void drawCard(T o) { hand.add(o); } public void drawCards(T[] o) { hand.addAll(Arrays.asList(o)); } public abstract void status(); public abstract int calculateScore(); } ``` Deck.java ``` package com.tn.deck; public interface Deck { T dealCard(); T[] dealCards(int n); void shuffle(); } ``` Rankable.java ``` package com.tn.deck; public interface Rankable> { boolean isConsecutive(T other); } ``` Suitable.java ``` package com.tn.deck; public interface Suitable> { boolean isSameSuit(T other); } ``` Card.java ``` package com.tn.blackjack; import com.tn.deck.Rankable; import com.tn.deck.Suitable; public class Card implements Suitable, Rankable, Comparable { private final Suit suit; private final Rank rank; Card(Suit suit, Rank rank) { this.suit = suit; this.rank = rank; } public Suit getSuit() { return suit; } public Rank getRank() { return rank; } public void print() { System.out.printf("%s%s ", suit.getIcon(), rank.getName()); } @Override public boolean isConsecutive(Card other) { return 1 + rank.ordinal() == other.rank.ordinal() || rank.ordinal() - 1 == other.rank.ordinal(); } @Override public boolean isSameSuit(Card other) { return suit.equals(other.suit); } @Override public int compareTo(Card other) { if(rank.getValue() == other.getRank().getValue() && suit.getIcon().equals(other.getSuit().getIcon())) { return 0; } else if(rank.getValue() < other.getRank()