instruction_seed stringlengths 71 95.1k | _source stringclasses 1
value |
|---|---|
I was given this small task in an interview recently. I'm usually terrible at coding questions in interviews, because with the time constraint and the lack of google I usually overthink and rush stuff and just end up with a mess of a program.
The task was to write a program that would compress the length of string, an... | stackexchange/codereview |
This is my solution to this LeetCode problem.
Essentially you want to get the next board state for a Minesweeper game. All test cases passed and the submission was accepted on leetcode. The submission on leetcode was I used a depth first search approach (hopefully it is implemented correctly).
I believe the run time fo... | stackexchange/codereview |
I have coded a system where each 'Player' class requires 5 components (could be more in the future, up to 10, 20 maybe even 30, once we add more and more features). What I want some advice on is a better way of creating these components, I am not saying that my current way is bad, I am just looking for anyone who could... | stackexchange/codereview |
I'm posting here to ask for some help improving myself using python since I'm fairly new to it and come from C#.
The main functionality of this bot is parsing the Wargaming API for player related information.
Project structure:
project
| main.py
└───ENV
│
└───data
| classes.py
| dbcontext.py
| ... | stackexchange/codereview |
After a week of searching and testing each approach via Stopwatch,
I came to this method using the fastest way possible to capture screen into a bitmap and then to a byte[].
Is it possible to make it any faster using parallel features or any idea I have not taken into account? (As I am a newbie, 4 months of self lea... | stackexchange/codereview |
I've decided to move my rendering code to a separate thread, to help facilitate the move I've created a pipeline system for rendering. With this pipeline I can insert commands into a queue which will be processed later on the rendering thread. Thus far the code has proven to work well, but I would like to know if there... | stackexchange/codereview |
This is for heapsort and am wondering about the heapifyDown method. Here it is for review. I included relevant helper methods.
The heap is stored in array starting at index 1.
/*swaps node at i with biggest child if larger*/
private void heapifyDown(final int i) {
while(!isLeaf(i)) {
//find biggest child
... | stackexchange/codereview |
I've just finished this function and wanted to know if anyone know another way to do the same:
function findtext(archivo,Delimit1, Delimit2 :String) :String;
var
Buffer :AnsiString;
ResLength :Integer;
i :Integer;
PosDelimit :Integer;
begin
Buffer := read_file_z(archivo);
if Pos(Delimit1, ... | stackexchange/codereview |
I have question regarding online PCA implemented in the paper. I am interested in the Algorithm 2. I am not certain if there is a bug in my code can someone confirm if my code is correct? The algorithm is as follows:
input: \$X\$,\$\Delta\$
\$U\leftarrow\$ all zero matrix (dimensions are not given in the paper , ... | stackexchange/codereview |
I have been working through the Cryptopals challenges in Ocaml. My interest in Ocaml is to better learn functional programming techniques and effective usage of the type system.
Set 1 Challenge 4 says 'One of the 60-character strings in this file has been encrypted by single-character XOR. Find it.'
My code finds the c... | stackexchange/codereview |
I'm starting to learn Clojure, and would like feedback on some code I wrote to manage database migrations. Any recommendations to make it more robust, efficient, idiomatic, elegant, etc... are welcome!
(ns myapp.models.migrations
(:require [clojure.java.jdbc :as sql]
[myapp.models.database :as db]))
... | stackexchange/codereview |
Please suggest ways of cleaning up this code.
Hashtable newValues = e.Values;
string NewPosition = null;
string NewFirst = null;
string NewLast = null;
string NewEmail = null;
int NewAppt = 0;
if (newValues["Position"] == null)
{
NewPosition = "";
}
else
{
NewPosition = newValues["Position"].ToString();
}
if... | stackexchange/codereview |
I'd like to create a cookie wrapper in my application to help support a DRY approach to coding common cookie methods, provide IntelliSense for cookie-type properties (keys), and protect against typo-errors when working with cookies from multiple classes and namespaces.
The best structure for this (that I can think of... | stackexchange/codereview |
I would like to know if the solution I came up with for managing relationships between entities is sensible. Guys in my team feel it is transparent, but maybe I'm missing a pitfall somewhere?
Consider the following situation:
@Entity
public class User {
@OneToMany(mappedBy = "user", cascade = ALL, orphanRemoval = ... | stackexchange/codereview |
I have an array of non-Equatable objects. I want to remove all the duplicates from the array.
class SearchResult { // non-equatable
var index: Int!
var score: Int!
init(_ index: Int, score: Int = 0) {
self.index = index
self.score = score
}
}
var searchResults: [SearchResult] = [Searc... | stackexchange/codereview |
At a job interview, I was asked to code the following algorithm:
Given are three robots which advance across a 1km lane at a different pace respectively. Each pace made by a robot is of a random distance.
All three robots stop once one of them is one pace away from reaching 1km. Once they stop, the robots' steps neares... | stackexchange/codereview |
I created a dates_in_range() function which checks if all of the dates passed to it ($dates array) are within $start_date and $end_date. If they aren't, it'll return false.
The code works fine, but I'm wondering if there's a way to refactor it better using something like array_filter? Or does this look fine?
function d... | stackexchange/codereview |
I am doing a project and I have come up with some code to swap every letter with every other letter in a string, only the project was to be "efficient as possible".
Example:
"rya" = yra, ray, ayr.. etc
I understand exactly how the code works. I would just like to make it efficient as possible.
public String testSwap(S... | stackexchange/codereview |
I have a controller that has gotten a little out of hand. This is my first AngularJS project and I am using it as a learning experience... but I feel like I am doing some things wrong.
This controller is used for resetting data on a weekly basis. There are "foos" of which 10 random foos are selected each week, "bars" w... | stackexchange/codereview |
The usual way of dealing with a SemaphoreSlim is
await semaphore.WaitAsync();
try
{
await DoStuff();
}
finally
{
semaphore.Release();
}
To help with not making mistakes like not releasing the semaphore or putting the semaphore in the try block, I created this extension class
public static class SemaphoreSlimE... | stackexchange/codereview |
There is a draft of my models.py. What can I do for code quality and readability increase?
from datetime import timedelta
from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone
class Rule(models.Model):
start_date = models.DateField()
end_date = models.Date... | stackexchange/codereview |
I'm not very familiar with MPI. I've written this little piece of code to draw the Mandelbrot fractal processing each row of the image in parallel. It works but it's really slow. I've written code to perform the same task with OpenMP and with no parallelization, and both run instantly with the default parameters, where... | stackexchange/codereview |
I want to improve my slider class as much as possible. Is this acceptable code for a slider?
I've tried to comment as much as I can. If you want to find out more about the Component class, check out my repository: dxLib.
slider.h:
#pragma once
#include "Component.h"
begin_UI // Namespace define
class Textbox;
class Ri... | stackexchange/codereview |
I have Conway's Game of Life working now and was hoping for direction on:
Unclear code - where would comments make it clearer?
Poor design choices - I already know of one in the countNeighbors method, as it needs knowledge of the game object's name
Improvements to make - I have already noted that I wish to add more te... | stackexchange/codereview |
I'm still somewhat new to C, so pardon me for any silly mistakes I've made.
I'm trying to convert video frames into Minecraft map colors using JNI and FFmpeg's av (and swscale) libraries. The code works below but it's sluggish and I'm going to assume it's prone to the branch prediction problem.
The Minecraft map data i... | stackexchange/codereview |
I just finished the Pluralsight courses about Inversion of Control and Mirco-ORMs, and I am struggling with the implementation aspect of some of the concepts.
This is my (simplified) repository implementation using Dapper:
public class AppRepository : IAppRepository
{
public string TableName { get; } = "apps";
... | stackexchange/codereview |
I have an implementation for my first binary search tree in C++. I was wondering if there was some cleaner way to avoid using the double pointer in the way I have my code setup? Such as on one line I have:
(*node)->left = insert(&((*node)->left),value);
Which seems a bit "messy", but it almost seems necessary for the ... | stackexchange/codereview |
I have two methods which are very similar apart from the method call inside and the return type. I wondered if there was a way to make it neater, i.e not duplicate the boiler plate connection code. I considered putting a flag in the method signature to switch, something like isMultiple but in the end I didn't like this... | stackexchange/codereview |
The requirements are as follows:
Create a Flight app service using React that does the following:
Login page:
When entering username: “user” and password: “password”, the user
will be routed to the app page.
otherwise - an error message should be presented.
Flight list page:
Table of flights with the fields: from, ... | stackexchange/codereview |
I have been trying recently to develop a code finding the next palindrome from a certain number. For example, if the input is 800, the output should be 808, as 808 being the next palindrome from 800.
Here's my code. It's fully functional, but on my online judge I get a problem with the time of the execution. My method ... | stackexchange/codereview |
I wrote the following C program to compare software version strings. Please provide any general feedback you'd like, but with special focus on error handling decisions, user input validation/sanitation, and robustness. My end-goal is for the program to properly handle user input and not have non-graceful crashes, etc..... | stackexchange/codereview |
Note: It's Part II of the User Management System project, focused on the frontend. See Part I here.
Here's the frontend part. I want to note that I realized even back then that copy-pasting a huge block of HTML into JS was a bad idea, but couldn't find a better solution without page reloads. I haven't practiced fronten... | stackexchange/codereview |
So I've made custom binary streams which work like this:
/// \brief Reads a variable from the stream.
/// \tparam T Type of the variable.
/// \param[out] var Variable to read.
/// \return Reference to this stream.
/// \throw TODO
/// \note No endianness conversion will be performed if a byte is not 8 bit
/// wide.
temp... | stackexchange/codereview |
I have just picked up Scala like 2 hours ago, and I am thinking of printing a series like 1 to 10 but in a recursive fashion. I do not understand what is wrong with this:
def printSeries(x:Int):Int = {
if(x==0) doNothing() else doSomething()
def doNothing() = {}
def doSomething() = {
println(x)
printSe... | stackexchange/codereview |
Zombies are questions with no upvoted answers.
I came up with this SEDE query to find answers with zero votes on questions that have no accepted answer and no answers with greater than zero score.
In other words, answers on questions that show up on the Unanswered tab,
until the answer receives an upvote. (Latest versi... | stackexchange/codereview |
So I got a project to refactor and I can't figure out what the best solution for this specific problem would be. I'm trying to reach some kind of elegant few-line-solution, but every idea I have seems to be a dead end. My brain does not work anymore... The original state:
public SearchParameterSet(ProviderRequestParame... | stackexchange/codereview |
I'm working on an HTML text-based game (think like OGame and other browser games of the genre). I've tried worked on a grid controller to display a map of points that you can move around when you have an entity to move yourself from point to point. The basic concept that I used is to grab a sub-grid of the total map po... | stackexchange/codereview |
I use this document as a basis for my mini-library:
Motivation
The std::rand friends are discouraged in C++14, so we want:
A direct replacement to the std::rand friends. Despite of the security issues, std::rand is considered both handy and useful as a
global uniform random number generator.
To expose the most wide... | stackexchange/codereview |
I have the following function, which I believe could be improved with functional-programming.
function findSelectedInList(list){
for(var i=0;i<=list.length;i++){
var currentItem = list[i];
if(currentItem.selected === "selected"){
return currentItem... | stackexchange/codereview |
Define a procedure that takes three numbers as arguments and returns the sum of squares of the two largest numbers.
I'm using just the machinery that was developed so far in SICP to be true to the exercise. My method works as far as I can tell -- I tested it for a number of cases and tested different permutations of... | stackexchange/codereview |
I have been using Python to learn programming, but I am just recently beginning to utilize classes. I have a basic game below. Please review and let me know what I should improve on.
import random
class Game:
def __init__(self):
self.winningNumber = random.randint(0,100)
self.humanGuess()... | stackexchange/codereview |
I’m trying to implement, for educational purposes only, an example of the Postel’s law on a demonstrative function.
This function is not for production code, it’s for pedagogical purposes only and might be considered as an over abstraction to an easy to understand list comprehension. This isn’t the topic I’m interreste... | stackexchange/codereview |
Imagine you are a company that wants to assist some US-based companies
to ship their goods to customers in Hamburg. To achieve this, lets
assume that every order can be represented by a tuple (orderId,
companyName, customerAddress, orderedItem).
Thus, some sample data might look like this:
001, SuperTrader, Stei... | stackexchange/codereview |
I built this web app to present a random group of questions for quizzes and tests. The page opens with random questions. Clicking anywhere shows (only) the spinner div. Clicking anywhere again brings up new questions.
One thing is bothering me, though. I have succeeded in moving all the JS out of the body except for th... | stackexchange/codereview |
I have a JavaScript function that increments a counter for each square on the chessboard as it becomes dominated by a queen and decrements it if one of the dominating queens are removed (only queens, this isn't actually a chess game with all of the pieces, it's essentially the 8 queens puzzle). If a square is dominated... | stackexchange/codereview |
Does this code show proper implementation of quick sort algorithm? If not, why? Can this code further be improved?
<?php
$unsorted = range(1,20);
shuffle($unsorted);
function quick_sort($array)
{
// find array size
$length = count($array);
// base case test, if array of length 0 then just return array
... | stackexchange/codereview |
This is a follow-up from my previous post, which can be found here. A readme for more detailed information can be found here.
It is a library to create console based tables where you can insert, remove and update entries. An example could look like this:
+---------------+-------------+-----------------+----------------... | stackexchange/codereview |
I tried to solve one SPOJ problem. I wrote one program in Python, however, it got accepted by the SPOJ judges, but its total execution time is 2.88s. The same algorithm used in C language having execution time 0.15s.
Please offer suggestions on improving this approach.
def tempPalindrome(inputString):
""" Code for ... | stackexchange/codereview |
Using Pandas to read a 14k lines CSV with many empty cells - what I call "Emmenthaler data", lots of holes :-) . A very short, simplified sampler (urlbuilder.csv):
"one","two","three"
"","foo","bacon",""
"spam","bar",""
The cells contain information to match against this web API, like this:
http://base_URL&two="foo"... | stackexchange/codereview |
I wrote a speech enhancement code for an Android App. The algorithm runs on 256 size frames of voice samples. On my PC the code runs per about 5ms per frame, while on my Nexsus 5 it more like 50ms per frame, making the speech enhancement on a 30sec long recording run for over two minutes. On my PC, enhancing the whole ... | stackexchange/codereview |
I have many small but similar classes like these:
class DepartmentSerializer < Serializer
self.root = false
attributes :id, :name
has_many :employees, serializer: EmployeeSerializer
has_one :location, serializer: LocationNameSerializer
end
class DepartmentWithManagersSerializer < Serializer
self.root = false... | stackexchange/codereview |
Mostly as a learning exercise, and partly as I thought it might be useful, I have written an implementation of AVL trees ( https://en.wikipedia.org/wiki/AVL_tree ).
An AVL tree is a height-balanced binary search tree, where if the
height difference of the left and right sub-trees becomes more than
one a "rotate" ... | stackexchange/codereview |
I have a table with this schema
ID, int primary key
PathKey, string not null
InsertDate, datetime not null
Value, int not null
In the table there are a medium-large number of records. 1632 different pathkey and 645627 total records
The PathKey is not unique (because I store also the old values).
You can identify a r... | stackexchange/codereview |
I've found this implementation on the web:
void insertSort(int a[], int length)
{
int i, j, value;
int k=0;
for(i = 1; i < length; i++)
{
value = a[i];
for (j = i - 1; j >= 0 && a[j] > value; j--)
{
a[j + 1] = a[j];
k++;
}
a[j+... | stackexchange/codereview |
Last week I started learning Haskell, and since I have some experience with Brainfuck already, I decided it would be a great idea to implement an interactive Brainfuck interpreter in Haskell. I'll first list the code and then add some remarks on it.
Main.hs
module Main where
import Lib
import System.Environment
main ... | stackexchange/codereview |
Context
My company uses a system that has access to the state of different items in the plant.
This software can be customized, by executing a single VBScript function, at a given interval.
The values taken by different variables in the system can be accessed using HMIRuntime.Tags("tagName").Read
Purpose
For trending p... | stackexchange/codereview |
Note:
I am using Unity3D game engine, which uses .Net 2.0 (.Net 2.0.50727.1433 to be precise) to compile code, so I don't have access to newest features of C# 6, or even C# 5. Please keep this in mind while writing your reviews.
What is this?
This (DataTable.cs) is a dictionary that takes two keys, and returns a valu... | stackexchange/codereview |
I wrote a script that moves files older than two days over to a network share (via scheduled task). Windows Task Scheduler doesn't seem to like the script so much, but it works well by itself.
Is there a faster way than what I have?
Is there a way to programmatically make it a scheduled task or service of some type?
... | stackexchange/codereview |
I hope you will tell me tips to ask good questions regarding checking my code. Here it's the code and thanks in advance!
const checkPalindrome = str => {
str = str.toLowerCase()
let reverse = str.split('').reverse().join('');
return reverse === str ? true : false;
}
console.log(checkPalindrome('Madam'))... | stackexchange/codereview |
I'm in the process of building a small application and obviously I need some sort of way to authenticate users. I'm not sure if I am way off or if this is close to what I should be thinking. Please let me know what you think...
<?php
class Authentication_controller {
private __constructor() {
include(Authen... | stackexchange/codereview |
I just read this post on how to avoid memory leaks with AsyncTask. The post proposed using a WeakReference and supplying a TextView as the object of the WeakReference.
In my code, I need to supply multiple parameters to the AsyncTask (not just one as shown in the post). So what I did was create an inner class with the ... | stackexchange/codereview |
I made a Minesweeper for school and it works already. The only problem I have is that I need to optimize one part of my code but I have no idea how. The code below is for the whole program. The second form is just a page for explaining to the user how to play. The part I need to optimize is the part where I basically r... | stackexchange/codereview |
I'm new To C++ and decided to have a go at the Spotify challenges on their website.
I have now finished but I get the feeling my code is just terrible. I'm guessing it would be very hard for someone else to read and I feel like there are much better ways to code this.
Their "Best Before" puzzle asks: Given a possibly a... | stackexchange/codereview |
I made a simple data entry application in WPF MVVM and was just hoping for some input as I am pretty new to WPF . I have done the same application using winforms. Now I have recreated the same application using WPF.
I have understood how to write wpf based application, how to use command and other aspects of c# develop... | stackexchange/codereview |
I have the situation where as long as the user gives valid input, the StringBuilder object will not be null.
StringBuilder sb = null;
switch(userInput)
{
case 1:
sb = method1();
break;
case 2:
sb = method2();
break;
case 3:
sb = method3();
break;
case 4:
sb = method4();
break;
default:... | stackexchange/codereview |
I'd like to be able to compare two objects with different equality checks. This should work if they're in a Set, List or Map as well.
An example use case is testing of deserialzation of a entity which might contain sensitive information, like passwords, the server side, but not in a REST response.
I'd be interested if ... | stackexchange/codereview |
I am currently writing a small configuration API for myself, i want to use it to easily read/write to a file, however, i want to make sure it's efficient and get some other options into the field of my programming. How can i make my classes even more efficient?
This is the class for the options for comments, headers an... | stackexchange/codereview |
I have an Ajax request which in turn on completion make another Ajax request:
$.ajax({
url: '<?php echo BASE_URL.'Dashboard/GetMyTrackList' ?>',
type: 'GET',
success: function (response) {
var list = JSON.parse(response);
$.each(list, function (k, v) {
... | stackexchange/codereview |
Example
String creditCardNumber1 = "4561261212345467";
int sum = IntStream.range(0, creditCardNumber1.length()).filter(i -> i % 2 != 0).map(i -> Character.getNumericValue(creditCardNumber1.charAt(i))).sum() + IntStream.range(0, creditCardNumber1.length()).filter(i -> i % 2 == 0).map(i -> Character.getNumericVal... | stackexchange/codereview |
I was working on the "Robot Name" exercise over on exercism.io (neat site, by the way), the gist of which is: Generate random, unique strings that match /[A-Za-z]{2}[0-9]{3}/, e.g. "xY123", "Gv020", and so on. So there are 2,704,000 possible names out there.
Now, the exercise's tests do not do a full-on check for uniqu... | stackexchange/codereview |
I've got a filter that I'd like to work out how to optimize. The most basic implementation, using loops is like the following:
import numpy as np
nrow = 500
ncol = 500
refArray = np.random.randint( 0,100, (nrow,ncol) )
boundsArray = np.random.randint( 90,95, (2,nrow,ncol) )
window = 31
halfwindow = window/2
result = np... | stackexchange/codereview |
Update: The code below has some obvious problems, and it is not allowed to revise code in the original question, so I have to post a new question, the revised code is here.
std::shared_ptr has the potential problem that two pointer point to the same object but to different control blocks. And its atomic operation is pu... | stackexchange/codereview |
I am pretty new to TDD and is following problems on spoj.pl for practice. I need help with following code; it was my first attempt.
Problem: Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. St... | stackexchange/codereview |
I need to find the length of elements within a string and return it to the user.
What is the best way of simplifying this code to make the amount of string lengths equate to user input? Also, how can I replace string1 with the user input, such as "The length of string 'Dog' is 3"?
num_of_items = int(input("How many ite... | stackexchange/codereview |
I have a bunch of different ports I want to listen on and the iterate over the available data to send to a Dataflow pipeline. In total I'm listening on 14 ports. I'm looking for any advice on how to reduce the CPU usage of the following code.
I'm just passing in the ports to a method then adding them to a list:
publ... | stackexchange/codereview |
I have been starting to learn MVVM to give my WPF projects better structure.
I have to sample classes, DeviceModel and DeviceViewModel. Currently it is set up so that the model is exposed as a property within the view model. The model can then be bound to directly in the view.
public DeviceModel Device
{
get { retu... | stackexchange/codereview |
Consider a struct with a name two Int values :
struct StructWithNameAndTwoInts {
let name: String
let from: Int
let to: Int
}
Now I want to compare two structs based on the values of from and to. There are three possibilities:
Not equal: from and to from both structs are different.
Half equal: Both froms ... | stackexchange/codereview |
I recently started learning C++ again, and I wrote a simple version of Conway's Game of Life. This version doesn't use 2 buffers to transfer changes over to the main view. Instead, it uses a stack of changes that are applied then drawn.
I'd like some feedback on how to improve my code.
Controls are:
Space - Start/Stop ... | stackexchange/codereview |
I consistently have code where I need to pull individual chunks of substrings out of a larger string; while I won't get into details, it's easy to replicate in a proof of concept:
var data = "alja5nerjvnalskjnbaeviunreklvnaslidhfvbaelkjnrfvliasndve";
var open = data.Substring(0, 4);
var inputLength = int.Parse(data.Sub... | stackexchange/codereview |
Can you please help me fulfill the following?
Requirements:
Create an iterable with unique elements. Their order should be preserved:
a | b | a | c → a | b | c
The program must continually write to stdout.
The program must be computationally efficient.
The program must be written in the Functional programming paradig... | stackexchange/codereview |
I often find myself abusing dictionary objects just for the exist method like this,
For Each x in Something
If Not dict.Exists(x) Then dict.Add x, False
Next x
Then just exploit the .Exists(x) method. It happens often enough that I thought it merited it's own class.
Instead of composing Scripting.Dictionary, I d... | stackexchange/codereview |
I am trying to solve this problem:
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
and this is my implementation:
public int searchInsert(int[] numbers, int target) {
int startIndex = 0;
int endIndex = n... | stackexchange/codereview |
I have a class that I use to manage a list to/from an API in Swift. Using a clean code approach, I'm wondering if, how, and why I should change it when I have a class that uses it for just one or two functions.
Here's the class:
import Foundation
protocol ApiWishListManagerDelegate
{
func didFailWishList(failErr... | stackexchange/codereview |
This is the primary module for my APL interpreter. The general idea is motivated by my two Stack Overflow questions, but the details I fear are easy to get wrong and I suspect there are a few corners that my eyes simply don't observe critically since they have the authority of having lain in the file so long without ch... | stackexchange/codereview |
This code works well, but it's too long and looks too bad. I've tried to format it, but it all sets data, so I don't know how to make it better.
Here is the class:
private static BrandProfitAndLoss getAllRateComparisonRecords(BrandProfitAndLoss brandProfitAndLoss , BrandProfitAndLoss brandProfitAndLossComp){
BrandP... | stackexchange/codereview |
I've two versions of promise code. The page is a simple one - an unordered list with a few items. I am trying to make the items show up (fadeIn) one-after-another sequentially. This exercise is done to sort of explain people what promises are...
Version 1:
$('li').hide();
var fadeInFunc = function (obj) {
var defe... | stackexchange/codereview |
Outside of the jQuery DSL I've hardly ever written any JavaScript. I never bothered learning JavaScript until a couple of months ago. After a slow start I got stuck in and created this game today.
I usually program in Ruby, and this is proving to be an obstacle because I'm thinking in ruby while writing JS.
The code ma... | stackexchange/codereview |
Write getfloat, the floating-point analog of getint. What types does getfloat return as its function value?
gefloat would also return an integer value.
Here is my solution:
int getfloat(double *pf) {
int c, sign;
double power;
while(isspace(c = getch()))
;
if(!isdigit(c) && c != EOF && c != '... | stackexchange/codereview |
I am trying to find a way to search an Int array (all numbers are > 0) and identify sequences where the sum of each element is a specific number. One element can be in more than one sequence.
This works:
let input = [2, 52, 23, 52, 28, 47, 13, 15]
let target = 75
var result: [[Int]] = []
let count = input.count
var s... | stackexchange/codereview |
I am working on an algorithm, which should group connected Arcs. The situation is described via code examples below.
I have Arcs:
public class Arc
{
public Point StartPoint { get; set; }
public Point EndPoint { get; set; }
public bool Visited { get; set; }
public Arc Successor { get; set; }
public A... | stackexchange/codereview |
I have a personal website that I use to share videos and images with friends. Below is a media generator using JavaScript and HTML. Its main purpose is to display one image at a time at the click of a button, but any type of media can be displayed. My goal was to create a fast-loading page to hold all of my media.
//... | stackexchange/codereview |
I have to implement a double linked list as an exercise for a further education.
There are three interfaces which have to be implemented:
IValueElement
package schnittstellen; // schnittstellen == interfaces
public interface IValueElement
{
public String getName();
public void setName (String paramName);
p... | stackexchange/codereview |
I've tried implementing priority queue with fixed size in Java using TreeSet and overriding add() method:
public class FixedSizePriorityQueue<E> extends TreeSet<E> {
private final int capacity;
public FixedSizePriorityQueue(final int capacity) {
this.capacity = capacity;
}
public FixedSizePrio... | stackexchange/codereview |
I've been working on implementing a doubly linked list from scratch in Java, and if anyone has time, could you critique it?
class Node {
Node prev;
Node next;
int data;
public Node(int d) {
data = d;
prev = null;
next = null;
}
}
class LinkedList {
Node head;
publi... | stackexchange/codereview |
I've written code that solves a problem from codewars.com. My code passes all the tests on the codewars site. It's a simple enough problem to solve naïvely, but I would love to improve the structure.
The prompt for the problem is as follows:
Write a function, persistence, that takes in a positive parameter num
and r... | stackexchange/codereview |
Below function checks if a grade exists
----------------------------------------------------------------------------
-- CHECK IF THE VALUES WE PASSED AS PARAMETERS EXISTS AS A ONE ROW RECORD IN THE TABLE
----------------------------------------------------------------------------
function record#exists(
i_m... | stackexchange/codereview |
Background:
I am currently in the process of abstracting and refactoring out EF for Dapper with Dapper.Contrib and the entity class definitions from EF are currently being generated by a T4 template. I have not swapped out the entities entirely for generic POCO base classes as yet as the EF implementation is functionin... | stackexchange/codereview |
Inspired by the recent surge of questions dealing with changing numbers to their English equivalents (See here, here, and here), I decided to write my own version in Python.
zero_to_nineteen = (
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"... | stackexchange/codereview |
I'm pretty new to ASP/MVC but have had some prior programming experience.
I am trying to retrieve statistics about URL clicks - total clicks and unique clicks by IP address. I started with:
ViewBag.ClicksToday = context.EmailLinkClicks
.Where(c => c.CreatedOn == DateTime.Today).Count();
ViewBag.ClicksWeek = conte... | stackexchange/codereview |
Let's assume I have an enum type
enum ComponentState {
TURNED_OFF,
TURNED_ON,
SUSPENDED,
TO_REPAIR;
}
This enum describes a state of some component. Now let's assume I want to export my component to as XML file. Then, of course, I'm going to import my component. So:
//Export:
componentElement.setAttrib... | stackexchange/codereview |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.