instruction
stringlengths
71
95.1k
Could you give me your opinion about this simple rock, paper, and scissors game code and tell me tips to improve this code? #include<iostream> #include<cstdlib> using namespace std; enum element {rock = 1, scissors = 2, paper = 3}; enum result {lose = 4, draw = 5, win = 6}; short random (short from, short to) { r...
I'm trying to learn Django by building an inventory management system, here's my final models.py. I'm looking for feedback! from django.core.exceptions import ValidationError from django.urls import reverse from django.db import models from core.models import Department from accounts.models import User class Item(mod...
this is the second version of this project, you can check previous post here: Terminal Graphical Visualizer, using a queue of different matrices I implemented bare-bones version of ncurses library (without using it obviously), and using it I implemented 3 visualizations: falling sand simulation - drop a line of sand p...
I have defined a data structure in Java that allows to manage certain type of elements like a Queue, with the special feature of using 2 inner rows (windows) to attend elements: import java.util.ArrayList; public class TwoWindowsQueue<E> { enum WindowState {CLOSED, OPEN} enum WindowTurn {WINDOW1, WINDOW2}...
Could you review this implementation of a queue data structure according to the principles of Object Oriented Programming and Clean Code? import java.util.ArrayList; public class SecurityCheckQueue<E extends ByAir> { private ArrayList<E> queue; public SecurityCheckQueue() { queue = new ArrayList<E>();...
The following is a general purpose file compression function with the following features: It can take either a single file or directory as the source input It defaults to the source directory when to destination is input It will compress all files of a type associated with the extension parameter It removes the origin...
I have a business use case that required running SQL insert queries to a local MSAccess database with a Python script. The actual script does many other things and the SQL function is just one of them, but it is a critical one. However, due to limitations outside my control, all I had to work with was Python 3.6 64 bit...
How can this code be improved? I'm a novice programmer trying to learn ml by doing it from scratch. This code is part of a transformer model that I'm working on. Do you have any ideas about how to improve it for better performance and easier reality? import jax import jax.numpy as jnp class Embedding(): def __in...
This is my attempt at making a basic TicTacToe game to play against another human player or a computer controlled opponent. The project was a lot harder for me than I initially thought it would be! I have the feeling I've over complicated some things and think that especially the 'AI' part is not very elegant/efficient...
This is the forth iteration of the Fast search for the longest repeating substrings in large text (Rev.3) code review. Special thanks goes to G. Sliepen who conducted all the reviews. Functional specification Having a large text and already built suffix array find the longest substrings (limited by the number of repeti...
This is a continuation of this review. I applied most of the proposed changes. These changes were focused mostly on decoupling the class from the rest of the program and making its interface more like STL collections. Description of the code: This is an implementation of a set data structure. It is optimized to efficie...
I've been working on a WordPress pricing page template and would appreciate feedback on the code structure, organization, and any potential improvements. The template is used to display a pricing list with categories and items. How can we reduce this whole amount of nestiness and code? <?php get_header(); $cennik_kat_...
I have currently implemented an increment method. A method to add bytes. And a method to print out the bitset.   Main.cpp #include <iostream> #include "DynamicBitset.h" int main() { DynamicBitset bitset; unsigned char count = 97; bitset.addByte(count); bitset++; bitset.printArray(); return 0; } DynamicBitset.h #p...
I'm the maintainer of the zxing-cpp library, a barcode image processing library written in C++. I recently decided to invest in a Rust wrapper library/crate that is now on crates.io. It is basically a very simple API: a bunch of enums, 4 structs/classes to pass parameters in/out and one static function: pub fn read_bar...
I'm new to SQL, but I've always heard that it's a very efficient way of searching databases. For the same task, in VBA I get a result in a few seconds for 1000 queries. In SQL it takes several minutes. I've tried going back and forth between my databases and my code to try and improve the execution speed of my triggers...
This CSS code creates an animation that describes a random movement using the CSS transition property for box-shadow which properly results in what resembles an ascending effect followed by hovering. <html><head> <style> body { background-color: #fff; height: 100%; margin: 0px; padding: 0px; w...
Implementation supporting both typing directions from left to right and from right to left. It also supports alternating typing directions and configurable letter spacing. With monospace font the typed line extends and narrow fluently. Developed around innerText method of HTMLElement to display the text to type and inn...
When creating little games or other programs I often need multidimensional arrays. Usually I just do the simple std::vector<std::vector<T>> thing for simplicity's sake. However, this runs way more allocations and the data is not stored in one contiguous location, which brings some drawbacks with it. To fix this I wante...
I'm really new to Rust with less than a day of rusting. I'd like to know if the following code is ok or could it be written somehow better, and specifically, which would be the preferred way to handle the actual error case. The return type bool represents whether a packet was received or not, so that the call to tryRec...
Suppose we have a string and we want to format different parts of it differently (like in Word). My goal here was to create a data structure that can hold all the various parts of the string as character ranges and store the formatting used for each. The user of this data structure should be able to call something like...
I have tried to implement a code that does the following: store words in an array (unordered) use function order_array() to place repetitions for the same word near (so the result, given a sample text file, could be: mom mom mom mom lamb lamb eye eye pain tears) use function count_frequency to store every word one sin...
In my React learning journey, I wanted to create a Note app following the SOLID principles and use as many hooks as possible to grasp things in React. If you can review my code and improve it, it would help me a lot. App //App.jsx import { useEffect, useState, useReducer } from "react"; import { initialNotes, notes...
This is related to my previous question. This is it, the full working code that resolves all file record segments in a Master File Table to absolute file paths. It is completely working and seems to working perfectly as I have manually checked dozens of the results against Active Disk Editor and have determined them to...
While migrating a Spring application to Spring Batch, I encountered a scenario where I need to process chunks of records from the database and invoke a stored procedure for each chunk. However, each stored procedure call is taking approximately 500 milliseconds, and the performance improvement isn't significant. Note :...
This function mimics Python's map() function (No, it doesn't support generic return types for the function or multiple iterables) by applying the provided function func to each element of the array iter. It returns a new array containing the results which must be passed to free(). #include <stdlib.h> #define map(count...
When we add lots of floating-point values, we can lose precision if we blindly use std::accumulate() or similar, when the running total becomes much larger than the terms we're adding to it. I wrote a small program to demonstrate those effects using four different strategies, each briefly commented in the code. #includ...
The Windows OS doesn't feature a Split command and although I do have a Linux partition, I mainly use Windows 11. As such, I implemented the Split command in C++20 so that I can use it on Windows. The program seems pretty fast; I used it with a large Linux ISO(~4GB) and it took only few seconds to finish(<10s). Please ...
I have a small package that provides some API for playing around with the <An+B> CSS microsyntax. It is 100% type hinted and tested, but doesn't actually have any real/useful features and this question is not about the main code anyway. I was introduced to the Hypothesis testing library in a previous question and have ...
I'm working on a stateful Jetpack Compose composable that follows the MVI architecture. I'm using collectAsStateWithLifecycle() to observe the view state from a view model, but I'm unsure about the best approach to collect side effects with lifecycle awareness. I'd appreciate your insights on: The correctness of the c...
Problem description from the Advent of Code website: Part 1: The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits and combining them into a two-digit number. The goal is to find the sum of...
All right, let's do this one last time. This is continuation of this review. I applied most of the proposed changes, making interface of my container very close to that of std::set. (I also added a few things that weren't explicitly mentioned but I found them on cppreference.com. For example, some type definitions like...
Problem statement: Sort integer array nums in O(N log N) time, without relying on any library sort routine. I am trying to use a tree sort method (using the creation of a BST and then performing inorder traversal) in order to sort an array of numbers. I have the following code: class TreeNode: def __init__(self, va...
This is a follow-up question for A recursive_find_if_all Template Function Implementation in C++, A recursive_all_of Template Function Implementation in C++ and A recursive_all_of Template Function with Unwrap Level Implementation in C++. To support std::string, std::wstring, std::u8string and std::pmr::string(making r...
Event driven architecture implementation resembling pulsing with configurable softness (intense, mild, subtle), pulsing mode (inhale, exhale), pulsing frequency (plain, dense, breathe), number of pulses (including countless pulsing) along with on demand ending and observable pulse ending event. <html> <head> <style> bo...
I am trying to solve a multi-class classification involving prediction the outcome of a football match (target variable = Win, Lose or Draw). With a dataset of 2280 rows, which is 6 seasons of football data. I have features with both numerical and categorical values (which I have encoded using one encoding). The data i...
I have a legacy PHP project using a self-styled configuration file (named globals.inc.php) which is generated by build scripts based on a template included in the code called globals.template.inc.php: <?php use MyPropject\Core\DBConn; require_once __DIR__ . "/vendor/autoload.php"; /** * GLOBAL variables * */ defi...
I'm writing a web bot using puppeteer and I'm logging (using winston) every action the bots does and running it inside try/catch blocks. For automating these processes and avoid code repetition I created this function: module.exports = { webAction: async function (logger, msg, func, ...args) { return new Promi...
Is this code for quicksort using the first index as a pivot correct? Also if I want to use the last or middle index as a pivot how would the whole code change? #include <iostream> using namespace std; void quicksort(int list[], int arraySize); void quickSort(int list[], int first, int last); int partition(int list[], ...
My last project shared here was apparently too complex so I figured I'd share something really simple Here's a UriValidator. Its purpose is to validate URI paths and schemes. Admittedly, one would expect it to validate entire URIs too, but I didn't need it, and SchemeAndPathValidator was too clumsy a name package com.e...
I know there are many good libraries for this, but to understand the issue better, here is my own basic attempt. The fetch will be retried if it fails with a promise rejection or the response indicates a server error. It assumes that GET, PUT, etc. are idempotent, like they should be. function retryWrapper (fun, delay,...
I'm making a random number guessing game in Python. Any suggestions? I'm going to add a restart button to it. import random #imports the random module to generate random numbers #defines the guess_number function, which creates the random int def guess_number(): #generates number random_number = random.randint(1...
I am transcoding video to different quality using ffmpeg using subprocess in Python. I want to make my transcoding faster. I tried multi-threading but it didn't help. Hardware acceleration is not possible as we are using an AWS EC2 t3.large instance at this time, which has 2 CPUs, 8GiB memory, and 30% baseline performa...
Problem For some user-facing string, I want to truncate it to some given maximum length (also useful for file name/path lengths on Windows etc.). However, I want to do it a little more elaborately than just appending ... or … or so at the end, as I want to place that character in the middle. I.e. I want both the start ...
import React, { Component } from 'react' import PropTypes from 'prop-types' import Flatpickr from 'flatpickr' const hooks = [ 'onChange', 'onOpen', 'onClose', 'onMonthChange', 'onYearChange', 'onReady', 'onValueUpdate', 'onDayCreate' ] class DateTimePicker extends Component { static propTypes = { ...
I have a code which does the following: For each value v in a 2D array, look at neighboring positions - how far to look is specified by distThreshold. If the count of values identical to v in the neighborhood is lower or equal to countThreshold, change v to a value which is most prevalent in the neighborhood. For examp...
I created this code in Svelte which will show a modal and remove it when the background is clicked, based on a native JavaScript implementation I wrote earlier. In the *.svelte files, I put the focus on the code and components, the styles are not included so that the code won't be too long in total. You can find the CS...
I've built the following isLeapYear function in Idris: module Leap import Data.Nat partial isDivisibleByFour : Nat -> Bool isDivisibleByFour (year) = (modNat year 4) == 0 partial isNotDivisibleByOneHundred : Nat -> Bool isNotDivisibleByOneHundred(year) = (modNat year 100) /= 0 partial isDivisibleByFourHundred : Nat...
I am writing the following VBA code to make a timeline, which I will be using for other parts of the code later on for other calculations and output. I have a userform where the following number of text boxes and labels are present: wkbox* and intbox* are textboxes which have weeks as input from user. wkbox* is durati...
This is a follow-up to this question. Please check it out first for the motivations, known use-cases and explanations. In this new version I've applied several of advices from this answer by @J_H: instead of a random ping content, timestamp and sequence number with hash "signature" are sent. This allows to report accu...
I am trying to implement an odometer in Rust. This should a be an iterator that yields items of type [u16; N] and it should be generic over const N. Configuration Parameters The iterator should be configurable with a starting state of type [u16; N] which should be the value yielded on the first iteration, and a limit w...
Introduction I have this semi-dynamic range minimum query (RMQ) tree in Java. It is called semi-dynamic due to the fact that it cannot be modified after it is constructed. However, the values associated with the keys may be updated. An RMQ tree maintains a set of (distinct) keys and associates a value with each key. Th...
The following code is code I wrote in c for a simple neural network with no backpropagation implementation yet. All the header files were put in one file because I am using visual studio which does not have a default for c code just c++ and the seperate header files were causing problems. The goal of this project is to...
Greetings One small problem that anyone have to tackle with in Python is handling invalid argument types ( without an automatic static type checking tool like Mypy ) One of the best methods for handling the invalid argument is raising an exception which would easily inform the code client with the required steps to fix...
The bisect module can only find the index to insert an element. I created a simple class based on the bisect module for precise searching and covered all the edge cases that came to mind with tests. Could you please check the correctness of the tests for the binary search extension module? I want to make sure that the ...
Objective: Write a program to count the frequencies of unique words from standard input, then print them out with their frequencies, ordered most frequent first. For example, given this input: The foo the foo the defenestration the The program should print the following: the 4 foo 2 defenestration 1 The test input ...
I needed to update a class in Node.js that parses the response from a new weather API endpoint but still preserves the same object structure and key values from having been using the old weather API endpoint. The return value from the class' main method should be an array of eight objects, each representing data from ...
This module is a simple event manager that works with decorators. I would like feedback on: Bugs Any ideas to get rid of the classevent decorator, which complicates the usage, and is error-prone. The readability of the code The quality and thoroughness of the unit tests event.py """A module that defines decorators to...
Could you please conduct code review for the code below and suggest some improvements? Functional specification Implement a function for fast tokenization of text in char[] buffer handling some natural language specifics below: Consider ‘ ‘ (space) as a delimiter, keeping a way to extends the list of delimiters later....
As a part of guice-context-scopes library for building custom Guice Scopes, I have a class named InjectionContext (code below), that stores scoped objects in a Map indexed by com.google.inject.Keys. On top of this library I have a library that provides websocket Scopes (and also properly re-implements Servlet Scopes), ...
import React, { useState, useEffect } from 'react'; import styled from 'styled-components' const GameArea = styled.div` height: 200px; width: 100px; border: '1px solid black'; ` const Box = styled.div` width: 50%; height: 50%; background-color: ${props => props.color}; text-align: center; opacity: ${p...
When testing or debugging allocator-aware objects, it can be useful to provide allocators that can provide insight into how they get called. The Tracing_alloc from A fixed-size dynamic array is a reasonable starting point, upon which I've built. I provide four allocator adapters, which all modify an underlying allocat...
This is the second iteration of the Natural language text fast tokenizer code review. Special thanks goes to G. Sliepen and Toby Speight who conducted the first review. Functional specification Implement a function for fast tokenization of text in char[] buffer handling some natural language specifics below: Consider ...
I created a Pascal's triangle. I'm in 2nd semester, so I'm not that professional in programming. If there are some suggestions for improvement, please tell (took me 2 & 1/2 hrs to find the logic). //Pascals Triangle package logicBuilding; import java.util.*; public class PascalsTriangle { static void print(int[] ...
Task: Write a program that is given three numbers corresponding to the number of times a race car driver has finished first, second, and third. The program computes and displays how many points that driver has earned given 5 points for a first, 3 points for a second, and 1 point for a third place finish. Code: #inclu...
This is my first Apache pipeline. It takes a JSON file and saves the correctly formatted rows in one table, and the misformed rows in another. My biggest worry is the efficiency. I have tested the code with the tiny (cr. 700 rows) file. The real input file is huge, it contains tens of millions of rows. The error messag...
I have implemented an Iterator for my Pojo class. The purpose here is to lazily decode multiple Pojos encoded in a buffer (bytes array). To improve performance, it needs to be thread-safe to be correctly used from multiple Thread (parallel Stream). The buffer is formed as follows : The first 4 bytes represent an int i...
I have a Node.js logging library that applies ANSI styling for text formatting. Currently, the code contains some redundancy and could be refactored for better readability. I'm particularly interested in simplifying the method definitions for applying bold and underline styles. Here's the existing code: class Logr { ...
Given the path to a filesystem directory, the task is to delete all empty directories within that root directory. After the process is finished, no empty dir should exist under the root directory (the root should also be deleted if it ends up empty). Examples (the d prefix means it's a directory): dA ...
I need to insert about 500k - 1 million data lines from a CSV file. The time of getting the reports list and insert to database by using SqlBulkCopy is very good (10k ~200ms). However, the time to check data validation and add elements to DataTable is very slow (10k data ~ 2 minute). I tried many ways but it didn't get...
Good morning, everyone. I have developed a C library whose goal is to store strings in an easily searchable tree structure (which I have dubbed tree-dictionary). I come from a math background and I have been coding in Python for a few months, but I am a still a complete beginner to C and this is my first non-trivial pr...
I have written the following simple find function template that does a linear search. #include <iterator> #include <concepts> #include <array> #include <random> #include <algorithm> template <std::input_or_output_iterator InputIt, class T> requires ( std::equality_comparable_with<std::iter_const_reference_t<InputIt>...
The main concern is the hard requirement for python3.12 since I couldn't find a clean replacement for pathlib.Path.relative_to(root, walk_up=True) in earlier pythons. I need it in order to generate relative URLs like ../../../.thumbs/some/dir/image.jpg Also not sure if the multithreading is sane for parallel thumbnail ...
This is my first rough attempt at creating a function to return the nth number within the look-and-say sequence. I'm pretty sure there are some ways to simplify it, even given my current approach. Also, I feel kind of guilty that the first number is hard-coded. def look_and_say(iterations): if iterations == 0: ...
I have a situation where I need to compare two strings with each other in a foreach loop that potentially run over millions of rows of data. The two strings will always contain between 1 and 12 different parameters, but these come in as a string concatenated with comma. The strings don't necessarily come sorted either,...
This is the third iteration of the Natural language text fast tokenizer code review. Special thanks goes to G. Sliepen, Toby Speight and uli who conducted previous reviews and to Matthieu M. and Adrian McCarthy who participated with important findings. Functional specification Implement a function for fast text tokeniz...
I have this class EfficientStorageEventProvider, which is responsible for efficient handling of StorageEvent EfficientStorageEventProvider.ts import { IStorageEventRecord } from "./IStorageEventRecord"; import { defer, Observable, share, Subject } from "rxjs"; import { doOnSubscriberCountChange } from "rx-do-on-subscri...
I have created a large module for downloading data from SAP and editing and displaying it on a plotly dashboard. While the code is running as desired there is one problem that bugs me: The submodules are themselves dependent on large third-party modules, some of which take a very long time to load. This is also due to ...
Motivated by the first commentor's suggestion on my MSAccess question: Python SQL insert to MSAccess with VBScript I am moving to use SQLite databases for a python application and I created this query builder class to help implement the SQL logic. One constraint is having to use Python 3.6 so that is why I used .format...
I wrote a simple text parser and a converter using Python 3.12.1. The purpose is to read a text file that contains 20000 words one per line, and create an output file that contains all the queries. Here is a snippet of the input file with fake values: aaaaaaaa bbbbbbbb cccccccc dddddddd I got this file from an externa...
This is my first time creating a non-trivial database and I was wondering what I could do better. As the title says this will be used a in toy version control system. Most of my choices feel "random" because I do not know what is and is not important. I also can not decide on what the tables should know about themselve...
We are using Searchkick to run our elasticsearch and Pundit to authorize users for specific actions. Below is our module SearchkickScope that does it's best to scope results to those found via the policy_scope supplied by Pundit. Since this is a security related module, I would love some outside opinions on this implem...
This is the forth iteration of the Natural language text fast tokenizer code review. Special thanks goes to G. Sliepen, Toby Speight and uli who conducted previous reviews and to Matthieu M. and Adrian McCarthy who participated with important findings. Functional specification Implement a class for fast text tokenizati...
I am writing a command line tool to copy files to or from locations, which can be a path inside a task inside a running Nomad task. The location can be either a stream or location on the local computer, or the location inside a Nomad task, where multiple "search" options are needed, each of them can be of any character...
As indicated in the title, this small project fetches content from the SEC's Edgar REST API. It was designed with the intention of automatically gathering/refreshing large datasets of public company financial data on a Linux server. For some additional context, I am starting a pivot from a pure financial services role ...
I am trying to adapt an R script that I wrote to perform several tasks in a for-loop. The for-loop run over thousands of items, for about 900 times, therefore I would like to optimise my code at the best. I decided to go for c++ via Rcpp. Here it is my code: cppFunction(' Rcpp::DataFrame FasterFunction(StringVector pat...
I recently started working on my own vector library for a project and I thought it would be a good idea to get some insight on the code that I have written so far. It's very simple as I'm new to C. Vector.h #ifndef _VECTORS_H #define _VECTORS_H #define ABS(n) (((n) < 0) ? -(n) : (n)) /* Absolute function */ #define TO...
I'm trying to find all unique file owners in an NTFS file system. Getting the number is fairly straightforward, but my current approac is very inefficient: $Shares = @( "\\Server\Share1", "\\Server\Share2", "\\Server\Share3", "\\Server2\Share1", ... ) $i = 0 foreach ($Share in $Shares) { $i++ ...
Task: The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits and combining them into a two-digit number. The goal is to find the sum of all these calibration values. For example: 1abc2 pqr3s...
This is the next iteration of the Natural language text fast tokenizer code review. Special thanks goes to G. Sliepen, Toby Speight and uli who conducted previous reviews and to Matthieu M. and Adrian McCarthy who participated with important findings. Functional specification Implement a class for fast text tokenizatio...
I decided to share with you a portion of my gateway project. It's an authentication extraction filter that extracts authentication claims without being coupled to any specific authentication mechanism. I have only one concrete AuthenticationExtractor implementation that parses JWT tokens, but you can simply create anot...
I was trying to find the Maximum sum BST of a binary tree on LeetCode. While the Java code I have come up with, mostly seems right and is able to pass 55 out of the given 59 test cases too, the error of 'Time Limit Exceeded' comes up. Is there anything I can change, in the same given code, that would optimize it and/or...
Originally I meant to discuss my entire project on stepper motors for Raspberry Pi. But I see that's out of scope. If you'd like to provide high level feedback, welcome to do so in github. The lack of true parallelism (multiple thread running simultaneously) due to the GIL, imposed a setback to my library as soon as I ...
I am new to C and have been learning it for about a month now. This is my attempt to implement a dynamic array. My code works, but i don't know whether or not it leaks memory. But my code works as I expected. Is my code good or bad? #include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct { int si...
Could you please conduct code review for the code below and suggest some improvements? Functional specification Implement a multithreading parser based on existing natural language tokenizer. Parser should compile text into sequences of lexem ids. Parser should create structures to get lexem text by id and id by lexem...
First my appologies. My mental faculties currently leave rather a lot to be desired and I have thus spend an inordinary amount of time on this pet project of mine, testing myself if you will. I find it incredible difficult to wrap my head around most of these things I used to be able to do in my sleep, and it is utterl...
Given a list of strings (say a text file containing some C symbols: c-symbols.txt), the program can: Generate a graph of the underlying trie (-p/--prefix can be specified to inspect a specific prefix subtree) with Graphviz dot: » time ./trie --prefix at --svg c-symbols.txt ./trie --prefix at --svg c-symbols.txt 0....
This is a follow-up question for A recursive_find_if Template Function with Unwrap Level Implementation in C++. I am trying to make some constrains on Proj and UnaryPredicate in recursive_all_of, recursive_find_if, recursive_any_of and recursive_none_of template functions. The recursive_invocable concept specifies that...
What would a good code of this look like, or is it good enough? import sys from pyfiglet import Figlet import random figlet = Figlet() list = figlet.getFonts() def main(): if len(sys.argv) == 1: text = input("Input: ") randomfont = random.choice(list) ...
Task: The task involves analyzing a calibration document containing lines of text. Each line represents a calibration value that needs to be recovered by extracting the first and last digits (which may also be spelled out as words) and combining them into a two-digit number. The goal is to find the sum of all these cal...
There is a code that performs calculations of parts of fuel injectors. There are two classes in which the basic calculations take place, they are called LiquidJetInjector and GasJetInjector, respectively. The Reynolds class stores constants for calculations. The SimilarCalculations class is a class in which the calcula...