instruction
stringlengths
71
95.1k
I have a Java program that does find and replace (like when you do it in a text editor for example notepad++) in files of a folder and all sub-folders. I created 4 functions: the first function has folder path in the parameters so it listed all the sub files if it's a folder then list all the sub files again: then in R...
I have a service that converts an Excel spreadsheet file into HTML. It is working just fine, but it is quite a big method that doesn't follow any SOLID principles. Therefore I would like to improve it to follow at least the Single Responsibility Principle. But I really don't know how to apply it and find the level of a...
The problem statement was pretty easy and I was able to run half of the test cases, but some of the test cases in the end gave me the error of memory limit reached. What can I do here to improve the memory efficiency of my code? Question: Find the min number of "usable" integers required to reach the N. The "usable int...
I have created a task that I need to query database for List of String and store it in neededDataList. I will use neededDataList in a scheduled task every 10 minutes to do a simple task. And I need to retrieve a fresh data of neededDataList every 1 hour. Will the scheduledExecutorService2 pick up the fresh neededDataLi...
I'm making a project that needs a simple cross-platform command-line parser. I made this. Hope you enjoy! #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #define __NUM_OF_ELEMENTS(ARR) (sizeof(ARR)/sizeof(ARR[0])) #define __HAS_ARG(FLAGS, ARG) (FLAGS & (1 << ARG)) void panic(const char...
I wrote a matrix class in C++ with an addition and multiplication method. It works fine, but I don't think a C++ programmer would enjoy reading this. I would love some help with that. #include <iostream> #include <string> class Matrix { public: int rows; int columns; int* contents; // Constructor ...
I haven't separated the stack code into its own header and source yet, this is just a proof of concept for now. Haven't chosen better function names yet because I ultimately want to integrate this code into a larger project where I need a way to store data into some kind of dynamic list. Settled for an stack API for no...
I am analyzing videos from the popular social media platform, TikTok, and extracting the songs into a Spotify playlist. Here is a gif of one of these videos: https://i.imgur.com/I0dVoac.mp4. Full video: https://vm.tiktok.com/ZMJwqpTPq Basically, after the video is downloaded, I get unique frames in 2 steps: Get frame...
I'm an amateur programmer making a career change into web development. I've found Advent of Code challenges are great way to sharpen my skills. I've cleaned up this solution for Day 10, 2020 as much as I know how. Here's a link to the description of the problem and my solution on GitHub. I've also summarized the proble...
I have the object with values. I trying to filter based on values. var data = { "map": { "0": ["abcd"], "1": ["efgh"], "2": ["xyz"], } } In above object I am trying to filter xyz which are have in array values. Expecting output: { '0': [ 'xyz' ] } I done the code but I am not sure it's efficient way....
Like most teams, we take turns to speak in our daily stand-ups. When we gather around the sprint board, it's easy to know who speaks when - we start at one end and pass the role along the line. At present, we're all working remotely, so there's no physical ordering that we would agree on. And we would get tired of u...
I made a skyscraper solver based on the kata on Codewars. To try to understand the problem you can try to solve a 4x4 Skyscraper here. There are also instructions available. Now on Codewars there are also more difficult katas were you have to solve 6x6 or even 7x7 Skyscraper puzzles. Why are they more difficult? You ru...
I'm preparing for junior developer interviews and am trying to come up with a more interesting/versatile solution to FizzBuzz than I've done in the past. Do you have any ideas of how I might DRY this up? Is it too difficult to read? const isMultiple = (num, mod) => { return num % mod == 0 } const fizzBuzz = (range...
I'm making a slide sidebar with vuejs and tailwind. It works but feels kind of sluggish. Is there a way to make it smoother ? working example: https://codepen.io/tuturu1014/pen/oNzRXeW <button @click="isOpen = !isOpen" class="bg-blue-200 p-5"> <span v-if="isOpen">Open</span> <span v-else>Close</span> </button> <div...
This is my take on the guess the number game. The user has three attempts to guess the number chosen at random. The number is between 0 and 9, including. It tells the user to guess higher or lower and reveals the number if the game is lost. Input that is not a number between 0 and 9, including, is not accepted and the ...
Hello everyone this is my first post here so please do critique my post if there's anything. I have made a program intended to pass a programming challenge on open.kattis.com, here. It should do as title says, but with the conditions that each traversal follows the rules of a "Knight" from chess, that being plus/minus ...
I have created my first npm package: https://github.com/sunnysideup/stretched-bg-image. The purpose of the package is to add a class to a div (or any other block element in the HTML) depending on the width / height ratio of the div (panorama / landscape / portrait / skyscraper) Below is the code. It works fine, but doe...
I'm using the minified version of SJCL to encrypt the backup files requested by the users. It is in a Google Apps Script add-on for Google Sheets. I'm mostly concerned with correct use, exception handling and best practices of adding the encryption part in the script. It is currently working as expected in backup and i...
I have a couple of general purpose LocalDateTime parser methods I wrote to handle Dates flowing between a number of legacy XML based processing pipelines over to a modern Spring Boot, Mongo applications. Because both the legacy and modern applications are set in stone, I'm stuck with a narrow conversion of legacy Stri...
Major Edit: I wish people threw in a comment regarding what they are expecting instead of downvoting this question. I am quite appreciative of constructive feedback. I know it is only 3 people out of 100 who have downvoted, but it still affects the poster's confidence and makes this forum unhelpful. I am trying to solv...
Not a professional coder, but my current hospital position is allowing me to code some workarounds for our abysmal EHR system. The following is part of my Python project to visualize laboratory data. The following code snippet works, but I haven't figured out a way with list comprehensions or np.where to streamline it ...
A parallel map written in Rust. I am new to Rust and wondering if there is things that could be done better or more efficiently. use crossbeam_channel::unbounded; use std::{thread, time}; fn parallel_map<T, U, F>(mut input_vec: Vec<T>, num_threads: usize, f: F) -> Vec<U> where F: FnOnce(T) -> U + Send + Copy + 'st...
I have over 17,000 pages that have been scanned (for a local history archive) which I have OCRed using Tesseract to individual TXT files. I want to be able to search/locate every page containing a search word of more than 3, lower case letters. So for each TXT file I need to: Delete all rubbish from the OCR text i.e. ...
I want to test a number of different functions I have written to solve the Fizzbuzz challenge and would like to know what is the best way to check the result? Each function returns a list of the answers and I want to check the list is correct. One of the functions is shown below def fizz_buzz_using_boolean(): f...
I have this Library to control errors; I would like if you can evaluate it and make a review of the code, not about the goals of the library: Everything works for me correctly, but I am also open to hear about any type of improvement that can be implemented in the code as long as it does not affect the objective of the...
I want to start by just mentioning I'm a semi-beginner at C# and cyber security so any feedback is appreciated :) What I think I need reviewing is the SQLite queries and maybe the hashing functions I'm making a password manager project (sorry in advance for wall of code): The supporting functions: (I probably don't nee...
This is a clone of the cat utility. The goal of this exercise was to get comfortable doing basic tasks in a new language, figure out how to set up testing, etc. So I'm really looking for feedback on writing more idiomatic Rust, if there are better ways to approach things, etc. In particular, my TextFixture class I use ...
I've just finally finished implementing std::vector. I'm currently re-implementing whatever I can in the hope to learn more of how data structures works. I tried to respect all requirements, but I probably missed a lot (or made mistakes). At first I thought implementing std::vector would be somewhat easy... but how wro...
I have a Connect Four game with a board that I made with a bunch of print functions, which is incredibly inefficient: print(" 0 1 2 3 4 5 6") print(" " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][ 4] + " | " + board[0][5] + " | " + b...
I’ve the following function which should be run in production I read some config If valid add the runner otherwise just return, the function is working! Is there a cleaner/better way to do it in go? error handling... https://play.golang.org/p/QcU9YHDXo36 func (z *zmp) Add(val string, runner Runner) { vmap := viper....
This is a matrix class with addition and multiplication. I tried incorporating all the helpful advice I got on my previous attempt C++ matrix class , specifically using std::vector for memory management, overloading operators, adding error messages and adhering to the rule of 5. #include <iostream> #include <vector> t...
Given a int optimumMemory and int[] array with list of available memories find the pair of indexes of memories whose sum of the values will be equal to the optimumMemory? If there exists more than one such pair whose sum of values are equal to the optimumMemory then filter out the indexes for the below conditions condi...
I'm writing a program that has the possibility of outputting a large amount of text on a single logical line to the console. In that scenario, I would like to wrap the text at word ends so that words are not split on the end of the line: i.e., the string lorem ipsum dolor sit amet should print: lorem ipsum dolor sit am...
I have an interface Animal with a class that implements it, Cat. public interface Animal { public int price(); public Breed.BreedType breedType(); } public class Cat implements Animal { private int price; private Breed.BreedType breedType; public Cat(int price) { this.price = price; }...
I have come across a problem on cyclic permutations. It is about swapping numbers around. It starts out with input N < 100,000 which makes the first N natural numbers as orders: 1 2 3 ... N-1 N Then we get the next input K < 200,000 as the period Next N input lines are the swaps: For example, the input is 5 4 1 3 1 2 2...
Due that fact that SwiftUI has poor ScrollView customization and doesn't support snap interval from the box I decided to implement my custom component to support such behaviour. Example I know, there are many hard coded values that should be replaced with dynamically calculated values. But for my debug purposes is en...
I'm sure there are several profilers written in C++ on here already, though with this one the goals are quite different. I attempted to make it as robust as possible, or 'fool-proof' if you will so that it is nearly impossible to crash via an unhandled exception or undefined behaviour. It supports redirection of stdin,...
I was trying to implement a faster, alternative implementation of std::function. I came up with the code below: template <typename R, typename ...Args> struct Function { template <typename Lambda> Function(Lambda f) { static auto function = f; func = + [] (Args... args) -> R { return function(ar...
I've been furthering my development and understanding in OOP (Object Oriented Programming) and would appreciate feedback on this new console program I've created. The main aspects I would like to know are have I made good use of OOP, can I improve upon techniques demonstrated in this program? Have I done anything bad? ...
I have developed what I believe to be a novel way of coding the Fibonacci series in Java using a for loop. This code appears to work, but I was wondering if this is a good solution and how it could be improved. static int loopFibonacci(int num) { if(num <1) { throw new IllegalArgumentException("thi...
I am trying to make a paragraph merger that takes multiple paragraphs and output a concatenated result with removing the duplicated overlapped lines due to redundancy. Each input paragraph is with the follows specifications. The leading/trailing spaces in each line have been removed. No empty line. The output merge...
My goal was to create a big invisible cube and inside that spawn small random cubes. These small cubes would have: A random position within the big cube. A random colour. A random size. A random lifetime. A higher chance to spawn with offset of 0 on y-axis than any other offset. Ability to rotate in sync with the big ...
I am developing a piece of code around a tree structure. The tree can do a few things - one of them being its ability to serialize & de-serialize its data. There are multiple different types of nodes, e.g. NodeA and NodeB, each represented by a class. Different types of nodes may have significantly different functional...
I am trying to make an algorithm that will find the index of a given substring (which I have labeled pattern) in a given String (which I have labeled text). This method can be compared to String.indexOf(String str). In addition to general feedback, I'm curious what the time complexity of my method is, and would appreci...
I decided to create a double pendulum simulation to trace out its path and explore chaos theory a bit. I'm looking for any feedback regarding my code. Are there any atrocious portions of my code or bad practices I did? import tkinter as tk import random from math import pi, sin, cos G = 9.81 class SimplePendulum(): ...
I have been writing a math library with more options than the standard builtin one, partially to make my life easier in the future, and partially just for practice. Here is what I have so far in the main file (master/xtrmth/xm.py): import typing as tp import decimal as dc _meganum = tp.Union[int, float, dc.Decimal, t...
I have to do some optimization on the function presented below. It makes some data like a payload based on the arguments passed into it. I am not much sure how to improve the code to look better & less. Please share some thoughts on this. //Process data and call track event for product added export function ProductAct...
this is a function given an array of numbers to find the one that appears an odd number of times. what I did is: Sort the array Check if the array is odd. If the array length is 1 then return this value. Assign every two values to a new array, and check if it is a number. Check if every two values are equals. If not e...
Is this a correct implementation of a generic Meyers Singleton in C++17? Any tips appreciated. Singleton.h #ifndef SINGLETON_H #define SINGLETON_H template<class T> class Singleton { public: static T& get() { static T obj; return obj; } protected: Singleton() = default; virtu...
I wrote a program about triangular numbers, which are derived from the sum of natural numbers one after the other. For example, the third triangular number is equal to: 1 + 2 + 3 = 6. I want to find divisors of triangular numbers. for example the third triangular number have 4 divisors which equal to : 1,2,3,6. Some tr...
So iam making a game using OOP in python however is this the best practise when defining your objects? are you meant to define them all at the end of the script like I've done, or are you meant to define them after each class you make? Thanks in advance and any other improvements would be much appreciated! import rando...
I want to make my own custom exception handling and I am curious if I am going the right path, maybe some of you could suggest to me how I could improve it? Or maybe I have went the wrong direction? (Also it would be amazing to know how I could make this piece of code more of a modern C++.) Here is a simple namespace w...
About I'm writing a header-only template library for helping with binary IO. It is inspired by pack-d, which is in turn inspired by Python's struct module. I've only finished the output part and posted it here for review. You can find the source (~300 lines of code) at the bottom of the post. It's basically like a prin...
This class is intended to fulfill these requirements: Output in Y-m-d H:i:s format Allow dates to be entered as m-d-Y or m-d-y Complain if an invalid birthdate is entered (i.e., in the future or otherwise) Allow simpler, friendlier coding without typing a lengthy DateTime instantiation <?php /** * CustomDateTime wit...
After reading one too many Lisp books, I decided to try extending R's syntax. My goal was to implement repeated matrix multiplication in a way such that I could write matrix%^%n to produce the result from multiplying matrix by itself n times (where n is a natural number). I produced the following working code that give...
I'm experimenting with C after working in high level languages for the last 15+ years, and trying to feel comfortable with C code bases again. One thing I needed for the code I'm writing was a resizable list collection that can grow as items are added to it. It seems to work under the basic case, so I'm wondering if I...
The following is my python code to find the number of iterations needed to generate random string iteratively to match the input string. Here I have repeated a similar kind of for loop in both the functions getRandomString() and getMatchString(). I tried to avoid it but couldn't. I want this to be combined together int...
This is a basic CLI email client in Python. It can send plain text emails and view inbox. settings.json contains a list of SMTP and IMAP servers used for different providers. This file can be edited. client.py import argparse import email import getpass import imaplib import json import os import re import smtplib impo...
I found a project that aims to implement a CLI calculator app in as many different languages and ways as possible. Having a little experience in PS, I tried my hand at it. The requirements are as follows: Use a set interface (that is correctly done here) Must use functions No builtins, unless it's to interact with the...
ERROR: type should be string, got "https://github.com/speedrun-program/load-extender\nThis is the previous post: C++ programs for Windows and Linux which let you lengthen the time it takes to access files REVISED VERSION\nTo compile this, you need to download and include robin_hood.h, and on Windows you also need to install EasyHook.\nI tried to add everything mentioned in the answer there except using an obj / o file because I read that you have to include something twice if it’s used in both files, so it seemed like it would make the size a lot bigger because the file for robin_hood map is big. I also would have had to put some of the functions in their own file because I want them to be compiled without printf calls unless it’s the testing program. And I also couldn’t figure out how to get it to work, the main file couldn’t see the things from the other file. But I’ll try again to get it to work if someone says it would still really be a good idea.\nI made this because it helps us save non-load time in a speedrun.\nI want this to be revised as well as possible because I don’t have Mac OS, so I need to ask someone else to compile it for that OS. So I want it to be written as well as I can get it so I won’t have to ask people to compile it multiple times due to revisions.\nclass_and_functions.h:\n#include <stdint.h>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <atomic>\n#include <vector>\n#include <exception>\n\nclass delay_sequence\n{\npublic:\n std::atomic<std::size_t> index;\n std::vector<std::chrono::milliseconds> delays;\n bool repeat;\n bool reset_all;\n\n delay_sequence() { index = 0; repeat = false; reset_all = false; }\n delay_sequence(const delay_sequence& copy_sequence)\n {\n index = copy_sequence.index.load();\n delays = copy_sequence.delays;\n repeat = copy_sequence.repeat;\n reset_all = copy_sequence.reset_all;\n }\n delay_sequence& operator=(delay_sequence copy_sequence)\n {\n index = copy_sequence.index.load();\n delays = copy_sequence.delays;\n repeat = copy_sequence.repeat;\n reset_all = copy_sequence.reset_all;\n return *this;\n }\n};\n\n// find out how much space to reserve for delays vector\nstatic std::size_t setup_delay_sequence(delay_sequence& current_sequence, std::wstring& line, std::size_t start_position)\n{\n std::size_t delay_sequence_length = 1;\n for (std::size_t line_position = start_position; line_position < line.length(); line_position++)\n {\n if (line[line_position] == L'/')\n {\n ++delay_sequence_length;\n }\n else if (line[line_position] == L'-') // no more delays past reset point\n {\n --delay_sequence_length; // the last slash was before the reset point, so it won't go in the vector\n if (delay_sequence_length == 0)\n {\n current_sequence.reset_all = true;\n break;\n }\n current_sequence.repeat = true;\n break;\n }\n }\n return delay_sequence_length;\n}\n\n// this will let the user write something like \"1,500\"\nstatic void remove_non_digits(std::wstring& delay_substr)\n{\n std::size_t position_to_write = 0;\n for (std::size_t i = 0; i < delay_substr.length(); i++)\n {\n if (isdigit(delay_substr[i]))\n {\n delay_substr[position_to_write] = delay_substr[i];\n ++position_to_write;\n }\n }\n delay_substr.erase(position_to_write);\n}\n\nstatic void set_delays(std::vector<std::chrono::milliseconds>& delays, std::wstring& line, std::size_t delay_sequence_length, std::size_t slash_position)\n{\n static bool too_big_delay_seen = false; // static so function will remember if it already printed the message in a previous call\n delays.reserve(delay_sequence_length);\n unsigned long long max_delay = std::chrono::milliseconds::max().count();\n while (slash_position != std::wstring::npos && delays.size() != delay_sequence_length)\n {\n std::size_t next_slash_position = line.find(L'/', slash_position + 1);\n std::wstring delay_substr = line.substr(slash_position + 1, next_slash_position - slash_position - 1);\n remove_non_digits(delay_substr);\n if (delay_substr.length() == 0) // no numbers were written\n {\n delays.push_back(std::chrono::milliseconds(0));\n slash_position = next_slash_position;\n continue;\n }\n try\n {\n unsigned long long delay_time = std::stoull(delay_substr);\n if (delay_time > max_delay)\n {\n throw std::out_of_range(NULL);\n }\n delays.push_back(std::chrono::milliseconds(delay_time));\n }\n catch (const std::out_of_range& oor)\n {\n if (!too_big_delay_seen)\n {\n printf(\"delay time can only be %llu milliseconds\\n\", max_delay);\n too_big_delay_seen = true;\n }\n delays.push_back(std::chrono::milliseconds(max_delay));\n }\n slash_position = next_slash_position;\n }\n}\n\nstatic void set_key_and_value(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& line)\n{\n std::size_t slash_position = line.find(L'/');\n if (slash_position == std::wstring::npos) // no slash so no delay sequence so line isn't valid\n {\n return;\n }\n std::size_t position_before_whitespace = line.find_last_not_of(L\" \\t\\f\\v\\r/\", slash_position);\n if (position_before_whitespace == std::wstring::npos) // the entire file name was whitespace\n {\n return;\n }\n std::wstring file_name = line.substr(0, position_before_whitespace + 1);\n delay_sequence current_sequence;\n std::size_t delay_sequence_length = setup_delay_sequence(current_sequence, line, slash_position + 1);\n set_delays(current_sequence.delays, line, delay_sequence_length, slash_position);\n my_rh_map[file_name] = current_sequence;\n}\n\nstatic bool rh_map_setup(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)\n{\n std::size_t line_count = 1;\n std::wstring line;\n std::wifstream my_file;\n my_file.open(\"files_and_delays.txt\");\n if (my_file.fail())\n {\n printf(\"couldn't open files_and_delays.txt\\n\");\n return false;\n }\n while (std::getline(my_file, line) && line_count < SIZE_MAX)\n {\n ++line_count;\n }\n if (line_count == SIZE_MAX)\n {\n printf(\"can't store %zu delays\\n\", SIZE_MAX);\n return false;\n }\n my_rh_map.reserve(line_count); // overestimates slightly due to extra newlines and starting at 1\n my_file.clear();\n if (!my_file.seekg(0, std::ios::beg))\n {\n printf(\"seekg on files_and_delays.txt failed\\n\");\n return false;\n }\n line.clear();\n while (std::getline(my_file, line))\n {\n set_key_and_value(my_rh_map, line);\n line.clear();\n }\n my_file.close();\n return true;\n}\n\nstatic void delay_file(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map, std::wstring& file_name)\n{\n rh::unordered_flat_map<std::wstring, delay_sequence>::iterator rh_map_iter = my_rh_map.find(file_name);\n if (rh_map_iter != my_rh_map.end()) // key found\n {\n printf(\"%ls successfully found in hash map\\n\", file_name.c_str());\n delay_sequence& found_sequence = rh_map_iter->second;\n if (found_sequence.reset_all) // reset all delay sequences\n {\n for (auto& it : my_rh_map)\n {\n it.second.index = 0;\n }\n printf(\"all delay sequences reset\\n\");\n }\n else\n {\n if (found_sequence.repeat) // reset delay sequence\n {\n if (found_sequence.index.load() > 0 && found_sequence.index.load() % found_sequence.delays.size() == 0)\n {\n printf(\"%ls delay sequence reset\\n\", file_name.c_str());\n }\n found_sequence.index = found_sequence.index.load() % found_sequence.delays.size();\n }\n if (found_sequence.index.load() < found_sequence.delays.size())\n {\n // this is defined in the main file so it won't sleep if being used with load_extender_test.exe\n #ifdef THIS_IS_NOT_THE_TEST_PROGRAM\n std::this_thread::sleep_for(found_sequence.delays[found_sequence.index.load()]);\n #else\n unsigned long long total_milliseconds = found_sequence.delays[found_sequence.index.load()].count();\n unsigned long long total_seconds = total_milliseconds / 1000;\n short remaining_milliseconds = total_milliseconds % 1000;\n printf(\"sleep for %llu second(s) and %d millisecond(s)\\n\", total_seconds, remaining_milliseconds);\n #endif\n found_sequence.index += 1;\n }\n else // delay sequence already finished\n {\n printf(\"%ls delay sequence already finished\\n\", file_name.c_str());\n }\n }\n }\n else // key not found\n {\n printf(\"%ls not found in hash map\\n\", file_name.c_str());\n }\n}\n\nload_extender_test.cpp:\n#include <chrono>\n#include <thread>\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\nnamespace rh = robin_hood;\n\n#include \"class_and_functions.h\" // included here so robin_hood alias can be used\n\nstatic void print_rh_map(rh::unordered_flat_map<std::wstring, delay_sequence>& my_rh_map)\n{\n printf(\"\\n---------- hash map current state ----------\\n\");\n for (auto& it : my_rh_map)\n {\n printf(\"%ls / \", it.first.c_str());\n delay_sequence& sequence_to_print = it.second;\n for (std::size_t i = 0; i < sequence_to_print.delays.size(); i++)\n {\n // casted to unsigned long long to get rid of warning message\n // visual studio on windows wants %lu, but gcc on linux wants %llu\n printf(\"%llu \", (unsigned long long)sequence_to_print.delays[i].count());\n }\n if (sequence_to_print.reset_all)\n {\n printf(\"RESET_ALL \");\n }\n else if (sequence_to_print.repeat)\n {\n printf(\"REPEAT \");\n }\n printf(\": INDEX %zu\", sequence_to_print.index.load());\n printf(\"\\n\");\n }\n printf(\"---------------------------------------------\\n\\n\");\n}\n\nstatic void test_all_inputs()\n{\n #ifdef _WIN32\n std::wstring path_separator = L\"\\\\\";\n #else\n std::wstring path_separator = L\"/\";\n #endif\n std::wstring test_path;\n std::wifstream input_test_file;\n input_test_file.open(\"test_input.txt\");\n if (input_test_file.fail())\n {\n printf(\"couldn't open test_input.txt\\n\");\n return;\n }\n rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n bool setup_succeeded = rh_map_setup(my_rh_map);\n if (setup_succeeded)\n {\n print_rh_map(my_rh_map);\n while (std::getline(input_test_file, test_path))\n {\n printf(\"testing path: %ls\\n\", test_path.c_str());\n // +1 so separator isn't included\n // If separator isn't found, the whole wstring is checked because npos is -1\n std::wstring test_file = test_path.substr(test_path.rfind(path_separator) + 1);\n delay_file(my_rh_map, test_file);\n print_rh_map(my_rh_map);\n test_path.clear();\n }\n }\n else\n {\n printf(\"setup failed\\n\");\n }\n input_test_file.close();\n}\n\nint main(int argc, char* argv[])\n{\n printf(\"\\ntest start\\n\");\n test_all_inputs();\n printf(\"test finished, press Enter to exit\\n\");\n std::wstring input;\n std::getline(std::wcin, input);\n return 0;\n}\n\nload_extender.cpp\n#include <chrono>\n#include <thread>\n#ifdef _WIN32\n #define NOMINMAX // allows std::chrono::milliseconds::max().count();\n #include <Windows.h>\n // easyhook.h installed with NuGet\n // https://easyhook.github.io/documentation.html\n #include <easyhook.h>\n#else\n #ifndef _GNU_SOURCE\n #define _GNU_SOURCE\n #endif\n #include <stdio.h>\n #include <dlfcn.h>\n#endif\n#include \"robin_hood.h\"\n// thank you for making this hash map, martinus.\n// here's his github: https://github.com/martinus/robin-hood-hashing\n\n#ifndef THIS_IS_NOT_THE_TEST_PROGRAM\n #define THIS_IS_NOT_THE_TEST_PROGRAM\n#endif\n\n#ifdef THIS_IS_NOT_THE_TEST_PROGRAM\n #define printf(fmt, ...) (0)\n#endif\n\nnamespace rh = robin_hood;\n\n#include \"class_and_functions.h\" // included here so robin_hood alias can be used\n\n#ifdef _WIN32\n static NTSTATUS WINAPI NtCreateFileHook(\n PHANDLE FileHandle,\n ACCESS_MASK DesiredAccess,\n POBJECT_ATTRIBUTES ObjectAttributes,\n PIO_STATUS_BLOCK IoStatusBlock,\n PLARGE_INTEGER AllocationSize,\n ULONG FileAttributes,\n ULONG ShareAccess,\n ULONG CreateDisposition,\n ULONG CreateOptions,\n PVOID EaBuffer,\n ULONG EaLength)\n {\n static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n static bool setup_succeeded = rh_map_setup(my_rh_map);\n if (setup_succeeded)\n {\n std::wstring file_path = ObjectAttributes->ObjectName->Buffer;\n // +1 so '\\' isn't included. If '\\' isn't found, the whole wstring is checked because npos is -1\n std::wstring file_name = file_path.substr(file_path.rfind(L\"\\\\\") + 1);\n delay_file(my_rh_map, file_name);\n }\n return NtCreateFile(\n FileHandle,\n DesiredAccess,\n ObjectAttributes,\n IoStatusBlock,\n AllocationSize,\n FileAttributes,\n ShareAccess,\n CreateDisposition,\n CreateOptions,\n EaBuffer,\n EaLength);\n }\n\n extern \"C\" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo);\n\n void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) {\n HOOK_TRACE_INFO hHook1 = { NULL };\n LhInstallHook(\n GetProcAddress(GetModuleHandle(TEXT(\"ntdll\")), \"NtCreateFile\"),\n NtCreateFileHook,\n NULL,\n &hHook1);\n ULONG ACLEntries[1] = { 0 };\n LhSetExclusiveACL(ACLEntries, 1, &hHook1);\n }\n#else\n FILE* fopen(const char* path, const char* mode)\n {\n static auto original_fopen = reinterpret_cast<FILE * (*)(const char* path, const char* mode)>(dlsym(RTLD_NEXT, \"fopen\"));\n static rh::unordered_flat_map<std::wstring, delay_sequence> my_rh_map;\n static bool setup_succeeded = rh_map_setup(my_rh_map);\n if (setup_succeeded)\n {\n // finding part of path which shows file name\n std::size_t file_name_index = SIZE_MAX; // overflows to 0 and checks entire path if no slash is found\n std::size_t end_index = 0;\n for (; path[end_index] != '\\0'; end_index++)\n {\n if (path[end_index] == '/')\n {\n file_name_index = end_index;\n }\n }\n std::wstring file_name(&path[file_name_index + 1], &path[end_index]);\n delay_file(my_rh_map, file_name);\n }\n return original_fopen(path, mode);\n }\n#endif\n\nload_extender_injector.cpp (only used on Windows, LD_PRELOAD and DYLD_INSERT_LIBRARIES can be used on Linux and Max OS):\n#include <tchar.h>\n#include <iostream>\n#include <string>\n#include <Windows.h>\n// easyhook.h installed with NuGet\n// https://easyhook.github.io/documentation.html\n#include <easyhook.h>\n\nvoid get_exit_input()\n{\n std::wcout << \"Press Enter to exit\";\n std::wstring input;\n std::getline(std::wcin, input);\n std::getline(std::wcin, input);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n WCHAR* dllToInject32 = NULL;\n WCHAR* dllToInject64 = NULL;\n LPCWSTR lpApplicationName = argv[0];\n DWORD lpBinaryType;\n if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6))\n {\n std::wcout << \"ERROR: This exe wasn't identified as 32-bit or as 64-bit\";\n get_exit_input();\n return 1;\n }\n else if (lpBinaryType == 0)\n {\n dllToInject32 = (WCHAR*)L\"load_extender_32.dll\";\n }\n else\n {\n dllToInject64 = (WCHAR*)L\"load_extender_64.dll\";\n }\n DWORD processId;\n std::wcout << \"Enter the target process Id: \";\n std::cin >> processId;\n\n wprintf(L\"Attempting to inject dll\\n\\n\");\n\n // Inject dllToInject into the target process Id, passing \n // freqOffset as the pass through data.\n NTSTATUS nt = RhInjectLibrary(\n processId, // The process to inject into\n 0, // ThreadId to wake up upon injection\n EASYHOOK_INJECT_DEFAULT,\n dllToInject32, // 32-bit\n dllToInject64, // 64-bit\n NULL, // data to send to injected DLL entry point\n 0 // size of data to send\n );\n\n if (nt != 0)\n {\n printf(\"RhInjectLibrary failed with error code = %d\\n\", nt);\n PWCHAR err = RtlGetLastErrorString();\n std::wcout << err << \"\\n\";\n get_exit_input();\n return 1;\n }\n else\n {\n std::wcout << L\"Library injected successfully.\\n\";\n }\n\n get_exit_input();\n return 0;\n}\n\n"
I create this menu filter component: with this menu, in practice, you can filter on a cards list feeling free to choose different filters at the same time; the cards list returned will be the results of all options selected. to generate this kind of filter I filter on filtered option and so on, in other words like so:...
I coded a basic feedforward neural network with all pure python with the exception of numpy in order to better understand how neural networks work. It works, but the only problem is it is extremely slow, and I have no idea how to fix it. The neural network looks like this: import numpy as np from digits import x_trai...
I have a simple array in PHP like this : Array ( [max_size_video] => 50000 [max_size_photo] => 8000 [token_expire] => 100 [dns] => mydns.fr ... ) I would like to convert this array to multidimensional format with underscore as a separator: Array ( [max] => Array ( [size] => ...
I am currently learning Python by working my way through Automate the Boring Stuff with Python. This project is from Chapter 8 which is focused on validating input by using the PyInputPlus module. Whenever I finish, I like to look the problem up and compare to other's solutions to see what I could have done better. How...
I have attempted to create an IconComponent that shows a different SVG icon depending on the string that is passed in. Example: <app-icon icon="tick"></app-icon> Would show an SVG of a tick. Small StackBlitz example I believe this approach, however, creates a new and unique TemplateRef for each instance of IconCompone...
I am trying to perform some conversions with multidimensional array in C# and I have checked the discussion ConvertAll and 2-dimensional arrays. I found that Array.ConvertAll still not support multidimensional array cases. Therefore, here's an experimental implementation for handling the process of conversions on multi...
I have the following code to do a majority vote for data in a dataframe: def vote(df, systems): test = df.drop_duplicates(subset=['begin', 'end', 'case', 'system']) n = int(len(systems)/2) data = [] for row in test.itertuples(): # get all matches fx = test.loc[(test.begin == row...
Based on what i understood of Binary Tree, queue and recursion I implemented this Breadth First Search algorithm as follows. Do you have any suggestions to improve (in term of readability, good practice etc...) it? # Definition for a binary tree node. class Node(object): def __init__(self, val=0, left=None, right=N...
I am solving LeetCode Dynamic Programming challenges (this one is #72, at https://leetcode.com/problems/edit-distance). Here below, I've implemented a Rust solution for the minimum edit distance between two strings problem. (Note that this solution works and passes all the test cases on LeetCode) use std::collections::...
I'm a SQL learner. In answering the question* For the region with the largest sales total_amt_usd, how many total orders were placed? for the following schema: (I am unsure of the dialect is but I think it is Postgres) I came up with the following solution and I wonder if am committing any bad practice (since the offi...
I would really appreciate feedback on my OOP Household Outgoings calculator. My objective is to develop in OOP. Have I used good OOP techniques? How can I improve on it? And anything else you might add. Thank you very much in advance for anyone who spends their time reviewing it. I've learned so much from this site and...
See this link for previous post on this subject Generating mathematical questions and answers I have an Android quiz app that I am building to learn kotlin / android app development. Here is an object I have which acts as one of many question builders. Since my last post I have: broken down the main method into smalle...
I'm a total beginoob in Lua. The aim is to display a 3D Torus in dots (see Figure1), or at least compute the positions, privileging clarity over performance. Pseudocode link. Don't hesitate to be picky, I'd like to learn proper Lua idioms. For instance, I was pleased to find operator overloading, but couldn't find a ne...
I am writing a program that has a 'base' class called Group. The class will have only one instance. Aside from some properties and methods, it needs to keep track of a variable amount of group_companies. After working with the program (that may involve adding or deleting group_companies), I want to save the current sta...
I'm writing my program in python and have it working properly, but it's over 500 lines of code. I think there is a way I can condense my code, but I'm not sure how I should do it Here's an example of some of my code: def click(): if clicked1.get() == "app1": os.startfile(r"C:\Users\red\Desktop\app1") ...
I want to solve for n in the expression (binomial coefficient): \$y=\frac{n^2+n}2\$ let y = (Math.pow(n, 2) + n) / 2; I know the \$y\$ value, but I want to compute \$n\$. Here is what I have so far, but I would want to know if there was a way to compute the value rather than look it up. In this example, I have to loo...
I have a DataGridView which displays an employee list. I use the employee ID to filter my global employee list and display information about the selected employee in various listboxes. This is my first coding project, and I'm pleased that it's working well, but I do feel like I'm repeating myself a lot. Is this an i...
//the strategy of take the rest of division by 1e06 is //to take the a number how 6 last digits are 269696 while (((square=current*current) % 1000000 != 269696) && (square<INT_MAX)) { current++; } This is part of the "C" example on rosettacode.org. The comments, and not only them, more belong to towero...
I have the following code: public class Car { public int numberOfWheels { get; set; } public string colour { get; set; } public Car(int numberOfWheels, string colour) { this.numberOfWheels = numberOfWheels; this.colour = colour; } } [Route("/")] public class CarController: Controll...
I have a pandas Series contain 0s and 1s. Now I want to convert all the 0s to 1s which come before the first 1, and rest of the 1s to 0s. I can achieve that using the below code: import pandas as pd a = [0,0,1,0,0,1] df = pd.Series(a) flag = True for i in range(df.shape[0]): if (df[i]!=1) & flag: df[i]=1 elif f...
Whilst refactoring an app I'm working on I moved a piece of code from the business logic layer to a helper. The code in question is a fire and forget method that will execute a piece of code if it hasn't been cancelled after an amount of time. The method looks like this: public async static void CancelAfter(int second...
The code below first searches for the first searchText and deletes all rows that precede it to establish a range for a table object. Once the table object is created, it's filtered by unnecessary fields. After ensuring the searchText is in the first row (header), it deletes all visible rows below it in order to keep al...
I have 4 CSV files that i need to process (filter out Part segment and then merge them) but the problem is that they do not fit in my memory. So I decided to: [open - filter - write out] each one of theses 4 files and merge them after reopening the filtered version. I learned that it was good practice to decouple the f...
I was trying to optimize the Radix Sort code, just because. Nothing more, nothing less. Here it is!!! So tell me, how does it look? Summary: instead of a div or mod ,i use left shift and right shift to avoid div or idiv compiler instruction. the dual instruction is for avoiding jumps and the usual stuff. btw you ca...
How can I change the function calc_obstacle_map(self, ox, oy) to get an equivalent result that runs as fast as possible? The time complexity of O(n³) takes a huge amount of time to calculate the obstacle map for bigger arrays. I'm glad about every hint to improve the running time, including a version of this code with ...
I'm trying to devise a tkinter gui, that, among others, lets users choose a 'working folder' and a 'destination folder (and there is more coming). I stripped the code to its bare functionality hereunder. I found myself duplicating code for the selection of both the 'working folder' and the 'destination' folder. I came ...
Here's what I came up with. What improvements might I make? All I want you to look at is the strncmpci() function--nothing else for improvements. Note that I want readable and maintainable code, NOT optimized code which is impossible to read. Goals: bug-free (does what it says it does, and does it well) handles potent...
Consider an array of numeric strings where each string is a positive whole number. Sort the array's string elements in ascending order of their numeric values, and return the sorted array. Return: string[n]: the array sorted in numeric order. Constraints: Each string is guaranteed to represent a positive whole integer....
The following is a quick attempt at testing some limits of my computer: import multiprocessing import time def main(): numbers = tuple(multiprocessing.Value('Q', 0, lock=False) for _ in range(multiprocessing.cpu_count())) processes = tuple(multiprocessing.Process(target=count, args=(number,)) for number in nu...
Asking for a review of this neural network code. I have officially finished my first neural net that works properly (by my standards right now). But I know there is more than likely some details I am missing or getting wrong that might be affecting the quality of the nets intelligence. I plan on making this a library s...
I'm trying to build a board game and solve it using algorithms such as Monte Carlo Tree Search in C++. My current design follows this python project, in which I have a class hierarchy for Board and a State template as follows // board.hpp #ifndef GAME_BOARD_H_ #define GAME_BOARD_H_ #include <vector> #include <unordere...
Background Lately, I found OpenSSL to be difficult to learn as a beginner, while it can be implemented inside beginner-friendly projects like socket programming. After two weeks of research, I've written the following program. I thought to share it with the community to detect issues that can be improved, and add a res...
I have written a very simple wrapper around std::shared_ptr that supports lazy initialization. Do you see any problems? #include <functional> #include <tuple> #include <utility> template <class T, typename ... Args> class LazySharedPtr { public: LazySharedPtr(Args ... args) : ptr(nullptr) { this->i...
I am trying to find the longest Euclidean distance to the origin for each point. Their positions are stored in two float arrays, denoting each point's position on the Cartesian plane. I tried to speed up the function using SIMD (WITHOUT SVML, so no _mm256_hypot_ps), however it still seemed a little bit slow. The code l...
How to improve my validation in JavaScript? Namely I am wondering whether some parts of code can be shortened, improved, or removed althogether. I don't want to change the ES5 syntax because so far I am not familiar with Es6 syntax. I also want to avoid using jQuery. This is my validation code: https://codepen.io/Robot...
I tried to implement something like a C++ enum class in Fortran. That means it should be typesafe and scope bound. (No comparison between integers and enum values for example.) The following works, but it is still possible to compare two instances of different enum classes at compile time. Do you have suggestions for p...
An eccentricity function with parameter \$r\$ on a metric space \$X\$ with \$N\$ points is \begin{gather} f(y) = \left( \sum_{x \in X} \frac {d^r(x, y)} N \right)^{1/r};~~~x,y \in X \end{gather} (Note: for the implementation \$X\$ is a finite metric space since \$N<\infty\$ for computability) I have tried to implement...
This is my first question here and I'd like to get some feedback. The program works but I'm not sure the classes I've used are right. First, a class to calculate the Body Mass Index from a double (kgs) and an integer (height in cm): //Data taken from https://codereview.stackexchange.com/questions/216933/java-swing-exer...
I have a connection.php file into my root folder and at the bottom, I added BASE_URL <?php $hostname = "localhost"; $username='root'; $password=''; $db='demo'; $charset = 'utf8mb4'; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::...
I am learning Swift and just had a quick question about use of parentheses. The code below runs just fine w/o using parentheses, but it certainly looks a lot cleaner using them in this instance. So my question is: In SwiftUI, is it basic practice to use parentheses for the sake of cleanliness? Might be a silly question...