instruction
stringlengths
71
95.1k
I have decided to rewrite what I did here, following the suggestions to use smart pointers. I will rewrite the other data structures as well using smart pointers where appropriate. I just want to see how my code stands now, I am sure there are still areas I need to improve or fix. I again want to thank this community i...
You need to remove the first element which contains a given value from a doubly linked list. I created two solutions since I find the edge case of removing the first element to be problematic. So I solved it using 2 approaches: using void function and ref using return value using System; using System.Diagnostics; usi...
Outline: This code uses the Split function to extract specific information from the following website: https://www.webscraper.io/test-sites/tables. The required information are the four tables visible on the page with headers "#", "First Name","Last Name","Username". I am extracting the information within these into 4...
This is only the front end side of things which I have at the moment, as the back end is still being worked on. But as this is my first attempt at a react component, I'd like to know if there is anything I can improve on it. The component has a text area for viewing the current data stored in the cache within our appl...
Having a view (grid control) that provides some functionallity via methods (primary SerializeView / DeserializeView) that should be called from the view model which is bound to the view. One point to consinder is, that the view model may not be bound to the view during the deserialization process. Therefore, the serial...
I'm working on a website where different things can occur on resize and scroll events. I only want one event handler that comes into play, whenever something in the DOM must be changed. So I created a TaskManager where you can register objects and callbacks, that are run, when the specific event is fired. The TaskManag...
I am new to C# programming. I wrote a little program in C# to calculate all primes until a user-given value. Ignoring the lack of computing power I wrote this program to handle theoretically very huge numbers. The code works properly. I have no error handling simply because it is a little program for myself. But I'd li...
I wrote PHP code to display a Woocommerce notice - "free shipping for $40 & under" only once on shop page and once on cart page, but also in cart should not be more than 40$. The code works, but i am not sure that it is the best way to do it: $actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "ht...
I wrote a simple C++ template meta function for filtering out types from a list not matching a predicate. This is similar to Filtering variadic template arguments but does pattern matching instead of std::conditional with the aim of being faster. To that end no empty typelists are concatenated which should incur less i...
I just wanted to ask if this is a secure code (doesn't really matter if it's optimal or not) The code if(!$_SESSION['logged']){ if(!$_POST['inputlogin']||!$_POST['inputpassword']){ require 'cpanellogin.php'; die(); } else{ $con=mysqli_connect("localhost","root","","librarydb"...
I am attempting to update some legacy code that I work with, but my knowledge of data access is limited to a basic use of Entity Framework and simple Dapper. After some research, I have a loose attempt at implementing the repository and unit of work patterns in C# using Dapper. In the actual implementation of this, the...
I have implemented travelling salesman problem using genetic algorithm. Since project is not so small I will give short introduction. GeneticAlgorithmParameters - Struct responsible for general algorithm parameters. Point - Super small struct, you can think about it as a city or whatever. Path - Class which contains on...
I implemented the Shunting-yard algorithm in Python, I have experience in C# but I'm looking for comments making this more pythonic. I'm also be interested if these methods would be better as classmethods instead of staticmethods. from collections import deque import re class ShuntingYardParser: """Converts an in...
I created this script to stop and then start specific services across an environment of 8 servers. The server names are Apollo-1 thru Apollo-8. I'm looking for suggested changes to make sure my script is acceptable for production. #Create a credential to be used on remote machines $User = "MyDomain\myusername" $Pas...
I'm trying to figure out how to create a NHibernate UnitOfWork using .NET Core Dependency Injection. I was just hard-coding the connection string before moving it to appsettings.json configuration file. Is this form of creating a UOW in the service.scope valid? It works, but I'm not sure if this is the intended way to...
I was solving this sorting problem, and I was wondering if I can get any code review and feedback. You can find this problem online. # Find Kth Smallest Element in a Range # # Prompt: Given an unsorted array of whole integers in the range # 1000 to 9000, find the Kth smallest element in linear time # ...
I would like to get some code review for my recursive implementation of python flatten array method. Write a piece of functioning code that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. I'm particularly looking for some feedback ...
I'm retrieving the operating system platform with .NET Core with system.runtime.interopservicesI have created the code below and was wondering if there was any other way that I could improve it since I haven't been able to get a switch statement to work in the OperatingSystem class. /// <summary> /// Operating System C...
I was given 15 minutes to write the code to reverse a singly-linked list. What do you think of the code style here? using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LinkedListQuestions { [TestClass] public class ReverseLinkedList { [TestMethod] public void ReservseLinkedListTes...
The method below is returning a string of random characters using RNGCryptoServiceProvider. The return string result is built by picking characters from the string chars by applying % chars.length on the byte values (0-255) in the array of bytes returned by GetBytes(). This means that some characters will be favoured...
I implemented a password field based on the peewee framework to handle passwords of accounts in web applications for Python 3.4. My goals were Secure hashing. No plain password leakage. Easy password verification. And this is what I came up with: peeweeplus.passwd: """Argon2-based password hashing.""" from argon2 im...
I wanted to create slider when it slide center slide width must have incresed and the two slide next to it stay on normal slide. I have tried one using slick slider. Here is the code pen link that I have tried. But this is not smooth and slide next to center slide not showing properly. If anyone know some better slider...
I'm very new to python and programming in general. For a school assignment, I made this Memory Game and would love to receive feedback from you guys. import tkinter as tk # imports tkinter as tk from tkinter import font as tkfont # imports font as tkfont import random # imports random import string # imports strin...
I'm currently learning python / network programming altogether and I coded this simple python reverse shell; I would like to hear any remarks from you regarding code structure, any common beginner mistake, actually pretty much anything that feels wrong with my code. The code is pretty straightforward, the client sends ...
Given an array of integers, find the longest consecutive sequence, where a sequence is defined as being either (strictly) ascending, (strictly) descending, or all-equal. 836926 then has the longest sequence 369, which happens to be ascending. 241455556 has the longest sequence 5555, which happens to be all equal. Pleas...
The Fortran program 'MAIN' below calls 3 subroutines. It opens a file if it is not present, (overwrites if it is already present). writes something on the file using the file identifier integer and closes the file. program MAIN 2001 FORMAT (A,I10) INTEGER FILEIDS(10) CHARACTER*64 fname FILEIDS(...
I'm currently developing a simple 2D game engine and I was just wondering, what are some things that I can do to improve my service locator class, at the moment it's very basic. For example, should I be checking for null objects, if so, what exceptions should I throw? Here's the code, thatnks in advance! using System; ...
I'm coding a turn-based RPG battle simulator (text based) in Java. I'm doing this as an exercise/project to learn OOP design. I've coded something similar in C, but just porting that code over to java would, of course, be rather silly. I'm going to be taking this extremely slow, focusing on getting each element right a...
I have around 300 log files in a directory and each log file contains around 3300000 lines. I need to read through each file line by line and count how many hostnames that appear on each line. I wrote basic code for that task, but it takes more than 1 hour to run and takes lots of memory as well. How can I improve this...
I have written this script in Python 2.7 and I was wondering where I could improve it or efficient. This is my first script so I don't now much. The script takes a text file from a folder removes blank spaces with list comprehension and then breaks it into smaller 20 elements and saves it each 20 elements as a definiti...
I created a BFS algorithm in order to solve an 8-puzzle, and while it works, it is awfully slow compared to my DFS implementation. My main point of concern is the puzzleExists() function, which determines whether the created puzzle already exists in the list and should therefore be dropped. Currently the algorithm slow...
This function formats the text in each cell of a CSV. The goal of the function is to make sure that the sequence of characters in text will never break the cell's partition. The correct output of this function looks like any of these: "foo" "123" "drop table 'chocolate'; -- this is fine, i don't care" "<script>alert("...
I was looking for a similar JavaScript method for http_build_query but did not find but create my own and here I am a bit confused to decide the right approach. Here is the problem. I have an object of params and need to create query string to append with URL with help of encodeURIComponent: const params = { "name"...
I'm trying to learn how to program with Java which is more or less my first programming language (had some basic Pascal and C,C++ in school and college) but still a Beginner, with a capital 'B'. Right now I'm working on a mini game, which is similar to the "breakout" game, but it's going to have my own implementation ...
I am using a toolbar button to present a modal view controller (in which I let the user export data as a PDF file). The main section of my app is a UITableViewController subclass embedded in a UINavigationController. Here is a schematic of my layout. The modal itself is embedded in a UINavigationController as I need i...
I had 15 minutes to code the following question: Given a file name return the char which appears maximal number of times. please do not take into account the unit test. Please look at the final foreach loop, I could have also used a for loop, I have doubts what is the best way to implement finding a max value and get t...
I was solving this problem for implementing LinkedList and ListNode classes, and Insert and Remove methods for LinkedList. I was wondering if I can get any code review and feedback. class ListNode: def __init__(self, value=None): self.value = value self.next = None self.prev = None def ...
I was asked to complete the task described below: Event Emitters are objects that serve as the core building block in event-driven architectures. They simplify the process of handling asynchronous events and enable clean and decoupled code. Create an Event Emitter module in JavaScript (as modern of a version as you ...
position: sticky; elements are sticky within the bounding box of their direct parent containers. I wanted to make a stickily-positioned button that sticks to the bottom of the viewport, not its parent. So here's what I did: #container { position: relative; top: -99999px; margin-bottom: -99999px; pointer-events:...
This is a follow-up to Searching online English dictionaries: import webbrowser import random available_dicts = [ ('Merriam-Webster Dictionary', 'https://www.merriam-webster.com/dictionary/', '%20'), ('Oxford Dictionary', 'https://en.oxforddictionaries.com/definition/', '_'), ('Camberidge Dictionary', 'htt...
Here is code I wrote to dynamically choose between three country options (United States, Canada, Other). After the user selects a country it will show the related select option or an empty input (when "Other" country is chosen). Then I pass the previous value into an input called spr(state/province/region). The end res...
I have a scenario where I do filters depending on checkboxes checked. Now I have only 2 checkbox and I need to cover all escenarios into if else conditionals like: if (!chkProjectTechs.Checked && !chkTeamLeader.Checked) { foreach (DataRowView list in lstTech.SelectedItems) ...
I've implemented a stored procedure for a search process SQL Server 2008. I'm not sure if everything I created is correct. Also I'm wondering if this code has any leaks or vulnerability on SQL Injection. Here is my stored procedure: USE [TestDB] GO /****** Object: StoredProcedure [dbo].[Search_Dictionary] Script Da...
This is probably the last time I will post this data structure that I have been working on. I have added in an iterator and const_iterator class (although I do not use them probably where I should be). I also did not follow another persons advice to add emplace, emplace_front, and emplace_back simply because I have no ...
I'm learning Java and I created a simple solution for the following problem: Given a file [filename].txt such that each line has the format string, double, find the minimum possible difference between any two values and identify if it is less than an arbitrary value mindDist package com.company; import java.io.*; im...
This is yet another take in Python for the infamous Sieve of Eratosthenes. I am a beginner in Python so any criticism is highly appreciated. # Find primes until this integer.. Modify to your taste.. upper_bound = 1000 # Pass a list of integers and a prime number, # will return you a list where numbers divisible by t...
I have code like below. By default the location is myloc. When user clicks btn-a it selects myloc and when btn-b is clicked it select myloc1. In my code I repeat the code L.circle three times, which is bad practice. So can anybody help me? How can I optimize this code, DRY it up and improve the quality as well? var myl...
The following function is designed to accept a string of characters and an integer. The function returns a string that's a reordered version of the original string. The reordering process is controlled by the second variable. If the function is called again with the same string and a different number, a different st...
I'm new to Java and am following a series of lectures on Stanford's YouTube. I know that the code works, but I'd like to know if it can be improved upon. /* * File: PythagoreanTheorem.java * Name: Will * Section Leader: N/A, I'm freeloading the class off Youtube. * ----------------------------- * This file is the ...
This is a rather minimal (though fully functional) implementation of a singly linked list. It supports \$\mathcal{O}(1)\$ front insertion and deletions, as well as \$\mathcal{O}(1)\$ random insertions and deletions via iterator. The goal was a clean and simple implementation that can be used effectively with standard a...
It is my first time trying to create smooth animations using rAF and I would like some insight from more experienced developers. Basically I have 16 elements with x,y coordinates and on mousemove over their parent container, all elements move a set amount in the opposite direction. When I do tests on lower-end machines...
I wrote a library implementing the RCON protocol to automate interaction with Minecraft servers. I know that there are already a couple of implementations out there, but neither I found was convincing me, so I re-invented the wheel. The library will also be featuring an implementation of the Query protocol, which is no...
I'm trying to find a simplest solution to append a newline character to a string. Although the following code works, I would like to know if it's possible to make the code simpler. (The argument should be const char* and not std::string) My Code : static void sysGui(const char *s) { char buf[1000]; std::strcpy(...
This is my first C program and I'm just looking for some constructive criticism before I start trying to do more with it. Am in quite unfamiliar territory here and am uncertain if I'm releasing all my resources, handling errors, and whatnot "properly". #include <errno.h> #include <share.h> #include <stdbool.h> #include...
I've written a very simple linked list based stack implementation and was wondering if this is the standard way to do it in C. typedef struct Node { int value; struct Node *prev; } Node; Node * push(Node *top, int value) { Node *node = (Node *) malloc(sizeof(Node)); node->value = value; node->prev...
I've been working on a solution to Pset3 of CS50 Harvard course for last couple of hours and managed to finish it. Although it works as intended I'm unhappy with how clean this code is, mostly because of use of multiple nested conditionals inside the main switch case. The function takes a string, for example "B#3", and...
Here is a static class with some helper methods for some common LINQ operations on enumerables, built against .NET Framework 2.0. This class is part of the xofz.Core98 library. Edit: a full review is not necessary. Any limitations or irritations discovered would be much appreciated. The code here is provided free fo...
I'm fairly new to python and pandas but trying to get better with it for parsing and processing large data files. I'm currently working on a project that requires me to parse a a few hundred CSV CAN files at the time. The files have 9 columns of interest (1 ID and 7 data fields), have about 1-2 million rows, and are en...
I've got the following code which is ran inside tampermonkey (It's a userscript), but there is a variable that is being declared, used, then overwritten by the next line. I'm looking for a way to shorten this code, or possibly remove the line if I can get the same results another way. $(function() { /***** RELA...
I'm a beginner to PHP and I've written a function that validates a U.K National Insurance Number. The function works by checking whether the given number against the format below; The National Insurance Number ($NINO) is made up of 3 components in the format AAnnnnnnA. The 3 components are the prefix, numeric body a...
I've wrote this code and it does what is expected. However, I'm thinking if there are better ways to write this, specially if is useful to wrap it in a class, or other ways to make it less loosen. I'll be glad and grateful for any others corrections or suggestions. interest_list = [0.5, 0.4, 0.3, 0.5, 0.7, 0.4, -0...
I've created a basic Python CLI script, which takes a Github username, and returns some basic information associated with said username. I use the requests for HTTP requests (I'm new to this area) and docopt for command-line handling. #!/usr/bin/env python3 """Github User Info Get basic information on a Github user ...
I have this code that hypothetically returns multiple rows from a database and encodes them in a JSON. I am wondering if this is the best and most presentable way to do it. Note: I am using msqli not PDO, and procedural php not OOP. <?php $query = $_REQUEST["query"]; require(connect.php); $response = array(); $respon...
I have been making an effort to add a fair amount of unit testing into my code. However, I find myself going against the DRY principle quite a bit. I am currently running tests on my API with my tests in the following folder structure: /user user.model.js user.test.js .... /blog blog.model.js blog.test.js ......
I just submitted a Python solution to the 'Two Sum' problem on LeetCode. The Problem Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example Given nu...
I have a function that generates HTML for hyperlinks. It's arguments may be string literals or variables read from the database. An example call to this function looks like: hLink('http://example.com', 'website', 'section', 'input=0', '_blank'); which returns: '<a HRef="http://example.com?input=0#section" target="_bla...
How can I remove the code duplication in this code? It is trying to cast the left and right numbers as integers or doubles and then using it. public Object example(Object left, Object right) { if(left instanceof Integer && right instanceof Integer) { switch (operator) { case ADD: ...
Over on SO I posted a question: Change transition duration during loop with requestAnimationFrame which hasn't got any responses just yet. I've since come up with this idea and wanted to know if there was any way to improve it. Essentially I would like to loop over an array of elements that have a smooth transition (a ...
This is my function: def two_powers(num): powers = [] i = 1 while i <= num: if i & num: powers.append(i) i <<= 1 return powers I have python 3.6(Windows 10 64-bit). I want the result in the form of a list. My problem statement is to express a integer(num) in the form of sum ...
So I've been trying to check through a string, looping for, [ (start) and ] (end). In this, I also have to check for nested brackets. My expected output, given input [depth1[depth2]] is as follows: depth2 depth1[depth2] To achieve this, I wrote this little snippet of code, which uses a Dictionary<int, int> to store t...
I have 4 functions that process texts or tweepy.models.Status object (this object stores text information, author information, retweets & likes information of a specific tweet). The first function is filter_unique, which is used to exclude duplicate tweets from a list of tweets. The result is a generator. The function ...
Is there the possibility to improve the code below? I am sure the result I got can be achieved with shorter code. Code awk -F, '{a[$2$7]+=$4}{b[$2$7]+=$5}{c[$2$7]+=$6}END{for(i in a)print i,a[i],b[i],c[i]}' tmp3 | sort -t, -k1n | awk 'BEGIN{ print ("\tCODE-1T COD-Area CODE-1 CODE-S CODE-T") printf ("\t...
I have been trying to solve this question. Given an unordered array consisting of consecutive integers [1, 2, 3, …, n], find the minimum number of two-element swaps to sort the array. I was able to solve it but my solution's complexity is not good enough that it terminated due to a timeout when it runs with bigger ...
Anyone remember "War games?" I have a very long way to go, but I thought it would be interesting to make a version of Tic Tac Toe which plays itself. At present the AI is "choose a random available space" (i.e nonexistent). I will build on that later, but for now I would value some feedback on my basic approach. I've u...
I'm very new to python (been coding for about two days) and have created a programme that simulates blackjack games so that I can work out optimal strategy over many iterations. The problem is that when I run it, my CPU goes to about 99.8% and it freezes (I run in terminal) - Does anybody have any suggestions on how I ...
You will be given an integer k and a list of integers. Count the number of distinct valid pair of integers (a,b) in the list for which a+k=b. For example, the array [1,1,1,2] has two different valid pairs:(1,1) and (1,2). Note that the three possible instances od pair (1,1) count as a single valid pair, as do the th...
I'm developing an audio recorder app for android using AudioRecord class to have a low level access to audio samples. mRecordingThread = new Thread(new Runnable() { @Override public void run() { android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_AUDIO); try { Fil...
I was trying to solve this problem from Leetcode: Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which the length is 3. Given "bbbbb", the answer is "b", with the length of 1. Given "pwwkew", the answer is "wke", with the length...
Since I am self taught, I would greatly appreciate some input on my code for this JS calculator: What redundancies i'm failing to see and remove? How is my naming for var's and functions? Is it clear or vague? How is my overall readability? Is what i'm writing even clear, or is it hard to decipher? Are my comments he...
I implemented an iterator pattern for C# using IEnumerator and IEnumerable. The goal of the implementation is to traverse a binary tree. using System.Collections; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DesignPatternsQuestions { [TestClass] public class T...
I wrote this program in Python 3.I would like to know if there is some more functionality that could be added/removed/is missing.Any comments would be helpful! #Steps from user : """ Enter Input P1 and P2 Each time for input will be preceded by a printed board. The game will continue until an input matches a win combin...
My project has many different objects from different classes, and I want each object to have a unique ID. IDs should be unique within each class type, but can be the same among different classes. For example Foo object1 and Foo object2 must have different unique IDs, but Foo object1 can have the same ID number as Bar o...
I have made a replica of the game 2048. It works exactly how the game should work. However I was just looking to know where I could've possibly cleaned up my code or make it more efficient. import random board =([0,0,0,0], [0,0,0,0], [0,0,0,0], [0,0,0,0]) def pieces_test(board): places =...
I was asked about this question by my friend, so I decided to implement it recursively. I would like to get some code review. # Create a BinarySearchTree class # # The BinarySearchTree class should contain the following # properties: # # root: {Node} (initially root ...
I have the following function which takes in an input and validates if that input is an Armstrong number or not: An Armstrong Number is a number such that the sum of the cubes of its digits is equal to the number itself. For example, 371 is an Armstrong number since 3 ** 3 + 7 ** 3 + 1 ** 3 = 371. Here's a link to th...
I have written a small library for C that implements the Huffman coding algorithm as outlined in David Huffman's paper on Minimum-Redundancy Codes, and a small test program to implement it. The library consists of two primary functions, huffman_encode() and huffman_decode(), and a series of helper functions. The progra...
I'm writing a basic program that calculates the total base resources needed to craft items in Minecraft. It's intended to be modular for support for modded versions of Minecraft (new items or different recipe's). To start, I created an Item class that will function as a base resource. A base resource is something I hav...
I've written a Powershell script that uses Robocopy to get the full path of all files on a drive and then run it through a foreach loop to get the owner for each file and generate it in a CSV. The code works, but is very slow when I run it against so many items. Can someone help me make it as efficient as possible? ...
This is a non-deterministic finite state automata (NFA) meant to be used with a Regex engine. To show some example usage, suppose you wanted to construct an NFA for the regex (ad|[0-9])*. It might look something like this: ad_literal = NFA.from_string('ad') number_set = NFA.from_set({str(x) for x in range(10)}) union =...
This is a recursive approach using DFS to counting the number of islands. However, I would like to improve performance, while keeping the code clean concise and readable. Better yet can this be solved using bitwise operations? var numIslands = function(grid) { const search = (row, col, grid) => { if (row < 0 |...
#include <iterator> #include <memory> #include <algorithm> template<typename RandomIt> void sub_merge(RandomIt begin, RandomIt mid, RandomIt end) { // create copy of input array; const auto left_size = std::distance(begin, mid); const auto right_size = std::distance(mid, end); auto left = std::make_unique<typ...
Here's my attempt at a C++2a Standard Library–friendly "topological sort" algorithm. There are several areas of interest here: The algorithm is comparison-based and in-place, just like std::sort. This makes it something like \$\mathcal{O}(n^3)\$, which is certainly worse than it ought to be. Can we speed it up somehow...
A good friend of mine had the challenge of trying to build a schedule using all available times and classes through a spreadsheet... by hand. He asked me if I could build a program to generate valid schedules, and with search algorithms being one of my favorite things to do, I accepted the task. At first glance through...
I am trying to continuously get the position of a div on screen and update the new position each time a "click" event listener is clicked. At the moment my code works but feels redundant and could be simplified into a single function to move the div around the screen. Any suggestions on how to approach this issue? /...
I want to implement a cumulative all through R's C interface. I was able to hack something together that produces the correct results, but I have little idea what idiomatic C should look like. The code should be easy to understand, even if you don't know about R. Description The cumulative all takes a LGLSXP (logical S...
For answering this question of stackoverflow I have written the code https://stackoverflow.com/questions/12033188/how-would-you-implement-your-own-reader-writer-lock-in-c11 Can someone review it - so that I can understand the possible problems in the code. #include <condition_variable> #include <iostream> #include <sh...
I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by adding numbers from a certain set, where any number in the set can be used N times. It is like if I have the number 10 and I want to find out how many ways 10 can be generat...
following the answer I got from t3chb0t last time News-reading application using the Observer pattern and also following the example here https://msdn.microsoft.com/en-us/library/dd990377(v=vs.110).aspx I implemented a the answer to the following question Design a kind of kindle fire application where we can subscri...
I have a number of these components, but will show just two as an example. They're very similar, but the differences are enough to where splitting them out felt needed. What I really need is some help. Is this the right approach, or would I be better served somehow combining them to reduce duplicate code? I have simila...
I am currently writing a C# console application. Part of it is, that the user needs to enter a fairly complex system name. To make it easier I wrote a function that uses a string[] keywords and auto completes the string the user is typing in - on the run (which makes it different to this post in my opinion) The code is...