instruction
stringlengths
71
95.1k
In my experience i had the need that some application (both desktop and web) can excange data to authenticate users (even if the data for authenticating users are not reacheable form desktop application). The simple solution i came up to, was to generate some kind of encrypted information to distribute to users, and th...
I created a binary tree that stores information about brackets in a single elimination tournament, the code works as expected, however I think the implementation could be better. I'm using PostOrder Traversing method to go over the tree and store the information about the teams participating in matchups with help of a...
My code for a Binary Expression Tree that takes postfix input from the user and recursively builds and evaluates the expression. Proper input can be assumed. class Node { constructor(data) { this.data = data, this.left = null, this.right = null } } class BinaryExpressionTree { cons...
There is an updated version of this code with some of the recommended changes made here. I have created an implementation of a multi-dimensional array which utilizes a single continuous memory buffer to improve cache locality. My intention is for this to behave in a similar way to a multi-dimensional vector in c++, and...
This is supposed to randomly pick out the pieces for a Tetris clone. When a piece doesn't get drawn, its probability of getting drawn increases. I want to know if there is a way to do any part of this (or the whole idea) more efficiently. I'm also curious how you would judge the readability. Thank you. This is the clas...
I'm trying to output the average of a list of fractions formatted as eighths and given as a total. For my purposes, eighths must remain as eighths and never be reduced. I've managed to write some horrid code that achieves this in the ugliest possible way. Can someone help improve this? A major improvement would assign ...
I was solving Group Anagram problem in leetcode. Link for the problem https://leetcode.com/problems/group-anagrams/ Below is the code which I wrote class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& inp) { if(inp.size() == 0) return vector<vector<string> > {{}}; int c...
This is a game I'm programming where you need to guess the secret safe code. I'm new to this so sorry for the poor code. I can't figure how to manage all the instances that could appear. import random import time from colored import fg pattern = ['1', '2', '3', '4'] greenText = fg('green') redText = fg('red') whit...
In my current project I try to implement the basic game logic of the game "Vampire Survival" (Little impression of the first level can be seen in this video on Youtube). Question I want to know if regarding to the concepts of OOP I should restructure my code from the beginning or continue building on it like I started....
I have this code, which isn't for the moment optimized: def capture_inputs(cleaner): return cleaner(input("What are valid programming paradigms?").split(",")) def clean_input(user_input): result = [] for paradigm in user_input: result.append(paradigm.strip()) return result def count_valid_prog...
So this is a follow up questions to Find proceses listening on the network outside of default package manager I managed to make it a little faster thanks to using /proc and hopefully managed to implement most of the suggestions. Some minor questions Can we get rid of the pipes in favor of here strings? I attempted but...
This is the next development for the Sieve of Eratosthenes algorithm, where all the multiples of 2,3 and 5 are eliminated, which will not take any memory or time. As my last question Improved Sieve of Eratosthenes I will follow your instructions and study it deeply as soon as I finish my exams. I wanted to know if ther...
I have written the following generic function template: #include <iostream> #include <array> #include <span> #include <iterator> #include <concepts> #include <compare> #include <cstddef> template <typename T> requires ( std::totally_ordered<T> && std::three_way_comparable<T> ) [[ nodiscard ]] constexpr std::ptrdiff_t...
I built a small wrapper script around pytesseract, that lets you check if an image contains some text, or pattern look for images, that contain some text, or pattern High Level Approach I get the image text with pytesseract.image_to_string(img), and then compare against the user supplied regex with pattern.search(tex...
I need help to make matrix multiplication in C run as fast as possible. On my AMD Phenom(tm) II X6 1090T, my program multiplies two square singe precision 4096x4096 matrices in about 6.9 seconds. NumPy, which is based on OpenBLAS, multiplies the same sized matrices in about 1.5 seconds. So I think it should be possible...
I am building TODO app using MVVM pattern. I have a recycler view that holds all the daily tasks. My goal was to update the task to be "complete task" and change the row layout when it's completed. I managed to do that successfully, however, I am wondering about the way I did that. My implementation: Every time the tas...
I'm fairly new to Java, and I've been working on the following program. It's a basic CRUD app utilizing JavaFX and MVC design pattern. I'm seeking advice because the class I took on Java only covered the fundamentals of syntax. So I need to improve when it comes to proper design and standards. Even though my program wo...
Attempting to write a simple Kanban board in ReactJS. Omiting the css code, mostly wanted some advise on best practices in the ReactJS code itself. export default function App() { const [todo, setTodo] = React.useState(["finish xyz", "finish abc"]); const [inprogress, setInprogress] = React.useState(["hello world"]...
Here I created a simple controller that returns a PDF label that's generated in my domain model. What bothers me is that I make mutations on my model in controller. Is that bad practice? Of course any other suggestions about the code are also more than welcome. class Binary(http.Controller): @http.route('/web/bina...
I have been learning C with K&R Book 2nd Ed. So far I have completed quite a few exercises. For the following exercise (Chapter 3, Ex-3.3): Exercise 3-3. Write a function expand(s1, s2) that expands shorthand notations like a-z in the string s1 into the equivalent complete list abc...xyz in s2. Allow for letters of ei...
For learning purposes, I built a timer that does something every x seconds in Unity using an async Task instead of a coroutine. I'd like to know if there is a less awkward way of writing this: What bothers me the most is that I need to check the task every frame in order to be able to cancel it at any moment, instead o...
Today, I've got a small FlowLogger for you to review. The idea is not to log pure messages, but focus on the flow of the app that might contain such items as: state - json-snapshot of variables etc event - something worth logging has occured started - the flow has started altered - the flow has been altered by some co...
I am doing a beginner c++ project, where you can add books, display books. I'm planning on adding other functionalities like searching the database and checking if a book is available for purchase. I was wondering if the code is actually following best practices. #include <string> #include <iostream> #include <vector> ...
A couple days ago I posted my first implementation of my data structure here, which implements a cache-optimized tensor representation. I have worked the ideas from the responses into my implementation and I would like to see how I could further improve it. Code Explanation I will provide a rough explanation of the ope...
I'm reading through Algorithms Fourth Edition by Sedgewick and doing some of the practice exercises in C++11 instead of Java. Exercise 1.3.29 is to write a Queue that uses a circular linked list, keeping only one Node instance variable (last). All comments are welcome, but especially ones focusing on advanced C++ techn...
I need to get a selection of dates from the given to the current, breaking the range of dates into equal parts of 3 months. My code works, but it's clearly not perfect. Give advice on code refactoring. from datetime import datetime from dateutil.relativedelta import relativedelta start_date = "2021-03-30" def get_da...
I am fairly new to coding and was wondering of any tips to improve the code, sorry if it's a pain to read, thanks :) def answer_type(): print("Would you like to check for duplicate characters in a : word, numbers, sentence?") answer = input(">").upper() if answer == "WORD" or answer == "W": fin...
In the context of MVVM, is this an efficient way to communicate to the view that I should display some TextViews? Any advice on how I can improve it? ViewModel code: private var _shouldDisplayDischargeCurrent = MutableLiveData<Boolean>() val shouldDisplayDischargeCurrent: LiveData<Boolean> get() = _shouldDi...
Pascal's triangle is a simple and effective way to expand a set of brackets in the form (a + b)ⁿ. In my code the user is asked an input for what order (n) they want and it outputs Pascal's triangle. The Code I added in comments to help you understand my reasoning. def get_super(x): # function to get superscript char. ...
This wrapper incorporates the logging feature and provides a few convenience methods, including a scalar values fetcher, a generator for paged row sets, a wrapper retrieving a row set via a JSON container, and a set of transaction management methods. For now this is mostly an exercise for me for learning the Python sql...
Pretty straightforward question. The methods SubscribeToOrdersAsync and SubscribeToFillsAsync are pretty similar due to ConnectionLost and ConnectionRestored. What would be the best approach to follow the DRY principle? I created the SubscribeToAsync method which is my point of view but I would like to know yours. usin...
I want to save simple string data as a simple text file (.txt) on the server (together with the IP), but I cannot find any clear guideline on how to do this correctly/efficiently/safely. (Maybe I'm searching with the wrong keywords..) Here is a code I came up with, it works well for storing but I'm not sure whether it'...
I would like to find out which address format is input and convert it to the German format. Examples: 5, Rue de l'exemple is luxembourgish. 742 Evergreen Terrace is American. The German format is street space house number (no comma). My solution approach is that no matter which of the three formats is present, the ho...
I have certain error states that I am displaying in my Android TextView but only one message is displayed at a time and if all values are set to 0, no message is displayed. So, I check all the values with if-else and set the associated switch in the chargeCurrentMap. I then clear the error message if all values in the ...
I am very much a beginner (only if/else, for, while, slice etc) and I wrote Hangman game. I needed to put in there code saying "let’s transform the player's guess to lowercase one every time he inputs an uppercase letter". What do you think of my code? var words = ["fish", "monkey", "pioni", "agreable"]; var randomWo...
I currently have 2 Maps intersectionDiffLeft, intersectionDiffRight with the structure of Map<Boolean, List<Map<String, Object>> Where if the boolean is true it means it is considered a matching record. If it is true there will be 1 true record from left side and one true record on right side. There can be zero to many...
I have made a simple round robin scheduler that switches between threads in ptable array. Currently it's only for 1 CPU, so there are no locks at the moment. But each CPU has its own curproc variable with the help of the GS register. More details in the comments. proc.c #include <stdint.h> #include "franklin/switch.h" ...
Here is an implementation of compression with Huffman coding. It works well by my testing. It compresses a 1 GB string in about 30 seconds, and decompresses in about 15 seconds with VisualStudio 2022 "Release Mode x64" on my machine. I've used std::vector<bool> as the "bitset", but simply replacing that type with boost...
For a project I'm working on we need a basic time holder class. This is written in CircuitPython, which is a stripped down version of CPython that's missing a number of libraries, including the whole datetime library. The class definition is as follows. Note that TimeDelta is very similar, it also holds a second and ...
In house we have been building our own MVC framework. One of the things that was important in the project was to not have to add routes manually but instead have a standard and let the index automatically handle routing based on that standard. We want to access the URL /home/login /home is the controller /login is the...
I'm practicing loops in Python and started trying to have a better approach with user inputs, is there better ways of dealing with inputs when coding? And I tried using deques too, it worked very well, but don't know if I should or need to; are deques better in this case or should I keep using lists? sum_numbers: list ...
"SET", not to be confused with the data-structure is a card game in which player try to find a combination of 3 cards. Each cards have 4 attributes: color, number, shape, and filling-pattern. A legal set must either have to contain all variant of a attribute (all color) or just one variant(say red). Therefore, any set...
Here's my code to evaluate a boolean expression: #include <iostream> size_t find_in_string(std::string s, size_t begin, size_t end, std::string target) { for (auto i = begin; i <= end; i++) { bool isAtI = true; for (size_t j = 0; j < target.length(); j++) { if (i + j > s.length())...
I have parse function which is parsing tree of categories. I've written it in simplest way possible and now struggling with refactoring it. Every nested loop is doing the same stuff but appending object to object childs initialized at the top. I think it's possible to refactor it with recursion but I'm struggling with ...
I tried to explain in detail everything there should be of concern regarding this particular implementation, and non-code body turned out quite long, scroll down if you just want to read the implementation. I needed memory storage for a bounded thread-safe queue, so I wrote a ring buffer. It's not really relevant here,...
For the following exercise (Chapter 4, Ex-4.6) of the Book (K&R 2nd Edition): Exercise 4-6. Add commands for handling variables. (It's easy to provide twenty-six variables with single-letter names.) Add a variable for the most recently printed value. I have written this solution. I'd like to know how to "improve" or ...
Objective I'd like to confirm if there is a more efficient approach for the working script below, which splits column data in my tsv files. I suspect this can be achieved with awk or maybe sed but my experience is limited, and I've been unable to use the correct words in my search, to find where someone has achieved a ...
I have created a code that displays a table with exchange rate data. Have I used loops and conditions (if else) in a good way? @model IEnumerable<CurrencyResponse> @{ ViewData["Title"] = "Index"; } @foreach (var obj in Model) { <div> <h5>Table: @obj.Table</h5> <h5>Table number: @obj.No</h5> ...
I solved this problem: the Edabit Hangman Game challenge. Create a function that, given a phrase and a number of letters guessed, returns a string with hyphens - for every letter of the phrase not guessed, and each letter guessed in place. Notes The letters are always given in lowercase, but they should be returned i...
I have written a Flappy Bird using SFML and C++, kindly review my code. I'm hoping for objective criticism. main.cpp #include "Game.h" int main() { Game game1; return 0; } Game.h #pragma once #include <SFML/Graphics.hpp> #include "Definitions.h" #include "ResourceHolder.h" #include "StateMachine.h" struct Gam...
I created a method to print a playing field in the console, but I think there are much better ways to do this than mine. public void DrawPlayingField() { for (int i = 5; i < 120; i++) { Console.SetCursorPosition(i, 1); Console.WriteLine('I'); } for (i...
I came up with the following function to obtain epoch seconds that correspond to previous midnight in a local time zone: #include <iostream> #include <chrono> #include <date/date.h> #include <date/tz.h> long local_midnight_epoch() { using namespace date; using namespace std::chrono; auto t = std::chrono::s...
I have been writting a lot of code that looks like this class LoginViewModel : ViewModel() { // A fragment observes this and shows/hides a progressbar val loader = MutableLiveData<Boolean>() fun fetchSomeData() = viewModelScope.launch { loader.postValue(true) // ... loader...
Bash script to count word occurrences in file.txt How can this script be made more proper or more elegant? Example output: Ok source folder & file /home/x/Music/file.txt = source file Ok /tmp/ folder & file /tmp/file1.txt = using RAM scratchpad, because speed & less drive wear Example output: 15374...
I need to write a function with the following requirements (Programming TypeScript book by B. Cherny, Chapter 4, exercise 5): Implement a small typesafe assertion library, is. Start by sketching out your types. When you’re done, you should be able to use it like this: // Compare a string and a string is('string', 'oth...
I am trying to execute a Bash command, get the pid, read the (error) output and optionally pass input. I am still quite new at C++ and I would like to know if this is a correct & safe implementation for use in real-world applications? The target operating systems are MacOS 12.5 & Ubuntu (server) 20.04. The target C++ v...
I'm working with ACF in WP which provides a get_field() function. The function can return an array of values, null or false. When the result of the function doesn't contain an array of values I want to default to an empty array. This is how I do it at the moment but would like to know if there's a neater way to accompl...
Is it a bad thing to use asserts to validate user inputs? Or should I keep using an if statement in case the number isnt positive? Code with assert statement: def get_posit_n() -> int: from locale import atoi while True: try: number = atoi(input('Enter a positive integer:\n-> ').strip()) ...
This is the first big thing I have tried in c++. I would like to know any improvements that I can make on it. It uses 4 custom header files, 3 of which are general tools. Also I am on linux and I have no idea how to check how this would work on windows. I know some colors might look different or it might not look as ex...
This is from my second homework assignment in my Data Structures class (in which we use Java), we were simply given the task of filling out the functions shown below (they were empty before) and I was wondering if there are any improvements that could be made to this. I've already submitted it, I just feel like I overc...
ERROR: type should be string, got "https://youtu.be/XEt09iK8IXs?t=1264\nBen Awad did a mock interview with a React developer, and asked this question. There are a set of 100 holes (0-99). A rabbit is located in one of these holes. Every time you check a hole, the rabbit jumps to an adjacent (to its position) hole. The goal is to come up with an algorithm to find the rabbit.\nRather than focus on the algorithm, I wanted to try to create a working model of this scenario (I think I did implement the correct search, though). I created a Rabbit class that will keep track of where it is and determine how it should move. To properly test the search algorithm, I needed more than just random movement. It's possible the rabbit could just move back and forth between the same two holes forever, and randomly choosing left or right will practically never produce that behavior. To that end, I gave it 4 movement styles that it will choose at random and do constantly for the duration of the run:\nRandom - Randomly choose left or right\nRange - Same as random, but it will stay within a given range\nUp - The rabbit will always move right (unless it's at the furthest-right hole)\nDown - Opposite of Up\nThat certainly doesn't cover every possible movement behavior the rabbit could exhibit, but I figured it was variable enough for a simple test simulation. Actually, I'm pretty sure the search works regardless of how the rabbit moves, but it was worth creating the functionality for learning purposes; I'm still a beginner. For range movement, I picked a range that is 20% (unless it's too close to the 1st or last hole) the size of the \"space\" (the number of holes).\nimport random\nimport logging\n\nLOG_FORMAT = '%(levelname)s %(asctime)s - %(message)s'\nDATE_FORMAT = '%Y-%m-%d %H:%M:%S'\nlogging.basicConfig(filename='log.log', filemode='w', level=logging.INFO, format=LOG_FORMAT, datefmt=DATE_FORMAT)\n\n\nclass Rabbit:\n \"\"\"\n A class to represent a rabbit\n\n ...\n\n Attributes\n ----------\n space : int\n The number of holes to which the rabbit can travel\n start : int\n the start position of the rabbit\n pos : int\n The current position of the rabbit\n style : int\n A number representing one of the 4 possible movement behaviors of the rabbit {1: 'random', 2: 'range',\n 3: 'up', 4: 'down'}\n max_pos : int\n The number of the furthest-right hole to which the rabbit can travel\n min_pos : int\n The number of the furthest-left hole to which the rabbit can travel\n range_set : bool\n Indicates whether a range has been set to restrict the rabbit's movement\n style_list : list\n A list of available movement methods\n\n Methods\n -------\n move_random()\n Increments or Decrements the rabbit's current position by 1, randomly\n move_range()\n Calculates 10% the size of the space attribute, updates max_pos to the current position\n plus the 10% figure, updates min_pos to the current position minus the 10% figure,\n and then Increments or Decrements the rabbit's current position by 1, randomly\n move_up()\n Increments the rabbit's current position by 1\n move_down()\n Decrements the rabbit's current position by 1\n move()\n Calls the appropriate movement method based on style and style_list\n \"\"\"\n def __init__(self, space: int):\n self.space = space\n self.start = random.choice([i for i in range(space)])\n self.pos = self.start\n self.style = random.choice([0, 1, 2, 3])\n self.max_pos = space - 1\n self.min_pos = 0\n self.range_set = False\n self.style_list = [self.move_random, self.move_range, self.move_up, self.move_down]\n\n def move_random(self):\n \"\"\"Increments or Decrements the rabbit's current position by 1, randomly\"\"\"\n self.pos += random.choice([1, -1])\n\n def move_range(self):\n \"\"\"Calculates 10% the size of the space attribute, updates max_pos to the current position\n plus the 10% figure, updates min_pos to the current position minus the 10% figure,\n and then Increments or Decrements the rabbit's current position by 1, randomly\"\"\"\n if not self.range_set:\n self.max_pos = self.pos + min(int(self.space * .1), self.max_pos - self.pos)\n self.min_pos = self.pos - min(int(self.space * .1), self.pos)\n self.range_set = True\n self.move_random()\n\n def move_up(self):\n \"\"\"Increments the rabbit's current position by 1\"\"\"\n self.pos += 1\n\n def move_down(self):\n \"\"\"Decrements the rabbit's current position by 1\"\"\"\n self.pos -= 1\n\n def move(self):\n \"\"\"Increments or decrements the rabbit's position if it is at the first or last\n hole, respectively. Otherwise, it calls the appropriate movement method based on the current\n style, using style_list\"\"\"\n if self.pos == self.max_pos:\n self.move_down()\n return\n\n if self.pos == self.min_pos:\n self.move_up()\n return\n\n self.style_list[self.style]()\n\n\ndef main(space_size: int):\n \"\"\"Compares the rabbit's current position to the current position being checked. If they are not equal,\n the rabbit's position is updated based on its current movement style\"\"\"\n r = Rabbit(space_size)\n found = False\n step = 0\n check_pos = 0\n check_inc = 1\n while not found:\n found = check_pos == r.pos\n if found:\n break\n check_pos += check_inc\n r.move()\n step += 1\n if check_pos == space_size - 1 or check_pos == 0:\n check_inc *= -1\n check_pos += check_inc\n\n logging.info(f\"\"\"\\n\nRange: {r.min_pos} : {r.max_pos}\nRabbit start on : {r.start}\nRabbit found on step: {step}\nStyle: {r.style_list[r.style].__name__}\nRabbit found: {found}\n\"\"\")\n\n return found\n\n\nmain(100)\n\n\n"
UPDATE: Thanks everyone for the suggestions! I made a follow up version here which fixes the bugs, incorporates the feedback, and has more tests. A ReversibleList behaves like a normal list when ReversibleList.reversed == False, but it behaves as if it had been reversed when ReversibleList.reversed == True. The trick ...
I have created a class Complex which represents a complex number of any arbitrary arithmetic type. Overloads are given for the 4 common functions, addition, subtraction, multiplication, and division. The overloads take two different template arguments so as to allow operating on complex numbers of different types toget...
I've got some tools that run perdiodically like weekly or monthly that don't support any retry mechanism. In order to increase their chance to succeed in case a database wasn't reachable or some other problem occured, I simply schedule them to run several times per day or a couple of days in month. Currently they do th...
I'm fairly new to JS and have been learning react this week. Struggling to properly understand the useEffect and useState but think I'm getting there. I do however think that my use of useRef isn't the right way of doing things and am looking for an experts view on what I have written. The goal is to write an animated ...
The dataset I'm working with is rather large so I've been experimenting with cudf and cupy. Here you can find instructions for installing cudf and cupy. You will need a capable GPU and the nvidia drivers. Below I have provided a small portion of the data and an example of how to mimic the gpu_session function. Their...
I've been using Python for about two months now and I know that there is a lot of improvement to be made. This script runs a command against a device within our SolarWinds Orion environment. The script works fine, I'd love to know how I could make improvements on the code quality and methods that are used. I appreciate...
Sometimes, you want to an type of a particular index in an std::variant, and do something with that type without having an actual object. An example use-case would be de-serialization. What do you think of the following approach? /** * @brief Used as placeholder to allow tag dispatching */ template<cl...
I wrote a small console app for converting RGB or Hex values (by specfying on top of the input file) to the nearest colour of DMC thread. I'm curious to know how I could improve my code organisation or if there are any best practices I could be following better. I know I have no tests and I'm uncertain of the best way ...
I'm new at Laravel and I got an assessment task from company where they want me to create a mini-blog with Users and Posts. I was using following methods: index, create, show, store, edit and destroy in PostController. When I finished I sent it to them but they told me: We still want you have a look at some parts of yo...
Basically, I am creating a random math generator. the first line has a random number from 1 to 99 also, the second line has a random number from 1 to 99 and we also generate a random operator (*, +, -), and the last line bold is the result of the calculation. on click, we call a function that generates a div with all ...
I was attempting to solve LeetCode 139 - Word Break Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. Example 1: Input: s =...
I've been trying to solve this Codewars problem https://www.codewars.com/kata/56e56756404bb1c950000992 In this kata you need to create a function that takes a 2D array/list of non-negative integer pairs and returns the sum of all the "saving" that you can have getting the LCM of each couple of number compared to their...
Motivation: I am working with sequences of n-bit values coming from an ADC. I was initially using a std::vector<unsigned short> to store these values (12 bit in my case) but I wanted to improve on memory efficiency since this approach uses 16 bit per value instead of the 12 bit of information. My main concern is disk u...
I have written the following code for diving a list 'seq' into 'k' segments such that the maximum sum of each segment is minimized. I have used dynamic programming to solve this problem. But my class "Segmentation" seems a little overwhelmed with too many redundant functions. Can anybody give me a few suggestions on ho...
This is version 2. As time allotted some improvements from version 1 suggestions. Question 1 In this script for Kubuntu 22.04.1, how to set the Terminal scroll-back from 1000 Lines to 999000 Lines? Question 2 What feature would you like to see added to this script? added to script count_words.sh to analyze words Script...
My SQLite database: CREATE TABLE Movimentacao ( mydate DATE , dividend_type VARCHAR(200) , dividends DECIMAL(19, 2) , ticker VARCHAR(300) ); Inserting some data: INSERT INTO Movimentacao VALUES ('2021-09-01', 'Dividend', 140, 'BBAS3 - BANCO DO BRASIL') , ('2021-09-14', 'Dividend', 14, 'PETR4 - PETROBRAS SA') , ('...
Below is a solution I came up with (in C++) for an algorithm that is supposed to find the first character in a string that only appears once in the input string (the input string is guaranteed to be made up of only lower case characters from English alphabet). The catch is that the algorithm must return the index of th...
public: vector<int> twoSum(vector<int>& nums, int target) { int size = nums.size(); vector<int> toRet; unordered_map<int,pair<int,int>> myMap; for(int i = 0; i < size; ++i){ myMap.emplace(nums[i],make_pair(nums[i],i)); } for(int i = 0; i < size; ++i){ ...
I want to define a function which compute the difference of two lists as multi-sets. For example, [1,2,2,3]-[1,2,3,4]=[2]. I defined the following in python. def SetDifferenceListDifference(A,B): # A-B, can have duplicate elements r=[] r1=list(set(A)) for i in r1: t1=A.count(i)-B.count(i) #...
I have been trying to solve Trie related problems over at leet code and came across this interesting problem 211. Design Add and Search Words Data Structure Here is the question for convenience: 211. Design Add and Search Words Data Structure Design a data structure that supports adding new words and finding if a stri...
I've got this code: import random import itertools from operator import itemgetter #En spelarklass för ett enkelt tärningsspel med spelare class Player: def __init__(self, name, score=0, wins=0, lastroll=0): # Attribut: Name, Score, Wins, Lastroll. Score, Wins och Lastroll ska alltid börja på 0 self.name = ...
I'm using Frida to run a script on a process, and I want to wait for it to send the result back to me, as a callback. My current code looks like this: def check(target): global msg script_to_run = ''' (omitted for brevity) ''' # callback to handle the output of the script def on_message(me...
This is an interview take-home challenge that has been translated to avoid compromising the company's question. Problem statement You are a goat that needs to race up a hill. Designated waypoint rocks on the hill must each be visited in sequence or skipped and a score penalty incurred. For the goat to get its balance, ...
I have a plain text file which contains lines with fields below: <str_addr_a> <hex_int_addr> <str_addr_a> <hex_int_addr> <dec_int_addr> <str_addr_a> <str_addr_b> <str_addr_a> <str_addr_b> <hex_int_addr> <str_addr_a> <str_addr_b> <hex_int_addr> <dec_int_addr> For example, the content of the file could be following: # <...
I'm working my way through the Foundations course on The Odin Project and just finished the Etch-a-Sketch assignment. The program receives a number from 1 - 100 from the user through a prompt and then creates a grid from the square of the number. Then, on mouse over, one square of the grid will be assigned a random num...
I'm new to rust and I'm trying to build a card game simulation to find all of the best actions with all possible hands. This requires a lot of simulations and my first 3 million are already taking a huge amount of time. I want to show you 2 variants of my code: first, the one with no threading which takes about 35 minu...
I have 2 Data Models let's call them Lecture/Teacher that have a one-to-many relationship, in a service method I need to get a teacherId given a certain condition and add it to the Lecture model instance. Below is the definition of the different Models. namespace Example.Core.Data; public class Lecture { public in...
ERROR: type should be string, got "https://github.com/speedrun-program/small_array/blob/main/small_array.py\nAs a personal project, I wanted to try to make Snake Game in pygame where the grid can be arbitrarily large. I made these classes so I could make larger grids before running out of memory.\nclass nbitndarray:\n \"a class which lets you use a byte array as if it was an arbitrarily deeply nested \"\n \"array with each index being any number of bits wide\"\n \n def __init__(self, dimensions, bits_per_index):\n self.bits_per_index = bits_per_index\n self.dimensions = tuple(dimensions)\n \n if any(d <= 0 for d in dimensions):\n raise ValueError(\"all dimensions must be greater than 0\")\n elif bits_per_index <= 0:\n raise ValueError(\"bits_per_index must be greater than 0\")\n elif not dimensions:\n raise ValueError(\"no dimensions given\")\n \n total_bits = bits_per_index\n for d in dimensions:\n total_bits *= d\n \n total_bytes = (total_bits // 8) + (total_bits % 8 != 0)\n self._array = bytearray(total_bytes)\n \n \n def _index_generator(self, position):\n for depth, (pos, dimension_length) in enumerate(zip(position, self.dimensions)):\n actual_position = pos if pos >= 0 else dimension_length + pos\n if not 0 <= actual_position < dimension_length:\n raise IndexError(f\"attempted to access index {pos} of dimension {depth}, which is length {dimension_length}\")\n \n yield actual_position\n \n \n def _get_actual_position(self, position): # returns (start_byte, start_bit)\n if (len(position) != len(self.dimensions)):\n raise ValueError(\n f\"position argument had {len(position)} dimensions, \"\n f\"but self.dimensions has {len(self.dimensions)} dimensions\"\n )\n \n index_generator = self._index_generator(position)\n which_bit = next(index_generator)\n for i, pos in enumerate(index_generator, 1):\n which_bit = (which_bit * self.dimensions[i]) + pos\n which_bit *= self.bits_per_index\n \n return divmod(which_bit, 8)\n \n \n def zero_bytes(self):\n self._array.__init__(len(self._array))\n \n \n def get(self, position):\n which_byte, byte_start_position = self._get_actual_position(position)\n bits_left_to_read = self.bits_per_index\n current_bit_position = min(8 - byte_start_position, bits_left_to_read)\n \n # reading first byte\n value = (self._array[which_byte] >> byte_start_position) & ((1 << current_bit_position) - 1)\n bits_left_to_read -= current_bit_position\n which_byte += 1\n \n # reading middle byte(s)\n while bits_left_to_read >= 8:\n value += self._array[which_byte] << current_bit_position\n bits_left_to_read -= 8\n current_bit_position += 8\n which_byte += 1\n \n #reading last byte\n if bits_left_to_read > 0:\n value += (self._array[which_byte] & ((1 << bits_left_to_read) - 1)) << current_bit_position\n \n return value\n \n \n def set(self, position, new_value):\n if new_value > ((1 << self.bits_per_index) - 1) or new_value < 0:\n raise ValueError(f\"value must be in range(0, {((1 << self.bits_per_index) - 1)})\")\n \n which_byte, byte_start_position = self._get_actual_position(position)\n bits_left_to_set = self.bits_per_index\n \n # setting first byte\n bits_left_in_first_byte = min(8 - byte_start_position, bits_left_to_set)\n first_byte_start_bits = self._array[which_byte] & ((1 << byte_start_position) - 1)\n current_value_to_write = new_value & ((1 << bits_left_in_first_byte) - 1)\n self._array[which_byte] >>= byte_start_position + bits_left_in_first_byte\n self._array[which_byte] <<= bits_left_in_first_byte\n self._array[which_byte] += current_value_to_write\n self._array[which_byte] <<= byte_start_position\n self._array[which_byte] += first_byte_start_bits\n new_value >>= bits_left_in_first_byte\n bits_left_to_set -= bits_left_in_first_byte\n which_byte += 1\n \n # setting middle byte(s)\n while bits_left_to_set >= 8:\n current_value_to_write = new_value & 0b11111111\n self._array[which_byte] = new_value\n new_value >>= 8\n bits_left_to_set -= 8\n which_byte += 1\n \n # setting last bit\n if bits_left_to_set > 0:\n self._array[which_byte] >>= bits_left_to_set\n self._array[which_byte] <<= bits_left_to_set\n self._array[which_byte] += new_value\n\n\nclass nbitarray(nbitndarray):\n \"a class which lets you use a byte array as if it was an \"\n \"array with each index being any number of bits wide\"\n \n def __init__(self, bits_per_index, initial_length=0):\n if bits_per_index <= 0:\n raise ValueError(\"bits_per_index must be greater than 0\")\n elif initial_length < 0:\n raise ValueError(\"initial_length must be greater than or equal to 0\")\n \n self.bits_per_index = bits_per_index\n self.length = initial_length\n \n total_bits = bits_per_index * initial_length\n total_bytes = (total_bits // 8) + (total_bits % 8 != 0)\n self._array = bytearray(total_bytes)\n \n \n def _get_actual_position(self, idx):\n non_negative_idx = idx if idx >= 0 else self.length + idx\n \n if not 0 <= non_negative_idx < self.length:\n raise IndexError(f\"attempted to access index {idx} of nbitarray, which is length {self.length}\")\n \n return divmod(non_negative_idx * self.bits_per_index, 8)\n \n \n def append(self, new_value):\n # allocating more space if necessary\n total_bits = self.bits_per_index * (self.length + 1)\n total_bytes = (total_bits // 8) + (total_bits % 8 != 0)\n while len(self._array) < total_bytes:\n self._array.append(0)\n \n self.length += 1\n self.set(-1, new_value)\n\n"
I've been out of the C++ game for a few years and I'm trying to knock the rust off by implementing a programming language. This Source interface is used to read characters from a file, standard input, etc. Includes and outer namespace are omitted below. source.h: class Source { public: virtual ~Source() = default; ...
I have written a script where I have a mocked data of couple of words in a list. The point is that I as a user will be able to input a text e.g. hello there world! and with this function I have written it should check if I have anything that matches and if it does it should print out that it matches else not. import re...
I was in two minds as whether to post this question on stackoverflow or dba stackexchange but because I am asking for review, I thought of posting here. I am new to Python and looking for feedback on whether the below code will work for a high website traffic, especially from database perspective and suggestions to mak...
I have built a simple Nuxt 3 app and have some custom api endpoints. I am currently tracking the user query and response statuses to have some insight when something goes wrong and that the app is working as expected. Running steps User will call the endpoint api/search with query parameters Endpoint will set up the p...
Until recently, I decided to go back to Chapter 1 of the K&R Book, Edition 2, to try to "improve" the code I've already done. I have also made some changes since I was limited to just using what they taught in each section of Chapter 1. Especially the following exercise: Exercise 1-22. Write a program to "fold" long i...
This code is applied to a master workbook with tabs containing characteristic information e.g. "Reliability standards", "Targets" etc. about each utility. The utilities of interest are selected by the user in the "Dashboard" tab The excel sheet has a tab "Dashboard" that allows any of a maximum of 23 utilities to be se...
I'd love to get a review of my code, which I've already submitted as homework. I'd like some guidance as to how to write it more DRY-ly: I wrote the whole round, sqrt and exponentiation twice — how could I write it only once? Ideally I'd want to do it within the same function, it'd be a little ugly to write a function ...
My function is a solution to the Knight's Travails problem. It receives start and end point coordinates on a chess board, and must return the shortest path from start to end. class Node{ constructor(coordinates){ this.value=coordinates this.possibleMoves=[] } } class Tree{ constructor(star...
Problem statement: Write a program that converts all given temperatures from a given input temperature scale to a given output temperature scale. The temperature scales to be supported are Kelvin, Celsius, Fahrenheit, Rankine, Delisle, Newton, Rømer, Réaumur. Synopsis: tempconv INPUT_SCALE OUTPUT_SCALE [TEMPERATURE]......
I'd love to get feedback on how to write this in a more expressive way. It works, but style-wise it's not especially thrilling in my opinion. I'm inserting into three lists (all_results, all_titles and all_field_order). Seems kind of cumbersome, but I can't quite wrap my mind around how to write this piece cleaner. Con...
Problem statement: Write a program that converts all given temperatures from a given input temperature scale to a given output temperature scale. The temperature scales to be supported are Kelvin, Celsius, Fahrenheit, Rankine, Delisle, Newton, Rømer, Réaumur. Synopsis: tempconv INPUT_SCALE OUTPUT_SCALE [TEMPERATURE]......