instruction
stringlengths
71
71.9k
I changed the program to use a dynamic array instead of a vector or storing the integers. This program works without bugs and executes relatively fast. The only doubt Istill have is how to fill the dynamic array in am ore elegant fashion (I couldn't get array={0} or array.fil(0) to work. At this point, there's to asses...
I have this background service, which runs continuously even when the application closed (Paused or Stopped). The service is to retrieve the user location and post it to server. public class LocationUpdaterService extends Service { public static final int TWO_MINUTES = 120000; // 120 seconds public static Boole...
I have written a safe read function for haskell (for education!). I think this is fairly idiomatic haskell code, but I'd like to know for sure. If you see anything else that could be improved, please let me know in your answer. module ReadNum (readNum) where main = print $ readNum "87k7" readNum :: String -> Maybe I...
I am working on a project for class, and it works as required by the rubric, though I am wondering if there is a slightly better way to implement a few things. I was docked a few points for an unnecessary mov in another project. Problem 1: "If—else (34 points): Write a program that asks the user to enter a single d...
Create a class diagram and Java code for the following system and scenario, taking into account the possibility of future extensions. The system is a command line utility that prints a short 'quote of the day' on the user's terminal when run. To begin with the quote is selected randomly from a set of hard-coded st...
I've grown tired of typing my password back and forth to all the hosts you connect to, i want to be able to jump to every single user on all the hosts with ease. So i've made this script with a quite messy oneliner at the end of it. The script first reads user input where to connect to. remote_user, remote_host and re...
I have written a very basic paint program in java using AWT and Swing. I have separated the program into two different class files; one of them holds the JFrame and adds a custom panel (this custom panel being the second class file, extending JPanel). In my first try, I tried using Timer and an ActionListener with repa...
private void loadTabsIfGPSAndInternetAvailable() { final Utils utils = new Utils(this); final LocationClient locationClient = new LocationClient(this); if (!utils.isConnected()) { utils.generateNoConnectivityAlert(); } else if (!locationClient.hasGPS()) ...
EDIT: Version 2 is now available here I am just getting to grips with ReactJs using es2015 classes, i have just converted a simple portion of an app i maintain into react code and tried a few things out, this displays a list of customers with a sub-list of the animals that they own. Am i utilising es2015 features corre...
Initial stage of implementation of the polynomial class. Essentially I need to implement the basic mathematical operations. Right now I have implemented just addition. Was wondering if this is a good way to proceed. I also want to be sure if the move constructor would be called during the addition operation. poly.h /* ...
I wrote a Java program with a Swing UI that calculates prime numbers. The primes are displayed into a listbox. I used a few optimizations to generate the primes faster. I’m using the NetBeans IDE, so there’s a lot of generated Swing code. Currently, the program finds as many primes as the user has input into a spinner ...
I have a system that outputs a comma separated string into a single column. I need to grab the individual values out of that list. The list could have random spaces and commas that need to be accounted for. I'm new to MySQL and I have a working example that just seems rather long. I'm wondering if there is a simple...
I am trying to write code to calcultate ex using: $$e^x = \sum_{n=0}^\infty \frac{x^n}{n!} = 1 + x + \frac{x^2}{2!} + \frac{x^3}{3!} + \frac{x^4}{4!} + \cdots $$ This is the code I have, which works for small values of x. Please do not pay attention to the variable e, specifically to the fact that user enters it. #inc...
I wrote this implementation of quicksort as a bit of practice and review for myself. I did not base my algorithm on anything more than my own understanding of quicksort and working through a couple of examples myself on paper, so please let me know of any improvements or optimizations that I could make! import java.ut...
I'm just starting out with Java, and trying to make a method to get a positive integer input from the console. My currently working implementation is this: public static Scanner sc = new Scanner(System.in); public static int getPositiveIntInput(String message) { int n; String error_message = "Error: input mu...
I made a merge sort implementation in C++, which I have tested with the values: 6, 38, 27, 7, 12, 58, 92, 43, 3, 9, 82, 10 producing the correct output of: 3 6 7 9 10 12 27 38 43 58 82 92 However, when running my program, it seemed pretty slow, and I was wondering if there were any places in my code where there is an...
I'm trying to improve my limited knowledge in PHP (7) and I wrote these two simple classes as a proof of concept. They both have just one (private) property ->email and they run validation before setting a value for it (unless it's null). They are both supposed to run at business-tier GtokenA uses magic methods and is...
After posting my original address book program I took the responses and edited my code. I have used every suggestion given, the code works great, and now I am looking for further review and suggestions from the Code Review community. Parent class (Person): //parent class #ifndef PERSON #define PERSON #pragma once #inc...
I'm pretty new with programming in general. I'm using Python 2 right now as it seems most of the courses are teaching Python 2 and not 3. I built this area calculator that will calculate square, rectangle, triangle, circle or trapezoid. I'm a little concerned about how I used the functions as well as my else stateme...
I recently posted an earlier version of this code on Code Review, and now with the given suggestions and many other improvements, I am back. I included the description of exactly what Cyther is supposed to do inside of my source code. Cyther's repo can be found here. My objective is to make sure that this code is as cr...
I am new to C++, learning from the book primer C++ The exercise: Write a program to read strings from standard input looking for duplicated words. The program should find places in the input where one word is followed immediately by itself. Keep track of the largest number of times a single repetition occurs and whi...
The problem statement is here. Problem Description The task is to rank the contestants in the contest based on following criteria Contestants are ranked first by the number of problems solved (the more the better) then by decreasing amounts of penalty time If two or more contestants are tied in both problems solved an...
I'm creating a console app that has the purpose to teach you how to use C# bitwise operators. I have several classes which contain info about the different operators and I instantiate/add them in the main class like this: var trainingDefinitions = new TrainingDefinitions(); var generalDefinitions = new GeneralDefinitio...
I've been writing basic Python scripts for a while now to help process data or automate some task but I've decided I should start picking up unit testing and objective orientated programming (the vast majority of my scripts so far have been procedural). As a starter I decided to follow along with Uncle Bob's bowling sc...
Question: Need to create three classes. Number Fraction Integer Requirements The first class should support “display”, “==”, and “+”. "Display" : This operation displays the Number itself in its original form. "+" : This operation adds the number itself with another number and returns a third number whose numeric va...
I want to ask the user about whether he wants to continue playing or not. For this I have used, char choice; do { System.out.println("Would you like to continue?(y/n)"); choice=sc.nextLine().charAt(0); if (choice!='y' && choice!='n') { System.out.println("Invalid Entry"); } }whi...
In my program below I am getting the parent node game 1 and then removing one of the two child nodes, depending on which one is clicked. I currently have two event listeners, with two separate functions for removing one child vs the other. It doesn't feel very dry to me, and I think I could benefit from having someone ...
Since I use C++ mainly to do physical calculations, I often come across the problem that I forget which units a certain variable is in, e.g. radian or degree, or meter vs. millimeter. For this reason, I started using a custom header file defining my units, which is posted below. The basic idea is that I never create so...
The following code fetches trending topics from Twitter's API using a WOEID. It caches the response, loading from this cache the next time if its relatively fresh (generated within the last 15 minutes) to avoid returning a "Rate limit exceeded" message from Twitter. A 'force-refresh' flag can be passed to skip the cach...
I have some code that reads a file and then does some parallel processing of the data. There are millions of lines in the file and this section of the code is the bottleneck in my program. Any information on how to improve processing times or any other suggestions to improve the code (e.g. error processing, string mani...
I am working on a generic repository. And I wondered if anyone could give some feedback on it. Interface for DbContext: public interface IDbContext { IDbSet<T> Set<T>() where T : class; DbEntityEntry Entry<T>(T entity) where T : class; void SaveChanges(); } Context class public class BookContext : DbContex...
Here's my lock-free channel impl lfchan, I didn't want to copy/paste the code here since it is multiple files. I'm trying to get an idea of what can be improved or if there are any bugs in it. chan.go type innerChan struct { q []aValue sendIdx uint32 recvIdx uint32 slen uint32 rlen uint3...
The goal of following MVC controller code is to achieve following workflow: User exports catalog (either with items of type Spread or of type Consumables) to Excel; User makes changes in exported Excel file; User uploads catalog to web; User preview his changes before committing to database. Because catalog can b...
I have been working on a Scrabble Word Finder for a couple of days now and have it working pretty much but would love to improve the efficiency. The code is made up of 2 classes: one for creating and managing a pool of letter tiles and another for iterating over a word dictionary (from a .txt file) to check/score word ...
I've recently started learning Rust, and I've managed to whip up this function, which reads and parses a thing from stdin. I don't like it though, and I feel it could be further simplified. What do you think? fn read_thing<T: str::FromStr>() -> Result<T, &'static str> { let mut buffer = String::new(); match io:...
I'm writing a binary PowerShell module and have recently started to add wildcard support to some cmdlets. I'm not sure if I'm using an efficient way of creating the final collection of objects to write back to the pipeline. I'm wondering if it might be slightly more efficient to use a HashSet<T> rather than a List<T> i...
I have managed to build an inheritance hierarchy for shape class object and I am wondering if there is a better solution to combine the following 2 hierarchies. To begin, I have a 4 shapes classes triangle, line, oval and square which 3 of (line, oval and square) inherit from abstract class SimpleTwoPointShape and this...
I've been out of working in Java for quite some time now (almost two years), so I've been working on a fun side project just to get back into the swing of things. Essentially, in the long term, the goal of this will to be to compile a library that can be used in to create basic platform-like 2D games. I'm never dealt w...
Microsoft Excel cells basically have two values: the formatted value that is shown to the user, and the actual value of the cell. These two values can be extremely different when the cell has certain formatting types such as date, datetime, currency, numbers with commas, etc. I am writing a script that cleans up databa...
I'm starting to play with F# to do some data parsing and I was able to create a function to group an array of string into sub groups. The code looks like this: let breakBy lines pattern = let rec breakByRec lines pattern acc = match lines with | [] -> acc | head::tail -> match ...
This is a program which computes the circumference of two circles and gives some information such as the difference between circumferences. I want to know whether the method declarations and method calling in my code is correct. I didn't face any errors. import java.text.*; import javax.swing.*; class Q5Main{ pub...
I'm currently learning Swift by following the Stanford developing iOS app 2015 lecture series. I have completed assignment 1 but am wondering if there is any improvement can be made to my code. Also, I have not been able to complete extra credit no. 4, so I would appreciate if someone could offer me a hint. import UIKi...
Checking if some port is up on the network is a very common task when working with remote services. A common way to check is using telnet, but I have two practical issues with that: telnet is not available in all systems, for example in recent versions of Windows. When connection is successful with telnet, an interact...
Is my algorithm slow because it has problems? Or, is any bitwise common prefix solution not going to give me the performance I'm looking for? After profiling my algorithm, I found that over 60% of the time was spent on one line len(os.path.commonprefix((item1, item2))). I'm only looking for the length of the prefix To...
I've created a function to return all the indices where an element is to be found in an array. If it occurs twice or more, all the respective indices will be returned, for now it returns them in natural counting (1,2,3...) and not how the computer sees them (0,1,2,...). #include <iostream> #include <vector> using names...
HRESULTs are the common way for Microsoft technologies like COM and Win32 to return either an error code or messages that mean a specific type of success. They are usually returned as the result of a function. They have various pieces of information encoded in their bits, such as the OS facility that erred, the error...
Before starting I would like to say that I just made this program after studying python for 5 hours for the first time so I am totally new to this programming language. This program tries to create 4X4 board denoting it with 0 everywhere. Now to deploy treasure, it randomly selects 9 position and deploy them on the boa...
I was given the task of making a grid peg solitaire puzzle. Here are the programs, the basic puzzle file, and the actual grid solitaire puzzle: The puzzle software class Puzzle: """" Snapshot of a full-information puzzle, which may be solved, unsolved, or even unsolvable. """ def fail_fast(self): ...
This is the first mini-project I have completed by myself with Python 2.7. I wrote a simple program that calculates the area of different two-dimensional shapes and it works. I want to know what you think of it and also want to know how it can be improved and if I did something wrong, so this is my code: def circle(pi...
The foreach loop seems ridiculously lengthy and I am trying to get rid of it altogether is possible. But there are a lot of things happening in there which I need to know in order to update the UI and create other values. For examples, variables mappedRuntimeName, mappedDeviceName are used for updating the UI and also ...
I've been learning more programming in the past few years (C, Java, Arduino) for my hobbies. I read the "C for Dummies" book and found that it was good, but did not cover much - especially pointers... One of my friends from college (CS major) suggested a simple program exercise to see if I could figure out how to use p...
I just finish coding this code which use for control robot using compass sensor with PID control to control motors. Trying to make javascript object for necessary job. Please guide me for a better code. Watch Video to get how it works I use johnny-five package for control Arduino and pid-controller for PID control. var...
Here is is a fixed code, taking in to account Spurious wakeup issue.Thanks to Costa for bringing that up. ISemaphore: package edu.vandy.utils; /** * This interface provides a simple counting semaphore to manage * concurrent access to a set of resources. A semaphore may implement * "Fair" or "U...
Let L be the language defined as follows: The words are made up of strings of a’s followed by b’s. The number of a’s is always equal to the number of b’s. Examples of words that belong to L are: ab, aabb, aaabbb etc... One way to test if a word w belong to this language is to use a stack to check if the number of a’...
I have a table in pandas that has two columns, QuarterHourDimID and StartDateDimID ; these columns give me an ID for each date / quarter hour pairing. For instance for January 1st, 2015, at 12:15PM the StartDateDimID would equal 1097 and QuarterHourDimID would equal 26. This is how the data I'm reading is organized. It...
I am experimenting with performance evaluation. From the hardware architecture point of view, two main factors are cache misses and incorrect prediction of conditional branches which can degrade the performance of an application. I have considered a small application for each case: Cache Misses: In this application, ...
I have created this ViewController using Swift. Its job is to track geolocation and draw a line on a map and save it to core data object. I just want some advice on improving the geolocation tracking using core location and storing information using core data. import CoreLocation import MapKit import UIKit import CoreD...
I'm not really sure if the following solution is the best fit, and I would like to know best practices when manipulating state and/or Ajax isomorphic fetch requests, in this case, in intervals. Users Module import { createAction, handleActions } from 'redux-actions' import { api } from '../utils/api' export const RE...
I have developed the following method for each as a replacement for $.each, and I am considering using it in my personal lightweight js library called LIBJS. The final version will be part of a javascript class as opposed to a stand alone function. /** * * @method each * @param {Object} obj ...
I have this method in C# that could be refactored. Should I use a design pattern? I see too much repetition and it gets worse if more conditionals are added. Should I change it to a method call? public void CreateOrUpdateReportDefinition(ReportGroupSubReport reportGroupSubReport, bool isNew, int report) { if (repo...
I only need three random numbers within the range of 1-54 (deck of cards) and none of the three numbers can be a duplicate. I cannot use an ArrayList; I must use a standard array. Is the method I chose to check for duplicates good enough? public class Test { public static int genRandom() { // generate random int ...
The diabolical Professor Boolean has captured you and a group of your hapless rabbit kin as test subjects for his terrible experiments! You're not sure what his real plans are, but currently it seems he's trying to make everyone faster and smarter? He's exposing rabbit test subjects to novel chemicals, genetic...
I have started to interest myself in artificial intelligence a while ago, especially within the game industry. I have started with state machines moved on to fuzzy logic and now I want to learn and implement a neural network which will also work for games. However to not overwhelm my tiny little head I wanted to start ...
I broke my server into two classes, a general server class and a client session class. I know the code isn't documented in the header, but I am more interested in the design of the server/session model and whether or not responsibility is correctly broken up between the modules. Also, whether or not the callbacks for s...
I'm comparing my algorithms, slice_prefix and bit_prefix, with existing ones to find the common prefix length of 2 strings as fast as possible. Another program I'm working with spends most of its time on one line len(os.path.commonprefix((item1, item2))). I've searched for other algorithms in Python and created my own...
I have been writing a compiler. While profiling the compiler, one method takes 5 seconds to compile 2k lines of code, my profiler tells me that this is the bottleneck. def toLLVMHelp(self, tree= None, isGlobal= True): if tree == None: tree = self.tree #tree is the Ast for i in tree: #iterate throug...
Task to accomplish: Made a function which counts the amount of words in a sentence. Please don't put attention to the HTML. Is just for testing-purposes. var sentence = document.querySelector('#sentence'); var exec = document.querySelector('#exec'); var result = document.querySelector('#result'); // ## THE ACTUAL FU...
The following code should prove to offer sufficient security for public API so my main concern is about design flaws in process. It is meant to describe the process and eventually get included in client side of API. Full code is available at github GitHub. As for time of publishing the question, it's in sync with code ...
I need to wrap httpClient because I'm using a custom token provider. I will use this code with asp.net mvc to communicate with our webApi2 server. ( Using webApi2 with directly from ui with angularjs etc. off the case. ) I shared this code and asking your opinions because; I don't want any deadlock to occur. I see c...
I need to parse logs and have got following code. I can see two problems: map().filter() may induce some performance penalties and copy-paste block parser.py: class Info(object): a = "" j = "" z = "" infoline = "" def __init__(self, a, j, z, infoline): self.a = a self.j = j ...
I'm very new to VBA and have put together a macro that currently does exactly what I want: copy cells from one worksheet to another, clear the cells copied, refresh my pivot tables and save the file. Here is what I am using for it: Sub Copyinfo() On Error GoTo Err_Execute Sheet1.Range("A17:R17").Copy Shee...
I wrote a NodeJS HTTP server specifically for serving static files. I didn't bother much about security since the server is going to be used locally in my Electron application. function buildStaticServer() { const fs = require("fs"); const urlModule = require("url"); return require("http").createServer(func...
For a post-graduate subject that I present, I maintain a repository of examples (on GitHub) from the textbook which is contributed and edited by my students, who are not very Python literate. I have written this code to run all the programs associated with figures, examples and exercises in the book and use it to alert...
Here is what I have to do: Write a function scramble(str1,str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false. For example: str1 is 'rkqodlw' and str2 is 'world' the output should return true. str1 is 'cedewaraaossoqqyt' and str2 is 'codewars' should retur...
The following code is part of a game I am making using the Phaser framework; the game is in the style of a top-down RPG, with the player moving their character in four possible directions using the arrow keys. This code appears in my update() method. I like the user experience provided by this code a lot: the character...
My assignment was to develop a REST service that will provide Airport information. This service is assumed to be used by multiple users, therefore data consistency (thread safety) and responding fast are the main concerns. Following you can see implementation details. AirportData is the core data object of this servic...
I have login page that looks like: It has a ViewModelBase and a ViewModel as: public abstract class UserViewModelBase { private string userId; private LdapDirectory ldapDir; private XXXPerson userDetails; public UserViewModelBase() { ldapDir = new LdapDirectory(); if (HttpContex...
My experience with autolayout tells me that it's very difficult to make app look good on whole variety of devices (from iPhone 4s to 6s especially). Size classes are useful with device position and distinguishing between iPhone and iPad. To make my app look right on each iPhone size, I connected contraints to my viewCo...
not too experienced with SQL, wondering if I can make this better... I am trying to check if a row exists and then add one to the frequency column if it does, if it does not exist it should return false... The table is indexed by the column in the first select statement I know about the risks of using formatting with p...
I've recently stared learning C++ so I'm new to all of it. I've got my fourth "software" under development. Could someone have a look through and give me some constructive criticism on what should I change or keep the same? #include <iostream> #include <string> #include <stdlib.h> #include <fstream> using namespace st...
I Have written this program to add workers into a list and print them. I'd like a review of this. I'm especially concerned if the method Addworker should be inside the class or in the main program. Person: class Person { public uint NumberId; public string Name; public string LastName; public uint Age; ...
This post builds on my post about quickly evaluating analytic Jacobian in Matlab. The key difference is that I am now working with the Hessian and I have to evaluate close to 700 matlabFunctions (instead of one matlabFunction like I did for the Jacobian) each time the hessian is evaluated. So there is an opportunity to...
I have made a Priority Queue implemented as a Binary Search Tree. I would appreciate comments related to optimization and proper functionality, but any comments/critiques are welcome. PQ.h: #ifndef PQ_H #define PQ_H #include <iostream> struct Node { int value; Node * left; Node * right; Node(int value...
I have created a common C file for a basic client server. It works fine on my Linux setup. Please provide your comments/suggestions on how the code can be optimized/enhanced. After compiling we need to give parameters "s" or "c" to executable from the command line to run it as a server or client respectively. The clien...
I have the following structure returned from MongoDB: [Class] 0:Class // -> this.data.userInfo as seen below in the code _id: "ksihHTAjdhsA9" createdAt:Tue Mar 29 2016 13:03:45 GMT-0400 (EDT) weightData: Array[3] 0: Class name: "my name 1" value: "...
The following function calculates temperature based off of a given suction pressure, where different regression coefficients are assigned depending on the value of the pressure. The regression equation is fairly standard, of the form: $$ax^2 + bx + c$$ where \$x\$ is the pressure, and \$a\$, \$b\$, and \$c\$ are the co...
I have a query that works as intended, kind of pulling from multiple records in a table, and flattening the data into one row. I am wondering if there is a faster/more semantically correct way to do this than multiple derived tables? ID Name Relationship Amount -------------------------------------------...
The program needs to find all contiguous sublists of numbers where the number of occurrences of every member in the contiguous sublist is divisible by 2. The first line of input is N (the number of ai, where N ≤ 353535). The second line of input contains the ai, delimited by spaces (where each ai < 109). Here is an ex...
This program generates 6 random numbers between 0 and 45 and the numbers cannot be repeated. Can this code be improved? $numbers = []; $i = 1; while($i <= 6) { $number = mt_rand(0, 45); if(!in_array($number, $numbers)) { array_push($numbers, $number); $i++; } } sort($numbers); echo ...
I am implementing a simulation of colliding disks (ideal 2D billiard balls) in JavaScript. I follow an event-driven algorithm that avoids discretizing time; the algorithm goes as follows at each step: Compute the moment of the next collision (with walls or between two disks) Translate the spheres during that time inte...
For a class, I was given an assignment to code a simple TCP connection between a server and a client. Once the TCP handshake is done, the client sends inquiries to the server. It's a 2 second conversation, if that. I need some feedback on my code. Please keep in mind that I am new to Python. The prof kinda threw the cl...
I have an Ajax request which in turn on completion make another Ajax request: $.ajax({ url: '<?php echo BASE_URL.'Dashboard/GetMyTrackList' ?>', type: 'GET', success: function (response) { var list = JSON.parse(response); $.each(list, function (k, v) { ...
There is a code that takes all files from input of multiple files, gets base64 for each of them, packs to array and jsonifies it. How to simplify and improve quality of code? text = $('#input-' + id).val(); var files = document.querySelector('#files' + id + ' > input[type=file]').files; if (text != '' || files.length >...
I have made the algorithm that split text into n-grams (collocations) and it counts probabilities and other statistics of this collocations. When file is more then 50 megabytes it takes long time to count maybe some one will help to improve it. import math import re import csv from itertools import zip_longest from dat...
My goal was to use the NHibernate Session and to create a UnitOfWork class that I could use thoughout my project. My goals are: Calling Commit should commit everything including un-flushed state (was mostly out of the box I believe) Rollback should roll back everything including whatever was not flushed from the scop...
My Scenario: #TmpDistinctFolderIds table contains one or many FolderId. fnGetAllParentFolderIds function receives the input as FolderId and return it's all possible parent folder ids (a parent folder can have N number of sub folders). I'm using the below block to get each folder's all possible hierarchy parent folder ...
Part of my standard modules deal with my company's employees and linking them to/from various data sets. The following are a series of enums/functions to handle peoples' names, namely an Enum for advisers and functions to: Provide a collection of names associated to each adviser (e.g. their name before/after getting m...
The method below converts an array of TheatreListData objects to an array of TheatreListDataWrapper. It also loads additional attributes such as patientIdentifierNumber and requestText to enrich the converted data. This method is called by many EJBs, and so I'm especially looking for ways to improve performance. /** *...
I have UserSignatures, a table with clientIPs, some of which have CountryIds that are null and need to be filled in. A second table, IpLookups, stores IPs, and a third table Country has the needed CountryId. This is workaround at the moment, because we don't fill CountryIp yet. declare @var1 int,@var2 int,@var3 int,@in...
I am currently working on a method, that can search based on a value and an operator. Currently I check which operator was supplied to the the method in a switch, and do operations accordingly to it. This is the current code: switch (enumOperator) { case Operator.Equal: tmpResult = tmpResult.Where(a => a.NU...