instruction
stringlengths
71
95.1k
My problem is I'm having a table and 7 child table. I'm fetching details using querying the main table first then querying the child tables one by one sequentially. To improve performance I decided to execute all the seven queries parallely using completable future. StoryDetail storyDetail = new StoryDetail(); C...
Design a class called Post. This class models a StackOverflow post. It should have properties for title, description and the date/time it was created. We should be able to up-vote or down-vote a post. We should also be able to see the current vote value. In the main method, create a post, up-vote and down-vote i...
I'm relatively new to Python and learned, that function cannot return nothing, not even None. In my application I want to iterate over a list and keep all non-None results of a complicated function: def complicated_function(x): if x < 0: return "a" elif x == 3.6: return "b" elif x == 4: ...
I made a calculator a few days ago and posted the code here. I got some very helpful feedback. So I remade the calculator and learned a lot in the process. Here's my new code: In the header file: #include <string> template <typename NUMTYPE> std::string calculate(const std::string&); template <typename NUMTYPE> std::s...
I have written a very basic algorithm, that counts the amount of times sub-string appears in a string. The algorithm is given: seq - a string sequence k - length of a sub-string L - a window of a string to search in t - times that sub-string, length k has to be present to be added to results from collections import ...
I've created a function that generates an <ul> of my wordpress custom taxonomy terms, displaying parent > child > second child heirachy. Functionally it is working perfectly and replaces my old hard-coded menu. The problem is I'm inexperienced and recognise it as an ugly, inefficient function but could not figure out ...
For work, we have to use Atlassian Jira, which is depressing. To make my life a bit easier, I decided to write a cli application to get ticket summaries, and I thought it would make a good first project in rust. The code below works, but I would be grateful for any tips/improvements. I'm a python programmer, so it's al...
In my web API, the client wants me to implement logic in order to control/block concurrent requests in a specific time period. I added RequestInterval which is 10 seconds in the appsettings of web config. I added the Authorization filter into my project. I tested, it looks working but I wonder if you can check and give...
I have had an attempt at the Mars Rover Kata and would very much appreciate a review and any suggestions to improve. MessageParser to parse incoming messages and create the domain models: public class MessageParser { private static readonly Regex GridDetailsRegex = new Regex(@"\d\s\d"); private stat...
I've made a simple brainfuck compiler, I feel like my code is unreadable and messy, how can I improve it? src/core.clj (ns brainfuck-asm.core (:require [brainfuck-asm.parse :as parse] [brainfuck-asm.optimize :as optimize] [brainfuck-asm.generate :as generate] [clojure.java.io :as i...
sudoedit_enhanced written POSIX-ly challenge While creating sudoedit_enhanced POSIX (apart from readlink I have been pointed out) shell script snippet, I face two challenges: check if all the files exist, it does not make sense to create a new file this way sudoedit does not work with symlinks, so translate symlinks ...
I have some code that is slow because it loops over every row in an input matrix Y. Obviously, this code does not scale with the number of rows. I don't think it's critical to understand what the code does, but for the curious, it is a Gibbs sampling step for sampling the dispersion parameter r for the negative binomia...
I designed a game with trying to use solid principles. What changes should I do for making program more extensible, readable. Thanks in advance. Cell class public class Squares { public int NumberOfAdjacentMines { get; set; } public bool IsMine { get; set; } public bool IsFlagged { get; set; } // show i...
New to coding/Javascript. Writing a basic Tic Tac Toe game. I'm writing the game to be dynamic, so it won't always be a three-by-three grid, but rather any size grid larger than 1. I have a completely functioning game and win checker function, but the win checker is very, very wet. I've tried several way to dry it up, ...
If I have a list that contains True and False values, how can I find the start and stop indices of where there are blocks of True values? x = [True, False, False, True, True, True, False, True, False, False, False, True, True, False, True] The output that I am looking for is: [[0, 0], [3, 5], [7, 7], [11, 12], [...
I recently wrote the following code: def freq_progress user_flashcards = input_flashcards.includes(:term) terms_unicos = user_flashcards.map(&:term).compact.uniq freq_1, freq_2, freq_3, freq_4, freq_5 = 0, 0, 0, 0, 0 terms_unicos.each do |term| case term.ranking when nil next ...
I (a junior back-end Java dev) decided I wanted to learn some front-end development skills; in particular, I wanted experience with React and websockets. I decided to write an app that would allow for remote play of a 9X9 variant of tic tac toe one of my college friends made up. The rules are: The board is divided int...
I've written the following function in C which shall take as input a character array (decayed to a char * of course), and mutate the string into a title-cased string in the form "this is a string" -> "This Is A String". void title_case(char str[]) { assert(str); size_t i; str[0] = toupper((int) str[0]); ...
I am trying to write a sql storeprocedure that basically returns a derived value from an outcome of a function call. The derived field returns the difference in days and if the difference is less than 24 hours then returns hours. It is working as desired but just need to ensure if the approach is right. Storeprocedure...
I want to remove the mail contact from all Groups in the "Member Of" tab. I am able to remove all MemberOf for mail contact. How can I improve the speed of the script? Get-MailContact <name> | ForEach-Object { Get-ADObject $_.distinguishedname -Properties memberof } | Remove-ADPrincipalGroupMembership -Identity $_ -Mem...
I am trying to solve ProjectEuler.net problem #50, Consecutive Prime Sum. Here is the problem: The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes bel...
This is one of my first projects in C++, and I would call it a program for storing, displaying data and prognosing numbers. I use following compiler: g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0 I will try to explain my code starting with the main method which is located at the bottom of the code. The main method in my prog...
In helpcovid git commit e27dd3b123c18300665 we have a stupid bug related to Linux GNU glibc argp program argument parsing. void hcv_parse_program_arguments(int &argc, char**argv) { struct argp_state argstate; memset (&argstate, 0, sizeof(argstate)); argstate.input = &hcv_progargs; hcv_progargs.hcv_progmagic = H...
I recently implemented a Bloom Filter in Haskell and, although I am not new to functional programming, I am a beginner when it comes to Haskell itself. I'll gladly take any feedback regarding the implementation or the code style. I tried to stick to the Haskell conventions regarding function and variable naming, but I ...
The code starts with 128 bits of 0 (size of md5sum checksum) then brute forces to find checksum matching regex (all characters of checksum in hex are digits). I know that there may be collisions and that not all 2^128 possible checksums will come out. I know that if the code is run, that it will not finish any time soo...
PHP coder here. Learning JavaScript this week. I made a sudoku game for practice. Features: Import puzzles by pasting a text string. Imported squares are gray. Your squares are white. Program doesn't let you make a clearly illegal move. It will blank your number and color the square red for 2 seconds. The sudoku puzzl...
ERROR: type should be string, got "https://leetcode.com/problems/sliding-window-median/\n\nMedian is the middle value in an ordered integer list. If the size of\n the list is even, there is no middle value. So the median is the mean\n of the two middle value.\nExamples: [2,3,4] , the median is 3\n[2,3], the median is (2 + 3) / 2 = 2.5\nGiven an array nums, there is a sliding window of size k which is\n moving from the very left of the array to the very right. You can only\n see the k numbers in the window. Each time the sliding window moves\n right by one position. Your job is to output the median array for each\n window in the original array.\nFor example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.\n\n\n\nTherefore, return the median sliding window as [1,-1,-1,3,5,6].\nNote: You may assume k is always valid, ie: k is always smaller than\n input array's size for non-empty array. Answers within 10^-5 of the\n actual value will be accepted as correct.\n\nPlease review for performance. also I am not sure about GetID function is there a smarter way to get the same result of unique number and sorting for median? \nusing System;\nusing System.Collections.Generic;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace TreeQuestions\n{\n /// <summary>\n /// https://leetcode.com/problems/sliding-window-median/\n /// </summary>\n [TestClass]\n public class SlidingWindowMedianTest\n {\n [TestMethod]\n public void ExampleTest()\n {\n int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 };\n int k = 3;\n double[] expected = { 1, -1, -1, 3, 5, 6 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n\n [TestMethod]\n public void ExampleTestFailed()\n {\n int[] nums = { 1, 4, 2, 3 };\n int k = 4;\n double[] expected = { 2.5 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n\n [TestMethod]\n public void ExampleTestOverFlow()\n {\n int[] nums = { 2147483647, 2147483647 };\n int k = 2;\n double[] expected = { 2147483647.0 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n\n [TestMethod]\n public void ExampleFailed2()\n {\n int[] nums = { 5, 2, 2, 7, 3, 7, 9, 0, 2, 3 };\n int k = 9;\n double[] expected = { 3.0, 3.0 };\n double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);\n CollectionAssert.AreEqual(expected, res);\n }\n }\n\n\n\n public class SlidingWindowMedian\n {\n public static double[] MedianSlidingWindow(int[] nums, int k)\n {\n var res = new List<double>();\n var med = new SortedList<long, int>();\n for (int i = 0; i < nums.Length; i++)\n {\n med.Add(GetId(i, nums), nums[i]);\n if (med.Count > k)\n {\n med.Remove(GetId(i - k, nums));\n }\n\n if (med.Count == k)\n {\n if (k % 2 == 0)\n {\n res.Add( ((long)med[med.Keys[k / 2 - 1]] + med[med.Keys[k / 2]])/2.0 );\n }\n else\n {\n res.Add(med[med.Keys[k / 2]]);\n }\n }\n }\n return res.ToArray();\n\n }\n\n private static long GetId(int i, int[] nums)\n {\n return Convert.ToInt64(nums[i]) * nums.Length + i;\n }\n }\n\n}\n\n"
I've taken up code streaming and I'm concerned that as I do so, I'll leak an API token somewhere. It was suggested that I use something like "a secrets.toml or secrets.yaml or secrets.json file." But I don't want it all in one file. If I did have a leak, I'd likely lose all my tokens at once. So I considered a secrets ...
I'm learning python and for educational purposes I implemented tar archive parser. I'm not beginner programmer. I would like to receive some feedback and tips about code, what can I improve, what could be done better and so on. Implementation: tar.py #!/usr/bin/env python3 import io import os import sys import math i...
I have made a 2 player Tic Tac Toe game in C++. I have put in some error checking also (like if the players enters an invalid position). The code is working absolutely fine. This is what my program output looks like. | | | | | | | | | Where you want to ma...
i'm trying to create a url router system, for educational purposes, that has a similar usage like Laravel has, but i'm curious about how i can register the routes like laravel does (with single calls to static methods), here's my "conceptual" code that i made using a TDD approach: $Route = new Route; $R...
The goal of my code is to implement a web scraping routine to obtain the name and the price of a product. I want to put this routine separated from the main program file. Sample url to scrape: https://www.amazon.co.uk/Samsung-MZ-76E1T0B-EU-Solid-State/dp/B078WST5RK/ref=sr_1_1?dchild=1&keywords=samsung+860+evo+1tb&qid=1...
I am building an ad-hoc text-editor. I have two functions which use a cache, provideHover and provideCompletionItems. "use strict"; import * as monaco from "monaco-editor/esm/vs/editor/editor.api"; const $ = require("jquery"); const urlResolve = require("url-resolve"); const AUTOCOMPLETE_ENDPOINT = "http://localhost:...
I have created a Snake console game using object-orientated programming methods. This is the first time I have ever used OOP so I just wanted to know if I was using the method correctly as well as hear any other advise I could possibly receive as this is my first time doing this. There are 4 header files and 4 .cpp fil...
This was one of my friends' Java OOP class assignments. They were tasked with writing a polynomial class in Java with multiplication functionality. I did it in C++ as a challenge and for improving my programming skills. I also added a little bit of extra functionality. Header File polynomial.hpp #include <vector> #incl...
I implemented the following Tron cycle game so that it can be run on GameCube / Wii devices (quarantine...). Indeed, there exist many tools (I rely on devkitPPC) and I thought a Tron game would be an easy starting point for this kind of development. I have no experience in C, neither in enforcing "classes" in C, or in ...
I'm implementing Sieve of Eratosthenes by working with multiples of 30 and comparing it to multiples of 3 from a previous answer code for multiples of 30: #include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ const unsigned int res[8] = {1,7,11,13,17,19,23,29}; const unsigned int N = 1000000000;...
I've been experimenting with Hooks lately and looking more into how can I replace Redux with useContext and useReduer. For me, Vuex was more intuitive when I first got into stores and I prefer their state management pattern, so I tried to build something close to that using the React Context. I aim to have one store/c...
Disclaimer: This is my first post here, so I'm not completely sure if this is on-topic. I recently added a decorator that wraps a context manager in pyfakefs (I'm a contributor), which has some optional arguments. In order to make the usage more convenient, I allowed both the usage with and without parentheses (mostly ...
This is the solution for a simple challenge from Hackerrank.I am just trying to solve Sorting: Bubble Sort Problem on HackerRank. We are asked to count the number of swaps performed during a bubble sort and to print the first and last item of the ordered vector. Sample input 3 3 2 1 First line is the number of element...
I wrote a simple antivirus in Python and would love feedback for additional ideas to implement, as well as general code review. So far it has a FileScanner that checks against a database of known virus hashes and a network scanner that checks against a database of potentially malicious IP addresses. I'm very curious ab...
The following is a c++ source code to get a matrix (std::vector<std::vector<T>>) transpose in parallel. The span is \$\Theta(\lg^2(n))\$ while the work is \$\Theta(n^2)\$ Any suggestion to improve will be appreciated. #include<vector> #include<iostream> #include<future> #include<iomanip> template <typename T> void para...
I'm trying to play around with Godot to learn C# and I was trying to creating pure functions to do the velocity, but I found I was repeating myself. public override void _PhysicsProcess(float delta) { base._PhysicsProcess(delta); Vector2 moveVelocity = velocity; moveVelocity = Run(moveV...
I have the below code that helps me do some formatting. But I want to increase the efficiency of the code by making it faster. Below are the formatting steps of the macro. Convert "Q" and "S" column to number format. Replicate the "I" column to new column by inserting a column next to it. Cut the column "AD" and paste...
This is regarding code quality and coding standards with respect to Spring Ecosystem. Here there are two methods: isRecordExists is using a class level static constant String query. (Definitely suggestable for old way where we use prepared statements) isRecordExists2 is using method level String query Which method is...
https://leetcode.com/problems/network-delay-time/ There are N network nodes, labelled 1 to N. Given times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target. Now, we send a signal ...
I have the following: #include <string> #include <string_view> #include <vector> #include <unordered_map> #include <iostream> namespace utils { void replace_all(std::string& string, const std::string_view from, const std::string_view to) { std::size_t start_pos{ 0 }; while ((start_pos = strin...
I have these following controller functions for registering a user and login, in my app, and I want to make it more clean and maintainable. Probably by using async/await and exec(). Also, the validations do not look not good. It would be great if you suggested me good practices to refactor this. registerUser: (req...
I sped through the 5hr F# pluralsight course this week-end and thought I'd sement my learning by going through as many Advent of Code puzzles I could with this new learning. However, already on day 2 I'm starting to question whether I'm too biased from C syntax and imperative coding to do it "right". I really really mi...
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class List<T> { private T[] arrayList; private int arrayLenght = 5; private int arrayIndex = 0; public List() { arrayList = new T[arrayLenght...
What I'm trying to achieve From a list of lists of elements (one element can be in multiple lists, but only once in each list), I want to generate a map whose keys are each elements and the values are the collection of elements that appear at least once with the key in the first lists. Example This is the input : List<...
I am a beginner with C++, I am not learning OOP yet, I will start when I finish this project. I'm working on "Educational Management System Project". So I had trouble to code the part of login and sign up, I am not comfortable with this approach, I wonder if there is a solution to simplify this code and reducing if-sta...
This is my first project and I wrote it to practice coding. However, I'm wondering if there is an actual practical use for it. What this code does is list the number of times a word occurs in a text entry, either by alphabetical order, listing the frequency of the word or listing the index in the text entry where that...
Hi I recently wrote some code in python that does the following: 1.) Pulls stock closing data from yahoo finance for x number of stock 2.) finds all possible combinations of x stocks in groups of y size (so all combinations of 13 stocks in groups of 10) 3.) applies some calculations to each of these groups 4.) returns ...
The goal of this code is to remove subnets from the list that are redundant (included in the larger ones) It is VERY slow. Wondering how it can be sped up. At present, I’m not looking to optimize the “CheckSubnet()” function, which isn’t my code... It MAY be slow (or not) but I’m hoping that a critical analysis of the...
I have tried to write a simple 3 x 3 tic tac toe program. Please I need a code review on this program, whether it is readable, maintainable or not. Judge it as much as you can. Here is the source code: #include <iostream> #include <string> #include <vector> void draw_board(std::vector<std::string> &board) { /** ...
I'm creating a small library of Python utilities, and I'd like feedback on a function which allows iterating over an arbitrary iterable in a sliding-window fashion. Relevant parts of iteration.py: import collections import itertools def sliding_window_iter(iterable, size): """Iterate through iterable using a slid...
I have a Predicate which takes employee object. Predicate<Employee> getPredicate() { return emp -> filter(emp); } Now the filter method is very complex, it calls four other methods which returns true/false if all the conditions are true, the predicate will return true. private boolean filter(Employee employee) { ...
I've got a function which takes a screenshot of a particular window. It's important that the screenshot works whether the window is focused/covered by other windows or not, hence why I've used PrintWindow. This function takes 45ms to complete, and I was hoping to decrease that. The end goal is to: Take a screenshot of...
Please download the file and save in home directory and extract it: https://www.dropbox.com/s/swtw8bk35zr1i6d/analyse.7z?dl=0 I can get some warrants info. import analyse df = analyse.warrants.get('0788') Now we got 0788's warrants info. It output df with better format: analyse.tabulate.tabulate(df) I want to simply ...
I want a feedback on my code for the below known problem from Daily coding challenge: You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on. Given this matrix, a start coordinate, and an end coordinate, re...
This problem is tested against 3 sets of input data to see if the submitted solution gives an incorrect answer, if the solution exceeds the time limit, or if the solution exceeds the memory limit: Test set 1 (Visible): 1 ≤ N ≤ 1000. Test set 2 (Visible) 1 ≤ N ≤ 10^6. Test set 3 (Hidden) 1 ≤ N ≤ 10^18. My solution (belo...
I've decided to implement Python's any in C++. I've gone about this using templates to allow multiple types of data to be passed, instead of overloading the function multiple times. This is my first time using templates so I would really like feedback about my usage of them. I'm also fairly new with references and poin...
I'd like some feedback on code I wrote to obfuscate text on-disk. The basic idea is the same as ROT13 (which is implemented in the Python standard library), except instead of rotating the English alphabet by 13, the underlying byte representation is rotated by 128. The use case is to hide data from a string-search. Bec...
This is a follow-up question to eCommerce Mockup App in JS. How do I implement the 'observe' pattern for the cart to regenerate html? So that, it will keep refresh its own. And any review on my coding style and code structure design? "use strict"; // Bugs // 1. UI bug for cart item count. Non responsive. // Initial...
I am a beginner using R and I am trying to solve some simple statistics problems and print the output. The following code takes in two datasets, computes the mean, variance and standard deviation. Finally it computes a 95-confidence interval for the standard deviation. This is just a sample and my real data consists o...
This code is a purely for-fun project and it comes from this challenge at freeCodeCamp. This is simply an algorithm challenge which is usually meant for JavaScript, but I decided to perform in C. It will not be used for any production reasons. Please leave any feedback you see fit, with special attention to the loops a...
Songs Class: public class Songs { //----------------------------------------------------------------- // Creates a SongCollection object and adds some songs to it. Prints // reports on the status of the collection. //----------------------------------------------------------------- public static v...
Problem Description: The purpose of this function is to take a list of sorted numbers and split it into two evenly balanced lists. By evenly balanced I mean the numbers in the two lists have as close as possible to an equal average while as close as possible in length. Put simply, the resulting lists should have the sa...
I just created a BinarySeachTree class in c++ which is supposed to store words read from a txt and the number of occurances of those words and i would just like some feedback from you. I think it works correctly and i used valgrind to check if it creates any memory leaks (and it doesn't). I am just worried for some thi...
I've put together a simple CRUD application to keep track of my library of books in an effort to learn the model-view-controller pattern, as well as better myself at PHP. Everything I have works so far, but I'm definitely looking to streamline/condense/refactor the more verbose parts of it, as well as address any possi...
I am currently self-studying on Python generator object and use it to generate training data and do augmentation on-the-fly, then feed it into Convolutional Neural Networks. Could anyone please help me to review my code? It runs properly, but I need review to make it more efficient and more properly structured. Besides...
I am making a super simple and dumb terminal text game to try out unittest in python. I have ran into a problem. When I run the test, the game loop is ran, and I have to manually insert input to continue to the tests. Is there a way to not run the game loop when I run my tests, so I can test the class methods only? An...
Here is a good article on an optional reference type in C++. They discuss std::optional<T&>, but as that doesn't compile I have made my own. One purpose of this type is to remove raw pointers from function signatures (where references alone cannot be used), as a raw pointer does not convey any indication of what it wil...
I am trying to get my head around exceptions, and implement exception handling that ultimately gets logged, since my code runs as a remote job and reviewing a txt log is the best means of reviewing results. Currently I have an issue where "unexpected" exceptions only show up in the console, so my focus right now is dea...
This is a script I've written to deploy the Elastic Stack. Can you help me improve it? Especially the parts called out with *** markings. deploy.sh: #!/usr/bin/env bash sudo sysctl -w vm.max_map_count=262144 #use the elastic utility to gen certs docker-compose -f create-certs.yml run --rm create_certs # Start the stack...
An exercise asks that we extend the below random number generator app to print to the console how many times the user guessed before guessing the correct random number. I first declared what I call a counter variable numberOfGuesses inside the keepPlaying while loop and then inside the continueGuessing while loop I in...
I would like to ask for a code review as I feel like it's not the most efficient way of doing it. For context I have a add-ins with all the code in module and then the SheetChangeevent is in ThisWorkbook. Also in the add-ins I have 2 sheets that will have data on it so that the ActiveWorkbook will be able to read this ...
In an interview I was giving the following problem: Count the number of click on on the entire page. Can you think of a better way to do this? let counter = 0; document.addEventListener('click', clickCounter); function clickCounter() { counter++; console.log(counter); }
I have a dataset X_train, which is an array where each entry is an email (a string of characters). There are 11,314 emails, each of which is about 500 characters long. (X_train is a processed version of the training data in the newsgroups dataset.) Ultimately, my goal is to build from scratch a tf-idf function (knowled...
I implemented a Simpletron simulator in C for learning C. Simpletron is a virtual machine invented by Deitel for his books. Simpletron runs programs written in the Simpletron Machine Language, an simple Machine Language. An instruction (and data) in the Simpletron Machine Language is a signed four-digit integer, like +...
As I was advised, I broke my code into 2 classes. Could you take a look at the repository class and report what problems this code has public class JsonSharedPreferences { private static Gson gson = new Gson(); private Context context; public JsonSharedPreferences(Context context) { this.context = context.getAppli...
I am learning C and, for learning purposes, I implemented a dice roller. It uses arc4random(3) for random number generation, as I couldn't find something better. It works both interactively, if no argument is given, reading dice string from stdin, one per line (I used getline(3) for this); and reading dice string from ...
Recently I was learning about TypeList and its algorithms in C++. When reading about its uses i got to know that TypeList along with the help of ClassHierarchy generators can be used to create Tuple Type in C++ (Andrei Alexandrescu). So i tried to write an implementation of it based on ClassHierarchy generator which is...
I worked out a zip operator similar to Python's, because I didn't find one in std. It allows to use range-based for loops to iterate at once over several equal-length containers (arrays, counters... anything that has an iterator and a static length). It should be safe (never exceed the iterator's capacity), be able to...
I made this encryption program in Python. I don't have much experience (or any experience at all) about encryption (since I just gave my 9th grade finals), but I had this idea about an algorithm some time back which would enable the user to encrypt words following an algorithm where the program would follow this proces...
I'm developing a Rust library that implements JSONSchema validation (Drafts 7 fully works at the moment). I have Rust-specific questions and concerns about my implementation. It works by compiling the input schema first and validating the data after it: use jsonschema::{JSONSchema, Draft}; use serde_json::json; let sc...
I was working on a code challenge with the following description: Given an array of positive or negative integers I= [i1,..,in] you have to produce a sorted array P of the form [ [p, sum of all ij of I for which p is a prime factor (p positive) of ij] ...] Example: I = [12, 15]; //result = [[2, 12], [3, 27], [5, 15]] ...
Introduction I am developing a dynamical system simulation/animation framework, which provides three abstract base classes, DynamicalSystem, Visualisation and Animation, from which clients can derive concrete classes for the purposes of animating dynamical (physical) systems in 3D (and 2D). The DynamicalSystem abstr...
I have a college assignment to implement a class called sorter, whose object is a sorted vector (the user is allowed to sort it by the method he/she desires). I have been able to implement it as following. Please review it and suggest me the changes I should make to make it efficient. template <typename T> class Sorter...
I've wrote a piece of code today that really make me sick about: if ( account.plan_id ) { const featuresToCheck = []; for (const vertical of Object.keys(account.account_settings.enabled_features)) { for (const feature of Object.keys(account.account_settings.enabled_features[vertical])){ feat...
I've created the following program to assist me in some template stuff I'm working on. The function get_type returns 0, 1, 2, 3 or nullopt corresponding to which group the argument T belongs to. This is my first template style project, so I'm looking for any critique possible. (Note the functions are marked static inte...
below code takes data (email,password,user type) from $_POST[] and use them to search whether a user exists on the database. If yes sends a JSON object to the client and also stores cookies on the browser. I have two user types and have them stored in two tables in my database. User_Table Driver_Table I need to chan...
I wrote code that stores an AWS Organization tree in a tree data structure in Rust. From the tree, I use a slightly modified preorder traversal algorithm to print all of the accounts in the organization in a table, while keeping track of all ancestors for each account. AWS Organizations are composed of a root organizat...
What do you think about this helper class to specify UTC time? It should also support an easy way to capture current time offsets. Let's say we expose it in API like this: interface IApi { void Start(Utc at); } Now it should go as: api.Start(new DateTime(2021, 01, 01)) // starts on 2021-01-01 UTC api.Start(new Tim...
I have two lists which are also having some duplicate elements , i am converting this list to map as key value pair with element index as the value for the key - element List 1 : [1, 2, 3, 4, 5, 6, 7, 2] = > MAP 1 (Map, List>) : {1=[0], 2=[1, 7], 3=[2], 4=[3], 5=[4], 6=[5], 7=[6]} List 2 : [3, 3, 2, 4, 7] = > MAP ...
I made a struct that will loop through a list, and return the next element on calls to the Get() method. It also allows to remove elements from the list by calling the Evict() method, and is safe for concurrent use. I'd appreciate any feedback: what's ok, what's not, what could be improved or changed. package generator...
I have written an automatically encrypting text editor (github link). The reasons that I wrote this program instead of using vim + gpg are: It's more convenient than vim + gpg (user only needs to enter password once). It's more secure than vim + gpg (see CVE-2010-2547 and CVE-2019-12735). User cannot accidentally cha...
Inspired by this question on Puzzling.StackExchange, I've decided to write a small python script that determines if a word is a BFF Word. Below are the parameters, solved by Puzzling user Stiv, also discussed in the program module docstring: If you remove two letters, you are left with an anagram of an animal which is...
ERROR: type should be string, got "https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/\n\nGiven an array of integers nums and a positive integer k, find whether\n it's possible to divide this array into sets of k consecutive numbers\n Return True if its possible otherwise return False.\nExample 1:\n\nInput: nums = [1,2,3,3,4,4,5,6], k = 4\nOutput: true\nExplanation: Array can be divided into [1,2,3,4] and [3,4,5,6].\n\nExample 2:\n\nInput: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3\nOutput: true\nExplanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].\n\nExample 3:\n\nInput: nums = [3,3,2,2,1,1], k = 3\nOutput: true\n\nExample 4:\n\nInput: nums = [1,2,3,4], k = 3\nOutput: false\nExplanation: Each array should be divided in subarrays of size 3.\n\n\n\nConstraints:\n\n1 <= nums.length <= 10^5\n1 <= nums[i] <= 10^9\n1 <= k <= nums.length\n\n\nPlease review for performance.\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace ArrayQuestions\n{\n /// <summary>\n /// https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/\n /// </summary>\n [TestClass]\n public class DivideArrayinSetsofKConsecutiveNumbersTest\n {\n [TestMethod]\n public void TestExample()\n {\n int[] nums = {1, 2, 3, 3, 4, 4, 5, 6};\n int k = 4;\n Assert.IsTrue(DivideArrayinSetsofKConsecutiveNumbers.IsPossibleDivide(nums, k));\n }\n\n [TestMethod]\n public void TestFailed()\n {\n int[] nums = { 1, 2, 3,4};\n int k = 3;\n Assert.IsFalse(DivideArrayinSetsofKConsecutiveNumbers.IsPossibleDivide(nums, k));\n }\n }\n\n public class DivideArrayinSetsofKConsecutiveNumbers\n {\n public static bool IsPossibleDivide(int[] nums, int k)\n {\n if (nums.Length % k != 0)\n {\n return false;\n }\n\n var dict = new SortedDictionary<int, int>();\n foreach (var num in nums)\n {\n if (!dict.TryGetValue(num, out var value))\n {\n value = dict[num] = 0;\n }\n\n dict[num] = value+1;\n }\n\n\n for (int i = 0; i < nums.Length / k; i++)\n {\n int start = dict.FirstOrDefault(x=>x.Value >0).Key;\n dict[start]--;\n for (int j = 1; j < k; j++)\n {\n if (!dict.ContainsKey(start + j) || dict[start + j] < 1)\n {\n return false;\n }\n\n dict[start + j]--;\n }\n }\n\n return true;\n }\n }\n}\n\n"