instruction stringlengths 71 95.1k |
|---|
I have an image toggle triggered by button clicks and checkboxes. My code is currently working how I need it to, but I'm very new to JavaScript so I'm sure there is a cleaner way to do this.
The desired functionality is this: There are three images that need to toggle, a before image, after image, and a combo image. Th... |
On StackOverflow I have asked a question a few minutes ago, but then by trying a bit more, I found the answer myself, and I'm posting the resulting working code here for review.
What the code does, is waiting for, and repeatedly prompting the user to enter a character; when the user enters one, the program echoes it ba... |
I've been learning programming own my for a couple of years mainly using python, and
I've created a tetris-like command line game using Python's Curses library.
The game seems to function as intended; but I lack experience writing object oriented code.
So, I would like feedback about the code's structure, and assuming ... |
I am new in Python coding. I think the code could be written in a better and more compact form. It compiles quite slowly due to the method of removing stop-words.
I wanted to find the top 10 most frequent words from the column excluding the URL links, special characters, punctuations... and stop-words.
Any criticisms a... |
My script presents an options menu for scripts contained within the "options" folder. The user selects the scripts they want to run, and enters "start". This then starts the scripts in a specific order (not included) - the order the scripts are in the options menu.
I believe it can be a lot shorter, more appealing and ... |
I decided to try writing up a port scanner to develop my understanding of Scapy. Here's a timed example of its use. The first two arguments are the address and range of ports to scan:
>>> timeit(lambda: print(port_scan("192.168.123.123", range(15000), timeout=5)), number=1)
[80, 11111]
32.23571190000001
I've made naïv... |
This is my first post here and I hope I will get some recommendations to improve my code. I have a parser which processes the file with the following structure:
SE|43171|ti|1|text|Distribution of metastases...
SE|43171|ti|1|entity|C0033522
SE|43171|ti|1|relation|C0686619|COEXISTS_WITH|C0279628
SE|43171|ab|2|text|The a... |
Looking forward to get your feedback on my attempt to replicate vector class functionality. Especially I have doubts about copy constructor and resize methods. I think that copy constructor could potentially cause memory leak, but I don't know how to make it better. I implemented two resize methods and they both seem t... |
I used llbuild ninja build --profile PATH to create a JSON file of build summary in the following format:
{ "name": "Building a.c", "ph": "B", "pid": 0, "tid": 0, "ts": 19967021195},
{ "name": "Building b.c", "ph": "B", "pid": 0, "tid": 1, "ts": 19967021196},
{ "name": "Building c.c", "ph": "B", "pid": 0, "tid": 0, "ts... |
I'm new here, therefore I hope to be clear in this question. Firstly, I want to underline that I'm not a programmer, and I attended only a beginner course in Python, but I like to solve problems writing down some codes (using Python 3.8). However, here's my issue.
My task is to reproduce the plot below.
Where is this ... |
I have to send multiple HTTP requests where their payload will be different, type will be different, headers will be different, URL will be different etc. The code I have right now is
pub async fn make_login_request(
client: &Client,
host: &String,
credentials: &HashMap<String, String>,
) -> Result<(), reqw... |
The code reads all my routes and return to my AJAX request the names of the routes without duplicates and just those that have the "rt_" prefix.
class RouteController extends Controller {
public function getRoutes()
{
//Get all the routes.
$routes = Route::getRoutes();
... |
I have to iterate through multiple text files. For each file I read its contents and append each line to its corresponding dictionary to then build a JSON file.
Each text file has the following structure:
Line 1: The title key.
Line 2: The name key.
Line 3: The date key.
Line 4: The feedback key.
Here is an example o... |
I have the following basic code, which connects to a websocket server and receives some data:
import websocket, json, time
def process_message(ws, msg):
message = json.loads(msg)
print(message)
def on_error(ws, error):
print('Error', e)
def on_close(ws):
print('Closing')
def on_open(ws):
def run... |
I want to refactor this code but am wondering how I should start it. I'm not sure this code is totally against clean code or not. I'm thinking to use RxJS or a JavaScript builtin method. I'd like to have some help here to learn how to have clean code or how I can minimize the code to few line or chain multiple method o... |
I have a Type class that will have many instances. I get the instances from a web service. The Type class has a code instance field that uniquely ids an instance:
@Data
@AllArgsConstructor
public class Type {
private String code;
}
Ten of these instances identify a special type. I have several places where I need t... |
In my React app using Material UI, I wrote a code to manage the size of the fields of a contact form. Those fields are elements that can be added or removed depending on a configuration.
The code I wrote works as should be but looks ugly and I need help to make it better
let size = 12;
if (useMediaQuery(theme.break... |
I attempted an online Python test the other day. The function I wrote works fine however takes too long to complete.
Question:
From a list of numbers find the indexes of two numbers that total n and return as a tuple.
I tried using itertools but I don't know if there is a function that would out perform my original. ... |
I try to get location data by a external HTTP call. For this API, any part in the data can be missing. Initially I wrote the following code to check whether data.res.accounts[0].contacts[0].location exists:
const getLocation = async () => {
const data = await fetchLocation();
if (
data == null
data.res == n... |
Suvat stands for kinematics or
(s)displacement
(u)initial velocity
(v)final velocity
(a)acceleration
(t)time
This calculator can find the remaining 2 variables given 3 other variables!
Enter x on the variables which are unknown.
Ex:
Distance: 20
Initialvelocity: 0
final velocity: 10
acceleration: x
time: x
-Output-
Ac... |
So i made a program, which allows you to translate from one language to another using the command prompt.
I would like advice about the design, optimizations, and the tips and tricks to avoid repetition and writing effective code.
Code:
import requests
from bs4 import BeautifulSoup
import sys
class Translator:
#... |
For example, these are expected outputs:
3: 2, 1
4: 4
5: 4, 1
6: 4, 2
7: 4, 2, 1
8: 8
9: 8, 1
...
20: 16, 4
...
25: 16, 8, 1
...
36: 32, 4
...
50: 32, 16, 2
Up to the max of 32 being the largest subunit. So then we get larger:
100: 32, 32, 32, 4
...
201: 32, 32, 32, 32, 32, 32, 8, 1
...
What is the equation / algorit... |
I have a sample React app that loads a username and password, and then randomly provides a login result on submission for the sake of example.
CodeSandbox: https://codesandbox.io/s/stack-xstate-login-review-brvuu
This state machine makes use of always to check and transition between states (e.g., when validating userna... |
I have the following scenario .
I have incoming file download requests and each download is happening in different thread until pool size is exceeded. And after a download completed, a processor processes the downloaded item. So I created the following. I wonder if uses of thread and executors make sense
DownloadTaskP... |
I am making an hours calculator app. It takes a start time, end time and time taken for lunch.
For the start and end time it takes a four-digit hh:mm time. For example: 10:20.
I have made a function which converts the time into a decimal,
so 10:20 = 10.33. The function works, but I feel it looks a little heavy and wond... |
The recurring problem to assemble a network packet out of payload, sequence number, header, and other misc. information is mostly solved either on the heap (e.g. appending to a std::vector) or by first allocating a (hopefully large enough) buffer and then writing to that buffer. Some of the elements always stay the sam... |
A few days ago I wrote my first own Bash script - did some really small thing a few years ago - to keep my costs in check and get an overview over them. Therefore, I want it to include cost adding, viewing and changing.
It works the way I wrote it, but I am not really sure if it's the "best" way to do it.
Also I wanted... |
This is exercise 3.2.1. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Consider the following data-type implementation for axis-aligned
rectangles, which represents each rectangle with the coordinates of
its center point and its width and height:
public class Rectangle
{
private f... |
The idea is that, in my application I have 5 routines named long_process_1, long_process_2, long_process_3, long_process_4, long_process_5. These are each long calculations that would hang the GUI and can only be called in that order. When each result is ready, user input is required about the result. So we call ask_us... |
Here is my Relay Network:
async function fetchQuery(
operation,
variables,
) {
// hash graphql query for unique listener
const hash = await digestMessage(operation.text);
// send query to websocket
doSend(JSON.stringify({
message: 'request',
query: operation.text,
hash,
... |
I have an AD Group I keep up-to-date based on a CSV file. Users not present in the file should be removed from the AD Group.
#Import New List
$NewList= (Import-Csv E:\Group_Update\newlist.csv).SamAccountName
#backup old members
Get-ADGroupMember LAB_HR | select SamAccountName | Export-Csv E:\Group_Update\Group_B4_upd... |
I have declared a react hook which will contain an array of object as follows:
const [rowDataTracker, setRowDataTracker] = useState([]);
Now I need to update the hook to basically create a payload as the following:
[
{id: 100, payload: {field1: "value", field2: "value"}},
{id: 105, payload: {field1: "value", fiel... |
Script simulates the Martingale betting strategy of betting a fixed amount until a loss occurs, at which point the bettor doubles the bet to make up for the loss. This continues until a win occurs. After a win, the bet is reset to the original bet value. I set the odds to mimic Blackjack (49% chance of a win). For simp... |
I have a task that is quite simple: I need to get the sum of values in the categories of each ID, and keep the category with the highest sum:
id category value
1 A 10
1 A 15
1 B 13
2 A 80
So, in this case the sum of value for each category-id pair would be:... |
I have a pet project (open source on GitHub) that I built as a learning exercise. It is a lyrics web application built in .NET Core MVC.
On the artists page of the site (view on mobile size viewport, it is only optimised for mobiles so far), I list all artists alphabetically. The artists are grouped by letter.
The code... |
This is exercise 3.2.7. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Implement a data type for rational numbers that supports addition, subtraction, multiplication, and division.
Here is my program:
public class Rational
{
private final int numerator;
private final int deno... |
I have written the following basic assembly program to find the maximum number in a list divisible by a number. Here is what I have thus far:
# Program: given a list or integers and a factor
# Find the max number in the list that the factor divides
# For example: INPUT: [3,9,50,27], factor: 3 | OUTPUT: 27
.section .rod... |
Is this a good approach to replace mysqli_num_rows?
$db is a PDO instance. ..
$result = $db->query("SELECT * FROM users");
$result_set = $result->fetchAll();
$count = count($result_set);
if($count>0){
//if $count>0 show something special
while($row = array_shift($result_set)){
// my code
}
... |
I had a sample file with a long string >50M like this.
CACTGCTGTCACCCTCCATGCACCTGCCCACCCTCCAAGGATCNNNNNNNCACTGCTGTCACCCTCCATGCACCTGCCCACCCTCCAAGGATCaagctCCgaTNNNNNNNNNNNNGgtgtgtatatatcatgtgtgGCCCTAGGGCCCTAGGGCCCTAtgtgtgGCCCTAGGGCtgtgtgGCCCTAGGGCGGatgtgtggtgtgtggggttagggttagggttaNNNNNNNNNNNCCCTCCAAGGATCaagctCCgaTNNNNNNN... |
I'm relatively new to python and for an assignment I had to write a program that fetches a webpage with BeautifulSoup, extract all Paragraphs from it, and extract all words ending with "ing", and in the end save it to a file with the format "Word" + tab + "wordcount" + "newline".
This is my code so far. Is there a more... |
I don't know it is some design pattern for it or I can't do it in a different way the code looks like this:
Iteam iteam = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, countryCode, currencyCode);
if(item == null){
item = itemRepository.findByNameAndNoAndCountryCodeAndCurrencyCode(name, "... |
I am trying to solve Q645. While the logic used for my code seems to be appropriate, the code itself is way too slow for the large number required in this question. May I ask for suggestion(s) to improve my code's performance?
The question is as in the link: https://projecteuler.net/problem=645
My Python code is as fol... |
I'm working on some Python code and have a few functions which do similar things, and the only way I've found of writing them is quite ugly and not very clear.
In the example below, the goal is to compute the Kronecker product over a tensor chain of length M, in which the mth tensor is R and every other tensor is J.
Is... |
My mergesort implementation currently takes a very long time, for a list with 1 million elements it takes over 130 seconds to get the list sorted.
Could someone kindly have a look at my code and suggest what could I do to improve it?
Is there anything particular in my code that is taking significantly long?
Code
de... |
I am using ASP.NET Core 3.1 and have been assigned a task to verify the count of changes done using SaveChanges().
It is expected that the developer should know how many records will be changed before-hand when SaveChanges() will be called.
To implement it, I have created an extension method for DbContext called SaveCh... |
I am using the following script to fuzzy search almost similar book names for duplicate:
import re
from nltk.util import ngrams
OriginalBooksList = list()
booksAfterRemovingStopWords = list()
booksWithNGrams = list()
duplicatesSorted = list()
stopWords = ['I', 'a', 'about', 'an', 'are', 'as', 'at', 'be', 'by', 'com',... |
This is exercise 3.2.8. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a data type Interval that implements the following API:
An interval is defined to be the set of all points on the line greater
than or equal to min and less than or equal to max.
This is exercise 3.2.10. ... |
I have programmed a chess AI in python as a first project to learn both Python and the inner workings of a chess engine and wanted to have some input on syntax, code efficiency and any tips in general on improving it before moving on with the project. My goal is to train a neural-network and use as a evaluation functio... |
I intend to extract a URL search parameter value using a regular expression in plain javascript. The parameter can be in any order in the search query.
So is there a better approach than ?
const query1 = '?someBoolean=false&q=&location=&testParam=dummy_value&testParam2=dummy_value2&requiredParam=requiredValue';
cons... |
The following searches recursively for all the mark down files - i. ending with the extension .md - inside a folder. It then stores the text of the files in an array. Finally, it sums their word count using a wordCount() function (from the compromise package).
import nlp from 'compromise'
import fs from 'fs'
import pat... |
I've created a short Python script in order to do some analysis on network flows.
I have an inventory of networks (/8 to /30 masks) of medium size (around 10k references) that provide several information for each of my networks (physical sites, VRF (routing instances), etc.).
I then have some humongous flows data (mill... |
I've been taking cs50 for about under a month now and I've finally finished with "filter" in pset4. The code passes all the green checks on check50. Our task was to implement functions in helpers.c so that a user can apply grayscale, reflection, blur, or edge detection filters to their images. We were asked not to modi... |
Problem Statement/Context:
Represent a ray, given a origin and direction. Besides this a min_t and max_t value are defined. These values define a distance along the ray and make it possible to describe an intervall on the ray. The propose of the ray class is to support 2d ray tracing (a 2D ray tracer visualization tool... |
I've just started a course that will require knowledge and experience with Python for future projects, which I don't have, so I thought I'd give it a go to familiarize myself with it and get some feedback. I got a decent summary of the language's main features from a 2 hour long overview video (https://www.youtube.com/... |
I have the below function which populates different time-related case classes based on what is present in the JSON input.
def parseTime(timeJson: JsValue) = {
val day = (timeJson \ "day").getOrElse(JsString("")).as[JsString].value.toInt
val week = (timeJson \ "month").getOrElse(JsString("")).as[JsString].value.to... |
This code "poisons" the ARP cache of victim computers. Given the IP addresses of hosts A and B, it will trick A into thinking that you're B, and B into thinking that you're A. This means that all the traffic that they send to the other will actually be sent to you, and you can either consume that data (DOS), or forward... |
I've published a Vim plugin that nudges visually selected lines up or down, which for the most part seems to function as designed. However, I believe there are likely ways that this plugin could be improved.
Questions
How do I register a movement that takes an optional amount?
In other words how can this plugin dif... |
How can I rewrite this if statement of which there are a lot. Or how, in principle, it can be rewritten to look good? This app is calculator. How it can be redone with a switch maybe. Or breaking it somehow into small functions
function pressNumber(e) {
let digit;
if (typeof e === 'string') {
digit = e;
} ... |
I have invoice and code data in the below Dataframes
Invoices
df = pd.DataFrame({
'invoice':[1,1,2,2,2,3,3,3,4,4,4,5,5,6,6,6,7],
'code':[101,104,105,101,106,106,104,101,104,105,111,109,111,110,101,114,112],
'qty':[2,1,1,3,2,4,7,1,1,1,1,4,2,1,2,2,1]
})
+---------+------+-----+
| invoice | code | qty |
+----... |
Based on my googling around generic lists in C I stumbled upon tagged unions. What I wanted to create was a data structure that can hold int, float, double and char, all in one list. There is a function to add an item to which type information has to be passed. What I am unsure about: I read that casting void pointers ... |
The following source code is a solution to the Marching Square problem.
The explanation of using random numbers in ambiguous cases can be found here.
import numpy as np
from PIL import Image, ImageDraw
im = Image.new('RGB', (500, 300), (128, 128, 128))
draw = ImageDraw.Draw(im)
class Square():
A = [0,0];
B = ... |
I have rolled my own Java method for converting ints to the hexadecimal Strings:
import java.util.Arrays;
import java.util.Random;
public class Main {
/**
* Converts the input integer into its textual hexadecimal representation.
*
* @param a the integer to convert.
* @return the string re... |
This is my iterative deepening alpha beta minimax algorithm for a two player game called Mancala, see rules
The game and corresponding classes (GameState etc) are provided by another source. I provide my class which optimizes a GameState.
All criticism is appreciated.
package ai;
import java.lang.System.Logger;
import... |
This is almost exercise 3.2.14. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne (since I am self-studying, I changed it a little bit):
Develop a version of Histogram that uses StdDraw, so that a client can
create multiple histograms. Use a test client that creates histograms
for flipp... |
Please review my class which is responsible of serialization and deserialization of the StringTuple data class.
data class StringTuple(
val first: String,
val second: String
)
The idea is to serialize StringTuple to ByteArray in the following format:
| first string size | first string serialized | second strin... |
I have some code that has three lists, and it then checks the index of the second list against the index of the first as long as the first list has six elements. The code will then append to the third list if part of a string matches in the index of the first list. If the string does not match, it will append a message... |
I created simple export tool for my project. My requirments was to create one csv file for details of my hero which contains name, level, gold etc. And second file for list of items.
Both of files contains static header and generated Data.
First, let me share my model classes:
public class Hero {
private String nam... |
I use ngrx in my Angular app to state management. At a certain time I was asked to save some variable to local storage and retrieve it with first load.
That made sense to make it as part of the effects, instead of managing one logic for localStorage and another logic for the selectors. So this is what I did;
I extended... |
Description
As an exercise of learning go concurrency patterns, I decided too build a concurrent web crawler.
I made use of the argparse module I put up for review a while back.
I'm looking for feedback on my concurrency pattern, but any and all aspect of the code is open to be flamed :)
Code
package main
import (
... |
My requirement is to match each line of a text file, including the line terminator of each, at most excluding the terminator of the last line, to take into account the crippled, non POSIX-compiant files generated on Windows; each line terminator can be either \n or \r\n.
As a consequence, no character in the file shoul... |
I wanted to create a vector that can be used for different types, as generics do not exist in C.
I came up with an implementation that maintains a buffer on the heap and reallocs itself when the buffer size is exceeded. The heart of the implementation are the macros that can be used to retrieve and insert elements conv... |
UPDATED
I would like to create a class, which is intended to represent a field of values on a 2D grid. So, I would like to access the elements with a double square bracket A[i][j], and inside the __global__ or __device__ function access the dimensions of the field - nx_, ny_, because I do not want to pass them each tim... |
Goal
I have developed a random check that I have thought of. I have used purely JavaScript to get used to the language and learn it. I have also used JavaScript to create elements, classes, id etc... and at the end, I have a simple validation check to check if all inputs have been filled.
I would to soon improve the va... |
I've got a method, CheckForValue(), that uses named pipes to send a message to another process running locally, and then receive a message from that process, returning a bool indicating if it is equivalent with some value.
I'm concerned that I am not handling CancellationTokens and errors correctly. If there any errors... |
Split: Write a function split that takes a delimiter value “c” and a list “iL”, and it splits the input list with respect to the delimiter “c”.
Example output:
split 0 [1,2,3,0,4,0,5,0,0,6,7,8,9,10]
[[1,2,3],[4],[5],[],[6,7,8,9,10]]
My split function:
split :: Eq a => a -> [a] -> [[a]]
split a iL = let
h... |
How does the following program look to print a list of strings? What places can I improve? Are there easier ways to print something like a linebreak after each string rather than hardcoding the \n into the string itself?
# Program, print out a list of strings, one per line
.data
SYS_EXIT = 60
SYS_WRITE = 1
SYS_STDO... |
So this is building off of Algorithm for dividing a number into largest "power of two" buckets?. Here is a slight modification of the answer from there:
let numbers = [1, 2, 3, 4, 5, 6, 7, 30, 31, 32, 33, 20, 25, 36, 50, 100, 201]
numbers.forEach(n => console.log(`${n} =`, split(n).join(', ')))
function split(number... |
Splitting a string in tokens is a more complex topic than String.Split() wants to make us believe. There are at least three common policies according to which a string might be interpreted and split in tokens.
Policy 1: Equivalent to String.Split()
There is not much to mention about this policy. Given a string s and a ... |
I am currently learning Haskell and as an exercise, I am building a simple tic-tac-toe program. I start with
import Data.Vector
data Cell = Empty | X | O
type Board = Vector Cell
and then, to render the board:
render :: Board -> IO ()
render b = do
renderSep
renderRow 0 b
renderSep
renderRow 1 b
r... |
This is exercise 3.2.23. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a program that creates an array of charged particles
from values given on standard input (each charged particle is
specified by its x-coordinate, y-coordinate, and charge value) and
produces a visualizatio... |
I've created a simple function to work as a level, where the dot on screen is centered when the device is completely flat. It changes position based on device orientation. I use RxSwift to update the position of the dot. I'm relatively new to RxSwift, so I'm worried that I'm not using it correctly or to its full value.... |
I am not very fluent in C++ and want to construct a Kd-Tree in C++ based on this paper Efficient Locally Weighted Polynomial Regression Predictions, to use it to conduct some fast implementations of local linear regression . However, the speed for creating the tree and search( especially) is very slow. I have tried a s... |
My goal was to create a script that would:
Pull certain data from an existing SQLite table
Apply a simple mathematical formula
Save the new values to another SQLite table
I’m just starting to learn Python (programming in general) and to be honest a lot of that is unclear to me. But using the internet and a lot of exi... |
I was trying to do this question and I get TLE on one the test cases (the actual link to the question will ask you to login).
What is an inversion?
An inversion of an element is the number of elements to the left which
are greater. Sum of number of numbers throughout a segment is the
answer.
It is based on Segment T... |
Code functionality
The following code tests whether the values that a user specifies for a lower bound and upper bound on two properties:
The lower bound is smaller than the upper bound.
The values are larger than 0 (positive).
Since it first checks whether the lower bound is smaller than the upper bound, it implicit... |
Here is my code:
def printBoard(board): # this prints the board
print(" | | ")
print(f" {board[0][0]} | {board[0][1]} | {board[0][2]} ")
print(" | | ")
print("---------|---------|---------")
print(" | | ")
... |
I have been programming for about 4 to 5 months now and I made a login script with tkinter in python. I tried to use classes and function definitions as best as I could. To get to know them better.
I wanted to ask you all, how does this code look and is there something I should or shouldn't do the next time I code?
THA... |
I am aware, that libraries exist for parsing python code, however, for the sake of learning how they parse errors, I'm creating a script that checks a file for only 6 Pep8 errors just for reference.
This is how my current 6 Pep8 functions look (they append an issue to the issues list if the issue was found)
"""
[S001] ... |
I am using a Deep Learning model I trained and want to improve its accuracy by implementing a rolling average prediction. I have already done it but want to improve it as I am making predictions on every 3 frames.
Input:
Each index represents a class and the respective prediction the model makes.
Order is not alphanume... |
I've written a short script to print a number to a string. This actually was very difficult for me to do -- I'm not sure if this is actually a tricky task or just because I'm so new to asm I was having a hard time. Here it is:
SYS_EXIT = 60
SYS_WRITE = 1
SYS_STDOUT = 1
.section .rodata
number: .long 774728
.t... |
This is exercise 3.2.23. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a recursive Turtle client that draws dragon fractal.
The following is the data-type implementation for Turtle graphics from the book which I beautified:
public class Turtle {
private double x;
priva... |
The following code asynchronously extract title from URLs (saved in book-urls.txt).
from bs4 import BeautifulSoup
import grequests
links = list()
file1 = open("book-urls.txt", "r")
Lines = file1.readlines()
for line in Lines:
links.append(line)
file1.close()
reqs = (grequests.get(link) for link in links)
resp = ... |
I've created a Game of Life implementation in JavaScript with the goal of having it be as fast as possible, with the rendering I'm satisfied (see picture bellow), however the next state calculation is really slow and I'm out of ideas how to speed it up even more.
Current state of the implementation
Rendering
Screenshot... |
I have this program finding 2 numbers in the array (unsorted) so that its sum equal to the target sum. Here is my program:
vector<int> findNumbers(vector<int>& nums, int target)
{
vector<int> result;
for(int i = 0; i < nums.size() - 1; i++)
for(int j = i + 1; j < nums.size(); j++)
... |
My solution runs properly and I have tested it against various test cases. Is this the best approach?
#include<stdio.h>
#include<math.h>
int primefactors(int);
int main()
{
int num;
printf("Enter a no:-\n");
scanf("%d",&num);
printf("%d",primefactors(num));
return 0;
}
int primefactors(int n){
f... |
I'm quite new to object-oriented C#. I wanted to test my knowledge by creating a Dog/Animal classes. I also tried to implement an IDangerous interface in my code.
Is there anything I could've done better/differently? Again, this is my first time on this Stack Exchange so if I could've restructured this post differently... |
This is how I implemented the guessing game - chapter 2 of the Rust book.
use std::io;
use std::io::Error;
use std::cmp::Ordering;
use std::num::ParseIntError;
use rand::Rng;
enum MyReadLineError {
FailReadLine(Error)
}
#[derive(Debug)]
enum MyReadU32Line {
FailReadLine(Error),
FailParse(ParseIntError)
... |
I have written this regex to validate an email. It seems to work fine. Can someone advise on the regex used? Does it work properly or can be done in a better way?
pattern=r"^[A-Za-z]+[-_$.A-Za-z]*@[A-Za-z]*\.[A-Za-z]+$"
x=re.search(pattern,"abc.xyz@gmail.com)
print x
Note: I have used x and print as Code Review needs ... |
I posted a recent question on code review detailing my previous C# object-oriented application which used animals as the main context. Although this example doesn't really include inheritance or anything similar, I did try and create something a little bit more interactive. Maybe, just maybe this could be practical for... |
I'm currently working on an AI-driven trading system, the code below aims to extract ticker data from polygon REST API, this is a paid service so, in order to test the code you will need to subscribe / obtain a free API key with limited data history. You'll find base_extractor.py, polygon_extractor.py and extract.py wh... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.