instruction
stringlengths
71
71.9k
How can I improve my singly linked list implementation? "use strict"; var LinkedList = function(){ this.head = null; this.tail = null; this.count = null; } var Node = function(value){ this.value = value; this.next = null; } LinkedList.prototype.addToHead = function(value){ var newNode = new Node(value);...
I have a products page with a search box. When a search is submitted there's a redirection to a search results page. If another search is submitted then the query string remains intact (results are populated via ajax). So what I've done is running twice to the server, one time using ajax to set the Session value and an...
Using JavaScript ES5, I would like to know if you could suggest me a more "elegant" and succinct way to overriding defaults variable when User pass custom values. In the following example, an animation is executed using _defaultOptions, a developer can change the default behavior passing only some properties to a funct...
Given a list of numbers, e.g.: 25626 25757 24367 24267 16 100 2 7277 Output a delta encoding for the sequence. In a delta encoding, the first element is reproduced as is. Each subsequent element is represented as the numeric difference from the element before it. E.g. for the sequence above, the delta encoding would be...
My code is working now. As you can see in the list.h some type definitions are too long and hard to read. Is there a way to do some short ones? And what happens if the code throws an exception? (I know I will have leaking memory parts) What can I do to collect garbage? And what other functions might be added to code to...
I'm developing a common library for my organisation that will be used across different services by different teams. The library is a simple wrapper for RabbitMQ. Some services will only be producers, some will only be consumers and some will be both. For that reason I have created a Consumer and a Producer. Each of the...
I've written a lambda to perform simple steps to a redshift database. It runs multiple queries with transaction. I use pg-promise. 'use strict'; const config = require('./redshift_config_from_env'); const redshiftConn = `pg://${config.user}:${config.password}@${config.host}/${config.database}`; const pgp = require('pg...
I'm currently developing a small Angular tagging module which will enable me to populate an array from a text input, pretty much like Selectize to give an example. I'm using a BehaviorSubject and give back the same BehaviorSubject as Observable to which I then subscribe and push the filtered value in an array. I have t...
I did this library to help me from one of my projects and decided to publish it on GitHub hoping people might find it useful, convenient and easy to use in their projects too. It's a header-only library. The library design is inspired by some popular Java code conventions, like naming of classes and the popular usage o...
This is my version of Merchant's Guide to the Galaxy: A merchant buys and sells items in the galaxy. Buying and selling over the galaxy requires you to convert numbers and units. The numbers used for intergalactic transactions follows similar convention to the roman numerals. Roman numerals are based on seven sy...
For a further education I had to do the following task: Implement the BubbleSort algorithm within the Java class algorithm.Sort. Submit your solution to the JUnit system for automatic evaluation. Here the source code of my Sort class. The requirements concerning the single methods I've added as comments. package al...
For building an LSH based system in Python, I need to have a very fast calculation of the hashcode. I won't need to explain here the LSH algorithm itself, but I need help in improving performance of the generate-Hash-Code operation: Given a big number of features n (example: 5000 or even 50000): multiply a dense matri...
Follow up to this question : Snake Game in C# The game plays like it did in my first question. The design is altered. Gameplay Video Some of the changes: Polymorphism is removed, replaced by Interfaces (see interfaces.cs) CreateGame, DeleteGame and GameOver are now methods in Game Snake movement is handled differenly...
I'm trying to generate a report from two doctrine entities. The fields to filter the report are optional. This is the code I've got now and it looks really bad to me. How can I improve this? public function filter($accountNumber, $companyName, $branchName, $branchManager) { $em = $this->managerRegistry->getManager(...
The reasons I create this program is because we had an issue of XML elements showing up with older assembly versions in, which were duplicate elements of the same element with the new assembly version in. Here is an example of the problematic files we have: <data attribute="value" > <value>Version="dot_net_4_assemb...
I am trying to brute force code Brainfuck code to get the desired output. For this, I need my code to be as fast as possible. I am fairly new to Java and making my code fast, in general, so don't assume that I have done something for a good reason. import java.util.regex.Pattern; public class BruteForceBF { public ...
I have an app where the user can search for items in my database by entering a set of information, then the server receives it and for each option it queries the database, and stores the result in a list. I have around 10 different options and each option have from two to three possible values, so it's taking around 20...
Here is my approach to creating a loading text spinner in the console. I did what I thought was best in designing the class, which means there is probably a lot of room for feedback. The class is below, along with it's usage inside a Utils class. You can also find it here on github if that's easier. Concerns I have pos...
I try to remove elements in an array if the number of contiguous element is greater than two. Here are the tests: test('delete pieces if number of piece contiguous greater than two', t => { t.deepEqual([null, null, null], removeIdenticalPieces([1, 1, 1])); t.deepEqual([null, null, null, null], removeIdenticalPi...
Given a heap of pixel data, and a width and height associated with that pixel data, I've written code which will save that data as an image, and it more-or-less works as expected. //I'm using the FreeImage library. #include<freeimage.h> /*Some other, irrelevant code*/ namespace filesystem = std::experimental::filesys...
Is there a shorter way to write this code or parts of it and where can i inculde some try and excepts for validation People={"Dan":22, "Matt":54, "Harry":78, "Bob":91} schoice=input('Enter existing name: ') while schoice not in People: schoice=input('Invalid entry name is non...
I am building a small and 'simple' PHP framework to see if I can bring my PHP skills to a new level and to review the knowledge I have required during OOP classes and tutorials I've done. Currently, I am building the Router class. I know people will try to discourage me reinventing the wheel, but since this is for lear...
This is my version of a LZ-77 lossless compression algorithm for text. It maintains a sliding window of 4095 characters and can pick up patterns up to 15 characters long. Basically, the compressed file is made of tuples (length, pos), with length on 4 bits and pos on 12 bits which makes 2 bytes each time. Besides, if I...
I've written a function that produces all combinations of elements in a given list: createGroups :: [a] -> [[(a, a)]] createGroups li@(x : xs) = map (\el -> map (\el2 -> (el, el2)) xs) li These nested maps seem quite messy -- is there a better way to do this?
Having a text file './inputs/dist.txt' as: 1 1 2.92 1 2 70.75 1 3 60.90 2 1 71.34 2 2 5.23 2 3 38.56 3 1 61.24 3 2 38.68 3 3 4.49 I'm reading the text file to stor...
I'm sure that my intentions are highly erroneous, and I really just want to see what you guys would suggest I do instead. I have a class I made for my game which helps store various values regarding resistances, aversions, attribute modifications for buffs and debuffs, and damage mitigation and damage amplification vs ...
Background: I have two lists: one with a list of workcentres and the other with a list of the stations in the centres. This code matches the stations to the centres by comparing the stations' workcentre number property with the name property of the centres. private void WsSorter(WorkcentreList wcl, List<Workstati...
This is my main class which handles the looping and setup of the game: import java.awt.Canvas; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferStrategy; public class Game extends Canvas implements Runnable { /** * */ private static final long seria...
In my previous question I got some pretty good suggestions which really improved the overall performance of the controls, but I decided to extend the application and add some more features : You can enable/disable auto-updating. You can select which processes you want to view currently available options are : Defaul...
For my game I decided to incorporate .ini Initialization Files to store game data. Items like: Weapons, Armor, Potions, Enemies, Actors, Loot Drops, and so much more. All of these things can be easily expressed as simple .ini files with the header-based schema, as I will show later. This design decision also came about...
What is this? This is a two-dimensional physics simulator that models gravity and collisions between circular objects (though it doesn't model rotation). How do you use it? You can tweak the following parameters of the simulation while it is running: Number of objects: The specified number of gravitational objects wil...
I needed to create commands simply with lambda and execute it in another thread. The following code works fine. Any suggestions about performance are appreciated. I want to use SSE aligned variables as lambda captures, for instance: __m128 xmm0; queue.Enqueue([xmm0](){ //... }); template<unsigned MaxCommand = 10...
Problem Given an array A of unique integers, find the index of values that satisfy A + B =C + D, where A,B,C & D are integers values in the array. Find all combinations of quadruples. I posted two versions of solutions and am wondering if there are any further smart ideas to make it run faster. I thought there mi...
I am working for an Aero-Design team and we make RC planes that are capable of humanitarian aid. We wished to make a tail dragger and for stability reasons the "Angle of Incidence" (AOI) of the plane has to be between 10 to 20 degrees when it is grounded. Now the AOI depends upon a number of factors such as LHT, LVT, h...
I am writing an application using Qt5.7.1 which suppose to run as single instance application. One of the requirements is whenever user launches second instance of application, this instance should notify original one and exit. To achieve that I wrote a class below (based off the SO question on similar topic). However...
I'm doing code challenges to learn Common Lisp. I'm trying to invert all the bits in any given positive integer. My current solution does it the math way, by recursing on a number, dividing it by two, and inverting the remainder before multiplying and adding back up: (defun invert-bits (n) (if (> n 0) (+ (...
I am a beginner C++ programmer and I have been working on a library to use for working with matrices. The library main features should be Working with matrices (addition, subtraction, arbitrary operations) Lazy Evaluation and Reference Counting Modifiable underlying container Of course, all of this trying to maintai...
I am studying Python, so it is very easy task. I want to get best and most elegant way to solve each simple task. The task is: Write a program that reads the integers from the console one number per line. For each entered number check: if the number is less than 10, skip that number; if the number is greater than 1...
Given a boxed integer (with a boxed short, int, ...) I want to convert it to an unboxed, nullable type instead. It should be possible to convert non-matching types (for example: boxed int to short?) Can you please comment on: using System; public class Test { public static void Main() { int? x = Unbox<...
I need to remove some unwanted characters from a given column in all Worksheets from my Workbook. The code below works perfectly, but I'd like to know if there is a better/cleaner/faster way of doing this. What exactly am I doing? I am storing all unwanted/forbidden characters in an Array, after that I'm walking throug...
I am learning Python online on Stepik platform, and unfortunately I don't have any opportunity to get reviews from the tutor. The platform only checks the correctness of the answer that my program gives. So I decided to share the code here. Comments and corrections would be much appreciated. Write a program that print...
I'm currently writing a web framework and I wanted to add a configuration module for reading environment variables and a configuration toml file. Here is the code. The comment in the Config class should explain it all. import os import sys import toml BASEPATH = os.path.dirname(sys.modules['__main__'].__file__) print(...
As the title says, the problem I had to do sounded something like this: We are given two words, S1 and S2. We must transform S1 into S2, using the following operations: insert: insert a character in S1 on whichever index you wish. delete: delete a character from S1 from whichever index you wish. replace: replace a cha...
I have been using SwiftyJSON to create my models of Object in Swift. But recently, I moved to CoreData for saving the objects locally. I am new to CoreData and want to know the best practices I should follow for creating the model. Here's what I have created to update and get User's data (after getting the JSON from we...
I'm trying to solve this challenge, which consists of finding the next biggest number formed by the digits of the passed in number. If it is impossible to find a number larger than the passed in parameter by rearranging the digits, return -1. EX: nextBigger(12) === 21 nextBigger(2017) === 2071 nextBigger(987654...
I have the following LINQ to SQL query which works fine but looks ugly: var filter = "filter"; query = query.Where(x => x.Name.Replace("'", "").Replace("\"", "").Replace("#", "").Replace("/", "").Replace("-", "").Contains(filter) || x.FullName.Replace("'", "").Replace("\"", "").Replace("#", "").Replace("/", ""...
I have the following code to find xml elements that have a particular attribute value: IEnumerable<XElement> elems = xmlDoc.Descendants("elemName") .Where(x => x.Attribute("attrName").Value .Equals( filename, StringComparison.OrdinalIgnoreCase ) ); The prob...
I have made a Python program to find the day of the week of an inputted date. I did not want to use the time or datetime module, like in this answer, as I found that a bit too easy. (I like to challenge myself) I want to improve on appropriately putting certain tasks in functions, so my program is easier to read and fo...
I need to iterate through a DataTable and columns in each rows and do some data manipulation. Below given is an extract from my code, I use c#.net. I expect maximum rows in datatable will be less than 25K. How I can improve the code for better performance? DataTable metadaDataTable = GetMetaDataTable(); foreach (DataRo...
I want to improve this code. I know I'm not fully utilizing the data structure. (This is not a homework assignment, I finished and passed the class this fall semester). I would really like to know for future reference. /** * Words indexed by this trie. */ ArrayList<String> words; /** * Root ...
Most importantly which bothers me in the following implementation is the call in BranchAddManager, do I really need to call base.StartAddNewOperation();? How can I get away without making this call? public override void AddNew() { //I would like to avoid calling the base method, if I forget then I may run i...
import time import csv import argparse from nsetools import Nse from colorama import Fore nse = Nse() t = time.time() CSV file contains the following data, I added it so that others may know the contents of the file. In the actual program I use a real CSV file in FILE_LOCATION variable. CSV file contents: Instrument...
This is my answer in freecodecamp "Basic Javascript: Profile Lookup" (third day trying javascript using Udemy and freecodecamp). My problem with the code is the huge number of lines on my lookUpProfile function. I would like to minimize the lines of code of my lookUpProfile function, can you suggest me ways to achieve ...
Working on a game I need to record events compute some values about it (the more the better). The twist is, I need to store as little data as possible. Constant (as in O(1)) weight is required. The following code is not acceptable : public class Player { private List<float> previousGamesDuration;//Too heavy flo...
I'm building an (open source) online tool for users with NO speech who are also blind. The program steps through a list of utterances in a female 'thinking' voice, and when one is selected, speaks it in a male 'speaking' voice (switch genders for a female target users). I've written a demo of the 'display' half of th...
I wrote a "Smoke" effect that I thought I'd post for code review. It's a decorative effect for a puzzle game I'm working on--there will be four of these, animated independently, probably with a purplish tint. I'm mostly interested in feedback on the "Smoke" class, not so much the little JavaFX scene that displays it. ...
I'm trying to create a generic notification service that works with Mail (smtp ) Sms (Third part vendor) Push events (For future) Purpose : Create a notification service and it should be pluggable A Common interface for all notification service public interface INotificationService { bool Notify(); } Mail Ser...
I need to run CPU-intensive tasks on a very old machine with overheating issues. The script below will monitor temperature and pause the jobs when it gets too high, continuing them when it's back to normal. The actual commands run are, of course, not included, since they are irrelevant to the question. I am looking fo...
I have been tasked to create a GUI that asks the user questions about a mobile device.the GUI I have created asks the user a sequence of questions to try and come to a solution.However, I feel that my inexperience with GUI has made me repeat myself a lot with this. Therefore, is there anything i can do to make this mor...
I am a Spanish programming teacher in a vocational training course and we are studying arrays. In order to practice and to get the students familiarized with some methods of the String class, I proposed them to reinvent the wheel, implementing some methods of the String class using char arrays. This is the solution tha...
I've made quite a long text-based game which I'm quite proud of and would like to know ways in which to improve it! I plan to keep working on it and make it much longer and more complex! Main: import java.util.Scanner; import Saves.GameSave; import Saves.GenderSave; public class MainGame { public static GameSave ...
As part of studying algorithms, I needed to make a function to count occurrences of characters in a string. My solution is below. I'd like some feedback about how I did - could the implementation be cleaner? Are there any conceptual gaps my code suggests? <?php function ra_count_chars($str){ $dict = str_split(strto...
I am trying to improve my general skills in C++ so I plan to write versions of shared_ptr and unique_ptr from scratch. I wrote a version of shared_ptr with reference counting and I was wondering for reviews. #ifndef __SHIVA_XSMARTPTRS__ #define __SHIVA_XSMARTPTRS__ /* This tries to define a reference counted smart poi...
I'm trying to continue the learning process in Java, and I've made a simple yet useful class which will allow me to retrieve the data inside a table from an Oracle DB, using JDBC. What I'm especially looking after in a review is: styleguide - as in naming variables / classes, spacing, and so on) usage of correct data...
I have the following code: resolved = [] rejected = [] for file in files_within("./_input/"): file = File(file) if file.extension.lower() == "gdb": resolved.append(file) else: rejected.append(file) MAP["resolved"] = resolved MAP["rejected"] = rejected And i would like to improve it to avoid...
I am working on a data recorder in my library for pseudo-realtime systems. I have a default templated record() function to cover basic data types, and library users can specialize that function for custom data types (e.g. for images they could write a flag to the main data file then record the image to a directory some...
I'm writing an operation to find the lowest missing element of a vector, V = 1..N + 1. This has to be performed in \$O(N)\$ time complexity. Solution One: std::vector<int> A {3,4,1,4,6,7}; int main() { int max_el = *std::max_element(A.begin(), A.end()); //Find max element std::vector<int> V(max_el); std::...
I have created this PHP script in Laravel. I have database table with items and in my app I can create tags with different regexes. If regex matches text in description or epoch. I will insert relation into ItemTag table. My current solution is really slow (few hours to run). I have about 200 000 items and will increas...
I posted the original question here, but I think it would be nice to have someone else's eye on this code for improving it. public override void Update(UserProfileDto item) { base.Update(item); var memberIntersestIds = _memberInterestService.GetAllPlusDeleted(); var dbIds = memberIntersestIds.Select(p => ...
I have a function that takes an unsigned value and transforms it into a std::vector<std::uint8_t>. The requirements (and post conditions) are as follows: The code must utilize "modern C++" up to C++14 The focus is on readability/maintainability first, performance second The most significant byte must be at index 0. Th...
I'm learning Elixir. while building a trivial cli application (as seen here http://asquera.de/blog/2015-04-10/writing-a-commandline-app-in-elixir/) I'm defining a module that implements a main/1 function that accepts a List as an argument. My question is: What is the best way to pattern match a method against a non-emp...
package com.company; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import static com.company.Person.id; public class Main { private static Scanner in = new Scanner(System.in); private static File file = new File("Addresses.txt"); static List<Person> peopl...
I wrote code for determining the push button state whether it is long pressed or not. This function is called by timer interrupt routine every 1ms. But it seems really dumb. How can I make it shorter and more efficient according to both readability and professional rules? What should I add or change to get double Tap p...
In Swift, should I be posting notifications to the iOS notification center from the device sending a text message or from the device receiving it? I'm using OneSignal, so my code to send a notification from the sender device to the receiver device looks like this: OneSignal.postNotification(["contents": ["en": "You've ...
I am implementing a Request class in my MVC framework that stores all the required information from a page request. It surely does it's job, but I was wondering if this is secure enough. I see alot of people advising against the use of $_SERVER['REQUEST_URI'], since this can be manipulated by the end user. Have I made ...
In this class, the order of the last 3 statements in the constructor is important. If you call OrderedCards = OrderCards(cards, wildcardsCount); last, it will crash with NRE. Is this a bad idea? If so, how should I fix it? /// <summary> /// The abstract result of analysis describing the combination of cards /// </summa...
See here: https://gitlab.com/linted/linted/blob/162b5e9fba53a90b3c6d78e214776e069c3c722b/src/ada-core/src/linted-queues.adb The code implements a concurrent queue. It can't allocate memory or use many other niceties because memory allocations are difficult to reason about with formal methods. So the package has to use ...
Problem: In a grid of nodes pick a starting node(has mode2), and using Breadth-First search, find one with a ending node (has mode1). You can make walls so it's harder for the search. And that inspired me to make an algorithm which creates mazes, so my search will have something interesting to solve. I want to know h...
I have a custom logger which logs all messages at WARNING level and above to a Slack channel. Certain error messages occur so frequently that they make it hard to see actual errors in the channel, so I would like to be able to disable Slack logging for a specific message, using something like logger.error("This is a co...
I'm writing a small custom DSL and interpreter as an exercise in understanding how the language stack (lexer/parser/(interpreter/compiler)) works. Because I want to be able to report the location of semantic errors, the AST needs to retain information about where the elements were in the source. For this purpose I wrot...
Please critique to help me learn: int getNextInt(int* number) { int value = *number; (*number)++; if (*number > 3)*number = 1; return value; } I want a function that will increment an external number by one, when it goes over than 3, then reset it to 1. essentially when I repeatedly call this function ...
I am a system admin, not a developer, so this might be pretty horrible code. This is a password generator. The point of the attempt was to become more familiar with Django at a lower level. I current host Django sites other developers write and sometimes it would help to have a better understanding of how the sites wor...
Problem: Given a picture of square with a bunch of horizontal and vertical lines in it (lines are not necessarily spanning the full square length, in other words think of a fine grid with many holes in it), design data structure(s) representing the data and a function that returns a number of squares pictured. My ide...
I was recently doing a challenge on Codewars and this is what challenge said: There are no explanations. You have to create the code that gives the following results: oneTwoThree(0) → ['0', '0'] oneTwoThree(1) → ['1', '1'] oneTwoThree(3) → ['3', '111'] oneTwoThree(19) → ['991', '1111111111111111111'] I have solved...
Assume a binary tree with a data structure like this: typedef struct binary_node BINARY_NODE; #define BINARY_NODE BINARY_NODE struct binary_node { BINARY_NODE *next[2]; /* 0 -> left */ }; Assume insertions maintain a relevant order, but there is no balancing criteria. removeBinaryNode() takes a node and its paren...
I have a folder which contains lots of files. I need to write C# code that will open and read and display the content of it. Is this efficient code or should something be changed? using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Security; using System.Threading; us...
I am an experienced Python developer learning C. I solved this assignement: Write a program that reads a word and some sentences from stdin. The word is separated by space from a sentences. The sentences are separated by one of the following characters: .!?. Words in sentences are separated by any char for which one o...
I wrote a simple calculator program. How can it be improved? #include <iostream> // get a double value from user double getDoubleValue () { while (1) { std::cout << "Enter a double number: "; double d; std::cin >> d; if (std::cin.fail()) { std::cin.clear(); ...
I am studying computer science and just for the sake of practise I thought of implementing an object pool. This is my first implementation, it is simple and works correctly, but I would love any thoughts on it. Currently, the memory is allocated on the stack, but I am thinking of using policy based design to allow heap...
About half year ago, I derived a integral of a piecewise polynomial, which was a complex formula. Below is one of that formula: Obviously, the above formula has relationship with four varibles \$u_i,\cdots u_{i+3}\$. In the begining, I implement it in Wolfram Mathematica with the help of Compile[] technique and corres...
I have a bit of EF Lambda code which returns a list of data from the db table, then orders by a field called IsDefault At first, the code was var listOfData = Db .TableName .Where(u => u.UserId == userId) .OrderBy(u => u.IsDefault) .ToList(); Which when writing down, sounds correct. However is wrong as...
Currently I'm trying to redo this code to avoid the breaking line because of the 80 characters rule: def decompress_all(directory_path, remove_after): """ """ try: if 0 in [ decompress(file_path, remove_after) \ for file_path in files_within(directory_path) ]: decompres...
I've developed a simple application to grab golfer index scores from a website that has no API. The application works but is very slow, with 6 users that require updating takes 60 seconds. I've tried to make my web requests asyncronous to offset some of this lag but it only resulted in a 15% increase in performance. De...
I'm trying to determine if this code could be a memory hog with huge files. Can anyone tell me if there is anything I can do to make this more memory efficient, or is this how java.crypto works? private byte[] symmetricDecryptAttachment(byte[] encryptedAttachmentBytes, byte[] keyBytes) throws IOException, GeneralSecuri...
please review my code on selection sort algorithm: selectionSort(); function selectionSort(){ var numArray = [4,34,2,5,12]; var MIN = 0; var totalNum = numArray.length, temp = 0, next_position = 0 for(var i = 0; i < totalNum; i++){ MIN = numArray[i]; next_position = i ...
Previously in the Settings JAVA_HOME with batch post, I had created a script in bash to change my JAVA_HOME env variable. Since then, I have been trying to use more and more PowerShell so I recreated the script with PowerShell. The script has several options that provide different functionalities: e or echo : output t...
I am using a global class (like a global model) that acts like a sql abstraction layer for my application. I am using it without problems now, but since the application I am creating is getting bigger, I would like this class to be reviewed if this is really a fine abstrraction layer. I cannot use a proper ORM or frame...
A binary relation \$R\$ on a set \$A\$ is called reflexive if and only if \$R(a, a)\$ for every element \$a \in A\$. I want to know if there can be any improvements made on the function below to make it more efficient. def reflexive(R): ''' @param R : set containing homogenous elements ''' result = [] ...
I recently added Pool Checkers to my Checkers game. My main concerns are about how I manage calling the correct variant in my PublicAPI functions. Because this is a library, any public-facing method in PublicAPI can be the starting point, and because I use pure functions, I have to get the information in every functi...
Here is my recursive implementation of a power set function in C++. One thing that concerns me is that I am iterating over the set of sets while modifying its size. The code nevertheless functions as desired. Any feedback would be highly appreciated. #include <iostream> #include <set> #include <vector> template <type...