instruction stringlengths 71 95.1k |
|---|
I've been interested in making fully repeatable, reproducible game states. This led me into the world of DDD, and specifically, the concept of Aggregates + Event Sourcing (although that's not necessarily a DDD concept). In this context, the state of the Aggregate is reconstituted from a sequence of Domain Events, each ... |
My code currently:
import os
import pandas as pd
from selenium import webdriver
from tabulate import tabulate
from datetime import datetime
import time
from bs4 import BeautifulSoup as bs
start = datetime.now()
browser = webdriver.Chrome()
class GameData:
def __init__(self):
self.date = []
self... |
This program tokenizes an arithmetic expression specified in infix notation. It is one of my personal projects and I would love to receive expert advice.
After compiling, you can run the program with one command-line argument:
$ tokenize <arith_expr>
This is an example of running the program:
$ tokenize "3^2 + 4.5 * (... |
This is an algorithm regarding the RKF method:
import numpy as np
class rkf():
def __init__(self,f, a, b, x0, atol, rtol, hmax, hmin):
self.f=f
self.a=a
self.b=b
self.x0=x0
self.atol=atol
self.rtol=rtol
self.hmax=hmax
self.hmin=hmin
def solve(se... |
I am working on a small side-project since a couple of weeks, I am using Flask but trying to use as few libraries as possible and no ORMs (for learning purposes.
I am currently working on the User service on my application and currently stuck in the registration email confirmation part regarding my design.
Since I am n... |
I wrote below piece of code generating dummy data loaded to MongoDB.
2 issues :
1.customer class has subscriber class so it nested with one level customer--> subsciber.
I think i'm not doing right:
self.subscriber = Subscriber().returnJson()
it does working ,
but what if need to add another class under subscriber? it ... |
What do you think of the following function to offer an alternative to fgets, looking for insights about portability, safety, readability and performance:
#include <stdio.h>
#include <errno.h>
int sc_gets(char *buf, int n)
{
int count = 0;
char c;
if (__glibc_unlikely(n <= 0))
return -1;
whil... |
I made myself a function to check if a string is a path or an URL:
import os
def isPath(s):
"""
@param s string containing a path or url
@return True if it's a path, False if it's an url'
"""
if os.path.exists(s): # if a file with name s exists, we don't check any further and just return True
... |
Problem
Output a receipt of purchased items. Inputs:
products_text_path: Products are found in a text file in <barcode>:<name>:<price> line format.
purchased_items_set: The purchased items are given as a list of integer barcodes. Same item be found several times.
discount_rules_text_path: There are discount rules in a... |
This is meant to be a drop in replacement for getline as it's not crossplatform.
I am trying to do as minimal work as possible in here including only calling strlen once at the very end to calculate the size of the final block.
returns -1 for error, 0 for EOF, 1 for success
The way it works it by setting the last two b... |
I am coding a JS Mandelbrot Set viewer and am looking for suggestions on how to improve my code.
I already did some cleanup and got the execution time from 7s to about 160ms on my computer.
Some info about my Code:
Complex numbers are stored as an array where the first number is the real part and the second one is the... |
I've just taken the leap over to RTK instead of 'vanilla' redux and am blown away by how much less code I need to write. I'm not entirely sure how to structure my slices, however, and figured I'd ask for a small code review so I do not accidentally start breaking conventions from the start. This is how one of my slices... |
I'm trying to practice some functional techniques. I haven't worked much in Haskell, so any language-specific tips would be very appreciated, but what I care for even more are general tips towards my approach that I can carry between functional languages. Performance is not a big concern of mine right now.
I implemente... |
I want to solve the following task --- I am given a vector of integers. I want to 'compress' this list, where the elements will be replaced with numbers 0 through n - 1, where n is the number of unique elements in the vector, such that the relative ordering among the elements is preserved, i.e., if previously vector[in... |
I am on my second iteration of the famous "Number Of Islands" graph problem on Leetcode.
https://leetcode.com/problems/number-of-islands/
Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting... |
I'm working on a project of mine which required multiple calls to strncat(), and it came to me that it'd have been much easier if C also had something like "file://" + getenv("HOME") + filename for string generation. So I built a function that works in a similar fashion, it is a variadic function, the arguments are NUL... |
I tried to make a Pong game in Java. It's my first game I have ever programmed, and I would be very pleased if you would take the time to advise me on what I could do better next time. Thank you so much :) .
Here is my code:
Start.java:
import java.awt.EventQueue;
public class Start {
public static void main(String[]... |
This is my first post on this forum. I have read the guidelines and will try to adhere to them, but I apologize if I miss something. The code I am posting is intended to duplicate the output of "date -u" in the XV6 OS. It does this, with the exception of dates before the 1700s (This wasn't relevant to the task, and t... |
It's been a while I have been on here and I hope I still understand the rules.
I have recently started learning PHP and WordPress for a Whatsapp Chatbot integration.
I have created a webhook on my WordPress site that returns a JSON, which is consumed by Google Dialogflow(Chatbot engine).
For example, my webhook returns... |
I wanted to have a function called timeit which can measure the time of execution of n iterations of any other function. I still learning C++ but I come up with that : Any thought ?
#include<chrono>
using namespace std;
template<typename output, typename ...ArgsT, typename ...Input>
double timeit(output (*function)(I... |
I am writing a simple wrapper around fetch.
async function apiCall(
endpoint: string,
{
data,
headers: customHeaders,
...customConfig
}: { data?: Object; headers?: Object } = {}
) {
const config = {
method: data ? 'POST' : 'GET',
body: data ? JSON.stringify(data) : undefined,
headers: {
... |
After a bit of struggling I've come up with the code
import discord
import os
import subprocess as sub
import psutil
client = discord.Client()
my_path = os.getcwd()
program_instance = False
currently_installed = os.path.isdir("web-application")
def run_command(command):
value = sub.Popen(command, stdout = sub.P... |
I have implemented a custom concurrent queue on top of GCD which offers two additional pieces of functionality:
Limit the maximum number of concurrently executing tasks.
Give manual control over which enqueued task is scheduled for execution next.
An OperationQueue could of course address the former but gives no cont... |
The code below is a Python module to flatten JSON-like structure (nested dictionaries and lists) to a single string. It also provides partial result in the form of flat list of strings. This flattening is intended to be used to generate commands for the command line variant of the Check Point Management API: https://sc... |
I want to determine the number of distinct subarrays that can form having at most a given number of odd elements. Two subarrays are distinct if they differ at even one position. The subarray is a contiguous position of an array. Please give some suggestions to improve the time and space complexity.
Exp1:
Input: nums = ... |
import csv
class CSV:
def __init__(self,title, row=[]):
self.row = row
self.title = title
def create(self):
csvfilename = "{}".format(self.title)
csvFileObj = open(csvfilename, 'w' , encoding='utf-8-sig', newline='')
csvWriterObj = csv.writer(csvFileObj)
csvWriterOb... |
I found this interesting challenge in Exercism.
This is my approach to comparing poker hands in Rust. I've strived for code clarity.
I wish I had figured out how to only implement Ord or PartialOrd, in the end I had to implement both for all structs.
It would be nice also if I had a way to avoid using the rank associat... |
So I'm very new if JavaScript and my question is this a right way to implement this functionality? How could I improve this code.
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
let correct... |
I need help to format all the input values to the format ‘##-##/##'.
My input might include whole number, fraction or mixed fraction...Sample input 3, 1/1, 1 1/2. I have tried the below code it is giving expected result. Can someone please help for a standard and concise way of doing this
using System.IO;
using System;... |
I'm a Haskell beginner and trying to hone my skill by solving algorithmic problems. Here's what I got for maxheapify from Introduction to Algorithms
ixParent :: Int -> Int
ixParent = floor . flip (/) 2 . fromIntegral
ixLeft :: Int -> Int
ixLeft = (*) 2
ixRight :: Int -> Int
ixRight = (+) 1 . (*) 2
maxHeapify :: (Sho... |
I'm making a user interface for an online coffee shop. I need to call methods that have already been created. The user is also able to make customisations to their drink order such as a different choice of milk, brown or white sugar etc. Once the user choice has been made it will add the drink to their basket. The user... |
The integration field needs to get recalculated every time the starting or goal coordinates change. I wanted to use the flow field algorithm for a problem that includes bigger mazes with changing starting or ending points every 0.5 seconds. Right now the algorithm is far too slow to be useful because the integration fi... |
This is my third day of learning Javascript through an online class. I learned about arrays and while/for loops today, and to practice all of that stuff the challenge I'm working on is to make a function that produces \$(n)\$ terms of the Fibonacci sequence in an array.
So I'm hoping for some feedback on this code! I t... |
I have to do a program in PHP that reads IGC files like this IGC file and gets records about the glider.
For now I came up with something like this:
<?php
class Pilot {
public $name;
public $gliderType;
public $competitionId;
public $gpsDatuml;
public... |
I have a code that does applies Dijkstra's algorithm for an adjacency list.
The data are taken from a file. In the file, the first line contains the number of vertices and edges, and the remaining lines contain three elements each (the first 2 are the numbers of the vertices and 3rd are the weight of the edges).
The ou... |
In the early days of Basic (1970's when i started coding) the midStr() function used left and right positions directly rather than left and length we now use with mid(). I always found it more efficient in my mind to code using the old midStr() method, so I finally just created some code to do it. It's certainly not as... |
//MEM = initial memory, INDATA, the actual floating point value
#define atomicAddFloatX(MEM, INDATA)\
{\
float data = INDATA;\
float prev_mem = uintBitsToFloat(MEM);\
float exchange_mem = prev_mem;\
float input_mem = (data + prev_mem);\ //initially this is what we assume we want to put in here.
wh... |
I have been trying to improve my Python coding and was just wondering if there was a more pythonic way to perform what I have done so far, namely around the date in the main() function.
import datetime
import sybase
account_list = []
def get_date(): # Date -1 day unless Monday then -3 days
d = datetime.date.today... |
I'm writing a code where a class member, if != -1, set its own position at array. If the value is == -1, the next free index (whose range is 0 too array's length) is used. In this review, I'm more interested in the algorithm, making it faster, accurate and readable than anything else. despite I'm using C#, I'd like to ... |
So in my free time, I made a discord bot to play around with and learn a bit of python. I'm mainly a java developer. The bot has a few commands that allow it to find and output recipe for cocktails and a few other things revolving around cocktails.
In the background, there are 2 JSON files. My bot mainly reads and filt... |
I need to store sensitive strings in DB, so decided to encrypt it in a DB and decrypt it at the application layer. And noticed that it is not so easy to find ready to use an example. Please check my code below. It is based on this damienbod's topic, but I included IV to the string itself and also want to know if it is... |
I'm building a very simple Lisp interpreter. Similar to the the one from here. Here is what I have so far for the parsing part, that is, everything from "text is passed to the the program" to "ast is built". How does the below look? What can be improved? The hardest part for me was the recursive read_from_tokens functi... |
Goal
In the vector x, I would like to insert the elements of the vector values at indices stored in vector positions. Note that the vector positions is not sorted.
For example, from the following input
std::vector<char> x = {'H','e','l','l','W','o','l','d'};
std::vector<char> values = {'r','o'};
std::vector<size_t> pos... |
To find neighbors of a vector and return array of Vectors which are neighbors of a Vector:
vector<XY> neighboursOf(XY coord){
short x = coord.x;
short y = coord.y;
vector<XY> neighbours;
neighbours.reserve(9);
neighbours.push_back(XY(x-1, y));
neighbours.push_back(XY(x-1, y-1));
neighbours... |
For a project I have a large dataset with a multitude of variables from different questionnaires. Not all variables are required for all analyses.
So I created a preprocessing script, in which subsets of variables (with and without abbreviations) are created. However it gets confusing pretty fast.
For convenience I dec... |
I'm just starting to learn website coding with html, css, and JavaScript. To get a bit of a hang for it, I'm trying to build a complete web page.
So far, I've only done the navbar. I started with a basic Bootstrap 5 navbar and modified it to get it to look and behave like I want. It took me three days, but it looks goo... |
This is a follow up of Skyscraper Solver for NxN Size Version 3
I know its getting old...
So I still have the same Issue the code is to slow to solve bigger skyscraper puzzles.
Since the last Version I made the following improvements:
-Implement Class ClueHint direktly with Fields
I removed unecessary std::optional in... |
Here is the problem.
Repeatedly ask the user to enter game scores in a format like team1 score1 - team2 score2. Store this information in a dictionary where the keys are the team names and the values are tuples of the form (wins, losses).
Here is my Solution, what can I change for the better in it?
number_of_games = in... |
My code currently doesn't insert data into MySQL fast enough. However I don't know how to measure the current speed.
def insert():
mycursor = mydb.cursor()
plik = input(":::")
agefile = open("C:/Users/juczi/Desktop/New Folder/" + plik, "r")
sql = "INSERT INTO wyciek (nick, ip) VALUES (%s, %s)"
... |
I implemented the iterative randomized depth-first search, with my goal for it to be performant, and have code that made complete sense.
It utilizes AtomicReference<T> inside of Cell to keep track of it's walls (as multiple cells can share walls). The randomization does not utilize Java 8 streams at all.
AdjacentDirec... |
I've recently started learning Python again after a long time away from it and doing MATLAB at university. Today, I spent some time working on a first little project of mine. Right now it works as it should minus ending the game when all the fields are full. I would love to get advice on how I could improve the code an... |
In my data I have few hierarchy values - example address
Name -> Street -> City -> County -> State -> Country
The validation I need is: if a value in the above hierarchy is present, then all the previous/higher order values should be present.
Below is a valid case
Name -> Street -> City -> State
This is valid even t... |
See code below and my comment with questions:
pub fn factors(n: u64) -> Vec<u64> {
let mut m = n; // is it possible to convert n to a mutable type without using another variable?
let mut a:Vec<u64> = Vec::new();
while m % 2 == 0 {
m /= 2;
a.push(2);
}
// in C we can just write for (i... |
I'm new to C# and would appreciate any feedback you might have on the following doubly-linked list implementation, particularly WRT the following language features:
Exception handling
Debug.Assert
Null state attributes (e.g. MaybeNullWhen)
The Try pattern with out params
Test style with xunit
Anything else that looks ... |
I would like to get some feed back on my code; the goal is to get all agencies address of banks. I wrote a pretty simple brute force algorithm.
I was wondering if you would have any advice to improve the code, design it differently (do I need an OOP approach here) etc .
import requests
from lxml import html
groupe = "... |
This is my implementation of the divide-and-conquer Quicksort algorithm using the Lomuto partition scheme in C. This is part of a personal project and I'm following Linus Torvalds's coding style.
void swap(int *i, int *j)
{
int tmp = *i;
*i = *j;
*j = tmp;
}
int partition(int *arr, int l, int r)
{
int ... |
If used right, strcmp is not dangerous. However the code calling it might be. Limiting the opportunity for bugs I might in large teams "dictate" some kind of preemptive strike against bugs from bad calling code. It seems problem number one is comparing not zero-terminated strings. The core of my solution so far is this... |
I made simple interpreter in C and now, I want to make my code better.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include "def.h"
int main(int argc, char *argv[])
{
int i;
char ch[100];
char input[100];
char sinput[100];
char output[100];
i... |
I wrote my own dynamic array library for C as I was not happy with the others I found. It is very crude but the basic logic should be correct, it mainly revolves making realloc easier to use and avoiding repetitive code.
Please offer your suggestions and criticisms!
#include <stdlib.h>
#include <string.h>
#define DYNA... |
In my real case I have a set of time series related to different IDs stored in a single DataFrame
Some are composed by 400 samples, some by 1000 samples, some by 2000.
They are stored in the same df and:
I would like to drop all the IDs made up of time series shorter than a custom length.
I wrote the following code, bu... |
I wasn't sure about how to name it, maybe "follow_ptr", "self_updating_ptr", or "stalking_ptr" or something on those lines. For now it's called Identifier.
What I'm trying to achieve is a pointer wrapper which will always refer to the same object even when that object is moved in memory (vector resizes is a quite frequ... |
This is a steganography tool enabling you to conceal any file within a PNG file. In order to compile the program you need libpng to be installed on the system. It is one of my personal projects and I would love to receive expert advice.
Running
Hide message in PNG file:
steg -h <file_in> <png_in> <png_out>
Read messag... |
I'm practicing refactoring and Java 8 with very simple examples of Powerball.
I used LottoRank enum to write a function that returns the matched LottoRank based on the number of matches and bonus balls.
The 1st place is when you hit all 6 numbers.
The 2nd place is when you hit 5 with bonus ball.
The 3rd place is whe... |
I been trying to implement a text processor in JavaScript that can handle 4 different types of operations: append, backspace, undo, redo.
The input for this text processor is an array of arraries of a single element or tuples. For example:
const input = [['APPEND', 'Hey'], ['APPEND', ' there'], ['APPEND', '!']]
tex... |
As a Haskell beginner I'm currently playing around the IO monad and prepared simple program which gets from the user two information:
URL (http)
Output file path
Then it performs GET request to the provided URL and stores the result in the selected file. HTTP status code of the response is displayed on the standard o... |
I would like to generate Millions of Random String and Hashes in Java fast as possible. For the moment, @Turing85 gave me a pretty good code who was pretty fast only 5 sec for 50M of random String but the next problem to which I am confronted is the slowness when I hash my passwords in my String. The only problem is th... |
I implemented a convenience class to time code execution and print it to the user. This is part of a bigger project that will be distributed to external users. The timer however is only called by other procedures, not by the user directly. I was interested in implementing this myself, so I'm not looking for an external... |
I'm beginner on doing programming and just started learning C language. Then, i decide to make Tic-Tac-Toe as my first program.
My Tic-Tac-Toe summary: User can choose whether want to play 2 player or against computer. For computer player, i use Minimax Algorithm so it's not easy for user to win, whether they choose to... |
I have a Scrabble game program which takes two players' words and calculates who has the winning score.
Whichever player has the highest score is the winner; there's a tie if the scores are the same.
It all seems to work how I have written it; however I am sure it can be done better. Just wondering if anyone could give... |
I am fairly new to C++ and I was wondering if there is anything I can improve in this code(perf, readability)? Thanks. This is the full code: Github Link
I will post the parser that creates a rpn representation of an input string and a function that evaluates the rpn here(the rest is on the github):
#include <iostream>... |
I have written a Common Lisp implementation of Scheme's s-expression comments (SRFI 62):
(eval-when (:compile-toplevel
:load-toplevel
:execute)
(defun handle-s-expression-comment (stream char n)
(declare (ignore char))
(when n
(error "Infix parameter not allowed in s-expression ... |
How could i improve the following code. This part was easy to implement but there is a lot of redondancy and i use pandas to return as dict which seems quite odd.
def pipeline_place_details(place_id, fields, lang):
"""Return a dataframe with useful information
Args:
place_id ([string]): Id retrieved fr... |
I'm trying to make a console application to sort and delete duplicate image files. I have a folder with about 20000 images which take up roughly 70GB of space.
I wrote the following script and it seems to work fine, but the issue is that my PC runs out of available RAM memory (it has 16GB) without reaching halfway thro... |
I have a table data stored in a database ships.db,
the data are informations of tracked ships hourly.
The table data looks like this.
time | shipId | longitude | latitude
---------------------------------------------------------------------
00:00:00 1 xx.xxxx yy.yyyy
00:00:00 ... |
I am processing an unknown "length" of generator object.
I have to keep things "lazy" because of memory management.
The processing is compute heavy, so writing it multiproc style is the solution (or at least it seems for me).
I have solved this problem of multiproc on generator object with a combination of monkey patc... |
I'm trying to get a list of unique colors (rgba values) in an image. Here are my attempts:
# 1 - too ugly and clunky
all_colors = []
for i in range(width):
for j in range(height):
color = pix[i, j]
if color not in all_colors:
all_colors.append(color)
OR
#... |
Intended as a small project to test out various C++20 features, as well as learn a little bit more about matrices and their uses, I decided to implement a relatively simple matrix class.
After implementing it, I figured out that every single part of it should be able to be done in a compile time context, and re-impleme... |
This Python code
im_data = np.ones((100,100))
im_data[20:50,20:50]=np.zeros((30,30))
can generate a 2d array that could be used to create an image
plt.axis('off')
axi = plt.imshow(im_data, cmap='Greys')
I'm trying to do the same job with Java
class Arr100{
public static void main(String[] args){
System.o... |
I'm trying to build an email verification for user signup using CreateView. This view check whether the user is a new or already existing inactive user? and resend verification if the user is inactive.
Here's how I did it(email sending part),
views.py
class SignUpView(CreateView):
""" SignUp view """
form_cla... |
I'm teaching myself Object Oriented Programming in JavaScript and I'm looking over this small P5 code of CodingTrain's No.78, which deals with flying particles in the canvas, as a material.
The full code is below:
// Daniel Shiffman
// http://codingtra.in
// Simple Particle System
// https://youtu.be/UcdigVaIYAk
cons... |
While answering this code review question, I came up with a way to convert an equation given at runtime to a std::function<double(double)> that would evaluate that equation at a given point. Assuming the equation was already split into tokens and converted to postfix notation, this is done by evaluating those tokens li... |
I implemented tic-tac-toe in Haskell. I'm trying to incorporate suggestions from my last question (which mostly revolved around algorithmic logic) while trying something new - IO logic.
What kind of improvements could I make to this program? Am I being too tricky anywhere? Are there some built-in library functions that... |
Solving the merge intervals problem in golang(link: https://leetcode.com/problems/merge-intervals/).
The Problem
Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
Example 1... |
I'm just here for suggestions and code optimisations, what i could've done better, are there any better coding practices...
There's github repo link if you're interested in the code with a form too https://github.com/throtz/Operators
You basically have 2 textboxes in which you enter numbers and choose with a combobox w... |
I'm learning to code for about a year and recently I finished my Javascript project. It contains of 11 fairly simple apps involving using APIs and DOM manipulations
https://github.com/matt765/js
it's live here https://www.blackravenstudio.net/javascript/
I would gladly hear any opinions on my code. Next project I plan ... |
I start with an hourly table that has around 40 of items (example: bread, barley, bagels, beef, chicken). The purpose of my code is to aggregate this hourly table's numbers to daily numbers but broken out by a sublocation or "type". My only way to allocate to type is to use a table that shows the % breakdown of type to... |
The below is to parse a lisp expression (doing as much as possible in 'one go'). How does it look, and what can be improved?
# goal: capture the next token then get the rest of the line
# to be used in a while-loop/yield
tokenizer = re.compile(r"""
\s* # any amount of whitespace...
# 1. captur... |
This is a question from a CS diploma question set :
Make a program that will create an abbreviation of any given name using the initials. For example if the name if "John Doe", the program will output "J.D".
My Code:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *abbr (const char *s) {
int key... |
From a CS Diploma course question set:
Create a two dimensional array of ints, fill it with any random integers. Now find the minimum and maximum number, also find the index of those numbers.
I was not sure what they meant by "fill it with any random integers". Should I just use my imagination? Since I wasn't sure, I... |
I wrote this simple Makefile but it ended up like a spaghetti code. I used basename multiple times. I have a special case for first.spec.scala.run and follow.spec.scala.run and maybe more antipattern code that I am not aware of. I am not happy with my code and I appreciate any feedback or review. Thank you.
SPECS=First... |
A common preprocessing in machine learning consists in replacing rare values in the data by a label stating "rare". So that subsequent learning algorithms will not try to generalize a value with few occurences.
Pipelines enable to describe a sequence of preprocessing and learning algorithms to end up with a single obje... |
I made a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.
#include <iostream>
#include <algorithm>
#include <string>
#include <random>
#include <array>
#include <map>
#include <limits>
namespace
{
enum Winner { Tie, Player, Computer, WinnerCount };
enum Items { Roc... |
I am building a library to abstract DOM manipulation. Here's what the usage looks like:
vsAddToSection() {
let _inChapter: c.InChapter;
let v$sections = vmap([], _ =>
vh('div.section.item', {}, {
listeners: {
click: (e, __) => {
this.ctrl.inSection(_inChapter, _)
... |
I just learned about arraylists and I got a mission to build Mobile phone application with contact list when you can add \ remove \ modify \ search for contacts.
If you think I should add something to the code feel free to tell me :)
MobilePhone class
public class MobilePhone{
private String phoneNumber;
publ... |
I successfully solved a problem on Hackerrank called Contacts, but I'm curious if my code in C++ looks good to C++ developers. If not, how it should be improved.
Below is the short description of the problem and then the code itself.
Problem
Add name, where name is a string denoting a contact name. This must store nam... |
I tried implementing a thread-safe ring queue in C++. I'm totally new to move semantics and C++11/14/17 in general.
#ifndef THREAD_SAFE_RING_QUEUE_HPP_
#define THREAD_SAFE_RING_QUEUE_HPP_
#include <mutex>
#include <optional>
#include <vector>
namespace structure {
class MaximumCapacityReachedError : public std::runti... |
I want to ask question about a better way for implementing single endpoint REST.
I want to build a rest API but I want it to only have single endpoint like: graphql, where you only have like: host/graphql.
I already doing this example in laravel where you need to put a key and method to go to a certain API.
The body lo... |
For a project, I need to make use of Selenium WebDrivers, and since they're so expensive to start, I decided to write a pool to manage them.
with driver_pool.FirefoxWebDriverPool(5) as d_pool:
# Sequentially visit a page 1000 times
for _ in range(1000):
# Don't actually run this. I accidentally go mysel... |
Learning Modern C++ patterns and this ended up being the direction I went to to create an encapsulation of SDL's window management, while trying to stay with RAII practices. This is meant to be a base for a software renderer (and possibly expanding to OpenGL after that).
window/input.h
#pragma once
#include <map>
... |
The following is my attempt to implement a insert_sorted() C++ function that accepts any sorted STL container and item and inserts it at the right position in the container:
template<template<typename, typename, typename> typename C, typename T1, typename Comp, typename A, typename T2>
inline typename C<std::enable_if_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.