instruction
stringlengths
71
95.1k
I'm putting together an example for students where I would like to show how we can optimize even such basic algorithm like a binary search with respect to hardware. I do not consider threads. I wrote it in C++ and the whole example can be found here. I'm trying to show some examples of the prefetching. Test data If we...
Given a DbSet<Client> from an Entity Framework 6 DbContext, I need to count the number of related Tickets of each type: Open, Responded, and Resolved. The below code works, and results in only one query (according to DbContext.Database.Log), as desired. However, the fact that the call to GroupBy results in an IGroupi...
I am writing a bash script to mount openshift service accounts into kubernetes objects. The right secret to use is highlighted in this text: $ oc describe sa sa-build-webhook-realworld Name: sa-build-webhook-realworld Namespace: your-eng2 Labels: app=sa-build-webhook-realworld An...
My brain is fried from looking from looking at this for so long. Is there a more efficient way to do this code block. We have the ability to use es6 code too if that helps. First it tries to set quantity to itemTemplateIDQty.value if itemTemplateQty is not valid and itemTemplateIDQty is valid. Then it basically ch...
Probably many people had to work with multithreaded applications with C++ and can understand how messy can be fine-grained locking of objects. So once in a while I came to idea of implementing some proxy objects using a so-called "drill down" property of operator-> and RAII in mind. Yes. There is some implementations t...
I'm prepping for a tech interview coming up and trying to have a better understanding of what I should look out for in writing code. Also, feel free to correct the terminology that I use as I want to be able to talk about my code clearly and succinctly. One of the specifications for the tech interview process is that I...
I'm trying to solve problem 86 in Project Euler. After some tinkering, I managed to unroll the DP solution into a loop. But still the solution takes >150s to complete. What can I do to improve the performance of this algorithm? (defn- square [n] (* n n)) (defn- is-perfect-square? [n] (let [sq (int (Math/sqrt n))] ...
Introduction If you know what FDF files are, you can skip this section. PDF files sometimes includes form fields. These fields can be represented as FDF in plain text form, extracted using certain utilities. Important things to note about this file are: A field is represented by /V () /T (Field) where "Field" is the f...
This is a helper class that helps fill models with data obtained from the database. public class Util { public static <M> ArrayList<M> createModel(M model, Cursor cursor) throws IOException { try { final Class<?> cls = model.getClass(); final ArrayList<M> result = new ArrayList<>(...
I have a thread which periodically executes a task. Something like the following: std::thread thr; std::atomic<bool> keepWorking; void stopThread() { keepWorking = false; thr.join(); } void threadLoop() { while(keepWorking) { std::this_thread::sleep_for(std::chrono::seconds(15)); // Do Work. } } The ...
Intro We have some old(in my eyes) software at the place I work at the moment, Some stuff needs to be done manually, for instance we need to insert a XML file into a Oracle table, which will trigger... stuff I got annoyed by having to do this manually all the time, So I decided to automate the process a bit with powers...
I made an authentication system for my software (no browser is used) that works like this: User receives a Key on it's mail after buying the software User registers account using that key and inputs username, mail, password. registration.php checks if the format is correct then sends an email with a confirmation code ...
I have attempted to implement the advice from the original post and debugged the original concept. Certain changes in the logic have necessitated other changes, including breaking into the library class and the test console app. Test console: using System; namespace LongCacheTest { public class Program { ...
I'm new to web programming, and writing some web apis to enable users to sync their data between devices. Is it okay to use singleton pattern to prevent reconnecting the MySQL database on every api call? <?php final class MySQLiConnection { private static $connection = null; private function __construct() {} ...
Some of you might remember my previous implementations of this idea in C++. The threads can be found here and here. I tried to implemented the same idea, but this time in python. A summary of the concept again: The idea is to organize data nicely in a table structure that is fully console-based but still highly custo...
I would like constructive criticism of a networking plugin I've written for Unity 3D. The use-case of the code is for people in "creative coding," where simple TCP and UDP messages are used for communication with lighting controllers, micro-controllers, and other devices, in addition to other computers. The requirement...
My code tries to solve the wooden snake chain puzzle: I do so by generating all possible link configurations which are then tested. I was hoping that laziness would take care of the very many configurations. But it seems that I was wrong. While the program runs for smaller chains (cf. lengths' which gives the lengths ...
Here is an initial attempt at unit test of user input in C. The thing that feels unusual is the use of freopen to send the test data to stdin. Are there better ways to implement this kind of test? #include <stdio.h> #include <stdlib.h> #include <assert.h> static size_t get_num(size_t tmpnum) { if (scanf("%zu", ...
Any problems with this D wrapper around libcomcom_run_command() C function from C library libcomcom? Does it work as expected? Is it idiomatic? Is it the right way to do this? module libcomcom_wrapper; import std.string; import std.algorithm.iteration : map; import std.array : array; import std.exception : ErrnoExcept...
I want to find the fastest method of getting the range object which contains all values in a worksheet, while only containing 1 area. Traditionally one might think this is what UsedRange does, however UsedRange often selects cells outside of the value range. I believe there is no existing VBA range which will suffice ...
This is considered as my second python project, I made the password generator where user has to input length of password minimum 5. I made the code that it will guarantee at least one lowers case, one upper case and one special character is included in the password. please review and comment. import random def letter...
I'm (very) new to writing unit tests and I'm wondering how I should approach testing a static method that constructs our API endpoints based on what the properties are set to in our environment.ts file. The environment.ts file changes with the environment, so I'm curious how I would accommodate for that in my test. Doe...
When you only want a couple styles from a workbook but not all of them it's easier to merge styles then remove those you don't want. How can I improve the form or the backing code? Userform with styles listed. 'CustomStyleRemoverForm Private Sub UserForm_Initialize() ListStyles End Sub Private Sub ListStyles() ...
I'm new learning python and image processing with python. For this reason, I took a project called "Classification of breast cancer images with deep learning". I applied the following techniques: 1)Threshold, 2)K-Means import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread('n001.tif', 0) _, bla...
I am writing this class to eventually create a playing card game (Spades) and also to utilize the object oriented paradigm. This was my attempt to model a card as an object. Each card has a suit and a rank that have each been given a specific weight that can be modified to fit the needs of the game. I have had several ...
So my code works as intended, but suffers major performance issues every time I add a new object to the screen. The speed of my objects basically gets cut in half. All you have to do to observe this is run the code and hit spacebar to create a new object. it is suppose to represent a production line. the product is ...
Today I started learning C++ and at the end of the day have made a simple generic matrix class. I'm looking for feedback on techniques and features. It's still not complete, though. But everything works! I put some functions outside the class and inside a namespace because I was trouble defining template member functio...
I have created a basic web page that contains a panel which displays some details about an object, and a panel which contains some tiles that are used to choose which object to view. The idea is straight-forward, and with plenty of C# experience, the learning curve was small. However, since I am relatively new to JavaS...
I have an exercise that ask to plot the prior and posterior distribution in the Poisson-Gamma model. I did it (I think it's correct) inspired in the answer of this question https://stats.stackexchange.com/questions/70661/how-does-the-beta-prior-affect-the-posterior-under-a-binomial-likelihood Is there anything that can...
I am using a panda's dataframe and I am doing filtering and some calculations per column and per row. The dataframe looks this: 100 200 300 400 0 1 1 0 1 1 1 1 1 0 Each header of the dataframe represents a company ID (x) and the rows represent specific users (y). If the user has accessed...
I have several (12) WCF services which are structured like this: I have inherited a very large 10-year-old project, I've introduced some inheritance so that I can have 1 echo method where I can control the timeout and not have duplicate code everywhere. The PostalAddressFinderServiceService (Shittly named I appreciate)...
I have an alternative solution for family tree that have been posted some time ago and please forgive the similarity of the task but when i tried to post alternative solution in someone else's post and asked for review I got deleted. Model the family tree such that: Input: Person=Alex Relation=Brothers Expected Out...
I have two processes. First (main) one is "dealing" with user stuff. Second one is doing some internal stuff and should update its internal state according to user actions. So I've created two pipes. By one I send actions to subprocess, from another I get messages that emits this subprocess. I wonder about two things: ...
I have a function which does the following: When new Post Entity is added some fields in Category table are updated. When new Thread Entity is added the same fields in Category table are updated. Because of this, some lines are completely the same. public function postPersist(LifecycleEventArgs $args) { $entity =...
I'm creating some web apis to sync some data between desktop/mobile apps. Working on it, I wrote a simple wrapper for mysqli connection to simplify querying like: // examples $connection = new MySQLiConnection(); $connection->execute("INSERT INTO songs VALUES ('God\'s Plan', 'Drake')"); $connection->execute('INSERT IN...
I have a spreadsheet with five sheets all of which run the same VBA code; everything was good when it was on just the one sheet, but now it's running on all five sheets Excel is extremely slow to load and the items take a while to update. I have a drop down menu in one column and if a user selects an item from this lis...
We use a third party dll which has an object called CServer and was provided by one of our software vendors to act as an API between our applications and their applications. CServer has the following method: bool SynchroniseData() which can be called if we want to fetch data from server which is very important for our...
I found a trick to significantly reduce the time needed to compute Huffman codes in my implementation of RFC1951. I was slightly surprised to find it slightly improves compression as well, something I had not anticipated. The trick is to encode the required information about a tree node in a ulong, arranged so that th...
Here's my solution for the LeetCode's Two Sum problem. 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 nums = [2, 7, 11, 15], tar...
I'm trying to determine if an instance of an object exists within a collection. I'm using array_walk_recursive to walk and check the leaves of an array. I've added a small short circuit, but still all leaves will be iterated over. I could alternatively use something like an exception which is thrown on the first find, ...
I know randomness in programming can be a deep topic, and searching the topic seems to result in Fisher-Yates being the best method, but I'm curious what people would say about this method. Basically, since I have the cards as objects, I just add a property of a random number then sort the entire array based on those r...
We have a little tournament in our company between coworkers and I decided to write an application for managing games, results and rankings of players and teams. The base logic for application is quite simple: We have players We have teams, which are formed from players We have game/s There are matches in a game, whi...
Task: convert this array of hashes: animals = [ {"cats" => 3}, {"dogs" => 5 } ] to this hash: { "cats" => 3, "dogs" => 5 } This is my solution, any feedback is appreciated :-) animals.reduce({}) {|m,e| e.each{|k,v| m[k] = v}; m }
I am trying to implement a minimal symbolic algebra library (AKA C.A.S.) in C++ that allows me to utilize delayed evaluation similar to this question from SO. My class hierarchy is getting a little complex, as it uses CRTP, abstract base classes, and smart pointers (which is where I'm running into issues). I'm not co...
I am working on saving the text messaging draft of a user. The flow currently works but I am looking to make this block of code easier to read and smaller. Could anyone help me achieve this? if (!hasDraft) { /** * This will get triggered when there is no draft * and you create one therefore we need a refr...
You were all so helpful with my Tc Tac Toe games in C. I was encouraged to put it up on GitHub and two very helpful users refactored it in ways that really taught me a thing or two. While I have switched focus to Python in anticipation of the upcoming 7DRL I was so happy about the way my C projects were reviewed that t...
I have a React component that generates a table based on an array of objects, which gets populated with data in an object. I'm trying to learn as much as I can about React.js / JavaScript. Could anyone with more experience in this area show me a way to simplify the code that I have here? Or if there are any other 'fanc...
I posted a question on Stack Overflow and got an answer that works but has a lot of duplicated code. In the future, the functionality may also require a third or more divs to be shown or hidden. The original script also came from a SO answer. Can this code be refactored or improved to accommodate more than 2 inputs and...
I've implemented Dijkstra's algorithm to find the minimum path between two nodes. class Node : CustomStringConvertible { // unique identifier required for each node var identifier : Int var distance : Int = Int.max var edges = [Edge]() var visited = false var description: String { retur...
I have a high performance, computation intensive application that runs on a Centos 7 machine with Python 2.7.5. I'll try to explain what the application does: The application runs an infinite loop, where it receives a message from an API call representing power levels of a device. The message is in Avro and encoded as...
This is just a basic accounting/banking system with the user being able to register an account, check their balance, make a withdrawal and deposit money etc. There is a few things a staff account can do also such as the removal of an account. AccountSystem.h #pragma once #include <iostream> #include <string> #include...
I have a simple piece of code which connects to an API, does a request and gets back the raw data. After getting this data I create several objects (models) and persist them into a MongoDB database. Example of a model: class Match: def __init__(self, data): self.data = data @property def match_id(...
As we all know, the syntax of allocating memory is a bit clunky in C. The recommended way is: int *p; int n=10; p = malloc(n*sizeof *p); You can use sizeof (int) instead of sizeof *p but it is bad practice. I made a solution to this with a macro: #define ALLOC(p,n) do{ *p=malloc(n*sizeof **p); } while(0) This get ...
I'm new to PHP OOP and I'm making some tests. I have 2 classes: database and posts and the two interact with each other. Class Database: class Database { // defining some variables private $host; private $user; private $pass; private $bd; protected $dbh; /* method construct This...
Is there a way to make this code run faster? I have over 6000 pictures in .jpg optimized to a maximum of 40 kB. It starts quickly but after like 2000 pictures it runs way slower. The final .xlsm file is about 380 MB. I'm using Excel 2016 with Windows 10 on a big server with 16 processors and 80 GiB RAM. Sub Button5_Cli...
My Python program parses songs from a website, corrects song titles and artists with the Last.fm API, searches for the spotify uri using the Spotify API, stores all the information in a SQLite database and then uploads it into a Spotify playlist with the Spotify API. I would like to make the program object oriented and...
The purpose of this was to practice web scraping, regex and GUI. I use a popular bitcoin website to scrape the names and prices of the top 16 cryptocurrencies. I then create a data frame and make a GUI to display the information based on the user's selection. I am looking for any and all input on how to improve this co...
I wrote classes to model a playing card, a deck, and a player to be used in multiple playing card games. I originally posted a Card class here, and now extended the project by adding a deck and player class and am really looking for some feedback. This is my first real object oriented design project and I feel unsure a...
This is my solution for the leetcode reverse int question: Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-...
For some background I'm pretty much a beginner and attempting to learn Python currently. So I decided after a few days of lessons I'd look for some beginner projects to test my knowledge. A website suggested I do a 'Guess the Number' game and basically suggested I follow this guideline. Random function Variables Integ...
Yes, It's called Snake++. I build it to learn C++. What features and techniques can be improved? I used SDL for some basic rendering, but my concern is more about the language use. Things I'm very concerned about: Generating a new food means trying random positions over and over again till one is free. This is going ...
I am using PHP to keep my webpage organized. The directory looks like this: root/folder/file1 root/folder/file2 root/folder/file3 root/index.php Each file is very simple html doc with content containing a title tag, which I use to create a nav bar. I want index.php to aggregate all the content from file1, file2 and fi...
I was bored so I crapped out a simple game that responds to commands and manipulates an inventory. I am interested in other possible ways to handle the inventory, and I think I went overboard with the linked lists #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <time.h> #include...
This is a shopping list program made in Python 3 and it will send the list by email. I am not very experienced but I consider this program as a starting point to what I will do next. import smtplib from email.message import EmailMessage from getpass import getpass name = str(input("Name: ")) email = str(input("Email...
Write the find_boundaries function, which will take a list of numbers. The function should return the tuple with the smallest and largest number in the set. If there is an item in the list that is not a number, it should be ignored. If an empty list is entered, the function should return None. My code: def find_bound...
As an exercise, I wrote a simple context free parser modeled from a pushdown automaton for chemical formulas such as NO2 or Fe(NO3)3. To explain a bit about the decisions made: The state functions (pstart, pchem and pnum) are lambdas because they carry around a lot of context. They could be methods of a class, it does...
I'm in the process of reading The Rust Programming Language, and decided to do the 3rd task at the end of the 8th chapter. The description is as follows: Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or ...
Problem is taken from leet code. Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur. Example 1: Inp...
A simple tip calculator that asks for the total bill amount, service quality (used to determine what percentage of the total cost will be tipped), and how many people are sharing the bill (used to split the tip so that everyone pays the same amount). I am primarily looking for possible improvements to performance or re...
Task: Create a service which will synchronize files on FTP server with files on local drive. FTP server allows up to 15 concurent connections Synchronize the files as fast as possible Files on FTP server are archived after 7 day, we should archive them too at our side Files once put on the FTP server do not change Fol...
Here's my solution for the Leet Code's Three Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting. This is Python 3. Problem: Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of ze...
I am about two months into programming with Python (no previous experience) and I tried to write a program which would generate a key and assign it to a student. import random import string code_list = [] students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana", "Gal", "Danijela", "Alma", "Ne...
This is my first programming assignment. This is a second file that is intended to test the setters and getters (both constructors and no-argument constructors). How can I clean this up (curly brackets or combining similar methods/lines) to make it look more legible and understandable? I'll be adding comments later. /*...
I am using Java 8. I want to build a final list using following data. All objects in basicData list must be added to final list. But if there is a matching object based on matching key from modData map with the basicData's id & isMod set to true, I want to add that object to the final list instead of basic. For exam...
using Microsoft.AspNetCore.WebUtilities; using System.Security.Cryptography; namespace UserManager.Cryptography { public class UrlToken { private const int BYTE_LENGTH = 32; /// <summary> /// Generate a fixed length token that can be used in url without endcoding it /// </summ...
I had an intuition that the maximal trajectory lengths for collatz conjecture numbers would be produced by numbers of the form (2**n)-1 so I wrote a program to test it (I was wrong). I thought I would put it up for review to catch any coding sins I committed, and see how others would improve my code. Orginal Code ''' *...
I passed a technical test the other day, one part included a cheap string validation and I am wondering this can be further improved to be more versatile to requirement changes. The requirements were something like that Create a Validate method, which accepts a string and returns true if it's valid and false if it's ...
I would like to transform a dict of one format into a dict of another format. The raw_input dict will have the shape: 'key': ['list of strings'] I would like to reformat it into a list of dicts with the following shape: [ {'key': 'string'}, {'key': 'string'}, ...etc for each item in the list of strings ] ...
Can this be done more efficiently? The code does the following: Do Stuff Show UserForm and ask user to confirm the shown data is ok User can manipulate and controll excel as usual As soon as user clicks the "yes" button "do some other stuff" is called The Module Sub ControlDataUI() Dim Ui As New UserForm1 Dim IsConf...
I am working on scanned documents (ID card, Driver licenses, ...). The problem I faced while I apply some preprocessing on them is that the documents occupy just a small area of the image, all the rest area is whether white/blank space or noised space. For that reason I wanted to develop a Python code that automaticall...
This script counts consecutive number strikes of a number that you determine in a number-sequence that you also determine. I would be very pleased if this script can be reviewed in terms of compactness, readability and quality. If this is perfect, please also let me know. But I am shure it will not be. The script can b...
My code already works perfectly. Here is the JS file: var movieData = { count: 6, movies: [{ id: 1, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, { id: 2, title: "Lorem Ipsum", thumb: "assets/img/placehold.png" }, { id: 3, ti...
I'm running a package that downloads data from the internet. This package makes logging calls from different modules. Suppose I have a package 'demopackage'. Here is how my logging is currently set up. Is it possible to improve this way of working? The main.py script runs triggered by a cron job. demopackage/init.py...
I am building a string for a search query and I think I am doing it the wrong way. So basically I have serveral textfields, dates, integers and so on in one form. On submit I am checking the forms if its empty or not and building the query string. I am submitting the model and building a kind of "pyramid" by checking i...
I have coded a simple card game that updates the GUI each second and contains many nodes in game which are used to display game events and animation. People who have tried the game said that their system slows down and memory and CPU usage goes up (I was shocked when I saw from one of my friend's screen that it used ar...
Here is the working code (intended to be executed with perl -e '<code>' ~/.ssh/config): Actual version: while(<>){if(/^Host (.+)/){$_=$1;foreach $i(/([^ ]+)/g){$h{$i}=1}}}print "$_ " for keys %h; Identical version with whitespace for reading: while(<>) { if(/^Host (.+)/) { $_=$1; foreach $i(/([^ ]...
How could I make this code more effective? static void print_decimal(double decimal, int precision) { size_t integer; while (precision--) { decimal *= 100.; integer = (int)decimal; if (!precision && (integer % 10) >= 5 && decimal != (double)integer) integer += 10; ...
Here's my code. javascript:x=document.createElement("script");x.src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"; document.getElementsByTagName("head")[0].appendChild(x);copy(1) Is this the correct way? Are there any flaws in it? Running: copy(1) doesn't work by itself so that's not a possibility,...
Edit: I got asked a lot why I need to have the LightSource base class or why do I keep one vector of all the light sources, so here's my explanation: In many points in the code I need to interact with all the lights regardless of their type. For example, I manually implemented a "shader" which looped over every face an...
A friend of mine has the following issue. He has a nearly-full 1TB hard drive on which he keeps copies of all the pictures from his digital camera(s). However, he knows that he has copied the entire contents of the camera to this drive multiple times, with slightly similar--but mostly identical--contents every time. He...
The following code cd's into the scrape folder, and enters the command "scrapy crawl yellow". It works well, however i want to make this more object oriented looking, utilizing something like if__name__== "__main__" not sure how to implement this kind of code. Ultimately i want this to be an executable which is why ...
In the main method, I have to call a factory to retrieve the Parser and cast it to a child parser to read the different file. How should I improve the code for it to make more sense? Can I avoid casting the parser? public interface Parser<T>{ public Parser read(T t){}; } public class ParserFromJson implements Parser...
I have a solution to find if two values are present in a binary tree (not a BST). I would like to know if there is a more efficient way to do this? a more elegant way to this? specific improvement for the parts I've marked with comments? a better way to generalize the solution if we have to check if some 'n' values (...
I wrote a function to find the closest value in a list to a given search value. What prompted me to write it was as boilerplate for a prime number problem so I could find the closest prime to a given number. My Code ''' * This function finds the closest value in a sorted list to a given search value. * Paramete...
Leetcode: Valid parentheses Given a string containing just the characters (, ), {, }, [ and ], determine if the input string is valid. For an input string to be valid: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is considered...
I have a set of rules as follows: Product One: If either part is acceptable, update both parts Product Two: If either part is acceptable, and one age is > 55, update both parts If either part is acceptable, and neither age is > 55, then update whichever part needs updating (or both) I know it's not the most nested ...
Recently I have solved the inverse matrix in three ways, found that their work efficiency has obvious differences. This is the case: typedef signed char int8; typedef signed short int16; typedef signed int int32; typedef unsigned char uint8; typedef unsigned short uint16; typedef unsigned int uint32; typedef float floa...
I made a program in IDL for performing a minimum distance classification on multispectral satellite data. This is what my main function looks like: function minimum_distance, stack, exercising_data ;variables nbands = get_number_of_bands() nclasses = get_number_of_classes() x_size = (size(stack, /DIMENSIONS))[...
here I am taking 3 inputs. 1st input will take test cases and the other two input will take starting and ending range. the program is running fine as expected but the limit of this question for compilation is 1 sec, and my code is taking 5.01 sec. How can I make it more efficient so that I can submit the code? The cha...
I'm making an online shopping store or e-commerce and I use an express session for many things. Example: Shopping Cart, Authentication user* I store the data chart list in the database based on the sessionID so when a user visits the website, the user does not need to log in for add to cart. As well as login, to chec...