body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>Before I go too far, does this look right?</p>
<p>This is mostly to have a "central" place that hold a "hierarchical/structured" errors message.</p>
<pre><code>public static class ValidationError
{
static ValidationError()
{
Prefix = "VE";
Notice = new _Notice();
Exporter = new _Exporter();
Importer = new _Importer();
Shipping = new _Shipping();
//few others one
}
public static string Prefix { get; private set; }
public static _Notice Notice { get; private set; }
public class _Notice
{
public _Notice()
{
Prefix = ValidationError.Prefix + "NO";
MustHaveOneTreatmentOption = Prefix + "001";
}
public string Prefix { get; private set; }
public string MustHaveOneTreatmentOption { get; private set; }
}
public static _Exporter Exporter { get; private set; }
public class _Exporter
{
public _Exporter()
{
Prefix = ValidationError.Prefix + "EX";
Mailing = new Address(Prefix, "MA");
Physical = new Address(Prefix, "PH");
}
public string Prefix { get; private set; }
public Address Mailing { get; private set; }
public Address Physical { get; private set; }
}
public static _Importer Importer { get; private set; }
public class _Importer
{
public _Importer()
{
Prefix = ValidationError.Prefix + "IM";
}
public string Prefix { get; private set; }
}
public static _Shipping Shipping { get; private set; }
public class _Shipping
{
public _Shipping()
{
Prefix = ValidationError.Prefix + "SH";
}
public string Prefix { get; private set; }
}
public class Address
{
public Address(string _Prefix, string _Suffix)
{
Prefix = _Prefix + _Suffix + "AD";
}
public string Prefix { get; private set; }
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:19:22.253",
"Id": "80137",
"Score": "4",
"body": "It will help if you stated the objectives you are aiming to achieve with this code and give it some context so people can try and provide the most appropriate solution. In the meantime, you could check out [FluentValidation](http://fluentvalidation.codeplex.com/) which can help you structure your validation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:26:27.670",
"Id": "80139",
"Score": "0",
"body": "The code doesn't make much sense to me, what is it supposed to do? All I can see is a static class with a few properties that are effectively constant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:38:25.203",
"Id": "80212",
"Score": "0",
"body": "To make life easier for reviewers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you."
}
] | [
{
"body": "<h2>Naming</h2>\n<p>Class names in C#, whether they're for a static, non-static, internal, public, private, abstract, nested or on-its-own class, should be <em>PascalCase</em>.</p>\n<p>Find the intruder:</p>\n<pre><code>public class _Notice\npublic class _Exporter\npublic class _Importer\npublic class _Shipping\npublic class Address\n</code></pre>\n<blockquote class=\"spoiler\">\n<p> Only <em>Address</em> is correct!</p>\n</blockquote>\n<p>Keep the underscore prefix for private fields, it seems you're using prefixes only to avoid name clashes - this smells, because in naming what's important is <strong>consistency</strong> - using arbitrary prefixes is bad practice.</p>\n<p>Also, it's possible the nested types are not warranted, but it's very hard to tell without seeing <em>how you're using</em> this <code>ValidationError</code> static class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T14:19:05.870",
"Id": "45944",
"ParentId": "45937",
"Score": "7"
}
},
{
"body": "<p><strong>Non-static static classes</strong><br>\nYour inner classes (<code>_Notice</code>, <code>_Exporter</code>, etc.) don't seem to have any use-case where their instances have independent meaning - their state is \"hard-coded\" on instantiation, and are read-only. Why don't you just declare them as static, just like their parent?</p>\n\n<p>Instead of:</p>\n\n<pre><code>public static _Notice Notice { get; private set; }\npublic class _Notice\n{\n public _Notice()\n { \n Prefix = ValidationError.Prefix + \"NO\";\n MustHaveOneTreatmentOption = Prefix + \"001\";\n }\n\n public string Prefix { get; private set; }\n public string MustHaveOneTreatmentOption { get; private set; }\n}\n</code></pre>\n\n<p>Simply declare:</p>\n\n<pre><code>public static class Notice\n{\n static Notice()\n { \n Prefix = ValidationError.Prefix + \"NO\";\n MustHaveOneTreatmentOption = Prefix + \"001\";\n }\n\n public static string Prefix { get; private set; }\n public static string MustHaveOneTreatmentOption { get; private set; }\n}\n</code></pre>\n\n<p>This gives you a few advantages:</p>\n\n<ul>\n<li>The awkward class name issue is solved</li>\n<li>Usage is still the same</li>\n<li>No need to worry about someone making instances of your classes (since you made their constructors public...)</li>\n</ul>\n\n<p><strong>Readonly properties</strong><br>\nThis is also recurring in your code - property getters for members which are initialized only upon instantiation. If you replace them with <code>readonly</code> members, you can make your code more succinct:</p>\n\n<pre><code>public static class Notice\n{\n public static readonly string Prefix = ValidationError.Prefix + \"NO\";\n public static readonly string MustHaveOneTreatmentOption = Prefix + \"001\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:00:04.387",
"Id": "80199",
"Score": "1",
"body": "Nice answer! ...but `public static` class exposing only `public static readonly` fields? At that point one might as well put them in a configuration file!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:49:01.283",
"Id": "80214",
"Score": "0",
"body": "@MatsMug I suspect that is about what the OP had in mind when he wrote this... A C# style DSL..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:12:11.717",
"Id": "45963",
"ParentId": "45937",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "45944",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T12:10:14.847",
"Id": "45937",
"Score": "3",
"Tags": [
"c#",
"validation",
"error-handling"
],
"Title": "Simple structure that would contain validation errors messages"
} | 45937 |
<p>I was thinking about how to implement a GPS navigation for my quadcopter. I was writing some functions to calculate the angle between two positions (from home point to the target).</p>
<p>I'd like a review of this code. I am not very sure whether I was calculating the geographic position right.</p>
<pre><code>/*
* Geographic calculations
*/
float UAVNav::width_of_merid_m(const float fLat_deg) {
float fdX_m = _2PI * _RADIUS_EARTH_m * cos(ToRad(fLat_deg) );
fdX_m /= 360.f;
return fdX_m;
}
float UAVNav::dist_2_equat_m(const float fLat_deg) {
return (_PERIMETER_EARTH_m / 360.f) * fLat_deg;
}
float UAVNav::dist_2_greenw_m(const float fLat_deg, const float fLon_deg) {
return width_of_merid_m(fLat_deg) * fLon_deg;
}
float UAVNav::home_2_target_deg() {
const float fMod = 10000000.f;
GPSPosition target = m_pReceiver->m_Waypoint;
GPSData home = m_pHalBoard->get_gps();
float fLatHome_deg = home.latitude / fMod;
float fLonHome_deg = home.longitude / fMod;
float fLatTarg_deg = target.latitude / fMod;
float fLonTarg_deg = target.longitude / fMod;
float fXHome = dist_2_greenw_m(fLatHome_deg, fLonHome_deg);
float fYHome = dist_2_equat_m(fLatHome_deg);
float fXTarg = dist_2_greenw_m(fLatTarg_deg, fLonTarg_deg);
float fYTarg = dist_2_equat_m(fLatTarg_deg);
float dX = fXTarg - fXHome;
float dY = fYTarg - fYHome;
// Calculate the angle to the destination direction
// NOTE: Here the system is inverted by 90° to align the magnetic north to 0°
m_fDestin_deg = ToDeg(atan2((float)dX, (float)dY) );
return m_fDestin_deg;
}
</code></pre>
| [] | [
{
"body": "<p>You naming convention is a bit weird. My assumption is that <code>fLat</code> stands for \"float latitude\". Because it is quite easy to know the type of a variable, there's no need for having the <code>f</code> prefix.</p>\n\n<p>You don't need to cast to <code>float</code> in <code>m_fDestin_deg = ToDeg(atan2((float)dX, (float)dY) );</code>.</p>\n\n<p>You don't need the temporary variable in <code>UAVNav::width_of_merid_m</code> especially as it makes the mathematical formula harder to read.</p>\n\n<p>Your method <code>UAVNav::home_2_target_deg()</code> seems to be doing two things : returning a value and updating a member. It would be clearer to have a (const) method returning a value and another method using it to set a member.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:14:21.427",
"Id": "45941",
"ParentId": "45939",
"Score": "2"
}
},
{
"body": "<p>There are some temporary variables that you might not use, such as <code>fLatTarg_deg</code> and <code>fLotTarg_deg</code>: you can commit the operation along with the function call. </p>\n\n<p>Also, the variables (which are actually costants, probably) <code>_RADIUS_EARTH_m</code> and <code>_PERIMETER_EARTH_m</code> are breaking the <a href=\"http://en.wikipedia.org/wiki/Naming_convention_%28programming%29#C_and_C.2B.2B\" rel=\"nofollow\">standard C++ naming conventions</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:33:13.833",
"Id": "80171",
"Score": "0",
"body": "@syb0rg Hope you won't mind, but did you seriously edit my answer to add a new line?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:50:48.470",
"Id": "80174",
"Score": "2",
"body": "It seems like he did. Isn't it better that way ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:00:07.123",
"Id": "80188",
"Score": "0",
"body": "@no1 I was out of votes for the day, and I had used one of my last votes on your answer. Then I bought the unicorn animation, and I may have wanted to test it out. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:42:16.737",
"Id": "80192",
"Score": "1",
"body": "@syb0rg shame on you, if you spend 40 votes, why not buy the unicorn animation ***before*** doing so ??"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T13:33:56.920",
"Id": "45942",
"ParentId": "45939",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>You don't have <code>std::</code> in front of <code>cos()</code> and <code>atan2()</code> (which belong to <code><cmath></code>), which means you're using <code>using namespace std</code>. This is discouraged as it could cause bugs in cases of name-clashing with existing names used in this namespace (or any <code>namespace</code>, although <code>std</code> is most commonly used). See <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">this</a> for more information.</p></li>\n<li><p>I agree with @Josay about the casting being unnecessary in <code>atan2()</code>. Its two arguments are already <code>float</code>, so casting will do nothing.</p>\n\n<p>Moreover, when you <em>do</em> need casts like these, prefer <code>static_cast<>()</code> in C++:</p>\n\n<pre><code>static_cast<type>(object);\n</code></pre>\n\n<p>More info about different types of casts <a href=\"https://stackoverflow.com/a/1255015/1950231\">here</a>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T10:29:58.173",
"Id": "81699",
"Score": "0",
"body": "I use math.h for reason and don't use: \"using namespace whatever\" in the whole program."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T14:18:35.517",
"Id": "81741",
"Score": "0",
"body": "@dgrat: Okay. Without showing the `#include`s, I would not have been able to tell."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:03:44.057",
"Id": "81750",
"Score": "0",
"body": "Well, I switched to static casts. The main reason why I was not using them is, that they look ugly, make code longer and contain even more brackets."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:04:48.337",
"Id": "81768",
"Score": "0",
"body": "@dgrat: I do agree that they're quite a bit longer. It may not matter much for smaller programs, though."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T03:21:25.863",
"Id": "46694",
"ParentId": "45939",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T12:47:13.067",
"Id": "45939",
"Score": "1",
"Tags": [
"c++",
"geospatial"
],
"Title": "Working and calculating with geographic positions"
} | 45939 |
<p>This code connects to a mongodb database and returns collection objects. I am concerned about the exception handling, variable names and comments.</p>
<pre><code> import config_files
import tweepy
import csv
import warnings
import importlib
import sys
from MongodbConnections import MongodbConnections
#Disable warning messages
warnings.filterwarnings("ignore")
#import parameters
class ControlArguments:
"""
method description: confirms mongodb client connection
input: None
output: Boolean(True/False)
"""
def checkDBconnection(self):
obj = MongodbConnections(self.getEnvironment())
try:
obj.getClient()
return True
except:
return False
"""
method description: returns LR user twitter screen name
input: command line argument
output: String
"""
def getUserScreenName(self):
return sys.argv[2]
"""
method description: returns User key token
input: None
output: String
"""
def getUserKeyToken(self):
return sys.argv[5]
"""
method description: return user secret token
input: None
output: String
"""
def getUserSecretToken(self):
return sys.argv[6]
"""
method description: return congif file object
input: None
output: importlib module
"""
def getConfig(self):
return importlib.import_module('config_files.config_'+self.getEnvironment())
"""
method description: return application consumer key
input: None
output: String
"""
def getApplicationConsumerKey(self):
return self.getConfig().application_consumer_key
"""
method description: return application consumer secret
input: None
output: String
"""
def getApplicationConsumerSecret(self):
return self.getConfig().application_consumer_secret
"""
method description: confirms if 6 argumets are sent
input: None
output: Boolean
"""
def checkArgumentsLength(self):
if len(sys.argv) == 7:
return True
else:
return False
"""
method description: returns keyword
input: None
output: String
"""
def getKeywordsIds(self):
return sys.argv[3].split('%')
"""
method description: returns environment of execution
input: None
output: String
"""
def getEnvironment(self):
return sys.argv[1]
"""
method description: returns debugger object
input: None
output: importlib object: debugger
"""
def getDebugger(self):
return importlib.import_module('config_files.debugger')
"""
method description: returns keyword from keyword ids
input: None
output: List of Strings
"""
def getKeywords(self):
keywords = []
obj = MongodbConnections(self.getEnvironment())
for keyid in self.getKeywordsIds():
try:
word = obj.getKeywordIndexCol().find_one({'keyid':keyid})['keyword']
self.getDebugger().info([keyid, word], self.getConfig().debug)
keywords.append(word)
except:
return False
return keywords
"""
method description: confirms user oAuth authentication
input:None
output: Boolean
"""
def twitterAuth(self):
try:
auth = tweepy.OAuthHandler(self.getApplicationConsumerKey(), self.getApplicationConsumerSecret())
auth.set_access_token(self.getUserKeyToken(), self.getUserSecretToken())
return [True,auth]
except:
return [False,0]
"""
method description: confirms, connects and returns twitter api object
input: None
output: api connection object
"""
def connectTwitterAPI(self):
try:
auth = self.twitterAuth()
api = tweepy.API(auth[1])
api.rate_limit_status()
return [True,api]
except:
return [False,0]
#extract keywords
"""
method description: returns autofavorite mode of user
input: None
output: integer(1/0)
"""
def getFavoriteMode(self):
try:
auto = int(sys.argv[4])
if auto == 1 or auto == 0:
return [True,auto]
else:
return [False,0]
except:
return False
</code></pre>
| [] | [
{
"body": "<p>So some minor comments to kick things off:</p>\n\n<p>Your method names are not PEP8 compliant. Usually camel case is avoided in Python. Names like <code>checkArgumentsLength</code> should really be more along the lines of <code>check_arguments_length</code>.</p>\n\n<p>It is bad practice to put <code>sys.argv</code> reads in the middle of your classes. Imagine a case where someone imports your code from Ipython, or from another script. This will cause it to break when no command line arguments are found (or the wrong arguments are found). Good practice would be to have those parameters passed as arguments to your class, with the <code>sys.argv</code> parameters only parsed under a conditional <code>if __name__==\"__main__\"</code> statement. This will add flexibility to the code. I realise that in the case of your code, a lot of what is going on is dependent on the command line arguments, but you might be better off having them parsed by a separate object that then feeds the arguments into your <code>ControlArguments</code> class (perhaps in a dictionary). </p>\n\n<p>New style classes should inherit from <code>object</code>. e.g. <code>class ControlArguments:</code> should be <code>class ControlArguments(object):</code> </p>\n\n<p>Your docstrings are not PEP257 compliant. They should go inside the functions that they relate to, not before them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:12:03.617",
"Id": "80561",
"Score": "0",
"body": "again great advice. agree with each of the points"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:30:04.413",
"Id": "46041",
"ParentId": "45949",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46041",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:44:53.707",
"Id": "45949",
"Score": "0",
"Tags": [
"python",
"exception-handling",
"mongodb"
],
"Title": "Class for connecting to mongodb databases and return collection object"
} | 45949 |
<p>Is my approach good to naming variables and exception handling? I would like to make this code more robust and maintainable. I need advice on exception handling, var naming and comments.</p>
<pre><code> import config_files
import math
"""
Performs logistic regression on tweets object passed and returns followback prediction
"""
class LogisticRegression():
"""
method: Constructor
input:
Object: Config file object
output: None
"""
def __init__(self,config):
self.config =config
"""
method: Computes and returns sigmoid function of sent parameter
input:
Integer: Prediction Paramter
output:
Float: Sigmoid function value on the parameter
"""
def sigmoid(self,x):
return 1 / (1 + math.exp(-x))
"""
method: Performs generalised linear regression (glm) on the tweet object
input:
Integer List: glm variables
output:
Float: Prediction (between 0-1)
"""
def glm(self, variables):
logistic_regression_predictors = [self.config.logistic_regression_parameters[0],0,0,0,0,0]
logistic_regression_vars = self.config.logistic_regression_parameters
key_pos_bin = variables[0]
user_power_bin = variables[1]
tweets_count = variables[2]
user_favorites_count = variables[3]
user_tweet_length = variables[4]
if key_pos_bin == True:
logistic_regression_predictors[1] = logistic_regression_vars[1]
if user_favorites_count == 3:
logistic_regression_predictors[2] = logistic_regression_vars[2]
elif user_favorites_count == 2:
logistic_regression_predictors[2] = logistic_regression_vars[3]
elif user_favorites_count == 0:
logistic_regression_predictors[2] = logistic_regression_vars[4]
if tweets_count == 2:
logistic_regression_predictors[3] = logistic_regression_vars[5]
if user_power_bin == False:
logistic_regression_predictors[4] == logistic_regression_vars[6]
if user_tweet_length == False:
logistic_regression_predictors[5] == logistic_regression_vars[7]
x = logistic_regression_predictors[0] + logistic_regression_predictors[1] + logistic_regression_predictors[2] + logistic_regression_predictors[3] + logistic_regression_predictors[4] + logistic_regression_predictors[5]
return self.sigmoid(x)
"""
method: This method computes and sends all the variables for the glm method
input:
Object: Tweet object in json format
String: Keyword of tweet
output:
Float: Prediction (between 0-1)
"""
def userFollowBackPrediction(self,tweet,keyword):
keyword = keyword.lower()
key_pos_bin = 0
user_power_bin = 0
tweets_count = 0
user_favorites_count = 0
user_tweet_length = 0
try:
if tweet['text'].lower().index(keyword) < self.config.tweet_keyword_index:
key_pos_bin = False
else:
key_pos_bin = True
except:
key_pos_bin = False
try:
user_power = tweet['user']['friends_count']/tweet['user']['followers_count']
if user_power >= self.config.user_power:
user_power_bin = True
else:
user_power_bin = False
except Exception as ex:
user_power_bin = 0
#calculate tweets_count
user_status_count = tweet['user']['statuses_count']
if user_status_count <=self.config.user_status_count:
tweets_count = 1
else:
tweets_count = 2
##calculate user_favorites_count
user_favorites_count = tweet['user']['favourites_count']
if user_favorites_count == self.config.user_favorites_count[0]:
user_favorites_count = 0
elif user_favorites_count >self.config.user_favorites_count[0] and user_favorites_count <=self.config.user_favorites_count[1]:
user_favorites_count = 1
elif user_favorites_count >self.config.user_favorites_count[1] and user_favorites_count <=self.config.user_favorites_count[2]:
user_favorites_count = 2
elif user_favorites_count >self.config.user_favorites_count[2]:
user_favorites_count = 3
#calculate user_tweet_length
if keyword in tweet['text'].lower() :
user_tweet_lengthext = len(tweet['text'])-self.config.tweet_link_length-len(keyword)
else:
user_tweet_lengthext = len(tweet['text'])-self.config.tweet_link_length
if user_tweet_lengthext < self.config.tweet_content_length:
user_tweet_length = False
else:
user_tweet_length = True
user_followback_prediction = self.glm([key_pos_bin, user_power_bin, tweets_count, user_favorites_count, user_tweet_length])
return user_followback_prediction
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:49:46.017",
"Id": "80181",
"Score": "1",
"body": "Your docstrings need to be below the `def` to be attached to the object properly."
}
] | [
{
"body": "<p>For a start : your naming convention does not follow <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> which is the usually accepted style guide for python code.</p>\n\n<hr>\n\n<p><code>sigmoid()</code> does not need to operate on an instance.</p>\n\n<hr>\n\n<p>In Python, you can chain your comparison in a clean way. For instance : </p>\n\n<pre><code> if user_favorites_count == self.config.user_favorites_count[0]:\n user_favorites_count = 0\n elif user_favorites_count >self.config.user_favorites_count[0] and user_favorites_count <=self.config.user_favorites_count[1]:\n user_favorites_count = 1\n elif user_favorites_count >self.config.user_favorites_count[1] and user_favorites_count <=self.config.user_favorites_count[2]:\n user_favorites_count = 2\n elif user_favorites_count >self.config.user_favorites_count[2]:\n user_favorites_count = 3\n</code></pre>\n\n<p>can be written :</p>\n\n<pre><code> if user_favorites_count == self.config.user_favorites_count[0]:\n user_favorites_count = 0\n elif self.config.user_favorites_count[0] < user_favorites_count <= self.config.user_favorites_count[1]:\n user_favorites_count = 1\n elif self.config.user_favorites_count[1] < user_favorites_count <= self.config.user_favorites_count[2]:\n user_favorites_count = 2\n elif self.config.user_favorites_count[2] < user_favorites_count:\n user_favorites_count = 3\n</code></pre>\n\n<hr>\n\n<p>You can use list unpacking to rewrite :</p>\n\n<pre><code> key_pos_bin = variables[0] \n user_power_bin = variables[1]\n tweets_count = variables[2]\n user_favorites_count = variables[3]\n user_tweet_length = variables[4]\n</code></pre>\n\n<p>just in one line :</p>\n\n<pre><code> key_pos_bin, user_power_bin, tweets_count, user_favorites_count, user_tweet_length = variables\n</code></pre>\n\n<p>This is probably not required at all as variables could be just as easily passed one by one.</p>\n\n<hr>\n\n<p>You don't need to assign to a temporary variable <code>user_followback_prediction</code> before returning.</p>\n\n<hr>\n\n<p>From the PEP 8 linked above :</p>\n\n<blockquote>\n <p>Don't compare boolean values to True or False using ==.</p>\n</blockquote>\n\n<hr>\n\n<p>Using an array for <code>logistic_regression_predictors</code> adds some un-needed complexity.</p>\n\n<hr>\n\n<p>You should try to understand which errors can be thrown instead of having <code>try</code> <code>catch</code> all over the place.</p>\n\n<hr>\n\n<p>The documentation is a nice touch but does not help at all as it's just a rewritten form of the signature of the function : a description of the structure of the config or such a thing could be helpful.</p>\n\n<p>Also, I have doubts that the way things have been splitted is really relevant : \n<code>logistic_regression_predictors</code> seems to be getting the right pieces of information to feed <code>glm</code> but them <code>glm</code> itself will perform some non-trivial logic before calling <code>sigmoid</code>. I guess this could be a single function and be just as clear (which doesn't mean much).</p>\n\n<p>This is probably as far as I can go without understanding much of it.</p>\n\n<pre><code>#!/usr/bin/python\n\nimport config_files\nimport math\n\n\"\"\"\nPerforms logistic regression on tweets object passed and returns followback prediction\n\"\"\"\nclass LogisticRegression():\n \"\"\"\n method: Constructor\n input:\n Object: Config file object\n output: None\n \"\"\"\n def __init__(self,config):\n self.config =config\n\n \"\"\"\n method: Computes and returns sigmoid function of sent parameter\n input:\n Integer: Prediction Paramter\n output:\n Float: Sigmoid function value on the parameter\n \"\"\"\n def sigmoid(x):\n return 1 / (1 + math.exp(-x))\n\n \"\"\"\n method: Performs generalised linear regression (glm) on the tweet object\n input:\n Integer List: glm variables\n output:\n Float: Prediction (between 0-1)\n \"\"\"\n\n def glm(self, key_pos_bin, user_power_bin, tweets_count, user_favorites_count, user_tweet_length):\n logistic_regression_vars = self.config.logistic_regression_parameters\n\n logistic_regression_predictors_0 = logistic_regression_vars[0] \n logistic_regression_predictors_1 = logistic_regression_vars[1] if key_pos_bin else 0\n\n if user_favorites_count == 3:\n logistic_regression_predictors_2 = logistic_regression_vars[2]\n elif user_favorites_count == 2:\n logistic_regression_predictors_2 = logistic_regression_vars[3]\n elif user_favorites_count == 0:\n logistic_regression_predictors_2 = logistic_regression_vars[4]\n else\n logistic_regression_predictors_2 = 0\n\n logistic_regression_predictors_3 = logistic_regression_vars[5] if tweets_count == 2 else 0\n\n logistic_regression_predictors_4 == logistic_regression_vars[6] if not user_power_bin else 0\n\n logistic_regression_predictors_5 == logistic_regression_vars[7] if not user_tweet_length else 0\n\n return sigmoid(logistic_regression_predictors_0 + logistic_regression_predictors_1 + logistic_regression_predictors_2 + logistic_regression_predictors_3 + logistic_regression_predictors_4 + logistic_regression_predictors_5)\n\n \"\"\"\n method: This method computes and sends all the variables for the glm method\n input:\n Object: Tweet object in json format\n String: Keyword of tweet\n output:\n Float: Prediction (between 0-1)\n\n \"\"\"\n def user_follow_back_prediction(self,tweet,keyword):\n keyword = keyword.lower()\n\n try:\n key_pos_bin = tweet['text'].lower().index(keyword) >= self.config.tweet_keyword_index:\n except:\n key_pos_bin = False\n\n try:\n user_power_bin = tweet['user']['friends_count']/tweet['user']['followers_count'] >= self.config.user_power:\n except Exception as ex:\n user_power_bin = 0\n\n #calculate tweets_count\n tweets_count = 1 if tweet['user']['statuses_count'] <=self.config.user_status_count else 2\n\n\n ##calculate user_favorites_count\n user_favorites_count = tweet['user']['favourites_count']\n\n if user_favorites_count == self.config.user_favorites_count[0]:\n user_favorites_count = 0\n elif self.config.user_favorites_count[0] < user_favorites_count <= self.config.user_favorites_count[1]:\n user_favorites_count = 1\n elif self.config.user_favorites_count[1] < user_favorites_count <= self.config.user_favorites_count[2]:\n user_favorites_count = 2\n elif self.config.user_favorites_count[2] < user_favorites_count:\n user_favorites_count = 3\n\n #calculate user_tweet_length\n\n if keyword in tweet['text'].lower() :\n user_tweet_lengthext = len(tweet['text'])-self.config.tweet_link_length-len(keyword)\n else:\n user_tweet_lengthext = len(tweet['text'])-self.config.tweet_link_length\n\n user_tweet_length = user_tweet_lengthext >= self.config.tweet_content_length:\n\n return self.glm(key_pos_bin, user_power_bin, tweets_count, user_favorites_count, user_tweet_length)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T17:37:31.507",
"Id": "80630",
"Score": "0",
"body": "did you intend to leave the self out of sigmoid?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:49:51.523",
"Id": "45958",
"ParentId": "45950",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "45958",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T15:50:28.550",
"Id": "45950",
"Score": "2",
"Tags": [
"python",
"exception-handling",
"statistics",
"machine-learning"
],
"Title": "Compute logistic regression on tweet objects"
} | 45950 |
<pre><code>public class AnagramNumber {
public static void checkAnagram(String[] str)
{
String[] sortedArray=new String[str.length];
for(int i=0;i<str.length;i++)
{
char[] strToCharArray=str[i].toCharArray();
sortedArray[i]=new String(sortCharArray(strToCharArray));
}
boolean flag=true;
for(int j=0;j<sortedArray.length-1;j++)
{
if(!sortedArray[j].equals(sortedArray[j+1]))
{
flag=false;
break;
}
}
if(flag)
System.out.println("The array has anagrams");
else
System.out.println("The array doesnt have only anagrams");
}
public static char[] sortCharArray(char[] charArray)
{
char temp='\u0000';
for(int i=0;i<charArray.length-1;i++)
{
for(int j=i+1;j<charArray.length;j++)
{
if(charArray[j]>charArray[i])
{
temp=charArray[j];
charArray[j]=charArray[i];
charArray[i]=temp;
}
}
System.out.println(Arrays.toString(charArray));
}
return charArray;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] str={"hello","helol","elloh"};
checkAnagram(str);
}
}
</code></pre>
<p>Please review program and provide the best practices and feedback on code optimizing. </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T08:22:17.150",
"Id": "80275",
"Score": "0",
"body": "please provide a bit of background. Are you trying to implement your own sorting algorithm? Otherwise, trust `Arrays.sort` from `Java`. Your sorting algorithm is using bubble sort which has O(n^2) complexity. There are faster algorithms. Also, do you have restriction in using built in methods in `String`class? Have a look [here](http://stackoverflow.com/questions/13692221/anagram-algorithm-in-java)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:43:07.243",
"Id": "80287",
"Score": "0",
"body": "This was an interview question in which I was asked to implement any sorting technique and not use the Arrays.sort()...no restriction on built in methods of String class"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:26:25.093",
"Id": "80304",
"Score": "0",
"body": "then you can probably use `toCharArray` method of `String`. Sorting of course you have to perform with your own provided method then. If they had not insisted on sorting, another way would be to build 2 maps, each with key=a unique char and val=#occurences and then check for equality. That is faster than sorting solution. Btw., this was asked for an interview to me as well few weeks ago, I proposed both solutions I mentioned and was selected (though I did not know what an Anagram was until then) :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:39:29.090",
"Id": "80306",
"Score": "0",
"body": "Can you elaborate on the 2nd solution? I didnt get it completely"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:44:11.433",
"Id": "80307",
"Score": "0",
"body": "check [this](http://stackoverflow.com/questions/15045640/how-to-check-if-two-words-are-anagrams-in-java) post, especially the selected answer."
}
] | [
{
"body": "<p><strong>Indentation</strong></p>\n\n<p>Your indentation seems consistent in your code, except for this part. It could be a problem in the question here on Code Review, but always pay attention to the indentation of your code. It's a major point for good readability.</p>\n\n<blockquote>\n<pre><code> for(int i=0;i<str.length;i++)\n {\n char[] strToCharArray=str[i].toCharArray();\n sortedArray[i]=new String(sortCharArray(strToCharArray));\n }\n</code></pre>\n</blockquote>\n\n<p>You should add spaces in all your conditions :</p>\n\n<blockquote>\n<pre><code>for(int i=0;i<str.length;i++)\n</code></pre>\n</blockquote>\n\n<p>Should be : </p>\n\n<pre><code>for(int i = 0; i < str.length; i++)\n</code></pre>\n\n<p><strong>Brace { }</strong></p>\n\n<p>This could be argue whether or not this is best practice, but I always like to see brackets, even if there is only one line of code. This can save a lot of troubles and if you ever need to add something to the block you won't have to add braces.</p>\n\n<blockquote>\n<pre><code> if(flag)\n System.out.println(\"The array has anagrams\");\n else\n System.out.println(\"The array doesnt have only anagrams\");\n</code></pre>\n</blockquote>\n\n<p>One thing for sure is that the first <code>{</code> should always be at the end of the line, not on a new line.</p>\n\n<pre><code>public static void checkAnagram(String[] str) {\n\n}\n</code></pre>\n\n<p><strong>Comments</strong></p>\n\n<p>You should remove <code>// TODO Auto-generated method stub</code> since this is now obsolete. This serve nothing in your code.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>There is some variables that could have a better name. Take <code>boolean flag</code>, by the name I know that it's a flag, but a flag for what ? This is not clear at all by the name. You could have use a relevant name that would show what are you flagging.</p>\n\n<p>Another example : </p>\n\n<blockquote>\n<pre><code>public static void checkAnagram(String[] str)\n</code></pre>\n</blockquote>\n\n<p>The name <code>str</code> is not relevant at all. I already know by the class that this is a <code>String</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:13:00.560",
"Id": "80176",
"Score": "0",
"body": "Thanks for your feedback....Could you also provide feedback on how i could optimize the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:14:31.453",
"Id": "80177",
"Score": "0",
"body": "I don't have time at the moment to look deep in your algo, but if there is no other answer by the time I'm free, I will gladly do it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:35:11.987",
"Id": "45956",
"ParentId": "45954",
"Score": "5"
}
},
{
"body": "<p><strong>Naming</strong><br>\nYour naming is quite verbose, which is good (not counting <code>flag</code>), but sometimes, although the name <em>looks</em> meaningful, it actually does not convey any useful meaning:</p>\n\n<ul>\n<li><code>AnagramNumber</code> - what does this class actually do? Counts the number of anagrams? Maybe finds anagrams for a number? Someone reading your code will never guess...</li>\n<li><code>checkAnagram</code> - what does it check for? Does it return anything?</li>\n<li><code>str</code> - OK, this is just a generic name, but it is extra confusing, since <code>str</code> implies a single string, while you expect an array. Btw, an array of words? sentences? URLs?</li>\n<li><code>\"The array has anagrams\"</code> vs <code>\"The array doesnt have only anagrams\"</code> - these sentences are <em>not</em> complementary, so one is obviously wrong. The first <em>should</em> say \"The array has only anagrams\". This is especially important, because you are not only talking with the reader of your code, here you are talking to your <strong><em>user</em></strong>. Confusing him means you have failed your task.</li>\n<li><code>char temp='\\u0000';</code> - this value is never used, so making it so verbose is confusing. A better choice would be not initializing the <code>temp</code> at all (<code>char temp</code>), or, better yet, declare it only where needed (<code>char temp = charArray[i]</code>)</li>\n<li><code>public static char[] sortCharArray(char[] charArray)</code> - here the problem is a little more subtle, but all the more serious. The signature of the method (returning a <code>char[]</code>) implies that it <em>creates a new</em> sorted array. Actually, it modifies the <em>input array itself</em>.<br>\nEither create a new array, and leave the one given as it is, or remove the return value. This will make it clear that the input array changes.</li>\n</ul>\n\n<p><strong>Exit Strategy</strong><br>\nYour use of <code>flag</code> makes your code a little awkward. Initializing it with <code>false</code>, and changing it to <code>true</code> makes it even more obfuscated, as it is counter-intuitive to most coders. As its name does not convey it any meaning, your gentle reader is left to guess its meaning by reading your code over and over...<br>\nI would drop the flag altogether, breaking from the method itself upon finding your stop condition:</p>\n\n<pre><code>for(int j=0;j<sortedArray.length-1;j++)\n{ \n if(!sortedArray[j].equals(sortedArray[j+1]))\n {\n System.out.println(\"The array doesn't have only anagrams\"); \n return;\n }\n}\n\nSystem.out.println(\"The array has only anagrams\");\n</code></pre>\n\n<p><strong>Optimizations</strong><br>\nSince you don't give any background, it is hard to give you feedback on your algorithm - are you trying to implement a specific sorting algorithm on your own? are you simply not familiar with java's own solution to sorting (<code>Arrays.sort</code>)? Optimal solutions for sorting an array are with complexity of \\$O(n \\cdot log(n))\\$, your solution is \\$O(n^2)\\$, so there is room for improvement there... you can find a myriad of sorting algorithms <a href=\"http://en.wikipedia.org/wiki/Sorting_algorithm\" rel=\"nofollow\">here</a>.</p>\n\n<p>You could further optimize your code by making a few quick checks on your data before doing the heavy lifting. For example: if not all the strings have the same <em>length</em>, you can immediately determine that they are not all an anagram of one another, and save yourself the sorting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:57:58.900",
"Id": "80187",
"Score": "0",
"body": "Thanks for your valuable feedback....I will incorporate it from the next program i write"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:34:00.557",
"Id": "80286",
"Score": "0",
"body": "public static char[] sortCharArray(char[] charArray) - here the problem is a little more subtle, but all the more serious. The signature of the method (returning a char[]) implies that it creates a new sorted array. Actually, it modifies the input array itself.\nEither create a new array, and leave the one given as it is, or remove the return value. This will make it clear that the input array changes......Can you elaborate on this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:54:58.137",
"Id": "80290",
"Score": "0",
"body": "@user3296744 The suggestion is to either make `sortCharArray` be a `void` return method, or creating a copy of the array and return that. Currently, your `char[] charArray` gets *modified* inside the method, and is also returned. I would suggest making the method `public static void sortCharArray(char[] charArray)`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:32:21.123",
"Id": "45959",
"ParentId": "45954",
"Score": "5"
}
},
{
"body": "<p>Besides what others have mentioned:</p>\n\n<ul>\n<li><p><code>System.out.println</code> in your sorting method just confused me. Either inform what exactly you are logging or remove it entirely. Preferably remove it.</p></li>\n<li><p>Speaking of removing, your sorting method can be replaced by a call to <code>Arrays.sort(strToCharArray);</code></p>\n\n<pre><code>char[] strToCharArray = str[i].toCharArray();\nArrays.sort(strToCharArray);\nsortedArray[i] = new String(strToCharArray);\n</code></pre></li>\n<li><p>Make your <code>checkAnagram</code> method (which should be renamed to <code>verifyIsOnlyAnagrams</code> or something similar) more flexible by returning the value of <code>flag</code> instead of outputting the result.</p>\n\n<pre><code>boolean flag = true;\nfor (int j = 0; j < sortedArray.length - 1; j++) {\n ...\n}\n\nreturn flag;\n</code></pre>\n\n<p>And then let the <code>main</code> method deal with the output:</p>\n\n<pre><code>public static void main(String[] args) {\n String[] str={\"hello\",\"helol\",\"elloh\"};\n if (verifyIsOnlyAnagram(str)) {\n System.out.println(...);\n }\n else {\n System.out.println(...);\n }\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:53:31.857",
"Id": "80184",
"Score": "0",
"body": "`System.out.println` is an expansive operation most of the time, this is a really major performance problem in a many cases. +1 for removing it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T17:47:09.327",
"Id": "45961",
"ParentId": "45954",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:02:30.423",
"Id": "45954",
"Score": "6",
"Tags": [
"java",
"optimization",
"strings"
],
"Title": "Anagram Checking"
} | 45954 |
<p>I have a form that posts (a,b) values into the following .php file, and displays an error message when the user tries to reach the .php file directly, instead via POST request.</p>
<p>This code is probably pretty messy, for example, I'm not sure I can post <code><p></code> tags right away, instead of having them inside the <code><html></code> tags, but since it's an if/else function, I'm not sure how to build this in the most efficient way.</p>
<pre><code><?php
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
?>
<p>You didn't come here through a Post.</p>
<?php
} else {
if(isset($_POST['a'])){
switch ($_POST['a']) {
case "1":
$var1 = "word1";
break;
case "2":
$var1 = "word2";
break;
default:
$var1 = "other";
}
}
if(isset($_POST['b'])){
switch ($_POST['b']) {
case "1":
$var2 = "word3";
break;
case "2":
$var2 = "word4";
break;
default:
$var2 = "other";
}
}
?>
<!doctype html>
<html>
<head>
<title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
#various-styles {
}
</style>
</head>
<body>
<div>
HTML-blocks that contain PHP such as <?php echo $var1; ?>, and <?php echo $var2; ?>.
</div>
</body>
</html>
<?php
}
?>
</code></pre>
| [] | [
{
"body": "<p>A few suggestions.</p>\n\n<ol>\n<li>Instead of writing styles in same file use an external style sheet</li>\n<li><p>Also you can restructure it like:</p>\n\n<pre><code> <!doctype html>\n <html>\n <head>\n <title>test</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <style>\n #various-styles {\n }\n </style>\n </head>\n <body>\n <div>\n <?php\n if ($_SERVER['REQUEST_METHOD'] !== 'POST')\n {\n ?>\n <p>You didn't come here through a Post.</p>\n<?php\n }\n else\n {\n if(isset($_POST['a']))\n {\n $status = \"HTML-blocks that contain PHP such as \";\n switch ($_POST['a'])\n {\n case \"1\":\n $status .= \"word1\";\n break;\n case \"2\":\n $status .= \"word2\";\n break;\n default:\n $status .= \"other\";\n }\n }\n\n if(isset($_POST['b']))\n {\n $status .= \"and \";\n switch ($_POST['b'])\n {\n case \"1\":\n $status .= \"word3\";\n break;\n case \"2\":\n $status .= \"word4\";\n break;\n default:\n $status .= \"other\";\n }\n }\n echo $status;\n ?>\n <!-- other html code else block here -->\n <?php\n }\n ?>\n\n </div>\n </body>\n </html>\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:13:03.823",
"Id": "80203",
"Score": "0",
"body": "thanks, but i'm afraid you have broke it down too much, the output inside the <DIV> is just an example, what If I'm going to have a whole <TABLE> inside with nested div, and I want a certain cell to echo something? I'm looking for a way for having the code of the HTML block as natural as it can be, so it can be easy to spot and modify as well when necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:14:45.383",
"Id": "80205",
"Score": "0",
"body": "@rockyraw: ohh, I see, I'm editing the answer"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:01:15.020",
"Id": "45975",
"ParentId": "45955",
"Score": "2"
}
},
{
"body": "<p>+1 to <em>Midhun MP</em>, the error page also should be valid HTML. Some other notes:</p>\n\n<ol>\n<li><p>Using indentation in the HTML code would be easier to read/follow:</p>\n\n<pre><code><!doctype html>\n<html>\n <head>\n <title>test</title>\n <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n <style>\n #various-styles {\n }\n </style>\n </head>\n <body>\n <div>HTML-blocks that contain PHP such as \n <?php echo $var1; ?>, and <?php echo $var2; ?>.</div>\n </body>\n</html>\n</code></pre></li>\n<li><p>You should initialize the variables in every code path. If a malcious client send a POST requiest without an <code>a</code> or <code>b</code> field you'll get some warnings in the error log or on the page (depending on the settings of your server and <a href=\"http://www.php.net/manual/en/function.error-reporting.php\" rel=\"nofollow noreferrer\"><code>error_reporting</code></a>):</p>\n\n<pre><code>[error] [client 127.0.0.1] PHP Notice: Undefined variable: a in .../index.php on line 3\n[error] [client 127.0.0.1] PHP Notice: Undefined variable: var1 in .../index.php on line 57\n[error] [client 127.0.0.1] PHP Notice: Undefined variable: var2 in .../index.php on line 57\n</code></pre>\n\n<p>I'd set the default value before the isset condition to avoid that:</p>\n\n<pre><code>$var1 = \"other\";\nif(isset($_POST['a'])){\n\n switch ($_POST['a']) {\n\n case \"1\":\n $var1 = \"word1\";\n break;\n\n case \"2\":\n $var1 = \"word2\";\n break;\n }\n}\n</code></pre></li>\n<li><p>Instead of this error message:</p>\n\n<blockquote>\n<pre><code> <p>You didn't come here through a Post.</p>\n</code></pre>\n</blockquote>\n\n<p>I'd print something helpful. What should the user do? Should they go back to the main page or to the form? Consider linking it.</p>\n\n<p>(You might also find useful <a href=\"https://codereview.stackexchange.com/a/45075/7076\">#3 here</a>.)</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:20:31.823",
"Id": "45979",
"ParentId": "45955",
"Score": "1"
}
},
{
"body": "<p>Ideally, when an request is unacceptable because it was made using the wrong HTTP method, the response should have a <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.6\" rel=\"nofollow\">405 (Method Not Allowed)</a> status code rather than the usual 200 (Success).</p>\n\n<p>To do so, use <a href=\"http://php.net/header\" rel=\"nofollow\"><code>header('HTTP/1.0 405 Method Not Allowed')</code></a>. This has to be called <em>before</em> a single byte of the HTML output has been sent; once the HTTP body starts, it is too late to alter the headers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:26:12.140",
"Id": "80303",
"Score": "0",
"body": "Thanks for the suggestion, why is it more idle? Also, in that Instance I've noticed that Chrome and FF won't display any message, rather a blank page. Does it mean I'll have to add to my htaccess a `ErrorDocument 405 /mesaage.php` If I want to display some message?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:15:48.247",
"Id": "80317",
"Score": "0",
"body": "I've just tried including a custom message and noticed that while FF/Chrome would display the custom message, IE would still have the 405, is that Ideal?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:51:34.710",
"Id": "45983",
"ParentId": "45955",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:08:50.623",
"Id": "45955",
"Score": "2",
"Tags": [
"php"
],
"Title": "If/else that contains HTML blocks, which contain additional PHP functions"
} | 45955 |
<p>This class' function is to change a given array's data into an ID.
The list is set by a configuration file. I have DI the outer array and objects into the class so that if there are any dependencies - it gets injected.</p>
<p>The protected <code>$_api;</code> is an external API class that contains some API call to an external address that will do a look up given type and value. It returns an ID and if there is a rare chance that it doesn't - it will return null.</p>
<p><code>redis</code> is a redis object that communicates with redis (it's being instantiated with a known lib so the set/get that you will see in the code are known).</p>
<p><code>table</code> is the list of tables being looked up.</p>
<p>2 steps:</p>
<ol>
<li><p>Go find in redis and see if the hash value is there - if it is we get the ID and we move on.</p></li>
<li><p>If it is not there - go call the API and fetch it, and insert it into redis</p></li>
</ol>
<p>My code used to pass the function <code>getID</code> and have that function do the look up / API call, however since I need several values - I decided to do <code>mGET</code> to get multiple values and only make one trip to redis.</p>
<p>The code works, however, I want to transform it to something better utilizing SOLID, and that's where the <code>mGET</code> got me and I'm stuck. I figure that after writing this code I can see it, but I can't which is what I need help on.</p>
<pre><code>class LookUp
{
protected $_api;
protected $_redis;
protected $_tables_switch_id;
public function __construct(\Redis $redis, Api\Track $api, $tables = array())
{
$this->_api = $api;
$this->_redis = $redis;
$this->_tables_switch_id = $tables;
}
public function changeDataIntoId($data)
{
$hash_value = array();
$index_array = array();
foreach ($this->_tables_switch_id as $index => $table) {
if (isset($data[$index])) {
$hash_value[$index] = md5(serialize(array($index => strtolower($data[$index]))));
$index_array[] = $index;
}
}
$ids = $this->_redis->mGet($hash_value);
$i = 0;
foreach ($ids as $id) {
$breakdown = $index_array[$i];
if ($id !== false) {
$data[$breakdown] = $id;
} else {
$api_id = $this->_api->getBreakdownID($breakdown, $data[$breakdown]);
if ($api_id == null) {
$api_id = 0;
}
$this->_redis->set($hash_value[$breakdown], $api_id);
$data[$breakdown] = $api_id;
}
$i++;
}
return $data;
}
}
</code></pre>
<p>One observation that might confuse you: why do I have two arrays.</p>
<p>One is the hash data, and the other one is an index. The entering data (<code>$data</code>) could be composed of numerous indexes. I'm only converting those who are from <code>$table</code>. This is the sole reason why I must retain the list and why I am also checking for <code>isset</code>.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T16:40:13.510",
"Id": "45957",
"Score": "1",
"Tags": [
"php",
"design-patterns",
"php5",
"redis"
],
"Title": "Data lookup table with Redis and API call"
} | 45957 |
<p>Is there anything horribly wrong with creating different representations of data behind the scenes when constructing a <code>std::vector<T></code> from a <code>std::vector<U></code>?</p>
<pre><code>std::vector<Color> initialScene(Settings::HRes * Settings::VRes);
std::vector<Pixel> finalScene(std::begin(initialScene), std::end(initialScene));
</code></pre>
<p>With the <code>Pixel(const Color&)</code> constructor doing something along the lines of:</p>
<pre><code>explicit Pixel(const Color& color) {
// Basically swaps blue and red channels
data[0] = color.blue;
data[1] = color.green;
data[2] = color.red;
}
</code></pre>
<p>Note: this is not exactly what the converting constructor does; it's more of an illustration.</p>
| [] | [
{
"body": "<p>No problem with that at all, since it's not the <code>copy</code> which is doing the conversion (which would be strange) but the constructor. Since the <code>vector</code> templates you've mentioned are clearly of different types, the operation you describe would not at all be unexpected. It's little different from using <code>std::copy</code> to read from a file into an STL container, which is a common idiom.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:52:43.387",
"Id": "45972",
"ParentId": "45968",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45972",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:40:24.140",
"Id": "45968",
"Score": "4",
"Tags": [
"c++",
"c++11"
],
"Title": "Trigger custom implicit conversion on \"copy\""
} | 45968 |
<p>In my current project, I find myself using <code>Dispatcher.Invoke</code> a lot. Before each call I test if the current dispatcher is the right one. I want to write a wrapper class like so:</p>
<pre><code>class SafeRunner
{
//From the thread we always need to run on
public static System.Windows.Threading.Dispatcher disp;
public static void Run<T>(Action<T> f, T arg)
{
if (disp != System.Windows.Threading.Dispatcher.CurrentDispatcher)
{
disp.Invoke(f, arg);
}
else
{
f(arg);
}
}
public static void Run<T1, T2>(Action<T1,T2> f, T1 arg1, T2 arg2)
{
if (disp != System.Windows.Threading.Dispatcher.CurrentDispatcher)
{
disp.Invoke(f, arg1, arg2);
}
else
{
f(arg1, arg2);
}
}
public static void Run<T1, T2, T3>(Action<T1,T2,T3> f, T1 arg1, T2 arg2, T3 arg3)
{...}
public static void Run<T1, T2, T3, T4>(Action<T1,T2,T3,T4> f, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{...}
}
</code></pre>
<p>And I can use it like this:</p>
<pre><code>SafeRunner.Run<string,string>((a,b) => {
doSomething(a,b);
doSomethingElse(a);
// Maybe a few more lines here
}, "Hello", "World");
</code></pre>
<p>This works, but doesn't <em>feel</em> right. Is there a better way?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:50:41.967",
"Id": "80194",
"Score": "0",
"body": "Your invocation may be able to be written as `SafeRunner.Run(doSomething, \"Hello\", \"World\")`. The methodgroup/delegate should match the parameters already, after all. That makes it closer to the dispatcher's syntax too, which is probably a good thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:54:41.077",
"Id": "80195",
"Score": "0",
"body": "@Magus Thanks. I was not clear in that there may be multiple lines of code. I have updated my post."
}
] | [
{
"body": "<p>A couple of things I notice, and they are both around the if statements</p>\n\n<p>I would flip the if statements around so that they are checking the positive test. I would also put the <code>disp</code> on the right side of the <code>==</code>. You can eliminate the else statement, all it really does is clutters up the code.</p>\n\n<pre><code>if (System.Windows.Threading.Dispatcher.CurrentDispatcher == disp)\n{\n f(arg);\n return; \n}\n\ndisp.Invoke(f, arg);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:56:03.010",
"Id": "80196",
"Score": "0",
"body": "Without the else, when `CurrentDispatcher == disp` the function will get run 2x. I only want it to run once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T19:05:53.017",
"Id": "80202",
"Score": "0",
"body": "Good point, for some reason I had it my head it was returning :) You can just add a return into the if..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:49:10.793",
"Id": "45971",
"ParentId": "45969",
"Score": "3"
}
},
{
"body": "<p>I suggest that you call your class <code>SafeDispatcher</code>, and your methods <code>Invoke</code>, since you actually wrap a <code>Dispatcher</code> (not <code>Runner</code>), and <code>Invoke</code> (not <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/system.windows.threading.dispatcher.run\" rel=\"nofollow\"><code>Run</code></a> which does something completely different in <code>Dispatcher</code>).</p>\n\n<p>Also, if performance is not an issue, you can use <code>DynamicInvoke</code>, and implement the whole thing in a single method:</p>\n\n<pre><code>class SafeDispatcher\n{\n public static System.Windows.Threading.Dispatcher disp;\n\n public static void Dispatch(Delegate f, params Object[] args)\n { \n if (System.Windows.Threading.Dispatcher.CurrentDispatcher == disp)\n {\n f.DynamicInvoke(args);\n }\n else\n {\n disp.Invoke(f, args);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:27:14.883",
"Id": "81918",
"Score": "0",
"body": "So, to call: `SafeDispatcher.Dispatch(new Action<string>((s)=>{...}), \"hello\");`, correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T12:30:30.950",
"Id": "81920",
"Score": "0",
"body": "I believe that `SafeDispatcher.Dispatch((s)=>{...}, \"hello\");` should also work"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:33:47.027",
"Id": "45981",
"ParentId": "45969",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:40:47.310",
"Id": "45969",
"Score": "4",
"Tags": [
"c#",
"multithreading",
"wpf"
],
"Title": "Same function, variable parameters and types with lambda"
} | 45969 |
<p>Please review my code for bearer token (JWT) authentication of Web API 2 (Self Hosted using OWIN)</p>
<p>Are there any security issues in the implementation?</p>
<p>Quick overview:</p>
<ul>
<li>Token creation and validation using JWT Handler</li>
<li>Symmetric key encryption</li>
<li>CORS support not yet checked for the authorization header</li>
<li>Web traffic will be on SSL.</li>
<li>The key cannot be auto-generated as it will break during a load balanced scenario. Can I save the key in config? Or switch to X509 certificates?</li>
</ul>
<p>This is the main class to create and validate tokens:</p>
<pre><code>public class TokenManager
{
public static string CreateJwtToken(string userName, string role)
{
var claimList = new List<Claim>()
{
new Claim(ClaimTypes.Name, userName),
new Claim(ClaimTypes.Role, role) //Not sure what this is for
};
var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true };
var sSKey = new InMemorySymmetricSecurityKey(SecurityConstants.KeyForHmacSha256);
var jwtToken = tokenHandler.CreateToken(
makeSecurityTokenDescriptor(sSKey, claimList));
return tokenHandler.WriteToken(jwtToken);
}
public static ClaimsPrincipal ValidateJwtToken(string jwtToken)
{
var tokenHandler = new JwtSecurityTokenHandler() { RequireExpirationTime = true };
// Parse JWT from the Base64UrlEncoded wire form
//(<Base64UrlEncoded header>.<Base64UrlEncoded body>.<signature>)
JwtSecurityToken parsedJwt = tokenHandler.ReadToken(jwtToken) as JwtSecurityToken;
TokenValidationParameters validationParams =
new TokenValidationParameters()
{
AllowedAudience = SecurityConstants.TokenAudience,
ValidIssuer = SecurityConstants.TokenIssuer,
ValidateIssuer = true,
SigningToken = new BinarySecretSecurityToken(SecurityConstants.KeyForHmacSha256),
};
return tokenHandler.ValidateToken(parsedJwt, validationParams);
}
private static SecurityTokenDescriptor makeSecurityTokenDescriptor(
InMemorySymmetricSecurityKey sSKey, List<Claim> claimList)
{
var now = DateTime.UtcNow;
Claim[] claims = claimList.ToArray();
return new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
TokenIssuerName = SecurityConstants.TokenIssuer,
AppliesToAddress = SecurityConstants.TokenAudience,
Lifetime = new Lifetime(now, now.AddMinutes(SecurityConstants.TokenLifetimeMinutes)),
SigningCredentials = new SigningCredentials(sSKey,
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256"),
};
}
}
</code></pre>
<p>I have a message handler to intercept the requests and I verify the validity of token <strong>except</strong> for the route for log in, using <code>TokenManager.ValidateJwtToken()</code> above.</p>
<p>To create the token, in the <code>LoginController</code>, I have the following code:</p>
<pre><code>[Route("login")]
[HttpPost]
public HttpResponseMessage Login(LoginBindingModel login)
{
if (login.Username == "admin" && login.Password == "password") //Do real auth
{
string role = "Librarian";
var jwtToken = TokenManager.CreateJwtToken(login.Username, role);
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ObjectContent<object>(new
{
UserName = login.Username,
Roles = role,
AccessToken = jwtToken
}, Configuration.Formatters.JsonFormatter)
};
}
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
</code></pre>
<p>The full working code is available <a href="https://github.com/rnarayana/JwtAuthWebApi">here</a> and the instructions to run the sample are in the Wiki.</p>
| [] | [
{
"body": "<p>Instead of keeping <code>KEY</code> in config, I would keep it with user records. A unique key for each user.</p>\n\n<p>I admit, I don't get why creating keys dynamically would break the load balancing scenario. We can have a key created at the back-end where we have a single service serving all the load balances servers (such as a database).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-26T23:03:33.630",
"Id": "55394",
"ParentId": "45974",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T18:57:48.893",
"Id": "45974",
"Score": "14",
"Tags": [
"c#",
"authentication",
"asp.net-web-api",
"jwt"
],
"Title": "Web API 2 authentication with JWT"
} | 45974 |
<p>I need to delete a file when an error occurs during loading it. It is not allowed to perform async operations in a catch block. </p>
<p>This has lead me to writing the following code:</p>
<pre><code> public async Task LoadFromStorageFile(string fileName)
{
StorageFile file = null;
Exception ex1 = null;
try
{
var folder = await ApplicationHelper.GetApplicationSaveFolder();
file = await folder.GetFileAsync(fileName);
// ...
}
catch (Exception ex)
{
ex1 = ex;
}
try
{
if (ex1 != null && file != null)
{
await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
catch (Exception)
{
//...
}
finally
{
if(ex1 != null)
throw ex1;
}
}
</code></pre>
<p>Is there a nicer way of doing this? The rethrown exception especially bugs me.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T17:06:53.543",
"Id": "81058",
"Score": "1",
"body": "“It is not allowed to perform async operations in a catch block.” Not yet, it's probably going to be allowed in C# 6.0."
}
] | [
{
"body": "<p>Couple random observations:</p>\n\n<p>This initialization is redundant:</p>\n\n<pre><code> StorageFile file = null; \n Exception ex1 = null;\n</code></pre>\n\n<p>Because all reference type default to <code>null</code>, this is rigorously equivalent:</p>\n\n<pre><code> StorageFile file; \n Exception ex1;\n</code></pre>\n\n<p>Your method is doing 2 things, it should be broken down into 2 methods.</p>\n\n<p><code>throw ex1</code> is kissing your stack trace goodbye, and throwing an exception in a <code>finally</code> block is rather... unusual. Why keep a reference to an exception that you're going to be throwing anyway? If the first <code>try</code> block throws, that's it, I'd be expecting <code>file</code> to be <code>null</code> and to not be entering the condition in the second <code>try</code> block.</p>\n\n<pre><code> catch (Exception)\n {\n //...\n }\n</code></pre>\n\n<p>This no-op <code>catch</code> block is swallowing any & all exceptions - don't do that. If you can't handle an exception in a meaningful and useful way, then <em>let it blow up</em>! Let the caller do something about an unhandled exception, don't just <em>pretend</em> everything went fine! The minimum you could do is something like this (assuming you're using a logging framework):</p>\n\n<pre><code> catch (Exception exception)\n {\n _logger.WarnException(exception);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:49:42.900",
"Id": "80225",
"Score": "1",
"body": "I'll contest `Type value = null;` is equivalent to `Type value;` since @thumbmunkeys is using ex1 in a finally block, it MUST be set to something before ever getting there. Try it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:49:59.283",
"Id": "80226",
"Score": "0",
"body": "thanks for your remarks. I know not to swallow exceptions, I left non relevant parts out of my code. You cannot access an uninitialized local variable in c#, so `file` and `ex1` have to be initialized. `folder` is in this context indeed not neccessary (in my real code it isn't). I agree the finalizer block is superflous. Could you give a suggestion how to divide the code, so that the stacktrace is not lost?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:51:40.740",
"Id": "80227",
"Score": "0",
"body": "@Tory good point"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:40:59.110",
"Id": "45982",
"ParentId": "45980",
"Score": "3"
}
},
{
"body": "<blockquote>\n <p><em>I need to delete a file when an error occurs during loading it.</em></p>\n</blockquote>\n\n<p>In other words:</p>\n\n<p><strong>Happy path</strong>:</p>\n\n<ul>\n<li>Load a file</li>\n<li>Move on</li>\n</ul>\n\n<p><strong>Unhappy path</strong>:</p>\n\n<ul>\n<li>Load a file, exception is thrown</li>\n<li>Delete the file</li>\n<li>Move on</li>\n</ul>\n\n<p><strong>Exceptional path</strong>:</p>\n\n<ul>\n<li>Load a file, exception is thrown</li>\n<li>Delete the file, exception is thrown</li>\n<li>Handle exception, move on</li>\n</ul>\n\n<hr>\n\n<p>From these points, it appears we'd need a task that loads a file. If that task fails, we need to try to handle the unhappy path gracefully.</p>\n\n<p>I haven't written async code with async/await, but I'd probably get away with this using a <code>Task</code> that loads the file, and then decide whether I'd <code>.ContinueWith</code> another <code>Task</code> that deletes the file, and then decide how to handle the exceptional path where that other task would have failed.</p>\n\n<hr>\n\n<h3>Signature</h3>\n\n<blockquote>\n<pre><code>public async Task LoadFromStorageFile(string fileName)\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/a/15951824/1188513\">This StackOverflow answer</a> refers to an authoritative source for async method naming conventions:</p>\n\n<blockquote>\n <p>The <a href=\"http://msdn.microsoft.com/en-us/library/hh873175.aspx\" rel=\"nofollow noreferrer\"><em>Task-based Asynchronous Pattern (TAP)</em></a> dictates that methods should\n always return a <code>Task<T></code> (or <code>Task</code>) and be named with an Async suffix;\n this is separate from the use of <code>async</code>. Certainly, <code>Task<bool> Connect()</code> \n (or <code>async Task<bool> Connect()</code>) will compile and run just\n fine, but you won't be following the TAP naming convention.</p>\n</blockquote>\n\n<p>The signature for <code>Task LoadFromStorageFile(string)</code> would follow the naming convention for the pattern, by appending \"Async\" to the method's name:</p>\n\n<pre><code>public async Task LoadFromStorageFileAsync(string fileName)\n</code></pre>\n\n<hr>\n\n<h3>Async/Await Exception Handling</h3>\n\n<p>As I've found in <a href=\"https://stackoverflow.com/a/5383408/1188513\">this StackOverflow answer</a>, an exception thrown in an async method will bubble up to the caller, so whoever called <code>await LoadFromStorageFileAsync(\"somefile.txt\");</code> can know whether to move on, or to handle the unhappy path.</p>\n\n<blockquote>\n <p><em>It is not allowed to perform async operations in a catch block.</em></p>\n</blockquote>\n\n<p>Indeed. There's <a href=\"https://stackoverflow.com/questions/8868123/await-in-catch-block\">a question on Stack Overflow</a>, with <a href=\"https://stackoverflow.com/a/8869589/1188513\">a nice answer</a> from one of our top reviewers here on CR, that shows how that limitation can be circumvented. In a nutshell:</p>\n\n<blockquote>\n<pre><code>bool loadSucceeded;\ntry\n{\n var folder = await ApplicationHelper.GetApplicationSaveFolder();\n file = await folder.GetFileAsync(fileName);\n // ...\n\n loadSucceeded = true;\n}\ncatch\n{\n loadSucceeded = false;\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p><code>LoadFromStorageFileAsync</code> can then look like this:</p>\n\n<pre><code>public async Task LoadFromStorageFileAsync(string fileName)\n{\n bool loadSucceeded;\n StorageFile file;\n\n try\n {\n // happy path\n var folder = await ApplicationHelper.GetApplicationSaveFolder();\n file = await folder.GetFileAsync(fileName);\n // ...\n\n loadSucceeded = true;\n }\n catch(Exception exception)\n {\n // log exception\n\n loadSucceeded = false;\n }\n\n if (!loadSucceeded && file != null) \n {\n try\n {\n // unhappy path\n await file.DeleteAsync(StorageDeleteOption.PermanentDelete);\n deleteSucceeded = true;\n }\n catch(Exception exception)\n {\n // exceptional path\n // log exception\n }\n }\n}\n</code></pre>\n\n<p>This code doesn't rethrow whatever exception caused <code>loadSucceeded</code> to be <code>false</code> - rethrowing that exception in the <em>unhappy path</em> makes no sense, as was said before, that <code>finally</code> block is not needed. Instead, you could <code>catch(Exception exception)</code> (or anything more specific) in the <em>happy path</em>'s <code>catch</code> block, and write a trace, a debug, or a warning log entry with the exception and its stack trace. At that point, it's taken care of, there's no need to re-throw it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T03:29:41.463",
"Id": "46004",
"ParentId": "45980",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "46004",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T20:22:35.243",
"Id": "45980",
"Score": "6",
"Tags": [
"c#",
"error-handling",
"async-await"
],
"Title": "Async and error-handling"
} | 45980 |
<p>I have been developing a small application for a client which combines two arrays together and then creates a URL and then loads the images on the same page from the given URL.</p>
<p>I'd like you to look at my code and give feedback on how to make it more maintainable and robust.</p>
<pre><code>function displayContent() {
document.getElementById("findCar").onsubmit = function () {
var registration = document.getElementById("regPlate").value,
reference = document.getElementById("stockRef").value;
var regArray = registration.split(''),
refArray = reference.split(''),
referenceNinth = refArray[10];
reverseReg = regArray.reverse();
var obfuscated = new Array();
var obf_index = 0;
for (i = 0; i <= 6; i++) {
obfuscated[obf_index] = refArray[i];
obf_index++;
obfuscated[obf_index] = reverseReg[i];
obf_index++;
}
obfuscated.push(referenceNinth);
obfuscatedString = obfuscated.join("");
var camera = new Array();
var cameraSize = "350";
var cam_index = 0;
for (i = 0; i <= 1; i++) {
if (i > 0) cameraSize = "800";
camera[cam_index++] = cameraSize + "/f";
camera[cam_index++] = cameraSize + "/i";
camera[cam_index++] = cameraSize + "/6";
camera[cam_index++] = cameraSize + "/5";
camera[cam_index++] = cameraSize + "/4";
camera[cam_index++] = cameraSize + "/r";
}
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "'
document.body.appendChild(img);
}
return false;
};
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T23:09:22.673",
"Id": "80245",
"Score": "0",
"body": "Could you explain better what your code does? Your first paragraph doesn't make any sense at all. \"Combining two arrays\" could mean anything. And what do two arrays (of what?) have to do with the creation of an URL? And what's \"the same page\"? The \"page\" of the URL? The page in which your script is running?"
}
] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>obfuscating urls from the javascript side will not stop any dedicated individual</li>\n<li><code>displayContent</code> is an unfortunate name for the function, it does not give away that all it does it setting a listener, consider <code>setFindCarListener</code></li>\n<li><code>var obfuscated = []</code> is considered better than <code>var obfuscated = new Array();</code></li>\n<li>It is considered better form to have a single <code>var</code> statement</li>\n<li><code>reverseReg</code> is an unfortunate name, it is unclear to me what it is supposed to contain</li>\n<li>Don't assign <code>onsubmit</code>, use <code>addEventListener</code> instead</li>\n<li>A loop that will only run twice should get unrolled ( <code>for (i = 0; i <= 1; i++) {</code> ), I would put the code in the loop block inside a helper function</li>\n<li>You have some indentation trouble, consider using jsbeautifier</li>\n<li><p><code>obf_index++</code> increases <code>obf_index</code> after evaluating it, so you can do</p>\n\n<pre><code>for (i = 0; i <= 6; i++) {\n obfuscated[obf_index++] = refArray[i];\n obfuscated[obf_index++] = reverseReg[i];\n}\n</code></pre></li>\n<li><p>Since you start from <code>0</code>, you are really simulating <code>push</code>, so you could also do</p>\n\n<pre><code>for (i = 0; i <= 6; i++) {\n obfuscated.push( refArray[i] );\n obfuscated.push( reverseReg[i] );\n}\n</code></pre></li>\n<li>lowerCamelCase is preferred in JavaScript so <code>obf_index</code> -> <code>obfIndex</code> -> <code>obfuscatedIndex</code></li>\n<li>You use both single quotes and double quotes for strings, stick to single quotes</li>\n<li>Use JsHint.com, you are not declaring every variable with <code>var</code></li>\n<li><code>refArray</code> is like reverse polish notation, postfixing the type of the variable, <code>regChars</code> would be a better name, it tells me that this contains the characters of the reg(istration)</li>\n</ul>\n\n<p>All in all ( this is untested ), I would go with something like this:</p>\n\n<pre><code>function addCameraEntries( array , cameraSize ) {\n array.push( cameraSize + \"/f\" );\n array.push( cameraSize + \"/i\" );\n array.push( cameraSize + \"/6\" );\n array.push( cameraSize + \"/5\" );\n array.push( cameraSize + \"/4\" );\n array.push( cameraSize + \"/r\" );\n}\n\nfunction setFindCarListener() {\n\n document.getElementById(\"findCar\").addEvenListener( \"submit\", function onSubmit() {\n var registration = document.getElementById(\"regPlate\").value,\n reference = document.getElementById(\"stockRef\").value,\n referenceChars = reference.split(''),\n ninthReference = referenceChars[10];\n registrationChars = registration.split('').reverse(),\n obfuscated = [],\n camera = [];\n for (i = 0; i <= 6; i++) {\n obfuscated.push( referenceChars[i] );\n obfuscated.push( registrationChars[i] );\n }\n obfuscated.push(ninthReference);\n obfuscatedString = obfuscated.join(\"\");\n addCameraEntries( camera , '350' );\n addCameraEntries( camera , '800' );\n for (i = 0; i <= 11; i++) {\n var img = new Image();\n img.src = 'http://imagecache.arnoldclark.com/imageserver/\" + obfuscatedString + \"/\" + camera[i] + \"'\n document.body.appendChild(img);\n }\n return false;\n };\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T22:54:49.270",
"Id": "45990",
"ParentId": "45985",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T22:11:48.430",
"Id": "45985",
"Score": "5",
"Tags": [
"javascript",
"array",
"image",
"url"
],
"Title": "Loading car photo's"
} | 45985 |
<p>How can I get Monday and Friday from a date range (<strong>start</strong> and <strong>end</strong> date)?</p>
<p>Example:</p>
<p><strong>startdate</strong> - 03/24/2014 <br/>
<strong>enddate</strong> - 04/01/2014</p>
<p>Result should be:</p>
<p><strong>Monday</strong> - 2 <br/>
<strong>Friday</strong> - 2</p>
<p>I tried this code: </p>
<pre><code>Monday = CountDays(DayOfWeek.Monday, startDate, endDate);
Friday = CountDays(DayOfWeek.Friday, startDate, endDate);
</code></pre>
<hr>
<pre><code>static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
TimeSpan ts = end - start;
int count = (int)Math.Floor(ts.TotalDays / 7);
int remainder = (int)(ts.TotalDays % 7);
int sinceLastDay = (int)(end.DayOfWeek - day);
if (sinceLastDay < 0) sinceLastDay += 7;
if (remainder >= sinceLastDay) count++;
return count > 0 ? count : 0;
}
</code></pre>
<p>And this code works! Is there any other way to simplify this code?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T06:18:35.593",
"Id": "80237",
"Score": "1",
"body": "I don't understand why you think increasing the time range would somehow increase the processing time. You're not iterating over anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T06:19:53.143",
"Id": "80238",
"Score": "0",
"body": "is there any other way that i can simplify that code? or is there any best way that i can do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T06:43:11.143",
"Id": "80267",
"Score": "1",
"body": "Please explain why there should be two Fridays between 2014-03-24 and 2014-04-01?"
}
] | [
{
"body": "<p>Your code is already good enough.</p>\n\n<pre><code>static int CountDays(DayOfWeek day, DateTime start, DateTime end)\n{\n start = start.Date.AddDays((7 + day - start.DayOfWeek) % 7);\n if (end < start)\n return 0;\n else\n return ((int)(end - start).TotalDays) / 7 + 1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T08:38:01.710",
"Id": "80240",
"Score": "0",
"body": "i think this code look more understandable than my work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T08:22:32.077",
"Id": "45988",
"ParentId": "45986",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-28T06:14:40.870",
"Id": "45986",
"Score": "3",
"Tags": [
"c#",
"datetime"
],
"Title": "Counting Monday and Friday from a Date Range"
} | 45986 |
<blockquote>
<p>Given an expression string exp, write a program to examine whether the
pairs and the orders of</p>
<pre><code>"{","}","(",")","[","]"
</code></pre>
<p>are correct in exp.</p>
<p>For example, the program should print true for</p>
<pre><code>exp = "[()]{}{[()()]()}"
</code></pre>
<p>and false for</p>
<pre><code>exp = "[(])"
</code></pre>
</blockquote>
<p>Complexity:</p>
<ul>
<li>Time complexity: \$O(n)\$ where \$n\$ is length of string</li>
<li>Space complexity: \$O(\frac{n}{2})\$ where \$n\$ is length of string </li>
</ul>
<p>I saw the Java version and thought "I want to submit a JavaScript version." Looking for code review, optimizations, and best practices.</p>
<p>In my version, the string can contain other characters than parentheses, <code>""</code> is accepted as input, and I did not care about short circuiting odd length strings.</p>
<pre><code>function parenthesesAreBalanced(s)
{
var parentheses = "[]{}()",
stack = [], //Parentheses stack
i, //Index in the string
c; //Character in the string
for (i = 0; c = s[i++];)
{
var bracePosition = parentheses.indexOf(c),
braceType;
//~ is truthy for any number but -1
if (!~bracePosition)
continue;
braceType = bracePosition % 2 ? 'closed' : 'open';
if (braceType === 'closed')
{
//If there is no open parenthese at all, return false OR
//if the opening parenthese does not match ( they should be neighbours )
if (!stack.length || parentheses.indexOf(stack.pop()) != bracePosition - 1)
return false;
}
else
{
stack.push(c);
}
}
//If anything is left on the stack <- not balanced
return !stack.length;
}
console.log('{}([]) true', parenthesesAreBalanced('{}([])'));
console.log('{{ false', parenthesesAreBalanced('{{'));
console.log('[(]) false', parenthesesAreBalanced('[(])'));
console.log("{}([]) true", parenthesesAreBalanced("{}([])"));
console.log("([}]) false", parenthesesAreBalanced("([}])"));
console.log("([]) true", parenthesesAreBalanced("([])"));
console.log("()[]{}[][]", parenthesesAreBalanced("()[]{}[][]"));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-29T09:37:56.040",
"Id": "398312",
"Score": "0",
"body": "add this check as the first validation, If the length of the expression is an odd number we can return false right away."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-29T12:48:52.843",
"Id": "398347",
"Score": "1",
"body": "@Ananda this supports non braces, \"abc\" and \"o[]\" are balanced and odd length"
}
] | [
{
"body": "<p>This is almost all style suggestions; the code itself looks great.</p>\n\n<p>Personally, I prefer the brace-on-same-line style for everything in JS, and I prefer proper blocks instead of inlining expressions. But those are just preferences. I've also skipped the bitwise trick, added some strict comparisons instead of <code>!stack.length</code> etc., moved the <code>i++</code> over to its \"usual\" place, and lengthened a few variable names, just for clarity.</p>\n\n<p>Again: This is all basically pointless, but I just like spelling things out.</p>\n\n<p>The only real difference is that rather than push the opening brace onto the stack, I push the position of the expected closing brace. It just makes the conditional a bit cleaner later on.</p>\n\n<pre><code>function parenthesesAreBalanced(string) {\n var parentheses = \"[]{}()\",\n stack = [],\n i, character, bracePosition;\n\n for(i = 0; character = string[i]; i++) {\n bracePosition = parentheses.indexOf(character);\n\n if(bracePosition === -1) {\n continue;\n }\n\n if(bracePosition % 2 === 0) {\n stack.push(bracePosition + 1); // push next expected brace position\n } else {\n if(stack.length === 0 || stack.pop() !== bracePosition) {\n return false;\n }\n }\n }\n\n return stack.length === 0;\n}\n</code></pre>\n\n<hr>\n\n<p>Update: Actually, you can skip one <code>stack.length</code> check in the inner conditional; <code>stack.pop()</code> will just return <code>undefined</code> if the stack's empty, so this is enough:</p>\n\n<pre><code>if(stack.pop() !== bracePosition) {\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:11:55.913",
"Id": "80313",
"Score": "3",
"body": "I very much like the idea of pushing the `bracePosition+1`, +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:08:46.983",
"Id": "46039",
"ParentId": "45991",
"Score": "33"
}
},
{
"body": "<p>I wrote a Node/JavaScript library called <strong><a href=\"https://github.com/icodeforlove/node-balanced\" rel=\"nofollow\">balanced</a></strong> that can do this and much more, but the main concept I used was using a stack, compiling a regexp of the <code>open</code>/<code>close</code> tags, and then doing 1 pass. It seemed to perform better than <code>indexOf</code> implementations.</p>\n\n<p>The way you would write your <code>isBalanced</code> method using balanced is</p>\n\n<pre><code>function isBalanced(string) {\n return !!balanced.matches({source: string, open: ['{', '(', '['], close: ['}', ')', ']'], balance: true});\n}\n</code></pre>\n\n<p>Here's a live example with exceptions: <strong><a href=\"http://jsfiddle.net/icodeforlove/3S4WR/\" rel=\"nofollow\">JSFiddle</a></strong> and heres an example ignoring comment blocks <strong><a href=\"http://jsfiddle.net/icodeforlove/8ULvA/\" rel=\"nofollow\">JSFiddle</a></strong></p>\n\n<p>For your example <code>balanced</code> will produce the following error</p>\n\n<pre><code>Balanced: mismatching close bracket, expected \")\" but found \"]\" at 1:3\n\n1: [(])\n-----^\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-07T15:50:43.073",
"Id": "391876",
"Score": "0",
"body": "I like your answer. But, there are some glitches. I think you should improve it and make it better to parse whole JS function or FILE. \nFor example: On your JS fiddle i pasted a JS line containing .replace(/[{]/g, \"\").replace(/[}]/g, \"\") . And it failed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-03T14:35:52.910",
"Id": "58919",
"ParentId": "45991",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46039",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-01T23:05:26.267",
"Id": "45991",
"Score": "42",
"Tags": [
"javascript",
"algorithm",
"strings",
"stack",
"balanced-delimiters"
],
"Title": "Balanced parentheses"
} | 45991 |
<p>For my own linked list implementation, I've decided to try something different: a linked list of groceries.</p>
<p>The main differences between this implementation and a standard list are:</p>
<ol>
<li>more data fields (name, quantity, if item has been purchased)</li>
<li>two size data members (different items and total items)</li>
<li>depending on quantity to be removed, an entire node <em>may not</em> be removed</li>
</ol>
<p>I don't have any particular concerns, and I'd like a general review of this.</p>
<p>I've tested this with some test cases on <a href="http://ideone.com/YNkS7a">Ideone</a>.</p>
<p><strong>GroceryList.hpp</strong></p>
<pre><code>#ifndef GROCERY_LIST_HPP
#define GROCERY_LIST_HPP
#include <cstddef>
#include <string>
class LinkedGroceryList
{
private:
struct Grocery
{
std::string name;
std::size_t quantity;
bool purchased;
Grocery* next;
};
Grocery* head;
std::size_t differentGroceries;
std::size_t totalGroceries;
public:
LinkedGroceryList();
~LinkedGroceryList();
void addGrocery(std::string const&, std::size_t);
void removeGrocery(std::string const&, unsigned int);
bool findGrocery(std::string const&) const;
void markAsPurchased(std::string const&);
void displayGroceries() const;
void clearGroceries();
std::size_t different() const { return differentGroceries; }
std::size_t total() const { return totalGroceries; }
bool empty() const { return differentGroceries == 0; }
};
#endif
</code></pre>
<p><strong>GroceryList.cpp</strong></p>
<pre><code>#include "GroceryList.hpp"
#include <iostream>
LinkedGroceryList::LinkedGroceryList()
: head(nullptr)
, differentGroceries(0)
, totalGroceries(0)
{}
LinkedGroceryList::~LinkedGroceryList()
{
clearGroceries();
}
void LinkedGroceryList::addGrocery(std::string const& name, std::size_t quantity)
{
Grocery* newGrocery = new Grocery;
newGrocery->name = name;
newGrocery->quantity = quantity;
newGrocery->purchased = false;
newGrocery->next = nullptr;
if (!head)
{
head = newGrocery;
}
else
{
Grocery* groceryPtr = head;
while (groceryPtr->next)
groceryPtr = groceryPtr->next;
groceryPtr->next = newGrocery;
}
differentGroceries++;
totalGroceries += quantity;
}
void LinkedGroceryList::removeGrocery(std::string const& name, unsigned int quantity)
{
if (!head) return;
Grocery* groceryPtr;
if (head->name == name)
{
groceryPtr = head;
head = groceryPtr->next;
totalGroceries -= quantity;
if (quantity == groceryPtr->quantity)
differentGroceries--;
else
{
groceryPtr->quantity -= quantity;
return;
}
delete groceryPtr;
}
else
{
Grocery* predPtr = nullptr;
groceryPtr = head;
while (groceryPtr && groceryPtr->name != name)
{
predPtr = groceryPtr;
groceryPtr = groceryPtr->next;
}
if (groceryPtr)
{
totalGroceries -= quantity;
if (quantity == groceryPtr->quantity)
differentGroceries--;
else
{
groceryPtr->quantity -= quantity;
return;
}
predPtr->next = groceryPtr->next;
delete groceryPtr;
}
}
}
bool LinkedGroceryList::findGrocery(std::string const& name) const
{
if (!head) return false;
if (head->name == name)
return true;
else
{
Grocery* groceryPtr = head->next;
while (groceryPtr)
{
if (groceryPtr->name == name)
return true;
groceryPtr = groceryPtr->next;
}
}
return false;
}
void LinkedGroceryList::markAsPurchased(std::string const& name)
{
Grocery* groceryPtr = head;
while (groceryPtr)
{
if (groceryPtr->name == name)
groceryPtr->purchased = true;
groceryPtr = groceryPtr->next;
}
}
void LinkedGroceryList::displayGroceries() const
{
if (!head) return;
Grocery* groceryPtr = head;
while (groceryPtr)
{
std::cout << groceryPtr->name << ", ";
std::cout << groceryPtr->quantity << ", ";
std::cout << ((groceryPtr->purchased) ? "purchased\n" : "not purchased\n");
groceryPtr = groceryPtr->next;
}
}
void LinkedGroceryList::clearGroceries()
{
if (!head) return;
Grocery* predPtr = head;
Grocery* nextGrocery;
while (predPtr)
{
nextGrocery = predPtr->next;
delete predPtr;
predPtr = nextGrocery;
}
head = nullptr;
differentGroceries = 0;
totalGroceries = 0;
}
</code></pre>
<p><strong>Driver</strong></p>
<pre><code>#include "GroceryList.hpp"
#include <iostream>
int main()
{
LinkedGroceryList meats;
meats.addGrocery("steak", 5);
meats.addGrocery("chicken", 3);
meats.addGrocery("pork", 2);
meats.displayGroceries();
std::cout << "\nDifferent items: " << meats.different() << "\n";
std::cout << "Total items: " << meats.total();
std::cout << "\nsteak present? " << std::boolalpha << meats.findGrocery("steak");
std::cout << "\ncarrots present? " << std::boolalpha << meats.findGrocery("carrots");
std::cout << "\n\nRemoving 1 pork...\n\n";
meats.removeGrocery("pork", 1);
meats.displayGroceries();
std::cout << "\nDifferent items: " << meats.different() << "\n";
std::cout << "Total items: " << meats.total();
std::cout << "\npork present? " << std::boolalpha << meats.findGrocery("pork");
meats.markAsPurchased("steak");
std::cout << "\n\nsteak has been purchased\n\n";
meats.displayGroceries();
}
</code></pre>
| [] | [
{
"body": "<p>Rather than having the user pass in name and quantity, have the user pass in a Grocery. You complete throw away any sense of encapsulation by having the user provide the components rather than the object.</p>\n\n<hr>\n\n<p>Rather than <code>displayGroceries</code>, I would overload <code>operator>></code> for <code>ostream</code>s.</p>\n\n<hr>\n\n<p>Give Grocery a constructor so you can condense the creation code to be a succinct one liner rather than a half-dozen assignments. (And a constructor can be more efficient since you can avoid a default construct of properties just to immediately assign to them.)</p>\n\n<hr>\n\n<p>Imagine you didn't write this code, and consider the following:</p>\n\n<pre><code>void addGrocery(std::string const&, std::size_t);\n</code></pre>\n\n<p>What in the world are the parameters? A string and a <code>size_t</code>. Alright... Maybe a name and quantity? Maybe a name and cost in cents? Maybe a name and the aisle the item is found on? Give your public declarations meaningful names!</p>\n\n<p>(Note that this is a perfect example of a reason to work on <code>Grocery</code>s, not <code>string</code>/<code>size_t</code> pairs.)</p>\n\n<hr>\n\n<p>Either keep a tail pointer or insert at the head of the list. <code>addGrocery</code> should not be linear time. That defeats the purpose of a linked list.</p>\n\n<hr>\n\n<p>For simple loop conditions, I prefer <code>for</code> loops:</p>\n\n<pre><code>for (Grocery* grocery = head; grocery; grocery = grocery->next) {\n // ...\n}\n</code></pre>\n\n<p>It's much easier to see what's going on without having to read through an entire <code>while</code></p>\n\n<hr>\n\n<p>You've way over complicated some of your loops with unnecessary special cases for when <code>head</code> is null. Just let a <code>for</code> not loop is head is <code>null</code>:</p>\n\n<pre><code>bool LinkedGroceryList::findGrocery(std::string const& name) const\n{\n\n for (auto node = head; node; node = node->next) {\n if (head->name == name) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p>The way you're using the names to do a linear search implies that you're using the wrong data structure. Any time you scan searching for one or more items with an exact match on a key, you need either a map (or mutlimap for one to many).</p>\n\n<hr>\n\n<p>Your <code>differentGroceries</code> and <code>totalGroceries</code> names are a bit confusing. I would consider calling them <code>numGroceries</code> and <code>quantitySum</code> (with similar changes for the method names).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T00:33:24.310",
"Id": "45996",
"ParentId": "45992",
"Score": "5"
}
},
{
"body": "<p>You need to consider the <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">Rule of Three</a>.</p>\n\n<p>That is: the default copy and assignment implementations will not handle the <code>head</code> as you'd like. You need to define them correctly, or hide them (or remove them in C++ 11).</p>\n\n<p>For example:</p>\n\n<pre><code>class LinkedGroceryList\n{\nprivate:\n LinkedGroceryList(const LinkedGroceryList& other);\npublic:\n// etc...\n};\n</code></pre>\n\n<p>I agreed with @Corbin as to the names for the sizes, but would consider using <code>size()</code> to hold the length of the list, i.e. <code>differentGroceries</code> to ape the standard library. Likewise <code>clear</code> rather than <code>clearGroceries</code>, as the element type is implicit in the container name.</p>\n\n<p>Similarly (and some would disagree), I prefer <code>findGrocery</code> to be <code>findGroceryByName</code>. That should not just return a <code>bool</code>, but ideally an iterator to the element with the grocery. Alternatively, rename to <code>containsGroceryWithName</code> or <code>containsGrocery</code>.</p>\n\n<p>Also consider some checking of invariants. For example, <code>differentGroceries == 0</code> <=> <code>head == nullptr</code>.</p>\n\n<p>In the method <code>markAsPurchased</code>, you should break out of the loop on a match. I'd also return <code>bool</code> indicating success in finding a match.</p>\n\n<p>Why does <code>add</code> take a <code>size_t</code> and <code>remove</code> an <code>unsigned</code>?</p>\n\n<p>In the <code>remove</code> method, for the head case:\n 1. You reassign the head without considering whether or not all it items are removed.\n 2. You should check to having a negative number or items which becomes an underflow.\n 3. The head and main case have common code that should be in a common method.</p>\n\n<p>In the <code>add</code> method, you need to check to see if your list already contains an item with that name. Actually there is a bigger problem here. If you merge items when added with the same name, you'll lose track of what is purchased. If you do not, you'll have much more complexity is <code>remove</code>. And what does <code>remove</code> mean for items that may be purchased or not?</p>\n\n<p>I think this means that <code>purchased</code> is not a <code>bool</code>, but a count of the number of items with the given key that have been purchased. The <code>markAsPurchased</code> method could, but does not necessarily need to, be updated to specify the number of items purchased.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T02:36:46.310",
"Id": "46001",
"ParentId": "45992",
"Score": "7"
}
},
{
"body": "<p>I'd start by making the code more generic:</p>\n\n<pre><code>template <class T>\nclass LinkedList {\n</code></pre>\n\n<p>Then I'd <em>probably</em> separate the user's data (what you're storing) from \"your\" data (the links used by the list itself):</p>\n\n<pre><code> class Node {\n T user_data;\n Node *next;\n</code></pre>\n\n<p>I'd then have a constructor for Node that took a (reference to a constant) <code>T</code> as a parameter, and created a Node holding that data:</p>\n\n<pre><code>Node(T const &data, Node *next = nullptr) : user_data(data), next(next) {}\n</code></pre>\n\n<p>To follow the modern \"rule of five\", we probably want a move constructor to go with that:</p>\n\n<pre><code>Node (T &&data, Node *next = nullptr) : user_data(data), next(next) {}\n</code></pre>\n\n<p>This will allow us to \"steal the guts\" of an existing data item when/if it's no longer going to be used. Depending on what the data item contains, that may be a big win. It may not be either, but implementing it is pretty easy (at least in this case) so it's probably worthwhile even though it's uncertain whether it'll do much (if any) real good.</p>\n\n<p>That (of course) is only for C++11 though. If you're stuck with an older compiler, you have to live without rvalue references (or update your compiler).</p>\n\n<p>While we're talking about C++11, there's another change we should consider: instead of managing memory on our own, we should at least consider using a <code>std::unique_ptr</code> to help us out, so <code>Node</code> becomes:</p>\n\n<pre><code>template <class T>\nclass Node {\n T user_data;\n std::unique_ptr<Node> next;\n};\n</code></pre>\n\n<p>To go with that, we want to use <code>std::make_unique</code> (which was accidentally left out of C++11, but will be in C++14). A simplified (but adequate for this purpose) version looks like this:</p>\n\n<pre><code>template<typename T, typename... Args>\nstd::unique_ptr<T> make_unique(Args&&... args)\n{\n return std::unique_ptr<T>(new T(std::forward<Args>(args)...));\n}\n</code></pre>\n\n<p>We use this to create a node for us, and <code>std::unique_ptr</code> automates deleting the node when it's no longer needed (i.e., when the unique_ptr that points to the node is destroyed).</p>\n\n<pre><code>Grocery* head;\n</code></pre>\n\n<p>This, of course, should probably be a <code>unique_ptr</code> as well. Depending on the situation, it <em>could</em> be a <code>shared_ptr</code> instead, but in any case almost certainly should <em>not</em> be a \"raw\" pointer.</p>\n\n<pre><code>std::size_t differentGroceries;\nstd::size_t totalGroceries;\n</code></pre>\n\n<p>At least in my opinion, maintaining the total number of items on a running basis is probably close to pointless. Of all the times I've gone shopping, I can't really remember the last time I wanted to know how many items I bought (or planned to buy).</p>\n\n<p>I agree with Corbin, however, that you have a more fundamental problem here: you're trying to implement a <code>set</code>, and a linked-list simply really isn't a very suitable structure for that task.</p>\n\n<p>Quite a bit has already been said about the implementation, so I'm only going to cover a couple of points I didn't notice in the other critiques.</p>\n\n<p>One point that struck me as seriously problematic is that <code>findGrocery</code>, <code>markAsPurchased</code> and <code>displayGroceries</code> all have essentially identical code to traverse the list. I'd prefer to see a single function to traverse the list, and apply some function to a node, and then (probably based on its return value) decide whether to continue. All three of these can then be implemented in terms of that function.</p>\n\n<pre><code>template <class F>\nbool traverse(F f) { \n for (auto pos = head; pos; pos=pos->next)\n if (f(pos->user_data))\n return true;\n return false;\n}\n</code></pre>\n\n<p>This will (probably) improve efficiency compared to your <code>markAsPurchased</code> (which continues to traverse the list even after it has found an item and marked it as purchased).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T04:35:59.250",
"Id": "46006",
"ParentId": "45992",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "45996",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-01T23:12:28.423",
"Id": "45992",
"Score": "6",
"Tags": [
"c++",
"c++11",
"linked-list"
],
"Title": "Singly-linked grocery list"
} | 45992 |
<p><a href="http://crystalcleanhomes.com/slide/" rel="nofollow">http://crystalcleanhomes.com/slide/</a></p>
<p>There are countless scripts that perform this simple slide-out navigation menu but they are all so bloated and the styles are so convoluted that I decided to make my own and it seems almost too simple and too basic so I've come here for criticism. From my testing it even works in IE7 and an older Android tablet (and of course flawlessly in Chrome, iOS, FF, etc.). So please critique this!</p>
<p>Here is a fiddle to more easily see the code: <a href="http://jsfiddle.net/9nT7B/" rel="nofollow">http://jsfiddle.net/9nT7B/</a></p>
<p><strong>Question: does this meet compliance?</strong></p>
<pre><code>$(function(){
$('#menubutton').click(function(e){
e.preventDefault();
e.stopPropagation();
});
function handler1(){
$("#page").animate({left:"200px"},150);
$("#menu").css("overflow-y","auto");
$("#menubutton").one("click",handler2);
}
function handler2(){
$("#page").animate({left:"0"},150);
$("#menu").css("overflow-y","hidden");
$("#menubutton").one("click",handler1);
}
$("#menubutton").one("click",handler1);
$("#page").click(handler2);
$("#menu").css("visibility","visible");
});
</code></pre>
| [] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li><p>You should put the closing brace at the level of <code>$</code> for readability:</p>\n\n<pre><code>$(function () {\n $('#menubutton').click(function (e) {\n e.preventDefault();\n e.stopPropagation();\n });\n\n function handler1() {\n $(\"#page\").animate({\n left: \"200px\"\n }, 150);\n $(\"#menu\").css(\"overflow-y\", \"auto\");\n $(\"#menubutton\").one(\"click\", handler2);\n }\n\n function handler2() {\n $(\"#page\").animate({\n left: \"0\"\n }, 150);\n $(\"#menu\").css(\"overflow-y\", \"hidden\");\n $(\"#menubutton\").one(\"click\", handler1);\n }\n $(\"#menubutton\").one(\"click\", handler1);\n $(\"#page\").click(handler2);\n $(\"#menu\").css(\"visibility\", \"visible\");\n});\n</code></pre></li>\n<li><code>handler1</code>, <code>handler2</code> are unfortunate names, these function names should convey what the function does ( perhaps <code>slideRight</code> and <code>slideLeft</code> ? )</li>\n<li>You access <code>$('#menubutton')</code> a number of times, you should cache it with <code>var $menuButton = $('#menubutton')</code> and then access $menuButton, you can use the same technique for the other jQuery calls as wel</li>\n<li>You are repeating yourself between <code>handler1</code> and <code>handler2</code>, but it seems that trying to find a common routine would make this code more complex, so I would leave that alone</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:03:28.500",
"Id": "46070",
"ParentId": "45995",
"Score": "3"
}
},
{
"body": "<p>you can try to use a boolean variable to do something like toogle </p>\n\n<pre><code>$(function(){\n var isOpen=false,$page=$(\"#page\");\n $('#menubutton').click(function(e){\n e.preventDefault();\n e.stopPropagation();\n menu();\n });\n function menu(){\n if(isOpen===false){\n open();\n }\n else{\n close();\n }\n }\n function open(){\n $page.animate({left:\"200px\"},150);\n isOpen=true;\n }\n function close(){\n $page.animate({left:\"0\"},150);\n isOpen=false;\n }\n $page.click(close);\n}); \n</code></pre>\n\n<p>other changes in the fiddle </p>\n\n<ul>\n<li>create a var $page=$(\"#page\")</li>\n<li>remove $(\"#menu\").css(\"overflow-y\", \"hidden\"); and set the css directly to auto </li>\n<li>no need to use .one every time you click the #menubutton </li>\n<li>change function names to open and close </li>\n</ul>\n\n<p><a href=\"http://jsfiddle.net/9nT7B/2/\" rel=\"nofollow\">http://jsfiddle.net/9nT7B/2/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:09:55.273",
"Id": "46072",
"ParentId": "45995",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46072",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T00:21:34.383",
"Id": "45995",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "slide out navigation bar seems too simple but it works, is it?"
} | 45995 |
<p>I'm looking for a more cleaner and simpler solution to auto-format a text-box field intended only for the user to enter their college Grade Point Average (GPA). Here is my code:</p>
<pre><code><label for="collegeGPA">GPA:</label>
<input type="text" name="collegeGPA" id="collegeGPA" maxlength="4" style="width:45px;">
<script type="text/javascript">
//<!-- When executed this script [BELOW] auto-formats a Grade Point Average (GPA) field given the element ID [BEGIN] -->
function FormatGPA(gPAElementID) {
re = /\D/g; // remove any characters that are not numbers
gPAVal = document.getElementById(gPAElementID).value.replace(re,"");
gPAValFirstCharacter = gPAVal.charAt(0);
if ( ( gPAVal >= 0 ) && ( gPAValFirstCharacter < 5 ) )
{
gPALen = gPAVal.length;
if( gPALen > 1)
{
gPAa=gPAVal.slice(0,1);
gPAb=gPAVal.slice(1);
document.getElementById(gPAElementID).value = gPAa + "." + gPAb;
}
else
{
document.getElementById(gPAElementID).value=gPAVal;
};
}
else
{
document.getElementById(gPAElementID).value="";
};
};
//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->
document.getElementById('collegeGPA').onblur = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').onfocus = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').onkeypress = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').oninput = function (e) { FormatGPA(this.id); };
document.getElementById('collegeGPA').onchange = function (e) { FormatGPA(this.id); };
</script>
</code></pre>
<p>...and here is my JSFiddle: <a href="http://jsfiddle.net/JamesAndersonJr/kxaBJ/1/" rel="nofollow">http://jsfiddle.net/JamesAndersonJr/kxaBJ/1/</a>
I'm looking for a simpler way to format the GPA input dynamically (i.e. as the user types it in).
The format should be: </p>
<ul>
<li><p>1st Character: any digit 0-4</p></li>
<li><p>2nd Character: Always a Period (should also be auto-inserted after
user types a valid first digit)</p></li>
<li><p>3rd Character: any digit</p></li>
<li><p>4th Character: any digit</p></li>
</ul>
<p><strong><em>UPDATE:</strong> Lowest possible GPA is 0.00, not 1.00.</em></p>
| [] | [
{
"body": "<p>First of all, I'd be hesitant to use as-you-type correction to begin with. It doesn't take much for something like that to be an annoyance rather than a help. It's probably better to validate the input only when it loses focus, or when the form is about to be submitted, and then inform the user somehow.</p>\n\n<p>Point is, it's not hard make your code trip over something. For instance, I just pasted in \"2312\" and got a GPA with 3 decimal places. I also tried typing in a valid value, and then went back with the arrow keys and removed the first digit with the intention of replacing it - but removing that first digit cleared the entire input. If I just select the first digit, and hit a key, my input gets ignored, valid or not. I can't manually enter a decimal point. The cursor jumps around... and so on.</p>\n\n<p>Unless your system is <em>perfect</em> and takes all possible interactions into account, it'll likely be <em>very annoying and frustrating to use.</em></p>\n\n<p>Point is, it's <em>a lot</em> easier to validate stuff, once it's all been entered. For instance, this regular expression <code>/^([0-3](\\.\\d\\d?)?|4(.00?)?)$/</code> will match a valid GPA with 0-2 decimal places.</p>\n\n<p>But don't change the value! You can format it, if it's otherwise valid (like adding \".00\" if the user just typed \"4\"), but leave it at that. Just call attention to the error, optimally with an explanation of why the value is invalid.</p>\n\n<p>In any event, presuming this is being sent to a server, always, <em>always</em> validate it on the server. Never trust the client™</p>\n\n<p>But there's still code to review here, regardless of its use.</p>\n\n<h3>Code notes:</h3>\n\n<ul>\n<li><strong>Declare your variables with <code>var</code></strong>. Right now, every variable is global! Big no-no.</li>\n<li>Don't find and re-find an element with <code>getElementById</code>; find it once, stick it in a variable, and use that instead.</li>\n<li>Don't use the old-school <code>.onblur =</code> etc. event handling. Favor <code>addEventListener</code> instead (or use a library to do the event handler registration for maximum compatibility)</li>\n</ul>\n\n<p>More broadly, there's no need to keep declaring a function like <code>function (e) { FormatGPA(this.id); }</code> for each event. Declare that function once, and use it for every event. Or simply don't use an argument for the format function, and let it know what element to find. <em>Or</em>, if you use <code>addEventListener</code>, the element will be available as <code>this</code> in the event handler, i.e.:</p>\n\n<pre><code>var someInput = document.getElementById(\"some-input\");\nsomeInput.addEventListener(\"click\", someHandler, false);\n\nfunction someHandler() {\n alert(this.value); // `this` refers to the element that triggered the event\n}\n</code></pre>\n\n<p>(using <code>alert</code> just as an example - it's obviously not an ideal way to provide feedback.)</p>\n\n<h3>Style notes:</h3>\n\n<ul>\n<li>Function names and variables should be <code>lowerCamelCase</code> (unless they are constructors), so: <code>formatGPA</code>. And if you've got an acronym at the start of your name, make it all-lowercase, i.e. <code>gpaElementId</code>.</li>\n<li>Don't use HTML comment syntax in your JS code; it doesn't matter, and makes little sense.</li>\n<li><p>Avoid the brace-on-new-line style. JavaScript has automatic semicolon insertion, which (long story short) means that you should stick to a style like</p>\n\n<pre><code>if(condition) {\n\n} else {\n\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:10:53.827",
"Id": "80448",
"Score": "0",
"body": "I've improved upon and updated my code, taking into account some of the things you've said. Now, about auto-formatting while typing: I'm creating a \"Smart-Form\" that never lets the user input bad values in the first place instead of nagging them with 100's of [\"silencable\" in most browsers] alert boxes while they're trying to submit the form."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T00:10:21.127",
"Id": "80458",
"Score": "1",
"body": "@JamesAndersonJr. I'm glad you found it helpful - however, please don't update your question (I'll roll it back to its previous state). When you do, answers lose their context. If you've got updated code you'd like reviewed, please post a new question instead. It also gives others a chance to offer their advice. As for nagging users: I never imagined using alert boxes. Simply highlight the invalid input(s) (e.g. with a CSS class), and let the user correct any errors before proceeding. It doesn't have to be obtrusive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:24:59.663",
"Id": "80490",
"Score": "0",
"body": "Why I have to repost my question, and in the process be guilty of spamming CR.SE - I don't know. Poor system of operation. I already have a question open. If someone search Google for this question, they may be mislead by an old solution, and to add insult to injury, the first question can't be deleted. Someone from moderators or admin, please contact me (personally) and explain more clearly how this site works, because I'm confused and it's just not making much sense to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:00:34.560",
"Id": "80497",
"Score": "0",
"body": "@JamesAndersonJr. You are, in a sense, _supposed_ to spam the site. It's a Q&A site: If someone finds your question, yes, they might see outdated code, but they'll see _equally outdated_ answers. The point of a Q&A format is that the Qs and the As fit together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-12T20:35:30.557",
"Id": "457436",
"Score": "0",
"body": "@JamesAndersonJr. You can edit your post to include a link to the new question. I also suggest marking this as the right answer using the checkmark underneath the down arrow"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:08:13.893",
"Id": "46025",
"ParentId": "45997",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T01:08:20.890",
"Id": "45997",
"Score": "7",
"Tags": [
"javascript",
"validation",
"formatting"
],
"Title": "Auto-Format GPA while typing"
} | 45997 |
<p>Here is another example of a moving ball. I would like to see how to make it more efficient and better. I think that moving the variables to the top of the function would be better but then I tried this and it would not work as good as it did.</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CH5EX9: Moving In Circle</title>
<script src="modernizr.js"></script>
<script type="text/javascript">
window.addEventListener('load', eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasApp() {
var radius = 100;
var circle = {centerX:250, centerY:250, radius:125, angle:0}
var ball = {x:0, y:0,speed:.1};
theCanvas = document.getElementById('canvasOne');
context = theCanvas.getContext('2d');
function drawScreen () {
context.fillStyle = '#EEEEEE';
context.fillRect(0, 0, theCanvas.width, theCanvas.height);
//Box
context.strokeStyle = '#000000';
context.strokeRect(1, 1, theCanvas.width-2, theCanvas.height-2);
ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;
ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;
circle.angle += ball.speed;
context.fillStyle = "#000000";
context.beginPath();
context.arc(ball.x,ball.y,15,0,Math.PI*2,true);
context.closePath();
context.fill();
}
function gameLoop() {
window.setTimeout(gameLoop, 20);
drawScreen()
}
gameLoop();
}
</script>
</head>
<body>
<div style="position: absolute; top: 50px; left: 50px;">
<canvas id="canvasOne" width="500" height="500">
Your browser does not support the HTML 5 Canvas.
</canvas>
</div>
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T06:58:30.820",
"Id": "80268",
"Score": "0",
"body": "Please make sure your code works before having it reviewed. If it does not work, head over to [StackOverflow](http://stackoverflow.com/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:50:40.073",
"Id": "80327",
"Score": "2",
"body": "It does work on this code I tried it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:43:32.720",
"Id": "80372",
"Score": "0",
"body": "In my mind, you are duping your questions, the changes in code are minimal between your 3 versions of the dropping ball."
}
] | [
{
"body": "<h1>Your Script</h1>\n\n<h3>Handlers</h3>\n\n<p>Unless your handlers are called somewhere else, you can just embed them</p>\n\n<pre><code>window.addEventListener('load', function () {\n canvasApp();\n});\n</code></pre>\n\n<h3>requestAnimationFrame</h3>\n\n<p>There's this timer function called <code>requestAnimationFrame</code> that is better than <code>setTimeout</code> and <code>setInterval</code>. It's more optimized for animations, aiming 60fps when possible. But it's prefixed in other browsers, check for compatibility first.</p>\n\n<pre><code>(function gameLoop() {\n window.requestAnimationFrame(gameLoop);\n drawScreen();\n // All other loop functions here\n}());\n</code></pre>\n\n<h3>Common gotchas in JS</h3>\n\n<ul>\n<li>Never forget semi-colons, even when JS allows you to forget them.</li>\n<li>Remember using <code>var</code> when declaring variables. Unless you have them in some upper scope, if you forget them, they automatically become globals - and that's bad practice.</li>\n</ul>\n\n<h3>Conclusion</h3>\n\n<p>There was little to go by, but here's what I got</p>\n\n<pre><code>function canvasApp() {\n var radius = 100;\n var circle = {\n centerX: 250,\n centerY: 250,\n radius: 30,\n angle: 0\n }\n var ball = {\n x: 0,\n y: 0,\n speed: .1\n };\n\n var theCanvas = document.getElementById('canvasOne');\n var context = theCanvas.getContext('2d');\n\n function drawScreen() {\n\n context.fillStyle = '#EEEEEE';\n context.fillRect(0, 0, theCanvas.width, theCanvas.height);\n\n //Box\n context.strokeStyle = '#000000';\n context.strokeRect(1, 1, theCanvas.width - 2, theCanvas.height - 2);\n\n ball.x = circle.centerX + Math.cos(circle.angle) * circle.radius;\n ball.y = circle.centerY + Math.sin(circle.angle) * circle.radius;\n\n circle.angle += ball.speed;\n\n context.fillStyle = \"#000000\";\n context.beginPath();\n context.arc(ball.x, ball.y, 15, 0, Math.PI * 2, true);\n context.closePath();\n context.fill();\n }\n\n (function gameLoop() {\n window.requestAnimationFrame(gameLoop);\n drawScreen();\n // All other loop functions here\n }());\n}\n\nwindow.addEventListener('load', function () {\n canvasApp();\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:01:06.580",
"Id": "46239",
"ParentId": "45998",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T01:13:23.760",
"Id": "45998",
"Score": "2",
"Tags": [
"javascript",
"optimization"
],
"Title": "Efficiency of moving ball"
} | 45998 |
<p>Inspired by all of the lovely linked lists lately, I decided to implement one in assembly language. This code maintains two linked lists - one is a free store and the other is the active linked list. Rather than allocating memory whenever a new node is needed, the Node is pulled from the free list and all of the pointers updated. The data is then copied into the newly "allocated" Node. </p>
<p>This program includes a test driver which reads a series of NUL terminated strings (C strings) from memory, calculates their lengths and then puts a pointer to the string and the length into each Node until the end of list is found.</p>
<p>If there are not enough free nodes to hold all of the found strings, the program silently exits with an error code of 1. If there is enough and there are no other errors, the program prints each of the found strings on a separate line and exits with a status code of 0.</p>
<p>The output is this:</p>
<pre><code>Alfred
Barbara
Carlos
Delores
Edward
Frances
</code></pre>
<p>My <code>Makefile</code> looks like this:</p>
<pre><code>%.o : %.asm
nasm -f elf64 -l foo.lst -g -F stabs -o $@ $<
% : %.o
ld -g -o $@ $<
</code></pre>
<p>The <code>Makefile</code> is invoked as <code>make linky</code>.</p>
<p>The program, which I've place in a file named <code>linky.asm</code> is below:</p>
<pre><code>; 64-bit linked list implementation in Linux NASM
global _start ; global entry point export for ld
MAX_NODES equ 300 ; this can easily be expanded
section .text
_start:
; first initialize the free node list
mov rcx, MAX_NODES-1
mov rdi, [freenode]
mov rsi, linkedlist
mov rax, Node_size
nodeclear:
add rsi, rax ; point to next node
mov [rdi + Node.next], rsi
add rdi, rax ; advance pointer
loop nodeclear
; set the last link to NULL
mov qword [rdi + Node.next], 0
; start out pointing to our rootnode pointer
mov rdi, rootnode
; our string pointer starts at the beginning
mov rbx, namestrings
looptop:
; fetch the next string
call FetchString
; skip to print function if we are at end of list
jrcxz finish
; insert the string into new node
call NodeInsert
jmp looptop
finish:
; print all strings in the linked list
mov rdi, rootnode
morenodes:
call NodePrint
or rdi,rdi
jnz morenodes
; (rdi is already 0 here)
; normal exit with status 0
exit:
mov rax, 60 ; sys_exit
syscall
errorExit:
mov rdi, 1 ; return 1 (error)
jmp exit
; NodePrint:
; advances to next node and prints if non-null
; Entry:
; rdi points to memory location containing pointer
; to next node
; Exit:
; rsi points to string just printed
; rdx is the length of the string just printed
; rdi = 0 if we are at the end of the linked list
NodePrint:
mov rsi, [rdi]
mov rdi, rsi
or rdi, rdi
jz retnow
mov rsi, [rdi + Node.mydata + mydata.msgptr]
mov rdx, [rdi + Node.mydata + mydata.msglen]
push rdi
call printstr
call printeol
pop rdi
retnow:
ret
; rsi = addr, rdx= len
; NodeInsert:
; creates and populates new node in linked list
; Entry:
; rdi points to memory location to which pointer
; to new node should be written
; rsi points to a string to be placed in the new Node
; rcx is the length of the string pointed to by rsi
NodeInsert:
push rax
push rbx
; steal a node from the freenode list
; [rootnode] = [freenode]
mov rbx, freenode ; rbx -> freenode
cmp qword [rbx], 0 ; Q: nodes available?
je errorExit ; N: nope, so leave
mov rax, [rbx] ;
mov qword [rdi], rax ;
mov rdi, rax ; rdi -> node
; [free] = [root.next]
mov rax, [rdi + Node.next]
mov [rbx], rax
; [root.next] = 0
mov qword [rdi + Node.next], 0
pop rbx
pop rax
;; fall through to NodeAddData
; NodeAddData:
; add string data to existing node
; rdi points to an existing Node
; rsi points to a string to be placed in the new Node
; rcx is the length of the string pointed to by rsi
NodeAddData:
mov [rdi + Node.mydata + mydata.msglen], rcx
mov [rdi + Node.mydata + mydata.msgptr], rsi
ret
; FetchString:
; fetch NUL terminated string and calculate len
; Entry:
; rbx points to start of NUL terminated string
; Exit:
; rsi points to string start
; rcx contains length of string
; rbx points to next string (if any)
FetchString:
push rax
push rdi
mov rdi, rbx ; copy pointer
mov rcx, -1 ; max count in ecx
mov al,0 ; look for NUL byte
cld ; count forward
repne scasb ; look for NUL
not rcx ; tricky math to get len
dec rcx
mov rsi, rbx
mov rbx, rdi ; recover original pointer
pop rdi
pop rax
ret
printeol:
mov rsi, eol
mov edx, 1
printstr:
mov rax, 1 ; sys_write
mov rdi, 1 ; stdout
syscall
ret
; ==== data section ====
section .data
; this is the data that goes into a node
struc mydata
.msglen resq 1
.msgptr resq 1
endstruc
; this is a node of the linked list
struc Node
.next resq 1
.mydata resb mydata_size
endstruc
eol: db 0x0a
namestrings: db 'Alfred', 0
db 'Barbara', 0
db 'Carlos', 0
db 'Delores', 0
db 'Edward', 0
db 'Frances', 0
db 0,0
rootnode dq 0
freenode dq linkedlist
section .bss
linkedlist resb MAX_NODES * Node_size
</code></pre>
| [] | [
{
"body": "<p>Just a few notes, mostly in micro-optimizations that even assembly language programmers probably ignore nowadays.</p>\n\n<pre><code> ; steal a node from the freenode list\n ; [rootnode] = [freenode]\n mov rbx, freenode ; rbx -> freenode\n cmp qword [rbx], 0 ; Q: nodes available?\n je errorExit ; N: nope, so leave\n mov rax, [rbx] ; \n</code></pre>\n\n<p>To compare to 0, I prefer to use a <code>test</code> instruction:</p>\n\n<pre><code>mov rbx, freenode\nmov rax, [rbx]\ntest rax, rax\njz errorExit\n; ...\n</code></pre>\n\n<p>Likewise, in NodePrint you use an <code>or</code> to determine whether a value is 0:</p>\n\n<pre><code> or rdi, rdi\n jz retnow\n</code></pre>\n\n<p>Again, a <code>test</code> is sufficient here. The difference is that <code>or</code> will normally affect not only the flags (which you want) but the register (which you don't). In this case, you haven't actually changed the value in the register, but some CPUs will assume you did, which can prevent some instruction level parallelism.</p>\n\n<p>When you're getting ready for the scasb in FetchString, you load a 0 into <code>AL</code>:</p>\n\n<pre><code> mov rcx, -1 ; max count in ecx\n mov al,0 ; look for NUL byte\n cld ; count forward\n repne scasb ; look for NUL\n</code></pre>\n\n<p>At least if memory serves, you'll get marginally smaller code with something like:</p>\n\n<pre><code>xor rax, rax\n</code></pre>\n\n<p>This zeros the entirety of rax instead of just AL, but you don't seem to need/use the rest of rax afterward. Some processors also have a partial register stall that makes essentially <em>any</em> operation on AL relatively slow (though I don't remember if this applies to any 64-bit processors, so it <em>may</em> not matter in this case).</p>\n\n<p>Although it's minutely more fragile, I'd consider whether it's worth replacing this:</p>\n\n<pre><code> loop nodeclear\n ; set the last link to NULL\n mov qword [rdi + Node.next], 0\n</code></pre>\n\n<p>...with code like:</p>\n\n<pre><code>loop nodeclear\nmov qword [rdi+Node.next], rcx\n</code></pre>\n\n<p>Taking advantage of the fact that immediately after executing a <code>loop</code>, we know rcx contains 0.</p>\n\n<p>I think it's worth noting, however, that all of these are really very minor. Overall, the code strikes me as quite clear and nicely written. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:09:13.690",
"Id": "84727",
"Score": "1",
"body": "With respect to `xor rax, rax` versus `mov al, 0`, `xor rax, rax` assembles to `48 31 C0`, whereas `mov al, 0` assembles to `B0 00`, so `mov al, 0` is shorter by one byte."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-27T00:04:04.177",
"Id": "48283",
"ParentId": "45999",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "48283",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T02:11:51.263",
"Id": "45999",
"Score": "14",
"Tags": [
"linked-list",
"linux",
"assembly"
],
"Title": "Linux NASM assembly linked list implementation"
} | 45999 |
<p>I wrote a stack implementation using a singly linked list in x86_64 assembly. This stack supports the usual <code>push</code>/<code>pop</code> operations as well as first/next for iterating over each element.</p>
<p>I'm looking for general feedback.</p>
<p>Here are the stack subroutines:</p>
<pre><code>; Stack Structure
; Pointer Head
; Pointer Current
; Stack Node
; Pointer Next
; Pointer Value
; input
; void
; output
; stack or 0 on error
StackCreate:
mov rdi, 24
call malloc
test rax,rax
jz StackCreate_end
xor rdi, rdi
mov [rax], rdi
mov [rax+8], rdi
ret
StackCreate_end:
add rsp, 8
ret
; input
; stack
; output
; void
StackDestroy:
call free
ret
; input
; stack
; value
; output
; 0 on error
StackPush:
push rdi
push rsi
mov rdi, 16
call malloc
test rax,rax
jz StackPush_end
pop rsi
pop rdi
mov rdx, [rdi]
mov [rax], rdx
mov [rax+8], rsi
mov [rdi], rax
ret
StackPush_end:
add rsp, 16
ret
; input
; stack
; output
; value or 0 if empty
StackPop:
mov rsi, rdi
mov rdi, [rdi]
test rdi, rdi
jz StackPop_end
mov rax, [rdi]
mov [rsi], rax
mov rax, [rdi+8]
push rax
call free
pop rax
ret
StackPop_end:
xor rax, rax
ret
nop;e
; input
; stack
; output
; value or 0 if empty
StackFirst:
mov rax, [rdi]
test rax, rax
jz StackFirst_end
mov rsi, [rax]
mov [rdi+8], rsi
mov rax, [rax+8]
StackFirst_end:
ret
; input
; stack
; output
; value or 0 if end
StackNext:
mov rsi, [rdi+8]
test rsi, rsi
jz StackNext_end
mov rax, [rsi]
mov [rdi+8], rax
mov rax, [rsi+8]
ret
StackNext_end:
xor rax, rax
ret
</code></pre>
<p>Here is a driver:</p>
<pre><code>[extern puts]
[extern malloc]
[extern free]
[SECTION .data]
arguments:
db "Incorrect arguments.",10,"Expected: stackme <string1> <string2> ...",0
[SECTION .text]
BITS 64
global main
wrong_arguments:
mov rdi, arguments
call puts
jmp main_end
main:
cmp rdi, 1
jle wrong_arguments
lea r12, [rsi+8]
lea r13, [rdi-1]
call StackCreate
test rax, rax
jz main_end
mov r14, rax
pushing_loop:
test r13, r13
jz pushing_done
mov rdi, r14
mov rsi, [r12]
call StackPush
add r12, 8
dec r13
jmp pushing_loop
pushing_done:
mov rdi, r14
call StackFirst
print_loop:
test rax, rax
jz print_done
mov rdi, rax
call puts
mov rdi, r14
call StackNext
jmp print_loop
print_done:
stack_delete:
mov rdi, r14
call StackPop
test rax, rax
jnz stack_delete
stack_delete_done:
mov rdi, r14
call StackDestroy
main_end:
xor eax, eax
ret
</code></pre>
<p>Assembling/Linking</p>
<pre><code>nasm -f elf64 -l stackme.lst stackme.asm
gcc -o stackme stackme.o
</code></pre>
| [] | [
{
"body": "<p>The code is generally well written and easy to understand, but I have a few comments on it that could help improve it.</p>\n\n<h2>Eliminate \"magic numbers\"</h2>\n\n<p>In the <code>StackCreate</code> routine, the first instruction is <code>mov rdi,24</code> but it's not clear what 24 signifies in this context. Either a comment or a named constant or both would help with that.</p>\n\n<h2>Add more meaningful comments</h2>\n\n<p>The stack structure is not very clear from the comments. We can infer that the stack consists of nodes, but it's not easy to tell from the code or the comments. </p>\n\n<p>Also, consider the user of the stack code. There isn't currently enough within the code to understand the calling sequence, register usage or return values. All of those would be useful to have in the comments. If you're intending to use a standard ABI, it would be useful to say which one.</p>\n\n<h2>Use <code>rep ret</code> as appropriate</h2>\n\n<p>The gcc compiler emits <code>rep ret</code> when the <code>ret</code> could be the target of a jump. This seems weird (and it is!) but the reason is that the branch prediction logic on both AMD and Intel processors works better when the <code>ret</code> is not the target of branch. So this means the <code>StackFirst_end</code> label in your code should actually have a <code>rep</code> prefix just before the <code>ret</code>.</p>\n\n<h2>Use <code>struc</code> as appropriate</h2>\n\n<p>Because your stack uses two structures, it would benefit from using NASM's <code>struc/endstruc</code> macros. This would both make it more clear when the code is manipulating data structures and also eliminate quite a few of the \"magic numbers\" I mentioned earlier.</p>\n\n<h2>Consider refactoring <code>StackFirst</code> and <code>StackNext</code></h2>\n\n<p>Other than minor differences in specific register selection, the <code>StackFirst</code> and <code>StackNext</code> routines are very similar. It may be possible to combine them to eliminate some code.</p>\n\n<h2>Reduce use of <code>malloc</code> and <code>free</code></h2>\n\n<p>The <code>malloc</code> and <code>free</code> calls tend to be relatively computationally expensive, especially relative to the assembly code you've got. For that reason, it would probably make more sense to either allocate and manage a block rather than calling <code>malloc</code> for every stack push, or to replace calls to <code>malloc</code> and <code>free</code> with some other memory allocation scheme that might be user-replaceable for speed.</p>\n\n<h2>Rearrange the loop to avoid unconditional jumps</h2>\n\n<p>The current <code>pushing_loop</code> looks like this:</p>\n\n<pre><code> pushing_loop:\n test r13, r13\n jz pushing_done\n mov rdi, r14\n mov rsi, [r12]\n call StackPush\n add r12, 8\n dec r13\n jmp pushing_loop\n pushing_done:\n</code></pre>\n\n<p>However, it could be slightly rearranged to eliminate one of the jumps:</p>\n\n<pre><code> inc r13\n jmp push_test\n\n pushing_loop:\n mov rdi, r14\n mov rsi, [r12]\n call StackPush\n add r12, 8\n push_test:\n dec r13\n jnz pushing_loop\n</code></pre>\n\n<p>The unconditional jump is only made once at the top of the loop and all other iterations use only the conditional test at the bottom of the loop. There are a few other places in the code this could be applied.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-05T01:50:05.700",
"Id": "48951",
"ParentId": "46000",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "48951",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T02:22:52.170",
"Id": "46000",
"Score": "27",
"Tags": [
"linked-list",
"stack",
"assembly"
],
"Title": "Stack implemented using linked list in x86_64 assembly"
} | 46000 |
<blockquote>
<p>Given <code>(</code> and <code>)</code> and length of 4, generate the following combinations -
<code>()()</code> and <code>(())</code>.</p>
</blockquote>
<p>Looking for code review, optimizations and best practices. Also verifying complexity to be O(2<sup>(n+1)</sup> - 1), where n is half the 'input length'.</p>
<pre><code>public final class BraceCombinations {
private BraceCombinations() {}
/**
* Returns sets of valid combinations.
*
* @param length the sum of length of all- opening + closing braces
* @return the valid brace combinations
*/
public static List<List<String>> getBraceCombinations(int length) {
if (length <= 0) {
throw new IllegalArgumentException("The length should be greater than zero");
}
if (length % 2 == 1) {
throw new IllegalArgumentException("The length should be positive");
}
final List<List<String>> paranthesesCombo = new ArrayList<List<String>>();
generate(paranthesesCombo, new LinkedList<String>(), 0, 0, length/2);
return paranthesesCombo;
}
private static void generate(List<List<String>> paranthesesCombo, LinkedList<String> parenthesis, int openBrace, int closeBrace, int halfLength) {
if (openBrace == halfLength && closeBrace == halfLength) {
paranthesesCombo.add(new ArrayList<String>(parenthesis));
}
if (openBrace > halfLength || closeBrace > openBrace) {
return;
}
parenthesis.add("(");
generate(paranthesesCombo, parenthesis, openBrace + 1, closeBrace, halfLength);
parenthesis.removeLast();
parenthesis.add(")");
generate(paranthesesCombo, parenthesis, openBrace, closeBrace + 1, halfLength);
parenthesis.removeLast();
}
public static void main(String[] args) {
List<List<String>> paths1 = Arrays.asList(
Arrays.asList("(", ")")
);
assertEquals(paths1, getBraceCombinations(2));
List<List<String>> paths = Arrays.asList(
Arrays.asList("(", "(", ")", ")"),
Arrays.asList("(", ")", "(", ")")
);
assertEquals(paths, getBraceCombinations(4));
}
}
</code></pre>
| [] | [
{
"body": "<p>Jus a few minor points:</p>\n\n<ol>\n<li><p>I guess you have a typo here:</p>\n\n<blockquote>\n<pre><code>if (length % 2 == 1) { \n throw new IllegalArgumentException(\"The length should be positive\");\n}\n</code></pre>\n</blockquote>\n\n<p>If <code>length</code> is <code>3</code> it prints that <code>The length should be positive</code>.</p></li>\n<li><p>An exaplanatory variable would be a little bit easier to read here and it would express the purpose of the expression:</p>\n\n<pre><code>final boolean oddLength = (length % 2 == 1);\nif (oddLength) {\n throw new IllegalArgumentException(\"...\");\n}\n</code></pre></li>\n<li><p>It could be easier to read and modify the expected outputs in the tests, especially if length is higher than four:</p>\n\n<pre><code>Arrays.asList(\"(\", \"(\", \"(\", \")\", \")\", \")\"),\n</code></pre>\n\n<p>I'd rather use a <a href=\"http://xunitpatterns.com/Custom%20Assertion.html#Verification%20Method\" rel=\"nofollow\">custom verification method</a> here:</p>\n\n<pre><code>private static void verifyPaths(final List<String> expectedPaths, \n final int length) {\n final List<List<String>> braceCombinations = getBraceCombinations(length);\n\n final List<String> joinedBraceCombinations = \n flattenBraceCombinations(braceCombinations);\n\n assertEquals(expectedPaths, joinedBraceCombinations);\n}\n\nprivate static List<String> flattenBraceCombinations(\n final List<List<String>> braceCombinations) {\n final Joiner joiner = Joiner.on(\"\");\n final List<String> joinedBraceCombinations = new ArrayList<>();\n for (final List<String> braceCombination: braceCombinations) {\n final String joinedBraceCombination = joiner.join(braceCombination);\n joinedBraceCombinations.add(joinedBraceCombination);\n }\n return joinedBraceCombinations;\n}\n</code></pre>\n\n<p>With plain strings as expected output:</p>\n\n<pre><code>final List<String> expectedPaths = Arrays.asList(\n \"((()))\", \n \"(()())\", \n \"(())()\", \n \"()(())\", \n \"()()()\");\nverifyPaths(expectedPaths, 6);\n</code></pre></li>\n<li><p>I would consider changing the current</p>\n\n<blockquote>\n<pre><code>List<List<String>>\n</code></pre>\n</blockquote>\n\n<p>return type to</p>\n\n<pre><code>Set<List<String>>\n</code></pre>\n\n<p>The order of combinations doesn't look so important and it would make the test less specified (the order of expected paths would not be important too).</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T04:51:51.950",
"Id": "46007",
"ParentId": "46003",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T03:20:34.360",
"Id": "46003",
"Score": "2",
"Tags": [
"java",
"algorithm",
"balanced-delimiters"
],
"Title": "Print all combinations of balanced parentheses"
} | 46003 |
<p>I just wrote this pool to avoid calling <code>malloc</code> and <code>free</code> when I have some code that frequently allocates and deallocates chunks of same-sized memory. I would like to know if there are any bugs I didn't notice and what would be the best solution to achieve this goal.</p>
<p>I'm using some small functions that aren't really required because I find the abstraction nice when using the code later and because I noticed the compiler will optimize them away when link-time optimization is turned on.</p>
<p>I'm using about the same code I posted before for the stack.</p>
<p><code>object_pool.h</code></p>
<pre><code>#ifndef OBJECT_POOL_H
#define OBJECT_POOL_H
#include <stdlib.h>
#include "dynamic_stack.h"
#define OP_SUCCESS 1
#define OP_ERROR 0
typedef struct Memory_Block {
char *position;
char *end;
struct Memory_Block *next;
} Memory_Block;
typedef struct Object_Pool {
Dynamic_Stack free_blocks;
size_t object_size;
size_t big_block_capacity;
Memory_Block *last_memory_block;
Memory_Block *first_memory_block;
size_t total_blocks;
} Object_Pool;
int op_init_custom(Object_Pool *op, size_t object_size, size_t big_block_capacity);
int op_init(Object_Pool *op, size_t object_size);
void op_destroy(Object_Pool *op);
void op_set_big_block_capacity(Object_Pool *op, size_t new_capacity);
size_t op_total_blocks(Object_Pool *op);
void *op_get(Object_Pool *op);
void op_release(Object_Pool *op, void *object);
void op_release_all(Object_Pool *op);
#endif
</code></pre>
<p><code>object_pool.c</code></p>
<pre><code>#include "object_pool.h"
#define DEFAULT_CAPACITY 128
#define STACK_CAPACITY 128
#define OP_FAIL_SAFE
static char *memory_block_start(Memory_Block *block)
{
return (char *)(block + 1);
}
static Memory_Block *new_memory_block(Object_Pool *op)
{
Memory_Block *temp = malloc(sizeof(Memory_Block) + op->object_size * op->big_block_capacity);
if(temp == NULL)
return NULL;
//If the stack can't support the same number of objects created, freeing objects might fail
#ifdef OP_FAIL_SAFE
if(dstack_increase_capacity(&op->free_blocks, op->big_block_capacity) == DSTACK_ERROR){
free(temp);
return OP_ERROR;
}
#endif
temp->position = memory_block_start(temp);
temp->end = temp->position + op->object_size * op->big_block_capacity;
temp->next = NULL;
op->total_blocks += op->big_block_capacity;
return temp;
}
int op_init_custom(Object_Pool *op, size_t object_size, size_t big_block_capacity)
{
op->object_size = object_size;
op->big_block_capacity = big_block_capacity;
op->total_blocks = 0;
if(dstack_init(&op->free_blocks, STACK_CAPACITY) == DSTACK_ERROR)
return OP_ERROR;
op->first_memory_block = op->last_memory_block = new_memory_block(op);
if(op->first_memory_block == NULL){
dstack_free(&op->free_blocks);
return OP_ERROR;
}
return OP_SUCCESS;
}
int op_init(Object_Pool *op, size_t object_size)
{
return op_init_custom(op, object_size, DEFAULT_CAPACITY);
}
void op_destroy(Object_Pool *op)
{
dstack_free(&op->free_blocks);
Memory_Block *next;
for(Memory_Block *ite = op->first_memory_block; ite != NULL; ite = next){
next = ite->next;
free(ite);
}
}
void op_set_big_block_capacity(Object_Pool *op, size_t new_capacity)
{
if(new_capacity >= op->object_size)
op->big_block_capacity = new_capacity;
}
size_t op_total_blocks(Object_Pool *op)
{
return op->total_blocks;
}
void *op_get(Object_Pool *op)
{
void *block = dstack_pop(&op->free_blocks);
if(block != DSTACK_EMPTY)
return block;
if((block = op->last_memory_block->position) < (void *)op->last_memory_block->end){
op->last_memory_block->position += op->object_size;
return block;
}
if((op->last_memory_block->next = new_memory_block(op)) == NULL)
return NULL;
op->last_memory_block = op->last_memory_block->next;
block = op->last_memory_block->position;
op->last_memory_block->position += op->object_size;
return block;
}
void op_release(Object_Pool *op, void *object)
{
dstack_push(&op->free_blocks, object);
}
void op_release_all(Object_Pool *op)
{
for(Memory_Block *ite = op->first_memory_block; ite != NULL; ite = ite->next)
ite->position = memory_block_start(ite);
//The stack must be cleared too to avoid handling the same block twice
dstack_clear(&op->free_blocks);
}
</code></pre>
<p><code>dynamic_stack.h</code></p>
<pre><code>#ifndef DYNAMIC_STACK
#define DYNAMIC_STACK
#include <stdlib.h>
#define DSTACK_SUCCESS 1
#define DSTACK_ERROR 0
extern void *DSTACK_EMPTY;
//The stack just stores pointers
typedef struct Dynamic_Stack Dynamic_Stack;
struct Dynamic_Stack {
void **start; //Array of pointer to void
void **position;
void **end;
};
//Set up stack
int dstack_init(Dynamic_Stack *stack, size_t slots);
void dstack_free(Dynamic_Stack *stack);
void dstack_clear(Dynamic_Stack *stack);
int dstack_push(Dynamic_Stack *stack, void *new_element);
void *dstack_pop(Dynamic_Stack *stack);
//0 is the top of the stack
void *dstack_peek(Dynamic_Stack *stack, size_t levels);
int dstack_increase_capacity(Dynamic_Stack *stack, size_t new_slots);
int dstack_decrease_capacity(Dynamic_Stack *stack, size_t remove_total);
void dstack_shrink_to_fit(Dynamic_Stack *stack);
#endif
</code></pre>
<p><code>dynamic_stack.c</code></p>
<pre><code>#include <stdlib.h>
#include "dynamic_stack.h"
#define MULTIPLIER 1.00 //Increase by 100% on every expansion
#define FIXED_EXPANSION 0 //Overrides multiplier
//Signal the stack is empty
char dummy = 'd';
void *DSTACK_EMPTY = &dummy;
//Internal
//Must keep at least 1 slot or it will break
static int dstack_resize(Dynamic_Stack *stack, size_t new_slot_capacity)
{
size_t position = stack->position - stack->start;
void *temp = realloc(stack->start, new_slot_capacity * sizeof(void *));
if(temp == NULL)
return DSTACK_ERROR;
stack->start = temp;
stack->end = stack->start + new_slot_capacity;
//Put position back if needed
stack->position = (position < new_slot_capacity)
? stack->start + position
: stack->end;
return DSTACK_SUCCESS;
}
#if FIXED_EXPANSION >= 1
static int expand(Dynamic_Stack *stack)
{
return dstack_resize(stack, stack->end - stack->start + FIXED_EXPANSION);
}
#else
static int expand(Dynamic_Stack *stack)
{
//Check if multiplier is producing at least 1 new slot
size_t old_slots = stack->end - stack->start;
size_t new_slots = old_slots * MULTIPLIER;
if(new_slots == 0)
return DSTACK_ERROR;
return dstack_resize(stack, old_slots + new_slots);
}
#endif
//Public
//Set up stack
int dstack_init(Dynamic_Stack *stack, size_t slots)
{
if((stack->start = malloc(sizeof(void *) * slots)) == NULL)
return DSTACK_ERROR;
stack->position = stack->start;
stack->end = stack->start + slots;
return DSTACK_SUCCESS;
}
void dstack_free(Dynamic_Stack *stack)
{
free(stack->start);
}
void dstack_clear(Dynamic_Stack *stack)
{
stack->position = stack->start;
}
int dstack_push(Dynamic_Stack *stack, void *new_element)
{
if(stack->position == stack->end && expand(stack) == DSTACK_ERROR)
return DSTACK_ERROR;
*stack->position = new_element;
++stack->position;
return DSTACK_SUCCESS;
}
void *dstack_pop(Dynamic_Stack *stack)
{
if(stack->position == stack->start)
return DSTACK_EMPTY;
return *--stack->position;
}
//0 is the top of the stack
void *dstack_peek(Dynamic_Stack *stack, size_t levels)
{
if(levels >= (size_t)(stack->position - stack->start))
return NULL;
return *(stack->position - 1 - levels);
}
int dstack_increase_capacity(Dynamic_Stack *stack, size_t new_slots)
{
return dstack_resize(stack, stack->end - stack->start + new_slots);
}
int dstack_decrease_capacity(Dynamic_Stack *stack, size_t remove_total)
{
if(remove_total >= (size_t)(stack->end - stack->start))
return DSTACK_ERROR;
return dstack_resize(stack, stack->end - stack->start - remove_total);
}
//Always leave 1 extra slot so there's no risk of resizing to 0
void dstack_shrink_to_fit(Dynamic_Stack *stack)
{
dstack_resize(stack, stack->position - stack->start + 1);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T00:22:29.713",
"Id": "85246",
"Score": "0",
"body": "Could you also post the contents of `\"dynamic_stack.h\"`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-02T09:00:34.697",
"Id": "85609",
"Score": "0",
"body": "@haneefmubarak I added the stack code, I'm looking forward to your review."
}
] | [
{
"body": "<p>You should always use curly braces around <code>if</code> statements and <code>for</code> loops. It's the safe thing to do, especially when you are dealing with memory-management. </p>\n\n<p>Something small like this:</p>\n\n<pre><code>if(temp == NULL)\n return NULL;\n</code></pre>\n\n<p>Can be one lined:</p>\n\n<pre><code>if(temp == NULL) return NULL;\n</code></pre>\n\n<p>Braces can be omitted on this one, because it is one lined and it's still very obvious that this is the entire if statement, and if someone comes along to add something to this they have to add braces anyway.</p>\n\n<hr>\n\n<p>Returning in an <code>if</code> statement should always be inside of curly braces:</p>\n\n<pre><code>int dstack_decrease_capacity(Dynamic_Stack *stack, size_t remove_total)\n{\n if(remove_total >= (size_t)(stack->end - stack->start))\n return DSTACK_ERROR;\n\n return dstack_resize(stack, stack->end - stack->start - remove_total);\n}\n</code></pre>\n\n<p>like this:</p>\n\n<pre><code>int dstack_decrease_capacity(Dynamic_Stack *stack, size_t remove_total)\n{\n if(remove_total >= (size_t)(stack->end - stack->start))\n {\n return DSTACK_ERROR;\n }\n return dstack_resize(stack, stack->end - stack->start - remove_total);\n}\n</code></pre>\n\n<p>You especially want the fact that this is throwing an error to stick out, this is easier to read in my opinion.</p>\n\n<hr>\n\n<p>The <code>for</code> loop!\nUGH!</p>\n\n<pre><code>void op_release_all(Object_Pool *op)\n{\n for(Memory_Block *ite = op->first_memory_block; ite != NULL; ite = ite->next)\n ite->position = memory_block_start(ite);\n\n //The stack must be cleared too to avoid handling the same block twice\n dstack_clear(&op->free_blocks);\n}\n</code></pre>\n\n<p>Don't write it like that, it looks ugly; this is much prettier I think:</p>\n\n<pre><code>void op_release_all(Object_Pool *op)\n{\n for(Memory_Block *ite = op->first_memory_block; ite != NULL; ite = ite->next)\n {\n ite->position = memory_block_start(ite);\n }\n\n //The stack must be cleared too to avoid handling the same block twice\n dstack_clear(&op->free_blocks);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T13:59:18.137",
"Id": "60799",
"ParentId": "46005",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T03:31:44.623",
"Id": "46005",
"Score": "8",
"Tags": [
"c",
"memory-management"
],
"Title": "Does this simple memory pool use too much memory?"
} | 46005 |
<p>I wonder if there are some possible ways to simplify my code. <br/></p>
<pre><code>startDate = '04/02/2014'
endDate = '04/06/2014'
mondayTag = 0
tuesdayTag = 0
wednesdayTag = 1
thursdayTag = 0
fridayTag = 1
saturdayTag = 0
sundayTag = 0
public int GetRemainingDays(DateTime startDate, DateTime endDate, bool mondayTag, bool tuesdayTag, bool wednesdayTag, bool thursdayTag, bool fridayTag, bool saturdayTag, bool sundayTag)
{
int i = 0;
for (DateTime day = startDate.AddDays(1); day.Date <= endDate.Date; day = day.AddDays(1))
{
if (day.DayOfWeek == DayOfWeek.Monday && mondayTag == true)
{
i = i + 1;
}
else if (day.DayOfWeek == DayOfWeek.Tuesday && tuesdayTag == true)
{
i = i + 1;
}
else if (day.DayOfWeek == DayOfWeek.Wednesday && wednesdayTag == true)
{
i = i + 1;
}
else if (day.DayOfWeek == DayOfWeek.Thursday && thursdayTag == true)
{
i = i + 1;
}
else if (day.DayOfWeek == DayOfWeek.Friday && fridayTag == true)
{
i = i + 1;
}
else if (day.DayOfWeek == DayOfWeek.Saturday && saturdayTag == true)
{
i = i + 1;
}
else if (day.DayOfWeek == DayOfWeek.Sunday && sundayTag == true)
{
i = i + 1;
}
}
return i > 0 ? i : 0;
}
</code></pre>
| [] | [
{
"body": "<p>Since DayOfWeek is a an Enum with 0 = Sunday through 6 = Saturday.</p>\n\n<p>Instead of passing Boolean tags, you can pass an array of integers where index = 0 is for Sunday, with value 1 for true and 0 for false.</p>\n\n<pre><code> var dayOfWeeksTags = new int[7];\n</code></pre>\n\n<p>then you can compute something like </p>\n\n<pre><code> i += dayOfWeeksTags[(int) day.DayOfWeek];\n</code></pre>\n\n<p>Your function becomes something like this.</p>\n\n<pre><code> public int GetRemainingDays(DateTime startDate, DateTime endDate, int[] dayOfWeekTags)\n {\n int i = 0;\n\n for (DateTime day = startDate.AddDays(1); day.Date <= endDate.Date; day = day.AddDays(1))\n i += dayOfWeekTags[(int) day.DayOfWeek];\n\n return i;\n } \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T06:53:49.087",
"Id": "46012",
"ParentId": "46010",
"Score": "1"
}
},
{
"body": "<p>Using <code>System.Linq</code> library the method can be rewritten like this:</p>\n\n<pre><code>public static int GetRemainingDays(DateTime startDate, DateTime endDate, ISet<DayOfWeek> includedDays)\n{\n return Enumerable.Range(0, Int32.MaxValue)\n .Select(n => startDate.AddDays(n+1))\n .TakeWhile(date => date <= endDate)\n .Count(date => includedDays.Contains(date.DayOfWeek));\n}\n</code></pre>\n\n<p>Which can then be more easily called like this:</p>\n\n<pre><code>GetRemainingDays(startDate, endDate, \n new HashSet<DayOfWeek>{DayOfWeek.Wednesday, DayOfWeek.Friday});\n</code></pre>\n\n<p>Note: You should test this (and the original version) against off-by-one errors.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:28:19.123",
"Id": "80571",
"Score": "0",
"body": "“You should test this against off-by-one errors.” I think you actually made one: the first `n` is 1, and you then use `n+1`, which means the first tested date is `strartDate.AddDays(2)`, which I think is wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:30:56.990",
"Id": "80572",
"Score": "0",
"body": "Also, I probably wouldn't bother with `ISet`. The maximum number of items in that set is 7, so you don't care about O(1) vs. O(n) here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:32:23.883",
"Id": "80573",
"Score": "0",
"body": "One more thing: what is the `TakeWhile()` trying to accomplish? Doesn't the original `Range()` already limit the range correctly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:57:41.537",
"Id": "80578",
"Score": "0",
"body": "@svick I was in doubt whether my \"refactoring\" preserved the `for` loop behavior to the letter, but as you pointed out in your answer the original version is also suspicious so really didn't bother to work out edge cases. As for `ISet` my first thought was `params DayOfWeek[]` but I thought it intention hiding. `DayOfWeek[]` is good though, and less verbose on the call site.As for `TakeWhile`, I removed redundancy in `Range` in the edit such that it more clearly mirrors `for` loop."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T07:32:42.477",
"Id": "46014",
"ParentId": "46010",
"Score": "4"
}
},
{
"body": "<h3>Interface</h3>\n\n<p>I can see this method being useful for, say, counting the number of times a class will meet if it is scheduled for Mondays, Wednesdays, and Fridays from 2014-01-01 to 2014-06-01.</p>\n\n<p>I would expect <code>startDate</code> to be included in the count; it surprises me that the <code>startDate</code> is not counted. It's not obvious whether <code>endDate</code> should be included or not. Either way, you need to document how the two dates at each end are treated.</p>\n\n<p>This method is a pure function, and should probably be made <code>static</code>.</p>\n\n<p>There is a maxim among programmers that there are either <a href=\"http://stevehanov.ca/blog/index.php?id=134\" rel=\"nofollow\">zero, one, or many</a> of something. If you ever need to handle three or seven of something, you should generalize to handle many. By that principle, the method signature should be</p>\n\n<pre><code>public static int CountOccurrences(DateTime startDate, DateTime endDate, DayOfWeek[] days)\n</code></pre>\n\n<p>One way to implement that is to sum the results of calling a helper method</p>\n\n<pre><code>public static int CountOccurrences(DateTime startDate, DateTime endDate, DayOfWeek day)\n</code></pre>\n\n<p>… for each of the <code>days</code>.</p>\n\n<h3>Implementation</h3>\n\n<p>The <code>return</code> statement should be just <code>return i;</code> since <code>i</code> will only be negative in case of overflow.</p>\n\n<p>Your implementation doesn't scale very well if the date range is large. You should find a way to count the number of whole weeks within the range, then handle the partial weeks at each end.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:36:36.520",
"Id": "80574",
"Score": "0",
"body": "That `CountOccurrences` for a single day is an interesting idea, especially since it wouldn't be that hard to implement it in O(1) (i.e. without loops). Though that's probably the premature optimizer in me talking."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T07:34:54.670",
"Id": "46015",
"ParentId": "46010",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T06:29:15.630",
"Id": "46010",
"Score": "5",
"Tags": [
"c#",
"datetime"
],
"Title": "Get remaining days in date range"
} | 46010 |
<p>Here is the code as it stands right now:</p>
<pre><code>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])
N = np.zeros(np.shape(Z))
for x in range(rows):
for y in range(cols):
Q = [q for q in [x-1, x, x+1] if ((q >= 0) and (q < cols))]
R = [r for r in [y-1, y, y+1] if ((r >= 0) and (r < rows))]
S = [Z[q][r] for q in Q for r in R if (q, r) != (x, y)]
N[x][y] = sum(S)
return N
def iterate(Z):
Zprime = Z.copy()
rows, cols = len(Zprime), len(Zprime[0])
N = computeNeighbours(Zprime)
for x in range(rows):
for y in range(cols):
if Zprime[x][y] == 1:
if (N[x][y] < 2) or (N[x][y] > 3):
Zprime[x][y] = 0
else:
if (N[x][y] == 3):
Zprime[x][y] = 1
return Zprime
fig = plt.figure()
Zs = [Z]
ims = []
for i in range(0, 100):
im = plt.imshow(Zs[len(Zs)-1], interpolation = 'nearest', cmap='binary')
ims.append([im])
Zs.append(iterate(Zs[len(Zs)-1]))
ani = animation.ArtistAnimation(fig, ims, interval=250, blit=True)
plt.show()
</code></pre>
<p><strong>I am interested in knowing what sequence of optimizations one would perform for this sort of an application</strong>, so that I can get a handle on how to use NumPy's power for my current project, which is simply a (perhaps) three dimensional, cellular automaton with many rules.</p>
| [] | [
{
"body": "<p>I'll just be cheeky and post a slightly modified version of my SO answer here.</p>\n\n<p>So first things first, you want to get rid of the loops. They are slow to execute.</p>\n\n<p>The first loop:</p>\n\n<pre><code>for x in range(rows):\n for y in range(cols):\n if Z[x][y] == 1:\n if (N[x][y] < 2) or (N[x][y] > 3):\n Z[x][y] = 0\n else:\n if (N[x][y] == 3):\n Z[x][y] = 1\n</code></pre>\n\n<p>could be replaced by:</p>\n\n<pre><code>set_zero_idxs = (Z==1) & ((N<2) | (N>3))\nset_one_idxs = (Z!=1) & (N==3)\nZ[set_zero_idxs] = 0\nZ[set_one_idxs] = 1\n</code></pre>\n\n<p>Here you are generating boolean arrays that indicate which values satisfy your criteria and then you are setting those values to either 0 or 1.</p>\n\n<p>Benchmarking this we see a significant improvement in speed (x 180):</p>\n\n<pre><code># new version without loop\nIn [49]: %timeit no_loop(z,n)\n1000 loops, best of 3: 177 us per loop\n\n# original version with loop \nIn [50]: %timeit loop(z,n)\n10 loops, best of 3: 31.2 ms per loop\n</code></pre>\n\n<p>The second major loop:</p>\n\n<pre><code>for x in range(rows):\n for y in range(cols):\n Q = [q for q in [x-1, x, x+1] if ((q >= 0) and (q < cols))]\n R = [r for r in [y-1, y, y+1] if ((r >= 0) and (r < rows))]\n S = [Z[q][r] for q in Q for r in R if (q, r) != (x, y)]\n N[x][y] = sum(S)\n</code></pre>\n\n<p>could be replaced by:</p>\n\n<pre><code>N = np.roll(Z,1,axis=1) + np.roll(Z,-1,axis=1) + np.roll(Z,1,axis=0) + np.roll(Z,-1,axis=0)\n</code></pre>\n\n<p>[Note: this is actually wrong for the game of life, as the code should check for diagonal neighbours as well. This is simply a refactoring of the original for loop construct.]</p>\n\n<p>Here there is an implicit assumption that the array does not have bounds and that <code>x[-1]</code> is next to <code>x[0]</code>. If this is a problem, you could add a buffer of zeros around your array with:</p>\n\n<pre><code>shape = Z.shape\nnew_shape = (shape[0]+2,shape[1]+2)\n# b_z is a new array which will be our buffer\nb_z = np.zeros(new_shape)\n\n# set the middle of the array equal to the original `Z`\nb_z[1:-1,1:-1] = Z\n\n# do our rolls on the buffered array so that we don't have boundary isssues\nb_n = np.roll(b_z,1,axis=1) + np.roll(b_z,-1,axis=1) + np.roll(b_z,1,axis=0) + np.roll(b_z,-1,axis=0)\n\n# write back the part of the array that is of interest to us\nN = b_n[1:-1,1:-1]\n</code></pre>\n\n<p>and for a benchmark:</p>\n\n<pre><code># original function with loops\nIn [4]: %timeit computeNeighbours(z)\n10 loops, best of 3: 140 ms per loop \n\n# new function without a buffer\nIn [5]: %timeit noloop_computeNeighbours(z)\n10000 loops, best of 3: 133 us per loop\n\n# new function with a buffer to remove boundary counts\nIn [6]: %timeit noloop_with_buffer_computeNeighbours(z)\n10000 loops, best of 3: 170 us per loop\n</code></pre>\n\n<p>So just a small improvement of a factor of <strong>x 1052</strong>. Hooray for Numpy!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T08:02:55.620",
"Id": "46020",
"ParentId": "46011",
"Score": "13"
}
}
] | {
"AcceptedAnswerId": "46020",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T06:36:34.753",
"Id": "46011",
"Score": "7",
"Tags": [
"python",
"numpy",
"animation",
"game-of-life",
"matplotlib"
],
"Title": "Optimizing very simple piece of “Game of Life” code by taking advantage of NumPy's functionality"
} | 46011 |
<p>Writing a MMORPG server in nodejs, I have to handle packets. These packets have a structure of </p>
<pre><code><length> <id> <data>
</code></pre>
<p>So what I did was use a node package called <a href="https://github.com/bigeasy/packet">packet</a></p>
<p>And first get the packet id:</p>
<pre><code>client.on('data', function(data) {
parser.extract("l16 => length, l16 => id", function (packet) {
if (packet.id === 300) {
}
if (packet.id === 301) {
}
if (packet.id === 302) {
}
if (packet.id === 303) {
}
});
// parse the packet id to handle it accordingly
parser.parse(data);
});
</code></pre>
<p>There are packet Id's upto 1000+ which would make my if statements very long. But each packet id contains different data and different ways to handle it.</p>
<p>For example packet 300 which is the handshake packet. It sends the client version to the server and the servers checks it and returns if it is correct or not, if not then client will error wrong version.</p>
<pre><code> if (packet.id === 300) {
console.log('[recieved] packet:handshake');
parser.extract("handshake", function (packet) {
if (packet.gameClientVer === config.gameClientVer) {
// do stuff
} else {
// do stuff
}
});
// parse structure for packet 300
parser.parse(data);
}
});
</code></pre>
<p>the handshake packet is defined as:</p>
<pre><code>serializer.packet("handshake", "l16 => length, l16 => id, l16 => gameClientVer, l16 => gameUpdateVer, l16 => gameDateVer");
</code></pre>
<p>My question is, how can I improve this?</p>
| [] | [
{
"body": "<p>You should compartmentalize your \"handlers\" for each of the packets. Each handler should contain a <code>canHandle</code> method that determines whether it can process the packet and a <code>process</code> method that does the work. Example:</p>\n\n<pre><code>var packet300Handler = {\n canHandle: function(packet) {\n return packet.id === 300;\n },\n process: function(packet) {\n // Do work here.\n }\n};\n\nvar handlers = [packet300Handler, packet301Handler, packet302Handler];\n\nclient.on('data', function(data) {\n parser.extract('DATA', function(packet) {\n for (var i = 0; i < handlers.length; i++) {\n var handler = handlers[i];\n\n if (handler.canHandle(packet)) {\n handler.process(packet);\n break; // Leave loop now that something has handled the packet.\n }\n }\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:23:55.290",
"Id": "80366",
"Score": "0",
"body": "Although the cost probably wouldn't be *too* bad, I don't see why you'd loop through an array looking for an element that can handle a given packet rather than just having an associative array keyed on packet.id and referring directly to the process function (as suggested in the other answer)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:38:14.833",
"Id": "46043",
"ParentId": "46013",
"Score": "4"
}
},
{
"body": "<p>I would have a function per <code>packet.id</code>:</p>\n\n<pre><code>function handleHandShake(packet, data)\n{\n //Do not use console.log for mmorpg's, write to a text file if you must\n //console.log('[recieved] packet:handshake');\n\n parser.extract(\"handshake\", function (packet) {\n if (packet.gameClientVer === config.gameClientVer) {\n // do stuff\n } else {\n // do stuff \n }\n });\n\n //parse structure for packet 300\n parser.parse(data);\n}\n</code></pre>\n\n<p>I would go for a <code>packet.id</code> based routing table:</p>\n\n<pre><code>var routes = [\n '300' : handleHandShake,\n '301' : addExperience,\n etc. etc.\n]\n</code></pre>\n\n<p>Then, you can extract the <code>packet.id</code> and execute the proper function</p>\n\n<pre><code>client.on('data', function(data) {\n parser.extract(\"l16 => length, l16 => id\", function (packet) {\n if( routes[packet.id] ){\n routes[packet.id](packet, data);\n } else {\n //Do something ( logging? ) if we get unknown packet id's\n }\n });\n\n // parse the packet id to handle it accordingly\n parser.parse(data);\n});\n</code></pre>\n\n<p>It was fun learning about the package module, great question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:07:57.043",
"Id": "80361",
"Score": "0",
"body": "This seems like a good approach. Care to explain why I shouldn't be `console.logging` on MMORPG? Does this have something to do with performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:10:53.697",
"Id": "80362",
"Score": "0",
"body": "Yes indeed, console.log is synchronous and will murder performance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:25:06.367",
"Id": "80368",
"Score": "0",
"body": "Oh, right. I should just make those logs available for debugging. Thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:41:12.287",
"Id": "46057",
"ParentId": "46013",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46057",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T07:29:52.133",
"Id": "46013",
"Score": "7",
"Tags": [
"javascript",
"node.js"
],
"Title": "Handling packets in nodejs for MMORPG"
} | 46013 |
<p>I was asked to answer the following question before setting up a phone interview, but they said my code wasn't detailed enough.</p>
<p>Question:</p>
<blockquote>
<p>Without using any of the .NET Collection or Linq libraries (i.e.
without using List), implement a ListOfStrings object that
contains a set of strings. This object has the following methods:<br>
Add(string) - inserts a string to the end of the list ToString() -
Returns the list as a comma separated string.</p>
<p>Example Usage:</p>
<pre><code>ListOfStrings list = new ListOfStrings(); // set is empty
list.Add("abc"); // set is "abc"
list.Add("xyz"); // set is now "abc", "xyz"
list.Add("123"); // set is now abc", "xyz", "123"
list.ToString(); // Should return "abc,xyz,123"
</code></pre>
<p>Ideally, this code should be able to handle large numbers of items.</p>
</blockquote>
<p>Answer:</p>
<pre><code>namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
while (true)
{
ListOfStrings ls = new ListOfStrings();
ls.Add("test1");
ls.Add("test2");
ls.Add("122");
ls.Add("");
ls.ToString();
Console.WriteLine(ls.ToString());
}
}
}
public class ListOfStrings
{
private string ListOfString;
public ListOfStrings()
{
ListOfString = null;
}
public string Add(string input)
{
if (input != string.Empty)
{
ListOfString = ListOfString == null ? input : ListOfString + "," + input;
}
return ListOfString;
}
public string ToString()
{
return ListOfString;
}
}
}
</code></pre>
<p>Please let me know feedback on the code.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T08:17:28.783",
"Id": "80274",
"Score": "3",
"body": "What did they mean by \"not detailed enough\"? They were expecting comments or something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:51:51.663",
"Id": "80289",
"Score": "0",
"body": "I would suggest reading the question again. They're not asking you to store a comma separated string. My best guess is they were looking for you to use an array or create your own collection object to store the strings rather than using the inbuilt collections in C#."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:59:18.660",
"Id": "80292",
"Score": "3",
"body": "@CarlWinder The specification is not clear enough to determine that. As long as only `Add` and `ToString` are required using `StringBuilder` is simple and efficient. If we really need a collection, the simplest approach would be a doubly linked list. If random access is required we'd need a tree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:13:51.257",
"Id": "80298",
"Score": "1",
"body": "@CodesInChaos They specifically ask for a list. Look at the comments // set is now “abc”, “xyz” NOT set is now “abc,xyz”. I don't think we will ever see eye to eye on this, I think the spec is quite clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:31:04.983",
"Id": "80305",
"Score": "0",
"body": "@CarlWinder I agree, it did ask for a \"set\" of strings, and therefore I would have implemented it using an array. However I would have added some comments to the end of the program noting any assumptions that have been made in answering the question, i.e that there was no requirement for deleting therefore an array was used rather than implementing a linked list structure. That way you are showing you took the requirements into consideration in choosing the solution you did, and didnt simply miss or ignore a key point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:46:19.663",
"Id": "80308",
"Score": "1",
"body": "@GavinCoates I'd consider an array a built in .NET Collection, thus violating the requirement. Without that requirement I'd prefer an array or the array based `List<T>` over a linked list as wll."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:12:13.727",
"Id": "80338",
"Score": "0",
"body": "@CodesInChaos Actually according to the [.net definition](http://msdn.microsoft.com/en-us/library/ybcx56wz.aspx) a collection is dynamic therefore an array isn't a collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:25:18.340",
"Id": "80340",
"Score": "0",
"body": "@CodesInChaos I think the purpose of the question is to make the user implement functionality similar to the List<T> class, by creating functions that manipulate the data stored. The restriction is there to prevent them from just using the collections classes, and creating an Add() function that just wraps the List.Add() function, but instead implement the logic themselves. Therefore using an array would not violate this. To be clear, I am referring to String[] arrays, NOT the Array() class, which would be cheating."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:26:15.650",
"Id": "80341",
"Score": "1",
"body": "@tinstaafl An array implements `IEnumerable<T>`, `ICollection<T>` and `IList<T>`, so claiming it's not a collection is dubious IMO. There are also various immutable and readonly collections. The .net parts of MSDN are generally pretty low quality and contain a number of dubious claims like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:29:52.373",
"Id": "80346",
"Score": "0",
"body": "@GavinCoates, Of course, the requirements also say \"set,\" so I would consider the possibility of `Set` functionality (ie, no duplicates). Mentioning that in the comments about assumptions made would be important, IMO, though."
}
] | [
{
"body": "<p>I don't have too much experience with C#, so just some notes about the algorithm/structure. (Maybe there are C#-related issues which I'm not aware of.)</p>\n\n<p>At first I was expecting some array manipulation logic here with extending the array if it's full. They might be expected the same but your solution is quite cool, why would you complicate it? <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\">YAGNI</a> and it's a really simple solution which could work. I have to say that I really like it. Maybe a few (selft-checking) unit tests would have helped you to get a better impression.</p>\n\n<p>A few minor notes:</p>\n\n<ol>\n<li><p>It was not a requirement to ignore empty strings.</p></li>\n<li><p><code>Add</code> could be <code>void</code>.</p></li>\n<li><p>The first line seems unnecessary here:</p>\n\n<blockquote>\n<pre><code>ls.ToString();\nConsole.WriteLine(ls.ToString());\n</code></pre>\n</blockquote></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:52:53.707",
"Id": "80378",
"Score": "0",
"body": "I would take the fact that they actively said to not use any of the .NET Collections to mean that I wouldn't be allowed to use an array either, as that has been appended with extension methods with LINQ. Although, if you remove that reference, I could possibly see using the purest form of array. Though I wouldn't want to risk that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T08:08:04.460",
"Id": "46021",
"ParentId": "46017",
"Score": "6"
}
},
{
"body": "<p>Well... I think you answered the question as simple as possible.\nIf this was a jobinterview, and you did not get the job, you should think \"Hooray\" - that company does not accept the simple solution, and I am not working there! :)</p>\n\n<p>That said, I would not have submitted the code with the while(true) thing. And maybe I would have initilized to \"\" and not null.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:12:58.470",
"Id": "46026",
"ParentId": "46017",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p><code>ListOfString = null;</code> is useless, fields get initialized to <code>default(T)</code> which is <code>null</code> for reference types. So you can drop the constructor.</p>\n\n<p>For simple initializations you can use inline initializers. e.g.</p>\n\n<pre><code>private string ListOfString = \"\";\n</code></pre></li>\n<li><p>You're hiding <code>ToString()</code> instead of overriding it.</p></li>\n<li>You're ignoring empty input strings, the spec doesn't require that. Curiously you're not ignoring <code>null</code> input strings.</li>\n<li><p>Using a <code>string</code> as accumulator leads to quadratic runtime since it has to create a new string which contains all current data for each append.</p>\n\n<p>Use <code>StringBuilder.Append</code> in <code>Add</code> instead. Don't return a string from <code>Add</code>, else you lose the performance advantage. Call <code>stringBuilder.ToString()</code> in your <code>ToString</code> operation. This has linear runtime.</p></li>\n<li>You're returning <code>null</code> if no value has ever been added. I'd expect the empty string instead.</li>\n</ol>\n\n<p>I don't know what they meant by calling your code \"not detailed enough\". You could add documentation for corner cases, possibly in the form of unit tests. For my observations 3 and 5 it's not clear if your code is behaving like you intended. Documentation and/or unit tests would have clarified your intent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:13:52.277",
"Id": "80374",
"Score": "1",
"body": "+1 for `StringBuilder`... and everything else - nice answer you've got here."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:30:13.510",
"Id": "46028",
"ParentId": "46017",
"Score": "20"
}
},
{
"body": "<p>I suspect that the question is badly worded, and/or that your answer is too clever and simple for their question, and that instead they wanted a class which implements a list.</p>\n\n<p>Something like:</p>\n\n<pre><code>public class ListOfStrings\n{\n class Node\n {\n internal Node(string stringValue) { this.stringValue = stringValue; }\n internal readonly string stringValue;\n internal Node nextNode;\n }\n\n Node firstNode;\n\n public string Add(string input)\n {\n Node newNode = new Node(stringValue)\n if (firstNode == null)\n {\n firstNode = newNode;\n return;\n }\n Node lastNode = firstNode;\n while (lastNode.nextNode != null)\n lastNode = lastNode.nextNode;\n lastNode.nextNode = newNode;\n }\n</code></pre>\n\n<p>In order to \"Ideally, this code should be able to handle large numbers of items\" you would want to store lastNode as well as firstNode as members (so that you don't need to recalculate lastNode every time you add a new string).</p>\n\n<p>There's some ambiguity when they talk about a 'set' of strings; perhaps they want to keep the strings unique.</p>\n\n<hr>\n\n<blockquote>\n <p>Also, I'd like to see what your ToString() would look like.</p>\n</blockquote>\n\n<pre><code>public override string ToString()\n{\n StringBuilder sb = new StringBuilder();\n if (firstNode != null)\n {\n sb.Append(firstNode.stringValue);\n // next strings if any are comma-delimited\n for (Node nextNode = firstNode.nextNode; nextNode != null; nextNode = nextNode.nextNode)\n {\n sb.Append(\",\");\n sb.Append(nextNode.stringValue);\n }\n }\n return sb.ToString();\n}\n</code></pre>\n\n<p>The above returns an empty string if there are no nodes/strings in the list. Alternatively you might want to return <code>null</code> so that the user can distinguish between an empty list, and list which contains one empty string.</p>\n\n<p>OTOH this storage/display format is already sightly ambiguous, e.g. if a string contains a comma when it's stored.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:01:21.847",
"Id": "80434",
"Score": "0",
"body": "Good Answer. I suspect from the interview question that they want to have the programmer create a linked list, which is IMO is a good interview question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:25:32.217",
"Id": "80491",
"Score": "0",
"body": "If you're not going to have a `lastNode` field, there's no need to even have a `Node` class -- just store your `stringValue` directly in `ListOfStrings`. Also, Id like to see what your `ToString()` would look like."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:08:21.443",
"Id": "80524",
"Score": "0",
"body": "@Gabe I updated my answer per your comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:10:14.387",
"Id": "80560",
"Score": "1",
"body": "@PhilVallone I think it's a really bad question if they actually expect that, but don't have anything in the requirements that forces you to use it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T17:10:33.673",
"Id": "46075",
"ParentId": "46017",
"Score": "4"
}
},
{
"body": "<p>I'm compelled to write an answer because no one has really covered the <code>set</code> thing yet. Sets, maps, queues, vectors, linked lists, etc are words that have meaning to programmers, and I have a hard time believing a programmer would ask a question like this without intending the elements be unique.</p>\n\n<p>Overall, I agree with ChrisW and Carl Winder...it looks like they wanted some underlying data structure, not just a <code>String</code> that you append to. And they don't want .Net collections or Linq to be used.</p>\n\n<p>Technically, you could use a <code>String[] arr</code> and be safe. However, adding a new item requires you to create a new array, copy all the old values in, and add in the newest value at the end. That's fairly expensive and will not work well with large sets.</p>\n\n<p>Extending ChrisW's code:</p>\n\n<pre><code>class ListOfStrings\n{\n class Node\n {\n internal Node(string stringValue) { this.stringValue = stringValue; }\n internal readonly string stringValue;\n internal Node nextNode;\n }\n Node firstNode;\n Node lastNode;\n\n public ListOfStrings() { }\n\n public void Add(String str)\n {\n if (str != null && !Exists(str))\n {\n if (firstNode == null)\n {\n firstNode = new Node(str);\n lastNode = firstNode;\n }\n else\n {\n Node n = new Node(str);\n lastNode.nextNode = n;\n lastNode = n;\n }\n }\n }\n\n private bool Exists(String str)\n {\n bool result = false;\n\n Node curr = firstNode;\n while (curr != null)\n {\n if(curr.stringValue.Equals(str))\n {\n result = true;\n break;\n }\n curr = curr.nextNode;\n }\n\n return result;\n }\n\n public override String ToString()\n {\n StringBuilder result = new StringBuilder(\"\");\n\n Node curr = firstNode;\n while (curr != null)\n {\n if (result.ToString().Equals(\"\"))\n result.Append(curr.stringValue);\n else\n result.Append(String.Format(\",{0}\", curr.stringValue));\n curr = curr.nextNode;\n }\n\n return result.ToString();\n }\n}\n</code></pre>\n\n<p>As you see, I used his <code>Node</code> verbatim, and added the <code>lastNode</code> like he recommended. Most importantly, I added <code>Exists</code>, which is scoped as private, and put in the <code>ToString</code> as well.</p>\n\n<p>Some important notes:</p>\n\n<ul>\n<li><p>I added the <code>override</code> keyword to <code>ToString</code>. Without doing so, you should get a compiler warning saying you're hiding object.ToString(). Heed these kinds of warnings, regardless of language! My rule of thumb is to eliminate most, if not all, warnings.</p></li>\n<li><p><code>ToString</code> uses a <code>StringBuilder</code> as well as <code>String.Format</code>. I did this because <code>String</code> is immutable, and doing assignments to <code>String</code> essentially destroys the <code>String</code> and remakes it - just like the <code>String[] arr</code> explanation above.</p></li>\n<li><p><code>Add</code> returns nothing. Typically, <code>setter</code>-type functions don't return a value. If they do, it's almost always a boolean which states whether the operation was a success or not.</p></li>\n<li><p><code>Exists</code> guarantees uniqueness. It is case sensitive, so elements <code>\"XYZ\"</code> and <code>\"xyz\"</code> can exist at the same time. Making new functions that aren't specified in the question can be beneficial: it shows the interviewer that you can break new functionality out into a separate method, which makes the code easier to read and maintain. It also shows you can scope new functions properly. The outside world, according to the problem, doesn't use <code>Exists</code>, so there's no reason to make it public or protected. This is a very minor detail, but sometimes it's the little things which make the biggest difference.</p></li>\n<li><p><code>Add</code> protects against adding <code>null</code> values, but it does not protect against adding the empty string: <code>\"\"</code>, since the spec didn't cover whether to ignore that or not.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:58:25.017",
"Id": "80432",
"Score": "0",
"body": "+1 but unfortunately that implementation of `Exists` is expensive i.e. O(n) instead of O(1)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:40:14.233",
"Id": "80445",
"Score": "0",
"body": "@ChrisW That's true, but without using some form of well-balanced tree structure you're essentially choosing which operations are O(n) and which are O(1). For an interview question, I don't think I would start with that kind of answer. It takes longer, and it's a good talking point if they proceed further with interviewing. Ie, \"How would you improve this?\" \"I would ....\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:08:47.953",
"Id": "80559",
"Score": "0",
"body": "If the type was really meant to be a set, why would they call it `ListOfStrings` and not `SetOfStrings`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:01:48.107",
"Id": "80586",
"Score": "0",
"body": "@svick Well, the two aren't mutually exclusive. You could have a vector set, a queue set, a circular buffer set, etc."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:07:30.493",
"Id": "46089",
"ParentId": "46017",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T07:45:11.743",
"Id": "46017",
"Score": "12",
"Tags": [
"c#",
"interview-questions"
],
"Title": "ToString() and AddString() method without using .Net Collections"
} | 46017 |
<p>Recursive version. The only interesting function:</p>
<pre><code> List& List::reverse()
{
if (empty())
{ return *this;
}
int val = head();
//
// The fun bit.
// See if you can figure this bit out.
return pop().reverse().append(val);
}
</code></pre>
<p>The rest:</p>
<pre><code>#include <iostream>
#include <memory>
struct List
{
struct Node
{
int val;
std::unique_ptr<Node> next;
Node(){}
Node(int v, Node* oldTail)
: val(v)
, next(nullptr)
{
oldTail->next.reset(this);
}
friend std::ostream& operator<<(std::ostream& s, Node const& data)
{
return s << data.val << " ";
}
};
Node sentinal;
Node* tail;
public:
List()
: tail(&sentinal)
{}
bool empty() const
{
return &sentinal == tail;
}
int& head()
{
// Pre-Condition not empty
return sentinal.next->val;
}
List& append(int val)
{
tail = new Node(val, tail);
return *this;
}
List& pop()
{
// Pre-Condition not empty
sentinal.next.reset(sentinal.next->next.release());
tail = sentinal.next.get() ? tail : &sentinal;
return *this;
}
List& reverse();
friend std::ostream& operator<<(std::ostream& s, List const& data)
{
for(Node* loop = data.sentinal.next.get(); loop != nullptr; loop=loop->next.get())
{ s << *loop;
}
return s << "\n";
}
};
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>See if you can figure this bit out.</p>\n</blockquote>\n\n<p>Is this meant to be a <a href=\"https://codegolf.stackexchange.com/\">Programming Puzzle</a>?</p>\n\n<p>You don't call <code>append</code> until after you finish calling <code>reverse</code>; <code>reverse</code> is recursive; so all the <code>append</code> calls will be called after all the <code>reverse</code> calls: and that explains why <code>reverse</code> will eventually terminate i.e. why the list will eventually be empty.</p>\n\n<p>From a code-review point of view:</p>\n\n<ol>\n<li>I fear that a recursive implementation might exceed your finite maximum stack size if the list is long.</li>\n<li>You're deleting and creating new Node objects; you might instead be able to do it in a way that reuses existing Node instances.</li>\n</ol>\n\n<p>Also, it should be spelled \"sentinel\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:00:34.190",
"Id": "80614",
"Score": "0",
"body": "Fixed everything but recursion. Because thats the bit that makes it \"fun\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:01:11.957",
"Id": "80615",
"Score": "0",
"body": "Not a puzzle. Valid code needs checking. Just fun code. Now the next time somebody posts a singly linked list implementation I have a reference to point them to. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T19:56:49.200",
"Id": "80642",
"Score": "2",
"body": "@LokiAstari: \"*Now the next time somebody posts a singly linked list implementation*\" Given the popularity of these implementations on this site, I hope you can keep up. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T20:04:57.497",
"Id": "80644",
"Score": "0",
"body": "@LokiAstari: Also, it appears that you've made some changes based on this answer (at least pertaining to the spelling). Please reverse those individual changes [as per site policy](http://meta.codereview.stackexchange.com/questions/1482/can-i-edit-my-own-question-to-include-suggested-changes-from-answers)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:45:33.400",
"Id": "46184",
"ParentId": "46019",
"Score": "5"
}
},
{
"body": "<p>Some minor things:</p>\n\n<ul>\n<li><p>You could just leave out <code>public</code> since you're only dealing with <code>struct</code>s. You could still maintain the following indentation to really keep it separate from the <code>Node</code> code.</p></li>\n<li><p>In C++11, you can now use <code>default</code> constructors if you still need your own:</p>\n\n<pre><code>Node() = default;\n</code></pre></li>\n<li><p>Consider making <code>List</code> a templated class if you'd like it to handle other types of values.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-03T22:40:14.140",
"Id": "58965",
"ParentId": "46019",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46184",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T07:49:46.297",
"Id": "46019",
"Score": "9",
"Tags": [
"c++",
"c++11",
"recursion",
"linked-list"
],
"Title": "Linked List reversal"
} | 46019 |
<p>I implemented K-Nearest Neighbours algorithm, but my experience using MATLAB is lacking. I need you to check the small portion of code and tell me what can be improved or modified. I hope it is a correct implementation of the algorithm.</p>
<pre><code>function test_data = knn(test_data, tr_data,k)
numoftestdata = size(test_data,1);
numoftrainingdata = size(tr_data,1);
for sample=1:numoftestdata
%Step 1: Computing euclidean distance for each testdata
R = repmat(test_data(sample,:),numoftrainingdata,1) ;
euclideandistance = (R(:,1) - tr_data(:,1)).^2;
%Step 2: compute k nearest neighbors and store them in an array
[dist position] = sort(euclideandistance,'ascend');
knearestneighbors=position(1:k);
knearestdistances=dist(1:k);
% Step 3 : Voting
for i=1:k
A(i) = tr_data(knearestneighbors(i),2);
end
M = mode(A);
if (M~=1)
test_data(sample,2) = mode(A);
else
test_data(sample,2) = tr_data(knearestneighbors(1),2);
end
end
</code></pre>
<p>To test it you can use : </p>
<ul>
<li>test_data = [6,0; 2,0; 5,0]</li>
<li>tr_data = [1,1;0,2;3,2; 4,4; 5,3]</li>
</ul>
| [] | [
{
"body": "<ul>\n<li>Use consistent indentation.</li>\n<li>You switch from extremely verbose all lower case variable names like <code>numoftrainingdata</code> to single letter capitalized variable names like <code>A</code>. Make your variable names descriptive and no longer than necessary, and be consistent.</li>\n<li>Use consistent white space between operators.</li>\n<li><p><code>knn()</code> doesn't need the second column of <code>test_data</code>, and the calling function doesn't need the first column of <code>test_data</code>.</p>\n\n<p>Rather than calling the function like this:</p>\n\n<pre><code>test_data = knn(test_data,tr_data,k);\n</code></pre>\n\n<p>Call it like this:</p>\n\n<pre><code>test_data(:,2) = knn(test_data(1,:),tr_data,k);\n</code></pre></li>\n<li><p>Do you want to handle certain error conditions like <code>0 >= k</code> or <code>k > size(tr_data,1)</code>?</p></li>\n<li>Rather than squaring the distance, you can use <code>abs()</code>.</li>\n<li>Remove the ascend parameter from <code>sort()</code>, that is the default mode.</li>\n<li><code>knearestdistances</code> is unused.</li>\n<li>You call <code>mode()</code> a second time rather than using <code>M</code>.</li>\n</ul>\n\n<p>Simplify:</p>\n\n<pre><code>[dist position] = sort(euclideandistance,'ascend');\nknearestneighbors = position(1:k);\nknearestdistances = dist(1:k);\nfor i=1:k\n A(i) = tr_data(knearestneighbors(i),2);\nend\nM = mode(A);\nif (M~=1)\n test_data(sample,2) = mode(A);\nelse \n test_data(sample,2) = tr_data(knearestneighbors(1),2);\nend\n</code></pre>\n\n<p>to</p>\n\n<pre><code>[~,position] = sort(euclideandistance);\nA = tr_data(position(1:k),2);\nM = mode(A);\nif (M~=1)\n test_data(sample,2) = M;\nelse\n test_data(sample,2) = tr_data(position(1),2);\nend\n</code></pre>\n\n<p>After applying the above suggestions and vectorizing the function you could write it as:</p>\n\n<pre><code>function out_data = knn(test_data,tr_data,k)\n test_data_n = size(test_data,1);\n tr_data_n = size(tr_data,1);\n\n % absolute distance between all test and training data\n dist = abs(repmat(test_data,1,tr_data_n) - repmat(tr_data(:,1)',test_data_n,1));\n\n % indicies of nearest neighbors\n [~,nearest] = sort(dist,2);\n % k nearest\n nearest = nearest(:,1:k);\n\n % mode of k nearest\n val = reshape(tr_data(nearest,2),[],k);\n out_data = mode(val,2);\n % if mode is 1, output nearest instead\n out_data(out_data==1) = val(out_data==1,1);\nend\n</code></pre>\n\n<h2>Edit</h2>\n\n<p>Regarding correctness, i'm not sure why you check to see if the mode is 1. There is nothing unique about a mode of 1 in general.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:43:08.040",
"Id": "80539",
"Score": "0",
"body": "I made a mistake, If the frequency of the mode is One , that means all values of `val` are unique, we choose the nearest."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:48:53.807",
"Id": "80540",
"Score": "0",
"body": "` [M,F] = mode(knntrdata);\n if (F~=1)\n test_data(sample,2) = M;\n else\n test_data(sample,2) = tr_data(position(1),2);\n end`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:10:06.083",
"Id": "80542",
"Score": "0",
"body": "is it necessary to vectorize the function ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:51:45.893",
"Id": "80655",
"Score": "1",
"body": "@ALJIMohamed Yes that code looks correct to check if all the values are unique. Vectorization is only necessary if your code is too verbose or slow. The only part of your code that needs to be vectorized is the assignment of `A`, because it is too verbose. I vectorized the rest as an example."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:49:12.570",
"Id": "46068",
"ParentId": "46027",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46068",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T10:23:54.483",
"Id": "46027",
"Score": "4",
"Tags": [
"algorithm",
"beginner",
"matlab",
"clustering"
],
"Title": "K-nearest neighbours in MATLAB"
} | 46027 |
<p>I just read the Lib/argparse.py code (class FileType) on <a href="http://hg.python.org/cpython/file/default/Lib/argparse.py" rel="noreferrer">http://hg.python.org/cpython/file/default/Lib/argparse.py</a>. File objects are opened without the with statement. For safe file opening/closing, should I instead encapsulate my argparse.ArgumentParser() in a contextlib stack like below? I feel very stupid for asking a question like this, but I am very much in doubt about the proper procedure.</p>
<pre><code>import argparse
import contextlib
import gzip
import os
import fileinput
import sys
def main():
with contextlib.ExitStack() as stack:
input = argparse(stack)
process_arguments(input)
def argparse(stack):
parser = argparse.ArgumentParser()
parser.add_argument('--input', default=[sys.stdin], nargs='+')
d_args = vars(parser.parse_args())
if d_args['input'] != [sys.stdin]:
input = stack.enter_context(fileinput.FileInput(
files=d_args['input'], openhook=hook_compressed_text))
else:
input = stack.enter_context(sys.stdin)
return input
def hook_compressed_text(filename, mode):
ext = os.path.splitext(filename)[1]
if ext == '.gz':
f = gzip.open(filename, mode + 't')
else:
f = open(filename, mode)
return f
</code></pre>
<p>Here the class FileType from Lib/argparse.py:</p>
<pre><code>class FileType(object):
"""Factory for creating file object types
Instances of FileType are typically passed as type= arguments to the
ArgumentParser add_argument() method.
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the builtin open() function.
- encoding -- The file's encoding. Accepts the same values as the
builtin open() function.
- errors -- A string indicating how encoding and decoding errors are to
be handled. Accepts the same value as the builtin open() function.
"""
def __init__(self, mode='r', bufsize=-1, encoding=None, errors=None):
self._mode = mode
self._bufsize = bufsize
self._encoding = encoding
self._errors = errors
def __call__(self, string):
# the special argument "-" means sys.std{in,out}
if string == '-':
if 'r' in self._mode:
return _sys.stdin
elif 'w' in self._mode:
return _sys.stdout
else:
msg = _('argument "-" with mode %r') % self._mode
raise ValueError(msg)
# all other arguments are used as file names
try:
return open(string, self._mode, self._bufsize, self._encoding,
self._errors)
except OSError as e:
message = _("can't open '%s': %s")
raise ArgumentTypeError(message % (string, e))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:55:03.793",
"Id": "80506",
"Score": "2",
"body": "See the discussion in http://bugs.python.org/issue13824"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-14T08:05:04.813",
"Id": "87464",
"Score": "0",
"body": "Yes, 'FileType' was written as a scripting convenience, and example of a custom 'type'. It's not a model of proper file handling, especially in Python3."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-14T22:07:50.237",
"Id": "87608",
"Score": "2",
"body": "@tommy.carstensen \"I feel very stupid for asking a question like this.\" I suspect that might be a bit of imposture syndrome rearing its head. You definitely seem like you know what you're doing, and I very much doubt it's a stupid question."
}
] | [
{
"body": "<p>I've expanded on your example, and explored some alternatives.</p>\n\n<p>Observations:</p>\n\n<ul>\n<li><p>your <code>def argparse</code> shadowed the module; I changed its name.</p></li>\n<li><p>using <code>FileType</code> to process the argparse input results in <code>unclosed file</code> warnings. It opens the files, but does not close them. So for multiple files, it is not right tool.</p></li>\n<li><p><code>simpler</code> just runs the <code>FileInput</code> without a context. <code>FileInput</code> handles <code>stdin</code> itself. It does not close <code>stdin</code> when done. It closes other files, even when processing is interrupted.</p></li>\n<li><p><code>main</code> with the context, closes <code>stdin</code>.</p></li>\n<li><p>I wrote a <code>process_arguments</code> with a break to test whether files are closed. <code>FileInput</code> properly closes the files, with or without the context.</p></li>\n<li><p><code>FileInput</code> also can read <code>sys.argv</code>, so you don't actually need <code>argparse</code> in this simple case. See <code>simplest</code>.</p></li>\n</ul>\n\n<p>The script:</p>\n\n<pre><code>import argparse\nimport contextlib\nimport fileinput\nimport sys\n\nfiles = set()\n\ndef filetype():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', nargs='*',type=argparse.FileType('r'))\n args = parser.parse_args()\n print(args)\n # gives ResourceWarning: unclosed file\n\ndef simpler():\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', nargs='*')\n args = parser.parse_args()\n input = fileinput.FileInput(\n files=args.input)\n process_arguments(input)\n\ndef simplest():\n # uses sys.argv[1:]\n process_arguments(fileinput.input()) \n\ndef main():\n with contextlib.ExitStack() as stack:\n input = myparse(stack)\n process_arguments(input)\n\ndef myparse(stack):\n # change name so as to not shadow the module\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', default=[sys.stdin], nargs='+')\n d_args = vars(parser.parse_args())\n print('d_args',d_args)\n if d_args['input'] != [sys.stdin]:\n input = stack.enter_context(fileinput.FileInput(\n files=d_args['input']))\n else:\n input = stack.enter_context(sys.stdin)\n return input\n\ndef process_arguments(input):\n try:\n print(input, input._files)\n except AttributeError as e:\n # error if input is not a FileInput\n print(e)\n return\n for l in input:\n print(input.filename(), input.fileno(), input.lineno(), input.filelineno())\n if not input.isstdin():\n files.add(input._file)\n if input.lineno()>15:\n break\n\nif __name__==\"__main__\":\n # simplest()\n simpler()\n # main()\n if files:\n print([(f.name, f.closed) for f in files])\n print('is stdin closed?', sys.stdin.closed)\n</code></pre>\n\n<p>This function is a simpler example (without <code>fileinput</code>) of processing a list of files with a proper context. I learned about this use of <code>stdin.fileno()</code> from another <code>argparse</code> bug issue, <a href=\"http://bugs.python.org/issue14156\" rel=\"nofollow\">http://bugs.python.org/issue14156</a>. </p>\n\n<pre><code>def other():\n # example with simple 'with open...'\n parser = argparse.ArgumentParser()\n parser.add_argument('--input', nargs='*', default=[sys.stdin])\n args = parser.parse_args()\n for file in args.input:\n if file is sys.stdin:\n # open(fileno) does not close the underlying file\n file = file.fileno()\n with open(file) as f:\n lines = f.readlines()\n print(f.name, f.fileno(), len(lines))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-14T21:50:26.823",
"Id": "49768",
"ParentId": "46031",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "49768",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:22:09.617",
"Id": "46031",
"Score": "7",
"Tags": [
"python",
"python-3.x"
],
"Title": "Should I put python3 argparse filetype objects in a contextlib stack?"
} | 46031 |
<p>I'm coding a little class hierarchy printing tool for easy show hierarchies of java classes.</p>
<p>This is my current code:</p>
<pre class="lang-java prettyprint-override"><code>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;
import javax.swing.JDialog;
import jdk.nashorn.internal.runtime.PropertyMap; // since Java 8, just for testing
import com.sun.javafx.collections.TrackableObservableList;
public class PrintClassHierarchy {
private static final String PADDING = " ";
private static final String PADDING_WITH_COLUMN = " | ";
private static final String PADDING_WITH_ENTRY = " |--- ";
private static final String BASE_CLASS = Object.class.getName();
private TreeMap<String, List<String>> entries;
private boolean[] moreToCome;
public static void main(final String[] args) {
new PrintClassHierarchy().printHierarchy(
PrintStream.class,
FileOutputStream.class,
FileInputStream.class,
TrackableObservableList.class,
PropertyMap.class,
JDialog.class
);
}
public void printHierarchy(final Class<?>... clazzes) {
// clean values
entries = new TreeMap<>();
moreToCome = new boolean[99];
// get all entries of tree
traverseClasses(clazzes);
// print collected entries as ASCII tree
printHierarchy(BASE_CLASS, 0);
}
private void printHierarchy(final String node, final int level) {
for (int i = 1; i < level; i++) {
System.out.print(moreToCome[i - 1] ? PADDING_WITH_COLUMN : PADDING);
}
if (level > 0) {
System.out.print(PADDING_WITH_ENTRY);
}
System.out.println(node);
if (entries.containsKey(node)) {
final List<String> list = entries.get(node);
for (int i = 0; i < list.size(); i++) {
moreToCome[level] = (i < list.size() - 1);
printHierarchy(list.get(i), level + 1);
}
}
}
private void traverseClasses(final Class<?>... clazzes) {
Arrays.asList(clazzes).forEach(c -> traverseClasses(c, 0));
}
private void traverseClasses(final Class<?> clazz, final int level) {
final Class<?> superClazz = clazz.getSuperclass();
if (superClazz == null) {
return;
}
final String name = clazz.getName();
final String superName = superClazz.getName();
if (entries.containsKey(superName)) {
final List<String> list = entries.get(superName);
if (!list.contains(name)) {
list.add(name);
Collections.sort(list); // SortedList
}
} else {
entries.put(superName, new ArrayList<String>(Arrays.asList(name)));
}
traverseClasses(superClazz, level + 1);
}
}
</code></pre>
<p>This prints out:</p>
<pre>
java.lang.Object
|--- java.awt.Component
| |--- java.awt.Container
| |--- java.awt.Window
| |--- java.awt.Dialog
| |--- javax.swing.JDialog
|--- java.io.InputStream
| |--- java.io.FileInputStream
|--- java.io.OutputStream
| |--- java.io.FileOutputStream
| |--- java.io.FilterOutputStream
| |--- java.io.PrintStream
|--- java.util.AbstractCollection
| |--- java.util.AbstractList
| |--- javafx.collections.ObservableListBase
| |--- javafx.collections.ModifiableObservableListBase
| |--- com.sun.javafx.collections.ObservableListWrapper
| |--- com.sun.javafx.collections.TrackableObservableList
|--- jdk.nashorn.internal.runtime.PropertyMap
</pre>
<p>This output is already valid. I want to know, if this is a good approach to do the task, or if there is another (better) way to do this?</p>
<p>I'm not sure, if the <code>entries</code> and <code>moreToCome</code> "global" variables are the way to go.</p>
<p>Or if you have general improvements, please let me know!</p>
<hr>
<p><strong>Edit 1:</strong></p>
<p>I reworked the code to find out the maximum level in hierarchy to discover how big the boolean array has to be. Also I reworked the method calls and put the <code>traverseClasses</code> into the constructor as recommended. Furthermore I renamed some variables to more descriptive names and added some comments. <code>moreToCome</code> is now <code>moreClassesInHierarchy</code>.</p>
<p>Second approach:</p>
<pre class="lang-java prettyprint-override"><code>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;
import javax.swing.JDialog;
import jdk.nashorn.internal.runtime.PropertyMap; // since Java 8, just for testing
import com.sun.javafx.collections.TrackableObservableList;
public class PrintClassHierarchy {
private static final String PADDING = " ";
private static final String PADDING_WITH_COLUMN = " | ";
private static final String PADDING_WITH_ENTRY = " |--- ";
private static final String BASE_CLASS = Object.class.getName();
private final TreeMap<String, List<String>> subClazzEntries;
private final boolean[] moreClassesInHierarchy;
private int maxLevel = 0;
public static void main(final String[] args) {
new PrintClassHierarchy(
PrintStream.class,
FileOutputStream.class,
FileInputStream.class,
TrackableObservableList.class,
PropertyMap.class,
JDialog.class
).printHierarchy();
}
public PrintClassHierarchy(final Class<?>... clazzes) {
subClazzEntries = new TreeMap<>();
// get all entries of tree
traverseClasses(clazzes);
// initialize array with size of maximum class hierarchy level
moreClassesInHierarchy = new boolean[maxLevel];
}
public void printHierarchy() {
// print collected entries as ASCII tree
printHierarchy(BASE_CLASS, 0);
}
private void printHierarchy(final String clazzName, final int level) {
for (int i = 1; i < level; i++) {
// The flag moreToCome holds an identifier, if there is another class
// on the specific value, that comes beneath the current class.
// So print either '|' or ' '.
System.out.print(moreClassesInHierarchy[i - 1] ? PADDING_WITH_COLUMN : PADDING);
}
if (level > 0) {
System.out.print(PADDING_WITH_ENTRY);
}
System.out.println(clazzName);
if (subClazzEntries.containsKey(clazzName)) {
final List<String> list = subClazzEntries.get(clazzName);
for (int i = 0; i < list.size(); i++) {
// if there is another class that comes beneath the next class,
// flag this level
moreClassesInHierarchy[level] = (i < list.size() - 1);
printHierarchy(list.get(i), level + 1);
}
}
}
private void traverseClasses(final Class<?>... clazzes) {
// do the traverseClasses on each provided class (possible since Java 8)
Arrays.asList(clazzes).forEach(c -> traverseClasses(c, 0));
}
private void traverseClasses(final Class<?> clazz, final int level) {
final Class<?> superClazz = clazz.getSuperclass();
if (level > maxLevel) {
// discover maximum level
maxLevel = level;
}
if (superClazz == null) {
// we arrived java.lang.Object
return;
}
final String name = clazz.getName();
final String superName = superClazz.getName();
if (subClazzEntries.containsKey(superName)) {
final List<String> list = subClazzEntries.get(superName);
if (!list.contains(name)) {
list.add(name);
Collections.sort(list); // SortedList
}
} else {
subClazzEntries.put(superName, new ArrayList<String>(Arrays.asList(name)));
}
traverseClasses(superClazz, level + 1);
}
}
</code></pre>
<hr>
<p><strong>Edit 2:</strong></p>
<p>Now I implemented the <code>Stack</code> solution from Uri Agassi in my code.<br>
This is much more cleaner, since I don't have to care about the Stack size and the current level. It just fits the requirement!<br>
Furthermore I got rid of the <code>TreeMap</code> since I don't really need a sorted map. Therefore <code>Map</code> (<code>HashMap</code>) remains.</p>
<p>Third approach:</p>
<pre><code>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import javax.swing.JDialog;
import jdk.nashorn.internal.runtime.PropertyMap; // since Java 8, just for testing
import com.sun.javafx.collections.TrackableObservableList;
public class PrintClassHierarchy {
private static final String PADDING = " ";
private static final String PADDING_WITH_COLUMN = " | ";
private static final String PADDING_WITH_ENTRY = " |--- ";
private static final String BASE_CLASS = Object.class.getName();
private final Map<String, List<String>> subClazzEntries = new HashMap<>();
public static void main(final String[] args) {
new PrintClassHierarchy(
PrintStream.class,
FileOutputStream.class,
FileInputStream.class,
TrackableObservableList.class,
PropertyMap.class,
JDialog.class
).printHierarchy();
}
public PrintClassHierarchy(final Class<?>... clazzes) {
// get all entries of tree
traverseClasses(clazzes);
}
public void printHierarchy() {
// print collected entries as ASCII tree
printHierarchy(BASE_CLASS, new Stack<Boolean>());
}
private void printHierarchy(final String clazzName, final Stack<Boolean> moreClassesInHierarchy) {
if (!moreClassesInHierarchy.empty()) {
for (final Boolean hasColumn : moreClassesInHierarchy.subList(0, moreClassesInHierarchy.size() - 1)) {
System.out.print(hasColumn.booleanValue() ? PADDING_WITH_COLUMN : PADDING);
}
}
if (!moreClassesInHierarchy.empty()) {
System.out.print(PADDING_WITH_ENTRY);
}
System.out.println(clazzName);
if (subClazzEntries.containsKey(clazzName)) {
final List<String> list = subClazzEntries.get(clazzName);
for (int i = 0; i < list.size(); i++) {
// if there is another class that comes beneath the next class, flag this level
moreClassesInHierarchy.push(new Boolean(i < list.size() - 1));
printHierarchy(list.get(i), moreClassesInHierarchy);
moreClassesInHierarchy.removeElementAt(moreClassesInHierarchy.size() - 1);
}
}
}
private void traverseClasses(final Class<?>... clazzes) {
// do the traverseClasses on each provided class (possible since Java 8)
Arrays.asList(clazzes).forEach(c -> traverseClasses(c, 0));
}
private void traverseClasses(final Class<?> clazz, final int level) {
final Class<?> superClazz = clazz.getSuperclass();
if (superClazz == null) {
// we arrived java.lang.Object
return;
}
final String name = clazz.getName();
final String superName = superClazz.getName();
if (subClazzEntries.containsKey(superName)) {
final List<String> list = subClazzEntries.get(superName);
if (!list.contains(name)) {
list.add(name);
Collections.sort(list); // SortedList
}
} else {
subClazzEntries.put(superName, new ArrayList<String>(Arrays.asList(name)));
}
traverseClasses(superClazz, level + 1);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:48:46.767",
"Id": "80326",
"Score": "0",
"body": "`entries` and `moreToCome` are private instance variable which is looking fine to me since they look as being use in every method of the class. If they were global that would be a really big problem ;) ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:11:19.517",
"Id": "80337",
"Score": "0",
"body": "That's right. It's not **that** global variable what you think. But on the other way I thought about passing these variables as parameters to the methods I have."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:17:24.533",
"Id": "80339",
"Score": "0",
"body": "I would not add it as a parameter since it would add complexity to the method calling. There is nothing wrong with having private class variable as long as their scope is good (which look like it)."
}
] | [
{
"body": "<p><strong>Mutators vs. Selectors</strong><br>\nThe method <code>printHierarchy(final Class<?>...)</code> both populates the instance, and prints the result. It would be a lot more predictable if it would be responsible only for one or the other. Its name implies that it only prints, so I would suggest to move the population of the <code>PrintClassHierarchy</code> to its constructor, leaving only the printing to the <code>printHierarchy</code> method:</p>\n\n<pre><code>public static void main(final String[] args) {\n new PrintClassHierarchy().printHierarchy(\n PrintStream.class,\n FileOutputStream.class,\n FileInputStream.class,\n TrackableObservableList.class,\n PropertyMap.class,\n JDialog.class\n ).printHierarchy();\n}\n</code></pre>\n\n<p><strong>More to come...?</strong><br>\nI don't have a concrete suggestion on how you <em>should</em> implement it, but the <code>moreToCome</code> solution you have is a little dodgy:</p>\n\n<ul>\n<li>It is not apparent how it works</li>\n<li>You initialize it in an arbitrary manner (<code>new boolean[99]</code>) - always a bad sign...</li>\n<li>Its usage looks very brittle, and any failure might be very hard to debug</li>\n</ul>\n\n<hr>\n\n<p><strong>More to come - part 2 (the second coming?)</strong><br>\nAfter you've refactored the mutator out of your selector, it is obvious that the only state change while printing your classes is the <code>moreClassesInHierarchy</code> (nee <code>moreToCome</code>) member. <strong>But</strong> a selector class <em>should not</em> change the state of the object!<br>\nThe design which emerges from this is that <code>moreToCome</code> should probably be a <strong>parameter</strong> which changes before and after the recursion, probably a <code>Stack<boolean></code>:</p>\n\n<pre><code>for (int i = 0; i < list.size(); i++) {\n // if there is another class that comes beneath the next class,\n // flag this level\n moreClassesInHierarchy.push(i < list.size() - 1);\n\n printHierarchy(list.get(i), moreClassesInHierarchy);\n\n moreClassesInHierarchy.pop();\n</code></pre>\n\n<p>}</p>\n\n<p>Note that in this solution, I've gotten rid of <code>level</code>, since is hidden in <code>moreClassesInHierarchy.size()</code>...</p>\n\n<p>So now the method becomes:</p>\n\n<pre><code>public void printHierarchy() {\n // print collected entries as ASCII tree\n printHierarchy(BASE_CLASS, new Stack<boolean>());\n}\n\nprivate void printHierarchy(final String clazzName, final Stack<boolean> moreClassesInHierarchy) {\n for (boolean hasColumn : moreClassesInHierarchy) {\n System.out.print(hasColumn ? PADDING_WITH_COLUMN : PADDING);\n }\n\n if (!moreClassesInHierarchy.empty()) {\n System.out.print(PADDING_WITH_ENTRY);\n }\n // ...cont\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:07:28.213",
"Id": "80336",
"Score": "0",
"body": "Thank you for your response! You're right. The `moreToCome` thingy is not well explained. What it does: it should tell the next line, if there will be another class on the same level beneath it for printing the column `|` on each level. Unfortunately, I can't explain it better... Also it's true, that initializing the array with a fixed length is a bad sign. I'm not sure how to replace it. Perhaps with a `Map<Integer, Boolean>` or just a `List<Boolean>`? If you understand what it should do, what's your preferred way of solving this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:36:30.260",
"Id": "80349",
"Score": "0",
"body": "Now I let discover the maximum level of hierarchy, so the array can be initialized with the fewest amount of fields."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:10:54.863",
"Id": "80373",
"Score": "0",
"body": "@bobbel - I've updated the answer according to your changes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:03:39.347",
"Id": "80418",
"Score": "1",
"body": "Thanks again for the great idea of using a `Stack`! I reworked my class again. Only in your for-each loop, I had to use a sub list of all elements except the last one. Otherwise it printed out a weird result."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:44:43.853",
"Id": "46044",
"ParentId": "46032",
"Score": "4"
}
},
{
"body": "<p>Just two quick points (for the original code):</p>\n\n<ol>\n<li><p>You could save a lot of logic with a <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/TreeMultimap.html\"><code>TreeMultimap</code></a> (from <a href=\"https://code.google.com/p/guava-libraries/\">Google Guava</a>):</p>\n\n<pre><code>private final TreeMultimap<String, String> entries = TreeMultimap.create();\n</code></pre>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code>if (entries.containsKey(node)) {\n final List<String> list = entries.get(node);\n\n for (int i = 0; i < list.size(); i++) {\n moreToCome[level] = (i < list.size() - 1);\n printHierarchy(list.get(i), level + 1);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>could be replaced with</p>\n\n<pre><code>for (String e: list) {\n moreToCome[level] = (i < list.size() - 1);\n printHierarchy(e, level + 1);\n i++;\n}\n</code></pre>\n\n<p>and this:</p>\n\n<blockquote>\n<pre><code>if (entries.containsKey(superName)) {\n final List<String> list = entries.get(superName);\n\n if (!list.contains(name)) {\n list.add(name);\n Collections.sort(list); // SortedList\n }\n} else {\n entries.put(superName, new ArrayList<String>(Arrays.asList(name)));\n}\n</code></pre>\n</blockquote>\n\n<p>could be replaced with</p>\n\n<pre><code>entries.put(superName, name);\n</code></pre>\n\n<p>(See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><p>I'd try to add a boolean parameter (<code>lastElementInThisLevel</code> or something similar) to the <code>printHierarchy</code> method to remove the <code>moreToCome</code> array and clean this loop:</p>\n\n<pre><code>int i = 0;\nfor (String e: list) {\n moreToCome[level] = (i < list.size() - 1);\n printHierarchy(e, level + 1);\n i++;\n}\n</code></pre>\n\n<p>(Use more descriptive names than <code>list</code> and <code>e</code>.)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:53:41.447",
"Id": "80356",
"Score": "0",
"body": "Thank you for your recommendations! I'm not using Guava yet, because I like to implement things without external libraries. My first thought about using external libraries is, that they will blow up the size of your application. For example, my program will be a few KB. With the library it will be over 2 MB! Finally, the library is perfect for doing some sub tasks of my problem. Thank you very much for showing this up!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:36:22.020",
"Id": "46056",
"ParentId": "46032",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:22:10.520",
"Id": "46032",
"Score": "8",
"Tags": [
"java",
"classes",
"tree",
"inheritance"
],
"Title": "Class for printing class hierarchy as text"
} | 46032 |
<pre><code>public class SudokuChecker{
static int[][] sMatrix={
{5,3,4,6,7,8,9,1,2},
{6,7,2,1,9,5,3,4,8},
{1,9,8,3,4,2,5,6,7},
{8,5,9,7,6,1,4,2,3},
{4,2,6,8,5,3,7,9,1},
{7,1,3,9,2,4,8,5,6},
{9,6,1,5,3,7,2,8,4},
{2,8,7,4,1,9,6,3,5},
{3,4,5,2,8,6,1,7,9}
};
static int rSum=0;
static int cSum=0;
static int[] rSumArray=new int[9];
static int[] cSumArray=new int[9];
static int[] boxSumArray=new int[9];
static boolean checkArrayStatus(int[] rSumArray,int[] cSumArray,int[] boxSumArray)
{
int i=0;
boolean sudukoStatus=true;
while(i<9){
if(rSumArray[i]!=45&&cSumArray[i]!=45&&rSumArray[i]!=45)
{
sudukoStatus=false;
break;
}
i++;
}
return sudukoStatus;
}
public static void main(String[] args) {
for(int i=0 ; i<sMatrix.length ; i++){
for(int j=0 ; j<sMatrix.length ; j++){
rSum+=sMatrix[i][j];
cSum+=sMatrix[j][i];
}
rSumArray[i]=rSum;
cSumArray[i]=cSum;
rSum=0;
cSum=0;
}
for(int i=0 ; i< sMatrix.length ; i++){
for(int j=0 ; j<sMatrix.length ; j++){
if(i<=2&&j<=2)
{
boxSumArray[0]+=sMatrix[i][j];
}
if(i<=2&&(j>=3&&j<=5))
{
boxSumArray[1]+=sMatrix[i][j];
}
if(i<=2&&(j>=6&&j<=8))
{
boxSumArray[2]+=sMatrix[i][j];
}
if((i>=3&&i<=5)&&(j<=2))
{
boxSumArray[3]+=sMatrix[i][j];
}
if((i>=3&&i<=5)&&(j>=3&&j<=5))
{
boxSumArray[4]+=sMatrix[i][j];
}
if((i>=3&&i<=5)&&(j>=6&&j<=8))
{
boxSumArray[5]+=sMatrix[i][j];
}
if((i>=6)&&(j<=2))
{
boxSumArray[6]+=sMatrix[i][j];
}
if((i>=6)&&(j>=3&&j<=5))
{
boxSumArray[7]+=sMatrix[i][j];
}
if((i>=6)&&(j>=6))
{
boxSumArray[8]+=sMatrix[i][j];
}
}
}
if(checkArrayStatus(rSumArray,cSumArray,boxSumArray))
{
System.out.println("The matrix is sudoku compliant");
}
else
{
System.out.println("The matrix is not sudoku compliant");
}
}
}
</code></pre>
<p>This a program which verifies if a 2D matrix is a Sudoku or not. The sum of every row, column and 3x3 matrices have to be 45. Please review the code and provide feedback on best practices and code optimization. </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:08:24.707",
"Id": "80311",
"Score": "3",
"body": "Hint why checking for `sum == 45` is not sufficient: `(1+9)+(2+8)+(3+7)+(4+6)+5` is OK, but `(1+9)+(1+9)+(1+9)+(1+9)+5` also fulfills that constraint!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:35:55.487",
"Id": "80348",
"Score": "0",
"body": "@amon For lack of ability to think straight at the moment, is it possible to simultaneously fulfill the 45 sum on all rows and columns and mini-grids using numbers other than 1-9 once each?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:01:49.900",
"Id": "80357",
"Score": "3",
"body": "Fill it all with 5. It sums 45 everywhere, but it is obviously not correct."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:35:24.177",
"Id": "80396",
"Score": "0",
"body": "@amon...Your right...i didn't think of this...Though i wrote another program which checks for unique elements rowwise,colomnwise and in each 3x3 box......Can i check for unique numbers(1 to 9) rowwise and columnwise and say its a sudoku?Will there be a situation in which the sudoku passes for unique rowwise and columwise and not boxwise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:38:33.890",
"Id": "80400",
"Score": "0",
"body": "@user326744 conceerning that, Edward had concerns... under my post you can see a sudoku that qualifies..."
}
] | [
{
"body": "<p>You have waaaay too many sums you are checking. <a href=\"http://en.wikipedia.org/wiki/Keep_it_simple_stupid\">KISS-Principle --> Keep it Simple {and} Stupid</a>:</p>\n\n<pre><code>private boolean checkSudokuStatus(int[][] grid) {\n for (int i = 0; i < 9; i++) {\n\n int[] row = new int[9];\n int[] square = new int[9];\n int[] column = grid[i].clone();\n\n for (int j = 0; j < 9; j ++) {\n row[j] = grid[j][i];\n square[j] = grid[(i / 3) * 3 + j / 3][i * 3 % 9 + j % 3];\n }\n if (!(validate(column) && validate(row) && validate(square)))\n return false;\n }\n return true;\n}\n\nprivate boolean validate(int[] check) {\n int i = 0;\n Arrays.sort(check);\n for (int number : check) {\n if (number != ++i)\n return false;\n }\n return true;\n}\n</code></pre>\n\n<h3>Short Explanation:</h3>\n\n<ol>\n<li><p>A Sudoku has three elements to validate. Each has to contain the single digit numbers from 1 to 9 exactly once. </p></li>\n<li><p>These three elements are: each single row, each single column, the 9 3x3 sqares.<br>\nThese elements are exactly mapped by the three variables you see in the for-loop.</p></li>\n<li><p>Each of these elements is given to a validate function to verify, that it contains the numbers only once. Originally this was a golfed solution, so the square calculation is heavily algorithmic.</p></li>\n<li><p>The validate function is quite simple. It initializes a counter to 0, and then walks the sorted \"validated element\" through, while always incrementing by 1. this gives the numbers from 1 to 9. In fact it is just a shortened for-loop, written a little different it's:</p></li>\n</ol>\n\n<p>this one</p>\n\n<pre><code>for(int i = 1; i <= 9; i++){\n if(check[i-1] != i){\n return false;\n }\n}\nreturn true;\n</code></pre>\n\n<h3>Longer Explanation</h3>\n\n<p>How I got to the algorithmic generation for the squares:</p>\n\n<pre><code>[(i / 3) * 3 + j / 3] [i * 3 % 9 + j % 3]\n</code></pre>\n\n<hr>\n\n<pre><code>(i / 3) * 3 + j / 3\n</code></pre>\n\n<p>This part is relatively simple. It gives the correct \"column\" by help of implicit integer conversion: The first part of the equation is a little difficult: </p>\n\n<blockquote>\n <p>\\$ (i / 3) \\$<br>\n \\$ {0,1,2} \\mapsto 0 \\$<br>\n \\$ {3,4,5} \\mapsto 1 \\$<br>\n \\$ {6,7,8} \\mapsto 2 \\$ </p>\n</blockquote>\n\n<p>take it <code>* 3</code> and you got the sqare you want to get in to. then if we now iterate row-wise, we need to jump to the next column every 3 Elements. That's done with <code>j / 3</code>.</p>\n\n<p>Now for the difficult one: </p>\n\n<pre><code> i * 3 % 9 + j % 3\n</code></pre>\n\n<blockquote>\n <p>\\$ (i * 3 \\% 9) \\$<br>\n \\$ {0,3,6} \\mapsto 0 \\$<br>\n \\$ {1,4,7} \\mapsto 3 \\$<br>\n \\$ {2,5,8} \\mapsto 6 \\$</p>\n</blockquote>\n\n<p>This one is for \"jumping\" the sqares vertically. Then we just have to iterate 0, 1, 2. This is accomplished by running the <code>% 3</code> operation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:06:15.697",
"Id": "80309",
"Score": "1",
"body": "Your variables `iterator` and `columnIterator` are very weird and hide their actual meaning – either use `i, j`, `row, column`, or `row, col`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:08:24.217",
"Id": "80310",
"Score": "0",
"body": "@amon row an column are taken, also I don't understand how you mean \"hide their actual meaning\", but I edited either way ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:12:06.283",
"Id": "80314",
"Score": "0",
"body": "(There are no `java.util.Iterator`s here, but you have integer indices)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:12:50.860",
"Id": "80315",
"Score": "0",
"body": "@amon I fully ignored that. not using Iterator much, thanks for the hint ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:53:55.693",
"Id": "80329",
"Score": "0",
"body": "@Edward sure: { 1, 2, 3, 4, 5, 6, 7, 8, 9 },\n { 9, 1, 2, 3, 4, 5, 6, 7, 8 },\n { 8, 9, 1, 2, 3, 4, 5, 6, 7 },\n { 7, 8, 9, 1, 2, 3, 4, 5, 6 },\n { 6, 7, 8, 9, 1, 2, 3, 4, 5 },\n { 5, 6, 7, 8, 9, 1, 2, 3, 4 },\n { 4, 5, 6, 7, 8, 9, 1, 2, 3 },\n { 3, 4, 5, 6, 7, 8, 9, 1, 2 },\n { 2, 3, 4, 5, 6, 7, 8, 9, 1 } \\*this really is missing code-formatting*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:30:01.633",
"Id": "80393",
"Score": "0",
"body": "@vogel.....Am still new to java but doesnt this fill up elements from the grid array columnwise and not rowwise? row[j] = grid[j][i];"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:30:39.570",
"Id": "80394",
"Score": "0",
"body": "@vogel how did you arrive at that square[j] = grid[(i / 3) * 3 + j / 3][i * 3 % 9 + j % 3];"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:37:08.447",
"Id": "80398",
"Score": "0",
"body": "@user concerning the first: that depends on which iterator you see as row, and which you see as column... in fact you are correct that it takes the \"columns\". Concerning the second, you might want to take a look at the answer from UriAgassi. It's about the same, just inverted...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:31:54.997",
"Id": "80512",
"Score": "0",
"body": "@user3296744 I added some explanation"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:01:30.107",
"Id": "46037",
"ParentId": "46033",
"Score": "27"
}
},
{
"body": "<p><strong>Mind your scope</strong><br>\nYou have a lot of <code>static</code> members (<code>cSum</code>, <code>rSum</code>, etc.), which you calculate in one method, and the pass them as arguments to other methods. This means that they should be members at all - they should be declared locally, and not be exposed outside the method. This way you can be sure no-one else is changing them when you are not looking...</p>\n\n<p><strong>What should a <code>main</code> method do?</strong><br>\nYour <code>main</code> method contains <em>a lot</em> of functionality. I suggest you move this functionality to another method (<code>checkBoard()</code>). This way, when you decide to take this code, and use it as a module in another application, you can simply do it!</p>\n\n<p><strong>Keep it DRY</strong><br>\nAs a programmer, you should have bells ringing in your head each time you find yourself using <code>Copy+Paste</code>. Say you find a bug in your code, now you have to fix it 9 times! and if you miss a fix somewhere - good luck finding where it is...<br>\nTake the similarities between your snippets, and refactor them out. Analyze the differences, and pass them as arguments. Find how you decide which argument values to pass, and develop an algorithm to make that decision for you:</p>\n\n<pre><code>for(int i=0 ; i< sMatrix.length ; i++){\n for(int j=0 ; j<sMatrix.length ; j++){\n int boxIndex = (i / 3) * 3 + j / 3;\n boxSumArray[boxIndex]+=sMatrix[i][j];\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:27:52.873",
"Id": "80391",
"Score": "0",
"body": "@uri....Thanks for your feedback...How did you come up with this int boxIndex = i % 3 * 3 + j % 3 ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:20:48.163",
"Id": "80408",
"Score": "0",
"body": "Sorry, my mistake - it should be `/`, not `%` (modulo) - I fixed my answer..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:48:40.873",
"Id": "81546",
"Score": "0",
"body": "In many cases I would also suggest moving the functionality out of the class and into its instances, although that doesn't really apply in this case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:30:36.663",
"Id": "46042",
"ParentId": "46033",
"Score": "9"
}
},
{
"body": "<p>Just a couple of minor things:</p>\n\n<ul>\n<li><p>In Java, <code>{</code> braces should be put at the end of the same line and not on it's own line.</p></li>\n<li><p>Instead of using break and a <code>boolean sudokuStatus</code> in your <code>checkArrayStatus</code> method, use a <code>return</code> statement</p>\n\n<pre><code>while (i < 9) {\n if (rSumArray[i] != 45 && cSumArray[i] != 45 && rSumArray[i] != 45) { \n return false;\n }\n i++;\n}\nreturn true;\n</code></pre></li>\n<li><p>Since the above loop is just doing a fixed-length iteration, replace <code>while (i < 9)</code> with</p>\n\n<pre><code>for (int i = 0; i < 9; i++)\n</code></pre></li>\n<li><p>9 is a \"magic number\" in your code. Let's say you wanted to change the Sudoku grid size (there are 4x4 Sudokus as well, in fact, almost any size is possible). If you wanted to change the size, you'd have to replace the value in many different places. Instead use a constant.</p>\n\n<pre><code>public static final int GRID_SIZE = 9;\n</code></pre>\n\n<p>Now, instead of writing <code>9</code> you can use <code>GRID_SIZE</code></p></li>\n</ul>\n\n<h1>And one major thing:</h1>\n\n<p>Just because some numbers sum up to 45 doesn't mean that it's valid in a Sudoku group!</p>\n\n<p>Consider these numbers: <code>1, 1, 1, 1, 5, 9, 9, 9, 9</code>. Do they some up to 45? Yes. Would it be a valid group/row/column in a Sudoku? <strong>NO!</strong> This is why @Vogel612's solution is a whole lot better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:25:53.063",
"Id": "80492",
"Score": "0",
"body": "@simon.....Yes i agree to what you said!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:28:14.363",
"Id": "80500",
"Score": "0",
"body": ":Instead of using break and a boolean sudokuStatus in your checkArrayStatus method, use a return statement....Can you tell me why this is prefered over a booleanStatus?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:29:17.673",
"Id": "80501",
"Score": "0",
"body": ":since the above loop is just doing a fixed-length iteration, replace while (i < 9) with for (int i = 0; i < 9; i++)...why is this prefered over a normal for loop?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:18:51.310",
"Id": "46046",
"ParentId": "46033",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:32:46.243",
"Id": "46033",
"Score": "15",
"Tags": [
"java",
"validation",
"sudoku"
],
"Title": "Sudoku Checker in Java"
} | 46033 |
<p>I'm a beginner and I only know limited amounts such as <code>if</code>, <code>while</code>, <code>do while</code>. So I'm here to check if I'm coding with best practise and the most effective methods to my current knowledge.</p>
<pre><code>import java.util.Scanner;
public class SixtyTwo {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Starting Number: ");
int n = keyboard.nextInt();
int counter = 0;
int stepsTaken = 0;
int largestNumber = 0;
System.out.println();
while ( n != 1 ){
if ( ( n & 1 ) == 0 ) {
System.out.print( (n = ( n / 2 )) + " " );
stepsTaken++;
counter++;
} else {
System.out.print( (n = ( n * 3 ) + 1) + " " );
stepsTaken++;
counter++;
}
if ( n > largestNumber ){
largestNumber = n;
}
if (counter == 9){
counter = 0;
System.out.print("\n");
}
}
System.out.println();
System.out.println("\nTerminated after " + stepsTaken + " steps.");
System.out.println("The largest value was " + largestNumber + ".");
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:12:57.403",
"Id": "80489",
"Score": "2",
"body": "[collatz research/ graphs/ leads/ papers/ ruby code/ many se Q/As](http://vzn1.wordpress.com/code/collatz-conjecture-experiments/)"
}
] | [
{
"body": "<p>That is some overall quite good code you have there, but I have a couple of comments.</p>\n\n<ul>\n<li><p><code>Scanner</code> should be closed when you are done with the input. Simply call <code>keyboard.close();</code> when you have acquired the input that you need.</p></li>\n<li><p>Your class is called <code>SixtyTwo</code> but I have no clue what that has to do with anything. A better name would be <code>Collatz</code></p></li>\n<li><p><code>if ( ( n & 1 ) == 0 )</code> although it is a nice way of checking if a number is even, it is for Java programmers more readable to use the <code>%</code> (modulo) operator. I would use <code>if (n % 2 == 0)</code>.</p></li>\n<li><p><code>System.out.print( (n = ( n / 2 )) + \" \" );</code> ...now this I'm not a big fan of. Sure, it works to both modify a value and outputting it on the same line, but I would separate the assignment to it's own line. Assign on one line, output on another, makes things much clearer to read.</p></li>\n<li><p><code>stepsTaken++;</code> and <code>counter++;</code> don't need to be inside the if-else blocks, put them outside them as they are always done no matter if your condition is true or false.</p></li>\n<li><p><code>if (counter == 9)</code> can instead be <code>if (stepsTaken % 9 == 0)</code>, which would remove the need for the <code>counter</code> variable entirely.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:57:02.480",
"Id": "46036",
"ParentId": "46034",
"Score": "11"
}
},
{
"body": "<p>Since Java 7 it is also possible to use <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resource</a> statements which closes the Scanner object automatically:</p>\n<pre class=\"lang-java prettyprint-override\"><code>try (Scanner keyboard = new Scanner(System.in)) {\n // doing stuff with keyboard\n}\n</code></pre>\n<p>This prevents also exception handling, because the stream will be closed in any case (like a finally block).</p>\n<p>As Marc-Andre pointed out, you should be aware that the <code>System.in</code> stream is also closed after the <code>try</code>-block. So you will not be able to scan more input from the user, because you can't reopen this stream!</p>\n<p>Also see: <a href=\"https://stackoverflow.com/questions/8941298/system-out-closed-can-i-reopen-it\">https://stackoverflow.com/questions/8941298/system-out-closed-can-i-reopen-it</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:49:15.890",
"Id": "80377",
"Score": "3",
"body": "Note that this will close `System.in`, so if you need it later it could cause some trouble. (This is just a warning, nothing wrong here)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T17:01:34.407",
"Id": "80379",
"Score": "0",
"body": "Thanks for highlighting this! I didn't know, that you really can close the `System.in` stream, since you're also not opening it in any way!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:04:46.750",
"Id": "46038",
"ParentId": "46034",
"Score": "6"
}
},
{
"body": "<p>You can greatly reduce the complexity of your code, by using the ternary operator:</p>\n<pre><code>while (n != 1){\n stepsTaken++;\n n = (n % 2 == 0) ? n / 2 : n * 3 + 1;\n System.out.print(n);\n\n //Your largest number and the linebreaks go here;\n}\n</code></pre>\n<p>I removed the <code>counter++</code> as you correctly mentioned, you can instead of <code>counter == 9</code> use <code>stepsTaken % 9 == 0</code></p>\n<h3>Small explanation:</h3>\n<p>this:</p>\n<pre><code>int i = {some value};\nif(i % 2 == 0){\n i = i / 2;\n}\nelse {\n i = i * 3 + 1;\n}\n</code></pre>\n<p>can be shortened to the terary operator. It has the following syntax:</p>\n<pre><code>i = (condition) ? if-branch : else-branch;\n</code></pre>\n<p>That is the whole magic behind the shortened code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:30:54.490",
"Id": "80320",
"Score": "0",
"body": "Thank you this seems really efficient, this may seem a silly question but the `n = (n % 2 == 0) ? n / 2 : n * 3 + n;` line includes a question mark, what does that do? Although using this method seems to save alot of code, what is better for readability? If/Else or Ternary? - seen edit, the question mark separates the condition and the If/Else?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:33:48.737",
"Id": "80321",
"Score": "2",
"body": "@Niall You can only use the Ternary operator for assignment operations (Afaik). In fact I personally love using it everywhere possible, but I think it depends on personal style, where you want it and where not. the ? is just the syntax requirement. I added a little explanation on that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:36:54.397",
"Id": "80322",
"Score": "0",
"body": "Brilliant explanation so it can only be used when assigning Ints/Strings etc, thank you I have learnt alot today!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:39:25.080",
"Id": "80323",
"Score": "0",
"body": "@NiallSzalkai keep in mind, the condition needs to have a boolean result, so no strings and ints there ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:54:20.890",
"Id": "80330",
"Score": "0",
"body": "boolean result is something I may have to look into more :D I've done little research but I think it is something that can have a true or false result, and based on the true/false result an output can be produced? - apologies for a million questions!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:56:25.837",
"Id": "80331",
"Score": "0",
"body": "@NIall exactly that is the ternary operator... boolean result just means true/false"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:36:34.970",
"Id": "80527",
"Score": "1",
"body": "You mean 3 * n + 1, not 3 * n + n. Although it might be educational to see what happens with 3 * n + n."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:38:59.373",
"Id": "80529",
"Score": "0",
"body": "@gnasher729 Oooops... It results in an infinite loop... n * 4 / 2 / 2 = n...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:05:46.803",
"Id": "80558",
"Score": "0",
"body": "@Vogel612 It's ok, I figured it out when making the amendments :P"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:22:05.070",
"Id": "46040",
"ParentId": "46034",
"Score": "8"
}
},
{
"body": "<p><strong>Indenting and spacing</strong><br>\nJava's indentation conventions are no more than four spaces in a block. Also don't overdo spacing inside your parentheses and between braces. See <a href=\"http://www.javaranch.com/style.jsp\">here</a> for more conventions:</p>\n\n<pre><code>while (n != 1){\n if (( n & 1 ) == 0) {\n System.out.print((n = (n / 2)) + \" \");\n stepsTaken++;\n counter++;\n } else {\n System.out.print((n = (n * 3) + 1) + \" \");\n stepsTaken++;\n counter++;\n }\n\n if (n > largestNumber) {\n largestNumber = n;\n }\n\n if (counter == 9) {\n counter = 0;\n System.out.print(\"\\n\");\n }\n}\n</code></pre>\n\n<p><strong>Don't change where you print</strong><br>\nYou have lines like this in your code:</p>\n\n<pre><code>System.out.print( (n = ( n / 2 )) + \" \" );\n</code></pre>\n\n<p>This is a very problematic line of code, since it logs as well as changes the value of <code>n</code>. The change is also not as obvious as you think, and might easily be missed. This causes two problems:</p>\n\n<ol>\n<li>Someone reading your code might not understand how it works, since it missed the point where you change the value.</li>\n<li>More seriously - if you decide to remove the printing, you might forget that it changes something, and simply comment it out or delete it.</li>\n</ol>\n\n<p>I suggest you re-write it into to separate lines - one for the change and one for the log:</p>\n\n<pre><code>n = n / 2;\nSystem.out.print(n + \" \");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T12:58:08.180",
"Id": "46045",
"ParentId": "46034",
"Score": "7"
}
},
{
"body": "<p>Now since the whole point of this code is to check the Collatz conjecture (which says that whatever integer you start with, you'll eventually end up at 1, and you won't get a repeating cycle or numbers growing more and more), could I suggest that you add a check that the number isn't getting too big. Because <em>if</em> there is a number where the sequence grows and grows then you would get an overflow, and from then on get the wrong results in the sequence. </p>\n\n<p>Typically you will get wrong results if n is odd and 3n + 1 > 2^31 - 1, or n > 715,827,882. I bet you don't need to search very far to find a number where that limit gets exceeded. Without such a check, the whole code is pointless. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:31:03.537",
"Id": "46073",
"ParentId": "46034",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "46036",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T11:38:13.017",
"Id": "46034",
"Score": "17",
"Tags": [
"java",
"beginner"
],
"Title": "Collatz Sequence"
} | 46034 |
<p>I needed a script for working out billing dates over a period of time. The date should be the same day every month however if the billing date starts on a date that doesn't exist in another month, then it should be on the last day of that month. This rules out the <code>DateTimeInterval</code> Object, because that causes months to 'rollover' (31/01 becomes 03/03 etc.) which is unacceptable for my use case.</p>
<p>Try as I might, I couldn't find anything in-built to accommodate for this, so I wrote the following, however it seems like a lot of code for what I'm trying to achieve so I was wondering if anyone could suggest a better / in-built way?</p>
<pre><code>$replaceVars = array(
'effectivedate' => '30-9-2014',
'vatpc' => 0.15,
'paymentamount' => 150.00,
'duration' => 12
);
$effectivedateObj = new DateTime($replaceVars['effectivedate']);
$iD = array(
'd' => $effectivedateObj->format('d'),
'm' => $effectivedateObj->format('m'),
'y' => $effectivedateObj->format('Y')
);
$payments = '';
for ($i=0; $i < $replaceVars['duration']; $i++)
{
$newDate = array(
'd' => $iD['d'],
'm' => (($iD['m'] + $i) > 12) ? (($iD['m'] + $i) % 12) : $iD['m'] + $i,
'y' => (($iD['m'] + $i) > 12 ? $iD['y'] + 1 : $iD['y'])
);
if($newDate['d'] > cal_days_in_month(CAL_GREGORIAN, $newDate['m'], $newDate['y']))
{
$newDate['d'] = cal_days_in_month(CAL_GREGORIAN, $newDate['m'], $newDate['y']);
}
$paymentString = '<tr>';
$paymentString .= '<td>Payment Number '.($i+1).'</td>';
$paymentString .= '<td>'. $newDate['d'] .'/'. $newDate['m'] .'/'. $newDate['y'] .'</td>';
$paymentString .= '<td>&pound;'. round(( $replaceVars['paymentamount'] + ( $replaceVars['paymentamount'] * $replaceVars['vatpc'] )), 2) .'</td>';
$paymentString .= '</tr>';
$payments .= $paymentString;
echo $paymentString . '<br>';
}
</code></pre>
<p>The top array and the lines that build the string are just for testing, but it still seems like a lot of code?</p>
<p>Also I have no idea how necessary my parenthesis are when creating ternary statements, and I do feel a bit neurotic about the amount that I use, so some advice on that would be appreciated.</p>
| [] | [
{
"body": "<p>I think the best thing you could do (as in easiest, most reliable and least code) is to go back to the <code>DatePeriod</code> class. Yes, it doesn't correct itself in terms of <em>\"month-overflow\"</em> (yet), but that's an easy fix:</p>\n\n<p>Assume the data from your example:</p>\n\n<pre><code>$replaceVars = array(\n 'effectivedate' => '30-9-2014',\n 'vatpc' => 0.15,\n 'paymentamount' => 150.00,\n 'duration' => 12\n);\n</code></pre>\n\n<p>Now let's see what we can do with this:</p>\n\n<pre><code>function getPaymentDates(array $data)\n{\n $begin = new DateTime($data['effectivedate']);\n $period = new DatePeriod(\n $begin,\n new DateInterval('P1M'),\n (int) $data['duration'] //added cast to be sure, in case this data comes from DB\n );\n $clean = array();//<-- return this\n $last = (int) $begin->format('m');\n foreach ($period as $date)\n {\n while($last != $date->format('m'))\n $date->modify('-1 day');//subtract days until we get to the last day of the previous month...\n $clean[] = $date;\n if (++$last > 12)\n $last = 1;//no 13th month, of course...\n }\n return $clean;\n}\n</code></pre>\n\n<p>I've tried this with starting date <code>2014-01-31</code>, and it produced the exact outcome you'd expect, no problem:</p>\n\n<pre><code>2014-01-31 00:00:00\n2014-02-28 00:00:00\n2014-03-31 00:00:00\n2014-04-30 00:00:00\n2014-05-31 00:00:00\n2014-06-30 00:00:00\n2014-07-31 00:00:00\n2014-08-31 00:00:00\n2014-09-30 00:00:00\n2014-10-31 00:00:00\n2014-11-30 00:00:00\n2014-12-31 00:00:00\n2015-01-31 00:00:00\n</code></pre>\n\n<p>But there is a problem here, of course: The period is 12 months in total, but this function returns 13 dates.<br>\nI did this for a reason, of course. There are 2 paths to go down for you, either pass a fourth argument to the <code>DatePeriod</code> constructor (<code>DatePeriod::EXCLUDE_START_DATE</code>), which will exclude the starting date from the returned dates, or return a slice of the array:</p>\n\n<pre><code>return array_slice(\n $clean,\n 0,\n $data['duration']//in this case 12\n);\n</code></pre>\n\n<p>Which drops the last date from the return array.<br>\nIdeally, I'd have this function take a second argument, with 3 possible values. Say, for example 1, 2 and 3: If that second argument is 1, then the first date won't be returned (basically, you'll pass <code>DatePeriod::EXCLUDE_START_DATE</code> to the constructor), if 2 is passed, then you'll slice the returned array (excluding the last date in the generated period). Passing 3 means that you return the resulting array (<code>$clean</code>) as is, no dates are removed, and its length will be that of <code>$data['duration']</code> + 1.</p>\n\n<p>If this function will be used as a class method, then I'd suggest using constants for this.<br>\nIn that case, your code could end up like this:</p>\n\n<pre><code>class Foo\n{\n const EXCLUDE_EFFECTIVE_DATE = 1;\n const EXCLUDE_FINAL_DATE = 2;\n const EXCLUDE_NO_DATE = 3;\n\n public function getPaymentDates(array $data, $exclude = self::EXCLUDE_NO_DATE)\n {\n $begin = new DateTime($data['effectivedate']);\n $exArg = null;\n if ($exclude === self::EXCLUDE_EFFECTIVE_DATE)\n $exArg = DatePeriod::EXCLUDE_START_DATE;\n $period = new DatePeriod(\n $begin,\n new DateInterval('P1M'),\n (int) $data['duration'],\n $exArg\n );\n $clean = array();\n $last = (int) $begin->format('m');\n foreach ($period as $date)\n {\n while($last != $date->format('m'))\n $date->modify('-1 day');\n $clean[] = $date;\n if (++$last > 12)\n $last = 1;\n }\n if ($exclude === self::EXCLUDE_FINAL_DATE)\n return array_slice($clean, 0, $data['duration']);\n return $clean;\n }\n</code></pre>\n\n<p>To generate the same output as you are getting now, becomes a piece of cake, and doesn't require ugly code (computation mixed in with <code>echo</code>'s isn't nice...):</p>\n\n<pre><code>$foo = new Foo;//<-- class-like example\n$replaceVars = array();//<-- imagine your data here\n$dates = getPaymentDates($replaceVars, Foo::EXCLUDE_FINAL_DATE); //is what you're doing now\n//assuming you have echo '<table><tbody>'; here somewhere\n//Calculate the payment values up front please!!\n$payment = round($replaceVars['paymentamount'] + $replaceVars['paymentamount'] * $replaceVars['vatpc'], 2);\nforeach ($dates as $i => $date)\n{\n echo '<tr><td>Payment number: ', $i+1, '</td><td>',\n $date->format('d/m/Y'), '</td><td>',\n '&pound;', $payment ,'</td></tr>';\n}\necho '</tbody></table>';\n</code></pre>\n\n<p>So one thing: calculate the payment value once, and echo it in the loop. There is <em>no point</em> in calculating the same thing over and over, just assign it to a temp variable and use that instead.<br>\nAs an asside: yes, those are <em>comma's</em> I'm using in the <code>echo</code> statement, and not concatenating <code>.</code> (dot)-operators. <code>echo</code> is a language construct that works in a similar fashion to C++'s <code>std::COUT</code>. You can push any number of values to it, it'll just push them to the <code>stdin</code> sequentially. That way, there's no reason to allocate new memory, and copy string chars to create a new, big string constant that'll just be passed to echo anyway.</p>\n\n<p>I've already <a href=\"https://stackoverflow.com/questions/20596098/php-closing-tag-deletes-the-line-feed/20596645#20596645\">explained this in great detail here</a>, in the comments below my answer there, there's a link to a page where the differences in exec. time are mentioned, too. Bottom line: The difference isn't dramatic, but <code>echo</code> without concatenation is faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:16:01.113",
"Id": "46049",
"ParentId": "46047",
"Score": "5"
}
},
{
"body": "<p>In the past I have run in to this problem.</p>\n\n<p>My PHP is non-existent, but the problem can be broken down and simplified....</p>\n\n<ol>\n<li>only 5 months of the year are vulnerable to this problem (in all other months, the following month has more or the same number of days):\n<ul>\n<li>January</li>\n<li>March</li>\n<li>May</li>\n<li>August</li>\n<li>October</li>\n</ul></li>\n<li>in the months with problems, you only have to worry about anything when the day-of-month is >= 29 (for January) or the 31st for other months.</li>\n<li>for days >= 29 in January the answer is (1 day less than march 1st)</li>\n</ol>\n\n<p>So, in reality, there are only (about - depending on leap years) 7 days in the year where this is a problem.</p>\n\n<p>For those 6 days 4 of them are constants (march 31, May 31, Aug 31 and Oct 31), and the January one needs some help.....</p>\n\n<p>So, a cascading <em>if</em> statement should work fine, and be fast.... using some artistic license with PHP syntax, it would look like:</p>\n\n<pre><code>if (dayofmonth == 31 || (month == january && day > 28))\n{\n billdate->add('P1M'); // add a month, it will overflow to following month\n dom = .... // get the day-of-month of the new billdate\n billdate->sub('P' + dom + 'D'); // subtract the nw day-of-month (will be 1 for most months, but may be as much as 3 for the 3rd of March....)....\n}\nelse\n{\n billdate ->add('P1M');\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:22:37.850",
"Id": "46050",
"ParentId": "46047",
"Score": "5"
}
},
{
"body": "<p>I'm inclined to keep it simple:</p>\n\n<pre><code>$start = new DateTime('30-Jan-2014', new DateTimeZone(\"America/Toronto\"));\n$end = clone $start;\n$end->modify('+1 month');\nwhile (($start->format('m')+1)%12 != $end->format('m')%12) {\n $end->modify('-1 day');\n}\necho $end->format('d-M-Y');\n</code></pre>\n\n<p>This just checks to see if the month is the expected one, and if not, backs up one day at a time until it is. The advantage is that it's short, clear, and will work even in leap years (try 2004 to verify that).</p>\n\n<p><strong>Edit:</strong> It's also easy to make this into a user-defined function:</p>\n\n<pre><code>function addMonth($begin) \n{\n $end = clone $begin;\n $end->modify('+1 month');\n while (($begin->format('m')+1)%12 != $end->format('m')%12) {\n $end->modify('-1 day');\n }\n return $end;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:02:31.843",
"Id": "80358",
"Score": "0",
"body": "would this work if the payment date were to span over two different years, from september 2013 - march 2014 for example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-01T03:38:00.957",
"Id": "160266",
"Score": "0",
"body": "Great solution, thanks for keeping it simple! Doesn't work in November though, since (11+1)%12 = 0. You can fix it by doing %12 on $end as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-08T13:34:10.940",
"Id": "222135",
"Score": "0",
"body": "FYI, anon user posted this alternative solution in a suggested edit: http://smobilesoft.com/?p=265 (feel free to mark this obsolete on reception)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:57:39.983",
"Id": "46061",
"ParentId": "46047",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:27:21.813",
"Id": "46047",
"Score": "8",
"Tags": [
"php",
"datetime"
],
"Title": "Calculate a month later than current month (without rolling over to next month)"
} | 46047 |
<p>Please review my code and let me know how I can possibly improve it.</p>
<pre><code>#include<iostream>
using namespace std;
class node
{
private:
int data;
public:
node *next;
node(int element)
{
data=element;
next=NULL;
}
int getdata()
{
return(data);
}
};
class stack
{
private:
node *start;
public:
void push(int element);
int pop();
void traverse();
stack()
{
start=NULL;
}
};
inline void stack::push(int element)
{
node *ptr;
node *temp=start;
ptr=new node(element);
if(start==NULL)
{
start=ptr;
ptr->next=NULL;
}
else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
ptr->next=NULL;
}
}
inline int stack::pop()
{
node *temp=start;
node *top=start;
while(temp->next!=NULL)
{
temp=temp->next;
}
while(top->next!=temp)
{
top=top->next;
}
top->next=NULL;
int item=temp->getdata();
delete (temp);
}
inline void stack::traverse()
{
node *temp=start;
while(temp!=NULL)
{
cout<<"data is"<<temp->getdata();
temp=temp->next;
}
}
int main()
{
stack a;
for(int i=0;i<10;i++)
{
a.push(i);
}
a.traverse();
for(int i=0;i<5;i++)
{
a.pop();
}
a.traverse();
return(0);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:17:15.730",
"Id": "80422",
"Score": "6",
"body": "Indenting seems very haphazard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-01T13:18:39.913",
"Id": "273840",
"Score": "0",
"body": "Correct me if I'm wrong (noob here), but I thought we were forbidden to use loops and if/else statements in inline functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-01T15:44:30.627",
"Id": "273864",
"Score": "0",
"body": "next step - make it generic so that is supports a stack of any type"
}
] | [
{
"body": "<p>First of all, I will start with one of the most common remarks: please, <a href=\"https://stackoverflow.com/q/1452721/1364752\">do not use <code>using namespace std;</code></a>. It is especially bad if you write it in a header file since it leads to namespace pollution and name clashes.</p>\n\n<hr>\n\n<p>Instead of a method named <code>traverse</code>, it would be better to overload <code>operator<<</code> to print your list. Here is how you could adapt your function (put that code in your class):</p>\n\n<pre><code>friend std::ostream& operator<<(std::ostream& stream, const stack& sta)\n{\n node *temp= sta.start;\n while(temp!=NULL)\n {\n stream<<\"data is\"<<temp->getdata();\n temp=temp->next;\n }\n return stream;\n}\n</code></pre>\n\n<p>Don't forget to make it a <code>friend</code> function so that it can access the <code>private</code> members of <code>stack</code>.</p>\n\n<hr>\n\n<p>Generally speaking, you shouldn't mark your functions <code>inline</code>. While it <em>may</em> sometimes speed up your code for small functions (your functions aren't small), most of the time, it will simply <strong><em>be totally ignored by the compiler</em></strong>. Even if it is taken into account by the compiler for inlining, it could still <a href=\"https://stackoverflow.com/a/145952/1364752\">make your executable larger</a> and will probably not significantly speed up your code. <em>Worse</em>: since <code>inline</code> functions have to live in the header file, you will have to compile again every file including this one when you change the implementation of your functions. Bottom line: remove all your <code>inline</code> qualifications, they won't gain you anything and may make things worse.</p>\n\n<hr>\n\n<p>From the implementation of <code>pop</code>, I bet that it is meant to return the popped <code>int</code> since you called <code>getdata</code>. However, you forgot to return <code>item</code>. Your compiler should have warned you about the unused variable <code>item</code> and the non-void function <code>pop</code> returning nothing. If not, you should tell your compiler to give you more warnings.</p>\n\n<hr>\n\n<p>You don't need to write <code>return 0;</code> at the end of the function <code>main</code> in C++. If nothing has been returned when the end of the function is reached, it automagically does <code>return 0;</code>. This remark only holds for the function <code>main</code> though. Also, you don't need to put parenthesis around the returned result; <code>return</code> is not a function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:27:15.303",
"Id": "80345",
"Score": "0",
"body": ":thanks a lot. I am a beginner, learning to write c++ code.This has helped me a lot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:19:49.837",
"Id": "80425",
"Score": "1",
"body": "Marking your functions `inline` will have no affect on the size or speed of your code. For `code-inlining` purposes the keyword `inline` is ignored by modern compilers (unless you explicitly force the compiler to use the hints). Humans are terrible at knowing when to inline code as a result compiler writers have long stopped trusting them and use pretty good huristics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:49:55.447",
"Id": "80454",
"Score": "0",
"body": "@LokiAstari Well, I was only quoting an answer on a reference question... And I actually just saw you comment on the aforementioned question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-29T20:51:12.903",
"Id": "220246",
"Score": "0",
"body": "using `using` is fine if it's not in a header file. Personally I think writing 'std::' everywhere looks quite messy in a source file. The whole point of namespaces is that you don't have to prefix symbols with something unique anymore."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:23:09.607",
"Id": "46051",
"ParentId": "46048",
"Score": "14"
}
},
{
"body": "<ul>\n<li><p>Please fix your indentation all over the header. It should be consistent with everything else.</p></li>\n<li><p>You don't need the <code>return 0</code> at the end of <code>main()</code>. Reaching this point implies successful termination, and the compiler will just insert it for you.</p></li>\n<li><p>In common stack implementations, <code>pop()</code> is <code>void</code> (merely pops off the top element). This is useful as it'll be much easier to terminate the function early if the stack is empty.</p>\n\n<p>For getting an element from the top, you would also have a <code>top()</code> function. It will also have to account for an empty stack, but it would be best to check for an empty list first.</p></li>\n<li><p>As @ChrisW has mentioned, the <code>node</code> class should be defined within the <code>stack</code> class as <code>private</code>. Also, there shouldn't be anything <code>public</code> inside the <code>node</code> class. If you put it within <code>stack</code>, its <code>private</code> data can still be accessed without an accessor.</p></li>\n<li><p>A member function like <code>getdata()</code> should be <code>const</code> as it doesn't modify any data members. You also don't need the <code>()</code> around <code>data</code>.</p>\n\n<pre><code>int getdata() const\n{\n return data;\n}\n</code></pre>\n\n<p>Moreover, you shouldn't have this function at all. A basic node structure should just have a data field and a pointer to the next/previous node in the list. As mentioned, anything containing this class will have access to its data.</p></li>\n<li><p>Prefer an initializer list instead of the constructor assignments:</p>\n\n<pre><code>node(int element) : data(element), next(NULL) {}\n</code></pre>\n\n<p>One advantage to this is that if you have any <code>const</code> data members, you'll be able to initialize them within this list. But with a constructor like yours, that won't work.</p></li>\n<li><p>You <em>must</em> have a destructor for a data structure that utilizes manual memory allocation. What happens if your structure object goes out of scope, but you haven't already popped every element? You'll have a memory leak.</p>\n\n<p>To prevent this, have the destructor traverse the list, using <code>delete</code> on each node.</p></li>\n<li><p>You can make your structure more intuitive and safer with a <code>empty()</code> function:</p>\n\n<pre><code>bool empty() const { start == NULL; }\n</code></pre>\n\n<p>This can just be defined within the class declaration and should be <code>public</code>.</p>\n\n<p>It is assumed that the list is empty if the head points to <code>NULL</code>, otherwise you can instead compare a size member to <code>0</code> (if you even want to bother with maintaining a size).</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:29:23.250",
"Id": "46054",
"ParentId": "46048",
"Score": "15"
}
},
{
"body": "<p>You could improve your use of whitespace; perhaps something more like this:</p>\n\n<pre><code>class node\n{\nprivate:\n int data;\npublic:\n node *next;\n node (int element)\n {\n data = element;\n next = NULL;\n }\n int getdata() const\n {\n return data;\n } \n};\n</code></pre>\n\n<p>The <code>node</code> class might be named <code>Node</code> instead (I usually use PascalCase for types and camelCase for identifiers).</p>\n\n<p><code>node</code> has public <code>data</code> member. I think it would be better if <code>node</code> were a private, nested type of <code>stack</code> (i.e. defined within and only usable by the <code>stack</code> class).</p>\n\n<p><code>traverse</code> could be <code>const</code> since it doesn't modify the data.</p>\n\n<p>Instead of <code>if { ... } else { ... }</code> I usually prefer <code>if { ... return; } ...</code>.</p>\n\n<p>You don't need to set ptr->next to NULL twice (once in the constructor and again in the <code>push</code> function).</p>\n\n<p><code>NULL</code> is deprecated in C++ (prefer <code>0</code>).</p>\n\n<p>Your push and pop are inefficient because you push and pop from the end of the list; you can push and pop from the beginning of the list instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:34:03.970",
"Id": "80442",
"Score": "0",
"body": "I know `nullptr` is the new preferred null pointer, but why is `0` better than `NULL`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:57:49.087",
"Id": "80447",
"Score": "0",
"body": "@200_success Apparently the standard now does `#define NULL 0` ... so `NULL` is the same as `0` ... but `NULL` is a (unnecessary/useless) C-style macro ... see e.g. http://www.stroustrup.com/bs_faq2.html#null ... Perhaps `NULL` used to cause problems years ago when a \"C/C++\" compiler defined it as `#define NULL (void*)0` and so NULL couldn't be assigned to e.g. a variable of type `char*`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:50:01.250",
"Id": "80479",
"Score": "0",
"body": "+1 for the suggestion to push/pop at the start of the list rather than the end. For large stacks this is a major speed improvement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T21:34:02.957",
"Id": "81418",
"Score": "0",
"body": "I have to disagree with 0 over `NULL`. `NULL` conveys meaning that 0 doesn't. Though the same as 0, `NULL` still mentally screams \"hey this is a pointer!\" I tend to agree that macros are evil, but I think `NULL` is an exception. `T* ptr = 0;` just doesn't have the same mental effect on me that `T* ptr = NULL;` does. Not to mention that compilers are still allowed to generate notices about `NULL`. A compiler can still have internal special meaning for `NULL` and treat it like it's a pointer type just in warning form instead of an error."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:41:13.153",
"Id": "46058",
"ParentId": "46048",
"Score": "9"
}
},
{
"body": "<p>it would be better if you start putting comments as it makes a better and understandable code!!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-17T11:21:54.083",
"Id": "140875",
"Score": "2",
"body": "Welcome to Code Review! You're correct about that, but in the future, please try to write more detailed answers. You could, for example, explain what kind of comments you would put in their code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-17T10:23:46.790",
"Id": "77794",
"ParentId": "46048",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46051",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T13:48:08.260",
"Id": "46048",
"Score": "15",
"Tags": [
"c++",
"beginner",
"stack",
"collections",
"pointers"
],
"Title": "Implementation of stack using pointers"
} | 46048 |
<p>I'm in a beginner JavaScript class and I feel like I have a pretty good grasp on all the intro material. All of my homework assignments work but they seem longer than they have to be, especially my most recent one. I'm not asking for answers to my homework as it is already complete (you can see the code works below) but I was seeing if anyone can give me some ideas for making my code more efficient.</p>
<p>Please don't provide me with new code and say paste this in as I really would like to think about it and learn. Maybe I haven't learned enough yet, but this looks pretty ugly to me from what I've seen online and I also repeat code... The only thing I'm required to do is build this with an object and there can only be one answer displayed at a time. I can't use jQuery or any other libraries.</p>
<pre><code>var obj = {
num1 : document.getElementById('num1'),
num2 : document.getElementById('num2'),
add : document.getElementById("add"),
sub : document.getElementById("sub"),
mult : document.getElementById("mult"),
div : document.getElementById("div"),
result : document.getElementById("result"),
init : function() {
document.getElementById("calculate").onclick = obj.calc;
},
calc : function() {
var num1 = parseFloat(obj.num1.value);
var num2 = parseFloat(obj.num2.value);
if(isNaN(num1) || isNaN(num2)) {
alert("You must enter a number for First Number and Second Number.");
}
else if (num2 === 0) {
alert("You cannot divide by zero");
}
else {
if (obj.add.checked === true) {
var result = num1 + num2;
}
else if (obj.sub.checked === true) {
var result = num1 - num2;
}
else if (obj.mult.checked === true) {
var result = num1 * num2;
}
else if (obj.div.checked === true) {
var result = num1 / num2;
}
else {
alert("Choose an operator")
}
if (obj.result.firstChild){
var para = document.getElementById("para");
console.log(para);
para.parentNode.removeChild(para);
var p = document.createElement("p");
p.setAttribute("id", "para");
p.appendChild(document.createTextNode("The answer is " + result));
obj.result.appendChild(p);
}
else {
var p = document.createElement("p");
p.setAttribute("id", "para");
p.appendChild(document.createTextNode("The answer is " + result));
obj.result.appendChild(p);
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>rather than query each radio to see if it is checked and then run the arithmetic based upon that, I would probably store the arithmetic as a closure in your obj, where the key is the value of the checked input and then run document.querySelector to find the checked input, something like this:</p>\n\n<pre><code>var obj = {\n num1 : document.getElementById('num1'),\n num2 : document.getElementById('num2'),\n add : function(n1, n2) { return n1 + n2; },\n sub : function(n1, n2) { return n1 - n2; },\n mult : function(n1, n2) { return n1 * n2; },\n div : function(n1, n2) { return n1 / n2; },\n result : document.getElementById(\"result\"),\n init : function() {\n document.getElementById(\"calculate\").onclick = obj.calc;\n },\n calc : function() {\n var num1 = parseFloat(obj.num1.value),\n num2 = parseFloat(obj.num2.value),\n operation, result;\n\n if(isNaN(num1) || isNaN(num2)) {\n return alert(\"You must enter a number for First Number and Second Number.\");\n }\n else if (num2 === 0) {\n return alert(\"You cannot divide by zero\"); \n }\n\n operation = document.querySelector('input[type=\"radio\"]:checked').value;\n\n result = obj[operation](num1, num2);\n\n obj.result.innerHTML = ''; \n\n p = document.createElement(\"p\");\n p.setAttribute(\"id\", \"para\");\n p.appendChild(document.createTextNode(\"The answer is \" + result));\n obj.result.appendChild(p);\n }\n }\n\nobj.init(); \n</code></pre>\n\n<p>This saves you from having a really long series of if / else checking for the checked input. I would also remove the logic of checking whether you have already created a P and added it to the result div, instead i'd just set the result divs innerHTML to '' each time, and add the P tag again, as the end result is the same.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:24:24.447",
"Id": "80367",
"Score": "0",
"body": "That's exactly the thought process I was using, but I didn't know how to go about it. Haven't used querySelector yet. Clearing the div makes a lot more sense. Thanks for the response!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:58:08.770",
"Id": "46062",
"ParentId": "46053",
"Score": "7"
}
},
{
"body": "<p>Welcome to CR, from a once over:</p>\n\n<ul>\n<li>You are warning about division by 0, even if I did not select 'Divide'</li>\n<li>You can consider using truthy evaluations to shorten code: <code>(obj.add.checked === true)</code> -> <code>(obj.add.checked)</code></li>\n<li>I would not go for the literal object notation to avoid having to type ( and read ) <code>obj.</code> every single time</li>\n<li>Instead of using <code>onclick = obj.calc;</code>, consider using <code>addEventListener</code></li>\n<li><p>It would be smart to already have a <code>para</code> node as part of the HTML, and then simply set the value of that <code>para</code> node, this</p>\n\n<pre><code> if (obj.result.firstChild){\n var para = document.getElementById(\"para\");\n console.log(para);\n para.parentNode.removeChild(para);\n var p = document.createElement(\"p\");\n p.setAttribute(\"id\", \"para\");\n p.appendChild(document.createTextNode(\"The answer is \" + result));\n obj.result.appendChild(p);\n }\n else {\n var p = document.createElement(\"p\");\n p.setAttribute(\"id\", \"para\");\n p.appendChild(document.createTextNode(\"The answer is \" + result));\n obj.result.appendChild(p);\n }\n</code></pre>\n\n<p>would become:</p>\n\n<pre><code>obj.para.innerText = \"The answer is \" + result;\n</code></pre>\n\n<p>assuming that on top you would declare</p>\n\n<pre><code> para : document.getElementById(\"para\"),\n</code></pre></li>\n<li><p><code>obj</code>, as names go, is pretty banal, I am sure you can do better</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:19:55.907",
"Id": "80365",
"Score": "0",
"body": "Thanks for the response! I didn't even think to use 0 if other operations were selected, thanks for that catch. I wasn't very clear on my assignment details. obj has to be the object name... I know this can be a lot better. I also can't edit the HTML file that was provided and have to use literal object notation. I haven't used addEventListener before so I'm going to look into that now. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:58:37.027",
"Id": "46063",
"ParentId": "46053",
"Score": "5"
}
},
{
"body": "<p>I like Keir Lavelle's answer, but I would modify it like this:</p>\n\n<pre><code>operation = document.querySelector('input[name=\"operation\"]:checked').value;\n\nif(isNaN(num1) || isNaN(num2)) {\n return alert(\"You must enter a number for First Number and Second Number.\");\n} \nelse if (num2 === 0 && operation == div) {\n return alert(\"You cannot divide by zero\"); \n}\n</code></pre>\n\n<ol>\n<li>move code for finding operation above the check for divide-by-zero</li>\n<li>change it to get radio list by name, not type (to avoid conflicts with new radio lists)</li>\n<li>in check for divide-by-zero, also check if the operator is division. With any other operator, it is okay to have zero for num2</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:32:57.840",
"Id": "80370",
"Score": "1",
"body": "What would be the reason for changing to name? I don't think it would matter in this specific case. I think I am answering my own question, but is it in the case that there are multiple radio buttons on a page and you only want to apply this code to the operations buttons? Thanks for the divide catch, I completely overlooked the fact that 0 didn't work for other operations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:17:44.540",
"Id": "80465",
"Score": "1",
"body": "Yes, that's exactly why. You're right that it wouldn't matter in this case. But once you add another radio button list to the page (for a different thing altogether), suddenly things won't work."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:17:20.453",
"Id": "46065",
"ParentId": "46053",
"Score": "7"
}
},
{
"body": "<p>Contrary to common belief, division by zero is not always disastrous. In fact, the IEEE 754 floating point standard specifies that dividing by zero produces +∞ or -∞. <a href=\"https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-3/numbers\" rel=\"nofollow\">JavaScript treats numbers as IEEE double-precision floating point</a>, so you get the following behaviour for free:</p>\n\n<pre><code>> 3 / 0\nInfinity\n> 3 / -0\n-Infinity\n> 1 / 0 - 1\nInfinity\n</code></pre>\n\n<p>Your calculator would be simpler and more useful if you don't check for division by zero.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T04:35:16.560",
"Id": "46142",
"ParentId": "46053",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:26:44.297",
"Id": "46053",
"Score": "7",
"Tags": [
"javascript",
"beginner",
"homework",
"calculator"
],
"Title": "Basic Calculator"
} | 46053 |
<p>I just got into Object Oriented Programming, and it made me think about certain code how I can make them as efficient as possible.</p>
<p>Right now I am just including my header and footer like the following:</p>
<p><strong>PHP</strong></p>
<pre><code>require_once 'core/init.php';
require_once 'includes/header.php';
//Big block of content goes here
require_once 'includes/footer.php';
</code></pre>
<p>I wonder if this is the neatest / most efficient way of doing that?</p>
| [] | [
{
"body": "<p>If you are working in PHP use a framework that has MVC such as Laravel(up and coming and popular), Symphony, Yii, Codeigniter(defunct), etc.</p>\n\n<p>Each of them will enable you to use some reuse mechanism.</p>\n\n<p>Laravel itself uses a template PHP called blade. There are several other template mechanism such as Twig that enables you to template your views to even add more granular way and cleaner.</p>\n\n<p>If its a single file system that you must what you are doing is fine because you are using require_once it enables you to call other files and you can modify that file and it will reflect any other files that references it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:25:07.307",
"Id": "46066",
"ParentId": "46059",
"Score": "7"
}
},
{
"body": "<p>According to <a href=\"http://php.about.com/od/tutorials/ht/template_site.htm\">a PHP blog post</a>, yes this is exactly the way that it should be done. Even <a href=\"http://www.w3schools.com/php/php_includes.asp\">w3schools</a> (whom you normally shouldn't trust too much since they're not related to the real w3 at all) recommends it.</p>\n\n<p>I like that you are using <code>require</code> instead of <code>include</code>. I am not so sure if you really need the <code>_once</code> though.</p>\n\n<p>I recommend you read <a href=\"http://se1.php.net/manual/en/function.include.php\">the documentation of the include function</a> (which also applies to require, require_once and include_once) to make sure that you really are aware of how it works. Note that if you are using any PHP scripts inside the included files, any global variables (which you should try avoid using too many of overall) also gets included to the calling script.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T15:55:21.030",
"Id": "46069",
"ParentId": "46059",
"Score": "5"
}
},
{
"body": "<p>This is the fastest method I know of that does not include pasting your code on every page. Also include is faster than require / require_once / include_once. However I don't think this is the way to go about it.</p>\n\n<p>I completely disagree with INIT / GLOBAL / STATIC. If you really intend to do this in an OOP fashion you can't program like a php4 programmer any more. Instead you should focus all your attention on making your application run as a series of components that work as independently as possible from one another. In other words:</p>\n\n<ol>\n<li>No init / setup functions / methods / files other than <em>autoload.php</em> and <em>bootsrap.php</em> in classes. Shift logic towards factory classes and separate classes.</li>\n<li>No complicated code / logic in constructors. Constructors should simply set up properties. Try to convert that logic out of the class as another object. (ie config object or a tiny / micro object with only 1-2 responsibilities).</li>\n<li>No configuration files that the app should depend on. Instead have the app run on configuration objects that can be loaded with information from configuration files.</li>\n</ol>\n\n<p>Using this design philosophy the actual printing out of output should be delegated to a class of it's own. Adding a header / footer / sidebar / etc should be dynamic and configurable. This is all very inefficient and creates many lines of code to do simple tasks. I think you should first build your app never even considering performance until it has been completed. After your app if fully built and tested. You can then go about searching for bottlenecks to try to optimize. Optimization during development will only hinder you and create more problems than solve them.</p>\n\n<p>You could also give register_shutdown_function() a try.</p>\n\n<p><strong>bootstrap.php</strong></p>\n\n<pre><code>include 'autoload.php';\n\n$Configuration = new Configuration({\n 'DATABASE' => new ArrayConfig(new File('./config/db.php'))\n 'TEMPLATE' => new YAMLConfig(new File('./config/template.yml'))\n //...... \n});\n\n$ModelFactory = new ModelFactory($Configuration);\n$TemplateFactory = new TemplateFactory($Configuration);\n\nregister_shutdown_function(function(){\n extract($_GLOBALS);\n include 'footer.php';\n});\n</code></pre>\n\n<p><strong>index.php</strong></p>\n\n<pre><code>include 'bootstrap.php';\n//......\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:25:50.320",
"Id": "46104",
"ParentId": "46059",
"Score": "4"
}
},
{
"body": "<p>Although this is a great way of automatically including headers/footers in each page, you should call a function from within the header/footer script, as you will sometimes need to include additional content. For example:</p>\n\n<p><strong>Displayed page</strong></p>\n\n<pre><code>require_once 'core/init.php';\n\nrequire_once 'includes/foothead.php';\n$foothead = new foothead();\n$foothead->showheader('AwesomePage','<script src=\"somescript.js\" />','<link rel=\"stylesheet\" href=\"othercss.css\"/>','<!--random header content-->');\n\n//Big block of content goes here\n\n$foothead->showfooter('<!--Other footer stuff-->');\n</code></pre>\n\n<p><strong>foothead.php</strong></p>\n\n<pre><code>public class foothead {\n function showheader($title=\"hello\",$scripts=\"\",$css=\"\",$other=\"\") {\n echo \"<html><head><insert your usual header stuff>{$scripts}{$css}<title>{$title}</title>{$other}\";\n }\n function showfooter($stuff=\"\") {\n echo \"<your footer {$stuff} (goes in somewhere) >\";\n }\n}\n</code></pre>\n\n<p>This obviously isn't the SIMPLEST way, but it is quite neat. While writing my website, I noticed (too late) that many of my pages required additional scripts/css. By using that ^ script, you can make sure your header/footer will be ready in case you need any additional things included.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:48:54.057",
"Id": "80532",
"Score": "0",
"body": "I like how you did it with the methods and that you just send the variables as parameters with the method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T23:15:15.737",
"Id": "46116",
"ParentId": "46059",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46069",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:44:14.897",
"Id": "46059",
"Score": "5",
"Tags": [
"php",
"object-oriented"
],
"Title": "Neatest way of including a header and footer on every page"
} | 46059 |
<p>The purpose of the below code is to update a column based on the name of the field name sent from the .NET code. This allows one piece of code to handle multiple rows when a user is only adding/updating one at a time.</p>
<p>I have been using Stored Procedures for a while but normally just Add/Update but not using variable field names. All tips appreciated. </p>
<pre><code>USE DB
GO
/****** Object: StoredProcedure [dbo].[spActionUpdateOldestDate] Script Date: 04/02/2014 14:24:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[spUpdateViaFieldName]
-- spActionUpdateOldestDate '1234','date','field'
-- Add the parameters for the stored procedure here
@AlphaNumbericalRef nvarchar(50)
,@vValue nvarchar(MAX)
,@vFieldName varchar(MAX)
AS
BEGIN
-- add selection for courseID etc.. here
Execute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')
END
</code></pre>
| [] | [
{
"body": "<p>I think your stored procedure looks great!</p>\n<p>The only line that had me scratching my head is this one:</p>\n<pre><code>Execute ('UPDATE [TblActionsOldest] SET ' + @vFieldName + ' = ''' + @vValue + ''' WHERE RefID = ''' + @AlphaNumbericalRef+ '''')\n</code></pre>\n<p>I'm guessing those apostrophes are escape characters for <a href=\"/questions/tagged/asp.net\" class=\"post-tag\" title=\"show questions tagged 'asp.net'\" rel=\"tag\">asp.net</a> but if that's not the case I would discard them.</p>\n<h1><strong>Nice work!</strong></h1>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-18T08:20:50.480",
"Id": "102508",
"Score": "0",
"body": "Sadly yes, they are. They took me longer I think than the rest (though I had help on here thankfully to get to the above code). I was going crazy for a while with apostrophes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-18T13:31:00.267",
"Id": "102560",
"Score": "0",
"body": "I was wrong @indofraiser. you do need the apostrophes for Dynamic SQL."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-17T21:46:24.533",
"Id": "57337",
"ParentId": "46060",
"Score": "3"
}
},
{
"body": "<p>The only option that you have if you don't want to use all the apostrophes is to create stored procedures for updating each column and then create an outside stored procedure that you provide the column name to and it picks the right stored procedure based on the parameters that you pick, you can still send</p>\n\n<pre><code>@AlphaNumbericalRef nvarchar(50) \n,@vValue nvarchar(MAX)\n</code></pre>\n\n<p>through to the nested Stored Procedures.</p>\n\n<p>I am thinking that the performance may be better if you do it this way as opposed to the Dynamic SQL, because the Server can optimize the Stored Procedures whereas the Dynamic SQL leaves the Server in the dark about what is going to happen and doesn't give it a chance to plan the query, with an <code>UPDATE</code> (or a <code>DELETE</code>) you want to give the Server enough information to plan these things out, especially if they are going to happen many times on a large scale.</p>\n\n<hr>\n\n<p>These are links that I found with a quick Google Search( of the title of this question \"<em>Update column based on input variable in stored procedure</em>\" ) I landed first on a StackOverflow question</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/a/2899296/1214743\">Answer to</a> This <a href=\"https://stackoverflow.com/q/2896488/1214743\">Question</a></li>\n<li><a href=\"http://www.sommarskog.se/dynamic_sql.html\" rel=\"nofollow noreferrer\">Dynamic SQL</a></li>\n<li><a href=\"http://www.sommarskog.se/dynamic_sql.html#queryplans\" rel=\"nofollow noreferrer\">Query Plans</a></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-18T13:37:20.057",
"Id": "57391",
"ParentId": "46060",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T14:45:43.047",
"Id": "46060",
"Score": "7",
"Tags": [
"sql",
"sql-server",
"stored-procedure"
],
"Title": "Update column based on input variable in stored procedure"
} | 46060 |
<p>This is a form generator I created so users can input a URL, description and link. The output will eventually be a JavaScript news slider. The HTML the form generated is irrelevant for now but I'd like to see how I can improve the JavaScript code handing the processing. </p>
<p>This is my first version/draft.</p>
<pre><code><style>
body{
background-color:green;
}
.hideElement{
display:none;
}
.container{
display: inline-block;
margin:25px;
border: 2px solid white;
padding:10px;
}
p.slidenum{
text-align: center;
font-size: 22px;
font-weight: bolder;
}
p{
font-size: 20px;
}
input[type="text"]{
background-color:white;
color:black;
font-size:16px;
padding:10px;
}
input[type="button"]{
background-color:#A17F3F;
color:white;
font-size:16px;
border:2px solid;
border-radius:5px;
padding:10px;
}
</style>
</code></pre>
<p></p>
<pre><code><div id="step1" class=" ">
<h1>How many slides do you want to generate?</h1>
<input type="text" id="numOfSlides" name="numOfSlides">
<input type="button" value="Continue" onClick="generateForm()">
</div>
<div id="step2" class="hideElement">
<input type="button" id="genCodeButton" value="Generate Code" onClick="generateCode(); hideForm()">
<input type="button" value="Go Back" onClick="hideStep1(); clearForm(); toggleStep2(); toggleCodeOutput(); showGenCodeButton()">
</div>
<!--empty div, will be populated once user enters num of slides -->
<div id="sliderFormGenerated" class=" "> </div>
<br>
<textarea id="codeOutput" class="hideElement" rows="30" cols="70"></textarea>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
function generateForm(){
//get num of slides required by user, limit to 8
var numOfSlides = document.getElementById('numOfSlides').value;
//make sure num of slides is a valid integer 1-8
if(isNaN(numOfSlides)){
alert("Well that doesn't make much sense. Please enter a positive integer 1-8");
//document.getElementById('sliderFormGenerated').innerHTML="<p>Please enter a positive integer 1-8.</p>";
}
else if (numOfSlides >= 9) {
alert("The limit is 8 slides, please enter 8 or less.");
//document.getElementById('sliderFormGenerated').innerHTML="<p>Please enter a positive integer 1-8.</p>";
}
else if(numOfSlides < 1){
alert("Please enter a positive integer 1-8");
//document.getElementById('sliderFormGenerated').innerHTML="<p>Please enter a positive integer 1-8.</p>";
}
else {
//document.getElementById('sliderFormGenerated').innerHTML="<p>Great! For simplicity, let's make one at a time</p>";
//document.getElementById('sliderFormGenerated').innerHTML=sliderFormNumber;
//for loop to add unique id to each generated element
for(var i=0; i < numOfSlides; i++){
//declare form to be inserted by fucntion call
var sliderForm = " <p>\"Read More\" URL: </p><input type=\'text\' id=\'link\'>";
$("#sliderFormGenerated").append("<div class=\"container\"><p class=\"slidenum\">Slide " +(i+1) + "</p><p>Image URL: </p> <input type=\'text\' id=\'imgsrc" + i + "\'" + ">" + i + "<p>Description: </p><input type=\'text\' id=\'description" + i + "\'>" + i +"<p>\"Read More\" URL: </p><input type=\'text\' id=\'link" + i +"\'>" +i + "</div>");
$('#sliderFormGenerated').removeClass("hideElement");
}
toggleStep2();
hideStep1();
}
}
function hideStep1(){
$('#step1').toggleClass("hideElement");
}
function toggleStep2(){
$('#step2').toggleClass("hideElement");
}
function showGenCodeButton(){
$('#genCodeButton').removeClass("hideElement");
}
function hideForm(){
$('#sliderFormGenerated').addClass("hideElement");
}
function toggleCodeOutput(){
$('#codeOutput').addClass("hideElement");
}
function clearForm(){
document.getElementById("sliderFormGenerated").innerHTML=" ";
}
function generateCode(){
$('#codeOutput').toggleClass("hideElement");
$('#genCodeButton').addClass("hideElement");
//TODO: this is the same as numOfSlides variable declared above
var slides = document.getElementById('numOfSlides').value;
var inputArray = [];
for (i = 0; i < slides; i++){
var temp = document.getElementById('imgsrc' + i).value;
var temp1 = document.getElementById('description' + i).value;
var temp2 = document.getElementById('link' + i).value;
inputArray.push("<img src=\'" + temp + "\'>" + "<p>" + temp1 + "</p>" + "<a href=\'"+temp2+"\'>Read More</a>");
}
document.getElementById('codeOutput').innerHTML=inputArray.join('');
}
</script>
</body>
</code></pre>
| [] | [
{
"body": "<p>I will start with a snooty remark; please don't submit your first draft, but submit the best code you think you can write.</p>\n\n<p>From a once over:</p>\n\n<ul>\n<li>You should consider having your JavaScript in a separate file, JavaScript mixed in with your HTML is old skool</li>\n<li>Indentation in <code>function generateForm(){</code> is off</li>\n<li>Do not use <code>alert</code>, it annoys users, the commented out approach of setting <code>document.getElementById('sliderFormGenerated').innerHTML</code> is superior</li>\n<li>Do not keep commented out code</li>\n<li><p><code>\" <p>\\\"Read More\\\" URL: </p><input type=\\'text\\' id=\\'link\\'>\";</code> -> I would prefer <br></p>\n\n<pre><code>' <p>\"Read More\" URL: </p><input type=\"text\" id=\"link\">';\n</code></pre></li>\n<li><code>onClick=\"hideStep1(); clearForm(); toggleStep2(); toggleCodeOutput(); showGenCodeButton()\"</code> <-You are lucky I was wearing goggles, this is terrible because\n<ul>\n<li>You are using <code>onclick</code> in the HTML tag -> please use <code>addEventListener</code> instead</li>\n<li>If you had to use <code>onclick</code>, then you should at least have grouped these functions into 1 well named function, this way you would not have to create functions like <code>showGenCodeButton()</code> which is a short one liner that you only use once.</li>\n</ul></li>\n<li><p>This:</p>\n\n<pre><code>var temp = document.getElementById('imgsrc' + i).value;\nvar temp1 = document.getElementById('description' + i).value;\nvar temp2 = document.getElementById('link' + i).value;\n</code></pre>\n\n<p>I am sure you could think up more creative names for those variable names</p></li>\n</ul>\n\n<p>I have some more items, but at this point I think you need to polish your script and if you wish resubmit it, the quality of this code is very low.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:50:07.983",
"Id": "46189",
"ParentId": "46071",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:03:59.850",
"Id": "46071",
"Score": "6",
"Tags": [
"javascript",
"jquery",
"css",
"form"
],
"Title": "Form generator for inputting URL, description and link"
} | 46071 |
<p>I've borrowed and written the following code to output the disconnect time. All works well but I'm curious as to how I could tighten/ shorten the code. If anyone feels like having some fun then I'd love to see what can be done. Be a learning lesson for me.</p>
<p>Excerpt of input:</p>
<pre><code>ftp> !:--- FTP commands below here ---
ftp> lcd C:\Utilities\Performance_Testing\
\Utilities\Performance_Testing\: File not found
Verbose mode On .
ftp> verbose
binary
200 Switching to Binary mode.
ftp> put "test_file_5M.bin"
200 PORT command successful.
150 Ok to send data.
226 File receive OK.
ftp: 5242880 bytes sent in Seconds Kbytes/sec.
ftp> 44.81117.00disconnect
221 Goodbye.
ftp> bye
</code></pre>
<p>Code:</p>
<pre><code>#Obtain UT external put value.
ut1intput=$(awk '
NR==70 {
for(i=1;i<=NF;i++) {
if($i=="ftp>") {
sub(/disconnect/, "", $(i+1));
print $(i+1)
}
}
}' filename.txt)
utintputvalue=`echo $ut1intput | awk -F. '{print $2"."$3}'| sed 's/^..//'`
</code></pre>
<p>Output:</p>
<pre><code>utintputvalue is 117.00
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T17:55:25.500",
"Id": "80380",
"Score": "0",
"body": "Is your first \"output\" actually the input in the context of this question? Could you explain what \"44.81117.00\" means, and why that translates to a desired output value of 1220.98?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:18:38.360",
"Id": "80388",
"Score": "0",
"body": "Sorry, I C/P and pasted the incorrect output (not enough coffee). Should read 117.00. The \"44.81117.00\" is FTP output in seconds. I've been asked to output \"after the 100th of a second\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:29:55.117",
"Id": "80392",
"Score": "0",
"body": "To clarify again… 44.81117.00 means a bit over 44.81 seconds, and you care only about the fact that it was 117.00 × 10^-5 seconds more?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:38:23.950",
"Id": "80399",
"Score": "1",
"body": "Should have made myself clearer. The 44.81 is the output in seconds. The 117.00 is the speed in kb. I'm grabbing the data \"after the 100th of a second\". for some reason the info I'm be provided has this in that odd format."
}
] | [
{
"body": "<p>Assuming the \"Output\" section is stored in \"filename.txt\", and assuming you have GNU tools:</p>\n\n<pre><code>grep -oP '(?<=\\.\\d\\d)\\d+\\.\\d\\d(?=disconnect)' filename.txt\n</code></pre>\n\n<p>That's a perl regex meaning: prececeded dot and two digits, find some digits, a dot and two digits, followed by \"disconnect\". grep's <code>-o</code> option means \"output only the matched text\".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T17:23:47.843",
"Id": "46078",
"ParentId": "46074",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T16:49:23.693",
"Id": "46074",
"Score": "4",
"Tags": [
"parsing",
"datetime",
"sed",
"awk"
],
"Title": "Extracting performance statistics from FTP session transcript"
} | 46074 |
<p>This is my code which receives a file to read and converts binary values to ASCII text.</p>
<p>The code works fine, so I am looking for a review on what I have written, and suggestions on how I could do it better, perhaps without the use of a <code>StringBuffer</code>.</p>
<pre><code>import java.io.File;
import java.util.Scanner;
/**
*
* @author Tumpi
*/
public class DN6 {
public static void main(String[] args)
throws Exception {
File file = new File("sporocilo.txt");
Scanner sc = new Scanner(file);
String lastString = "";
while (sc.hasNextLine()) {
String line = sc.nextLine();
lastString = lastString + line;
}
StringBuffer result = new StringBuffer();
for (int i = 0; i < lastString.length(); i += 8) {
result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));
}
System.out.println(result);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:02:22.587",
"Id": "80381",
"Score": "2",
"body": "Why not use a `StringBuffer`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:02:34.523",
"Id": "80382",
"Score": "1",
"body": "Your question is not a review question, it is a question on about how to do something with code, if you read the http://codereview.stackexchange.com/about page you can better familiarize yourself with what questions to ask here. Your question would be better asked on StackOverflow"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:02:43.317",
"Id": "80383",
"Score": "3",
"body": "Is this code single thread or not ? If it's single thread you should use `StringBuilder` instead of `StringBuffer`.`StringBuffer` is use when there are multithreading."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:13:30.423",
"Id": "80385",
"Score": "0",
"body": "I wouldn't ask this on SO. It is possible to use simple string concatenation `str = str + \"more\";` but I wouldn't recommend that, a StringBuilder is really the best way to go."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:14:20.657",
"Id": "80386",
"Score": "0",
"body": "Or you could use a simple `char[]` of course."
}
] | [
{
"body": "<p>You should be using <code>StringBuilder</code> instead of <code>StringBuffer</code>, since <code>StringBuffer</code> has synchronization for thread safety that you don't need.</p>\n\n<p>To make the code more modular and reusable, consider writing it as a <code>FilterInputStream</code> instead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:17:21.810",
"Id": "80387",
"Score": "0",
"body": "+ 1 since I can't agree more with what I've said in comments :D ! I would suggest using a second `StringBuilder` for the first `for` loop too ! (If you want to add it!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:36:31.067",
"Id": "80397",
"Score": "1",
"body": "@Marc-Andre Concrete suggestions for improvements should be answers, not comments, [even if they are short](http://meta.codereview.stackexchange.com/a/1479/9357)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:15:31.947",
"Id": "46081",
"ParentId": "46080",
"Score": "10"
}
},
{
"body": "<p>Aside from turning <code>StringBuffer</code> into <code>StringBuilder</code>, there are a few more things I'd like to note about your code.</p>\n\n<h1>Compound assignment operator</h1>\n\n<p>This line:</p>\n\n<pre><code> lastString = lastString + line;\n</code></pre>\n\n<p>Can be rewritten as this one:</p>\n\n<pre><code> lastString += line;\n</code></pre>\n\n<p>It's short and it complies with what many people would expect: a concatenation. By explicitly mentioning the original variable again, many people might think it is a different variable before looking at it more closely.</p>\n\n<p>Additionally, you might also want to add a <code>StringBuilder</code> to the reading of the file. Even if the inputfile isn't that big, it would still be consistent.</p>\n\n<h1>Magic values</h1>\n\n<p>Consider this code:</p>\n\n<pre><code>for (int i = 0; i < lastString.length(); i += 8) {\n result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));\n}\n</code></pre>\n\n<p>Can someone other than the authro tell with certainty what the value <code>8</code> is? An educated guess would lead to the bit representation of 2 bytes, but we shouldn't have to guess that. Get rid of this so called \"magic value\" by adding a variable which clears it up:</p>\n\n<pre><code>int amountOfBits = 8;\nfor (int i = 0; i < lastString.length(); i += amountOfBits ) {\n result.append((char) Integer.parseInt(lastString.substring(i, i + amountOfBits ), 2));\n}\n</code></pre>\n\n<h1>Exception handling</h1>\n\n<p>You're completely bypassing exception handling. I'm assuming this is just so this contrived sample wouldn't get cluttered with code, but just in case it isn't:</p>\n\n<pre><code>throws Exception\n</code></pre>\n\n<p>is always a bad idea in an actual program. You should catch the <em>exact</em> exception and handle it appropriately. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:23:11.407",
"Id": "46082",
"ParentId": "46080",
"Score": "12"
}
},
{
"body": "<p>Because of the result String being of a size that can be pre-determined, and you are handling chars on the way, I would use a <code>char[]</code> (char array), and transforming the char array to a String using a String constructor.</p>\n\n<p>I believe this is more efficient than using a <code>StringBuilder</code> or any other approach.</p>\n\n<pre><code>String lastString = \"0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100\";\nchar[] result = new char[lastString.length() / 8];\nfor (int i = 0; i < lastString.length(); i += 8) {\n String sub = lastString.substring(i, i + 8);\n result[i / 8] = (char) Integer.parseInt(sub, 2);\n}\nSystem.out.println(new String(result));\n</code></pre>\n\n<p>You could also store the resulting string length in a variable, and switch the <code>i</code> variable to only iterate from 0 to the resulting string length.</p>\n\n<pre><code>String lastString = \"0100100001100101011011000110110001101111001000000101011101101111011100100110110001100100\";\nint resultLength = lastString.length() / 8;\nchar[] result = new char[resultLength];\nfor (int i = 0; i < resultLength; i++) {\n String sub = lastString.substring(i * 8, (i + 1) * 8);\n result[i] = (char) Integer.parseInt(sub, 2);\n}\nSystem.out.println(new String(result));\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:32:22.283",
"Id": "46084",
"ParentId": "46080",
"Score": "3"
}
},
{
"body": "<p>In adition to everything else being said, I would like to point out that your tabbing is done incorrectly, and would look much sexier like this</p>\n\n<pre><code>import java.io.File;\nimport java.util.Scanner;\n\n/**\n * @author Tumpi\n */\npublic class DN6 {\n public static void main(String[] args)\n throws Exception {\n\n File file = new File(\"sporocilo.txt\");\n\n Scanner sc = new Scanner(file);\n String lastString = \"\";\n\n while (sc.hasNextLine()) {\n String line = sc.nextLine();\n lastString = lastString + line;\n }\n\n StringBuffer result = new StringBuffer();\n for (int i = 0; i < lastString.length(); i += 8) {\n result.append((char) Integer.parseInt(lastString.substring(i, i + 8), 2));\n }\n System.out.println(result);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:42:22.220",
"Id": "46085",
"ParentId": "46080",
"Score": "4"
}
},
{
"body": "<ul>\n<li><p>You absolutely must close that Scanner.</p></li>\n<li><p>This snippet</p></li>\n</ul>\n\n<p>The scanner loop</p>\n\n<pre><code>while (sc.hasNextLine()) {\n String line = sc.nextLine();\n lastString = lastString + line;\n}\n</code></pre>\n\n<p>creates a new String Object every time it loops. I also have no idea of how large you file is, but this will ultimately read the entire file into memory.\nIn fact if you want to fully build lastString as you do here, you're better of using a <code>StringBuilder</code>.</p>\n\n<ul>\n<li>Can you avoid <code>StringBuffer</code> (and <code>StringBuilder</code>)? Well, certainly. You can handle the file character by character, and print everything to the <code>System.out</code> character by character as well :</li>\n</ul>\n\n<p>example :</p>\n\n<pre><code>public static void main(String[] args) {\n\n File file = new File(\"sporocilo.txt\");\n\n try (Reader reader = new InputStreamReader(new FileInputStream(file))) {\n int c = 0;\n int count = 0;\n for (int readChar = reader.read(); readChar != -1; readChar = reader.read()) {\n switch (readChar) {\n case '0':\n case '1':\n c <<= 1;\n c |= readChar - '0';\n count++;\n break;\n default:\n }\n if (count == 8) {\n System.out.print((char) c);\n c = 0;\n count = 0;\n }\n }\n System.out.println();\n } catch (IOException e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:55:21.160",
"Id": "80518",
"Score": "0",
"body": "Filling a `char[]` array is generally more efficient than calling `.read()` to fetch a character at a time. Correctly implementing the array version is tricker, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:10:52.193",
"Id": "80619",
"Score": "0",
"body": "True, if performance turns out to be problematic, that may be a possible refactoring."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:13:11.383",
"Id": "80621",
"Score": "0",
"body": "I wouldn't call that [refactoring](http://refactoring.com) — just rewriting."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:09:07.737",
"Id": "46090",
"ParentId": "46080",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46082",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T17:59:43.603",
"Id": "46080",
"Score": "10",
"Tags": [
"java",
"strings"
],
"Title": "Read and convert binary files to ASCII text"
} | 46080 |
<p>I was asked to create a test APK file by a company HR when I applied for an Android developers job,</p>
<p>Specification:</p>
<blockquote>
<p>The goal is to develop a simple application which finds the local
restaurants. The application will contain 2 screens:</p>
<p>A list of nearby restaurants within 1 mile radius A map that shows the
restaurants and their location The application should be able to work
in an offline mode showing the latest places found so far (even if
these are outside the 1 mile radius). In addition, the user must have
an option to refresh the data regardless of the screen he currently
sees.</p>
<p>In order to get restaurant information please use the Google Places
API.</p>
</blockquote>
<p>I put in my best effort and created the app and when I emailed them the source code, I was given the following feedback:</p>
<blockquote>
<p>The team felt you didn't have enough knowledge about Android in
general - you use some slow ways to send data inside the application,
don't know the design guidelines for Android and provided an
application that looks like an IOS clone. We are not asking people to
do beautiful applications but implementing things that Google says
never do on Android is certainly a negative point during review.</p>
</blockquote>
<p>I think that the above comments are a bit rude and unreasonable. Could an experienced Android developer PLEASE review my code and let me know if these comments are true and where have I done wrong!</p>
<p>This has completely ruined my day, and I am feeling very depressed that my code and knowledge of Android has been rated that bad.</p>
<p><strong>RestaurantsActivity.java</strong></p>
<pre><code>RestaurantsActivity extends FragmentActivity implements
RestaurantListFragment.Contract {
private final static String TAG = RestaurantsActivity.class.getSimpleName();
private static final String TAG_LEFT_FRAG = "info_headers";
private RestaurantListFragment left_frag = null;
private DatabaseHelper mDBHelper = null;
private Boolean isInternetPresent = false;
private ConnectionDetector connectionDetector;
GooglePlaces googlePlaces;
GPSTracker gpsTracker;
ProgressDialog pDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.info_sub_system_main);
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
mDBHelper = new DatabaseHelper(RestaurantsActivity.this);
connectionDetector = new ConnectionDetector(getApplicationContext());
// Check if Internet present
isInternetPresent = connectionDetector.isConnectingToInternet();
if (!isInternetPresent) {
Toast.makeText(this, "Internet connection unavailable", Toast.LENGTH_SHORT).show();
}
gpsTracker = new GPSTracker(this);
if (gpsTracker.canGetLocation()) {
Log.d("Your Location", "latitude:" + gpsTracker.getLatitude() + ", longitude: "
+ gpsTracker.getLongitude());
new LoadPlaces().execute();
} else {
Toast.makeText(
RestaurantsActivity.this,
"Couldn't get location information. Please enable GPS \nWill use cached data from previous search if available",
Toast.LENGTH_LONG).show();
}
left_frag = (RestaurantListFragment)getSupportFragmentManager().findFragmentByTag(
TAG_LEFT_FRAG);
if (left_frag == null) {
left_frag = new RestaurantListFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.info_header_mainfrag, left_frag, TAG_LEFT_FRAG).commit();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
@Override
public void onRestaurantSelected(Place place) {
if (place != null) {
Intent detailsIntent = new Intent(getApplicationContext(),
RestaurantDetailActivity.class);
detailsIntent.putExtra("reference", place.getRef());
detailsIntent.putExtra("name", place.getName());
detailsIntent.putExtra("formatted_address", place.getFormattedAddress());
detailsIntent.putExtra("formatted_phone_number", place.getPhone());
detailsIntent.putExtra("lat", place.getLatitudeAsString());
detailsIntent.putExtra("lng", place.getLongitudeAsString());
startActivity(detailsIntent);
}
}
@Override
public boolean isPersistentSelection() {
return false;
}
@Override
public void onDestroy() {
super.onDestroy();
mDBHelper.close();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ab_map:
startActivity(new Intent(RestaurantsActivity.this, ShowPlacesOnMapActivity.class));
return true;
case R.id.ab_search:
new LoadPlaces().execute();
return true;
}
return false;
}
class LoadPlaces extends AsyncTask<String, String, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RestaurantsActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Boolean doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
String types = "cafe|restaurant";
double radius = 1600; // 1 mile (in meters)
List<Place> listPlace = googlePlaces.search(gpsTracker.getLatitude(),
gpsTracker.getLongitude(), radius, types);
if (listPlace != null && listPlace.size() > 0) {
for (Place p : listPlace) {
Place place = googlePlaces.getPlaceDetails(p.getRef());
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.UNIQUEID, place.getId());
cv.put(DatabaseHelper.REFERENCE, place.getRef());
cv.put(DatabaseHelper.NAME, place.getName());
cv.put(DatabaseHelper.ADDRESS, place.getFormattedAddress());
cv.put(DatabaseHelper.PHONE, place.getPhone());
cv.put(DatabaseHelper.LAT, place.getLatitude());
cv.put(DatabaseHelper.LNG, place.getLongitude());
mDBHelper.getWritableDatabase().replace(DatabaseHelper.TABLE, null, cv);
}
}
return true;
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return false;
}
@Override
protected void onPostExecute(Boolean success) {
pDialog.dismiss();
if (success) {
if (left_frag != null && left_frag.isVisible()) {
Log.d(TAG, "Calling fillListView after FETCHING");
left_frag.fillListView();
}
} else {
Toast.makeText(RestaurantsActivity.this, "Sorry error occured.", Toast.LENGTH_SHORT)
.show();
}
}
}
</code></pre>
<p><strong>RestaurantListFragment.java</strong></p>
<pre><code>public class RestaurantListFragment extends ContractListFragment<RestaurantListFragment.Contract> {
static private final String STATE_CHECKED = "com.example.restaurantsnearby.STATE_CHECKED";
private PlacesAdapter adapter = null;
private String TAG = RestaurantListFragment.class.getSimpleName();
@Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
setHasOptionsMenu(true);
getListView().setSelector(R.drawable.list_selector);
getListView().setDrawSelectorOnTop(false);
fillListView();
if (state != null) {
int position = state.getInt(STATE_CHECKED, -1);
Log.d(TAG + "List View Item Position = ", String.valueOf(position));
if (position > -1) {
getListView().setItemChecked(position, true);
}
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.info_header_listview, container, false);
return view;
}
@Override
public void onDestroyView() {
super.onDestroyView();
setListAdapter(null);
}
@Override
public void onResume() {
Log.d(TAG, "onResume Called");
super.onResume();
//fillListView();
}
public void fillListView() {
Log.d(TAG, "fillListView Called");
if (getListView().getAdapter() == null) {
Log.d(TAG, "SETTING ADAPTER");
adapter = new PlacesAdapter(fetchFromDB());
setListAdapter(adapter);
} else {
Log.d(TAG, "REFILLING ADAPTER");
adapter.refill(fetchFromDB());
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (getContract().isPersistentSelection()) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
l.setItemChecked(position, true);
} else {
getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
}
Log.d(TAG, ((Place) this.getListAdapter().getItem(position-1)).getRef());
getContract().onRestaurantSelected(((Place) this.getListAdapter().getItem(position-1)));
}
@Override
public void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
if (getView() != null) {
state.putInt(STATE_CHECKED, getListView().getCheckedItemPosition());
}
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.ab_view, menu);
}
private List<Place> fetchFromDB() {
Cursor cursor = null;
List<Place> list = new ArrayList<Place>();
try {
DatabaseHelper dbHelper = new DatabaseHelper(getActivity());
cursor = dbHelper.getReadableDatabase().rawQuery(
"SELECT * FROM " + DatabaseHelper.TABLE, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Place place = new Place();
place.setId(cursor.getString(cursor.getColumnIndex(DatabaseHelper.UNIQUEID)));
place.setRef(cursor.getString(cursor.getColumnIndex(DatabaseHelper.REFERENCE)));
place.setName(cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME)));
place.setFormattedAddress(cursor.getString(cursor.getColumnIndex(DatabaseHelper.ADDRESS)));
place.setPhone(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PHONE)));
place.setLatitude(cursor.isNull(cursor.getColumnIndex(DatabaseHelper.LAT)) ? 0 : cursor.getDouble(cursor.getColumnIndex(DatabaseHelper.LAT)));
place.setLongitude(cursor.isNull(cursor.getColumnIndex(DatabaseHelper.LNG)) ? 0 : cursor.getDouble(cursor.getColumnIndex(DatabaseHelper.LNG)));
list.add(place);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, e.toString());
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return list;
}
// LIST ADAPTER BEGIN
class PlacesAdapter extends ArrayAdapter<Place> {
PlacesAdapter(List<Place> placesList) {
super(getActivity(), R.layout.info_header_row, R.id.restaurant_name, placesList);
Log.d(TAG + " PlacesAdapter List Size = ", String.valueOf(placesList.size()));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PlacesViewHolder wrapper = null;
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.info_header_row,
null);
wrapper = new PlacesViewHolder(convertView, getActivity());
convertView.setTag(wrapper);
} else {
wrapper = (PlacesViewHolder)convertView.getTag();
}
wrapper.populateFrom(getItem(position));
return (convertView);
}
@TargetApi(11)
public void refill(List<Place> placesList) {
adapter.clear();
if (placesList != null) {
Log.d(TAG + "REFILL ADAPTER List Size = ", String.valueOf(placesList.size()));
// If the platform supports it, use addAll
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
adapter.addAll(placesList);
} else {
for (Place place : placesList) {
adapter.add(place);
}
}
} else{
Log.d(TAG , "PLACES LIST IS NULL");
}
notifyDataSetChanged();
Log.d("notifyDataSetChanged();", "CALLED");
}
}
interface Contract {
void onRestaurantSelected(Place place);
boolean isPersistentSelection();
}
}
</code></pre>
<p><strong>ShowPlacesOnMapActivity.java</strong></p>
<pre><code>public class ShowPlacesOnMapActivity extends Activity {
// Google Map
private GoogleMap googleMap;
private DatabaseHelper mDBHelper = null;
@SuppressWarnings("unused")
private Boolean isInternetPresent = false;
private ConnectionDetector connectionDetector;
GooglePlaces googlePlaces;
GPSTracker gpsTracker;
ProgressDialog pDialog;
private final String TAG = ShowPlacesOnMapActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.map_places);
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
mDBHelper = new DatabaseHelper(ShowPlacesOnMapActivity.this);
connectionDetector = new ConnectionDetector(getApplicationContext());
isInternetPresent = connectionDetector.isConnectingToInternet();
gpsTracker = new GPSTracker(this);
try {
initilizeMap();
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setZoomGesturesEnabled(true);
List<Place> placeList = fetchFromDB();
if (placeList.size() <= 0) {
finish();
}
Double lastLat = 0.0;
Double lastLng = 0.0;
for (Place place : placeList) {
lastLat = place.getLatitude();
lastLng = place.getLongitude();
if (lastLat + lastLng != 0) {
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(lastLat, lastLng)).title(place.getName())
.snippet(place.getFormattedAddress());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
googleMap.addMarker(marker);
}
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lastLat, lastLng)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
@Override
protected void onResume() {
super.onResume();
initilizeMap();
}
@SuppressLint("NewApi")
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(), "Sorry! unable to create maps",
Toast.LENGTH_SHORT).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.ab_view_map, menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.ab_search:
// check if GPS location can get
if (gpsTracker.canGetLocation()) {
Log.d("Your Location", "latitude:" + gpsTracker.getLatitude() + ", longitude: "
+ gpsTracker.getLongitude());
new LoadPlaces().execute();
} else {
// Can't get user's current location
Toast.makeText(
ShowPlacesOnMapActivity.this,
"Couldn't get location information. Please enable GPS \nWill use cached data from previous search if available",
Toast.LENGTH_LONG).show();
}
return true;
}
return false;
}
private List<Place> fetchFromDB() {
Cursor cursor = null;
List<Place> list = new ArrayList<Place>();
try {
DatabaseHelper dbHelper = new DatabaseHelper(ShowPlacesOnMapActivity.this);
cursor = dbHelper.getReadableDatabase().rawQuery(
"SELECT * FROM " + DatabaseHelper.TABLE, null);
if (cursor != null && cursor.moveToFirst()) {
do {
Place place = new Place();
place.setId(cursor.getString(cursor.getColumnIndex(DatabaseHelper.UNIQUEID)));
place.setRef(cursor.getString(cursor.getColumnIndex(DatabaseHelper.REFERENCE)));
place.setName(cursor.getString(cursor.getColumnIndex(DatabaseHelper.NAME)));
place.setFormattedAddress(cursor.getString(cursor
.getColumnIndex(DatabaseHelper.ADDRESS)));
place.setPhone(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PHONE)));
place.setLatitude(cursor.isNull(cursor.getColumnIndex(DatabaseHelper.LAT)) ? 0
: cursor.getDouble(cursor.getColumnIndex(DatabaseHelper.LAT)));
place.setLongitude(cursor.isNull(cursor.getColumnIndex(DatabaseHelper.LNG)) ? 0
: cursor.getDouble(cursor.getColumnIndex(DatabaseHelper.LNG)));
list.add(place);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d(TAG, e.toString());
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return list;
}
@Override
public void onDestroy() {
super.onDestroy();
mDBHelper.close();
}
class LoadPlaces extends AsyncTask<String, String, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ShowPlacesOnMapActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places JSON
*/
@Override
protected Boolean doInBackground(String... args) {
// creating Places class object
googlePlaces = new GooglePlaces();
try {
String types = "cafe|restaurant"; // Listing places only cafes,
double radius = 1600; // 1 mile (in meters)
// get nearest places
List<Place> listPlace = googlePlaces.search(gpsTracker.getLatitude(),
gpsTracker.getLongitude(), radius, types);
if (listPlace != null && listPlace.size() > 0) {
for (Place p : listPlace) {
Place place = googlePlaces.getPlaceDetails(p.getRef());
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.UNIQUEID, place.getId());
cv.put(DatabaseHelper.REFERENCE, place.getRef());
cv.put(DatabaseHelper.NAME, place.getName());
cv.put(DatabaseHelper.ADDRESS, place.getFormattedAddress());
cv.put(DatabaseHelper.PHONE, place.getPhone());
cv.put(DatabaseHelper.LAT, place.getLatitude());
cv.put(DatabaseHelper.LNG, place.getLongitude());
mDBHelper.getWritableDatabase().replace(DatabaseHelper.TABLE, null, cv);
}
}
return true;
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return false;
}
@Override
protected void onPostExecute(Boolean success) {
pDialog.dismiss();
if (success) {
List<Place> placeList = fetchFromDB();
if (placeList.size() <= 0) {
finish();
}
Double lastLat = 0.0;
Double lastLng = 0.0;
for (Place place : placeList) {
lastLat = place.getLatitude();
lastLng = place.getLongitude();
if (lastLat + lastLng != 0) {
MarkerOptions marker = new MarkerOptions()
.position(new LatLng(lastLat, lastLng)).title(place.getName())
.snippet(place.getFormattedAddress());
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
googleMap.addMarker(marker);
}
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lastLat, lastLng)).zoom(15).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
} else {
Toast.makeText(ShowPlacesOnMapActivity.this, "Sorry error occured.",
Toast.LENGTH_SHORT).show();
}
}
}
}
</code></pre>
<p><strong>GooglePlaces.java</strong></p>
<pre><code>public class GooglePlaces {
// Google API Key
//private static final String API_KEY = "MY GOOGLE KEY GOES HERE"; // Android
private static final String API_KEY = "MY GOOGLE KEY GOES HERE"; // Browser
private static final String TAG = GooglePlaces.class.getSimpleName();
// Google Places serach url's
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";
@SuppressWarnings("unused")
private double _latitude;
@SuppressWarnings("unused")
private double _longitude;
private double _radius;
/**
* Searching places
* @param latitude - latitude of place
* @params longitude - longitude of place
* @param radius - radius of searchable area
* @param types - type of place to search
* @return list of places
* */
public List<Place> search(double latitude, double longitude, double radius, String types)
throws Exception {
this._latitude = latitude;
this._longitude = longitude;
this._radius = radius;
StringBuilder urlString = new StringBuilder(
PLACES_SEARCH_URL);
urlString.append("&location=");
urlString.append(Double.toString(latitude));
urlString.append(",");
urlString.append(Double.toString(longitude));
urlString.append("&radius=" + _radius);
urlString.append("&types=" + types);
urlString.append("&sensor=false&key=" + API_KEY);
Log.d(TAG, urlString.toString());
try {
String json = getJSON(urlString.toString());
Log.d(TAG, json);
JSONObject object = new JSONObject(json);
JSONArray array = object.getJSONArray("results");
List<Place> arrayList = new ArrayList<Place>();
for (int i = 0; i < array.length(); i++) {
try {
Place place = Place
.jsonToPontoReferencia((JSONObject) array.get(i),false);
Log.d("Places Services ", "" + place);
arrayList.add(place);
} catch (Exception e) {
Log.d(TAG, e.toString());
}
}
return arrayList;
} catch (JSONException ex) {
Logger.getLogger(GooglePlaces.class.getName()).log(Level.SEVERE,
null, ex);
}
return null;
}
/**
* Searching single place full details
* @param refrence - reference id of place
* - which you will get in search api request
* */
public Place getPlaceDetails(String reference) throws Exception {
StringBuilder urlString = new StringBuilder(
PLACES_DETAILS_URL);
urlString.append("&reference=" + reference);
urlString.append("&sensor=false&key=" + API_KEY);
Log.d(TAG, urlString.toString());
Place place = new Place();
try {
String json = getJSON(urlString.toString());
JSONObject object = new JSONObject(json);
JSONObject result=object.getJSONObject("result");
place = Place.jsonToPontoReferencia(result, true);
return place;
} catch (JSONException ex) {
Logger.getLogger(GooglePlaces.class.getName()).log(Level.SEVERE,
null, ex);
}
return null;
}
protected String getJSON(String url) {
return getUrlContents(url);
}
private String getUrlContents(String theUrl) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theUrl);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()), 8);
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
}catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
</code></pre>
<p>The other classes are for checking data connectivity and gps.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:19:07.963",
"Id": "80407",
"Score": "0",
"body": "I don't know much about API key, but you do know that they are now public, since they are in the code (just want to make if those key are suppose to be private, they should be remove)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:21:39.173",
"Id": "80409",
"Score": "0",
"body": "Thanks Marc-Andre, I have commented out my google api keys."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:07:03.560",
"Id": "80419",
"Score": "1",
"body": "@user1957341 Do know that they are still visible in the history of the post, you should revoke those keys and get new one for your private use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:13:40.703",
"Id": "80598",
"Score": "0",
"body": "Hi guys, so could someone let me know if I have done something really wrong in the above code? Specifically something that Google says never to do on Android?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:15:32.000",
"Id": "80601",
"Score": "0",
"body": "Anything that could justify the statement \"You use some slow ways to send data inside the application, don't know the design guidelines for Android\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:58:17.813",
"Id": "80789",
"Score": "0",
"body": "Hmmm, as far as I understand their writing… they seem to not only have had a problem with your project because it didn't fit [some fundamentals](http://developer.android.com/guide/components/fundamentals.html), but also – more important – they say your project did not fit the [Android design guidelines](http://developer.android.com/design/index.html). That later point represents a real neck-breaker! The fact they mention your app looked like an iOS clone even underlines the fact that the failure to adhere to Android design guidelines was one of the main reasons to reject the submitted project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:29:19.423",
"Id": "81017",
"Score": "0",
"body": "@e-sushi, Thanks for taking time and replying, The requirement was to write a simple app which is what I did and it worked well too in meeting the requirements, however I still fail to understand where I have failed in the design guidelines or fundamentals? They wanted a list and a map (two activities) I dont understand why did the iOS clone come in? When I requested them for feedback as to where I went wrong, they are not bothered to reply back, if I have broken the said rules, they should not be difficult to point out!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:41:37.050",
"Id": "81020",
"Score": "1",
"body": "I certainly agree with you that they should have - at least - given you a bit more feedback upon your request... OTOH it's Google - my personal experience with them shows you shouldn't expect them to bother with anything if it's not in their interest. A shame actually, but who am I to judge their company policies? ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T15:08:08.637",
"Id": "83637",
"Score": "0",
"body": "You had to spend quite a lot of time creating the application, therefore I would expect that the company would provide you with propper feedback. Anyway, you should post your code in smaller pieces, because posting hundreds of lines of code is pretty hard to review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-02T14:40:42.670",
"Id": "262769",
"Score": "0",
"body": "@redbridge Just FYI, mods are able to remove things from history, so in the future if the key is something that can't be revoked (like a personal phone number) then you can get a mod you purge it from history. Of course whoever saw will still have seen it, but it's better than nothing."
}
] | [
{
"body": "<ol>\n<li><p><code>GooglePlaces.search</code> could return empty list instead of <code>null</code>. It would save you a few <code>null</code> checks in clients. (<em>Effective Java, Second Edition</em>, <em>Item 43: Return empty arrays or collections, not nulls</em>)</p></li>\n<li><p>Be careful about <code>Double.toString</code>:</p>\n\n<blockquote>\n<pre><code>urlString.append(\"&location=\");\nurlString.append(Double.toString(latitude));\nurlString.append(\",\");\nurlString.append(Double.toString(longitude));\n</code></pre>\n</blockquote>\n\n<p><code>Double.toString(0.000974)</code> returns <code>9.74E-4</code> which might not be what you want. (Google Maps might or might not handle it.)</p></li>\n</ol>\n\n<h2>RestaurantListFragment</h2>\n\n<ol>\n<li><p><code>list</code> could be renamed to <code>result</code> to express its purpose.</p></li>\n<li><p><code>list</code> could have a smaller scope. (<em>Effective Java, Second Edition</em>, <em>Item 45: Minimize the scope of local variables</em> It has a good overview on the topic.)</p></li>\n<li><p>You could use <a href=\"https://stackoverflow.com/a/18875101/843804\">only a while loop and <code>cursor.moveToNext()</code></a> to iterate over the cursor.</p></li>\n<li><p>Guard clauses makes the code <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow noreferrer\">flatten</a>.</p></li>\n<li><p>You could remove some duplication with a helper method:</p>\n\n<pre><code>private String getString(Cursor cursor, String attributeName) {\n return cursor.getString(cursor.getColumnIndex(attributeName));\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>place.setId(getString(cursor, DatabaseHelper.UNIQUEID));\nplace.setRef(getString(cursor, DatabaseHelper.REFERENCE));\n...\n</code></pre></li>\n<li><p>Here is another one:</p>\n\n<pre><code>private double getDoubleWithDefault(Cursor cursor, String attributeName, \n double defaultValue) {\n if (cursor.isNull(cursor.getColumnIndex(attributeName))) {\n return defaultValue;\n }\n return cursor.getDouble(cursor.getColumnIndex(attributeName));\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>place.setLatitude(getDoubleWithDefault(cursor, DatabaseHelper.LAT, 0));\nplace.setLongitude(getDoubleWithDefault(cursor, DatabaseHelper.LNG, 0));\n</code></pre></li>\n</ol>\n\n<p>Here is an improved version of <code>fetchFromDB</code>:</p>\n\n<pre><code>private List<Place> fetchFromDB() {\n Cursor cursor = null;\n try {\n DatabaseHelper dbHelper = new DatabaseHelper(getActivity());\n cursor = dbHelper.getReadableDatabase().rawQuery(\"SELECT * FROM \" \n + DatabaseHelper.TABLE, null);\n if (cursor == null) {\n return Collections.emptyList();\n }\n List<Place> list = new ArrayList<Place>();\n while (cursor.moveToNext()) {\n Place place = new Place();\n place.setId(getString(cursor, DatabaseHelper.UNIQUEID));\n place.setRef(getString(cursor, DatabaseHelper.REFERENCE));\n place.setName(getString(cursor, DatabaseHelper.NAME));\n place.setFormattedAddress(getString(cursor, DatabaseHelper.ADDRESS));\n place.setPhone(cursor.getString(cursor.getColumnIndex(DatabaseHelper.PHONE)));\n place.setLatitude(getDoubleWithDefault(cursor, DatabaseHelper.LAT, 0));\n place.setLongitude(getDoubleWithDefault(cursor, DatabaseHelper.LNG, 0));\n list.add(place);\n }\n return list;\n } catch (Exception e) {\n Log.d(TAG, e.toString());\n return Collections.emptyList();\n } finally {\n if (cursor != null && !cursor.isClosed()) {\n cursor.close();\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:32:29.940",
"Id": "81018",
"Score": "0",
"body": "Thank you very much for reviewing my in depth, and I shall make a note of all your points and try to implement them in future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T13:38:04.870",
"Id": "81019",
"Score": "0",
"body": "Do you agree with the comments that I have not followed the android fundamentals and broken the design patters that one has to follow? I am sure that the task could be achieved more efficiently and cleaner, I will happily accept my errors if they are clearly pointed out, and If I have broken the minimum fundamental rules and design patterns then it should be obvious and glaring in the face."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T14:23:20.643",
"Id": "81027",
"Score": "1",
"body": "@redbridge: I can't say too much, I'm not familiar with Android development. You might get more reviews later. If not, there are at least two things you could do. 1. Place a bounty on the question. Unfortunately you don't have enough reputation for that yet. 2. Fix the issues mentioned above and post a follow-up question (or mabye more later) (http://meta.codereview.stackexchange.com/q/1065/7076). Try to post less code, currently it looks too much. It's easier to review shorter questions and they usually get more reviews."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T01:39:49.493",
"Id": "46341",
"ParentId": "46086",
"Score": "8"
}
},
{
"body": "<p>The worst thing you are doing that I am able to see by skimming through your code is this: you read from the database on the main thread instead of using the <a href=\"http://developer.android.com/guide/components/loaders.html\">Loader API</a>. In general, this is discouraged, because it may render the application UI unresponsive, depending on the amount of work the underlying database must perform to satisfy your query. You indeed perform database writing on a different thread, precisely an <code>AsyncTask</code>, but given that reads are on the main thread I would maintain that the writing-on-another-thread just happened by chance, not by design.</p>\n\n<p>Besides, some nitpicking: you call a field <code>left_frag</code>, which not only is a meaningless label, but also violates the naming conventions in the Java language. This would have made me suspicious of your general experience with the language. I'm also curious as to why you are using <code>TAG_LEFT_FRAG</code> instead of declaring <code>RestaurantListFragment.TAG</code> public and using it.</p>\n\n<p>As far as the iOS look is concerned, this is really impossible to judge unless you provide a couple of screenshots.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T15:04:16.277",
"Id": "83636",
"Score": "0",
"body": "Thanks @Giulio, Cursor Loader makes a lot of sense. This was a quick demo that I had to write but still your points are very valid, I shall bear that in mind, Thanks for your time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-20T13:57:15.650",
"Id": "47716",
"ParentId": "46086",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:50:25.997",
"Id": "46086",
"Score": "9",
"Tags": [
"java",
"android",
"interview-questions",
"geospatial",
"google-maps"
],
"Title": "Simple application for finding local restaurants"
} | 46086 |
<p>The following is some code I just wrote. I keep wondering as always what I can do to make this more efficient. Please help me make this code object oriented and if anyone could help me write automated or even non automated tests for my widget... </p>
<p>Also is this considered a closure? I don't think it is but I would love to know how to produce better quality/reusable code. Oh- bonus points for any corrections to my techniques used as well. I'm really trying to step my JS game up and I know it needs work... </p>
<pre><code>var ExplodedContentWidget = $('[data-widget~="exploded-content"]');
// search for existance of the exploded widget in DOM
if (ExplodedContentWidget[0]){
var ExplodedDefaultEl = $('[data-function~="default-state"]');
var ExplodedEl = $('[data-function~="exploded-state-1"]');
var ExplodedEl2 = $('[data-function~="exploded-state-2"]');
var CloseButton = $('.button-close');
ExplodedEl.hide(); // default exploded content is hidden
ExplodedEl2.hide();
CloseButton.hide();
ExplodedContentWidget.on('click',function(){
ExplodedEl.slideToggle('slow');
});
var FullScreenViewButton = $('button');
FullScreenViewButton.on('click',function(){
ExplodedDefaultEl.hide();
ExplodedContentWidget.addClass('exploded-fullscreen-state');
ExplodedEl2.slideToggle('slow');
CloseButton.fadeIn();
ExplodedEl2.on('click',function(){
ExplodedContentWidget.removeClass('exploded-fullscreen-state');
ExplodedDefaultEl.show();
ExplodedEl.toggle();
ExplodedEl2.toggle();
CloseButton.hide();
});
});
}
</code></pre>
<p><a href="http://jsfiddle.net/J49Q9/2/" rel="nofollow">PS: Here is the fiddle</a></p>
| [] | [
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>Do not use <code>data-function~=\"exploded-state-1\"</code>, instead assign id's and search by id, this is the common ( and faster, better ) approach</li>\n<li>One single <code>var</code> statement with comma separated variables is considered better</li>\n<li>I would go for <code>if (ExplodedContentWidget.length){</code> instead of <code>if (ExplodedContentWidget[0]){</code></li>\n<li>Variable names should follow lowerCamelCase so <code>ExplodedEl</code> -> <code>explodedEl</code>, the exception to that is for jQuery results so you could also use <code>$exploded1</code></li>\n<li><p>This : </p>\n\n<pre><code>ExplodedEl.hide(); // default exploded content is hidden\nExplodedEl2.hide();\nCloseButton.hide();\n</code></pre>\n\n<p>I would have addressed with a css class that hides these elements</p></li>\n<li>You indent the code after <code>var FullScreenViewButton = $('button');</code>, dont do that. Consider using the jsbeautifier website</li>\n<li><code>$('button');</code> <- This is code waiting to go wrong, what if you have more than 1 button. Give the button an id, and select on that id</li>\n<li><p>Your code passes JsHint.com nicely, well done</p></li>\n<li><p><em>Also is this considered a closure?</em> Your inline functions for <code>.on('click'</code> are closures.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:24:51.010",
"Id": "80410",
"Score": "0",
"body": "Thanks, I appreciate the help! The button was generic on purpose good point though! That would be a production nightmare haha? Any luck on how I could make this function pass object oriented?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:37:52.063",
"Id": "80413",
"Score": "0",
"body": "Making it OO is a different ball of wax, I am afraid we don't re-write code, we *just* review it and sometimes propose an alternative way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:58:08.127",
"Id": "80416",
"Score": "0",
"body": "is there another stackexchange outlet I should be asking this in? Im really just trying to gain the basic concept of this OOJS stuff and would love it if I could see how someone with advanced jquery/js skills would approach the module I have included"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:11:52.407",
"Id": "46091",
"ParentId": "46087",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T18:54:52.210",
"Id": "46087",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Object Oriented Modular Closure"
} | 46087 |
<p>I'm on chapter 7 of Chris Pine's book, trying to work on the last exercise in that chapter. This code works fine, but I'm wondering if there is a better way to do this...</p>
<pre><code>toc_array = ['Table of Contents', 'Chapter 1: Numbers', 'page 1', 'Chapter 2: Letters', 'page 72', 'Chapter 3: Variables', 'page 118']
linewidth = 30
puts toc_array[0].center(linewidth*2)
puts (toc_array[1].ljust(linewidth)) + (toc_array[1].rjust(linewidth))
puts (toc_array[2].ljust(linewidth)) + (toc_array[3].rjust(linewidth))
puts (toc_array[4].ljust(linewidth)) + (toc_array[5].rjust(linewidth))
</code></pre>
<p>Is there more efficient way to print the formatted array?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:13:59.630",
"Id": "80404",
"Score": "2",
"body": "What does this have to do with sorting (as indicated in the title)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:32:44.850",
"Id": "80411",
"Score": "0",
"body": "Elements of the array have to be sorted [0-5] and then formatted in a certain way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:36:06.647",
"Id": "80412",
"Score": "0",
"body": "They _are_ sorted, as far as I can tell. Heading, followed by chapters and page numbers in their proper order. All that's left is formatting"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:44:12.197",
"Id": "80414",
"Score": "0",
"body": "Please check that you got your array indexes right. The output looks suspiciously wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:01:56.033",
"Id": "80417",
"Score": "0",
"body": "There is no output in my message. If you do run it, it will print fine. Thanks for your reply."
}
] | [
{
"body": "<p>Your code is very brittle and hard-coded. Code is supposed to be as generic and flexible as possible so you could re-use it. A new chapter, a different layout, anything would require you to change the whole code.</p>\n\n<p>Code is about doing work <em>for you</em>. Think generically - can this code be used for a different book? (I don't mean by you copying it, pasting it and changing it...)</p>\n\n<p>You need to abstract it - what do you have here?</p>\n\n<p>You have a <code>title</code>, which is different than a <code>chapter</code>. A <code>chapter</code> has a <code>page number</code>. There are some chapters in a book. The TOC needs to be laid out using some logic...</p>\n\n<p><code>title</code> and <code>chapter</code> are <em>objects</em> is your system, the layout logic is a <em>method</em>.</p>\n\n<p>For example - I pass to a method called <code>format_toc</code> a title, and a list of chapters, which (for simplicity) contain their name and their page number in an array. The method than lays out the TOC page according to the format in your code. Note that the <em>data</em> does not contain the words <code>'Chapter'</code> or <code>'page'</code> - they are part of the layout, not the data:</p>\n\n<pre><code>def format_toc(title, chapters)\n line_width = 30\n toc = chapters.each_with_index.map do |chapter, i|\n \"Chapter #{i}: #{chapter[0]}\".ljust(line_width) + \"page #{chapter[1]}\".rjust(line_width)\n end.join(\"\\n\")\n \"#{title.center(line_width*2)}\\n#{toc}\"\nend\nputs format_toc 'Table of Contents', [['Numbers', 1], ['Letters', 72], ['Variables', 118]]\n#=> Table of Contents \n#=>Chapter 1: Numbers page 1\n#=>Chapter 2: Letters page 72\n#=>Chapter 3: Variables page 118\n</code></pre>\n\n<hr>\n\n<p><strong>But wait - you are still using hard-coded indexes!</strong><br>\nTrue, <code>[0]</code> and <code>[1]</code> are still there, which looks a little \"hard-coded\", but these indexes refer to the data <em>structure</em>, not the data itself. A more elaborate design would likely use a hash to hold chapter data (<code>{name: 'Numbers', page: 1}</code>), or even a class having two properties, but for the example above it shows the concept of <em>encapsulation</em> - as long as two modules know the <em>language</em> (=API), they can independently change things in their domain (wither adding chapters to the book, or change the layout), without affecting other parts of the code.</p>\n\n<p>I also took the liberty of changing the structure of the input, as @Flambino remarked, but only because I assumed the choice of the structure of the input was not an outside constraint, but a design choice (it didn't make much sense otherwise).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:16:38.357",
"Id": "80421",
"Score": "0",
"body": "Sorry, but -1 for the code: You still have a hard coded index, and you're changing the input array's \"format\" to suit your code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:29:04.370",
"Id": "80427",
"Score": "0",
"body": "Thank you, Uri. I liked the main concepts you mentioned in your answer. It never occurred to me to make layout a method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:15:46.710",
"Id": "80498",
"Score": "0",
"body": "@Flambino - see my addition to the answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:52:50.110",
"Id": "80505",
"Score": "0",
"body": "Read it, and must admit I was too quick on the trigger earlier - I apologize, and I've cancelled my downvote. For whatever reason, I read `chapter[i]` in one place, and `chapter[1]` in another, and assumed it was leftover code - that's what I meant by \"hard coded indexes\", but I simply misread it. As for changing the input data's structure, I assumed the opposite of you: that it was an outside constraint. I don't know. But I figured that was \"the challenge\" so to speak; otherwise the simplest solution is to structure the input to match the intended output and skip the code :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:46:32.557",
"Id": "46093",
"ParentId": "46088",
"Score": "3"
}
},
{
"body": "<p>Er, no, the code doesn't work fine. I get:</p>\n\n<pre><code> Table of Contents \nChapter 1: Numbers Chapter 1: Numbers\npage 1 Chapter 2: Letters\npage 72 Chapter 3: Variables\n</code></pre>\n\n<p>Chapters and page numbers are reversed (compared to a regular table of contents anyway), and chapter 1's page number isn't shown.</p>\n\n<p>Anyway, I assume you can figure out what array indices should be fixed.</p>\n\n<p>Point #2: <code>linewidth</code> is a bad name. It's exactly <em>half</em> of the desired linewidth.</p>\n\n<p>Point #3: DRY - Don't Repeat Yourself. Go read the documentation for <a href=\"http://www.ruby-doc.org/core-2.1.1/Array.html\" rel=\"nofollow\"><code>Array</code></a> and the <a href=\"http://www.ruby-doc.org/core-2.1.1/Enumerable.html\" rel=\"nofollow\"><code>Enumerable</code></a> module that's included in <code>Array</code>: You practically <em>never</em> have to manually copy lines and change indexes</p>\n\n<p>Given these inputs</p>\n\n<pre><code>toc_array = ['Table of Contents', 'Chapter 1: Numbers', 'page 1', 'Chapter 2: Letters', 'page 72', 'Chapter 3: Variables', 'page 118']\nline_width = 60\nhalf_line_width = line_width / 2\n</code></pre>\n\n<p>it's much easier to do this</p>\n\n<pre><code>puts toc_array.shift.center(line_width)\ntoc_array.each_slice(2) do |chapter, page|\n puts chapter.ljust(half_line_width) + page.rjust(half_line_width)\nend\n</code></pre>\n\n<p>which gives you</p>\n\n<pre><code> Table of Contents \nChapter 1: Numbers page 1\nChapter 2: Letters page 72\nChapter 3: Variables page 118\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:18:14.007",
"Id": "80423",
"Score": "0",
"body": "Ooo... there are many things there that I don't know yet. What are those (2) arguments in the array toc_array.each_slice(2)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:24:21.357",
"Id": "80426",
"Score": "0",
"body": "@user39963 See the the docs for `each_slice` (already linked in my answer). If you mean the two arguments for the block: [Destructuring](http://tony.pitluga.com/2011/08/08/destructuring-with-ruby.html). `each_slice(2)` loops over an array, 2 elements at a time, passing those elements to the block as a array. But because ruby let's you use destructuring, the two elements are assigned to `chapter` and `title` respectively."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:00:12.880",
"Id": "46096",
"ParentId": "46088",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46096",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:05:15.800",
"Id": "46088",
"Score": "-1",
"Tags": [
"ruby",
"formatting"
],
"Title": "Efficient way to sort a formatted array (Chris Pine book, ch 7)"
} | 46088 |
<p>I would like to test reliability of system <code>flock</code> in a multi-threaded and concurrent environment as some <a href="https://stackoverflow.com/a/2921596/223226">suggest that they are not reliable</a> (in comments).</p>
<p>Thus I wrote this code which requests non-blocking exclusive lock, with multiple threads at the same time (well, almost same time). </p>
<p>Is there better way to test flock mutex functionality, or how to be sure that it is always exclusive?</p>
<pre><code>use strict;
use warnings;
use autodie;
use threads;
use Time::HiRes qw(time sleep);
use Fcntl qw(:flock);
sub fo{ my $fh; open($fh, ">", pop) && $fh }
my $t = time();
my $one = grep $_->join,
map async {
my $f = fo("/tmp/flock.test");
sleep 2+$t-time();
my $l = flock($f, LOCK_EX|LOCK_NB);
sleep 1;
return $l;
}, 1..90;
# should always be 1
print "$one is 1\n";
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:32:40.820",
"Id": "80783",
"Score": "1",
"body": "Sorry, no. 1st: the [comment you are referring to](https://stackoverflow.com/questions/2921469/php-mutual-exclusion-mutex/2921596#comment5291305_2921596) is simply wrong. File locks are [mostly](http://perldoc.perl.org/perlport.html#flock) guaranteed to work, end of discussion. However, locks will generally be voluntary, and may not work on all filesystems. 2nd: locks are per-process, not per-thread. 3rd: I think you can write better code than that. Are you sure Code Review is the correct address? 4th: Your *actual* question is whether locks are reliable, and how to use them → ask on [so]."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:57:19.850",
"Id": "80788",
"Score": "0",
"body": "@amon tnx for comment; I was referring to OS&&FS on which they do work. Code above was my attempt to acquire more than one exclusive advisory lock (it did not happen). Do you have suggestion how to improve it?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:14:21.227",
"Id": "46092",
"Score": "1",
"Tags": [
"perl",
"file-system",
"locking",
"concurrency"
],
"Title": "Reliability of flock mutex (LOCK_EX|LOCK_NB)"
} | 46092 |
<p>I've currently got a MSSQL stored procedure that uses multiple SQL functions to achieve a number of returns. Now I've been told about using sets rather than functions as it creates " bad code smell of a DBA who is not yet thinking in sets" <a href="https://stackoverflow.com/questions/22808489/speeding-up-mssql-select-distinct-statement/22816252#22816252">Original Link</a></p>
<p>I'd like to better my code and love to know what sets are. So below are two of my functions from a long list of functions. Thanks to any that attempt the answer.</p>
<h2>Function that returns a long list of values</h2>
<pre><code>CREATE FUNCTION dbo.funcGetPropertyEnviListFR
(
@PropertyId AS INT
)
RETURNS VARCHAR(200)
AS
BEGIN
DECLARE @ENVIFR VARCHAR(200)
SET @ENVIFR = ''
SELECT
@ENVIFR = COALESCE(@ENVIFR + ', ', '') + ENVIRONMENT.FR
FROM
ENVIRONMENT
INNER JOIN
MATRIXPROPENVIRONMENT
ON
MATRIXPROPENVIRONMENT.EnvironmentId = ENVIRONMENT.id
WHERE
MATRIXPROPENVIRONMENT.PropertyId = @PropertyId
ORDER BY
Weight
SET @ENVIFR = SUBSTRING(@ENVIFR, 3, 200)
RETURN @ENVIFR
END
</code></pre>
<p><em>Result may look like</em> - <code>Coastal, Village, Habitat</code></p>
<h2>Function that returns a seller's ID</h2>
<pre><code>CREATE FUNCTION dbo.funcSellIdByPropId
(
@PropertyId AS INT
)
RETURNS INT
AS
BEGIN
DECLARE @ID AS INT
SET @ID = 0
SELECT
@ID = MATRIXAGENCYPROPERTY.AgencyId
FROM
MATRIXAGENCYPROPERTY
WHERE
MATRIXAGENCYPROPERTY.PropertyId = @PropertyId
IF @ID = 0
BEGIN
SELECT
@ID = PRIVATESELLERS.id
FROM
PRIVATESELLERS
WHERE
PRIVATESELLERS.PropertyId = @PropertyId
END
RETURN @ID
END
</code></pre>
<p><em>Result may look like</em> - <code>43</code></p>
<h2>Function that returns an image value from database</h2>
<pre><code>CREATE FUNCTION dbo.funcDefaultImage
(
@PropertyId INT,
@Position INT
)
RETURNS VARCHAR(50)
AS
BEGIN
DECLARE @IMAGE VARCHAR(50)
SELECT @IMAGE = T.image
FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY weight DESC) AS [rownum],
PROPERTYGALLERY.image
FROM
PROPERTYGALLERY
WHERE
PROPERTYGALLERY.PropertyId = @PropertyId
) T
WHERE
rownum = @Position
RETURN @IMAGE
END
</code></pre>
<p><em>Result may look like</em> - <code>property_0001.png</code></p>
| [] | [
{
"body": "<p>First goal in thinking in SQL (or thinking in sets) is to get rid of IF statements and Loops (or cursors). So for your 2nd function this is much better:</p>\n\n<pre><code>CREATE FUNCTION dbo.funcSellIdByPropId\n(\n@PropertyId AS INT\n)\nRETURNS INT\nAS\nBEGIN\n DECLARE @ID AS INT\n\n SELECT @ID = COALESCE(MATRIXAGENCYPROPERTY.AgencyId, PRIVATESELLERS.id, 0)\n FROM MATRIXAGENCYPROPERTY, PRIVATESELLERS\n WHERE MATRIXAGENCYPROPERTY.PropertyId = @PropertyId AND \n PRIVATESELLERS.PropertyId = @PropertyId\n\n RETURN @ID\nEND\n</code></pre>\n\n<p>This select can now be implemented as a view and then joined to any other select statement instead of calling a function.</p>\n\n<hr>\n\n<p>For the 3rd function you could implement a view like this:</p>\n\n<pre><code>SELECT\n PropertyId \n ROW_NUMBER() OVER (PARTITION BY PropertyId ORDER BY weight DESC) AS [imgnum],\n image\nFROM PROPERTYGALLERY\n</code></pre>\n\n<p>Now you can join on this view by PropertyId and imgnum instead of calling a function</p>\n\n<hr>\n\n<p>For your first function take a look at this answer I posted on <a href=\"https://stackoverflow.com/a/1785923/215752\">SO</a>. Using the XML generator like this is considered the fastest way to create a comma separated list in MS SQL. Like the others examples I've given here, this technique could be used in a view to create a list of comma separated values partitioned by PropertyId</p>\n\n<hr>\n\n<p>The key to both of these solutions is thinking in sets. Instead of solving one problem (as the function does) they solve all the problems. Then when you join to these queries you limit to just the data you need. </p>\n\n<p>SQL Engines love this -- their optimizers are designed to make this kind of process work really fast.</p>\n\n<hr>\n\n<p><strong>Detailed Example</strong> (see comments)</p>\n\n<p>First create the view:</p>\n\n<pre><code>-- MATRIXAGENCYPROPERTY.AgencyId and PRIVATESELLERS.id are mutually exclusive. \n-- Grab all of them with their PropertyID\nCREATE VIEW SellIDByPropertyID(ID, PropertyID) AS\n(\n SELECT AgencyId, PropertyID \n FROM MATRIXAGENCYPROPERTY\n UNION ALL\n SELECT ID, PropertyId\n FROM PRIVATESELLERS\n)\n</code></pre>\n\n<p>Now we can integrate it into your original query:</p>\n\n<pre><code>SELECT \n ...\n dbo.funcSellIdByPropId(T0.id) as SellerId, \n ...\nFROM T0 \n ...\n</code></pre>\n\n<p>To</p>\n\n<pre><code>SELECT \n ...\n S2P.ID, \n ...\nFROM T0 \nJOIN SellIDByPropertyID S2P ON T0.id = S2P.PropertyId\n ...\n</code></pre>\n\n<p><strong>Why this works</strong></p>\n\n<p>Once again the key to understanding is to think in sets. If you just think about a single record a reaction might be the original SP would be faster because if it is a agency property it will only do one select and the IF statement will stop the 2nd select from being run giving a speed advantage. </p>\n\n<blockquote>\n <p>Side note: often on SQL Engines a select statement will be slower than\n an if statement so even the above assumption is wrong, but I'll ignore\n that for now.</p>\n</blockquote>\n\n<p>However, this goes out the window as soon as we look at the set. If the original query is returning more than one record -- say N records then with the original function call we have the overhead of N function calls + N Selects + N/2 Selects (if half are not agencies). With the view we have just 2 Selects. Clearly O(3.5N) > O(2)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:50:00.970",
"Id": "80430",
"Score": "0",
"body": "I have never used views. I know this is very hand holding but how would I use the 1st example you've shown as a view as that to me still looks like a SQL function that'd I'd call in the same way as I already am. Cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:53:45.377",
"Id": "80431",
"Score": "0",
"body": "@TheAngrySaxon - You are going to owe me some unicoins - is MATRIXAGENCYPROPERTY.PropertyID or PRIVATESELLERS.PropertyID a superset of the other or are they mutually exclusive"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:14:01.320",
"Id": "80546",
"Score": "0",
"body": "I think unicoins was an April fools from stackexchange, was it not? They are mutually exclusive"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:41:55.253",
"Id": "80591",
"Score": "0",
"body": "@TheAngrySaxon - An April fools joke, or no, they are still the only \"official\" virtual currency of the stack exchange network. I take what I can get. :) I'll post an example after I put out the fire here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:35:05.463",
"Id": "46099",
"ParentId": "46094",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46099",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T19:46:49.880",
"Id": "46094",
"Score": "2",
"Tags": [
"sql",
"sql-server"
],
"Title": "The use of database \"sets\" rather than \"functions\""
} | 46094 |
<p>I have spent a few hours on this code, but think it could be improved a bit. It requires eSpeak to be installed to run the speech synthesis, but the voice can be toggled on or off using the <code>togglevoice</code> command. This was created for Python 2.7.3.</p>
<p>My major concerns are the fluctuations of the use of <code>global</code> to define global variables, the re-use of the variable <code>n</code> in functions and readability of the <code>d</code> array. It currently works fine on a Raspberry Pi running the latest version of Raspbian.</p>
<pre><code>import os
def talk(n):
if voice_mode == 1:
os.system("espeak -ven+m3 '" + n + "' 2>/dev/null")
else:
print n
def print_score(n):
if n == 0:
other_n = 1
else:
other_n = 0
if d[n][1] == 0:
score1 = "love"
else:
score1 = str(d[n][1])
if d[other_n][1] == 0:
score2 = "love"
else:
score2 = str(d[other_n][1])
talk(score1 + " " + score2)
def win(n):
global first_server
talk(d[n][0] + " wins the game")
d[n][2] += 1
d[0][1] = 0
d[1][1] = 0
deuce_mode = 0
serve_turns = old_serve_turns
if first_server == 0:
first_server = 1
current_server = 1
else:
first_server = 0
current_server = 0
if d[n][2] == match_points:
talk(d[n][0] + " wins the match")
d[0][2] = 0
d[1][2] = 0
def add_score(n):
global deuce_mode
global current_server
global serve_turns
d[n][1] += 1
if n == 0:
other_n = 1
else:
other_n = 0
if deuce_mode == 0:
if d[0][1] == d[1][1] and d[0][1] == game_points - 1:
deuce_mode = 1
old_serve_turns = serve_turns
serve_turns = 1
if current_server == 0:
print_score(0)
else:
print_score(1)
if d[n][1] == game_points:
win(n)
else:
if d[n][1] == d[other_n][1] + 2:
if current_server == 0:
print_score(0)
else:
print_score(1)
win(n)
else:
if current_server == 0:
print_score(0)
else:
print_score(1)
if (d[0][1] + d[1][1]) % serve_turns == 0:
if current_server == 0:
current_server = 1
talk(d[1][0] + " is serving next")
else:
current_server = 0
talk(d[0][0] + " is serving next")
d = []
for i in xrange(2):
d.append(["", 0, 0])
d[0][0] = "Player 1"
d[1][0] = "Player 2"
game_points = 11
match_points = 2
deuce_mode = 0
voice_mode = 1
serve_turns = 2
old_serve_turns = 2
current_server = 2
first_server = 0
talk("Ready to play")
while True:
c = raw_input("Command: ").lower()
if c == "z":
if current_server != 2:
add_score(0)
else:
talk(d[0][0] + " is serving first")
current_server = 0
first_server = 0
elif c == "x":
if current_server != 2:
add_score(1)
else:
talk(d[1][0] + " is serving first")
current_server = 1
first_server = 1
elif c == "1name":
d[0][0] = raw_input("Player 1 name: ")
talk("Welcome, " + d[0][0])
elif c == "2name":
d[1][0] = raw_input("Player 2 name: ")
talk("Welcome, " + d[1][0])
elif c == "gm":
game_points = int(raw_input("Game points: "))
match_points = int(raw_input("Match points: "))
elif c == "s":
serve_turns = int(raw_input("Serve turns: "))
elif c == "togglevoice":
if voice_mode == 0:
voice_mode = 1
else:
voice_mode = 0
elif c == "quit":
quit()
else:
talk("Command not recognised")
</code></pre>
| [] | [
{
"body": "<h1>Line by line analysis</h1>\n\n<pre><code>import os\n</code></pre>\n\n<p>You need 2 blank lines before each global function definition.</p>\n\n<pre><code>def talk(n):\n</code></pre>\n\n<p><code>n</code> is not descriptive and associated with a number. Don't use one letter variables unless it's really obvious (for example <code>i</code> loop counter, <code>k</code> and <code>v</code> as dict key and a value, or <code>d</code> as Twisted's deferred object. Something like <code>phrase</code> would be better.</p>\n\n<pre><code> if voice_mode == 1:\n</code></pre>\n\n<p>Where does the <code>voice_mode</code> come from? Global variables are bad, pas it as a parameter to a <code>talk</code> method. Also, canonical way of checking if boolean is True is simply <code>if voice_mode</code>.</p>\n\n<pre><code> os.system(\"espeak -ven+m3 '\" + n + \"' 2>/dev/null\")\n else:\n print n\n\ndef print_score(n):\n</code></pre>\n\n<p>Again, <code>n</code> does not tell reader a lot.</p>\n\n<pre><code> if n == 0:\n other_n = 1\n</code></pre>\n\n<p>What is <code>other_n</code>? If there's no better name for it - add a comment.</p>\n\n<pre><code> else:\n other_n = 0\n if d[n][1] == 0:\n</code></pre>\n\n<p>Where did <code>d</code> come from? Pass it to a function. Also, better name.</p>\n\n<pre><code> score1 = \"love\"\n else:\n score1 = str(d[n][1])\n if d[other_n][1] == 0:\n score2 = \"love\"\n else:\n score2 = str(d[other_n][1])\n talk(score1 + \" \" + score2)\n\ndef win(n):\n</code></pre>\n\n<p>Same thing with the <code>n</code> variable. Also, docstring might be helpful for this method.</p>\n\n<pre><code> global first_server\n</code></pre>\n\n<p>Global variables are bad, really bad. Make your method take and return this if you need the variable.</p>\n\n<pre><code> talk(d[n][0] + \" wins the game\")\n</code></pre>\n\n<p>This <code>d</code> is really quite obscure.</p>\n\n<pre><code> d[n][2] += 1\n d[0][1] = 0\n d[1][1] = 0\n deuce_mode = 0\n serve_turns = old_serve_turns\n if first_server == 0:\n first_server = 1\n current_server = 1\n else:\n first_server = 0\n current_server = 0\n if d[n][2] == match_points:\n talk(d[n][0] + \" wins the match\")\n d[0][2] = 0\n d[1][2] = 0\n\ndef add_score(n):\n</code></pre>\n\n<p>Same thing: add docstring, replace <code>n</code> with better name and pass all the global variables as arguments to the function.</p>\n\n<pre><code> global deuce_mode\n global current_server\n global serve_turns\n d[n][1] += 1\n if n == 0:\n other_n = 1\n else:\n other_n = 0\n if deuce_mode == 0:\n if d[0][1] == d[1][1] and d[0][1] == game_points - 1:\n deuce_mode = 1\n old_serve_turns = serve_turns\n</code></pre>\n\n<p>I don't see <code>old_serve_turns</code> used anywhere.</p>\n\n<pre><code> serve_turns = 1\n if current_server == 0:\n print_score(0)\n else:\n print_score(1)\n if d[n][1] == game_points:\n win(n)\n else:\n if d[n][1] == d[other_n][1] + 2:\n if current_server == 0:\n print_score(0)\n else:\n print_score(1)\n win(n)\n else:\n if current_server == 0:\n print_score(0)\n else:\n print_score(1)\n if (d[0][1] + d[1][1]) % serve_turns == 0:\n if current_server == 0:\n current_server = 1\n talk(d[1][0] + \" is serving next\")\n else:\n current_server = 0\n talk(d[0][0] + \" is serving next\")\n\nd = []\n</code></pre>\n\n<p>You need either a better data structure, or at least a good comment explained what the <code>d</code> is. Also, <code>d</code> needs a better name.</p>\n\n<pre><code>for i in xrange(2):\n d.append([\"\", 0, 0])\nd[0][0] = \"Player 1\"\nd[1][0] = \"Player 2\"\ngame_points = 11\nmatch_points = 2\ndeuce_mode = 0\nvoice_mode = 1\nserve_turns = 2\nold_serve_turns = 2\ncurrent_server = 2\n</code></pre>\n\n<p>You only play with server 0 and 1, correct? Why do you need to obscure and add server 2 which is only there to start the game? Better have a flag of some sort.</p>\n\n<pre><code>first_server = 0\n\ntalk(\"Ready to play\")\nwhile True:\n c = raw_input(\"Command: \").lower()\n</code></pre>\n\n<p>Better name: <code>command</code>.</p>\n\n<pre><code> if c == \"z\":\n if current_server != 2:\n add_score(0)\n else:\n talk(d[0][0] + \" is serving first\")\n current_server = 0\n first_server = 0\n elif c == \"x\":\n if current_server != 2:\n add_score(1)\n else:\n talk(d[1][0] + \" is serving first\")\n current_server = 1\n first_server = 1\n elif c == \"1name\":\n d[0][0] = raw_input(\"Player 1 name: \")\n talk(\"Welcome, \" + d[0][0])\n elif c == \"2name\":\n d[1][0] = raw_input(\"Player 2 name: \")\n talk(\"Welcome, \" + d[1][0])\n elif c == \"gm\":\n game_points = int(raw_input(\"Game points: \"))\n match_points = int(raw_input(\"Match points: \"))\n elif c == \"s\":\n serve_turns = int(raw_input(\"Serve turns: \"))\n elif c == \"togglevoice\":\n if voice_mode == 0:\n voice_mode = 1\n else:\n voice_mode = 0\n elif c == \"quit\":\n quit()\n else:\n talk(\"Command not recognised\")\n</code></pre>\n\n<p>Even though this if/else tree is acceptable in your scope, you might want to look into Strategy pattern. This is further reading though.</p>\n\n<h1>Summary</h1>\n\n<p>Overall, your variable naming needs to be more readable. Don't use global variables, just pass the ones you need as arguments. For example, your <code>talk</code> function could be changed like this:</p>\n\n<pre><code>def talk(phrase, voice_mode=True):\n \"\"\"Pronounce the phrase if the voice mode is on, otherwise print.\"\"\"\n if voice_mode:\n os.system(\"espeak -ven+m3 '%s' 2>/dev/null\" % phrase)\n else:\n print phrase\n</code></pre>\n\n<p>Don't forget to specify docstrings for non-trivial methods. Make them long if you need to. Use comments extensively to elaborate if variable name or a data structure is not descriptive enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:15:05.097",
"Id": "80508",
"Score": "1",
"body": "Thanks! This was put together in a rush without much python experience. You really cleared some things up for me! The `d` array is for holding user data, such as `d[0][0]` holds Player 1's name and `d[1][1]` holds Player 2's score."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:13:58.373",
"Id": "80600",
"Score": "0",
"body": "@NatZimmermann Might be better to name it `player_data` and turn it into a dict: `player_data = {'player1': {'name': 'Foo', 'score': 3}, 'player2': {'name': 'Bar', 'score': 8}}`. This is more explicit and lets you easier add additional parameters to the structure (if you decide to keep track of players' height for example)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:15:43.083",
"Id": "80602",
"Score": "0",
"body": "Ok thanks, I'll get to changing all the stuff now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:57:44.343",
"Id": "80613",
"Score": "0",
"body": "@NatZimmermann If you're interested - you can create another topic (don't adjust or edit this one) with your improved code and you might get higher level analysis (think design patterns)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:14:22.213",
"Id": "46145",
"ParentId": "46097",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46145",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:08:44.510",
"Id": "46097",
"Score": "5",
"Tags": [
"python",
"python-2.x",
"linux",
"raspberry-pi"
],
"Title": "Ping Pong Pi - A Ping Pong score and serving manager"
} | 46097 |
<p>I am a high school intern, and I am trying to parse my mentor's code so that he can read in an XML file and call simple methods to edit or get information from his XML file. </p>
<p>I was hoping someone could provide me with some (any) feedback - ways to optimize the code perhaps?</p>
<p>The XML file that my mentor uses is: (It's not necessary to look at his code - it's just for reference / a general idea)</p>
<pre><code><global>
<fringe_depth value="3"/>
<ignore_direction dir="z"/>
<minimize_overlap/>
<operating_conditions velocity="0.99756405,0.069756473,0" pressure="0"/>
<solver method="BlockImplicit"
equations="IncompressibleEuler"
num_time_steps="1"
steady_state="yes" time_step="0.1"
cfl="1280">
<block_implicit num_dual_time_steps="500"
max_inviscid_order="5"/>
</solver>
<output>
<grid_file filename="Plot/plot.g" style="p3d"
frequency="-1" byte_order="little_endian" format="unformatted"/>
<solution_file filename="Plot/plot.func" style="func"
frequency="-1" byte_order="little_endian" format="unformatted"/>
<grid_file filename="Plot/plot.xyz" style="p3dwib"
frequency="-1" format="formatted"/>
<solution_file filename="Plot/plot.q" style="p3dq"
frequency="-1" format="formatted"/>
<domain_connectivity filename="output++.dci" style="dci"/>
</output>
<body name="root">
<body name="airfoil">
<volume_grid name="left" style="p3d" filename="Grids/block_1.sp3dudl">
<skip_overlap_opt set_dsf_value="1e-20"/>
<boundary_surface name="imin">
<region range1="min" range2="all" range3="all"/>
<boundary_condition type="overlap"/>
<solver_boundary_condition type="overlap"/>
</boundary_surface>
<boundary_surface name="imax">
<region range1="max" range2="all" range3="all"/>
<boundary_condition type="overlap"/>
<solver_boundary_condition type="overlap"/>
</boundary_surface>
<boundary_surface name="jmin">
<region range1="all" range2="min" range3="all"/>
<boundary_condition type="solid"/>
<solver_boundary_condition type="solid"/>
</boundary_surface>
<boundary_surface name="jmax">
<region range1="all" range2="max" range3="all"/>
<boundary_condition type="overlap"/>
<solver_boundary_condition type="overlap"/>
</boundary_surface>
<boundary_surface name="kmin">
<region range1="all" range2="all" range3="min"/>
<boundary_condition type="symmetry"/>
<solver_boundary_condition type="zero_gradient"/>
</boundary_surface>
<boundary_surface name="kmax">
<region range1="all" range2="all" range3="max"/>
<boundary_condition type="symmetry"/>
<solver_boundary_condition type="zero_gradient"/>
</boundary_surface>
</volume_grid>
<volume_grid name="right" style="p3d" filename="Grids/block_2.sp3dudl">
<skip_overlap_opt set_dsf_value="1e-20"/>
<boundary_surface name="imin">
<region range1="min" range2="all" range3="all"/>
<boundary_condition type="overlap"/>
<solver_boundary_condition type="overlap"/>
</boundary_surface>
<boundary_surface name="imax">
<region range1="max" range2="all" range3="all"/>
<boundary_condition type="overlap"/>
<solver_boundary_condition type="overlap"/>
</boundary_surface>
<boundary_surface name="jmin">
<region range1="all" range2="min" range3="all"/>
<boundary_condition type="solid"/>
<solver_boundary_condition type="solid"/>
</boundary_surface>
<boundary_surface name="jmax">
<region range1="all" range2="max" range3="all"/>
<boundary_condition type="overlap"/>
<solver_boundary_condition type="overlap"/>
</boundary_surface>
<boundary_surface name="kmin">
<region range1="all" range2="all" range3="min"/>
<boundary_condition type="symmetry"/>
<solver_boundary_condition type="zero_gradient"/>
</boundary_surface>
<boundary_surface name="kmax">
<region range1="all" range2="all" range3="max"/>
<boundary_condition type="symmetry"/>
<solver_boundary_condition type="zero_gradient"/>
</boundary_surface>
</volume_grid>
</body>
<body name="box">
<volume_grid name="box" style="p3d" filename="Grids/block_3.sp3dudl" cartesian_grid="yes">
<boundary_surface name="imin">
<region range1="min" range2="all" range3="all"/>
<boundary_condition type="farfield"/>
<solver_boundary_condition type="farfield"/>
</boundary_surface>
<boundary_surface name="imax">
<region range1="max" range2="all" range3="all"/>
<boundary_condition type="farfield"/>
<solver_boundary_condition type="farfield"/>
</boundary_surface>
<boundary_surface name="jmin">
<region range1="all" range2="min" range3="all"/>
<boundary_condition type="farfield"/>
<solver_boundary_condition type="farfield"/>
</boundary_surface>
<boundary_surface name="jmax">
<region range1="all" range2="max" range3="all"/>
<boundary_condition type="farfield"/>
<solver_boundary_condition type="farfield"/>
</boundary_surface>
<boundary_surface name="kmin">
<region range1="all" range2="all" range3="min"/>
<boundary_condition type="symmetry"/>
<solver_boundary_condition type="zero_gradient"/>
</boundary_surface>
<boundary_surface name="kmax">
<region range1="all" range2="all" range3="max"/>
<boundary_condition type="symmetry"/>
<solver_boundary_condition type="zero_gradient"/>
</boundary_surface>
</volume_grid>
</body>
</body>
</global>
</code></pre>
<p>The code that I have written in Python is what I would like feedback on:</p>
<pre><code>import xml.etree.ElementTree as ET
import math
def parse(fileName):
global tree, root
tree = ET.parse(fileName)
root = tree.getroot()
'''
Returns total number of 'volume_grid' elements
'''
def getNumGrids():
count = 0
for volume_grid in root.iter('volume_grid'):
count+=1
return count
'''
Returns all of 'the volume_grid' name attributes as a list
'''
def getGridNames():
att = []
for grid in root.iter('volume_grid'):
att.append(grid.attrib)
names = []
for n in att:
names.append(n.get('name'))
return names
'''
Helper method for getBoundarySurfaceNamesForVolumeGrid(grid)
Returns list of attributes for a particular 'volume_grid', which is given as parameter
'''
def getGridBoundarySurfaceNameAttributes(volumeGridName):
selectedAtt = []
att = []
names = []
for v in root.iter('volume_grid'):
att.append(v.attrib)
for a in att:
names.append(a.get('name'))
for n in names:
if n == volumeGridName:
for surface in v.iter('boundary_surface'):
selectedAtt.append(surface.attrib)
return selectedAtt
'''
Returns a list of the names for a particular volume_grid, which is given as a parameter
'''
def getBoundarySurfaceNamesForVolumeGrid(grid):
g = getGridNames()
n = []
for names in g:
if names == grid:
n = (getGridBoundarySurfaceNameAttributes(names))
return n
'''
Changes 'solver_boundary_condition' type attribute in a specified volume_grid
takes 3 parameters:
1. 'volumeGridName' -- name of the 'volume_grid'
2. 'boundarySurfaceName' -- 'boundary_surface' 'name' attribute
3. 'newType' -- the new 'type' for the 'solver_boundary_condition'
'''
def setSolverBoundaryConditionType(volumeGridName, boundarySurfaceName, newType):
for v in root.iter('volume_grid'):
if v.get('name') == volumeGridName:
for b in v.iter('boundary_surface'):
if b.get('name') == boundarySurfaceName:
for s in b.iter('solver_boundary_condition'):
s.set('type', newType)
'''
returns type of 'solver_boundary_condition' within a volume grid and boundary surface
'''
def getSolverBoundaryConditionType(volumeGridName, boundarySurfaceName):
for v in root.iter('volume_grid'):
if v.get('name') == volumeGridName:
for b in v.iter('boundary_surface'):
if b.get('name') == boundarySurfaceName:
for s in b.iter('solver_boundary_condition'):
return s.get('type')
'''
Changes all solver_boundary_condition 'type' attributes from the first parameter 'old' to the second 'new'.
Only changes if 'type' originally contains 'old'
'''
def setAllSameSolverBoundaryConditionTypes(old, new):
for v in root.iter('volume_grid'):
for b in v.iter('boundary_surface'):
for s in b.iter('solver_boundary_condition'):
if s.get('type') == old:
s.set('type', new)
'''
Changes 'boundary_condition' type attribute in a specified volume_grid
Takes 3 parameters:
1. 'volumeGridName' -- name of the 'volume_grid'
2. 'boundarySurfaceName' -- 'boundary_surface' 'name' attribute
3. 'newType' -- the new 'type' for the 'solver_boundary_condition'
'''
def setBoundaryConditionType(volumeGridName, boundarySurfaceName, newType):
for v in root.iter('volume_grid'):
if v.get('name') == volumeGridName:
for b in v.iter('boundary_surface'):
if b.get('name') == boundarySurfaceName:
for s in b.iter('boundary_condition'):
s.set('type', newType)
'''
Changes all 'boundary_condition' 'type' attributes from the first parameter 'old' to the second 'new'.
Only changes if 'type' originally contains 'old'
'''
def setAllSameBoundaryConditionTypes(old, new):
for v in root.iter('volume_grid'):
for b in v.iter('boundary_surface'):
for s in b.iter('boundary_condition'):
if s.get('type') == old:
s.set('type', new)
'''
Given the volumeGrid name parameter (1st), the user can choose to edit either the style (2nd) or filename (3rd) parameters.
If the user wants only to edit one of the two editable parameters, they can put in 'NC' (no change) for the unchanged parameter
'''
def setVolumeGrid(name, style, fileName):
for grid in root.iter('volume_grid'):
if (grid.get('name') == name):
if (style != 'NC'):
grid.set('style', style)
if (fileName != 'NC'):
grid.set('filename', fileName)
'''
helper method for setOperatingConditionsPolarVelocity()
Changes operating conditions, takes in velocity and pressure parameters
Velocity parameter is in form "x,y,z"
'NC' (no change) for any parameter that should not be changed
'''
def setOperatingConditions(velocity, pressure):
for cond in root.iter('operating_conditions'):
if (velocity!= 'NC'):
cond.set('velocity', velocity)
if(pressure != 'NC'):
cond.set('pressure', pressure)
'''
Given a radius and theta as parameters, calculates the velocity for operating_conditions in xyz.
Then sets the operating conditions attributes by calling setOperatingConditions()
User can put in 'NC' (no change) for any parameter that should not be changed
r = magnitude, theta = inflow angle
'''
def setOperatingConditionsPolarVelocity(r, theta, pressure):
x =str(r*math.cos(theta))
y = str(r*math.sin(theta))
z = str(0)
velocity = ''.join(x + ',' + y + ',' + z)
setOperatingConditions(velocity, pressure)
'''
Returns the current operating conditions: velocity and pressure as a dictionary
'''
def getOperatingConditions():
for cond in root.iter('operating_conditions'):
return cond.attrib
'''
Changes solver element attributes
NC if no change
'''
def setSolverType(method, equations, numTimeSteps, steadyState, timeStep, cfl):
for sol in root.iter('solver'):
if method!='NC':
sol.set('method', method)
if equations != 'NC':
sol.set('equations', equations)
if numTimeSteps != 'NC':
sol.set('num_time_steps', numTimeSteps)
if steadyState != 'NC':
sol.set('steady_state', steadyState)
if timeStep!='NC':
sol.set('time_step', timeStep)
if cfl !='NC':
sol.set('cfl', cfl)
'''
provides the attributes for output grid_file, given the filename
The parameter filename is in the form Plot/Plot.name, but to make it easier for the user, he/she must only type in the name part
For example, getOutputGridFileInfo(xyz) would work for the filename 'Plot/plot.xyz'
'''
def getOutputGridFileInfo(filename):
filename = 'Plot/plot.' + filename
for file in root.iter('grid_file'):
if (file.get('filename') == filename):
return (file.attrib)
'''
Allow the user to change the style, frequency, and format attributes within <output> <grid_file> given the filename
The parameter filename is in the form Plot/Plot.name, but to make it easier for the user, he/she must only type in the name part
Note: format is a built-in symbol, so formatting was used in place
'''
def setOutputGridFile(filename, style, frequency, formatting):
filename = 'Plot/plot.' + filename
for g in root.iter('grid_file'):
if g.get('filename') == filename:
if style !='NC':
g.set('style', style)
if frequency != 'NC':
g.set('frequency', frequency)
if formatting != 'NC':
g.set('format', formatting)
'''
Returns all of the attricutes for a grid_file in output given a filename.
The parameter filename is in the form Plot/Plot.name, but to make it easier for the user, he/she must only type in the name part
'''
def getOutputSolutionFile(filename):
filename = 'Plot/plot.' + filename
for file in root.iter('solution_file'):
if (file.get('filename') == filename):
return (file.attrib)
'''
returns the name of each body element in a list
'''
def getBodyNames():
att = []
for body in root.iter('body'):
att.append(body.attrib)
names = []
for n in att:
names.append(n.get('name'))
return names
'''
Changes the old body name (oldName parameter) to a new body name (newName parameter)
'''
def setBodyName(oldName, newName):
for body in root.iter('body'):
if body.get('name') == oldName:
body.set('name', newName)
'''
Writes the file onto a new XML.
Useful when importing this module because etree will not need to be imported/file re-parsed to write the file out from other module
'''
def writeFile(name):
tree.write(name)
</code></pre>
<p>My mentor would import my module in terminal and use that to call the methods.</p>
| [] | [
{
"body": "<p>Overall, it’s pretty good. I can follow what you’re doing fairly easily, and the docstrings make it easy to see what each function does (even though I’ve not used this module before). Here are some suggestions for how you could make your code more “Pythonic”, and more compact:</p>\n\n<ul>\n<li><p>Take a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\">PEP 8</a>, which is the style guide for Python. Two obvious ways in which your code could be considered “un-Pythonic”:</p>\n\n<ul>\n<li><p>Docstrings should live inside the function definition, not directly before them. This is covered further in <a href=\"http://legacy.python.org/dev/peps/pep-0257/\">PEP 257</a>:</p>\n\n<blockquote>\n <p>A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition.</p>\n</blockquote>\n\n<p>Single-line docstrings also don’t need separate lines for their opening and closing quotes; it can all go together.</p></li>\n<li><p>The Python convention for function names is lowercase with underscores, not mixed case. There’s also a tendency to use long, descriptive names (e.g. <code>attributes</code> instead of <code>att</code>), which would make your code easier to read.</p></li>\n</ul></li>\n<li><p>The <code>parse</code> function declares the global variables <code>tree</code> and <code>root</code>, but this isn’t a good way to do it: if you try to parse two files in a row, then what happens? Um… The fact that this is ambiguous or potentially confusing means you should probably do something different.</p>\n\n<p>I’d suggest turning this into a new class, with <code>tree</code> and <code>root</code> attributes. This allows you to work with multiple files in the same session. Something like this should get you started:</p>\n\n\n\n<pre><code>class MentorTree(object):\n def __init__(self, filename):\n self.tree = ET.parse(filename)\n self.root = self.tree.getroot()\n</code></pre></li>\n<li><p>Most of the functions use <code>if</code> and <code>for</code> loops. It all works, but you can use list comprehensions and data structures to make the code more compact, and less nested. (Lots of nested constructions aren’t necessarily a bad thing, but I prefer to avoid them when I don’t need them.)</p>\n\n<p>For example, in <code>getNumGrids()</code>, you can get the length of the iterator with a single list comprehension:</p>\n\n\n\n<pre><code>def get_grid_count(self):\n \"\"\"Return the number of 'volume_grid' elements.\"\"\"\n return sum(1 for _ in self.root.iter('volume_grid'))\n</code></pre>\n\n<p>Similarly for <code>getGridNames()</code>:</p>\n\n\n\n<pre><code>def get_grid_names(self):\n \"\"\"Returns a list of the 'volume_grid' name attributes.\"\"\"\n attributes = [grid.attrib for grid in root.iter('volume_grid')]\n return [n.get('name') for n in attributes]\n</code></pre>\n\n<p>Lots of other functions can be modified this way.</p>\n\n<p>Where you have long strings of <code>if</code> statements of the form <code>X != 'NC'</code>, you can clean then up with something like a dictionary or list. For example, here’s <code>setSolverType()</code>:</p>\n\n\n\n<pre><code>def set_solver_type(method, equations, num_time_steps, steady_state, time_step, cfl):\n \"\"\"\n Change the solver element attributes.\n Attribute is not updated if the argument is 'None'.\n \"\"\"\n element_attributes = [\n 'method', 'equations', 'num_time_steps', 'steady_state', 'time_step', 'cfl'\n ]\n for sol in root.iter('solver'):\n for attribute in element_attributes:\n if eval(attribute) is not None:\n sol.set(attribute, eval(attribute))\n</code></pre>\n\n<p>Horrible abuse of <code>eval()</code>, but there you are. Note that I replaced <code>'NC'</code> by <code>None</code>.</p></li>\n</ul>\n\n<p>I feel like there’s more that could be done, but I need to go to bed and this seems like enough to get you started.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T23:15:34.850",
"Id": "46117",
"ParentId": "46098",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "46117",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:28:29.513",
"Id": "46098",
"Score": "7",
"Tags": [
"python",
"parsing",
"xml"
],
"Title": "Parse XML using Python XML eTree"
} | 46098 |
<p>I'm trying to implement interfaces in my design but not sure if this is correct or if there is a better way to do it.</p>
<p>What I need to do is </p>
<ol>
<li><p>open a text file</p></li>
<li><p>keep searching blocks of text until I find a string that matches against one of the classes that defines that string pattern</p></li>
<li><p>process the string I found</p></li>
<li><p>continue processing file where I left off</p></li>
</ol>
<p>This is the code I'm using so far, but not sure if the design is correct.
Maybe something about creating a new instance of each stringType class just to check if the string matches with the one defined in the class seems wrong to me. I don't need to create the instance of the object until I actually need to do work on it.</p>
<p><strong>EDIT - Forgot to add the process function, not sure if that changes anything</strong></p>
<pre><code>static void Main(string[] args)
{
//get types that implement IStringType interface
List<IStringType> types = TypeFactory.GetTypeList();
//scan text file and check against the types, store any matches found
var stringMatches = from t in types
where Regex.IsMatch(sourceString, t.stringPattern)
select t.getNewInstance(Regex.Match(sourceString,t.stringPattern).Value);
if (stringMatches.Any())
{
//process string matches
}
}
public class stringType1 : IStringType
{
public string stringPattern { get { return @"(?m)^TEST1.+[\r\n]"; } set { this.stringPattern = value; } }
private string _Message { get; set; }
public stringType1() { }
public stringType1(string str)
{
_Message = str;
}
public string ProcessString(string match)
{
//specific code to processes stringType1
}
public IStringType getNewInstance(string msg)
{
return (IStringType)(new stringType1(msg));
}
}
public class stringType2 : IStringType
{
public string stringPattern { get { return @"(?m)^BLAH2.+[\r\n]"; } set { this.stringPattern = value; } }
private string _Message { get; set; }
public stringType2() { }
public stringType2(string str)
{
_Message = str;
}
public string ProcessString(string match)
{
//specific code to processes stringType2
}
public IStringType getNewInstance(string msg)
{
return (IStringType)(new stringType2(msg));
}
}
public interface IStringType
{
string stringPattern { get; set; }
string ProcessString(string str);
IStringType getNewInstance(string str);
}
public static class TypeFactory
{
public static List<IStringType> GetTypeList()
{
List<IStringType> types = new List<IStringType>();
types.AddRange(from assembly in AppDomain.CurrentDomain.GetAssemblies()
from t in assembly.GetTypes()
where t.IsClass && t.GetInterfaces().Contains(typeof(IStringType))
select Activator.CreateInstance(t) as IStringType);
return types;
}
}
</code></pre>
| [] | [
{
"body": "<p>It's very easy: you shouldn't. An interface is used to indicate that a subset of classes present common behaviour or should be considered similar in some way.</p>\n<p>In your situation there simply is no reason to make this change because all you do is change a text value in a property, which could just as easily be done by taking an argument in your constructor and keeping a <code>private</code> backing fields which should then be used to populate the property's regex.</p>\n<p>This will result in several code optimizations:</p>\n<ul>\n<li><p>No heavy duplication of code in <code>StringType1</code> and <code>StringType2</code> (this should have been a red flag)</p>\n</li>\n<li><p>No reflection necessary to get the different types. Just keep a collection of the different regexes and return a collection of <code>StringType</code> objects, constructed with your regexes.</p>\n</li>\n</ul>\n<p>Additionally, this code will also be obsolete:</p>\n<pre><code>public IStringType getNewInstance(string msg)\n{\n return (IStringType)(new stringType2(msg));\n}\n</code></pre>\n<p>since you should just overwrite that variable with <code>new Stringtype(thisVariable.StringPattern, message)</code>.</p>\n<p>Ultimately, your code would look something like this:</p>\n<pre><code>public class StringType\n{\n private IPatternProcessor _processor;\n private string _pattern;\n private string _message { get; set; }\n\n public StringType(string str, IPatternProcessor processor)\n {\n _message = str;\n _processor = processor;\n }\n\n public string StringPattern { \n get { return pattern; } \n set { pattern = value; } \n }\n\n public void Process() {\n _processor.Process(_message);\n }\n} \n\npublic static class PatternFactory\n{\n private static List<String> _patterns = new List<String>();\n\n static PatternFactory() {\n _patterns.Add("(?m)^TEST1.+[\\r\\n]";);\n _patterns.Add("(?m)^BLAH2.+[\\r\\n]";);\n } \n\n public static List<StringType> GetTypeList()\n {\n return _patterns.Select(x => new StringType(x));\n }\n}\n\npublic interface IPatternProcessor { \n void Process(string input);\n}\n\npublic class ProcessMethod1 : IPatternProcessor { }\npublic class ProcessMethod2 : IPatternProcessor { }\n</code></pre>\n<p>If you want to make it easy for your user, you can hardcode these different methods into properties:</p>\n<pre><code>public class PatternProcessor {\n public IPatternProcessor ProcessMethod1 { get { return new ProcessMethod1(); } private set; };\n public IPatternProcessor ProcessMethod2 { get { return new ProcessMethod2(); } private set; };\n}\n</code></pre>\n<p>Now you can simply call this with</p>\n<pre><code>new StringType(input, PatternProcessor.ProcessMethod1).Process();\n</code></pre>\n<p>If you were really into it, you could just cache the <code>IProcessMethod</code> objects in a collection in your <code>PatternProcessor</code> class (provided each method is stateless), but that might be going a little too far out of the scope of this review.</p>\n<h1>Style notes</h1>\n<ul>\n<li>Classes are UpperCamelCase (<code>StringType</code>)</li>\n<li>Private fields are less standardized but they are often written as <code>_field</code></li>\n<li>Methods and constructors are always capitalized (<code>StringPattern</code>, <code>StringType</code>), just like the class</li>\n</ul>\n<h1>Conclusion</h1>\n<p>This code does not benefit from interfaces at all and as such it is impossible to review it since interfaces are the main problem with the code.</p>\n<h1>Post-edit</h1>\n<p>So, with the additional requirement of pattern-specific behaviour the introduction of interfaces and separate types now makes a lot more sense. I see two architecture options off the bat:</p>\n<ul>\n<li><p>Separate <code>StringType</code> classes for each situation (if you name them <code>StringType1</code>, <code>StringType2</code> etc, I'll chase you with a bat)</p>\n</li>\n<li><p>Separate strategies (strategy pattern) for each type of processing with a sauce of factory pattern</p>\n</li>\n</ul>\n<p>I will go with the second option because it would require less rewriting. Someone else can write the less complex first option but the second option is more flexible in terms of allowing two different patterns to use the same processing option.</p>\n<p>I will change the earlier block of code with some additions to keep everything in one place.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:10:13.597",
"Id": "80435",
"Score": "0",
"body": "`static { _patterns.Add(\"(?m)^TEST1.+[\\r\\n]\";); [...]` won't compile, it's not Java ;) it should be `static PatternFactory` instead. The answer is on the nose anyway"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:11:47.503",
"Id": "80436",
"Score": "0",
"body": "but I need to process each string different, each stringType class for example has a process() function that processes the string specifically for each type"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:20:12.023",
"Id": "80437",
"Score": "0",
"body": "@Morawski: cheers, feel free to edit yourself though! I always switch it up between C# and Java ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:21:22.203",
"Id": "80438",
"Score": "0",
"body": "@erotavlas: why would you leave out the entire reason why someone would use an interface.. If anything had to be in there, it was that `process()` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:22:07.133",
"Id": "80439",
"Score": "0",
"body": "@Jeroen Vannevel I know I'm so sorry :/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:22:57.057",
"Id": "80440",
"Score": "0",
"body": "We can still salvage this, don't worry. Give me a few moments to introduce you to the strategy pattern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:39:42.353",
"Id": "80444",
"Score": "0",
"body": "@erotavlas: I have expanded upon my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T00:25:37.760",
"Id": "80459",
"Score": "2",
"body": "+1 for *if you name them StringType1, StringType2 etc, I'll chase you with a bat* ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:32:23.047",
"Id": "80823",
"Score": "0",
"body": "@JeroenVannevel it seems like a a pretty good approach, but I'm wondering now how I can associate which PatternProcessor to pass, each processor belongs only to one pattern, is that just something I have to take care of before I pass the parameters into the StringType constructor? (i.e. I have to external to this find a way to link the string with the correct processor before passing them in)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:38:49.267",
"Id": "80824",
"Score": "0",
"body": "If you want to explicitly combine them then you can incorporate something you did earlier: different classes that hold a pattern and a processor and then you can simply instantiate the class that you want and you'll get the pattern and the processor combined. In the end this will look quite a bit like your original solution, but there is an extra layer which allows you to reuse the same processor and the interface usage feels more clean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-24T17:16:44.450",
"Id": "84352",
"Score": "0",
"body": "@JeroenVannevel I don't see how the PatternFactory is used in the code sample. How would it be used to invoke the correct PatternProcessor based on the input string?"
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:00:17.087",
"Id": "46101",
"ParentId": "46100",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T20:42:30.817",
"Id": "46100",
"Score": "3",
"Tags": [
"c#",
"design-patterns",
"strings",
".net"
],
"Title": "Searching text files for string patterns that are each defined in their own classes"
} | 46100 |
<p>I've built this small jQuery plugin to work with HTML5 History State functions. It's my first jQuery plugin, so I'm not sure if it's up to the best practices, or what could be done better. Keeping it simple and small is my main concern.</p>
<p>If you have any suggestions on how to improve it, I'd love to see them.</p>
<pre><code>// FunkyHistory Plugin
(function ( $, window, document, undefined ) {
jQuery.fn.FunkyHistory = function( options, callback ) {
// Don't do anything if History not supported
if (!window.history && !window.history.pushState) {
return this;
}
// These are the defaults.
var settings = jQuery.extend({
target: null,
selector: "body"
}, options );
// Prepare
var FunkyHistory = {};
FunkyHistory.selector = this.selector;
FunkyHistory.clickedEl = null;
// Update content on page
FunkyHistory.loadNewContent = function(target, url, selector){
jQuery.get(url, function(data) {
// Update content on page
var newContent = jQuery(data).find(selector);
// Only update content if a target is set
if( settings.target ) {
jQuery(target).replaceWith(newContent);
}
// Callback
if (typeof callback == 'function') { // make sure the callback is a function
callback.call(FunkyHistory.clickedEl, data); // brings the scope to the callback
}
}, 'text');
}
// When browser back/forward button is pressed
FunkyHistory.bindPopState = function(){
jQuery(window).on('popstate',function(event){
// Load in correct conetent
FunkyHistory.loadNewContent(settings.target, location.href, settings.selector);
});
}
// Bind to click of tags
FunkyHistory.bindClicks = function(){
jQuery(document).on('click', FunkyHistory.selector, function(e){
e.preventDefault();
// Cahce the clicked elements "this"
FunkyHistory.clickedEl = this;
// Set State to history
var stateObj = {
selector: settings.selector,
url: jQuery(this).attr('href')
};
history.pushState(stateObj, null, stateObj.url);
FunkyHistory.loadNewContent( settings.target, stateObj.url, settings.selector );
});
}
// Do stuff
FunkyHistory.bindPopState();
FunkyHistory.bindClicks();
// Return tags to be chainable
return this;
};
})( jQuery, window, document );
</code></pre>
<p>And you'd call it like this:</p>
<pre><code>jQuery('#menu a').FunkyHistory({
target: '#content', // This is replaced by AJAX content
selector: "#content.new" // This is what to look for in the AJAX content
}, function(data){
// Callback in here
console.log(this, data);
});
</code></pre>
<p>I have a working example of it <a href="http://labs.funkhausdesign.com/examples/history/" rel="nofollow noreferrer">here</a>.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T21:11:18.197",
"Id": "46102",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"design-patterns",
"html5",
"state"
],
"Title": "jQuery Plugin - HTML5 History State"
} | 46102 |
<p>I wrote this script for a code challenge on TreeHouse. I already submitted my code, but I am looking for an after the fact feedback.</p>
<p>The challenge was to open a file of text, remove specific words (provided in another file) and do the following:</p>
<blockquote>
<p>Output to the screen in a readable fashion<br>
1. total word count after filtering<br>
2. highest occurring word<br>
3. longest word(s) and its / their length<br>
4. sort the list from most occurring to least occurring then output that data to the screen as an unordered list<br>
5. Bonus: Return the word list in JSON.</p>
</blockquote>
<p>I decided to split the solution into two classes:</p>
<ol>
<li>One class to sanitise the string into words only</li>
<li>Another class to do the analysis</li>
</ol>
<p>This is the sanitiser class. Given text it should return a string of words only. It should remove anything that is <em>not a letter or an apostrophe</em>, and <em>compress all white space into a single space character</em>.</p>
<p>I accept that <a href="https://gist.github.com/abitdodgy/e3201365dd8328efbfd3#file-output-txt-L175" rel="nofollow">this has problems</a>. For example, I found an instance of an apostrophe as a word. Perhaps it was a leading or a trailing one. But defining the boundaries of a word is a tricky proposition.</p>
<pre><code>class WordsOnlySanitizer
# Allow for diacritics, hence p{Alpha} and not \w
# We should not split words on apostrophes either
WORDS_ONLY_REGEX = /[^\p{Alpha}']/i
# We want to reduce all white space into a single space
SPACE_ONLY_REGEX = /\s+/
def self.to_words(text)
text.gsub(WORDS_ONLY_REGEX, ' ').gsub(SPACE_ONLY_REGEX, ' ')
end
end
</code></pre>
<p>This is the analyser class. It's self explanatory. There is duplication in the <code>longest_words</code> and <code>highest_occuring_words</code> methods. But I'm not sure how to remove this duplication without making the code less readable.</p>
<p>The <code>html_list</code> method also looks a little suspect, but I can't tell why.</p>
<pre><code>require 'json'
class Analyser
def initialize(text, filter)
@words = text.split
@filter = filter.split
end
def word_count
filtered_words.size
end
def word_occurrences
@word_occurrences ||= filtered_words.inject(Hash.new(0)) do |result, word|
result[word] += 1
result
end
end
def highest_occurring_words
word_occurrences.group_by { |key, value| value }.max_by { |key, value| key }.last
end
def longest_words
filtered_words.inject({}) do |result, word|
result[word] = word.length
result
end.group_by { |key, value| value }.max_by { |key, value| key }.last
end
def html_list
list = ""
word_occurrences.sort_by { |key, value| value }.reverse.each do |key, value|
list << " <li>#{key}: #{value}</li>\n"
end
"<ul>\n" + list + "</ul>"
end
def json_list
JSON.parse(word_occurrences.to_json)
end
private
def filtered_words
@filtered_words ||= @words.reject do |word|
# Downcase so that Hello and hello count as two occurrences
word.downcase!
@filter.include?(word)
end
end
end
</code></pre>
<h2>Usage</h2>
<p>Here's how you would use this:</p>
<pre><code>text = WordsOnlySanitizer.to_words(File.read('words.txt'))
filter = WordsOnlySanitizer.to_words(File.read('filter_words.txt'))
analyser = Analyser.new(text, filter)
puts "Word count after filtering is: #{analyser.word_count}"
puts "\n"
puts "The most frequent words are:"
analyser.highest_occurring_words.each do |key, value|
puts " - #{key}: #{value} occurences"
end
puts "\n"
puts "The longest words are:"
analyser.longest_words.each do |word|
puts " - #{word.first}: #{word.last} characters"
end
puts "\n"
puts "Word list:"
puts analyser.html_list
puts "JSON object:"
puts analyser.json_list
</code></pre>
<p>Here's <a href="https://gist.github.com/abitdodgy/e3201365dd8328efbfd3" rel="nofollow">a gist with all the files</a>. Warning: There are large text files. </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:27:13.707",
"Id": "80608",
"Score": "0",
"body": "Just curious, what is the problem with defining word boundaries by simple whitespace?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:07:32.000",
"Id": "80617",
"Score": "0",
"body": "@Jonah Are you referring to my `WORDS_ONLY_REGEX`? If so, it's because things like `\"!'` and `i.` and `ii.` get included as words, when they are not. My intention was to clean up anything that's not alpha, compress all white space into one space, then split into an array. So in a sense, I am doing that. Perhaps I don't understand your question fully, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T19:47:50.103",
"Id": "80641",
"Score": "0",
"body": "Got it, that makes sense. However `\\p{Alpha}` would still include stuff `i.` and `ii.`, grabbing them without the period, correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:04:30.660",
"Id": "80650",
"Score": "0",
"body": "@Jonah yes, and I suppose you can consider that a flaw. This is why I mentioned that defining word boundaries is tricky. My regex also does not account for non-word-apostrophes. So any `'` character is not removed, regardless whether it is an apostrophe or not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:06:45.223",
"Id": "80651",
"Score": "0",
"body": "@Jonah here's a Rubular to illustrate this behaviour. http://rubular.com/r/BpTzjvo2GU"
}
] | [
{
"body": "<p>The first thing I noticed is that you've defined methods such as <code>word_occurrences</code>, which do nothing but set instance variables (<code>@word_occurrences</code>, etc.). This is a bit redundant, and it would be better to do one of two things:</p>\n\n<ol>\n<li>Define all of your instance variables under the <code>initialize</code> method. or</li>\n<li>Take out the <code>@word_occurrences ||=</code> part of the method definition.</li>\n</ol>\n\n<p>I think from a performance standpoint, it might be better to take the first approach, since you don't want to have to calculate <code>word_occurrences</code> every time you call it as a method. I also noticed that you only use <code>@words</code> and <code>@filter</code> once, and that's to define <code>filtered_words</code>, so you can make things simple by just defining <code>@words</code> to be what <code>filtered_words</code> is currently. See below:</p>\n\n<pre><code>def initialize(text, filter)\n @words = text.split.reject {|word| filter.split.include? word.downcase}\n @occurrences = @words.each_with_object(Hash.new(0)) {|word, result| result[word] += 1}\n @lengths = @words.each_with_object({}) {|word, result| result[word] ||= word.length}\nend\n</code></pre>\n\n<p>I've made <code>@words</code> the new <code>filtered_words</code>, shortened <code>word_occurrences</code> to just <code>@occurrences</code> (and made it an instance variable so that we're only evaluating it once, upon initialization of the instance), and added another instance variable <code>@lengths</code>, which represents a part of your <code>longest_words</code> function, a hash of each word and how long it is.</p>\n\n<p>Also, notice that I simplified your use of <code>inject</code> to create a hash of word occurrences and word lengths, by using the handy <code>each_with_object</code> function instead.</p>\n\n<p>I also changed <code>=</code> to <code>||=</code> for the part where you're building up a hash of word lengths. I believe this will be better for performance, as you're not re-calculating the word length for words you already have.</p>\n\n<p>You mentioned duplication between <code>longest_words</code> and <code>highest_occurring_words</code> -- you could solve this by pulling out the part you reused into a private function, which I would call <code>highest_ranking</code>:</p>\n\n<pre><code>private\n\ndef highest_ranking(entries)\n # Takes a hashmap of the form {\"foo\" => 100, \"bar\" => 45} and returns an array\n # containing the entries (array-ified) with the highest number as a value.\n entries.group_by{|word, occs| occs}.sort.last.last\nend\n</code></pre>\n\n<p>I simplified <code>max_by{|key, value| key}.last</code> to just <code>sort.last.last</code> -- it turns out that <code>Enumerable#sort</code> knows how to properly handle sorting by keys, so getting the highest one is just a matter of sorting the hash and grabbing the last item in the resulting array. (The extra <code>last</code> is there for the same reason the <code>last</code> is there in your function -- to drop the number of occurrences and just return the key/value entries in the result array)</p>\n\n<p>Now that you have this useful helper function, finding the highest occurring words and longest words is simple:</p>\n\n<pre><code>public\n\ndef highest_occurring_words\n highest_ranking @occurrences\nend\n\ndef longest_words\n highest_ranking @lengths\nend\n</code></pre>\n\n<p>Finally, I would refactor your <code>html_list</code> function like this:</p>\n\n<pre><code>def html_list\n list = word_occurrences.sort_by {|word, occs| occs}.reverse.map do |word, occs|\n \" <li>#{word}: #{occs}</li>\"\n end.join(\"\\n\")\n \"<ul>\\n\" + list + \"\\n</ul>\"\nend\n</code></pre>\n\n<p>Instead of starting with list as <code>\"\"</code> and iterating through each word/occurrences pair to add onto it a little at a time, you can take a functional approach and use <code>map</code> to turn each word/occurrences pair into a string like <code>\" <li>antibubbles: 4</li>\"</code>, then use <code>join</code> to turn the resulting array into one long string with \"\\n\" inserted in between each list item. I also inserted two spaces before each list item so that they appear indented in the HTML. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-29T03:10:38.130",
"Id": "85066",
"Score": "0",
"body": "Thank you for the insightful answer. At further glance, do you think that the `initialize` method is doing too much? How would you test something like that? I feels hard to test, to me at least."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:34:14.897",
"Id": "85310",
"Score": "0",
"body": "I've bundled this into a gem, taking into account some of your improvements. https://github.com/abitdodgy/words_counted Thanks for your input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:34:50.040",
"Id": "85312",
"Score": "0",
"body": "Your `initialize` method should set up your instance variables -- in this case, `@words`, `@lengths` and `@occurrences` -- and very little else, if anything. A lot of the time you're just passing in arguments, like `@name = name; @age = age`, etc. I think this is a good example of a case where you can do something more complex within the `initialize` method, while still keeping your code concise and readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-30T15:35:13.283",
"Id": "85313",
"Score": "0",
"body": "Happy to help! :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T19:53:57.093",
"Id": "47515",
"ParentId": "46105",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "47515",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:14:18.303",
"Id": "46105",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "A Ruby string analyser"
} | 46105 |
<p>I have a GUI that contains a Table Object (for displaying columns of data) and a Table Model. The Table Object contains the Table Model.</p>
<p>Is it better to store the Table Model as a object in the User interface or de-reference it as needed? Is there any performance gain keeping it separate? If there is, is it a good design to implement this?</p>
<p>For example:</p>
<pre><code>public GUI {
private Table table;
private TableModel model;
public UI() {
this.table = new Table();
this.model = table.getModel();
}
public void actionPerformed() {
// Performance improvement
// without having to de-reference it from table
model.setRowLimit();
}
// OR
public void actionPerformed() {
// Slower but is it better OO Design
table.getModel().setRowLimit();
}
}
</code></pre>
<p>The GUI has 10 public methods exposed where the model could be updated or changed.</p>
| [] | [
{
"body": "<p>There will be no difference in performance whatsoever between the two approaches.</p>\n\n<p>I would suggest you don't break the responsibility principle and leave the handling of the tablemodel to the <code>Table</code> class.</p>\n\n<p>One remark though: if there are additional computations done in <code>getTableModel()</code> aside from a plain setter, you will bypass these if your create the local variable. This may or may not be something you desire.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:31:36.763",
"Id": "46110",
"ParentId": "46106",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46110",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:16:55.267",
"Id": "46106",
"Score": "1",
"Tags": [
"java",
"optimization"
],
"Title": "Store object in memory or de-reference it for performance"
} | 46106 |
<p>Is there a better way to handle this ClassNotFoundException ?</p>
<pre><code>private Class<?> getClass(String value)
{
Class<?> columnClass = null;
try
{
columnClass = Class.forName(StringUtils.trim(value));
}
catch (ClassNotFoundException ex)
{
if (value.contains("double") || value.contains("Double"))
{
columnClass = Double.class;
}
else if (value.contains("int") || value.contains("Int"))
{
columnClass = Integer.class;
}
else if (value.contains("bool"))
{
columnClass = Boolean.class;
}
else if (value.contains("long") || value.contains("Long"))
{
columnClass = Long.class;
}
else
{
log.error("FAILED. Class object is not supported: " + value, ex);
}
}
return columnClass;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:50:55.130",
"Id": "80455",
"Score": "0",
"body": "Can you provide more context about how this code is called, and how often?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:56:49.000",
"Id": "80584",
"Score": "0",
"body": "I have an internal table describing a huge data set with each type of column having different types of classes (Integer, Double, Boolean etc...), so when I load the data into the table or GUI, the formatting for each column is displayed appropiately based upon class type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:20:57.483",
"Id": "80589",
"Score": "0",
"body": "It would only call this method once per column, with only a few columns < 10."
}
] | [
{
"body": "<p>You do not provide much context for this method, so I can only give you general advice.</p>\n<h2>Logic</h2>\n<ol>\n<li><p>never use exception handling as part of the routine/regular code path in you program. Most Java VM's require significant locking and processing to generate the actual exception and its stack trace. I have seen 10% performance improvements in large commercial applications where simple pre-validation of common exceptional conditions saves a huge amount of processing resources.</p>\n</li>\n<li><p>What if the user enters the non-existent class name <code>dev.null.TurningIntoZomies</code>, they get an <code>Integer.class</code> back.</p>\n</li>\n<li><p>In the event that the <code>Class.forname(...)</code> fails, you do exception handling and return null. If the program asks for the same value again, it will do the full search again, and so on. If the class exists, it is not normally very slow, but, if the class does not exist, the <code>Class.forname()</code> has to search the entire classpath. Cache the results (of both the successes and the failures so you only have to call <code>Class.forName()</code> once.</p>\n</li>\n</ol>\n<h2>Code Style</h2>\n<ul>\n<li>Use correct Java brace placement, at the end of the line.</li>\n</ul>\n<p>Finally, you can use short-circuit return statements to make it easier:</p>\n<pre><code>private Class<?> getClass(String value) {\n try {\n return Class.forName(StringUtils.trim(value));\n } catch (ClassNotFoundException ex) {\n if (value.contains("double") || value.contains("Double")) {\n return Double.class;\n }\n if (value.contains("int") || value.contains("Int")) {\n return Integer.class;\n }\n if (value.contains("bool")) {\n return = Boolean.class;\n }\n if (value.contains("long") || value.contains("Long")) {\n return Long.class;\n }\n log.error("FAILED. Class object is not supported: " + value, ex);\n return null;\n\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:36:08.777",
"Id": "46112",
"ParentId": "46107",
"Score": "3"
}
},
{
"body": "<p>With a limited set as this, you might as well skip the <code>Class.forName()</code> entirely and just keep the <code>if</code> statements. Exceptions are expensive, <code>if</code> statements not so much and there are only 4 options anyway.</p>\n\n<p>Furthermore you could reduce the semi-repeating a little by providing a unified version of the input to compare against (all characters in lower/uppercase).</p>\n\n<p>In fact, I would change it to use a simple lookup table.</p>\n\n<p>This results in something like this:</p>\n\n<pre><code>static Map<String, Class<?>> lookup = new HashMap<>();\n\nstatic {\n lookup.put(\"double\", Double.class);\n lookup.put(\"int\", Integer.class);\n lookup.put(\"bool\", Boolean.class);\n lookup.put(\"long\", Long.class);\n}\n\nprivate Class<?> getClass(String value){\n for(String key : lookup.keySet()){\n if(value.toLowerCase().contains(key.toLowerCase())){\n return lookup.get(key);\n }\n }\n return null;\n}\n</code></pre>\n\n<p>You can remove the intermediate <code>columnClass</code> variable entirely since the try-catch is now gone and there is no additional logic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:40:49.003",
"Id": "80450",
"Score": "0",
"body": "The OP's 'contains' logic and your switch logic are not the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:41:45.127",
"Id": "80451",
"Score": "0",
"body": "Ah, right. I first switched everything to `if` statements and stopped thinking at that point and moved it to a switch instead. Let me just revert that.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:42:36.843",
"Id": "80452",
"Score": "0",
"body": "I think the OP's use-case is significantly flawed anyway.... really, your answer is fine-ish, given the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:51:56.487",
"Id": "80456",
"Score": "0",
"body": "3rd approach, best approach."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:38:15.117",
"Id": "46113",
"ParentId": "46107",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46113",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:22:20.960",
"Id": "46107",
"Score": "2",
"Tags": [
"java",
"exception-handling"
],
"Title": "Java ClassNotFoundException Handling"
} | 46107 |
<p>I'm trying to build an app which crawls a website to find the emails that it has and prints them. I also want to allow the user to type "false" into the console when they want to skip the website (maybe the user has already found 2 emails and doesn't need any more).</p>
<p>Is the way I'm approaching this the best way? If not, then how can I improve, and what am I missing?</p>
<pre><code>require "nokogiri"
require "json"
require 'mechanize'
require 'anemone'
require "typhoeus"
require "timeout"
class String
def to_bool()
return true if self == "true"
return false if self == "false"
return nil
end
end
class Query
def initialize(keyword)
10.times do |n|
num = (n * 10 + 1).to_s
p num
req = Typhoeus::Request.new("https://www.googleapis.com/customsearch/v1?key=[my_key]&cx=018020274830505137072:utuofm0ugh0&q=" + keyword + "&start=" + num, followlocation: true)
res = req.run
File.open("file.json","w") do |file|
file.write(res.body)
end
continue = "true"
fs = File.read("file.json");
string = JSON.parse(fs);
string["items"].each do |item|
p continue.to_s + "<- item"
begin
Anemone.crawl("http://" + item["displayLink"] + "/") do |anemone|
anemone.on_every_page do |page|
if continue.chomp.to_bool == false
raise "no more please"
end
request = Typhoeus::Request.new(page.url, followlocation: true)
response = request.run
email = /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\.[a-zA-Z]{2,4}/.match(response.body)
if email.nil?
else
p email
begin
continue = Timeout::timeout(2) do
p "insert now false/nothing"
gets
end
rescue Timeout::Error
continue = "true"
end
end
end
end
rescue Exception => e
p e
continue = "true"
next
end
p "---------------------------------------------------------"
end
p "new request"
end
end
end
qs = Query.new("texas+web+development")
</code></pre>
| [] | [
{
"body": "<p>As @tokland pointed out, the major thing that jumps out when reading your code is the indentation problems. In most Ruby code you see, the standard indentation is 2 spaces. It looks like you are using hard-tabs, which are generally a bad idea. You should explore the settings of your text editor -- most have an option to insert spaces instead of tabs when you press the \"tab\" key. Here is your code would look like if indented properly:</p>\n\n<pre><code>require \"nokogiri\"\nrequire \"json\"\nrequire 'mechanize'\nrequire 'anemone'\nrequire \"typhoeus\"\nrequire \"timeout\"\n\nclass String\n def to_bool()\n return true if self == \"true\"\n return false if self == \"false\"\n return nil\n end\nend\n\nclass Query\n def initialize(keyword)\n 10.times do |n|\n num = (n * 10 + 1).to_s\n p num\n req = Typhoeus::Request.new(\"https://www.googleapis.com/customsearch/v1?key=[my_key]&cx=018020274830505137072:utuofm0ugh0&q=\" + keyword + \"&start=\" + num, followlocation: true)\n res = req.run\n File.open(\"file.json\",\"w\") do |file|\n file.write(res.body)\n end\n continue = \"true\"\n fs = File.read(\"file.json\");\n string = JSON.parse(fs);\n string[\"items\"].each do |item|\n p continue.to_s + \"<- item\"\n begin \n Anemone.crawl(\"http://\" + item[\"displayLink\"] + \"/\") do |anemone|\n anemone.on_every_page do |page| \n if continue.chomp.to_bool == false\n raise \"no more please\"\n end\n request = Typhoeus::Request.new(page.url, followlocation: true)\n response = request.run\n email = /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\\.[a-zA-Z]{2,4}/.match(response.body)\n if email.nil?\n else\n p email\n begin\n continue = Timeout::timeout(2) do\n p \"insert now false/nothing\"\n gets\n end\n rescue Timeout::Error\n continue = \"true\"\n end\n end \n end \n end \n rescue Exception => e\n p e\n continue = \"true\"\n next \n end\n p \"---------------------------------------------------------\"\n end\n p \"new request\"\n end\n end\nend\n\nqs = Query.new(\"texas+web+development\")\n</code></pre>\n\n<p>For your <code>to_bool()</code> function, this might be a little nitpicky, but I would rewrite it as a <code>case</code> statement like this:</p>\n\n<pre><code>class String\n def to_bool()\n case self\n when \"true\"; true\n when \"false\"; false\n else; nil\n end\n end\nend\n</code></pre>\n\n<p>The URL you're passing to <code>Typhoeus::Request.new</code> is ratehr long. You might consider doing something like this to shorten your line lengths a little:</p>\n\n<pre><code>base_url = \"https://www.googleapis.com/customsearch/v1?key=[my_key]&cx=018020274830505137072:utuofm0ugh0&q=\"\nreq_url = base_url + keyword + \"&start=\" + num\nreq = Typhoeus::Request.new(req_url, followlocation: true)\n</code></pre>\n\n<p>Or, if you want to be really diligent about not having long lines, you could do this:</p>\n\n<pre><code>base_url = \"https://www.googleapis.com/customsearch/v1\"\nkey = \"[my_key]\"\ncx = \"018020274830505137072:utuofm0ugh0\"\nreq_url = \"#{base_url}?key=#{key}&cx=#{cx}&q=#{keyword}&start=#{num}\"\n</code></pre>\n\n<p>You have a part of your code that goes <code>if email.nil?</code> (nothing) <code>else</code> (something). A better way to put this would be: </p>\n\n<pre><code>unless email.nil?\n p email\n # etc.\n</code></pre>\n\n<p>As a general note, you could make your code more concise by using less \"intermediate\" or \"throw-away\" variables. Take advantage of Ruby's method chaining and try condensing your code like this:</p>\n\n<pre><code>...\n\n# No need to define a variable res; req.run is short enough\nreq = Typhoeus::Request.new(req_url, followlocation: true)\nFile.open(\"file.json\", \"w\") do |file|\n file.write(req.run.body)\nend\n\n...\n\n# You can get rid of the fs and string variables and do this: \nJSON.parse(File.read(\"file.json\"))[\"items\"].each do |item|\n p continue.to_s + \"<- item\"\n # etc.\n\n...\n\n# You could change the name of the variable from request to req, \n# for consistency -- you named another Typhoeus request \"req\"\n# earlier in the code, and it doesn't look like you still need\n# that variable, so there's no harm in re-using the name \"req.\"\n\n# Notice how you can eliminate the need for the variables \"response\"\n# \"email\" like this:\nreq = Typhoeus::Request.new(page.url, followlocation: true)\nemail_pattern = /[-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+\\.[a-zA-Z]{2,4}/\nunless email_pattern.match(req.run.body).nil?\n # etc.\n</code></pre>\n\n<p>You might consider changing <code>if continue.chomp.to_bool == false</code> to <code>unless continue.chomp.to_bool</code>, or even <code>if continue.chomp == \"false\"</code>. In fact, I think I like the last way the best -- you could totally do away with monkey-patching a <code>String#to_bool</code> method and just compare <code>continue.chomp</code> to <code>\"true\"</code> or <code>\"false\"</code>. It's your call, of course. :)</p>\n\n<p>Lastly, this is just my 2 cents, but I think you could simplify the way you're using <code>continue</code>. If I'm understanding correctly, it starts as \"true\" and you want the program to keep running unless the user types \"false\" when prompted. I would consider doing away with your <code>String#to_bool</code> method and just comparing whether or not <code>continue.chomp.downcase</code> equals <code>\"stop\"</code>, <code>\"exit\"</code> or <code>\"quit\"</code>. You could do something like this:</p>\n\n<pre><code>stop_words = [\"stop\", \"exit\", \"quit\"]\ncontinue = \"\"\n\n...\n\nif stop_words.include? continue.chomp.downcase\n raise \"no more please\"\nend\n</code></pre>\n\n<p>This would save you from having to keep doing <code>continue = \"true\"</code> to make sure the program doesn't stop. As long as the value of <code>continue.chomp.downcase</code> is not one of the stop words, the program will keep running.</p>\n\n<p>I admit, though, that I don't really understand the use of <code>continue</code> in <code>p continue.to_s + \"<- item\"</code>, so maybe there is something I'm missing.</p>\n\n<p>Anyway, hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T18:13:11.723",
"Id": "82185",
"Score": "1",
"body": "Thank you for this huge and in depth answer. I must say that I will have to start indenting my code a bit better. The p continue.to_s is for debugging purposes but since this application now works I should've indeed removed it. Also the method chaining is actually quite a nice idea. The unless statement is indeed a very nice idea however I have some problems reading the code myself if I use unless however I will have to adapt :D. The case statement does indeed look more neater and the \"2 cents\" is I guess quite a nice way to make my program more intuitive. Thank you yet again"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T17:05:59.420",
"Id": "46828",
"ParentId": "46108",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46828",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:25:12.000",
"Id": "46108",
"Score": "3",
"Tags": [
"ruby",
"http",
"email",
"web-scraping"
],
"Title": "Crawling for emails on websites given by Google API"
} | 46108 |
<p>This is my second jQuery script: a universal tooltip for my entire web page. It took me a couple of days to research and make it work.</p>
<p>Now, I need help from the experts to optimize my newbie code.</p>
<p>This is one of the ways I can show the tooltip:</p>
<pre><code><a class="tooltip" data-tooltip="this is the text for my tooltip" href="#">My tooltip</a>
</code></pre>
<p>jQuery:</p>
<pre><code>$('.tooltip').hover(function(){
var text = $(this).attr('data-tooltip');
// get coordinates (top, left) of clicked element
var offset = $(this).offset();
// append tooltip to body, hide it, insert text
// center the tooltip to the clicked element and display it 3 pixels above the clicked element
$('<p class="tooltipbox"></p>')
.hide()
.text(text)
.appendTo('body')
.css("left", offset.left - (($(".tooltipbox").outerWidth() - $(this).width()) / 2 )) // center the tooltip
.css("top", offset.top - $(".tooltipbox").outerHeight() - 3)
.fadeIn(200);
}, function() {
// hover out the tooltip box
$('.tooltipbox').remove();
});
</code></pre>
<p>Something simple that works ok. Any way to improve my second jQuery script?</p>
| [] | [
{
"body": "<p>You don't really need a <code>tooltip</code> class on your target element. Since you already have a <code>data-tooltip</code> attribute, that's enough to find the relevant elements:</p>\n\n<pre><code>$(\"[data-tooltip]\") // find all elements with a data-tooltip attribute\n</code></pre>\n\n<p>This will also let you use the <code>tooltip</code> class for the actual tooltip, which makes more sense, given the name.</p>\n\n<p>You call <code>$(this)</code> multiple times instead of calling it once and storing it a variable, e.g.</p>\n\n<pre><code>var target = $(this);\n</code></pre>\n\n<p>You're also creating an element in your code, yet you're fetching it back through jQuery. That really isn't necessary, since that can go in a variable too. And you can use jQuery to your advantage a bit more.</p>\n\n<pre><code>var tooltip = $(\"<p></p>\")\n .hide()\n .addClass(\"tooltipbox\")\n .appendTo(document.body);\n</code></pre>\n\n<p>then, when positioning it, it might be nice with yet more variables, just to improve clarity a bit</p>\n\n<pre><code>var top = offset.top - tooltip.outerHeight() - 3,\n left = offset.left - (tooltip.outerWidth() - target.width()) / 2;\n\ntooltip.css({\n left: left,\n top: top\n});\n</code></pre>\n\n<p>Also, you may want to <em>not</em> hide the tooltip, if the user mouses over it. Doing so will require more trickery, though, so it's a bit out-of-scope for this answer. But the point is that right now, moving over the tooltip causes it to disappear, which can cause a bunch of flickering, since it's being displayed practically where the cursor already is. </p>\n\n<p>Lastly, it'd be better to use a <code>div</code> or <code>span</code> for the tooltip. While not strictly necessary, the <code>div</code> element is a better fit, because it's semantically neutral, and <code>span</code> just means \"a run of text\". A <code>p</code> element means paragraph, but a tooltip is usually just a tiny snippet; not really a paragraph in and of itself. There's nothing preventing you from using a <code>p</code> or any other element, but that also means you might as well use a more appropriate element than <code>p</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:15:39.297",
"Id": "46124",
"ParentId": "46111",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:32:39.903",
"Id": "46111",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "jQuery tooltip optimization"
} | 46111 |
<p>Two trees are called isomorphic if one of them can be obtained from other by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. </p>
<ol>
<li>Looking for code-review, optimizations and best practices</li>
<li>This class appears to be threadsafe. Am I correct ?</li>
<li>Verifying - Complexity appears to be O(n), where n is number of nodes of larger tree.</li>
</ol>
<p></p>
<pre><code>public final class IsomorphicChecker<T> {
private TreeNode<T> root;
/**
* Constructs a binary tree in order of elements in an array.
* The input list is treated as BFS representation of the list.
* Note that it is the clients reponsibility to not modify input list in objects lifetime.
*/
IsomorphicChecker(List<T> items) {
create(items);
}
private void create(List<? extends T> items) {
root = new TreeNode<T>(null, items.get(0), null);
final Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode<T> current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2;
if (items.get(left) != null) {
current.left = new TreeNode<T>(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode<T>(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
private static class TreeNode<T> {
TreeNode<T> left;
T item;
TreeNode<T> right;
TreeNode(TreeNode<T> left, T item, TreeNode<T> right) {
this.left = left;
this.item = item;
this.right = right;
}
}
/**
* Checks if trees are isomorphic
*
* @param tree the input tree
* @return true if input tree is isomorphic to current tree
*/
public boolean checkIsomortphic(IsomorphicChecker<T> tree) {
return checker(root, tree.root);
}
private boolean checker(TreeNode<T> node1, TreeNode<T> node2) {
if (node1 == null && node2 == null) {
return true;
}
if (node1 == null || node2 == null) {
return false;
}
if (!node1.item.equals(node2.item)) {
return false;
}
return checker(node1.left, node2.left) && checker(node1.right, node2.right) ||
checker(node1.left, node2.right) && checker(node1.right, node2.left);
}
public static void main(String[] args) {
IsomorphicChecker<Integer> nonRecursiveTraversal1 = new IsomorphicChecker<Integer>(Arrays.asList(1, 2, 3));
IsomorphicChecker<Integer> nonRecursiveTraversal2 = new IsomorphicChecker<Integer>(Arrays.asList(1, 2, 3));
IsomorphicChecker<Integer> nonRecursiveTraversal3 = new IsomorphicChecker<Integer>(Arrays.asList(1, 3, 2));
assertTrue(nonRecursiveTraversal1.checkIsomortphic(nonRecursiveTraversal2));
assertTrue(nonRecursiveTraversal1.checkIsomortphic(nonRecursiveTraversal3));
IsomorphicChecker<Integer> nonRecursiveTraversal4 = new IsomorphicChecker<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, null, null, null, 7, 8, null, null, null, null));
IsomorphicChecker<Integer> nonRecursiveTraversal5 = new IsomorphicChecker<Integer>(Arrays.asList(1, 2, 3, 4, 5, 6, null, null, null, 7, 8, null, null, null, null));
IsomorphicChecker<Integer> nonRecursiveTraversal6 = new IsomorphicChecker<Integer>(Arrays.asList(1, 3, 2, null, 6, 4, 5, null, null, null, null, null, null, 8, 7));
assertTrue(nonRecursiveTraversal4.checkIsomortphic(nonRecursiveTraversal5));
assertTrue(nonRecursiveTraversal4.checkIsomortphic(nonRecursiveTraversal6));
assertFalse(nonRecursiveTraversal4.checkIsomortphic(nonRecursiveTraversal1));
}
}
</code></pre>
| [] | [
{
"body": "<p>As a general comment, your code has improved significantly in the last few months. It is to your benefit for multiple reasons.... the 'easy' things to review have gone (code style, variable names, etc.) and the core logic is much more readable. Reviewing your work is harder now because the easy things are all done right.</p>\n\n<h2>TreeNode</h2>\n\n<ul>\n<li><p>final item:</p>\n\n<blockquote>\n <p>T item</p>\n</blockquote>\n\n<p>should be final.</p></li>\n<li><p>Even though it is an internal class, you should still have getters/setters for left, right, and item. This makes it more readable in the code instead of having chained field names.... for example:</p>\n\n<blockquote>\n<pre><code>if (!node1.item.equals(node2.item)) {\n</code></pre>\n</blockquote>\n\n<p>should be:</p>\n\n<pre><code>if (!node1.getItem().equals(node2.getItem())) {\n</code></pre>\n\n<p>Speaking of which ... do you intend to support <code>null</code> items?</p>\n\n<p>Another issue with not having the getters, is the confusion with code like:</p>\n\n<blockquote>\n<pre><code>current.left = new TreeNode<T>(null, items.get(left), null);\n</code></pre>\n</blockquote>\n\n<p>On that line, <code>current.left</code> is a TreeNode, but the <code>left</code> in <code>items.get(left)</code> is an integer. it would be better as:</p>\n\n<pre><code>current.setLeft(new TreeNode<T>(null, items.get(left), null));\n</code></pre></li>\n</ul>\n\n<h2>checkIsoMorphic(...)</h2>\n\n<ul>\n<li>should be spelled correctly ;-)</li>\n</ul>\n\n<h2>Checker</h2>\n\n<ul>\n<li>you should consider using the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#equals%28java.lang.Object,%20java.lang.Object%29\" rel=\"nofollow\">new-to-Java7 <code>Objects.equals(a,b)</code></a> methods instead of your own. To do that, you should implement the <code>equals()</code> and <code>hashCode()</code> methods on <code>TreeNode</code></li>\n</ul>\n\n<h2>Complexity</h2>\n\n<p>It is <em>O(n)</em>, but where <code>n</code> is the size of the smaller tree, not the larger tree.</p>\n\n<h2>Concurrency</h2>\n\n<p>This is a complicated question. But, basically, no, it is not.</p>\n\n<p>If you assume that the core tree is static for the lifetime of the <code>IsomorphicChecker</code> instance, and that the test teee is static for the lifetime of the <code>checkIsomorphic</code>, then, the code can be considered reentrant.</p>\n\n<p>But, even though you say <em>\"Note that it is the clients reponsibility to not modify input list in objects lifetime.\"</em>, that comment does not make the code thread-safe.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:15:25.723",
"Id": "80464",
"Score": "0",
"body": "Firstly I thank you and community to help me grow, but I had some comments - 1. final item : the reason for not making this final is because in general a collections say entry in linkedlist can be subject to changed value. Although this code does not change it, I still dont want to \"force\" to not change it. 2. About getters/setters: I just followed Linkedlist.java of Sun, and code was of internal Node. They did not add getter/setters as it was private and internal and it would be in my opinion an overkill. 3. I agree with complexity. its the smaller tree. 4. Interesting insight on concurrency"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T23:16:31.867",
"Id": "46118",
"ParentId": "46114",
"Score": "2"
}
},
{
"body": "<p>A minor bug: You get an <code>IndexOutOfBoundsException</code> for an empty list in <code>IsomorphicChecker.create(List<? extends T> items)</code>. You don't have a comment stating you need to input a list containing at least something. Consider returning <code>IllegalArgumentException</code> and adding a comment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-17T11:08:45.117",
"Id": "63141",
"ParentId": "46114",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T22:53:19.660",
"Id": "46114",
"Score": "2",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Isomorphic trees verification"
} | 46114 |
<p>I just jumped to a new project, which uses the active record pattern. It's a subscription service website. </p>
<p>I have the following <code>User</code> object that extends a framework specific <code>ORM</code> object:</p>
<pre><code>class User extends ORM {
public function isSubscriber()
{
$activeSubscription = $this->subscriptions->where('active','=',1)->find_all();
return $activeSubscription->count();
}
}
</code></pre>
<p>In client code, I have the following code:</p>
<pre><code>class Test_Controller extends Controller {
public function test()
{
// Framework speific way to get a current user
// returns User orm
$user = Auth::instance()->get_user();
var_dump($user->isSubscriber());
}
}
</code></pre>
<p>As you see, it's very straightforward and easy to understand. What's bothering me is that there's no way to test this simple <code>User</code> object unless I hack it.</p>
<p>The problem is that inside <code>ORM</code> objects, it uses a singleton pattern (something like <code>Database::getInstance()</code>) to get a database object and uses it to query to database, making it impossible to properly mock it.</p>
<p>I extracted <code>isSubscriber()</code> from <code>User</code> to a service like this:</p>
<pre><code>class SubscriberVerificationService {
public function __construct(SubscriptionRepositoryInterface $subscriptionRepository)
{
$this->subscriptionRepository = $subscriptionRepository;
}
public function isSubscriber(User $user)
{
$subscriptions = $this->subscriptionRepository->findActiveSubscriptionsByUserId($user->id);
return count($subscriptions);
}
}
</code></pre>
<p><strong>Client code</strong></p>
<pre><code>class Test_Controller {
public function __construct(SubscriberVerificationService $subscriberVerificationService)
{
$this->subscriberVerificationService = $subscriberVerificationService;
}
public function test()
{
$user = Auth::instance()->get_user();
var_dump($this->subscriberVerificationService->isSubscriber($user));
}
}
</code></pre>
<p>Now I can properly mock <code>SubscriptionRepositoryInterface</code> and and <code>User</code> objects in my test.</p>
<p>I feel like this is the way to go, but I just want to hear advice from people who use the active record pattern day-to-day.</p>
<p>It doesn't have to be a repository (<code>SubscriptionRepositoryInterface</code>) in the service. It can be a <code>Subscription</code> <code>ORM</code> as long as I can mock it.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T19:58:59.413",
"Id": "80643",
"Score": "0",
"body": "Unrelated, but I'm going to have nightmares now... but what hellish framework are you using? An ORM that is built around a singleton DB? ffs, that's just horrible. Oh, and as an asside: each time you call `$user->isSubscriber()`, do you really _want_ to perform that query? I mean: why not assign it to a property and return that? It's what most ORM's would do, after all"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T00:38:10.433",
"Id": "80664",
"Score": "0",
"body": "@EliasVanOotegem // Exactly what I want to ask to the previous maintainer. The framework is Kohana. So the actual code saves the result to a property for caching. I tried to make it simple enough to make people understand."
}
] | [
{
"body": "<p>Avoid hacking the code, if possible. Instead, you should have a test environment with a testing database. <code>Database::getInstance()</code> should use a configuration file containing the database connection parameters. It should configure itself to use the testing database when running unit tests.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:37:23.970",
"Id": "80478",
"Score": "2",
"body": "Well, isn't that an integration test?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:54:12.167",
"Id": "46128",
"ParentId": "46119",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T23:23:07.453",
"Id": "46119",
"Score": "4",
"Tags": [
"php",
"unit-testing"
],
"Title": "Active record pattern for a subscription service website"
} | 46119 |
<p>I have a class created for the sole purpose is to help handle files. The class holds a path (folder) that contains a single file at a time. Some extra properties to this class are: age of a file and max file size. I'm a very procedural style coder, and I'm trying to shift my work to a more OOP and eventually end up with something more SOLID.</p>
<p>The <code>FileHandler</code> receive a path and a file name. A majority of the functions described are basically a wrapper for system file manipulation. Now before you wonder why wrap things when you easily call them: I want to OOP this and on a bigger scale files are being manipulated for processing from another object. Another reason why I did this, up until recently <code>file_get_content()</code> was nice so far with files under 2MB but as it is growing now using file_get_content is no longer ideal, so on a larger application I will be changing commands.</p>
<p>Small goal:</p>
<p>A worker object process files by writing into files. If we set the max file to be MB, it needs to check for this, and create a new file, switch to it and continue writing into this. It should also check if the file it tries to write into is not idle for more than <code>MAX_EXPIRE</code>.</p>
<p>Another (independent) worker process files. It takes a single file, reads it, and moves it.</p>
<p>One of the more important concept that I got stuck on is that now I have this class that works but I need to refactor it into a Code with Intent (so that it follows SOLID). Is it already there? Can we do more? Should I break it into more classes to serve my purpose?</p>
<pre><code>class FileHandler
{
protected $path;
protected $file_name;
protected $max_file_size;
protected $max_age;
protected $creation_time = false;
public function __construct($file_path = "./", $file_name = '', $size = 5242880, $max_age = 900)
{
$this->path = $file_path;
$this->file_name = $file_name;
$this->max_file_size = $size;
$this->max_age = $max_age;
}
public function fileExists()
{
return @file_exists($this->path.'/'.$this->file_name);
}
public function directoryExists()
{
return @file_exists($this->path);
}
public function read()
{
if ($this->isFile($this->path."/".$this->file_name)) {
return @file_get_contents($this->path."/".$this->file_name);
}
throw new FileNotFoundException("File does not exist at path {$this->path}");
}
public function write(DataRepository $data)
{
if (!file_put_contents($this->path."/".$this->file_name, $data->getData(), FILE_APPEND)) {
throw new FileCannotWriteException("Unable to write in the log file : ".$this->file_name);
}
return true;
}
public function create()
{
if (!$this->directoryExists()) {
$this->makeDirectory($this->path);
}
$this->creation_time = time();
return file_put_contents($this->path."/".$this->file_name, '');
}
public function dataSize()
{
return @filesize($this->path."/".$this->file_name);
}
public function delete()
{
return @unlink($this->path."/".$this->file_name);
}
public function changeFile($file_name)
{
$this->file_name = $file_name;
}
public function changeDirectory($path)
{
$this->path = $path;
if (!$this->isWritable()) {
$this->makeDirectory($this->path);
}
}
public function writeLimit()
{
clearstatcache();
return ($this->dataSize()<$this->max_file_size) ? true : false;
}
public function isWritable()
{
return is_writable($this->path."/".$this->file_name);
}
private static function _glob($pattern, $flags = 0)
{
return glob($pattern, $flags);
}
public static function files($directory)
{
$glob = self::_glob($directory.'/*');
if ($glob === false) {
return array();
}
return array_filter($glob, function ($file) {
return filetype($file) == 'file';
});
}
public function makeDirectory($path, $mode = 0777, $recursive = false, $force = false)
{
if ($force) {
return @mkdir($path, $mode, $recursive);
} else {
return mkdir($path, $mode, $recursive);
}
}
public function moveFile($target)
{
$file_name = $this->file_name;
if (@rename($this->path."/".$file_name, $target."/".$file_name)) {
$this->file_name = "";
return true;
}
return false;
}
public function isFile($file)
{
return is_file($file);
}
public function getPath()
{
return $this->path;
}
public function lockFile()
{
if ($lock = @fopen($this->path."/".$this->file_name, "r+")) {
if (@flock($lock, LOCK_EX|LOCK_NB)) {
return $lock;
}
}
return false;
}
public function unlockFile($lock)
{
if ($lock !== null) {
if (flock($lock, LOCK_UN)) {
$lock = null;
return true;
}
}
return false;
}
public function getLastModification()
{
return filemtime($this->path."/".$this->file_name);
}
public function getRelativeFilename()
{
return $this->file_name;
}
public function getAbsoluteFilename()
{
return $this->path."/".$this->file_name;
}
public function isMaxAgeReached()
{
return $this->creation_time !== false && time() - $this->creation_time >= $this->max_age;
}
public static function generateFileFolderByDate($file)
{
$timestamp = false;
$name_type_1 = '#filelog_\d+_(\d+)\.log#';
$name_type_2 = '#(\d+)_filelog_\d+\.log#';
if (preg_match($name_type_1, $file, $match) || preg_match($name_type_2, $file, $match)) {
$timestamp = $match[1];
}
if ($timestamp === false) {
return '';
}
return date('Ymd', $timestamp);
}
}
</code></pre>
| [] | [
{
"body": "<p>The class in on itself seems fine to me, but the question you should be asking is <strong>what problem am I solving here?</strong>.</p>\n\n<p>OOP design works well on the big picture. Let's say you have a simple application where you want to CRUD a user's contacts. And let's say that you decided for some reason not to use a database but to use plain 'ol files.</p>\n\n<p>In that case, it makes sense for your application to work with <code>User</code> and <code>Contact</code> objects, where each <code>User</code> object contains a bunch of <code>Contact</code> objects. Have you noticed what the application doesn't know? That's right, <strong>the application has no idea where the data came from</strong>, and that's part of SOLID.</p>\n\n<p>In that sense, you would have <code>UserMapper</code> and <code>ContactMapper</code> to connect the User and Contact respectively to the files. Note that even the User or Contact objects don't know where the data they hold came from. Example:</p>\n\n<pre><code>class User {\n public $id;\n public $name;\n public $contacts;\n}\n\nclass UserMapper implements Mapper {\n public function fetch($id, User $user) {\n //Talk to files to get the information needed for the user, and map that information to the $user object.\n $user->name = $someQueryResult->getName();\n //etc...\n }\n public function save(User $user) {\n //Save user details back to files\n }\n}\n</code></pre>\n\n<p>Note that this way the User has no knowledge of where the data in it came from, could have been files, could have been a session or even a REST api.</p>\n\n<hr>\n\n<p>So you see, it's nice to have a FileHandler helper to do some tasks, but it all comes down to how things work together in your general application sense.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-27T12:35:42.977",
"Id": "51820",
"ParentId": "46120",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-02T23:30:51.780",
"Id": "46120",
"Score": "7",
"Tags": [
"php",
"object-oriented",
"design-patterns",
"file-system"
],
"Title": "Making a FileHandler more OOP-friendly using SOLID"
} | 46120 |
<p>I'm using this code to bring my phone numbers in a consistent format.</p>
<blockquote>
<p>Desired: <code>+(country code)phone number</code></p>
</blockquote>
<p>Possible patterns:</p>
<blockquote>
<p><code>01721234567</code> -> change to desired pattern</p>
<p><code>00491234567</code> -> change to desired pattern</p>
<p><code>+4912345678</code> -> do nothing, already desired pattern</p>
</blockquote>
<p>This is what I use:</p>
<pre><code>String number = allContactNumbers.get(i).get(j);
number = number.replaceAll("[^+0-9]", ""); // All weird characters such as /, -, ...
String country_code = getResources().getString(R.string.countrycode_de);
if (number.substring(0, 1).compareTo("0") == 0 && number.substring(1, 2).compareTo("0") != 0) {
number = "+" + country_code + number.substring(1); // e.g. 0172 12 34 567 -> + (country_code) 172 12 34 567
}
number = number.replaceAll("^[0]{1,4}", "+"); // e.g. 004912345678 -> +4912345678
</code></pre>
<p>For some reason I'm not happy with it though. I hope there is somebody to tell me, whether my code is written properly!</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:40:20.217",
"Id": "80468",
"Score": "0",
"body": "Is there a reason not to remove all `+` and all leading zeroes as step 1, and then just add the leading `+` at the end? No country code begins with 0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:42:58.023",
"Id": "80469",
"Score": "0",
"body": "like make every number begin with [1-9] and then simply add +? what would be the easiest way to do this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T04:31:33.590",
"Id": "80483",
"Score": "0",
"body": "@Edward - the existing code appears to assume a number beginning with \"0\" is a national number and prefixes it with a defined national prefix code. While no country code begins with 0, several countries use 0 as the prefix for national dialling (i.e. the same function a prefix of \"1\" serves for North American numbers)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:18:09.837",
"Id": "80499",
"Score": "0",
"body": "Given how localized telephone number formats can be, I think you'll get better answers if you can at least indicate which country/region you are focusing on. There are countries where phone numbers certainly don't start with 1, 0, 00 or nation-wide prefixes for that matter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:10:45.053",
"Id": "80543",
"Score": "0",
"body": "It would help us understand what you're trying to do if you replaced \"-> change to desired pattern\" with the actual result you're expecting. Are you asking for advice in writing code that meets your specification, or would you like advice on how best to handle international phone numbers? You say \"my phone numbers\". Is this intended as something that will be used by yourself, or is it intended to be used by a wide audience?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:27:19.220",
"Id": "80551",
"Score": "0",
"body": "@Jules: actually dialing 0 in Germany means that you're about to start direct dialing an international number. It's the IDD, which is different from the country code of 1 for North America. Dialing to US from Germany would start with \"0 1\" (IDD + country code). Dialing to Germany from US would start with \"011 49\" (IDD + country code). Dialing from the UK to the US would start with \"00 1\" etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:47:18.857",
"Id": "80553",
"Score": "0",
"body": "@Edward this isn't true. See http://en.wikipedia.org/wiki/List_of_dialling_codes_in_Germany - the international prefix in Germany is 00, 0 is described as the \"trunk prefix\" on that page, i.e. the same thing \"1\" is in NANP numbers. To dial the US from Germany, you'd dial 00 1 <number>."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:44:12.563",
"Id": "80576",
"Score": "1",
"body": "There is a _very_ good library written by Google which deals with a lot of the hard problems around number formatting: https://code.google.com/p/libphonenumber/"
}
] | [
{
"body": "<p>There are two aspects to this, the general design, and the implementation.</p>\n<h2>Implementation</h2>\n<p>The entire things should be extracted as a function. The first line of code:</p>\n<blockquote>\n<pre><code>String number = allContactNumbers.get(i).get(j);\n</code></pre>\n</blockquote>\n<p>indicates that this code is being run inside a loop (i,j). You need to extract it to be:</p>\n<pre><code>String number = normalizePhoneNumber(allContactNumbers.get(i).get(j));\n</code></pre>\n<p>and the function would look something like:</p>\n<pre><code>public String normalizePhoneNumber(String number) {\n ......\n return normalized;\n}\n</code></pre>\n<p>Right, about that function, putting your code in it ends up with:</p>\n<pre><code>public String normalizePhoneNumber(String number) {\n\n number = number.replaceAll("[^+0-9]", ""); // All weird characters such as /, -, ...\n \n String country_code = getResources().getString(R.string.countrycode_de);\n \n if (number.substring(0, 1).compareTo("0") == 0 && number.substring(1, 2).compareTo("0") != 0) {\n number = "+" + country_code + number.substring(1); // e.g. 0172 12 34 567 -> + (country_code) 172 12 34 567\n }\n \n number = number.replaceAll("^[0]{1,4}", "+"); // e.g. 004912345678 -> +4912345678\n\n return number;\n}\n</code></pre>\n<h2>Design</h2>\n<p>OK, about the design.... I believe this is a problem. Handling phone numbers is much more complicated than what you have.... it is really a challenging problem.</p>\n<p>It is easy enough to strip off the junk, but it gets hard really fast. For example, this is the the Queen of England's land-line number (not kidding):</p>\n<blockquote>\n<pre><code>Public Information Officer\nBuckingham Palace\nLondon SW1A 1AA\nTel (during 9am - 5pm (GMT) Monday to Friday): (+44) (0)20 7930 4832. Please note, calls to this number may be recorded.\n</code></pre>\n</blockquote>\n<p>As a Canadian, the international dialing code for this would be:</p>\n<pre><code>01144207934832\n</code></pre>\n<p>How will your script translate that in to:</p>\n<pre><code>+442079305832\n</code></pre>\n<p>I think you need to revise your plan for this problem, it is more complicated than you realize.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:17:47.663",
"Id": "80471",
"Score": "0",
"body": "I dont see why you have to dial `01144207934832` from canada instead of `+442079305832`. If this number: ` (+44) (0)20 7930 4832` is provided, my script would first make it:\n`+4402079304832` then in the second step it would erase the plus, delete all zeroes in the beginning (there are none in this example) then add the + again, this would lead to `+4402079304832`, which is wrong, since there is a 0 after the country code, BUT nobody would have it in his adressbook like this. and if, its their fault."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:37:18.120",
"Id": "80475",
"Score": "1",
"body": "The 011 is the international direct dial (IDD) number that must be dialed before the country code in Canada and the US. In Germany the IDD is 0 and the UK the IDD is 00."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:07:14.533",
"Id": "46130",
"ParentId": "46125",
"Score": "6"
}
},
{
"body": "<p>I don't have a handy way to check this code right now, but I believe it could be done like this:</p>\n\n<pre><code>// only keep digits\nnumber = number.replaceAll(\"[^0-9]\", \"\"); \n// trim leading zeroes\nnumber = \"+\" + number.replaceFirst(\"^0*(.*)\",\"$1\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:18:45.360",
"Id": "80472",
"Score": "0",
"body": "but in this example you dont check whether country code is given or not"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:29:56.267",
"Id": "80474",
"Score": "0",
"body": "That's correct. Reducing a phone number with embedded spaces and parentheses and possibly leading zeroes is relatively simple. Picking out the country code is, as the other answer notes, much more complex. For example +1 is actually not a country code but a signifier of the North American numbering plan. Further, the US and Canada both use +1 with no other signifier. And it's not even tidy geographically. A number beginning with +1 809 is the Dominican Republic but Haiti (on the other end of the same island!) is +509. There's no simple way to untangle it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T04:40:01.017",
"Id": "80485",
"Score": "1",
"body": "@Edward: \"For example +1 is actually not a country code but a signifier of the North American numbering plan.\" -- That's a distinction without a difference. From an outsider's perspective it's simply a country code that corresponds to more than one country. It is isomorphic to a country code of \"1\" with a national dialing prefix of \"1\" being ignored. The fact that multiple countries fall within the code is irrelevant to almost all purposes you might have for this kind of algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:22:40.470",
"Id": "80549",
"Score": "0",
"body": "@Jules: Many people, even in Europe, consider Canada and the US to be different countries. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:08:10.170",
"Id": "46132",
"ParentId": "46125",
"Score": "2"
}
},
{
"body": "<p>The biggest problem I have is that your code assumes a particular pattern for national numbers and international numbers that really ought to be end-user configurable. You should have preferences for international prefix (probably defaulting to \"00\"), for local national code (which you are currently retrieving from a resource, which should instead be used to set the default value for the preference) and for local number national prefix (which you currently have hardwired to \"0\"). Then, assuming you have a method to retrieve a preference with the signature <code>getPreferenceString(String preferenceName, String defaultValue)</code>, the algorithm would look something like:</p>\n\n<pre><code>String originalNumber = (whatever code you need to get the original number)\nString internationalPrefix = getPreferenceString(PREF_INTERNATIONAL_PREFIX, \"00\");\nString defaultCountryCode = getPreferenceString(PREF_DEFAULT_COUNTRY_CODE, \n getResources().getString(R.string.countrycode_de));\nString defaultCountryNationalPrefix = getPreferenceString(PREF_NATIONAL_PREFIX, \"0\");\n\n// strip any non-significant characters\nString number = originalNumber.replaceAll(\"[^0-9+]\", \"\"); \n// check for prefixes\nif (number.startsWith (\"+\")) // already in desired format\n return number;\nif (number.startsWith(internationalPrefix)) \n return number.replace(internationalPrefix, \"+\");\nelse if (number.startsWith(defaultCountryNationalPrefix))\n return number.replace(defaultCountryNationalPrefix, \"+\" + defaultCountryCode);\nelse \n throw new IllegalArgumentException (\"Number \" + originalNumber + \" does not have either an international or a national prefix\");\n</code></pre>\n\n<p>Note that this code can throw an exception if the phone number does not conform to expectations, e.g. if it lacks either an international or national prefix. In such a case, either the preferences are set incorrectly, or the phone has local numbers in its database, which the system I've described doesn't have enough information to translate. Such numbers wouldn't be usable on a mobile phone, as mobile networks do not typically support dialing local numbers, but I don't know that there aren't desk phones with Android installed on them somewhere...</p>\n\n<p>As a side comment, you're doing your string comparisons in an odd way. You should use <code>string.equals(\"expected value\")</code> not <code>string.compareTo(\"expected value\") == 0</code> to check for equality (and <code>!string.equals(...)</code> rather than <code>... != 0</code> for inequality) because (1) it's easier to read and (2) it's slightly more efficient at run time. </p>\n\n<p>Also, there's a method <code>startsWith(String)</code>. Use it, rather than extracting a substring and comparing the result, which is error-prone (if you get the length of the substring wrong the comparison will always fail, or if the string you're comparing is shorter than the prefix you're checking for an <code>IndexOutOfBoundsException</code> will be thrown).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:03:13.177",
"Id": "46143",
"ParentId": "46125",
"Score": "1"
}
},
{
"body": "<p>If you are going to use regular expressions, use them effectively so that you don't have to resort to low-level string manipulation. In particular, make use of capturing parentheses to figure out what was found during matching.</p>\n\n<pre><code>public class TelephoneNumberCanonicalizer {\n private static final Pattern EUROPEAN_DIALING_PLAN = Pattern.compile(\"^\\\\+|(00)|(0)\");\n private final String countryCode;\n\n public TelephoneNumberCanonicalizer(String countryCode) {\n this.countryCode = countryCode;\n }\n\n public String canonicalize(String number) {\n // Remove all weird characters such as /, -, ...\n number = number.replaceAll(\"[^+0-9]\", \"\");\n\n Matcher match = EUROPEAN_DIALING_PLAN.matcher(number);\n if (!match.find()) {\n throw new IllegalArgumentException(number);\n } else if (match.group(1) != null) { // Starts with \"00\"\n return match.replaceFirst(\"+\");\n } else if (match.group(2) != null) { // Starts with \"0\"\n return match.replaceFirst(\"+\" + this.countryCode);\n } else { // Starts with \"+\"\n return number;\n }\n }\n}\n</code></pre>\n\n<h3>Test case</h3>\n\n<pre><code>public static void main(String[] args) {\n String[] testCases = new String[] {\n \"01721234567\",\n \"00491234567\",\n \"+4912345678\"\n };\n TelephoneNumberCanonicalizer german = new TelephoneNumberCanonicalizer(\"49\");\n for (String testCase : testCases) {\n System.out.printf(\"%s -> %s\\n\", testCase, german.canonicalize(testCase));\n }\n}\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>01721234567 -> +491721234567\n00491234567 -> +491234567\n+4912345678 -> +4912345678\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:25:37.730",
"Id": "46148",
"ParentId": "46125",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46130",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T01:18:17.517",
"Id": "46125",
"Score": "9",
"Tags": [
"java",
"regex"
],
"Title": "Bring phone numbers in consistent format"
} | 46125 |
<p>Please be brutal and let me know what you think of the code below, if written at an interview.</p>
<p>Problem:</p>
<blockquote>
<p>Given an index <em>k</em>, return the kth row of the Pascal's triangle.</p>
<p>For example, given k = 3, return [1,3,3,1].</p>
<p><strong>Time it took:</strong><br>
25 minutes (perfectly working solution)</p>
<p><strong>Space Complexity:</strong><br>
O(K)</p>
<p><strong>Time Complexity:</strong><br>
O(N<sup>2</sup>)?</p>
</blockquote>
<hr>
<pre><code>public ArrayList<Integer> getRow(int rowIndex) {
List<ArrayList<Integer>> allList = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> toAdd = new ArrayList<Integer>();
if(rowIndex==0){
toAdd.add(1);
return toAdd;
}
if(rowIndex>=1){
toAdd = new ArrayList<Integer>();
toAdd.add(1);
toAdd.add(1);
allList.add(toAdd);
if(rowIndex==1){
return toAdd;
}
}
for(int i=1; i<rowIndex; i++){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(1);
for(int j=1; j<allList.get(i-1).size(); j++){
temp.add(allList.get(i-1).get(j-1) + allList.get(i-1).get(j));
}
temp.add(1);
allList.add(temp);
}
return allList.get(rowIndex-1);
}
</code></pre>
| [] | [
{
"body": "<h2>Types</h2>\n<p>Given the description, I would assume that the return value is supposed to be <code>int[]</code> instead of <code>List<Integer></code>....</p>\n<p>... but, you are not using the more general <code>List<Integer></code> value, but instead the <code>ArrayList<Integer></code>. Always use the most general class type for your interfaces.</p>\n<p>Also, by keeping the data as Integer values, you are doing a lot of boxing, and unboxing in the loops. Really, you should keep the calculations as Java primitives (<code>int</code>), and then box the results if needed.</p>\n<h2>Conditions</h2>\n<p>Your code has a special-case for row 0, where it returns <code>[1]</code>. By preference, I recommend not having special cases, although it is a rule I bend often.</p>\n<p>Still, after the <code>rowIndex == 0</code> special case, you then check to see whether it is <code>rowIndex >= 1</code>. This does not make sense because the <code>rowIndex == 0</code> case returned from the function, so the other condition is useless. Well, not quite useless, it avoids an error condition for negative values. But, the negative-value condition should have been checked at the method start. Basically, it is a useless check. Consider this restructure:</p>\n<pre><code>if (rowIndex < 0) {\n throw new IllegalArgumentException("Nevative row");\n}\nif(rowIndex==0){\n toAdd.add(1);\n return toAdd;\n}\n\ntoAdd = new ArrayList<Integer>();\ntoAdd.add(1);\ntoAdd.add(1);\nallList.add(toAdd);\nif(rowIndex==1){\n return toAdd;\n}\n</code></pre>\n<h2>Conclusion</h2>\n<p>I agree that the complexity is about <em>O(n<sup>2</sup>)</em>, but I know it must be psosible to do it faster. The data types are a problem, but the result looks accurate.</p>\n<h2>Alternative...</h2>\n<p>So, I cheated, and looked at wiki, and it has a <a href=\"http://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_a_row_or_diagonal_by_itself\" rel=\"nofollow noreferrer\">relatively easy function for calculating the row values for a function</a>. I adapted it here. This is the way I would have done it, if I was able to google the algorithm. I would have used a similar approach to you, but as arrays-of-int instead, if I could not search the algorithm.</p>\n<pre><code>public static final int[] pascalRow(final int row) {\n // using same names as wikipedia:\n // http://en.wikipedia.org/wiki/Pascal%27s_triangle#Calculating_a_row_or_diagonal_by_itself\n int n = row + 1;\n int[] ret = new int[n];\n int val = 1;\n final int mid = (n)/2;\n for (int k = 0; k <= mid; k++) {\n ret[k] = val;\n ret[n - 1 - k] = val;\n val = (int)(val * ((n - k - 1) / (double)(k + 1)));\n }\n return ret;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:38:07.827",
"Id": "80652",
"Score": "0",
"body": "I don't understand what you mean by the under condition is useless. If rowIndex is 0, then my function returns end of story. As far as the [x, x,x]values going, that's just how the problem describes it, the return value is supposed to be a List; so that's not an issue. Thank you for your time as always."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:41:33.223",
"Id": "80653",
"Score": "0",
"body": "@bazang - edited to include an 'revised' version of what I expect."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:54:12.280",
"Id": "46137",
"ParentId": "46131",
"Score": "5"
}
},
{
"body": "<p><strong>Here is an alternative design:</strong></p>\n\n<p>Write a function that takes a row and returns the next row, and then call this function <code>k</code> times:</p>\n\n<pre><code>private ArrayList<Integer> getNextRow(ArrayList<Integer> currRow)\n{\n ArrayList<Integer> nextRow = new ArrayList<Integer>();\n nextRow.add(1);\n for (int i=0; i<currRow.size()-1; i++)\n nextRow.add(currRow.get(i)+currRow.get(i+1));\n nextRow.add(1);\n return nextRow;\n}\n\npublic ArrayList<Integer> getRow(int rowIndex)\n{\n ArrayList<Integer> row = new ArrayList<Integer>();\n row.add(1);\n for (int i=0; i<rowIndex; i++)\n row = getNextRow(row);\n return row;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:52:45.753",
"Id": "46219",
"ParentId": "46131",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46137",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:07:59.487",
"Id": "46131",
"Score": "5",
"Tags": [
"java",
"algorithm",
"interview-questions"
],
"Title": "Pascal triangle produced for a particular integer K"
} | 46131 |
<p>I have previeous;y posted my php code with way to many nested blocks I hope I fixed it right. </p>
<p>I'd also like some tips on my OOP, as this is new to me.</p>
<pre><code>class event {
//Builds the event in html
public function renderEvent($Array) {
echo "</p>";
echo "<p>";
if ($Array['ad']) {
echo "<img src='images/" . $Array['ad'] . "' alt='event-ad' width='300' height='100' />";
} else {
echo "&nbsp;";
}
echo "</p>";
echo "<p>&nbsp;</p>";
echo "<div class='toggleLink' style='cursor: pointer; color: #333;'>";
echo $Array['starttime'] . " " . $Array['title'];
echo "</p>";
echo "</div>";
echo " <div class='toggle'>";
echo "<p class='toggleLink'>";
echo "(" . $Array['starttime'] . "-" . $Array['endtime'] . ") " . $Array['location'] . " - " . $Array['address'] . " - Admission Price: $" . $Array['price'] . "<br>" . $Array['description'];
echo "</div>";
}
public function recurring($recur, $event, $Date, $savedDate) {
$recurring = $recur['type'];
$displaydate = $Date->format("Ymd");
$startdate = date('Ymd', strtotime($recur['startdate']));
$enddate = date('Ymd', strtotime($recur['enddate']));
Switch ($recurring) {
Case 'None':
//If the date in the range is the same as the displaydate
if ($Date->format("Ymd") == $savedDate->format('Ymd')) {
//Create event
$this->renderEvent($event);
}
break;
Case 'Daily':
//Check margin between start and end date of recurring event
$this->check_date_range($displaydate, $startdate, $enddate);
$this->recur_daily($recur, $event, $Date);
break;
Case 'Weekly':
//Check margin between start and end date of recurring event
$this->check_date_range($displaydate, $startdate, $enddate);
$this->recur_weekly($recur, $event, $Date);
break;
Case 'Monthly1':
//Check margin between start and end date of recurring event
$this->check_date_range($displaydate, $startdate, $enddate);
$this->recur_Monthly1($recur, $event, $Date);
break;
Case 'Monthly2':
//Check margin between start and end date of recurring event
$this->check_date_range($displaydate, $startdate, $enddate);
//Code still to be made.
break;
}
}
public function check_date_range($displaydate, $startdate, $enddate) {
//Check margin between start and end date of recurring event
if (!($displaydate >= $startdate) && !($displaydate <= $enddate)) {
exit();
}
}
public function recur_daily($recur, $event, $Date) {
//Check if the day number is the same
if ($recur['day'] - 1 == $Date->format("w")) {
//Create event
$this->renderEvent($event);
}
}
public function recur_weekly($recur, $event, $Date) {
$first = DateTime::createFromFormat('m/d/Y', $recur['startdate']);
$second = DateTime::createFromFormat('m/d/Y', $recur['enddate']);
if ($recur['enddate'] > $recur['startdate']) {
}
$weekRange = floor($first->diff($second)->days / 7);
$weeks = $weekRange / $recur['weekday'];
//Returns the week cuurent week to display
$currentWeek = $Date->format("W");
//Loop for every #(1, 2, 3, 4) of weeks
for ($n = 0; $n < $weeks; $n++) {
//Display event if weeks are the same
if ($n == $currentWeek) {
//Put days in array
$days = explode(",", $recur['weekday']);
//If number day of the week is the same display event
foreach ($days as $day) {
//Check if the day number is the same
if ($day == $Date->format("w")) {
//Create event
$this->renderEvent($event);
}
}
}
}
}
public function recur_Monthly1($recur, $event, $Date) {
//make string to date
$bdate = strtotime($recur['startdate']);
$edate = strtotime($recur['enddate']);
$monthsRange = 0;
//get how many month are between two dates
while ($bdate < $edate) {
$monthsRange++;
$bdate = strtotime('+1 MONTH', $bdate);
if ($bdate > $edate) {
$monthsRange--;
}
}
$months = $monthsRange / $recur['month'];
//Do for (selected number up to 4) every month
for ($n = 0; $n < $months; $n++) {
//Check to see if it is the same day in the month
if ($recur['day'] == $Date->format('d')) {
//Create event
$this->renderEvent($event);
break;
}
}
}
//Display event with renderEvent
public function dispalyEvent(DateTime $Date) {
$event_query = mysql_query("SELECT * FROM calendar WHERE Approved='Approved' ORDER BY starttime");
//Go through all event in the database
while ($event = mysql_fetch_array($event_query)) {
$date1 = new DateTime($event['startyear'] . $event['startmonth'] . $event['startdate']);
$date2 = new DateTime($event['endyear'] . $event['endmonth'] . $event['enddate']);
$date2->modify('+1 day');
$period = new DatePeriod($date1, new DateInterval('P1D'), $date2);
$title = $event['title'];
$name = $event['name'];
$recur_query = mysql_query("SELECT * FROM recur WHERE title = '$title' AND name = '$name'");
$recur = mysql_fetch_array($recur_query);
//Go through each date in the range
foreach ($period as $savedDate) {
$this->recurring($recur, $event, $Date, $savedDate);
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:10:36.447",
"Id": "80477",
"Score": "0",
"body": "Please state the goal of your class so that we can help you refactor it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:56:55.123",
"Id": "80480",
"Score": "0",
"body": "well I want to display events and depending if they are recurring it could display multiple times on different dates in the calendar. My goal is to make my code as efficient as possible and eliminate DRY (don't repeat yourself). And also to see if I used the proper way to program as I am a beginner."
}
] | [
{
"body": "<p>Given that this is a follow-up question, and <a href=\"https://codereview.stackexchange.com/questions/45801/i-have-a-huge-function-filled-with-nested-blocks\">I've dealt with some issues here already</a>, I'm not going to be as verbose. I will, however, refer to a couple of my initial critiques, and offer some advice on this code, too. I see several issues, I've listed them below, but some do require some explanation, so if after a huge blob of text, you see a new list item, that means I'm touching on a new subject. Just for clarity, because this answer could do with some refactoring, too :)</p>\n\n<ul>\n<li><p><strong><em>Functions return</em></strong>: Functions, or methods for that matter, <strong><em>do not <code>echo</code> anything</em></strong>. Functional entities (functions, methods, and classes, for that matter) <em>return</em> things, they do not <code>echo</code>. The <code>renderEvent</code> method you have is still littered with <code>echo</code> statements.</p></li>\n<li><p><strong><em>Classes throw, they don't exit</em></strong>: A class is a single, supposedly portable unit. It should not be able to control the entire flow of the application it is a part of. That's why methods contain no <code>exit</code> calls, your do. <strong><em>DON'T. DO. THAT!</em></strong>. When a method encounters an issue, and the class has no code to deal with such an event, then you have an <em>\"exceptional\"</em> situation. What any good class then does is <em>throw an exception</em>. For example:</p></li>\n</ul>\n\n<p>Say I have this method:</p>\n\n<pre><code>public function notGreatButJustAnExample(array $argument)\n{\n $return = '';//instead of echo\n if (isset($argument['images']) && is_array($argument['images']))\n {\n foreach ($argument['images'] as $k => $image)\n {\n $return .= ($k+1).' image == '. $image. PHP_EOL;\n }\n }\n if (!isset($argument['important_key']))\n {//without this, I can't continue\n throw new InvalidArgumentException(__METHOD__.' needs important_key to be set in argument-array');\n }\n}\n</code></pre>\n\n<p>I need this key, without it, the method can't do its job. If that key is missing, the data is, too, and the method has received an invalid argument. Hence, the <code>InvalidArgumentException</code> is thrown.<Br>\nOther exceptions that could be thrown in such a method is when 2 keys need to be arrays that are equally long, for example <code>$argument['images']</code> and <code>$argument['img_descriptions']</code>. If the two arrays exist, but aren't equally long, then the code that called the method probably contained bad logic, in that case:</p>\n\n<pre><code>if (count($argument['images']) != count($argument['img_descriptions']))\n{\n throw new LogicException('Number of images does not match number of descriptions');\n}\n</code></pre>\n\n<p>Notifies the user of this problem. Think of exceptions as your class shouting back at whomever calls one of its methods: <em>\"If you want me to do so and so, then I expect valid input. If I don't have valid input, then that's your problem\"</em>. That's why you throw it back to the caller.</p>\n\n<ul>\n<li><p><strong><em>only make <code>public</code> what needs to be called</em></strong>: What the user doesn't need, he shouldn't see. Any method that is used <em>internally</em> by the class, shouldn't be callable from anywhere else. The user should <em>not</em> be allowed to call it, so make it <code>protected</code> (or <code>private</code>). I tend to prefer <code>protected</code>, which means that, if every you extend your class, the children will have access to these methods, too. <code>private</code> methods only exist in the scope of the class itself. <code>protected</code> exists in the scope of the class, and all of its children.</p></li>\n<li><p><strong><em>Style and standards</em></strong>: Try to adhere to <a href=\"http://www.php-fig.org\" rel=\"nofollow noreferrer\">the coding standards</a> as much as possible. That is to say: class names start with an Upper-case char, and their opening brace go on the next line. You wrote <code>class event {</code>.</p></li>\n</ul>\n\n<p>According to the standards (unofficial, but it's the only one we've got), it should be written like this:</p>\n\n<pre><code>class Event\n{\n</code></pre>\n\n<ul>\n<li><strong><em>A S.O.L.I.D. start</em></strong>: The SOLID principles are well known by many. I'm prepared to defend the following statement(s) to the bitter end, though I am aware that this might enrage some people. The most important of all <a href=\"http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)\" rel=\"nofollow noreferrer\">SOLID principles</a> is, IMHO, SRP. The <em>Single Responsability Prinsiple</em>. These principles aren't just for show. A lot of <em>good practices</em> and principles sound great in theory, but the SOLID principles tend to be quite easy to follow, especially the SRP. Not only are they easy to apply, they will in fact help you write better, more generic code quite easily.<br>\nI've always been skeptical about <em>\"ultimate mega-super-unbeatable-design theories\"</em>, believe you me. But these 5 principles are just simple, common-sense ideas put together. What is wrong with common sense?</li>\n</ul>\n\n<p>If you answered nothing to my rhetorical question, you should realize 2 things: First, you don't answer to rhetorical questions and second: Your class violates the SRP quite blatantly. It connects to the DB and fetches data (1 task/reason to change), formats it (another task/reason to change) <em>and</em> takes care of the output (another task/reason to change). That's 3 distinct responsibilities. Ideally, you'd use 3 classes for this, but given PHP's suitability as a templating language, 2 will do, too (the output part can be a simple PHP+HTML script, containing <em>no logic</em> other than the occasional loop and <code>if-else</code>.</p>\n\n<ul>\n<li><strong><em>\"What's in a name?\"</em></strong>: <em>That, which you call <code>event</code>, by any other name would work as good</em>... Or something. Well, when writing code, there's a lot in a name, especially when classes are involved.</li>\n</ul>\n\n<p>Allow me to explain myself:<Br>\nGood code is <em>self-documenting</em>. A class name, and its methods tell the user a lot about what it's for. Your class is called <code>Event</code>. If I see a line of code that reads <code>new Event()</code>, I expect it to create a data model, an instance that describes an <em>event</em> of sorts.<br>\nOnce I notice I can pass it instances of <code>DateTime</code>, I'll assume the instance describes an event that can be recurrent, or stretch out over a period of time. I'd also expect to be able to pass strings (descriptors) and perhaps an array of attendees to this object.</p>\n\n<p>This data itself should be gotten via an <code>EventMapper</code> instance, which does the DB work. At least, I'd expect to see something of the sorts. This mapper could have methods that return <code>Event</code> instances, depending on arguments (for example: 2 dates, returns an array of all events that take place in that date range).</p>\n\n<p>These <code>Event</code> instances could then move on to an <code>EventRenderer</code> class, which has a <code>getOutput</code> or <code>render</code> method. The constuctor could take a value (preferably predefined constants) that set the output mode I'd like. When I call this <code>render</code> method, I'd expect it to <strong><em>return</em></strong> something that I can echo, if I so desire. I might choose to write the output to a file or DB, too. That's up to me, not up to the class to decide. Hence: <em>method's don't echo</em>. Here's an example:</p>\n\n<pre><code>class RenderEvent\n{\n const RENDER_JSON_MODE = 1;\n const RENDER_HTML_MODE = 2;\n const RENDER_XML_MODE = 4;\n const RENDER_ALL_MODES = 7;\n\n protected $mode = null;\n\n public function __construct($mode = self::RENDER_HTML_MODE)\n {//default\n $this->mode = $mode;\n }\n\n /**\n * Takes an event, renders it according to the set mode\n * @param Event $event\n * @return string\n */\n public function render(Event $event)\n {\n if ($this->mode === self::RENDER_ALL_MODES)\n {//return assoc array, use constants as key\n return array(\n self::RENDER_JSON_MODE => $this->setOutputMode(self::RENDER_JSON_MODE)\n ->render($event),\n self::RENDER_HTML_MODE => $this->setOutputMode(self::RENDER_HTML_MODE)\n ->render($event),\n self::RENDER_XML_MODE => $this->setOutputMode(self::RENDER_XML_MODE)\n ->render($event),\n );\n }\n if ($this->mode === self::RENDER_JSON_MODE)\n return $event->toArray();//or something\n $dom = new DOMDocument();\n if ($this->mode === self::RENDER_HTML_MODE)\n {\n $dom = new DOMDocument;\n $table = $dom->createElement('table');\n //build dom\n return $dom->saveHTML();\n }\n //no if required, we're rendering XML once we get here\n //very similar to render HTML, but:\n return $dom->saveXML();\n }\n\n /**\n * Change output mode\n * @param int $mode\n * @return EventRenderer\n * @throws InvalidArgumentException\n */\n public function setOutputMode($mode)\n {\n if ($mode === self::RENDER_ALL_MODES)\n $this->mode = $mode;\n else if (($mode & self::RENDER_ALL_MODES) === $mode)\n $this->mode = $mode;\n else\n throw new InvalidArgumentException('Use constants for modes, '.$mode.' is not a valid output mode');\n return $this;\n }\n\n}\n</code></pre>\n\n<p>This code allows the user to use your events in ajax calls, or NoSQL data storage situations:</p>\n\n<pre><code>$event = new Event();//<-- assume everything is set up\n$renderer = new EventRenderer(EventRenderer::RENDER_JSON_MODE);\n$json = $renderer->render($event);\n$mongo->save($json);\n//or in AJAX call context:\necho $json;\n</code></pre>\n\n<p>As you can tell, I have the choice here: echo or pass the rendered data. That makes this code a more likely candidate for re-use.</p>\n\n<ul>\n<li><p><strong><em>type-hints</em></strong>: You've used 1 type-hint. That's all fine and dandy, but I'd like to see you use type-hints as much as possible. The first method takes one argument <code>$Array</code>, but what if I were to pass a string? change the signature to <code>public function renderEvent(array $Array)</code>, to prevent such issues.</p></li>\n<li><p><strong><em>Markup is structured, strigs are not</em></strong>: stringing together markup is un-maintainable. As you start getting the hang of OOP, you'll perhaps one day want to <code>extend</code> this class. Having it string together markup will mean you'll have to override any method that does so, in order for it to work in the child's context. That's not ideal.<BR>\nAdd to that the fact that stringing together markup is a delicate procedure, and once a bug rears its ugly head, it's a nightmare to debug.<br>\nUsing a <code>DOMDocument</code> instance allows you to create nodes, hold references to them, and add, remove and move them about in the dom as you please. Ensuring valid markup every time. Chec <a href=\"http://www.php.net/DOMDocument\" rel=\"nofollow noreferrer\">the documentation for <code>DOMDocument</code> and all its related classes</a>. It's a bit tricky to get your head round at first, but it <em>is</em> worth it.</p></li>\n</ul>\n\n<hr>\n\n<p>Now, <code>mysql_*</code>. You've commented on my other answer, saying you are aware of <code>mysql_*</code> being deprecated, but the project is already using this extension. Pardon my french, but that's utter bulls***.<br>\nIf the existing code is using a <em>deprecated</em> an (hopefully) soon to be removed extension, the <em>last</em> thing you should be doing is adding new code that makes that very same mistake. You'll have to refactor the existing code at some point in the future. By adding more code that will need to be refactored, the only thing you're doing is increasing the amount of code that will need to be re-written.</p>\n\n<p>Do I mean that you should refactor the entire project before you start adding code? Not necessarily. But if you are going to add new features/code, then at least write them in such a way that <em>the new code</em> doesn't require refactoring! That's common sense.</p>\n\n<p>I always like to use extensive analogies to explain what I'm saying, so humour me and let me give you a weird analogy for this, too:<br>\nSay you have a house, it's not brand new, but it's home. There are a couple of doors that squeek and the carpets could do with some cleaning. Due to circumstances, you've had to spend your savings on an annexe you're building. Would you fit that annexe with dirty, old, worn out carpets, or would you fit new, nicer carpets there first? Of course you'd go for the new carpets, and you'd start saving up to fit new carpets in the rest of the house as soon as possible.<br>\nWhat you're doing is the exact opposite. You're writing new code (ie building an annexe), but you're fitting it with the same old, worn out and scruffy carpets. That kind of takes the shine away, doesn't it? And to add insult to injury, you'll have to save up some more, because when you want to refit the carpet, you'll have to buy more, and there's going to be more work that needs doing, too. Save yourself the pain of having to do twice the work: whatever code you add, make sure it's future-proof. Meanwhile, work on ditching that <code>mysql_*</code> from the existing code-base.</p>\n\n<p>You can do this quite easily now that you've decided to go with an OO approach. The great thing about your using classes is that a class needn't care about anything that is going on outside of itself. It can hold its own DB connection (not create it itself, but rather _inject it as a dependency => SOLID), using whatever extension <em>you</em> (as its author) choose. I'd suggest you provide your class with an up-to-date db connection, and think about refactoring the rest of the project in due time.<Br>\nWhatever you do <strong><em>do not increase the amount of code you'll need to refactor</em></strong> by simply adding <code>mysql_*</code> code. Whatever new code code you add should use the new extensions. The old code should be re-factored, or factored out.</p>\n\n<p><strong>Some other niggles</strong><Br>\nThe code you have now still suffers from the same injection vulnerabilities I pointed out in my initial answer. Other issues still exist, too, like your creating new <code>DateTime</code> instances too many times. The <code>recur*</code> methods, too, could do with a bit more work.<br>\nAs luck would have it, I've <a href=\"https://codereview.stackexchange.com/questions/46047/calculate-a-month-later-than-current-month-without-rolling-over-to-next-month/46049#46049\">written a substantial answer that is very much related to what you're doing</a> just yesterday. Check that out, and refactor the recurrency methods accordingly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:11:38.677",
"Id": "46154",
"ParentId": "46133",
"Score": "4"
}
},
{
"body": "<p>You need to explain your code better. Give an example of some input and output. What does the value of <code>$Date</code> represent and how does it relate to the purpose of diplsayEvent()? Define a daily, weekly, monthly1, and monthly2 reoccurring event. What is the format and meaning of <code>$recur['weekday'] $recur['day'] $recur['month'] $event['startdate'] $event['enddate'] $event['startyear'] $event['startmonth']</code>? This information is important to evaluate if your code works as intended and how it can be improved. I had to make some assumptions below. My suggestions are in the comments. I changed the style of the code just because it is easier for me to read. There is nothing wrong with your style it is neat and consistent. You should continue using your style.</p>\n\n<pre><code>class Event\n{\n public function dispalyEvent(DateTime $Date)\n {\n // I'm not sure of the format of startdate and enddate, but this optimization might be possible.\n // SELECT * FROM calendar WHERE Approved='Approved' AND startdate <= $Date AND $Date <= enddate ORDER BY starttime\"\n // This MySQL extension is deprecated switch to a supported extension.\n // If you call this function with multiple $Dates then run this query once, cache it, and pass the results to this function.\n $event_query = mysql_query(\"SELECT * FROM calendar WHERE Approved='Approved' ORDER BY starttime\");\n // Check return value.\n if($event_query == false)\n return;\n\n // You don't use numbered indices so exclude them.\n while($event = mysql_fetch_array($event_query,MYSQL_ASSOC))\n {\n // Move date logic together.\n $title = $event['title'];\n $name = $event['name'];\n\n // 1. Warning: SQL Injection Vulnerability\n // Any user that may alter $title or $name may change your query.\n // mysql_query() normally only allows one statement per call, but do not depend on that for security. It also doesn't prevent selecting other tables.\n // 2. Select based on unique IDs not things like title and name, which might not be unique.\n // 3. There seems to be a one-to-one mapping between rows in calendar and rows in recur, with title and name being duplicated. Add the columns of recur to calendar to reduce the number of queries.\n // Post your database design to http://dba.stackexchange.com/ for more suggestions on how to improve your database.\n $recur_query = mysql_query(\"SELECT * FROM recur WHERE title = '$title' AND name = '$name'\");\n // Check return value.\n if($event_query == false)\n continue;\n $recur = mysql_fetch_array($recur_query);\n if($recur == false)\n continue;\n\n // Now let's simplify your date logic.\n\n // Again, I'm not sure of the format of startdate and enddate. You might have to convert these to a DateTime using a different method.\n $startdate = new DateTime($recur['startdate']);\n $enddate = new DateTime($recur['enddate']);\n\n // Move this check to the top.\n if( ($startdate > $Date) || ($Date > $enddate) )\n continue;\n\n // This code will call renderEvent() once for every valid reoccurring date, but the output of renderEvent() is the same every time.\n // I'm guessing that you only want to call renderEvent() once if $Date is a reoccurring date for the event.\n\n // $date1 = new DateTime($event['startyear'] . $event['startmonth'] . $event['startdate']);\n // $date2 = new DateTime($event['endyear'] . $event['endmonth'] . $event['enddate']);\n // $date2->modify('+1 day');\n // $period = new DatePeriod($date1, new DateInterval('P1D'), $date2);\n // Go through each date in the range\n // foreach ($period as $savedDate)\n // this->recurring($recur, $event, $Date, $savedDate);\n\n switch($recur['type'])\n {\n case 'None':\n $this->renderEvent($event);\n break;\n case 'Daily':\n $this->recur_daily($recur, $event, $Date);\n break;\n case 'Weekly':\n $this->recur_weekly($recur, $event, $Date);\n break;\n case 'Monthly1':\n $this->recur_Monthly1($recur, $event, $Date);\n break;\n case 'Monthly2':\n //Code still to be made.\n break;\n }\n }\n }\n\n // We no longer use this method, but I'm guessing that you don't want to call exit(). That will prevent other events from being rendered. Return a value instead.\n // You would use it like\n // if(!$this->check_date_range($displaydate, $startdate, $enddate))\n // $this->recur_daily($recur, $event, $Date);\n // private function check_date_range($displaydate, $startdate, $enddate)\n // {\n // // Simplify boolean logic.\n // return ($displaydate < $startdate) || ($displaydate > $enddate);\n // }\n\n // We don't want code outside this class to call this method so make it private.\n private function recur_daily($recur, $event, $Date)\n {\n // Check if day of weeks are the same.\n if($recur['day'] - 1 == $Date->format(\"w\"))\n $this->renderEvent($event);\n }\n\n //private\n private function recur_weekly($recur, $event, $Date)\n {\n // Create array of reoccurring day of week.\n $days = explode(\",\",$recur['weekday']);\n // Check if the day of week of $Date is in the array of reoccurring days.\n // In recur_daily() the day of week was off by one, so consider if you need to do this.\n //if(in_array($Date->format(\"w\")+1,$days))\n if(in_array($Date->format(\"w\"),$days))\n $this->renderEvent($event);\n }\n\n //private\n private function recur_Monthly1($recur, $event, $Date)\n {\n //$Date must be on month $recur['month'] and day $recur['day'].\n if( ($Date->format(\"m\") == $recur['month']) && ($recur['day'] == $Date->format('d') )\n $this->renderEvent($event);\n }\n\n //private\n private function renderEvent($Array)\n {\n // Warning: Not Secure.\n // Anyone that can modify ad, stattime, endtime, title, location, address, price, or description in your database can print anything they want to a visitor's browser.\n // This includes a cookie stealer, malware, or obscene pictures.\n // Users could also destroy your HTML by accident.\n // Consider if a user enters the following for a description: \"<a Do stuff <b Do other stuff <c ??? <d Profit\".\n // You must escape the output so it cannot print valid HTML, javascript, etc.\n // I will leave this for you to research and implement.\n\n // Check opening and closing of p tag.\n echo \"</p>\"; // Open p tags: -1\n echo \"<p>\"; // Open p tags: 0\n if($Array['ad'])\n echo \"<img src='images/\" . $Array['ad'] . \"' alt='event-ad' width='300' height='100' />\";\n else\n echo \"&nbsp;\";\n echo \"</p>\"; // Open p tags: -1\n echo \"<p>&nbsp;</p>\"; // Open p tags: -1\n echo \"<div class='toggleLink' style='cursor: pointer; color: #333;'>\";\n echo $Array['starttime'] . \" \" . $Array['title'];\n echo \"</p>\"; // Open p tags: -2\n echo \"</div>\";\n echo \" <div class='toggle'>\";\n echo \"<p class='toggleLink'>\"; // Open p tags: -1\n echo \"(\" . $Array['starttime'] . \"-\" . $Array['endtime'] . \") \" . $Array['location'] . \" - \" . $Array['address'] . \" - Admission Price: $\" . $Array['price'] . \"<br>\" . $Array['description'];\n echo \"</div>\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:35:19.380",
"Id": "80515",
"Score": "3",
"body": "Completely disagree with your comment of leaving out type-hints. If a method is _public_, it can be called by anyone who creates an instance of this class. The clearer the API, and the more restrictive (within reasonable bounds) the methods' signature is,the better. Leave the type-hint out, and you could call this method with `displayEvent(array('Foo' => 'bar'));`, and your method would fail. _force_ the user to pass a _valid_ argument as much as you can."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:37:57.347",
"Id": "80516",
"Score": "0",
"body": "Thanks for correcting me. That was my misunderstanding of the language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:41:36.010",
"Id": "80517",
"Score": "0",
"body": "Cheers, removed -1. Though perhaps edit your answer a bit more. ATM, you ask what the meaning of `$Date` is. The type-hint (`DateTime`) makes this quite clear: it's a `DateTime` instance, which can be used to create a formatted date string `($Date->format('Y-m-d H:i:s')` yields that date as MySQL would format it, for example"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T20:12:17.360",
"Id": "80645",
"Score": "0",
"body": "@EliasVanOotegem I suspect \"what is the meaning of `$Date`\" has more to do with the poorly-named variable than it's type: the date of what? today? the event start? three full moons from now? Similarly, `$Array` should be `$event` or whatever data the array holds. *Never* name a variable based solely on its type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T20:35:57.723",
"Id": "80646",
"Score": "0",
"body": "@DavidHarkness: Hence my mentioning _\"what's in a name\"_ and self-documenting code in my answer. But instead of just asking a rhetorical question, if you review code, you should offer some suggestions or at least explain the issue you have with a var name, no? If not, your answer is as vague as the `$array` variable"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T20:47:55.130",
"Id": "80647",
"Score": "0",
"body": "@DavidHarkness: just say my comment. If you took it as being defensive or dismissive, that's not how I intended it :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T00:02:47.420",
"Id": "80661",
"Score": "0",
"body": "@EliasVanOotegem No worries. I misunderstood your initial comment (\"the type-hint makes this quite clear\") to mean the name `$Date` was appropriate which we both agree it is not. I hadn't read through your whole answer since it was an obvious +1 after the first few paragraphs. ;)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:21:37.200",
"Id": "46156",
"ParentId": "46133",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T02:59:06.123",
"Id": "46133",
"Score": "1",
"Tags": [
"php",
"beginner",
"html",
"datetime"
],
"Title": "Too many nested blocks fixed but not sure if this way is right"
} | 46133 |
<p>I have taken a look at several answered questions on Stack Overflow about jQuery's new (since 1.9.1 upgrade)</p>
<pre><code>.on('click','',function(){}
</code></pre>
<p>and that you need to delegate. However, in each one, it just provides the solution to fix the issue, but I need a bit more finest or an explanation to why it must be done like that.</p>
<p>Here is my code segment which I have already made it working. My question will follow after the code.</p>
<pre><code>jQuery(document).ready(function($){
/* Shopping Cart Items */
$(".header-shopping-cart div .toggle-items").on('click', function(){ // Show/Hide Shopping Cart Items
if ($(".header-shopping-cart-items").css("display") == "none" && $("#items-amount").html() > 0) {
$(".header-shopping-cart-items").fadeIn();
$(this).find("i").removeClass("icon-angle-right").addClass("icon-angle-down");
}
else {
$(".header-shopping-cart-items").fadeOut();
$(this).find("i").removeClass("icon-angle-down").addClass("icon-angle-right");
}
return false;
});
$(document).on('click','.header-shopping-cart-items .item a', function(){
var amount = $("#items-amount").html();
if (amount > 0) {
$("#items-amount").html(amount - 1); // Dicrease the amount of SC items
$(this).parent().slideUp(); // Hide this item
if (amount - 1 == 0) {
$(".header-shopping-cart-items").fadeOut(); // When there's no any items in the cart, hide the items block
$(".header-shopping-cart div .toggle-items i").fadeOut();
}
}
return false;
});
});
</code></pre>
<p>The short end of the code basically have two purpose: one the toggle makes it so that when press a drop down opens up.</p>
<p>The second one (which is where I have confusion on) enables a way to remove (or delete) a row from the drop down.</p>
<p>My questions:</p>
<ol>
<li><p>When the HTML used to be static, I can do both the operation of toggling the HTML and the deletion of the row without issues. However when I now append the row, I could no longer remove the row by hitting the second <code>on('click')</code>. So I had to modify it with <code>$(document)</code> and then shift the <code>.header-shopping-cart-items .item a</code> into the delegation position. I don't know why it is that.</p></li>
<li><p>Must I use the document as the starting point of the delegation? Is it because these rows are not statically there at first and were actually generated later via an event.</p></li>
<li><p>If I want to omit </p>
<pre><code>jQuery(document).ready(function($){
//code
});
</code></pre>
<p>I should have done IIFE instead - however is there a "trap" in doing so. Trap as in must I start changing the code structure around in order to achieve the same effect.</p></li>
</ol>
<p>Please note that I read <a href="https://stackoverflow.com/questions/17878276/on-click-not-working-in-jquery-1-9-1">this</a> in order to fix my JavaScript up to achieve the current code which works.</p>
| [] | [
{
"body": "<p>I'm not sure this question really fits into the site but I'm going to answer it anyway. </p>\n\n<ol>\n<li><p>Since the elements don't exist when the page is loaded you can't add a click event to it (yet). If you try to attach the event handler directly to the elements at this time it won't do anything since the elements don't exist. So instead you attach the click element to the document element (which does exist) and then when the click handler is fired (with a click anywhere on the document) it looks to see if the click event was done on an object that matched the selector you entered at that point. If it was then the click handler is fired.</p>\n\n<p>That was confusing even to me. Let me try a different way.</p>\n\n<p>Option 1</p>\n\n<p>Attempt to attach the event handler to the actual element on page load using the selector.</p>\n\n<pre><code>$('.class-name').on('click', function(){})\n</code></pre>\n\n<p>The element does not exist yet so this does nothing.</p>\n\n<p>Option 2</p>\n\n<p>Attach the event handler to a static element and provide a delegated selector to test for when the item is clicked.</p>\n\n<pre><code>$(document).on('click','.class-name', function(){})\n</code></pre>\n\n<p>This event handler is successfully added to the document object. Now when any click happens within the document, the selector is tested and if a match the function is fired. </p></li>\n<li><p>No, but you need to use a static element. I used the document but it could be any static element as long as all dynamic elements will be contained within. In your case it <em>might</em> be something like <code>$('.header-shopping-cart-items').on('click', '.item a', function() {})</code> provided the <code>.header-shopping-cart-items</code> container were static (always there).</p>\n\n<p>Another option, although much more difficult and probably not worth the effort would be to attach the event handler directly to the item row when you inject it. I wouldn't recommend that approach.</p></li>\n<li><p>You could look into putting this into a module and calling that module when needed. But I don't know that you would be gaining anything by putting this into a IIFE. And I wouldn't say that IIFEs are preferred over the jQuery.ready function. That said, this whole code could probably be put into a IIFE without any changes. You would just need to put it at the bottom of the document.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:36:15.213",
"Id": "80493",
"Score": "0",
"body": "#2) So I could have attached myself to any close static element (a div even) rather than a dom?\n\n#3) is a question: I'm basically asking to convert from a document.ready into a non document.ready (since that is the prefered practice) what are the kind of pitfall or if there isn't any really."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:38:29.127",
"Id": "80494",
"Score": "0",
"body": "#2) Any static element that is a container of *all* the items you will need to handle with the event handler."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:44:51.133",
"Id": "80495",
"Score": "0",
"body": "I put my notes on #3 in an edit to my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T17:22:57.317",
"Id": "80627",
"Score": "0",
"body": "My pleasure, I hope it was helpful."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:20:27.190",
"Id": "46147",
"ParentId": "46135",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46147",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:09:21.797",
"Id": "46135",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Is there a way to avoid calling the document with jQuery on click?"
} | 46135 |
<p>I've been trying to expand my programming horizons, and have entered the world of grammars and parsing, which I'm brand new to. I have been improving a little implementation of Dijkstra's shunting yard algorithm that currently handles negatives and parentheses correctly (which took a bit of work). I'm well aware that I could make it much easier by using a parser generator, but for now I want to try to hand code it.</p>
<pre><code>template <typename Iterator>
void inline skip_space(Iterator& head, Iterator last)
{
while(head != last && std::isspace(*head)) ++head;
}
bool inline is_numeric(char ch)
{
switch(ch)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
return true;
default:
return false;
}
}
// Pump characters though to output while input is currently a number, and advance head iterator past number
template <typename Iterator1, typename Iterator2>
bool inline process_number(Iterator1& head, Iterator1 last, Iterator2& output)
{
skip_space(head, last);
bool valid = false;
while(head != last && is_numeric(*head)) valid = true, *output++ = *head++;
if(valid && *head == '.')
{
*output++ = '.';
while(is_numeric(*++head)) *output++ = *head;
}
*output++ = ' ';
return valid;
}
// Get next symbol and advance head iterator past it
template <typename Iterator1, typename Iterator2>
char inline get_symbol(Iterator1& head, Iterator1 last, Iterator2 symbols_begin, Iterator2 symbols_end)
{
using namespace std;
head = find_first_of(head, last, symbols_begin, symbols_end);
if(head == last) return 0;
else return *head++;
}
// Requires at least an input iterator for Iterator1, and an output iterator for Iterator2
template <typename NumType = double, typename Iterator1, typename Iterator2>
bool parse_to_rpn(Iterator1 head, Iterator1 last, Iterator2 output)
{
using namespace std;
// Token list for matching
static const char tokens[] = {'+', '-', '*', '/', '^', '(', ')'};
// Map containing information about operators
static map<char, tuple<unsigned int /* precedence */, bool /* is binary */, bool /* is left associative */>> operator_info
{
{'+', make_tuple(1U, true, true)},
{'-', make_tuple(1U, true, true)},
{'*', make_tuple(2U, true, true)},
{'/', make_tuple(2U, true, true)},
{'^', make_tuple(4U, true, false)},
{'n', make_tuple(3U, false, true)}
};
// Operator stack
stack<char> oper_stack;
// Some defines to make my life a bit easier
#define IS_BINARY(c) std::get<1>(operator_info.at(c))
#define IS_LEFT_ASSOCIATIVE(c) std::get<2>(operator_info.at(c))
#define PRECEDENCE(c) std::get<0>(operator_info.at(c))
bool need_numeric = true; // If true, parser looks for a number value (or a parenthesized expression)...
// If false, parser looks for an operator
// Try block to isolate any exceptions; simply returns false if one is caught
try {
// Skip whitespace
skip_space(head, last);
while(head != last)
{
// Mode 1: looking for something that will evaluate to a number
if(need_numeric)
{
if(head == last) return false;
// Handle positive or negative sign properly if looking for a number
else if(*head == '+')
{
++head;
}
else if(*head == '-')
{
oper_stack.push('n'); // Push unary negation operator onto stack
++head;
}
if(head == last) return false;
else if(*head == '(')
{
oper_stack.push('('); // Push left parenthesis onto stack
++head;
}
else if(process_number(head, last, output)) need_numeric = false; // If a number was found, switch modes
else return false;
}
// Mode 2: looking for an operator
else
{
char symbol = get_symbol(head, last, begin(tokens), end(tokens)); // Get next symbol
if(symbol == '(') return false; // Mistmatched parenthesis
else if(symbol == ')') // Pop operators off stack until matching parenthesis
{
if(oper_stack.size() == 0) return false; // Mismatched parenthesis
while(oper_stack.top() != '(')
{
if(oper_stack.size() == 1) return false; // Mismatched parenthesis
*output++ = oper_stack.top();
oper_stack.pop();
}
oper_stack.pop();
}
// The core of this parser: Dijkstra's shunting yard algorithm
else if(IS_BINARY(symbol))
{
if(IS_LEFT_ASSOCIATIVE(symbol))
{
while(oper_stack.size() > 0 && oper_stack.top() != '(' && PRECEDENCE(symbol) <= PRECEDENCE(oper_stack.top()))
{
*output++ = oper_stack.top();
oper_stack.pop();
}
oper_stack.push(symbol);
}
else
{
while(oper_stack.size() > 0 && oper_stack.top() != '(' && PRECEDENCE(symbol) < PRECEDENCE(oper_stack.top()))
{
*output++ = oper_stack.top();
oper_stack.pop();
}
oper_stack.push(symbol);
}
need_numeric = true; // Binary operator needs another operand, obviously; switch modes
}
else
{
while(oper_stack.size() > 0 && oper_stack.top() != '(' && PRECEDENCE(symbol) <= PRECEDENCE(oper_stack.top()))
{
*output++ = oper_stack.top();
oper_stack.pop();
}
oper_stack.push(symbol);
}
}
skip_space(head, last);
}
}
catch(...)
{
return false;
}
// Pop remaining operators into output
while(oper_stack.size())
{
if(oper_stack.top() == '(') return false; // Mismatched parenthesis
*output++ = oper_stack.top();
oper_stack.pop();
}
#undef IS_BINARY
#undef IS_LEFT_ASSOCIATIVE
#undef PRECEDENCE
}
</code></pre>
<p>Again, I'm really new to writing parsers, so how can I clean this up and make it more extensible? My next goal is to parse into a tree instead of text-based RPN notation. I figure that won't be too difficult in itself, but I'd also like to later include the ability to handle operators of arbitrary length, and possibly even function names and variables. To be able to do that, would it be necessary (or at least prudent) to write a separate tokenizer?</p>
<p>A side question: for implementing a parse tree, would it be a better choice to use an abstract base class for all nodes and implement leaf nodes and operator/function nodes as children, or to use a struct containing an ID of some sort, and a union that contains all the necessary data for each possible type of node?</p>
| [] | [
{
"body": "<p>A few tips:</p>\n\n<ul>\n<li>Your function <code>is_numeric</code> is rather useless. There is a function named <code>std::isdigit</code> in the standard header <code><cctype></code> which does exactly the same thing.</li>\n<li>Instead of <code>skip_space</code>, I would have named the functions <code>skip_spaces</code>. <code>skip_space</code> is a misleading name since the function may actually skip many spaces at once.</li>\n<li><p>This piece of code:</p>\n\n<pre><code>if(head == last) return 0;\nelse return *head++;\n</code></pre>\n\n<p>could be rewritten as such (without the <code>else</code> and with <code>{}</code> after the <code>if</code>):</p>\n\n<pre><code>if (head == last)\n{\n return 0;\n}\nreturn *head++;\n</code></pre>\n\n<p>You should always put curly braces after an <code>if</code> clause. It's not required, but most of the guidelines will tell you to do so. It makes it easier to extend your code to avoid errors. By the way, please, never do this again:</p>\n\n<pre><code>while(head != last && is_numeric(*head)) valid = true, *output++ = *head++;\n</code></pre>\n\n<p>You should really use one line per statement, and separate your statements by <code>;</code>, not by <code>,</code>. You should have written this instead:</p>\n\n<pre><code>while (head != last && std::isdigit(*head))\n{\n valid = true;\n *output++ = *head++;\n}\n</code></pre></li>\n<li><p>Your function <code>process_number</code> accepts numbers contaning a dot or ending with a dot but does not accept as valid numbers beginning with a dot, which is rather strange. You should either accept numbers beginning with a dot or forbid number ending with a dot.</p></li>\n<li><p>The following macros are not needed:</p>\n\n<pre><code>#define IS_BINARY(c) std::get<1>(operator_info.at(c))\n#define IS_LEFT_ASSOCIATIVE(c) std::get<2>(operator_info.at(c))\n#define PRECEDENCE(c) std::get<0>(operator_info.at(c))\n</code></pre>\n\n<p>You can replaced them by inline functions, or even by lambdas since it seems that you are using C++11.</p></li>\n<li><p>You use an <code>std::tuple</code> to represent the information associated to an operator. And as you can see, you are forced to name your parameters in the comments and to use positional arguments (<code>std::get<...></code>). What you need are named parameters to make it clear. Use a plain old struct instead of <code>std::tuple</code>:</p>\n\n<pre><code>struct Operator\n{\n unsigned precedence;\n bool is_binary;\n bool is_left_associative;\n};\n</code></pre>\n\n<p>It will allow you to simplify your <code>map</code> declaration even further thanks to aggregate initialization:</p>\n\n<pre><code>static map<char, Operator> operator_info\n{\n { '+', { 1U, true, true } },\n { '-', { 1U, true, true } },\n { '*', { 2U, true, true } },\n { '/', { 2U, true, true } },\n { '^', { 4U, true, false } },\n { 'n', { 3U, false, true } }\n};\n</code></pre></li>\n<li><p>Your function <code>get_symbol</code> is supposed to return a <code>char</code> but when there is an error, you simply write <code>return 0;</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:15:58.823",
"Id": "80587",
"Score": "0",
"body": "Thanks for your suggestions! I must've missed std::isdigit in the docs, so I'll use that instead. Also, I will fix up that unneeded else and the dirty loop code. Plus, the struct is a nice idea. Though, I used the macros for simplicity to avoid writing yet another function to fetch data about the operator, but if I use a struct there won't be a need to use the macros OR a function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:19:02.763",
"Id": "80588",
"Score": "1",
"body": "@mebob Exactly, named members are self-documenting :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T08:48:33.017",
"Id": "46161",
"ParentId": "46136",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "46161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:36:00.283",
"Id": "46136",
"Score": "8",
"Tags": [
"c++",
"c++11",
"parsing"
],
"Title": "Infix-to-postfix parser using Dijkstra's shunting yard algorithm"
} | 46136 |
<p>I have code that is used for retrieving and storing conversation for a chat application. I found this from a tutorial and tweak it a little bit. This script works fine but my concern is if it's the standard way. Can somebody please check this for me if to see if it's deprecated or a bad practice? And is there any other way of writing this script?</p>
<pre><code> //Gets the current messages from the server
function getChatText() {
if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
receiveReq.open("GET", 'includes/getChat.php?chat='+uid+'&last=' + lastMessage, true);
receiveReq.onreadystatechange = handleReceiveChat;
receiveReq.send(null);
}
}
//Add a message to the chat server.
function sendChatText() {
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'includes/getChat.php?last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('txtA').value;
param += '&name='+user;
param += '&uid='+uid;
param += '&rid='+document.getElementById('trg').value;
sendReq.send(param);
document.getElementById('txtA').value = '';
}
}
//When our message has been sent, update our page.
function handleSendChat() {
//Clear out the existing timer so we don't have
//multiple timer instances running.
clearInterval(mTimer);
AjaxRetrieve();
}
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value;
$.get('includes/getChat.php?chat='+uid + '&rid=' + rid + '&name=' + user,function(data)
{
$("#clog").html(data);
});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T04:28:26.937",
"Id": "80482",
"Score": "0",
"body": "Can you show a complete example, including what `receiveReq` and `sendReq` are"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T04:32:41.723",
"Id": "80484",
"Score": "0",
"body": "@megawac I forgot to add these vars\n\n`var sendReq = getXmlHttpRequestObject();\nvar receiveReq = getXmlHttpRequestObject();` sorry about that"
}
] | [
{
"body": "<p>This is really odd. As I read the code, I was thinking you'd go all-native. Then, suddenly a <code>$.get</code> is found at the bottom. You had jQuery all along! Why not go ahead and use it for all the AJAX functions you have. Overhead is not really a concern here, but readability and maintainability is. Use jQuery all the way, keeps your code short.</p>\n\n<pre><code>// If they remain static, then move them out so you won't be running around the DOM\nvar message = $('#txtA').val();\nvar roomId = $('#trg').val();\nvar clog = $(\"#clog\");\n\n//Gets the current messages from the server\nfunction getChatText() {\n $.get('includes/getChat.php', {\n chat: uid,\n last: lastMessage\n }, handleReceiveChat);\n}\n\n//Add a message to the chat server.\nfunction sendChatText() {\n\n $.post('includes/getChat.php', {\n last: lastMessage,\n message: message,\n name: user,\n uid: uid,\n rid: roomId\n }, handleSendChat);\n message.val('');\n}\n\nfunction handleSendChat() {\n // No need to stop the timers. Have it run continuously.\n}\n// This function should retrieve the latest messages, and not everything.\n// Also, if you are polling, use one timer that perpetually runs.\nfunction AjaxRetrieve() {\n $.get('includes/getChat.php', {\n chat: uid,\n rid: roomId,\n name: user\n }, function (data) {\n clog.html(data);\n });\n}\n</code></pre>\n\n<p>Other things I notice:</p>\n\n<ul>\n<li><p>You manually pick out the values to send to the server. Why not place everything in a form, like place it in hidden input tags, and then take advantage of <a href=\"https://api.jquery.com/serialize/\" rel=\"nofollow\"><code>jQuery.serialize</code></a>. This makes your code much easier by not doing <code>document.getElement...value</code>. You can hook up the form with a submit handler, prevent the normal submit, serialize the form and do ajax.</p>\n\n<pre><code><form id=\"chat\">\n ...\n <input type=\"text\" name=\"message\">\n ...\n</form>\n\n<script>\n $('#chat').on('submit',function(event){\n // Prevent the normal submit\n event.preventDefault(); \n // From here, it's as simple as a grab and go\n var formData = $(this).serialize();\n $.post('includes/getChat.php',formData,function(){...});\n });\n</script>\n</code></pre></li>\n<li><p>Polling is a good starter for doing semi-live chat. But that's stressful for the server. Imagine millions of people using your app, polling every 1 second for live data. That's 60 million requests to your server a minute! I suggest you look into <a href=\"http://www.websocket.org/\" rel=\"nofollow\">WebSockets</a> for a much more efficient implementation.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:56:29.053",
"Id": "80496",
"Score": "0",
"body": "Thank you for these wonderful pointers I'll keep this in mind.. Your right about the polling so I might really consider using WebSockets instead but I'm quite worried.. doesn't websockets have compatibility issues?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:43:09.167",
"Id": "80504",
"Score": "1",
"body": "@user256009 [Here's the compatibility table](http://caniuse.com/websockets), and you guessed it, IE."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:44:34.693",
"Id": "46149",
"ParentId": "46138",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46149",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T03:57:08.193",
"Id": "46138",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"ajax",
"chat"
],
"Title": "AJAX chat client"
} | 46138 |
<p>I have an <code>Account</code>, <code>User</code> and <code>Group</code> model. All <code>User</code> and <code>Group</code> records belong to an <code>Account</code>, so it is possible for both users and groups to be related to various accounts.</p>
<p>Basically, I have some really hacky, pieced together SQL queries that lookup all <code>Account</code> records related to a given <code>User</code> or <code>Group</code> record through various
associations.</p>
<p>Even though it's fast and only requires a single query for everything to work, I really hate the way it's written.</p>
<p>I was wondering if there is any way I could do this more <em>programatically</em> with something like <code>arel</code>, or if there was a better approach. I also have some security concerns about the code.</p>
<pre class="lang-rb prettyprint-override"><code>class Account < ActiveRecord::Base
belongs_to :accountable, touch: true, polymorphic: true
CLAUSE_FOR_RELATED = '"accounts"."accountable_type" = \'%s\' AND "accounts"."accountable_id" IN (%s)'.freeze
def self.related_to_user(user)
groups = user.groups.select('"groups".id')
friends = user.following_friendships.select('"friendships".following_id')
queries = []
queries.push ['Group', groups.to_sql]
queries.push ['User', friends.to_sql]
queries.push ['User', user.id]
self.related_to(queries)
end
def self.related_to_group(group)
queries = [
['User', group.members.select('"users".id').to_sql]
]
self.related_to(queries)
end
def self.related_to(queries)
clauses = queries.map do |clause|
sprintf(CLAUSE_FOR_RELATED, clause[0], clause[1])
end
self.where(clauses.join(" OR "))
end
end
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T04:31:04.847",
"Id": "88530",
"Score": "0",
"body": "Is the SQL tag properly used here? Was looking for SQL to review in your code but found only tiny snippets. No bad karma just seems a bit misleading."
}
] | [
{
"body": "<p>I would try to use as much as possible what is provided by <code>ActiveRecord</code>. I was thinking to something like:</p>\n\n<pre><code>class Account < ActiveRecord::Base\n belongs_to :accountable, touch: true, polymorphic: true\n CLAUSE_FOR_RELATED = '\"accounts\".\"accountable_type\" = \\'%s\\' AND \"accounts\".\"accountable_id\" IN (%s)'.freeze\n\n class << self\n def related_to_user(user)\n group_ids = user.groups.pluck('groups.id')\n friend_ids = user.following_friendships.pluck('friendships.following_id') \n\n query = [\n compose_clause('Group', group_ids.join(', ')),\n compose_clause('User', [user.id, *friend_ids].join(', '))\n ].join(' or ')\n\n where(query)\n end\n\n def related_to_group(group)\n member_ids = group.members.pluck('users.id')\n where(compose_clause('User', member_ids.join(', ')))\n end\n\n private\n def compose_clause(accountable_type, ids)\n sprintf(CLAUSE_FOR_RELATED, accountable_type, ids)\n end\n end\nend\n</code></pre>\n\n<p>Now in Rails 5 you could even write it like:</p>\n\n<pre><code>class Account < ActiveRecord::Base\n belongs_to :accountable, touch: true, polymorphic: true\n\n class << self\n def related_to_user(user)\n group_ids = user.groups.pluck('groups.id')\n friend_ids = user.following_friendships.pluck('friendships.following_id') \n\n where(accountable_type: 'Group', accountable_id: group_ids).or(\n Account.where(accountable_type: 'User', accountable_id: [user.id, *friend_ids])\n )\n end\n\n def related_to_group(group)\n member_ids = group.members.pluck('users.id')\n where(accountable_type: 'User', accountable_id: member_ids)\n end\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-27T21:09:34.000",
"Id": "176674",
"ParentId": "46139",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T04:05:16.287",
"Id": "46139",
"Score": "5",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Querying multiple related records in Rails"
} | 46139 |
<p>I need to further simplify this solution to auto-format a text-box field intended only for the user to enter their college Grade Point Average (GPA). Here is my code:</p>
<pre><code><label for="collegeGPA">GPA:</label>
<input type="text" name="collegeGPA" id="collegeGPA" maxlength="4" style="width:45px;" onpaste="return false;" autocomplete="off" >
<script type="text/javascript">
//<!-- When executed this script [BELOW] auto-formats a Grade Point Average (GPA) field given the element ID [BEGIN] -->
function formatGPA(gPAElementID) {
var rE = /\D/g; // remove any characters that are not numbers
var originalGPA = document.getElementById(gPAElementID);
var originalGPAVal = originalGPA.value;
var gPAVal = originalGPA.value.replace(rE,"");
var gPAValFirstCharacter = gPAVal.charAt(0);
if ( ( ( parseFloat(originalGPAVal) ) > 4 ) && ( ( parseFloat(originalGPAVal) ) < 5 ) )
{
originalGPA.value = "4.00";
}
else
{
if ( ( gPAVal >= 0 ) && ( gPAValFirstCharacter < 5 ) )
{
gPALen = gPAVal.length;
if ( gPALen > 1 )
{
gPAa=gPAVal.slice(0,1);
gPAb=gPAVal.slice(1);
originalGPA.value = gPAa + "." + gPAb;
}
else if ( gPALen == 1 )
{
originalGPA.value = gPAVal + ".";
}
else
{
originalGPA.value = gPAVal;
};
}
else
{
originalGPA.value = "";
};
};
};
//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->
document.getElementById('collegeGPA').onblur = function (e) { formatGPA(this.id); };
document.getElementById('collegeGPA').onfocus = function (e) { formatGPA(this.id); };
document.getElementById('collegeGPA').onkeypress = function (e) { formatGPA(this.id); };
document.getElementById('collegeGPA').oninput = function (e) { formatGPA(this.id); };
document.getElementById('collegeGPA').onchange = function (e) { formatGPA(this.id); };
</script>
</code></pre>
<p>...and here is my JSFiddle: <a href="http://jsfiddle.net/JamesAndersonJr/kxaBJ/1/" rel="nofollow">http://jsfiddle.net/JamesAndersonJr/kxaBJ/1/</a> I'm looking for a simpler way to format the GPA input dynamically (i.e. as the user types it in). The format should be:</p>
<p>1st Character: any digit 0-4</p>
<p>2nd Character: Always a Period (should also be auto-inserted after user types a valid first digit)</p>
<p>3rd Character: any digit</p>
<p>4th Character: any digit</p>
| [] | [
{
"body": "<p>I'd maybe try something like the following. What I've done is remove the string manipulation and concentrate on rounding the numbers.</p>\n\n<pre><code>function formatGPA(originalGPA) {\n\n var originalGPAVal = originalGPA.value;\n var gPAVal = parseFloat(originalGPAVal);\n\n if (gPAVal < 0) {\n gPAVal = 0;\n } else if (gPAVal > 4) {\n gPAVal = 4;\n }\n\n if (isNaN(gPAVal)) {\n // Some kind of error handling\n } else {\n originalGPA.value = gPAVal.toFixed(2);\n }\n\n}\n\n//<!-- When executed this script [ABOVE] auto-formats a Grade Point Average (GPA) field given the element ID [END] -->\n\ndocument.getElementById('collegeGPA').onblur = function () {\n formatGPA(this);\n};\n</code></pre>\n\n<p>The only problem with this is it's difficult to manipulate it as one types. Therefore I've actioned the manipulation only on <code>blur</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T19:52:03.987",
"Id": "46213",
"ParentId": "46146",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T05:17:12.037",
"Id": "46146",
"Score": "2",
"Tags": [
"javascript",
"validation"
],
"Title": "Auto-Format GPA while typing : REVISED"
} | 46146 |
<p>Given a complete binary tree returns the following format (Parent ( leftchild (leftchild, rightchild), rightchild(leftchild,rightchild) ). Looking for code review, optimizations and best practices. </p>
<pre><code>public final class PreOrderList {
private TreeNode root;
/**
* Constructs a binary tree in order of elements in an array.
* The input list is treated as BFS representation of the list.
* Note that it is the clients responsibility to not modify input list in objects lifetime.
*
*/
PreOrderList(List<String> items) {
create (items);
}
private static class TreeNode {
TreeNode left;
String item;
TreeNode right;
TreeNode(TreeNode left, String item, TreeNode right) {
this.left = left;
this.item = item;
this.right = right;
}
}
private void create (List<String> items) {
root = new TreeNode(null, items.get(0), null);
final Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
final int half = items.size() / 2;
for (int i = 0; i < half; i++) {
if (items.get(i) != null) {
final TreeNode current = queue.poll();
final int left = 2 * i + 1;
final int right = 2 * i + 2; // http://stackoverflow.com/questions/21156774/unit-testing-complicated-methods-what-to-test-and-what-to-assume
if (items.get(left) != null) {
current.left = new TreeNode(null, items.get(left), null);
queue.add(current.left);
}
if (right < items.size() && items.get(right) != null) {
current.right = new TreeNode(null, items.get(right), null);
queue.add(current.right);
}
}
}
}
/**
* Returns the string representation of the format
* (Parent ( leftchild (leftchild, rightchild), rightchild(leftchild,rightchild) )
* It needs a complete balanced tree, else invalid format is be returned.
*
* @return the String representation.
*/
public String getPreorderList() {
if (root == null) {
throw new NoSuchElementException("The element cannot be null.");
}
final StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(root.item);
preOrder(root, sb);
sb.append(")");
return sb.toString();
}
private void preOrder(TreeNode node, StringBuilder sb) {
if (node.left != null) {
sb.append("(");
sb = sb.append(node.left.item);
preOrder(node.left, sb);
}
if (node.right != null) {
sb.append(",");
sb = sb.append(node.right.item + "");
preOrder(node.right, sb);
sb.append(")");
}
}
public static void main(String[] args) {
PreOrderList pol = new PreOrderList(new ArrayList<String>(Arrays.asList("1", "2", "3", "4", "5", "6", "7")));
assertEquals("(1(2(4,5),3(6,7)))", pol.getPreorderList());
}
}
</code></pre>
| [] | [
{
"body": "<p>I haven't fully parsed your code, but I would definitely add a check before creating the root. This <code>get(0)</code> would break on an empty list, and would break on a null list. Or you could throw an <code>IllegalArgumentException</code> as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:02:53.600",
"Id": "46290",
"ParentId": "46151",
"Score": "4"
}
},
{
"body": "<p>This class should be generalized to allow trees with any type of value to be used. Add a type parameter <code>E</code> to the <code>PreOrderList</code> and <code>TreeNode</code> classes. Your <code>getPreOrderList</code> and <code>preOrder</code> method should be erased entirely; that should be implemented inside the <code>TreeNode</code> class. In fact, there is no need for the <code>PreOrderList</code> class at all; all that behavior could be implemented inside <code>TreeNode</code>:</p>\n\n<pre><code>public class TreeNode<E>{\n\n public static TreeNode<E> fromIterator(Iterator<E> it){\n if(!it.hasNext()) return null;\n TreeNode<E> root = new TreeNode<E>();\n while(it.hasNext())\n root.add(it.next());\n }\n public static TreeNode<E> fromIterable(Iterable<E> iterable){\n return fromIterator(iterable.iterator());\n }\n public static TreeNode<E> fromArray(E ... array){\n return fromIterable(Arrays.asList(array));\n }\n\n\n TreeNode<E> [] children;\n E item;\n\n private TreeNode(E item, TreeNode ... children) {\n this.children = children;\n this.item = item;\n }\n\n int childIdx;\n public void add(E item){\n if(children[childIdx] == null)\n children[childIdx] = new TreeNode(item, new TreeNode[children.length]);\n else children[childIdx].add(item);\n\n childIdx++;\n }\n\n public boolean contains(Object item){\n if (item==null?this.item==null:item.equals(this.item)) return true;\n for(TreeNode<?> child: children)\n if(child.contains(item)) return true;\n return false;\n }\n\n @Override\n public String toString(){\n return String.format(\"%s(%s,%s)\",item,left,right);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:28:06.647",
"Id": "46292",
"ParentId": "46151",
"Score": "2"
}
},
{
"body": "<p>You can simplify </p>\n\n<pre><code>PreOrderList pol = new PreOrderList(new ArrayList<String>(Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\")));\n</code></pre>\n\n<p>to</p>\n\n<pre><code>PreOrderList pol = new PreOrderList(Arrays.asList(\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\"));\n</code></pre>\n\n<p>If you take a look at <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList%28T...%29\" rel=\"nofollow\">method signature</a> for <code>Arrays.asList</code> you can see it is parameterized by the class of its input. Therefore <code>Arrays.asList(\"1\", \"2\", \"3\")</code> knows to return <code>List<String></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:40:41.907",
"Id": "46295",
"ParentId": "46151",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:15:23.013",
"Id": "46151",
"Score": "1",
"Tags": [
"java",
"algorithm",
"tree"
],
"Title": "Preorder traversal of binary tree to produce formatted string"
} | 46151 |
<p>I am trying to create a <em>library</em> of my own which contains (among others), a <code>class</code> called <strong>Point</strong>. As the name suggests, it is intended to encapsulate a <em>point</em> represented in 2D space. This is what I've come up with:</p>
<pre><code>package geom;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.pow;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.toDegrees;
import static java.lang.Math.toRadians;
/**
* A class that provides factory methods for creation of {@code Points}, utility
* functions based on operations regarding points.
* <p>
* The constructor has been made {@code private} because of the following
* reason: A {@code Point} can be initialized in <i>two</i> different ways:
* <ul>
* <li>Using the <b>Cartesian System</b> of using two variables to represent the
* coordinates of the {@code Point}.</li>
* <li>Using the <b>Polar System</b> of using the distance from the original and
* the angle between the line joining the point and the origin and the X-axis to
* represent the location of the {@code Point}.</li>
* </ul>
* Since there are <i>two</i> parameters in both cases, and each is of the type
* {@code double}, an ambiguity arises.
* <p>
* A solution to the above problem is to use <em>Factory Methods</em>.<br>
* Factory methods are {@code public static} methods which can accessed through
* class reference, like:
* <p>
* <code>Point point = Point.getCartesian(10, 20);</code><p>
* The advantages of using Factory Methods are many; a few of them are:
* <ol><li>Through the use of Factory Methods with descriptive names, the
* ambiguity is removed.</li>
* <li>These methods return a {@code new Point} if it has not been created
* before.<br>
* If a pre-existing point exists, the {@code Point} is returned from the
* {@code PointTracker}.</li>
* </ol>
*
*
* @author ambigram_maker
* @version 1.0
* @version 2014-04-02
*/
public class Point {
/*
* This variable represents the state of the output.
* It is static because any change to this variable is reflected in all the
* instances.
*/
private static State state;
/**
* The Point object representing the reference point at the intersection of
* the coordinate axes. Essentially, it is a point whose coordinates are
* <pre>(0,0)</pre>.
*/
public static final Point ORIGIN = getCartesianPoint(0, 0);
/**
* This factory method returns a {@code Point} object with the (Cartesian)
* coordinates passed as parameters.
*
* @param x The X-coordinate of the {@code Point} object.
* @param y The Y-coordinate of the {@code Point} object.
* @return The required {@code Point} object.
*/
public static Point getCartesianPoint(double x, double y) {
Point p = new Point();
p.x = x;
p.y = y;
p.radius = sqrt(x * x + y * y);
p.angleR = atan2(x, y);
p.angleD = toDegrees(p.getAngleRadians());
return p;
}
/**
* This factory method returns a {@code Point} object with the (Polar)
* coordinates passed as the parameters.
*
* @param radius The distance of the required {@code Point} from the origin
* (0,0)
* @param degrees The angle between the line joining the required
* {@code Point} and the origin and the X-axis (in degrees i.e. from 0 to
* 360).
* @return The required {@code Point} object.
*/
public static Point getPolarDegreesPoint(double radius, double degrees) {
Point p = new Point();
p.radius = radius;
p.angleD = degrees;
p.angleR = toRadians(degrees);
initPolar(p);
return p;
}
/**
* This factory method returns a {@code Point} object with the (Polar)
* coordinates passed as the parameters.
*
* @param radius The distance of the required {@code Point} from the origin
* (0,0)
* @param radians The angle between the line joining the required
* {@code Point} and the origin and the X-axis (in radians i.e. from 0 to
* 360).
* @return The required {@code Point} object.
*/
public static Point getPolarRadiansPoint(double radius, double radians) {
Point p = new Point();
p.radius = radius;
p.angleR = radians;
p.angleD = toDegrees(radians);
initPolar(p);
return p;
}
/*
* This method is common to both the 'getPolar_______Point()' methods.
*/
private static void initPolar(Point point) {
double angle = point.getAngleRadians();
point.x = point.getRadius() * cos(angle);
point.y = point.getRadius() * sin(angle);
}
/**
* This method is used to change the form of representation of <em>ALL</em>
* {@code Point} objects.
*
* @see State
* @param state The {@code State} constant to set.
*/
public static void setState(State state) {
Point.state = state;
}
/*
* The coordinates of this Point in the Cartesian system.
*/
private double x; // The perpendicular distance from the Y-axis.
private double y; // The perpendicular distance from the X-axis.
/*
* The coordinates of this Point in the Polar System.
*/
private double radius; // The distance from the Origin (0,0).
private double angleR; // The angle in Radians.
private double angleD; // The angle in Degrees.
private Quadrant location;
/*
* Instances of Point are not meant to be created through the default
* contructor. Use the Factory Methods instead.
*/
private Point() {
// Provision to add itself to the PointTracker.
}
/**
* Returns the <i>distance</i> between {@code this Point} and the one passed
* in the parameter.
*
* @param other The <i>other</i> {@code Point} which acts as the reference
* for calculating the distance.
* @return The distance {@code this Point} and the <i>other</i> one.
*/
public double distanceFrom(Point other) {
return other.equals(Point.ORIGIN) ? radius
: sqrt(pow(this.getX() - other.getX(), 2)
+ pow(this.getY() - other.getY(), 2));
}
/**
* This method returns the {@code Point} which is a reflection of
* {@code this Point} in the X-axis.
*
* @return Returns the {@code Point} which is a reflection of
* {@code this Point} in the X-axis.
*/
public Point reflectionXAxis() {
return getCartesianPoint(getX(), -getY());
}
/**
* This method returns the {@code Point} which is a reflection of
* {@code this Point} in the Y-axis.
*
* @return Returns the {@code Point} which is a reflection of
* {@code this Point} in the Y-axis.
*/
public Point reflectionYAxis() {
return getCartesianPoint(-getX(), getY());
}
/**
* This method returns the {@code Point} which is a reflection of
* {@code this Point} in the Origin.
*
* @return Returns the {@code Point} which is a reflection of
* {@code this Point} in the Origin.
*/
public Point reflectionOrigin() {
return getCartesianPoint(-getX(), -getY());
}
/**
* This method returns the {@code Point} which is a reflection of
* {@code this Point} in the {@code Point} passed as a parameter.
*
* @param other The reference for calculating the reflection of
* {@code this Point}
* @return Returns the {@code Point} which is a reflection of
* {@code this Point} in the X-axis.
*/
public Point reflectionFrom(Point other) {
if (other.equals(Point.ORIGIN)) {
return reflectionOrigin();
}
return getCartesianPoint(
2 * other.getX() - this.getX(),
2 * other.getY() - this.getY());
}
/**
* Returns the X-coordinate of {@code this Point}.
* <p>
* The magnitude of the X-coordinate is the perpendicular distance between
* {@code this Point} and the Y-axis. If {@code this Point} is above the
* X-axis, the X-coordinate is positive. If {@code this Point} is below the
* X-axis, the X-coordinate is negative.
*
* @return the X coordinate of {@code this Point}.
*/
public double getX() {
return x;
}
/**
* Returns the Y-coordinate of {@code this Point}.
* <p>
* The magnitude of the Y-coordinate is the perpendicular distance between
* {@code this Point} and the X-axis. If {@code this Point} is above the
* Y-axis, the Y-coordinate is positive. If {@code this Point} is below the
* Y-axis, the Y-coordinate is negative.
*
* @return the Y coordinate of {@code this Point}.
*/
public double getY() {
return y;
}
/**
* Returns the distance between the origin (0,0) and {@code this Point}.
* Considering the origin to be at the center and {@code this Point} at the
* circumference, this distance is the <i>radius</i>.
*
* @return The Distance between the origin and {@code this Point}.
*/
public double getRadius() {
return radius;
}
/**
* Returns the angle between the line joining {@code this Point} and the
* origin, and the X-axis in Radians.
*
* @return The angle between the line joining {@code this Point} and the
* origin, and the X-axis in Radians.
*/
public double getAngleRadians() {
return angleR;
}
/**
* Returns the angle between the line joining {@code this Point} and the
* origin, and the X-axis in Degrees.
*
* @return The angle between the line joining {@code this Point} and the
* origin, and the X-axis in Degrees.
*/
public double getAngleDegrees() {
return angleD;
}
/**
* Returns the <i>location</i> of {@code this Point} in a broader
*
* @return
*/
public Quadrant getLocation() {
if (location == null) {
if (this.equals(Point.ORIGIN)) {
location = Quadrant.ON_ORIGIN;
} else if (x == 0) {
location = Quadrant.ON_Y_AXIS;
} else if (y == 0) {
location = Quadrant.ON_X_AXIS;
} else if (x > 0 && y > 0) {
location = Quadrant.FIRST_QUADRANT;
} else if (x < 0 && y > 0) {
location = Quadrant.SECOND_QUADRANT;
} else if (x < 0 && y < 0) {
location = Quadrant.THIRD_QUADRANT;
} else if (x > 0 && y < 0) {
location = Quadrant.FOURTH_QUADRANT;
}
}
return location;
}
/**
* This method is used to check if two instances of {@code Point} are equal.
* This method checks the {@code Point}s using their hashcodes.
*
* @see Point#hashCode()
* @param o The {@code Object} to compare this instance with.
* @return {@code true} if the {@code Object} passed as parameter is an
* instance of type {@code Point} and the two {@code Point}s are
* <i>equal</i>
*/
@Override
public boolean equals(Object o) {
if (o instanceof Point) {
Point p = (Point) o;
return this.hashCode() == p.hashCode();
}
return false;
}
@Override
public int hashCode() {
int hash = 0;
hash += (int) (Double.doubleToLongBits(this.getX())
^ (Double.doubleToLongBits(this.getX()) >>> 32));
hash += (int) (Double.doubleToLongBits(this.getY())
^ (Double.doubleToLongBits(this.getY()) >>> 32));
return hash;
}
@Override
public String toString() {
Thread t = new Thread();
String summary = "\tCartesian:\t( x\t: " + x + ", y\t: " + y + " )";
if (state == null) {
setState(State.SHORT_SUMMARY);
}
if (!state.equals(State.NO_SUMMARY)) {
summary += "\n\tPolar:\n\t\tDegrees\t( radius\t: " + radius + ", angle\t: "
+ angleD + " )\n";
summary += "\t\tRadians\t( radius\t: " + radius + ", angle\t: "
+ angleR + " )\n";
}
if (state.equals(State.LONG_SUMMARY)) {
summary += "\tQuadrant\t: " + getLocation();
// summary += "\n\t" + Integer.toHexString(hashCode());
}
return summary;
}
/**
*
*/
@SuppressWarnings("PublicInnerClass")
public static enum State {
/**
* If the {@code state} of a {@code Point} is set to this value, then
* the {@code toString()} will display:
* <ol>
* <li>Cartesian Representation : (x,y)</li>
* <li>Polar Representation (r,θ) in :
* <ul><li>Degrees</li><li>Radians</li></ul></li>
* <li>The quadrant in which the {@code Point} is located.</li>
* </ol>
*/
LONG_SUMMARY,
/**
* If the {@code state} of a {@code Point} is set to this value, then
* the {@code toString()} will display:
* <ol>
* <li>Cartesian Representation : (x,y)</li>
* <li>Polar Representation (r,θ) in :
* <ul><li>Degrees</li><li>Radians</li></ul></li>
* </ol>
*
*/
SHORT_SUMMARY,
/**
* If the {@code state} of a {@code Point} is set to this value, then
* the {@code toString()} will display the Cartesian Representation :
* (x,y) of this {@code Point}.
*/
NO_SUMMARY;
}
@SuppressWarnings("PublicInnerClass")
public static enum Quadrant {
FIRST_QUADRANT,
SECOND_QUADRANT,
THIRD_QUADRANT,
FOURTH_QUADRANT,
ON_X_AXIS,
ON_Y_AXIS,
ON_ORIGIN;
}
}
</code></pre>
<hr>
<p>I used NetBeans 8.0 to create the above class, so the arrangement, the <em>warning suppression</em> has been suggested by this software. I need people to criticize and discuss upon:</p>
<ol>
<li>The effectiveness of the code.</li>
<li>The organization of the code.</li>
<li>Possible ways to <em>improve</em> the performance, readability, simplicity, etc.</li>
<li><strong>Is the <em>hashing</em> good enough?</strong></li>
<li>Any errors in the documentation (technical, accidental) of the code.</li>
<li>Any other aspect focused upon improvement of my programming skills.</li>
</ol>
<p>through downvotes (and upvotes?<sup>1</sup>), comments and answers (of course!). Please note that <strong>this is a library class that anyone can use or modify</strong>, but inform me first.</p>
<hr>
<h2>EDIT:</h2>
<p>After <em>[encountering]</em> so many varied answers, I have decided to change these aspects:</p>
<ol>
<li>As suggested by <a href="https://codereview.stackexchange.com/users/2035/rotora">RoToRa</a> in <a href="https://codereview.stackexchange.com/a/46179/37479">this</a> answer, I'll get rid of the <code>State</code> idea completely, because it is actually temporary.</li>
<li>From the same answer, I'll change the name of the factory methods to start with <code>create...</code>.</li>
<li>Fix the <em>bug</em> pertaining to the angle (from the same answer).</li>
<li>Modify the <code>hashcode()</code> and <code>equals()</code> method. (I have done it <a href="https://stackoverflow.com/questions/22860639/how-do-i-correct-my-hash-function">here</a>).</li>
<li>As suggested by <a href="https://codereview.stackexchange.com/users/37033/coredump">coredump</a> in <a href="https://codereview.stackexchange.com/a/46186/37479">this</a> answer, I'll change <code>initPolar()</code> (or maybe even get rid of it).</li>
<li>As suggested by <a href="https://codereview.stackexchange.com/users/34451/eike-schulte">Eike Schulte</a> in <a href="https://codereview.stackexchange.com/a/46209/37479">this</a> answer, I'll fix the <code>atan2(y,x)</code> bug.</li>
<li>As suggested by <a href="https://codereview.stackexchange.com/users/34757/chrisw">ChrisW</a> over <a href="https://codereview.stackexchange.com/a/46169/37479">here</a>, I'll use <code>pow(..)</code> throughout.</li>
<li>Use a <em>5-parameter constructor</em> (for use by the factory methods).</li>
</ol>
<p>(These changes haven't been applied to the code above.)</p>
<ul>
<li>In addition to these, I'm thinking of adding a <code>scale</code> variable (<code>double</code>) that is used to decide the degree of accuracy (and overcome the <a href="https://stackoverflow.com/questions/22189081/how-to-overcome-inaccuracy-in-java"><em>floating-point issues</em></a>). Is it really practical?</li>
<li><strong>Justification for <code>PointTracker</code>:</strong><br>
I'll add a post later on about the class <code>PointTracker</code> after some time. This class is (as the name suggests) supposed to track (all?) the <code>Points</code> created during runtime. It'll add support for <em>yet another library class</em>: <code>Line</code>. (Hence, you can expect quite a few posts related to this topic.)</li>
<li><strong>Last, but not the least</strong> I invite more answers pertaining to topics other than those resolved above, so that this <code>Point</code> is the <em>ideal</em> class. I also invite demonstrations of <em>just-in-time</em> implementations of the <strong>inter-conversion of the angles</strong> or other related operations.</li>
</ul>
<p><em>Please guys, remember that this is for <strong>you</strong>; so give suggestions to make it more <strong>personal</strong></em>.</p>
<hr>
<p><sup>1 : Help CodeReview <a href="https://codereview.meta.stackexchange.com/questions/1572/what-are-the-advantages-of-graduation">graduate</a>!</sup></p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T22:30:47.950",
"Id": "80657",
"Score": "4",
"body": "The hashing could be more effective but it's actually fine. The `equals` depending on `hashCode` is very bad. We would not expect `(1, 0)` and `(0, 1)` to be considered equal and right now they are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T17:14:42.927",
"Id": "80819",
"Score": "0",
"body": "Why bother special-casing the origin in `reflectionFrom`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:59:05.273",
"Id": "80860",
"Score": "0",
"body": "Why is it mutable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:34:19.470",
"Id": "80970",
"Score": "0",
"body": "@user2357112 As I've commented below ChrisW's answer: _\"Using this.equals(ORIGIN) helps save some time coz, the dist. b/w `this Point` and `Point.ORIGIN` is already stored --> `radius`\"_. But then again, I don't know if it's practical."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:35:57.173",
"Id": "80971",
"Score": "0",
"body": "@Alex I didn't want it to be, but I had to make it mutable to implement the _factory methods_. Now, I can make x, y, radius, etc. `final` thanks to all the generous people of CodeReview. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:46:15.233",
"Id": "80974",
"Score": "0",
"body": "@ambigram_maker: It adds additional code complexity and some overhead for the not-origin case, which probably isn't worth it. Furthermore, it's premature optimization. You don't know whether the case where the other point is the origin is common enough, and the savings in that case great enough, that it even improves the average runtime of the method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:49:05.373",
"Id": "80975",
"Score": "0",
"body": "@user2357112 So... I guess -\"down with the `if-else`\"_ then?"
}
] | [
{
"body": "<p>This will be an incomplete review because I don't really know Java.</p>\n\n<p>Instead of <code>State</code> maybe call it <code>SummaryType</code> or <code>FormatType</code>.</p>\n\n<p>In <code>distanceFrom</code> I don't see why you have a special case for <code>other.equals(Point.ORIGIN)</code>; and given that you do, I don't see why you don't also have a special case for <code>this.equals(Point.ORIGIN)</code>.</p>\n\n<p>Your implementation of <code>equals</code> might be buggy: if points are equal then their hash codes are equal; but different points might be able to have the same hash code.</p>\n\n<p>You're carrying redundant/duplicate information in each instance: e.g. the angle in degrees and in radians. You could store only one and calculate the other just-in-time if it's asked for. Similarly you're pre-calculating and storing its cartesian and its polar representation: would it be better to store one and calculate the other just-in-time; or have two different classes (<code>CartesianPoint</code> and <code>PolarPoint</code>) for the two different representations?</p>\n\n<p>Sometimes you use <code>pow(..., 2)</code> and sometimes you use <code>x * x</code>: is that deliberate?</p>\n\n<p>Are there values (along an axis) for which <code>atan2</code> doesn't work well because its behaviour is asymptotic?</p>\n\n<p>Calculated points risk being never-equal due to rounding errors. It's usual with floating-point to arithmetic to decide they're 'equal' if they're \"close enough\". That could interfere with hashing though (if it's required that equal values must have equal hashes). So you might want to define another function \"nearlyEqual\" which returns true if <code>distanceFrom</code> is less than some small epsilon.</p>\n\n<p>Because of rounding errors you may find anomalies e.g. that a point initialized using polar coordinates doesn't return the right <code>getLocation()</code> value. If you had two classes then the <code>getLocation</code> method for the polar class could do its test using the angle instead of using the <code>x</code> and <code>y</code> values.</p>\n\n<p>Do you want to use <code>double</code> for your <code>x</code> and <code>y</code> types? It might be better (e.g. so that you don't have trouble comparing <code>1</code> with <code>1.0000000000000001</code>) to use <code>int</code> instead, if that's appropriate for example if <code>x</code> and <code>y</code> are measures of integer pixel value. </p>\n\n<p>I'd like to see a list of unit-tests, so that I know what values you have tested it for.</p>\n\n<p>This comment is untrue (not implemented):</p>\n\n<blockquote>\n <p>If a pre-existing point exists, the {@code Point} is returned from the {@code PointTracker}.</p>\n</blockquote>\n\n<p>It might be better if the data members were <code>final</code>. You could implement this even when you have multiple factory methods, by:</p>\n\n<ul>\n<li>Having a constructor which takes all values via parameters</li>\n<li>Calculate all those parameter values in the static factory methods, and then call the constructor.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:48:11.670",
"Id": "80554",
"Score": "0",
"body": "My `package` is incomplete, just like your review. (-> JOKE: No Offence!) :-) I have yet to implement my `PointTracker` (see the body of my constructor (but that's another post)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:49:57.343",
"Id": "80555",
"Score": "0",
"body": "I'm prefering _factory methods_ to the constructor because of the _ambiguity issue_: read (or try to :-) )the documentation just above the main class for justification."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:52:05.943",
"Id": "80556",
"Score": "0",
"body": "I'm intentionally using `double` for `x` and `y`, instead of `int` (that's why I need some hint regarding **hashing** and **equality**)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:54:06.223",
"Id": "80557",
"Score": "0",
"body": "Using `this.equals(ORIGIN)` helps save some time coz, the dist. b/w `this Point` and `Point.ORIGIN` is already stored --> `radius`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:13:47.903",
"Id": "80564",
"Score": "2",
"body": "@ambigram_maker I understand why you have factory methods (though it might be better to have different classes, one for Cartesian and one for Polar). If your members are final (which perhaps they could/should be) then I think you initialize them in one place e.g. in a constructor. Having a non-trivial constructor is not incompatible with having factory methods: you can have a constructor which takes all 5 parameters, and calculate those 5 parameter values in the factory method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:08:55.677",
"Id": "80683",
"Score": "0",
"body": "I have edited the question, so please take a look."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:32:44.970",
"Id": "46169",
"ParentId": "46152",
"Score": "8"
}
},
{
"body": "<p>Use use of a \"state\" to distinguish between different output formats is very wrong. If you need different formats, use multiple output methods (have <code>toString</code> just for debug output), or even better, write a separate class for converting <code>Point</code>s to a string representation.</p>\n\n<p>I think you have overdone it with the JavaDoc. IMHO it's neither the place for theoretical excursus on how coordinate systems work, nor the place to discuss implementation decisions (\"Since there are <i>two</i> parameters in both cases, and each is of the type {@code double}, an ambiguity arises.\").</p>\n\n<p>The names of the factory methods shouldn't begin with <code>get...</code> since they are not getters. Use <code>create...</code> instead.</p>\n\n<p>You should modulo the degrees to 360 (and the radians to 2π) otherwise you get:</p>\n\n<pre><code>Point p1 = Point.getPolarDegreesPoint(10,45);\nPoint p2 = Point.getPolarDegreesPoint(10,405);\nSystem.out.println(p1.equals(p2)); // prints false, but should be true.\n</code></pre>\n\n<p>The use of the hash code inside the equals not good. One of the functions of <code>equals</code> is to distinguish between two objects with the same hash code - which will happen, considering you are \"squeezing\" two 64 bit double values into a 32 bit integer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:45:40.020",
"Id": "80593",
"Score": "0",
"body": "Thanks for the loophole about the angle... And could (please?) demonstrate a _better_ way to **hash** the `Points`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:46:48.490",
"Id": "80594",
"Score": "3",
"body": "The hash is ok. Just don't use it in the `equals()` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:07:59.820",
"Id": "80681",
"Score": "0",
"body": "I have edited the question, so please take a look."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:57:58.133",
"Id": "46179",
"ParentId": "46152",
"Score": "16"
}
},
{
"body": "<h2>1. Why <code>static</code> ?</h2>\n\n<p>I have a minor issue with the following:</p>\n\n<blockquote>\n <p>private static void initPolar(Point point) {</p>\n</blockquote>\n\n<p>Why do you define a static function when the argument is an instance of a <code>Point</code> and thus could be a method?</p>\n\n<pre><code>private void initPolar() {\n double angle = getAngleRadians();\n x = getRadius() * cos(angle);\n y = getRadius() * sin(angle);\n}\n</code></pre>\n\n<h2>2. Do you need caching ?</h2>\n\n<blockquote>\n <p>If a pre-existing point exists, the {@code Point} is returned from the {@code PointTracker}</p>\n</blockquote>\n\n<p>This looks like premature optimization to me. What is the intended benefits of storing and looking up points in a cache (which takes time and memory) instead of creating multiple instances of points. How likely it is that points will be created at the exact same location?</p>\n\n<p>How are you going to implement the tracker? using a hash map? will you create a temporary point just to check whether it already belongs to the set and discard it in order to return the stored instance?</p>\n\n<p>Besides, if you really need caching, this is not the responsability of the <code>Point</code> class to do it. The class exposes a <code>hash</code> function so that other classes can use it.</p>\n\n<h2>3. Class hierarchy</h2>\n\n<p>It has already been suggested, but you can define two kind of points, \"polar\" and \"cartesian\" ones, both having well-defined public constructors:</p>\n\n<pre><code> public CartesionPoint (double x, y) ...\n public CartesionPoint (PolarPoint pp) ...\n\n public PolarPoint (double radius, radians) ...\n public PolarPoint (CartesionPoint cp) ...\n</code></pre>\n\n<p>If you really want to build PolarPoint with either radians/degrees, maybe your constructor can take an optional unit parameter (e.g. RADIANS or DEGREES, defined in an enum type).</p>\n\n<p>I hope I don't sound too harsh. Good luck :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:44:15.280",
"Id": "80592",
"Score": "0",
"body": "As for #2, you are absolutely right: I will create a `PointTracker` class for the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:24:02.043",
"Id": "80605",
"Score": "0",
"body": "@ambigram_maker That's good, but I honestly don't understand why you need a `PointTracker`; is it really necessary?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:08:31.557",
"Id": "80682",
"Score": "0",
"body": "I have edited the question, so please take a look."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:37:41.977",
"Id": "80691",
"Score": "0",
"body": "@ambigram_maker Let's try another approach: in [the standard library](http://docs.oracle.com/javase/7/docs/api/), I see no `FileTracker`, `DoubleTracker` nor `InputStreamTracker` (there *is* a `MediaTracker` class, though). If anyone wants to track points in their applications, they will do it. *But **you** can't do this in a generic way*: will you use spatial hashing? or simply lists? you can't know what is good for everyone; I'am afraid you are over-architecting *this part* of the library. I'd suggest writing applications to test its API: try a bottom-up approach instead of a top-down one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T22:27:49.537",
"Id": "82011",
"Score": "0",
"body": "Very nice answer! Feel free to join us in [our chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:28:59.133",
"Id": "46186",
"ParentId": "46152",
"Score": "13"
}
},
{
"body": "<p>The <code>Math.atan2</code> function is defined rather strangely (not only in Java, but in every programming language I know) and the correct use is <code>atan2(y, x)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T18:32:49.160",
"Id": "80634",
"Score": "0",
"body": "I'm not familiar with `atan2` or anything in math, but why would it be the correct use ? Should you call the Java version with `atan2(y, x)` or not ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T18:43:04.600",
"Id": "80637",
"Score": "6",
"body": "@Marc-Andre [Java's atan2](http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html) wants `y, x`: but the OP wrote `x, y` which therefore seems to be a bug."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:09:52.780",
"Id": "80684",
"Score": "0",
"body": "I have edited the question, so please take a look."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T18:11:39.803",
"Id": "46209",
"ParentId": "46152",
"Score": "10"
}
},
{
"body": "<p>One line review</p>\n\n<p>I don't see any use of <code>Thread t = new Thread()</code> in <code>toString</code> method.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:10:47.917",
"Id": "80686",
"Score": "0",
"body": "I have edited the question, so please take a look."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:49:25.937",
"Id": "80730",
"Score": "0",
"body": "@ambigram_maker The point is that you SHOULDN'T."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:51:53.410",
"Id": "80732",
"Score": "1",
"body": "@ambigram_maker ehhh what are you saying? you have done it. See your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:10:24.180",
"Id": "80738",
"Score": "0",
"body": ":-O. Man... I've gone crazy!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T18:59:44.730",
"Id": "46211",
"ParentId": "46152",
"Score": "8"
}
},
{
"body": "<p>If a class is supposed to serve as a data holder, two instances which report themselves as equal should have the same properties; further, values corresponding to constructor/factory parameters should match the values used in creating the object. It would be possible to have a polar-coordinate type whose properties were the rho and theta values, or an xy coordinate type, whose properties were x and y, or perhaps even an abstract coordinate type with subtypes that hold degree-polar coordinates, radian-polar coordinates, and xy coordinates (each of which would store a different set of properties). Defining how the latter should work, though, could be tricky.</p>\n\n<p>Consider what happens, for example, if one constructs a point with polar coordinates (angle=45 degrees, radius=2.0) and then constructs another point whose xy coordinates match the first. Any possible behavior by the class is apt to be \"surprising\", since the xy-constructed object will have a radius of 2.0000000000000004; this means that either:</p>\n\n<ul>\n<li>The xy-constructed object won't be equal to another object whose coordinates are reportedly the same, or</li>\n<li>The xy-constructed object, though supposedly equal to the polar-constructed one, will have a different radius, or</li>\n<li>The radius of the polar-constructed object won't match the specified value.</li>\n</ul>\n\n<p>Of these, perhaps the first would be most justifiable if one says that degree-polar objects are unequal to any xy object except when the angle is a multiple of 90 degrees, and radian-polar objects are unequal to any other object except when the angle is zero. Even though the closest <code>double</code> to the polar-degree object's x coordinate is 1.4142135623730951, the actual x coordinate is closer to 1.4142135623730950488016887242097, so it won't quite match any point whose xy coordinates are specified using a <code>double</code>.</p>\n\n<p>Unless there's some particular reason for using polar coordinates, I'd suggest having the <code>Point</code> type explicitly encapsulate an <code>x</code> and <code>y</code>, both of type <code>double</code>. Use <code>public final</code> fields for those and set them in a private constructor. Even if you have other methods which can construct a point for a given radius and angle, or report the radius and angle associated with a point, make it clear that reported values are not inherent properties of the object, but simply calculations based upon its x and y.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:10:24.733",
"Id": "80685",
"Score": "0",
"body": "I have edited the question, so please take a look."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:08:31.697",
"Id": "80792",
"Score": "0",
"body": "Your edit doesn't address the biggest issue, which is whether a request to construct a point with (angle=45deg; radius=2.0) should yield a point with exactly that angle and radius, or whether it should yield the nearest point whose x and y coordinates are representable. As for `PointTracker`, I would suggest that `Point` itself should handle caching (with the assistance of one or more other classes), but allow allow the factory methods' callers to indicate when caching is particularly likely to be helpful. With regard to caching of computations, I would suggest..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:13:22.600",
"Id": "80794",
"Score": "0",
"body": "...that it might be useful to have your `Point` hold an `X` and `Y`, and a reference to a `PointInfo` object which could have additional information, including possibly a sequence number and the identity of another lower-sequenced `PointInfo` which is known to be equal. Using such an approach would mean that if two points are compared and found to be equal, the result of any computation upon either (whether performed before or after the comparison) would be cached for both. Further, if A has found equal to B and B to C, then computations on A would be cached for C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:14:20.410",
"Id": "80795",
"Score": "0",
"body": "There are some wrinkles one needs to be careful of in such a design to avoid having things go bonkers if points are accessed in different threads, but it could still be an interesting approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T04:32:03.243",
"Id": "80969",
"Score": "0",
"body": "Well... as for the accuracy issue: _\" I'm thinking of adding a `scale` variable\"_ as I've said in the edit. This ought to take care of minor adjustments (like rounding) but has yet to be implemented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T23:09:44.567",
"Id": "81091",
"Score": "0",
"body": "@ambigram_maker: Adding a `scale` variable is apt to make equivalence even murkier than its absence. Java collections expect that objects can be divided into equivalence classes [mathematical term], such that all of them objects in each equivalence class are equivalent to each other, and none of them are equivalent to anything outside the class. Strings are divided into equivalence classes based on character sequence; two strings are equivalent if and only if they contain the same characters. How should `Point`'s equivalence classes be defined?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T20:30:54.980",
"Id": "46216",
"ParentId": "46152",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:15:55.120",
"Id": "46152",
"Score": "25",
"Tags": [
"java",
"design-patterns",
"library",
"library-design"
],
"Title": "A Library Class : Point"
} | 46152 |
<p>I have a method that finds 3 numbers in an array that add up to a desired number.</p>
<pre><code>public static void threeSum(int[] arr, int sum) {
quicksort(arr, 0, arr.length - 1);
for (int i = 0; i < arr.length - 2; i++) {
for (int j = 1; j < arr.length - 1; j++) {
for (int k = arr.length - 1; k > j; k--) {
if ((arr[i] + arr[j] + arr[k]) == sum) {
System.out.println(Integer.toString(i) + "+" + Integer.toString(j) + "+" + Integer.toString(k) + "=" + sum);
}
}
}
}
}
</code></pre>
<p>I'm not sure about the big O of this method. I have a hard time wrapping my head around this right now. My guess is O(n<sup>2</sup>) or O(n<sup>2</sup>logn). But these are complete guesses. I can't prove this. Could someone help me wrap my head around this?</p>
| [] | [
{
"body": "<p>Are you looking for three distinct numbers, or can <em>i</em>, <em>j</em>, and <em>k</em> be the same? The loop limits suggest that you expect the numbers to be distinct. However, you don't actually check that the results are distinct.</p>\n\n<p>To be consistent, you should either:</p>\n\n<ul>\n<li>Make all three loops consider entries from the entire array, or</li>\n<li>Discard solutions where <em>i</em> = <em>j</em> or where <em>j</em> = <em>k</em> or where <em>i</em> = <em>k</em>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:25:47.827",
"Id": "80510",
"Score": "0",
"body": "I figured out the big O of my program. However you made a really good point about the values of the numbers. I am going to look into this!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:33:15.963",
"Id": "80513",
"Score": "0",
"body": "O(n^3) for those wondering"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:21:22.123",
"Id": "46155",
"ParentId": "46153",
"Score": "3"
}
},
{
"body": "<p>The running time is O(<em>n</em><sup>3</sup>). You have three nested loops:</p>\n\n<ul>\n<li>Approximately <em>n</em> iterations of <em>i</em></li>\n<li>For each <em>i</em>, approximately <em>n</em> iterations of <em>j</em></li>\n<li>For each (<em>i</em>, <em>j</em>) pair, up to about <em>n</em> iterations of <em>k</em>. On average, it take just 0.5 * <em>n</em> iterations of <em>k</em>, but the constant factor doesn't matter.</li>\n</ul>\n\n<p>Quicksort is generally O(<em>n</em> log <em>n</em>). So the total is O(<em>n</em> log <em>n</em> + 0.5 <em>n</em> × <em>n</em> × <em>n</em>), which is O(<em>n</em><sup>3</sup>).</p>\n\n<p>Since you took the trouble to sort the array, the innermost loop could be replaced by a binary search, which is O(log <em>n</em>). Therefore, an improved algorithm could work in O(<em>n</em><sup>2</sup> log <em>n</em>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:33:42.897",
"Id": "80514",
"Score": "0",
"body": "Oh wow Binary search within the inner loop! Never though of that thank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:31:09.943",
"Id": "46158",
"ParentId": "46153",
"Score": "7"
}
},
{
"body": "<p>This won't change the Big O but the second loop can start at j = i + 1.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:43:07.527",
"Id": "46170",
"ParentId": "46153",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46158",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T06:43:24.283",
"Id": "46153",
"Score": "6",
"Tags": [
"java",
"performance",
"complexity"
],
"Title": "Performance analysis of 3 digits sum"
} | 46153 |
<pre><code>import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
public class LargestPalindrome{
static ArrayList<String> palinList=new ArrayList<String>();
public static void splitString(){
String actualString="ABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOOD";
for(int i=0 ; i<actualString.length() ; i++){
for(int j=i ; j<actualString.length() ; j++){
findPalindrome(actualString.substring(i,j));
}
}
}
public static void findPalindrome(String actualStr){
String reversedStr="";
//int palindromeCount=0;
for(int i=actualStr.length()-1 ; i>=0 ; i--){
reversedStr+=actualStr.charAt(i);
}
if(actualStr.equals(reversedStr)&&actualStr.length()>=3){
//System.out.println(actualStr);
palinList.add(actualStr);
}
}
public static String largestPalindromeCheck(ArrayList<String> palList){
int maxLength=palList.get(0).length();
int index=0;
for(int i=1 ; i<palList.size() ; i++){
if(palList.get(i).length()>maxLength){
maxLength=palList.get(i).length();
index=i;
}
}
return palList.get(index);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
splitString();
//System.out.println(palinList);
System.out.println(largestPalindromeCheck(palinList));
}
}
</code></pre>
<p>Please review the code and provide feedback on best practices and code optimization.</p>
| [] | [
{
"body": "<p><strong>Re-organising the code</strong></p>\n\n<p>You've tried to split the logic into small functions and that was a good idea. Unfortunately, because of the way it plays with a class member <code>palinList</code>, the flow is quite hard to follow. In order to avoid this, the best is to define small functions that perform a simple task and return a result and to try to avoid side-effects if we don't need them.</p>\n\n<p>Also, your function and argument names are not really clear. In particular :</p>\n\n<ul>\n<li><code>splitString()</code> : one would expect this to get a string and to return a list of string</li>\n<li><code>actualString</code> : what is a \"non-actual\" string ?</li>\n<li><code>largestPalindromeCheck(ArrayList<String> palList)</code> : this returns the biggest string in the list, it doesn't really matter whether this is a list of palindromes or not.</li>\n</ul>\n\n<p>You are importing useless packages.</p>\n\n<p>You should remove useless code before submitting to code review.</p>\n\n<p>The style for spacing and brackets is a bit unusual.</p>\n\n<p>Taking this simple comments into account (except for the last one because I can't be bothered), here's the code I have rewritten :</p>\n\n<pre><code>import java.util.ArrayList;\n\npublic class LargestPalindrome{\n\n public static String findLargestPalindrome(String s){\n return getLargestString(findPalindromes(s));\n }\n\n public static String reverseString(String s){\n String reversedStr=\"\";\n for(int i = s.length()-1 ; i >= 0 ; i--){\n reversedStr += s.charAt(i);\n }\n return reversedStr;\n }\n\n public static ArrayList<String> findPalindromes(String s){\n ArrayList<String> palinList=new ArrayList<String>();\n for(int i=0 ; i<s.length() ; i++){\n for(int j=i ; j<s.length() ; j++){\n String sub = s.substring(i,j);\n if(sub.equals(reverseString(sub))&&sub.length()>=3){\n palinList.add(sub);\n }\n }\n }\n return palinList;\n }\n\n public static String getLargestString(ArrayList<String> list){\n int maxLength=list.get(0).length();\n int index=0;\n for(int i=1 ; i<list.size() ; i++){\n if(list.get(i).length()>maxLength){\n maxLength=list.get(i).length();\n index=i;\n }\n }\n return list.get(index);\n }\n\n\n public static void main(String[] args) {\n String s=\"JUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGERJUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGER\";\n System.out.println(findLargestPalindrome(s));\n }\n}\n</code></pre>\n\n<p><strong>Making things faster</strong></p>\n\n<p><code>if(sub.equals(reverseString(sub))&&sub.length()>=3)</code> can be rewritten <code>if(sub.length()>=3 && sub.equals(reverseString(sub)))</code> to avoid going through list construction if we don't need to.</p>\n\n<p>Actually, this is not so much of an issue because we can make the check for palindromes more efficient : reusing <a href=\"https://stackoverflow.com/a/15018381/1104488\">this answer</a>, one can define a check for palindromness that doesn't need to build a string and stops as soon as the string is indeed not a palindrom. With my examples, instead of going through 2420363 iterations in <code>reverseString()</code>, we now perform 31423 iterations in <code>isPalindrome</code>.</p>\n\n<p>Now, for a more dramatic improvement we have to focus on what we really want to achieve, what we are really looking for : we don't care that much about populating a list of palindromes, we only care about the biggest one. What does this imply ? It implies that we can ignore whatever is smaller than what we have already found.</p>\n\n<p>At this stage, the code looks like this :</p>\n\n<pre><code>public class LargestPalindrome{\n\n public static boolean isPalindrome(String str) {\n int n = str.length();\n for( int i = 0; i < n/2; i++ )\n {\n if (str.charAt(i) != str.charAt(n-i-1)) return false;\n }\n return true;\n }\n\n public static String findLargestPalindrome(String s){\n String biggestPalindrome = \"\";\n for(int i=0 ; i<s.length() ; i++){\n for(int j=i ; j<s.length() ; j++){\n String sub = s.substring(i,j);\n if (sub.length()>biggestPalindrome.length() && isPalindrome(sub)){\n biggestPalindrome = sub;\n }\n }\n }\n return biggestPalindrome;\n }\n\n public static void main(String[] args) {\n String s=\"JUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGERJUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGER\";\n System.out.println(findLargestPalindrome(s));\n }\n}\n</code></pre>\n\n<p>Now, an additional trick : for a given <code>i</code>, <code>j</code> will go through all values from <code>i</code> to <code>s.length() -1</code> and the order does not really matter (yet). Thus, the loop can be returned : <code>for(int j=i ; j<s.length() ; j++)</code> becomes <code>for(int j=s.length()-1 ; j >= i ; j--)</code>. First cool thing : for a given <code>i</code>, we'll call <code>length()</code> only once : it doesn't look like much but as it comes for free, it's pretty good already but the best is still to come. Indeed, for a given <code>i</code>, the substrings we are considering will get smaller and smaller. Thus, we can stop iterating whenever the strings we would consider become smaller than what we have found already.</p>\n\n<p>This can be written :</p>\n\n<pre><code>public static String findLargestPalindrome(String s){\n String biggestPalindrome = \"\";\n for(int i=0 ; i<s.length() ; i++){\n for(int j=s.length()-1 ; j >= i ; j--){\n nbIt++;\n String sub = s.substring(i,j);\n if (sub.length() < biggestPalindrome.length()) break;\n if (isPalindrome(sub)){\n biggestPalindrome = sub;\n }\n }\n }\n return biggestPalindrome;\n}\n</code></pre>\n\n<p>Actually, we don't even need to build that substring to consider its length : because of the way we construct it, <code>sub.length() == j-i</code> and this optimisation can be included as part of the <code>for</code> syntax : <code>for(int j=s.length()-1 ; j >= i + biggestPalindrome.length(); j--)</code>.</p>\n\n<p>At the end, my final version of the code looks like :</p>\n\n<pre><code>public class LargestPalindrome{\n\n public static boolean isPalindrome(String str) {\n int n = str.length();\n for( int i = 0; i < n/2; i++ )\n {\n if (str.charAt(i) != str.charAt(n-i-1)) return false;\n }\n return true;\n }\n\n public static String findLargestPalindrome(String s){\n String biggestPalindrome = \"\";\n for(int i=0 ; i<s.length() ; i++){\n for(int j=s.length()-1 ; j >= i + biggestPalindrome.length(); j--){\n String sub = s.substring(i,j);\n if (isPalindrome(sub)){\n biggestPalindrome = sub;\n }\n }\n }\n return biggestPalindrome;\n }\n\n public static void main(String[] args) {\n String s=\"JUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGERJUSTTOMAKETHESTRINGABITLONGERABCBAHELLOHOWRACECARAREYOUILOVEUEVOLIIAMAIDOINGGOODRISETOVOTESIRJUSTTOMAKETHESTRINGABITLONGER\";\n System.out.println(findLargestPalindrome(s));\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T17:22:37.543",
"Id": "80626",
"Score": "0",
"body": "Amazing feedback!!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T17:31:12.870",
"Id": "80629",
"Score": "0",
"body": "for(int j=s.length()-1 ; j >= i + biggestPalindrome.length(); j--){\n String sub = s.substring(i,j);\n if (isPalindrome(sub)){\n biggestPalindrome = sub;\n }\n } this portion of the code i didn't understand @Josay"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T07:47:15.060",
"Id": "80679",
"Score": "0",
"body": "Just like `for(int j=i ; j<s.length() ; j++)` makes j start from i and increase it as long as `j < s.length()` , `for(int j=s.length()-1 ; j >= i + biggestPalindrome.length(); j--)` makes j start from `s.length()` and decrease it as long as `j >= i + biggestPalindrome.length()` which basically means as long as \"the string we will consider is bigger than the biggest palindrome found so far\". Then the inside of the loop is nothing but extracting the substring, checking if it is a palindrome and if is it so, update the variable `biggestPalindrome` accordingly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:03:54.110",
"Id": "46163",
"ParentId": "46157",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46163",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T07:22:10.897",
"Id": "46157",
"Score": "3",
"Tags": [
"java",
"palindrome"
],
"Title": "Largest Palindrome Checker"
} | 46157 |
<p>I have implemented a <code>ThreadPoolExecutor</code> that will run a <code>Consumer<T></code> only on elements not already consumed. This code uses Java 8.</p>
<p>The background behind this is that I scan a directory every x time units for which files are present, I must maintain a 100% accuracy on finding files and other mechanisms such as <em>JNotify</em> or a simple plain <code>WatcherService</code> do not achieve that.</p>
<pre><code>public class SingleExecutionThreadPoolExecutor<E> extends ThreadPoolExecutor {
private final Consumer<E> consumer;
private final List<E> elementsInProcess = new ArrayList<>();
public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
this.consumer = consumer;
}
public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
this.consumer = consumer;
}
public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
this.consumer = consumer;
}
public SingleExecutionThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, Consumer<E> consumer, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
this.consumer = consumer;
}
public void execute(E element) {
if (!elementsInProcess.contains(element)) {
super.execute(() -> consumer.accept(element));
elementsInProcess.add(element);
}
}
@Override
@Deprecated
public void execute(Runnable command) { }
}
</code></pre>
<p>It is called using the following classes and snippets:</p>
<pre><code>public final class UniqueTimePath {
private final Path path;
private final FileTime fileTime;
public UniqueTimePath(final Path path) {
this.path = path;
try {
this.fileTime = Files.getLastModifiedTime(path);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
public Path getPath() {
return path;
}
public FileTime getFileTime() {
return fileTime;
}
@Override
public int hashCode() {
int hash = 3;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final UniqueTimePath other = (UniqueTimePath) obj;
if (!Objects.equals(this.path, other.path)) {
return false;
}
if (!Objects.equals(this.fileTime, other.fileTime)) {
return false;
}
return true;
}
@Override
public String toString() {
return "{" + path + ", " + fileTime + "}";
}
}
</code></pre>
<hr>
<pre><code>private SingleExecutionThreadPoolExecutor<UniqueTimePath> executor;
//...
executor = new SingleExecutionThreadPoolExecutor<>(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), fileConsumer);
//...
Files.list(directory)
.map(UniqueTimePath::new)
.forEach(executor::execute);
</code></pre>
| [] | [
{
"body": "<h1>.equals</h1>\n\n<p>The last part of your <code>.equals</code> implementation can be simplified to:</p>\n\n<pre><code>return Objects.equals(this.path, other.path) && Objects.equals(this.fileTime, other.fileTime);\n</code></pre>\n\n<h1>HashCode</h1>\n\n<pre><code>int hash = 3;\nreturn hash;\n</code></pre>\n\n<p>Do I even have to comment anything about what I think about this implementation? You use Objects.equals above, you can use <code>Objects.hashCode(this.path, this.fileTime);</code> here. It is preferred if <code>hashCode</code> and <code>equals</code> use the same fields for their operations.</p>\n\n<h1>Set or List?</h1>\n\n<p>Whenever you use a <code>List</code> in a program, ask yourself the question: Does the order of the elements matter?</p>\n\n<p>In this case, they don't. Use the <code>Set</code> interface and create as <code>HashSet</code> for your <code>elementsInProcess</code> variable.</p>\n\n<pre><code>private final Set<E> elementsInProcess = new HashSet<>();\n</code></pre>\n\n<p>When using a Set, it is <strong>extra important</strong> that the elements in the set has properly implemented <code>hashCode</code> and <code>equals</code>! (Or are using the default implementations inherited from the <code>Object</code> class)</p>\n\n<h1>Cleanup</h1>\n\n<p>I suggest you override the <code>shutdown</code> methods of a <code>ThreadPoolExecutor</code> to clear the <code>elementsInProcess</code> collection.</p>\n\n<h1><code>execute(Runnable command)</code></h1>\n\n<p>Please throw a <code>UnsupportedOperationException</code> or similar in this method:</p>\n\n<pre><code>public void execute(Runnable command) { }\n</code></pre>\n\n<p><strong>Edit:</strong> Scratch that. I think palacsint is absolutely right. By doing nothing here, you're breaking the contract of the <code>Executor</code> interface (which you implement, whether you know it or not - by extending an ExecutorService). The Javadoc for the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html#execute%28java.lang.Runnable%29\">execute(Runnable command)</a> method says: </p>\n\n<blockquote>\n <p>Executes the given command at some time in the future.</p>\n</blockquote>\n\n<p>As it currently stands, you are not doing that and have no real ability of doing so in that method. This fact is an indication that you should not use <code>extends ThreadPoolExecutor</code> and instead use a <code>private ThreadPoolExecutor executor;</code>, and therefore using composition over inheritance.</p>\n\n<h1>Concurrency</h1>\n\n<p><em>If</em> two threads would call <code>execute</code> at the same time, there is a concurrency issue on <code>elementsInProcess</code>. You need to synchronize on something there, for minimal blocking I suggest you do something like this:</p>\n\n<pre><code>synchronize (lock) {\n if (elementsInProcess.contains(element)) {\n return;\n }\n elementsInProcess.add(element);\n}\nsuper.execute(() -> consumer.accept(element));\n</code></pre>\n\n<p>Where <code>lock</code> is a <code>private final Object lock = new Object();</code></p>\n\n<p>Or, you could utilize the fact that the <code>.add</code> method of a set actually returns a boolean indicating if the add was successful and use a <code>Collections.synchronizedSet</code>.</p>\n\n<pre><code>if (!elementsInProcess.add(element)) {\n return;\n}\nsuper.execute(() -> consumer.accept(element));\n</code></pre>\n\n<p>It is important when using a synchronized Set that you only do one method call here, as there could otherwise be a gap between <code>.contains</code> and <code>.add</code> which would again cause concurrency issues between threads.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:49:04.597",
"Id": "46166",
"ParentId": "46159",
"Score": "10"
}
},
{
"body": "<ol>\n<li><p>I would definitely use composition here instead of inheritance. It would eliminate the following ugly (and <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smelly</a>) code too:</p>\n\n<blockquote>\n<pre><code>@Override\n@Deprecated\npublic void execute(Runnable command) { }\n</code></pre>\n</blockquote>\n\n<p>The internals of <code>ThreadPoolExecutor</code> could be changed by JDK developers, so in a future release <code>submit()</code> methods might not call the overridden empty <code>execute()</code> method any more or they could provide a new public <code>execute</code> method which bypass your <code>execute()</code>.</p>\n\n<p>See also: <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em></p></li>\n<li><p>The code should check that the <code>consumer</code> is <code>null</code> in the constructors and throw an <code>IllegalArgumentException</code> or <code>NullPointerException</code> right there.\nIf it remains <code>null</code> you'll get an exception later in the <code>execute</code> method anyway. Throwing an exception immediately helps debugging a lot since you get a stacktrace with the frames of the erroneous client, not just a <code>NullPointerException</code> later, probably from another thread. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt and David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><p>Most developers would expect that <a href=\"https://stackoverflow.com/q/1702386/843804\">submitting jobs from different threads is thread-safe</a>, so I'd use a properly synchronized <code>elementsInProcess</code> list instead of <code>ArrayList</code> to meet this expectation.</p></li>\n<li><p>The following will lead to <a href=\"https://stackoverflow.com/a/11579032/843804\">poor performance if you use your objects in a <code>HashMap</code></a>:</p>\n\n<blockquote>\n<pre><code>@Override\npublic int hashCode() {\n int hash = 3;\n return hash;\n}\n</code></pre>\n</blockquote>\n\n<p>Consider implementing a proper <code>hashCode</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:02:18.200",
"Id": "80533",
"Score": "0",
"body": "Is composition here worth the fact that you need to add delegating methods for **all** functionality of `ThreadPoolExecutor`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:07:08.547",
"Id": "80534",
"Score": "1",
"body": "@skiwi: Eclipse can generate those methods for you, so it is not too much work but you will have a lot more control, better API and less bugs in the long run. The referred Effective Java item mentions the `Properties` class as famous bad example, read that chapter if you can. (http://stackoverflow.com/a/11344295/843804)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:11:45.953",
"Id": "80535",
"Score": "0",
"body": "However if normal (non-default) methods get added to `ThreadPoolExecutor`, then clients of my code will not have access to those methods, that is also a concern."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:22:12.170",
"Id": "80537",
"Score": "0",
"body": "@skiwi: Later you can make those available to your clients with a new release of your code but removing a method from a public API is much harder since it could break existing clients."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T02:25:18.570",
"Id": "80667",
"Score": "2",
"body": "If new methods are added, you should consider which must be available from your class. Allowing a helper class to dictate your class's API without your knowledge or ability to vet the changes is a recipe for disaster, i.e. random bugs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T04:51:36.733",
"Id": "80671",
"Score": "1",
"body": "+1 to composition over inheritance for this one. I'm not usually a strong advocate for this principle, but I *am* a strong advocate for the *Liskov Substitution Principle* (see http://www.oodesign.com/liskov-s-substitution-principle.html), which your code violates. Using composition and not exposing the parts of the API that you prevent from operating as their contract specifies would be the best approach here. (Yes, it's also violated by several parts of the core Java library, but that is the most serious design error in Java to my mind.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T04:55:20.830",
"Id": "80672",
"Score": "1",
"body": "@skiwi Do you really need to expose *all* the methods of a `ThreadPoolExecutor`? Your example of use only uses a small handful of them, so why not only expose those?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:59:06.943",
"Id": "46168",
"ParentId": "46159",
"Score": "10"
}
},
{
"body": "<p>I agree with @SimonAndréForsberg and @palacsint's answers, I have however reconsidered the design and noticed that I do not even want to really use composition for the <code>ThreadPoolExecutor</code>.</p>\n\n<p>I have refactored the code to the class below, where the following assumptions hold:</p>\n\n<ul>\n<li>The <code>Consumer<T></code> is already known.</li>\n<li>The <code>Executor</code> has already been instantiated, in this case an instantiation of a <code>ThreadPoolExecutor</code>.</li>\n</ul>\n\n\n\n<pre><code>public class SingleExecutionExecutorBridge<T> implements Consumer<T> {\n private final Consumer<T> consumer;\n private final Executor executor;\n\n private final Set<T> elementsInProcess = Collections.synchronizedSet(new HashSet<>());\n\n public SingleExecutionExecutorBridge(final Consumer<T> consumer, final Executor executor) {\n this.consumer = Objects.requireNonNull(consumer);\n this.executor = Objects.requireNonNull(executor);\n }\n\n @Override\n public void accept(final T element) {\n if (!elementsInProcess.add(element)) {\n return;\n }\n executor.execute(() -> consumer.accept(element));\n }\n}\n</code></pre>\n\n<p>With this approach everything is decoupled nicely, and the following code snippets are now relevant:</p>\n\n<pre><code>private final SingleExecutionExecutorBridge<UniqueTimePath> singleExecutionExecutorBridge;\nprivate ThreadPoolExecutor executor;\n\n//...\n\npublic BaseChecker(final Path directory, final Consumer<UniqueTimePath> fileConsumer, final Path configFile) {\n this.directory = Objects.requireNonNull(directory);\n this.configFile = Objects.requireNonNull(configFile);\n this.subClass = this.getClass();\n this.singleExecutionExecutorBridge = new SingleExecutionExecutorBridge<>(Objects.requireNonNull(fileConsumer), executor);\n}\n\n//...\n\nexecutor = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());\n\n//...\n\nFiles.list(directory)\n .map(UniqueTimePath::new)\n .forEach(singleExecutionExecutorBridge::accept);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:18:14.250",
"Id": "80565",
"Score": "0",
"body": "Nice, well done. You might want to add `Objects.requireNonNull` in your constructor for `SingleExecutionExecutorBridge` though"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:19:32.253",
"Id": "80566",
"Score": "0",
"body": "@SimonAndréForsberg Yes, yes I do, I'll edit the post to include them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T23:09:35.547",
"Id": "80659",
"Score": "3",
"body": "I have to say that what you did here is composition :-). Unfortunately I didn't have time earlier to show a complete example like this one but I'm glad that you write it. Furthermore, I've found the constructor injection really easy to test with mocked executors. So it's much better than creating a new `ThreadPoolExecutor` inside the class could be."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:15:42.643",
"Id": "46181",
"ParentId": "46159",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46166",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T08:03:38.467",
"Id": "46159",
"Score": "11",
"Tags": [
"java",
"multithreading"
],
"Title": "Extending ThreadPoolExecutor"
} | 46159 |
<p>I have a model Collection which has a many to many relation to a model Item.</p>
<p>I want to be able to add or remove items to this collection using Django Rest Framework.</p>
<p>Option1 - make an action:</p>
<pre><code>class CollectionViewSet(viewsets.ModelViewSet):
queryset = Collection.objects.all()
serializer_class = CollectionSerializer
@action()
def update_items(self, request, **kwargs):
collection = self.get_object()
add_items_id = request.DATA.pop('add_items', [])
remove_items_id = request.DATA.pop('remove_items', [])
items_add = Item.objects.filter(id__in=add_items_id).all()
collection.items.add(*items_add)
items_remove = Item.objects.filter(id__in=remove_items_id).all()
collection.items.remove(*items_remove)
return Response()
</code></pre>
<p>I see two downsides with this:</p>
<ol>
<li>I cannot make one single request to update the collection with items and other fields (not without also modifying these.</li>
<li>I do not get the "API documentation" for free.</li>
</ol>
<p>Option2 - override the update method and use two different serializers</p>
<pre><code>class CollectionSerializer(serializers.HyperlinkedModelSerializer):
items = ItemSerializer(many=True, read_only=True)
class Meta:
model = Collection
fields = ('id', 'title', 'items')
class CollectionUpdateSerializer(serializers.HyperlinkedModelSerializer):
add_items = serializers.PrimaryKeyRelatedField(many=True, source='items', queryset=Item.objects.all())
remove_items = serializers.PrimaryKeyRelatedField(many=True, source='items', queryset=Item.objects.all())
class Meta:
model = Collection
fields = ('id', 'title', 'add_items', 'remove_items')
class CollectionViewSet(viewsets.ModelViewSet):
queryset = Collection.objects.all()
def update(self, request, *args, **kwargs):
collection = self.get_object()
add_items_id = request.DATA.pop('add_items', [])
remove_items_id = request.DATA.pop('remove_items', [])
items_add = Item.objects.filter(id__in=add_items_id).all()
collection.items.add(*items_add)
items_remove = Item.objects.filter(id__in=remove_items_id).all()
collection.items.remove(*items_remove)
# fool DRF to set items to the new list of items (add_items/remove_items has source 'items')
request.DATA['add_items'] = collection.items.values_list('id', flat=True)
request.DATA['remove_items'] = request.DATA['add_items']
return super().update(request, *args, **kwargs)
def get_serializer_class(self):
if self.request.method == "PUT":
return CollectionUpdateSerializer
return CollectionSerializer
</code></pre>
<p>Unfortunately, option2 has this horrible and inefficient hack. Here is why:</p>
<p>Super is called to handle the other properties (in this case only 'title'), it will see that add_items/remove_items is on the source 'items', (and at this point add_items/remove_items params would be empty) so it would remove all items. </p>
<p>What would be the canonical way to handle add/remove of items in a list via django-rest-framework, such that we still get:
- 1 request to update the object (i.e. not via a separate action request)
- re-using DRF patterns / auto-generated API</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-20T14:42:01.827",
"Id": "413693",
"Score": "0",
"body": "What about actions https://www.django-rest-framework.org/api-guide/viewsets/#marking-extra-actions-for-routing"
}
] | [
{
"body": "<p>If the collection is at another model then you must setup the serializer with the 'many' kwarg.</p>\n\n<pre><code>class CollectionContainerViewSet(viewsets.ModelViewSet):\n queryset = CollectionContainer.objects.all()\n collection_ids = serializers.PrimaryKeyRelatedField(\n many=true,\n queryset=Collection.objects.all()\n )\n</code></pre>\n\n<p>Or maybe change the collection to accept updating many?</p>\n\n<pre><code>class CollectionViewSet(viewsets.ModelViewSet):\n queryset = Collection.objects.all()\n serializer_class = CollectionSerializer(many=True)\n</code></pre>\n\n<p>I guess that in most situations you don't explicitly add or remove, but you are change the collection to a known state - containing a specific set of items. If that is not the case and you really must add and remove explicitly I think it is better to have two actions, one for adding and one for removing items by id.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T16:08:02.147",
"Id": "239323",
"ParentId": "46160",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T08:29:33.303",
"Id": "46160",
"Score": "16",
"Tags": [
"python",
"django"
],
"Title": "Django Rest Framework - add/remove to a list"
} | 46160 |
<p>How could I reduce the length of my functions restricting them to max 10 lines?
Other comments are welcome on the code in general.</p>
<pre><code>import config_files
import math
from datetime import datetime
import importlib
import sys
from scan_twittosphere import *
from tweets import *
import nltk
debugger = importlib.import_module('config_files.debugger')
"""
Performs operations of allocating lr users to pertinent tweets and users and sending the result back
to create_json object
"""
class filter_tweets:
"""
method: constructor
input:
String: lr user screen name
String List: List of user keywords
Object: Twitter api connection object
Object: Config file object
Integer: User Autofavorite mode
String: environment of execution
output: None
"""
def __init__(self,screen_name, keywords, api, config,mode_auto_favorite, env):
self.screen_name = screen_name
self.keywords = keywords
self.api = api
self.config = config
self.mode_auto_favorite = mode_auto_favorite
self.MongoObj = MongodbConnections(env)
self.count = 0
"""
method: This method returns list of tweets and meta data back
input:
Object: scan_twittosphere object
output:
Dictionary list: Twitter dictionary list element containing
Integer: Tweet id
Float: lr tweet score
String: Keyword of tweet
"""
def stream_score_tweets(self,scan_twittosphere_obj):
tweets_list = []
'''
search UserFactory
'''
for keyword in self.keywords:
self.count = 0
if self.count < self.config.max_tweet:
scan_twittosphere_obj.stream_tweets(keyword,'tweet')
tweets_list = self.add_tweets(keyword,tweets_list)
else:
return tweets_list
return tweets_list
"""
method: This method adds a tweet to the list from the mongodb database and updates the
new user allocated to the tweet
input:
String: keyword
String List: tweets dictionary
output:
String List: tweets dictionary
"""
def add_tweets(self,keyword,tweets_list):
for tweet in self.MongoObj.getTweetFactoryCol().find({'keyword':keyword}):
tweet_dict = {}
user_list = []
if len(tweet['user_list']) <= self.config.max_user_list:
user_list = tweet['user_list']
if self.screen_name not in user_list:
user_list.append(self.screen_name)
self.MongoObj.getTweetFactoryCol().update({'tweet_id':tweet['tweet_id']}, {'$set': {'user_list':user_list}})
tweet_dict['tweet_id'] = tweet['tweet_id']
tweet_dict['twittalikescore'] = tweet['twittalikescore']
tweet_dict['keyword'] = keyword
self.addFavorite(tweet["tweet_id"])
tweets_list.append(tweet_dict)
self.count += 1
if self.count >= self.config.max_tweet:
return tweets_list
return tweets_list
"""
method: This method adds a tweet to the favorites section of the user
input:
Integer: Tweet id
output:
Boolean: True or (False in case of exception)
"""
def addFavorite(self,tweet_id):
if self.mode_auto_favorite == 1:
try:
self.api.create_favorite(tweet_id)
return True
except:
return False
"""
method: This method returns list of users and meta data back
input:
Object: scan_twittosphere object
output:
Dictionary list: Twitter dictionary list containing
Integer: User id
Float: lr tweet score
String: Keyword of User
"""
def stream_score_users(self,scan_twittosphere_obj):
users_list = []
'''
search UserFactory
'''
for keyword in self.keywords:
self.count = 0
#debugger.info(keyword,self.config.log)
if self.count < self.config.max_users:
scan_twittosphere_obj.stream_tweets(keyword,'user')
users_list = self.add_users(keyword,users_list)
else:
return users_list
return users_list
"""
method: This method adds a user to the list from the mongodb database and updates the
new lr twitter user allocated to the recommended twitter user
input:
String: keyword
String List: users dictionary
output:
String List: users dictionary
"""
def add_users(self,keyword,users_list):
for user in self.MongoObj.getUserFactoryCol().find({'keyword':keyword}):
user_dict = {}
user_reco_list = []
if len(user['user_list']) <= self.config.max_user_list:
user_reco_list = user['user_list']
if self.screen_name not in user_reco_list:
user_reco_list.append(self.screen_name)
self.MongoObj.getUserFactoryCol().update({'user_id':user['user_id']}, {'$set': {'user_list':user_reco_list}})
user_dict['user_id'] = user['user_id']
user_dict['twittalikescore'] = user['twittalikescore']
user_dict['keyword'] = keyword
self.addFavorite(user["tweet_id"])
users_list.append(user_dict)
self.count += 1
if self.count >= self.config.max_users:
return users_list
return users_list
</code></pre>
| [] | [
{
"body": "<p>There is nothing inherently wrong with having methods longer than 10 lines. If there are no reusable elements in those methods then the only reason to break them into more methods is aesthetic (and can also improve readability if you name your methods well).</p>\n\n<p>A couple of comments on the rest of the code:</p>\n\n<p><strong>Imports</strong></p>\n\n<pre><code>from scan_twittosphere import *\nfrom tweets import *\n</code></pre>\n\n<p>Try to avoid <code>import *</code> whenever possible. It clutters the namespace and makes the code much less readable to people who do not already know the libraries you are using well. If you are using many methods or classes from these modules use:</p>\n\n<pre><code>import scan_twittosphere as stw\nimport tweets as tw\n</code></pre>\n\n<p>and if you are just using a few bit and pieces:</p>\n\n<pre><code>from scan_twittosphere import <names of>,<functions>,<or classes>\nfrom tweets import <names of>,<functions>,<or classes>\n</code></pre>\n\n<p><strong>Docstrings</strong></p>\n\n<p>While your docstrings are nicely laid out and readable, they should reside inside the method, function or class they pertain to, not above. See here for the appropriate PEP257 docstring conventions, <a href=\"http://legacy.python.org/dev/peps/pep-0257/\">http://legacy.python.org/dev/peps/pep-0257/</a>.</p>\n\n<p><strong>New-style classes</strong></p>\n\n<p>New-style classes (<a href=\"https://www.python.org/doc/newstyle/\">https://www.python.org/doc/newstyle/</a>) should inherit from <code>object</code>. i.e. </p>\n\n<pre><code>class filter_tweets:\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>class filter_tweets(object):\n</code></pre>\n\n<p><strong>Naming conventions</strong></p>\n\n<p>So generally it good to follow PEP8 guidelines (<a href=\"http://legacy.python.org/dev/peps/pep-0008/\">http://legacy.python.org/dev/peps/pep-0008/</a>) for naming of variables, functions, classes, etc.</p>\n\n<p>Each word in a class name should be capitalised and there should be no underscores:</p>\n\n<pre><code>class filter_tweets(object):\n</code></pre>\n\n<p>goes to:</p>\n\n<pre><code>class FilterTweets(object): \n</code></pre>\n\n<p>also to quote PEP8:</p>\n\n<blockquote>\n <p>A style guide is about consistency. Consistency with this style guide\n is important. Consistency within a project is more important.\n Consistency within one module or function is most important.</p>\n</blockquote>\n\n<p>This applies to your <code>addFavorite</code> method, which should really be <code>add_favorite</code>. Speaking of this method:</p>\n\n<pre><code>def addFavorite(self,tweet_id):\n if self.mode_auto_favorite == 1:\n try:\n self.api.create_favorite(tweet_id)\n return True\n except:\n return False\n</code></pre>\n\n<p>you aren't using those return values anywhere. Also it may be worth catching the certain errors that might be caused by your code, like invalid types for <code>tweet_id</code> (as python is dynamically typed). This isn't a big issue, but it can often help with debugging.</p>\n\n<p>All in all the code looks pretty good, with nice documentation and (even more importantly) descriptive variable names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:28:58.447",
"Id": "80552",
"Score": "2",
"body": "No worries, it's easy to review well laid out code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:32:57.680",
"Id": "46164",
"ParentId": "46162",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "46164",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T08:48:35.693",
"Id": "46162",
"Score": "5",
"Tags": [
"python"
],
"Title": "Reducing lines in methods of Python class to manage tweets"
} | 46162 |
<pre><code>#!/usr/bin/env python
from os import environ, path, name as os_name, getuid
from sys import exit
from fileinput import input
update_environ = lambda: environ.update(dict(env.split('=')
for env in
open('/etc/environment', 'r').readlines()))
if os_name != 'nt' and getuid() != 0:
print "Rerun {0} as `sudo`".format(__file__)
exit(1)
def custom_vars(e_vars):
if not path.isfile('custom_vars.txt'):
return e_vars
with open('custom_vars.txt', 'r') as f:
for line in f.readline():
var = line.split()
e_vars[var[0]] = var[1]
def append_environment(e_vars):
for line in input('/etc/environment', inplace=True):
var, _, val = line.partition('=')
nline = '{var}={val}'.format(var=var, val=e_vars.pop(var, val))
if nline and nline != '=' and nline != '\n' and nline != '=\n':
print nline # inplace editing
if e_vars:
lines = filter(lambda l: l != '=\n' and nline != '\n',
['{var}={val}\n'.format(var=k, val=e_vars[k])
for k in e_vars])
with open('/etc/environment', 'a') as f:
f.writelines(lines)
if __name__ == '__main__':
environment_vars = {'NOM_REPOS': path.join(path.expanduser("~"), 'NOM'),
'NOM_API': path.join('/var', 'www')}
environment_vars = custom_vars(environment_vars)
append_environment(environment_vars)
</code></pre>
<p>I have written a similar script in Bash; with identical functionality:</p>
<pre><code>#!/usr/bin/env bash
sudo sed -i "/^NOM*/d" /etc/environment
for i in `env | grep NOM | cut -f1 -d=`; do
unset "$i";
done
function set_var()
{
VAR="$1"
VAL="$2"
sudo sed -i "/^$VAR/d" /etc/environment
printf "$VAR=$VAL\n" | sudo tee -a /etc/environment > /dev/null
# make the variable available for use in this script and custom_env_vars.sh
export "$VAR=$VAL"
}
set_var NOM_REPOS "$HOME/NOM"
set_var NOM_API /var/www
if [ -f custom_env_vars.sh ]; then
. ./custom_env_vars.sh
else
echo "You can set custom environment variables in 'custom_env_vars.sh'"
fi
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:21:58.940",
"Id": "80536",
"Score": "0",
"body": "Can you give some context? What is the purpose of this code? What are you trying to achieve?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:27:24.973",
"Id": "80538",
"Score": "0",
"body": "I have a variety of scripts; the first set env vars; the others utilise these vars to clone/update repositories, install/update dependencies + OS and configure the system (e.g.: deploy the `.conf`s for my web and application servers). The env vars are also used by my remote log daemons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:05:13.157",
"Id": "80541",
"Score": "1",
"body": "That's a bit vague. Can you describe a use case in detail?"
}
] | [
{
"body": "<p><code>env | grep '^NOM'</code> would more exactly align with the sed command.</p>\n\n<p>ensure you're exactly matching the variable name:</p>\n\n<pre><code>sudo sed -i \"/^$VAR=/d\" /etc/environment\n# .................^\n</code></pre>\n\n<p>Use %-formatters for printf:</p>\n\n<pre><code>printf '%s=\"%s\"\\n\" \"$VAR\" \"$VAL\"\n</code></pre>\n\n<p>In the function, use <code>local</code> to limit the scope of VAR and VAL</p>\n\n<hr>\n\n<p>had another thought about that function. Change</p>\n\n<pre><code>sudo sed -i \"/^$VAR/d\" /etc/environment\nprintf \"$VAR=$VAL\\n\" | sudo tee -a /etc/environment > /dev/null\n</code></pre>\n\n<p>to</p>\n\n<pre><code>tmpfile=$(mktemp)\ngrep -v \"^$VAR=\" /etc/environment > $tmpfile\necho \"$VAR=$VAL\" >> $tmpfile\nsudo mv $tmpfile /etc/environment\n</code></pre>\n\n<p>That minimized any possibility that the /etc/environment file contains \"invalid\" data -- it overwrites the previous good file with the new good file all at once.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:18:05.073",
"Id": "46176",
"ParentId": "46165",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T09:41:28.493",
"Id": "46165",
"Score": "4",
"Tags": [
"python",
"bash"
],
"Title": "Setting global environment vars from Python or Bash"
} | 46165 |
<p>I have a completed application which I'm trying to write unit tests for (Yeah I know, talk about bad practices)</p>
<p>I have the following class here</p>
<pre><code>public class UserManagementService : IUserManagementService
{
private static readonly IUserDao userDao = DataAccess.UserDao;
private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public LoginResponse Login(LoginRequest request)
{
var response = new LoginResponse(request.RequestId);
try
{
var user = userDao.GetByUserId(request.UserId);
if (user != null)
{
if (request.Password != "")
{
if (Authenticate(user, request.Password))
{
return response;
}
response.ErrorCode = "IncorrectPassword";
}
else
{
response.ErrorCode = "PasswordNotFound";
}
}
else
{
response.ErrorCode = "UserNotFound";
}
response.Acknowledge = AcknowledgeType.Failure;
return response;
}
catch (Exception ex)
{
Log.Error(ex);
response.Acknowledge = AcknowledgeType.Failure;
response.ErrorCode = "Exception";
return response;
}
}
public bool Authenticate(User user, string password)
{
if (user == null) return false;
using (var deriveBytes = new Rfc2898DeriveBytes(password, user.Salt))
{
var derivedPassword = deriveBytes.GetBytes(20);
if (!derivedPassword.SequenceEqual(user.Password)) return false;
}
return true;
}
}
</code></pre>
<p><code>userDao</code> follows the singleton pattern and this <code>userDao.GetByUserId(request.UserId);</code> basically makes a call to my DB</p>
<p>I have written the following test, which will definitely give rise to some issues because I haven't figured how to Mock the userDao, and the Log</p>
<pre><code>[Theory]
[InlineData("manager", "manager")]
public void LoginTest(string userId, string password)
{
// Arrange
// System under test
IUserManagementService userService = new UserManagementService();
var request = new LoginRequest().Prepare();
request.UserId = userId;
request.Password = password;
var expectedResponse = new LoginResponse(request.RequestId)
{
Acknowledge = AcknowledgeType.Success
};
//Act
var actualResponse = userService.Login(request);
//Assert
Assert.AreEqual(actualResponse.Acknowledge, expectedResponse.Acknowledge);
}
</code></pre>
<p>How can I refactor my <code>Login</code> method, and <code>UserManagementService</code> class without breaking too much of its structure to support unit testing so I can inject <code>userDao</code> and <code>Log</code>?</p>
<p>Any help would be great to help me kickstart what is going to be a long tedious process of refactoring the rest of my classes.</p>
<p>EDIT: This is a WCF service which follows the facade pattern. I have removed the 10 other static DAO similar to userDao to lessen the code clutter for this example.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:27:58.867",
"Id": "80569",
"Score": "0",
"body": "FYI I prefer [automated system tests instead of automated unit tests](http://stackoverflow.com/q/856115/49942)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:24:58.263",
"Id": "80590",
"Score": "2",
"body": "For one thing, I wouldn't fetch the log and dao from magical statics in the nether in the hopes that they are correctly configured. I'd pass them in. It doesn't look like it'd be a problem to have a constructor take them. Then the class doesn't know whether the things it accesses are singletons or not, which is very freeing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:37:21.177",
"Id": "80690",
"Score": "0",
"body": "Here lies the problem: *`userDao` follows the singleton pattern*."
}
] | [
{
"body": "<p>Following on what Magnus said in comments can you not inject the necessary dependencies.</p>\n\n<p>For example:</p>\n\n<pre><code>public class UserManagementService : IUserManagementService\n{ \n private readonly IUserDao userDao ;\n private readonly ILog log;\n\n public UserManagementService(IUserDao userDao, ILog logger)\n {\n this.userDao = userDao;\n this.log = logger;\n }\n\n public LoginResponse Login(LoginRequest request)\n {\n // etc\n } \n}\n</code></pre>\n\n<p>Now the class has no dependencies on concrete implementations and you can mock the interfaces however you feel. For example, the ILog interface you might want to mock so it logs to the console only. The IUserDao interface might be mocked to a internal list implementation or you might use a mocking framework such as <a href=\"https://github.com/Moq/moq4\">Moq</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T19:18:07.947",
"Id": "46212",
"ParentId": "46172",
"Score": "6"
}
},
{
"body": "<p>+1 to <em>@dreza</em>, and two minor notes about the code.</p>\n\n<ol>\n<li><p>I' create a helper method for creating the response:</p>\n\n<pre><code>private LoginResponse CreateLoginFailureReponse(LoginRequest request, string errorCode)\n{\n var response = new LoginResponse(request.RequestId);\n response.Acknowledge = AcknowledgeType.Failure;\n response.ErrorCode = errorCode;\n return response;\n}\n</code></pre>\n\n<p>And use it from the Login method with <a href=\"http://blog.codinghorror.com/flattening-arrow-code/\" rel=\"nofollow\">guard clauses</a>:</p>\n\n<pre><code>public LoginResponse Login(LoginRequest request)\n{\n try\n { \n var user = userDao.GetByUserId(request.UserId);\n if (user == null)\n { \n return CreateLoginFailureReponse(request, \"UserNotFound\");\n } \n\n if (request.Password == \"\")\n { \n return CreateLoginFailureReponse(request, \"PasswordNotFound\");\n }\n\n if (!Authenticate(user, request.Password))\n { \n return CreateLoginFailureReponse(request, \"IncorrectPassword\");\n } \n\n return new LoginResponse(request.RequestId);\n }\n catch (Exception ex)\n {\n Log.Error(ex);\n return CreateLoginFailureReponse(request, \"Exception\");\n }\n}\n</code></pre>\n\n<p>They makes the code easier to follow, I've found the deep nested if statements are rather hard to read.</p></li>\n<li><p>I've found one-liners like this hard to read:</p>\n\n<blockquote>\n<pre><code>if (!derivedPassword.SequenceEqual(user.Password)) return false;\n</code></pre>\n</blockquote>\n\n<p>If you scan the code line by line it's easy to miss that at the end of the line there is a return statement. I would put that into a new line.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T05:47:08.897",
"Id": "80981",
"Score": "1",
"body": "+1 for refactoring the if statements. I didn't even look into those but I'm a big fan of reducing nesting if I can."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:15:09.490",
"Id": "46253",
"ParentId": "46172",
"Score": "2"
}
},
{
"body": "<p>@dreza's answer is correct. However, my concern is that since constructor injection is not being applied in <code>UserManagementService</code>, I'm going to assume that none of your other services do either. Given this, I'm also assuming that you're constructing your services manually (i.e. <code>var userManagementService = new UserManagementService()</code> and other similar code all over the place). In which case, not only will you have to refactor every service class to accept dependencies via their constructors, you also have to refactor all of the code that uses these services.</p>\n\n<p>So to reduce the overall impact on the existing code base, you could do the following with your service classes (with <code>UserManagementService</code> as an example):</p>\n\n<pre><code>public class UserManagementService : IUserManagementService\n{\n // remove the readonly modifiers so you can replace them with mocked versions\n private static IUserDao UserDao = DataAccess.UserDao;\n private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);\n\n // add a public default constructor so existing code doesn't break\n public UserManagementService() { }\n\n // add an internal constructor which accepts dependencies that you want to replace in your unit tests\n internal UserManagementService(IUserDao userDao, ILog log)\n {\n UserDao = userDao;\n Log = log;\n }\n}\n</code></pre>\n\n<p><em>Note: if your tests are in another assembly, then you need to mark the assembly containing <code>UserManagementService</code> with the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx\" rel=\"nofollow\">InternalsVisibleToAttribute</a>, passing in the name of your test assembly.</em></p>\n\n<p>Now you can test it like so:</p>\n\n<pre><code>[Theory]\n[InlineData(\"manager\", \"manager\")]\npublic void LoginTest(string userId, string password)\n{\n // Arrange\n var mockUserDao = // setup mock here\n var mockLog = // setup mock here\n\n // System under test\n IUserManagementService userService = new UserManagementService(mockUserDao, mockLog);\n\n // rest of test code \n}\n</code></pre>\n\n<p>The advantage of doing it this way is that you only need to change the internal implementation details of each service class without it affecting other parts of the system.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:22:16.820",
"Id": "80744",
"Score": "0",
"body": "This is looks very viable.. However I have lots of Static DAOs just like userDao in this class.. I'm a little reluctant to add all of them as constructor injection"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:44:01.370",
"Id": "80751",
"Score": "0",
"body": "Reluctant because of the time you'll spend doing it? Changing your service classes as such will only take a minute or so per class (depending on how many dependencies you have, of course). Besides, you're only adding them as a means to easily unit test the class in question. Ultimately, the investment asked of you is insignificant in comparison to the benefits you'll receive from unit testing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:54:39.390",
"Id": "80787",
"Score": "0",
"body": "Reluctant because the thought of passing 10 parameters into my constructor is a little off putting. But yeah I get your point"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:23:13.657",
"Id": "46255",
"ParentId": "46172",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46212",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:45:09.850",
"Id": "46172",
"Score": "8",
"Tags": [
"c#",
"unit-testing",
"dependency-injection"
],
"Title": "Refactoring method to make it unit testing friendly"
} | 46172 |
<p>I'm doing VBA macros and need to use Arrays of values extensively. After the below help from @TonyDallimore on Stack Overflow, I've decided to use nested variant arrays.</p>
<p><a href="https://stackoverflow.com/questions/20971161/vba-chrashes-when-trying-to-execute-generated-sub/20973615#20973615">VBA chrashes when trying to execute generated sub</a></p>
<p>I use multidimensional, jagged arrays to <code>SELECT</code> data from DB's and efficiently perform calculations and write to a Worksheet. The data is sometimes a single value (<a href="http://en.wikipedia.org/wiki/Rank_(computer_programming)" rel="nofollow noreferrer">Rank</a>:0) sometimes a row of values (Rank:1) sometimes a table of values with some cells containing rows of values (Rank:3). I use the function below to determine what kind of operations are possible and should be performed to such arrays.</p>
<p>This function, along with all my array related functions reside in a module: modCustomArrayFunctions.</p>
<pre><code>'***************************************************************************'
'Returns the rank of the passed array '
'Parameters: '
' Arr: The array to be processed '
'Returns: '
' The rank of the array '
'***************************************************************************'
Public Function Rank(ByRef Arr As Variant) As Byte
'Declarations **************************************************************'
Dim MaxRank As Byte 'Maximum rank of the elements of the array '
Dim i As Integer
'***************************************************************************'
If IsArray(Arr) Then
If IsArrInitialized(Arr) Then
MaxRank = 0
For i = LBound(Arr) To UBound(Arr)
Rank = Rank(Arr(i)) + 1
If Rank > MaxRank Then MaxRank = Rank
Next i
Rank = MaxRank
Else
Rank = 0
End If
Else
Rank = 0
End If
End Function
'***************************************************************************'
</code></pre>
<p>I code my routines pretty much this way.</p>
<p>And the accompanying test is as follows:</p>
<pre><code>'***************************************************************************'
Public Sub Rank_Test()
Dim TestArr As Variant
Dim TestRank As Integer
'Test Non-Array
If Rank(TestArr) = 0 Then
Debug.Print "Non-Array OK"
Else
Debug.Print "Non-Array FAILED!"
End If
'Test Ranks 1 to 100
For TestRank = 1 To 100
TestArr = MakeArray(TestRank)
If Rank(TestArr) = TestRank Then
Debug.Print TestRank & "D OK"
Else
Debug.Print TestRank & "D FAILED!"
End If
Next TestRank
End Sub
'***************************************************************************'
</code></pre>
<p>Can the code, comments and test be deemed acceptable, what is there to improve?
Is the test okay or have I got the whole unit testing idea wrong?</p>
<p><code>IsArrInitialized()</code> and <code>MakeArray(n)</code> are listed for completeness here. Note that <code>MakeArray(n)</code> is only used to create test arrays and is private to the array test module.</p>
<pre><code>'***************************************************************************'
Private Function MakeArray( _
RankArr As Integer, _
Optional Value As Variant = 1 _
) As Variant
Dim TestArr As Variant
Dim DummyArr As Variant
Dim i As Integer
If RankArr = 0 Then
MakeArray = Value
ElseIf RankArr = 1 Then
ReDim TestArr(1 To 1)
TestArr(1) = Value
MakeArray = TestArr
Else
ReDim TestArr(1 To 1)
ReDim DummyArr(1 To 1)
DummyArr(1) = Value
For i = 1 To RankArr - 1
DoEvents
TestArr(1) = DummyArr
DummyArr = TestArr
Next i
MakeArray = TestArr
End If
End Function
'***************************************************************************'
</code></pre>
<hr>
<pre><code>'***************************************************************************'
'Determines if a dynamic array has been initialized '
'Parameters: '
' Arr: The array to be processed '
'Returns: '
' True if initialized, False if not '
'***************************************************************************'
Public Function IsArrInitialized(ByRef Arr As Variant) As Boolean
'Declarations **************************************************************'
Dim dum As Long
'***************************************************************************'
On Error GoTo ErrLine
If IsArray(Arr) Then
dum = LBound(Arr)
If dum > UBound(Arr) Then
GoTo ErrLine
Else
IsArrInitialized = True
End If
Else
IsArrInitialized = False
End If
Exit Function
ErrLine:
IsArrInitialized = False
End Function
'***************************************************************************'
</code></pre>
| [] | [
{
"body": "<p>Regarding the not-listed <code>IsArrInitialized</code>, after investigating on StackOverflow, I ended up using this:</p>\n<pre><code>Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _\n (pDst As Any, pSrc As Any, ByVal ByteLen As Long)\n\n'returns true if specified array is initialized.\nPublic Function IsArrayInitialized(arr) As Boolean\n\n Dim memVal As Long\n\n CopyMemory memVal, ByVal VarPtr(arr) + 8, ByVal 4 'get pointer to array\n CopyMemory memVal, ByVal memVal, ByVal 4 'see if it points to an address...\n IsArrayInitialized = (memVal <> 0) '...if it does, array is intialized\n\nEnd Function\n</code></pre>\n<p>I would love to see your <code>MakeArray</code> implementation, but I'll stick to the <code>Rank</code> function.</p>\n<h3>Comments</h3>\n<pre><code>'***************************************************************************'\n'Returns the rank of the passed array '\n'Parameters: '\n' Arr: The array to be processed '\n'Returns: '\n' The rank of the array '\n'***************************************************************************'\n</code></pre>\n<p>I remember being told, in school, that this was a good way of documenting code. However, real-world experience has proven otherwise. These comments only clutter up the code, add to the burden of maintenance and inevitably become stale/obsolete/lies.</p>\n<p>What's the need exactly? <em>Say what the thing does</em>. Good, useful comments don't do that - the <em>code itself</em> says "what", good comments say "why". How do you know what the thing does? With proper encapsulation and naming!</p>\n<p>If the <code>Rank</code> function is defined in a code module called <code>Helpers.bas</code> that contains dozens of unrelated specialized functions like this, you have a problem. If it's defined in a code module called <code>ArrayHelpers.bas</code> that contains dozens of somewhat related specifalized functions like this, you have a lesser problem, but a problem still: in VBA anything <code>Public</code> declared in a code module (.bas) is accessible as a "macro" - a <code>Public Function</code> in Excel VBA could even be used as a cell formula, so naming is very important to avoid clashes with existing/"native" functions.</p>\n<pre><code>'Declarations **************************************************************'\n</code></pre>\n<p>Please don't. If you feel the need to "sectionize" the code inside a function, chances are that function is doing too many things.</p>\n<pre><code>Dim MaxRank As Byte 'Maximum rank of the elements of the array \n</code></pre>\n<p>These comments shouldn't be needed; it should be clear what <code>MaxRank</code> is used for, and if it isn't, then the identifier needs a better name, not a comment.</p>\n<hr />\n<h3>Naming</h3>\n<p>I think <code>Rank</code> is a poor name for what the function does. First, I'm tempted to read it as a <em>verb</em>, but you intend it as a <em>noun</em> - nouns are generally <em>classes</em> (/objects), and verbs are for <em>methods</em>, <em>functions</em> and <em>procedures</em>.</p>\n<h3>Readability</h3>\n<p>Your function is recursive, and it's not clear what the intent is - arrays have <em>indices</em>, not "ranks" - the multiple assignments of the function's return value are also a hinderance, consider this:</p>\n<pre><code>Public Function Rank(ByRef Arr As Variant) As Byte\n Dim Result As Byte\n Dim MaxRank As Byte\n Dim i As Integer\n\n If IsArray(Arr) Then\n If IsArrInitialized(Arr) Then\n\n MaxRank = 0\n\n For i = LBound(Arr) To UBound(Arr)\n Result = Rank(Arr(i)) + 1 ' recursive call\n If Result > MaxRank Then MaxRank = Result\n Next i\n\n Result = MaxRank\n\n Else\n Result = 0\n End If\n Else\n Result = 0\n End If\n\n Rank = Result\nEnd Function\n</code></pre>\n<p>The function's return value being only assigned once, makes it easier to rename it and easier to read and tell the reads from the writes and recursive calls at a glance.</p>\n<h3>Bug?</h3>\n<p>Unless you've specified <a href=\"http://msdn.microsoft.com/en-us/library/aa266179(v=vs.60).aspx\" rel=\"nofollow noreferrer\"><code>Option Base 1</code> VBA arrays are 0-based</a>, which means a return value of 0 could be problematic. Typical VBA code would return -1 for an invalid index, so you can tell an invalid index from a zero-based first index.</p>\n<p>This, of course, is countered by explicitly declaring the lower bound of your arrays <code>(1 to 1, 1 to 1, 1 to n)</code>, but that's a rather verbose way of declaring an array.</p>\n<hr />\n<p>That said, I'm not 100% clear on exactly what that function is achieving, even after reading your SO post. Is it possible that you don't <em>really</em> need a multidimensional array (1,1,n), but rather a list of objects that encapsulate an array and two other fields? <a href=\"https://codereview.stackexchange.com/questions/32618/listt-implementation-for-vb6-vba\">This code</a> could be of interest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:47:59.527",
"Id": "80692",
"Score": "0",
"body": "Thank you for the thorough review. I will definitely keep your points in mind when I revise this and write new code. I tend to use too much comments, I know and this is due to the fact that a DBA with little xp in programming will have to maintain, while I'm away for some months. A return value of 0 would actually mean that the variant is actually a single value and not an array. I added the missing functions and also stated my motivation to use such a function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:03:41.417",
"Id": "46203",
"ParentId": "46174",
"Score": "2"
}
},
{
"body": "<p>From above:<Blockquote>you have a lesser problem, but a problem still: in VBA anything Public declared in a code module (.bas) is accessible as a \"macro\" - a Public Function in Excel VBA could even be used as a cell formula, so naming is very important to avoid clashes with existing/\"native\" functions.</Blockquote></p>\n\n<p>To keep your internal public subs and functions from appearing in the user macro list, define them with an optional parameter, even though it is never used.</p>\n\n<pre><code>Public Sub YourName(Optional Dummy As Variant = Nothing)\n ' Your code goes here.\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-04T13:56:23.180",
"Id": "257499",
"Score": "0",
"body": "Dummy arguments? **NO!** Terrible practice. There is literally an in-built option for this, `Option Private Module`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-20T11:46:32.973",
"Id": "117350",
"ParentId": "46174",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46203",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T10:55:23.330",
"Id": "46174",
"Score": "6",
"Tags": [
"array",
"unit-testing",
"vba"
],
"Title": "Ranking a variant array with variable dimensions"
} | 46174 |
<p>I have the below enum. I need to get the description by code. It is working but can it be improved still? </p>
<pre><code>public enum Maps {
COLOR_RED("ABC", "abc description");
private final String code;
private final String description;
private static Map<String, String> mMap;
private Maps(String code, String description) {
this.code = code;
this.description = description;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
public static String getDescriptionByCode(String code) {
if (mMap == null) {
initializeMapping();
}
if (mMap.containsKey(code)) {
return mMap.get(code);
}
return null;
}
private static void initializeMapping() {
mMap = new HashMap<String, String>();
for (Maps s : Maps.values()) {
mMap.put(s.code, s.description);
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Your code is very neat and clean, there is only one thing that I would change:</p>\n\n<pre><code>private static Map<String, String> mMap;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>private static final Map<String, String> mMap = Collections.unmodifiableMap(initializeMapping());\n</code></pre>\n\n<p>The reasons:</p>\n\n<ol>\n<li><p>By not declaring it final and not using a call to <code>unmodifiableMap</code> it is mutable, and it would be possible to modify the reference using reflection or to use <code>.remove(\"ABC\")</code> on the map. Declaring it as final makes sure that the referenced map cannot change and unmodifiableMap makes sure that no changes can be done to the map itself.</p></li>\n<li><p>Multi-threading issues. As it currently stands, if two threads would call the <code>getDescriptionByCode</code> method at the same time you would initialize the mapping twice, which is not needed.</p></li>\n</ol>\n\n<p>This also of course requires a slight change in your <code>initializeMapping()</code>:</p>\n\n<pre><code>private static Map<String, String> initializeMapping() {\n Map<String, String> mMap = new HashMap<String, String>();\n for (Maps s : Maps.values()) {\n mMap.put(s.code, s.description);\n }\n return mMap;\n}\n</code></pre>\n\n<p>Besides this, it all looks good. Well done!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:33:33.907",
"Id": "80809",
"Score": "0",
"body": "To get around those multi-threading issues, use a static initialization block, which is guaranteed to be run exactly once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T16:38:49.443",
"Id": "80811",
"Score": "0",
"body": "@WChargin AFAIK `private static final Map<String, String> mMap = Collections.unmodifiableMap(initializeMapping());` is also guaranteed to only run once. The initialization is done as a static final variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-18T22:22:00.940",
"Id": "147338",
"Score": "0",
"body": "WTF? mMap is private; nothing can change which object it references or add/remove entries from the map. Yeah you could use reflection, but in almost all cases it's a _terrible_ idea to try to design classes to be resistant to reflection messing with their internals."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-18T23:26:18.717",
"Id": "147340",
"Score": "1",
"body": "@BrianGordon Making it private and unmodifiable protects you from accidentally writing code in the future that modifies it. Additionally, it makes it a lot easier to see when inspecting the code what the intended usage of it is. I am not talking about reflection here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:41:10.607",
"Id": "46178",
"ParentId": "46175",
"Score": "39"
}
},
{
"body": "<p>You could change:</p>\n\n<blockquote>\n<pre><code>if (mMap.containsKey(code)) {\n return mMap.get(code);\n}\nreturn null;\n</code></pre>\n</blockquote>\n\n<p>to:</p>\n\n<pre><code>return mMap.get(code);\n</code></pre>\n\n<p>since <code>HashMap.get()</code> returns <code>null</code> if there is no such key in the map.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:31:11.340",
"Id": "80799",
"Score": "1",
"body": "Actually, you *should*. It is shorter and leverages the api better. You could add a comment (for ppl less familiar with the Map api) telling if the key is not contained, `null` is returned"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2014-04-03T12:06:11.713",
"Id": "46180",
"ParentId": "46175",
"Score": "24"
}
},
{
"body": "<p>This may be just a matter of preference, but it would seem more useful to me to have the map store the instance of <code>Maps</code> rather than the description directly, because then you also get for free the ability to find other information (the enum entry name, its ordinal value, etc). You may not need this, but as it is very simple to do, I would definitely consider it better.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:52:42.670",
"Id": "46190",
"ParentId": "46175",
"Score": "15"
}
},
{
"body": "<p>First of all, the names in your code are not very clear.\nWhat does <code>Maps</code> mean? why <code>COLOR_RED</code>, and why is the associated code <code>ABC</code>?\nDo you have only one value in you enum?</p>\n\n<p>Maybe this is just an example code, but this is rather difficult to analyze.</p>\n\n<p>For example, if your value was named <code>ABC</code>, you could simply call <code>Maps.valueOf(\"ABC\")</code> to have the associated enum and get the corresponding description without needing a internal map.</p>\n\n<p>Of course, if you need both <code>Colors</code> and <code>Codes</code>, you will have to relate them somehow. But <strong>why</strong> even use <em>Strings</em>? Maybe you could have another enumeration called <code>Colors</code> (defining COLOR_RED), so that the relationship between a color and a code is done only using enumerated types. </p>\n\n<p>I haven't written in Java for some time now, but if I remember correctly, <code>EnumMap</code>s (e.g. from <code>Colors</code> to <code>Codes</code> and conversely) are very efficient (like integer indices in an array); moreover, <code>switch</code> case over enums are also more efficient and provide more feedback from the compiler: static analysis can tell you whether you take into account all the possible enums, or not; this simplifies a lot your code because you don't need to bother with error checking.</p>\n\n<p>Of course, Strings are necessary when dealing with data coming from outside of your application. But the can be avoided most of the time when exchanging data internally.</p>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:21:18.047",
"Id": "46192",
"ParentId": "46175",
"Score": "6"
}
},
{
"body": "<p>For this class, lazy initialization brings too little benefit relative to the complication it adds. You only have one member in the enum, and each member of the enum is trivially simple to construct. Therefore, you should populate the map at class-loading time using a static initializer block. (As a bonus, it's guaranteed that the initialization happens only once, so it's thread-safe.)</p>\n\n<pre><code>public enum Maps {\n\n COLOR_RED(\"ABC\", \"abc description\");\n\n private final String code;\n private final String description;\n\n private static final Map<String, String> MAP = new HashMap<String, String>();\n static {\n for (Maps s : Maps.values()) {\n MAP.put(s.code, s.description);\n }\n }\n\n private Maps(String code, String description) {\n this.code = code;\n this.description = description;\n } \n\n public String getCode() { \n return code; \n } \n\n public String getDescription() { \n return description; \n } \n\n public static String getDescriptionByCode(String code) { \n return MAP.get(code);\n }\n}\n</code></pre>\n\n<p>Also, if <code>COLOR_RED</code> doesn't have any useful meaning, and the code strings are also valid Java identifiers, consider using the code itself as the name of each enum member. Enums already have t he ability to look up members by name, so you can take advantage of that mechanism.</p>\n\n<pre><code>public enum SimplerMap { \n\n ABC(\"abc description\");\n\n private final String description; \n\n private SimplerMap(String description) { \n this.description = description; \n } \n\n public String getCode() {\n return this.toString(); \n } \n\n public String getDescription() {\n return this.description; \n } \n\n public static String getDescriptionByCode(String code) {\n try {\n return valueOf(code).getCode();\n } catch (IllegalArgumentException noSuchCode) {\n return null;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T05:36:17.103",
"Id": "46233",
"ParentId": "46175",
"Score": "8"
}
},
{
"body": "<p>Simply having an immutable map initialized within a static block. \nAlso, placing lambdas can achieve higher goal: </p>\n\n<pre><code>private static final Map<String, String> mapCodes = new HashMap<>(); \nstatic {\n final Map<String, String> items = EnumSet.allOf(Maps.class)\n .stream()\n /*.filter(// Can do some filtering excluding values) */\n .collect(Collectors.toMap(Maps::code, Maps::description)); \n\n mapCodes.putAll(items);\n}\n</code></pre>\n\n<p>Depending on the level of re-usability, recommended is accessing to unique values plus Enum instances.</p>\n\n<pre><code>.collect(Collectors.toMap(Maps::code, m-> m));\n</code></pre>\n\n<p>Also, in getter method can reinforce immutability as:</p>\n\n<ul>\n<li>Guava: <code>ImmutableMap.copyOf(mapCodes) //Recommended: Protects original map values of being mutated</code></li>\n</ul>\n\n<p>Or:</p>\n\n<ul>\n<li>Java Collections: <code>Collections.unmodifiableMap(mapCodes)</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T23:07:15.280",
"Id": "241104",
"ParentId": "46175",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:17:33.700",
"Id": "46175",
"Score": "39",
"Tags": [
"java",
"enum",
"hash-map"
],
"Title": "Java enum containing a hash map for look up"
} | 46175 |
<p>I need to use SQL extensively in VBA macros that I write. Since the DB is from our enterprise application, I use vendor's library for this.</p>
<p>I generate dynamic queries, sometimes with many <code>JOIN</code>s and <code>UNION</code>s, and the queries can be quite complex.</p>
<p>The procedure that I coded screams "I'm open to SQL injection". The macros using this function are all internal but I need to make it safe anyway.</p>
<p>How can I make the below code only run <code>SELECT</code> statements and safe against injections?</p>
<p>Please note that it is not possible to make views for all possible <code>SELECT</code> statements and use them instead, according to the parameters, one or more DB's need to be queried and <code>UNION</code>'d sometimes.</p>
<p>How can I safely query an arbitrary number of columns with an arbitrary number of constraints from an arbitrary number of tables in an arbitrary number of DBs?</p>
<pre><code>'***************************************************************************'
'Evaluates and executes the passed query and returns the results '
'Parameters: '
' Query: The main query body with optional placeholders like #0 starting '
' with 0 '
' Args : Optional arguments to replace placeholders '
'Returns: '
' The resulting recordset '
'***************************************************************************'
Public Function DirectQuery( _
Query As String, _
ParamArray Args() As Variant _
) As NetRS
'Declarations **************************************************************'
Dim ReturnRs As NetRS
Dim Params As Variant
'***************************************************************************'
On Error GoTo ErrorHandler
'This code shouldn't be used
MsgBox "This code is dangerous. Don't copy-paste and use it."
Exit Function
Params = Args
Set ReturnRs = 3rdPartyObject.NewRecordset(DBConnection)
ReturnRs.Open EvaluateQuery(Query, Params)
Set DirectQuery = ReturnRs
Set ReturnRs = Nothing
Exit Function
ErrorHandler:
End Function
'***************************************************************************'
</code></pre>
<p></p>
<pre><code>'***************************************************************************'
'Evaluates the arguments in a query string and returns the formed query '
'Parameters: '
' Query: The main query body with optional placeholders like #0 starting '
' with 0 '
' Args : Optional arguments to replace placeholders '
'Returns: '
' The formed query string '
'***************************************************************************'
Public Function EvaluateQuery( _
Query As String, _
ParamArray Args() As Variant _
) As String
'Declarations **************************************************************'
Dim i As Integer
Dim Params As Variant
'***************************************************************************'
On Error GoTo ErrorHandler
Params = Args
EvaluateQuery = Query
For i = LBound(Params(0)) To UBound(Params(0))
EvaluateQuery = Replace(EvaluateQuery, "#" & i, Params(0)(i))
Next i
Exit Function
ErrorHandler:
EvaluateQuery = ""
End Function
'***************************************************************************'
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T18:47:35.310",
"Id": "80856",
"Score": "1",
"body": "You can take a look at [this code](http://codereview.stackexchange.com/questions/46312/simplistic-naive-adodb-wrapper) that lets you easily create parameterized ADODB queries (wrote that today!)."
}
] | [
{
"body": "<h3>Error Handling / Execution Flow: Beware of Raptors</h3>\n<p>I realize you haven't implemented it yet, but you've set yourself up for some twisted execution flow:</p>\n<pre><code> Exit Function 'fixed indentation\nErrorHandler:\n EvaluateQuery = ""\nEnd Function\n</code></pre>\n<p>When you <em>do</em> implement error handling, you'll likely be cleaning up resources (closing recordsets, connections, etc.) - you'll want to do that in case of error, <em>and</em> in normal execution paths too.</p>\n<p>I'd remove <code>Exit Function</code> and rework the <code>ErrorHandler:</code> part:</p>\n<pre><code>ErrorHandler:\n 'todo: cleanup\n If Err.Number <> 0 Then\n 'todo: handle errors\n End If\nEnd Function\n</code></pre>\n<p>This way you'll avoid introducing another label (<code>Cleanup:</code>?) and a <code>GoTo Cleanup</code>, and raptors won't get you.</p>\n<hr />\n<h3>SQL Injection</h3>\n<p>I know only 1 way of preventing SQL injection: <em>let the server handle the parameters</em>. I don't know what 3rd party you're using nor what a <code>NetRs</code> is (why not use ADODB?), but the code in <code>EvaluateQuery</code> seems to be concatenating the parameters into the query.</p>\n<p>This means a <code>String</code> parameter would have to be surrounded by single quotes, and that a string that says <code>"Robert'); DROP TABLE Students;--"</code> would be concatenated - and executed as such. Thus you are correct, this code is screaming SQL injection vulnerability.</p>\n<p>Don't even try "sanitizing" the strings before concatenating them into your query. It's the server's job to deal with the parameters. With ADODB you'd be sending the server a query like:</p>\n<pre><code>"SELECT SomeField FROM SomeTable WHERE SomeOtherField = ?"\n</code></pre>\n<p>Where <code>?</code> is replaced <em>by the server</em>, by its parameter value - no need to worry about single quotes around string parameters, the parameter itself has all the information needed for the server to know how to handle.</p>\n<p>On top of being more secure, such queries are more performant: if you execute them in a loop, the server receives the same query everytime, only with different parameters - it reuses the same query plan every time and only calculates it once. If you send the parameter values embedded in the query, the server receives a different query every time, and has to recalculate a query plan each time.</p>\n<p>See <a href=\"http://support.microsoft.com/kb/181734\" rel=\"noreferrer\">MSDN</a> for more info on parameterized ADODB queries.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T17:17:35.757",
"Id": "46207",
"ParentId": "46177",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T11:36:51.417",
"Id": "46177",
"Score": "5",
"Tags": [
"vba",
"sql-injection"
],
"Title": "Making VBA generated dynamic SQL statements safe against injection"
} | 46177 |
<p>I got the point of PEP8 naming conventions, docstrings going inside methods, catching exceptions and printing them, not doing import *. will correct them. </p>
<p>I need a bit of advice on the robustness and flexibility for the following code. Do you find the variable names descriptive and the flow of code optimal?</p>
<pre><code>import config_files
from filter_tweets import *
from tweets import *
from twitter import *
from MongodbConnections import MongodbConnections
import importlib
import sys
from datetime import datetime
debugger = importlib.import_module('config_files.debugger')
"""
Uses twitter api to stream data from twitter and storing scored tweets and users into the mongodb database
"""
class scan_twittosphere:
"""
Method description: Constructor
input:
String: Keyword
Object: Twitter api object
Object: Config file object
String: User key token
String: User key secret
String: Environment of execution
output: None
"""
def __init__(self, screen_name, keyword, api, config, key, secret, env):
self.screen_name = screen_name
self.keyword = keyword
self.api = api
self.config = config
self.key = key
self.secret = secret
self.MongoObj = MongodbConnections(env)
"""
Method description: Return Twitter API object
input: None
output:
Object: Twitter API
"""
def getTwitterAPIobj(self):
twitter_api_obj = Twitter(
auth=OAuth(self.key, self.secret,
self.config.application_consumer_key, self.config.application_consumer_secret)
)
return twitter_api_obj
"""
Method description: Retrieves tweet objects using Twitter API seach function
input:
String: Language
String: Keyword
String: Search type for User/Tweets
output: None
"""
def searchTwitter(self, lang, keyword, type_search):
#debugger.info("arrive searchTweets",config.debug)
twitter_api_obj = self.getTwitterAPIobj()
since_ID = -1
max_ID = 0
while(since_ID != max_ID):
#debugger.info("arrive stream tweets2",config.debug)
if lang == "ww":
search = twitter_api_obj.search.tweets(q = keyword, count = 100, since_id = max_ID)
else:
search = twitter_api_obj.search.tweets(q = keyword, lang = "en", count = 100, since_id = max_ID)
if len(search['statuses']) == 0:
debugger.info("arrive stream tweets4",self.config.debug)
#print 'end'
break
since_ID = search['search_metadata']['since_id_str']
max_ID = search['search_metadata']['max_id_str']
tweets_obj = Tweets(self.config, self.MongoObj.getBadwordCol())
self.insertAllobj(tweets_obj, search, type_search,keyword)
"""
Method description: Inserts filtered object to the database
input:
Object: Tweets
Object: Tweets class object
String: Search type for User/Tweets
String: Keyword
output: None
"""
def insertAllobj(self, tweets_obj, search, type_search,keyword):
for tweet in search['statuses']:
if type_search == 'tweet':
debugger.info("score tweets",self.config.debug)
result = tweets_obj.score_tweet(tweet,keyword)
if result[0] == True:
self.insertTweet(tweet,result,keyword)
elif type_search == 'user':
result = tweets_obj.score_user(tweet)
if result[0] == True:
self.insertUser(tweet,result,keyword)
"""
Method description: This method executes Twitter API search for different languages
input:
String: Keyword
String: Search type for User/Tweets
output: None
"""
def stream_tweets(self, keyword, type_search):
debugger.info("arrive stream tweets",self.config.debug)
self.searchTwitter("ww",keyword,type_search)
self.searchTwitter("en",keyword,type_search)
"""
Method description: Checks if the user exists in the database
input:
Integer: user id
String: Keyword
output: Integer(0/1)
"""
def userExists(self,user_id):
return self.MongoObj.getUsersIndex().find({'user_id': user_id}).count(True)
"""
Method description: Checks if the tweet exists in the database
input:
Integer: tweet id
Integer: user id
output: Integer(0 or more)
"""
def tweetExists(self, tweet_id, user_id):
return self.MongoObj.getTweetsIndex().find({'tweet_id': tweet_id}).count(True) + self.MongoObj.getTweetsIndex().find({'user_id': user_id}).count(True)
"""
Method description: Inserts User in database
input:
Object: tweet object
Mixed List (Boolean and Integer): result[True/False, Score]
output: None
"""
def insertUser(self,tweet, result,keyword):
user_exist = self.userExists(tweet['user']['id'])
if user_exist == 0:
self.MongoObj.getUsersIndex().insert({'user_id' : tweet['user']['id'], 'time':datetime.now()})
self.MongoObj.getUserFactoryCol().insert({'tweet': tweet['text'], 'tweet_id': tweet['id'], 'keyword': keyword, 'screen_name': tweet['user']['screen_name'], 'user_id': tweet['user']['id'], 'twittalikescore':result[1], 'time':datetime.now(), 'user_list':[]})
"""
Method description: Inserts Tweet in database
input:
Object: tweet object
Mixed List (Boolean and Float): result[True/False, Score]
output: None
"""
def insertTweet(self,tweet,result,keyword):
tweet_exist = self.tweetExists(tweet['id'], tweet['user']['id'])
if tweet_exist == 0:
'''
add in master base
'''
self.MongoObj.getTweetsIndex().insert({'tweet_id': tweet['id'], 'user_id' : tweet['user']['id'], 'time':datetime.now()})
self.MongoObj.getTweetFactoryCol().insert({'tweet': tweet['text'], 'tweet_id': tweet['id'], 'keyword': keyword, 'screen_name': tweet['user']['screen_name'], 'user_id': tweet['user']['id'], 'prediction': result[1],'twittalikescore':result[1],'time':datetime.now(), 'user_list':[]})
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Please wrap your code at column 80. Otherwise, we have to do a lot of sideways scrolling to read it. Besides, 79 byte lines is <a href=\"http://legacy.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow\">what PEP8 recommends</a>.</p></li>\n<li><p>Your variable and method names are quite descriptive.</p></li>\n<li><p>Your method descriptions should go <em>inside</em> the method. For example, rather than this,</p>\n\n<pre><code>\"\"\"\nMethod description: Return Twitter API object\ninput: None\noutput: \n Object: Twitter API\n\"\"\"\ndef getTwitterAPIobj(self):\n twitter_api_obj = Twitter(\n auth=OAuth(self.key, \n self.secret,\n self.config.application_consumer_key,\n self.config.application_consumer_secret)\n )\n return twitter_api_obj\n</code></pre>\n\n<p>do this:</p>\n\n<pre><code>def getTwitterAPIobj(self):\n \"\"\"\n Method description: Return Twitter API object\n input: None\n output: \n Object: Twitter API\n \"\"\"\n twitter_api_obj = Twitter(\n auth=OAuth(self.key, \n self.secret,\n self.config.application_consumer_key, \n self.config.application_consumer_secret)\n )\n return twitter_api_obj\n</code></pre>\n\n<p>Otherwise, pydoc will not put your descriptions in the right place. For example, when I run pydoc on your current file, the first method description shows up as the description of the entire class.</p></li>\n<li><p>Your comments answer the question, \"What does this method/program/set of lines do?\" Often, the answer to that is obvious from the code, especially with method and variable names as descriptive as yours. I think comments are more useful when they answer <em>why</em> sorts of questions. </p>\n\n<p>For example, your first comment at the top of the file says, \"Uses twitter api to stream data from twitter and storing scored tweets and users into the mongodb database.\" Okay, but does it pull in every single tweet ever? If not, what's the basis for selecting tweets to be stored? How are tweets scored? What's the relationship between tweets and users? Are the users the authors of the tweets or followers of the authors or what? Once we've stored all this information in Mongo, what are we going to do with it? What's the bigger picture that this piece of code fits into?</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-18T03:58:33.147",
"Id": "47536",
"ParentId": "46182",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:17:14.173",
"Id": "46182",
"Score": "3",
"Tags": [
"python"
],
"Title": "Robustness and maintanability based on descriptiveness of variables and docstrings"
} | 46182 |
<p>So the two functions below both send emails via PHPMailer but both hold different messages (which use different data from the db). I was just wondering (as I plan to use PHPMailer more) a way to consolidate these functions into perhaps a <code>sendMail()</code> function which could handle different data variables and messages, whilst also allowing me to only set the <code>$mail</code> parameters once. </p>
<pre><code> public function sendConfirmationEmail($firstName, $email, $emailCode) {
global $mail;
$to = $email;
try {
$mail->IsSMTP();
$mail->Username = "hello@connectd.io";
$mail->Password = "••••••••";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->addAddress($to);
$mail->From = 'hello@connectd.io';
$mail->FromName = 'Connectd.io';
$mail->AddReplyTo( 'hello@connectd.io', 'Contact Connectd.io' );
$mail->isHTML(true);
$mail->Subject = 'Activate your new Connectd account';
$mail->Body = "<p>Hey " . $firstName . "!</p>";
$mail->Body .= "<p>Thank you for registering with Connectd. Please visit the link below so we can activate your account:</p>";
$mail->Body .= "<p>" . BASE_URL . "login.php?email=" . $email . "&email_code=" . $emailCode . "</p>";
$mail->Body .= "<p>-- Connectd team</p>";
$mail->Body .= "<p><a href='http://connectd.io'>www.connectd.io</a></p>";
$mail->Body .= "<img width='180' src='" . BASE_URL . "assets/img/logo-email.jpg' alt='Connectd.io logo'><br>";
$mail->Send();
}catch(phpmailerException $e) {
$general = new General($db);
$general->errorView($general, $e);
}catch(Exception $e) {
$general = new General($db);
$general->errorView($general, $e);
}
}
public function sendVoteEmail($firstName, $email, $votes) {
global $mail;
$to = $email;
try {
$mail->IsSMTP();
$mail->Username = "hello@connectd.io";
$mail->Password = "••••••••";
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "smtp.gmail.com";
$mail->Port = 587;
$mail->addAddress($to);
$mail->From = 'hello@connectd.io';
$mail->FromName = 'Connectd.io';
$mail->AddReplyTo('hello@connectd.io', 'Contact Connectd.io');
$mail->isHTML(true);
$mail->Subject = 'You just got a vote on Connectd Trials!';
$mail->Body = "<p>Hey " . $firstName . "!</p>";
$mail->Body .= "<p>Congratulations - Someone has voted for you on Connectd Trials. </p>";
$mail->Body .= "<p>You now have <strong>" . $votes['CountOfvote_id'] . "/10</strong> votes</p>";
$mail->Body .= "<p>-- Connectd team</p>";
$mail->Body .= "<p><a href='http://connectd.io'>www.connectd.io</a></p>";
$mail->Body .= "<img width='180' src='" . BASE_URL . "assets/img/logo-email.jpg' alt='Connectd.io logo'><br>";
$mail->Send();
}catch(phpmailerException $e) {
$general = new General($db);
$general->errorView($general, $e);
}catch(Exception $e) {
$general = new General($db);
$general->errorView($general, $e);
}
}
</code></pre>
| [] | [
{
"body": "<p>You should pass the body of the mail as an argument and it will do what you need. The body part should have been on the outside and independent of the mailing function. This way if you decide to expand this - you wont need to copy paste a third version</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:59:57.013",
"Id": "80585",
"Score": "0",
"body": "But then what happens when I need to grab custom data in the body of an email?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:24:12.300",
"Id": "80607",
"Score": "0",
"body": "you do it from the outside. you build the entire body FROM the outside..its about the equivalent of calculating an area of a shape. the formula is inside the function, the length, width, height are coming from the outside."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:16:43.840",
"Id": "80708",
"Score": "0",
"body": "So say the body is just an included PHP file, and the function is just `sendMail()` - surely I will get an unexpected variable error if I pass say `sendMail($firstName, $votes)`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:38:08.333",
"Id": "80729",
"Score": "0",
"body": "there are no unexpected variable if firstName and votes are blank. The send will simply fail and you need to add validation. In PHP you need your important variables to have checks on it. Furthermore good programming tells you that also. What YOU want to do is require_once a template that has variables inside because the HTML is formatted. The proper way is to have a function that takes an input, array, DB result or something and returns a variable which is your $body and within that function you validate all your variables. If something is missing and is of value you will need to catch it"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:07:17.717",
"Id": "46185",
"ParentId": "46183",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T12:40:12.060",
"Id": "46183",
"Score": "1",
"Tags": [
"php",
"optimization",
"php5",
"email"
],
"Title": "Optimising and consolidating multiple PHPMailer functions"
} | 46183 |
<h1>Problem Statement</h1>
<blockquote>
<p><strong>Input</strong></p>
<p>The input begins with the number t of test cases in a single line
(t<=10). In each of the next t lines there are two numbers m and n (1
<= m <= n <= 1000000000, n-m<=100000) separated by a space.</p>
<p><strong>Output</strong></p>
<p>For every test case print all prime numbers p such that m <= p <= n,
one number per line, test cases separated by an empty line.</p>
<p><strong>Example</strong></p>
<p>Input:</p>
<pre><code>2
1 10
3 5
</code></pre>
<p>Output:</p>
<pre><code>2
3
5
7
3
5
</code></pre>
</blockquote>
<p><strong>My Problem</strong></p>
<p>I have tried very hard to optimize the code to my best, but still the online judge shows that I am exceeding the time limit. Is it possible to optimize the following code further or I should look for an alternative approach?</p>
<pre><code>import sys
final=[]
for i in xrange(int(sys.stdin.readline())):
start,end=[int(x) for x in sys.stdin.readline().split()]
if start==1:
start=2
# sieve of eras** algorithm
final.append(list(sorted(set(xrange(start,end+1)).difference(set((p * f) for p in xrange(2, int(end ** 0.5) + 2) for f in xrange(2, int(end/p) + 1))))))
# print final list items
for item1 in final:
print("\n".join([str(x) for x in item1]))
print('\n')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:13:48.953",
"Id": "80599",
"Score": "0",
"body": "The accepted answer to [your previous question](http://codereview.stackexchange.com/q/45857/10916) proposes a more efficient implementation of the sieve. Have you not tried it here?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-11T01:25:36.047",
"Id": "107645",
"Score": "0",
"body": "I've solved a very similar problem using a double-sieve approach."
}
] | [
{
"body": "<p><strong>Re-organising the code</strong></p>\n\n<p>A quite easy thing to start with is to split the logic into a part collecting the input and a part performing computation from this input. This makes things clearer but also this might make testing easier and make some optimisations possible later on.</p>\n\n<p>You can also take this chance to remove whatever is not needed :</p>\n\n<ul>\n<li><code>i</code> is not needed, the usage is to use <code>_</code> for throw-away values in Python.</li>\n<li><code>final</code> is not needed : you populate it one element at a time and then you iterate on it to display the elements.</li>\n<li>You don't need to recreate a new string to call <code>join</code>, you can use generator expressions.</li>\n</ul>\n\n<p>Here's what I have at this stage :</p>\n\n<pre><code>#!/usr/bin/python\n\nimport sys\n\nif False :\n # Test from standard input\n inputs = []\n for _ in xrange(int(sys.stdin.readline())):\n start,end=[int(x) for x in sys.stdin.readline().split()]\n if start==1:\n start=2\n inputs.append((start,end))\nelse:\n # Hardcoded test\n inputs = [(2,10),(5,7)]\n\nfor start,end in inputs:\n # sieve of eras** algorithm\n primes = (list(sorted(set(xrange(start,end+1)).difference(set((p * f) for p in xrange(2, int(end ** 0.5) + 2) for f in xrange(2, int(end/p) + 1))))))\n print(\"\\n\".join(str(p) for p in primes)+\"\\n\")\n</code></pre>\n\n<p>Now, I can use <code>inputs = [(2,10),(5,7),(9999985,10000000),(9999937,9999987)]</code> for performance testing.</p>\n\n<p><strong>Computing things once</strong></p>\n\n<p>At the moment, you re-compute your sieve multiple times. You might as well juste do it once with the biggest max you can find.</p>\n\n<pre><code>def sieve_of_era(n):\n primes = [True]*(n+1)\n primes[0] = primes[1] = False\n for i in range(2, int(n**0.5)+1):\n if primes[i]:\n for j in range(i*i, n+1, i):\n primes[j] = False\n return primes\n\nsieve = sieve_of_era(max(end for _,end in inputs))\n</code></pre>\n\n<p>Then, it's only a matter of collecting the information and printing it :</p>\n\n<pre><code>print \"\\n\\n\".join(\"\\n\".join(str(p) for p in xrange(start,end+1) if sieve[p]) for start,end in inputs)\n</code></pre>\n\n<p><strong>A last remark</strong></p>\n\n<p>Your \"sieve\" considers 1 as a prime number and for that number, you added a hack to change 1 into 2 in the inputs. This is not required anymore and once it's removed, everything can be included in a single list comprehension.</p>\n\n<p>The code becomes :</p>\n\n<pre><code>#!/usr/bin/python\n\nimport sys\n\ninputs = [[int(x) for x in sys.stdin.readline().split()] for _ in xrange(int(sys.stdin.readline()))] if False else [(2,10),(5,7),(9999985,10000000),(9999937,9999987)]\n\ndef sieve_of_era(n):\n primes = [True]*(n+1)\n primes[0] = primes[1] = False\n for i in range(2, int(n**0.5)+1):\n if primes[i]:\n for j in range(i*i, n+1, i):\n primes[j] = False\n return primes\n\nsieve = sieve_of_era(max(end for _,end in inputs))\n\nprint \"\\n\\n\".join(\"\\n\".join(str(p) for p in xrange(start,end+1) if sieve[p]) for start,end in inputs)\n</code></pre>\n\n<p>I haven't tried edge cases for the <code>sieve</code> function but it looks ok.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:58:31.410",
"Id": "80595",
"Score": "0",
"body": "Thank you So much You solved a whole lot of my problems..:)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T16:51:47.500",
"Id": "80625",
"Score": "0",
"body": "The program is producing memory error for values : 999900000 1000000000"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T11:50:09.777",
"Id": "81487",
"Score": "0",
"body": "@Andres if you have code that doesn't work you could try stackoverflow.com. For very large numbers you could consider keeping a set of primes found so far, rather than a list of ALL numbers. The set of primes will be much smaller."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T14:37:01.597",
"Id": "46193",
"ParentId": "46187",
"Score": "7"
}
},
{
"body": "<h1>Readability</h1>\n<p>First, long lines make your code hard to read. The easier the code is to read, the easier it is for you to see what it does and spot potential improvements. It's also easier for others to suggest improvements to your code if it's easy for them to read it.</p>\n<p>It is true that sometimes a one line expression can run faster than a loop over several lines, but even a one liner can be displayed over several lines by using brackets or parentheses for <a href=\"https://docs.python.org/release/2.5.2/ref/implicit-joining.html\" rel=\"nofollow noreferrer\" title=\"continuation using brackets, parentheses or braces\">implicit line continuation</a>. This still counts as a one liner from the bytecode compiler's point of view and will run just as fast.\nI won't point out minor spacing issues as you use spacing very readably in some parts, so I'm guessing the other parts are not lack of knowledge. There's <a href=\"http://legacy.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\" title=\"style guide\">PEP 8</a> if you want finer guidance on presentation, but I'm reviewing for time performance here.</p>\n<h1>Comments</h1>\n<p>I heard Eratosthenes died, no need to worry about copyright - you can use his full name in the comments. More seriously, comments are discarded before the code is compiled to bytecode and run, so you don't need to worry about shortening them. Longer comments make the file slightly larger, but they do not affect the running time at all. Full words and clear sentences are good.</p>\n<h1>Tweaks</h1>\n<p>Small improvements to speed can be made by being aware of how Python works. For example, defining <code>r = xrange(2, int(end ** 2) + 2)</code> before your loop and using <code>r</code> inside your loop will save Python having to define the range each time through the loop (including calculating <code>end ** 2</code> each time through the loop). Such fine tuning won't make much difference if you have an inefficient algorithm though.</p>\n<h1>Algorithm</h1>\n<p>The biggest improvements in speed are very often from changing the algorithm - using a different approach rather than just tweaking the performance of the current approach\nThere are parts of your long line (sieve of Eratosthenes algorithm) that appear to be making unnecessary extra work:</p>\n<pre><code>for p in xrange(2, int(end ** 0.5) + 2)\n</code></pre>\n<p>This gives you the range up to <strong>and including</strong> <code>int(end ** 0.5) + 1)</code>, which is always more than the square root, even when considering a square number. Since you only need to check numbers which are less than or equal to the square root, I would change the <code>+ 2</code> to say <code>+ 1</code>.</p>\n<p>The major inefficiency with your algorithm is that you are checking all numbers up to the square root, rather than all prime numbers up to the square root. To see why this is unnecessary, consider that when you remove all multiples of 4, they have already been removed when you removed all multiples of 2. Then the same when you remove all multiples of 6, all multiples of 8, and so on. The same thing happens again with multiples of 6, 9, 12 because you have already removed all multiples of 3. With large numbers this will cause a huge amount of repetition - creating and taking differences of sets which already have no elements in common, and repeating this unnecessary step huge numbers of times.</p>\n<p>For this reason it is well worth your time to think about how you could only remove multiples of prime numbers. The extra time your program takes keeping a list of prime numbers already found will save you so much time over the course of the run that you will see a very significant speed up for large numbers.</p>\n<p><a href=\"https://codereview.stackexchange.com/a/46193/37331\" title=\"Josay's answer to this question\">Josay's</a> answer already shows such an improvement in the example code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:05:30.873",
"Id": "46195",
"ParentId": "46187",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T13:29:10.957",
"Id": "46187",
"Score": "5",
"Tags": [
"python",
"programming-challenge",
"primes",
"time-limit-exceeded"
],
"Title": "Prime generator program SPOJ time limit exceed"
} | 46187 |
<p>I have some concerns on my refactoring for the data layer in my current Project. Just for a small info, I am currently building a CRM as "training JEE application". But enough of talk, let's talk code!</p>
<p><strong>IService.java:</strong> (7 lines, 160 bytes)</p>
<pre><code>public interface IService<T> {
public void update(T update);
public void delete(long id);
public T getById(long id);
}
</code></pre>
<p><strong>IListService.java:</strong> (8 lines, 169 bytes)</p>
<pre><code>public interface IListService<T> extends IService<T> {
public void add(T add);
public List<T> getAll();
}
</code></pre>
<p><strong>IDependentListService.java:</strong> (8 lines, 225 bytes)</p>
<pre><code>public interface IDependentListService<T> extends IService<T> {
void add(T entity, long masterRecordId);
List<T> getAllByMasterRecordId(long masterRecordId);
}
</code></pre>
<p><strong>IAddressService.java:</strong> (7 lines, 199 bytes)</p>
<pre><code>public interface IAddressService extends IDependentListService<Address>{
public void promoteToMainAddress(long addressId);
}
</code></pre>
<p><strong>IContactPersonService.java:</strong> (7 lines, 167 bytes)</p>
<pre><code>public interface IContactPersonService extends IDependentListService<ContactPerson>{
}
</code></pre>
<p><strong>IContractService.java:</strong> (9 lines, 234 bytes)</p>
<pre><code>public interface IContractService extends IDependentListService<Contract> {
public List<Contract> getAllContractsByLoggedInUser();
}
</code></pre>
<p><strong>ICustomerService.java:</strong> (9 lines, 220 bytes)</p>
<pre><code>public interface ICustomerService extends IListService<Customer> {
}
</code></pre>
<p><strong>IProductService.java:</strong> (10 lines, 262 bytes)</p>
<pre><code>public interface IProductService extends IListService<Product> {
public List<Product> getAllCurrentProducts();
public List<Product> getAllArchivedProducts();
}
</code></pre>
<p><strong>IProjectService.java:</strong> (9 lines, 228 bytes)</p>
<pre><code>public interface IProjectService extends IDependentListService<Project>{
public List<Project> getAllProjectsByLoggedInUser();
}
</code></pre>
<p><strong>IUserService.java:</strong> (7 lines, 129 bytes)</p>
<pre><code>public interface IUserService extends IListService<User>{
}
</code></pre>
<h2>Update (Code):</h2>
<p>The code for the IUserService changed a bit, after reviewing the implementation of the CustomerService:</p>
<p><strong>IUserService.java:</strong></p>
<pre><code>public interface IUserService extends IListService<User>{
User getLoggedInUser();
}
</code></pre>
<h1>Questions</h1>
<ul>
<li>Does this code follow good practices, especially concerning inheritance?</li>
<li>Naming. Should I really prepend I before the Interfaces? (Implementations are named without <code>I</code>). Are the names clear enough?</li>
<li>Everything else you see as problematic ;)</li>
</ul>
<h2>Update (Questions):</h2>
<p>I am currently in the process of writing Javadoc for this code after refactoring it. Currently I use the interfaces as a Platform to place the Javadoc. In the implementation I would then just <code>@see</code> to the Interface Javadoc. Is it okay to do this, should I instead write out the Javadoc for the Implementations too and just <code>@see</code> to other implementations and the interfaces?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:09:28.173",
"Id": "80596",
"Score": "6",
"body": "+1 simply for using my [question generator tool](http://codereview.stackexchange.com/questions/41225/follow-up-to-tool-for-posting-code-review-questions) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-19T00:34:07.043",
"Id": "109411",
"Score": "0",
"body": "This question is [currently referenced on Meta](http://meta.codereview.stackexchange.com/questions/2308/questions-about-interfaces-protocols-and-apis)"
}
] | [
{
"body": "<p>This answer will reflect the naming convention at my work. </p>\n\n<p><strong>Naming Convention</strong></p>\n\n<p>Prefixing <code>I</code> to all your interface seems superfluous, since we use a simple name like <code>ContractService</code>. The implementation class would have <code>Impl</code> suffixed to the name of the service like : <code>ContractServiceImpl</code>. Normally you will use DI to inject the implementation where you need it, so you will only see the interface name.</p>\n\n<p>Prefixing <code>I</code> seems odd to me if I'm looking at the Java collections API where you have : <code>List</code>, <code>Map</code>, etc. </p>\n\n<p>If you only use <code>ContractService</code> as the name of the implementation, it could not be clear at first read that you are using an implementation directly and not the interface. Using <code>Impl</code> as a suffix make it clear that it's the implementation, so if you see it in your code, it can show that something smelly is going on.</p>\n\n<p><strong>Naming of methods</strong></p>\n\n<blockquote>\n<pre><code>public interface IProductService extends IListService<Product> {\n public List<Product> getAllCurrentProducts();\n public List<Product> getAllArchivedProducts();\n}\n</code></pre>\n</blockquote>\n\n<p>Those methods are very good! If you can keep clear names like those, using your services will be easy. I like the way you named all you method!</p>\n\n<p><strong>Delete</strong></p>\n\n<blockquote>\n<pre><code>public void delete(long id);\n</code></pre>\n</blockquote>\n\n<p>You could return the object that has been deleted. It could be useful if you want to show the information of the item that has been deleted. The client could decide if he wants to use the object or not.</p>\n\n<p>Edit: In fact, you should not return an object since you're just working with <code>long id</code> and not the object directly. If the signature was <code>public void delete(T delete)</code> this would have been a good advice, but with the current signature, you would have a to retrieve the object, delete it and then return the deleted object.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:23:34.013",
"Id": "46197",
"ParentId": "46194",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "46197",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:04:45.703",
"Id": "46194",
"Score": "12",
"Tags": [
"java",
"inheritance",
"interface"
],
"Title": "DataLayer Interfaces Genericized"
} | 46194 |
<p>I am implementing merge sort in Java and I have a performance problem in this method:</p>
<pre><code> private static void marge(int[] source, int[] buffer, int startingIndex, int count) {
int index1 = startingIndex;
int index2 = startingIndex + count / 2;
int maxIndex1 = index2;
int maxIndex2 = startingIndex + count;
for(int i = 0; i < count; i++){
if(index2 >= maxIndex2 || (index1 < maxIndex1 && source[index1] < source[index2])){
buffer[startingIndex + i] = source[index1];
index1++;
}
else{
buffer[startingIndex + i] = source[index2];
index2++;
}
}
// System.arraycopy(source, startingIndex, buffer, startingIndex, count);
}
</code></pre>
<p>If I replace this method content with the content of the comment, like this:</p>
<pre><code>private static void marge(int[] source, int[] buffer, int startingIndex, int count) {
System.arraycopy(source, startingIndex, buffer, startingIndex, count);
}
</code></pre>
<p>It performs <strong>10 to 20 times faster</strong>. I understand that I have more calculations in my original method but "10 to 20 times" seems too much for me. </p>
<p>Do you have any idea how to improve performance?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:31:00.227",
"Id": "80609",
"Score": "5",
"body": "`System.arraycopy` calls native code, so it will always be *much* faster: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/System.java#System.arraycopy%28java.lang.Object%2Cint%2Cjava.lang.Object%2Cint%2Cint%29"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:44:36.717",
"Id": "80611",
"Score": "0",
"body": "@konjin out of pure interest.. if you implemented the same algorithm like the native code one, how much faster would it be when written in native code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:46:16.873",
"Id": "80612",
"Score": "2",
"body": "Who is marge? Please update the function name to something meaningful -- did you mean \"merge\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T18:19:07.383",
"Id": "80633",
"Score": "0",
"body": "@Vogel612 - This is almost impossible to do since native code (machine language) allows you to copy data with a single instruction cf http://en.wikipedia.org/wiki/MOV_%28x86_instruction%29"
}
] | [
{
"body": "<p>Some pointers:</p>\n\n<ul>\n<li><p>You keep adding 2 numbers here: <code>startingIndex + i</code>, that could probably be avoided if you went <code>for(int i = startIndex; i < lastIndex; i++){</code> where <code>lastIndex</code> would be <code>startIndex + count</code></p></li>\n<li><p>Since <code>++</code> happens post evaluation you could simply do <code>buffer[startingIndex + i] = source[index1++];</code>, it does not have to be a separate statement</p></li>\n<li><p>Short circuit logic : if <code>index2 >= maxIndex2</code>, then you should probably have a <code>System.arraycopy</code> copy that fills the rest into <code>index1</code> and get out. You could the same for when <code>index1 > maxIndex1</code> but obviously you would fill into <code>index2</code> then</p></li>\n</ul>\n\n<p>From a naming perspective, I would rather read <code>upperIndex</code> and <code>lowerIndex</code> than <code>index1</code> and <code>index2</code></p>\n\n<p>Totally untested, I would try something like this:</p>\n\n<pre><code>private static void merge(int[] source, int[] buffer, int startingIndex, int count) {\n int lowerIndex = startingIndex;\n int lowerBound = startingIndex + count / 2;\n int upperIndex = lowerBound;\n int upperBound = startingIndex + count;\n\n for(int i = startingIndex ; i < upperBound ; i++){\n if(upperIndex >= upperBound ){\n System.arraycopy(source, lowerIndex , buffer, i, i - startingIndex );\n return;\n }\n if(lowerIndex >= lowerBound ){\n System.arraycopy(source, upperIndex , buffer, i, i - startingIndex );\n return;\n }\n buffer[i] = source[lowerIndex] < source[upperIndex] ? source[lowerIndex++] : source[upperIndex++]\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:34:35.900",
"Id": "46200",
"ParentId": "46198",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "46200",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:24:36.340",
"Id": "46198",
"Score": "6",
"Tags": [
"java",
"performance",
"sorting",
"mergesort"
],
"Title": "Merge sort could work 10 times faster"
} | 46198 |
<p>Let's say that I have a method that makes an HTTP request that will take a long time to finish. While that's happening the UI is not updating because I'm doing it in the UI's thread. </p>
<p>One solution is to:</p>
<ol>
<li>Show the "Loading" animation.</li>
<li>Start the HTTP request on a thread.</li>
<li>On the completion callback stop the "Loading" animation and work on the response.</li>
</ol>
<p>That's all nice and good, but it means that I went from code that was sequential in nature to something that has callbacks or something similar (promises).</p>
<p>So, I'm trying to keep the sequential nature while updating the UI. Having something like await/async would help here, but even in that case the caller has to be aware of this (plus I need .NET 4.5, let's assume that this is not an option). So I came up with something that keep the sequential nature of the original call, doesn't affect the caller of the function makes the HTTP request but updates the UI.</p>
<p>So, here it is:</p>
<pre class="lang-cs prettyprint-override"><code>public class Async<T>
{
public static T Run(Func<T> action)
{
var worker = new BackgroundWorker();
var error = new Exception[] {null};
var result = new[] {default(T)};
// The original call will run in a separate thread.
worker.DoWork += (sender, ea) => { result[0] = action(); };
worker.RunWorkerCompleted += (sender, ea) => { error[0] = ea.Error; };
worker.RunWorkerAsync();
// While the work is being done in a separate thread, update the UI's event loop (is this safe???)
while (worker.IsBusy)
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate { }));
Thread.Sleep(20);
}
// Re raise the exception if needed
if (error[0] != null)
throw error[0];
return result[0];
}
}
//Usage
var someVariable = 123;
var responseA = Async<T>.Run(DoSuperLongTask);
var responseB = Async<T>.Run(() =>
{
return DoSuperComplicatedTask(someVariable);
});
</code></pre>
<p>It'll be something like
</p>
<pre><code>await Task.Run(() => DoWork());
await Task.Run(() => DoWork());
</code></pre>
<p>I'm not an expert in GUIs, and I'm especially not an expert in WPF. So my question to you is: </p>
<p><strong>Is this safe to use?</strong> </p>
<p>So far it seems to work okay.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T18:56:44.330",
"Id": "80640",
"Score": "0",
"body": "“plus I need .NET 4.5” You don't, you can use `async`-`await` on .Net 4.0 using [Microsoft.Bcl.Async](http://nuget.org/packages/Microsoft.Bcl.Async). But you do need at least VS 2012."
}
] | [
{
"body": "<p>Good you have a <code>BackgroundWorker</code>. If I understood correctly, let's say you want to update a button, whether to enable it or not. you can use this:</p>\n\n<pre><code>delegate void EnableButton(Button b, bool enable);\npublic void ActuallyEnableButton(Button b, bool enable)\n{\n if (b.InvokeRequired)\n {\n EnableButton del = ActuallyEnableButton;\n b.Invoke(del, new object[] { b, enable });\n //in some cases add \"return\" statement\n }\n b.Enabled = enable;\n}\n</code></pre>\n\n<p>Call <code>ActuallyEnableButton(btn, true)</code> for example, inside <code>DoWork</code> event of <code>BackgroundWorker</code>.</p>\n\n<p>This applies to <code>Label</code>, <code>TextBox</code>, <code>ComboBox</code>, <code>ListView</code>, <code>ProgressBar</code>, etc. No need to use this code if you want to update <code>ToolStripStatusLabel</code> and <code>ToolStripProgressBar</code>.</p>\n\n<p>Hope this helped.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-13T16:31:05.893",
"Id": "298443",
"Score": "0",
"body": "***Why NOT need to use this code*** if I want to update `ToolStripStatusLabel` and `ToolStripProgressBar` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-20T02:54:37.863",
"Id": "299465",
"Score": "0",
"body": "Yup @Kiquenet. You can update those controls directly without a delegate function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T04:50:41.077",
"Id": "46609",
"ParentId": "46199",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T15:25:53.873",
"Id": "46199",
"Score": "3",
"Tags": [
"c#",
"wpf"
],
"Title": "Keep the sequential nature while updating the UI of the progress of the HTTP request"
} | 46199 |
<p>This tag is obsolete. Don't use it. See <a href="http://meta.codereview.stackexchange.com/q/1694/9357">Tag soup: [dijkstra]</a></p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T17:06:35.637",
"Id": "46205",
"Score": "0",
"Tags": null,
"Title": null
} | 46205 |
This tag is obsolete. Don't use it. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T17:06:35.637",
"Id": "46206",
"Score": "0",
"Tags": null,
"Title": null
} | 46206 |
<p>I usually take my school code as a playground to mess around with things. I was given a bunch of premade hash functions and had to test their output and find when they reach a specific lower range. Since the functions all have the same structure, I made a check function that uses a function pointer parameter(I think this is the most efficient way to deal with this problem?). Which I'm iterating through the potential keys to feed to all of the functions it I wanted it to stop at the first one of each, but couldn't think of a way to do so without using 11 individual flags or for loops. I've never messed with bitmasks (I specifically only remember the gist of them because there was a couple commands in quake3 that used them!), but I did that instead and it turned out to not be as pretty/elegant as I thought it would in practice.</p>
<p>in short:</p>
<p>How would you approach the assignment "Using the given 11 hash functions, find each of their first 'low' output?"</p>
<pre><code>void findLowHash();
bool foundLow(unsigned int (*hash)(const std::string &key), std::string key);
void findLowHash() {
string key;
key.push_back(0);
int mask = 2047;
for (int i = 0; i < 100000; ++i) {
incrStr(key);
carryStr(key);
if (mask == 0)
break;
if (mask >> 0 & 1) {
if (foundLow(RSHash, key)) {
mask -= 1;
cout << "RSHash"
<< " " << mask << endl;
}
}
if (mask >> 1 & 1) {
//cout<<JSHash(key)<<" "<<key<<endl;
if (foundLow(JSHash, key)) {
mask -= 2;
cout << "JSHash"
<< " " << mask << endl;
}
}
if (mask >> 2 & 1) {
if (foundLow(PJWHash, key)) {
mask -= 4;
cout << "PJWHash"
<< " " << mask << endl;
}
}
if (mask >> 3 & 1) {
if (foundLow(ELFHash, key)) {
mask -= 8;
cout << "ELFHash"
<< " " << mask << endl;
}
}
if (mask >> 4 & 1) {
if (foundLow(BKDRHash, key)) {
mask -= 16;
cout << "BKDRHash"
<< " " << mask << endl;
}
}
if (mask >> 5 & 1) {
if (foundLow(SDBMHash, key)) {
mask -= 32;
cout << "SDBMHash"
<< " " << mask << endl;
}
}
if (mask >> 6 & 1) {
if (foundLow(DJBHash, key)) {
mask -= 64;
cout << "DJBHash"
<< " " << mask << endl;
}
}
if (mask >> 7 & 1) {
if (foundLow(DEKHash, key)) {
mask -= 128;
cout << "DEKHash"
<< " " << mask << endl;
}
}
if (mask >> 8 & 1) {
if (foundLow(FNVHash, key)) {
mask -= 256;
cout << "FNVHash"
<< " " << mask << endl;
}
}
if (mask >> 9 & 1) {
if (foundLow(BPHash, key)) {
mask -= 512;
cout << "BPHash"
<< " " << mask << endl;
}
}
if (mask >> 10 & 1) {
if (foundLow(APHash, key)) {
mask -= 1024;
cout << "APHash"
<< " " << mask << endl;
}
}
}
}
bool foundLow(unsigned int (*hash)(const std::string &key), std::string key) {
if ((*hash)(key) < 10000) {
std::cout << "key: " << key << " Output:" << ((*hash)(key)) << " ";
return true;
}
return false;
}
</code></pre>
| [] | [
{
"body": "<p>Your code does seem open to some improvement. Right now, you're not really getting much good out of using a pointer to a function. You could just about as well invoke each hash function directly in <code>findLowHash</code> as call it via a pointer in <code>foundLow</code>.</p>\n\n<p>In this case, we have a number of functions that all have the same signature, so we can create an array of the pointers to functions. Of course, <code>array</code> should also set off alarm bells--you should almost always prefer <code>std::array</code> or <code>std::vector</code>. In this case, I'll use <code>st::vector</code>, but if you're using a compiler new enough to include it, <code>std::array</code> would be an excellent choice as well.</p>\n\n<pre><code>typedef unsigned int (*hash)(std::string const &key);\n\nstd::vector<hash> hashes{\n RSHash, JSHash, PJWHash, ELFHash, BKDRHash, \n SDBMHash, DJBHash, DEKHash, FNVHash, BPHash, APHash\n};\n</code></pre>\n\n<p>Depending on the age of compiler you're using, it might not support the braced init-list like I've used above. At that point, it's open to argument that (under the circumstances) it would be easier to use an actual array instead. </p>\n\n<p>In any case, once you have your pointers to functions in something you can index like array, you can use a loop to walk through the array of functions, and use each function in turn:</p>\n\n<pre><code>for (int h=0; h<hashes.size(); h++)\n for (int i=0; i<100000; i++) {\n incrStr(key);\n carryStr(key);\n if (hashes[h](key) < 10000) {\n std::cout << // ...\n break; // breaks inner loop, so goes to testing next hash function\n }\n }\n</code></pre>\n\n<p>Again, if you have a new enough compiler (C++11) available, you can make the outer loop a little prettier using a range-based for loop:</p>\n\n<pre><code>for (auto &&hash : hashes) \n // ...\n if (hash(key) < 10000) \n // ...\n</code></pre>\n\n<p>Once you've done that, there are a few more fairly obvious points, such as replacing the magic numbers like <code>100000</code> and <code>10000</code> with defined constants with more meaningful names.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T05:26:53.367",
"Id": "46232",
"ParentId": "46214",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46232",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T19:57:22.700",
"Id": "46214",
"Score": "5",
"Tags": [
"c++",
"bitwise",
"hashcode"
],
"Title": "Eliminating repetitiveness in code to test hash functions"
} | 46214 |
<p>I have the following method in a web service class. I'm a little unhappy about the big block of <code>new JProperty(...)</code> calls in the for loop. Is there a way to simplify that?</p>
<pre><code>public string UserCatalog(string numericSessionId, JObject incomingRequestJson)
{
JObject json = new JObject();
JObject returningJson = new JObject();
JArray userCatalogArray = new JArray();
string deviceId = incomingRequestJson.SelectToken("deviceId", true).ToString();
string version = getOptionalData(incomingRequestJson, "version", "1.0.0");
requireMinVersion(incomingRequestJson);
IEnumerable<Bookcard> catalog = readerBLL.UserCatalog(numericSessionId, deviceId);
var publicKeyRSA = readerTools.GetPublicKey(HttpUtility.HtmlDecode(numericSessionId), HttpUtility.HtmlDecode(version));
//Build the userCatalog json array
foreach (Bookcard card in catalog)
{
JObject arrayEntry = new JObject(
new JProperty("bookThumbnailUrl", card.bookThumbnailUrl),
new JProperty("bookId", card.bookId),
new JProperty("bookTitle", card.bookTitle),
new JProperty("titlePrefix", card.titlePrefix),
new JProperty("author", card.author),
new JProperty("annotation", card.annotation),
new JProperty("publisher", card.publisher),
new JProperty("numPages", card.numPages),
new JProperty("returnDate", card.returnDate),
new JProperty("downloaded", card.downloaded),
new JProperty("deviceId", card.deviceId),
new JProperty("currentPageLabel", card.currentPageLabel),
new JProperty("furthestPageLabel", card.furthestPageLabel),
new JProperty("currentReadPosition", card.currentReadPosition),
new JProperty("furthestReadPosition", card.furthestReadPosition),
new JProperty("lastReadTimestamp", card.lastReadTimestamp),
new JProperty("bookLength", card.bookLength),
new JProperty("ttsEnabled", card.ttsEnabled),
new JProperty("mackinCheckoutID", card.mackinCheckoutID),
new JProperty("runtime", card.runtime),
new JProperty("readerType", card.readerType),
new JProperty("dop", card.dop),
new JProperty("externalId", card.externalId),
new JProperty("externalSessionKey", card.externalSessionKey),
new JProperty("externalCheckoutSessionKey", card.externalBookSessionKey),
new JProperty("externalCheckoutId", card.externalCheckoutId),
new JProperty("externalAccountId", card.externalAccountId + findawayBLL.AccountSuffix)
);
if (card.printAllowed && !readerTools.isOldVersion(1, 3, 0, version))
{
arrayEntry.Add(new JProperty("printAllowed", readerTools.EncryptRSA("print_OK_" + card.bookId, publicKeyRSA)));
}
userCatalogArray.Add(arrayEntry);
}
returningJson.Add("userCatalog", userCatalogArray);
return returningJson.ToString();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:46:39.300",
"Id": "80654",
"Score": "2",
"body": "why do you want to simplify it? it looks very simple. In other words, I'm curious about what you don't like about it.\n\nYou could 'Extract Method' on the line that initializes the array."
}
] | [
{
"body": "<p>If you want to remove the big block of new JProperties, then you need to abstract what varies and find a way in which you can loop over the list of properties you wish to serialise to JSON. You can do this using reflection, which won't be as fast as this code, but it would be more generic and reusable. The XmlSerializer that's been in the .net Framework since version 1.0 works this way, and I'd recommend a similar approach using attributes on public properties and fields that you wish to serialize.</p>\n\n<p>I'm not particularly experienced in serialising JSON, but I'd be suprised if there weren't already a plethora of libraries using this approach. In fact a quick Google turns up the <a href=\"http://james.newtonking.com/json\" rel=\"nofollow\">JSON.net library</a> which looks popular and appears to work in this manner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T00:27:00.540",
"Id": "80663",
"Score": "0",
"body": "Unless I'm mistaken JProperty is out of the JSON.net library already"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T05:43:02.997",
"Id": "81119",
"Score": "0",
"body": "@dreza correct, it's in the `Newtonsoft.Json.Linq` namespace."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T00:22:43.523",
"Id": "46225",
"ParentId": "46217",
"Score": "3"
}
},
{
"body": "<p>As @WillNewton commented, you could always move all that <code>new</code>ing up elsewhere (perhaps in an extension method that extends the <code>Bookcard</code> type and adds a <code>ToJObject</code> method), but the length would remain the same - there's not much repetition in here.</p>\n\n<p>If all properties of <code>BookCard</code> (that's not a typo - I really think it should be <code>BookCard</code>) are mapped to a JProperty, then you could use some reflection to get each property's name and value:</p>\n\n<pre><code>public static IEnumerable<JProperty> GetJProperties(this BookCard card)\n{\n var create = new Func<string, object,JProperty>((name, value) => new JProperty(name, value));\n foreach (var property in card.GetType().GetProperties())\n {\n yield return create(property.Name, property.GetValue(card));\n }\n}\n</code></pre>\n\n<p>and then I presume (haven't tested) this would work:</p>\n\n<pre><code>public static JObject ToJObject(this BookCard card)\n{\n return new JObject(card.GetJProperties());\n}\n</code></pre>\n\n<p>This extension method would allow you to rewrite your <code>foreach</code> loop like this:</p>\n\n<pre><code>foreach(BookCard card in catalog)\n{\n var arrayEntry = card.ToJObject();\n // ...\n}\n</code></pre>\n\n<p>Alternatively, JSON.net gives you the <code>JsonConvert</code> class; you might be interested in the <code>Newtonsoft.Json.JsonConvert.SerializeObject</code> and <code>Newtonsoft.Json.JsonConvert.DeserializeObject</code> static methods, each with overloads that let you customize the process.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-10T20:55:35.730",
"Id": "81988",
"Score": "0",
"body": "Thanks for this answer. I ended up using `JsonConvert` with some changes to my `BookCard` (which I also renamed)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T02:19:45.510",
"Id": "46227",
"ParentId": "46217",
"Score": "2"
}
},
{
"body": "<p>It is not clear (since you don't show the definition of card) however if all you are doing is creating properties for each public property of card then try this:</p>\n\n<pre><code>JObject arrayEntry = JObject.FromObject(card);\n</code></pre>\n\n<p>You might need a few more lines to add or remove additional properties based on your business rules. But this would cut down on a lot of the clutter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T03:38:06.013",
"Id": "81104",
"Score": "1",
"body": "@Mat'sMug - lol, thanks Mat. However, I'm sure if we looked at the source code for `Jobject.FromObject()` it is implemented as you describe, so this is really exactly the same as your answer -- just has already been implemented."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-05T15:58:53.103",
"Id": "46381",
"ParentId": "46217",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "46227",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T21:06:08.880",
"Id": "46217",
"Score": "3",
"Tags": [
"c#",
"json"
],
"Title": "Simplifying a web service method"
} | 46217 |
<p>I made a search method because I want to use binary data like PNG files. The point of this is to be able to find strings like <code>IEND</code> in a PNG file. I think it works properly. Any improvements/fixes would be appreciated.</p>
<pre><code>public static int findString(byte[] in, byte[] find) {
boolean done = false;
for(int i = 0; i < in.length; i++) {
if(in[i] == find[0]) {
for(int ii = 1; ii < find.length; i++) {
if(in[i+ii] != find[ii]) break;
else if(ii==find.length-1) done = true;
}
if(done) return i-1;
}
}
return -1;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:56:18.657",
"Id": "80734",
"Score": "0",
"body": "Your edit invalidates advice that was already given in an existing answer, and is therefore not allowable. I've rolled Rev 3 back to Rev 2."
}
] | [
{
"body": "<ol>\n<li><p>I might have misunderstood something but both of these tests fail:</p>\n\n<pre><code>@Test\npublic void test3() {\n byte[] in = { 1, 2, 3, 4, 5, 6 };\n byte[] find = { 3, 4, 5 };\n assertEquals(2, findString(in, find)); // returns -1\n}\n\n@Test\npublic void test5() {\n byte[] in = { 1, 2, 3, 4, 5, 6 };\n byte[] find = { 4, 5, 6 };\n assertEquals(3, findString(in, find)); // returns -1\n}\n</code></pre>\n\n<p>I think you should increase <code>ii++</code> here instead of <code>i</code>:</p>\n\n<blockquote>\n<pre><code>for(int ii = 1; ii < find.length; i++) {\n</code></pre>\n</blockquote>\n\n<p>So, try to use variables which are easer to tell apart from each other.</p></li>\n<li><p>Anyway, don't reinvent the wheel, there is a library for that! <a href=\"https://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Guava</a> has a <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/primitives/Bytes.html#indexOf%28byte%5b%5d,%20byte%5b%5d%29\" rel=\"nofollow\"><code>Bytes</code></a> class with the following method:</p>\n\n<blockquote>\n<pre><code>public static int indexOf(byte[] array, byte[] target)\n</code></pre>\n \n <p>Returns the start position of the first occurrence of the specified target within array, or -1 if there is no such occurrence. </p>\n</blockquote>\n\n<p>It's open-source, so you can compare <a href=\"https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/primitives/Bytes.java#118\" rel=\"nofollow\">their code</a> with yours.</p>\n\n<p>See also: <em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> (The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:50:57.890",
"Id": "80731",
"Score": "2",
"body": "It was actually supposed to be ii++ thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T22:46:49.897",
"Id": "46221",
"ParentId": "46220",
"Score": "6"
}
},
{
"body": "<p>I recommend naming the parameters <code>haystack</code> and <code>needle</code> for clarity. (It's one of the few things <a href=\"http://php.net/strstr\">PHP did well</a>!)</p>\n\n<p>You don't test your bounds properly. This test crashes with an <code>ArrayIndexOutOfBoundsException</code>:</p>\n\n<pre><code>byte[] haystack = new byte[] { 1, 2, 3, 4, 5 };\nbyte[] needle = new byte[] { 4, 5, 6 };\nfindString(haystack, needle);\n</code></pre>\n\n<p>The conditional <code>if(in[i] == find[0])</code> is superfluous. Just have the inner loop start with <code>ii = 0</code>.</p>\n\n<p>Avoid using variables like <code>done</code> pointlessly. If you're done, and it's possible to return the result immediately, then do it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T22:55:33.063",
"Id": "46222",
"ParentId": "46220",
"Score": "6"
}
},
{
"body": "<p>If you want to look for a particular chunk of bytes in a PNG file, don't scan it naïvely byte by byte. Not only would it be <a href=\"http://www.w3.org/TR/PNG-Rationale.html#R.Chunk-layout\">slow</a>, you could also accidentally match some data that happens to look like a marker.</p>\n\n<p>Instead, you should take advantage of the <a href=\"http://www.w3.org/TR/PNG/#5Chunk-layout\">chunk layout</a> described in the PNG specification. Each chunk is tagged with a type and a length. If the tag is of a type that you are not interested in, seek ahead to the next chunk — the length field will tell you how many bytes to skip.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T23:06:46.723",
"Id": "46224",
"ParentId": "46220",
"Score": "10"
}
},
{
"body": "<p>Here another implementation, probably more readable:</p>\n\n<pre><code>public static int search(byte[] input, byte[] searchedFor) {\n //convert byte[] to Byte[]\n Byte[] searchedForB = new Byte[searchedFor.length];\n for(int x = 0; x<searchedFor.length; x++){\n searchedForB[x] = searchedFor[x];\n }\n\n int idx = -1;\n\n //search:\n Deque<Byte> q = new ArrayDeque<Byte>(input.length);\n for(int i=0; i<input.length; i++){\n if(q.size() == searchedForB.length){\n //here I can check\n Byte[] cur = q.toArray(new Byte[]{});\n if(Arrays.equals(cur, searchedForB)){\n //found!\n idx = i - searchedForB.length;\n break;\n } else {\n //not found\n q.pop();\n q.addLast(input[i]);\n }\n } else {\n q.addLast(input[i]);\n }\n }\n\n return idx;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:38:15.573",
"Id": "46272",
"ParentId": "46220",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "46224",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T22:09:47.703",
"Id": "46220",
"Score": "11",
"Tags": [
"java",
"array",
"search"
],
"Title": "Find byte[] in byte[] with Java"
} | 46220 |
<ol>
<li>What is the best method/practice to keep, let's say, over 3,000 lines of code organized for readability?</li>
<li>What kind of NO-NOs in regards to coding habits should I get rid of before they become bad habits?</li>
<li>Inversely what kind of good coding habits should I be picking up?</li>
<li>Any glaringly obvious mistakes? Any helpful links for further reading would be appreciated.</li>
</ol>
<p>I am including code that I have been working on for the past couple weeks. Basically it will help to increase the efficiency of my workflow from pulling inventory off trucks, to getting it to where it needs to go.</p>
<p>The following code navigates to a website and extracts information about an Item.</p>
<pre><code># -*- coding: utf8 -*-
import csv, time, os, random, difflib, re, json
from itertools import islice
import httplib
import urllib2
from bs4 import BeautifulSoup as BS
from shutil import copyfile
def get_product_info(item_number):
''' Returns a dictionary of item information '''
# offer_id_orig = '#NK420#########'
offer_id_orig = item_number
item_uts_number = offer_id_orig[1:6]
print offer_id_orig
# DOWNLOAD PRODUCT INFO IF WE DON"T HAVE IT
def download_page_info(item_uts_number):
#import time, os, random
#import httplib
#import urllib2
# ITEM_NUMBER MUST BE 4NK4200000100 FORMAT
# assigned_row_titles 'offer_id_orig' : current_row[2]
print item_uts_number
httplib.HTTPConnection.debuglevel = 1
# take multiple arguments?
fp = os.path.join(folder,item_uts_number)
print "Fetching:"+fp+"\n"
try:
request = urllib2.Request('http://www.fingerhut.com/product/'+item_uts_number.upper()+'.uts')
request.add_header('User-Agent','jmunsch_thnx_v2.0 +http://jamesmunsch.com/')
opener = urllib2.build_opener()
data = opener.open(request).read()
with open(fp,'w+') as f:
f.write(data)
time.sleep(1+random.random())
print "Fetched."
except Exception,e:print e
return data
# Get the images
def get_images(fp,item_number):
#### TODO ###
# get the correct schema
# will need to use selenium for this? since the page loads with jquery and javascript
################## 3-16-14
# labeling schema for images itemnumber_letter_999
#### This is not require if I get image url from the original init variables from html/json
# letters = [ 'A','B','C','D','E','F','G','VA','VB','VC','VD','VE','VF','VG' ]
# for letter in letters:
# url_string = item_number+"_"+letter+"_999?"
#+"&scl=1"
#+"$swatch$"
# imgName = item_number+"_"+letter+"_999"
try:
# build the url
image_url = "http://s7d5.scene7.com/is/image/bluestembrands/"+url_string
print image_url
# build request header
user_agent = 'jmunsch_v3 (+http://jamesmunsch.com/)'
headers = { 'User-Agent' : user_agent }
imgRequest = urllib2.Request(image_url, headers=headers)
# get the image data
imgData = urllib2.urlopen(imgRequest).read()
#write teh image data
with open(os.path.join(fp,imgName),'w+') as imgFile:
imgFile.write(imgData)
# except problem i.e. wrong filepath / 403 / incorrect request
except Exception,e:
print "Oops: "+str(e)
# Get Item info ( description, specs, picUrl )
def extract_product_info(data):
''' Extract product info from the data from download_page_info '''
#from bs4 import BeautifulSoup as BS
#id="productTabs_tab1"
#id="productTabs_tab3"
# Grab Description
try:
json_data = data.split("page.init(")[1].split("});")[0]
json_data = json_data + "}"
print "Trying to load json"
json_data = json.loads(json_data.replace('\\uXXXX',''))
description = json_data['product']['description']
d_soup = BS(description)
# Remove tags with information that can lead back to FH
for tag in d_soup.find_all('h3'):
tag.replaceWith('')
for tag in d_soup.find_all('script'):
tag.replaceWith('')
for tag in d_soup.find_all('a'):
tag.replaceWith('')
for tag in d_soup.find_all('li'):
if "Available" in tag.text:
tag.replaceWith('')
description = d_soup
except Exception,e:
print e
print 'unable to get description'
#print description
print json_data
description = None
# Grab Specifications
try:
json_data = data.split("page.init(")[1].split("});")[0]
json_data = json_data + "}"
print "Trying to load json"
json_data = json.loads(json_data)
specifications = json_data['product']['specifications']
specs ="<br>".join(x for x in specifications)
except Exception,e:
print e
print 'unable to get specifications'
print json_data
#print specs
specs = None
# Grab Images
image_list = []
try:
json_data = data.split("page.init(")[1].split("});")[0]
json_data = json_data + "}"
print "Trying to load json"
json_data = json.loads(json_data)
images = json_data['product']['media']['image']
if len(images) is not 0:
for url in images:
tmp_str = url['hiRes'].encode('utf8').split('?')[0].split('/')[-1]
#print tmp_str
image_list.append(tmp_str)
if len(images) is 0:
print " images is empty "
split_data = data.split('\"')
for line in split_data:
if ( offer_id_orig[1:6] and "is/bluestembrands" ) in line:
image_list.append(line.split('/')[-1].split('?')[0])
if len(image_list) is 0:
raise NameError('imgList0')
except NameError,n:
print "\n###"+str(n)
if 'imgList0' in n:
print '#~# Didnt find any images...? Good luck.'
image_list = [offer_id_orig]
pass
except Exception,e:
print e
#print json_data
print " Unable to get image_list "
image_list = None
image_list = list(set(image_list))
if len(image_list) is not 0:
print "Got Images."
results = { 'description' : description ,
'specs' : specs ,
'image_list' : image_list
}
return results
# Check if item page has been downloaded
# Get page data
# Make item folder
try:
folder = 'item_number_pages'
os.mkdir(folder)
except Exception,e:print e
fp = os.path.join(folder,item_uts_number)
# Check if the file exists if not download it
if os.path.isfile(fp) is True:
data = open(fp,'r').read()
elif os.path.isfile(fp) is False:
data = download_page_info(item_uts_number)
else:
print "what?"
exit()
# extract product info returns
# 'description','specs','image_list'
#
########################################
results = extract_product_info(data)
print results
return results
</code></pre>
<p>And the wxPython code that I am hacking together will display the Item Picture and allow me to make changes to the item information. I also plan to create a dialogue that shows all the images for a particular SKU, some features for inventorying/receiving these items, and eventually write this out to a csv the code below is unfinished:</p>
<pre><code>import wx, urllib2, os
from PIL import Image
class PhotoCtrl(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title)
#self.frame = wx.Frame(None,'Sky Group Scanner')
#self.frame = wx.Frame(None, title='Photo Control')
self.panel = wx.Panel(self)
self.PhotoMaxSize = 240
self.createWidgets()
self.Show()
def createWidgets(self):
filepath = fp
if fp is not None:
img = wx.Image(fp, wx.BITMAP_TYPE_ANY)
if fp is None:
img = wx.EmptyImage(240,240)
self.imageCtrl = wx.StaticBitmap(self.panel, wx.ID_ANY,
wx.BitmapFromImage(img))
instructions = 'Is this image correct?'
instructLbl = wx.StaticText(self.panel, label=instructions)
# menubar
#####################
file = wx.Menu()
edit = wx.Menu()
help = wx.Menu()
file.Append(101,'&Open', 'Open a file')
file.Append(102,'&Save', 'Save a file')
file.AppendSeparator()
quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
file.AppendItem(quit)
menubar = wx.MenuBar()
menubar.Append(file, '&File')
menubar.Append(edit,'&Edit')
menubar.Append(help,'&Help')
self.SetMenuBar(menubar)
self.CreateStatusBar()
#photo txt and browse Button
##################
self.photoTxt = wx.TextCtrl(self.panel, size=(200,-1))
browseBtn = wx.Button(self.panel, label='Browse')
browseBtn.Bind(wx.EVT_BUTTON, self.onBrowse)
SelectImageBtn = wx.Button(self.panel, label="Select Image Choices")
SelectImageBtn.Bind(wx.EVT_BUTTON, self.onBrowse)
# Description Text
##########################
descriptionTextField = wx.TextCtrl(self.panel,size=(300,500), style=wx.TE_MULTILINE | wx.TE_RICH2)
descriptionTextField.AppendText(str(itemInfo['specs'].decode('utf8')+itemInfo['description'].decode('utf8')))
# Add Widgets
#########################
self.mainSizer = wx.BoxSizer(wx.HORIZONTAL)
self.lSizer = wx.BoxSizer(wx.VERTICAL)
self.rSizer = wx.BoxSizer(wx.HORIZONTAL)
self.mainSizer.Add(wx.StaticLine(self.panel, wx.ID_ANY),
0, wx.ALL|wx.EXPAND, 5)
self.lSizer.Add(instructLbl, 0, wx.ALL, 5)
self.lSizer.Add(self.imageCtrl, 0, wx.ALL, 5)
self.lSizer.Add(self.photoTxt, 0, wx.ALL, 5)
self.lSizer.Add(browseBtn, 0, wx.ALL, 5)
self.lSizer.Add(SelectImageBtn, 0, wx.ALL, 5)
self.rSizer.Add(descriptionTextField, 0, wx.ALL, 5)
self.mainSizer.Add(self.lSizer, flag=wx.ALIGN_LEFT)
self.mainSizer.Add(self.rSizer, flag=wx.ALIGN_RIGHT)
self.panel.SetSizer(self.mainSizer)
self.mainSizer.Fit(self)
self.panel.Layout()
def onBrowse(self, event):
"""
Browse for file
"""
wildcard = "JPEG files (*.jpg)|*.jpg"
dialog = wx.FileDialog(None, "Choose a file",
wildcard=wildcard,
style=wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
self.photoTxt.SetValue(dialog.GetPath())
dialog.Destroy()
self.onView()
def onView(self):
#filepath = self.photoTxt.GetValue()
#img = wx.Image(filepath, wx.BITMAP_TYPE_ANY)
filepath = fp
img = wx.Image(fp, wx.BITMAP_TYPE_ANY)
# scale the image, preserving the aspect ratio
W = img.GetWidth()
H = img.GetHeight()
if W > H:
NewW = self.PhotoMaxSize
NewH = self.PhotoMaxSize * H / W
else:
NewH = self.PhotoMaxSize
NewW = self.PhotoMaxSize * W / H
img = img.Scale(NewW,NewH)
self.imageCtrl.SetBitmap(wx.BitmapFromImage(img))
self.panel.Refresh()
def get_image(item_info,item_number):
global fp
global itemInfo
global itemNumber
itemInfo = item_info
itemNumber = item_number
try:
uts_number = item_info['image_list'][0]
uts_ = uts_number + '?'
folder = 'item_number_pages'
imgName = item_number+'.JPEG'
fp = os.path.join(folder,imgName)
if os.path.isfile(fp) is False:
print uts_number
# build the url
image_url = "http://s7d5.scene7.com/is/image/bluestembrands/"+uts_
print image_url
# build request header
user_agent = 'jmunsch_v3 (+http://jamesmunsch.com/)'
headers = { 'User-Agent' : user_agent }
imgRequest = urllib2.Request(image_url, headers=headers)
# get the image data
imgData = urllib2.urlopen(imgRequest).read()
#write teh image data
# uh... windows requires wb ...
with open(fp,'wb') as imgFile:
print('Writing Image:' + fp)
imgFile.write(imgData)
# except problem i.e. wrong filepath / 403 / incorrect request
except Exception,e:
print "display_image: Oops1: "+str(e)
app = wx.App(False)
frame = PhotoCtrl(None,'Sky Group Scanner')
app.MainLoop()
return
if __name__ == '__main__':
global fp
global itemInfo
global itemNumber
fp = None
itemInfo = {'description':'Empty','specs':'Empty'}
itemNumber = "Empty"
app = wx.App(False)
frame = PhotoCtrl(None,'A Simple Scanner')
app.MainLoop()
</code></pre>
<h1>Update:</h1>
<p>Based off of the recommendations of @alexwlchan I have begun using a dedicated IDE for python called Ninja-IDE. It has been pretty handy in comparison to using NotePad++. It is a little slow in regards to searching for multiple instances of a search term and the implemented terminal doesn't remember history, but overall it has been a good fit. The IDE I think is written in python so could be coded and possibly merged if the Ninja team is interested, but I haven't dug into that code.</p>
<p>I also began using github a little more extensively for peace of mind and also to have backups of backups and to keep a basepoint for a working version in case I really mess my code somewhere. <a href="http://github.com/jmunsch/Sky_Group_Inventory_Scanner-wxpython" rel="nofollow">http://github.com/jmunsch/Sky_Group_Inventory_Scanner-wxpython</a></p>
<p>And also instead of littering my code with a bunch of print statements for debugging, I have been using <code>import pdb; pdb.set_trace()</code> right before the code that I want to step through and debug.</p>
<p>Also, Modularizing the code has been really helpful.</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T23:14:52.860",
"Id": "80660",
"Score": "2",
"body": "Could you please explain the purpose of this code? Titles here should also reflect on that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T00:22:25.170",
"Id": "80662",
"Score": "3",
"body": "Welcome to CR! Thanks for putting in the effort, +1 ;)"
}
] | [
{
"body": "<p>As a piece of code for a “beginner” (reading from the tag), this is pretty good. I’ll start by offering some suggestions on your specific questions, and then make some comments on the code itself:</p>\n\n<ol>\n<li><p><strong>What is the best method/practice to keep, let's say, over 3,000 lines of code organized for readability?</strong></p>\n\n<ul>\n<li><p>Scratch readability for now, just keeping 3,000 lines of code organised will get painful quickly. Are you using some sort of version control system (VCS) with the code? If not, I’d recommend looking into one. As you maintain and extend the code, you can keep “snapshots” of working versions or experimental techniques. Using a VCS, and committing regularly, is a really good habit for larger codebases.</p>\n\n<p>The <a href=\"http://rypress.com/tutorials/git/index.html\">Rypress tutorial</a> is a good introduction to Git, a fairly common VCS.\nYou can either run a VCS locally, or <a href=\"https://bitbucket.org\">Bitbucket</a> offers free private repositories. (Bitbucket also have tutorials for Git and Mercurial when you sign up.)</p></li>\n<li><p>Put TODO notes in a separate file. Otherwise it gets hard to find and will get lost in the mix.</p></li>\n<li><p>Write docstrings for all of your non-trivial functions. You remember what <code>onView()</code> is meant to do right now, but you might find it harder to remember in six months time when you’re debugging it. Read <a href=\"https://www.python.org/dev/peps/pep-0257/\">PEP 257</a> for the Python standards for writing docstrings.</p></li>\n<li><p>Don’t litter the file with multiple newlines between functions or within functions. One is quite enough, and doesn’t break the file up so much.</p></li>\n</ul></li>\n<li><p><strong>What kind of NO-NOs in regards to coding habits should I get rid of before they become bad habits?</strong></p>\n\n<ul>\n<li><p>Don’t just copy-and-paste special strings into the code; declare them as global variables at the top of the file and use them as appropriate. This means you can only change them once when you need to.</p>\n\n<p>For example, these lines from the two different files give me pause for thought:</p>\n\n \n\n<pre><code>request.add_header('User-Agent','jmunsch_thnx_v2.0 +http://jamesmunsch.com/')\nuser_agent = 'jmunsch_v3 (+http://jamesmunsch.com/)'\n</code></pre>\n\n<p>Is there a reason for the two user agent strings to have a different format? And why do they have different version numbers? etc.</p></li>\n<li><p>Have you read <a href=\"http://legacy.python.org/dev/peps/pep-0008/\">PEP 8</a>? This is the Python style guide. Overall you’re pretty good, but there are one or two things that could be tweaked: </p>\n\n<ul>\n<li><p>Spacing around commas goes like an English sentence: none before, one after. So <code>except Exception,e:print e</code> becomes</p>\n\n\n\n<pre><code>except Exception, e:\n print e\n</code></pre>\n\n<p>Also, put blocks after a colon like this on a new line.</p></li>\n<li><p>Same goes for whitespace around binary operators. So <code>print \"Oops: \"+str(e)</code> becomes <code>print \"Oops: \" + str(e)</code>.</p></li>\n</ul>\n\n<p>Style issues aren’t going to break your code, but it will make it easier for other people to read and debug your code (and conversely, it will make it easier for you to read other people’s Python), because the styles match.</p></li>\n</ul></li>\n<li><p><strong>Inversely what kind of good coding habits should I be picking up?</strong></p>\n\n<p>Don’t do what I said not to do in 2. ;)</p></li>\n<li><p><strong>Any glaringly obvious mistakes?</strong></p>\n\n<p>Beyond what I’ve already mentioned, nothing stands out as being terrible. (At least, to my eyes.)</p>\n\n<p>If you want more on good programming practice, then I’d suggest reading a copy of <a href=\"http://pragprog.com/the-pragmatic-programmer\">The Pragmatic Programmer</a>, which contains some excellent advice on good style (including most of what I wrote above, and a lot more).</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:44:44.180",
"Id": "80785",
"Score": "0",
"body": "Nice. The Rypress git tutorial looks really great. I've messed with git a little bit, but not to keep code organized with versions. I've just been saving copies with the date and throwing them in a folder. I look forward to reading the book suggestion and styling guide. I really appreciate your time and suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T16:35:52.853",
"Id": "81366",
"Score": "0",
"body": "@alexslchan I also started using an IDE... I had been using notepad++. It incorporates a PEP8 format checker, plugins for Git, and a bunch of other goodies that I haven't dived into yet, but this looks promising. Using NINJA-IDE since I have been coding mostly in python."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:08:23.540",
"Id": "46240",
"ParentId": "46223",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46240",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T22:56:08.170",
"Id": "46223",
"Score": "11",
"Tags": [
"python",
"beginner",
"gui"
],
"Title": "wxPython Item Information Scraper"
} | 46223 |
<p>I wrote a small utility function that divides a total into <em>n</em> parts in the ratio given in <code>load_list</code>. Numbers in each part should be positive integers. It supports an optional <code>min_num</code> argument that, when specified, puts at least <code>min_num</code> in each of the <em>n</em> parts before distributing the rest. Please review.</p>
<pre><code>def reduce_ratio(load_list, total_num, min_num=1):
"""
Returns the distribution of `total_num` in the ratio of `load_list` in the best possible way
`min_num` gives the minimum per entry
>>> reduce_ratio([5, 10, 15], 12)
[2, 4, 6]
>>> reduce_ratio([7, 13, 30], 6, 0)
[1, 2, 3]
>>> reduce_ratio([7, 13, 50], 6)
[1, 1, 4]
>>> reduce_ratio([7, 13, 50], 6, 3)
Traceback (most recent call last):
...
ValueError: Could not satisfy min_num
>>> reduce_ratio([7, 13, 50], 100, 15)
[15, 18, 67]
>>> reduce_ratio([7, 13, 50], 100)
[10, 19, 71]
"""
num_loads = [ [load, min_num] for load in load_list ]
yet_to_split = total_num - ( len(num_loads) * min_num )
if yet_to_split < 0:
raise ValueError('Could not satisfy min_num')
for _ in range(yet_to_split):
min_elem = min(num_loads, key=lambda (load, count): (float(count)/load, load))
min_elem[1] += 1
reduced_loads = map(itemgetter(1), num_loads)
if sum(reduced_loads) != total_num:
raise Exception('Could not split loads to required total')
return reduced_loads
</code></pre>
| [] | [
{
"body": "<p>Because the problem is not quite formalised and is mostly defined by the way your code currently works, I must confess that I find it quite hard to make thinds more efficient/concise.</p>\n\n<p>A few point however:</p>\n\n<ul>\n<li>using <code>( len(num_loads) * min_num )</code> un-necessarly relies on the way you have populated <code>num_loads</code>. You could something more generic like : <code>yet_to_split = total_num - sum(num for _,num in num_loads)</code> so that things work no matter what.</li>\n<li>at the moment, I don't think it is possible for the condition <code>sum(reduced_loads) != total_num</code> to be true. Indeed, at the beginning, the definition of <code>yet_to_split</code> leads to the following property : <code>yet_to_split + sum_of_loads = total_num</code>. Then as we iterate over <code>yet_to_split</code>, <code>sum_of_loads</code> gets increased one by one. Because the condition cannot be true, it's not really wise to expect anyone to expect and catch this exception. If you want to perform the verification, <code>assert</code> is what you should be using : <code>assert(sum(reduced_loads) == total_num)</code>.</li>\n<li>in order to avoid any troubles while processing the input, you might want to add more checks.</li>\n</ul>\n\n<p>My suggestions are the following :</p>\n\n<pre><code>if not load_list:\n raise ValueError('Cannot distribute over an empty container')\nif any(l <= 0 for l in load_list):\n raise ValueError('Load list must contain only stricly positive elements')\n</code></pre>\n\n<ul>\n<li>A bit of a naive question but couldn't the <code>min_num</code> logic be extracted out by processing the <code>load_list</code> normally and only at the end (in a potentially different function) check that <code>min(return_array) >= min_num</code> ? This makes performance slightly worse for cases leading to failures but makes this usual case a bit clearer.</li>\n</ul>\n\n<p>For instance, the code would be like :</p>\n\n<pre><code>num_loads = [ [load, 0] for load in load_list ]\nfor _ in range(total_num):\n min_elem = min(num_loads, key=lambda (load, count): (float(count)/load, load))\n min_elem[1] += 1\nreduced_loads = [num for _,num in num_loads]\nassert(sum(reduced_loads) == total_num)\nreturn reduced_loads\n</code></pre>\n\n<ul>\n<li>Just a suggestion but instead of recomputing the minimal element by reprocessing the whole array every-time, maybe you could use an appropriate data structure like <a href=\"https://docs.python.org/2/library/heapq.html\" rel=\"nofollow\">heapq</a> to get the minimal element quickly and then re-add it to the structure once updated.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:25:08.143",
"Id": "46256",
"ParentId": "46226",
"Score": "4"
}
},
{
"body": "<p>So in terms of code layout this is a little hard to follow, but apart form that is fine and the docstring is good. However, I'm not sure that your code gives the right result. Also it could also be sped up by at least a factor of four.</p>\n\n<p>Take the example:</p>\n\n<pre><code>In [22]: reduce_ratio([1,50,23],32,6)\nOut[22]: [6, 18, 8] \n</code></pre>\n\n<p>so the first thing the code should do is put 6 in each output as this is <code>min_num</code>, this should give:</p>\n\n<pre><code>[6, 6, 6]\n</code></pre>\n\n<p>So this removes <code>3*6=18</code> from <code>total_num</code> leaving 14 to distribute according to your <code>load_list</code>.</p>\n\n<p>This gives:</p>\n\n<pre><code>In [3]: [14*float(load)/sum(load_list) for load in load_list]\nOut[3]: [0.1891891891891892, 9.4594594594594597, 4.3513513513513518]\n</code></pre>\n\n<p>Now obviously <code>0.1891891891891892</code> rounds to zero, so we pop that from the list and move on. We now have to split 14 with <code>load_list=[50,23]</code>. This gives:</p>\n\n<pre><code>In [6]: [14*float(load)/sum(load_list) for load in load_list]\nOut[6]: [9.5890410958904102, 4.4109589041095889]\n</code></pre>\n\n<p>Rounding this obviously gives <code>[10,4]</code>. So we have successfully split the number 14 into <code>[0,10,4]</code> with <code>load_list=[50,23]</code>. Adding this to our list of <code>min_num</code> (<code>[6,6,6]</code>) gives:</p>\n\n<pre><code>[6, 16, 10]\n</code></pre>\n\n<p>and <code>[6, 16, 10] != [6, 18, 8]</code>.</p>\n\n<p>Apologies if I have missed something in the code and <code>[6, 18, 8]</code> was the desired result. Below is the code I used to get my answer:</p>\n\n<pre><code>def new_reduce_ratio(load_list, total_num, min_num=1):\n output = [min_num for _ in load_list]\n total_num -= sum(output)\n if total_num < 0:\n raise Exception('Could not satisfy min_num')\n elif total_num == 0:\n return output\n\n nloads = len(load_list)\n for ii in range(nloads):\n load_sum = float( sum(load_list) )\n load = load_list.pop(0)\n value = int( round(total_num*load/load_sum) )\n output[ii] += value\n total_num -= value\n return output\n</code></pre>\n\n<p>This code also has some speed benefits over your current implementation:</p>\n\n<pre><code>In [2]: %timeit reduce_ratio([1,50,23],32,6)\n10000 loops, best of 3: 44 us per loop\n\nIn [3]: %timeit new_reduce_ratio([1,50,23],32,6)\n100000 loops, best of 3: 9.21 us per loop\n</code></pre>\n\n<p>here we get a speed up of a factor of ~4.8.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:03:47.700",
"Id": "80736",
"Score": "0",
"body": "I think OP's code chooses 18 and 8 because 50/18 is approximately equal to 23/8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:09:32.473",
"Id": "80737",
"Score": "0",
"body": "Disclaimer : I have no idea what I am doing. I have defined the 2 following functions to compare results - this is pretty arbitrary so one shouldn't rely too much on its results :\n\n\n`def normalise(l): return [float(e)/min(l) for e in l]` ; `def evaluate_ratio(l1,l2): return sum((e1-e2)**2 for e1,e2 in zip(normalise(l1),normalise(l2)))` and I get : \n`evaluate_ratio([1,50,23],[1,50,23])` -> 0.0\n`evaluate_ratio([1,50,23],[6,16,10])` ->2695.5555555555557\n`evaluate_ratio([1,50,23],[6,18,8])` -> 2678.4444444444443 so this might be a justification for OP's results anyway. Have my upvote anyway!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:13:04.473",
"Id": "80741",
"Score": "0",
"body": "@JanneKarila I agree. I can see how the result is obtained, I'm just not sure it is the right way to do it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:25:02.417",
"Id": "80746",
"Score": "0",
"body": "@Josay: The OP says that you first put `min_num` in each output and then distribute what remains from `total_num`. So really you should be evaluating `evaluate_ratio([1,50,23],[0,10,4])` and `evaluate_ratio([1,50,23],[0,12,2])`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:39:56.177",
"Id": "80750",
"Score": "0",
"body": "Indeed, that's a way to see it (even though it would make my functions crash :'()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:03:14.883",
"Id": "80752",
"Score": "0",
"body": "Can't you just switch your normalise function to `def normalise(l): return [float(e)/sum(l) for e in l]` (which is the correct normalisation here anyway). A number closer to zero means a better match. I get `evaluate_ratio([1,50,23],[6,18,8]) = 0.046` which beats `evaluate_ratio([1,50,23],[6,16,10]) = 0.061`, but `evaluate_ratio([1,50,23],[0,10,4]) = 0.002` which beats `evaluate_ratio([1,50,23],[0,12,2]) = 0.061`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:53:07.647",
"Id": "46260",
"ParentId": "46226",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T01:17:47.510",
"Id": "46226",
"Score": "5",
"Tags": [
"python"
],
"Title": "Utility function to split a number into n parts in the given ratio"
} | 46226 |
<p>Here's a program to take a bitfield like 7 and decompose it into the flags [1,2,4].
Ignore that the algorithm for doing this doesn't use bit shifting/is stupid.</p>
<p>Problems: it seems like I have to have the <code>bithelp</code> function for the sole purpose of calling the other ones, since <code>getFlags</code> and <code>findPower</code> both need to be given given a "starter value" as their second argument (since I can't find a good way to make the argument optional on the first try).</p>
<p>Is there any other way to do what they're doing without recursion? Is recursion like this the standard way to "loop" in FP?</p>
<p>I'll be pleased to be shown anything else I'm doing stupidly here:</p>
<pre><code>-- Algorithm:
-- * given any integer:
-- * find largest power of 2 that fits inside the integer
-- * going from largest to smallest powers of 2, progressively substract any power of 2 that can be subtracted until you get to zero
-- * collect these powers and return them as a list
--
-- These represent the bits that are set within the bitfield
-- E.g. bithelp of 51 = [32,16,2,1]
-- process bitfield
bithelp :: Int -> [Int]
bithelp bitfield = getFlags bitfield $ findPower bitfield 0
-- find starting number: largest power of 2 to fit within bits
findPower :: Int -> Int -> Int
findPower bitfield power
| 2^power > bitfield = 2^last -- when overshoot bitfield, return last power
| otherwise = findPower bitfield next
where next = power + 1
last = power - 1
-- starting with flag, subtracts down the list of flags, returning list of matches
getFlags :: Int -> Int -> [Int]
getFlags currentBits flag
| currentBits == flag = [flag] -- only one flag left, last item
| found = [flag] ++ getFlags remainingBits nextFlag
| not found = getFlags currentBits nextFlag
where remainingBits = currentBits - flag
nextFlag = flag `div` 2
found = currentBits >= flag -- means bits could be substracted
-- get user input and print list of matched bits
main = do
putStrLn "Bitfield:"
line <- getLine
let bitfield = read line :: Int
let flags = bithelp bitfield
putStrLn "List of flags:"
print flags
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T03:39:20.580",
"Id": "80670",
"Score": "1",
"body": "`Is there any other way to do what they're doing without recursion? Is recursion like this the standard way to \"loop\" in FP?` Yes, recursion is the only way to loop in Pure FP languages, however very rarely should you be performing the loop yourself, you should be using higher-order functions such as `map` and `filter` to do the looping for you, and to take advantage of stream fusion and more predictable tail-recursion optimisation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T00:50:35.253",
"Id": "81092",
"Score": "0",
"body": "Perhaps use [**`Data.Bits`**](http://hackage.haskell.org/package/base-4.6.0.1/docs/Data-Bits.html)?"
}
] | [
{
"body": "<p>A more common way of \"initializing\" values on the first call is to define an inner worker function.</p>\n\n<pre><code>findPower :: Int -> Int\nfindPower bitfield = go 0\n where go i = ... -- Note that the bitfield argument is still in scope\n</code></pre>\n\n<p>Recursion is the standard way to loop in Haskell (so much so that in lots of code you will find locally defined recursive functions named <code>loop</code>), but your code might be more terse without <em>explicit</em> recursion.</p>\n\n<p>Here's my first pass at a rewrite of the <code>findPower</code> function using higher order functions.</p>\n\n<pre><code>findPower :: Int -> Int\nfindPower i = last . takeWhile (<= i) $ map (2^) [0..]\n</code></pre>\n\n<p>Note that this function still isn't total, i.e. it will fail when passed Ints <= 0. Your version would recurse until <code>2^power</code> overflows, whereas mine will fail fast with an empty list exception due to the use of <code>last</code>. It's considered good style to make your Haskell functions total, so here's my second pass.</p>\n\n<pre><code>findPower :: Int -> Maybe Int\nfindPower 0 = Just 0\nfindPower i | i < 0 = Nothing\n | otherwise = Just . last . takeWhile (<= i) $ map (2^) [0..]\n</code></pre>\n\n<p>Using <code>Maybe</code> here is probably overkill, and in fact you probably want your program to crash when given bad input! Here's a final version.</p>\n\n<pre><code>findPower :: Int -> Int\nfindPower i | i < 0 = error \"findPower: Can't find power of negative number\"\n | i == 0 = 0\n | otherwise = last . takeWhile (<= i) $ map (2^) [0..]\n</code></pre>\n\n<p>On this line <code>| found = [flag] ++ ...</code>, if you're adding a single element to the front of a list, this is just regular cons! Use <code>| found = flag : ...</code> instead.</p>\n\n<p>You've defined a lot of constants in <code>where</code> clauses for your two functions which only get used once. Sometimes it can be helpful to give a name to something that might be non-obvious, but in this case it makes your code longer and arguably adds a bit of cognitive overhead to what are very simple transformations. For instance, I would consider this more readable.</p>\n\n<pre><code>getFlags currentBits flag | currentBits == flag = [flag]\n | currentBits > flag = flag : getFlags (currentBits - flag) (flag `div` 2)\n | otherwise = getFlags currentBits (flag `div` 2)\n</code></pre>\n\n<p>In your definition of <code>main</code>, you can omit the type annotation from <code>read line</code> and the compiler will deduce you want an <code>Int</code> due to the type signature of <code>bithelp</code>. On its own this is a small change, but leveraging the type system in this way is entirely natural and reduces the number of changes you would have to make if, say, you changed your functions to operate on <code>Integer</code>s.</p>\n\n<p>See if this isn't more clear.</p>\n\n<pre><code>main = do putStrLn \"Enter a positive integer:\"\n nstr <- getLine\n putStrLn \"List of flags:\"\n print $ bithelp (read nstr)\n</code></pre>\n\n<p>The last thing to do would be to eliminate the <code>bithelp</code> function by rewriting the <code>getFlags</code> function with a call to <code>findPower</code> inside of it, passed to an inner worker function. I'll leave that as an exercise to the reader.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T03:25:47.870",
"Id": "46230",
"ParentId": "46228",
"Score": "3"
}
},
{
"body": "<h2><em>Always Use a Library When Available!</em></h2>\n\n<p>Perhaps use <a href=\"http://hackage.haskell.org/package/base-4.6.0.1/docs/Data-Bits.html\" rel=\"nofollow\"><strong><code>Data.Bits</code></strong></a>? It was designed for this kind of stuff!</p>\n\n<p>Now that we have chosen the right library, lets look at the right algorithm. </p>\n\n<p>There are no loops in functional languages. Functional languages use recursion when performing iterative computations. In order to generate list of variable length as output, we will need to use recursion.</p>\n\n<p>Here is how I would define your function recursively:</p>\n\n<pre><code>import Data.Bits\n\n{-- List of set flag values in ascending order --}\nbithelp :: (Bits a, Integral a) => a -> [a]\nbithelp n = bithelp' 0 n -- for a given n start by checking power 0\n where -- increment the power at each recursive step\n bithelp' e n -- and conditionally decide how to proceed\n | n < power = [] -- if the power is larger than n we are done\n | testBit n e = power : bithelp' (e+1) n -- if the bitflag is set add the power\n | otherwise = bithelp' (e+1) n -- otherwise just check the next power\n where power = shiftL 1 e -- precompute the power\n\nmain = do\n putStrLn \"Bitfield:\"\n line <- getLine\n let bitfield = read line :: Int\n let flags = bithelp bitfield\n putStrLn \"List of flags:\"\n print flags\n</code></pre>\n\n<p><strong>Examples:</strong></p>\n\n<pre><code>ghci> bithelp 7\n[1,2,4]\nghci> bithelp 51\n[1,2,16,32]\nghci> bithelp 8675309\n[1,4,8,32,64,128,256,512,1024,2048,4096,16384,262144,8388608]\nghci> bithelp 93825764591328014238947101\n[1,4,8,16,256,512,1024,4096,65536,131072,8388608,16777216,33554432,67108864,536870912,2147483648,4294967296,8589934592,17179869184,68719476736,274877906944,549755813888,2199023255552,4398046511104,140737488355328,281474976710656,562949953421312,1125899906842624,9007199254740992,18014398509481984,36028797018963968,72057594037927936,144115188075855872,2305843009213693952,4611686018427387904,9223372036854775808,590295810358705651712,1180591620717411303424,18889465931478580854784,37778931862957161709568,75557863725914323419136,604462909807314587353088,1208925819614629174706176,4835703278458516698824704,9671406556917033397649408,77371252455336267181195264]\nghci> (sum $ bithelp 93825764591328014238947101) == 93825764591328014238947101\nTrue\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T01:18:46.783",
"Id": "46421",
"ParentId": "46228",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46230",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T02:20:01.253",
"Id": "46228",
"Score": "6",
"Tags": [
"haskell",
"functional-programming",
"bitwise"
],
"Title": "Decomposing bitfield with Haskell: is recursion the only way to do this?"
} | 46228 |
<p>I'm looking for code-review, optimization and best practices. Also verifying complexity to be O(E) time and O(V+E) space complexity.</p>
<pre><code>final class NodeClone<T> {
private final T item;
NodeClone(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
final class EdgeClone<T> {
private final NodeClone<T> node1;
private final NodeClone<T> node2;
EdgeClone (NodeClone<T> node1, NodeClone<T> node2) {
this.node1 = node1;
this.node2 = node2;
}
public NodeClone<T> getNode1() {
return node1;
}
public NodeClone<T> getNode2() {
return node2;
}
}
public class CloneGraph<T> implements Iterable<NodeClone<T>> {
/*
* A map from nodes in the graph to list of outgoing edges.
*/
private final Map<NodeClone<T>, List<EdgeClone<T>>> graph;
public CloneGraph() {
graph = new HashMap<NodeClone<T>, List<EdgeClone<T>>>();
}
public CloneGraph(Map<NodeClone<T>, List<EdgeClone<T>>> graph) {
this.graph = graph;
}
/**
* Adds a new node to the graph. If the node already exists then its a
* no-op.
*
* @param node Adds to a graph. If node is null then this is a no-op.
* @return true if node is added, false otherwise.
*/
public boolean addNode(NodeClone<T> node) {
if (node == null) {
throw new NullPointerException("The input node cannot be null.");
}
if (graph.containsKey(node)) return false;
graph.put(node, new ArrayList<EdgeClone<T>>());
return true;
}
/**
* Given the two nodes it would add an arc from source
* to destination node.
*
* @param node1 the node1 node.
* @param node2 the node2 node.
* @param length if length if string
* @throws NullPointerException if node1 or nod2 is null.
* @throws NoSuchElementException if either node1 or node2 does not exists.
*/
public void addEdge (NodeClone<T> node1, NodeClone<T> node2) {
if (node1 == null || node2 == null) {
throw new NullPointerException("node1 and node2, both should be non-null.");
}
if (!graph.containsKey(node1) || !graph.containsKey(node2)) {
throw new NoSuchElementException("node1 and node2, both should be part of graph");
}
final EdgeClone<T> edgeClone = new EdgeClone<T>(node1, node2);
graph.get(node1).add(edgeClone);
graph.get(node2).add(edgeClone);
}
/**
* Removes an edge from the graph.
*
* @param node1 If the first node.
* @param node2 If the second node.
* @throws NullPointerException if either node1 or node2 specified is null
* @throws NoSuchElementException if graph does not contain either node1 or node2
*/
public void removeEdge (NodeClone<T> node1, NodeClone<T> node2) {
if (node1 == null || node2 == null) {
throw new NullPointerException("node1 and node2, both should be non-null.");
}
if (!graph.containsKey(node1) || !graph.containsKey(node2)) {
throw new NoSuchElementException("node1 and node2, both should be part of graph");
}
graph.get(node1).remove(node2);
}
/**
* Given a node, returns the edges going outward that node,
* as an immutable map.
*
* @param node The node whose edges should be queried.
* @return An immutable view of the edges leaving that node.
* @throws NullPointerException If input node is null.
* @throws NoSuchElementException If node is not in graph.
*/
public List<EdgeClone<T>> edgesFrom(NodeClone<T> node) {
if (node == null) {
throw new NullPointerException("The node should not be null.");
}
List<EdgeClone<T>> edges = graph.get(node);
if (edges == null) {
throw new NoSuchElementException("node does not exist.");
}
return Collections.unmodifiableList(edges);
}
@Override
public Iterator<NodeClone<T>> iterator() {
return graph.keySet().iterator();
}
public CloneGraph<T> clone() {
final Map<NodeClone<T>, List<EdgeClone<T>>> clonedGraph = new HashMap<NodeClone<T>, List<EdgeClone<T>>>();
for (Entry<NodeClone<T>, List<EdgeClone<T>>> entry : this.graph.entrySet()) {
final NodeClone<T> node = entry.getKey();
final List<EdgeClone<T>> edgeList = entry.getValue();
clonedGraph.put(new NodeClone<T>(node.getItem()), new ArrayList<EdgeClone<T>>(edgeList));
}
return new CloneGraph<T>(clonedGraph);
}
public static void main(String[] args) {
CloneGraph<Integer> graph = new CloneGraph<Integer>();
NodeClone<Integer> nodeA = new NodeClone<Integer>(1);
NodeClone<Integer> nodeB = new NodeClone<Integer>(2);
NodeClone<Integer> nodeC = new NodeClone<Integer>(3);
graph.addNode(nodeA);
graph.addNode(nodeB);
graph.addNode(nodeC);
graph.addEdge(nodeA, nodeB);
graph.addEdge(nodeB, nodeC);
graph.addEdge(nodeA, nodeC);
CloneGraph<Integer> clonedGraph = graph.clone();
Iterator<NodeClone<Integer>> itr = clonedGraph.iterator();
while (itr.hasNext()) {
NodeClone<Integer> node = itr.next();
System.out.println("Item : " + node.getItem());
System.out.println("Edges: ");
for (EdgeClone<Integer> edge : clonedGraph.edgesFrom(node)) {
System.out.println(edge.getNode1().getItem() + " : " + edge.getNode2().getItem());
}
System.out.println();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T16:09:34.080",
"Id": "81162",
"Score": "0",
"body": "Can you describe in more detail what you are trying to do? It seems that you should not create any new classes, but just write a method to clone your original graph. But I'm not quite sure what you are trying to accomplish."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T19:15:29.977",
"Id": "81205",
"Score": "0",
"body": "toto2 I have done the same thing you suggested, but name of my class is very confusing."
}
] | [
{
"body": "<p>looking at it I came across what might be an issue. When you are cloning the graph you create new nodes, that is good. <strong>However</strong>, the edge objects stays the same so they are pointing to the old NodeClone objects. So this way they are actually pointing to the nodes in the \"old\" graph and not to the node in the new Graph. </p>\n\n<p>Another point that I was thinking about is if you might want to embed the \"clone\" feature into the nodes and edges itself. I would suggest couple changed to enable that. </p>\n\n<p>First of all I would add a list of outgoing edges to the NodeClone objects. The reason being is that I think it is more natural to enable the NodeClone itself to know the edges, not to keep this information in the map. Following this opinion, I would also add the incoming edges list. </p>\n\n<p>The counter argument is that you kind of duplicate the information but then you don't need any class Graph. When you insert a new edge or node you simply traverse the structure, which you need to do anyway otherwise you dont know what to connect to what, and \"append\" the node. </p>\n\n<p>That was about changes to the structure of the graph. After you have that than you could do the cloning method in the following manner. I am going to include direction in the graph because even though you said it is unidirectional but then you use a map and state that the edges are outgoing. Making it unidirectional is easy just look at both incoming and outgoing as same edges.</p>\n\n<pre><code>//In the class EdgeClone\npublic EdgeClone clone(){\n Node from = node1.clone(); //This could be used to introduce the direction in the graph\n Node to = node2.clone(); //for the direction of the edge\n EdgeClone edge = new EdgeClone(from, to);\n from.addOutgoing(edge);\n to.addIncoming(edge); \n}\n</code></pre>\n\n<p>For the NodeClone you could have something like this:</p>\n\n<pre><code>//In the class NodeClone\nprivate NodeClone copyOfMe; //instance variable to use during cloning\npublic NodeClone clone(){\n if ( this.copyOfMe != null ){ //This is recursion traversal break.\n return this.copyOfMe; //If throught the process of cloning the graph I get into the same node through different routes I will not clone it again but just return the prepared copy.\n } \n NodeClone copyOfMeLocal = new NodeClone(item); //Here it might be worth considering if you want need to clone the item as well\n this.copyOfMe = copyOfMeLocal;\n //both outgoing and incoming, because if you start in a node that has only incoming edges (a leaf node) nothing would get clones if you would not include here both incoming and outgoing edges.\n for(EdgeClone edge: myAllEdges){ \n edge.clone();\n }\n this.copyOfMe = null; //copying done, setting this to null \n return copyOfMeLocal; //returning valid copy \n}\n</code></pre>\n\n<p>The recursion break in NodeClone method should ensure that you dont get multiple copies of the originally same node when you run the cloning.</p>\n\n<p>This has the advantage that you can start cloning in any node. The disadvantage is that you cannot filter what gets cloned and what not, if you would desire to do so. Complexity should be O(E + V) since you traverse all nodes (V) plus all edges (E), just once.</p>\n\n<p>Hope I provided you with a helpful angle of how this problem could be handled. If you find any discrepancies in my code feel or have additional questions free to comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T19:12:26.083",
"Id": "81204",
"Score": "0",
"body": "However, the edge objects stays the same so they are pointing to the old NodeClone objects. - good catch"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-06T12:29:56.647",
"Id": "46451",
"ParentId": "46237",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T06:54:19.043",
"Id": "46237",
"Score": "3",
"Tags": [
"java",
"algorithm",
"graph"
],
"Title": "Clone an undirected graph"
} | 46237 |
<p>I have been trying to get as close to SRP in my code as possible. I have a situation where I need to log leads when interactions happen for a contact. A lead may be created or updated. There are three different states that I would like to set leads to.</p>
<ul>
<li>Active - new interested interactions causes active lead to be created</li>
<li>Converted - a existing lead is updated to converted if the product was purchased - this is managed with conversion flag</li>
<li>Stale - a existing lead is updated to stale if the contact is not interested</li>
</ul>
<p></p>
<pre><code>class LeadGeneration
def initialize contact_id, options={}
@lead = Lead.find_or_initialize_by(contact_id: contact_id)
options.reverse_merge!(conversion: false, interested:true)
@conversion = options[:conversion]
@interested = options[:interested]
end
def call
if conversion?
convert_lead
else
process_lead
end
end
private
def lead
@lead
end
def conversion?
@conversion
end
def interested?
@interested
end
def convert_lead
lead.converted! unless lead.new_record? # new leads cannot be saved as converted
end
def process_lead
if interested?
activate_lead
else
stale_lead
end
end
def activate_lead
lead.active!
end
def stale_lead
lead.stale! unless lead.new_record? # new leads cannot be saved as stale
end
end
</code></pre>
<p>Right now I feel like I should be splitting up converting a lead and managing stale/active states. I'm not really sure what to do and tests are a little confusing right now.</p>
| [] | [
{
"body": "<p>I'm not sure how you intend to use this class, but the <code>call</code> method is very fishy. This method seems to do one of three things: <code>convert_lead</code>, <code>activate_lead</code> or <code>stale_lead</code>. The choice of which of them should actually be executed is made in the <code>options</code> argument during object construction.</p>\n\n<p>This is not very easy to understand from reading the code, and I can't really see the reasoning behind it. Is it an implementation of a <a href=\"https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0CCoQFjAA&url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FCommand_pattern&ei=TW4-U-6tDur_ygP9u4JA&usg=AFQjCNG7Nqol9kI7bA4uJ_ZXTqCILKPhmA&sig2=zG775kJNDa1jmmy01wfHzQ&bvm=bv.64125504,d.bGQ\" rel=\"nofollow noreferrer\">Command pattern</a>? that is not very ruby-like.</p>\n\n<p>Since all this class actually does is quite basic delegation (<code>@lead.converted!</code>, <code>@lead.stale!</code> or <code>@lead.active!</code>) I would consider foregoing this class altogether, and simply doing the action. It is unnecessarily long and convoluted, and hides more than explains what it does.</p>\n\n<hr>\n\n<p>From your comment below I understand that <code>LeadGeneration</code> should be a <code>Service Object</code>. It is true that service objects may have a single method called <code>call</code>, as is suggested in this <a href=\"http://jamesgolick.com/2012/5/22/objectify-a-better-way-to-build-rails-applications.html\" rel=\"nofollow noreferrer\">blog post</a>:</p>\n\n<blockquote>\n <p>Service objects are responsible for retrieving and/or manipulating\n data — essentially any work that needs to be done that you might have\n put in a controller or model object before. They typically only have\n one method, which I like to define as “#call” (they're usually named\n something like PictureCreationService, so naming the method #create\n would seem redundant).</p>\n</blockquote>\n\n<p>But note, though, the <em>reason</em> a single method <code>call</code> is allowable - it is apparent from the <em>class name</em> <strong>exactly</strong> what the method should do.<br>\nIf your service object was called <code>LeadConversionService</code>, then a <code>call</code> method would be good enough.</p>\n\n<p>Being a service object, it is even more important than usual in ruby for the class to be small and transparent.</p>\n\n<p>If you want to go to the extreme SRP suggested in the quote above, you'd have three classes, each with <code>#call</code> and <code>#allowed?</code> methods:</p>\n\n<pre><code>class LeadConversionService\n def initialize(lead)\n @lead = lead\n end\n\n def call\n @lead.converted!\n end\n\n def allowed?\n !@lead.new_record?\n end\nend\n</code></pre>\n\n<p>OR, you could be a little less extreme, and decide the <code>LeadGeneration</code> (or maybe <code>LeadLifeCycleService</code>?) is a good enough scope, and let it have three method:</p>\n\n<pre><code>class LeadLifeCycleService\n def initialize(lead)\n @lead = lead\n end\n\n def convert!\n raise LifeCycleException if @lead.new_record?\n @lead.convert!\n end\n\n def activate!\n @lead.active!\n end\n\n def stale!\n raise LifeCycleException if @lead.new_record?\n @lead.stale!\n end\nend\n</code></pre>\n\n<p>Writing this solution makes it obvious again, that this service doesn't do much, since it only delegates (so it doesn't even save code in your model...). All it does is validates pre-conditions to your actions, which may be better handled by a state-machine, as <a href=\"https://codereview.stackexchange.com/q/46238/22648\">@Flambino suggested</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:22:39.033",
"Id": "80709",
"Score": "0",
"body": "It is a service object. I want to ensure that the logic regarding how leads are captured is stored within this service object. Otherwise I would need to pull it out into other objects. From my reading using 'call' is acceptable practice for calling service objects. I had all this logic in my models, but from my reading - it is bad practice to bloat your models with logic not related to basic CRUD. Abstractive it into it's own service object makes is much more testable. Sorry I should have said it is a service object in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:49:50.447",
"Id": "80717",
"Score": "0",
"body": "@Ryan-NealMes - updated my answer for service objects..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:17:29.340",
"Id": "80721",
"Score": "0",
"body": "Does exposing #allowed? pass the responsibility of knowing to check if a lead can be converted outside the responsibility of the service class? would I not do @lead.converted! if allowed? [Thanks for clearing up so much for me!]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:24:42.633",
"Id": "80723",
"Score": "0",
"body": "@Ryan-NealMes - The `#allowed?` method might be part of a _policy_, and not part of the _service_. The `@lead.converted! if allowed?` is not advisable, since it hides errors (as @Flambrino said). A better way would be to **raise an error** `unless allowed?`, or, at least expose a `boolean` as to whether the operation actually occurred."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:37:39.967",
"Id": "46241",
"ParentId": "46238",
"Score": "4"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/46241/14370\">Uri already had a good answer</a> suggesting different approaches. I'd roll this into the <code>Lead</code> model too, and treat it as a straight-up state machine.</p>\n\n<p>As far as I can tell, the states, in order, are:</p>\n\n<pre><code>Stale → Active (default) → Interested → Converted\n</code></pre>\n\n<p>Point being that you can't transition more than one step at a time (can't convert before being interested, can't be interested unless already active, etc.).</p>\n\n<p><a href=\"https://www.ruby-toolbox.com/categories/state_machines\" rel=\"nofollow noreferrer\">There are a number of state machine gems</a> you can use to your advantage. Many (most?) include a simple DSL allowing you do perform the state transitions, trigger other code when a certain transition happens, etc.</p>\n\n<p>Right now, you're passing either <code>interested</code> or <code>conversion</code> (or both?) to the initializer, which doesn't make sense without knowing the current state. The logic of your class hides all that, and doesn't provide much feedback (e.g. exceptions) if you attempt to do things \"out of step\" with the current state. For instance, if I pass <code>interested: false, conversion: true</code> what does that mean? Seems illogical. What if I pass <code>conversion: true</code> on a stale lead? These things make it confusing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:28:00.177",
"Id": "80712",
"Score": "0",
"body": "Interested and conversion are based off interactions the contact has with out application (you do not need to know the state of the lead). These interactions cause changes to the state in the lead. Eg if the interaction is not interested the lead if set to stale if it exists, if it doesn't exist no lead is captured. I pulled this out to a service object because it violates SRP if I put it into the lead or interaction models. If I put this stuff in my models I would have to use callbacks as well which is bad practice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:02:08.983",
"Id": "46244",
"ParentId": "46238",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46241",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T06:57:57.843",
"Id": "46238",
"Score": "2",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Logging leads when interactions happen for a contact"
} | 46238 |
<p>Here is my single parse code for splitting a <code>std::string</code> on a <code>char</code> into a <code>std::vector<std::string></code>:</p>
<pre><code>#include <iostream>
#include <vector>
std::vector<std::string> split_uri(std::string, unsigned chr='/');
int main() {
std::vector<std::string> uri_v = split_uri(uri, '/');
for (auto elem: uri_v)
std::cout << elem << std::endl;
}
std::vector<std::string> split_uri(std::string uri, unsigned chr) {
bool start=true;
std::string part;
std::vector<std::string> vec;
vec.reserve(uri.length()/2);
for(char c: uri) {
switch(c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
part += c;
break;
default:
if (c == chr) {
if (!start)
vec.push_back(part);
else start = false;
part.clear();
part += c;
}
else {
std::cerr << "Invalid URI; from: \'" << c << "\' (hex: " << std::hex << "0x" << (unsigned int)c << ")\n";
vec.clear();
return vec;
}
}
}
return vec;
}
</code></pre>
<p>What can I do to improve its efficiency?</p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:58:02.177",
"Id": "80694",
"Score": "0",
"body": "Your edit is invalid: `case chr:` won't work since `chr` is not a constant expression."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:58:23.620",
"Id": "80695",
"Score": "0",
"body": "Yeah; was just looking into `constexpr` for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:59:42.120",
"Id": "80696",
"Score": "0",
"body": "That won't work either. `case` only accepts integer and char literals, not generalized constant expressions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:02:39.790",
"Id": "80701",
"Score": "0",
"body": "Actually you can [create a hash table](http://stackoverflow.com/a/16388610/587021) of sorts at compile time using `constexpr` and a `switch`/`case`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:05:10.350",
"Id": "80704",
"Score": "0",
"body": "@AT Your `chr` can change at runtime anyway, so you won't be able to get your code to work with your current design."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:07:27.410",
"Id": "80705",
"Score": "0",
"body": "Okay; I'll just have to add an `if` conditional check to `default:`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:09:56.827",
"Id": "80706",
"Score": "0",
"body": "My bad for the `constexpr` stuff though. I really did think that such a thing wouldn't work. Gotta read the relevant part of the standard again..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:14:22.687",
"Id": "80720",
"Score": "0",
"body": "You should avoid passing std::string objects by-value. Instead, you can pass it in as a const reference to avoid a potentially expensive copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:19:47.227",
"Id": "80797",
"Score": "1",
"body": "PS: A URI is a bit more complex than that."
}
] | [
{
"body": "<p>First, consider passing potentially expensive-to-copy objects such as <code>std::string</code> as const reference rather than by-value. The obvious approach is to use <code>std::istringstream</code> and <code>std::getline</code>.</p>\n\n<pre><code>std::vector<std::string> split_uri(const std::string uri&, char chr)\n{\n std::istringstream iss(uri);\n std::vector<std::string> vec;\n\n for(std::string token; getline(iss, token, chr); )\n vec.push_back(token);\n\n return vec;\n}\n</code></pre>\n\n<p>With the input being <code>\\bar\\can</code>, the output is <code>{\"\", \"bar\", \"can\"}</code>.</p>\n\n<p>However, <code>std::istringstream</code> is not known for its speed. If you don't want to use <code>std::istringstream</code>, you don't have to. The following should be much faster:</p>\n\n<pre><code>std::vector<std::string> split_uri(const std::string& uri, char chr)\n{\n std::string::const_iterator first = uri.cbegin();\n std::string::const_iterator second = std::find(first+1, uri.cend(), chr);\n std::vector<std::string> vec;\n\n while(second != uri.cend())\n {\n vec.emplace_back(first, second);\n first = second;\n second = std::find(second+1, uri.cend(), chr);\n }\n\n vec.emplace_back(first, uri.cend());\n\n return vec;\n}\n</code></pre>\n\n<p>With the input being <code>\\bar\\can</code>, the output is <code>{\"\\bar\", \"\\can\"}</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:23:55.463",
"Id": "80710",
"Score": "0",
"body": "That's much more concise; and skips the string concatenation overhead. Is it more efficient overall?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:29:23.560",
"Id": "80713",
"Score": "0",
"body": "@mrm That's indeed way more concise. However, I tried to benchmark that with `g++ -O3` and it seems 1.5 times slower than the first version. It was even 2.5 times slower with `clang++ -O3`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:23:44.927",
"Id": "80722",
"Score": "0",
"body": "@mrm Ok, that second version is like two to three times faster than the OP one on both compilers. It's even faster if you replace `push_back(std::string(...))` by `emplace_back(...)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:36:40.263",
"Id": "80724",
"Score": "0",
"body": "@Morwenn Cool! And yeah, of course. Let's do `emplace_back` too :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T08:41:08.380",
"Id": "81685",
"Score": "0",
"body": "Great; thanks. I've used your second one with a slight edit (`for` rather than `while`)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:17:53.250",
"Id": "46245",
"ParentId": "46242",
"Score": "4"
}
},
{
"body": "<p>I would have done:</p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n#include <vector>\n#include <iterator>\n#include <algorithm>\n</code></pre>\n\n<h3>The Work</h3>\n\n<pre><code>// A generic routine to split a string into pieces and put\n// them into an array. The array is then returned (not expensive\n// because of RVO).\n//\n// The Splitter merely needs to be convertible to the type Return\n// and can be used with `operator>>` so you can read it from a stream.\n// \n// In a user defined type this means:\n// 1) defining a cast operator\n// operator Return () const {return <A Return Type>;}\n//\n// 2) defining operator>> as a function\n// that takes the class as a second parameter and reads \n// it from the stream.\n//\n// Note: But it can be used by any types (not just custom types)\n// std::vector<int> data1(splitString<int>(\"1 2 3 4 5 6\"));\n// std::vector<std::string> data2(splitString<std::string>(\"A word per item\"));\n// \ntemplate<typename Result, typename Spliter = Result>\nstd::vector<Result> splitString(std::stringstream input)\n{\n typedef std::istream_iterator<Spliter> Iterator;\n return std::vector<Result>(Iterator(input), Iterator());\n}\n</code></pre>\n\n<h3>Simple Utility class as an example</h3>\n\n<pre><code>// A simple class that reads `split` separated string objects \n// from a stream. This is a simple utility class that works well\n// with std::istream_iterator.\n// \ntemplate<char split>\nstruct Part\n{\n std::string part;\n operator std::string const& () const {return part;}\n friend std::istream& operator>>(std::istream& s, Part& data)\n {\n // This is a simple example.\n // It does not duplicate the functionality of the code\n // provided by the OP. But this is where it would go.\n\n return std::getline(s, data.part, split);\n }\n};\n</code></pre>\n\n<h3>Put it all together</h3>\n\n<pre><code>int main()\n{\n std::string str(\"Part1/Part2/Part3/Part4\");\n std::vector<std::string> data(splitString<std::string, Part<'/'>>(str));\n\n std::copy(std::begin(data), std::end(data), std::ostream_iterator<std::string>(std::cout, \"\\n\"));\n\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:11:05.143",
"Id": "46283",
"ParentId": "46242",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "46245",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T08:47:47.797",
"Id": "46242",
"Score": "2",
"Tags": [
"c++",
"performance",
"memory-management",
"vectors",
"cyclomatic-complexity"
],
"Title": "split string into container on char; efficiently?"
} | 46242 |
<p>I want to split a list using another list which contains the lengths of each split.</p>
<p>E.g:</p>
<pre class="lang-py prettyprint-override"><code>>>> print list(split_by_lengths(list('abcdefg'), [2,1]))
... [['a', 'b'], ['c'], ['d', 'e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [2,2]))
... [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [2,2,6]))
... [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [1,10]))
... [['a'], ['b', 'c', 'd', 'e', 'f', 'g']]
>>> print list(split_by_lengths(list('abcdefg'), [2,2,6,5]))
... [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]
</code></pre>
<p>As you can notice, if the lengths list does not cover all the list I append the remaining elements as an additional sublist. Also, I want to avoid empty lists at the end in the cases that the lengths list produces more elements that are in the list to split.</p>
<p>I already have a function that works as I want:</p>
<pre class="lang-py prettyprint-override"><code>def take(n, iterable):
"Return first n items of the iterable as a list"
return list(islice(iterable, n))
def split_by_lengths(list_, lens):
li = iter(list_)
for l in lens:
elems = take(l,li)
if not elems:
break
yield elems
else:
remaining = list(li)
if remaining:
yield remaining
</code></pre>
<p>But I wonder if there is a more pythonic way to write a function such that one.</p>
<p><em>Note:</em> I grabbed <code>take(n, iterable)</code> from <a href="https://docs.python.org/2/library/itertools.html#recipes" rel="nofollow noreferrer">Itertools Recipes</a></p>
<p><em>Note:</em> This question is a repost from a <a href="https://stackoverflow.com/posts/22857572/">stackoverflow question</a></p>
| [] | [
{
"body": "<p>You can do it by just slicing the sequence — there's really no advantage to having a helper function like<code>take()</code>. I also added a keyword argument to make the returning of anything remaining optional.</p>\n\n<pre><code>def split_by_lengths(sequence, lengths, remainder=True):\n last, SequenceLength = 0, len(sequence)\n for length in lengths:\n if last >= SequenceLength: return # avoid empty lists\n adjacent = last + length\n yield sequence[last:adjacent]\n last = adjacent\n if last < SequenceLength and remainder:\n yield sequence[last:]\n\nprint list(split_by_lengths(list('abcdefg'), [2, 1]))\n# [['a', 'b'], ['c'], ['d', 'e', 'f', 'g']]\nprint list(split_by_lengths(list('abcdefg'), [2, 2]))\n# [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]\nprint list(split_by_lengths(list('abcdefg'), [2, 2, 6]))\n# [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]\nprint list(split_by_lengths(list('abcdefg'), [1, 10]))\n# [['a'], ['b', 'c', 'd', 'e', 'f', 'g']]\nprint list(split_by_lengths(list('abcdefg'), [2, 2, 6, 5]))\n# [['a', 'b'], ['c', 'd'], ['e', 'f', 'g']]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:45:14.693",
"Id": "46247",
"ParentId": "46246",
"Score": "3"
}
},
{
"body": "<p>This is my first <a href=\"https://stackoverflow.com/a/22857694/846892\">answer</a> that I gave on stackoverflow:</p>\n\n<pre><code>from itertools import islice\n\ndef split_by_lengths(seq, num):\n it = iter(seq)\n for n in num:\n out = list(islice(it, n))\n if out:\n yield out\n else:\n return #StopIteration \n remain = list(it)\n if remain:\n yield remain\n</code></pre>\n\n<p>Here I am not using a for-else loop because we can end the generator by using a simple <code>return</code> statement. And IMO there's no need to define an extra <code>take</code> function just to slice an iterator.</p>\n\n<p><strong>Second answer:</strong></p>\n\n<p>This one is slightly different from the first one because this won't <strong>short-circuit</strong> as soon as one of the length exhausts the iterator. But it is more compact compared to my first answer.</p>\n\n<pre><code>def split_by_lengths(seq, num):\n it = iter(seq)\n out = [x for x in (list(islice(it, n)) for n in num) if x]\n remain = list(it)\n return out if not remain else out + [remain]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:39:58.947",
"Id": "80725",
"Score": "0",
"body": "Agreed that `take(n, iterable)` is not necessary."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:03:03.260",
"Id": "46249",
"ParentId": "46246",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46249",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:39:54.243",
"Id": "46246",
"Score": "8",
"Tags": [
"python"
],
"Title": "Split a list using another list whose items are the split lengths"
} | 46246 |
<p>I am working on some code and I have come across the following:</p>
<pre><code>private int getPosition() {
List<IDescriptor> fragmentDescriptors = new ArrayList<IDescriptor>(mDescriptors);
int position = -1;
for (IDescriptor fragmentDescriptor : fragmentDescriptors) {
if (fragmentDescriptor instanceof VideoDescriptor) {
position = fragmentDescriptors.indexOf(fragmentDescriptor);
}
}
return position;
}
</code></pre>
<p>In a situation like this, how can one find an index of a specific implementation within a list without using <code>instanceOf</code>?</p>
<p><strong>Update:</strong>
Few points: <code>mDesciptors</code> is a set. The point of the question was: The set of <code>IDescriptor</code> is injected into the class, the class has no idea what the set will contain, it does however know there maybe a <code>IDescriptor</code> that is meant for video.. the problem is the current method relies on <code>VideoDescriptor</code>, therefore if that implementation changes, the position will no longer be found.</p>
<p>I'd like a general review of this. The method was really just to demonstrate the dependency on <code>VideoDescriptor</code>. </p>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:10:34.730",
"Id": "80740",
"Score": "1",
"body": "What kind of changes are you afraid of? If the name of the class changes, how do you think you will be able to identify this (or any other relevant) class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:24:37.177",
"Id": "80745",
"Score": "2",
"body": "btw, if the `mDescriptors` is a `Set`, what's the meaning of `getPosition()`? A `Set` is not ordered..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:35:29.447",
"Id": "80749",
"Score": "0",
"body": "LinkedHashSet.. is ordered"
}
] | [
{
"body": "<p>Are you asking if you can find the first element in a list of a certain type without asking for its type? That's a strange question... What's wrong with <code>instanceof</code>?</p>\n\n<p>As for the code, being code-review, I've got some observations:</p>\n\n<p>This code actually finds the <em>last</em> instance of type <code>VideoDescriptor</code> in <code>mDescriptor</code>. It is also very inefficient, since it iterates over the collection <strong>at least three times</strong> to find it </p>\n\n<ul>\n<li>It wrap it in an <code>ArrayList</code>, </li>\n<li>It finds <em>all</em> items of the right type (no stop condition here - so it iterates over the whole array)</li>\n<li>For each item of the correct type, it iterates over the array <em>again</em> using <code>indexOf</code></li>\n</ul>\n\n<p>(perhaps you are asking about <code>indexOf</code> and not <code>instanceOf</code>?)</p>\n\n<p>A better way would be to simply iterate once over the collection, keeping the current position, returning upon reaching the correct type:</p>\n\n<pre><code>private int getPosition() { \n int position = -1;\n\n for (IDescriptor fragmentDescriptor : mDesciptors) {\n position++;\n if (fragmentDescriptor instanceof VideoDescriptor) {\n return position;\n }\n }\n\n return -1;\n}\n</code></pre>\n\n<p>if the collection has random access, you can use a classic <code>for</code> loop:</p>\n\n<pre><code>private int getPosition() { \n for (int i = 0; i < mDescriptors.size(); i++) {\n if (mDescriptors.get(i) instanceof VideoDescriptor) {\n return i;\n }\n }\n\n return -1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:57:09.727",
"Id": "80735",
"Score": "0",
"body": "I have updated the question, as it wasn't very clear."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:45:43.513",
"Id": "46251",
"ParentId": "46248",
"Score": "3"
}
},
{
"body": "<p>I totally agree with Uri and have some further comments:</p>\n\n<blockquote>\n <p>the class has no idea what the set will contain, it does however know there maybe a IDescriptor that is meant for video..</p>\n</blockquote>\n\n<p>I'm sorry, but I have to ask: If you're not sure about exactly what the Set contains, why are you storing it in a set in the first place?</p>\n\n<p>Consider instead something like <code>Map<KEY_TYPE, List<? extends IDescriptor>> descriptors;</code> where <code>KEY_TYPE</code> can be a <code>Class<? extends IDescriptor></code>, a <code>String</code>, or something else that can tell you what type it is.</p>\n\n<p>When adding items to this map you could use:</p>\n\n<pre><code>List<? extends IDescriptor> list = descriptors.get(descriptor.getClass());\nif (list == null) {\n list = new ArrayList<>();\n descriptors.put(descriptor.getClass(), list);\n}\nlist.add(descriptor);\n</code></pre>\n\n<p>And then all you would need to do is to use <code>descriptors.get(VideoDescriptor.class)</code> (assuming <code>VideoDescriptor</code> is not subclassed, otherwise you could loop through the supertypes as well when adding to the list).</p>\n\n<hr>\n\n<p>Another thought is that you can use a <code>enum</code> to describe what kind of <code>IDescriptor</code> it is, and the <code>IDescriptor</code> type can have a <code>getDescriptorType</code> method. Then you could check <code>if (fragmentDescriptor.getDescriptorType() == DescriptorType.VIDEO)</code></p>\n\n<p>As I only see a portion of your code and not the big picture, I can't really tell what would be best for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:20:00.623",
"Id": "46263",
"ParentId": "46248",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "46263",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T09:51:35.407",
"Id": "46248",
"Score": "2",
"Tags": [
"java",
"design-patterns"
],
"Title": "Avoiding instanceOf when finding index of an interface within a list"
} | 46248 |
<p>I'm using an API which returns text in the following format:</p>
<pre><code>#start
#p 09060 20131010
#p 09180 AK
#p 01001 19110212982
#end
#start
#p 09060 20131110
#p 09180 AB
#p 01001 12110212982
#end
</code></pre>
<p>I'm converting this to a list of objects:</p>
<pre><code>var result = data.match(/#start[\s\S]+?#end/ig).map(function(v){
var lines = v.split('\n'),
ret = {};
$.each(lines, function(_, v2){
var split = v2.split(' ');
if(split[1] && split[2])
ret[split[1]] = split[2];
});
return ret;
});
</code></pre>
<p>My concern is that the API returns quite a lot of data, therefore I would like some feedback regarding on how to improve the performance.</p>
<p>For instance, is there any way to reduce the mapping complexity from O(N<sup>2</sup>) to O(N)?</p>
<p>Also, please suggest regex improvements :)</p>
| [] | [
{
"body": "<p>If you use regular expressions for parsing, then I would recommend using them for everything. Here's a solution that proceeds line by line, using capturing parentheses to see what the line contained.</p>\n\n<pre><code>function parse(data) {\n var re = /(#start)|(#end)|#p\\s+(\\S+)\\s+(\\S+)/ig;\n var results = [], match, obj;\n while (match = re.exec(data)) {\n if (match[1]) { // #start\n obj = {};\n\n } else if (match[2]) { // #end\n results.push(obj);\n obj = null; // ← Prevent accidental reuse if input is malformed\n\n } else { // #p something something\n obj[match[3]] = match[4];\n }\n }\n return results;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T15:53:33.243",
"Id": "81767",
"Score": "0",
"body": "Followup question: If a line looks like `#p 09180` instead of `#p 09180 AK`, I get `#p` in `match[4]`. I've played around a bit with the regex but I can't get it right. Could you please help me adjust it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:29:52.320",
"Id": "81771",
"Score": "1",
"body": "Changing the regular expression to `/(#start)|(#end)|#p\\s+(\\S+)\\s*(\\S*)/ig` would let the third field be optionally empty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:36:58.767",
"Id": "81773",
"Score": "0",
"body": "Oh, nice, thanks. A final question which might be a bit trickier: Is there any way to allow the last group to contain spaces e.g. `#p 09180 AK` could also be `#p 09180 AK 2` or `#p 09180 AK B 2` where I would like to catch `AK 2` and `AK B 2`. I guess you could say that anything between the third match and each line break would be the value I'm looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T16:44:26.953",
"Id": "81775",
"Score": "0",
"body": "I know that I can do something like `(\\S*\\s*\\S*)`, but can it be more generic?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T17:27:20.187",
"Id": "81786",
"Score": "1",
"body": "Changing the regular expression to `/(#start)|(#end)|#p\\s+(\\S+)\\s*(.*)/ig` would let the third field contain anything, including an empty string or a string containing spaces."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:47:25.400",
"Id": "46259",
"ParentId": "46250",
"Score": "3"
}
},
{
"body": "<p>I dislike regexes with a passion ;) Especially because sometimes they beat solutions that ought to be faster.</p>\n\n<p>I would counter propose a solution where you keep using <code>indexOf</code> while keeping track where you are in the data. This way you only go thru the data once. I would also name your constants <code>0</code> and <code>1</code> so that the reader instinctively knows what you are doing. Furthermore, given that your script is horizontally quite short, I would spell out your variables. I am not a big fan of <code>v</code>, <code>v2</code> , <code>_</code> etc. Finally, if speed is important, then good old loops will always beat <code>forEach</code>.</p>\n\n<pre><code>function parseResults( data )\n{\n var index = -1,\n lastIndex = -1,\n objects = [],\n object,\n line,\n parts,\n KEY = 0,\n VALUE = 1;\n //~ is a short circuit for comparing to -1\n while( ~ (index = data.indexOf('\\n',index) ) )\n {\n line = data.substring( lastIndex , index );\n if( line == '#start')\n object = {};\n else if( line == '#end' )\n objects.push( object );\n else \n {\n parts = line.split(' ');\n if( parts[KEY] && parts[VALUE] )\n object[ parts[KEY] ] = parts[VALUE];\n }\n //+1 because I dont want to do ++ in the while, another +1 to make substring work\n //admittedly not very elegant looking :\\\n lastIndex = index + 2;\n }\n return objects;\n}\n</code></pre>\n\n<p>I would be most curious if you run this version and you run the 200_success version which one would be more performing with large sets of data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:03:22.430",
"Id": "80790",
"Score": "0",
"body": "Thank you for an alternative solution. Yes, regex is always my very last resort. I _think_ this will be slower than @200's version due to the use of `indexOf`. Regarding `index++ + 1`; why not do `index += 2`? I only have dummy data to test with at the moment, but I'll try to remember to post some performance results here once I get some real data to play around with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:50:40.710",
"Id": "80800",
"Score": "0",
"body": "for ++ +1, because I am an idiot ;) Also, for indexOf because of the startPosition, I am not convinced yet that it will be slower"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T15:52:51.107",
"Id": "80801",
"Score": "0",
"body": "Hehe, well I'll try to remember to post the results ;) Thanks again"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-09T18:16:19.057",
"Id": "81794",
"Score": "1",
"body": "Hi! Just FYI; I would say that the performance difference was neglectable (+- a few ms)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T14:44:09.527",
"Id": "46280",
"ParentId": "46250",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "46259",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T10:32:28.727",
"Id": "46250",
"Score": "6",
"Tags": [
"javascript",
"performance",
"jquery",
"parsing",
"regex"
],
"Title": "Performance tuning on a text file to object conversion"
} | 46250 |
<p>I've been following along a blog post on <a href="http://www.2ality.com/2012/01/js-inheritance-by-example.html" rel="nofollow noreferrer">JavaScript inheritance</a>. I wanted to slightly adapt this and try to write something more like I've seen in Backbone (extend method). See I set about it, and run into problems. Then I came across this <a href="https://stackoverflow.com/questions/10430279/javascript-object-extending">SO post</a>. It was so much simpler. So after some minor tweaks to that I set about writing a way each extended constructor could have their own extend method (inherited from Base). This is what I have:</p>
<pre><code>var Base = function(name){
this.name = name;
}
Base.prototype.extend = function(new_constructor){
//new_constructor.prototype = new this.constructor();
new_constructor.prototype = Object.create(this.constructor.prototype);
new_constructor.prototype.constructor = new_constructor;
return new_constructor;
}
var Robot = Base.prototype.extend(function(name, material){
Base.call(this, name)
this.material = material
this.type = 'robot';
});
var T1000 = Robot.prototype.extend(function(options){
Robot.call(this, options.name, options.material)
this.guns = options.guns;
this.type = 'killer robot';
});
robot = new Robot("Boutros", "metal");
t1000 = new T1000({name: "Arnie", material:"flesh/metal", guns:3});
console.log(robot)
console.log(t1000)
</code></pre>
<p>Anyway seems to work, but I'm a little new to this. Can anyone suggest any limitations with this approach. Also, I'd like to move the <code>[Constructor].call</code> out of the new constructor function and into the extend function so this is handled automatically, not sure if I can. Would appreciate your feedback.</p>
<p>Btw, here is my <a href="http://jsfiddle.net/bizt/Y9bL9/1/" rel="nofollow noreferrer">jsFiddle</a></p>
| [] | [
{
"body": "<p>I think you cannot move parent constructor call out of child constructor. At least because you have different parameters, extend function cannot guess what kind of parameters it should pass.</p>\n\n<p>But even if you standardize all constructors, you will have to make a \"smart\" constructor in Base class, that know about possible \"sub-constructors\". I don't think its a good idea ))</p>\n\n<p>But what i would do - remove any mention of parent-class from children constructors'.</p>\n\n<pre><code>var Base = function(name){\n this.name = name;\n}\nBase.prototype.extend = function(new_constructor){\n //new_constructor.prototype = new this.constructor();\n new_constructor.prototype = Object.create(this.constructor.prototype);\n new_constructor.prototype.constructor = new_constructor;\n new_constructor.prototype.parentConstructor = this.constructor;\n\n return new_constructor;\n}\n\nvar Robot = Base.prototype.extend(function(name, material){\n Robot.prototype.parentConstructor.call(this, name)\n this.material = material\n this.type = 'robot';\n});\n\nvar T1000 = Robot.prototype.extend(function(options){\n T1000.prototype.parentConstructor.call(this, options.name, options.material)\n this.guns = options.guns;\n this.type = 'killer robot';\n});\n\nrobot = new Robot(\"Boutros\", \"metal\");\nt1000 = new T1000({name: \"Arnie\", material:\"flesh/metal\", guns:3});\n\nconsole.log(robot)\nconsole.log(t1000)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T10:43:19.910",
"Id": "46535",
"ParentId": "46254",
"Score": "2"
}
},
{
"body": "<p>I usually evaluate OO frameworks by asking 4 questions:</p>\n\n<ul>\n<li>Does <code>instanceof</code> still work ? -> Yes, good</li>\n<li>Do you introduce new properties causing potential naming clashes -> No, good</li>\n<li>Can parameters easily be provided to the constructors -> Yes, good</li>\n<li>Can I easily have properties in <code>.prototype</code> -> Yes, good</li>\n</ul>\n\n<p>This is one of the better OO approaches I have seen on CodeReview.</p>\n\n<p>I would not create a new custom property <code>parentConstructor</code> the parent constructor call, instead I would want to try to build a closure that calls both the parent constructor and the passed constructor. This means you would need to have deep thoughts about parameters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T12:23:20.083",
"Id": "46545",
"ParentId": "46254",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:22:02.007",
"Id": "46254",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Good way to write extend method of a contructor?"
} | 46254 |
<pre><code>import java.util.Collections;//for frequency of words
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Arrays;
/**
Output--In phrase count duplicate substrings or strings or with space
psuedo code---
1.splt phrase by particular length
get list of each particular splited length word
for each word in list
for each word count if its count> 1 after having counted at least one, remove duplicates from List
getword and its frequency
2.split phrase with space then get frequency of words
3.splt phrase by particular length space included
then get frequency of words
*/
public class DuplicateSubString {
//@SuppressWarnings("unchecked")
public static void main(String[] args) {
// String phrase = "a r b k c d se f g a d f s s f d s ft gh f ws w f v x s g h d h j j k f sd j e wed a d f";
//String phrase ="How do you do in How";
String phrase ="How do you do in Howdy How";
Scanner sc = new Scanner( System.in );
System.out.println( "Please enter how many characters of grouping between 0 to 5" );
int splitleng=splitleng = sc.nextInt();
if(splitleng>0){
int string_to_test=1;
System.out.println( "Please enter type 1 for with space or else without space " );
string_to_test=sc.nextInt();
if(string_to_test==1){
System.out.println( "split with specified group of characters space included");
getListwithFreq(listOfWords( phrase,splitleng));
}else{
System.out.println( "split phrase with space & check also in substring for repition");
getListwithFreq(wordRepitionList( phrase, splitleng));
}
}else{
System.out.println( "space split and get frequency of words");
getListwithFreq(wordRepitionList( phrase));
}
System.out.println("Phrase is ---"+ phrase);
}
//phrase splited by particular length include space
private static List<String> listOfWords(String phrase,int splitleng ){
int k=phrase.length();
ArrayList< String > wordlist = new ArrayList< String >();
for(int l=0;l<=k-splitleng;l++){
String s4=(phrase.substring(l,l+splitleng));
//System.out.println("s4["+l+"]"+s4 );
wordlist.add(s4);
}
return wordlist;
}
//pass list of word which is splited by particular length include space
private static void getListwithFreq(List<String> items){
int count = 0;
//System.out.println("test 111");
Map<String,Integer> wordsWithCountHMap=new HashMap<String,Integer>();
for( int i = 0; i < items.size(); i++ )
{
//System.out.printf( "item: %s ", items.get( i ) );
for( int j = 0; j < items.size(); j++ )
{
//System.out.println( " items.size() "+items.size()+" items of j "+j+" is "+items.get( j ) );
if( items.get( i ).equals( items.get( j ) ) ){
count++;
//System.out.println("i "+i+" j "+j +" count "+count);
}
if( items.get( i ).equals( items.get( j ) ) && count > 1 ){
items.remove( j ); // after having counted at least one, remove duplicates from List
//System.out.println("in both i "+i+" j "+j +" count "+count);
}
}
//System.out.printf( " count %d\n", count );
//same above frequency of words we can get by {count=Collections.frequency(items, word)}
wordsWithCountHMap.put(items.get( i ),count);
count = 0;
}
printMap(wordsWithCountHMap);
}
public static void printMap(Map<String, Integer> map){
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
}
private static List<String> wordRepitionList(String phrase){
//System.out.println("word list break with space ");
String[] wordlist=phrase.split(" ");
//List<String> list = Arrays.asList(wordlist); Arrays will not suport remove for list and gives unsuportedexception
List<String> list=new ArrayList<String>();
for(String word:wordlist)
list.add(word);
//System.out.println("test ");
return list;
}
//get list of all duplicate in SubStrings and duplicates in string too
private static List<String> wordRepitionList(String phrase,int splitleng){
String[] wordlist=phrase.split(" ");
List<String> listSubStringInWord=new ArrayList<String>();
int m=0;
for(String word:wordlist){
int k=word.length();
if(k>splitleng){//subtring duplicates
for(int l=0;l<=k-splitleng;l++){
String s4=(word.substring(l,l+splitleng));
int getfromcurrentm=listSubStringInWord.size();
listSubStringInWord.add(s4);
}
}else{
listSubStringInWord.add(word);
}
}
return listSubStringInWord;
}
}//class
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T11:54:49.173",
"Id": "82098",
"Score": "0",
"body": "Please see this meta-post about [appropriate ways to edit your post after it has been reviewed](http://meta.codereview.stackexchange.com/questions/1482/can-i-edit-my-own-question-to-include-suggested-changes-from-answers). Thanks. I have rolled back your edits so that the current answers stay valid."
}
] | [
{
"body": "<h1>Spaces</h1>\n<p>I see many code segments like this:</p>\n<pre><code>splitleng>0\nstring_to_test=1\nstring_to_test=sc.nextInt()\n</code></pre>\n<p>Put spaces between your two expressions to result in this:</p>\n<pre><code>splitleng > 0\nstring_to_test = 1\nstring_to_test = sc.nextInt()\n</code></pre>\n<p>I consider the latter a lot more readable.</p>\n<p>As a sidenote (but this is a matter of preference): I'm not a fan of adding spaces inside brackets like here:</p>\n<pre><code>getListwithFreq(wordRepitionList( phrase, splitleng));\n</code></pre>\n<p>That space doesn't add any readability and it is very inconsistently used in your code. I prefer this:</p>\n<pre><code>getListwithFreq(wordRepitionList(phrase, splitleng));\n</code></pre>\n<p>Even more about spaces: consider the following method declaration:</p>\n<pre><code>private static List<String> listOfWords(String phrase,int splitleng ){\n</code></pre>\n<p>Can you spot the 3 comments I will make about spacing?</p>\n<h1>Naming</h1>\n<p>Keep naming conventions in mind. A method should be in the form of <code><verb><subject></code> with an obvious example for a getter: <code>getFirstName()</code>. At first glance I can immediately say what this method will do: it will return me data and I know what data.</p>\n<p>Will I know what it does when its name is <code>listOfWords()</code>? Using <code>get-</code> and <code>set-</code> prefixes are very common and you should try to use them wherever applicable.</p>\n<p>Same goes for capitalization! In Java, we use <code>lowerCamelCase</code> for our methods. This means that</p>\n<pre><code>getListwithFreq\n</code></pre>\n<p>becomes</p>\n<pre><code>getListWithFreq\n</code></pre>\n<p>Aside from that: write the entire word, don't shorten it. <code>Freq</code> should become <code>Frequency</code>. Also try to make your name more descriptive: right now it seems as if your method will take 2 arguments, a list and a frequency. This is not reflected in your method's actual signature.</p>\n<p>Another note: your class is named <code>DuplicateSubString</code>. This bears no meaning in itself and thus I would suggest something that actually describes what it does: <code>DuplicateSubStringFinder</code>.</p>\n<h1>Encapsulation</h1>\n<p>Encapsulation exists in many forms but in the end they all have one thing in common: hide implementationd details.</p>\n<p>You have a variable named <code>wordsWithCountHMap</code>. What if you decide to use a <code>TreeMap</code> later on? Now you'll have to change the name of this variable! That's unacceptable, programmers are supposed to be lazy. Hide the actual implementation details by simply not putting it in the name (you're not having your <code>firstName</code> declared as <code>firstNameString</code> either).</p>\n<h1>Declaration</h1>\n<p>This code</p>\n<pre><code>ArrayList< String > wordlist = new ArrayList< String >();\n</code></pre>\n<p>Can be abbreviated to (notice the name- and spacingchanges)</p>\n<pre><code>List<String> wordList = new ArrayList<>();\n</code></pre>\n<p>Assuming you use at least Java 7. For more information on this style, read <a href=\"https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface\">this post</a>.</p>\n<p>You're already partially doing this here</p>\n<pre><code>Map<String,Integer> wordsWithCountHMap=new HashMap<String,Integer>();\n</code></pre>\n<p>so this can be turned just as well into</p>\n<pre><code>Map<String,Integer> wordsWithCountHMap = new HashMap<>();\n</code></pre>\n<h1>Keep to your own</h1>\n<p>Your method <code>printMap</code> is declared as <code>public</code> but should only get called from inside your current class. Make it <code>private</code> instead.</p>\n<h1>Static</h1>\n<p>All your methods are declared as <code>static</code> so they can directly be accessed from your <code>main</code> method. While it seems easier, it's also useless and curses at OO programming.</p>\n<p>Instead, make them all instance methods (aka: remove the <code>static</code> modifier) and create an instance of <code>DuplicateSubString</code> instead. Now you can work with this class and it's a lot more OO-oriented.</p>\n<h1>Conclusion</h1>\n<p>All together you have many recurring code issues but because many of them can be categorized in the same aspects you will find it easy to pull your game to the next level if you adapt just a few changes.</p>\n<p>Your code will become a lot easier to read and interpret by adding some spacing and choosing clearer names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T03:00:50.380",
"Id": "81254",
"Score": "0",
"body": "Please let me know for anymore improvements @jeroen-vannevel"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-07T18:57:16.667",
"Id": "81409",
"Score": "0",
"body": "@user2628716: please rollback your post and create a new one with the new situation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:34:14.263",
"Id": "82413",
"Score": "0",
"body": "how to rollback"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T14:37:15.200",
"Id": "82414",
"Score": "0",
"body": "It's okay, a moderator has already done it for you. If you have a new question, simply create a new post."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T13:58:11.057",
"Id": "46274",
"ParentId": "46257",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:32:19.810",
"Id": "46257",
"Score": "4",
"Tags": [
"java",
"strings"
],
"Title": "Word duplicate finder and counter"
} | 46257 |
<p>I made a command line Hacker News reader in Ruby that pulls the latest 10 stories from HN and allows the user to cycle through them or open them with Launchy. This was to play around with Ruby and APIs.</p>
<p>The data that I pulled from HN was messy, like an array of hashes with arrays and hashes inside. I feel like my code is messy, and I am unsure of how it can be made cleaner.</p>
<p>Any advice? I'm still a begninner.</p>
<p>news.rb --</p>
<pre><code>class News
def initialize title, url, author
@title = title
@url = url
@author = author
end
# Format display of each story.
def to_s
"\n\tTitle: #{@title}\n
\tAuthor: #{@author}\n
\tUrl: #{@url}\n\n"
end
# Insert current object's url into a variable accessible by Launchy
def get_url
@url
end
end
# Show the news story, and ask if user wants open link or move on.
def show_story
puts @stories[@counter]
@link = @stories[@counter].get_url
puts "To view this story in your browser, type OPEN\n
To see the next story, type NEXT"
@start = gets.chomp.downcase
shuffle
end
# Determine if user wants to open link or move on.
def shuffle
if @start == "open"
Launchy.open(@link)
next_story
elsif @start == "next"
@counter += 1
show_story
else
puts "Sorry, you didn't type a correct command.\n
To view this story in your browser, type OPEN\n
To see the next story, type NEXT"
@start = gets.chomp.downcase
shuffle
end
end
# After opening link, ask if user still wants to see next story
def next_story
puts "Would you still like to see the next story? Type NEXT"
@start = gets.chomp.downcase
shuffle
end
</code></pre>
<p>runner.rb --</p>
<pre><code>require 'json'
require 'rest-client'
require 'launchy'
require_relative 'news.rb'
# Pull the latest/top 10 stories from Hacker News
data = RestClient.get('http://api.thriftdb.com/api.hnsearch.com/items/_search?limit=10&sortby=product(points,pow(2,div(div(ms(create_ts,NOW),3600000),72)))%20desc&pretty_print=true')
# Parse using JSON
parsed = JSON.parse data
# Take out the everything not under "Results" key
results = parsed.reject { |key, value| key != "results"}
# Create array and slap the value of "Results" into it
pull_items = []
pull_items = results["results"].each do |items|
pull_items << items
end
# Create an array and make each "Item" into its own item
pull_info = []
pull_items.each do |x|
pull_info << x["item"]
end
# Create a new object for each news story
@stories = pull_info.map do |s|
News.new s["title"], s["url"], s["username"]
end
# Logo and Welcome Message
puts <<STRING
_ _ _ _ _
| | | | | | | \\ | |
| |_| | __ _ ___| | _____ _ __ | \\| | _____ _____
| _ |/ _` |/ __| |/ / _ | '__| | . ` |/ _ \\ \\ /\\ / / __|
| | | | (_| | (__| | __| | | |\\ | __/\\ V V /\\__ \
\\_| |_/\\__,_|\\___|_|\\_\\___|_| \\_| \\_/\\___| \\_/\\_/ |___/
Welcome to Hacker News... from the Command Line!
STRING
# View the first story
puts "\nTo see the latest post, press any key"
start = gets
@counter = 0
show_story
</code></pre>
| [] | [
{
"body": "<p><strong>Redundant operations</strong><br>\nAfter reading the data from the web service, you go over it a number of times, which seems redundant:</p>\n\n<blockquote>\n<pre><code>results = parsed.reject { |key, value| key != \"results\"}\n</code></pre>\n</blockquote>\n\n<p>Why is that important? You go over the whole JSON, and discard everything - but you gain nothing. Simply use only what you need, no need to actively <em>remove</em> it.</p>\n\n<blockquote>\n<pre><code>pull_items = []\npull_items = results[\"results\"].each do |items|\n pull_items << items\nend\n</code></pre>\n</blockquote>\n\n<p>This is simply a very convoluted way of saying <code>pull_items = results['results']</code>...</p>\n\n<blockquote>\n<pre><code>pull_info = []\npull_items.each do |x|\n pull_info << x[\"item\"]\nend\n</code></pre>\n</blockquote>\n\n<p>Ruby's idiomatic way of saying the same thing is <code>pull_info = pull_items.map { |x| x['item'] }</code></p>\n\n<blockquote>\n<pre><code>@stories = pull_info.map do |s|\n News.new s[\"title\"], s[\"url\"], s[\"username\"]\nend\n</code></pre>\n</blockquote>\n\n<p>If this is what you actually wanted, you don't really need all the temporary artifacts in the middle - simply do it in one swoop: </p>\n\n<pre><code>@stories = results['results'].map do |r| \n item = r['item']\n News.new item['title'], item['url'], item['username']\nend\n</code></pre>\n\n<p><strong>Naming Conventions</strong><br>\nIt is conventional in ruby to name getters by the name of the member, without the <code>get_XXX</code>. For that convention, there is even a shortcut - <code>attr_reader</code>. So, instead of writing <code>def get_url</code> you should do:</p>\n\n<pre><code>class News\n attr_reader :url\n ...\nend\n\n@link = @stories[@counter].url\n</code></pre>\n\n<p>and it will just work...</p>\n\n<p><strong>Code Encapsulation</strong><br>\nA ruby file should contain a single class. It should not contain any floating methods.<br>\nActually, there should not be any floating methods. Create a different class, or a module, which will contain the <code>show_story</code>, <code>shuffle</code>, and <code>next_story</code>. This will also force you to <em>name</em> the module, and make it more obvious what is its role in your application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T12:08:12.763",
"Id": "46261",
"ParentId": "46258",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-04T11:40:21.613",
"Id": "46258",
"Score": "4",
"Tags": [
"beginner",
"ruby",
"json"
],
"Title": "Refactor Ruby code from Hacker News API. Trouble parsing the JSON data"
} | 46258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.