instruction
stringlengths
71
95.1k
I am doing some simple projects in an attempt to get good at programming, this is my first GUI would love some feedback, and some guidelines. from tkinter import * import random root = Tk() root.resizable(False, False) root.title('Coinflipper') topframe = Frame(root) topframe.pack() botframe = Frame(root) botframe.p...
When I was studying Monad Transformer, I decided to create StateT s m a from scratch with instances for Functor, Applicative and Monad. This is what I have: newtype StateT s m a = StateT { runStateT :: (s -> m (a, s)) } instance Functor m => Functor (StateT s m) where -- fmap :: (a -> b) -> StateT s m a -> StateT...
I've been working on some code to pull questions from the realtime feed on stackexchange.com and query more information about them from the API. It works, but I'd love some feedback on how I could make better use of some of the monads and how I could make better use of Aeson. I'd also love general refactoring/code orga...
Ants Requirement Given a natural number \$n\$, representing the number of days the study is made, and then a number \$x\$ of \$n\$ natural numbers, representing the number of working ant flies after food, where the \$x_i\$ number of working ants is the day \$i\$. It is required to determine the number of maximum seque...
I am trying to manage an "app list" in my app (I currently have "MS Office" app list, "Games" app list and "other" app list). lists table: list_id | list_name ---------------------------- 1 | MS Office 2 | Games 3 | Other app to list table: app_id | list_...
I have a script that changes the display brightness using xrandr. It is my first bash script. I mainly had a lot of trouble with dealing with the floating point values. I think that is one of the main reasons the performance is bad. 1 #!/bin/bash ...
I made using SFML my first game project. It's a snake game, and I used 2 custom classes: snake fruit (snake grow by 1 when eat it) Here's main.cpp code: #include <SFML/Graphics.hpp> #include "snake.h" #include "fruit.h" int main() { sf::RenderWindow app(sf::VideoMode(800, 600), "SFML window"); snake snake; ...
I am a newbie in a programming, and I just randomly chose a task for training from some group on Facebook. The task is to calculate the cost of cement for a construction project. The input is the number of pounds of cement required (guaranteed not to be a multiple of 120). The store sells cement in 120-pound bags, each...
Have a look at this dataset. The"a" and "b" are used to make possible differentiate when the same variable was measured. In this case X1a and X1b access the same variable, but "a" was (suppose..) in the last year and "b" was this year. I just want to correlate "a" and "b" and plot it. Simple like that and I really im...
I've been wanting to experiment with a bit of error handling and robustness to make my code more user friendly. I was inspired by this answer on UX to try and add a progress bar to a button - but was unable to find any simple text based progress bars out there, so I decided to write my own in that style. It boils down ...
In this question I present a method to solve the Traveling Salesman Problem and/or the Single Route Optimization problem. I am extracting 100 lat/long points from Google Maps and placing these into a text file. The program should be able to read in the text file, calculate the haversine distance between each point, and...
This is similar to the game War, but with notable differences. For this program, it is the player versus the computer (so each with half of the deck). They draw the top card of their deck and compare. Whoever has the higher value card wins both cards and put both cards into the bottom of their decks (first the card th...
This is an implementation of mine to an exercise found in the book Core Java SE 9 for the Impatient. Goal is basically to print a monthly calendar by accepting month and year information from the user. Here is a sample run in my local: java App 1984 4 1 2 3 4 5 6 7 8 9 10 1...
My goal is to design an Auction that will take in data like this: Bidder A - ( StartingBid , AutoIncrement , MaxBid) Bidder B - ( StartingBid , AutoIncrement , MaxBid) This Auction will generate a winner based on the bidders entered. The Auction algorithm will automatically increment a bidder's starting bid given h...
I'm using bootstrap buttons, and in this case I have 5 different buttons with 5 different classes. When one of the buttons is clicked on, I want it to be the only one filled in, and the others to only be the outline. Here is how I currently do it: $(".canvas_btn").on("click",function(){ for(var i = 0; i < $(".canva...
As part of my journey in learning the Rust programming language, I decided to make a miniature cat clone (catty) in it. The following is my code, which depends on clap for argument parsing (see below). It currently only supports concatenating 1 file with possibly numbered lines (-n/--number). I tried to be as close as ...
Beginner programmer here. What can I improve in my code? Are there things I'm doing wrong or are there easier ways of doing what I did? def reduce(n): n = abs(n) ctr = 0 factors_list = [] for i in range(2,n+1): if ctr >= 1: break if n % i == 0: factors_list.append...
I have been working on this hackerrank problem: Louise and Richard have developed a numbers game. They pick a number (1 ≤ n < 264) and check to see if it is a power of 2. If it is, they divide it by 2. If not, they reduce it by the next lower number which is a power of 2. Whoever reduces the number to 1 wins the...
This is my attempt at the 4th problem on Project Euler: #include "stdafx.h" #include <string> #include <vector> #include <iostream> using namespace std; int palindromeCheck(int pp) { int temp = pp; string palindrome = std::to_string(pp); auto it1 = palindrome.begin(); auto it2 = palindrome.end() - 1;...
I've just written my first C# class, so I'm looking for some feedback before I go and write more code. The goal of the code is to provide a Singleton-like class to deal with common operations on the set of prime numbers that I will need to complete projecteuler.net problems. I'm interested in feedback for all aspects ...
I am currently attempting to implement Matrix Math for another project I am working on. However, I am not sure whether this implementation will work. Can someone please tell me if there are any errors with my implementation? #include <iostream> #include <vector> #include <cassert> using namespace std; typedef vector<...
This is a link to my application that actually runs on the design specified in the image. The idea behind the image is that the SubjectInfoViewer behaves as the context in the strategy pattern, and the ViewingQueryComponent behaves as the strategy interface, as well as the component class in the decorator pattern, an...
We are using spring-batch to extract data from a SAP system, during processing we pass the extracted full texts to a tagging service, in the end the enriched documents are stored in Solr to be served to the user. The problem during this ETL chain is that the tagging service is slow. Unfortunately we cannot improve its ...
I'd like to find the best way to format date to YYYY, YYYYMM or YYYYMMDD. Here is what I've got so far: # gets the position of a character in the format def get_pos(format, letter, number): it_number = 0 it_pos = 0 for char in format: if char == letter: it_number += 1 if it_n...
I am no newcomer to Java. One thing that confounds me is why it is so messy to load values from .properties files. I have an application where, if the .properties file is found, then the value if found, should be used. And in any other circumstance, to use the default. (In the correct deployment, the server is run with...
I've been using Monogame for hobby game development for the last year now. My game assets aren't large so I usually load them all on startup. I would have a static AssetManager class with a public static Load(ContentManager content); method. Assets would be loaded and stored in multiple Dictionaries like so: private st...
This is the beginning of my program that calculates simple interest. Interest rate will have the following format : 0.97 , 0.67 , 0.17 etc. They won't be bigger than 1. So if the user enter 9 for the interest, program will convert it to 0.09 (by dividing it by 100) . Also user can enter input using '/'. So program will...
I'm making a CLI app for myself for tracking my budget. How can I improve this code? #!/usr/bin/python3 def t_lines(): import os terminal_size = os.get_terminal_size() print("-" * terminal_size.columns) def main(): import sqlite3 as sql conn = sql.connect("expenses.db") cur = conn.cursor() ...
Sometimes I need to call async code from a synchronous method. This leads to repetition in code to wait for the task to complete, then ensure that the expected exception is thrown instead of an aggregate exception (assuming there's only 1 exception returned, as is the case unless we're iterating through a list / somet...
I made a B+Tree example for C++. I tested it a lot. I didn't get any errors or mistakes but i can't be sure it is really works (without any bug) or I don't know it is suitable for use (Memory problems, optimization etc.). I want your comments, test results and suggestions. /* * C++ Program to Implement B+ Tree */...
My main computer is a laptop which I run i3wm atop Arch Linux. As such, my monitor situation sometimes changes, so I wanted to code a script to configure my monitors based on which ones are connected to the system. The script runs on startup of i3wm. As for the monitors, sometimes I may not have an external display con...
I'm doing a Daily Challenges to get better with Python. I completed the first challenges with a working code but I want to make sure if there's anyway to improve or optimize it. I have a function that adds 2 items from a list in search of those that will match the already defined result. def main(): listA = [10,11,...
I have a map that I want to print out sorted by value, I convert it to vector and sort the vector. Is this code correct? #include <map> #include <iostream> #include <vector> #include <algorithm> #include <utility> int main() { std::map<char, int> freq; std::string text; std::getline(std::cin, text); std...
I've created my own take on a navigation bar using FlexBox (currently not refined for smaller screen media queries). I would just like someone to go through my code notes and see if I am going about it correctly. It seems to work but am I doing this inefficiently? Should i be using other methods? Have I aligned using t...
I have a simple web application where a user uploads a CSV of some dataset and some summary statistics and box plots are displayed. I heard that it is better to have so called skinny views and fat models, though I'm unsure how is best to divide the work. How could I improve my database schema and division of labour? vi...
I am coding in java since some time but I was not always really organized about methods and commentaries, here is a quick code to use the Cesar code : package cesar_code; import java.text.Normalizer; import java.util.Scanner; public class CesarCode { private static Scanner sc = new Scanner(System.in); priva...
I've stumbled upon this pretty old article about a hashing interview question, and here it is converted to Swift in a more generic way: struct CustomHasher { /// An enum of the errors that may be thrown enum HashingError: Error { /// Thrown by the initializer /// when the alphabet contains rep...
Introduction I decided to get my feet wet in Rust by going ahead an implementing a full crate with the tests, documentation, and all other accompanying stuff. This is a toy implementation of a library containing a function that checks whether a given u64 is prime or not. What I've also done is implement a main.rs in a...
In a practice academic interview of mine, we discussed question six, round one, of the United Kingdom Mathematics Trust's 2015 British Mathematical Olympiad. Which states: A positive integer is called charming if it is equal to 2 or is of the form 3i5j where i and j are non-negative integers. Prove that every positi...
For plotting I often use a dictionary that contains my data of interest, regarding my numerical simulations. For example I have a numpy array let's call it U the contains a discretization of a equation in every simulation timestep. Simply put, my U is a 2D np.array where each row is a given timestep (first row first ti...
I've written a script in Python using multiprocessing to handle multiple process at the same time and make the scraping process faster. I've used locking within it to prevent two processes from changing its internal state. As I'm very new to implement locking within multiprocessing, I suppose there is room for improvem...
The function receives a string containing a sentence. Its goal is to shorten every word in it to a length of 4 characters until the string is shorter than 38 characters and return. The 38 characters max length is mandatory and must be reached with the least amount of deletion possible. Here is what I've done: # reduc...
I created a where I select a video using QOpenFileDialog and play the video on QGraphicsView. After that I select an area on video using mouse and QRubberBand class and want to draw a rectangle on selected area when I release left mouse click. Since I'm newbie can you tell me which parts of my code is bad practice, uno...
I wrote this program just to remove duplicates from wordlist used for brute-force, but it can be used for every txt file i guess. It is a pretty long program for what it does, and I'm sure there is a way I can make it easier and better for everyone to look at. I'm still a beginner in python. def wordcount_initial(): #...
I'm writing a application that reads from a queue of messages from a legacy mainframe system. Some characteristics of message in the queue: Message from the Q is always fixed length plain text : 64 char length Each index or group of index indicates some meaning full data The first 20 chars represent first name, next 2...
In this code, I generate the coordinates of a tube made of multiple rings. Finally, I write those x,y,z coordinates in a .csv file. I want to simplify this code (maybe using a for loop?). import numpy as np import matplotlib.pyplot as plt bLength=1.6 numPoints=10 radius = bLength*numPoints / (2 * np.pi) theta = np.lin...
I have read so many times that one should not subclass standard containers. Is there cases that one can subclass them ? for example, I have the following case: struct Materials { std::map<std::string, std::unique_ptr<Material>> materials; void setFrom(const Database& db); void echo(std::ostream&) const; }; I...
I have a question: Write a class that represents a sorted list of filenames. The filenames are sorted by most recently added first. Duplicates are not allowed. And I wrote this solution: public class RecentlyUsedList { private readonly List<string> items; public RecentlyUsedList() { items = n...
I am trying to fill missing values with linearly interpolated values in an Rcpp::NumericVector -- leaving in place leading and trailing NA-values. The desired output is below: R> x <- c(NA, NA, NA, 1:4, NA, 6:8, NA, 10, NA, NA, NA) R> naLinInt(x) R> [1] NA NA NA 1 2 3 4 5 6 7 8 9 10 NA NA NA I've implemente...
If you split a string like foobar with something like [::3], [1::3], [2::3] it will give you ['fb','oa','or']. I needed to then be able to rejoin that into foobar and I got given a challenge to make it in one line. This is my solution: split_join = lambda t:''.join(''.join([s.ljust(len(max(t,key=len))) for s in t])[i::...
Is there a shorter way to write this? discounted_price = original_ticket_price - discount_value if discounted_price < 0: discounted_price = 0
I recently learned quick sort through https://www.geeksforgeeks.org/quick-sort/ but found it hard to follow. So, from what I understand wrote the following program. #include <stdio.h> void quick_sort(int[],int,int); int main(){ int arr[100]; int n; printf("Enter the elements :"); scanf("%d",&n); fo...
Edit Found the original contract name resolution by .NET MEF, the code below is not useful anymore. See response! My issue was to use existing code, to make a MEF ExportFactory, imported via [Import] attribute to a property, return instances of Moq mocks (for unit testing). Problem was, that the original code always us...
Requirement: Based on mainArray which contains the master list of items, and compArray which has items of interest; construct a 2 dimensional third array that contains the array of contiguous elements. The purpose of this requirement is for plotting poly-line on map wherever an incident occurred in contiguous manner, p...
I wrote a matrix class for use in a ray tracer. I already have a 'scalar' version up and running, but now I'm trying to rewrite it to use Intel SIMD Instrinsics. I realize my compiler (clang-7.0.0) will probably generate code that is at least as fast as mine (chances are, it's going to be faster), but I'm doing this be...
I did the following Excercise from Automate the boring stuff with Python Chapter 7: Write a function that uses regular exppressions to make sure the password string it is passed is strong. A strong password is defined as one that is at least eight characters long, contains both uppercase and lowercase characters...
I built a small WinForm application that has checkboxes to filters users with different properties. Each user has a name, color and number. With the program you can filter by color or name the users that you will see: Inside the application there is a static list of users: // SomeUser(<name>, <color>, <number>); Som...
For my first ML project I have modeled a dice game called Ten Thousand, or Farkle, depending on who you ask, as a vastly over-engineered solution to a computer player. You can find the complete game, with perfectly good computer player composed of about 15 lines of logic, here. In way of brief explanation of the game, ...
I'm currently trying to make a screen recorder in C#, and so far it works but the problem is that something as simple as a 20second video will take about 1GB of space. I have it setup so a timer continuously takes screenshots with this method: void takeScreenshot() { Rectangle bounds = Screen.FromControl(this).Boun...
I'm working on a program that aim to take sentences (currently in french) and compact them to a length of 38 characters while retaining as much information as possible. You can find another part of this project here replacing words with their abbreviations I've made a function that removes determiners from a string usi...
The exercise is from Alex Allain's book "Jumping into C++". From Chapter 10 Practical Problem 4: Write a small tic-tac-toe program that allows two players to play tic-tac-toe competitively. Your program should check to see if either player has won, or if the board is filled completely (with the game ending in a...
This is my code to generate and store password localy hashed in txt file. I would like to kindly ask you whether you could review my code. Btw it is coded as console app. I am currently working on making GUI. Thanks in advance. import random import hashlib class randomPass(): action = '' def __init__(self): ...
I have made a General Knowledge quiz in python as a project from my school import time score=int() print("Welcome to the General knowledge Quesions Quiz") time.sleep(2) print("Question 1") time.sleep(2) Question1 = input ("A vehicle with the national registration code ‘PK’ would originate from which country? ") if Que...
I have two lists of Slots public class Slot { public DateTime Start { get; set; } public DateTime End { get; set; } public List<Service> Services { get; set; } } public class Service { public int Id { get; set; } public int Duration { get; set; } } public class MergingClass { public List<Sl...
I wondered how an expandable list could be implemented. My first thought: You could create a class that has an array and you can create a new array each time the user wants to append an element and than you can copy the old array plus the new element into the new array. But this seems very inefficient to me. Then I rea...
I am concerned about how certain processes of an exercise or CRUD example should be implemented in a PHP document, looking for the best practices in terms of security and development techniques of that script. Suddenly, my question may be considered as opinion based, so I will try to be as specific as possible: Approac...
Any tips or improvement to speed my code? I'm looping each file in the specify folder and subfolders. I will open each file and get the values I need and copy it to my activesheet. It is taking quit some time, any tips to help? FolderName = InputBox("Enter path", "Get File") Dim fso, oFolder, oSubfolder, oFile, queue ...
I develop this mini project as an exercise. It is a simplified employee salary calculator. Requirements: Employees are characterized by name, employment date, employee group and base salary. There are three groups of employees: Employee, Manager, Salesman. Each employee might have a supervisor. Each employee except "E...
I have currently two use-cases that require JSON transformations before it can be deserialized. The first use-case requires changing the custom short type property name from $t to $type and resolving full type names from their aliases. This is the same as in my previous question. The second use-case is about fixing pr...
The program interacts between cards and four players among whom cards are to be distributed. The Program do the following function Creates a deck of cards. Shuffle the deck. Shows the deck. Deal cards equally among four players. Show the cards of each Player. Please suggest some better ways of doing this program. A...
Problem Dupe detection for a vector of ints. I simply want a count of the unique input characters that occurred at least twice. The goal is to count a dupe only once and ignore that input character if another dupe of it is seen in the future. A test input could look something like this vector<int> test = { 4,5,9,6,9,9,...
I've been working on a note tool for my company to help streamline verifying and noting accounts. I've added in extra features that help with different aspects of the job as well. I'm wondering if there is anything I can do to streamline some of the functions I've created. Such as the "Prefill options". They take the ...
I tried writing my very first template engine today. I designed it to just replace variables in templates, and keep it basic for now. Can anyone give me some constructive criticism? I'm getting ready to write my own mini framework, and want to improve as much as I can. I just need to know if this is the default way (l...
Before I start writing my first MVC framework, I want to improve my code quality as much as I can, can anyone give me some constructive criticism on how I can improve this? It is a simple router, built for simple use. It should be pretty simple what's going on, and the usage should be easy to picture. It's nothing majo...
I've created a somewhat "Brute-force search engine" based on a document's filename, as well as an additional keyword that describes the said document. I had to make one as my company's resources are a mess and not fully structured, so it's tough to search for a document using just the regular Windows search tool. What ...
I am trying to solve a coding challenge: Given N integers A1, A2, …, AN, count the number of triplets (x, y, z) (with 1 ≤ x < y < z ≤ N) such that at least one of the following is true: Ax = Ay × Az, and/or Ay = Ax × Az, and/or Az = Ax × Ay Sample case 1 5 2 4 6 3 1 In Sample Case #1, the only triplet satisfying the c...
I'm struggling to make a React/JS map I have more efficient. Essentially, I have a list of cards, and then a map of markers. When I hover on one of the cards, it changes the styling of the marker. Here’s what it looks like: But the way I'm doing this...I'm pretty sure is really inefficient, so here's how I have it se...
For scanning my subnet using my IP address, I need to run the following command nmap -sn 192.168.100.* I want to extend this functionality such that I don't have to manually specify the first three parts of the IP range myself. I came up with this rough solution. ip=$( hostname -I | awk '{print $1}' | awk -F. '{print ...
I was faced with below interview question today and I came up with below solution but somehow interviewer was not happy. I am not sure why.. Given a binary search tree, find the kth smallest element in it. Is there any better or more efficient way to do this problem? /***********************************************...
I'm working on a program that aim to take sentences (currently in french) and compact them to a length of 38 characters while retaining as much information as possible. You can find another part of this project here Remove determiners in a string You can also find a follow up for this question here: Replacing words wit...
I have made a Rubiks Cube object which builds a Cube out of Cubelet objects and then allows you to move it. Things I still plan to do is add tower cubes and triangles and other shapes as well as a method to save and load files and a graphics program to use it however I decided it was probably done enough to see what pe...
I was asked to define a function that takes a list as an argument and returns the index of the smallest value. This is what I came up with: def index_finder(lst): """ parameters: lst of type list returns: index of the lst's smallest value """ for i in range(len(lst)): if lst[i]==index(lst): ...
I have written my own expendable list in Java. LinkedList in Java Now I tried to write that thing in Python. Did I have used the elements of the python language properly? class Node: def __init__(self): self.object = None self.nextNode = None def hasObject(self): return self.object != ...
I have made a C++ class to manipulate 3D vectors in Cartesian coordinates. However, the performance of my class is much slower (about 2.5x) than simply using something like double p [3] and then running for loops for additions, subtractions, etc. My specific concerns are: Is there something fundamentally wrong that I ...
I have the following input: case class Client(key: String, time: Option[Instant], bool: Boolean) val l = List ( Client("87658763", Some(Instant.EPOCH), false), Client("87658769", Some(Instant.EPOCH), false), Client("87658769", Some(Instant.EPOCH), true) ) For context, this data is the result of concatenated List...
In my application, the user may or may not want to ignore some directories. I can do that, but it seems like I am repeating myself. Does anyone have an idea to refactor that? from os import walk, path exclude = ['dir1/foo'] for root, dirs, files in walk('.', topdown=True): if exclude != None: dirs[:] = [d f...
My VBA macro displays an animation based on a row-by-row time step simulation in the worksheet. The user enters the desired inputs and the worksheet calculates the evolution of the simulation in a 1000 row table. The user then runs the macro to display the results in an animation. The macro loops through the rows in th...
I am an extreme novice in Java and thus trying to practise some online exercises. One of them involved creating a basic student record system. This is what I've come up with but I think a lot of things are quite redundant in my code so any reviews are greatly appreciated. Student.java class Student { int rollno; ...
I did the following Excercise from Automate the boring stuff with Python Chapter 8: Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the word ADJECTIVE, NOUN, ADVERB, or VERB appears in the text file. For example, a text file may look like this: The ADJECTIVE panda w...
I am trying to compare any performance gain(s) from moving a current offset-based pagination endpoint to a cursor based one. I have the following ruby code: @limit = 25 @max_pages = 200 def query @q ||= MyDataBaseClass.where(status: "open").order(:id) end def offset_paginatiion # count is currently an implementat...
Before I can perform a more or less complex mappings, treatments in business objects and saving results in databases, I often need to validate contents from flat text files or excel files All the validation libraries I know are designed to validate the content of strongly typed objects. The parsers or readers I tried ...
I am working on a component for a navigation bar. This navigation bar currently has two variations: a "back" version, and a "close" version. I have come up with three different implementations but I am uncertain of which one is the best. Currently, I am leaning towards this implementation as it reads the best in my opi...
I tried to write a function bin_add() in C to add two positive binary numbers represented as zero terminated strings: #include <errno.h> #include <stdbool.h> #include <stddef.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #define MAX(x, y) ((x) > (y) ? (x) : (y)) size_t gpp(char const *s) { char *n...
Here's some code I wrote to manage the different types of morphism and their compositions in C++17. Let me know if you had any suggestions for substantial simplifications or improvements, or if I missed something. There's an example at the end that composes a number of different morphisms together and then confirms tha...
I have written a simple script that searches twitter for keywords and saves them to a csv file if they contain those words. It can be found on my github here. How can I improve this code to generally be more efficient and be up to coding standards ? """ Script that goes through english tweets that are filtered by secur...
First time implementing a hash table. I resolve collisions using the separate chaining method (closed addressing), i.e with linked lists. The hash function used is: murmurhash3 (please tell me why this could be a bad choice or why it is a good choice (briefly)). If you want to investigate it more, or even test it, all...
I have a code where the goal is to give score to strings based on how much score certain substrings are worth (including repeating substrings). The way my code (which is based on the Aho-Corasick algorithm) works is: Creating a tree-like data structure where each node represents one prefix of a string (or the full str...
I'm recently working on a project that involves animation in the background. It works well on desktop but performance drops drastically on mobile. I'm using Paper.js to import a svg and animate it. This is the demo. paper.project.importSVG(svg, function(item) { var moveSpeed = 70; var movementRadius...
I wrote an iterator to access the pixel in an packed image. It works, but it is slow. 1.Are there any mistakes that can be avoided and might lead to better speed? 2.Are there any pitfalls that wait for me when using this code? 3.Is there a solution to the operator-> ? 4.Has any of the above an extra answer when usi...
I'm relatively new to Python from a strong Java background. I am trying to create a base class to do Hoare Logic. Function decorators seem to be the way to go with this. I've produced the following code, can you comment on this, and suggest an easier way to do this? It seems awfully over complicated to how easy thi...