instruction stringlengths 71 95.1k |
|---|
I am starting to learn python and this has been my first project but I am not entirely happy, I think it could be done better. Could you help me? The strings are in Spanish but I think it does not harm understanding.
elegir_magnitud = int(input(
"""1 = Temperatura
2 = Longitud
3 = Masa
4 = Volumen
5 = Tiempo
6 = D... |
I'm parsing a file made up of various sections. I have a current_section variable that tracks which portion of the file I'm currently processing and the following check_for_next_section method that returns either the next section based on the contents of the current line or current_section if there are no matches based... |
Any advice on how to make this code; cleaner, more effective, just overall better!
Program has three options that can be passed int NewsId,Year and CategoryId. I collection all the data and then do additional filter base on the values that are being passed into the method.
public List<News> GetNewsbyYear(int NewsId, in... |
I am having a look at Rust, this is the first data structure I have tried to implement ( the standard library has a max-heap implementation, so this is a learning exercise ).
/// Heap is an array organised so the smallest element can be efficiently removed.
pub struct Heap<T>{ vec: Vec<T> }
impl<T: Ord+Copy> Heap<T> /... |
Problem :- Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Here is... |
This is an update to a question I posed nearly two years ago about my implementation of Huffman Coding which I had written in C. Since then I have had time to grow as a programmer and have managed to integrate most, if not all, of the suggestions given to me then and I am looking for fresh feedback on the current versi... |
I'm creating a basic Dynamic Array class in C++, and I'd like to know if there are any bugs/memory leaks I haven't noticed yet.
dyn_arr.h :
#ifndef DYN_ARR_H_INCLUDED
#define DYN_ARR_H_INCLUDED
template <class T>
class DynArr
{
public:
DynArr(uint16_t startSize = 0);
~DynArr();
T& operato... |
I was reading this question:
Why is my function timing out when run with a larger data set?
And although I couldn't quite grasp the OP's implementation and so didn't feel like answering.
I did some implementations of my own and created a benchmark for them.
Here is the problem definition:
There is a queue for the self... |
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
Given a rows x cols matrix grid representing a field of cherries.
Each cell in grid represents the number of cherries that you can
collect.
You have two robots that can collect cherries f... |
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Example 1:
Input: [[1,1],[2,2],[3,3]]
Output: 3
^
|
| o
| o
| o
+------... |
Background
I have a pipeline that I run and it spins up multiple EC2 instances that process many jobs. I noticed that in many parts of my pipeline i am downloading files from amazon s3 multiple times. I can save lot of time if i just cache them since after a certain stage in the pipeline those files are not updated but... |
In an attempt to solve a problem on Leetcode, I used dictionary and sets to have O(1) time complexity.
However, my speed is too slow, better than just the 5% of Python submissions.
Here is my code:
from typing import List
class ValidWordAbbr:
def __init__(self, dictionary: List[str]):
self.dictionary = ... |
I have created a simple bot using Discord.py which outputs the contents of text files which contain scraped sports fixtures and channel data (scraped data is received from other small scripts I created but haven't included here).
discordbot.py
import discord
import os
from dotenv import load_dotenv
client = discord.C... |
Not sure the best way to solve this using recursion. Below is what I have tried so far:
public static void findSum(int[] a, int sum, int i, int j) {
if (i == a.length)
return;
if (j == a.length)
return;
sum = (a[i] + a[j] > sum) ? (a[i] + a[j]) : sum;
System.out.println("Sum:" + sum + ... |
I have a nested for-loop that looks like the following. The for-loop is used to scan a spatio-temporal (3D) cube and run a specific kind of cross-correlation used in seismology.
# some initialization
i,j,k = np.where(Pg1t > 0.1)
qp = np.sum(Pg1t[:-1,20:40,20:40],axis = 1)/20
corr_arr_x = np.zeros((1750,384,384))
corr_... |
I'm writing a C application for the Networking course at the University.
Basically it's a UDP server that can receive two commands:
GET key
SET key value
That are executed against a Hash Table data structure.
I'm now writing the code that parses the string into a command struct, and the logic is the following:
A comm... |
My co-worker and I have been tasked with encrypting and decrypting text data using AES256. However both of us feel quite uncomfortable with this as this sits squarely outside our normal problem solving domain.
So first, the code we've come up with:
public class AesManagedTextEncryptionService
{
public byte[] Genera... |
I have the files "locale/{languageCode}.json" saved as part of the project, the reason that I made the read synchronous is because I think it is better that the internationalisation library I am using is initialised with the correct locale (rather than an async read, then dealing with promise resolution and updating th... |
I created a Python class called Score. I intend to use it to assign scores depending on two parameters.
the type of score, score_name, and
the user_input.
If I want to get the score of a loan term I will enter 'loan_term' as the score_name and 36 as user_input. The method Score.get_score then calculates the score and... |
Sometimes I need to push data to the array, but I have one different key (here I have key color and key name) and another part of the object is the same. I use IF/else to check this, but i wonder is there any better and cleanest way to handle this?
getData(passedData, dataControl: string) {
const data = [];
... |
I have written a Python scraping program, using the Scrapy framework. The following code reads a list of urls that need to crawled and gets product highlights from the list. It also follows the next page button.
The resulting products are automatically written to an output file, as I have set FEED_URI in setting.py (wh... |
I am return an student object from my database and I want to convert it into a StudentRecoredRequest model. The way i have implement is shown below. I was wondering if there was a nicer way to convert from the student object to studentsystemrecordrequest. Thanks
var result = await _context.Student.ToListAsync()... |
I have a class which uses the Azure SDK. The class has two constructors, shown in pseudo code below:
public StephensWorkerClass(){
this.azureClient = await getNewAzureClient();
} //normally used
//just for testing
public StephensWorkerClass(IAzure azureClient){
this.azureClient = azureClient;
}
In normal usag... |
I have an endpoint to retrieve the user's authorization based on Joseph Silber's Bouncer.
I have a global can() function. It creates a unique key based on the authorization request and sets an object's property based on that key.
can (ability, model = null, id = null) {
const key = `${ability}_${model}_${id}`
const... |
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
Given two words (begin and end), and a dictionary's word list,
find all shortest transformation sequence(s) from begin to end,
such that:
Only one letter can be changed at a time.
Each tr... |
I am currently taking back Python after over 6 years I do not use it, and to do that I am solving some small challenges on Hacker Rank. I wrote a code that works, but which is not performant and I would like to have some ideas to optimize it.
Problem statement
Given a certain string, count how many anagrams are possibl... |
I'm learning OOP and the first exercise of the course was to made a Stopwatch class. I did it really fast and decided to make an interface for this little app.
I created the interface. Basically I want to know if the aproach that I used is fine, if I needed to create another class to control the ui, etc. I'm really los... |
The code obtains Box and Cox transformed data. The original data is a Pandas DataFrame and the process uses this DataFrame.
I am trying to speed up the following code. If you can elaborate in faster way of doing this it would be very helpful.
import numpy as np
import pandas as pd
from numpy.random import randn
from sc... |
I've decided to learn python as my main language and after watching some tutorial on youtube I decided to write this blackjack game using OOP. Im sure it has a lot of beginner mistakes and might be simply bad. I also don't guarantee that it will always work but i would appreciate any feedback you could give me that cou... |
I am reaching my one year on programming and decided to create a simple pin and password program to better help me understand arrays. As far as coding standards, best practices, and functionality what else could I do to this to make it better?
public static void main(String []args){
choicePrompt(); // Prompt to c... |
The desire for such a function came out of the necessity of generating a "source" of Lorem ipsum by repeating over and over the same 50 or something paragraphs of the text.
Actually I am curious to know how to do it in C++ (I guess boost::hana has something to offer in this respect), and I have asked a question on Stac... |
Background and objective of the code
Based on this Dev.to challenge, I wrote the Python code below (TIO link also available).
The task was to return the least number of coins in a given denomination to from a specified amount of money. I generalised this into a function that gives all possible combinations of coins tha... |
This project is designed to enable clear-net browsing over the Tor network with the Lynx web-browser. Currently everything seems to be functioning as intended, however, it would be most appreciated if anyone could point out mistakes and/or ways that this project can be improved.
Questions
Are there any mistakes in th... |
I'm working on a bot that can use a wordlist to play hangman optimally as fast as possible. With the current implementation, the simulateGame function, which plays a whole game against the bot, takes ~500-700 microseconds to execute for the words I've tested, like "fatherhood", "esoteric", "joyousnesses", etc.
Wordlist... |
I wrote this piece of code which works as expected:
XElement theContentWhichIncludeBuilds = xDocument.XPathSelectElement($"//Project/Group").Elements()
.FirstOrDefault(e => e.Name== "Content" && e.Attribute("Included").Value == "buildings");
It targets all the Group elements under the Project nodes,
where its Conten... |
Yet another implementation of A* pathfinding. It is focused on:
Performance (both speed and memory allocations).
Readability and simplicity.
Well defined objects and methods.
Accordance with general conventions (naming, signatures, class structure, design principles etc).
Path is calculated on 2D grid using integer v... |
I'm working with Knockout3 in a Chromium 40 environment (ES5).
I have a series of preset difficulty options, and a player has an option to switch to custom difficulty and tweak the options. When they tweak an option the save button lights up and the player cannot proceed to start the game until they save their settings... |
I have recently been working through a number of the Cryptopals Cryptography Challenges to try and improve my knowledge and understanding of both cryptography and Python. As five of the first six challenges are XOR related problems I thought it would be a good idea to compile my work into a single program capable of en... |
I want to know if it is okay/safe to use a prepared statement and mysqli_num_rows like this:
public function getUnreadNumber() {
$userLoggedIn = $this->user_obj->getUsername();
// get_result for * and bind for select columns
// bind_result Doesn't work with SQL query that use *
$query = $this->con->pre... |
I Used MediaStore to scan and display media files from my storage using below code
private void displayAllVideos() {
Uri uri;
Cursor cursor;
VideoAdapter videoAdapter;
int column_index_data,thum;
String absolutePathThumb;
uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
String[] projectio... |
I'm looking to see if there are any better / faster ways of identifying table structures on a page without gridlines.
The text is extracted from the file and the coordinates of each block of text are stored in a dataframe. For the sake of this snippet, this has already been generated and has yielded the dataframe below... |
I'm building a functional React component that allows a list of products to be sorted by various properties. The properties could be top-level or nested properties. And I'd also like a sort order to be defined. As a secondary sort, I'd like a name property to be used.
I have left out the React parts to boil it down to ... |
I'm posting my code for a LeetCode problem copied here. If you would like to review, please do so. Thank you for your time!
Problem
Given a non-empty array of unique positive integers A, consider the
following graph:
There are nums.length nodes, labeled nums[0] to nums[nums.length - 1];
There is an edge between nums... |
I have the following code:
void record_preferences(int ranks[]){ // Update preferences given one voter's ranks
for(int i = 0; i < candidate_count; i++){ //Cycle through candidates
for(int j = 0; j < candidate_count; j++){ //Cycle through... |
Here is my simple model.
public class Product
{
public String Name { get; set; }
public int Price { get; set; }
public String Info { get; set; }
}
When I use this in viewmodel as following:
public MainViewModel()
{
Item = new Product() { Name = "Coffee", Price = 4, Info = "Coffe is hot" };
... |
Here is my solution to a series of problems in JS fundamentals. I've made it pass but I know this could be more efficient. I'm not looking for anyone to rewrite the code, but just asking what methods should be used when writing similar code in the future.
The goal is basically to input two parameters, both have to be p... |
I have been designing websites with Django for a while and I have also designed various sites. But here is a question that comes to mind at the beginning of any new project:
What is the best URLs architectural Design that creates both logical and meaningful URLs path as well as pluggable apps?
I will explain my questio... |
I've created a little class which helps me to generalize many query cases. I have a DbService and couple methods in it. Can you please take a look at it and share some criticism? The usage of that tool is really easy to me and I do wanna know how to make it safer and optimized.
public class DbServiceImpl implements Db... |
Please explain what I can improve, and why. I'm new to Python, Tkinter & Code Review, so I have a lot to learn. :)
I created a Tkinter app for user-input, and the same types of widgets are repeated on each row. A single row is similar to a slide in PowerPoint because it has an image, numbers, and input text. I will lat... |
This is my first F# program. It's a simple Rock-Paper-Scissors implementation.
I am looking for feedback of all sorts, e.g. the choice of types (e.g. List vs Array), whether there are parts that could be solved more elegantly / idiomatic, formatting, etc.
open System
let allowedActions = [ "r"; "p"; "s" ]
let randomI... |
I'm posting my code for a LeetCode problem. If you'd like to review, please do so. Thank you for your time!
Problem
A game on an undirected graph is played by two players, Mouse and Cat,
who alternate turns.
The graph is given as follows: graph[a] is a list of all nodes b such
that ab is an edge of the graph.
Mouse st... |
I'm relatively new to Scala and made a small TicTacToe in a functional Style.
Any improvement options would be highly appreciated.
There are some things which I am unsure of if they are made in an optimal way.
Error Handling in the readMove Function
If i should incorporate types like (type Player = Char, type Field = ... |
This is my first major project in F#, looking for any critique on how I can make it more standard or more concise.
Some things I feel like I could have done better are the command flag parsing and the actual crypto random generation itself. I do know that crypto generators are slower than pseudo rng but I figure that a... |
I'm writing an adjacency matrix, in this moment I'm trying to figure out how to indicate a default numeric value for an unassigned edge. There is the macro _I64_MAX but it is said that it's a bad practice to use macros. I wish to know if there's other way to assign such value (as a keyword as in the case of nullptr ins... |
I had an xls file with lots of full names in the following form at work:
+----------------------------+--------------+-----+-----+
| [Full name] | [More data] |[...]|[...]|
+----------------------------|--------------------------+
| Cristiano RONALDO | ... | ... | ... |
+--------------... |
For practice, I wrote some NASM code that prints out the hailstone sequence of a (unfortunately, hardcoded) number.
This is by far the most complex code I've ever written in NASM. I'd like advice on anything, but specifically:
I'm trying to abide by CDECL. Am I doing anything off?
The multiplication part seems overly ... |
Very simple square root calculator. I am sure it's terrible and can be made much better.
I feel it's way too many lines.
import random
## ask user for a number to find sq root for
num1 = input("Please enter number for which we'll find sq root:\n")
## generate a random number and test it
randomNum1 = random.randint(1,... |
I just finished coding a Tic Tac Toe game for my first Python project. I need some advice on things I can improve; please help. Everything seems to be running correctly. I used many functions. In the comments you can know what functions do; there is board initialization and prints the board out to the console checks th... |
I have a .tgz file that I need to download given a url inside a Testing folder and then decompress it. I am able to download the .tgz file successfully from the url and also able to successfully decompress it without any issues. My .tgz file will be approx 100 MB max. I am using SharpZipLib library here to decompress.
... |
I just finished my first project in Javascript. It takes an array of locations (with coordinates on position 6 and 7) as Input, then the first location is checked against all other locations. After that it takes the closest neighbor and adds it to the route. Then it takes the coordinates of the neighbor which it just f... |
I wrote a linked list class and don't know how to optimize it, please suggest some ideas for optimizing and fixing possible memory leaks.
#define indexTooLarge -1
template <typename T>
class LincedList
{
public:
LincedList(){}
template<typename... Types>
LincedList(T value,Types... values) : LincedList(val... |
I am trying to render in a leaflet map that should render a single marker. I am building the JavaScript as follows.
build the map
an even listener for when the user opens the page where the map is rendered.
I query as follows:
@company = Company.friendly.find_by(
slug: [ params[:id],
... |
Looks next nested if a little structure redundancy? Any better way for next nested if?
# !/usr/bin/python3
num = int(input("enter number"))
if num%2 == 0:
if num%3 == 0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3 == 0:
print ("divisible by... |
This is my C++ implementation of a Red-Black Tree, referring the CLRS book.
Half for fun, half for studying.
As implementing child node, I chose std::unique_ptr over std::shared_ptr because std::unique_ptr is cheaper/faster and the nodes are not shared across multiple threads with indeterminate access order. Of course... |
Goal:
I have thought of a project to create and came up with this goal of: "To record temperatures for different Fridges or Freezers."
Current situation
I have a working method to get data from html and send it to MySQL. But I feel like it can be simplified, as I have way too much code.
I'd like to see if anyone has di... |
Dole Out Cadbury
Problem Description
You are a teacher in reputed school. During Celebration Day you were assigned a task to distribute Cadbury such that maximum children get the chocolate. You have a box full of Cadbury with different width and height. You can only distribute largest square shape Cadbury. So if you h... |
As a first step into the world of Alloy, I've done my own version of the Fox/Chicken/Grain problem. I'd be grateful for any comments (also, is there a better place to do this?).
I thought it worth separating out the Farmer from the other items so I don't have to keep removing it from the set of items.
open util/orderin... |
We need to create a car with apiCar and log in two places CosmosDB and the logger, whether there is an error or not. Except if the error happens in Cosmos, in that case we only log in the logger. Finally, if there is an exception, any exception, we need rethrow it so the "MyFunction" caller can handle it.
This is my be... |
I'm quite novice here so apologies for any silly mistake in advance
I've been writing a simple tic tac toe game which is a part of my course in udemy
Since this is my first project, I want to do my best in order to learn new things besides learning how to code better. Generally, I want to optimize my code as much as po... |
I am trying to save a radiobutton string if it clicked. I am making a survey where I need to save a "yes" or "no" into a MYSQL table using volley. I am having a little trouble doing this and have tried to use the method below. Does anyone have any insight on how to do this? Right now I am
Please find my code below:
pri... |
I was cleaning up some old code and came across this (it's to read input from a terminal):
static public int read_input_key() {
/*
F1 ESC O P [27 79 80]
F2 ESC O Q [27 79 81]
F3 ESC O R [27 79 82]
F4 ESC O S [27 79 83]
Up ESC [ A [27 91 65]
Down ESC [ B [27 91 66]
Left ESC [ D [27 ... |
The previous code on codereview
I'm quite novice here so apologies for any silly mistake in advance
I've been writing a simple tic tac toe game which is a part of my course in udemy
Since this is my first project, I want to do my best in order to learn new things besides learning how to code better. Generally, I want t... |
I have improved my code since the last time asking for its review.
I'd like to know if it is up to the current standards.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
error_reporting(-1);
require '../../config/connect.php';
$con = new mysqli(...$dbCredentials);
$first_name = htmlspecialchars(trim(strip... |
Not sure if I am overcomplicating the requirement but this is what I need (for simplicity I will show a the List<Map<String, Object>> as a JSON):
[
{
"project": "Project1",
"workType": "Dev",
"taskTitle": "Dev Title 1",
"effort": 150
},
{
"project": "Project1",
... |
I've implemented a simple Maybe type around std::function that implements function composition where any function in the composition can fail (causing the entire composition to fail) - in essence, a Maybe monad where operator<< implements bind.
For example,
// one binary function that cannot fail.
std::function<int... |
I will describe two techniques, then the question will be how I can make an algorithm that is more efficient, if possible.
I want to find an efficient way to determine the squares where the pieces on a chess board can go. I want to start with a simple case, and just find the square where two rooks could move in an othe... |
I'm just trying to build a quick and crude error messaging system. It currently looks like this:
#include <exception>
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <map>
enum MsgTy {
OK = 0,
WARNING,
ERROR,
CRITICAL,
};
class FileWriter {
std::string filename... |
I'm working on a multivariate cross-entropy minimization model (for more details about it, see this paper, pp. 32-33). It's purpose is to adjust a prior multivariate distribution (in this case, a gaussian normal) with information on marginals coming from real observations.
The code at the end of the post represents my ... |
I've created a fake WeakReference class for VBA by chance. A Weak Reference is not counted (i.e. IUnknown::AddRef method is not called). I knew about the Weak Reference concept from Swift and I accidentaly read about a COM Variant.
In short, I am using a Variant (ByRef) to manipulate the first 2 bytes (var type) in a s... |
I made program for parsing CSV and XLS files, I just want to know if there is some space to improvement and is it all written good?
My goal is when I got CSV or XLS file to parse that file and got list of objects for specific class, besides of getting list I made metod to populate datatable and show data in DataGridVie... |
I am creating an \$O(n)\$ solver for an \$Ax = b\$ system where \$A\$ has the form
\$
A = \begin{pmatrix}
a_1 & b_1 &&&d_{u}\\ c_1 & a_2 & b_2\\& \ddots & \ddots & \ddots\\& & c_{n-2}&a_{n-1}& b_{n-1}\\ d_{l} &&&c_{n-1}& a_{n}
\end{pmatrix}
\$
To do this, I wrote a basic function that just performs Ga... |
My first attempt at a sudoku solver using the backtrack algorithm.
# Functions for solving Sudoku puzzles of any size
# NumPy makes it easier to work with 2D arrays
import numpy as np
def find_empty_cells(board):
"""Traverse the board and return a tuple of positions of empty cells"""
return [(i, j) for i in ... |
I am working on a little project where I need to scan all the files present in a folder on the disk and load it in memory. Below is my code which does that exactly and works fine.
Here are the steps:
On the disk there is already a default Records folder which has all the default config files present. This is to fallba... |
Here is a programming task:
Write a program with a function that converts a string of digits into an integer value. Do not use the strtol() function or any other standard C library function. Write your own!
I wanted this program to work perfectly with no errors. First I did the power function (power) and then next is... |
I am Relatively new to C, and did a calculator for my first year project. Could you guys, rate the calculator's efficiency and suggest some improvements?
Link to the previous version of this calculator: Math Calculator in C
Improvements added to this:
I did formatting from this website: https://codebeautify.org/c-forma... |
This is a personal project of mine. I made a simple seven day agenda program in Python that stores tasks as a string, saves it into a .dat file, and returns that task when you input a day of the week. This works on a terminal. I'm new to programming in general.
This is Python 3.8.2, 32 bit, and in a virtual environm... |
I'm working through Chapter 6 in "Automate the Boring Stuff, 2nd Edition." Here is the chapter project at the end.
Write a function named printTable() that takes a list of lists of strings and displays it in a well-organized table with each column right-justified. Assume that all the inner lists will contain the same n... |
I wanted to make an extremely light-weight logging system. What are your thoughts on this and what can be done to improve it?
First, the usage:
int main( )
{
logging::level = logging::fatal | logging::warning;
mini_log( logging::fatal, "entry point", "nothing", " is ", "happening!" );
}
Now, the code:
#if defi... |
I have implemented a bitarr class that does bit manipulations. I would love to know if there is any way to make the code more optimized. Any input would be much appreciated. Thank you! Note: int main() should not be modified.
#include <iostream>
#include <vector>
#include <climits>
#include <cst... |
I have come up with the following solution to find the maximum product for a contiguous sub-array:
def maxProduct(nums):
max_prod = [0]*len(nums)
min_prod = [0]*len(nums)
for i in range(0, len(nums)):
min_prod[i] = min(nums[i], min_prod[i-1]*nums[i], max_prod[i-1]*nums[i])
max_prod[i] =... |
I have solved the palindrome question on LeetCode today, but I wasn't happy with the original solution - I used strings, it worked slowly and used a lot of memory.
So I rewrote the answer using a dictionary approach instead knowing that looking up a value in a dictionary has lower time complexity than searching through... |
How to refactor this go code to make it more easy to understand and to maintain?
It is email sender worker-pool skeleton.
To understand the working-pool logic I coded it without real email client and database code.
To simulate the read from database, I used ints, taking them in random groups (0..6 items each) with rand... |
I am new in coding in React and I have just joined a new organization where I need to send my code for review .The functionality is working fine but it seems to me that code in my component has become very lengthy ,also my submithandler method is making me iterate the array a couple of times,I don't know how to do it o... |
I have implemented a neural network in C++. But I'm not sure whether my implementation is correct or not. My code of the implementation of neural networks given bellow.
As an inexperienced programmer, I welcome any and all insights to improve my skill.
#include "csv.h"
using namespace rapidcsv;
using namespace std;
c... |
Hello dear colleagues.
As an exercise for Java streams, I've written simple program, which scrapes links to references from a news portal. Basically, I wanted to find out, which portals are the most referenced.
Right now, I ended up with the following piece of code:
final Map<String, List<URL>> hostToURLs = Analyzer.ma... |
Consider the taxicab ring metric space shown below. This is a discrete metric space in which we have both a grid and concentric diamond rings. This metric space stretches infinitely in all four directions, but I have only drawn four rings.
I want to write a function that returns the shortest distance between any two po... |
I am making an OOP to calculate growth of money according to theory of interest. I have made 3 classes: Contribution which contain data of a deposit and its growth, InterestRate, and GrowthTL which means to calculate the accumulated value at the t_end of all contributions with applied, may be varying, interest rates. I... |
I have a simple localStorage cache class written in TypeScript, would love to have some insights on any way/aspect you think it can be improved (making it more readable, maintainable, usable, etc.):
export interface CacheItem<T> {
data: T;
expiration: number;
}
class SimpleLocalStorageCache<T> {
constructor(priv... |
Solved, question with improved code
I've created a simple npm module and CLI program to get the latest GitHub and Bitbucket release from their APIs using Node.js. Please tell me if there's anything to improve!
Module code:
#!/usr/bin/env node
const fetch = require("node-fetch");
/**
* @param {string} string
* @retur... |
So I'm making my own singly linked list class, with methods that you'd expect such as remove() and insert(). I don't use pointers that much (almost never), so I thought by making a SLL class it would be good practice for me. But I'm not sure if I'm deallocating my memory correctly.
Here's the structure of my SLL:
class... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.