instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
I've built a Palindrome checker in JavaScript. It's fairly simple.
I'm still learning JS and am looking to learn.
So I would love hear ideas on how to improve the JavaScript in this. Like more efficient ways to resolve the task of checking for Palindrome.
Source code is below. Link to CodePen is her: http://codepen.io/... | stackexchange/codereview |
I am trying to convert a BeautifulSoup4 HTML Table to a list of lists, iterating over each Tag elements and handling them accordingly.
I have an implementation of this that works at a surface level using BeautifulSoup4. However, the code is getting repetitive and complicated needlessly, but every time I try to improve ... | stackexchange/codereview |
The task is to assign the n numbers given as input by the user in an array . For Ex : If user gives 10 as input then the generated array should be like this ,
arr[0] = 0
arr[1] = 1
arr[2] = 2
arr[3] = 3
.
.
.
arr[10] = 10
The code below works fine but i am using a loop to assign this numbers to an array which can pro... | stackexchange/codereview |
Here's a function that allows you to convert an array of functions into an object of functions where each property is set to the name of the function.
var _ = require("underscore")
function functionName(fn){
//http://stackoverflow.com/a/17923727/340688
if(fn.name) return fn.name
return /^function\s+([\w\$]+)\s*\... | stackexchange/codereview |
The Win32 API has a so-called 'high performance counter' (QueryPerformanceCounter() and friends) but often it is neither precise enough nor reliable enough, due to high jitter.
The low resolution is no surprise since the value is often derived by shifting off the 10 low bits of the CPU's time stamp counter (TSC), after... | stackexchange/codereview |
I don't feel that my code is secure, and would like some help in using prepare statements for the following;
$track = "INSERT INTO resources_record (name,email,stage,format,topic,max_cost,mentor,total_cost,duration)
VALUES ('".$fullName."', '".$email."', '".$stage."', '".$format."', '".$topic."', '".$cost."',... | stackexchange/codereview |
I wonder if I should divide this class into two, since it contains two "ifs" with different messages. Would breaking it down be in keeping with the "S" of SOLID?
internal class ValidDateApuration : IBusineeOfValidation<DtoFormGnre>
{
public MessageValidation Validar(DtoFormGnre obj)
{
var paymentDate = ... | stackexchange/codereview |
I am learning how to program and during the Python course on Codecademy I was encouraged to rewrite it all with new features (2 players, various ship sizes, etc.).
In summary this works as follows:
Board configuration is set
Players and their deployment is initialized
Deployment info is exchanged between players
Each ... | stackexchange/codereview |
I am trying to solve this problem:
Given an array of integers, find two numbers such that they add up to a specific target number.
and this is my strategy:
For each i in array num, do a binary search in numfor target - i in num.
class Solution:
# @return a tuple, (index1, index2)
def binary_search(self, a... | stackexchange/codereview |
So I have some code here:
First a simple random # generator and a array-choosing function:
function Rand(min,max)
{
return parseFloat(Math.floor(Math.random()* max-min+1)))+parseFloat(min);
}
function Choose(arr)
{
//Returns an element from an array at random.
return arr[Math.floor(Math.random()*arr.length)... | stackexchange/codereview |
I would like some advice which relates to the "fat model skinny controller" concept in Rails.
See my show action in the Micropost controller
def show
@micropost = Micropost.find(params[:id])
@tags = @micropost.tag_counts_on(:tags)
@responses = @micropost.responses
@response = current_user.respons... | stackexchange/codereview |
I'm building an application that implements the A* algorithm to calculate a route between two rooms. I am trying to create a graph which the algorithm can operate on and I am not sure if this is the right way to do it.
Here's what I've done so far:
Vect2.java:
package myalgorithm;
public class Vect2 {
private int... | stackexchange/codereview |
I'm wondering if there is a faster way to do the following code, which works fine. It needs to be applied to every row of the DataFrame df. class_dct contains a different NLTK NaiveBayes classifier for each of 9 regions.
for region in regions:
new_app=[]
for title in df.booktitle:
nlp_genre=class_dct['C... | stackexchange/codereview |
I've been working on what is essentially my first proper attempt at making a useful PHP wrapper class for the Wordpress Settings API. It works great so far and I plan to add more methods as I go so that I eventually build up a class that can be used in pretty much any situation.
As this is my first proper PHP class, I'... | stackexchange/codereview |
I wrote a program for one of my Object Oriented Programming in Java classes(Program 2) and I got docked off because my method was too long, which I'm not complaining about.
I got the note: "Modularize more, method too long."
I was wondering what any of you more experienced programmers would do to simplify/shorten my co... | stackexchange/codereview |
I'm working through Sedgewick's Algorithms book for fun and educational purposes. I am implementing a simple Stack<T>, using System.Collections.Generic.Stack<T> as a guide:
[System.Diagnostics.DebuggerDisplay("Count = {Count}, Size = {_values.Length}")]
public class Stack<T>
{
// Constructors
public Stack(int c... | stackexchange/codereview |
I have created an Angular pipe to suppress the sensitive information like credit cards, bank account, ABA numbers etc.
This is working fine but I would like to know if this is the best possible way to implement the logic.
Here is the Typescript code for pipe logic.
export class SuppressInfoPipe implements PipeTransfor... | stackexchange/codereview |
I've been working on an LR(1) parser, and I've just finished making the LR(1) item. I'm very rusty with C++, so any pointers (especially optimization and code structure) would be appreciated. Here are my files:
main.cpp:
#include <iostream>
#include <array>
#include <vector>
#include <unordered_map>
#include "lritem.cp... | stackexchange/codereview |
I have some simple HTML for a +/- Button, Phone Number Textbox, and a Phone Number Type Dropdown.
I'm new to Bootstrap, so with the help of the tool Bootstrap Studio I generated this code that I currently have:
<div class="row">
<div class="col-lg-1 col-md-1 col-sm-1 col-xs-3">
<form>
<div class... | stackexchange/codereview |
I've been trying to set up an n-layered application in ASP.NET MVC 5. I've converted my account controller to look like this.
I would like some feedback as to whether this is going in the right direction. What I'm trying to achieve is to off-load my controllers and leave the logic to the service. My Controller should j... | stackexchange/codereview |
I just started learning about the MVC architecture. And I started to create my own MVC framework to how I like it the most.
Here I've got the index.php, indexcontroller.php and view.php. I'm not too sure if what I am doing is right, or with best practices. So I would like to know if there is anything I missed so far, o... | stackexchange/codereview |
This is improved code from my previous question. This mini game which we call "Moon Buggy" is available in beta from the google playstore.
The action is that you control a vechicle on the moon and you defend yourself against evil UFO:s.
I have written a separate class for the UFO which is instanciated once for every... | stackexchange/codereview |
I want to configure my website to force a www. prefix on the name, and the HTTPS protocol.
<system.webServer>
<rewrite xdt:Transform="Insert">
<rules>
<clear/>
<rule name="Add WWW prefix" enabled="true">
<match url="(.*)" ignoreCase="true" />
<conditions>
<add input="{HTTP_HO... | stackexchange/codereview |
Async SelectMany takes an enumeration (length unknown) of tasks, each of which returns another enumeration (length unknown and likely different from one another), and returns results from the second dimension as soon as they are ready. I used the name FoldAsync to make it descriptive, but I'm open to suggestions.
Imagi... | stackexchange/codereview |
I'm adding an onclick listener to the whole document then checking the source of the click. If the source of the click contains the attribute data-widget I want to go to the appropriate action. I did it but I'm hoping for a more efficient way of doing things and if I can do without the self invoking function.
<div dat... | stackexchange/codereview |
I am completely new to this coding thing and am completely lost. I've been asked
"Create a method called ValidString that will return true/false if the string that is passed in is not null and not empty. You should use the IsNullOrEmpty or the IsNullOrWhiteSpace methods of the string class to check if the string is emp... | stackexchange/codereview |
I have this method which successfully sorts the incoming dictionary alphabetically:
private Dictionary<string, string> sortMacroDictionary(Dictionary<string, string> whichDictionary) {
Dictionary<string, string> sortedDictionary = new Dictionary<string, string>();
List<string> tempList = new List<string>();
... | stackexchange/codereview |
I am performing search in a contact list using linear search with complexity \$O(n)\$. Please suggest me how to improve search strategy in my code.
public class ContactService {
private Set<Contact> contacts;
public ContactService() {
this.contacts = new TreeSet<>();
}
public void addContact... | stackexchange/codereview |
Given some points that are represented as (X, Y) coordinates, my task is to count the points that are inside a circle, on the circle, and outside the circle.
The input is given in the following way: first, the number n is provided. Then, n numbers are inputted that represent the SetX. Afterwards, the numbers for m and ... | stackexchange/codereview |
I have the following piece of code and I would like to see what different approaches would be to solve that in a more elegant way.
The thing is that I don't know whether is better to have the null checks or the try/catch block there or maybe the code below should not happen in the first place. Maybe one can give anot... | stackexchange/codereview |
I am trying to improve the algorithms for the following code!
The problem I am trying to solve is that I have nested loops that don't look efficient. This includes the Sales_item.h file from C++ primer 5th edition that may have to be updated if we want to go another design route.
#include <iostream>
#include <fstream>... | stackexchange/codereview |
I am making a Tic Tac Toe game to be played in the console either against another human or a simple AI. It is a little rough but it works. What concerns me is how well it adheres to SOLID and other design principles as this is my first time using them in practice. I would appreciate a review of how my classes are struc... | stackexchange/codereview |
As regarding the following question I have completed the code as below.
But I am curious about other effective solutions. I am also curious about if there is any solution that could be applicable by using java stream API.
It is not mandatory to keep records at int[][] matrix. Any data structure can be used.
My solution... | stackexchange/codereview |
As this is pure Python so using loop with big files make the code very slow
any improvements or suggestions.
Hide Code
# Consts
HEADER_SIZE = 54
DELIMITER = "$"
class LSBEncrypter(object):
def __init__(self):
self.image_byte_counter = 0
self.new_image_data = ''
self.original_image = ''
... | stackexchange/codereview |
So I am making post requests to a page for search queries. I am turning them into a session array so I can paginate the results. The process kind of feels ugly and long winded. I need code review for two things.
Shortening / making this code more elegant if possible
Security - any glaringly obvious vulnerabilities I h... | stackexchange/codereview |
When I submit the form, I need to validate the input data from an HTML form field, which comes from the user who submitted the data. So inside the Page_Load event, I added this.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
AntiForgery.Validate();
}... | stackexchange/codereview |
To learn more about design patterns, particularly the Model-View-Presenter (MVP) pattern, I am currently creating a CLI weight tracker application in Python. I would like you to review the code to determine if it adheres to the MVP pattern.
The code or business logic itself is not finished yet. The application can curr... | stackexchange/codereview |
My goal is to have a memory pool non-template class that is used to store arrays of objects.
The same memory pool object must be reusable for a different array (difference size, different type and/or alignment).
I already posted a series of questions on SO about this subject:
Correctly using type-punning and erasure f... | stackexchange/codereview |
Are there any security flaws in what I plan to do?
I need to store the following in my DB:
a random string to act as a salt for encrypting a password
the encrypted password that used the salt in #1
Here's the PHP code I have to accomplish the above tasks:
<?php
function decrypt($string, $encryption_key = '')
... | stackexchange/codereview |
I have a photo list page where each photo has multiple tags (as spaced words). I'm trying to display most of the tags on the page after:
Removing duplicate tags
Sorting tags by having most occurring tags first
The code looks like this:
$tags1 = "red blue green yellow colors";
$tags2 = "blue green grass tree garden";... | stackexchange/codereview |
I've been finding myself wanting the following pattern recently:
void perform_async_operation(std::function<void(int)>);
class some_class {
public:
void foo() {
perform_async_operation([this](int result) {
data_ = result;
});
}
private:
int data_;
};
Now, the issue here is that th... | stackexchange/codereview |
For development I'm using timer classes that are based on Win32 functions like QueryPerformanceCounter() or the time stamp counter of Intel-compatible CPUs. However, for self-contained little test programs that can be posted here (or put in a place like PasteBin and linked) I'm looking for a replacement that does not r... | stackexchange/codereview |
My computer has been having this issue where when I press a key, two key presses get registered. The goal of this program is to detect the time delta between the two keys so that I can set an effective debounce threshold. I also thought that it would be a good idea to try out Rust, so here it is:
use std::{mem, ptr, en... | stackexchange/codereview |
I implemented a Python Hash Table using only lists.
Here is my implementation:
class HashTable:
# Initialize the table with a fixed size of 54 slots
def __init__(self):
self.Table = [None] * 54
def _get_value(self, key): #This is my hash function.
# It finds the hash of every string. total ... | stackexchange/codereview |
Maybe this is a little large for a simple code review, but I think it included a lot of different needs and how I tried to meet them. Pick a section or function and let me know where I might improve.
The code is for a nand gate simulator and takes an input file with wiring pairs. Like variable to gate or gate to other ... | stackexchange/codereview |
I've been learning Java Database Programming for like 2 days, I read theory at first. Now decided to get stuck in. I just wanted a few pointers.
I am using JavaDB (Netbeans Service) should I be using something better? As I've read it has some security flaws.
I split one class to two (as you'll see below), is what I'v... | stackexchange/codereview |
Basically, I'm performing an if statement on an array based on the returned value
<?php
if($array[1]>10000 AND $array[1]<50000){
$selling = $array[1] - 250;
}
elseif($array[1]>50000 AND $array[1]<100000){
$selling = $array[1] - 500;
}
else{
$selling = $array[1] - 100;
}
$... | stackexchange/codereview |
Here is a "Roman Numerals" kata implementation. Given a decimal number one has to return a corresponding roman number.
I have following questions:
Is memory management correct? Here I assume that the caller is responsible for freeing memory.
Does this code conform to c code style?
Does it look like idiomatic c?
Thank... | stackexchange/codereview |
I have a below read function which is called by multiple go routines to read s3 files and it populates two concurrent map as shown below.
During server startup, it calls read function below to populate two concurrent map.
And also periodically every 30 seconds, it calls read function again to read new s3 files and pop... | stackexchange/codereview |
I wrote a solution for SPOJ "It's a murder!". I'm exceeding the time limit even after n log(n) solution and fast I/O.
Given a list of numbers, I need to calculate the sum of the sum of the previously encountered numbers that are smaller than the current number. For example, given 1 5 3 6 4, the answer is
(0) + (1) + (... | stackexchange/codereview |
This is a warm-up programming exercise for learning string methods in Python from HackerRank:
You are given a string S.
Your task is to find if string S contains: alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters.
Input Format
Single line containing, string S.
Constraints
... | stackexchange/codereview |
I created two programs (one with JAVA8) to calculate the total count of uppercase and lowercase characters in given String. After checking the execution time JAVA8 is taking longer execution time than expected. Is there any possible way to optimize any of these code more to reduce execution time and complexity?
Code:
i... | stackexchange/codereview |
I've refactored my previous query and added better checks when selecting the data. The query link can be found here. The formulas used to calculate the two percentages are the same, and can be seen below:
$$
\text{Answered Percentage} = 100 - \left(\frac{\text{Unanswered}}{\text{Answered}} \times 100\right) \\
\text{Un... | stackexchange/codereview |
I've written a little program that I need for fixing two problems in my spherical panorama images.
It does two things:
If the image does overlap horizontally, it cuts away the overlapping pixels from the right side.
It fills up the image vertically with black, so that it has a ratio of 2 to 1.
I'm not too experienced... | stackexchange/codereview |
I am learning decorator design pattern in PHP. Please see what i am doing is correct or wrong, would appreciate your review, feedback, comments, suggestions.
<?php
/**
* NotifierService interface is used as abstraction for Notification Mechanism
*
* It can be later implemented as EmailNotifierService, PushNotifierSe... | stackexchange/codereview |
This is code I'm writing for an android game where I want to be able to randomly generate small planet sprites. It seems like the best way to do this is to have a set of small PNG textures that can be layered onto each other. I found code for recolouring a drawable programmatically here that was very helpful.
The idea ... | stackexchange/codereview |
I am trying to build a simple algorithm to achieve the best combination of values based on two params in an array of objects.
The whole code is available here
First I have an array holding objects. The items which will be analyzed and packed into volumes together. All of the values are in percentages.
const nonStackabl... | stackexchange/codereview |
I'm a beginner and self learning programming students. While learning binary tree data types, for the sake of understanding graph theory and other interesting programming problems, I've writen the below implementation. Would you please suggest if there's anything wrong or either this can be improved.
It may seem rein... | stackexchange/codereview |
Sorry if this question has been asked before, but I am having trouble searching for the answer I am looking for. This question is in regards to efficiency and overall C# standards.
I have an integer that I manipulate by 1, either by -- or ++ depending on a user's input. I then use this integer as an index to grab an ob... | stackexchange/codereview |
I responded to this question about designing around interdependant methods with the strategy pattern.
Afterwards I started thinking about the functional additions to java 8 and wondered if I was being an old foggy stuck in the past and if maybe there was a better way with all these fancy new tricks.
So I started hammer... | stackexchange/codereview |
I'm currently working on a grade calculator for a university (professionally), and I am wondering if anyone can suggest an improvement to the following query? Here is my database:
The query returns the following table:
SELECT
`course`.`title` AS `course_title`,
`yearGroup`.`id` AS `year_group_id`,
... | stackexchange/codereview |
I was doing a simple exercise to calculate the amount based on an expression.
For example:
(((2*2)+(3*5/5)+(2*5))) outputs 17
((2*2)(3*5/5)(2*5)) output 120 etc
I have written the code, but I am not satisfied with what I've done. Could you please help me to review the code and suggest the best approach for that?
import... | stackexchange/codereview |
I've written a small C program that has ad hoc implementation of cruise control for my Altera DE2 FPGA. It works alright but there are too many global variables. Preferably there should be no global variables. How can I reduce the amount of global variables?
#include <stdio.h>
#include "system.h"
#include "includes.h"
... | stackexchange/codereview |
Recently I found that the binary search (std::ranges::lower_bound and std::ranges::upper_bound) is the main bottleneck in my library.
So I wanted to improve it, one attempt was to use SIMD to replace the C++ standard library binary search. In short, the result was actually little bit slower than original binary search.... | stackexchange/codereview |
I have an array of items on which I have to perform 2 tasks:
Applying a function on the array item
Checking if the value is true or false.
The functional approach to solving this would be
var result = arr.map(function(item){return some_action(item);}).filter(function(item){return other_action(item) == true;});
But ... | stackexchange/codereview |
from datasets import load_dataset #Huggingface
from transformers import BertTokenizer #Huggingface:
def tokenized_dataset(dataset):
""" Method that tokenizes each document in the train, test and validation dataset
Args:
dataset (DatasetDict): dataset that will be tokenized (train, test, validation)
... | stackexchange/codereview |
The following ingests a preexisting SqlCommand and returns the values.
A couple caveats right now.
1 ) Type properties must be named identical to the SQL column
2) properties must be given a custom [SQLColumn] attribute.
The attribute contains a string which I plan to use later for variation in property names while ke... | stackexchange/codereview |
Is it appropriate for the class to subscribe to its own events like this? Should the class not subscribe, and instead move that code to before the OnEventName(Object args) methods call the EventHandlers? I'm curious if there are any downfalls to this approach.
On one hand, with this approach I could remove all the null... | stackexchange/codereview |
Last week I posted a piece of code to apply Dijkastra algorithm to calculate the shortest path between to nodes in a graph. Now, I've made some improvements, but I am still having difficulties.
I have a class Graph that is going to be constructed by two other classes. A vector of elements are instances of a class Edg... | stackexchange/codereview |
Within our project we've used a lot of boolean setOutputValue(char pinNumber, boolean pinValue) kind of functions.
Within those functions we do the following (for example):
hardware_layer:
#define L9823_HIGH 0
#define L9823_LOW 1
void hardware_L9823_setOutput(U8BIT pin, U8BIT value)
{
/* some SPI interfacing is ha... | stackexchange/codereview |
This one is, or rather, should be, fairly simple. I have a list of tuples of XY positions, and am trying to pull out angles relative to the origin from it. However, unlike atan2 / friends, I want it to be continuous, in other words not wrapping. I know (and am assuming) that the differences between successive XY coordi... | stackexchange/codereview |
I have two sets of points in lists list1 and list2 given below
list1 = [['a',[1.2,3.6,4.5]],['b',[3.2,-5.4,6.6]],['c',[1.1,2.2,9.9]],['d',[5.5,12.5,2.9]],['e',[3.5,6.5,22.9]]]
list2 = [['v',[11.2,3.6,4.5]],['x',[13.2,-5.4,6.6]],['y',[11.1,2.2,9.9]],['z',[15.5,12.5,2.9]]]
If all the points in list1 are rotated and/or t... | stackexchange/codereview |
I have a Makefile, which should when calling make just call make in a list of subdirectories. The subdirectories should not be automatically detected but are fine to be hard coded (Tool1, Package2, Submodule3 below). Furthermore, if I call make Tool1, Tool1 should be built (i.e. the directory names should be recognised... | stackexchange/codereview |
I created a brainfuck interpreter in javascript. It works good to me as I have seen no bugs in my compiler. I like to get a suggestion and review from you to what should this compiler improve.
Here's the short code:
function bf(str, input){
var array = str.split("");
var memory = [0];
var pointer = 0;
var result ... | stackexchange/codereview |
Which one of these two would you prefer writing in your code?
This:
tweet = tweet.replaceAll("@\\w+|#\\w+|\\bRT\\b", "");
tweet = tweet.replaceAll("\n", " ");
tweet = tweet.replaceAll("[^\\p{L}\\p{N} ]+", " ");
tweet = tweet.replaceAll(" +", " ").trim();
Or this:
tweet = tweet.replaceAll("@\\w+|#\\w+|\\bRT\\b", "")... | stackexchange/codereview |
The code below works fine for me. Is there any way that I can improve this code more? Note: delimiter is single whitespace only for email address.
getmail.py
#!/usr/bin/python
import re
handleone = open("scratchmail.txt", "r")
f1 = handleone.readlines()
handletwo = open("mailout.txt", "a+")
match_list = [ ]
fo... | stackexchange/codereview |
I made a tiny little bash script, that prints the current IP Address to the command line. I checked the script with ShellCheck (0.4.6-1) on a local debian install and I get the following message:
SC2026: This word is outside of quotes. Did you intend to 'nest '"'single quotes'"' instead'?
What is wrong with the way I... | stackexchange/codereview |
This is the second thing I've ever written in Python. I am just looking for what I could improve upon along with things that could be done better. It is as compact as I could make it with my current experience.
import random
def war_handler():
war_handler.count += 1
print "War is {0} is happening.".format(war... | stackexchange/codereview |
I have been trying learn OOP lately, and have made a simple program that simulates some sort of drive thru experience using a 9 digit keypad to add, delete, and pay for items ordered from the menu.
Everything works as intended, as far as I can tell. I feel like some of my classes may be doing too much, and that overall... | stackexchange/codereview |
My Python implementation of for Hack Assembly Language. See this question for the Java implementation. Any comment about best practices and performance improvement?
import sys
import os
def usage():
print "Usage: %s namefile.asm" % os.path.basename(sys.argv[0])
def tobin(val, nbits):
return bin((val + (1 << nb... | stackexchange/codereview |
I am using idenity server 3 authentication.
I have to implement refresh token logic.
AccessTokenLifetime is 1 hour, and after that time I want to update access token with refresh token.
I want do this only once, by using filter in mvc. My idea is to check if token has expired, and if yes that get new token.
This is my ... | stackexchange/codereview |
I was tasked with writing a function, that checks whether a date is valid in the following format: DD.MM.YYYY. Here's what I wrote:
bool isValidDate(const char* date)
{
int a, b, c;
size_t len = strnlen(date, 255);
for (size_t i = 0; i < len; i++)
{
if (!isdigit(date[i]) && date[i] != '.') retu... | stackexchange/codereview |
This class encapsulates a List<KeyValuePair> (see List<T> implementation here, and KeyValuePair implementation here) and exposes a richer set of members than the typical Scripting.Dictionary, ..not to mention the anemic Collection class.
The class enforces some "type safety", in the sense that if you add a KeyValuePair... | stackexchange/codereview |
I have an array of hashes, each of which has two attributes: "title" and "Zscore". I want to return either the result of find or the last element. This can be done with:
a = array.select{|i| i["title"] == "some title"}
b = a.find{|i| i["Zscore"].to_f >= 5} || a.last
Is there an elegant way to put the conditional insid... | stackexchange/codereview |
I am learning clojure this week end and just starting to develop a simple checkers engine. I currently coded some basic functions to create the board and display it. I would love to get some feedback !
(ns sandbox.checkers)
(def standard-size 10)
(defn empty-board [size]
(vec (replicate size (vec (rep... | stackexchange/codereview |
This problem is identical to the one here:
Suppose that you have been assigned the job of buying the plumbing
pipes for a construction project. Your foreman gives you a list of the
varying lengths of pipe needed, but the distributor sells stock pipe
only in one fixed size. You can, however, cut each stock pipe i... | stackexchange/codereview |
Problem Description:
Find the maximum sum of a compact subsequence of array elements after
performing a single swap operation.
Solution:
def maxsum(lst): # Get maximum sum of all possible slices in list
max_ending = max_slice = lst[0]
for i in xrange(1,len(lst)):
max_ending = max(lst[i], max_ending ... | stackexchange/codereview |
I am needing to import a tab delimited text file that has 11 columns and an unknown number of rows (always minimum 3 rows).
I would like to import this text file as an array and be able to call data from it as needed, throughout my project. And then, to make things more difficult, I need to replace items in the array, ... | stackexchange/codereview |
For an assignment, I am told to write two methods: incrementDay() and incrementMonth():
incrementDay()
This method takes no input and returns nothing. If the previous
month's balance was not paid in full, the credit card charges interest
on the current balance after each day. To do this, the class will need
two ... | stackexchange/codereview |
This is the smallest SSCCE of my project. I get flickering on the screen with this code.
Main class (on which I start the application)
import javax.swing.JFrame;
public class MainFrame {
public static void main(String[] args) {
final JFrame frame = new JFrame();
final GamePanel gamePanel ... | stackexchange/codereview |
I feel like this maybe to much for one method... This method lives inside of a service class which is called by an interface. It dumps data into three different tables within a database.
public UserAccount CreateAccount(NewAccount newAccount)
{
if (!AccountAlreadyExists(newAccount.UserName))
{
string salt = St... | stackexchange/codereview |
I'd like to improve this selection sort code
package com.arun.sort;
import java.util.Arrays;
public class SelectionSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 131, 13, 11, 1 };
SelectionSort sort = new SelectionSort();
sort.selectionSort(arr);
System.ou... | stackexchange/codereview |
It's been long since I have put any of my codes for review. Today I want to review my Android code written for a BM70_BLE device with which one can change the color and brightness of the LED light. The code works, however, I would like to improve it further any suggestions for improvement or any logical changes are app... | stackexchange/codereview |
I have the following code that converts a couple of bash commands into Windows cmd commands, as well as adding some commands. This is only my second day programming in C++, so any and all suggestions would be helpful.
#include "stdafx.h"
#include <iostream>
#include <string>
#include <regex>
#include <fstream>
#include... | stackexchange/codereview |
I often find myself working with files I get from other users that mostly work on Windows machines (I, myself, am on a macOS) and they tend to name their files in all sorts of (weird & difficult to handle) ways.
For example, the files I get may contain any or all of the following:
a space
a dash
a comma
one or more do... | stackexchange/codereview |
I'm still pretty new to programming, only been doing it a week. I'm just wondering if I made any glaring mistakes or anything that could be improved code wise?
import random
the_board = []
players = [{'type': 'player', 'piece': 'X'},
{'type': 'player', 'level': 'smart', 'piece': 'O'}]
def print_board(boar... | stackexchange/codereview |
I wrote a function to find the closest value in a list to a given search value. What prompted me to write it was as boilerplate for a prime number problem so I could find the closest prime to a given number.
My Code
'''
* This function finds the closest value in a sorted list to a given search value.
* Paramete... | stackexchange/codereview |
I have written a few C++ functions that should:
take in a string
transform it based on index
transform it based on number of alphabetic characters seen
return the transformed string
Example first, detail after:
$ rotn_a("Hello, World!")
> Igopt, Exbwp!
$ rotn_a("aaaaaaaaaaaaaaaaaaaaaaaaaaa")
> bcdefghijklmnopqrstuvw... | stackexchange/codereview |
SICP exercise 2.18 asks the following:
Exercise 2.18. Define a procedure
reverse that takes a list as argument
and returns a list of the same
elements in reverse order:
(reverse (list 1 4 9 16 25))
(25 16 9 4 1)
I wrote this iterative function:
(define (reverse n)
(define (iter a b)
(if (null? a) b
... | stackexchange/codereview |
Staying true to the mantra: "The third time you do something, you automate", I've built up a decent collection of shell scripts that live in ~/bin. Some of these scripts contain useful boilerplate code, or just stuff I can't bring myself to memorise (like colour output stuff). Other scripts I find myself elaborating on... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.