instruction
stringlengths
71
95.1k
My professor required we make a LinkedList class with a bool add(in newEntry) method. Two things I'm questioning my choices on is the variable name temporary and instances of how to return False if it isn't successfully added. Or is simply not returning True is going to return something False? Is there a better convent...
I am a beginnner and have put up a code that talks to pagerduty API and then it fethces oncall info for a team (get team id, get escalation policy id, then finally get on call info). response is loaded in a json and then am fetching the values I need and saving them into dictionary. my concern is my code works perfectl...
I made this script that takes 3 images taken with a polarising filter 45° apart as inputs and outputs an RGB preview and an image which encodes the polarization parameters as HSV. However it's way too slow, taking 155.8125 seconds to process it. What can I do to improve it? import cv2 import numpy as np import matplotl...
I am looking for criticism or direction for simplifying this game. I plan to build a player class and Parent that into a terminal player and a my first machine learning minimax algorithm. For that reason, I am looking for a really concise direction on how I could better implement the basic function of a tic-tac-toe boa...
I want to use async/await by AsyncStream for Bluetooth scanning. The CoreBluetooth is using the delegate pattern. The following code provides an adapter for using async await with CoreBluetooth. Is there any potential problem with the following code? Thanks class BLEManager: NSObject { private var isPowerOnContinua...
The title is pretty clear. I have a code snippet I took from Stack Overflow that's licensed under Creative Commons and I want to attribute it properly. My understanding is with Creative Commons you need to do TASL, Title (if present) Author (and preferably a link to their online presence) Source (where it is from) Lic...
I wrote a method that finds the maximum sum of consecutive decreasing sequence of odd integers. For example: if sequence is 13 9 7 12 13 15 13, then sum is 29 (13 + 9 + 7). I don't think it's as good as it could be, because the same code is repeated multiple times. static int SumOfLargestSequence(int[] array) {...
I need to print those numbers in console: 0 1 2 3 - 5 6 7 8 - 10 11 12 13 - 15 16 17 18 As you can see I am not printing 4, 9, 14. So I coded this: top = 18 counter = 0 print("Using option 1") for i in range(top -2): print(counter) if counter == 3 or counter == 8 or counter == 13: counter = count...
I am making a board game with a computer player. The game is on a 6x6 grid. It's like chess but with pawns only. Each player has 6 pawns; one player is circles and one is crosses. The goal is to be the first player to reach the other side of the board. Each move is either one step forward, or a "jump" on a diagonal ove...
I have a map with the following data let res = new Map(); res.set('2022-10-31', 'nav'); res.set('2022-10-27', 'entry'); res.set('2022-10-27/duplicate/sending', 'sending'); res.set('2022-10-27/duplicate/cancellation', 'cancellation'); res.set('2022-10-27/duplicate/paymentToManager', 'paymentToManager'); And I need to s...
I am working project where I need to build ASP.net control base on JSON data. I am using this method below to get all the data into class. I as using FirstOrDefault and the Where(x => x.Type == ??? to drill down into the data. I think the logic could be simplified, Any suggestions are welcomed. working sample below JSO...
I implemented Willans' formula to calculate the nth prime number in Rust: use std::f64::consts::PI; pub trait Factorial { fn factorial(&self) -> u128; } impl Factorial for u8 { fn factorial(&self) -> u128 { let mut x = *self as u128; let mut product: u128 = 1; loop { if x ...
I have been writing Hunt the Wumpus game in C++, and i think it's finished. It's first non-trivial project, and it DOES work properly (at least 20 hours of debugging showed so). How can the code be more clean or simply better ? Rules are in the game.cpp. Any criticism or suggestions are welcome. game.cpp #pragma once #...
In my Svelte app, I need to reactively fetch data from the server and then render the result. The ideal data struture for this is a store whose values are promises – eg. like this: let article = writable("about"); let text = derived(article, a => fetch(`http://example.com?article=${a}`)); However, the way I want to re...
The project outline: Write a program that finds all files with a given prefix, such as spam001.txt, spam002.txt, and so on, in a single folder and locates any gaps in the numbering (such as if there is a spam001.txt and spam003.txt but no spam002.txt). Have the program rename all the later files to close this gap. My...
using UnityEngine; namespace Jumping { public class JumpingMechanics : MonoBehaviour { [SerializeField] private Transform TransformWhichJumps; [SerializeField] private AnimationCurve AnimationCurveWhichDescribesJumpingTrajectory; public bool ShouldThisCharacterJumpNow { get; set; } ...
I am learning Rust and I would like to get some feedback around my solution to calculate the median value from a list of integers. I believe the logic is correct as my tests pass, but I'm concerned the right types and if I coded "the Rust way". use std::f32; fn main() { let mut v = Vec::new(); v.push(5); v...
I have solved a leetcode problem (Median of Two Sorted Arrays), and I came up with two solutions. Solution 1 def findMedianSortedArrays(nums1, nums2) -> float: nums1.extend(nums2) nums1.sort() median = 0 num_len = len(nums1) while((num_len % 2) == 0): median = (nums1[int((num_len - 1)/2)] + ...
Introduction: Any angular dev should know that Angular tends to provide multiple ways of doing things. When it comes to forms, I tend to prefer to rely on forms of the template-driven variety, and for dynamic template-driven forms, two-way binding with the default change detection strategy is helpful toward keeping yo...
Sample code below - it works, but feels clunky. clients is provided from a DB as a json_encoded array of objects (in the real app this is several hundred items.) Objective: filter the list based on user input, which can be a partial case-insensitive string of code or name. The user knows in advance what the id or name ...
I recently had the problem that I wanted a hashmap where there would be a variable amount of distinct classes which each could be used to look up each other. I couldn't find any implementation online so I wrote it myself: // Compile with c++20 because this code uses concepts #include <concepts> #include <vector> #inclu...
I solved LC12 (Integer to Roman) in Rust. I am a beginner with Rust, so I translated my previous solution from C++ to Rust. I am looking for feedback on how I could improve the following Rust code. The make_digit is nested because I got error saying it's not available in the current scope. I could find the following ca...
I'm preparing for the Advent of Code 2022, and in order to shake off the cobwebs, I'm attempting some problems from the previous year in rust. Starting at Day 1, I've been trying to get comfortable with iterator mechanics. The problem description for both parts is: Suppose you had the following report: 199 200 208 210...
I am implementing an API that implements an interface, but I do not need to implement all methods. In that case, is it better to just return null or throw an IllegalStateException because it if not implemented? Thanks. @Override public ResponseEntity get(long id) { // ... some meaningful code return response; }...
This algorithm adds two numbers digit by digit using their string representations. I am wondering what the time and space complexities of the following algorithm are. In particular, I am wondering about the string addition lines, which may make it a quadratic time complexity. In general, what are some ways to improve t...
So we have many vlans at work, often it is nice to see which ip ranges are associated with said vlan. We have a well developed api for displaying information about our network and thus I wrote a small script to extract this information. The only issue is that to access the API we require a token, no older than X hours....
A small, simple yet always needed function to compare two strings for equality. int strequal (const char *str1, const char *str2) { while(1) { if((*str1) != (*str2)) { return 1; /* Not Equal*/ } else if((*str1) == '\0') { return 0; /* Equal */ ...
The assignment is to be implemented on the following instructions: You are to write a Knapsack class and the main() to support and demonstrate the functionality required here. A function generate(int) is prototyped in collect.h and defined in the library libGenerate.a. It returns a letter (char) that identifies which ...
This is a wrapper around RabbitMQ.Client's ConnectionFactory. Here is the simplest Producer/Consumer RabbitMQ example https://github.com/delaneybrian/jumpstartCS-rabbitmq-csharp/tree/master/1-First-RabbitMQ-App. I would like to get a code review over that factory method and its dependencies because I feel like the prop...
The application is a virtual piano with only one octave for simplicity. What can I improve with this code? #include <iostream> #include <SFML/Audio.hpp> #include <SFML/Graphics.hpp> #include <math.h> static const int SAMPLE_RATE = 441000; static const int WIDTH = 400; static const int HEIGHT = 150; static const int KE...
This code draws a star from mario. It's somewhat simple, but I feel like it could be a lot shorter. Do you have any suggestions? from turtle import Turtle a = Turtle() #size of square side side = 20 #number of squares in a row numSquares = 17 a.speed(11) a.hideturtle() #defines how to fill color in a square def squa...
I have a class that stores some data and two methods that set this data from strings and convert it back to a string. I call AddDetail(string detail) when reading multiple lines of a text file, so it gets called many times. I don't like multiple if and else if statements and I use loops whenever possible. Is it possibl...
I'd like to seek advice on my implementation of rate controlling or throtting tool which implemented by C#.NET 6. correctness of implementation performance issue or any improvement can be done. public sealed class RateLimiter : IDisposable { private const string KEY = "RL"; private readonly Timer _timer; ...
Is there a way to make this code bellow more DRY or is this fine as it is? I am wondering if there could for instance be a way to combine the two functions in to 1, the output type of which would be determined by some typescript logic but I don't see how yet. Please let me know if you happen to see anything else worth ...
I'm learning Factory pattern and I've implemented this simple example of an abstract factory. I've followed this video a little bit while writing this small example. Is there anything anti-pattern or wrong in this example? I've created two different Pizzas public interface IPizza { public string Name { get; set; } ...
I've been coding for some time now and since I am working alone I'm not strict in my coding structure approach(bad idea) and was only focused on getting things done which resulted in MVC(MASSIVE-View-Controllers). Now recently I've started adapting to MVVM and things are looking clean and simple. But I'm not sure if I'...
I am building a TCP server in C++, and right now it's a test version without logic to handle server-client packet transactions. Please check if there are any memory leak related issues or anything else I can do better. Program.cpp #include <iostream> #include "Network/Server.cpp" int main() { srand(time(NULL)); ...
I created the below class to help working with ND Arrays, mapping based on this question. This will help in implementing the code for handling convolutions. How can I improve upon this? Is there something essential I'm missing from the interface? header: class NDArrayIndex{ public: NDArrayIndex( std::initializer_...
Hi, I am making a Minesweeper game using SFML 2.0. I am just a beginner in C++ and started using the framework for 2 weeks now, so it is safe to say I may have made lots of mistake especially when it comes to data types or algorithm implementations. Before I start, I'll have to explain this two setting variables to avo...
Yesterday, inspired by some great questions here, I decided to give myself some practice with Rust, by solving all the introductory questions over on LeetCode. It was a great learning exercise, and one of the problems left me wanting your advice: “Middle of the Linked List” Their summary of the problem: Given the hea...
I have this simple POJO: package com.github.coderodde.person; import java.util.Objects; public class Person { private int age; private String firstName; private String lastName; public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName ...
The code below is working however, if more zeros (empty cells) are added to the sudoku grid g, it takes longer to run, if it ever finishes. def is_solved(grid): for row, col in zip(grid, [*zip(*grid)]): for i in range(1, 10): if (i not in row) or (i not in col): return False ...
Below is the game code written in cpp. This is the first time I have consciously used pointers. I can't handle the logic of winning. I have no idea how to solve this in a different, more accessible way. I know that such straining of if statements is bad and the code is unmaintable. I realize that for some reasons you c...
Hello beautiful people! I have created a script where I have two database functions (Feed and Product) where I have a list of Feeds in a store and a list of Product in the store. What I have done is that I am pulling from database every 60 seconds to get all Feeds & Products and see if there is a new URL that has been ...
Hello I'm currently developing a FPS game for my portfolio and I made a weapon shoot system, and I would like to receive feedback about my code to make more cleaner and efficient. Thanks. using UnityEngine; [RequireComponent(typeof(PlayerGunController))] public class PlayerGunShootManager : MonoBehaviour { priva...
This is my simple Blackjack game made in Python. I would love some feedback to write better code. from art import logo import random input("Do you want to play black-jack ? 'y' or 'no': ") print() print(logo) cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] user_hand = [] com_hand = [] def print_score(score...
I want to implement a multithreading LRU cache in C++. And here is the code. Can you tell me what should I do to make it more multithreading? #include <iostream> #include <unordered_map> #include <thread> #include <chrono> #include <mutex> using namespace std; class LRUCache { public: class Node { public: ...
I tried so many things to do this task. I have no idea why doesn't it work. Please help! '''Create a function in Python that accepts two parameters. The first will be a list of numbers. The second parameter will be a string that can be one of the following values: asc, desc, and none. If the second parameter is "asc,"...
As All PayPal PHP SDK deprecated, I wrote a simple PHP class to make payment with PayPal through cURL and verifying it. Note : I didn't add shipment details for payment because didn't need that. For some reasons, I want to redirect users to PayPal gateway (and not using popup method) class paypal-curl.class.php : ...
I am beginner for the openCV. I am using below codes to get four video in a file system and show to user. Like this: V1 | V2 V3 | V4 Video length does not match, If the video comes to end I restart again: import numpy as np import cv2 v1 = cv2.VideoCapture('first.avi') v2 = cv2.VideoCapture('second.avi') v3 = cv2.V...
For school, I have to create a server-client communication through Unix signals and only with SIGUSR1 and SIGUSR2. Client program #include "common.h" int s_received = 0; int ft_atoi(const char *nptr) { int i; int sign; int res; i = 0; sign = 1; res = 0; while (nptr[i] == ' ' || (nptr[i] ...
I am making a poker game and poker-evaluator that I am using to tell me only the outcome from the cards 'invalid hand', 'high card', 'one pair', 'two pairs', 'three of a kind', 'straight', 'flush', 'full house', 'four of a kind', 'straight flush' I am trying to know which cards in t...
The class assigns various strings to the build number. So the build might look like 3.4.5.1 which would be of the format version.major.minor.patch. When picking set codever button, it assigns (or replaces) the current MsCodeVer with the new string. so basically, I have a global var MsCodeVer that is used in every proce...
I'm trying to change my sync code to asynchronous. It's my first time doing it like this, so I don't know if this is the right way. ASYNC_CONTAINER = [] def async_kafka_listener(*topics, **configs): from concurrent.futures import ThreadPoolExecutor pool = ThreadPoolExecutor() def get_message(fn: Callab...
#include <iostream> #include <string> using namespace std; string reversal(string a) { int i = a.length(); string reversed_string{}; for (; i >= 0; --i) reversed_string += a[i]; return reversed_string; } bool palindrome(string a) { if (a == reversal(...
I am trying to implement a getcwd(3) (or env::current_dir() in Rust std). In the implementation, I use a Composer (an iterator) to yield (call next() on Composer) each path entry: CWD = /home/steve, returns Ok(Some("steve")) CWD = /home, returns Some(Ok("home")) CWD = /, returns None Src Playground Link use std::{ ...
I'm writing a data structure to solve a problem related to servicing hardware interrupts. I have to translate a 64-bit pointer to a 16-bit handle and back again. Unfortunately the hardware completions aren't guaranteed to be in order, and some conventional solutions like lock-free stacks cause a lot of contention as th...
I have the following code: class HiringRequirements: def employee_eligible(self, employee, role): if employee.grades_percent_average >= self.minimum_hiring_grades_percent: if not self.role_occupied(role): return True else: print("Somebody is occupying ...
I was given a test assignment for the interview of the company and below is the code that I shared with them. I developed it using .NET 6 (Core) Console application. Actual problem statement: Coding Exercise Description For the purposes of this exercise, it’s expected to implement a console application driven from a m...
I came up with a suitable solution to a HackerRank problem that failed because the execution took longer than 10 seconds on lists that were of very large size. The problem: Given a list arr and an integer d, find all combinations of length 3 whose sum is divisible by d My solution: [ sum(p) % d for p in combina...
I have found that a bottleneck of the OpenCV application I use is the bilinear interpolation, so I have tried to optimize it. The bilinear interpolation is in 8D space, so each "color" is an 8 dimensional vector in [0,255]. I have also written a small benchmarking program. My code is between 0% and 50% faster than the ...
Introduction I implemented a class to store a matrix with entries at positions (i,j) that are strings. The matrices I would like to efficiently store in this class have strings as entries and it occurs very often that entries are the same. I am at the moment not interested in reading out the matrix, but to store the ov...
Usually my project directory structure look like: project_name/ lib/ utils.py logs/ main.py requirements.txt config.json My config.json file looks like: { "api": { "api_key": "abcdefg", "api_secret": "hijklmn" }, "trading": { "invest_amount": 50, "mode": "futures", ...
It is a Windows command line utility for counting lines of code in a source code directory. It will count loc and sloc. I read from a file character by character using fgetc in the CountLines(...) function. I set a buffer size of 4096 bytes. Observed speed is not much different from the default case. How can I improve ...
The following method was meant to build a message depending on the type of signature of an invoice. It contains some if-else statements and code duplication. The original method : private String createSignatureMessage(InvoiceDTO invoiceDetails, int signatureType, Amount paid, Amount remaining) { List<Object> params...
What the code does What the JQuery code does is add / remove classes on div's elsewhere on the page, depending on the button clicked. Button 1 clicked → add class showModule to divs with class Module1 (remove showModule class from all other divs) Button 2 clicked → add class showModule to divs with class Module2 (remov...
I have created a CLI python game that allows for the creation of local accounts and the data is stored in local .csv files. The passwords are hashed so can be stored securely. It keeps track of the players score and has a leaderboard. I created this in my freetime for my computer science gcse programming test. I have u...
The following code creates a WhatsApp button. How would you improve this code? document.body.insertAdjacentHTML('beforeend', ` <aside class="cbwtphone_wrapper"> <img class="cbwtphone_icon" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6b/WhatsApp.svg/1024px-WhatsApp.svg.png"></img> <...
I'd love some feedback on the C++ base class shown below. It's basically a toy problem for a fake video game where the monsters that you have to avoid will all be sub-classed from the class shown below. I'm particularly interested in feedback on the way I handled the character_count counter, which is meant to count the...
I've created a function to split a period into the biggest different time unit possible. It can be years, months, weeks or days. However, it ended up being quite big and I feel it can be greatly improved, but I'm having difficulties finding ways to do it. import calendar from datetime import datetime, timedelta def c...
Description of the code: The code provides asynchronous IPC functionality in C++ using the Boost libraries and pipes. Each process asynchronously "listens" on the read end of the pipe and the messages are added to a queue, which means you won't have to call read() manually: you just have to send messages and they're au...
I have a multi-page form to submit and update an application for an event built using ASP.NET Core MVC. Each page of the form consists of the display information managed by the organizer (1) and the information entered by the user (2) (e.g. a list of locations of venues (1) the the choice of venues (2)). I want it to u...
I have been developing a C++ driver for the incremental rotary encoder (irc) based speed sensor. It is a part of my embedded software project. The driver is basically decomposed into two layers: The first layer consists of the driver for the fpga peripheral for processing the signals generated by the irc sensor. This ...
I'm wondering how I could optimize this method that takes in a list of UserPrincipal objects, filters them by Regex and inserts the new class instance into a list. It takes 4 to 5 seconds for an input list of 2000 entries, which seems too slow for that amount of entries. private static Dictionary<string, User> ProcessU...
I'm making a game with Pygame in which the user can place machines that would output resources called producers and you can use those resources to craft items with crafters which you would then move the items to a seller with conveyors that's basically the main game. Since I would have a lot of sprites I can't do this ...
(See also the next iteration.) I have this small simulation program simulating a toilet seat. The toilet seat may be in two positions: up or down. If a male arrives to the toilet to urinate, and notices that it is down, he must put it upwards. What we are measuring, are two strategies: Each visitor leaves the seat in ...
The program is simulate a situation where my goal is to lose money in Corresponding exchange, however I will win max_lose times with min_amount_per_lot amount in Corresponding exchange and lose the same amount in Bybit, using martingale strategy in Bybit will lead to magnify the capital needed in Bybit each time losing...
I want to create a function that checks if an email has a username that is 5 to 20 characters long, starts with an alphabet letter and ends with one domain names of (.org, .net, .org). It also corrects, if the user enters a capital letter. I am fully aware of that the code does not make sense as employing regular expre...
This script takes a CSV of numbers and processes them to check to see if the numbers conform to the UK standard 11 digit numbers. Any errors are outputted to a log and the correct numbers sent to an XML for processing by a server process. import csv import re import datetime import xml.etree.cElementTree as ET import ...
I wrote a small script to demonstrate two ways of looping in Python: with and without using the index. I want to know which way is better. Please see the example: #################################################################################################### # Imagine there is some registration info of some people...
I have a problem that needs path finding to solve. It is a vector of ints; 1 for passable terrain and 0 for non-passable. My implementation is not fast enough for the test. How could I make it faster? #include "findpath.h" #include <algorithm> struct node { std::pair<int, int> position; float length = 0; in...
(See the previous iteration.) This time, I removed the stuff I don't need in my demo runner. Also, I consolidated some code that seemed DRY to me. Simulation rules When a female arrives, she ensures that the seat is down before performing the urge. She leaves the seat down before exiting. When a male arrives to pee, h...
I have this pseudorandom number generator: package com.github.coderodde.util; public class Random { private static final long MASK = 0xba42_87df_9103_cd55L; private static final long LARGE_PRIME = 2396568697254547L; private static final int TURN_OFF_INT_SIGN_BIT = 0x7fff_ffff; private long counter; ...
I am working project where I need to build ASP.net control based on JSON data. I am using the method below GetMeetingPollingQuestion to create this model. Any suggestions/comments are greatly appreciated to improve the code further. Thanks. JSON [{"MeetingPollingQuestionId":1,"MeetingPollingQuestionType":"LongAnswerTex...
I have been using a TCP communications between Python and C# program. Python side (server) runs on a raspberry pi 4 and C# side (client) runs on my computer. RPi and PC connected over Wi-Fi. I have a class in python to listen selected port: class ListenPort: def __init__(self, port: int, event_handler=None, delay: ...
I am new to swing and GUIS in general. I am not sure how to structure projects with gui so help me fix mistakes I have done in this project Main: import java.io.IOException; public class Main { public static void main(String[] args) throws IOException { new Board(); } } import javax.swing.*; import java.awt.*;...
I read here that "Furthermore, for a zero of multiplicity 1, the convergence is at least quadratic (see rate of convergence) in a neighbourhood of the zero, which intuitively means that the number of correct digits roughly doubles in every step.". The code which I've written to find the square root using Newton-Raphson...
This is a continuation from a previous question; I updated the code with the suggestions and added an additional iteration. Templates are not an option because of the usage: The objects are stored as a class members where the sizes are not known at compile time Iterators are not used, not even for scan_kernel because ...
The following function is supposed to return the points p1 on line segment a, and p2 line segment b, such that |p1 - p2| is minimized. point_pair get_closest_points(line_segment const& a, line_segment const& b) { auto const intersect = intersection(extension(a), extension(b)); if(line_segment::valid(intersect.a...
This is a discord bot that i am working on having learned it from watching the youtube video by neuralnine. I wonder if there could be some optimization somewhere. import discord from neuralintents import GenericAssistant chatbot = GenericAssistant('intents.json') chatbot.train_model() chatbot.save_model() intents = ...
I have a function that has a few and/or operators in it. I'm sure there is a better way to write this but can't seem to figure it out. I thought I could use arrays but ran into an issue with having more than one search value I need to check for. My function: If the user (level 3) has clicked a button, user_meta is upda...
A memory arena implementation targeting standard C - this is draft code for Slider 3 (https://mrsename.blogspot.com/), a new programming language implementation being developed. Other memory arena implementations (as far as I know) are large, complex, slow, proprietary or non-portable. In the following code: An arena's...
I would like to expose a nullable referance of a "mesh" object, so I am returning a const pointer. However, I explicitly want to prevent anyone handling this from deleting the object. The following is my solution. Mesh class class IMesh { public: virtual ~IMesh() = 0; // pure abstract protected: IMesh() = ...
I am completely new to this coding thing and am completely lost. I've been asked "Create a method called ValidString that will return true/false if the string that is passed in is not null and not empty. You should use the IsNullOrEmpty or the IsNullOrWhiteSpace methods of the string class to check if the string is emp...
I am new to OpenGL learning it on amazing website learnopengl.com I wanted to a convenient way to use shader programs thats why I created this struct, please review it. ShaderProgram.h #ifndef HELLO_TRIANGLE_SHADERPROGRAM_H #define HELLO_TRIANGLE_SHADERPROGRAM_H #include <glad/glad.h> #include <GLFW/glfw3.h> #include ...
I made a program that converts JSON to a PHP array and checks every value of the multidimensional array with a loop and if a value matches certain values then it deletes that key and value and converts it back to JSON. I am trying to make this with less code. I use a nested foreach loop to check every element in the ar...
In the following I reimplement the Walker-Vose Alias method for sampling from nonuniform, discrete probability distributions. I am well aware that there is https://en.cppreference.com/w/cpp/numeric/random/discrete_distribution which I would use for production code. alias_lib.h contains the main logic. main.cpp contain...
I wrote a non recursive binary search implementation in C, for this time I think there are no bugs. Here's the code: size_t search_no_recursion(int *arr, int target, int start, int end) { size_t middle; while(start < end) { middle = (start + end) / 2; if(target == arr[m...
I'm trying to fetch the latest price from two exchanges and to do further actions based on the prices. exchanges.py: from abc import ABC, abstractmethod from bybit import usdt_perpetual import requests class Exchange(ABC): @abstractmethod def get_latest_price(self): pass class Bybit(Exchange): se...
I have 3 classes to create a simple checkers move validator. The entry point is checkers.py and is mostly complete with a few things hard-coded. For example, the auto-generated board (if none is given) starts with the upper left square as white, whereas if we are given a board, we are assuming the upper left square is ...