instruction
stringlengths
71
71.9k
I'm using C# in .NET 4. The class holds an array of double that represents a 2-D rectangular matrix but (due to business requirements) must be stored flattened (i.e. a double[]). The class also stores the dimensions of the array. I wish to sort the array by the (virtual) first column. Obviously I have to unflatten it, ...
I created a script to hide a menu during user inactivity and when the position of my page is left < 2. I would like to know if I use a good method regarding the performances. It's not too heavy ? Should I optimize my code ? var interval = 1; setInterval(function(){ var posx=$("#page").offset(); if (interval ==...
I have made a small game in Javascript, while simultaneously learn about the ever so popular model view controller. The game is this, there are 3 players(green, purple, yellow) and they have to try and build a path of arrows to the blue square. The first player to make the path go to the blue square wins. When the path...
I have to list the number of documents related to items in a hierarchical tree. The specification states: The tree will only ever be 2 levels deep. The higher level items will list not only the number of documents in it's folder, but also the total count of documents in the child folders. They want this total to in...
I am working on a socket HTTP post request. Here is one method that I come up with. It looks dirty and is in C instead of C++. bool SendBasicInfo(USER* user, SOCKET sock) { char FormBuffer[1024]; char DataType1[] = "a="; char DataType2[] = "&b="; char DataType3[] = "&c="; char FormAction[] = "/g...
I've started coding about 3 weeks ago, just for fun and maybe practical uses later. My GF dared me to make a PGM that would replace this dice game where you roll two dice, one with body parts and one with actions, then resulting in stuff like 'kiss, lips'. All I know is off of YouTube and sites such as Stack Overflow. ...
I'm trying to figure out a better way to structure some of my code so that I don't have a ton of conditionals here. I have a series of checkboxes that someone authors on the backend and if they are checked I set a variable with a specific value. I then use that variable and set options in my jQuery plugin. This works j...
This is my very-first-ever run at TDD. How did I do? In keeping with Uncle Bob's Three Rules, I wrote every test first, starting in order from the top down as you see here (below). Here's the sequence I used: For each new method in Production I entered the method-name-to-be in Test. I received a compile-time error. I ...
I am working on a project in which I construct a URL with a valid hostname (but not a blocked hostname) and then execute that URL using RestTemplate from my main thread. I also have a single background thread in my application which parses the data from the URL and extracts the block list of hostnames from it. If any b...
I have an n-tier solution which consist of DAL,BL and a ASP.net WebAPI project. I'm new with Asynchronous Pattern and I'm trying to add it to my Framework. Am I using the asynchronous pattern correctly? I'm not convinced with my implementation of it. Could you give me a recommendation on how to use it correctly or any ...
I have the following linq statement that is ordering a list of assets by the sort order of a child item: Assets.OrderBy(a => a.GalleryItems != null && a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCode == productId) != null ? a.GalleryItems.FirstOrDefault(gi => gi.ProductItemCo...
I've been working on a new project and I've found myself needing to make multiple Ajax calls, often on the same page and at the same time. I decided rather than repeating code that I would try and make a reusable object that to handle these calls. I'm very new to Object Orientated JavaScript so I'm looking for some fe...
I want to show how to interact with C from C++ and chose a simple and small library to demonstrate. zlib's gzopen, gzwrite and gzclose looked like a reasonably closed set of funtions. Does anyone see anything fundamentally wrong with my presentaion? The main code I present here is in class GzWrite. Intro section: #incl...
I've wrote this CoffeScript function to compare values in a table, but it turned out to be a HUGE function. Since the code is really really long, you can find it here as well. Code explanation: The code searches for all the values in a dynamically created datatable and appends the comparison values in another column, M...
Context: I have to create an interface between devices and a client. My package is composed of: Device.py Error.py DeviceA.py (for example) DeviceB.py ... Basically each DeviceA, DeviceB, ... inherit Device class. Device is composed of one FSM (state machine: module Fysom) and does several thing about communication, ...
For the server of which this is part, it makes a request to one of our web servers to validate whether the PHP Session ID is actually valid. The location this._options.url is a URL that, given a PHPSESSID as a cookie, will return the user ID that is attached. One of the issues that has crept up is the CPU utilization ...
In the following code I'm trying to calculate Net Wage of employees and classes Earning, Deduction and WageBalance has a composition relationship with WageInfo. And there is a class called WageManager which is having a association with WageInfo, handling all operations like BalanceWage(). DataService class encapsulates...
I've been writing a small library that allows for easy querying of the Stack Exchange websockets. I'm going to add an enum to replace the manual SiteId at every RequestParameter so you can let that one slide (unless you have something else in mind). A few thoughts I have: RequestParameters defines its ResponseDataType...
I would like to develop a student management system with repository pattern using ado.net (no EF or MVC). I decided to create the model (business objects) and interfaces as one project "StudentModel". Implementing the interfaces to fetch data from DB as one project "StudentImpl" and the third will be the web applicatio...
I'm working through SICP and have implemented exercise 1.11 (Pascal's Triangle). What I'm curious about here is performance considerations by defining functions within the main function. I would assume they get reassigned with each invocation of the function. In saying that, this style appeals to me, as the functionali...
Just for the fun of it, I decided I would try to create sort of an intermediate DNS system for the oddsock SOCKS proxy. With this, the domain name extension .unet is statically resolved when requested. All of this is hooked into the oddsocks proxy system via inserting into the DYLD before libevent does. Tell me what yo...
As a test of my C# skills, I have been asked to create a simple web service which will take a message from a queue table in a SQL database and send it to a web application when a button is pressed on the application. I have never written a web service before so I am going in a little blind here so was after some advis...
Let's say I have a configuration file with a property in it: <add key="LoadedCode" value="L" /> I know I can reference this using the ConfigurationManager: System.Configuration.ConfigurationManager.AppSettings["LoadedCode"]; This has some drawbacks. It can get bulky when it gets used in multiple locations. I lose s...
<!DOCTYPE html> <html> <script> //////////////////////////// // Code by Zachary Holmes // //////////////////////////// // This program determines the number of boxes that can fit into the back of a truck // Declaring box size in centimetres, and converting it into metres var boxHeight = prompt("What is the he...
I am building an ASP.NET MVC 5 application and, for reasons which are irrelevant at this point, I am attempting to build my own means of authenticating users. I'm still very new to programming, especially to this sort of thing, and I realize that what looks fine to me may be full of problems. Thus, I present my code, s...
I've written a working web crawler in Java that finds the frequencies of words on web pages. I have two issues with it. The organization of my code in WebCrawler.java is terrible. Is there a way I could refactor the class to make it more readable? Perhaps splitting it into multiple classes? I want to find a way to g...
This code works as I intended, but I am definitely a JS noob (C++ background), so I'm not sure if this is the best way to do it (for example using .each instead of some kind of a for loop was completely new to me). https://github.com/TaylorHuston/menuBreak/blob/master/menuBreak.js function menuBreak() { var windowWidt...
Which of these three methods is better? import java.util.* ; public class anycode{ public static void print_digits3(int num){ //this method converts integer to string and parses it int digit = 0 ; String num_str = new Integer(num).toString() ; int counter = 0 ; while(counter != num_str.lengt...
I have made a lot of changes to the code over the course of the evening, but after making most of the suggested changes, the variable that the answer is returning is showing up as "undefined". Could someone please help me find my errors in this code? I have tried and have not been able to find the errors due to my limi...
For example, given the string "xyz", return the string "xxyyzz". I was given this as a part of a test. I would really appreciate if you can help me to find a better way of doing it. I came up with two methods to do the same thing but one was an extension method. I have a couple more questions which I will post in separ...
I'm looking for a review of my code for better design (to make sure it's more readable and legible). <?php // define variables and set to empty values $nameErr = $phoneErr = $streetErr = $cityErr = $stateErr = $zipErr = ""; $name = $phone = $street = $city = $state = $zip = ""; // start script if the form is submitte...
Context: I am using XNA to create a simple game / learning project. Problem: I have three interfaces, each with a different purpose in mind. However, the way I use them, as well as their implementations, makes me feel as if my code is overdesigned and poorly thought out, so I am looking for better approaches, if possib...
Use recursion in the solution. I would really appreciate if you can help me to find a better way to do it. public class AppendCharacterAfterEachCharacterInString { int index =0; StringBuilder outputString = new StringBuilder(); public string AppendInputCharacterAfterEachCharacterInString(string sInputStrin...
I would really appreciate if you can help me to find a better way to do it. public class SplitArray { public SplitArray() { } public bool CanArrayBeSplit(int[] intArray) { foreach(var pair in GeneratePairs(intArray)) { if (pair.Item1 == pair.Item2) re...
which of the following code you prefer and why? The scenario is, I need to pass the recent folder path to folder browser dialog and if user selects any folder, need to save it back. The value is stored in Application settings. My settings class. internal sealed class Settings : ApplicationSettingsBase { ...
I'm creating a small project, but in the past I've used a Repository pattern for it, and it just seemed too bloated. I ended up having repo classes with huge amounts of queries. I'm trying to move away from that. I invite you to critique/help/guide me on my journey to less abstraction: Note: I like the syntax style of ...
I was trying to get my computer information and I came up with this code. It is working but I need opinions on how I am doing it. It is my first time to using std::string to return strings. Is it good or is there another way around? struct USER { std::string ID; std::string Username; std::string PCName; ...
In my application, a notification should be displayed when a chat message arrives. There are some rules which decide what notification message is to be displayed. I have created a helper method which takes a ChatMessage object and returns the message to be displayed in the notification. How can I refactor or improve...
The purpose: an express node.js server which can be launched using naught, with an integration test using supertest. Each worker naught runs will test itself on a unique port, and only if passes it will listen in on the main port and join the pool. Major concerns are - no idea what I'm doing. How I provision the port...
I have big search method in my model that corresponds to search a proper Car. It looks like this: def self.search(params) cars = joins(:reservations).where.not("reservations.reception_time <= ? AND reservations.return_time >= ?", params[:return_date], params[:handover_date]) cars = joins(:car_class)....
Please tell me how I can improve the structure of this simple tool (depends on MissingH): module Main (main) where import Data.List(isInfixOf) import Data.String.Utils(replace) import System.Environment(getArgs) import System.Directory(renameFile, getDirectoryContents) pathsContaining :: String -> [String] -> [String...
I am moving a project from Python to C++, partly in order to achieve a speed up. This part of the code reads large .txt data files (well only about 2MB per file, but quite a lot of files), and needs to convert the data to floating point. This C++ code does is not faster than Python bytecode (.pyc). Regardless, my appl...
I am currently working on a piece of legacy code that I inherited. The current Java version is 6, but this will change in the next few weeks to Java 7. I think I might have been working on it for too long as I get the impression that it can be made much more readable as I have many byte-wise operations, but cannot find...
I am parsing a text file (UTF-8) and checking for several conditions that need to be satisfied for the code to be happy. If not, then there is no point to continue and the program should die. At the moment I am catching exceptions and if caught, throw RuntimeException to signal the user that something went wrong. Wha...
I'm wondering if providing default behavior is ever worth the confusion caused by ignoring generic type passed in. Another question brought up this issue: public class Activate<D extends CanQuack & CanWalk> { D d; //Must match D's type Activate(D d) { this.d = d; } //Completely ig...
I have created a class called CommandMessages public class CommandMessages { public string CommandType { get; set; } public string Command { get; set; } public DateTime? SendDateTime { get; set; } public CommandMessages() { } public CommandMessages(strin...
I'm not sure if my lock usage is correct and safe. I wanted to know what will be best approach to deal with situation when one thread have to wait for being initialized by another so I written this test: import java.util.concurrent.locks.ReentrantLock import java.util.{TimerTask, Timer, Date} import scala.concurrent.{E...
I'm looking for a review on my code. I am also looking for ways to transform this function into something more Pythonic. I'm fairly new to Python, so any advice would be appreciated. def get_rsi(self, period): rsi = [] for i in xrange(1, len(self.hist_d) - period + 1): gains = 0.0 losses = 0.0...
I wrote a "foreach" implementation for std::tuple: #pragma once #include <tuple> /** * Callback example: struct Call{ float k=0; template<typename T, int Index> // lambda function not efficient than this. Tested -O2 clang, gcc 4.8 inline void call(T &&t){ std::cout << t.h << " ; " << "id ...
So I have this rather large function, which adds to an array. What it also does is searches the array to see if the item already exists and adds to the quantity if it does. If has_options == 1 then it will search the oid instead of the pid. Is there any better way to write this? As it seems there's a lot of duplicated...
I've not done JavaScript in quite a while, but I wanted to make it so that I can circle (in many different ways) around the bounding box of a tagged item. Is this a good way of doing what I'm wanting? Is there a better way? E.g. can this be done with only CSS? Or better style? E.g. can I use better, more understandabl...
Following advice to "Make good use of toString() for all Domain classes", I made what I thought was the most useful toString for my class. I found that certain operations happen before there are values for the components of the toString. I wonder if there is a cleaner way to check for nulls or even if I need to appr...
I am creating a social sharing counter plugin for my WordPress blog. I want to fetch the counts of number of likes, shares, Facebook comments (I am using Facebook comment box), twitter tweet counts and a count of how many users have added a particular article to reading list. The way I have implemented is the following...
What do I need to do to prevent injections? In addition, if I have any statement/parameter errors, please tell me. <? $username = 'username'; $pass = 'pass'; $cpass = 'cpass'; $email = 'email'; $gender = 'gender'; $firstname = 'firstname'; $lastname = 'lastname'; $phone = 'phone'; $addr...
I'm currently working on a Qt project writing Excel files through a third party DLL. As the third party DLL has a COM interface, I have to do lots of conversions between QString and BSTR... I wrote the following two methods to do the conversions: QString ExcelClass::bstrToQString(const BSTR &bStr) const { _bstr...
I'm making a JSON call and receiving data and inputting the data received into some HTML. However I don't think this is the best way to return the data. It's seems like a bit of a hack as I'm injecting a bunch of HTML in my jQuery. I'm also adding an image inside of my jQuery cause I want it to appear between some of t...
class ReportFormat(object): PDF = 0 TEXT = 1 class Report(object): """Strategy context.""" def __init__(self, format_): self.title = 'Monthly report' self.text = ['Things are going', 'really, really well.'] self.format_ = format_ class Handler(object): def __init__(self...
I came across Java like Scala code that I am trying to refactor to make it functional and immutable. The first obvious flaw is that it's violating thread safety by using mutable public class level collections. Those methods (insText, insInt, etc) look unnecessary and can be removed with higher order function (where fu...
I'm coming from Backbone and trying to wrap my head around Angular for a new project and would like to get some feedback on whether I'm using it correctly or not. Plunker What I'm trying to accomplish is this: I have a list of items that can be very easily rendered with an ngRepeat. Each item starts off in an inactive ...
I have one container div which contains some children div members. From time to time, I need to run a custom blinking effects on some of the child div members. The effect steps are as follows: Change font color to Yellow Pause for 0.5 secs Change background color to yellow and text color to black Pause for 0.25 secs ...
On my machine it runs in about 60 seconds and about 2-3 minutes live. The criteria needed are: Current month only (from first of month until current day) I need the rank of the currently logged in person based on total sales. I have two tables across two databases where this data is to be gathered: Database 1: ProPit...
I'm using the Observer pattern to notify my UI that the object they're representing has changed. Also, I'm refreshing this object from the interwebs. Therefore, I'm ending up with two instances representing the same object. One with old values, one with refreshed values. I have written this util class that recursively ...
I've started caring about standards and the beauty of my code. I doubt whether I've written it correctly and aesthetically. Can you please judge this simple, exemplary program? I want to know of any mistakes I've made. It converts an integer number given in the argument to binary, hexadecimal and octal number. Ignore t...
This code determines the maximum number of boxes (one size) that can fit into the back of a truck, checking all possible orientations to ensure maximum Bin Packing excitement. This is (hopefully) the final version of this code. Please share any modifications that you would make to this code below. <!DOCTYPE html> <htm...
I am working on a project that will allow developers to create a console application using a dependency injection service container. Both the console and container are Symfony components with some glue code to make it all work together. The project can be found here and the script in question is here. I'm hoping that s...
This is a Python script I made to download a URL from the clipboard. When a new URL is copied to a clipboard it adds the URL to a download queue, then on a separate thread it downloads the URL to a file. I am new to multithreading. Is my script properly using multithreading? It needs to download the data while still ...
I feel that this implementation can still be simplified. I've tried to keep variable scopes low and have used as much of the standard library as I could. It currently works with a hard-coded word or phrase, but I eventually plan on having it work with random words or phrases from a file. My main concern is in regards ...
I'm trying to create some helper functions that will allow me to convert from one unit of measurement to another. I eventually will need to be able to do speeds and temperatures as well, but so far, I've only implemented lengths. I'm not using C++11 for this solution. Here are my structs. My structs are basically wrapp...
I'm trying to figure out if there's a way I can simplify this code which is used to generate a robots.txt file with numerous rules. Different files/folders are separated in separate arrays because they're applied differently but in some cases they are applied the same. In these cases, rather than write out a separate...
I wrote a script that would change example.jpg to example-color.jpg (.png, .gif would work too) on mouse hover and changes it back on mouse leave. I'm making a portfolio, and I have examples of my work in black and white thumbnails, on hover they switch to colored ones. I'm just wondering if I did this in a redundant ...
A script which scans a local filesystem and writes to a file a list of world-writable files found on the filesystem. I ran it on a server with a couple terabytes of storage; not all of it used. In fact, only 195GB have been used. I'm not sure how many files there are, though. The script takes 23 minutes to run. Is ther...
I have faced this question in an interview: If we enter a number it will convert into individual strings and display in same order. Ex: If I enter 564 then the output should be FIVE SIX FOUR. I have written the following working code (of course it has some limitations). Suggest any possible ways of optimizing this c...
I have a WPF application (using MVVM pattern) that allows users to perform a search for a record/records based on their selection choices and entries into the different UI controls (TextBox, CheckBox, RadioButton, DatePicker, TimerPicker,etc). It does this by retrieving information from an Access database. I have an A...
I just started a new project which reads in a video file and splits it up into frames. I started by just throwing everything in the GUI, but decided I wanted to make this a more well designed program, backed with unit tests. So I started to split out functionality into its own class and have a few questions on best pra...
Just over half way through in K&R, came across an exercise to convert from postfix ("reverse-Polish") notation to infix (standard) notation. Basically I'm posting here to see if there is anything excessive in my code, or any way to reduce the amount of storage it takes up. It runs extremely fast and doesn't take up mu...
I am working on a project in which I construct a URL with a valid hostname (but not a blocked hostname) and then execute that URL using RestTemplate from my main application thread. I also have a single background thread in my application which parses the data from the URL and extracts the block list of hostnames from ...
Problem Statement: T1, T2 to Tn threads prints numbers up to N such that each threads prints number in circular sequential fashion. T1 prints 1, T2 prints 2, T3 prints 3 and T1 prints 4 again following strict ordering. This implementation would allow us to control any number of threads to do sequential ordered...
I have designed a generic method to convert list of array of Objects to result into single map. This is working fine, but I want to check weather a key object is valid key (whether it is overriding equals and hashcode method or immutable instance). Am I missing anything else in my code? /** @parms objects : list of ar...
I have an input with numbers 1, 2, 3, 4 and I want to change the order of this number dynamically according to users input. You can find my code below and also a running example here. HTML <input type="text" name="name1" id="1" value="1" class="order"> <input type="text" name="name2" id="2" value="2" class="order"> <in...
I have the following code. I was wondering if anyone can give me any pointers on how to make this more concise and neater? Should I be splitting this down into smaller functions? private void ReturnValue() { //create our WebService object var sample = new TestProjectService.Service1(); ...
In my real life example I am at a layout stage and before I actually move any further I would like to review my current approach. I am still learning about UI, XAML on WPF technology and I guess I haven't gotten my head around all the possible approaches yet. I have built this very simple SSCCE to better demonstrate wh...
The more I consider object oriented JavaScript the more I am confused. There are so many different ways and concepts and I simply do not know any longer what fits best for my purposes. I like the constructor pattern but I have the feeling that I've mixed different concepts: Subclass.prototype = Object.create(Superclass...
Situation I've written a simple black and white image filter application with JavaScript using html5 canvas. I have take two approaches, one with websockets and the other normally, the code is hosted on github On my desktop browser and Firefox OS, for images of dimensions less than 1024X768 px, the application worked ...
This is taken from my post at Stack Overflow here. I need your help to review my code for improvement and best practice. private void logSessionToServer() { // TODO Auto-generated method stub Thread thread = new Thread(){ public void run(){ strUsername = etUsername.getText().toString(); ...
Little backstory: I'm trying to write code that will read messages from INetworkConnection that the INetworkConnection publishes and then send those up to the NetworkController which should do some processing and then send that off to an injected IObserver<IMessage> (which is a single observer because there's a global ...
I was wondering if it is the proper way to always put the return statement of a function with a try-catch clause in the finally clause. I have for example this function which returns the version of an sql server: public String getVersion() { String version = new String(); final String query = "Select VE...
I just wrote the session class below. I humbly request for a review on how to make this even more secured/ how sessions are normally written. The code below works, but I would love to make it even more secure and robust. <?php session_start(); require_once('classes/function.php'); require_once('classes/user.php'); c...
I've got a jQuery/JavaScript script for a menu that uses icons as well as label text. When the icon or text is clicked, it turns blue, until such time as another icon is clicked. Also, the page scrolls down to the relevant div on the page, but the menu bar still stays fixed along the top of the screen. I've created se...
I am trying to make the fastest #to_struct method in Ruby's Hash. I am including a use case and benchmark so you can run and see if you have really improved the code. This is my implementation and the benchmark is included. The time at the bottom is the time it takes on my machine. How can I make this faster? require "...
I have a navigation bar that when the list elements are clicked their respective body container appears and the other body containers disappear. navigation <ul> <li><a id="home" href="#"><img src="img/home-icon.png" alt="Home">HOME</a></li> <li><a id="about" href="#"><img src="img/about-icon.png" alt="Home">AB...
I'm really tired of having to type for (int iSomething = rangeBegin; iSomething < rangeEnd; ++iSomething) { ... } whenever I want to iterate over an integer range (most IDEs help with the typing, but still it looks so verbose, naming the integer 3 times!) I wanted something like this: for (int iSomething : LoopRang...
I have many sets of 2 strings. I'm trying to determine the number of matching elements in these 2 strings. The rules are if the strings share a common letter, that's a point, order does matter, but each letter in the first string can only match one of the letters in the second string. So in the strings 'aaaab', 'acccc'...
I recently have given a coding test in a reputable IT company. There were three coding questions. They refused me by saying that as we felt they didn't demonstrate the level of technical depth we're seeking from candidates Please help me understanding what type of the technical depth my solution is missing? Thanks...
This code is a slot machine simulator that uses elements of both HTML and JavaScript. Please pardon the lack of comments. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>www.loseloselose.com</title> <font color="white"> <script> function Re...
I decided to refactor the code for a responsive image gallery, that I setup not too long ago. Following the suggestions @joseph-the-dreamer made, and some other best practices, I cut down on the number of if statements. Is there anything else I could do to make the activateSlider function more concise? Is there another...
Is there a way to use CPS in this code to make the two insert functions tail-call optimized? defmodule BTree do defstruct tree: {node: nil, left: nil, right: nil} def new(element), do: %BTree{tree: {node: element, left: nil, right: nil}} #insert when there's some data in the tree def insert(%BTree{tree: {node...
I recently have given a coding test in a reputable IT company. There were three coding questions. They refused me by saying that as we felt they didn't demonstrate the level of technical depth we're seeking from candidates Question 1 : Missing level of technical depth (Recursive to Iterative) Question 3 : Missing lev...
I recently have given a coding test in a reputable IT company. There were three coding questions. They refused me by saying that as we felt they didn't demonstrate the level of technical depth we're seeking from candidates Question 1 : Missing level of technical depth (Recursive to Iterative) Question 2 : Missing lev...
I made a function to find the element that yields the largest value when put into a custom functor. I think this is missing from the STL. I can think of three ways to do this in STL: Transform the container by the functor. Find the maximum in the transformed version. Take the corresponding element from the original co...
In this project (C# Win forms) I'm supposed to calculate wages of employees. These are the steps: Calculate earnings from Attendance data. Here all regular earnings like BasicSalary, OverTimeAmount etc will be calculated. Then these earning details will be shown in a grid where user can enter values for blank columns ...