instruction_seed
stringlengths
71
95.1k
_source
stringclasses
1 value
Here is a self imposed exercise and solution to learn Scalaz state monad. How can I refactor it to take it to the next level? So far I've only studied the state monad so would welcome suggestions on introducing other Scalaz features of relevance, as well as general Scala style/approach. Exercise Use state monad to s...
stackexchange/codereview
We have a string text = "SOME OTHER TEXT WHITE SPACES AND NEW LINES [HitObjects] 109,192,7241,1,0,0:0:0:0: 256,192,7413,1,0,0:0:0:0: 475,192,75865,1,0,0:0:0:0: 329,192,86524,1,0,0:0:0:0: 182,192,256242,1,0,0:0:0:0: 256,192,306521,1,2,0:0:0:0: WHITE SPACES AND NEW LINES " The third number of every row is the millise...
stackexchange/codereview
A problem from Coderbyte. Find the longest word in a sentence after removing the punctuations and if two or more words are of same length return the first word Below is my solution: def cleanWord(word): # To remove punctuations punctuations = ['!','.','\'','"',',','&'] new_word = '' for c in word: if c in ...
stackexchange/codereview
This script is designed to be run via windows task scheduler once per day. All callables passed to this function should only return a bool. The callables are called until either the maximum number of call attempts is reached, or until they return True. If one or more callables returns False, the program will sleep for ...
stackexchange/codereview
I know this is basic, being a Bash beginner, I like to learn the level of checking and testing when calling commands like; cp, mkdir, wget,... in a Bash function, and returning a result for the function execution status. For example, consider the following function. # copy a file to a directory # ${1} : full file path...
stackexchange/codereview
I want to build a set of builders for generating test data. On one side I want my builders API to be natural to use for my teammates. On the other side I'm great fun of creating DSLs, because it eliminates writing the same boilerplate code and let you read the code as English sentences. However, I found those require...
stackexchange/codereview
I call many dataframes (using pickle), then I extract the interesting values of each one and finally combine them. Is there a better way to do it? For example with a for loop call them automatically instead of having to repeat the code many times? #Dataframe 1 df_NB_E = pd.read_pickle('/Dataframes/Total Accuracy NB_E...
stackexchange/codereview
I wrote a program to calculate Collatz sequences for initial numbers between 1 and a given integer i, then find the one with the largest cycle length. My code is pretty fast, but I want to increase the speed more. Please have a look at my code and if there are any changes to made in my code to make it faster. import ...
stackexchange/codereview
I can't understand why this strange behavior when I call the method remotely is expensive. I have observed a performance issue when my object method called remotely compared to when it's called within the same process. To confess, I don't have good understanding of .NET remoting technology. Yes I have read few articl...
stackexchange/codereview
In my app users can create and soft-delete payment gateways something like Paypal. Users of a website can connect to the gateway and make payments. I've written the logic in a transaction also locking a matching record (on website field) which was soft-deleted by the user because of race-condition. Read code for a bett...
stackexchange/codereview
In a 2-dimensional array grid, each value grid[i][j] represents the height of a building located there. We are allowed to increase the height of any number of buildings, by any amount (the amounts can be different for different buildings). Height 0 is considered to be a building as well. In the end, the "skyline" when...
stackexchange/codereview
I have the actions and the times in an instructions.js file: module.exports = { temperature : { "00:00" : 100, "01:00" : 110, "02:00" : 120, "03:00" : 130 }, ventilation : { "00:00" : 0, "00:30" : 25, "01:30" : 75, "02:30" : 100 }, end : "03:30" } Then after importing the inst...
stackexchange/codereview
Given a list of words, this program outputs the starting letters of the words capitalized. I was reviewing this question that solves the same task, but over time so many changes accumulated, that I think my programme bears little resemblance to the original one, so instead of posting it as an answer, I ask you for furt...
stackexchange/codereview
I'm trying to generate a strong(er) type wrapper for C++. I've seen the NamedType by Jonathan Boccara, but I want a slightly different behavior. Ideally I would be able to use something like using StrongInt = Named<int, "description here">; But due to limitations of C++ a const char* cannot be used directly as a templ...
stackexchange/codereview
The rules of the game are pretty simple. I'll put it here in case people don't know them It's a two player game hand game where they alternate being a batsman and a bowler. Who decides to do what initially is determined by a toss. These are the hand gestures which has a corresponding score Both the batsman and t...
stackexchange/codereview
One major annoyance in VBA programming is that it's hard to keep a secret secret. In this particular case, it's the ADODB.Connection. For reasons not germane to the post, it is necessary to be able to re-create new instances of ADODB.Connection, which also implies filling in the connection string which could contain us...
stackexchange/codereview
I am slowly learning C and C++, and decided after a few lessons to dive in myself without any help. I developed this prime number generator. It seems fast, but I'm wondering if I'm following the best practices for C++, or if I am missing anything important. #include "stdafx.h" #include "stdio.h" bool checkPrime(int Num...
stackexchange/codereview
I've got a list of dicts, data, that updates periodically and is persisted to a database. Every time data is updated, the gui needs to display the collated data in a table format. The columns of the table, in order, are TEST, RANGE and the dates of all possible dates that are represented in data. test names may contain...
stackexchange/codereview
I am currently working on Shopify webhooks which posts XML to the Colorado timber line API. But due to the order protocol of the Colorado timber line API, it is required to modify the XML posted by Shopify webhook to be restuctured. Here's how I did the restucturing: $doc = new DOMDocument; $doc->load('timber.xml'); $...
stackexchange/codereview
I've just started out writing an app that will visualize genomic data for anybody to understand. When you get your genome sequenced the raw data usually comes in the form of a VCF file. I started out by drafting parser below that essentially creates a JavaScript object out of a VCF text file. Next I think want to write...
stackexchange/codereview
I've updated my code according to some tips from a previous post and would like to post the new code for review. // Calculates and generates a report card of students final grades #include <iostream> #include <fstream> #include <string> float assignWeight; float midtermWeight; float finalWeight; float participationW...
stackexchange/codereview
Please can you review my standard exception handler for Python 3.x. It is located under the # +=+= line. The code above the line is to create an exception and so the code is code complete and runs standalone. The code is just a standard exception formatter, so users are presented with easier to read messages rather tha...
stackexchange/codereview
I personally don't like the boilerplate of most __init__ methods: self.a = a self.b = b ... So I thought this would be a nice opportunity to learn a bit more about decorators. As this is my first attempt on a class decorator I'm sure there is a lot to improve so fire away: Implementation from collections import namedt...
stackexchange/codereview
Can it be made faster, and I am a newbie to complexity but I'm pretty sure the average case for this would be O(n). Am I wrong? Output for the first list should be: (1,9), (2,8), (5,5), (-11,21) The program finds pairs of an array whose sum is equal to ten. #find pairs of an array whose sum is equal to ten #bonus do it...
stackexchange/codereview
I have a simple code that loops through a text file to fix a few things in it and I use mostly dictionaries to find and handle the adjustment. However, with larger files (about 30K lines) it seems to get exponentially slower in a specific line of a loop. This line shouldn't be so slow because it just has to access an e...
stackexchange/codereview
As part of a small game engine I'm currently working on, I have written a "NetLib". NetLib should manage different types of packages through PacketStreams which are based on TcpClients. I'm quite unsure if my implementation of PacketStream and related classes is reasonable or whether I'm overdoing it. public class Pack...
stackexchange/codereview
Here is the code as it stands right now: import numpy as np from matplotlib import pyplot as plt from matplotlib import animation from random import randint arraySize = 50 Z = np.array([[randint(0, 1) for x in range(arraySize)] for y in range(arraySize)]) def computeNeighbours(Z): rows, cols = len(Z), len(Z[0]) ...
stackexchange/codereview
I have a table with this schema: CREATE TABLE [td].[MyTable] ( [ID] [int] NOT NULL ,[FatherID] [int] NULL ) (Note: I have excluded all the columns not relevant to the discussion) I receive an [ID] as input, and I need to collect the relative record and all of its fathers in one single output. Every record ha...
stackexchange/codereview
To delete a key from a trie, there are four cases: For the explanation of trie data structure, please check the following link: http://www.geeksforgeeks.org/trie-insert-and-search/ (1) Key is not in the trie. (2) Key present in the trie as a unique key. (3) Key is the prefix of another longer key. (4) Key presents i...
stackexchange/codereview
spam = ['apples','dogs','tofu'] try: def comma(items): if range(len(items) >= 2): for i in range(len(items) - 2): print(items[i], end=', ') if range(len(items) > 2): print(items[-2] + ', and ' + items[-1]) elif range(len(items) <= 2): ...
stackexchange/codereview
A cricketer can score 1, 2, 4 or 6 in a ball. Find in how many ways the player can score a total of "n" runs without hitting 3 consecutive boundaries. Note: Scoring 4 or 6 is considered as a boundary. My solution is: int *arr; //global array to save calculated ways int waysUtil(int n, int boundaries){ if(n==0) ...
stackexchange/codereview
I want to split a song into multiple parts, given the song duration and number of parts. My code achieves that, but it feels a little "stupid" and I would like to learn a more sophisticated - and shorter - way. Particularly, I feel that the marker variable is a little overkill. I would welcome any suggestions. song...
stackexchange/codereview
I created the following program that transforms a numerical month into the corresponding textual month. I initially calculated the starPoint and endPoint in the class constructor; then I changed that calculation to the getName method. Which is a better option? Calculating in the class constructor, or in a separate meth...
stackexchange/codereview
In my Gruntfile, I use the grunt-contrib-watch task to watch a directory for file changes: watch: { releases: { files: ['source/md/releases/*.md'], tasks: ['process:auto'] } } Also, in the Gruntfile, I have a "watch" event handler. Inside this handler, I temporarily store the file path of the f...
stackexchange/codereview
I am developing a WEB based GPS system and one of its functionalities is to be able to send messages and routes to GARMIN devices. I have never been using sockets before, and for some (obvious) reason, I don't feel ready to submit my code before being reviewed by more experienced users. If some of you have the time to ...
stackexchange/codereview
I wrote a program that reads a pcap file and parses the HTTP traffic in the pcap to generate a dictionary that contains HTTP headers for each request and response in this pcap. My code does the following: Uses tcpflow to reassemble the tcp segments Read the files generated by tcpflow and check if it related to HTTP If...
stackexchange/codereview
I have a CLI wrapper for https://yakuake.kde.org/. Python 3.4.*. #! /usr/bin/env python # coding: utf-8 import click import subprocess def get_postfix(title): file_path = '/tmp/yakuake_{}_postfix'.format(title) try: with open(file_path, 'r') as f: postfix_number = int(f.readline()) ...
stackexchange/codereview
I made some games in Pygame, but I am still new to making games. I made this RPG game, and this code is just a part of the game. The game executes different Pygame files for different levels of the game as it can be seen in this part of the code (this is for random battles): if (mainCharacterCoordinates.colliderect(b...
stackexchange/codereview
The Application I have an application in testing that runs off of an MS SQL Server database. The app allows users to authenticate using Windows authentication (that is, using the Windows username the user is currently logged in with), but the need was discovered for the app to a have a built-in, independent method of a...
stackexchange/codereview
To check if a given point is inside a polygon or not is a very useful piece of code. Here is my implementation in JavaScript of an algorithm counting the number of times a ray crosses the perimeter of the polygon, and subsequently checking the parity. I have included an initial test doing a fast comparison with the rec...
stackexchange/codereview
This is an update of Using an API to obtain JSON data and get the date string and determine if data is stale This is a Nagios check that will use an API URL, get JSON data, flatten the data into a usable Perl hash, and ultimately obtain a date string. Once the date is obtained, it should recognize the strftime format b...
stackexchange/codereview
I am doubtful about the security of my PHP code. I am new to programming, but want to learn how to secure things, protect my databases from SQL injection, and other best practices. I'd like to know if my databases are safe from attacks with this code. public function __construct( $data = array() ) { if( ...
stackexchange/codereview
I started out creating a simple game in an Object Oriented way to practice. The rules are pretty simple There are two players You let one player choose if they want Heads or Tails. You assign the leftover option to the other player. You simulate a coin flip and say who won that game. More than the logic, naming con...
stackexchange/codereview
I wrote a small method for convert number from base-10 number system to any number system (code is not perfect but that is not the point). My question is if I get right single responsibility principle. Is 2nd approach better than 1st or 'charReplace' functionality is too small for creating own method ? public stati...
stackexchange/codereview
I have started a hobby project and would like to integrate better and more thorough testing practices. Since I am not too used to it, I'd love to have some feedback on the sample code below. In particular, I'd be interested in the best practices surrounding setting up data necessary to feed a particular testing functio...
stackexchange/codereview
use std::collections::HashMap; use std::collections::HashSet; use std::collections::vec_deque::VecDeque; use std::ops::AddAssign; type Vertex = u64; type Graph = HashMap<Vertex, HashSet<Vertex>>; /** * Constructs a graph from a sequence of parent child pairs */ pub fn from_pairs(pairs: &[(u64, u64)]) -> Graph { ...
stackexchange/codereview
This was my C# implementation of Parzen Window Density Estimation. The following is my implementation of the same in Matlab: parzen.m function [retval] = parzen (matrix, dataPoint, variance) [r c] = size(matrix); A = ones(r, c).*dataPoint; sub = matrix - A; up = sub.^2; dw = 2 * variance; firstP...
stackexchange/codereview
This calculates the mobility and it's derivative of one element. If I calculate with 1 value of w, it's very fast. %**setting the equation to calculate** syms m w k e mi c w t L z ; a = (((m * w ^ 2 - k) ^ 2 + (c * w) ^ 2) / (e * mi) ^ 2) ^ (1 / 8); B = 1 / 4 * atan(-c * w / (m * w ^ 2 - k)) + 3.14159 / 4; X = a * ...
stackexchange/codereview
I have a simple task: Given a sequence of real numbers, replace all of its members larger than Z by Z and count the number of replacements. I solved this task using Scala, but my code looks like imperative-style code. I want to make my code more functional. How can I rewrite my program so it becomes functional-sty...
stackexchange/codereview
I coded a (more or less) simple Tetris game as an example for some of the other trainees in my company. Since I am used to my coding style I would like to have some other people to look over it and maybe give me some advices to improve the readability of the code. Some of the class names in the code (such as actor) are...
stackexchange/codereview
This program starts with initial balance and the individual book balances which must match the initial balance to proceed. The user then enters the selections for the day along with stake, odds etc., then the program calculates the new balance with the new book balances. def main(): def balances(msg): while...
stackexchange/codereview
I've implemented a polling function with a timer in C, that every 10s checks a given condition (I've just replaced it for a log to stdout for testing purposes only) but I would like to know your opinion on this code, namely if there is a simpler way to achieve the same result, what issues may arise concerning performan...
stackexchange/codereview
In PHP how can I follow the DRY (don't repeat yourself) principle in this piece of code? The 2 classes in question share an awful lot of code. <?php interface iSelect { public static function display(); } class CountrySelect implements iSelect { static $template = 'select_template.php'; public static f...
stackexchange/codereview
Inspired by Sam's question (Brute-force string generator) and rolfl's really short version of the algorithm I started to experiment with a different approach and created one that seems to run a little bit faster (about 40-50ms for a string of length 4). As it doesn't really optimize the orginal algorithm but is a compl...
stackexchange/codereview
I have created this piece of js purely for learning purposes and I was hoping you could code review to see any mistakes / improvements I can make. Basically I have a tree structure and I will use the depth variable to work out what level of the menu I will display. Here is the code example: http://jsfiddle.net/nqGbw/5/...
stackexchange/codereview
I am trying to translate the book Game Coding Complete by Mike McShaffry 4E to modern C++17 standard and faced with the code of Mersenne Twister by Takuji Nishimura and Makoto Matsumoto. Is it right to convert random generator code from book like that: from: #include <ctime> #define CMATH_N 624 #define CMATH_M 397 #def...
stackexchange/codereview
A string that contains only 0s, 1s, and 2s is called a ternary string. Find a total ternary strings of length n that do not contain two consecutive 0s or two consecutive 1s. I have defined a recurrence relation as dp[i][j] means the total number os trings ending with j where i is the length of the string and j is eithe...
stackexchange/codereview
I've researched this morning how to use Google Analytics to track outbound page views. However, I think the implementation might be a bit difficult on our website (as we have hundreds of outbound links) Here's what google recommends. /** * Function that tracks a click on an outbound link in Analytics. * This functio...
stackexchange/codereview
I have a small gem that I've been maintaining. This gem provides a simple way to do translation using an alternative Google API. I've been working with Java last year and recently did some refactoring on that gem, but I don't think it's Rubyist enough. require_relative 'extractor' require_relative 'requester' require_r...
stackexchange/codereview
This is an interactive script for selecting and reading the manual pages from the terminal command line. This is the 3rd version of this script. If you want to see the evolution of this script, follow the links for version 1 and version 2. In previous versions of this script I had mentioned wanting to make a database o...
stackexchange/codereview
The following classes are used for web development. And I was wondering if I'm implementing them correctly specially the Base class. This is a version 2.0 of the question the classes are as follows: MyPDO Session Security Base Examples: <?php //using the autoloader require "../classes/autoloader.php"; // checking if...
stackexchange/codereview
Intro I want to visit the value held by a class, which could be of multiple types. This class is very similar to a std::any, so I will be using this in this question. I wanted to create a reusable solution that accesses the value efficiently (without recursion, or unnecessary calls), that worked similarly to how std::v...
stackexchange/codereview
(See the initial and previous version.) This time, I have incorporated all the good points made by mtj. See what I have: com.github.coderodde.weblog.viewcounter.CountViewServlet.java: package com.github.coderodde.weblog.viewcounter; import static com.github.coderodde.weblog.viewcounter.Util.objects; import com.google....
stackexchange/codereview
What would be the shortest way to capture folder structure in code? I would like to have a more or less reusable strictly typed approach to use in scripts instead of stringly typed paths we all usually deal with. Here is how a part of my simple “system info” utility looks like: static void Main(string[] args) { for...
stackexchange/codereview
I wrote basic Python code for the summation of n primes. It works but I wanted to find out how I could improve it and what shortcuts I missed. """ So this program is designed to add up the first 'b' primes ==> Prime number is defined as a number only divisible by itself or 1""" def is_prime(a): """ This f...
stackexchange/codereview
I decided to make a simple tic-tac-toe game in C++ as a small project. All help and suggestions are greatly appreciated! main.cpp: #include <iostream> #include <string> #include "TicTacToe.hpp" TicTacToe game; void turnPlayer1(); void turnPlayer2(); bool gameOver = false; int main() { std::cout << "**************...
stackexchange/codereview
I have this type: type Future<'a> () = let mutable _value: 'a option = None member x.Resolve value = if _value.IsSome then failwith "can only resolve once" _value <- Some value member x.IsResolved with get () = _value.IsSome member x.Value with get () = match _va...
stackexchange/codereview
What are anagrams? An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other def anagram_check(string1,string2): list1 = [char1.lower() for char1 in string1 if char1 != " "] list2 = [char...
stackexchange/codereview
Part 2: JSON Test Harness: Part 2 Part 3: JSON Test Harness: Part 3 Part 4: JSON Test Harness: Part 4 Time to review some test harness code I have written. https://github.com/Loki-Astari/JsonBenchmark I wrote a C++ JSON parser/serializer and wanted to compare performance against other JSON parsers. This was originally...
stackexchange/codereview
I have a class that encapsulates a PowerShell Runspace object which, among many other things, has methods for getting and setting variables in the session state. There is no apparent mechanism for enumerating the variables, only get/set. To simplify access to the variables from my code I've been using a specific index...
stackexchange/codereview
After having a good experience with virtualenvwrapper built on top of the venv, I thought maybe it could be benefitial to have similar shortcuts for standard activities with git which could be time saving as opposite to typing many commands. I've given it a try like the following: Start session (sync current repository...
stackexchange/codereview
This code is working fine, but it looks awful (yes, I am a rookie on this thing). How can I improve it to look better? Private Sub Worksheet_Change(ByVal Target As Range) 'Conditional Formatting Application.ScreenUpdating = False If Target.Column > 6 And Target.Column < 8 And (Target.Value = "G" Or Target.Value = "Y...
stackexchange/codereview
For an iOS app which helps me rolling back vandalism on Stack Exchange, I have a piece of Swift code which downloads a revision page (example) and tries to find the 'spacer' fragment just above a certain revision. It might not be clear what I'm talking about, so here's a picture from Firefox + developer tools: I have ...
stackexchange/codereview
Expected behavior of the code below: There will be one static SessionManager accessed by many threads. Multiple calls to SessionManager.UseTheSession for a given session ID must be processed on a first come first serve basis (similarly, calling EndSession should allow any currently executing UseTheSession's to finish)...
stackexchange/codereview
I'm trying to reduce the boilerplate code for the visitor/double dispatcher pattern. First I've created a way to enforce the dispatcher to declare the dispatch(T) function for every type supported and also a dispatch_gen(T) for the generic case which I don't need to implement. This is not too hard: /* A generic way to ...
stackexchange/codereview
Is there a better way (I'm pretty sure there is) to create a stored procedure to do dynamic paging, filtering and sorting than the following code? I'm actually generating this sproc from a database using a T4 template. CREATE PROCEDURE [uspProductWithPagingSortingFiltering] ( -- Optional Filters for Dynamic Search @Pro...
stackexchange/codereview
Background I added a few items to a codepen that displayed a list of beers. One of them was the citation of the brewer who gave tips. Previously the tips were just generated into a <p> but now I have wrapped it inside a blockquote Code <blockquote> <p> <span class="bright">Tips from the brewer:</span> "{{ be...
stackexchange/codereview
I have a text parser that reads certain information from a given file with a specified format. The text file contains some measured properties of a product. The date model number/lot number is written on the file name. class SomeTextFileParser { private static int POINT_COUNT = 15; string filePath; string ...
stackexchange/codereview
I am experimenting with making my own re-usable libraries. Therefore, I decided to start with some of the plots that I generally use during development/debugging to check what is actually inside my data. My questions therefore are: Would this be the correct way of writing a library? Are there any pieces of my code tha...
stackexchange/codereview
I have a method to replace URL parameters in an URL. It receives url as mandatory parameter and prefix and/or hash as optional parameters. Examples: url_replace( '/news?b=2', { b: nil } ) # => '/news' url_replace( '/news?b=2', { b: 3 } ) # => '/news?b=3' url_replace( '/news?a=b...
stackexchange/codereview
I have downloaded the latest version of the Linux kernel and I want to perform thorough analysis on it. I want to start by eliminating comments from all the source and header files that belong to it. I am using a code I wrote sometime ago and I want to use it recursively. In the past I tested it on my code and it worke...
stackexchange/codereview
I have a program that gets 5 random dice throws from random.org over and over. In order to avoid doing getaddrinfo() over and over with the exact same data, I moved some of the code to an initialization function (and an unused finalization function). My issues are: is this a bad idea? can bad things happen to the prog...
stackexchange/codereview
It's pretty typical for Linux command-line utilities that deal with files to accept either a file as input, or stdin. It's also pretty common for them to be able to output to a file or to stdout. These should be supported: python myprogram.py input output cat input | python myprogram.py > output python myprogram.py in...
stackexchange/codereview
public class BlobStorageHelper { private readonly StorageSharedKeyCredential _sharedKeyCredential; private readonly BlobClient _blobClient; public BlobStorageHelper(BlobClient blobClient) { _blobClient = blobClient; _sharedKeyCredential = new StorageS...
stackexchange/codereview
I'm using a index system to say: On index i use: <?php core::doPage(); ?> Core code is: <?php class core { public static function doPage() { if(!isset($_GET["page"]) || empty($_GET) || !is_string($_GET["page"])) { if(!include_once('./_pages/index.php')) die("404 - File not found.")...
stackexchange/codereview
I'm writing a simple sanity tool for a simple USB driver. The customer is directly facing the output so I have to care about how it looks. The log messages that I need to print are varying length, and they have "[ SUCCESS ]" and "[ FAIL ]" trailing part too and the middle is filled with dots. So what I do is calcula...
stackexchange/codereview
I had trouble solving instances of Exact Three Cover with 100 units in input C. All in a reasonable amount of time. Mainly because the problem is NP-complete. So I came up with an approximate solution (Don't ask me the ratio for correctness, because I don't know) I have gotten 100, 500 and 1000 units in C to return co...
stackexchange/codereview
I just want to know if my code can be weak. Can anyone also spot a mistake in my code? Encrypt public static String byte2hex(byte[] b) { //we know exactly how long the resulting string should be so pass that information along to minimize allocations StringBuilder hs = new StringBuilder(b.length*2); for (int...
stackexchange/codereview
I am using Telerik's Kendo UI suite for a project, and was excited when they announced compatibility with Angular, but as I got a lot of code written I realized that they hadn't yet made the widget directives work with real JSON data - it only bound and talked to bare bones primitives. This was an undesired behavior, a...
stackexchange/codereview
I have a wrapper which interacts with a third party component. In Each function i am performing the operation if it the component is initialized. I have other function to check the errorCode and component initialization check. Is this right way to do this? I am not happy with the readability of this code. Help me imp...
stackexchange/codereview
Is it a good practice to initialize the max to -100000 and min to 100000? Is there any other way to initialize both min and max to 0? import javax.swing.*; import java.util.*; public class arrayTajba { public static void main(String[] args) throws Exception { String userStringInput = " "; ...
stackexchange/codereview
I recently had the need to loop from zero to some limit only known at runtime. Instead of writing: for(int i = 0; i < limit; ++i) { // Some repetitive thing } I wanted to write something similar to what I often use in Python and D: for i in range(0, limit): # Some repetitive thing foreach(i; 0 .. limit) { ...
stackexchange/codereview
I am working with some Java code. Basically I have a wrapper class that holds a string and implements some of the many useful python string methods in Java. My goal here is to implement the Python method .ljust and my hope is to be as efficient as possible. Currently, I am using a while loop which I imagine is terrible...
stackexchange/codereview
This struct is used a lot throughout my programme. This struct is responsible for only things regarding colour, not anything else. I'm largely concerned of the bitwise operations, and the fact that I store four byte values in a uint but access them with bitwise flags. This is a concept I use throughout the programme. (...
stackexchange/codereview
I've a class called MassIndexer.java (on GitHub) and it uses chained invocation for building a batch job. Each method assigns a property of this job and finally the job will be started using method MassIndexer#start(). Here's an example for Java EE: long executionId = new MassIndexer() .addRootEntities(Company....
stackexchange/codereview
My goal is to read from standard input, break up the input into words (Unicode letters and apostrophes), case-insensitively, and produce a report to standard output, where each line is a word followed by a space followed by its count. The output should be sorted by words. This is my code: using System; using System.Tex...
stackexchange/codereview
Sometimes I need to create character vectors like this one: datanames <- c( "europe_co2_min", "europe_co2_max", "europe_temperature_min", "europe_temperature_max", "asia_co2_min", "asia_co2_max", "asia_temperature_min", "asia_temperature_max" ) Notice that this is actually the Cartesian product of the ...
stackexchange/codereview
I would like to show the tree-like structure contained in a multi-dimensional tuple by using the set of graphical glyphs that exist in Unicode fonts (e.g. \u2500, \u2502, \u2514 and others). Here is an example of the kind of output, I'm talking about: >>> showtree('(01, (02, 03, 04), 05, ((06, 07), 08), (09, (10, 11),...
stackexchange/codereview
I've written this Wack-a-mole like game on my iPad in the app Pythonista. Keeping that in mind, it uses a different graphic interface from the one I have usually seen used, Tkinter. I'm a beginner and this is my first major project, so any tips on how to code more efficiently and improve this program would be greatly a...
stackexchange/codereview
Interested in a review of this code, in particular the (hopefully monadic) bind. I actually put this to good use. It was a nice complement to Guava's Optional, and shorter than: Optional.fromNullable(x).or(y); And I threw in a bind method, which I think lifts it up into monad space. One question I wasn't sure of the ...
stackexchange/codereview