instruction stringlengths 71 71.9k |
|---|
I based this implementation upon the implementation given in this answer and the book linked in it, but modified it to, instead of a constraint list and a substitution stack, generate a substitution tree in a single tree traversal operation.
Each node in the substitution tree is a VariableType. Child nodes are in the ... |
I'm in a location with poor Internet access. In order to ensure that a call to an external service succeeds, I am wrapping the call in a pseudo-do-while in Python. Additionally, I am limiting the call to running a maximum of three times:
def post_safe(url, params):
done = 0
max_tries = 3
messages = []
... |
I am trying to write clean code in Java for reading text of any size and printing the word count in ascending order without using Java collection framework.
For example, given the following input text "What is the your name of the name?", it should print:
your 1
of 1
is 1
What 1
name 2
the 2
I have written the below c... |
I have a function which sends an email via outlook when given text, a subject, and recipients shown below:
def __Emailer(text, subject, recipient, auto=True):
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
if type(recipient) == type([]):
... |
This morning, I wrote a quick-and-dirty table-revision generation script: (gist). It is intended to be run in the command line. Here's the entirety of it (149 lines):
/**
* Creates a revision table for an already-existing table.
* TODO: Better error checking/handling
* TODO: Sanitize table name input
*
* Usage:
... |
I'm at loggerheads between performing operations one-by-one within a method, performing all of them at once (in one block) within the method, or breaking them up into four different methods.
In terms of best-practice, which of the following three options seems most advantageous, and why would it be preferred over the o... |
bool loadFileContents(const std::string& fileName, std::string &out) {
bool res = false;
FILE* file = fopen(fileName.c_str(), "r");
char buf[128] = { 0 };
if (file) {
while (fread(buf, 1, sizeof(buf), file))
out += std::string(buf);
res = true;
}
fclose(file);
ret... |
These arrays are the result of Store Procedure. They are to build a Google Chart, therefore I need transform the array to a specific format. I also want to remove the $col and $row elements that have a Null value. These arrays are dynamic to their length variable, but a $row element array always has the same length ... |
I recently read the book Clean Code and I also did some research on the SOLID principles. I'm looking for general feedback on if I was able to transpose the examples (written in Java) to Python while still maintaining a "Pythonic" program.
I wrote a simple TicTacToe game in Python using Tkinter as the GUI and I tried t... |
I wrote a simple tool to allow to daemonize any process under Microsoft Windows.
The goal is to push any process into the background with no questions asked. That includes GUI applications, which means that the main window will not be created...or at least not shown. For console applications it will simply detach the p... |
Elsewhere, there was a question about finding an elegant solution to a particular problem, and the following solution was presented.
I'm curious whether this solution is elegant from the perspective of easy to understand for a Ruby programmer (which I am no longer).
merged_file = File.open("merge_out.txt", "w")
files ... |
A few months ago I wrote this module but, coming back to it, I find it a bit hard to read and reason about. I want to ask community's opinion on whether this needs to be refactored, and how I could approach this.
(function (q) {
'use strict';
var DELAY_BEFORE_RENDERING_NEXT_PAGE_VIEW = 3 * 1000;
window.st.view... |
I have the following factory class, wonder if this code can be implemented in better way. I saw few discussions about spring factory bean, but don't find good examples.
@service
public CustomerSearchFactory{
@Autowired
private CustomerSearchByID searchById;
@Autowired
private CustomerSearchByName searcyByName;
... |
I'm making a Windows service that watches a directory for new files to process them.
I hit a race condition between the file copying going on and me trying to process it. Going by a SO answer I wrote the following wait-and-retry method to make sure I can work with the file:
public static void WaitForFile(string file, C... |
Background of the problem
My Class level variables:
static int secondsInterval = 100000000;
static long secondsSpecial=0;
static Date dateSecondsReg;
static Integer intValue;
I have a function which uses the standard Java Calendar:
The function accepts a value in long(Which is seconds elapsed from a ... |
As I understand it, blowfish (actually eksblowfish, as it's used one way) is generally seen a secure hashing algorithm, even for enterprise use (correct me if I'm wrong). Because of this, I created functions to create and check secure password hashes using this algorithm, and using the (also deemed cryptographically se... |
I tend to write quite explicit tests for my rails controllers exposing APIs with two seperate concerns:
meeting the defined API-Response with headers headers and the response itself
ensuring the right calls to underlaying methods/objects are made
However when the calls are not simply executable in a test the controll... |
I have two threads - one thread queues items another thread dequeues. dequeue is fast enough and so we can assume that queue is never contains more than 65536 items.
C++ doesn't contain "ring-buffer." Boost has one, but it doesn't allow "reuse" of elements. So I wrote my own ring-buffer, which I think is very fast and... |
Is it possible to create dynamic TR and TD elements in an HTML table? Something similar but better than this:
jQuery(document).ready(function() {
$('button[name="new-title"]').on('click', function(){
var table = $('table[name="errortitle"]');
var tr = $('<tr />');
var td = $('<td />');
var input = $(... |
I am getting data from JSON and then create rows of it:
$.each(data.GetwebMethodResult, function (index, item) {
$("#TableABC").append(FunABC(item.aID, item.b, item.c, item.d, item.e, item.f));
});
function FunABC(a, b, c, d, e, f) {
var row =
"<tr class='Row' onclick=\"AnotherUnrel... |
I have a class foo that needs to get input from different sources, namely input streams,
arrays and iterators. The code that actually does the work in the end takes iterators as
input, and all the other methods end up calling it behind the scenes:
void from_stream(std::istream& in); // Read from stream and insert at en... |
I'm wondering about the following code:
def ValidateGoto(placeToGo):
conditions = {}
conditions["not placeToGo"] = "Enter a positive integer in the text box"
conditions[
"int(placeToGo) <= 0"] = "I need a positive integer in the text box please"
conditions[
"not DataStore.DBFILE... |
I created a JS widget library for distribution purpose on external websites and would like your thoughts on it.
What widget does: It adds an always visible text on the screen. When user clicks on text, an external page gets loaded in iFrame in a lightbox. Internally, widgets loads jQuery library and some external JS an... |
I have a process, let's call it Proc1. It is installed in two different directories and one instance of each is running:
C:\DirA\Proc1.exe
C:\DirB\Proc1.exe
When iterating through all currently running processes, I need to be able to differentiate one from the other. I do this by looking at the full path to the pro... |
Background
This is my first experience with functional programming and totally self-study. I just have 2-3 days' worth experience in Haskell. Now let's continue with actual code.
For Problem 2 of 99 haskell problems I wrote this function
module Functions
(
lastButOne
) where
lastButOne :: [a] -> a
lastButOne [a, b] ... |
I'm looking for advice how to improve the code. It's a mess, but I don't know how to improve it. There are some mathematical errors, projectile movements are behaving strangely, code is messy in general, unit positions are off, etc.
var canvas = document.createElement("canvas");
canvas.id = "canvas";
var ctx = canvas... |
Since I am new to MVC and the Entity Framework, I have been struggling to grasp the concept of creating useful Data and Service layers. I have come across a scenario where I believe my code has become very redundant:
Data Access Layer:
public static class DeploymentOrderDataLayer
{
public static usr_OrderF... |
I am doing a little in-between semester reading in my C++ book, and I came up with the wonderful idea to try to make Yahtzee in C++. So far the code generates 5 random numbers and then calls the function that I made to display a rendering of the die. I cannot figure out how to allow the users to hold the dice that they... |
This thing kills me:
def report_subtitle
case params[:kind]
when 'position' then h("for Position: #{@current_company.positions.find_by_id(params[:id])}")
when 'grade' then h("for Grade: #{params[:id]}")
when 'location' then h("for Location: #{Location.find_by_id(p... |
I'v written this code snippet that's part of a code competition.
I want to do the trick without the for-loop, or simply find a way to optimize this code for speed.
for ( i=1; i<=N; i++ )
How is it possible, if it is? What do I need to modify to speed up this code considering a very large input file?
Here is the c... |
From a previous question, I got the idea of moving boilerplate code structures into a helper function and passing in a lambda function to it.
I then applied the idea to a data access class (code below). I'm not sure how to handle the result of my ProcessDatabaseCall helper function; it seems irrelevant to my pattern o... |
Which style of printing strings from the SI registry in NASM is more correct?
I'm learning assembly and x86 architecture, but I'm rather new in it, so I've prepared two styles (in NASM) of printing a string, which is held in the SI register.
For a clear text, the samples are at the bottom of the question content. I al... |
I wrote this function to find the index of the first substring. I was wondering if you can help me find some flaws or possibly help increase performance?
Example:
str = "happy" substr = "app"
index = 1
My code:
public static int subStringIndex(String str, String substr) {
int substrlen = substr.length();
int ... |
I'm looking for a review paying special attention as to whether the code can be optimized in the form of number of variables used, especially for the delete() method.
public class circularLL {
Node start;
Node last;
circularLL()
{
start=null;
last=null;
}
class Node
{
... |
I have a text file that contains name, age, salary, hoursWorked, randomText and are filled with different delimiters.
Text file:
susan:25-2600,28[asd]
mary:21-2200,38[asd]
john:23-3400,46[asd]
Instead of breaking them into individual strings using the code shown below:
string name,age,salary,hoursWorked,randomText;
if... |
To catch errors, I have written if-else blocks in every function which looks bad. Please suggest a better way to handle errors in async node.
async.waterfall([
function(callback){
fnOne.GetOne(req, res,function(err,result) {
if(err){
console.erro... |
I am thinking about passing a private variable of one class into another class, for some belonging case like 'company --> department --> employee'. As an employee can tell some information of his company, there's some private variables I'd like to pass.
I think this relationship is not as same as common class and supCl... |
I currently have a basic application that has a database backing it. I originally connected to the database with Entity Framework, but my tutor has requested from me to recreate the functionality with ADO.NET SQL. This has gone well so far using the SqlDataReader, however I have come across a problem.
My database store... |
I am pretty new to Python and just wanted to make sure I am going in the right direction with my coding style.
After reading this, I'm not so sure.
The following is a convenience class that has operations used a lot in my main code.
import requests
try: import simplejson as json
except ImportError: import json
"""
Ba... |
I am not new to html however would like to know about best practices. I need to develop a layout like this:
This is what I have proposed:
<div id="body">
<div id="body-main">
<div id="body-main-upper">
<div id="body-main-upper-image">
<image></image>
</div>
... |
Refactor this code so that I don't have to insert the parameters any time I need to use one of the functions.
I have a class, say julian, for calculating Julian dates of today, a date I insert and the difference between these two Julian dates.
int julian::calc_julianToday()
{
time_t t = tim... |
I have written a wrapper for Soap based 3rd party web service.
https://gist.github.com/veganista/bd940750d9e240e63b89
I'm pretty happy with it so far (I think, anyway). It's only a small sub-set of what the full API offers but will suffice for my needs at the moment.
I'm looking for some criticism from some other deve... |
Continuation of this question: https://codereview.stackexchange.com/questions/36561/unit-of-work-with-generic-repository-pattern-mvvm-vol-2
I have made some modifications:
Implement lazy-loading (hope so)
Add() and Update() returns T instead of void
Add IFeedItemRepository, FeedItemRepository, IBaseRepository<T>
IBas... |
Here's a problem that I tried solving:
Lakshagraha was a house built of lacquer, made by the Kauravas to kill
the Pandavas. The Kauravas wanted to burn the house down when the
Pandavas were asleep at night. But poor Kauravas – once again they
underestimated their cousins. Having been warned of the nefarious
p... |
I want to create a class ClientSocket with PHP, which is an adapter of the fsockopen, fread, and fwrite.
Class ClientSocket extends SenderAdapterAbstract
{
private $s = null;
public function __construct($host, $port)
{
$this->s = fsockopen($host, $port);
}
// Abstract method concrete imple... |
A job application of mine has been declined because the test project I submitted was not coded in a clean and straightforward way.
Fine, but that's all the feedback I got. Since I like to continuously improve my coding skills, are there people here who want to check out this project at Github? It's not complicated of c... |
I have designed the following input validation implementation with one goal: DRY. I'd like to know whether it is intuitive and what are the possible shortcomings.
$vlad = new \ay\vlad\Vlad();
$test = $vlad->test([ // Test script
[ // Group of selectors and validators. Each selector is assessed against each validat... |
I have this script that moves a box around the screen and the loops the second part of the movement. I have altered the code to drop another three boxes (4 in total) into the animation so the boxes follow each other around the screen.
I want it to work exactly like it does, but I'm sure there's a much better way of doi... |
This is code for FizzBuzz. I have also hosted in on my GitHub.
FizzChecker Tests
[TestClass]
public class FizzChecker_Tests
{
IFizzChecker _fizzChecker;
bool isFizz;
[TestInitialize]
public void TestInitialize()
{
//Arrange
_fizzChecker = new FizzChecker();
isFizz = default(... |
Suppose I have a text file which contains 10,000 random values between 0 and 1, and I want to count the number of values within a specific interval. An example may explain it more clearly.
Suppose my Datefile.txt contains data like:
0.0102244
0.028072
0.0144578
0.064578
0.08148
0.012749
0.12749.....and 10,000 more val... |
My company has asked me to write a few Java based programs to deal with sending HTTP requests and parsing the response. After playing around with the Apache HTTP Commons library and making plenty of shortsighted programs using it, I've decided to make a little library for us to use and avoid major code duplication. We'... |
There must surely be a nicer way of writing this.
The wrinkle of complexity is that prev_seq or next_seq might be an empty string if the user moves the question to the first or last position, but it could also validly be '0.0' so I can't just rely on 'falsiness'.
I hope it's clear what I'm trying to achieve from the be... |
I have written a function for switching advert image based on $template. Function is working completely fine without any problem and getting everything dynamically with no issue.
Concerning performance, I want some feedback and suggestion from you experts to optimize code in better way.
Since below code is dynamically ... |
This is a .wav to .flac encoder that I wrote a little while ago. The only method that is really called is encode(), which takes in a .wav file, converts it to FLAC, and stores it in the .flac file that is taken in as a parameter.
I would prefer suggestions on how to improve the method, decrease run-time, or cut down o... |
I have been using HTML and CSS for a long time, and just starting to learn jQuery. I created a calculator by myself from research and trial and error. I would like someone to let me know what I'm doing wrong (pertaining to the jQuery) as far as code efficiency, structure, and comments.
Here is the HTML:
<!DOCTYPE htm... |
This 43 line program is designed to listen for Syslog messages on port 514 and record the messages to an MS SQL Server database table.
I would appreciate feedback from experienced node.js developers.
I am just starting to learn node.js. I'm average at JavaScript, still getting my head around closures. I am really str... |
I have an ASP.NET application which uses a Service Reference to a (third-party, offsite) payment processor.
The service reference class is generated automatically.
Its implementation is a subclass of ServiceModel.ClientBase, which
MSDN documents as, "Any instance members are not guaranteed to be thread safe."
Is the ... |
The following class's method public IAsyncResult BeginInvoke(Delegate method, object[] args) is called by a third party dll. This dll may or may not be multi-threaded.
The dll also calls public bool InvokeRequired { get; } to check if it should call the BeginInvoke method. The third party dll does this every time it ge... |
I have a business object base class which is inherited by my business objects:
public class ErrorBase
{
public bool HasError { get; set; }
public List<Error> ErrorList { get; set; }
public ErrorBase()
{
HasError = false;
ErrorList = new List<Error>();
}
}
Can this be optimized? My ... |
Below is my Interface:
public interface IDBClient {
public String read(ClientInput input);
}
This is my implementation of the interface:
public class DatabaseClient implements IDBClient {
@Override
public String read(ClientInput input) {
}
}
Now I have a factory which gets the instance of DatabaseCl... |
I am struggling with commenting and variable naming. My teacher says my comments need to be more explanatory and explicit. He says my variable names are also sometimes confusing. I was just wondering whether you could go through my code and see whether you are able to understand the comments and add in comments/edit wh... |
OK, maybe crazy overkill and a little silly, but why not? Here's a Python FizzBuzz Acceptance Test:
import unittest
from fizzbuzzmodule import fizzbuzz
class FizzBuzzAcceptanceTestCase(unittest.TestCase):
'''
Test that fizzbuzz(int) returns int
unless multiple of 3 (then returns 'fizz')
multipl... |
This was a project I worked on for fun that basically uses a genetic algorithm to produce simple Brainfuck programs that output whatever the user specifies.
I was just was hoping for criticism of the code, mainly if I'm doing anything blatantly wrong. I'm not too familiar with the STL, so there may have been algorithms... |
Say you have a dictionary some_dict and want to make sure there's no key some_key in it. What's the best way to do this stylistically speaking and why?
Option 1
some_dict.pop(some_key, None)
Option 2
try:
del some_dict[some_key]
except KeyError:
pass
Option 3
if some_key in some_dict:
del some_dict[some_k... |
This is my first shot at implementing a fully static version of the Observer pattern in C++11. It is static in that all notifications are dispatched via CRTP, and therefore there is no virtual overhead. It also has the benefit of catching unimplemented notifications at compile time, by checking available overloads ba... |
Assume the following requirements:
Is it a good idea to use the Composite design-pattern for this, taking into account that there will be:
Only 1 TestPlan
a TestPlan can only have TestSequences
a TestSequence can only have Tests
a Test can only have Asserts
I've started coding using the Composite pattern but I got t... |
Introduction
I have a hierarchically nested tree class (like SampleFolder, s.b.) that I want to serialize.
The problem arises with the collection of sub items like this one:
List<SampleFolder> subFolders;
I do not want to load the entire tree but only one folder at a time, when I deserialize!
So instead of creating ... |
In a sorted array, I am trying to find pairs that sum up to a certain value. I was wondering if anyone could help me improve my code in performance or memory. I believe my code is O(n). If there are other method for finding pairs the sum up to a certain value that is much more efficient, I am open to these methods!
sta... |
I'm working on a simple program and am trying to make it faster.
import time
import numpy as np
import matplotlib.pyplot as plt
import pp
first_file = open("ac_data.dat", 'r') #real dataset includes about 20000 terms
res_file = open("res.dat", 'w')
times_file = open("times.dat", 'a')
#times = [0.000000, 0.000500, 0.0... |
I have implemented the shuffling algorithm of Fisher-Yates in C++, but I've stumbled across the modulo bias. Is this random number generation by rand() correct for Fisher-Yates?
srand(time(NULL));
vector<int> elements;
// push numbers from 1 to 9 into the vector
for (int i = 1; i < 9; ++i)
{
elements.push_back(i);... |
I want to share something with this community. I did a class connection between Python and MySQL. I hope you can help me with this project and help me do a better class.
Here is the class connection code:
import mysql
__author__ = 'Alejandro'
import mysql.connector
from mysql.connector import errorcode
class Mysql... |
<?php
/**
*session.php
*danutz0501
*@copyright 2013
**/
//defined('BASE_PATH')||(header("HTTP/1.1 403 Forbidden")&die('403 - Acces direct interzis.'));
class session{
private $db, $table_name = 'session_data', $session_name = 'PDOSESSID', $session_litetime = 1440;
private static $instance = null;
public ... |
So I have built a clock widget. It basically has 2 hands and displays a time, either the current time or a selected time. There is another option which tells the clock if it should move around as the time does.
Is this a good way to do this? It seems to work well in my app but I was wondering if there might be some p... |
Please review for readability.
/*
Takes a screenshot of the current tab, then scales it to width and height.
Returns null if the tab is smaller than width and height.
Crops the screenshot to maintain aspect ratio.
Also crops the screenshot to avoid scaling down by more maximumScaleFactor.
*/
var GetCurrentScreenshot = ... |
Here's Project Euler problem 451:
Consider the number \$15\$.
There are eight positive numbers less than \$15\$ which are coprime to \$15\$:
\begin{align*} 1, 2, 4, 7, 8, 11, 13, 14. \end{align*}
The modular inverses of these numbers modulo \$15\$ are:
\begin{align*} 1, 8, 4, 13, 2, 11, 7, 14 \end{align*}
b... |
I have a specific method that I like because it lets me decide whether or not I want to use the default. If I want anything different I enter in :option => value otherwise I get the default. Here's a concrete example that works, but is a little ugly.
How can I accomplish the same thing in a more elegant manner?
def con... |
I've just complete a Pig Latin translator as a code kata and I was hoping someone would review it for me.
Here is the kata:
PigLatin Kata
Create a PigLatin class that is initialized with a string
- detail: The string is a list of words separated by spaces: 'hello world'
- detail: The string is accessed b... |
I want to first search for a specific regular expression.
If it is not found then I would like to search for another regular expression
If that one is also not found then I would like to search for a third
(And so on...)
Whenever a matching regular expression is found, I want to return a String array containing:
The... |
I'm trying to make a simple UI to better understand how interfaces and the System.Windows.Forms Controls behave.
Like the above namespace, I will be able to get and set the Focus on a particular control, with a helper method to drill down to see which Control (or child Control) actually has the focus. I'm pretty rubbis... |
I've been coding for a while, but this is the first actual project I've made. I generally do contest programming, and as you might imagine, good code practices are not exactly the top priority. I'd appreciate any pointers, whether overall design of the program, or variable naming, or things that I should have split up ... |
I had an overloaded method, but Grails doesn't allow overloaded methods in controller actions. The overloaded method looked like this:
def punch(User user, User source) {
user.userVersion++
punch(user, source, null, null)
}
def punch(User user, User source, String latitude, String longitude) {
UserP... |
I have been slowly getting more and more "at home" with Android development and I would like some guidance. I have made an app that uses a ListActivity, that attaches to an SQLite DB. I'm using the onListItemClick function to fire up a "single record view" where I can delete and edit the record. There is also a way to ... |
I'm working on a Project Euler problem and am trying to get the smallest prime factor of a BigInteger:
private static BigInteger smallestPrimeFactor( BigInteger n ){
for( BigInteger i = new BigInteger("2"); n.compareTo(i) >= 0 ; i = i.add(BigInteger.ONE) ){
while( n.mod(i) == BigInteger.ZERO )
r... |
In our company we have a machine hostname as -
dbx111.dc1.host.com
dbx112.dc2.host.com
dcx113.dc3.host.com
Here dc1, dc2, dc3 are our datacenter and we will be having only three datacenter. But it might be possible that they can have more dots in between separated by another domain.
Now I need to find in which datac... |
I am studying Clojure and functional programming. I wrote this function to compute the centroid of a polygon specified as a vector of points, e.g. [[10 20] [0 11] [50 30]]).
Here you can read how to compute the centroid of a polygon.
Can you give me hints and suggestions on how to improve this code from a functional c... |
I am building a Webhook model so users can receive data from a messaging app.
I have never created such a system before, and I'd like to get some feedback on my attempt.
$url = 'https://www.example.com/user-webhook-request.php';
$handshakeKey = "1234abcd";
$data = array('title' => 'Hello',
'message' => 'World',
'url'... |
I have attempted the GUI controls creation in a prompt based on data from dictionary. Is this the best way of implementing this?
import sys
from PyQt4 import QtCore, QtGui
class MessageBox(QtGui.QDialog):
"""docstring for MessageBox"""
def __init__(self, data=None, parent=None):
super(MessageBox, sel... |
I would like to share a part of some code written several years ago (I have changed from mysql to mysqli); this code works perfectly. I am new to my company, and our senior programmers wrote some extra lines to optimize branch predictions. My question is: is it necessary to follow this code? Does it improve performance... |
I'm doing a clock in javascript and I am not sure this way is the best way to rotate the pointers.
Is this ok, or is there a better way?
// browser vendors
var browsers = [
'webkit',
'Moz',
'ms',
'O',
''];
// function to move the pointers
function moveMe(el, unit) {
var deg = unit * 360 / 60... |
I wrote a simple emacs module that generates standard templates that I use for my blog's static site generator.
(defun hakyll-site-location ()
"Return the location of the Hakyll files."
"~/Sites/hblog/")
(defun hakyll-new-post (title tags)
"Create a new Hakyll post for today with TITLE and TAGS."
(interactive ... |
I have tried to design a class for a complete graph.
Needless to say, disadvantages of my current solution are very visible:
dependent inputs have led to verification headaches.
In this code we rely on 2 inputs set of nodes and edge map. This creates the need to add a special verification function called addEdgeVerifi... |
I'm very new to C, so pointing out better ways of doing things, errors, bad practices, etc would be optimal at this stage.
Code on GitHub
#include <stdio.h>
#include <stdlib.h>
int *calculateFibonacciSequence(int n, int start)
{
int i;
// Allocate memory for our fibonacci sequence from the heap
int *numbers = m... |
I have a naming problem: lists with un-named elements. I wish to get the names of the elements in the list, without going back upstream to where the list was created. An example is modelList below:
## naming problem
lmNms <- c( "mod1", "mod2", "mod3", "mod4", "mod5", "mod6")
lapply(lmNms,
function(N) assign(N,... |
Not long ago, I posted this dynamic stack for review. Now I wrote a new version, which is hopefully a better one.
Please take a look and let me know how I could improve performance and increase code quality.
It works by storing pointers to the content. If there's not enough memory, it will try to increase the allocated... |
I am new to C++ and would like to know the most efficient way of forcing a user to enter an integer. Here is my function that I have created. Please show me the best way and explain why it's better than this.
int getInt(){
int x;
while (true){
cout << "Enter an int." << endl;
cin.clear();
... |
I wrote this function for Project Euler Problem 1.
prob001 :: (Integral a) => [a] -> [a] -> a
prob001 a b = sum [x | x <- a, product ( map (x `rem`) b ) == 0]
The use is like this
GHCi> prob001 [1..999] [3, 5]
233168
But I am not at all satisfied with it. The list comprehension looks like something I have taken from... |
I know that there is one more topic about the exercise 4-11, but the difference is that I solved this exercise and i just need some feedback on my solution. So, I'll explain how it works on an output like "3 4 +\n", for example. The static variable c is initialized with the value ' ' so the condition of the first if st... |
In several places, I have some code that looks like the following, the only difference is in the type of listener.
public class CustomFragment extends android.app.Fragment {
SomeListener listener;
@Override
public void onAttach(android.app.Activity activity) {
super.onAttach(activity);
// ... |
I'm a Java/C coder getting started with some Python for a side-project. I've written some unit tests for a recent side-project I'm working on, but I have a sinking suspicion I'm just writing Java-code, translated into Python.
I've posted a small sample of some unit-tests I wrote. I'd really appreciate any advice in h... |
I think my code works pretty well, although I'm biased: http://jsfiddle.net/AHKb4/2/
Basic Overview: I'm working on building a math skill game, where the objective is to drag and drop div's to a container. Each div will have a value, likely set with classes. Each container must equal theSumNum to pass the level. Just g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.