instruction
stringlengths
71
71.9k
I've dabbled with PHP for a couple of years, I can generally get what I need done and I've been teaching myself PDO. The problem is I want to set it up with classes but i'm not really sure how to. Below is my code, which takes data from a form, does some rough checking to see if the email is right and the fields are f...
I'm learning Scala and functional programming. Can I make it more functional? class Student(val firstname: String, val lastname: String) { override def toString: String = firstname + " " + lastname } class ClassRoom { var rows: List[Array[Student]] = List[Array[Student]]() var total: Int = _ def addRow(row: Arr...
I want to write my database access code for a Snap application in a way that makes the queries easy to test from the ghci repl, while also working within the Snap context. My solution so far is to define a HasPostgres instance for IO and to write all my DB access functions following the pattern of allUsers in the code ...
I've wrote this script to fetch and format content from my DB. It also counts how many result there are and separates them into pages. I'm barely learning PHP and MySQL so I don't know much about performance. function fetch_content($section, $subsection, &$count, $page = 0){ $section = substr($section, 0,8); $s...
How do you guys think I can improve the code for collision detection on my website asteroidfield.eu5.org? The current code is var dx = Math.abs(c1.getcx() - c2.getcx()); var dy = Math.abs(c1.getcy() - c2.getcy()); var dist = Math.sqrt((dx * dx) + (dy * dy)); if (dist - (c1.getR() + c2.getR()) <= 0) { if (done === fa...
I need to speed up this code: it creates a multilinear function. I considered the below methods but no idea which with the largest benefit. replacing dummy variables with things such as anonymous functions having all code in the same file (my instructor's hint) improving the looping: getting rid of num2str other? I n...
I am unit testing this role provider. I have a few asserts in the code for my test. I am sure there are more test I could preform. Does anyone have any suggestions for more test for this role of the membership provider? [TestMethod] public void TestDeleteUserAccess() { try { string s...
I want to adopt good coding habits now. the below code was written under tight constraints. We don't do assignment post mortems in class to discuss "real world" best practices -- we just get letter grades with little or no feedback. What are some examples of good questions I can ask myself to determine when code that...
I just have a somewhat simple question on coding practices. I have never written a large application before and I am currently working on building a game engine in JavaScript. The part that confuses me is what the best method of organization is in this particular case. I have my base engine class, Engine, a graphics cl...
def _getCallerLogger(): caller = inspect.currentframe().f_back.f_back name = "{}-{}".format(caller.f_globals['__name__'], caller.f_code.co_name ) logger = logging.getLogger(name) return logger log = lambda msg : _getCallerLogger().debug(msg) info = lambda msg: _getCallerLogger().info(msg) warning = lam...
I was asked to do a code review for the following block of code. It implemented a bug fix to prevent some values being added to some drop down lists depending on the user's domain, in an ASP.NET WebForms app. The three lines adding items to the lists were from the pre-bug-fix code (not part of the fix), so I didn't rev...
I am a huge proponent of self-documenting code (when at all possible). I prefer to have code be self evident by the very nature of the names of the variables, methods, etc. For instance: if (TheSky.IsBlue && TheGrass.IsGreen) BeHappy(); I have run into a situation that has defied all attempts to name the method i...
I am required to read the following text from a keyboard (stdin). Please note that it will be entered by the user from the keyboard in this format only. #the total size of physical memory (units are B, KB, MB, GB) 512MB 2 #the following are memory allocations { abc = alloc(1KB); ...
Is there a safer/ more readable way of using this code? I gotta translate this code into a better , safer and more readable sample of code and get my onclick to work.(its currently called from another thread then what it is created from.) public class TemperaturePresenter { MainView _view; // TODO ojoj det ble...
I am attempting to develop an XML schema (XSD) to represent a set of unit tests for some code. (Specifically, I am testing Oracle PL/SQL stored procedures.) I would like to have something that represents: the procedure itself the data used for each test (both arguments to be supplied to the procedure, and data to be l...
I'm working on an application, which tracks expenses. I have users, and each user can create his categories for the expenses (like Food, Bills, Transport, Drinks, Clothes) and then create expenses - each expense has one category (OneToMany relationship). For example, the expense Banana is in the category Food for the u...
Doing database access in ViewModel is generally considered a bad practice. However, when you have a <select> in your view, you need to populate it using the ViewBag or the ViewModel (I prefer the ViewModel). This leads to the following code: public class NewUserViewModel { public string Username {get;set;} publ...
I'm quite new to javaScript and jQuery and wrote the following function to creat some dynamic tabs. I'd be very interested to know how professional programmers would improve this code. jsFiddle JavaScript $(document).ready(function(){ function createVerticalTabs(options){ var container = options["container"]; ...
This method changes all URLs in the string into an HTML link. The goal is to not mutate the string passed in, which I believe is a good practice. The new_string code in this method does not seem idiomatic. def autolink_string string return if string.nil? return '' if string.empty? regex = /(\S+\.(com|net|org...
I wrote the following code as a way of plucking data from a n-depth JavaScript object. It works a charm and even appends the parents of the the found item. I was just wondering if you guys had any ideas on making it better. //#region function recursiveFind function recursiveFind(data, key, childKey, match, result) { ...
I've created the following model for an academic project, and I'm wondering if this is a sensible way to manage a model: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization; using ...
I made a template pipe and filters to replace an old pipe and filters implementation that used inheritance and had a very heavy base class. #include <iostream> #include <boost/bind.hpp> #include <boost/function.hpp> #include <list> template <typename Data> class pipeline { typedef boost::function<Data(Data)> filte...
I want to run a background job on my web server to do some database maintenance. I am looking at using APScheduler to do this. I am planning on running the below code in a separate process to my main web server. I don't really want to tie the code to my web server. Question: Is using While True pass at the end of a cro...
I am learning how to use the module unittest for test-driven development. Below is a simple yet practical example of an issue I will have many times: one single problem (e.g. an Abstract Data Type (ADT) describing a Data Type and an Operator on it), and various Data Structures (DS) implementing this ADT; in this case t...
I am teaching myself Ruby and Ruby-on-rails, as part of this regimen I thought it would be a good idea to do some Ruby quiz exercises and so I started with the solitaire cipher. The basic functionality of decoding a properly formatted message is there but only just so. I've come to the realization that I've written t...
I have implemented a doubly linked list in C++. I have tested it and everything works as expected, but I am not sure if my copy constructor and assignment operator perform a deep copy. Can someone tell whether I am doing a shallow or deep copy? Just by looking at my code, does my destructor seem to work properly? I th...
I just finished (re)reading Clean Code, and one of the ideas I learned was the SRP. However, I am not quite sure on what defines a "Single Responsibility." In the piece of code below, I have a Note class which I think may be doing too many things; it stores pitch and length, and converts these into a Names enum and a L...
I have a solution to the puzzle at https://kattis.csc.kth.se/problem?id=codes. What can I do to make my algorithm much much faster? What the algorithm does is take an N×K matrix and search for the minimum distance — that is, the least number of 1 for all the products of the matrix and a vector that ranges from 00001 to...
I've made a program that goes through your download directory (or any other directory; you just have to change the path) and finds the files that matches your query then asks you to rename or remove the file of your choice. I'd like to know how to make my program shorter. #include <stdio.h> #include <stdlib.h> #include...
I need a global data in my application. My application uses several threads to access and add items to my global variable. The global variable is a ConcurrentDictionary I choose to ensure data is added to the variable. What do you think about my approach? public class GlobalData { private static volatile GlobalData...
In my program I read several information's about the system. I read each categories like CPU, memory, services, software and so on with a own thread. The main program have to wait for the longest thread. To implement this, I use LINQ and the Join function from Thread. Here is a small part from my code: var culture = Cu...
I'm relatively new to bash scripting, and I'm wondering how I've done on this. Basically it's a script where if I'm in a github or bitbucket repository in my terminal, I can type browse-repository to open it up in the browser. I can also type something like browse-repository issues to visit the issues page, or browse-r...
I've developed a script to set up an encrypted tunnel between two Linux hosts, using iproute2, ssh and setkey. The goal is to allow setting up ad-hoc secure tunnels with minimum of setup and dependencies. Mirrored here: #!/bin/bash # Setup encrypted IPv4 tunnel over IPv4 or IPv6 on two Linux nodes using SSH for tunnel...
I am walking through a sample MVC4 ASP.NET tutorial available on PluralSight.com, by Scott Allen. I am in a section #5, Working with Data (part 2), "Listing Reviews". This application has a database of restaurant reviews. I'm following a section right now in which Scott shows how to add links in the Restaurant view t...
As an exercise, I've written quicksort algorithm in C using pointers. Please comment and help me find the cases where it breaks (if any). void qsort(int *, int, int); void swap(int *, int *); void qsort(int *v, int left, int right) { int i, *last; if (right <= left) return; last = v + left; //choo...
I made a class to perform tasks concurrently and have implemented it. From appearances and testing, everything seems to work. How can I improve this? I understand this is somewhat a broad question, so please let me know how I should narrow it down. Here is the pseudocode: The general idea is a single Starter spawns mul...
I have written a caching wrapper class for ConcurrentDictionary. Basically it has a timer that checks if items are expired and removes them. Since ConcurrentDictionary does not have RemoveAll method that takes a predicate as a parameter, it has to decide which ones are expired first, then remove them. The problem is an...
I'm new to Android. I was wondering if anyone had any suggestions. It's basically an AsyncTask to get a remote JSON array and put it into a native array. Would be very grateful for suggestions. package com.example.test2; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java...
A generic blocking queue has the following properties: It is thread-safe. It allows queuing and de-queuing of items of a certain type (T). If a de-queue operation is performed and the queue is empty, the de-queuing thread waits indefinitely for an item to be queued and then retrieves it (i.e. a de-queue operation c...
I have the following function: def item_by_index(iterable, index, default=Ellipsis): """Return the item of <iterable> with the given index. Can be used even if <iterable> is not indexable. If <default> is given, it is returned if the iterator is exhausted before the given index is reached.""" ite...
I am making a web editor for fun and I was told that the way I was doing it (using PHP) would be a bad way. I also thought about it while I was making it, and in massive sums of data transfer it would be a bad idea to do it this way. I can't think of another way to do it and was looking for someone to help me improve i...
I am actually quite new to C++, although I have previously programmed in Java. Do you see any ways I can improve readability, maintainability and performance, and make it more object-oriented? /* Control + 0 = enable aimbot */ #include "stdafx.h" #include <math.h> const float pi = 3.14159265358979f; /* * I am ...
How could this code be improved and have fewer repeated lines? vent.on("createAccountLayout:rendered", function() { logger.info('createAccountLayout:rendered => CreateAccountLayoutController'); showRegion(['phoneNumberRegion', 'keyboardRegion', 'nextRegion', 'quitRegion']); vent.trigger('createAccountLayou...
Background Breaking from MVC, I've implemented the following architecture: POST/GET ➤ PHP ➤ Database Calls ➤ XML ➤ XSLT ➤ HTML All database interactions are relegated to the call method in the Database class, without exception. This adheres to the DRY principle. This design allows the following, which is a critical ap...
The following is a small part of some code I am working on Which is better/faster/nicer? 1. for (Future<Subscription> future : futures) { try { executorService.submit(new Updater(future.get())); } catch (ExecutionException e) { logger.error(e, e); } } 2. for (Future<Subscription...
eval { # here is put some code that may throw exception 1; # Why is the "1;" here ? } or do { my $error = $@; # Handle error. }; Does the following style protect against $@ not being set correctly ? What does the following "1;" protect against? Is the "or do{" better than the saying "if ($@){ " ? If s...
My application. The repository and the file that needs review. Here is the source code $(function () { var draft = function (parsed, title) { var self = this; var wordCount = parsed.wordCount; self.date = new Date(parsed.time).toDateString(); self.count = wordCount; self.title = title; self.pl...
Using OpenMP, is it correct to parallelize a for loop inside a function "func" as follows? void func(REAL coeff, DATAMPOT *dmp, int a, int la, int b, int lb, REAL L) { int i,j,k; REAL dx,dy,dz; REAL dx2,dy2,dz2; REAL r; #pragma omp parallel for default(shared) private(k,i,j,dx,dy,dz,dx2,dy2,dz2,r) ...
I am summing the total .outerHeight() of multiple divs like this: var h = $('#div1').outerHeight() + $('#div2').outerHeight() + $('#div3').outerHeight() + $('#div4').outerHeight(); Is there any way to do this more efficiently? I was considering something like this (but it doesn't work): $('#div1, #div2, #div3').outerH...
I made this Javascript to hide, show and change some DIVs but I believe it's not really good code. Can you help me to make it better? function colorM(n) { switch(n){ case 1: document.getElementById("slideM1").style.backgroundColor="#009CFF"; document.getElementById("slideM1").classNa...
I just wrote this code to concatenate two wide characters strings. Could someone please comment if it looks OK? (seems to work at least). SomeStringClass amount = Window->get_text(); wchar_t strAmount[100] = L"Amount: "; // I know I could remove 100 from here too wchar_t *ptr = wcscat( strAmount, amount.c_str() ); Some...
I need to implement a system of queueing that extracts elements equally from x queues to one single queue with y positions. Let's say I have 5 queues, each with a number of elements and I need to extract elements from each of the 5 queues to build a new queue containing the extracted elements until the new queue is ful...
Is there any way I can DRY up this Rails 4 routes.rb code? match '/oauth/apps/' => 'oauth/applications#index', :as => :oauth_applications, :via => :get match '/oauth/apps/new/' => 'oauth/applications#new', :as => :new_oauth_application, :via => :get match '/oauth/apps/new/' => 'oauth/applications#create', :via =>...
Consider a process composed of three algorithms: makeRuns, meld and traverse (each taking the output of the previous one as input): it is interesting to test each separately. Now consider three (or more) instances (e.g. singleton, twoPairs, SimplePair): it is interesting to test the behavior of the three algorithms on ...
def stopWatchSeconds(secondCnt) : """ counts second for secondCnt seconds """ # is there a better way to do this? startTime = time.clock() ellapsed = 0 for x in range(0, secondCnt, 1) : print "loop cycle time: %f, seconds cnt: %02d" % (ellapsed , x) ellapsed = 1 - (time.clock() ...
The TopCoder question specifies (in summary): Two words are considered rhyming if they have the same ending pattern (defined below). This comparison is case-insensitive (see Example 1.) An ending pattern is a substring of a word such that: The word ends with that substring, The substring contains exactly one contiguo...
I've been writing this data structure for a few days, and now I'm really curious about what it actually is, and to get some critique on my logic. A branch, based on this usage, exists when a HEAD node contains at least one node of the same type referenced. The purpose of the structure is to have branches that are ar...
I have this class that pulls people out of a database. I want it to be a little prettier and function better. <?php class comps extends db_config { public $output = array(); private $arr = array(); public $area; public $me; public $options = array(); public function __construct() { $th...
I am diving into Scala (using 2.10) headfirst and am trying out a simple task of taking bulk data and then doing something with that stream. The first part is generating that stream. I have seem to be able to cobble together what seems to work, but I think I am missing shortcuts in scala. Any pointers or code cleanup r...
I'm trying to read some SNMP packets on my own. So far so good, I was able to put up some functions to write some SNMP TRAP packets as I need them. However, now I need to be able to read them and while my code works, I'm not happy with it. I'd like to see if any of you could please tell me if there's a better way to do...
I'm trying to implement a PID without floating point operations on a micro controller. I appreciate all feedback I can get. Header file: #ifndef BRUSHPID_H #define BRUSHPID_H #if defined(ARDUINO) && (ARDUINO >= 100) // Arduino Library #include "Arduino.h" #else #include "WProgram.h" #endif #define KU_CONSTANT 2 #de...
This is working code for a URI template (RFC 6570) implementation; when the character to render is not within a specific character set, it is needed to grab the UTF-8 representation of that character and encode each byte as a percent-encoded sequence. The question is whether something more efficient than this exists? p...
I'm trying to figure out whether I should do the following: This class (over-simplified version) retrieves information about an order by having 1 main query function that select a specific column from the table and throws out the value for that column and that specific order ID. class jobinfo { protected $id; ...
If you were interviewing me, and saw this code written in a little under an hour, would you consider me as a candidate for a position at your company if you knew I had 2 years of C++ experience? #include <stdlib.h> #include <cassert> /*! \class Node to be used in likned list like constructors */ template <typename T>...
Firstly, here's a link to the fiddle. Basically my situation is that there is a requirement to show tooltips on textboxes on some forms being created for a website to allow employees to update their personal information (among other things). The customer likes the idea of the tooltip being displayed to the right of th...
I'd like a review of Haskell tree heap code in Turning a tree into a heap in Haskell. module Heapify where data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving Show ourTree = Node (Node (Leaf 8) 2 (Leaf 4)) 3 (Node (Leaf 1) 7 (Leaf 9)) atTop :: Tree a -> a atTop (Leaf a) = a atTop (Node _ a _) = a replace...
I have Winform application and I want to separate the button click event from the main form. My application has Add button which adds files into my Listbox and until now all my code was inside this button click event and caused my code to look complicated. So I created this class: public class ListboxFile { public ...
The following program is supposed to return the length of a 'hidden' string within each of the sentences of another string, using pointers and avoiding as much as possible the use of [] as a means to access strings. We were instructed on how to declare the functions, hence their declarations are a given. #include <stdi...
While working on one of my projects I actively used Reflection. While working with class Type I expected methods: TryGetMember, TryGetProperty, TryGetField, TryGetMethod. I've implemented them as extension methods: public static class TypeExtensions { private const BindingFlags DEFAULT_LOOKUP = BindingFlags.Instanc...
I have implemented the first coding challenge on http://projecteuler.net/. I would love to get it reviewed by some expert rubyists! # Multiples of 3 and 5 # # If we list all of the natural numbers below 10 that are multiples of # 3 and 5, we get 3,5,6 and 9. THe sum of these multiples is 23. # # Find the sum of all the...
I have the following code: <?php include '../../inc/config.php'; $size = isset($_REQUEST['size']) ? $_REQUEST['size'] : 'full'; $image = isset($_REQUEST['image']) ? $_REQUEST['image'] : FALSE; if(!$image) { print 'Nenhuma imagem definida!'; exit; } $img_hash = $PDO->prepare("SELECT url FROM missionary_photo...
I'm having some issues understanding why PDO is 6X slower executing a query than the depreciated MySQL query function. Here's my code: $conn = new PDO('mysql:host=localhost;dbname=work', 'root', 'Montreal'); protected function query_s($table, $col = '*', $where_col , $where, $return_col) { $q = $conn->q...
I have the List method that takes sorting parameter to sort results. The sorting parameter value is the same as the column name. public ActionResult List(string sorting = "Name", string sortingMethod = "ASC") { var productList = productRepository.Get(); if(!String.IsNullOrEmpty(Sorting){ if(String.IsN...
I implemented sleepsort in Go. I am new to channels, and I'd like to get some advice on them, especially on how to close channels after N messages have been sent on them. Currently I use a counter and an if statement (see the second for loop in Sleepsort), but maybe this can be done in a nicer way? package main import...
I got this class in C# which works fine. But I was wondering if there was a more elegant solution to what I am trying to do. It looks rather clumsy and inefficient for a Logging functionality. The code should be fairly self-explanatory. public static class Log { public static string EngineName { get; set; } pri...
I am writing a game like Pong. Therefore I am using an entity system approach, so I use a Component-based design. The hardest part until now was to write the collision system. As I just began with the component based design I am sometimes very unsure how to do something with this approach. With a "normal" OOP approach ...
I am trying to calculate work progress in percentage. I have multiple batches, and each batch contains a set of tasks and each task also contains a set of sub tasks. Below code is the best I could do. Is there any more efficient way to do this? I just edited the code using the Math static method to do help with roun...
I've been developing a simple console application in C++ using the TinyXML2 library, and I honestly can't help but feel what I'm doing is not very robust. Maybe that's just the nature of parsing XML (this is my first foray into the topic, so I've no idea.) The following code works to the best of my knowledge, but it fe...
This is a simple but complete console application where I experiment with genetic algorithm to try to figure out the best way to construct a battle mech that would win in a simple turn-based combat. I welcome your criticism and pointers about what I could improve in the code above: architecture-wise, technique-wise, p...
I have three tables for a blog system. The blog CREATE TABLE IF NOT EXISTS lm_blog( blog_id INT UNSIGNED NOT NULL AUTO_INCREMENT, title VARCHAR(80) NOT NULL UNIQUE, action VARCHAR(80) NOT NULL UNIQUE INDEX, url VARCHAR(80) NOT NULL UNIQUE, summary VARCHAR (255) NOT NULL, ...
I have this version of John Conway's Game Of Life in Java: Frame class: import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import j...
I have been playing with event driven javascript lately, and have wondered if it's a good/bad thing for objects listening for their own events as a way of abstracting and simplifying internal logic. Consider the following: function MyModule(options) { this.options = options; this.data = {}; this.setList...
I want to separate the code inside my Add button click event from the code in order to make my code looks more arranged. this is my code before these changes (i am using BackgroundWorker in order to avoid my GUI to freeze because every file that I am choosing need to open process and check if this is file OK before add...
I'll keep this short. I've never actually done professional C++. I don't really know any of the 'best practices'. I'd like to get some review on a simple class that I've made. My Vector2d.h file: #ifndef VECTOR2D_H #define VECTOR2D_H #include <cfloat> #include <climits> /*The Vector2d class is an object consisting of...
In my Rails 4 app i used to have every view contain a content_for :nav tag which included all of the links for the nav bar in my layout. This was getting annoying because if i wanted to add a button i would have to go through every view and add that link. I decide to make a partial view in layouts/_nav.haml which conta...
I'm reading on design patterns for a software engineering class. I am doing small implementations of some I find the most interesting / applicable to better understand them. I'd like a code review on my design, more particularly on the degree of coupling between my Observer and Publisher classes. I feel that the add_ob...
I know this dining philosophers problem has been researched a lot and there are resources everywhere. But I wrote simple code to solve this problem with C and then turned to the Internet to see if it's correct. I wrote this with mutexes only and almost all implementations on the Internet use a semaphore. Now I'm not su...
Please assume I've exhaustively tried to come up with a set-based solution to my T-SQL problem, and that I need to use a cursor. The following is the typical1 boilerplate for a T-SQL cursor: DECLARE @myId AS INT; DECLARE myCursor CURSOR FAST_FORWARD FOR SELECT id FROM MyTable; OPEN myCursor; FETCH NEXT FROM myCursor...
I'm looking for the best and fastest way to do a determinant, for determinants until 15x15. int Determinant(const vector<vector<int> > &a,int n) { int i,j,j1,j2; int det = 0; vector<vector<int> > m(n, vector<int>(n)); if (n == 1) { /* Shouldn't get used */ det = a[0][0]; } else if (n == 2) { ...
I have made a mini image gallery which consists of one large div which has a background image of one of the galleries images. Underneath that are five thumbnail images, that when clicked, change the background image of the large div above. All code works as expected but it looks like it could be improved. How can I re...
I'm solving Project Euler problems and uploading my solutions to GitHub. Some of my solutions are just based on math and are thanks to that very fast, but #14 is way too slow, and I have no idea how to optimize it. """ Longest Collatz sequence ------------------------ The following iterative sequence is defined for th...
Code reviews and suggestions to improve coding style are welcome. using ExpressionEvaluatorLibrary; namespace ExpressionEvaluator { class Program { static void Main(string[] args) { ConsoleKeyInfo cki = new ConsoleKeyInfo(); Console.WriteLine(" Mathematical Expression Evaluation"); C...
This is a continuation from here: https://stackoverflow.com/questions/16761207/java-theory-classes-design-for-currency-futures-and-metals-analysis I have created 2 classes for now. 1) Historical Data 2) Futures. Here is the Code: It does the following: Takes in a file, checks if it is a file, dynamically creates an ...
Is this code good for checking if the variable texto is empty or not? How would it be done with try and catch? public class RedProfesionalException extends Exception { public RedProfesionalException(String message) { super(message); } } public class Comentari extends Object { private String autor, ...
There are a few common jQuery call I find my self calling when creating my app. I need some help and maybe a better way to do all this or rewrite it. 1) Singleton Selector If I want to select only one class I would do it like this: $("#tempo").on("click", ".entity", function(e){ $(".selected").removeClass("selected...
I am breaking my head with how to get rid of semantic duplication(Code that is syntactically the same but does different things). I can't find anywhere a post or something that mentions a bit how to refactor this kind of duplication. All I found was this: Duplicate Code and Ceremony in Java but it does not go into deta...
I made my first Brainfuck program today, which prints the numbers 0-255 and the corresponding character. I was wondering if I could improve my program, as I'm repeating myself a lot (e.g. 3 x copy & paste "comparer" function): max == 255 LF == 10 space == 32 '0' == 48 '9' == 57 ':' == 58 Memory: counter ...
I'm making a comparing section, which I've just started typing, trying to get something working. It's working now, but as you can see its pretty messy. I feel this could be done in one or two less queries, or I should break it apart into smaller methods. foreach (XMLObject source in Sources) { var matchedElement =...
I have never been entirely comfortable using malloc() and free() directly. For one thing, 99% of the time that I would like to call malloc, I would prefer it to take two arguments like calloc and do the multiplication itself, instead of taking one argument. Beyond that, I've often wished that free could magically zero ...
I'm trying to join two tables based on one to one mapping without any common column. For example, I have 3 records in the first table and 2 records in the second table. The mapping should be as follows: As there is no third record in the second table, nulls should be displayed. In order to implement this, I've tried ...