body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>This exercise gave me some trouble, but I think I have a solution here that fulfils the spec. However it's very long compared to what I'm looking at on the solutions page at <a href="http://www.clc-wiki.net/wiki/KR2_Exercise_1-22" rel="nofollow">clc-wiki.net</a>. </p> <p>In the course of solving the problem I loop over my buffered line three or four times. This seems like quite a lot, and the various edge cases I have to account for means my prog is over 100 lines long (including spacing). </p> <p>If anyone is kind enough to have patience to read it, I'd really appreciate your thoughts. Could it be shorter? Are there any glaring redundancies? </p> <pre><code>#include &lt;stdio.h&gt; #define FOLD 20 int getline( char s[], int max ); int does_line_have_blanks( char line[], int len ); int locate_last_space ( char line[], int len ); int find_split( char line[], int len, int offset); int mark_split_and_clean_trailing_spaces( char line[], int len, int spacecount ); int print_with_split( char s[], int split_pos ); int main() { int len, i, split_pos, offset; char line[FOLD+1]; len = split_pos = 0; for ( i = 0; i &lt; FOLD+1; ++i ) line[i] = 0; offset = 0; /*keeps track of characters that overflow the split so next buffer may be shortened accordingly*/ while ( ( len = getline(line, (FOLD+1) - offset) ) &gt; 0 ) { split_pos = find_split ( line, len, offset ); offset = print_with_split( line, split_pos ); /* clean out buffer*/ for ( i = 0; i &lt; FOLD+1; ++i ) line[i] = '\0'; } return 0; } int getline ( char s[], int max ) /* doesn't add newlines as K&amp;R's does */ { int i, c; for (i = 0 ; i &lt; max-1 &amp;&amp; (c = getchar()) != EOF &amp;&amp; c != '\n'; i++ ) s[i] = c; s[i] = '\0'; return i; } int find_split( char line[], int len, int offset ) { int i, split_pos, blanks; i = split_pos = 0; /*make sure there are blanks - if not the line will be printed as-is*/ blanks = does_line_have_blanks( line, len ); if ( len &lt; FOLD-offset || blanks != 1 ) { split_pos = len; /* hit a newline or EOF - split at end of input */ } else { split_pos = locate_last_space( line, len ); } return split_pos; } int does_line_have_blanks( char line[], int len ) { int i, blanks; i = blanks = 0; for ( i = 0; i &lt; len; ++i ) { /*len is at null char in line*/ if (line[i] == ' ' ) blanks= 1; } return blanks; } int locate_last_space ( char line[], int len ) { int i, inspace, spacecount, split_pos; inspace = spacecount = split_pos = 0; for ( i = 0; i &lt; len; ++i ) { if ( line[i] == ' ' ) { inspace = 1; ++spacecount; } else { inspace = 0; if ( spacecount &gt; 0 ) { /*if we leave inspace state, split on the preceding char */ spacecount = 0; split_pos = i -1; } } } if ( inspace == 1 ) { /* and if we left in a space... */ split_pos = mark_split_and_clean_trailing_spaces( line, len, spacecount ); } return split_pos; } int mark_split_and_clean_trailing_spaces( char line[], int len, int spacecount ) { int split_pos, i; split_pos = i = 0; split_pos = len - spacecount; /*... split where it started */ for ( i = split_pos + 1; i &lt; len; ++i ) { /*nullify trailing spaces as per instructions*/ line[i] = '\0'; } return split_pos; } int print_with_split( char line[], int split_pos ) { int i, offset; offset = 0; for ( i = 0; i &lt; split_pos; ++i ) { putchar(line[i]); } putchar('\n'); for ( i = (split_pos + 1 ); line[i] != '\0'; ++i) /*miss out the space we split on*/ { ++offset; /* extra chars on next line, so buffer will be smaller */ putchar(line[i]); } return offset; } </code></pre> <p><strong>EDIT</strong> Added a return type for <code>main()</code></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T19:00:24.723", "Id": "7471", "Score": "1", "body": "I know it's K&R but always give all functions return types. `main()` is just another (special) function and it should have an explicit return type just like any other. You _should_ want to anyway for consistency sake. ;)" } ]
[ { "body": "<p>Instead of reading an entire line, then finding where to break the line, I think I'd read one word, and depending on the length of the line up to that point and the length of the word, decide whether or not to write a new-line before writing that word.</p>\n\n<p>That way, the main loop would come out something like this:</p>\n\n<pre><code>while (getword(buffer, max_len)!=EOF) {\n if (current_length + strlen(buffer) &gt; max_len) {\n print(\"\\n\");\n current_length = 0;\n }\n print(buffer);\n current_length += strlen(buffer);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T15:48:31.610", "Id": "7468", "Score": "0", "body": "reading word-by-word seems much more elegant. though wouldn't it break its bounds (and the next line's) if the word were longer than max_len? needing to be able to break mid-word is why i ended up using a split index along with `putchar()`, instead of `printf()` or `print` (which i admit i haven't encountered in the book yet)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T23:56:49.227", "Id": "7474", "Score": "0", "body": "@djb: the idea was to have `getword` only read up to the specified maximum size, so a word in the input that was longer would be broken automatically at that point. And no, `print` is something you won't find in the book -- I was intentionally write this more as C-like pseudo-code than something you'd be able to compile directly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T11:08:32.300", "Id": "7480", "Score": "0", "body": "ok. I might try and make this program..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T15:13:04.583", "Id": "4998", "ParentId": "4997", "Score": "2" } }, { "body": "<p>You should be aware that you're re-writing functionality present in the standard library.<br>\nThis is all right if you're learning, and I would encourage you to continue to do so (it's a great way to learn), but here are a few thoughts from this angle:</p>\n\n<p><code>getline</code> - this is basically <code>fgets</code>.</p>\n\n<p><code>locate_last_space</code> - this is what <code>strrchr(str, ' ')</code> does. (Note the extra <b>r</b> in there means \"search in reverse\")</p>\n\n<p><code>does_line_have_space</code> - you can use <code>strchr(str, ' ')</code> as a boolean expression. (If the result is non-NULL then it has that character.)</p>\n\n<p><code>find_split</code> - it seems a bit redundant to call <code>does_line_have_space</code> before <code>locate_last_space</code>. You can use the result of <code>strrchr(str, ' ')</code> to determine both that there is a space (result is non-NULL) and where the last space is (using the result as a pointer).</p>\n\n<p>As a style point I would argue that it would be more \"C-like\" to talk in terms of pointer arithmetic rather than offsets. (i.e. Take the result of <code>strrchr</code>, do something with that pointer, rather than thinking in terms of \"give me the offset of the next space\".)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T11:01:56.503", "Id": "7515", "Score": "0", "body": "thanks for the advice - now learning the standard library and finding it tremendously useful. found reinventing the wheel to be a useful learning process :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T19:40:02.917", "Id": "7530", "Score": "0", "body": "@djb - I agree that rewriting these is good to learn. You might want to try rewriting the functions themselves, conforming to the same interfaces as in the standard library. For example `strchr` might look like this: `char *strchr(char *s, int c) { while (*s) { if (*s == c) return s; else ++s; } return NULL; }`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T08:57:18.570", "Id": "7559", "Score": "0", "body": "great idea, thanks. i will attempt these when i have covered a bit more ground." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T18:15:31.997", "Id": "5021", "ParentId": "4997", "Score": "1" } } ]
{ "AcceptedAnswerId": "5021", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-25T12:06:02.653", "Id": "4997", "Score": "5", "Tags": [ "c" ], "Title": "Learning C: K&R 1-22: 'fold'. Is this solution very unwieldy?" }
4997
<p>Background is <a href="https://codereview.stackexchange.com/questions/4164/can-you-recommend-what-to-prioritize-when-rewriting-this-class">this question</a> and to create something like Craigslist or olx.com i.e. classifieds advertisement webapp / site and I've basically <a href="http://montao.com.br" rel="nofollow noreferrer">solved the problem</a> and had a mess of unstructured code that built other code and generated SQL and other stuff and now I've first rewritten it from Java which got the source down from 30 MB to about ½ MB and fixed tons of old bugs to now in Python (GAE) and the Python file to handle Brazil looks basically like this</p> <pre><code>from __future__ import with_statement # coding=utf-8 import os from google.appengine.api.users import is_current_user_admin, UserNotFoundError import time import cgi import geo.geotypes import main from main import Ad import captcha import facebookconf from google.appengine import api from google.appengine.ext import webapp, search from google.appengine.ext.webapp import template from google.appengine.runtime import DeadlineExceededError from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db from google.appengine.api import users from google.appengine.ext import blobstore from google.appengine.ext.blobstore import BlobInfo from google.appengine.api import images from google.appengine.ext.db import djangoforms from django import forms from django.core.exceptions import ValidationError from paginator import Paginator, InvalidPage, EmptyPage from django.utils import translation from datetime import datetime, timedelta os.environ['DJANGO_SETTINGS_MODULE'] = 'conf.settings' from django.conf import settings from django.template import RequestContext from util import I18NHandler, FacebookBaseHandler import util from google.appengine.api import urlfetch, taskqueue from django.template.defaultfilters import register from django.utils import simplejson as json from functools import wraps from google.appengine.api import urlfetch, taskqueue from google.appengine.ext import db, webapp from google.appengine.ext.webapp import util, template from google.appengine.runtime import DeadlineExceededError from random import randrange import Cookie import base64 import cgi import conf import datetime import hashlib import hmac import logging import time import traceback import urllib import twitter_oauth_handler from twitter_oauth_handler import OAuthClient from geo.geomodel import GeoModel from google.appengine.api import images from django.utils.translation import gettext_lazy as _ webapp.template.register_template_library('common.templatefilters') logo = 'market' class Handler(FacebookBaseHandler,I18NHandler): def get(self, region='São Paulo', city='Grande São Paulo', category='For sale', cursor=None, limit=60, PAGESIZE = 50, twittername = None): lon = -46.38 lat = -23.33 region = region.replace("_"," ").title() if region is city: city = None else: city = city.replace("_"," ").title() category = category.replace("_"," ") page = int(self.request.GET.get('page', '1')) timeline = datetime.datetime.now () - timedelta (days = limit) m=int(self.request.get('r')) if self.request.get('r') else 804670 q = self.request.get('q').encode("utf-8") location_map = { 1: {'name': 'São Paulo', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 2: {'name': 'Rio De Janeiro', 'lat': -22.90, 'long': -43.21, 'radius': 294200}, 3: {'name': 'Acre', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 4: {'name': 'Alagoas', 'lat': -22.90, 'long': -43.21, 'radius': 294200}, 5: {'name': 'Amazonas', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 6: {'name': 'Amapá', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 7: {'name': 'Bahia', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 8: {'name': 'Ceará', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 9: {'name': 'Distrito Federal', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 10: {'name': 'Espírito Santo', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 11: {'name': 'Goiás', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 12: {'name': 'Mato Grosso', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 13: {'name': 'Maranhão', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 14: {'name': 'Minas Gerais', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 15: {'name': 'Pará', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 16: {'name': 'Paraíba', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 17: {'name': 'Paraná', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 18: {'name': 'Pernambuco', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 19: {'name': 'Piauí', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 20: {'name': 'Rio de Janeiro', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 21: {'name': 'Rio Grande do Norte', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 221: {'name': 'Rio Grande do Sul', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 231: {'name': 'Rondônia', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 241: {'name': 'Roraima', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 251: {'name': 'Santa Catarina', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 281: {'name': 'Sergipe', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 271: {'name': 'Tocantins', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, } if region is 'Sao Paulo': location_map.pop('1') region = 'São Paulo' elif region is 'Rio De Janeiro': location_map.pop('2') if region is 'Acre': location_map.pop('3') location_map_br_11_cap = { 1: {'name': 'Toda Região 11 (ddd)', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 2: {'name': 'Todo Estado de São Paulo', 'lat': -22.90, 'long': -43.21, 'radius': 294200}, 1: {'name': 'Toda região Sudeste do Brasil', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, } location_map_br_11 = { 232: {'name': '- Zona Centro', 'lat': -22.90, 'long': -43.21, 'radius': 294200}, 133: {'name': '- Zona Norte', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 12: {'name': '- Zona Sul', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 111: {'name': '- Zona Leste', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 121: {'name': '- Zona Oeste', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 12223: {'name': 'Atibaia', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 14: {'name': 'Barueri', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 16: {'name': 'Bragança Paulista', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 17: {'name': 'Carapicuíba', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 18: {'name': 'Cotia', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 19: {'name': 'Diadema', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 10: {'name': 'Embu', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 21: {'name': 'Ferraz de Vasconcelos', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 221: {'name': 'Francisco Morato', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 231: {'name': 'Franco da Rocha', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 241: {'name': 'Guarulhos', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 251: {'name': 'Itapecerica da Serra', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 261: {'name': 'Itaquaquecetuba', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 271: {'name': 'Itu', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 281: {'name': 'Jundiaí', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 291: {'name': 'Mauá', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 311: {'name': 'Poá', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 321: {'name': 'Ribeirão Pires', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 331: {'name': 'Santana de Parnaíba', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 341: {'name': 'Santo André', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 351: {'name': 'São Bernardo do Campo', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 361: {'name': 'São Caetano do Sul', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 371: {'name': 'Suzano', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 381: {'name': 'Taboão da Serra', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, 391: {'name': 'Várzea Paulista', 'lat': -23.55, 'long': -46.64, 'radius': 294200}, } #order_by = self.request.get('order') """ query = Owner.all() query.filter("owner =", user) if not order_by: query.order("owner_tag") elif order_by == 'date': query.order("-date") ... &lt;a href="your_page_url?order=date"&gt;order tags by most recent&lt;/a&gt; """ #query = Ad.all().search(self.request.get('q')).filter("url IN", ['www.montao.com.br','montao']).filter("modified &gt;", timeline).filter("published =", True).order("-modified") ads = Ad.proximity_fetch(Ad.all().search(self.request.get('q')).filter("modified &gt;", timeline).filter("published =", True).order("-modified") ,db.GeoPt(lat, lon),max_results=PAGESIZE+1, max_distance=m) ads = sorted(ads, key=lambda x: x.modified, reverse=True) if ads and len(ads) == PAGESIZE+1: next = ads[-1].modified ads = ads[:PAGESIZE] paginator = Paginator(ads,PAGESIZE) ads = paginator.page(page) location_map = sorted(location_map.iteritems(), key=lambda x: x[1]["name"]) location_map_br_11_cap = sorted(location_map_br_11_cap.iteritems(), key=lambda x: x[1]["name"]) location_map_br_11 = sorted(location_map_br_11.iteritems(), key=lambda x: x[1]["name"]) all_count = Ad.all().filter("modified &gt;", timeline).filter("published =", True).count(100000000) private_count = Ad.all().filter("modified &gt;", timeline).filter("published =", True).filter("company_ad =", False).count(100000000) company_count = Ad.all().filter("modified &gt;", timeline).filter("published =", True).filter("company_ad =", True).count(100000000) to = PAGESIZE * page fromand = to - PAGESIZE + 1 if to &gt; all_count: to = all_count self.render(u'for_sale_br', country='Brazil', region=region, category=category, city=city, location_map_br_11_cap = location_map_br_11_cap, location_map_br_11 = location_map_br_11, to=to, fromand=fromand, all_count=all_count, private_count=private_count, company_count=company_count,location_map=location_map, paginator=paginator,twittername=twittername,request=self.request,lat=self.request.get('lat'),lon=self.request.get('lon'),q=q,logo=logo,ads=ads, user_url=users.create_logout_url(self.request.uri) if users.get_current_user() else None, admin=users.is_current_user_admin(),user=users.get_current_user() if users.get_current_user() else None, ) application = webapp.WSGIApplication([('/([^/]+)/?([^/]*)/?([^/]*)',Handler),],debug=True) def main(): logging.getLogger().setLevel(logging.DEBUG) run_wsgi_app(application) if __name__ == "__main__": main() </code></pre>
[]
[ { "body": "<p>Your imports could use some cleanup, you import that same thing a few different times. I also suspect you aren't using some of the stuff you are importing, so yeah I suggest some effort to clean that up.</p>\n\n<p>Your indentation is messed up on here, making it harder to read. Probably a copy/paste error somewhere along the way.</p>\n\n<p>Your big dictionaries of data should be global variables or loaded from a seperate file.</p>\n\n<p><code>if region is city:</code>, I don't think this means what you think it means. It compares the object identity not the contents of the string. It will always come out false in this peice of code. I think you meant <code>==</code></p>\n\n<pre><code>region = region.replace(\"_\",\" \").title()\n</code></pre>\n\n<p>You do this basic operation several times, put it in a reusable and well-named function.</p>\n\n<pre><code>page = int(self.request.GET.get('page', '1'))\n</code></pre>\n\n<p>What if the web request has something that is not a number in there? You've gotta be careful with user input.</p>\n\n<pre><code>m=int(self.request.get('r')) if self.request.get('r') else 804670\n</code></pre>\n\n<p>m is a very mysterious variable name, it doesn't give much hints as to what you are doing. Also, if self.request is a dictionary, get takes a second parameter which is a default. </p>\n\n<pre><code>if region is 'Sao Paulo':\n location_map.pop('1')\n region = 'São Paulo'\nelif region is 'Rio De Janeiro':\n location_map.pop('2')\nif region is 'Acre':\n location_map.pop('3')\n</code></pre>\n\n<p><code>is</code> doesn't do what you want here, if this has escaped your notice until now, you seriously need to improve your testing practices.</p>\n\n<pre><code>#order_by = self.request.get('order')\n \"\"\"\n query = Owner.all()\n query.filter(\"owner =\", user)\n if not order_by:\n query.order(\"owner_tag\")\n elif order_by == 'date':\n query.order(\"-date\")\n ...\n &lt;a href=\"your_page_url?order=date\"&gt;order tags by most recent&lt;/a&gt;\n \"\"\"\n\n#query = Ad.all().search(self.request.get('q')).filter(\"url IN\", ['www.montao.com.br','montao']).filter(\"modified &gt;\", timeline).filter(\"published =\", True).order(\"-modified\")\n</code></pre>\n\n<p>Don't leave commented code in your code. It clutters the code.</p>\n\n<pre><code> ads = Ad.proximity_fetch(Ad.all().search(self.request.get('q')).filter(\"modified &gt;\", timeline).filter(\"published =\", True).order(\"-modified\") ,db.GeoPt(lat, lon),max_results=PAGESIZE+1, max_distance=m)\n</code></pre>\n\n<p>Line is seriously too long. Look at breaking it up over several lines</p>\n\n<pre><code> ads = sorted(ads, key=lambda x: x.modified, reverse=True)\n</code></pre>\n\n<p>if ads has an order specified, why are you sorting?</p>\n\n<pre><code> if ads and len(ads) == PAGESIZE+1:\n next = ads[-1].modified\n ads = ads[:PAGESIZE]\n</code></pre>\n\n<p><code>next</code> is a builtin python function. Consider using another name</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T17:34:57.380", "Id": "7484", "Score": "0", "body": "Thank for the elaborate answer. I created a seperate question for the imports on SO and will take the measure to handle everything you mention to improve my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T15:10:44.940", "Id": "5004", "ParentId": "5002", "Score": "2" } } ]
{ "AcceptedAnswerId": "5004", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T10:58:09.410", "Id": "5002", "Score": "2", "Tags": [ "python", "google-app-engine" ], "Title": "Modularizing this file to make it more convenient and more readable" }
5002
<p>My first jQuery plugin is working, but I wonder if my coding is conventional. What can I do better and how can I make it more efficient?</p> <p>I know it's only a small plugin, so efficiency is not a big deal, but I don't want to start with bad habits.</p> <p>What this plugin is doing:</p> <ul> <li>It transforms a div to a widget (with header and content) </li> <li>When double-clicked on header, content fades in/out (depending on current state open or closed)</li> <li>Load content via Ajax when opened </li> <li>Has option for reloading content when opened again</li> <li>Has option for refreshing content when opened</li> </ul> <pre class="lang-js prettyprint-override"><code>(function($){ $.fn.extend({ widgetIt: function(options) { var defaults = { title: 'Widget Title', load:'', top: '50px', left: '400px', width: '500px', afterLoad: function(){}, reload:false, //if true the content gets reloaded everytime widget opens refresh:false //if set to (example) 3000, the content gets refreshed when widget is open }; var options = $.extend(defaults, options); var o=options; //conditional manipulate options if(o.refresh){o.reload=true}//when refresh is set, reload is true return this.each(function() { var container=$(this).css({'z-index':3, display:'inline-block',position:'absolute',top:o.top,left:o.left,'max-width':o.width}) .addClass('widget_container'); var header = $('&lt;div&gt;&lt;/div&gt;') .addClass('ui-widget-header widgethead') .css({'min-width':'130px'}); var title =$('&lt;div&gt;&lt;/div&gt;').addClass("w_tit").html(o.title); var content =$('&lt;div&gt;&lt;/div&gt;') .addClass("w_content") .hide(); var timer = null; //whats the best place to put this function? //is it good to have it this in each function? function loadData(){ $.ajax({ url: o.load, context: content, success: function(data){ $(content).html(data); reload=false; //[hide ajax spinner] if(o.refresh){ timer=setTimeout(loadData,o.refresh) ;} o.afterLoad.call(); }, error: function(){ // error code here } }); } //append $(title).appendTo(header) ; $(header).appendTo(container) ; $(content).appendTo(container) ; //make draggable $(container).draggable({ cancel: 'input,option, select,textarea,.w_content', opacity: 0.45, cursor: 'move' }); //cbinding var display=$(content).css('display'); //check if widget is open=block or closed=none var reload=true ; //set initially to true-&gt;reload content every time widget opens $(header).dblclick(function(){ $(content).fadeToggle();//first open or close widget //[show ajax spinner] if(display="block" &amp;&amp; reload){//only load on widget open event loadData(); }else if(display="none"){reload=o.reload;clearTimeout(timer);}//set reload true or false }); $(header).click(function (){ $(container).topZIndex('.widget_container'); }); //close all open widgets and animate back to original position $('#deco').click(function (){ $(content).hide(); $(container).animate({ "left": o.left, "top": o.top}, "slow"); }); }); } }); })(jQuery); </code></pre>
[]
[ { "body": "<p>Only two small points of improvement:</p>\n\n<pre><code>var defaults = {\n title: 'Widget Title',\n load:'',\n top: '50px',\n left: '400px',\n width: '500px',\n afterLoad: function(){},\n reload:false, //if true the content gets reloaded everytime widget opens\n refresh:false //if set to (example) 3000, the content gets refreshed when widget is open\n };\n</code></pre>\n\n<p>can be put outside the <code>widgetIt</code> function. I do this as a standard as (in theory) it doesn't get created each time. The difference in reality is probably indistinguishable</p>\n\n<pre><code>(function($){\n var defaults = {\n title: 'Widget Title',\n load:'',\n top: '50px',\n left: '400px',\n width: '500px',\n afterLoad: function(){},\n reload:false, //if true the content gets reloaded everytime widget opens\n refresh:false //if set to (example) 3000, the content gets refreshed when widget is open\n };\n $.fn.extend({\n // etc. \n</code></pre>\n\n<p>secondly as a matter of tidyness: </p>\n\n<pre><code>var options = $.extend(defaults, options);\nvar o=options;\n</code></pre>\n\n<p>is redundant. Either use <code>options</code> or <code>o</code> but don't have both as this can get confusing. Also I wouldn't use single letter variable names for anything other than <code>i</code>. Being Explicit about the variable leads to an easier read in 6 months when you come back to it. </p>\n\n<p><strong>EDIT:-</strong> I've noticed another tidyness issue:</p>\n\n<pre><code>widgetIt: function(options){\n var options = //...\n</code></pre>\n\n<p>you don't need to redeclare the options just use it.</p>\n\n<pre><code>widgetIt: function(options){\n options = //...\n</code></pre>\n\n<p>Just as a help I often paste my code into <a href=\"http://jsfiddle.net\" rel=\"nofollow\">http://jsfiddle.net</a> and click \"JSLint\". Its not always correct (as I don't always paste all my code in) but it helps a lot. Also the \"TidyUp\" buttons is awesome too.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T01:20:16.087", "Id": "5149", "ParentId": "5005", "Score": "4" } }, { "body": "<p>I see a little bug on lines 85 - 85:</p>\n\n<pre><code>if(display=\"block\" &amp;&amp; reload){//only load on widget open event\n loadData();\n}\nelse if(display=\"none\"){\n reload=o.reload;clearTimeout(timer);\n }//set reload true or false\n</code></pre>\n\n<p>Here you are setting the value of a variable called display instead of evaluating its value. The &amp;&amp; operator JavaScript may work different than you expect. It evaulates the first expression and returns the result of it if its true, the first is false it returns the result of the second expression. So this means line 83 will ALWAYS return true since anything that doesn't evaluate to FALSE in JavaScript is true, like setting the value of a variable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T01:32:34.293", "Id": "5150", "ParentId": "5005", "Score": "2" } }, { "body": "<p>For feedback on your code, I'd group your var statements together instead of declaring them separately. For example: </p>\n\n<pre><code>var container=$(this).css({'z-index':3, display:'inline-block',position:'absolute',top:o.top,left:o.left,'max-width':o.width})\n .addClass('widget_container'),\nheader = $('&lt;div&gt;&lt;/div&gt;')\n .addClass('ui-widget-header widgethead')\n .css({'min-width':'130px'}),\ntitle =$('&lt;div&gt;&lt;/div&gt;').addClass(\"w_tit\").html(o.title),\ncontent =$('&lt;div&gt;&lt;/div&gt;')\n .addClass(\"w_content\")\n .hide(),\ntimer = null;\n</code></pre>\n\n<p>In the blow lines you are doubling jQuery:</p>\n\n<pre><code>//append\n$(title).appendTo(header) ;\n$(header).appendTo(container) ;\n$(content).appendTo(container) ;\n</code></pre>\n\n<p>This could be written like: </p>\n\n<p>//append\n title.appendTo(header) ;\n header.appendTo(container) ;\n content.appendTo(container) ;</p>\n\n<p>When you created the objects, they already have jquery attached to them. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T01:54:27.353", "Id": "7724", "Score": "0", "body": "I wouldn't group my statements like that when they contain multiple chains. `.css().addClass()` etc. It will make it too hard to read. I'd do one or the other." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T01:49:31.777", "Id": "5151", "ParentId": "5005", "Score": "1" } }, { "body": "<ul>\n<li>Typically, jQuery plugins follow the jQuery Core Style guidelines. This has a number of benefits, including that it's easier for potential savvy users to proof-read/review the plugin before using it, extend the plugin, or incorporate it into some larger project (e.g. jQuery UI). A more verbose explanation is available in slides 18-27 of <a href=\"http://code.bocoup.com/jquery-you-and-i/#slide-18\" rel=\"nofollow\">this presentation</a>.</li>\n<li>You may wish to return <code>this</code> from your <code>widgetIt</code> method to allow chaining (for consistency with the rest of the jQuery API).</li>\n<li>You may want to expose <code>defaults</code> in a way that allows users to override it (a la <code>$.datepicker.setDefaults</code>).</li>\n<li>It seems like there might be a bug in <code>$.extend(defaults, options)</code>; I believe that modifies your default settings. I've usually seen it written <code>$.extend({}, defaults, options)</code>.</li>\n</ul>\n\n<p>For more plugin best practices, you might want to take a look at the <a href=\"https://github.com/cowboy/talks/blob/master/jquery-plugin-authoring.js\" rel=\"nofollow\">\"slides\"</a> from the presentation Ben Alman delivered at this year's jQuery Boston conference.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T00:57:12.807", "Id": "5261", "ParentId": "5005", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T15:29:47.870", "Id": "5005", "Score": "4", "Tags": [ "javascript", "performance", "jquery" ], "Title": "Transforming a div to a widget" }
5005
<p>I've written the following controller and i was looking for some input/advice on how i could go about cleaning this up or rewriting it. I feel like i'm repeating myself a lot or that there might be a better way to do this.</p> <pre><code>namespace WebUI.Controllers { [Authorize(Roles="Administrator,Registrar")] public class RegistrarController : BaseController { private readonly IRegistrationService _registrationService; public const string WizardKey = "Wizard"; public const string ActionKey = "Action"; public RegistrarController(IRegistrationService registrationService) { this._registrationService = registrationService; } [HttpGet] public ActionResult Step1() { if (string.IsNullOrEmpty(this.RegistrarId)) { ViewBag.ErrorMessage = "A valid registrar id is not associated with this account."; return View("Error"); } PersonRegistrationWizard wizard; if (!PrepareAndCheckStep(1, out wizard)) { /* Should always be true... */ } return View(wizard.Step1Model); } [HttpPost] public ActionResult Step1(NewRegistrantModel model) { var wizard = TempData[WizardKey] as PersonRegistrationWizard; if (wizard == null) wizard = new PersonRegistrationWizard(); if (!ModelState.IsValid) { wizard.Step1Model = model; TempData[WizardKey] = wizard; return View("Step1", model); } var eventDate = _registrationService.GetUpcomingEventFor(DateTime.Now); if (!eventDate.HasValue) { wizard.Step1Model = model; TempData[WizardKey] = wizard; ViewBag.ErrorMessage = "Sorry, no upcoming event was found within our database."; return View("Error"); } if (!_registrationService.EligibleToRegister(model.Birthdate.Value, eventDate.Value)) { wizard.Step1Model = model; TempData[WizardKey] = wizard; ModelState.AddModelError("","Error Goes Here"); return View("Step1", model); } wizard.Step1Model = model; if (wizard.MaxCompletedStep &lt; 1) wizard.MaxCompletedStep = 1; TempData[WizardKey] = wizard; return RedirectToAction("Step2"); } [HttpGet] public ActionResult Step2() { PersonRegistrationWizard wizard; if (!PrepareAndCheckStep(2, out wizard)) { return RedirectToAction("Step1"); } return View(wizard.Step2Model); } [HttpPost] public ActionResult Step2(PersonInformationModel model) { var wizard = TempData[WizardKey] as PersonRegistrationWizard; if (wizard == null || wizard.Step1Model == null || wizard.MaxCompletedStep &lt; 1) return RedirectToAction("Step1"); if (!ModelState.IsValid) { wizard.Step2Model = model; TempData[WizardKey] = wizard; return View("Step2", model); } model.Person.NotInStreetIndex = !StreetDataValid(model.Person); if (model.Person.NotInStreet &amp;&amp; !model.ConfirmResident) { wizard.Step2Model = model; TempData[WizardKey] = wizard; ModelState.AddModelError("ConfirmResident", "The address entered was not found in our database. Please confirm that you a resident of ...."); return View(model); } wizard.Step2Model = model; wizard = MoveDataFromStep1ToStep2(wizard); if (wizard.MaxCompletedStep &lt; 2) wizard.MaxCompletedStep = 2; TempData[WizardKey] = wizard; return RedirectToAction("Step3"); } [HttpGet] public ActionResult Step3() { PersonRegistrationWizard wizard; if (!PrepareAndCheckStep(3, out wizard)) return RedirectToAction("Step1"); return View(wizard); } [HttpPost] public ActionResult Step3(FormCollection form) { var wizard = TempData[WizardKey] as PersonRegistrationWizard; if (wizard == null || wizard.MaxCompletedStep &lt; 2 || wizard.Step1Model == null || wizard.Step2Model == null) return RedirectToAction("Step1"); if (!string.IsNullOrEmpty(form["editStep1"])) return RedirectToAction("Step1"); else if (!string.IsNullOrEmpty(form["editStep2"])) return RedirectToAction("Step2"); else { if (wizard.MaxCompletedStep &lt; 2) { // Display Error } if (ModelState.IsValid) { wizard = MoveDataFromStep1ToStep2(wizard); var Person = BuildPersonFromModel(wizard); var registration = new RegistrarPersonRegistration(); if (Person.Id &gt; 0) { registration = _registrationService.GetManyRegistrarPersonRegistrationsBy(v =&gt; v.PersonId == Person.Id).FirstOrDefault(); if (registration == null || registration.Person == null) throw new InvalidProgramException("The Person id supplied does not have a Person registration"); Person.LastUpdatedOn = DateTime.Now; registration.Person.Copy(Person); registration = _registrationService.UpdateRegistrarPersonRegistration(registration); } else { Person.CreatedBy = this.User.Identity.Name; Person.CreatedOn = DateTime.Now; Person.RegistrationTypeCode = "REG"; Person.RegistrationStatusCode = "P"; Person.RegistrationDate = DateTime.Now; registration = _registrationService.RegistrarRegisterPerson(wizard.RegistrarId, Person); } _registrationService.Save(); wizard.Step2Model.Person.PersonId = registration.PersonId; if (wizard.MaxCompletedStep &lt; 3) wizard.MaxCompletedStep = 3; TempData[WizardKey] = wizard; } else { // TO DO: Display Errors that prevent the user from continuing TempData[WizardKey] = wizard; return View(wizard); } return RedirectToAction("Step4"); } } [HttpGet] public ActionResult Step4() { PersonRegistrationWizard wizard; if (!PrepareAndCheckStep(4, out wizard)) return RedirectToAction("Step1"); return View(wizard); } [HttpPost] public ActionResult Step4(FormCollection form) { var wizard = TempData[WizardKey] as PersonRegistrationWizard; string action = form[ActionKey] == null ? string.Empty : form[ActionKey].ToString().ToUpper(); if (wizard == null || wizard.MaxCompletedStep &lt; 3 || wizard.Step2Model == null || wizard.Step2Model.Person == null || !wizard.Step2Model.Person.PersonId.HasValue || wizard.Step2Model.Person.PersonId.Value &lt;= 0) return RedirectToAction("Step1"); int PersonId = wizard.Step2Model.Person.PersonId.Value; var registration = new RegistrarPersonRegistration(); switch (action) { case "PRINT": registration = _registrationService.GetManyRegistrarPersonRegistrationsBy(rvr =&gt; rvr.PersonId == PersonId).FirstOrDefault(); if (registration == null) { ViewBag.ErrorMessage = "No Person id was provided."; wizard = null; return View("Error"); } registration.Person.RegistrationStatusCode = "C"; _registrationService.UpdateRegistrarPersonRegistration(registration); _registrationService.Save(); TempData[WizardKey] = null; // Return Form return RedirectToAction("GenerateRegistrationForm", "Report", new { id = registration.Id }); break; case "ADD": TempData[WizardKey] = null; return RedirectToAction("Step1"); case "HOME": TempData[WizardKey] = null; return RedirectToAction("Dashboard"); default: break; } return View(wizard); } /// &lt;summary&gt; /// Prepares the wizard and checks to see if the previous steps were completed /// &lt;/summary&gt; /// &lt;param name="step"&gt;Current step&lt;/param&gt; /// &lt;param name="wizard"&gt;Registration Wizard&lt;/param&gt; /// &lt;returns&gt;returns true if the previous steps have been completed and false if not&lt;/returns&gt; private bool PrepareAndCheckStep(int step, out PersonRegistrationWizard wizard) { bool isValid = false; wizard = TempData[WizardKey] as PersonRegistrationWizard; switch (step) { case 1: if (wizard == null || wizard.Step1Model == null) { wizard = new PersonRegistrationWizard(); wizard.RegistrarId = this.RegistrarId; wizard.Step1Model = new NewRegistrantModel(); } isValid = true; break; case 2: if (wizard != null &amp;&amp; wizard.MaxCompletedStep &gt;= 1 &amp;&amp; wizard.Step1Model != null) { isValid = true; if (wizard.Step2Model == null) wizard.Step2Model = new PersonInformationModel(); wizard = MoveDataFromStep1ToStep2(wizard); } break; case 3: case 4: isValid = wizard != null &amp;&amp; wizard.MaxCompletedStep &gt;= step - 1 &amp;&amp; wizard.Step1Model != null &amp;&amp; wizard.Step2Model != null; break; default: if (wizard == null) wizard = new PersonRegistrationWizard(); break; } if (wizard != null) { if (string.IsNullOrEmpty(wizard.RegistrarId)) wizard.RegistrarId = this.RegistrarId; wizard.CurrentStep = step; TempData[WizardKey] = wizard; } return isValid; } private Person BuildPersonFromModel(PersonRegistrationWizard wizard) { int PersonId = 0; var modelPerson = wizard.Step2Model.Person; var Person = new Person(); if (modelPerson.PersonId.HasValue) { Person = _registrationService.GetPersonBy(v =&gt; v.Id == modelPerson.PersonId.Value); if (Person == null) throw new InvalidOperationException(string.Format("An invalid Person id was supplied {0}", Person.Id)); PersonId = Person.Id; } Person = modelPerson.ToEntity(); Person.Id = PersonId; return Person; } private PersonRegistrationWizard MoveDataFromStep1ToStep2(PersonRegistrationWizard wizard) { if (wizard == null || wizard.Step1Model == null) return null; if (wizard.Step2Model == null) { wizard.Step2Model = new PersonInformationModel(); } wizard.Step2Model.Person.Identification = wizard.Step1Model.Identification; wizard.Step2Model.Person.Birthdate = wizard.Step1Model.Birthdate; wizard.Step2Model.Person.SocialSecurityNumber = wizard.Step1Model.SocialSecurityNumber; wizard.Step2Model.Person.IdSupplied = wizard.Step1Model.OtherIdProvided; return wizard; } private bool StreetDataValid(PersonData Person) { return _registrationService.ValidateStreet(Person.AddressNumber.Value, Person.AddressDirection, Person.AddressStreet, Person.AddressStreetType, Person.AddressPostDirection, Person.AddressCity, Person.AddressZip); } } } </code></pre> <p>Thanks </p>
[]
[ { "body": "<p>Here the UI model is tightly coupled with the data structures required. Hence the need arises for transfering data from step 1 to step 2 etc. \nInstead the data structures should be based on business objects required - e.g. Person object with nested objects like social security info, personal info, residence info etc. Let all steps deal with the same Person object, updating inputs given by user in each step. </p>\n\n<p>Also the 'Step' itself can be separated out into an interface / abstract class. Let's say IStep is in interface with ValidateInput(), Prepare() and ExecuteStep() methods. ExecuteStep() internally calls ValidateInput() and Prepare() and returns ActionResult object. \nThen we have 4 small subclasses, one for each step implementing IStep. The controller code will be simplified, it just needs to create an instance of next step (depending on ActionResult received from earlier step) and call Execute() on the same. All step objects will share the same Person object, which can be passed to the constructor. </p>\n\n<p>Please reply back with specific queries if this approach is not clear.</p>\n\n<p>Following are the advantages of this approach</p>\n\n<ol>\n<li>The controller code is much simpler</li>\n<li>It is easier to modify a step</li>\n<li>It is easier to add/remove a step. Controller class will have very minimal effect of calling the new step.Execute() or removing call for an existing step. Other steps will not be affected at all. </li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:04:52.880", "Id": "7519", "Score": "0", "body": "Thanks for the feedback! I had a question though. If i were to use a business object instead of the data structure how would i go about using the built in validation with data annotations that asp.net mvc framework provides? Some properties of the business object would not required until a certain step is complete. The reason i had to seperate it was because of this. Thanks once again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T05:02:45.747", "Id": "5030", "ParentId": "5006", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T17:49:05.933", "Id": "5006", "Score": "4", "Tags": [ "c#", "asp.net-mvc-3", "controller" ], "Title": "Need help with cleaning up this Controller" }
5006
<p>I previously asked for a review at <a href="https://codereview.stackexchange.com/questions/2669/code-review-count-to-target-with-javascript/2680#2680">Count to target with JavaScript</a>, and it was a great help. I'm now looking for comments on the extended version. This code very simply counts in the direction of a particular target number, with the count slowing down as the target gets nearer. The target number is stored in a nearby file and is often modified by other processes (so this should display a gradual change towards the new number. </p> <p>Please be as brutal as you like with ways to improve the code or the algorithm (I'm aware there should be comments) - I'm a recreational programmer and would like to be improving my skills. This is absolutely my first use of AJAX and I'm amazed it worked at all :) </p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN "http://www.w3.org/TR/html4/strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Count to a particular target&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 id="myDiv"&gt;Starting&lt;/h1&gt; &lt;script type="text/javascript"&gt; currentValue = 100; targetValue = 1000;//as an initialisation value ticks=0; function count() { ticks++; if (ticks==100) { ticks=0; loadtarget(); } if (currentValue == targetValue) return; currentValue &lt; targetValue ? currentValue++ : currentValue--; document.getElementById('myDiv').innerHTML = 'Total wordcount:'+ currentValue.toString(); setTimeout(count,Math.max(20, 1000 - Math.abs(currentValue - targetValue))/10); } function loadtarget() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { targetValue=xmlhttp.responseText; } } xmlhttp.open("GET","target.txt",true); xmlhttp.send(); } loadtarget(); count() &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN \"http://www.w3.org/TR/html4/strict.dtd\"&gt; \n&lt;html&gt; \n&lt;head&gt; \n &lt;title&gt;Count to a particular target&lt;/title&gt; \n&lt;/head&gt; \n&lt;body&gt; \n&lt;h1 id=\"myDiv\"&gt;Starting&lt;/h1&gt; \n&lt;script type=\"text/javascript\"&gt;\n\n var zCurrentValue = 100, zTargetValue = 1000, zTicks=0; // z-prefix synonym with control variables\n getHostValue(); // initial load of server data \n intervalCheck(); \n\nfunction intervalCheck() {\n zTicks++; \n\n if (zTicks==100) getHostValue(); // limit reached - get stuff\n if (zCurrentValue == zTargetValue) return; // equal - stop processing over all\n\n zCurrentValue &lt; zTargetValue ? zCurrentValue++ : zCurrentValue--; // get closer to target ...\n document.getElementById('myDiv').innerHTML = 'Total word count:'+ zCurrentValue.toString(); // visualisation\n setTimeout(intervalCheck,Math.max(20, 1000 - Math.abs(zCurrentValue - zTargetValue))/10); // fiddle the milliseconds\n}\nfunction getHostValue() {\n\nvar xmlhttp = new XMLHttpRequest();\nxmlhttp.onreadystatechange=function() { (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) ? zTargetValue = xmlhttp.responseText : zTicks=0 ; } // zTicks = 0 always true, at least once\nxmlhttp.open(\"GET\",\"target.txt\",true);\nxmlhttp.send();\n}\n&lt;/script&gt; \n&lt;/body&gt; \n&lt;/html&gt; \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T11:10:58.240", "Id": "7493", "Score": "0", "body": "It can be reduced somewhat more, but the setTimeout should be reworked - so it is more clear what is going on ..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T11:09:45.027", "Id": "5014", "ParentId": "5008", "Score": "1" } } ]
{ "AcceptedAnswerId": "5014", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-26T21:32:07.710", "Id": "5008", "Score": "1", "Tags": [ "javascript" ], "Title": "Count to target with javascript extended" }
5008
<p>This is a JUnit asserts for this function: </p> <pre><code> assertEquals(0, obj.generateListSize(0)); assertEquals(1, obj.generateListSize(1)); assertEquals(1, obj.generateListSize(2)); assertEquals(3, obj.generateListSize(3)); assertEquals(3, obj.generateListSize(4)); assertEquals(5, obj.generateListSize(5)); assertEquals(5, obj.generateListSize(6)); assertEquals(7, obj.generateListSize(7)); assertEquals(7, obj.generateListSize(8)); assertEquals(7, obj.generateListSize(9)); assertEquals(10, obj.generateListSize(10)); assertEquals(10, obj.generateListSize(11)); assertEquals(10, obj.generateListSize(12)); </code></pre> <p>and this is my implementation:</p> <pre><code>public int generateListSize(int listSize) { int result; if (listSize &lt; 1) { result = 0; } else if (7 &lt; listSize &amp;&amp; listSize &lt; 10) { result = 7; } else if (10 &lt;= listSize) { result = 10; } else if (listSize % 2 == 0) { result = listSize - 1; } else { result = listSize; } return result; } </code></pre> <p>This function is use to truncate list to 1,3,5,7,10 elements. When list has 8 elements then return is 7.</p>
[]
[ { "body": "<p>This looks like a very arbitrary function to me. \nI'm wary of long lists of <code>if</code>-statements, but if the function is indeed arbitrary, I don't know how to improve that.</p>\n\n<p>FWIW I'd move the <code>else if (10 &lt; listSize)</code> up, to make it the second conditional. That way the boundary cases are covered first. Your unit tests still pass then.</p>\n\n<p><strong>EDIT</strong>:<br>\nI was able to create a function rule for the range [1,8]. However, this does not change the number of conditionals, as the value returned for listSize==9 remains a special case. Also, it relies on shifting bits, which I do not consider good programming practice when using function rules. For those interested, though, I include it here:</p>\n\n<pre><code>int result = 0;\nif (listSize &lt; 1) {\n result = 0;\n} else if ( listSize &lt; 9 ) {\n result = ( ( ( 1 + listSize ) &gt;&gt; 1 ) &lt;&lt; 1 ) - 1;\n} else if ( listSize == 9 ) {\n result = 7;\n} else if (10 &lt;= listSize) {\n result = 10;\n}\n</code></pre>\n\n<p>In this case I put the <code>if (10 &lt;= listSize)</code> at the bottom. This way the different cases are sorted by the value of <code>listSize</code> that they accept. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T10:03:06.763", "Id": "5013", "ParentId": "5011", "Score": "2" } }, { "body": "<p>Since the rule has lot of exceptions, I fear it is hard to avoid all the ifs...<br>\nHere is my best attempt, not really better than your (perhaps even slightly more cryptic because of the usage of modulo...):</p>\n\n<pre><code>public int generateListSize(int listSize) {\n int result;\n if (listSize &lt; 1) {\n result = 0;\n } else if (listSize &gt;= 10) {\n result = 10;\n } else if (listSize == 9) {\n result = 7;\n } else {\n result = listSize - (1 - listSize % 2);\n }\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T11:50:03.310", "Id": "5015", "ParentId": "5011", "Score": "2" } }, { "body": "<p>I wouldn't search for a \"rule\", just store the \"truncate points\"</p>\n\n<pre><code>private final static int[] truncateSizes = {10,7,5,3,1,0};\n\npublic int generateListSize(int listSize) {\n for(int truncateSize : truncateSizes) {\n if (listSize &gt;= truncateSize) { \n return truncateSize; \n }\n }\n throw new IllegalArgumentException(\"Negative list size\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T14:29:12.123", "Id": "7500", "Score": "0", "body": "Nice one! BTW you need an type declaration in the `for` clause." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T14:08:03.333", "Id": "5016", "ParentId": "5011", "Score": "16" } }, { "body": "<p>I would write the test method as:</p>\n\n<pre><code>// list sizes = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };\nint[] expected = { 0, 1, 1, 3, 3, 5, 5, 7, 7, 7, 10, 10, 10 };\n\nfor (int i = 0; i &lt; results.length; ++i) {\n assertEquals(expected[i], obj.generateListSize(i));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T20:59:03.613", "Id": "7796", "Score": "1", "body": "I disagree. A unit test that contains logic is harder to understand, and is more likely to have bugs in it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T09:03:59.730", "Id": "5108", "ParentId": "5011", "Score": "0" } }, { "body": "<p>Too many assert in one test is a bad smell. It's <a href=\"http://xunitpatterns.com/Assertion%20Roulette.html\" rel=\"nofollow\">Assertion Roulette</a> and you lost <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">Defect Localization</a>. If the first <code>assertEquals</code> throws an exception you don't know anything about the results of the other assert calls which could be important because they could help debugging and defect localization.</p>\n\n<p>The solution is easy, use a parameterized test:</p>\n\n<pre><code>import java.util.Arrays;\nimport java.util.Collection;\n\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\n@RunWith(Parameterized.class)\npublic class ClientTest {\n\n private final int expected;\n private final int input;\n\n public ClientTest(final int expected, final int input) {\n this.expected = expected;\n this.input = input;\n\n }\n\n @Parameters\n public static Collection&lt;Object[]&gt; data() {\n final Object[][] data = new Object[][] { \n { 0, 0 }, { 1, 1 }, { 1, 2 }, { 3, 3 }, { 3, 4 }, { 5, 5 }, { 5, 6 },\n { 7, 7 }, { 7, 8 }, { 7, 9 }, { 10, 10 }, { 10, 11 }, { 10, 12 } };\n return Arrays.asList(data);\n }\n\n @Test\n public void testGenerateListSize() throws Exception {\n final Client obj = new Client();\n assertEquals(expected, obj.generateListSize(input));\n }\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T11:50:53.857", "Id": "6915", "ParentId": "5011", "Score": "0" } } ]
{ "AcceptedAnswerId": "5016", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T08:33:03.583", "Id": "5011", "Score": "6", "Tags": [ "java", "unit-testing" ], "Title": "Simple function in Java" }
5011
<p>I started creating a Dictionary class that accepts objects as there keys:</p> <pre><code>class Dictionary implements ArrayAccess { private $_keys = array(); private $_values = array(); public function offsetExists( $key ) { return false !== array_search( $key, $this-&gt;_keys, true ); } public function offsetGet( $key ) { if( false === ( $index = array_search( $key, $this-&gt;_keys, true ) ) ) { throw new OutOfBoundsException( 'Invalid dictionary key' ); } if( !isset( $this-&gt;_values[ $index ] ) ) { throw new LogicException( 'No matching value found for dictionary key' ); } return $this-&gt;_values[ $index ]; } public function offsetSet( $key, $value ) { if( false !== ( $index = array_search( $key, $this-&gt;_keys, true ) ) ) { $this-&gt;_values[ $index ] = $value; } else { $this-&gt;_keys[] = $key; $this-&gt;_values[] = $value; } } public function offsetUnset( $key ) { if( false === ( $index = array_search( $key, $this-&gt;_keys, true ) ) ) { throw new OutOfBoundsException( 'Invalid dictionary key' ); } if( !isset( $this-&gt;_values[ $index ] ) ) { throw new LogicException( 'No matching value found for dictionary key' ); } array_splice( $this-&gt;_keys, $index, 1 ); array_splice( $this-&gt;_values, $index, 1 ); } } </code></pre> <p>It works pretty well for the very elementary test cases I've done so far. However, I'm worried about three things:</p> <ol> <li><p>Can you think of a situation where <code>$this-&gt;_keys</code> and <code>$this-&gt;_values</code> will not be synchronized with each other anymore, thus leading to data corruption? I thought maybe there could occur a situation where something might happen between the two <code>array_splice</code>s, for instance, in:</p> <pre><code>public function offsetUnset( $key ) { ... array_splice( $this-&gt;_keys, $index, 1 ); array_splice( $this-&gt;_values, $index, 1 ); </code></pre> <p>... leading to data corruption.</p></li> <li><p>I feel <code>array_search()</code> might be inefficient, but I specifically don't want to resort to using <code>spl_object_hash()</code> as keys (and thereby circumventing the need for an internal <em>keys</em> and <em>values</em> <code>array</code>) as I belief this is not bulletproof, as it doesn't guarantee hash uniqueness for objects at all.</p></li> <li><p>I feel <code>array_splice()</code> might be inefficient, but I don't want to resort to <code>unset()</code> as I feel this could lead to unwieldy internal <code>array</code>s keys eventually. I'd like to keep the internal <code>array</code>s keys as tightly packed as possible.</p></li> </ol> <p>Looking forward to your feedback.</p>
[]
[ { "body": "<p>First, I do have to say that you look like you are re-inventing the wheel. You can get all of that with <a href=\"http://www.php.net/manual/en/class.splobjectstorage.php\" rel=\"nofollow\"><code>SplObjectStorage</code></a>. Since you're using <code>OutOfBoundsException</code>, you're already using the Spl types.\n<hr />\nTo your specific questions:</p>\n\n<ol>\n<li>It is hard to think of such a situation, but that doesn't mean that it is inconceivable.</li>\n<li>While <code>spl_object_hash</code> is not guaranteed unique, it is highly likely that you will run out of memory far before encountering a hash collision. As the documents state: <em><code>A string that is unique for each currently existing object and is always the same for each object.</code></em> It is both faster and cheaper than keeping/maintaining your own internal state.</li>\n<li>Yes, the internal keys will not be quite as ordered in the internal arrays, but it will only make a substantial difference if you actually have a problem keeping the two arrays synced &mdash; basically, if you can get #1 to work consistently and without fail, then <code>unset</code> will not matter here.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T17:58:04.470", "Id": "5020", "ParentId": "5018", "Score": "3" } }, { "body": "<p>I stumbled upon your implementation and I can really appreciate it - I think this will work well for most people without extreme engineering.</p>\n\n<p>Unfortunately, <code>spl_object_hash</code> is just a string representation of the object reference in memory. For example, if you create two copies of the same array: <code>array( 'a' =&gt; 1, 'b' =&gt; 2 )</code>, each object will return a different <code>spl_object_hash</code>.</p>\n\n<p>Other languages (such as Java and C#) have a concept of <code>Equatable</code> objects. <code>Equatable</code> objects do 2 things:</p>\n\n<ol>\n<li><code>GetHashCode()</code></li>\n<li><code>IsEqual( $other )</code> - this seems to be what your <code>array_search()</code> is doing.</li>\n</ol>\n\n<p>BUT (pay careful attention here) <code>GetHashCode()</code> IS NOT COMPLETELY UNIQUE. <code>GetHashCode()</code> is 2 different things:</p>\n\n<ul>\n<li>Consistent!</li>\n<li>FAST!</li>\n</ul>\n\n<p>The idea here is that you can reduce the array passed to <code>array_search</code> VERY QUICKLY using <code>GetHashCode()</code>, THEN you find the actual match using <code>array_search()</code>/<code>IsEqual()</code>.</p>\n\n<p>The code might look something like this:</p>\n\n<pre><code>$objectiveLookup = new ObjectiveLookup();\n\n//create an association between $obj1 and $val1\n$objectiveLookup[ $obj1 ] = $val1;\n\n//Here's what actually happens:\n {\n $hash_code = $obj1-&gt;GetHashCode();\n if( !isset( $objectiveLookup-&gt;_similarValues[ $hash_code ] ) )\n $objectiveLookup-&gt;_similarValues[ $hash_code ] = array();\n\n //regular array\n $objectiveLookup-&gt;_similarValues[ $hash_code ][] = $obj1;\n\n //this is an SplObjectStorage\n $objectiveLookup-&gt;_actualValues[ $obj1 ] = $val1;\n }\n</code></pre>\n\n<p>Then, after thousands, or even millions of objects are in memory, only a fraction of this should be <code>_similarValues</code>.</p>\n\n<p>Because of this, finding values should be MUCH faster:</p>\n\n<pre><code>//this NEW object should be \"IsEqual()\" to $obj1\n$obj1075383 = new CoolObject();\n\n//get a value\n$val1 = $objectiveLookup[ $obj1075383 ];\n\n//Here's what actually happens:\n $hash_code = $obj1075383-&gt;GetHashCode();\n if( isset( $objectiveLookup-&gt;_similarValues[ $hash_code ] ) )\n {\n $similar_values = $objectiveLookup-&gt;_similarValues[ $hash_code ];\n\n //find the one that IsEqual()\n $matching_index = array_search( $similar_values, $obj1075383 );\n $actual_object_key = $similar_values[ $matching_index ];\n\n $actual_value = $objectiveLookup-&gt;_actualValues[ $actual_object_key ];\n return $actual_value;\n }\n</code></pre>\n\n<p>Overall, nice work fireeyedboy!!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-22T03:29:21.480", "Id": "5516", "ParentId": "5018", "Score": "0" } } ]
{ "AcceptedAnswerId": "5020", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T16:27:40.907", "Id": "5018", "Score": "2", "Tags": [ "php", "optimization", "performance" ], "Title": "PHP Dictionary class accepting objects as keys" }
5018
<p>I have created an extension for unit-testing my own equality implementations. Is it a good approach in general to have such extensions for unit testing? What unit-testing extensions do you use?</p> <pre><code>public static class EqualityExtensions { /// &lt;summary&gt; /// Checks that all variations Equals method conforms to equality by properties /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt; /// &lt;param name="variations"&gt;&lt;/param&gt; /// &lt;param name="propertyAccessors"&gt;Property accessors specifying which properties contribute to equality&lt;/param&gt; /// &lt;returns&gt;True, if all instances from a set conform to property equality&lt;/returns&gt; /// &lt;example&gt; /// Assert.IsTrue(from name in new[] {"foo","bar"} from count in new[] {1,2} select new MyClass{Name=name,Count=count}).ConformToPropertyEquality(x=&gt;x.Name,x=&gt;x.Count)) /// &lt;/example&gt; public static bool ConformToPropertyEquality&lt;T&gt;(this IEnumerable&lt;T&gt; variations, params Func&lt;T, object&gt;[] propertyAccessors) { var propertyComparisions = from lhs in variations from rhs in variations select Equals( (from comparator in propertyAccessors select Equals(comparator(lhs), comparator(rhs))).All(c =&gt; c), Equals(lhs, rhs) ); return propertyComparisions.All(p =&gt; p); } } </code></pre>
[]
[ { "body": "<p>It's perfectly OK. As an example <a href=\"http://sharptestex.codeplex.com/\" rel=\"nofollow\">SharpTestEx</a> is a whole library with such an extensions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T19:14:01.797", "Id": "5022", "ParentId": "5019", "Score": "1" } } ]
{ "AcceptedAnswerId": "5022", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T17:36:13.603", "Id": "5019", "Score": "4", "Tags": [ "c#", "unit-testing" ], "Title": "Unit testing extension for equality testing" }
5019
<p>I'm a complete beginner of <a href="http://factorcode.org/">Factor</a>, but I just managed to solved <a href="http://projecteuler.net/problem=1">Euler Problem #1</a> using it, and would love to have the code reviewed. Anything that can be improved? In particular I'm wondering if there is a cleaner or more idiomatic way to write the <strong>mult3or5?</strong> word.</p> <pre><code>USING: math kernel sequences math.ranges prettyprint ; IN: euler1 : mult? ( x y -- ? ) rem 0 = ; : mult3? ( x -- ? ) 3 mult? ; : mult5? ( x -- ? ) 5 mult? ; : mult3or5? ( x -- ? ) dup mult3? swap mult5? or ; : sumMultsOf3or5 ( seq -- n ) [ mult3or5? ] filter sum ; : solveEuler1 ( -- ) 0 1000 (a,b) sumMultsOf3or5 . ; </code></pre>
[]
[ { "body": "<p>I'm a Factor beginner too, but I'd use the <code>zero?</code> word from <code>math</code> in the definition of <code>mult</code>:</p>\n\n<pre><code>: mult? ( x y -- ? ) rem zero? ;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T21:12:15.893", "Id": "7799", "Score": "0", "body": "Thanks. A small improvement though. Let me know if you find something else." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T23:08:28.717", "Id": "5048", "ParentId": "5024", "Score": "5" } }, { "body": "<p>dup f swap g is a common idiom, so Factor has bi.</p>\n\n<pre><code>: mult3or5? ( x -- ? ) [ mult3? ] [ mult5? ] bi or ;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T01:42:40.330", "Id": "12917", "ParentId": "5024", "Score": "6" } } ]
{ "AcceptedAnswerId": "12917", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T20:37:53.587", "Id": "5024", "Score": "10", "Tags": [ "project-euler", "factor-lang" ], "Title": "Project Euler problem 1 in Factor" }
5024
<p>I've created a program that uses <code>System.Graphics</code> to render a simple (small) 2D scene to the screen. The problem is, for some reason, it starts to quickly accumulate memory. In fact, it goes from only 100,000K Mem to <strong>ten times that</strong> and then crashes. As expected, the frame-rate of the program drops dramatically as well (100+ to 1fps).</p> <p>I believe the culprit is in my rendering loop. Problem is, as hard as I search, besides a couple bits of messy code, I can't find anything relevant to the problem.</p> <p>It may not be inside of this code snippet - if not, that's ok. I'll just continue my search personally through my application.</p> <p>Here is my <code>Engine.vb</code> source:</p> <pre><code>Public Class Engine Public debugEnabled As Boolean = False Private _currentMap Public Property currentMap As Map Get Return _currentMap End Get Set(ByVal value As Map) _currentMap = value luaEngine.Close() cTime.Reset() sprites.Clear() cTime.Start() luaEngine = New Lua End Set End Property Public currentData As MemoryGrid Public currentInstance As MemoryGrid Public fForm As Control Public cTime As New Stopwatch Public buffer As Bitmap Friend Shared luaEngine As New Lua Public sprites As New Dictionary(Of String, Bitmap) #Region "EVENTS" Public Event event_keydown(ByVal key As String) Public Event event_keyup(ByVal key As String) #End Region Public Sub Render() Dim fpsTimer As New Stopwatch fpsTimer.Start() If fForm IsNot Nothing Then If buffer IsNot Nothing Then Dim e As Graphics = fForm.CreateGraphics() e.InterpolationMode = Drawing2D.InterpolationMode.NearestNeighbor e.DrawImage(buffer, New Rectangle(0, 0, fForm.Width, fForm.Height)) buffer.Dispose() End If buffer = New Bitmap(fForm.Width, fForm.Height) Using gfx As Graphics = Graphics.FromImage(buffer) gfx.FillRectangle(Brushes.Black, 0, 0, fForm.Width, fForm.Height) If currentMap IsNot Nothing Then For z As Integer = 0 To Grid.LAYERLIMIT For x As Integer = currentMap.DisplayXOffset To currentMap.DisplayXOffset + Math.Ceiling(fForm.Width / 8) For y As Integer = currentMap.DisplayYOffset To currentMap.DisplayYOffset + Math.Ceiling(fForm.Height / 8) Dim terrObj As GridElement = currentMap.Level.getCell(z, x, y) If terrObj IsNot Nothing Then Dim _position As Point Dim _size As Size terrObj.tileImage(Me, _position, _size) Dim cSprites As Bitmap = Nothing : sprites.TryGetValue(terrObj.SpriteSheet &amp; ".png", cSprites) gfx.DrawImage(cSprites, (x - currentMap.DisplayXOffset) * 8 + terrObj.XOffset, (y - currentMap.DisplayYOffset) * 8 + terrObj.YOffset, New RectangleF(_position.X, _position.Y, _size.Width, _size.Height), Drawing.GraphicsUnit.Pixel) End If Next Next Next End If gfx.DrawString("FPS: " &amp; Math.Round(1000 / fpsTimer.ElapsedMilliseconds), New Font("Arial", 7), Brushes.Red, New PointF(5, 5)) fpsTimer.Stop() End Using End If End Sub </code></pre> <p><code>'...</code></p> <p>There are a couple more procedures after this, but, they are related to my Lua implementation. The problem has existed since before I implemented Lua.</p> <p>Basically, the variables are at the top, I also have my <code>Sub Render()</code> at the bottom. If you need any of the other code, I'll make sure to post it. Just say so in the comments.</p> <p><strong>REMEMBER:</strong> I'm not 100% sure that the issue lies in this one class (or in this class at all). If you can't find a reason, so be it. Anything to speed it up (if perhaps my messy programming has slowed it down that bad) would also be appreciated.</p> <p><strong>EDIT 1</strong></p> <p>Please take a look at the following screenshot of me using ANTS Memory Profiler:</p> <p><img src="https://i.stack.imgur.com/iEbDD.png" alt="enter image description here"></p> <p>I have a multidimensional array that contains instances of a class called 'GridElement'. The array is 3D. I use it to layer and get elements from specific locations to display. According to this though, it says it takes of like 94% of my application's memory, and for the most part, it's filled with empty slots. The highest number of elements I've put into it is like 20-30 (which is a fraction of what it needs to be able to handle).</p> <p>So basically, how is this empty 3D array taking up so much space when it has only a couple of elements in it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T19:19:07.973", "Id": "7579", "Score": "0", "body": "So you chose my response as correct, but I'm curious; what was the ultimate cause?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:21:36.630", "Id": "7582", "Score": "0", "body": "@EdS. The problem wasn't actually directly inside of the information above. Using the ANT program and some simple tools (basically, elimination via commenting out code and running), I determined that it was the line running `terrObj.tileImage(Me, _position, _size)`. I've figure out why thanks to you. It will just be a while before I get a non-hacked up method for getting it to work. Thanks a ton :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T04:16:15.173", "Id": "57217", "Score": "0", "body": "Just to make sure: is your code working now? This post is still receiving close votes, but it'll stop if the code does work." } ]
[ { "body": "<p>First off; Use a good memory profiler. If you can reason about why something like this is happening quickly then fine. Otherwise you are wasting time when there are plenty of great tools out there which can make your life a whole lot easier. I personally use <a href=\"http://www.red-gate.com/products/dotnet-development/ants-memory-profiler/\" rel=\"nofollow\">RedGate's Profiler</a> for .NET apps (I have no affiliation with them, I just think it's really good and it has a 14 day free trial, fully featured).</p>\n\n<p>Now, onto your code...</p>\n\n<p>You are creating <code>Graphics</code> objects without disposing them in one area. It should be:</p>\n\n<pre><code>Using e As Graphics = fForm.CreateGraphics()\n e.InterpolationMode = Drawing2D.InterpolationMode.NearestNeighbor\n e.DrawImage(buffer, New Rectangle(0, 0, fForm.Width, fForm.Height))\n buffer.Dispose()\nEnd Using\n</code></pre>\n\n<p>Next, you have some code which is really not optimal in a tight render loop. For example, using <code>TryGetValue</code> is a bad idea as it will throw a (handled) exception if the value is not found. You really don't want to be throwing exceptions in that area of code. Design it such that you can assume the value exists.</p>\n\n<p>You are also creating a lot of <code>Bitmap</code>s. If that is called in a tight loop then you may not be allowing enough time for the GC to come in an clean up after you. Also, the memory is likely allocated on the LOH (Large Object Heap), so you may have a lot of fragmentation going on. Why not use one <code>Bitmap</code> and be done with it? You don't need to create a new one each time if the width and height is constant, which it really should be for a game. Just draw over the same frame buffer in each call to <code>Render</code>.</p>\n\n<p>Again though, go use a decent profiler. It will tell you where your memory is allocated and it will also alert you to LOH fragmentation, as well as <code>IDisposable</code> objects that you are not calling <code>Dispose()</code> on.</p>\n\n<p>EDIT: You are reading your profiling results incorrectly. It is telling you that 784MB (the <em>vast</em> majority of the memory allocated to your process) is unmanaged, i.e., probably Bitamps. Look for IDisposables that you are not disposing of. Have you tried using a single screen buffer instead of creating one every frame like I suggested?</p>\n\n<p>You also have ~800MB allocated to the runtime that is not being used. You need to continue with the profiler and analyze the results. That is just the first page, they have tutorials which will lead you through the rest of it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T13:45:33.817", "Id": "7518", "Score": "0", "body": "Could you please take a look at my edit please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T01:15:31.707", "Id": "57206", "Score": "0", "body": "`Dictionary.TryGetValue()` doesn't throw. It's like `Int32.TryParse` - the idea is *specifically* to avoid throwing an exception, by returning `False` if the operation fails." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T01:24:26.610", "Id": "57210", "Score": "1", "body": "@retailcoder: You didn't read closely enough. An exception is thrown, and then handles, and then false is returned. That doesn't mean that the exception was never thrown. In a tight loop you want to avoid any exceptions being thrown" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-14T01:26:14.360", "Id": "57211", "Score": "0", "body": "You're right, I *did* skim through. Downvote removed :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T23:54:33.370", "Id": "5028", "ParentId": "5027", "Score": "5" } } ]
{ "AcceptedAnswerId": "5028", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-27T23:04:17.490", "Id": "5027", "Score": "3", "Tags": [ "vb.net", "memory-management" ], "Title": "My program spikes from 100,000K mem to 1,000,000K mem in a matter of minutes in my program in VB.net" }
5027
<p>I had an efficiency problem like I thought and I didn't have the best solution <a href="https://stackoverflow.com/questions/7552604/should-i-merge-images-in-memory-py-or-in-view-html">here</a>.</p> <p>My solution was \$O(n)\$ and directly a more experienced member told me a solution that is \$O(1)\$, that only fetches one element and doesn't have to do a count. I'd like to rewrite to that solution, if you agree that is the next thing I should do. I've also been considering adding the function crop image to the <a href="http://apps.facebook.com/cyberfaze" rel="nofollow noreferrer">Facebook application</a> I write where there is no bug. I just plan to implement the proposed change so that images get fetches faster exactly like was suggested as answer to the question above.</p> <p>Do you agree that it's the next thing to do about this code?</p> <pre><code>import random from google.appengine.api import files, images class CyberFazeHandler(BaseHandler): """ Every time you call this function, it will perform a count operation, which is O(n) with the number of FileInfo entities, then perform an offset query, which is O(n) with the offset. This is extremely slow and inefficient, and will get more so as you increase the number of images. If you expect the set of images to be small (less than a few thousand) and fairly constant, simply store them in code, which will be faster than any other option. If the set is larger, or changes at runtime, assign a random value between 0 and 1 to each entity, and use a query like this to retrieve a randomly selected one: """ def get_random_image(self, category): fileinfos = FileInfo.all().filter('category =', category) return fileinfos[random.randint(0, fileinfos.count() - 1)] """ do like this instead q = FileInfo.all() q.filter('category =', category) q.filter('random &gt;=', random.random()) return q.get() """ def get(self): """ If the user will be loading a lot of these mashups, it makes more sense to send them as separate images, because there will be fewer images for the browser to cache (a+b+c images instead of a*b*c). """ eyes_image = self.get_random_image(category='eyes') nose_image = self.get_random_image(category='nose') mouth_image = self.get_random_image(category='mouth') eyes_data = None try: eyes_data = blobstore.fetch_data(eyes_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find eyes data for file ' + str(eyes_image.key().id()) + ' (' + unicode(e) + u')') eyes_img = None try: eyes_img = images.Image(image_data=eyes_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find eyes img for file ' + str(eyes_image.key().id()) + ' (' + unicode(e) + u')') nose_data = None try: nose_data = blobstore.fetch_data(nose_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find nose data for file ' + str(nose_image.key().id()) + ' (' + unicode(e) + u')') nose_img = None try: nose_img = images.Image(image_data=nose_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find nose img for file ' + str(nose_image.key().id()) + ' (' + unicode(e) + u')') mouth_data = None try: mouth_data = blobstore.fetch_data(mouth_image.blob.key(), 0, 50000) except Exception, e: self.set_message(type=u'error', content=u'Could not find mouth data for file ' + str(eyes_image.key().id()) + ' (' + unicode(e) + u')') mouth_img = None try: mouth_img = images.Image(image_data=mouth_data) except Exception, e: self.set_message(type=u'error', content=u'Could not find mouth img for file ' + str(mouth_image.key().id()) + ' (' + unicode(e) + u')') minimum = min(int(eyes_img.width), int(nose_img.width), int(mouth_img.width)) eyes_url = images.get_serving_url(str(eyes_image.blob.key()), size=minimum) nose_url = images.get_serving_url(str(nose_image.blob.key()), size=minimum) mouth_url = images.get_serving_url(str(mouth_image.blob.key()), size=minimum) self.render( u'cyberfaze', minimum=minimum, eyes_image=eyes_image, eyes_url=eyes_url, nose_image=nose_image, nose_url=nose_url, mouth_image=mouth_image, mouth_url=mouth_url, form_url=blobstore.create_upload_url('/upload'), ) class UserRunsHandler(BaseHandler): """Show a specific user's runs,""" # ensure friendship with the logged in user""" @user_required def get(self, user_id): if True: # self.user.friends.count(user_id) or self.user.user_id == user_id: user = User.get_by_key_name(user_id) if not user: self.set_message(type=u'error', content=u'That user does not use Run with Friends.' ) self.redirect(u'/') return self.render(u'user', user=user, runs=Run.find_by_user_ids([user_id])) else: self.set_message(type=u'error', content=u'You are not allowed to see that.' ) self.redirect(u'/') class RunHandler(BaseHandler): """Add a run""" @user_required def post(self): try: location = self.request.POST[u'location'].strip() if not location: raise RunException(u'Please specify a location.') distance = float(self.request.POST[u'distance'].strip()) if distance &lt; 0: raise RunException(u'Invalid distance.') date_year = int(self.request.POST[u'date_year'].strip()) date_month = int(self.request.POST[u'date_month'].strip()) date_day = int(self.request.POST[u'date_day'].strip()) if date_year &lt; 0 or date_month &lt; 0 or date_day &lt; 0: raise RunException(u'Invalid date.') date = datetime.date(date_year, date_month, date_day) run = Run(user_id=self.user.user_id, location=location, distance=distance, date=date) run.put() title = run.pretty_distance + u' miles @' + location publish = u'&lt;a onclick=\'publishRun(' \ + json.dumps(htmlescape(title)) \ + u')\'&gt;Post to facebook.&lt;/a&gt;' self.set_message(type=u'success', content=u'Added your run. ' + publish) except RunException, e: self.set_message(type=u'error', content=unicode(e)) except KeyError: self.set_message(type=u'error', content=u'Please specify location, distance &amp; date.' ) except ValueError: self.set_message(type=u'error', content=u'Please specify a valid distance &amp; date.' ) except Exception, e: self.set_message(type=u'error', content=u'Unknown error occured. (' + unicode(e) + u')') self.redirect(u'/') class RealtimeHandler(BaseHandler): """Handles Facebook Real-time API interactions""" csrf_protect = False def get(self): if self.request.GET.get(u'setup') == u'1' and self.user \ and conf.ADMIN_USER_IDS.count(self.user.user_id): self.setup_subscription() self.set_message(type=u'success', content=u'Successfully setup Real-time subscription.' ) elif self.request.GET.get(u'hub.mode') == u'subscribe' \ and self.request.GET.get(u'hub.verify_token') \ == conf.FACEBOOK_REALTIME_VERIFY_TOKEN: self.response.out.write(self.request.GET.get(u'hub.challenge' )) logging.info(u'Successful Real-time subscription confirmation ping.' ) return else: self.set_message(type=u'error', content=u'You are not allowed to do that.') self.redirect(u'/') def post(self): body = self.request.body if self.request.headers[u'X-Hub-Signature'] != u'sha1=' \ + hmac.new(self.facebook.app_secret, msg=body, digestmod=hashlib.sha1).hexdigest(): logging.error(u'Real-time signature check failed: ' + unicode(self.request)) return data = json.loads(body) if data[u'object'] == u'user': for entry in data[u'entry']: taskqueue.add(url=u'/task/refresh-user/' + entry[u'id']) logging.info('Added task to queue to refresh user data.' ) else: logging.warn(u'Unhandled Real-time ping: ' + body) def setup_subscription(self): path = u'/' + conf.FACEBOOK_APP_ID + u'/subscriptions' params = { u'access_token': conf.FACEBOOK_APP_ID + u'|' \ + conf.FACEBOOK_APP_SECRET, u'object': u'user', u'fields': _USER_FIELDS, u'callback_url': conf.EXTERNAL_HREF + u'realtime', u'verify_token': conf.FACEBOOK_REALTIME_VERIFY_TOKEN, } response = self.facebook.api(path, params, u'POST') logging.info(u'Real-time setup API call response: ' + unicode(response)) class RefreshUserHandler(BaseHandler): """Used as an App Engine Task to refresh a single user's data if possible""" csrf_protect = False def post(self, user_id): logging.info('Refreshing user data for ' + user_id) user = User.get_by_key_name(user_id) if not user: return try: user.refresh_data() except FacebookApiError: user.dirty = True user.put() class FileInfo(db.Model): blob = blobstore.BlobReferenceProperty(required=True) uploaded_by = db.UserProperty() facebook_user_id = db.StringProperty() uploaded_at = db.DateTimeProperty(required=True, auto_now_add=True) category = db.CategoryProperty(choices=('eyes', 'nose', 'mouth', 'other')) class FileBaseHandler(webapp.RequestHandler): def render_template(self, file, template_args): path = os.path.join(os.path.dirname(__file__), 'templates', file) self.response.out.write(template.render(path, template_args)) class FileUploadFormHandler(FileBaseHandler): # @util.login_required # @user_required def get(self): # user = users.get_current_user() if True: # user: # signed in already # self.response.out.write('Hello &lt;em&gt;%s&lt;/em&gt;! [&lt;a href="%s"&gt;sign out&lt;/a&gt;]' % ( # user.nickname(), users.create_logout_url(self.request.uri))) self.render_template('upload.html', {'logout_url' : (users.create_logout_url(r'/' ) if users.get_current_user() else None)}) else: # let user choose authenticator self.response.out.write('Hello world! Sign in at: ') class FileUploadHandler(BaseHandler, blobstore_handlers.BlobstoreUploadHandler): csrf_protect = False def post(self): blob_info = self.get_uploads()[0] if False: # not users.get_current_user(): blob_info.delete() self.redirect(users.create_login_url(r'/')) return file_info = FileInfo(blob=blob_info.key()) # , logging.debug('if user') if self.user: logging.debug('found user') file_info.facebook_user_id = self.user.user_id logging.debug('set user id') db.put(file_info) self.redirect('/file/%d' % (file_info.key().id(), )) class AjaxSuccessHandler(FileBaseHandler): def get(self, file_id): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write('%s/file/%s' % (self.request.host_url, file_id)) class FileInfoHandler(BaseHandler, FileBaseHandler): def get(self, file_id): file_info = FileInfo.get_by_id(long(file_id)) if not file_info: self.error(404) return self.render(u'info', file_info=file_info, logout_url=users.create_logout_url(r'/')) class FileDownloadHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, file_id): file_info = FileInfo.get_by_id(long(file_id)) if not file_info or not file_info.blob: self.error(404) return self.send_blob(file_info.blob, save_as=True) class GenerateUploadUrlHandler(FileBaseHandler): # @util.login_required def get(self): self.response.headers['Content-Type'] = 'text/plain' self.response.out.write(blobstore.create_upload_url('/upload')) class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, resource): resource = str(urllib.unquote(resource)) blob_info = blobstore.BlobInfo.get(resource) self.send_blob(blob_info) class SetCategoryHandler(webapp.RequestHandler): def get(self, file_id): file_info = FileInfo.get_by_id(long(file_id)) if not file_info or not file_info.blob or file_id == '25001': self.error(404) return file_info.category = self.request.get('cg') file_info.put() self.response.out.write('category updated') def main(): routes = [ (r'/', CyberFazeHandler), (r'/user/(.*)', UserRunsHandler), (r'/run', RunHandler), (r'/realtime', RealtimeHandler), (r'/task/refresh-user/(.*)', RefreshUserHandler), ('/ai', FileUploadFormHandler), ('/serve/([^/]+)?', ServeHandler), ('/upload', FileUploadHandler), ('/generate_upload_url', GenerateUploadUrlHandler), ('/file/([0-9]+)', FileInfoHandler), ('/file/set/([0-9]+)', SetCategoryHandler), ('/file/([0-9]+)/download', FileDownloadHandler), ('/file/([0-9]+)/success', AjaxSuccessHandler), ] application = webapp.WSGIApplication(routes, debug=os.environ.get('SERVER_SOFTWARE', '').startswith('Dev' )) util.run_wsgi_app(application) if __name__ == u'__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T21:07:44.343", "Id": "7536", "Score": "1", "body": "the next thing you do is up to you. There isn't a defined order of how you should do things. What are your priorities? That's how you decide where you should spend your effort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T06:04:01.840", "Id": "7554", "Score": "0", "body": "@Winston Ewert I fixed this issue and now I just do next thing and it's up to me. Thank you for the excellent encouragement and support. I prioritize performance, security and user-friendliness in that order. Is there something else to prioritize?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T12:07:54.700", "Id": "7563", "Score": "2", "body": "How about correctness?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T15:48:40.257", "Id": "7571", "Score": "0", "body": "Naturally and only the best solution is the correct one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T15:55:49.343", "Id": "7572", "Score": "1", "body": "Right, so I'd probably put my priorties as security, correctness, user-friendliness, and then performance. So performance is the least important concern. Its much more important that its correct, easy to use and secure then it being fast." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:01:30.827", "Id": "7580", "Score": "0", "body": "That's interesting since it tells us what to choose when we face a common tradeoff between security and performance. A higher security is usually slower." } ]
[ { "body": "<pre><code>class CyberFazeHandler(BaseHandler):\n\n def get_random_image(self, category):\n</code></pre>\n\n<p>I'd recommend you consider adding docstrings, to a give quick explanation what your functions are doing.</p>\n\n<pre><code> q = FileInfo.all()\n q.filter('category =', category)\n q.filter('randomvalue &gt;=', random.random())\n return q.get()\n\n def get_random_image_legacy(self, category):\n fileinfos = FileInfo.all().filter('category =', category)\n return fileinfos[random.randint(0, fileinfos.count() - 1)]\n</code></pre>\n\n<p>Why would you keep a legacy method around? </p>\n\n<pre><code> def get(self):\n\n eyes_image = self.get_random_image(category='eyes')\n if not eyes_image:\n logging.debug(\"getting eyes failed, trying legacy method\")\n eyes_image = self.get_random_image_legacy(category='eyes')\n nose_image = self.get_random_image(category='nose')\n if not nose_image:\n nose_image = self.get_random_image_legacy(category='nose')\n\n mouth_image = self.get_random_image(category='mouth')\n if not mouth_image:\n mouth_image = self.get_random_image_legacy(category='mouth')\n</code></pre>\n\n<p>You've got pretty much the same thing repeated three times. Write a generic function that can handle getting the image and handling the failure case</p>\n\n<pre><code> eyes_data = None\n try:\n eyes_data = blobstore.fetch_data(eyes_image.blob.key(), 0,\n 50000)\n except Exception, e:\n self.set_message(type=u'error',\n content=u'Could not find eyes data for file '\n + str(eyes_image.key().id()) + ' ('\n + unicode(e) + u')')\n</code></pre>\n\n<p>Do you really want to catch any exception here? Usually you want to catch a more specific exception. </p>\n\n<pre><code> eyes_img = None\n</code></pre>\n\n<p>Do this in the except clause</p>\n\n<pre><code> try:\n eyes_img = images.Image(image_data=eyes_data)\n except Exception, e:\n self.set_message(type=u'error',\n content=u'Could not find eyes img for file '\n + str(eyes_image.key().id()) + ' ('\n + unicode(e) + u')')\n\n nose_data = None\n try:\n nose_data = blobstore.fetch_data(nose_image.blob.key(), 0,\n 50000)\n except Exception, e:\n self.set_message(type=u'error',\n content=u'Could not find nose data for file '\n + str(nose_image.key().id()) + ' ('\n + unicode(e) + u')')\n\n nose_img = None\n\n try:\n nose_img = images.Image(image_data=nose_data)\n except Exception, e:\n self.set_message(type=u'error',\n content=u'Could not find nose img for file '\n + str(nose_image.key().id()) + ' ('\n + unicode(e) + u')')\n\n mouth_data = None\n try:\n mouth_data = blobstore.fetch_data(mouth_image.blob.key(),\n 0, 50000)\n except Exception, e:\n self.set_message(type=u'error',\n content=u'Could not find mouth data for file '\n + str(eyes_image.key().id()) + ' ('\n + unicode(e) + u')')\n\n mouth_img = None\n\n try:\n mouth_img = images.Image(image_data=mouth_data)\n except Exception, e:\n self.set_message(type=u'error',\n content=u'Could not find mouth img for file '\n + str(mouth_image.key().id()) + ' ('\n + unicode(e) + u')')\n</code></pre>\n\n<p>Again almost exact code duplicated several times, refactor it into a function.</p>\n\n<pre><code> minimum = min(int(eyes_img.width), int(nose_img.width),\n int(mouth_img.width))\n</code></pre>\n\n<p>I'd put the int on the outside so you don't have to repeat it</p>\n\n<pre><code> eyes_url = images.get_serving_url(str(eyes_image.blob.key()),\n size=minimum)\n nose_url = images.get_serving_url(str(nose_image.blob.key()),\n size=minimum)\n mouth_url = images.get_serving_url(str(mouth_image.blob.key()),\n size=minimum)\n\n self.render(\n u'cyberfaze',\n minimum=minimum,\n eyes_image=eyes_image,\n eyes_url=eyes_url,\n nose_image=nose_image,\n nose_url=nose_url,\n mouth_image=mouth_image,\n mouth_url=mouth_url,\n form_url=blobstore.create_upload_url('/upload'),\n )\n</code></pre>\n\n<p>Basically, you've got the same logic repeating for eyes, nose and mouth. I'd probably write a FaceFeature object to handle that logic and then create three of them. That way we'd get rid of the duplication.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:03:45.770", "Id": "7581", "Score": "0", "body": "Thank you for very clear instructions how I can improve! The reason I kept the legacy method is that even though it is slow (it uses count()) it always works so if there was an error with the new code that is faster since it only fetches one element then it could work slower and with the legacy function. The change I did was to add the randomness to the entity instead of the fetch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:32:16.840", "Id": "7585", "Score": "0", "body": "@NiklasR, If there is an error with the new code fix that, don't introduce a fallback." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T16:26:43.147", "Id": "5060", "ParentId": "5032", "Score": "2" } } ]
{ "AcceptedAnswerId": "5060", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T12:15:06.907", "Id": "5032", "Score": "1", "Tags": [ "python", "performance", "google-app-engine", "facebook" ], "Title": "CyberFaze app for Facebook" }
5032
<p>This is a INSERT function. It's working... I just pulled out the function from the class, atm to try it out. And improve. I think the code is a bit messy, And I am pretty sure I can improve the code, less code, for example.. Any ideas?</p> <pre><code> $data['test'] = array('username' =&gt; 'john', 'password' =&gt; 'hello', 'userlevel' =&gt; '__d'); $table = 'users'; $numItems = count($data['test']); $i = 0; $sql = "INSERT INTO " . $table . "(". implode(", ", array_keys($data['test'])) .")"; $sql .= " VALUES ("; $i = 0; foreach ($data['test'] as $value) { if ($i+1 == $numItems and $value == '__d') { $sql .= "" . 'NOW()' . ")"; } else if ($i+1 == $numItems) { $sql .= "'" . $value . "')"; } else if ($value == '__d') { $sql .= "" . 'NOW()' . ", "; } else { $sql .= "'" . $value . "', "; } $i++; } echo $sql; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:38:47.283", "Id": "7521", "Score": "0", "body": "inside the `foreach` why the comparation of `$i + 1 == $numItems` if you end up doing the same, be that comparation true or false?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:43:41.630", "Id": "7523", "Score": "0", "body": "Well I need to determine If I am going to end with a , or ') :)" } ]
[ { "body": "<p>Why do you not do:</p>\n\n<p>VALUES = <code>implode(\", \", array_values($values))</code></p>\n\n<p>If you can do:</p>\n\n<pre><code>$values = array('username' =&gt; \"'john'\", \n 'password' =&gt; \"'hello'\",\n 'userlevel' =&gt; \"0\");\n</code></pre>\n\n<blockquote>\n <p>There are many way to mark up the value of array with double quote.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:39:21.980", "Id": "7522", "Score": "0", "body": "It feels easier to type 'username' => $_POST['username'], 'date' = '__d' then just having all these \"\" and ''" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:22:38.253", "Id": "5035", "ParentId": "5033", "Score": "0" } }, { "body": "<p>This is what you have, cleaned a little</p>\n\n<pre><code>foreach ($data['test'] as $value) {\n\n if ($value == '__d') {\n $sql .= 'NOW()';\n } else {\n $sql .= \"'\" . $value . \"'\";\n }\n $i++; // add before the comparisson\n // make the comparrison at one place\n // if the number != total, then we need a comma.\n if($i != $numItems) $sql .= ',';\n}\n// always end with a close paren.\n$sql .= ')';\n</code></pre>\n\n<p>But you are better off using implode and replace:</p>\n\n<pre><code>// implode using the quotes and commas.\n$values = \"'\".implode(\"', '\", array_values($values)).\"'\";\n// swap out __d for NOW\n$sql .= str_replace(\"'__d'\",'NOW()',$values);\n</code></pre>\n\n<p>Of course, you really need to make sure that you've cleaned all of those values with <code>mysql_real_escape_string</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:56:27.747", "Id": "5037", "ParentId": "5033", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T14:04:01.350", "Id": "5033", "Score": "1", "Tags": [ "php", "mysql", "sql", "array" ], "Title": "Php INSERT class function" }
5033
<p>I have written a small template Viewer/Controller esque library that I would like some critiques on.</p> <p>The library is <a href="https://github.com/maniator/SmallFry/tree/f957f3609c1f108c8cd3b79e4d47a57740e85b42">located here</a></p> <p>If you are looking for where to start, check out <code>App.php</code> and <code>AppController.php</code> in the <code>classes</code> folder</p> <p>I would really love to hear your critiques on:</p> <ul> <li>Code quality</li> <li>Code clarity</li> <li>How to improve</li> <li>Anything else that needs clarification expansion etc </li> <li>I have also heard that my static methods (like my <code>get</code> and <code>set</code> methods in <code>App</code>) should be replaced with something more <em>dynamic</em>, How would I go about doing that?</li> </ul> <p>I'm more interested in what I'm doing wrong than right. </p> <p>Any opinions on the actual usefulness of the library are welcome.</p> <p><a href="https://github.com/maniator/SmallFry/blob/f957f3609c1f108c8cd3b79e4d47a57740e85b42/classes/App.php">App.php</a>:</p> <pre><code>&lt;?php /** * Description of App * * @author nlubin */ class App { /** * Holds all of the app variables * @var array */ private static $app_vars = array(); /** * Will be an App object * @var App */ private static $app = null; /** * Get a single app_vars variable * @param string $v * @return mixed */ public static function get($v){ return isset(self::$app_vars[$v])?self::$app_vars[$v]:false; } /** * Get all app_vars variables * @return array app_vars */ public static function getAll(){ return self::$app_vars; } /** * Set an app_vars variable * * @param string $v * @param mixed $va * @return mixed */ public static function set($v, $va){ if(self::$app == null){ //create App on first set. if not, the app does not exist self::$app = new self(); } return self::$app_vars[$v] = $va; } /** * Clean up the app_vars variable */ public static function clean(){ self::$app_vars = array(); } public function __construct() { $this-&gt;_connection = Database::getConnection(); } private function render_template(){ $rPath = $this-&gt;read_path(); foreach($rPath as $key=&gt;$value){ $$key = $value; } unset($rPath); ob_start(); App::set('page_title',App::get('DEFAULT_TITLE')); App::set('template',App::get('DEFAULT_TEMPLATE')); App::set('page',$page); //LOGIN if(!isset($_SESSION['LOGIN']) || $_SESSION['LOGIN'] == false){ Login::check_login(); } else { $modFolders = array('images', 'js', 'css'); //load controller if(strlen($controller) == 0) $controller = App::get('DEFAULT_CONTROLLER'); if(count(array_intersect($path_info, $modFolders)) == 0){ //load it only if it is not in one of those folders $controllerName = "{$controller}Controller"; $app_controller = $this-&gt;create_controller($controllerName, $args); } else { //fake mod-rewrite $this-&gt;rewrite($path_info); } } $main = ob_get_clean(); App::set('main', $main); //LOAD VIEW ob_start(); $this-&gt;load_view($app_controller, 0); //END LOAD VIEW //LOAD TEMPLATE $main = ob_get_clean(); App::set('main', $main); $this-&gt;load_template($app_controller, $app_controller-&gt;get('jQuery')); //END LOAD TEMPLATE } private function read_path(){ $path = isset($_SERVER["PATH_INFO"])?$_SERVER["PATH_INFO"]:'/'.App::get('DEFAULT_CONTROLLER'); $path_info = explode("/",$path); $page = (isset($path_info[2]) &amp;&amp; strlen($path_info[2]) &gt; 0)?$path_info[2]:'index'; list($page, $temp) = explode('.', $page) + array('index', null); $args = array_slice($path_info, 3); $controller = isset($path_info[1])?$path_info[1]:App::get('DEFAULT_CONTROLLER'); return array( 'path_info'=&gt;$path_info, 'page'=&gt;$page, 'args'=&gt;$args, 'controller'=&gt;$controller ); } private function create_controller($controllerName, $args = array()){ if (class_exists($controllerName)) { $app_controller = new $controllerName(); } else { //show nothing header("HTTP/1.1 404 Not Found"); exit; } echo $app_controller-&gt;display_page($args); return $app_controller; } private function load_template($controllerName, $jQuery = null){ $page_title = $controllerName-&gt;get('title')?$controllerName-&gt;get('title'):App::get('DEFAULT_TITLE'); //display output $cwd = dirname(__FILE__); $template_file = $cwd.'/../view/'.App::get('template').'.stp'; if(is_file($template_file)){ include $template_file; } else { include $cwd.'/../view/missingfile.stp'; //no such file error } } private function load_view($controllerName, $saveIndex){ //Bring the variables to the global scope $vars = $controllerName-&gt;getAll(); foreach($vars as $key=&gt;$variable){ $$key = $variable; } $cwd = dirname(__FILE__); if(App::get('view')){ $template_file = $cwd.'/../view/'.App::get('view').'/'.App::get('method').'.stp'; if(is_file($template_file)){ include $template_file; } else { include $cwd.'/../view/missingview.stp'; //no such view error } } else { App::set('template', 'blank'); include $cwd.'/../view/missingfunction.stp'; //no such function error } } private function rewrite($path_info){ $rewrite = $path_info[count($path_info) - 2]; $file_name = $path_info[count($path_info) - 1]; $file = WEBROOT.$rewrite."/".$file_name; // echo $file; header('Location: '.$file); exit; } public function __destruct() { $this-&gt;render_template(); } } ?&gt; </code></pre> <p><a href="https://github.com/maniator/SmallFry/blob/f957f3609c1f108c8cd3b79e4d47a57740e85b42/classes/AppController.php">AppController.php</a></p> <pre><code>&lt;?php /** * Description of AppController * * @author nlubin */ class AppController { /** * * @var mySQL */ protected $_mysql; protected $_page_on, $_allowed_pages = array(), $_not_allowed_pages = array( '__construct', 'get', 'set', 'getAll', 'display_page', 'error_page', 'include_jQuery', 'include_js', '_setHelpers', '_validate_posts', '_doValidate', '_make_error' ); protected $app_vars = array(); var $name = __CLASS__; var $helpers = array(); var $validate = array(); var $posts = array(); protected $validator; public function __construct() { $this-&gt;_mysql = Database::getConnection(); $this-&gt;_page_on = App::get('page'); App::set('view', strtolower($this-&gt;name)); $this-&gt;_allowed_pages = get_class_methods($this); $this-&gt;set('jQuery', $this-&gt;include_jQuery()); $this-&gt;setHelpers(); $this-&gt;validator = new FormValidator(); $this-&gt;_validate_posts(); $this-&gt;posts = (object) $this-&gt;posts; if(!isset($_SESSION[App::get('APP_NAME')][strtolower($this-&gt;name)])){ $_SESSION[App::get('APP_NAME')][strtolower($this-&gt;name)] = array(); } return; } public function init(){ } public function get($v){ return isset($this-&gt;app_vars[$v])?$this-&gt;app_vars[$v]:false; } protected function set($v, $va){ return $this-&gt;app_vars[$v] = $va; } public function getAll(){ return $this-&gt;app_vars; } /** * Show the current page in the browser * @return string */ public function display_page($args) { App::set('method', $this-&gt;_page_on); $private_fn = (strpos($this-&gt;_page_on, '__') === 0); if(in_array($this-&gt;_page_on, $this-&gt;_allowed_pages) &amp;&amp; !in_array($this-&gt;_page_on, $this-&gt;_not_allowed_pages) &amp;&amp; !$private_fn) { $home = $this-&gt;include_jQuery(); call_user_func_array(array($this, $this-&gt;_page_on), $args); } else { if(App::get('view') == strtolower(__CLASS__) || $private_fn || in_array($this-&gt;_page_on, $this-&gt;_not_allowed_pages)){ header("HTTP/1.1 404 Not Found"); } else { App::set('method', '../missingfunction'); //don't even allow trying the page return($this-&gt;error_page(App::get('view')."/{$this-&gt;_page_on} does not exist.")); } exit; } } /** * * @return string */ function index() {} /** * * @param string $msg * @return string */ protected function error_page($msg = null) { $err = '&lt;span class="error"&gt;%s&lt;/span&gt;'; return sprintf($err, $msg); } /** * * @return string */ protected function include_jQuery(){ $ret = '&lt;script type="text/javascript" src="js/jquery-1.6.2.min.js"&gt;&lt;/script&gt;'.PHP_EOL; $ret .= ' &lt;script type="text/javascript" src="js/jquery-ui-1.8.9.custom.min.js"&gt;&lt;/script&gt;'.PHP_EOL; return $ret; } /** * * @param string $src * @return string */ protected function include_js($src){ $script = '&lt;script type="text/javascript" src="js/%s.js"&gt;&lt;/script&gt;'.PHP_EOL; return sprintf($script, $src); } protected function setHelpers(){ $helpers = array(); foreach($this-&gt;helpers as $helper){ $help = "{$helper}Helper"; $this-&gt;$helper = new $help(); $helpers[$helper] = $this-&gt;$helper; } self::set('helpers', (object) $helpers); } protected function logout(){ session_destroy(); header('Location: '.WEBROOT.'index.php'); exit; } protected function _validate_posts(){ foreach($this-&gt;validate as $field =&gt; $rules){ foreach($rules as $validate=&gt;$message){ $this-&gt;validator-&gt;addValidation($field, $validate, $message); } } $this-&gt;_doValidate(); } protected function _doValidate(){ if(!(!isset($_POST) || count($_POST) == 0)){ //some form was submitted if(!$this-&gt;validator-&gt;ValidateForm()){ $error = ''; $error_hash = $this-&gt;validator-&gt;GetErrors(); foreach($error_hash as $inpname =&gt; $inp_err) { $error .= "$inp_err&lt;br/&gt;\n"; } $this-&gt;_make_error($error); } foreach($_POST as $key=&gt;$post){ $this-&gt;posts[$key] = $post; } } } function __get($var_name){ // echo $var_name."&lt;br&gt;"; if(isset($this-&gt;posts-&gt;$var_name)){ return $this-&gt;posts-&gt;$var_name; } else{ ?&gt;&lt;div class="errors"&gt;&lt;?php echo "$var_name is not set&lt;br/&gt;\n"; ?&gt;&lt;/div&gt;&lt;?php exit; } } function __call($name, $arguments){ if($name == 'mysql'){ return (strlen($this-&gt;$arguments[0])==0?"NULL":"'{$this-&gt;$arguments[0]}'"); } } function _make_error($str){ ?&gt;&lt;div class="errors"&gt;&lt;?php echo $str; ?&gt;&lt;/div&gt;&lt;?php exit; } } ?&gt; </code></pre>
[]
[ { "body": "<p>Your code looks acutally great, and it has also good PHP-Doc, but I think the comments inside the methods are a bit confusing, because they have always a different writing style (sometimes uppercase, sometimes lowercase, sometimes sentences sometimes just simple words etc.), so you should cleanup them and set a convention how you document these points in the code.</p>\n\n<p>Also you should be a bit carefully with the foreach loop in <code>load_view</code>, because there you set <code>$$key = $variable;</code>. If you know what you are setting to the controller, this isn't anything bad, but what is if you try to set <code>$this</code>? I didn't try it, but it would actually generate an error, so I would recommend you just to create an array of reserved variables, which will be checked before loading the view. There you should also add the <code>$cwd</code> and the <code>$template_file</code>, perhaps there are more vars like these.</p>\n\n<p>Also something I actually see in your code, what is just a bit of coding convention, is the closing PHP tag at the end of the file (<code>?&gt;</code>). Of course I see many developers using that right now, but I recommend you to leave that away, you could instead just add a comment like <code>/* End of File */</code>. The problem is, if you have a space after the closing PHP Tag and you try to modify the header later, it won't work, you'll just get errors.</p>\n\n<p>And the replacement of your <code>get</code> and <code>set</code> methods could be done with <a href=\"http://www.php.net/manual/en/language.oop5.magic.php\" rel=\"nofollow\">PHP magic methods.</a>. You should use <code>__get($var)</code> and <code>__set($var)</code> than you could access them like normal object properties. E.g. <code>$this-&gt;newTemplateVar = \"Hello World!\";</code>.</p>\n\n<p>I hope my post helps you; if not, just say it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T10:02:47.567", "Id": "5277", "ParentId": "5039", "Score": "4" } }, { "body": "<p>I've spent about 20 minutes reading your code and I've identified several issues.</p>\n\n<h2>Relative paths</h2>\n\n<pre><code>private function load_template($controllerName, $jQuery = null){\n $page_title = $controllerName-&gt;get('title') ? $controllerName-&gt;get('title') : App::get('DEFAULT_TITLE');\n\n //display output\n $cwd = dirname(__FILE__);\n $template_file = $cwd.'/../view/'.App::get('template').'.stp';\n if(is_file($template_file)){\n include $template_file;\n }\n else {\n include $cwd.'/../view/missingfile.stp'; //no such file error\n }\n} \n</code></pre>\n\n<p>What happens if at a later point you decide to change your directory structure? Instead of using <code>dirname(__FILE__)</code> you could just pass that base directory as a function parameter.</p>\n\n<h2>Function names inconsistencies</h2>\n\n<p>You prefix <em>some</em> private / protected variables and functions with an underscore: </p>\n\n<pre><code>protected $_mysql;\n</code></pre>\n\n<p>Two points: </p>\n\n<ol>\n<li>Either do it for every private / protected variable and function or don't do it at all</li>\n<li>Don't do it at all</li>\n</ol>\n\n<p>Some justification on the second point: </p>\n\n<ul>\n<li>Every decent IDE out there allows for sorting of variables and functions based on their visibillity / scope. Eclipse goes a step further and uses green for public, and red for private / public in the Outline view, so everything is easily identifiable.</li>\n<li>In PHP functions that are prefixed with an underscore might be mistaken for magic methods (which are prefixed by two underscores). </li>\n</ul>\n\n<p>Note that while almost all php IDEs will treat:</p>\n\n<pre><code>function foo() \n</code></pre>\n\n<p>as:</p>\n\n<pre><code>public function foo()\n</code></pre>\n\n<p>you could help the IDE by adding the public keyword. That's also a readibillity point and a PHP4 style (<code>function foo()</code>) vs PHP5 style (<code>public function foo()</code>). </p>\n\n<h2>Inline HTML</h2>\n\n<pre><code>protected function error_page($msg = null) {\n $err = '&lt;span class=\"error\"&gt;%s&lt;/span&gt;';\n return sprintf($err, $msg);\n}\n\nprotected function include_jQuery(){\n $ret = '&lt;script type=\"text/javascript\" src=\"js/jquery-1.6.2.min.js\"&gt;&lt;/script&gt;'.PHP_EOL;\n $ret .= ' &lt;script type=\"text/javascript\" src=\"js/jquery-ui-1.8.9.custom.min.js\"&gt;&lt;/script&gt;'.PHP_EOL;\n return $ret;\n}\n\nfunction __get($var_name){\n // echo $var_name.\"&lt;br&gt;\";\n if(isset($this-&gt;posts-&gt;$var_name)){\n return $this-&gt;posts-&gt;$var_name;\n }\n else{\n ?&gt;&lt;div class=\"errors\"&gt;&lt;?php\n echo \"$var_name is not set&lt;br/&gt;\\n\";\n ?&gt;&lt;/div&gt;&lt;?php\n exit;\n }\n} \n</code></pre>\n\n<p>Don't do that, you <strong>must</strong> <a href=\"https://stackoverflow.com/questions/62617/whats-the-best-way-to-separate-php-code-and-html\">separate presentation from logic</a>.</p>\n\n<h2>Sessions</h2>\n\n<p>In AppController.php you utilize sessions:</p>\n\n<pre><code>if(!isset($_SESSION[App::get('APP_NAME')][strtolower($this-&gt;name)])){\n $_SESSION[App::get('APP_NAME')][strtolower($this-&gt;name)] = array();\n}\n</code></pre>\n\n<p>But you don't have <code>session_start()</code> at the beginning of the script. Granted, you probably start the session in the caller script, but that means that your class will throw notices (<code>$_SESSION</code> array not initialized) if called from anywhere where <code>session_start()</code> hasn't been called. You can do something like:</p>\n\n<pre><code>if( !isset($_SESSION) ) session_start();\n</code></pre>\n\n<p>at the top of each script that uses sessions.</p>\n\n<h2>Comments</h2>\n\n<p>You have some phpDoc comments, you need one for <em>every</em> function. But please note that I've been <a href=\"https://codereview.stackexchange.com/questions/2715/critique-request-php-cookie-library/2727#2727\">accused</a> of overcommenting :)</p>\n\n<h2>PHP4 style class members</h2>\n\n<p>You are using some PHP4 style class members:</p>\n\n<pre><code>var $name = __CLASS__;\nvar $helpers = array();\nvar $validate = array();\nvar $posts = array();\n</code></pre>\n\n<p>You should be using PHP5 access control (public / private / protected) members everywhere.</p>\n\n<h2>Ternary operator readability</h2>\n\n<p>This: </p>\n\n<pre><code>return isset(self::$app_vars[$v])?self::$app_vars[$v]:false;\n</code></pre>\n\n<p>is not very readable. Consider something like:</p>\n\n<pre><code>return\n isset(self::$app_vars[$v])\n ? self::$app_vars[$v]\n : false;\n</code></pre>\n\n<p>or at least something like this: </p>\n\n<pre><code>return isset(self::$app_vars[$v]) ? self::$app_vars[$v] : false;\n</code></pre>\n\n<p>Similarly, please add spaces before and after concatenation points: </p>\n\n<pre><code>$cwd.'/../view/'.App::get('template').'.stp'; // somewhat unreadable\n$cwd . '/../view/'.App::get('template') . '.stp'; // friendlier to the eyes\n</code></pre>\n\n<h2>Minor stuff</h2>\n\n<pre><code>private function load_template($controllerName, $jQuery = null) {}\n</code></pre>\n\n<p>You don't utilize the <code>$jQuery</code> variable in the function. Is your code complete? If not, you shouldn't have posted it up for review.</p>\n\n<pre><code>function __get($var_name){\n // echo $var_name.\"&lt;br&gt;\";\n if(isset($this-&gt;posts-&gt;$var_name)){\n return $this-&gt;posts-&gt;$var_name;\n }\n else{\n ?&gt;&lt;div class=\"errors\"&gt;&lt;?php\n echo \"$var_name is not set&lt;br/&gt;\\n\";\n ?&gt;&lt;/div&gt;&lt;?php\n exit;\n }\n}\n</code></pre>\n\n<p><code>else</code> is not needed (as <code>if block</code> returns, which means that execution of the function stops there):</p>\n\n<pre><code>function __get($var_name){\n // echo $var_name.\"&lt;br&gt;\";\n if(isset($this-&gt;posts-&gt;$var_name)){\n return $this-&gt;posts-&gt;$var_name;\n }\n\n ?&gt;&lt;div class=\"errors\"&gt;&lt;?php\n echo \"$var_name is not set&lt;br/&gt;\\n\";\n ?&gt;&lt;/div&gt;&lt;?php\n exit; \n}\n</code></pre>\n\n<p>Here: </p>\n\n<pre><code>private function create_controller($controllerName, $args = array()){\n if (class_exists($controllerName)) { \n</code></pre>\n\n<p>You treat <code>$controllerName</code> as a parameter that holds a class name, but in the very next function:</p>\n\n<pre><code>private function load_template($controllerName, $jQuery = null){\n $page_title = $controllerName-&gt;get('title')?$controllerName-&gt;get('title'):App::get('DEFAULT_TITLE');\n</code></pre>\n\n<p>you also have a <code>$controllerName</code> parameter that holds an object. Rename the second one to <code>$controller</code>.</p>\n\n<h2>In conclusion</h2>\n\n<p>Your code has a lot of minor inconsistencies, several readabillity issues, a few major problems (especially the html thingy) and it's clearly still a work in progress (especially AppController.php). You need to try and at least rewrite it in a more consistent matter.</p>\n\n<p>PS. You should remove <code>?&gt;</code> from the end of every class script, as leo <a href=\"https://codereview.stackexchange.com/questions/5039/small-php-viewer-controller-template/5277#5277\">suggests</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-09T14:01:16.817", "Id": "9077", "Score": "0", "body": "Wow. How thorough! look at this related SO question: http://stackoverflow.com/questions/7676515/should-i-remove-static-function-from-my-code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-08T21:57:07.333", "Id": "10325", "Score": "0", "body": "I have updated some of my library ^_^" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-03T22:53:19.140", "Id": "11667", "Score": "0", "body": "[see my updated code](https://github.com/maniator/SmallFry/tree/5e1d2a3d1c2f14aeec0feaf8b0def5baa3ec8508) do you think I should make a new question related to it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-05T15:43:32.167", "Id": "11748", "Score": "0", "body": "I just hope it doesnt get closed as a duplicate (I am fixing the underscore issue in my update coming soon, switching to all camelCase for the most part)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-05T15:46:44.523", "Id": "11751", "Score": "0", "body": "@Neal I don't think it would be a duplicate, you are not just copy pasting the same code, you've done a fair share of modifications. The discussion on what [constitutes a dupe in Code Review](http://meta.codereview.stackexchange.com/questions/8/how-do-we-define-duplicate-questions) is still open, so I can't really say for sure... But go for it, either way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-05T16:10:07.963", "Id": "11757", "Score": "0", "body": "I have a question of how I can fix the `Relative paths`. Basically, how can I do it with my new code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-05T16:12:26.887", "Id": "11758", "Score": "0", "body": "@Yanniss [Here is a chat link](http://chat.stackoverflow.com/transcript/message/2288204#2288204)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-06T14:56:21.133", "Id": "11818", "Score": "0", "body": "Here is my new question: http://codereview.stackexchange.com/q/7531/3163" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-13T14:21:57.120", "Id": "12245", "Score": "0", "body": "Still no use to my bounty on my new question hehe" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-09T04:08:53.700", "Id": "5913", "ParentId": "5039", "Score": "19" } }, { "body": "<p>I agree with yannis. But 1 last thing.</p>\n\n<p>Constructors are simply supposed to assign values to properties. Your constructor seems to do a lot more than that. Switch it up to accept a database connection. Remember statics are evil cause they make testing difficult.</p>\n\n<pre><code>$Settings = new FileSettings(new File('Config.php'));\n$MFactory = new ModelFactory;\n$TFactory = new TemplateFactory($Settings['UI']['Template']);\n\n$Database = $MFactory-&gt;createDB($Settings['DB']['Driver'], ....);\n$Request = $MFactory-&gt;createRequest($_SERVER['PHP_SELF'], $_GET, $_POST);\n$View = $TFactory-&gt;createView($Request-&gt;getView());\n\n$Controller = new Controller($Database, $TFactory, $MFactory);\n$Action = $Request-&gt;getAction()?: 'index';\n\nif (is_callable(array($Controller, $Action))) {\n call_user_function(array($Controller, $Action));\n}\n\nelse $Controller-&gt;error($Request);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-24T16:58:52.740", "Id": "42678", "ParentId": "5039", "Score": "0" } } ]
{ "AcceptedAnswerId": "5913", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T16:03:50.940", "Id": "5039", "Score": "32", "Tags": [ "php", "library" ], "Title": "Small PHP Viewer/Controller template" }
5039
<p>I am working on a small script for a mobile site. Is there any way to improve on the regex here? or remove it completely?</p> <pre><code>function fn_page_change(event) { event.preventDefault(); var activePage = $(".ui-active"); var newPage = $(event.target.getAttribute("href")); activePage.className = activePage.className.replace(/(?:^|\s)ui-active(?!\S)/, " ui-inactive "); newPage.className = newPage.className.replace(/(?:^|\s)ui-inactive(?!\S)/, " ui-active"); } </code></pre> <p>I'm not using jQuery, the <code>$</code> is myown</p> <pre><code>function $(selector, el) { if (!el) { el = document; } var tmp = el.querySelectorAll(selector); if (tmp.length === 1) { return tmp[0]; } return tmp; } </code></pre> <p><a href="http://jsfiddle.net/rlemon/ujGjd/" rel="nofollow">Here is an example</a></p>
[]
[ { "body": "<p>You will have less code if you use a regex because you need the word boundary detection that is built into regex. I'd suggest putting it in a utility function to make it cleaner and more readable:</p>\n\n<pre><code>function replaceClass(el, oldClass, newClass) {\n el.className = el.className.replace(new RegExp(\"\\\\b\" + oldClass + \"\\\\b\"), newClass);\n}\n\nfunction fn_page_change(event) {\n event.preventDefault();\n var activePage = $(\".ui-active\");\n var newPage = $(event.target.getAttribute(\"href\"));\n replaceClass(activePage, \"ui-active\", \"ui-inactive\");\n replaceClass(newPage, \"ui-inactive\", \"ui-active\");\n}\n</code></pre>\n\n<p>If you wanted a version of <code>replaceClass()</code> that would handle either of the types of return values you get out of your selector function (single DOM object or array of DOM objects), then you could use this:</p>\n\n<pre><code>function replaceClass(el, oldClass, newClass) {\n var re = new RegExp(\"\\\\b\" + oldClass + \"\\\\b\");\n if (el.nodeType) {\n el.className = el.className.replace(re, newClass);\n } else {\n for (var i = 0; i &lt; el.length; i++) {\n el[i].className = el[i].className.replace(re, newClass);\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T18:55:32.263", "Id": "5042", "ParentId": "5040", "Score": "3" } }, { "body": "<p>You don't need to worry about regular expressions or word boundaries in this particular use case for two reasons:</p>\n\n<ol>\n<li>You know the exact class names you are targeting.</li>\n<li>Neither class name is embedded verbatim within the other (for example 'ui-active' and 'ui-active-false' would require a regex that reads word boundaries).</li>\n</ol>\n\n<p>In your case though, 'ui-active' and 'ui-inactive' will never throw a false positive match for one another in string or regex form.</p>\n\n<p>This means you can simply search and swap the exact class names themselves.</p>\n\n<pre><code>activePage.className = activePage.className.replace('ui-active','ui-inactive');\nnewPage.className = newPage.className.replace('ui-inactive','ui-active');\n\n//OR if you do prefer to stick with regular expressions, simply use...\n\nactivePage.className = activePage.className.replace(/ui-active/,'ui-inactive');\nnewPage.className = newPage.className.replace(/ui-inactive/,'ui-active');\n</code></pre>\n\n<p>You also do not need to worry about adding an additional space in front of the class name you are adding in this case (I noticed you putting an extra space, such as ' ui-inactive' for the the replacement class, for example). Since the spaces between class names in the className value are already space delimited, the fact that this alternative approach only targets the class name itself, without touching or altering the white-space, you do not need to worry about extra spaces in your substitution values.</p>\n\n<p>Again, this is not a solution that will work in <em>every</em> situation for replacing class names for elements, but given your specific use case, and given the class names you are specifically targeting, it provides a simpler alternative that will still easily fulfill your desired functionality.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-26T16:39:44.247", "Id": "290748", "Score": "0", "body": "As a side-note, I'm new to posting here and found this post through the 'Related' side panel coming from another post. And only now did I just realize the post is 5 years old. Maybe someone out there will find some use for the answer though. Whoops haha" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-26T17:06:12.143", "Id": "290758", "Score": "0", "body": "Well, it's a nice enough [revival](http://codereview.stackexchange.com/help/badges/59/revival)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-26T16:37:40.500", "Id": "153682", "ParentId": "5040", "Score": "1" } } ]
{ "AcceptedAnswerId": "5042", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T18:32:05.163", "Id": "5040", "Score": "1", "Tags": [ "javascript", "performance", "regex" ], "Title": "Improve on Regex replacing classnames" }
5040
<p>This <a href="https://stackoverflow.com/questions/7587110/basic-user-input-string-validation">question</a> came up today on StackOverflow. I find it more unfortunate than (as some others said) idiotic. And it recalled an old function I have which I just remembered.</p> <p>I have a user.config file which has some settings which can be updated through user action. My rationale was "if the setting is changed, it should be saved." So I made a static class to cover for those settings so as not to handle the operations each time. And I came up with this:</p> <pre><code>public static class UserSettings { public static string ProcessPath { get { return _processPath; } set { _processPath = Settings.Default.ProcessPath = value; Settings.Default.Save(); } } //Other functions and properties } </code></pre> <p>Yes, I know, it reeks. I feel shame. I want to make this right. I'm thinking this:</p> <ul> <li>the class is static, it should at least be a singleton;</li> <li>the property should itself not be static;</li> <li>there's no point in saving the settings <em>every time</em>, just on closing the app, and that would basically <strike>be safe in a destructor for the class</strike> be best suited for a dedicated function called SaveSettings. Any other object can call it when they see fit, no surprise effects. (further evidence of the need for a singleton).</li> </ul> <p>Are these <em>good intentions</em> in the right direction?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T18:54:02.977", "Id": "7529", "Score": "3", "body": "Oh my, that question you linked to just killed a part of my soul. Ouch. Your example however, I don't really have a problem with." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T07:11:06.437", "Id": "7557", "Score": "0", "body": "You are welcome to see my post then. You are almost right, there is no troubles using application/user scope with settings along with singletone implementation in .NET. Just use singleton serialization helper and serializatpion class, inherited from ISerializable interface, and make use of the Default static property to access your serialized properties." } ]
[ { "body": "<p>First, I think making it a singleton would be a mistake (singleton usually is). At best it would be extra work with zero benefit. At worst, it's a handicap, such as when/if you decide to support two top-level windows with independent settings for each.</p>\n\n<p>Second, I think I'd add a Boolean named <code>dirty</code> (or something similar). When you set the value, dirty is set to true. When you save the value, you check if dirty is true, and only write out the value if it is (then you set dirty to false).</p>\n\n<p>Personally, I'd probably change it from a static class named <code>ProcessPath</code> to a normal class named (something like) <code>config_string</code>, with an instance for ProcessPath, and a the possibility for other instances holding other strings. To do that, you'd pass <code>Settings.Default.ProcessPath</code> as a parameter when you construct the object.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T20:13:14.437", "Id": "7533", "Score": "1", "body": "Why do you say singletons usually are mistakes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T20:19:41.447", "Id": "7534", "Score": "1", "body": "@MPelletier: If you Google for something like `singleton antipattern`, you should get [some](http://accu.org/index.php/journals/337) [pretty](http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-join-new-project.html) [decent](http://misko.hevery.com/2008/08/21/where-have-all-the-singletons-gone/) [ideas](http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T21:14:46.240", "Id": "7537", "Score": "0", "body": "A dirty for every value? What if a class contains 100 values?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T22:02:32.677", "Id": "7539", "Score": "1", "body": "@0A0D: Right now it contains *one* value. If it contains 100 values, it will depend. If each can be/is reasonably written out separately, then probably yes. If they're all going to be written together, then a single Boolean suffices for all of them. Keep in mind that 100 bits is only 12.5 bytes. Even if you round up to 13 or even 16 (next power of 2), and it's still pretty minimal. You don't have to save many writes to disk to justify 16 bytes of storage." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T23:58:29.470", "Id": "7540", "Score": "0", "body": "@0A0D @Jerry Actually, since this is basically a cover class for user.config settings, `Settings.Default.Save();` saves all values, so a single `dirty` variable would suffice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T07:09:31.197", "Id": "7556", "Score": "0", "body": "@MPelletier : I've got an idea, please, see my post then." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T09:23:02.817", "Id": "7560", "Score": "0", "body": "If you use a constructor initialization, you will likely not be very happy to write as a paremeters 100 values, that is why IoC, DI is on the play. It is much simplier to have attributed 100 properties rathen than pass it to the constructor. It is based on a practice." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T19:24:48.457", "Id": "5043", "ParentId": "5041", "Score": "1" } }, { "body": "<p>I understand your idea. You have to use both patterns: singleton pattern, and load/save pattern.</p>\n\n<p>You can use <code>UserSettings</code> class implementation, with load/save functionality, inherited from the <code>ApplicationSettingsBase</code> class. </p>\n\n<p>Example of using <code>UserSettings</code> singleton class in Windows Forms Application:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n this.Location = UserSettings.Default.FormLocation;\n this.Size = UserSettings.Default.FormSize;\n this.textBox1.Text = UserSettings.Default.ProcessPath;\n }\n\n private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n {\n UserSettings.Default.FormLocation = this.Location;\n UserSettings.Default.FormSize = this.Size;\n UserSettings.Default.ProcessPath = this.textBox1.Text;\n UserSettings.Default.Save();\n }\n}\n</code></pre>\n\n<p>Sources:</p>\n\n<pre><code>[SettingsSerializeAs(SettingsSerializeAs.Xml)]\npublic sealed class UserSettings : ApplicationSettingsBase, INotifyPropertyChanged, ISerializable\n{\n private static UserSettings _defaultInstance = new UserSettings();\n\n [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]\n void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)\n {\n info.SetType(typeof(SingletonSerializationHelper));\n }\n\n private UserSettings() { }\n\n public static UserSettings Default { get { return _defaultInstance; } }\n\n private const string FormLocationProperty = \"FormLocation\";\n private const string FormSizeProperty = \"FormSize\";\n private const string ProcessPathProperty = \"ProcessPath\";\n\n // public properties\n [UserScopedSetting()]\n [DefaultSettingValue(\"0, 0\")]\n public Point FormLocation\n {\n get { return (Point)(this[FormLocationProperty]); }\n set { this[FormLocationProperty] = value; }\n }\n\n [UserScopedSetting()]\n [DefaultSettingValue(\"300, 300\")]\n public Size FormSize\n {\n get { return (Size)this[FormSizeProperty]; }\n set { this[FormSizeProperty] = value; }\n }\n\n [UserScopedSetting]\n [DefaultSettingValue(\"\")]\n public string ProcessPath\n {\n get { return (string)this[ProcessPathProperty]; }\n set { this[ProcessPathProperty] = value; }\n }\n}\n\n[Serializable]\ninternal sealed class SingletonSerializationHelper : IObjectReference\n{\n public object GetRealObject(StreamingContext context)\n {\n return UserSettings.Default;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T09:56:48.677", "Id": "7562", "Score": "0", "body": "I see what you did with the singleton pattern. Impressive, I had always just seen GetInstance(), never an actual named oject. I guess it tells us the original Properties.Settings.Default is itself a singleton... Your class would serialize (and deserialize) as user.config? What would be the advantage here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T13:37:00.967", "Id": "7565", "Score": "0", "body": "@MPelletier: There is no real advantage of using this class except it is a singleton and is an ancestor of the `ApplicationSettingsBase` class, and can be used anywere `ApplicationSettingsBase` is used. So it solves the problem of multiple instancies of applications settings classes, in my opinion. Persistent storage, accessible anywere, which also has default values set, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T14:16:55.393", "Id": "7568", "Score": "0", "body": "I think I see... A lot of that stuff I don't need in the current project. Way too much overhead. But in the right place, it would be very useful. I'm just not sure where the right place would be at the moment. That is by no means a way of saying I don't like your solution. I do like it. I'm just not sure I understand all of it :S" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T02:35:19.210", "Id": "7595", "Score": "1", "body": "@PMelletier: It's OK. This is a community. I got another solutions, which you can find in my careers profile, f.e. you can use custom XML serialization to serialize anything you want at http://xmlserialization.codeplex.com, etc." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T06:15:51.243", "Id": "5053", "ParentId": "5041", "Score": "1" } }, { "body": "<p>Here is the cheats I use -</p>\n\n<p>To prevent having to type \"Settings.Default\":</p>\n\n<pre><code>using Res = MyApp.Properties.Resources;\nusing Set = MyApp.Properties.Settings;\n\n/// in class\nprivate static Set def{\n get{\n return Set.Default;\n }\n}\n// usage\ndef.Data=\"blah\"\n</code></pre>\n\n<p>And then take a look at</p>\n\n<pre><code>public event SettingChangingEventHandler SettingChanging\n</code></pre>\n\n<p>of ApplicationSettingsBase</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-13T14:38:54.710", "Id": "7770", "ParentId": "5041", "Score": "0" } } ]
{ "AcceptedAnswerId": "5043", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T18:37:20.667", "Id": "5041", "Score": "2", "Tags": [ "c#" ], "Title": "Saving settings in user.config" }
5041
<p>We have interviewees write sample code, but now we want them to modify some simple working code. I came up with the following proposal, which is a syntax-directed interpreter implemented with a table-driven finite state machine. The interpreter simply accepts whitespace-delimited text and outputs "Hello" when it sees the case-insensitive command "HELLO". Any other input is an error.</p> <p>This is a highly-simplified version of some C code converted to C# for the interview:</p> <pre><code>enum Lexeme { Error, EOF, Whitespace, H, E, L, O } static Lexeme LexemeOfIntChar(int cIn) { if (cIn &lt; 0) return Lexeme.EOF; switch (Convert.ToChar(cIn)) { case 'H': case 'h': return Lexeme.H; case 'E': case 'e': return Lexeme.E; case 'L': case 'l': return Lexeme.L; case 'O': case 'o': return Lexeme.O; case ' ': case '\t': case '\r': case '\n': return Lexeme.Whitespace; default: return Lexeme.Error; } } static void Main(string[] args) { // Transition table. // Each row is a state, each column is the new state given the column lexeme. // State -1 is error. No need to define an Error row since we never transition from it. // State 7 is end. We never transition from this either. int[,] transition = { // Err,EOF, Ws, H, E, L, O // Lexeme { -1, 7, 0, 1, -1, -1, -1 }, // 0 = Start { -1, -1, -1, -1, 2, -1, -1 }, // 1 = first H { -1, -1, -1, -1, -1, 3, -1 }, // 2 = first E { -1, -1, -1, -1, -1, 4, -1 }, // 3 = first L { -1, -1, -1, -1, -1, -1, 5 }, // 4 = second L { -1, 6, 6, -1, -1, -1, -1 }, // 5 = first O { -1, 7, 0, 1, -1, -1, -1 }, // 6 = 'HELLO' }; int currentState = 0; // 0 = Start while ((currentState &gt;= 0) &amp;&amp; (currentState != 7)) { Lexeme t = LexemeOfIntChar(Console.Read()); currentState = transition[currentState, (int)t]; switch (currentState) { case -1: Console.WriteLine("Invalid character!"); break; case 6: Console.WriteLine("Hello"); break; // 6 = saw 'HELLO' with terminal symbol } } } </code></pre> <p>The proposed exercise is to extend this interpreter to accept a "HELP" command that will print out:</p> <blockquote> <p>"usage 'HelloScript &lt;scriptfile'</p> </blockquote> <p>This can be done in about a half-dozen changes.</p> <p>A co-worker I asked this about was able to complete it in under 15 minutes, but wanted to argue about terminology, implementation, et al.</p> <p>The intent is for it to be a simple exercise only to see if interviewees can understand and maintain existing code. How understandable and maintainable is it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T19:52:39.330", "Id": "7531", "Score": "3", "body": "Not sure what this will tell you about the candidate. If you asked me to maintain it I would delete it and replace it with a Lex and Yacc file." } ]
[ { "body": "<p>If I were a candidate, I'd judge what I think the quality of your code looks like based on this simple, and I'd have some concerns:</p>\n\n<ol>\n<li>Your transition table depends on the values of the <code>Lexeme</code> <code>enum</code> not changing (say by inserting additional values). If this is the case I'd like there to be a comment on <code>enum</code> saying order is significant or having the values explicitly given orders. Otherwise I'd expect the actual numbers to not matter.</li>\n<li>Your code contains a transition table. That's hard to read and hard to modify. Why would you do that? </li>\n<li><p>You've two extra sets of parens here:</p>\n\n<pre><code>while ((currentState &gt;= 0) &amp;&amp; (currentState != 7))\n</code></pre></li>\n<li>Your states and done via magic numbers and not an <code>enum</code>.</li>\n<li>The check for -1 feels like it's in the wrong place. It is handling an error condition. But the other element of the switch isn't an error condition.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T22:15:16.103", "Id": "5046", "ParentId": "5044", "Score": "4" } } ]
{ "AcceptedAnswerId": "5046", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-28T19:42:59.860", "Id": "5044", "Score": "3", "Tags": [ "c#", "interview-questions", "state-machine" ], "Title": "Sample table-driven finite-state machine" }
5044
<p>The following code is a javascript typeOf function. We aren't here to discuss coding conventions or whether or not extending a native object like I have is kosher or not. I want to know in what cases this would fail to correctly identify an object and hopefully ways to correct it. Or is this sufficient for 99% of cases?</p> <p>Also, if you think of a way to make this smaller while keeping the information intact I'd be glad to hear that as well.</p> <pre><code>"use strict" var FN = Function, g = FN('return this')(); //jslint safe 'global' reference Object.typeOf = (function (g) { return function (o) { var n = null, r = false, nodeType = { 1:'element_node', 2:'attribute_node', 3:'text_node', 4:'cdata_section_node', 5:'entity_reference_node', 6:'entity_node', 7:'processing_instrction_node', 8:'comment_node', 9:'document_node', 10:'document_type_node', 11:'document_fragment_node1', 12:'notation_node' }, u; /********* * Following if statements are direct comparisons * because any additional checks on o if it equals * either of these results in an error. So we check * these first prior to proceeding. *********/ if (o === u) { return 'undefined'; } if (o === n) { return 'null'; } /********* * If we made it this far, just return the set the * r variable and return at the end; *********/ switch (o) { case g: r = 'global'; break; case g.document: r = 'htmldocument'; break; default: break; } /********* * Originally a large switch statement changed * due to below comments. *********/ if (o.nodeType &amp;&amp; nodeType[o.nodeType]) { r = nodeType[o.nodeType]; } /********* * If r is still false, we do a standard check * using the Object.toString.call method to determine * its "correct" type; *********/ return r || ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); } }(g)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T05:49:41.013", "Id": "7551", "Score": "0", "body": "In this changed part: `if (o.nodeType && nodeType[o.nodeType]) { r = o.nodeType;}`, I think you mean to use: `r = nodeType[o.nodeType]`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T08:20:44.057", "Id": "7929", "Score": "0", "body": "Oops, haha good catch I've corrected it" } ]
[ { "body": "<p>Before evaluating something, you must first establish what the evaluation criteria are. So you must first define what \"correctly identify an object\" means.</p>\n\n<p>The ECMAScript <em>typeof</em> operator returns values as specified in ECMA-262, unfortunately they are different values to the actual <em>Type</em> as defined in the spec. Nor does the value have much relationship to the internal <em>class</em> property. </p>\n\n<p>Futher, host objects can return anything they like for <em>typeof</em> and internal <em>class</em>, they can even throw errors if you attempt to access them.</p>\n\n<p>It is rarely necessary to know in a general sense what \"type\" something is, it's more common to want to know if a value meets specific criteria for the intended purpose. For example, passing a DOM element's style object to your function in Firefox returns \"cssstyledeclaration\", in IE it returns \"object\".</p>\n\n<p>Does that meet your criteria for \"correctly identify\" (whatever they might be)? What is the caller to make of the different values? Why would it want to know?</p>\n\n<p>I don't know the answers (or even the full set of questions that might be asked), so I can't work out if your function does the right thing or not.</p>\n\n<p>Some comments on the code:</p>\n\n<pre><code>&gt; var FN = Function, \n&gt; g = FN('return this')(); //jslint safe 'global' reference\n</code></pre>\n\n<p>Isn't:</p>\n\n<pre><code>var g = this;\n</code></pre>\n\n<p>sufficient?</p>\n\n<pre><code>&gt; Object.typeOf = (function (g) {\n&gt; return function (o) {\n</code></pre>\n\n<p>What is the point of the IIFE? There is no code run in it, all it does is add a closure to an empty (more or less) variable object of the outer function.</p>\n\n<pre><code>&gt; }\n&gt; }(g));\n</code></pre>\n\n<p>If the sole purpose was to pass in a reference to the global object, then:</p>\n\n<pre><code> }\n}(this));\n</code></pre>\n\n<p>will do the job. Since you aren't in strict mode, you can use the following within a normal function expression:</p>\n\n<pre><code>var global = (function(){return this;})();\n</code></pre>\n\n<p>the big switch statement can be replaced by something like:</p>\n\n<pre><code>if (typeof o.nodeType == 'number') {\n var nodeTypes = {1:'element_node',2:'attribute_node',3:'text_node',4:'cdata_section_node',\n 5:'entity_reference_node',6:'entity_node',7:'processing_instrction_node',\n 8:'comment_node',9:'document_node',10:'document_type_node',\n 11:'document_fragment_node1',12:'notation_node'};\n r = nodeTypes[o.nodeType];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T05:03:13.787", "Id": "7548", "Score": "0", "body": "Much obliged. Note I added \"use strict\" & changed out the nodeType portion; does that change any of the code for global you supplied or no?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T05:59:15.437", "Id": "7552", "Score": "0", "body": "It means you can just pass *this* to the function rather than the global *g* (and threfore don't need to initialise *g* either). I think you need to define what objects you want to know the type of, and then specify what they are. e.g. passing an xmlHTTPRequest object to your function returns different values in different browsers (IE 8 vs Firefox)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T04:52:40.987", "Id": "5052", "ParentId": "5051", "Score": "7" } }, { "body": "<p><sub><sup><a href=\"https://codereview.stackexchange.com/faq#questions\">Not to be intentionally pedantic, but we are here to discuss things like coding conventions.</a></sup></sub></p>\n\n<p>I find myself disliking how you switch from one style to another within the same method. </p>\n\n<pre><code> if (o === n) {\n return 'null';\n }\n\n /*********\n * If we made it this far, just return the set the\n * r variable and return at the end;\n *********/\n\n switch (o) {\n case g:\n r = 'global';\n break;\n case g.document:\n r = 'htmldocument';\n break;\n default:\n break;\n }\n</code></pre>\n\n<p>This switch statement could be written (shorter) as two if statements (and the comments add nothing to the function).</p>\n\n<p>The <code>r</code> variable is unnecessary (anywhere it is used can be replaced with a return statement).</p>\n\n<p>The rest of the variables within that function are constants WRT it.</p>\n\n<p>I would rewrite this whole thing like so:</p>\n\n<pre><code>/*jslint maxerr: 50, indent: 4 */\n(function (g, Object, n, u) {\n \"use strict\";\n var nodeType = {\n 1: 'element_node',\n 2: 'attribute_node',\n 3: 'text_node',\n 4: 'cdata_section_node',\n 5: 'entity_reference_node',\n 6: 'entity_node',\n 7: 'processing_instrction_node',\n 8: 'comment_node',\n 9: 'document_node',\n 10: 'document_type_node',\n 11: 'document_fragment_node1',\n 12: 'notation_node'\n };\n Object.typeOf = function (o) {\n if (o === u) {\n return 'undefined';\n }\n\n if (o === n) {\n return 'null';\n }\n\n if (o === g) {\n return 'global';\n }\n\n if (o === g.document) {\n return 'htmldocument';\n }\n\n if (o.nodeType &amp;&amp; nodeType[o.nodeType]) {\n return nodeType[o.nodeType];\n }\n\n return ({}).toString.call(o).match(/\\s([a-z|A-Z]+)/)[1].toLowerCase();\n };\n}(this, Object, null));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-26T18:02:26.710", "Id": "11234", "ParentId": "5051", "Score": "2" } } ]
{ "AcceptedAnswerId": "5052", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T04:42:11.410", "Id": "5051", "Score": "4", "Tags": [ "javascript" ], "Title": "Javascript typeOf" }
5051
<p>I would like a serious, blunt and cold judgement on this code. Would it be considered 'good' code? In general, is it well written? Is the design reasonable?</p> <pre><code>#include &lt;iostream&gt; // C++ IO library code to include. #include &lt;string&gt; // C++ string functions. using namespace std ; // Use standard C++ names for functions. //====== class declaration. class Tpacket_list {public: // functions that are available to code outside the class. // put the command line into the list. Tpacket_list(int param_index, string param) ; void print_list() ; // print the list. Tpacket_list* find( string target) ; int tell_id() ; string tell_payload() ; protected: // Data in a class is normally hidden from other code. string payload ; // C++ strings are classes so this is aggregation. int id ; // Such strings are more powerful and easier to use Tpacket_list *next ; // than the older C string routines, also slower! } ; Tpacket_list *list_head ; // Start of linked list, set to 1st item. Tpacket_list *work_ptr ; // Work pointer to work along list. //====== Class Body ========================================================= //------ Constructor gets called when the class is created. It puts in the // payload and sets up the chain of pointers.All this is hideen from // the user of the class. Tpacket_list::Tpacket_list(int param_index, string param) {//--- save information for this parameter. id = param_index ; payload = param ; cout &lt;&lt; " Adding parameter # " &lt;&lt; id &lt;&lt; ", value = " &lt;&lt; payload &lt;&lt; endl ; //--- form list. next = list_head ; list_head = this ; } //------ Print the list. Note how the function calls the print_list function // in the next item in the link list. // Function prints from the current link list item to the end. void Tpacket_list::print_list() {//--- cout &lt;&lt; " id = " &lt;&lt; id &lt;&lt; ", payload = " &lt;&lt; payload &lt;&lt; ", length " &lt;&lt; payload.length() &lt;&lt; " characters."&lt;&lt; endl ; if ( next != NULL) // if there is a next item, get it to print itself. next-&gt;print_list() ; } //------ Find item in the list. Tpacket_list* Tpacket_list::find( string target) {//--- if ( payload == target) return ( this) ; // return pointer to current object. if ( next == NULL) return( NULL) ; // end of list, not match, return NULL. //--- if got here there is a valid next. return( next-&gt;find( target)) ; } //------ Tell of internal data. int Tpacket_list::tell_id() { return( id) ; } string Tpacket_list::tell_payload() { return( payload) ; } //====== Start program here ================================================= int main(int argc, char *argv[]) // argc = number strings on command line. // argv is array of strings each holding // a parameter. {//--- Initialize link list with command parameters. cout &lt;&lt; endl &lt;&lt; " Form link list of command line parameters." &lt;&lt; endl ; list_head = NULL ; int i = 1 ; while ( i &lt; argc) { new Tpacket_list(i, argv[i]) ; i++ ; } //--- print out the list. cout &lt;&lt; " Print paramters from head of list the end of list." &lt;&lt; endl ; if ( list_head != NULL) list_head-&gt;print_list() ; else cout &lt;&lt; " List is empty." &lt;&lt; endl ; //--- search for parameters cout &lt;&lt; " Find first 0 parameter (working last to first parameter, list head to tail)." &lt;&lt; endl ; Tpacket_list *found ; if ( list_head != NULL) { found = list_head-&gt;find("0") ; if ( found != NULL) cout &lt;&lt; " Found target on parameter # " &lt;&lt; found-&gt;tell_id() &lt;&lt; endl ; else cout &lt;&lt; " No \"0\" found." &lt;&lt; endl ; } cout &lt;&lt; endl ; return(0) ; } </code></pre> <p>P.S. It's not my code, it's actually the lecturer's.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-09T23:57:53.920", "Id": "13832", "Score": "2", "body": "Your question title is no good." } ]
[ { "body": "<p>To say the truth, it's bad code, the comments are the only good thing, though they could be better. Here are some ways to improve your code:</p>\n\n<ul>\n<li>use multiple files: the declarations of the class and functions should be in .h, while the implementation should be in a separate file, it would be better also to put the main separately</li>\n<li>there is a lot of formatting to be done, </li>\n</ul>\n\n<p>like for </p>\n\n<pre><code>if ( found != NULL)\n cout &lt;&lt; \" Found target on parameter # \" &lt;&lt; found-&gt;tell_id() &lt;&lt; endl ;\n else cout &lt;&lt; \" No \\\"0\\\" found.\" &lt;&lt; endl ;\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>if ( found != NULL)\n cout &lt;&lt; \" Found target on parameter # \" &lt;&lt; found-&gt;tell_id() &lt;&lt; endl ;\nelse \n cout &lt;&lt; \" No \\\"0\\\" found.\" &lt;&lt; endl ;\n</code></pre>\n\n<p>or even better</p>\n\n<pre><code>if ( found != NULL) {\n cout &lt;&lt; \" Found target on parameter # \" &lt;&lt; found-&gt;tell_id() &lt;&lt; endl ;\n} else {\n cout &lt;&lt; \" No \\\"0\\\" found.\" &lt;&lt; endl ;\n}\n</code></pre>\n\n<p>so that you can add code later without any problem</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T13:42:55.687", "Id": "7566", "Score": "1", "body": "Where in the world did you get the idea that C++ should use camel case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T13:52:43.693", "Id": "7567", "Score": "0", "body": "I thought it is recommended, isn't it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T14:33:21.837", "Id": "7569", "Score": "2", "body": "@Mansuro: Using the underscores in C++ is still very standard. See the Google style guide: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml \"Variable names are all lowercase, with underscores between words\". This is what STL and Boost do, as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T16:05:19.800", "Id": "7573", "Score": "5", "body": "Sorry, I disagree. The comments are hands down the worst thing in this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T16:11:09.363", "Id": "7574", "Score": "0", "body": "@KonradRudolph it's true they are ugly, but since they are for teaching purposes I guess they could be acceptable" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T11:06:16.563", "Id": "5055", "ParentId": "5054", "Score": "2" } }, { "body": "<pre><code>#include &lt;iostream&gt; // C++ IO library code to include.\n#include &lt;string&gt; // C++ string functions.\nusing namespace std ; // Use standard C++ names for functions.\n\n\n//====== class declaration.\n\nclass Tpacket_list\n{public: // functions that are available to code outside the class.\n</code></pre>\n\n<p>Better to put public on a line by itself</p>\n\n<pre><code> // put the command line into the list.\n Tpacket_list(int param_index, string param) ; \n void print_list() ; // print the list.\n Tpacket_list* find( string target) ;\n int tell_id() ;\n string tell_payload() ;\n</code></pre>\n\n<p>tell? typically people use get, or no prefix. Using tell is odd.</p>\n\n<pre><code> protected: // Data in a class is normally hidden from other code.\n string payload ; // C++ strings are classes so this is aggregation.\n int id ; // Such strings are more powerful and easier to use\n Tpacket_list *next ; // than the older C string routines, also slower!\n} ;\n\n\nTpacket_list *list_head ; // Start of linked list, set to 1st item.\nTpacket_list *work_ptr ; // Work pointer to work along list.\n</code></pre>\n\n<p>Global variables are not recommended</p>\n\n<pre><code>//====== Class Body =========================================================\n\n//------ Constructor gets called when the class is created. It puts in the\n// payload and sets up the chain of pointers.All this is hideen from\n// the user of the class.\n</code></pre>\n\n<p>You don't need to tell me that a constructor gets called when teh class is created. Anybody reading your code will know that. Your comment should really describe the meaning of the parameters not discussion of what is hidden from the user. </p>\n\n<pre><code>Tpacket_list::Tpacket_list(int param_index, string param) \n{//--- save information for this parameter.\n id = param_index ;\n payload = param ;\n cout &lt;&lt; \" Adding parameter # \" &lt;&lt; id &lt;&lt; \", value = \" &lt;&lt; payload &lt;&lt; endl ;\n //--- form list.\n next = list_head ;\n list_head = this ;\n</code></pre>\n\n<p>Its usually better to manage the list outside of the class. Always putting ever element in a list is usually a bad idea. </p>\n\n<pre><code>}\n\n//------ Print the list. Note how the function calls the print_list function\n// in the next item in the link list.\n// Function prints from the current link list item to the end.\nvoid Tpacket_list::print_list()\n{//---\n cout &lt;&lt; \" id = \" &lt;&lt; id &lt;&lt; \", payload = \" &lt;&lt; payload &lt;&lt; \", length \" &lt;&lt; payload.length() &lt;&lt; \" characters.\"&lt;&lt; endl ;\n if ( next != NULL) // if there is a next item, get it to print itself.\n next-&gt;print_list() ;\n}\n</code></pre>\n\n<p>This function is recursive, but that is not generally a good idea. It'll limit how many elements you can have in your list and be less efficent then an iterative solution.</p>\n\n<pre><code>//------ Find item in the list.\nTpacket_list* Tpacket_list::find( string target)\n{//---\n if ( payload == target)\n return ( this) ; // return pointer to current object.\n</code></pre>\n\n<p>You don't need parens for a return statement.</p>\n\n<pre><code> if ( next == NULL)\n return( NULL) ; // end of list, not match, return NULL.\n //--- if got here there is a valid next.\n return( next-&gt;find( target)) ;\n}\n\n//------ Tell of internal data.\nint Tpacket_list::tell_id() \n { return( id) ;\n }\n\nstring Tpacket_list::tell_payload()\n { return( payload) ;\n }\n\n//====== Start program here =================================================\n\nint main(int argc, char *argv[]) // argc = number strings on command line.\n // argv is array of strings each holding \n // a parameter.\n\n{//--- Initialize link list with command parameters.\n cout &lt;&lt; endl &lt;&lt; \" Form link list of command line parameters.\" &lt;&lt; endl ;\n list_head = NULL ;\n int i = 1 ;\n while ( i &lt; argc)\n { new Tpacket_list(i, argv[i]) ;\n i++ ;\n }\n</code></pre>\n\n<p>Use a for loop, not a while loop here.</p>\n\n<pre><code> //--- print out the list.\n cout &lt;&lt; \" Print paramters from head of list the end of list.\" &lt;&lt; endl ;\n if ( list_head != NULL)\n list_head-&gt;print_list() ;\n else cout &lt;&lt; \" List is empty.\" &lt;&lt; endl ;\n\n //--- search for parameters\n cout &lt;&lt; \" Find first 0 parameter (working last to first parameter, list head to tail).\" &lt;&lt; endl ;\n Tpacket_list *found ;\n if ( list_head != NULL)\n { found = list_head-&gt;find(\"0\") ;\n</code></pre>\n\n<p>I recommend not putting the statement on the same line as {1</p>\n\n<pre><code> if ( found != NULL)\n cout &lt;&lt; \" Found target on parameter # \" &lt;&lt; found-&gt;tell_id() &lt;&lt; endl ;\n else cout &lt;&lt; \" No \\\"0\\\" found.\" &lt;&lt; endl ;\n }\n\n cout &lt;&lt; endl ;\n return(0) ;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T12:46:08.100", "Id": "5056", "ParentId": "5054", "Score": "2" } }, { "body": "<p>First off, as a disclaimer, I don't code in C/C++, so I may critique some common practices that are considered acceptable as it's the norm.</p>\n\n<p>Nevertheless, a few things stand out.</p>\n\n<p><strong>Comments</strong></p>\n\n<p>Comments should be used to describe why something is being done. The code itself should be self-descriptive as to what it is doing.</p>\n\n<p><code>Tpacket_list *work_ptr ; // Work pointer to work along list.</code></p>\n\n<p>For example, could this variable be renamed to make it self-descriptive? Perhaps <code>*current_list_item</code>. Perhaps something else that would eliminate the need for the comment.</p>\n\n<p><strong>One File Per Class</strong></p>\n\n<p>Generally speaking, you want one file per class. I also believe it is common practice for C/C++ programs to have one file for the header and one for the code for that header. Maybe something like <code>Tpacket_list.h</code> and <code>Tpacket_list.cpp</code>, as well as your <code>main.cpp</code>.</p>\n\n<p><strong>Scope</strong></p>\n\n<p>Why are your Tpacket_list variables protected? Is there a reason they aren't private?</p>\n\n<p>Also, list_head is declared in main, then freely accessed as a global variable within the Tpacket_list class. Rather than do this, it is considered better practice to use Dependency Injection. Pass this variable in to the class that requires access to it.</p>\n\n<p>It will make your code far easier to maintain later. It will also open up the possibility of unit testing your class.</p>\n\n<p><strong>Random Thoughts</strong></p>\n\n<ul>\n<li>Can you simply return early if there is no list?</li>\n<li>Tpacket_list seems to be both the collection and the items of the collection. Would splitting these concepts out make sense? If the program remains small, I'm sure it's fine. If it grows to be large, this will gain value.</li>\n<li>It's stylistic as to whether or not you use curly brackets around the contents of if-else statements however I would note that I've never seen someone make an error with them in place, yet I have seen mistakes where they were missing.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T12:52:20.820", "Id": "5057", "ParentId": "5054", "Score": "2" } }, { "body": "<p>For overall quality, I'd give this about a 2 or maybe a 3 (on a scale of 1-10). Honestly, even 3 is being pretty generous though.</p>\n\n<pre><code>#include &lt;iostream&gt; // C++ IO library code to include.\n#include &lt;string&gt; // C++ string functions.\nusing namespace std ; // Use standard C++ names for functions.\n</code></pre>\n\n<p><code>using namespace std;</code> is generally frowned upon. There are reasons for <code>using</code> a namespace, but doing it globally like this (especially with the <code>std</code>namespace) is just a lousy idea.</p>\n\n<pre><code>//====== class declaration.\n</code></pre>\n\n<p>I'm sort of split on this one. On one hand, vacuous comments like this are generally worse than useless. At the same time, given that it's written exclusively for teaching, it may be excusable to include a few things we'd normally reject, describing basics of how C++ works. This would be a no-no in real code, but under the circumstances it's understandable and (I guess) reasonable.</p>\n\n<pre><code>class Tpacket_list\n{public: // functions that are available to code outside the class.\n</code></pre>\n\n<p>Your teacher seems to be working hard at disproving the usual wisdom about formatting. Most people figure that the exact formatting you choose is less important than using it consistently. This is one of the few I've seen that really does seem to make the code more difficult to read.</p>\n\n<pre><code> // put the command line into the list.\n Tpacket_list(int param_index, string param) ; \n void print_list() ; // print the list.\n Tpacket_list* find( string target) ;\n int tell_id() ;\n string tell_payload() ;\n</code></pre>\n\n<p>The comment here is misleading at best. The code to put the command line into the list is elsewhere (somewhere down in <code>main</code>).</p>\n\n<pre><code> protected: // Data in a class is normally hidden from other code.\n string payload ; // C++ strings are classes so this is aggregation.\n int id ; // Such strings are more powerful and easier to use\n Tpacket_list *next ; // than the older C string routines, also slower!\n} ;\n</code></pre>\n\n<p>Here we have a real design problem. He's conflating two ideas that should be completely separate: a linked list, and a node <em>in</em> a linked list. To work at all well, a linked list nearly needs to separate the two:</p>\n\n<pre><code>class list { \n struct Node { \n int id;\n std::string param;\n Node *next;\n\n Node(int param_index, std::string const &amp;p) :\n id(param_index), param(p)\n {}\n }\n\npublic:\n list(list const &amp;);\n // ...\nprivate:\n node *list_head;\n};\n</code></pre>\n\n<p>In this case, a <code>node</code> is pretty much just dumb data; the list class has all the real \"knowledge\" of how to do useful things. Also note that in reality, this should almost certainly be a class template instead of an actual class. Instead of hard-coding an <code>int</code> and a <code>std::string</code> as the types of data being stored, we really want to make those template parameters so we can create a linked list holding any kind of data we want.</p>\n\n<pre><code>Tpacket_list *list_head ; // Start of linked list, set to 1st item.\nTpacket_list *work_ptr ; // Work pointer to work along list.\n</code></pre>\n\n<p>\"Daddy, he defined a global!\"<br>\n\"Son, what have I told you about using language like that?\"<br></p>\n\n<pre><code>//====== Class Body =========================================================\n\n//------ Constructor gets called when the class is created. It puts in the\n// payload and sets up the chain of pointers.All this is hideen from\n// the user of the class.\n</code></pre>\n\n<p>I'll repeat the earlier comment about comments for emphasis: while (barely) acceptable under the circumstances, these would clearly have no place in real code.</p>\n\n<pre><code>Tpacket_list::Tpacket_list(int param_index, string param) \n{//--- save information for this parameter.\n id = param_index ;\n payload = param ;\n cout &lt;&lt; \" Adding parameter # \" &lt;&lt; id &lt;&lt; \", value = \" &lt;&lt; payload &lt;&lt; endl ;\n //--- form list.\n next = list_head ;\n list_head = this ;\n}\n</code></pre>\n\n<p>This code has quite a problems. First of all, you should generally prefer initializing the members in an initializer list:</p>\n\n<pre><code>Tpacket_list::Tpacket_list(int param_index, string param) :\n id(param_index),\n payload(param)\n</code></pre>\n\n<p>OTOH, per the earlier comment, this code should really be in Node::Node instead. From the viewpoint of the linked list, this code shouldn't be in a ctor at all. Following the usual conventions for C++, this would be a function named <code>push_front</code> (and it would normally only take <em>one</em> data type as the input -- to store an <code>int</code> and a <code>std::string</code>, we'd put those together into a struct of some sort -- an <code>std::pair</code>, if nothing else.</p>\n\n<pre><code>//------ Print the list. Note how the function calls the print_list function\n// in the next item in the link list.\n// Function prints from the current link list item to the end.\nvoid Tpacket_list::print_list()\n{//---\n cout &lt;&lt; \" id = \" &lt;&lt; id &lt;&lt; \", payload = \" &lt;&lt; payload &lt;&lt; \", length \" &lt;&lt; payload.length() &lt;&lt; \" characters.\"&lt;&lt; endl ;\n if ( next != NULL) // if there is a next item, get it to print itself.\n next-&gt;print_list() ;\n}\n</code></pre>\n\n<p>IMO, the very existence of this function is a problem. To print out the contents of a list, we really want to apply an algorithm (e.g., <code>std::copy</code>) to the list (or some subset thereof). To do that, our list should define <code>begin()</code> and <code>end()</code>, which return list iterators. The iterator type should define (at least) operator++ to traverse the list. In our case, the iterator type would be a fairly thin wrapper around a pointer to a node:</p>\n\n<pre><code>class list {\n class Node { /* ... */ };\n\n // warning: typing this in off the top of my head. It probably has at least a few\n // problems.\n class iterator {\n Node *pos;\n public:\n Node operator*() { return *pos; }\n iterator &amp;operator++() { \n if (NULL == pos)\n return NULL;\n pos = pos -&gt; next;\n return *this;\n }\n bool operator==(iterator const &amp;other) { \n return pos == other.pos;\n }\n };\n</code></pre>\n\n<p>This way, when we want to print out a list, we can use the same algorithms (and idioms in general) that we can with any of the other containers in the standard library.</p>\n\n<pre><code>//------ Find item in the list.\nTpacket_list* Tpacket_list::find( string target)\n{//---\n if ( payload == target)\n return ( this) ; // return pointer to current object.\n if ( next == NULL)\n return( NULL) ; // end of list, not match, return NULL.\n //--- if got here there is a valid next.\n return( next-&gt;find( target)) ;\n}\n</code></pre>\n\n<p>Again, probably pointless -- instead of a <code>find</code> member function, provide a conforming iterator type so you use use <code>std::find</code> (among other things).</p>\n\n<pre><code>//------ Tell of internal data.\nint Tpacket_list::tell_id() \n { return( id) ;\n }\n\nstring Tpacket_list::tell_payload()\n { return( payload) ;\n }\n</code></pre>\n\n<p>I can't say I <em>like</em> these much, but they're about the only thing so far that isn't obviously/blatantly wrong...</p>\n\n<pre><code>//====== Start program here =================================================\n\nint main(int argc, char *argv[]) // argc = number strings on command line.\n // argv is array of strings each holding \n // a parameter.\n\n{//--- Initialize link list with command parameters.\n cout &lt;&lt; endl &lt;&lt; \" Form link list of command line parameters.\" &lt;&lt; endl ;\n list_head = NULL ;\n int i = 1 ;\n while ( i &lt; argc)\n { new Tpacket_list(i, argv[i]) ;\n i++ ;\n }\n</code></pre>\n\n<p>Here we see the bad effects of the poor design. This code <em>claims</em> to create (and, incidentally, leak) <code>argc-1</code> separate <code>Tpacket_list</code>s. In reality, it creates a single linked list, because the ctor does an implicit <code>push_front</code> on the (singular) global linked list represented by the nasty global. For usability we clearly want something like this:</p>\n\n<pre><code> linked_list&lt;std::pair&lt;int, std::string&gt; &gt; list;\n\n for (int i=1; i&lt;argc; i++)\n list.push_back(std::make_pair(i, argv[i]));\n\n //--- print out the list.\n cout &lt;&lt; \" Print paramters from head of list the end of list.\" &lt;&lt; endl ;\n if ( list_head != NULL)\n list_head-&gt;print_list() ;\n else cout &lt;&lt; \" List is empty.\" &lt;&lt; endl ;\n</code></pre>\n\n<p>Then, to print out the list, we'd have code like:</p>\n\n<pre><code>if (list.empty())\n std::cout &lt;&lt; \"List is empty.\\n\";\nelse\n std::copy(list.begin(), list.end(),\n std::ostream_iterator&lt;std::pair&lt;int, std::string&gt;(std::cout, \"\\n\"));\n</code></pre>\n\n<p>and of course:</p>\n\n<pre><code> //--- search for parameters\n cout &lt;&lt; \" Find first 0 parameter (working last to first parameter, list head to tail).\" &lt;&lt; endl ;\n Tpacket_list *found ;\n if ( list_head != NULL)\n { found = list_head-&gt;find(\"0\") ;\n if ( found != NULL)\n cout &lt;&lt; \" Found target on parameter # \" &lt;&lt; found-&gt;tell_id() &lt;&lt; endl ;\n else cout &lt;&lt; \" No \\\"0\\\" found.\" &lt;&lt; endl ;\n }\n</code></pre>\n\n<p>...searching in the linked list would be done with <code>std::find</code> instead of writing our own (clumsy) imitation.</p>\n\n<p>As a final note, since the linked list allocates Nodes dynamically, we almost certainly need to provide a dtor that will delete those nodes. We also want to either provide a copy ctor that will copy the nodes, or else declare the copy ctor privately<sup>1</sup> to prevent anybody from copying a linked list at all.</p>\n\n<hr>\n\n<p><sup>1</sup> In C++11, we could use the <code>=delete</code> syntax to remove it as well, but it may be a bit premature to teach that as normal C++ usage just yet.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T15:00:13.397", "Id": "7570", "Score": "1", "body": "Great explanation, I would vote more than once if I could" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T16:34:17.127", "Id": "7575", "Score": "1", "body": "Can't fault any of your comments if this was production code. But this is code being used to teach concepts to people that have not learned all of them. The inclusion of `list_head` is an indication that this is not complete (otherwise your application can only have one list) and is being used as a work in progress that will be improved upon as more advanced techniques are introduced." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-27T19:30:47.113", "Id": "9837", "Score": "0", "body": "@Jerry: If he provides copy-ctor, he has to provide copy-assignment as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-09T23:55:51.097", "Id": "13830", "Score": "0", "body": "Some of the comments are vacuous but possibly useful to beginners. Not \"`Class Body`\", however, that's just wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-02-10T01:18:19.390", "Id": "13838", "Score": "0", "body": "Thank you for your indepth assessment of the code. I had a feeling that some of it was pretty bad, especially the design! I needed to be sure as to what exactly was wrong with it, so that I myself, don't learn incorrectly from it. Unfortunately, this code is what we are supposed to use as a 'model'.\n\nThank you for your time. I too wish that I could vote you up more than once!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T14:49:48.863", "Id": "5058", "ParentId": "5054", "Score": "12" } }, { "body": "<p>The code below is not perfect. But we have to take into consideration that we are trying to convey basic concepts to a group of people that do not understand the full scope of C++ yet. Thus certain shortcuts will be made on a class of this complexity. Over the course of a year you may re-visit this code and see incremental improvements as your class increases its knowledge of the language.</p>\n<p>For example I have commented on places where I would expect to see streams/smart pointers/const corectnes/Iterators/exceptions. But it would be pointless to include these concepts into a program being taught to absolute beginners. You need to teach the concept then retrofit the code with the new concept.</p>\n<hr />\n<h3>Summary:</h3>\n<p>The code wraps functionality into a node object that should probably be contained in a higher level construct (like the list object). There are a few clues in the code that indicate that this is a work in progress to teach concepts (so we can forgive that).</p>\n<p>Way to many comments for real code.<br />\nThey clutter things up and make it hard to read (But OK since it is part of teaching course).</p>\n<p>This is just lazy<br />\nAvoid <code>using namespace</code> if at all possible</p>\n<pre><code>using namespace std ;\n</code></pre>\n<blockquote>\n<p>Data in a class is normally hidden from other code.C++ strings are classes so this is aggregation. Such strings are more powerful and easier to use than the older C string routines, also slower!</p>\n</blockquote>\n<p>I disagree with the <code>slower</code>. C++ string may use a couple more bytes but if general usage will be quicker because the size if pre-computed (you would be surprised how many times the size of a C-string is re-computed).</p>\n<pre><code>class Tpacket_list\n{public:\n</code></pre>\n<p>That is really ugly. Put the <code>public</code> on its own line (make it readable).</p>\n<pre><code>void print_list() ;\n</code></pre>\n<p>Print the list where? Usually when you print something you are printing to a stream (std::cout). Usually you want to make sure you can pass in a different type of stream so it can go to a file or be serialized to a string for transport. SO I would have expected a print statement to take a stream object so the stream could be printed.</p>\n<p>Also in C++ objects are usually printed via the &lt;&lt; operator. But it is acceptable to put a print method in the class to act as a helper for the operator. The stream operator may be something that will come latter in the course.</p>\n<pre><code> Tpacket_list* find( string target) ;\n</code></pre>\n<p>Pointers are a really bad idea. They do not convey ownership of the returned object (so who is responsible for deleting them). I assume the problem is that if you can find the object you need a way to indicate that it was not contained and you can use NULL to indicate this. Containers in C++ usually return iterators on a find. A failure to find an element returns end() (which is an iterator to one passed the end of the container).</p>\n<p>Also prefer to pass parameters by const reference (prevents an unnecessary copy).</p>\n<pre><code> int tell_id() ;\n string tell_payload() ;\n</code></pre>\n<p>Looks like the last three methods should all be marked const.\nThey all seem to be non mutating methods. Thus they are all const.</p>\n<pre><code> protected: \n</code></pre>\n<p>Protected provides no protection (it does but it is an illusion that is easily pierced). Prefer to use private (especially in this case). By using public/protected you are including all these members in the public interface (this is an OO concept not a C++ concept) of the object. Anything in the public interface must be maintained in the future thus tightly binding you to this implementation.</p>\n<pre><code> Tpacket_list *next ;\n</code></pre>\n<p>Combining business data and resource management into a single object breaks the <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\">separation of concerns principle</a>. By making your object do both resource management (handling the actions of a list) and business logic (packet data) you might be making it more compact but you are making the code more complex to handle this situation. As a result you will pay for your compact data with more code.</p>\n<pre><code>Tpacket_list *list_head ; // Start of linked list, set to 1st item.\nTpacket_list *work_ptr ; // Work pointer to work along list.\n</code></pre>\n<p>OK. I am going to ignore this and assume it is a work in progress. Otherwise your application can only have one list.</p>\n<pre><code>Tpacket_list::Tpacket_list(int param_index, string param)\n{\n id = param_index ;\n payload = param ;\n</code></pre>\n<p>Prefer to use the initializer list.</p>\n<pre><code>void Tpacket_list::print_list()\n{\n if ( next != NULL)\n next-&gt;print_list() ;\n</code></pre>\n<p>Recursion is a neat trick to teach for education purposes. But in industrial code prefer a loop here. Recursion has the potential of blowing your stack. A loop will always work no matter what the size of the list. Should be encapsulated in at a higher level (the owner of the list nodes).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T16:11:59.823", "Id": "5059", "ParentId": "5054", "Score": "3" } } ]
{ "AcceptedAnswerId": "5058", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T09:56:01.637", "Id": "5054", "Score": "5", "Tags": [ "c++" ], "Title": "I would like to know if the following code is 'good'" }
5054
<p>Simple question:</p> <p>What would you rather do?</p> <pre><code>public class FooRepository { public Foo GetById(int id) { Foo foo = null; using (IDataReader data = /* Get Foo's data */) { // Let the Foo object set it's own fields using the data object foo = new Foo(data); } return foo; } } </code></pre> <p>Or...</p> <pre><code>public class FooRepository { public Foo GetById(int id) { Foo foo = null; using (IDataReader data = /* Get Foo's data */) { // Let the Repository class set the Foo object fields foo = new Foo(); foo.Id = Convert.ToInt32(data["FooID"]); foo.Name = data["Name"].ToString(); } return foo; } } </code></pre> <p>Assuming you can't use an ORM (NHibernate, L2S, EF) to handle this for you and that you will need to create Foo in other methods of the repository.</p> <p>Any explanation will be welcome!</p>
[]
[ { "body": "<p>Part of the goal for using the Repository pattern is to separate the storage from the domain. By passing the IDataReader in to a Foo object, I feel like the domain gains too much knowledge of the underlying storage mechanism.</p>\n\n<p>So, between the options listed, I prefer setting the object's properties in the Repository. That being said, if the object doesn't make sense without a certain property, it should still demand it during its creation. However, even in this case, the Repository would still be responsible for setting all the properties requested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T22:20:22.927", "Id": "7591", "Score": "0", "body": "Thanks! I have found the first case to be useful in certain cases (by using inheritance and constructor inheritance for example), but still think that the second one separates concerns more clearly." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T18:46:54.687", "Id": "5062", "ParentId": "5061", "Score": "3" } }, { "body": "<p>I would vote for the second option for sure, because it allows you to separate your domain objects from the database. Mapping is a responsibility of a data access layer and not of domain objects. But usually these kind of logic is moved to a special classes which are called DataMappers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T22:04:14.937", "Id": "7589", "Score": "0", "body": "Great, thanks! Regarding DataMappers, wouldn't that be an overkill if I were **always** using Databases? I've been using the first approach because it's easier, but I'm considering to start using the second one to clearly separate concerns." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T18:47:09.270", "Id": "5063", "ParentId": "5061", "Score": "2" } }, { "body": "<p>Given no ORM, I generally have a DAL helper method like:</p>\n\n<pre><code>IEnumerable&lt;T&gt; ExecuteEnumerable&lt;T&gt;(string commandText, CommandType commandType, IEnumerable&lt;IDbDataParameter&gt; parameters, Func&lt;IDataRecord, T&gt; processRecord)\n{\n ...\n using(IDataReader reader ...)\n {\n while(reader.Read())\n {\n yield return reader;\n }\n }\n}\n</code></pre>\n\n<p>Then I'd use it as follows:</p>\n\n<pre><code>private static Foo GetFooFromRecord(IDataRecord record)\n{\n foo = new Foo(); \n foo.Id = Convert.ToInt32(record[\"FooID\"]); \n foo.Name = record[\"Name\"].ToString();\n return foo;\n}\n\npublic Foo GetById(int id) \n{ \n ... \n // PK - I know there's at most one result\n return ExecuteEnumerable(..., GetFooFromRecord).FirstOrDefault(); \n}\n\npublic IList&lt;Foo&gt; GetByName(string name)\n{\n ... \n // May be more than one match\n return ExecuteEnumerable(..., GetFooFromRecord).ToList(); \n}\n</code></pre>\n\n<p>The static <code>GetFooFromRecord</code> method is in the repository, and can be reused for multiple queries.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T17:18:48.623", "Id": "5083", "ParentId": "5061", "Score": "2" } } ]
{ "AcceptedAnswerId": "5062", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T16:51:11.833", "Id": "5061", "Score": "5", "Tags": [ "c#" ], "Title": "Recomendations on where to set an object properties (Repository Pattern)" }
5061
<p>Here is the question. From SPOJ [HS11DIVS]. Now , the problem is that my code works perfectly for small numbers. But when it comes to <strong>Large numbers</strong> , the time limit exceeds. <br>I am not getting any hint on how to make it more efficient. The code is simple enough to understand. I mean its a pretty basic question but difficult to make it efficient. </p> <blockquote> <p>For given integers a and b we need to find how many integers in the range [a,b] are divisible by a number x, and have the additional property that the sum of their digits lies in the ,range [l,r] for given l,r.</p> <p><strong>Input</strong></p> <p>In the first line you're given a and b ( <strong>1 &lt;= a &lt;= b &lt; 10^100</strong> ). In the second line you're given three positive integers x ( 1 &lt;= x &lt;= 10 ), l, r ( 1 &lt;= l &lt;= r &lt;= 1,000 ).</p> <p><strong>Output</strong></p> <p>In the first and only line output the result modulo 1,000,000,007.</p> </blockquote> <p>And this is my attempt to the question. </p> <p><strong>UPDATED :</strong> </p> <pre><code>#include &lt;stdio.h&gt; int sumOfDigits(int number) { int sum=0; while(number!=0) { sum = sum + (number%10); number = number/10; } return sum; } /* UPDATED SEGMENT */ unsigned long long int first(unsigned long long int a,unsigned long long int b,int x) { unsigned long long int m = a%x; a = a - m + x; return a; } int main (void) { unsigned long long int a, b; int x, l, r; int counter=0,sum; scanf("%llu %llu", &amp;a, &amp;b); scanf("%d %d %d", &amp;x, &amp;l, &amp;r); a = first(a,b,x); // gives the first number divisible by x. while(a&lt;=b) { sum = sumOfDigits(a); if(l&lt;=sum &amp;&amp; r&gt;=sum) // check if sum of digits lies b/w l&amp;r. { counter+=1; } a+=x; // increment a by multiples of x. } printf("%d", counter); return 0; } </code></pre> <p><br> Where am i being inefficient? I even calculated the first number divisible by x , and then assign it to a , and then increase a by multiples of x ( a+=x; ). <br></p> <p>Here is a sample output : <br></p> <blockquote> <p><strong>Input</strong>: 1 100 5 10 50</p> <p><strong>Output</strong>: 5</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-18T12:01:50.183", "Id": "109222", "Score": "0", "body": "Would you please avoid making changes to the code in the question after the question has been asked? I see in the edit history that you have altered the code repeatedly. This will invalidate any answers already given and is generally not approved of at CR." } ]
[ { "body": "<p>First you need to correct first()</p>\n\n<pre><code>unsigned long long int first(unsigned long long int a,unsigned long long int b,int x)\n{\n // Removed b\n return a;\n} ^^^ otherwise the main loop will run through everything in the main loop (from 0).\n</code></pre>\n\n<p>Though first() looks efficient because you are doing it only once. The questioner may carefully craft a,b,x to take a long time. So you can optimize its evaluation:</p>\n\n<pre><code>unsigned long long int m = a%x;\na = a - m + x; // a now first valid value.\n</code></pre>\n\n<p>Your summing of the digits does a lot of extra work.</p>\n\n<pre><code>99 = 18\n199 = 19 1 + sum_of_digits(99)\n</code></pre>\n\n<p>You can use this to cache results and re-use them in later calculations.</p>\n\n<p>Pre compute the following array and compile it into your application.</p>\n\n<pre><code>sum_cache[10000] cache = {\n /* Generated code goes here */\n\n };\n\n\nint sumOfDigits(int number)\n{\n int sum=sum_cache[number % 10000];\n for(number = number/10000;number != 0; number/= 10)\n {\n sum += (number%10);\n }\n return sum;\n}\n</code></pre>\n\n<h3>Edit (based on comments below)</h3>\n\n<pre><code>int sumOfDigits(int number)\n{\n int sum=0;\n while(number!=0)\n {\n sum = sum + (number%10);\n number = number/10;\n }\n return sum;\n}\nint main()\n{\n std::ofstream data(\"data.d\");\n\n data &lt;&lt; 0;\n for(int loop=1; loop &lt; 10000; ++loop)\n {\n data &lt;&lt; \", \" &lt;&lt; sumOfDigits(loop);\n }\n}\n</code></pre>\n\n<p>Then change the code above too:</p>\n\n<pre><code>sum_cache[] cache = {\n /* Generated code goes here */\n #include \"data.d\"\n };\n</code></pre>\n\n<h3>Edit 2:</h3>\n\n<p>Improved: (I was hopping you would see the simple optimization)<br>\nDoes this help? </p>\n\n<pre><code>int sumOfDigits(int number)\n{\n int sum=0;\n for(;number != 0; number/= 10000)\n {\n sum += sum_cache[number % 10000];\n }\n return sum;\n}\n</code></pre>\n\n<h3>Max Loop:</h3>\n\n<pre><code>Original Version (your Code) 100 = 100\nFirst Cache Version 100-4 = 96\nSecond Cache Version 100/4 = 25\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:30:24.927", "Id": "7584", "Score": "0", "body": "I didnt get the sum_cache part. What is this \" Generated code goes here \" ? Which code shall i place there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:36:32.197", "Id": "7586", "Score": "1", "body": "You should write a program that generates the pre-computed values for 1->100000 and outputs them as a comma separated list. Then you add the output (the comma separated list of values) into this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:48:01.657", "Id": "7587", "Score": "0", "body": "But the thing is , i can't create another file and use it. I have to do everything in 1 program only.\nhere is the link to the problem : **https://hs.spoj.pl/problems/HS11DIVS/**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T22:12:33.513", "Id": "7590", "Score": "0", "body": "1 program != 1 file. A single program can be compiled from *n* files." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T23:08:21.010", "Id": "7592", "Score": "0", "body": "@Niteesh Mehra: Once you have generated the numbers and placed the output in a file you can throw the first program away. Using a program is just a short cut to typing out the number by hand (you can type all the numbers by hand and get the same result there is only 10000 in my version but I can see you doing the first 1 million easily)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T03:11:47.260", "Id": "7596", "Score": "0", "body": "Yes am getting the idea. So can u modify and provide me the complete code please?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T04:32:48.753", "Id": "7599", "Score": "0", "body": "The thing is how do i submit it online? Compling n files into one @Ed S." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T05:45:03.107", "Id": "7601", "Score": "0", "body": "@Tux-D : i tried your code. still no help for numbers greater than 10^9. the problem states that b can have value upto 10^100 !" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T16:19:15.980", "Id": "7608", "Score": "0", "body": "@Niteesh: Update 2 above. Also don't forget this line: `output the result modulo 1,000,000,007`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T17:08:47.447", "Id": "7613", "Score": "0", "body": "@Tux-D First off , how to even input numbers as large as 10^100 , let alone outputting the result as modulo 1,000,000,007 ??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T17:51:58.553", "Id": "7614", "Score": "0", "body": "Google: \"C++ BigInt\"" } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T19:54:04.170", "Id": "5069", "ParentId": "5064", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T18:53:42.097", "Id": "5064", "Score": "5", "Tags": [ "c", "programming-challenge", "time-limit-exceeded" ], "Title": "Time Limit Exceeds [HS11DIVS] - How to make it faster?" }
5064
<p>I'm not very experienced in test-driven development (TDD), but I'm trying to get into the groove. Here I am making a console app that creates records in a database. I bootstrapped by creating a console app and then let MSTest make a unit test for <code>Main(string [] args)</code>.</p> <p>I know I'm doing at least something right, because the tests didn't pass until I did the development -- they "drove" me to "develop".</p> <p>But I feel like maybe I'm still missing the point, as I didn't really test my code - I tested the database the code acted on. How would an experienced TDDer approach this?</p> <pre><code>[TestClass] public class ProgramTest { private MyEntities _model; [TestInitialize()] public void MyTestInitialize() { _model = new MyEntities(); } [TestCleanup()] public void MyTestCleanup() { _model.Dispose(); } [TestMethod()] public void MainTest_01_Create_PayTerms() { string[] args = new[] { "/Operation", "Insert", "/RecordType", "PayTerms" }; DirectAgentsService.Program.Main(args); _model.PayTerms.SelectValue&lt;string&gt;("it.Name").ShouldContain("Biweekly", "Retainer", "Net 7", "Net 15", "Net 30"); } } static public class Extensions { static public void ShouldContain(this string[] source, params string[] targets) { foreach (var target in targets) { Assert.IsTrue(targets.Any(c =&gt; c == target), "{0} is missing from collection", target); } } static public void ShouldContain&lt;T&gt;(this T source, params string[] targets) where T : ObjectQuery&lt;string&gt; { source.ToArray().ShouldContain(targets); } } </code></pre>
[]
[ { "body": "<p>You should not use <code>MyEntities</code> in your unit tests. Effectively you are doing integration testing here since each test will use the database and is dependent on the data stored there.</p>\n\n<p>Instead mock out <code>MyEntities</code> or make <code>MyEntities</code> derive from an interface <code>IMyEntities</code> that is the contract for your persistence layer.</p>\n\n<p>Now you can create a separate <code>MyTestEntities</code> the implements <code>IMyEntities</code> so you can verify your expectations independent of the data store. Then after you execute the class/method under test verify against the mock.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T18:54:33.177", "Id": "5066", "ParentId": "5065", "Score": "4" } }, { "body": "<p>Assuming you are speaking of Unit test driven development there are two things you need to get your head around first (or should I say, things I had to get my head around).\nBoth of them are actually about writing unit testable code (as compared to actually writing test first, etc)</p>\n\n<ul>\n<li><strong>Dependency injection:</strong> Avoid constucting objects inside other objects; instead, pass already constructed ones in through the constructor, or properties if appropriate. Look out for the <code>new</code> keyword and avoid it (exceptions apply, such as for classes that are pure data). Of course at some point objects need to be constructed. This should be done at high level classes (say somewhere near your console app's <code>main()</code>) at such a point that is simple enough to need no (unit) testing (since you won't be able to unit test it).\nDependency injection will allow you to inject mock or fake versions of the other classes you are dependent on.</li>\n<li><strong>Mocking/Stubbing/Faking/Test Doubles:</strong> Your unit tests should test only one thing, not all the things that one this is dependent on (they have their own tests). This allows you to localise (as in know the location of) any errors that show up. You can write your own stubs, but there are great libraries out there, and using them introduces a bit more consistency about how your tests work/look. <a href=\"http://nsubstitute.github.com/help.html\">NSubstitute</a> is a good choice becuase it uses extension methods to be really easy to read.</li>\n</ul>\n\n<p>As to the granularity for Unit Tests, it is as granular as you can go. That way you can localise errors (also the less granular/more integration test like, the harder is it to write tests, they become long). There is some argument about whether private methods should be tested or not. I would say it comes down to whether the private method is just a part of some public method (no) or it has its own well defined purpose (yes).</p>\n\n<p>However, Unit tests driven development isn't the only kind: BDD (behavour driven development) focuses on Functional tests.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-08T21:32:45.087", "Id": "11919", "Score": "0", "body": "+1 for mentioning NSubstitute. I didn't know about it, but it reaaly seems to have a clean, suggestive syntax so I think I'll give it a try." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T12:56:41.073", "Id": "5114", "ParentId": "5065", "Score": "9" } } ]
{ "AcceptedAnswerId": "5114", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T18:46:23.577", "Id": "5065", "Score": "7", "Tags": [ "c#", "unit-testing" ], "Title": "What's the right granularity for test-driven development?" }
5065
<p>I'm working on an implementation of the Double-Ended Queue as a Doubly-Linked List (for personal enrichment), and I was wondering if anyone minded taking a look at my Constructor/Destructor and Empty functions to see if I'm on the right track. It should be self-explanatory enough on it's own (I hope).</p> <pre><code> DeQueue::DeQueue() { // set up the sentinels head = new QueueItem(); tail = new QueueItem(); head-&gt;next = tail; tail-&gt;last = head; head-&gt;data = NULL; tail-&gt;data = NULL; tail-&gt;next = head-&gt;last = NULL; } DeQueue::~DeQueue() { QueueItem* current = head; QueueItem* next; current = current-&gt;next; for (;current != tail; current = current-&gt;next){ delete current-&gt;last; } delete current; } bool DeQueue::Empty() { return tail-&gt;last == head; } </code></pre> <p>The idea is that the two <code>head</code> and <code>tail</code> sentinels will always remain at the ends, so the easiest way to check if it is empty is to determine if <code>head</code> points to <code>tail</code> or vice versa. Also, in my destructor, I start at the tail and delete everything from there back, sentinels included. Any suggestions?</p> <p><strong>EDIT:</strong> The destructor now moves forward one node, deletes what's behind it, then moves on. Sound like a better approach?</p>
[]
[ { "body": "<p>I would make it so that you only have one sentanal.</p>\n\n<p>Then the list is empty when head and tail point at the same object.</p>\n\n<pre><code>DeQueue::DeQueue()\n // set up the sentinels\n : head(new QueueItem()) // prefer to use initialize list.\n , tail(head) // Make sure your declarations are in the correct order.\n{\n\n head-&gt;next = head; // Circular linked list.\n head-&gt;last = head;\n\n head-&gt;data = NULL; // No data in the fake node.\n}\n</code></pre>\n\n<p>Your delete loop does not actually move:</p>\n\n<pre><code>while(current-&gt;next != head)\n{\n delete current-&gt;next; // your deleting the element\n // But not moving the the current item\n // So the loop will not exit.\n}\n\n\nDeQueue::~DeQueue()\n{\n // Delete from the head.\n // Just slowly loop over the nodes deleting them as you go\n while(head != tail)\n {\n QueueItem* old = head;\n head = head-&gt;next;\n\n delete old;\n }\n // Delete the sentanal object created in the constructor.\n delete tail;\n}\n\n// Simplify empty.\nbool DeQueue::Empty()\n{\n return tail == head;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:24:41.233", "Id": "7583", "Score": "0", "body": "Thanks, I didn't even realize that. I think I'll stick with the dual sentinels for now (I'm a bit brain-dead at the moment) but how about this for the destructor? (check original post)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T16:27:38.980", "Id": "7610", "Score": "0", "body": "@wtfsven: Your destructor now works. But you should still use the initializaer list in your constructor." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T16:54:15.260", "Id": "7612", "Score": "0", "body": "+1 for initializer lists. Also, the QueueItem should set data to NULL in its constructor, so you don't need to worry about doing that in DeQueue." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T19:10:48.783", "Id": "7616", "Score": "0", "body": "@dominic: That depends. QueueItem may be a plain old POD type so adding a constructor will change its layout and some gurantees. Also if QueueItem is fully contained as a private member class of DeQueue then being so strict on its construction may not be beneficial when DeQueue is going to manage all its interactions anyway." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:06:16.710", "Id": "5070", "ParentId": "5067", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T19:27:26.673", "Id": "5067", "Score": "7", "Tags": [ "c++", "queue", "memory-management" ], "Title": "Double-Ended Queue - Have I over-engineered it again?" }
5067
<p>I've been spending a lot of time reading about JavaScript lately, and this is my first piece code that I've tried to apply some of what I've read to. I'm trying to stay clear of using a framework for this so I can have a better understanding of the JavaScript language itself. </p> <p>This code is part of a chrome extention I wrote to add a toolbar on the bottom of a users GitHub dashboard so they can filter out items. </p> <p>I'd like to get some feedback on its correctness, if there any best practices I've missed, and if there are any areas where I can be more "functional". Obviously I'd like to know if there are any obvious errors as well.</p> <pre><code>var filterObj = (function(){ var filterObj, newsItems = [], hiddenClasses = [], moreLink, visibleCount = 30, filterObjects = [], filters, versionKey = "githubNewsFilterVersion", filterKey = "filters"; //private var getFilters = function(){ //check for filters in the local storage, otherwise create a new object if(!localStorage[filterKey]){ filters = { issueComment : {text: "Issue Comment",id: "issues_comment",checked: false}, pullRequest : {text: "Pull Request &amp; Issue Opened",id: "issues_opened",checked: false}, follow : {text: "Follow",id: "follow",checked: false}, gist : {text: "Gist",id: "gist",checked: false}, push : {text: "Push",id: "push",checked: false}, created : {text: "Created Branch", id:"create",checked: false}, issueClosed : {text: "Close &amp; Merge", id:"issues_closed",checked: false}, fork: {text: "Forked", id: "fork",checked: false}, watch: {text: "Watch", id: "watch_started",checked: false}, editWiki : {text: "Wiki", id: "gollum",checked: false} }; localStorage[filterKey] = JSON.stringify(filters); } else{ filters = JSON.parse(localStorage[filterKey]); } }; var getNewsItems = function(callback){ var items = getElementsByClass("div","alert"), len = items.length, newsLength = newsItems.length, found = false, currentItem = ""; for(var i = 0; i &lt; len; i++){ found = false; currentItem = items[i]; //check that the items isn't in the list for(var x = 0; x &lt; newsLength; x++) { if(newsItems[x] == currentItem){ found = true; break; } } if(!found){ newsItems.push(items[i]); } } if(callback){ callback(); } }; var createDiv = function(){ var newDiv = document.createElement("div"); newDiv.id = "filterDiv"; newDiv.className = "filterBar"; document.getElementById("footer").appendChild(newDiv); filterObj = newDiv; createImg(); }; var createImg = function(){ var closeSpan = document.createElement("span"), closeImage = document.createElement("img"); closeImage.src = chrome.extension.getURL("assets/close.png"); closeSpan.className = "closeBtn"; closeImage.addEventListener("click",function(){ document.getElementById("filterDiv").style.display = "none"; }); closeSpan.appendChild(closeImage); filterObj.appendChild(closeSpan); }; var createElement = function(theType, theID, theName, theValue, theAttrs, theClass){ var newElem = document.createElement(theType), prop; newElem.id = theID || ""; newElem.name = theName || ""; newElem.value = theValue || ""; newElem.className = theClass || ""; for(prop in theAttrs){ if(theAttrs.hasOwnProperty(prop)){ newElem[prop] = theAttrs[prop]; } } return newElem; }; var setFilters = function(){ var prop; for(prop in filters){ var newFilterOption = createElement("input", prop, prop, filters[prop].id, {type : "checkbox"}); addListener(newFilterOption); if(filters[prop].checked){ newFilterOption.checked = true; } var newFilterLabel = createElement("label"); newFilterLabel.innerHTML = filters[prop].text; var newFilterWrapper = createElement("span"); newFilterWrapper.className = "filterOption"; newFilterWrapper.appendChild(newFilterLabel); newFilterWrapper.appendChild(newFilterOption); filterObjects.push(newFilterOption); filterObj.appendChild(newFilterWrapper); } }; var addListener = function(elem){ elem.addEventListener("change",function(){ var newsObjects = newsItems, len = newsObjects.length, i; if(elem.checked === true){ //loop through the elements array instead for(i = 0; i &lt; len; i++){ if(hasClass(newsObjects[i], elem.value)){ newsObjects[i].style.display = "none"; --visibleCount; } } } else{ for(i = 0; i &lt; len; i++){ if(hasClass(newsObjects[i], elem.value)){ newsObjects[i].style.display = "inherit"; ++visibleCount; } } } setFilterVal(elem.value,elem.checked); }); }; var setFilterVal = function(className,isChecked){ for(filterObj in filters){ if(filters[filterObj].id === className){ filters[filterObj]["checked"] = isChecked; break; } } localStorage[filterKey] = JSON.stringify(filters); }; var getMoreLink = function(){ var moreDiv = getElementsByClass('div',"ajax_paginate")[0]; moreLink = moreDiv.firstChild; attachClickListener(); }; var attachClickListener = function(){ moreLink.addEventListener("click",function(){ var i = 0; var intervalID = window.setInterval(function(){ i++; getNewsItems(runFilters); if( i === 20 ){ //reattach the event getMoreLink(); window.clearInterval(intervalID); } },200); }); } var runFilters = function(){ var len = filterObjects.length; for(var i = 0; i &lt; len; i++){ if(filterObjects[i].checked === true){ var evt = document.createEvent("HTMLEvents"); evt.initEvent("change", false, true); filterObjects[i].dispatchEvent(evt); } } } //looks like this function and the function below it can be rolled up into a partial //application var getElementsByClass = function(startTag, theClass){ //if no start tag was specified then get all the elements var elements = startTag ? document.getElementsByTagName(startTag) : document.all; var matches = []; var pattern = new RegExp("(^| )" + theClass + "( |$)"); for(var i =0; i&lt; elements.length; i++){ if(pattern.test(elements[i].className)){ matches.push(elements[i]); } } return matches; }; var hasClass = function(elem, theClass){ var pattern = new RegExp("(^| )" + theClass + "( |$)"); return pattern.test(elem.className); }; var checkVersion = function(){ var storedVersion = localStorage[versionKey], currentVersion = manifest.version; if(!storedVersion || storedVersion !== currentVersion){ localStorage.removeItem(filterKey); localStorage[versionKey] = currentVersion; } }; var manifest = (function() { var manifestObject = false; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { manifestObject = JSON.parse(xhr.responseText); } }; xhr.open("GET", chrome.extension.getURL('/manifest.json'), false); try { xhr.send(); } catch(e) { } return manifestObject; })(); //public return { Init : function(){ checkVersion(); getFilters(); createDiv(); getNewsItems(); setFilters(); getMoreLink(); runFilters(); } }; }()); filterObj.Init(); </code></pre>
[]
[ { "body": "<p>From a best practices standpoint, more comments will go a long way. Also the use of consistent camelCase is good and appreciated. One good practice which is pretty easy to implement is to declare all your variables at the start of the scope / function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T16:42:24.733", "Id": "5144", "ParentId": "5068", "Score": "5" } }, { "body": "<p>Personally I wouldn't use the pattern</p>\n\n<pre><code>var functionName = function (params, etc) { \n};\n</code></pre>\n\n<p>as this will make any debugging a PITA. The call stack will show something like: </p>\n\n<pre><code>Anonymous method: line 12\nAnonymous method: line 4\n</code></pre>\n\n<p>etc etc.</p>\n\n<p>Since you already have it inside just do:</p>\n\n<pre><code>(function(){\n function functionName ( params, etc){\n }\n})());\n</code></pre>\n\n<p>and you should be right to go. <a href=\"http://jsfiddle.net/6V26R/\">http://jsfiddle.net/6V26R/</a></p>\n\n<p>As a personal preference I wouldn't do:</p>\n\n<pre><code>var filterObj = (function(){\n var filterObj,\n //etc\n</code></pre>\n\n<p>as I find our brains cannot read that so well. Instead I would do:</p>\n\n<pre><code>var filterObj = (function(){\n var filterObjElement,\n //etc\n</code></pre>\n\n<p>now my brain distinguishes between the global object and the local variable holding an element. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T02:11:38.143", "Id": "7726", "Score": "1", "body": "Great point on the naming of the local variables. I think i ran out of creativity at that point!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T01:10:52.900", "Id": "5148", "ParentId": "5068", "Score": "7" } }, { "body": "<p>Why not continue your initial comma separated <code>var</code> declaration through to your functions? Like so:</p>\n\n<pre><code>versionKey = \"githubNewsFilterVersion\",\nfilterKey = \"filters\",\ngetFilters = function(){\n ...\n},\ngetNewsItems = function(callback){\n ...\n</code></pre>\n\n<p>And so on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T08:54:42.220", "Id": "5155", "ParentId": "5068", "Score": "0" } }, { "body": "<p>I'm going to post some of the feedback I got from the jsmentors group on google. This is the kind of stuff I was looking for. </p>\n\n<p>From Nathan Sweet:</p>\n\n<blockquote>\n <ol>\n <li><p>There is a structural issue in the way you organize you're code.\n You expose two global variables when you don't need to, not that it\n matters that much in this case. You are using a simple\n run-the-code-once scenario, which I personally think warrants the use\n of an anonymous object, but an anonymous function works well. Still,\n there is no need to initialize your code outside the function, in\n fact if everything was a function declaration you could initialize\n above all your functions. This is what an anonymous object looks \n like: ({ \n Init :function(){/<em>run your code</em>/}, \n method1:function(){this.method2();}, \n method2:function(){/<em>does something</em>/} }).Init() </p></li>\n <li><p>Just being nitpicky, you've built a getElementsByClass method, and\n I'm not entirely sure what it does, but I see you're checking the\n individual className of the elements in the method. Chrome has a\n built in method for getting elements by class. </p></li>\n <li>Lines 66-81 are painful, and I think you know it. Instead of\n looping through every element, try giving all the elements a unique\n id, or something like that, so that you can hash the results of one\n of those arrays and create an O(n) loop instead of an O(n*n) pattern.</li>\n </ol>\n</blockquote>\n\n<p>From Austin Cheney:</p>\n\n<blockquote>\n <p>This is the assignment way of creating a function: var whatever =\n function () {}; </p>\n \n <p>This is the declaration way of creating a function: function whatever\n () {} </p>\n \n <p>The second one is hoisted, which is often convenient and rarely a\n problem. However, in those exotic instances when hoisting is a\n problem it is catastrophic. There is nothing you can do to prevent\n the var keyword from being hoisted, but you can prevent functions from\n being hoisted. The only exception about hoisting and declared\n functions is when the function is immediately invoked just like the\n \"filterObj\" function in your code. This is because the function\n executes immediately in its current form and position. </p>\n \n <p>The common argument in favor of the declaration method, which I\n believe Rob was implying, is that for some people the declaration\n method is easier to read because you can quickly identify what is or\n is not a function. This is most certainly valid and I even agree with\n this fully for smaller applications. For larger applications\n containing many functions this argument fails. What is the value in\n trying to identify what is or is not a function if you have a\n container with 60 functions? At that point it is significantly faster\n to read the code by looking for the identifier and then determining\n whether the identifier is or is not a function by reading the very\n next word to its right. </p>\n \n <p>I also find that the declarative way is more challenging to maintain\n in an extremely large application because it is not tied to the var\n keyword. I find that binding references, whether variables or\n function names, to a single var keyword dramatically reduces\n complexity of actually reading the code. Because of this I always\n recommend using no more than one var keyword per function and ensuring\n that nothing comes before this one var keyword except immediately\n invoked functions and the \"use strict\" pragma. This one variable rule\n when used with the \"use strict\" pragma results in generally more\n sturdy and portable code as well as code that is easier to read. </p>\n \n <p>I see that around line 298 you are using a try/catch block. I\n absolutely detest try/catch blocks as a cheap attempt to mitigate\n known bugs. If you are aware of the possibility of a bug then correct\n your code. It the bug is the result of user input then output a\n response to this effect so that your user will know why the executed\n failed to perform as expected. </p>\n \n <p>I also do not see the value in using a return on an anonymous object\n literal at the end of your application. Clearly this goes to the\n architecture of your application in that you want a series of\n sub-global functions to execute in a particular order that may or may\n not return anything but none the less result in a the global\n \"filterObj\" returning some object literal. This is an old convention,\n particularly the use of something named \"init\" that strings together a\n series of unrelated executions. Part of the reason you are probably\n using this convention is that all the functions in your application\n appear to exist in an equal scope directly under the global\n \"filterObj\" contain, and this is inefficient. Only create functions\n in the scope where they are needed, or if some functions are needed in\n different locations then at the minimum possible scope for reuse. \n Doing this decreases lookups, which dramatically increases execution\n speed. Speed in JavaScript really comes down to reducing lookups and\n using the most appropriate operator or method for a given job. </p>\n \n <p>You also have some minor syntax violations in your code. For instance\n the \"attachClickListener\" is missing a terminating semicolon. This\n would prevent a bug free minification of your code. I would\n suggestion applying the prior mentioned guidance first and then after\n submitting your code through the JSLint tool.</p>\n</blockquote>\n\n<p>From Fyodorov \"bga\" Alexander:</p>\n\n<blockquote>\n <p>1) convert your code to </p>\n</blockquote>\n\n<pre><code> { const singletonObject = (function(){ \n // helper fns \n return { \n // privare members \n newsItems_: [], \n _init: function(){ \n // your object init here \n delete this._init // prevent double init \n return this \n }, \n // methods \n getFilters: function(){ \n } \n }._init() })() } \n</code></pre>\n\n<blockquote>\n <p>2) replace {!localStogare[foo]} to {localStogare[foo] != null}<br>\n 3) put 1 extra space after comma in fn ivoke code { _fn(a, b) }<br>\n 4) you have monster fn {createElement}. Too many args. Plz use cfg object. {createElement('div', {id: 'foo'})}<br>\n 5) you can forget about semicolon\n 6) try to use fn style in js maximally, not </p>\n</blockquote>\n\n<pre><code>{getElementsByClass('div', 'foo')}, { \n el.getElementsByTag('div')._map(function(v){ return \n v.getElementsByClass('foo') })._reduce(function(v1, v2){ return \n v1.concat(v2) }) }\n</code></pre>\n\n<blockquote>\n <p>7) use {localStogare.getItem}, not {localStogare[]}<br>\n 8) alloc vars in place where you use it. For example> in {getNewsItems} you alloc {found} in top, but must in 68 line<br>\n 9) you use direct DOM building using {document.createElement}, use > templates, its more readable and maintainable than set of {appendChild} and {createElement} ) \n 10) in lines 71 - 75 you have > {Array.prototype.indexOf}<br>\n 11) its good that you use rule 1 var = 1 line</p>\n</blockquote>\n\n<p>The full thread can be found <a href=\"http://groups.google.com/group/jsmentors/browse_thread/thread/cf8bdfa1398ea9a1\" rel=\"nofollow\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T20:42:17.240", "Id": "5203", "ParentId": "5068", "Score": "3" } } ]
{ "AcceptedAnswerId": "5203", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T19:41:24.013", "Id": "5068", "Score": "11", "Tags": [ "javascript", "html", "dom" ], "Title": "Application that creates a toolbar to show/hide elements on a page" }
5068
<p>I'd like to get some feedback on a PHP Database Abstraction Layer I've created. It's a little long, but there really wasn't a way to just post part of it. Here is the base <code>DBObject</code> class for MySQL:</p> <pre><code>&lt;?php /** * Description: The DBObject class is the generic database object. It is not to be used directly, but extended * by additional classes, each corresponding to a database table. This particular DBObject is for use with a * MySQL PDO driver. * Dependencies: A database connection script that uses the MySQL PDO extension * Requirements: PHP 5.2 or higher */ class DBObject { protected $alias = NULL; protected $boundValues = array(); protected $db; protected $fields = array(); protected $groupBy = NULL; protected $having = NULL; protected $joins = NULL; protected $limit = NULL; protected $numBoundValues = 0; protected $offset = NULL; protected $orderBy = NULL; protected $patterns = array(); protected $prefix; protected $selectList = NULL; protected $table; protected $tablePrefix = NULL; protected $unions = array(); protected $valueStorage = array(); protected $where = NULL; /** * @param object $db - The PDO database connection object * @param string $table - The name of the table * @param array $fields - The names of each field in the table * @param string $schema - The schema * @param $prefix - optional - A prefix for the table * @return The object for chaining */ function __construct(PDO $db, $table, array $fields, $schema, $prefix = NULL){ $this-&gt;db = $db; $this-&gt;prefix = $prefix; $this-&gt;tablePrefix = ($prefix) ? $prefix.$table : $table; $this-&gt;table = $table; foreach($fields as $key) { $this-&gt;fields[$key] = NULL; } return $this; } /** * @param string $key - The table column name to retrieve * @return mixed - The value of the key, if the key exists, FALSE otherwise */ function __get($key){ return (array_key_exists($key, $this-&gt;valueStorage)) ? $this-&gt;valueStorage[$key] : FALSE; } /** * @param string $key - The table column name to be assigned a value * @param $value - The value to assign to the key * @return boolean - TRUE if the key exists, FALSE otherwise */ function __set($key, $value){ if (array_key_exists($key, $this-&gt;fields)){ $this-&gt;valueStorage[$key] = $value; return TRUE; } else { return FALSE; } } /** * Adds a value to be bound on query execution * @param mixed $value - The value(s) to be bound * @return string - The named value placeholder */ protected function addBoundValue($value){ if (is_array($value)){ $valueNames = array(); foreach ($value as $val){ $this-&gt;numBoundValues += 1; $valueName = ':'.$this-&gt;numBoundValues; $this-&gt;boundValues[$valueName] = $val; $this-&gt;patterns[] = '#(\s'.$valueName.'[\s]?)#'; $valueNames[] = $valueName; } return $valueNames; } else { $this-&gt;numBoundValues += 1; $valueName = ':'.$this-&gt;numBoundValues; $this-&gt;boundValues[$valueName] = $value; $this-&gt;patterns[] = '#(\s'.$valueName.'[\s]?)#'; return $valueName; } } /** * Adds space separators to each bound value * @return array - The spaced bound values */ protected function getSpacedBoundValues(){ $boundValues = ' '.implode(' | ', $this-&gt;boundValues).' '; return explode('|', $boundValues); } /** * @param string $alias - Sets the alias for the main table. Optional for query build. * @return The object for chaining */ public function alias($alias) { $this-&gt;alias = $alias; return $this; } /** * @var array $selectList - Used for determining which database fields should be selected. Fields from joins may be included, * but must include either the full table name or alias as a prefix. * @return The object for chaining */ public function selectList(array $selectList) { foreach($selectList as $value) { $this-&gt;selectList[] = $value; } return $this; } /** * @param string $quotable - Escapes an input variable for use in an SQL query. Returns the escaped string. Optional for query build. * @return The escaped input */ public function quote($quotable) { return $this-&gt;db-&gt;quote($quotable); } /** * Joins will be added to the join array and processed in their array order and use the ON syntax * rather than USING. Optional for query build. * @param string $joinType -The type of join to be performed. Acceptable values are 'left', 'right', 'inner', and 'full' * @param string $table - The name of the table to be joined with the current table * @param string $column - The column(s) to be compared to the value * @param string $operator - The operator to be used in the comparison * @param string $value - The value to which $column is compared * @param string $tableAlias - optional - The alias of the joined table. If not set, alias defaults to the table name * @return The object for chaining */ public function addJoin($joinType, $table, $column, $operator, $value, $tableAlias=NULL){ $joinAlias = ($tableAlias) ? $tableAlias : $table; $joinName = ($this-&gt;prefix) ? $this-&gt;prefix.$table : $table; $expr = "$column $operator $value"; switch (strtolower($joinType)) { case "left": $this-&gt;joins[] = " LEFT JOIN $joinName AS $joinAlias ON $expr"; break; case "right": $this-&gt;joins[] = " RIGHT JOIN $joinName AS $joinAlias ON $expr"; break; case "inner": $this-&gt;joins[] = " INNER JOIN $joinName AS $joinAlias ON $expr"; break; case "full": $this-&gt;joins[] = " FULL JOIN $joinName AS $joinAlias ON $expr"; break; default: throw new Vm_Db_Exception("'$joinType' is not a supported join type."); } return $this; } /** * Creates a where clause. Optional for query build. * @param string $column - The column(s) to be compared to the value * @param string $operator - The operator to be used in the comparison. * @param mixed $value - The value to which $column is compared - If multiple values are entered as an array, they will be wrapped in parentheses, else use a string * @param string (optional) $antecedent - The operator preceding the WHERE clause. Acceptable values are 'AND' and 'OR' * @param string (optional) $paren - Adds a paren to the WHERE clause - 'open', 'close', 'both' * @param boolean $caseSensitive - optional - Whether or not the clause should be case sensitive, defaults TRUE. If FALSE, will use UTF8_GENERAL_CI * @param boolean $bind - optional - Whether or not $value should be a bound parameter, defaults TRUE. Use FALSE when $value is a subquery * @return The object for chaining */ public function where($column, $operator, $value, $antecedent=NULL, $paren=NULL, $caseSensitive = TRUE, $bind = TRUE){ $value = ($bind) ? $this-&gt;addBoundValue($value) : $value; $value = (is_array($value)) ? '( '.implode(', ', $value).')' : $value; $operator = ($caseSensitive) ? $operator : 'COLLATE UTF8_GENERAL_CI '.$operator; switch ($paren){ case 'open': $this-&gt;where[] = ($antecedent) ? " $antecedent ($column $operator $value" : " ($column $operator $value"; break; case 'close': $this-&gt;where[] = ($antecedent) ? " $antecedent $column $operator $value)" : " $column $operator $value)"; break; case 'both': $this-&gt;where[] = ($antecedent) ? " $antecedent ($column $operator $value)" : " ($column $operator $value)"; break; default: $this-&gt;where[] = ($antecedent) ? " $antecedent $column $operator $value" : " $column $operator $value"; } return $this; } /** * @param array $groupBy - The fields by which the result set should be grouped. Optional for query build. * @return The object for chaining */ public function groupBy(array $groupBy) { foreach($groupBy as $value) { $this-&gt;groupBy[] = $value; } return $this; } /** * Creates a HAVING clause. Optional for query build. MUST be used in conjunction with the GROUP BY clause * @param string $column - The column(s) to be compared to the value. Note: The column is not a bound parameter in this clause * @param string $operator - The operator to be used in the comparison * @param string $value - The value to which $column is compared * @param string $antecedent - optional - The operator preceding the HAVING clause. Acceptable values are 'AND' and 'OR' * @param string $function - optional - The SQL function to apply to the column * @return The object for chaining */ public function having($column, $operator, $value, $antecedent=NULL, $function=NULL) { $column = $this-&gt;addBoundValue($column); $column = ($function) ? "$function( $column)" : $column; $value = $this-&gt;addBoundValue($value); $this-&gt;having[] = ($antecedent) ? " $antecedent $column $operator $value" : "$column $operator $value"; return $this; } /** * Orders the query. Optional for query build * @param string $field - The field to sort by * @param string $sort (optional) - The sort type. Acceptable values are ASC and DESC * @param boolean $caseSensitive - optional - Whether or not the ordering should be case sensitive, defaults TRUE. If FALSE, will use UTF8_GENERAL_CI * @return The object for chaining */ public function orderBy($field, $sort=NULL, $caseSensitive=TRUE){ $sort = (strtolower($sort) == 'desc') ? 'DESC' : 'ASC'; $sort = ($caseSensitive) ? $sort : 'COLLATE UTF8_GENERAL_CI '.$sort; $this-&gt;orderBy[] = ' '.$field." $sort"; return $this; } /** * @param int $limit - The limit of the result set. Optional for query build. * @return The object for chaining */ public function limit($limit) { if (!is_int($limit)){ throw new Vm_Db_Exception('Limit must be an integer'); } $this-&gt;limit = ($limit != 0) ? $limit : NULL; return $this; } /** * @param int $offset - The offset of the result set. Optional for query build. * @return The object for chaining */ public function offset($offset) { if (!is_int($offset)){ throw new Vm_Db_Exception('Offset must be an integer'); } $this-&gt;offset = ($offset != 0) ? $offset : NULL; return $this; } /** * Clears all class variables by setting them to NULL, allow class instance reuse * @param boolean $clearBound - optional - Whether or not the bound variables should be cleared, defaults TRUE */ public function clear($clearBound = TRUE) { $this-&gt;valueStorage = NULL; $this-&gt;selectList = NULL; $this-&gt;alias = NULL; $this-&gt;joins = NULL; $this-&gt;where = NULL; $this-&gt;groupBy = NULL; $this-&gt;having = NULL; $this-&gt;orderBy = NULL; $this-&gt;limit = NULL; $this-&gt;offset = NULL; if ($clearBound){ $this-&gt;boundValues = NULL; $this-&gt;numBoundValues = 0; } } /** * Compiles the given data into a select query and returns a result set based on the query * @param string (optional) $mode - * If set to 'single', returns a single result set which may be accessed through magic methods. * * Example: $user-&gt;name or $user-&gt;{'name'} * * If set to 'assoc', will return the result set as an associative array, which can be accessed through * a foreach loop * * Example: foreach ($user-&gt;select("assoc") as $row) { * echo "ID = ".$row['userId']."\t"; * echo "Type = ".$row['firstName']."\t"; * echo "Parent = ".$row['lastName']."&lt;br&gt;"; * } * * If set to 'num', will return the result set as a numerical array * * If set to 'obj', will return an anonymous object with property names that correspond to the column * names returned in your result set * * If set to 'lazy', will return a combination of 'both' and 'obj', creating the object variable names * as they are accessed * * If set to 'subquery', will wrap the query in parentheses and return it for use in a subquery without executing it. * WARNING: Bound parameters are not used for subqueries * * If set to "count", will return the number of rows * * Example: $number = $user-&gt;select("count"); * * If set to "union", will add the query to the unions array. Note: you must reuse the object to use union. * * Example: * * $user = new Db_User($db); * * //First Query * $user-&gt;where('lastName', '=', 'Jones'); * $user-&gt;select('union'); * * //Second Query * $user-&gt;where('lastName', '=', 'Smith'); * $user-&gt;select('union'); * * //Get union results (orderBy and limit are optional) * $user-&gt;orderBy('lastName', 'ASC'); * $user-&gt;orderBy('firstName', 'ASC'); * $user-&gt;limit(25); * $users = $user-&gt;select('assoc'); * * If set to "debug", prints the compiled query * * Example: $user-&gt;select-&gt;("debug"); * * If left unset, the default return set is 'both', which returns the combination of both an associative array * and a numerical array * @param string $selectType - optional - 'DISTINCT' or 'ALL'. Note: $selectType is ignored for the first select query in a set of unions * @return mixed - The query result set */ public function select($mode=NULL, $selectType=NULL) { if ($selectType){ $type = ($selectType == 'ALL') ? ' ALL' : ' DISTINCT'; } else { $type = NULL; } $selectList = ($this-&gt;selectList) ? ' '.implode(', ', $this-&gt;selectList) : ' *'; $alias = ($this-&gt;alias) ? ' AS '.$this-&gt;alias : ' AS '.$this-&gt;table; $joins = ($this-&gt;joins) ? implode('', $this-&gt;joins) : NULL; $where = ($this-&gt;where) ? ' WHERE'.implode('', $this-&gt;where) : NULL; if (!$this-&gt;groupBy) { $groupBy = NULL; $having = NULL; } else { $groupBy = ' GROUP BY '.implode(', ', $this-&gt;groupBy); $having = ($this-&gt;having) ? ' HAVING '.implode('', $this-&gt;having) : NULL; } $orderBy = ($this-&gt;orderBy) ? ' ORDER BY '.implode(', ', $this-&gt;orderBy) : NULL; if ($this-&gt;limit) { $limit = ($this-&gt;offset) ? ' LIMIT '.$this-&gt;offset.', '.$this-&gt;limit : ' LIMIT '.$this-&gt;limit; } else { $limit = NULL; } if ((sizeof($this-&gt;unions) &gt; 0)&amp;&amp;($mode != 'union')){ $query = implode(' ', $this-&gt;unions)."$orderBy$limit"; } else { $query = "SELECT$type$selectList FROM ".$this-&gt;tablePrefix."$alias$joins$where$groupBy$having$orderBy$limit"; } $result = $this-&gt;db-&gt;prepare($query); if ((is_array($this-&gt;boundValues))&amp;&amp;(!in_array($mode, array('subquery', 'union')))){ foreach ($this-&gt;boundValues as $name=&gt;$value) { $result-&gt;bindValue($name, $value); } } if (strtolower($mode) == "debug") { return preg_replace($this-&gt;patterns, $this-&gt;getSpacedBoundValues(), $result-&gt;queryString, 1); } else if (strtolower($mode) == "subquery") { $this-&gt;clear(FALSE); return '('.$result-&gt;queryString.')'; } else if (strtolower($mode) == "union") { $this-&gt;clear(FALSE); $this-&gt;unions[] = (sizeof($this-&gt;unions) &gt;= 1) ? "UNION $selectType (".$result-&gt;queryString.')' : '('.$result-&gt;queryString.')'; } else { $result-&gt;execute(); switch (strtolower($mode)) { case "assoc": return $result-&gt;fetchAll(PDO::FETCH_ASSOC); case "count": return count($result-&gt;fetchAll()); case "num": return $result-&gt;fetchAll(PDO::FETCH_NUM); case "lazy": return $result-&gt;fetch(PDO::FETCH_LAZY); case "obj": return $result-&gt;fetchAll(PDO::FETCH_OBJ); case "single": $rows = $result-&gt;fetch(PDO::FETCH_ASSOC); if (is_array($rows)){ foreach(array_keys($rows) as $key) { $this-&gt;valueStorage[$key] = $rows[$key]; } } return $rows; default: return $result-&gt;fetchAll(PDO::FETCH_BOTH); } } } /** * The insert function inserts records into the database. Magic methods are used to insert * values into each field. Fields that are not assigned a value will not be included in the compiled query. * Example usage: * $users = new Db_Users($db); * $users-&gt;username = 'jDoe'; * $users-&gt;firstName = 'John'; * $users-&gt;{'lastName'} = 'Doe'; //An alternate syntax * $users-&gt;{'age'} = 37; * $users-&gt;insert(); * @param string $mode - optional - * If set to 'debug', returns the compiled SQL query * @return mixed - The last insert id if the query is successful, the compiled query if mode is set to debug, * FALSE otherwise. */ public function insert($mode=NULL) { $valueTypes = array('array'=&gt;FALSE, 'single'=&gt;FALSE); $arrayLength = 0; $fieldNames = array(); $values = array(); $params = array(); foreach ($this-&gt;valueStorage as $name=&gt;$value) { $fieldNames[] = $name; if (is_array($value)){ if (!$valueTypes['array']){ $valueTypes['array'] = TRUE; } if ($valueTypes['single']) { throw new Vm_Db_Exception('Insert values must be either arrays of the same length or a single value'); } $i = 0; foreach ($value as $inputValue){ $params[$i][] = '?'; $values[$i][] = $inputValue; $i++; } } else { if (!$valueTypes['single']){ $valueTypes['single'] = TRUE; } if ($valueTypes['array']) { throw new Vm_Db_Exception('Insert values must be either arrays of the same length or a single value'); } $params[0][] = '?'; $values[0][] = $value; } } $numInserts = 0; foreach ($params as $count=&gt;$value){ $params[$count] = '('.implode(',', $value).')'; $numInserts += 1; } $params = implode(',', $params); $numValues = sizeof($values[0]); $boundValues = array(); foreach ($values as $value){ if (sizeof($value) != $numValues){ throw new Vm_Db_Exception('Insert values must be either arrays of the same length or a single value'); } foreach ($value as $boundValue){ $boundValues[] = $boundValue; } } $query = 'INSERT INTO '.$this-&gt;tablePrefix.' ('.implode(',', $fieldNames).') VALUES '.$params; $result = $this-&gt;db-&gt;prepare($query); if (strtolower($mode) == 'debug') { $patterns = array(); foreach ($boundValues as $value){ $patterns[] = '#\?#'; } return preg_replace($patterns, $boundValues, $result-&gt;queryString, 1); } else { $i = 0; foreach ($boundValues as $value){ $boundValues[$i] = $boundValues[$i]; $result-&gt;bindValue(($i+1), $boundValues[$i]); $i++; } $result-&gt;execute(); return $this-&gt;db-&gt;lastInsertId() + $numInserts - 1; } } /** * Updates a database field with values obtained from magic methods representing the field names. * Notes: Multiple table updates are currently not supported, nor are ordering or limiting result sets due to * DBMS syntax inconsistencies * @param string $mode - optional - If set to 'debug', returns the compiled SQL query * @return int - The number of affected rows */ public function update($mode=NULL) { $fields = array(); $boundValues = array(); foreach (array_keys($this-&gt;valueStorage) as $field) { $fields[]= "$field="; } $parameters = implode("?, ", $fields).'?'; $i = 1; foreach (array_keys($this-&gt;valueStorage) as $field){ $boundValues[$i]= $this-&gt;valueStorage[$field]; $i++; } $where = ($this-&gt;where) ? ' WHERE'.implode('', $this-&gt;where) : NULL; $where = preg_replace('#(\s:[\w-]+[\s]?)#', ' ? ', $where); $boundValues = array_merge($boundValues, array_values($this-&gt;boundValues)); $boundValues = $boundValues; $query = "UPDATE ".$this-&gt;tablePrefix." SET $parameters$where"; $result = $this-&gt;db-&gt;prepare($query); if (strtolower($mode) == 'debug') { $patterns = array(); foreach ($boundValues as $value){ $patterns[] = '#\?#'; } return preg_replace($patterns, $boundValues, $result-&gt;queryString, 1); } else { $i = 0; foreach ($boundValues as $value){ $boundValues[$i] = $boundValues[$i]; $result-&gt;bindValue($i+1, $boundValues[$i]); $i++; } $result-&gt;execute(); return $result-&gt;rowCount(); } } /** * The delete function deletes all rows that meet the conditions specified in the where clause * and returns the number of affected rows * @param string $mode - optional - Acceptable value is 'debug', which prints the compiled query */ public function delete($mode=NULL) { $where = ($this-&gt;where) ? ' WHERE'.implode('', $this-&gt;where) : NULL; $query = 'DELETE FROM '.$this-&gt;tablePrefix.$where; $result = $this-&gt;db-&gt;prepare($query); if (strtolower($mode) == 'debug') { return preg_replace($this-&gt;patterns, $this-&gt;getSpacedBoundValues(), $result-&gt;queryString, 1); } else { foreach ($this-&gt;boundValues as $name=&gt;$value) { $result-&gt;bindValue($name, $value); } $result-&gt;execute(); return $result-&gt;rowCount(); } } /** * Description: Deletes all rows in the table, returns the number of affected rows. * @return int - The number of affected rows */ public function deleteAll(){ $result = $this-&gt;db-&gt;prepare('DELETE FROM '.$this-&gt;tablePrefix); $result-&gt;execute(); return $result-&gt;rowCount(); } } ?&gt; </code></pre> <p>The <code>DBObject</code> class is meant to be extended by additional classes, one for each table in the database. As an example, here are two for pages and comments:</p> <pre><code>&lt;?php class Db_Pages extends DBObject { function __construct($db, $prefix = NULL) { parent::__construct($db, 'pages', array('pageId', 'pageTitle', 'pageCreationDate', 'pageContent'), 'public', $prefix); } } ?&gt; </code></pre> <p>And:</p> <pre><code>&lt;?php class Db_Comments extends DBObject { function __construct($db, $prefix = NULL) { parent::__construct($db, 'comments', array('commentId', 'pageId', 'commentDate', 'comment'), 'public', $prefix); } } ?&gt; </code></pre> <p>The extending classes are the classes you would actually use in your code. Here's an example of how you would create a new page:</p> <pre><code>//$db = the PDO database connection $page = new Db_Pages($db); $page-&gt;pageTitle = 'Sample Page Title'; $page-&gt;pageContent = 'This is the content for the sample page'; $page-&gt;insert(); </code></pre> <p>Create multiple pages:</p> <pre><code>//$db = the PDO database connection $page = new Db_Pages($db); $page-&gt;pageTitle = array('Sample Page Title 1', 'Title 2', 'Title 3'); $page-&gt;pageContent = array('This is the content for the sample page', 'Content 2', 'Content 3'); $page-&gt;insert(); </code></pre> <p>Here is how you would access a single page:</p> <pre><code>//$db = the PDO database connection $page = new Db_Pages($db); $page-&gt;where('pageId', '=', 1); $page-&gt;select('single'); echo $page-&gt;pageTitle; echo $page-&gt;pageContent; </code></pre> <p>Or multiple pages:</p> <pre><code>//$db = the PDO database connection $page = new Db_Pages($db); $pages = $page-&gt;select('assoc'); foreach($pages as $page){ echo $page['pageTitle']; echo $page['pageContent']; } </code></pre> <p>Update a page:</p> <pre><code>//$db = the PDO database connection $page = new Db_Pages($db); $page-&gt;where('pageId', '=', 1); $page-&gt;pageTitle = 'New Page Title'; $page-&gt;update(); </code></pre> <p>Delete a page:</p> <pre><code>//$db = the PDO database connection $page = new Db_Pages($db); $page-&gt;where('pageId', '=', 1); $page-&gt;delete(); </code></pre> <p>Get comments for a page, sorted by date:</p> <pre><code>//$db = the PDO database connection $comments = new Db_Comments($db); $comments-&gt;alias('c'); $comments-&gt;selectList(array('c.commentDate', 'c.comment')); $comments-&gt;addJoin('left', 'pages', 'c.pageId', '=', 'p.pageId', 'p'); $comments-&gt;where('p.pageId', '=', 1); $comments-&gt;orderBy('c.commentDate', 'ASC'); $commentList = $comments-&gt;select('assoc'); foreach ($commentList as $comment){ echo $comment['commentDate']; echo $comment['comment']; } </code></pre> <p>If you prefer a less verbose syntax, you can also chain the clause functions together:</p> <pre><code>//$db = the PDO database connection $comments = new Db_Comments($db) -&gt;alias('c') -&gt;selectList(array('c.commentDate', 'c.comment')) -&gt;addJoin('left', 'pages', 'c.pageId', '=', 'p.pageId', 'p') -&gt;where('p.pageId', '=', 1) -&gt;orderBy('c.commentDate', 'ASC'); $commentList = $comments-&gt;select('assoc'); foreach ($commentList as $comment){ echo $comment['commentDate']; echo $comment['comment']; } </code></pre> <p>If you want to debug your SQL statement:</p> <pre><code>//$db = the PDO database connection $page = new Db_Pages($db); $page-&gt;where('pageId', '=', 1); echo $page-&gt;select('debug'); //Prints: SELECT * FROM 'pages' WHERE 'pageId' = 1 </code></pre> <p>The DB class can also handle <code>LIMIT</code>, <code>GROUPBY</code>, Offset &amp; <code>HAVING</code> clauses, subqueries, other types of <code>join</code>s, and <code>union</code>s. It uses PDO and all inputs are bound parameters automatically. </p> <p>The <code>DBObject</code> above is for MySQL only, but I am creating other <code>DBObject</code> classes for other DB types as well, with the idea of being able to substitute one DB type for another without have to change any of the application code (just load the <code>DBObject</code> for that DB type).</p> <p>All of the extending DB classes like <code>Db_Pages</code> and <code>Db_Comments</code> can be generated automatically. I have a separate class for database operations like creating or editing new tables, etc. that functions in a similar manner as <code>DBObject</code>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T02:09:03.757", "Id": "7594", "Score": "0", "body": "Well, what benefit does this have over the major ORM systems (Or PEAR DB_Object if we want something closer to your implementation)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T04:43:12.157", "Id": "7600", "Score": "0", "body": "Pear DB_DataObject is for PHP 4 and this is PHP 5+. This uses PDO, so all the parameters are bound and injection-safe. Also, it will allow your application to support multiple database types without requiring a rewrite of your code. Just swap the MySQL DB_Object out with whatever database type you want to use. I'd like to think using it is pretty easy as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T10:47:55.770", "Id": "7637", "Score": "0", "body": "As PDO is OOPlicious itself, did you consider extending the PDO classes instead of creating your own base class? I think it would save you some effort, and also make it possible for users of the class to fall back to PDO's methods if doing so would make certain tasks easier than using your class's." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T17:23:00.710", "Id": "7641", "Score": "0", "body": "@GarrettAlbright - I did consider that, but chose to pass it in through the constructor instead. Users can still access it that way if they need to, but if PDO was extended, I would have had to connect to the database each time a query was executed. This way, I connect once and just pass that connection in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T09:17:14.453", "Id": "7673", "Score": "1", "body": "What is the license for your code? Did you intend to release it in an Open Source license MIT or BSD like?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-19T01:52:48.337", "Id": "9516", "Score": "0", "body": "Something that'd make me want to use it is if you implemented validation. The best solution I can think of is allowing the user to add a method like `(bool) validationPageId($string)` to `class Db_Pages extends DBObject`, which would then automatically be called and generate an error/throw an exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-19T02:21:32.080", "Id": "9517", "Score": "0", "body": "@KristianAntonsen - Thanks for the suggestion. It's an interesting idea, but I think I'd prefer to keep the validation separate. However, you could implement an ActiveRecord-type of layer on top of the Db_Pages class (`class Pages extends Db_Pages` or Pages could simply use Db_Pages rather than extending it). Pages would have methods like newPage($id, $title, $content), getPage($id), deletePage($id), etc. That would be a great place to handle validation and exceptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-19T14:00:50.267", "Id": "9520", "Score": "0", "body": "Yeah, your suggestion is better. I just hate having to handle validation at all. It'd be great if it'd all be taken care of without you really noticed it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-19T21:21:27.800", "Id": "9521", "Score": "0", "body": "@KristianAntonsen - That would definitely be cool, but it would be extremely difficult to pull off as no two databases are exactly the same. I really don't know where I would begin to try to abstract something like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-09T07:58:09.240", "Id": "175970", "Score": "0", "body": "excuse me but can your pdo support the usage of IN? i tried, but it returns as uncaught exception error.\n//$dt range is a string variable holding value such as ('2012-01-01','2011-01-01') `$test->where('date','IN',$dtrange);\n$test->where('Used','=','Yes','AND');\n$test->orderBy('date');\n$tests=$test->select('assoc');`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-07-10T08:23:36.543", "Id": "176239", "Score": "0", "body": "@MrGan - Try making $dtrange an array with the values you listed without the parentheses. `$test->where('date','IN',array('2012-01-01','2011-01-01'));`" } ]
[ { "body": "<p>Ok, it's a huge work, so, I'll try to do this by iteration, adding then when I've a little time.</p>\n\n<p>I'll start with the form.</p>\n\n<p><strong>Iteration 1</strong><br>\n<em>Readability:</em></p>\n\n<p>Thereafter is the code with some improvements about it's readability.</p>\n\n<p>I've limited the width to 78 columns, use 2 spaces soft tabs instead of 4, add a line feed (and indentation) before <code>{</code>, etc.</p>\n\n<p>IMHO, 2 spaces soft tab make easier the target of 78 columns, so I prefer it to the conventional 4 spaces soft tab.</p>\n\n<p>I like to target 78 columns because the target is generally 80. But some repositories with very strict commitment rules can block you when they considers a <code>lf</code> like a character, or a <code>crlf</code> like two.</p>\n\n<p>As you can see, it also bring the advantage to not have an horizontal slider here.</p>\n\n<p>One important thing: I've deleted the <code>?&gt;</code> at the end of the file, for the same reasons as those of the <a href=\"http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html\" rel=\"nofollow\">Zend Framework PHP File Formatting convention</a>:</p>\n\n<blockquote>\n <p>For files that contain only PHP code, the closing tag (\"?>\") is never permitted. It is not required by PHP, and omitting it´ prevents the accidental injection of trailing white space into the response.</p>\n</blockquote>\n\n<p>It's just my vision of a more readable code, and it will help me for further iteration if I found some time for it...</p>\n\n<pre><code>&lt;?php\n/**\n * Description: The DBObject class is the generic database object. It is not\n * to be used directly, but extended by additional classes, each\n * corresponding to a database table. This particular DBObject is for use\n * with a MySQL PDO driver.\n * Dependencies: A database connection script that uses the MySQL PDO\n * extension\n * Requirements: PHP 5.2 or higher\n */\nclass DBObject {\n\n protected $alias = NULL;\n protected $boundValues = array();\n protected $db;\n protected $fields = array();\n protected $groupBy = NULL;\n protected $having = NULL;\n protected $joins = NULL; \n protected $limit = NULL;\n protected $numBoundValues = 0;\n protected $offset = NULL;\n protected $orderBy = NULL;\n protected $patterns = array();\n protected $prefix; \n protected $selectList = NULL;\n protected $table;\n protected $tablePrefix = NULL;\n protected $unions = array();\n protected $valueStorage = array();\n protected $where = NULL;\n\n /**\n * @param object $db - The PDO database connection object\n * @param string $table - The name of the table\n * @param array $fields - The names of each field in the table\n * @param string $schema - The schema\n * @param $prefix - optional - A prefix for the table\n * @return The object for chaining \n */\n function __construct(\n PDO $db,\n $table,\n array $fields,\n $schema,\n $prefix = NULL)\n {\n $this-&gt;db = $db;\n $this-&gt;prefix = $prefix;\n $this-&gt;tablePrefix = ($prefix) ? $prefix.$table : $table;\n $this-&gt;table = $table; \n foreach($fields as $key)\n {\n $this-&gt;fields[$key] = NULL;\n }\n return $this;\n }\n\n /**\n * @param string $key - The table column name to retrieve \n * @return mixed - The value of the key, if the key exists, FALSE otherwise\n */\n function __get($key)\n {\n return (array_key_exists($key, $this-&gt;valueStorage)) ?\n $this-&gt;valueStorage[$key] : FALSE; \n }\n\n /**\n * @param string $key - The table column name to be assigned a value\n * @param $value - The value to assign to the key\n * @return boolean - TRUE if the key exists, FALSE otherwise\n */\n function __set($key, $value){\n if (array_key_exists($key, $this-&gt;fields))\n {\n $this-&gt;valueStorage[$key] = $value;\n return TRUE;\n }\n else\n {\n return FALSE;\n }\n }\n\n /**\n * Adds a value to be bound on query execution\n * @param mixed $value - The value(s) to be bound\n * @return string - The named value placeholder\n */\n protected function addBoundValue($value)\n {\n if (is_array($value))\n {\n $valueNames = array();\n foreach ($value as $val)\n {\n $this-&gt;numBoundValues += 1;\n $valueName = ':'.$this-&gt;numBoundValues;\n $this-&gt;boundValues[$valueName] = $val;\n $this-&gt;patterns[] = '#(\\s'.$valueName.'[\\s]?)#';\n $valueNames[] = $valueName;\n }\n return $valueNames; \n }\n else\n {\n $this-&gt;numBoundValues += 1;\n $valueName = ':'.$this-&gt;numBoundValues;\n $this-&gt;boundValues[$valueName] = $value;\n $this-&gt;patterns[] = '#(\\s'.$valueName.'[\\s]?)#';\n return $valueName;\n }\n }\n\n /**\n * Adds space separators to each bound value\n * @return array - The spaced bound values\n */\n protected function getSpacedBoundValues()\n {\n $boundValues = ' '.implode(' | ', $this-&gt;boundValues).' ';\n return explode('|', $boundValues);\n }\n\n /**\n * @param string $alias - Sets the alias for the main table. Optional for\n * query build.\n * @return The object for chaining \n */\n public function alias($alias)\n {\n $this-&gt;alias = $alias;\n return $this;\n } \n\n /**\n * @var array $selectList - Used for determining which database fields\n * should be selected. Fields from joins may be included, but must include\n * either the full table name or alias as a prefix. \n * @return The object for chaining\n */\n public function selectList(array $selectList)\n {\n foreach($selectList as $value)\n {\n $this-&gt;selectList[] = $value;\n }\n return $this;\n }\n\n /**\n * @param string $quotable - Escapes an input variable for use in an SQL\n * query. Returns the escaped string. Optional for query build.\n * @return The escaped input\n */\n public function quote($quotable)\n {\n return $this-&gt;db-&gt;quote($quotable);\n }\n\n /**\n * Joins will be added to the join array and processed in their array order\n * and use the ON syntax rather than USING. Optional for query build.\n * @param string $joinType - The type of join to be performed. Acceptable\n * values are 'left', 'right', 'inner', and 'full'\n * @param string $table - The name of the table to be joined with the\n * current table\n * @param string $column - The column(s) to be compared to the value\n * @param string $operator - The operator to be used in the comparison\n * @param string $value - The value to which $column is compared\n * @param string $tableAlias - optional - The alias of the joined table. If\n * not set, alias defaults to the table name\n * @return The object for chaining\n */\n public function addJoin(\n $joinType,\n $table,\n $column,\n $operator,\n $value,\n $tableAlias=NULL)\n {\n $joinAlias = ($tableAlias) ? $tableAlias : $table;\n $joinName = ($this-&gt;prefix) ? $this-&gt;prefix.$table : $table;\n $expr = \"$column $operator $value\"; \n switch (strtolower($joinType)) {\n case \"left\":\n $this-&gt;joins[] = \" LEFT JOIN $joinName AS $joinAlias ON $expr\";\n break;\n case \"right\":\n $this-&gt;joins[] = \" RIGHT JOIN $joinName AS $joinAlias ON $expr\";\n break; \n case \"inner\":\n $this-&gt;joins[] = \" INNER JOIN $joinName AS $joinAlias ON $expr\";\n break;\n case \"full\":\n $this-&gt;joins[] = \" FULL JOIN $joinName AS $joinAlias ON $expr\";\n break;\n default:\n throw new Vm_Db_Exception(\n \"'$joinType' is not a supported join type.\");\n }\n return $this;\n }\n\n /**\n * Creates a where clause. Optional for query build.\n * @param string $column - The column(s) to be compared to the value\n * @param string $operator - The operator to be used in the comparison. \n * @param mixed $value - The value to which $column is compared - If\n * multiple values are entered as an array, they will be wrapped in\n * parentheses, else use a string\n * @param string (optional) $antecedent - The operator preceding the WHERE\n * clause. Acceptable values are 'AND' and 'OR' \n * @param string (optional) $paren - Adds a paren to the WHERE clause -\n * 'open', 'close', 'both'\n * @param boolean $caseSensitive - optional - Whether or not the clause\n * should be case sensitive, defaults TRUE. If FALSE, will use\n * UTF8_GENERAL_CI\n * @param boolean $bind - optional - Whether or not $value should be a\n * bound parameter, defaults TRUE. Use FALSE when $value is a subquery\n * @return The object for chaining\n */\n public function where(\n $column,\n $operator,\n $value,\n $antecedent = NULL,\n $paren = NULL,\n $caseSensitive = TRUE,\n $bind = TRUE)\n {\n $value = ($bind) ? $this-&gt;addBoundValue($value) : $value;\n $value = (is_array($value)) ? '( '.implode(', ', $value).')' : $value;\n $operator =\n ($caseSensitive) ? $operator : 'COLLATE UTF8_GENERAL_CI '.$operator;\n switch ($paren){\n case 'open':\n $this-&gt;where[] = ($antecedent) ?\n \" $antecedent ($column $operator $value\"\n : \" ($column $operator $value\";\n break;\n case 'close':\n $this-&gt;where[] = ($antecedent) ?\n \" $antecedent $column $operator $value)\"\n : \" $column $operator $value)\";\n break;\n case 'both':\n $this-&gt;where[] = ($antecedent) ?\n \" $antecedent ($column $operator $value)\"\n : \" ($column $operator $value)\";\n break; \n default:\n $this-&gt;where[] = ($antecedent) ?\n \" $antecedent $column $operator $value\"\n : \" $column $operator $value\"; \n }\n return $this; \n }\n\n /**\n * @param array $groupBy - The fields by which the result set should be\n * grouped. Optional for query build.\n * @return The object for chaining\n */\n public function groupBy(array $groupBy)\n {\n foreach($groupBy as $value)\n {\n $this-&gt;groupBy[] = $value;\n }\n return $this;\n }\n\n /**\n * Creates a HAVING clause. Optional for query build. MUST be used in\n * conjunction with the GROUP BY clause\n * @param string $column - The column(s) to be compared to the value. Note:\n * The column is not a bound parameter in this clause\n * @param string $operator - The operator to be used in the comparison\n * @param string $value - The value to which $column is compared\n * @param string $antecedent - optional - The operator preceding the HAVING\n * clause. Acceptable values are 'AND' and 'OR'\n * @param string $function - optional - The SQL function to apply to the\n * column\n * @return The object for chaining \n */\n public function having(\n $column,\n $operator,\n $value,\n $antecedent = NULL,\n $function = NULL)\n {\n $column = $this-&gt;addBoundValue($column);\n $column = ($function) ? \"$function( $column)\" : $column;\n $value = $this-&gt;addBoundValue($value);\n $this-&gt;having[] = ($antecedent) ?\n \" $antecedent $column $operator $value\" : \"$column $operator $value\";\n return $this;\n }\n\n /**\n * Orders the query. Optional for query build\n * @param string $field - The field to sort by\n * @param string $sort (optional) - The sort type. Acceptable values are\n * ASC and DESC\n * @param boolean $caseSensitive - optional - Whether or not the ordering\n * should be case sensitive, defaults TRUE. If FALSE, will use\n * UTF8_GENERAL_CI\n * @return The object for chaining\n */\n public function orderBy($field, $sort = NULL, $caseSensitive = TRUE)\n {\n $sort = (strtolower($sort) == 'desc') ? 'DESC' : 'ASC';\n $sort = ($caseSensitive) ? $sort : 'COLLATE UTF8_GENERAL_CI '.$sort;\n $this-&gt;orderBy[] = ' '.$field.\" $sort\";\n return $this;\n }\n\n /**\n * @param int $limit - The limit of the result set. Optional for query\n * build.\n * @return The object for chaining\n */\n public function limit($limit)\n {\n if (!is_int($limit))\n {\n throw new Vm_Db_Exception('Limit must be an integer');\n }\n $this-&gt;limit = ($limit != 0) ? $limit : NULL;\n return $this;\n }\n\n /**\n * @param int $offset - The offset of the result set. Optional for query\n * build.\n * @return The object for chaining\n */\n public function offset($offset)\n {\n if (!is_int($offset))\n {\n throw new Vm_Db_Exception('Offset must be an integer');\n }\n $this-&gt;offset = ($offset != 0) ? $offset : NULL;\n return $this;\n }\n\n /**\n * Clears all class variables by setting them to NULL, allow class instance\n * reuse\n * @param boolean $clearBound - optional - Whether or not the bound\n * variables should be cleared, defaults TRUE\n */\n public function clear($clearBound = TRUE)\n {\n $this-&gt;valueStorage = NULL;\n $this-&gt;selectList = NULL;\n $this-&gt;alias = NULL;\n $this-&gt;joins = NULL;\n $this-&gt;where = NULL;\n $this-&gt;groupBy = NULL; \n $this-&gt;having = NULL; \n $this-&gt;orderBy = NULL;\n $this-&gt;limit = NULL;\n $this-&gt;offset = NULL;\n if ($clearBound)\n {\n $this-&gt;boundValues = NULL;\n $this-&gt;numBoundValues = 0;\n }\n } \n\n /**\n * Compiles the given data into a select query and returns a result set\n * based on the query\n * @param string (optional) $mode - \n * If set to 'single', returns a single result set which may be accessed\n * through magic methods.\n * \n * Example: $user-&gt;name or $user-&gt;{'name'} \n *\n * If set to 'assoc', will return the result set as an associative array,\n * which can be accessed through a foreach loop\n *\n * Example: foreach ($user-&gt;select(\"assoc\") as $row)\n * {\n * echo \"ID = \".$row['userId'].\"\\t\";\n * echo \"Type = \".$row['firstName'].\"\\t\";\n * echo \"Parent = \".$row['lastName'].\"&lt;br&gt;\";\n * }\n *\n * If set to 'num', will return the result set as a numerical array\n *\n * If set to 'obj', will return an anonymous object with property names\n * that correspond to the column names returned in your result set\n *\n * If set to 'lazy', will return a combination of 'both' and 'obj',\n * creating the object variable names as they are accessed\n *\n * If set to 'subquery', will wrap the query in parantheses and return it\n * for use in a subquery without executing it.\n * WARNING: Bound parameters are not used for subqueries \n *\n * If set to \"count\", will return the number of rows\n *\n * Example: $number = $user-&gt;select(\"count\");\n *\n * If set to \"union\", will add the query to the unions array. Note: you\n * must reuse the object to use union.\n * \n * Example:\n * \n * $user = new Db_User($db);\n * \n * //First Query\n * $user-&gt;where('lastName', '=', 'Jones');\n * $user-&gt;select('union');\n * \n * //Second Query\n * $user-&gt;where('lastName', '=', 'Smith');\n * $user-&gt;select('union');\n * \n * //Get union results (orderBy and limit are optional)\n * $user-&gt;orderBy('lastName', 'ASC');\n * $user-&gt;orderBy('firstName', 'ASC');\n * $user-&gt;limit(25);\n * $users = $user-&gt;select('assoc');\n *\n * If set to \"debug\", prints the compiled query\n *\n * Example: $user-&gt;select-&gt;(\"debug\"); \n *\n * If left unset, the default return set is 'both', which returns the\n * combination of both an associative array\n * and a numerical array\n * @param string $selectType - optional - 'DISTINCT' or 'ALL'. Note:\n * $selectType is ignored for the first select query in a set of unions\n * @return mixed - The query result set\n */\n public function select($mode=NULL, $selectType=NULL)\n {\n if ($selectType)\n {\n $type = ($selectType == 'ALL') ? ' ALL' : ' DISTINCT';\n }\n else\n {\n $type = NULL;\n }\n\n $selectList = ($this-&gt;selectList) ?\n ' '.implode(', ', $this-&gt;selectList) : ' *';\n $alias = ($this-&gt;alias) ? ' AS '.$this-&gt;alias : ' AS '.$this-&gt;table; \n $joins = ($this-&gt;joins) ? implode('', $this-&gt;joins) : NULL;\n $where = ($this-&gt;where) ? ' WHERE'.implode('', $this-&gt;where) : NULL;\n\n if (!$this-&gt;groupBy)\n {\n $groupBy = NULL;\n $having = NULL; \n }\n else\n {\n $groupBy = ' GROUP BY '.implode(', ', $this-&gt;groupBy);\n $having = ($this-&gt;having) ?\n ' HAVING '.implode('', $this-&gt;having) : NULL;\n }\n\n $orderBy = ($this-&gt;orderBy) ?\n ' ORDER BY '.implode(', ', $this-&gt;orderBy) : NULL;\n\n if ($this-&gt;limit)\n {\n $limit = ($this-&gt;offset) ?\n ' LIMIT '.$this-&gt;offset.', '.$this-&gt;limit\n : ' LIMIT '.$this-&gt;limit;\n }\n else\n {\n $limit = NULL;\n }\n\n if ((sizeof($this-&gt;unions) &gt; 0) &amp;&amp; ($mode != 'union'))\n {\n $query = implode(' ', $this-&gt;unions).\"$orderBy$limit\";\n }\n else\n {\n $query = \"SELECT$type$selectList FROM \"\n .$this-&gt;tablePrefix\n .\"$alias$joins$where$groupBy$having$orderBy$limit\";\n }\n $result = $this-&gt;db-&gt;prepare($query);\n\n if ((is_array($this-&gt;boundValues))\n &amp;&amp;(!in_array($mode, array('subquery', 'union'))))\n {\n foreach ($this-&gt;boundValues as $name =&gt; $value)\n {\n $result-&gt;bindValue($name, $value);\n }\n }\n\n if (strtolower($mode) == \"debug\")\n {\n return preg_replace(\n $this-&gt;patterns, $this-&gt;getSpacedBoundValues(),\n $result-&gt;queryString, 1);\n }\n else if(strtolower($mode) == \"subquery\")\n {\n $this-&gt;clear(FALSE);\n return '('.$result-&gt;queryString.')';\n }\n else if (strtolower($mode) == \"union\")\n {\n $this-&gt;clear(FALSE);\n $this-&gt;unions[] = (sizeof($this-&gt;unions) &gt;= 1) ?\n \"UNION $selectType (\".$result-&gt;queryString.')'\n : '('.$result-&gt;queryString.')'; \n }\n else\n {\n $result-&gt;execute();\n switch (strtolower($mode)) {\n case \"assoc\":\n return $result-&gt;fetchAll(PDO::FETCH_ASSOC);\n case \"count\":\n return count($result-&gt;fetchAll());\n case \"num\":\n return $result-&gt;fetchAll(PDO::FETCH_NUM);\n case \"lazy\":\n return $result-&gt;fetch(PDO::FETCH_LAZY);\n case \"obj\":\n return $result-&gt;fetchAll(PDO::FETCH_OBJ);\n case \"single\":\n $rows = $result-&gt;fetch(PDO::FETCH_ASSOC);\n if (is_array($rows))\n {\n foreach(array_keys($rows) as $key)\n {\n $this-&gt;valueStorage[$key] = $rows[$key];\n }\n }\n return $rows; \n default:\n return $result-&gt;fetchAll(PDO::FETCH_BOTH); \n }\n }\n } \n\n /**\n * The insert function inserts records into the database. Magic methods are\n * used to insert values into each field. Fields that are not assigned a\n * value will not be included in the compiled query.\n * Example usage: \n * $users = new Db_Users($db);\n * $users-&gt;username = 'jDoe';\n * $users-&gt;firstName = 'John';\n * $users-&gt;{'lastName'} = 'Doe'; //An alternate syntax\n * $users-&gt;{'age'} = 37;\n * $users-&gt;insert();\n * @param string $mode - optional - \n * If set to 'debug', returns the compiled SQL query \n * @return mixed - The last insert id if the query is successful, the\n * compiled query if mode is set to debug, \n * FALSE otherwise.\n */\n public function insert($mode=NULL)\n {\n $valueTypes = array('array'=&gt;FALSE, 'single'=&gt;FALSE);\n $arrayLength = 0;\n $fieldNames = array();\n $values = array();\n $params = array();\n\n foreach ($this-&gt;valueStorage as $name =&gt; $value)\n {\n $fieldNames[] = $name;\n if (is_array($value))\n {\n if (!$valueTypes['array'])\n {\n $valueTypes['array'] = TRUE;\n }\n if ($valueTypes['single'])\n {\n throw new Vm_Db_Exception(\n 'Insert values must be either arrays '\n .'of the same length or a single value');\n } \n $i = 0;\n foreach ($value as $inputValue)\n {\n $params[$i][] = '?';\n $values[$i][] = $inputValue;\n $i++;\n }\n }\n else\n {\n if (!$valueTypes['single']){\n $valueTypes['single'] = TRUE;\n }\n if ($valueTypes['array']) {\n throw new Vm_Db_Exception(\n 'Insert values must be either arrays of the same length or a '\n .'single value');\n }\n $params[0][] = '?';\n $values[0][] = $value;\n }\n }\n $numInserts = 0;\n foreach ($params as $count=&gt;$value)\n {\n $params[$count] = '('.implode(',', $value).')';\n $numInserts += 1;\n }\n $params = implode(',', $params);\n\n $numValues = sizeof($values[0]);\n $boundValues = array();\n foreach ($values as $value)\n {\n if (sizeof($value) != $numValues)\n {\n throw new Vm_Db_Exception(\n 'Insert values must be either arrays of the same length or a'\n .'single value');\n }\n foreach ($value as $boundValue)\n {\n $boundValues[] = $boundValue;\n }\n }\n\n $query = \n 'INSERT INTO '\n .$this-&gt;tablePrefix\n .' ('\n .implode(',', $fieldNames)\n .') VALUES '\n .$params;\n\n $result = $this-&gt;db-&gt;prepare($query);\n\n if (strtolower($mode) == 'debug')\n {\n $patterns = array();\n foreach ($boundValues as $value)\n {\n $patterns[] = '#\\?#';\n }\n return preg_replace($patterns, $boundValues, $result-&gt;queryString, 1);\n }\n else\n {\n $i = 0;\n foreach ($boundValues as $value)\n {\n $boundValues[$i] = $boundValues[$i];\n $result-&gt;bindValue(($i+1), $boundValues[$i]);\n $i++;\n }\n $result-&gt;execute();\n return $this-&gt;db-&gt;lastInsertId() + $numInserts - 1;\n }\n } \n\n /**\n * Updates a database field with values obtained from magic methods\n * representing the field names. \n * Notes: Multiple table updates are currently not supported, nor are\n * ordering or limiting result sets due to DBMS syntax inconsistencies\n * @param string $mode - optional - If set to 'debug', returns the compiled\n * SQL query\n * @return int - The number of affected rows \n */\n public function update($mode = NULL)\n {\n $fields = array();\n $boundValues = array();\n\n foreach (array_keys($this-&gt;valueStorage) as $field)\n {\n $fields[]= \"$field=\";\n }\n $parameters = implode(\"?, \", $fields).'?';\n\n $i = 1;\n foreach (array_keys($this-&gt;valueStorage) as $field)\n {\n $boundValues[$i]= $this-&gt;valueStorage[$field];\n $i++;\n }\n\n $where = ($this-&gt;where) ? ' WHERE'.implode('', $this-&gt;where) : NULL;\n $where = preg_replace('#(\\s:[\\w-]+[\\s]?)#', ' ? ', $where);\n $boundValues =\n array_merge($boundValues, array_values($this-&gt;boundValues));\n $boundValues = $boundValues;\n\n $query = \"UPDATE \".$this-&gt;tablePrefix.\" SET $parameters$where\";\n $result = $this-&gt;db-&gt;prepare($query);\n\n if (strtolower($mode) == 'debug')\n {\n $patterns = array();\n foreach ($boundValues as $value)\n {\n $patterns[] = '#\\?#';\n }\n return preg_replace($patterns, $boundValues, $result-&gt;queryString, 1);\n }\n else\n {\n $i = 0;\n foreach ($boundValues as $value)\n {\n $boundValues[$i] = $boundValues[$i];\n $result-&gt;bindValue($i+1, $boundValues[$i]);\n $i++;\n }\n $result-&gt;execute();\n return $result-&gt;rowCount();\n }\n } \n\n /**\n * The delete function deletes all rows that meet the conditions specified\n * in the where clause and returns the number of affected rows\n * @param string $mode - optional - Acceptable value is 'debug', which\n * prints the compiled query\n */\n public function delete($mode = NULL)\n {\n $where = ($this-&gt;where) ? ' WHERE'.implode('', $this-&gt;where) : NULL;\n $query = 'DELETE FROM '.$this-&gt;tablePrefix.$where;\n $result = $this-&gt;db-&gt;prepare($query);\n\n if (strtolower($mode) == 'debug') \n {\n return preg_replace(\n $this-&gt;patterns,\n $this-&gt;getSpacedBoundValues(),\n $result-&gt;queryString,\n 1);\n }\n else\n {\n foreach ($this-&gt;boundValues as $name=&gt;$value)\n {\n $result-&gt;bindValue($name, $value);\n }\n $result-&gt;execute();\n return $result-&gt;rowCount();\n }\n }\n\n /**\n * Description: Deletes all rows in the table, returns the number of\n * affected rows.\n * @return int - The number of affected rows\n */\n public function deleteAll()\n {\n $result = $this-&gt;db-&gt;prepare('DELETE FROM '.$this-&gt;tablePrefix);\n $result-&gt;execute();\n return $result-&gt;rowCount();\n } \n}\n</code></pre>\n\n<p>Maybe more to come...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T18:33:21.623", "Id": "7777", "Score": "0", "body": "Thanks for the answer, G. Qyy. The closing tag suggestion is useful, but I was hoping for a little different feedback than reformatting my code to a different style. If you could, would you please take a look at the last paragraph of what I wrote and perhaps address some of those questions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T18:22:46.173", "Id": "7966", "Score": "0", "body": "Excuse me, I don't have a lot of time, and I can't afford to affect a lot of time if I don't know the licence of your code. If it's non-viral open source, it can really interest me, but if it's not..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T10:36:08.160", "Id": "5135", "ParentId": "5071", "Score": "6" } }, { "body": "<p>This is a pretty ambitious chunk of code, but it looks pretty well done. </p>\n\n<p>I like your variable names, the are nice and expressive. Too many developers these days seem to take variable naming for granted.</p>\n\n<p>One thing I'd suggest is to make the users of your API think even less. I'd create a few convenience methods for different types of joins like so:</p>\n\n<pre><code>addLeftJoin($table, $column, $operator, $value, $tableAlias=NULL){\n return addJoin(\"left\", $table, $column, $operator, $value, $tableAlias=NULL);\n}\n\naddRightJoin($table, $column, $operator, $value, $tableAlias=NULL){\n ...\n}\n\naddInnerJoin($table, $column, $operator, $value, $tableAlias=NULL){\n ...\n}\n\naddFullJoin($table, $column, $operator, $value, $tableAlias=NULL){\n ...\n}\n</code></pre>\n\n<p>If you do this you could even hide the implementation if your addJoin which will give you more felxability to change it in the future, as long as your convenience method's dont change their signatures none of the users of your API see a differenece. </p>\n\n<p>Looks like you are doing some good error checking in most places, but I do see a possible place for an error in your \"where\" and \"having\" functions, it looks like somebody can pass in an any string as an operator that would make the query crash. </p>\n\n<pre><code>//$db = the PDO database connection\n$page = new Db_Pages($db);\n$page-&gt;where('pageId', 'foo', 1); //crash\n</code></pre>\n\n<p>You might also want to consider checking the column array when somebody adds a column to the groupby function to make sure that the sql is valid.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T04:26:08.323", "Id": "7927", "Score": "0", "body": "Thanks, Ryan. This was the kind of answer I was hoping for and your suggestions are very useful." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T21:19:07.243", "Id": "5240", "ParentId": "5071", "Score": "5" } }, { "body": "<p>This code seemed pretty completed, tried using it on a small project. Then it hit me, there is no way for you to insert or select nulls properly. This has to be done with a specific bind param with PDO, example change in select method:</p>\n\n<p>replace:</p>\n\n<pre><code> $result-&gt;bindValue($name, $value\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>if($value === null)\n $result-&gt;bindValue($name, null, PDO::PARAM_NULL);\nelse\n $result-&gt;bindValue($name, $value);\n</code></pre>\n\n<p>Another thing that I had to change was the requirement of the first constructor param to be PDO. Better to check if $db is PDO OR subclassed PDO with is_subclass_of() .</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-20T21:47:44.413", "Id": "9543", "Score": "0", "body": "+1 on the NULL parameter binding, I'm not sure how I missed that. Could you expand on the PDO subclass comment? I'm curious as to what subclasses you would use as I just basically create a connection and pass it in." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-20T20:56:20.767", "Id": "6172", "ParentId": "5071", "Score": "5" } } ]
{ "AcceptedAnswerId": "5240", "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-29T20:17:29.623", "Id": "5071", "Score": "12", "Tags": [ "php", "security", "pdo" ], "Title": "PHP PDO Database Abstraction Layer" }
5071
<p>I am trying to make a generic form parser for Javascript. The idea being, a developer could drop the function onto a form and sumbit via AJAX, or do something with a form besides submit it. The result will be in the same format used in a query string.</p> <p>What I have posted works, so I am basically wondering if this is a good design? What could be improved? Thanks for the help!</p> <pre><code>function test_submit(id){ var results=[],form=document.getElementById(id); for(var i=0;i&lt;form.elements.length;++i){ var obj=form.elements[i]; if(obj.name&amp;&amp;!obj.disabled){ switch(obj.tagName){ case 'SELECT': for(var j=0;j&lt;obj.length;++j){ if(obj.options[j].selected){ var value=obj.options[j].value; if(!value)value=obj.options[j].text; results.push(obj.name+'='+escape(value)); } } break; case 'INPUT': case 'TEXTAREA': var type=obj.type,value=obj.value; if(type)type=type.toLowerCase(); if(type&amp;&amp;(type=='radio'||type=='checkbox')){ if(obj.checked)results.push(obj.name+'='+(value?escape(value):'on')); } else results.push(obj.name+'='+escape(value)); break; } } } return results.join('&amp;'); } </code></pre>
[]
[ { "body": "<p>I'd change two things. I'd start by declaring your var's in one statement like so:</p>\n\n<pre><code>function test_submit(id){\n var q=[],\n p=$(id).getElementsByTagName('SELECT');\n</code></pre>\n\n<p>Second I'd use more descriptive variable names than i, p, r, n. If you run this code through a minifier it'll do this for you. When you come back to edit this code in a few months you'll want to know exactly what each variable is for, and using a descriptive name helps with that.</p>\n\n<p>I'd also be leary of using $ in the global namespace as a variable name since a lot of the popular libraries use it and you don't want to have any collisions with those. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T21:03:37.617", "Id": "7619", "Score": "0", "body": "Understood! Made the appropriate changes. You are right, I often minify the code by hand when it is not necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T21:32:54.707", "Id": "7620", "Score": "0", "body": "@steveo225 So my answer was good, just not \"upvote\" good? :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T21:53:55.580", "Id": "7621", "Score": "0", "body": "Just taking my time..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T19:29:04.713", "Id": "5087", "ParentId": "5085", "Score": "3" } }, { "body": "<p>In regards to variables <code>i</code> and <code>j</code> they are loop index variables and can be declared in the loop alone instead of at the top. It will clean up the code.</p>\n\n<p>Example </p>\n\n<pre><code>for (var j=0;j&lt;obj.length;++j){...}\n</code></pre>\n\n<p>Personally I would write it up like this describing <code>p</code> and <code>i</code> which are form elements. In additon there is no need to duplicate code (example would be 3 identical for statments), you can gather all the form elements and concat the arrays together in one. Then by using a switch statement you can minimize the duplicate <code>if</code>s for each element type and eliminate the need for duplicate for statements. Have a look below. it is much cleaner.</p>\n\n<pre><code>function test_submit(id){ \n var params=[],\n results=[],\n form=document.getElementById(id),\n obj; \n\n for(var i = 0, var formElement = form.elements[i]; i &lt; form.elements.length; i++) { \n if (formElement.name) {\n switch (formElement.tagName) {\n case \"SELECT\":\n for(var j=0, var optionItem = formElement.options[j]; j &lt; formElement.length; j++){ \n if(optionItem.selected){ \n var value = optionItem.value; \n if(!value) value = optionItem.text; \n params.push([formElement.name,value]); \n } \n } \n break;\n case \"INPUT\":\n var type=formElement.type,\n value=formElement.value; \n if(type) type=type.toLowerCase(); \n if(type &amp;&amp; (type == 'radio' || type == 'checkbox')) { \n if(formElement.checked) params.push([formElement.name,value?value:'on']); \n } \n else params.push([formElement.name,value]); \n break;\n case \"TEXTAREA\":\n params.push([formElement.name,formElement.value]); \n break;\n }\n }\n }\n for (var i in params) results.push(params[i][0]+'='+escape(params[i][1])); \n return results.join('&amp;'); \n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T00:48:17.537", "Id": "7624", "Score": "0", "body": "The only issue I see, `getElementsByTagName` returns an object, not array, so `concat()` doesn't work" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T01:35:41.870", "Id": "7626", "Score": "0", "body": "@stevo225 actually what was I thinking you can simply iterate over form.elements. The above code corrects my brain fart of trying to concat multiple HTMLCollections. Sorry about that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T12:26:09.163", "Id": "7630", "Score": "0", "body": "I like that, no using `getElementsByTagName` and they come in the proper order (not that it matters). I made a couple edits for my own taste." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T00:25:15.353", "Id": "5092", "ParentId": "5085", "Score": "2" } }, { "body": "<p>A few things:</p>\n\n<p>1 I'd like to see it handle password fields separately: you might want to process them in some way, obfuscation, validation, strength testing etc.</p>\n\n<p>2 Personally, I'd avoid using 'form' as a variable name. Just for the sake of my own sanity, if nothing else. </p>\n\n<p>3 What if the form elements have no <code>name</code>s?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T11:51:31.680", "Id": "7745", "Score": "0", "body": "1) The best approach would be to add a callback that handles `password` fields, otherwise it isn't standard and wouldn't behave like the browser, also password fields as not always used for passwords, so strength testing and validation don't always apply" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T11:52:27.920", "Id": "7746", "Score": "0", "body": "2) I used `form` because that is what it points to, the form, also it is just a local variable, but that is really user preference" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T11:53:43.223", "Id": "7747", "Score": "0", "body": "3) That is handled. Look at the first `if` statement in the `for` loop: `if(obj.name) ...`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T12:27:37.447", "Id": "7748", "Score": "0", "body": "3 Ah... I didn't make myself clear. I meant: what if the form inputs are identified via ID attributes, not NAMEs?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T13:48:43.240", "Id": "7755", "Score": "0", "body": "To be sent by the browser, the name attribute is required, that is how I modeled this function, to work exactly how the browser would work if the form were actually submitted." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T09:18:23.803", "Id": "5157", "ParentId": "5085", "Score": "0" } }, { "body": "<p>Elegant solution overall. Try jQuery as it has some nice features that can let you do some of this in one-liners. Code-on brother.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T13:00:56.563", "Id": "7961", "Score": "0", "body": "I know, but I was looking for a non-jQuery solution." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T02:22:13.740", "Id": "5252", "ParentId": "5085", "Score": "1" } } ]
{ "AcceptedAnswerId": "5087", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T19:18:02.937", "Id": "5085", "Score": "7", "Tags": [ "javascript" ], "Title": "Javascript form parser" }
5085
<p>Should I leave in <code>&lt;cfif reFindNoCase( "\.cfc$" , targetPage ) eq 0&gt;</code> or not?</p> <p>Direct CFC calls are flushed when the method returns. Either way, <code>onRequestEnd</code> will stop debug output from being returned for AJAX requests.</p> <p><strong>Keep If Statement</strong></p> <p>Additional regular expression search on every AJAX call. Direct CFC calls return quicker. Direct CFC call may not be trimmed.</p> <p><strong>Remove If Statement (inner code executes for all AJAX requests)</strong></p> <p>Direct CFC calls' value is stored in a variable. AJAX calls to pages return quicker. All AJAX responses are trimmed.</p> <p>I'm using ColdFusion 8.</p> <pre><code>&lt;cfcomponent output= "false"&gt; &lt;cfset this.name= "AJAX Debug Output" /&gt; &lt;cffunction name= "onRequestEnd" returnType= "void" hint= "I run on the end of requests (how clever)."&gt; &lt;cfargument name= "targetPage" hint= "Path from the web root to the requested page." /&gt; &lt;cfif isAJAXRequest()&gt; &lt;cfsetting showDebugOutput= "false" enableCFOutputOnly= "true" /&gt; &lt;!--- Response from CFC is already flushed to browser. Skip output. ---&gt; &lt;cfif reFindNoCase( "\.cfc$" , targetPage ) eq 0&gt; &lt;!--- If AJAXResponse is not set, then generated content is response. ---&gt; &lt;cfparam name= "request.AJAXResponse" default= "#getPageContext().getOut().getString()#" /&gt; &lt;cfcontent reset= "true" /&gt; &lt;cfoutput&gt;#trim( request.AJAXResponse )#&lt;/cfoutput&gt; &lt;cfabort /&gt; &lt;/cfif&gt; &lt;/cfif&gt; &lt;/cffunction&gt; &lt;cffunction name= "isAJAXRequest" output= "false" access= "private" hint= "I check to see if the request came across with ajax headers"&gt; &lt;cfif structKeyExists( getHTTPRequestData().headers , "X-Requested-With" )&gt; &lt;cfreturn true /&gt; &lt;/cfif&gt; &lt;cfreturn false /&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T18:01:03.970", "Id": "7774", "Score": "0", "body": "I primarily call pages for AJAX requests versus calling CFCs. Removing the conditional may cause a speed bump for edge cases, but a majority of requests will run optimal code. Nice to know CF9 solved this issue with onCFCRequest." } ]
[ { "body": "<p>If you're using ColdFusion 9, you can use onCFCRequest to deal with this type of issue. Which version of CF are you using?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T12:55:38.287", "Id": "7682", "Score": "0", "body": "I'm using 8. Hopefully will be on 9 soon. Interesting to know that's available." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T21:56:07.780", "Id": "5090", "ParentId": "5086", "Score": "6" } }, { "body": "<p>And, if you are using CF 9.0.1 you don't have to worry about the debug output at all, on direct CFC Requests. Starting with 9.0.1, CF will automatically suppress the debug output. (Thank God)</p>\n\n<p>A few years back, Ray and I were hashing out how to target a request via it's header, and came up with this:</p>\n\n<pre><code>&lt;cfif structKeyExists(reqData.headers,\"X-Requested-With\") and reqData.headers[\"X-Requested-With\"] eq \"XMLHttpRequest\"&gt;\n</code></pre>\n\n<p>That worked great, as all of the Ajax libraries (that we tested) were using the same thing. That is, until JQuery released 1.6, at which point they created a custom header type (jqXHR, I think) that they use with requests.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T13:11:55.757", "Id": "7683", "Score": "0", "body": "That's interesting. jQuery 1.6.2 and 1.6.4 send X-Requested-With headers. \n \nThe reason why I created the isAJAXRequest function was to allow for inevitable change. \n \nI'm curious about the second condition. Have you found an X-Requested-With header that wasn't XMLHttpRequest?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T10:15:54.537", "Id": "7742", "Score": "1", "body": "I had to go back and check the JQuery docs again, as I was sure I had read it the other day. Sure enough, documentation of the .ajax() method options tells you this about the beforeSend option: \"A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent.\" http://api.jquery.com/jQuery.ajax/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T18:04:02.423", "Id": "7775", "Score": "0", "body": "Great info to digest. If I was primarily calling CFC's for AJAX requests, then I'd probably leave in the conditional. It also makes sense to remove the conditional to keep inline with CF9." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T12:26:57.930", "Id": "5112", "ParentId": "5086", "Score": "3" } } ]
{ "AcceptedAnswerId": "5112", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T19:27:09.363", "Id": "5086", "Score": "4", "Tags": [ "coldfusion", "cfml" ], "Title": "Should I treat direct CFC Calls differently than Page Requests?" }
5086
<p>This module makes a doubly linked list and initializes each member. I couldn't do it with a loop, so I gave up and made each node individually.</p> <p>How can I improve it? Can somebody help me make a loop to chain all these lists together? This is from a Checkers game I'm making.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;memory.h&gt; #include &lt;malloc.h&gt; #include &lt;assert.h&gt; #include "LISTA.h" #include "PEC.h" #define TABULEIRO_OWN #include "TABULEIRO.h" #undef TABULEIRO_OWN typedef struct TAB_tagInfoCasa { void * pValor1; void * pValor2; }TAB_tpInfoCasa ; typedef struct TAB_tagTabuleiro { LIS_tppLista pElem ; /* elemento de uma lista de listas, ou seja, uma lista */ struct TAB_tagTabuleiro *pProx ; /* Ponteiro para o elemento sucessor */ struct TAB_tagTabuleiro * pAnt ; /* Ponteiro para o elemento predecessor */ }TAB_tpTabuleiro ; /***** Dados encapsulados no módulo *****/ static TAB_tpTabuleiro * pTabuleiro = NULL ; /* Ponteiro para a cabeça do tabuleiro */ /***** Protótipos das funções encapsuladas no módulo *****/ static void EsvaziarTabuleiro( ) ; static LIS_tpCondRet InserirInfoCasa( LIS_tppLista pLista, PEC_tpPEC pPEC, int PosCasa ) ; /***** Código das funções exportadas pelo módulo *****/ /*************************************************************************** * Função TAB Criar tabuleiro ***************************************************************************/ TAB_tpCondRet TAB_CriarTabuleiro( ) { LIS_tpCondRet CondRet ; int PosCasa ; int CasaBranca = -1 ; /************************** Declarações dos nós do tabuleiro ***************/ TAB_tpTabuleiro * pTab ; TAB_tpTabuleiro * pTab2 ; TAB_tpTabuleiro * pTab3 ; TAB_tpTabuleiro * pTab4 ; TAB_tpTabuleiro * pTab5 ; TAB_tpTabuleiro * pTab6 ; TAB_tpTabuleiro * pTab7 ; TAB_tpTabuleiro * pTab8 ; /************************** Declaração das listas **************************/ LIS_tppLista pListaA ; LIS_tppLista pListaB ; LIS_tppLista pListaC ; LIS_tppLista pListaD ; LIS_tppLista pListaE ; LIS_tppLista pListaF ; LIS_tppLista pListaG ; LIS_tppLista pListaH ; /************************** Declaração das peças **************************/ PEC_tpPEC PECBranca ; PEC_tpPEC PECPreta ; /************************** Criação das peças **************************/ PECBranca = PEC_CriarPEC( BRANCA, NORMAL ); if ( PECBranca == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ PECPreta = PEC_CriarPEC( PRETA, NORMAL ); if ( PECPreta == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ /************************** Criação das listas **************************/ pListaA = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaA == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pListaB = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaB == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pListaC = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaC == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pListaD = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaD == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pListaE = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaE == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pListaF = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaF == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pListaG = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaG == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pListaH = LIS_CriarLista( PEC_DestruirPEC ) ; if ( pListaH == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ /* Inserção dos elementos da lista A */ CondRet = InserirInfoCasa( pListaA, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 5 ; CondRet = InserirInfoCasa( pListaA, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaA, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 13 ; CondRet = InserirInfoCasa( pListaA, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaA, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 21 ; CondRet = InserirInfoCasa( pListaA, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaA, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 29 ; CondRet = InserirInfoCasa( pListaA, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaA ) ; /* Inserção dos elementos da lista B */ PosCasa = 1 ; CondRet = InserirInfoCasa( pListaB, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaB, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 9 ; CondRet = InserirInfoCasa( pListaB, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaB, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 17 ; CondRet = InserirInfoCasa( pListaB, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaB, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 25 ; CondRet = InserirInfoCasa( pListaB, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaB, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaB ) ; /* Inserção dos elementos da lista C */ CondRet = InserirInfoCasa( pListaC, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 6 ; CondRet = InserirInfoCasa( pListaC, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaC, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 14 ; CondRet = InserirInfoCasa( pListaC, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaC, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 22 ; CondRet = InserirInfoCasa( pListaC, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaC, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 30 ; CondRet = InserirInfoCasa( pListaC, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaC ) ; /* Inserção dos elementos da lista D */ PosCasa = 2 ; CondRet = InserirInfoCasa( pListaD, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaD, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 10 ; CondRet = InserirInfoCasa( pListaD, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaD, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 18 ; CondRet = InserirInfoCasa( pListaD, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaD, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 26 ; CondRet = InserirInfoCasa( pListaD, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaD, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaD ) ; /* Inserção dos elementos da lista E */ CondRet = InserirInfoCasa( pListaE, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 7 ; CondRet = InserirInfoCasa( pListaE, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaE, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 15 ; CondRet = InserirInfoCasa( pListaE, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaE, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 23 ; CondRet = InserirInfoCasa( pListaE, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaE, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 31 ; CondRet = InserirInfoCasa( pListaE, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaE ) ; /* Inserção dos elementos da lista F */ PosCasa = 3 ; CondRet = InserirInfoCasa( pListaF, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaF, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 11 ; CondRet = InserirInfoCasa( pListaF, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaF, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 19 ; CondRet = InserirInfoCasa( pListaF, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaF, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 27 ; CondRet = InserirInfoCasa( pListaF, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaF, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaF ) ; /* Inserção dos elementos da lista G */ CondRet = InserirInfoCasa( pListaG, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 8 ; CondRet = InserirInfoCasa( pListaG, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaG, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 16 ; CondRet = InserirInfoCasa( pListaG, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaG, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 24 ; CondRet = InserirInfoCasa( pListaG, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaG, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 32 ; CondRet = InserirInfoCasa( pListaG, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaG ) ; /* Inserção dos elementos da lista H */ PosCasa = 4 ; CondRet = InserirInfoCasa( pListaH, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaH, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 12 ; CondRet = InserirInfoCasa( pListaH, PECBranca, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaH, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 20 ; CondRet = InserirInfoCasa( pListaH, NULL, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaH, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ PosCasa = 28 ; CondRet = InserirInfoCasa( pListaH, PECPreta, PosCasa ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ CondRet = InserirInfoCasa( pListaH, NULL, CasaBranca ) ; if ( CondRet != LIS_CondRetOK ) { return CondRet ; } /* if */ IrInicioLista( pListaH ) ; /************************** Criação dos nós do tabuleiro **************************/ pTab = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pTab2 = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab2 == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pTab3 = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab3 == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pTab4 = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab4 == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pTab5 = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab5 == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pTab6 = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab6 == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pTab7 = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab7 == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ pTab8 = ( TAB_tpTabuleiro * ) malloc( sizeof( TAB_tpTabuleiro ) ) ; if ( pTab8 == NULL ) { return TAB_CondRetFaltouMemoria ; } /* if */ /******************** Setando os elementos do tabuleiro e fazendo as ligações entre os nós ***********/ pTabuleiro = pTab ; /* pTab é a origem do tabuleiro */ pTab-&gt;pAnt = NULL ; pTab-&gt;pProx = pTab2 ; pTab-&gt;pElem = pListaA ; pTab2-&gt;pAnt = pTab ; pTab2-&gt;pProx = pTab3 ; pTab2-&gt;pElem = pListaB ; pTab3-&gt;pAnt = pTab2 ; pTab3-&gt;pProx = pTab4 ; pTab3-&gt;pElem = pListaC ; pTab4-&gt;pAnt = pTab3 ; pTab4-&gt;pProx = pTab5 ; pTab4-&gt;pElem = pListaD ; pTab5-&gt;pAnt = pTab4 ; pTab5-&gt;pProx = pTab6 ; pTab5-&gt;pElem = pListaE ; pTab6-&gt;pAnt = pTab5 ; pTab6-&gt;pProx = pTab7 ; pTab6-&gt;pElem = pListaF ; pTab7-&gt;pAnt = pTab6 ; pTab7-&gt;pProx = pTab8 ; pTab7-&gt;pElem = pListaG ; pTab8-&gt;pAnt = pTab7 ; pTab8-&gt;pProx = NULL ; pTab8-&gt;pElem = pListaH; return TAB_CondRetOK ; } /* Fim função: TAB &amp;Criar tabuleiro */ /*************************************************************************** * * Função: TAB &amp;Destruir tabuleiro * ****/ TAB_tpCondRet TAB_DestruirTabuleiro( ) { #ifdef _DEBUG assert( pTabuleiro != NULL ) ; #endif EsvaziarTabuleiro( ) ; free( pTabuleiro ) ; pTabuleiro = NULL ; return TAB_CondRetOK ; } /* Fim função: TAB &amp;Destruir tabuleiro */ /*************************************************************************** * * Função: TAB &amp;Avancar Elemento Corrente * ****/ TAB_tppTabuleiro TAB_AvancarElemento( int numElem ) { int i ; TAB_tppTabuleiro pTab = pTabuleiro ; if ( pTabuleiro == NULL ) return NULL; //#ifdef _DEBUG // assert( pTab != NULL ) ; //#endif #ifdef _DEBUG assert( numElem &lt;= 7 ) ; #endif /* Tratar lista vazia */ if ( pTab-&gt;pElem == NULL ) { return NULL ; } /* fim ativa: Tratar lista vazia */ /* Tratar avançar para frente */ if ( numElem &gt; 0 ) { for( i = numElem ; i &gt; 0 ; i-- ) { if ( pTab == NULL ) { break ; } /* if */ pTab = pTab-&gt;pProx ; } /* for */ if ( pTab-&gt;pElem != NULL ) { return pTab ; } /* if */ } /* fim ativa: Tratar avançar para frente */ /* Retorno caso numElem seja igual a 0 ou outro número inválido */ return pTab ; } /* Fim função: TAB &amp;Avançar elemento */ /*************************************************************************** * * Função: TAB &amp;Obter Valor de uma lista de listas * ****/ void * TAB_ObterValorTab( TAB_tppTabuleiro pTab ) { #ifdef _DEBUG assert( pTab != NULL ) ; #endif if ( pTab-&gt;pElem == NULL ) { return NULL ; } /* if */ return pTab-&gt;pElem ; } /* Fim função: TAB &amp;Obter referência para o valor contido no elemento */ /*************************************************************************** * * Função: TAB &amp;Obter Valor 1 da estrutura TAB_tagInfoCasa * ****/ void * TAB_ObterValor1Casa( TAB_tppInfoCasa pInfo ) { if ( pInfo == NULL ) { return ( void * ) -1 ; } /* if */ return pInfo-&gt;pValor1 ; } /* Fim função: TAB &amp;Obter referência para o valor 1 contido no elemento */ /*************************************************************************** * * Função: TAB &amp;Obter Valor 2 da estrutura TAB_tagInfoCasa * ****/ void * TAB_ObterValor2Casa( TAB_tppInfoCasa pInfo ) { if ( pInfo == NULL ) { return ( void * ) -1 ; } /* if */ return pInfo-&gt;pValor2 ; } /* Fim função: TAB &amp;Obter referência para o valor 2 contido no elemento */ /***** Código das funções encapsuladas no módulo *****/ /*********************************************************************** * * $FC Função: TAB &amp;Esvaziar tabuleiro * * $ED Descrição da função * Elimina todos os elementos, sem contudo eliminar o tabuleiro * * $EP Parâmetros * pTabuleiro - ponteiro para o tabuleiro a ser esvaziado * ***********************************************************************/ static void EsvaziarTabuleiro( ) { TAB_tpTabuleiro * pNext ; TAB_tpTabuleiro * pCurr = pTabuleiro ; #ifdef _DEBUG assert( pTabuleiro != NULL ) ; #endif /* IrInicioLista( pTabuleiro ) ;*/ while ( pCurr != NULL ) { pNext = pCurr-&gt;pProx ; LIS_DestruirLista( pCurr-&gt;pElem ) ; pCurr = pNext ; } /* while */ } /* Fim função: TAB &amp;Esvaziar tabuleiro */ /*********************************************************************** * * $FC Função: TAB &amp;Inserir elemento numa casa do tabuleiro * * $ED Descrição da função * Preenche uma variável do tipo TAB_tagInfoCasa com os parâmetros * recebidos e chama a função de inserir do módulo lista, preenchendo * a informação necessária de uma casa do tabuleiro. * * $EP Parâmetros * pLista - ponteiro para a lista em que será inserida a informação * pPEC - ponteiro para a peça que será inserida. * Poscasa - valor da numeração da casa que será inserida. * * $FV Valor retornado * Valor retornado * LIS_CondRetOK * LIS_CondRetFaltouMemoria * ***********************************************************************/ static LIS_tpCondRet InserirInfoCasa( LIS_tppLista pLista, PEC_tpPEC pPEC, int PosCasa ) { /***** Declaração do tipo que será inserido numa casa do tabuleiro *****/ TAB_tppInfoCasa pInfo ; /***** Alocação do tipo que será inserido numa casa do tabuleiro *****/ pInfo = ( TAB_tpInfoCasa * ) malloc ( sizeof ( TAB_tpInfoCasa ) ) ; if ( pInfo == NULL ) { return LIS_CondRetFaltouMemoria ; } /* if */ pInfo-&gt;pValor1 = ( void * ) pPEC ; pInfo-&gt;pValor2 = ( void * ) PosCasa ; return LIS_InserirElementoApos( pLista, pInfo ) ; } /* Fim função: TAB &amp;Inserir elemento numa casa */ /********** Fim do módulo de implementação: TAB Tabuleiro **********/ </code></pre>
[]
[ { "body": "<p>Well, <em>some</em> parts can be converted to loops pretty easily. Just for the most obvious example, your series of code like:</p>\n\n<pre><code> pListaA = LIS_CriarLista( PEC_DestruirPEC ) ;\n if ( pListaA == NULL )\n {\n return TAB_CondRetFaltouMemoria ;\n } /* if */\n</code></pre>\n\n<p>(repeated for pListaB...pListaH), can be converted to a loop quite easily:</p>\n\n<pre><code>#define num_tabs 8\n\nTAB_tpTabuleiro *Tabs[num_tabs];\n\nfor (i=0; i&lt;num_tabs; i++) {\n Tabs[i] = LIS_CriarLista( PEC_DestruirPEC ) ;\n if (Tabs[i] == NULL)\n return TAB_CondRetFaltouMemoria ;\n} \n</code></pre>\n\n<p>Some of the other parts look just irregular enough that the conversion is likely to be a bit more complex. While I could certainly write some code that would produce the same result, I'm pretty sure I'm not following enough of what all this is really supposed to accomplish. I can puzzle out <em>just</em> enough of the meaning of some of the names to convince me that I really don't understand the code as well as I should to produce something that's as clean as possible. I could undoubtedly figure out what it means even without names that are meaningful to me, but having done that many times before, I'm pretty sure it would take more time than I'm willing to spend on it at the moment.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T04:44:31.733", "Id": "5096", "ParentId": "5088", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T19:44:47.577", "Id": "5088", "Score": "5", "Tags": [ "optimization", "c", "design-patterns" ], "Title": "Module for making a doubly linked list" }
5088
<p>Simply put, is this function a correct and safe way to add and/or subtract time to a <code>tm</code> <code>struct</code> (from <code>&lt;time.h&gt;</code>)?</p> <pre><code>void AddTime(int seconds, tm *date) { date-&gt;tm_sec += seconds; mktime(date); } </code></pre> <p><code>seconds</code> could be any value, supposedly larger than 60 (or smaller than -60). I'm using <code>mktime</code> to readjust the other values in <code>tm</code>, but I don't know if that's right.</p> <p>I'm also not taking into account going below 1970 or above 3001 for the year, which I think are the default bounds for <code>mktime</code> to operate. I can check for that elsewhere.</p>
[]
[ { "body": "<p>I would add a sanity check on the pointer as well:</p>\n\n<pre><code>void AddTime(int seconds, tm* date) {\n if (date == NULL) return;\n date-&gt;tm_sec += seconds;\n mktime(date);\n}\n</code></pre>\n\n<p>But other than that it looks correct.</p>\n\n<p>Reading some <a href=\"http://www.cplusplus.com/reference/clibrary/ctime/mktime/\" rel=\"nofollow\">documentation on mktime</a>, this appears to be what it was meant for.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-19T16:09:50.100", "Id": "348689", "Score": "2", "body": "Your code example will not compile as is. `struct tm *date` will help with that." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T22:05:11.750", "Id": "5101", "ParentId": "5089", "Score": "3" } }, { "body": "<p>You should put more validations. For example, if you add more than 60 seconds, you need to increment minutes too. If the minutes value is 59, you must increment hours too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-29T13:59:44.030", "Id": "30601", "Score": "2", "body": "I thought mktime distributed the overflows accordingly. Does it not?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-29T16:47:03.113", "Id": "30612", "Score": "3", "body": "`mktime` does perform normalization on its values" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-29T13:55:39.593", "Id": "19151", "ParentId": "5089", "Score": "-1" } }, { "body": "<p>This may be unrelated to your application, but it should be noted that you haven't mentioned the size of int for your system. For a 16-bit system (very common on micro controllers) your function will only be valid in the range of -32768 to 32767. </p>\n\n<p>You also need to take into account that the value date.tm_min can already be in the range of 0-59, so you that makes the new range -32768 to (32767-59).</p>\n\n<p>I mention this because 32767 seconds corresponds to roughly 9 hours, which may not be enough for your application.</p>\n\n<p>You can convert the tm structure to seconds using time_t values generated with mktime, do your subtraction, then convert back to tm with gmtime(). Be careful to make sure you use the correct starting year (1900 and 1970 are the usual ones). Also, be aware of the 2038 overflow for 32 bit time_t.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-08T01:36:04.287", "Id": "314493", "Score": "0", "body": "You are absolutely right, thanks for the correction." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-06-02T15:09:50.080", "Id": "164789", "ParentId": "5089", "Score": "3" } } ]
{ "AcceptedAnswerId": "5101", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T21:38:24.903", "Id": "5089", "Score": "9", "Tags": [ "c", "datetime" ], "Title": "Adding time to struct tm" }
5089
<pre><code>def int_to_roman (integer): returnstring='' table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]] for pair in table: while integer-pair[1]&gt;=0: integer-=pair[1] returnstring+=pair[0] return returnstring def rom_to_int(string): table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]] returnint=0 for pair in table: continueyes=True while continueyes: if len(string)&gt;=len(pair[0]): if string[0:len(pair[0])]==pair[0]: returnint+=pair[1] string=string[len(pair[0]):] else: continueyes=False else: continueyes=False return returnint </code></pre>
[]
[ { "body": "<p>Looks good. I have a few thoughts, every one of them very minor and based in opinion.</p>\n\n<ul>\n<li><p>I think it would be clearer to iterate over roms and nums instead of having pairs and having to remember which is which. This uses a Python feature called 'tuple unpacking':</p>\n\n<pre><code>for (rom, num) in table:\n print rom\n print num\n</code></pre></li>\n<li><p>Concatenating strings over and over is slower than appending to a list - but that this is something that would likely never matter for this application! If you want, you could collect your Roman numerals in a list before joining them at the end:</p>\n\n<pre><code>l = []\nfor i in range(10):\n l.append('s')\ns = \"\".join(l)\nprint s\n</code></pre></li>\n<li><p><code>table</code> is information common to both functions; not that it's going to change, but if evidence for new Roman numerals ever was found, it'd be nice to just add them in one place. <code>table</code> could therefore be a module-level variable. </p></li>\n<li><p>I personally find <code>continueyes</code> to be an awkward variable name - you could use <code>continue_</code>, following a convention of adding a trailing underscore to avoid a Python keyword.</p></li>\n<li><p>You could use <code>break</code> instead of setting <code>continueyet = True</code> and waiting for the <code>while</code> to check the condition.</p>\n\n<pre><code>while True:\n if done:\n break\n</code></pre></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T00:49:19.277", "Id": "5093", "ParentId": "5091", "Score": "5" } }, { "body": "<pre><code>def int_to_roman (integer):\n\n returnstring=''\n table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]\n</code></pre>\n\n<p>The element in your list should really be tuples not lists. It should also be a global constant so that you can reuse across both functions.</p>\n\n<pre><code> for pair in table:\n</code></pre>\n\n<p>Use <code>for letter, value in table:</code> rather then indexing the tuples.</p>\n\n<pre><code> while integer-pair[1]&gt;=0:\n</code></pre>\n\n<p>I think the code looks better with spacing around binary operators. Also why this instead of: <code>while integer &gt;= pair[1]:</code>?</p>\n\n<pre><code> integer-=pair[1]\n returnstring+=pair[0]\n</code></pre>\n\n<p>It'll probably be better to create and append to list and then join the list elements together at the end.</p>\n\n<pre><code> return returnstring\n\ndef rom_to_int(string):\n\n table=[['M',1000],['CM',900],['D',500],['CD',400],['C',100],['XC',90],['L',50],['XL',40],['X',10],['IX',9],['V',5],['IV',4],['I',1]]\n returnint=0\n for pair in table:\n\n\n continueyes=True\n</code></pre>\n\n<p>Whenever I use a logical flag like this, I think: it should be removed. I figure that flags like this only serve to confuse the logic of what you are doing. i think a break is clearer then setting a flag.</p>\n\n<pre><code> while continueyes:\n if len(string)&gt;=len(pair[0]):\n\n if string[0:len(pair[0])]==pair[0]:\n</code></pre>\n\n<p>strings have a funciton: startswith that does this. You should use it here. There is also need to check the length. If you take a slice past the end of a string in python, you just get a shorter string. </p>\n\n<pre><code> returnint+=pair[1]\n string=string[len(pair[0]):]\n\n else: continueyes=False\n else: continueyes=False\n\n return returnint\n</code></pre>\n\n<p>My version of your code:</p>\n\n<pre><code>def int_to_roman (integer):\n parts = []\n for letter, value in TABLE:\n while value &lt;= integer:\n integer -= value\n parts.append(letter)\n return ''.join(parts)\n\ndef rom_to_int(string):\n result = 0\n for letter, value in table:\n while string.startswith(letter):\n result += value\n string = string[len(pairs[0]):]\n return result\n</code></pre>\n\n<p>One last thought. Your rom_to_int doesn't handle the case where an invalid string is passed. You might want to consider having it throw an exception or something in that case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T23:09:42.467", "Id": "7716", "Score": "1", "body": "thank you! This is incredibly helpful. This all makes a lot of sense. I learned python (my first prog. language since turbo pascal in 1980s) very quickly and with specific tasks in mind, really don't yet know how to utilize its features..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T03:41:10.637", "Id": "5095", "ParentId": "5091", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T00:18:48.033", "Id": "5091", "Score": "14", "Tags": [ "python", "converting", "integer", "roman-numerals" ], "Title": "Converting Roman numerals to integers and vice versa" }
5091
<p>I've tried to create optimal in terms of performance and memmory consumption. But also I've tried to make it functional and scala way. I want to get you comment on how to make it more 'scala'stic</p> <pre><code>object LifeGame extends App { trait Matrix extends Iterable[(Int, Int)] { def apply(p: (Int, Int)): Boolean def update(p: (Int, Int), b: Boolean): Unit def newInstance: Matrix; } class SparseMapMatrix extends Matrix { type Point = (Int, Int) private var data = Set[(Int, Int)]() def apply(p: Point): Boolean = data.contains(p) def update(p: Point, b: Boolean) = if (b) data += p else data -= p def newInstance = new SparseMapMatrix() def iterator = data.iterator override def toString() = { val sb = new StringBuilder() def best(func: (Int, Int) =&gt; Int)(p1: Point, p2: Point) = (func(p1._1, p2._1), func(p1._2, p2._2)) val minBoundary = ((0, 0) /: iterator)(best(math.min)) val maxBoundary = ((0, 0) /: iterator)(best(math.max)) for (i &lt;- minBoundary._1 to maxBoundary._1) { sb.append("\n") for (j &lt;- minBoundary._2 to maxBoundary._2) { sb.append(if (this((i, j))) "x" else " ") } } sb.append("\nmin=%s, max=%s" format(minBoundary, maxBoundary)) sb.toString() } } object Engine { def apply(input: Matrix): Matrix = { val result = input.newInstance def block2D(pp: (Int, Int)): Seq[(Int, Int)] = for (ii &lt;- block1D(pp._1); jj &lt;- block1D(pp._2)) yield (ii, jj) val liveCells = for (p &lt;- input.iterator.flatMap(block2D).toSet[(Int, Int)].par) yield { val offsets = block2D(p).filter(_ != p) val nn = offsets.map(p =&gt; input(p)).count(_ == true) case class State(l: Boolean, n: Int) val newValue = State(input(p), nn) match { case State(true, n) if n &lt; 2 =&gt; false case State(true, 2) | State(true, 3) =&gt; true case State(true, n) if n &gt; 3 =&gt; false case State(false, 3) =&gt; true case State(value, _) =&gt; value }; if(newValue) Some(p) else None } liveCells.seq.foreach { _ match { case Some(p:Point) =&gt; result(p) = true; case _ =&gt; ;}} result } } def block1D(i: Int) = i - 1 to i + 1 } </code></pre>
[]
[ { "body": "<p>The main-things I changed:</p>\n\n<ul>\n<li>Matrix is now completely immutable</li>\n<li>Code is more self-documenting (extract complex code to methods, etc.)</li>\n<li>I deleted the unnecessary inheritance</li>\n<li>I don't like apply-methods which are used as contains-methods -> name change</li>\n<li>I deleted parentheses in side-effect free methods</li>\n<li>Many syntax improvements</li>\n</ul>\n\n<p>The code:</p>\n\n<pre><code>object LifeGame extends App {\n case class Point(x: Int = 0, y: Int = 0)\n\n object Matrix {\n def empty: Matrix =\n Matrix(Set.empty)\n }\n\n case class Matrix(private val data: Set[Point]) {\n\n def contains(p: Point): Boolean =\n data contains p\n\n def update(p: Point, b: Boolean) =\n if (b) copy(data+p) else copy(data-p)\n\n def iterator: Iterator[Point] =\n data.iterator\n\n override def toString = {\n def best(func: (Int, Int) =&gt; Int)(p1: Point, p2: Point) =\n Point(func(p1.x, p2.x), func(p1.y, p2.y))\n\n val minBoundary = (Point() /: iterator) { best(math.min) }\n val maxBoundary = (Point() /: iterator) { best(math.max) }\n\n val sb = StringBuilder.newBuilder\n for (i &lt;- minBoundary.x to maxBoundary.x) {\n sb.append(\"\\n\")\n for (j &lt;- minBoundary.y to maxBoundary.y) {\n sb.append(if (this contains Point(i, j)) \"x\" else \" \")\n }\n }\n sb.append(\"\\nmin=%s, max=%s\" format (minBoundary, maxBoundary))\n sb.toString\n }\n }\n\n object Engine {\n\n def newCell: (Boolean, Int) =&gt; Boolean = {\n case (true, 0 | 1) =&gt; false\n case (true, 2 | 3) =&gt; true\n case (true, _) =&gt; false\n case (false, n) =&gt; n == 3\n }\n\n def apply(input: Matrix): Matrix = {\n def block1D(i: Int) =\n Seq(i-1, i, i+1)\n\n def block2D(p: Point) =\n for (x &lt;- block1D(p.x); y &lt;- block1D(p.y)) yield Point(x, y)\n\n def points =\n (input.iterator flatMap block2D).toSet.par\n\n def calcCell(p: Point) = {\n val neighbours = block2D(p) filter { p != }\n val alive = neighbours map { input contains } count { true == }\n\n if (newCell(input contains p, alive)) Some(p)\n else None\n }\n\n val cells = (points map calcCell).seq collect { case Some(p) =&gt; p }\n (Matrix.empty /: cells) { (result, p) =&gt; result(p) = true }\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T10:05:28.017", "Id": "7675", "Score": "0", "body": "Thanks, great response. BTW why do you think `def newCell: (Boolean, Int) => Boolean ` better than `de newCell(p:(Boolean,Int)):Boolean` ? And Don't you think that builder is better approach(in terms of speed) for creating immutable Matrix?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T13:50:58.420", "Id": "7685", "Score": "0", "body": "A PartialFunction allows syntax sugar (you don't need to write the match-keyword). Functional programming is not the way to create really performance programs. The JVM can optimize very well so I don't think about performance unless I get problems." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T16:47:38.803", "Id": "5099", "ParentId": "5097", "Score": "4" } } ]
{ "AcceptedAnswerId": "5099", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T13:04:10.517", "Id": "5097", "Score": "6", "Tags": [ "scala", "game-of-life" ], "Title": "Conway life game implementation with scala" }
5097
<p>I am using the following code to run an operation on a .dat file, which is working fine. The .dat file can be treated as a text file. My main concern is improving execution time when you have to run a <code>for</code> loop on 25 Mb of data.</p> <pre><code>$file_name='grid_10min_sunp.dat'; $handle = fopen($file_name, "r"); $lat1=13.86082; $lan1=100.50509; $lat_lon_sunshines = make_sunshine_dict($file_name); // echo '&lt;pre&gt;'; //print_r($lat_lon_sunshines); //echo count($lat_lon_sunshines); $closest = 500; for($c=0;$c&lt;count($lat_lon_sunshines);$c++) { //echo $c; //echo $c; $lat2=$lat_lon_sunshines[$c]['lat']; $lan2=$lat_lon_sunshines[$c]['lan']; $sunshines=$lat_lon_sunshines[$c]['sunshine']; //print_r($sunshines);die; //die; $lat_diff = abs(round((float)($lat1), 4)-$lat2); if ($lat_diff &lt; $closest) { $diff = $lat_diff + abs(round((float)($lan1), 4)-$lan2); if($diff &lt; $closest) { $closest = $diff; $sunshinesfinal=$sunshines; } } $sunshines=''; } //echo 'sumit'; print_r($sunshinesfinal);die; function make_sunshine_dict($file_name) { $sunshines_dict = array(); $f = file_get_contents($file_name); $handle = fopen($file_name, "r"); /* for($kkk=0;$kkk&lt;100;$kkk++) { $buffer = fgets($handle);*/ while($buffer = fgets($handle)) { // print_r($buffer);die; $tok = strtok($buffer, " \n\t"); $lat=$tok; $latArray[]=$tok; //$lat=round(float(values[0]), 4) //print_r($buffer); // print_r($tok); $tok = strtok(" \n\t"); $months = ''; $months = array(); //print_r($tok);die; for ($k = 0; $tok !== false; $k+=1) { if($k==0) { $lan=$tok; $lanArray[]=$tok; } if($k!=0) { /// echo $tok; $months[] = $tok ; "month $k : ".$months[$k]."&lt;br&gt;"; } $tok = strtok(" \n\t"); } /*echo $lat; echo '&lt;br&gt;'; echo $lang; echo '&lt;br&gt;'; print_r($months);*/ //$data=new stdClass(); /*$data-&gt;sunshine[]-&gt;lat=$lat; $data-&gt;sunshine[]-&gt;lan=$lang;*/ $data[$kkk]['lat']=$lat; $data[$kkk]['lan']=$lan; //$sunshines=array(); foreach($months as $m=&gt;$sunshine) { $sunshines=array(); $sumD = 0; // $iteration= ($m+1)*30+1; $iteration= 31; for($n=1;$n&lt;=$iteration;$n++) { $J = ($m+1)*$n; $P = asin(.39795*cos(.2163108 + 2*atan(.9671396*tan(.00860*($J-186))))); $value=(sin(0.8333*pi/180) + sin($lat*pi/180)*sin($P))/(cos($lat*pi/180)*cos($P)); /* $value ? ($value &gt; 1 and 1) : $value; $value ? ($value &lt; -1 and -1): $value;*/ $D = 24 - ((24/pi) * acos($value)); $sumD = $sumD + $D; } $sunshinesdata=(($sumD/30)*(float)($sunshine)*.01); //echo '&lt;pre&gt;'; //print_r($sunshines);die; $data[$kkk]['sunshine'][$m]=$sunshinesdata; $sunshines=''; } //echo '&lt;pre&gt;'; //print_r($data); } //die; return $data; } </code></pre> <p>There are no problems in the above code, except that the .dat file I am using is 25 Mb, so you can understand it will take a long, long time to run it. How can I decrease the execution time? Can I use indexing or what?</p> <pre><code>// echo '&lt;pre&gt;'; //print_r($lat_lon_sunshines); //echo count($lat_lon_sunshines); $closest = 500; for($c=0;$c&lt;count($lat_lon_sunshines);$c++) { //echo $c; //echo $c; $lat2=$lat_lon_sunshines[$c]['lat']; $lan2=$lat_lon_sunshines[$c]['lan']; $sunshines=$lat_lon_sunshines[$c]['sunshine']; //print_r($sunshines);die; //die; $lat_diff = abs(round((float)($lat1), 4)-$lat2); if ($lat_diff &lt; $closest) { $diff = $lat_diff + abs(round((float)($lan1), 4)-$lan2); if($diff &lt; $closest) { $closest = $diff; $sunshinesfinal=$sunshines; } } $sunshines=''; } //echo 'sumit'; print_r($sunshinesfinal);die; function make_sunshine_dict($file_name) { $sunshines_dict = array(); $f = file_get_contents($file_name); $handle = fopen($file_name, "r"); /* for($kkk=0;$kkk&lt;100;$kkk++) { $buffer = fgets($handle);*/ while($buffer = fgets($handle)) { // print_r($buffer);die; $tok = strtok($buffer, " \n\t"); $lat=$tok; $latArray[]=$tok; //$lat=round(float(values[0]), 4) //print_r($buffer); // print_r($tok); $tok = strtok(" \n\t"); $months = ''; $months = array(); //print_r($tok);die; for ($k = 0; $tok !== false; $k+=1) { if($k==0) { $lan=$tok; $lanArray[]=$tok; } if($k!=0) { /// echo $tok; $months[] = $tok ; "month $k : ".$months[$k]."&lt;br&gt;"; } $tok = strtok(" \n\t"); } /*echo $lat; echo '&lt;br&gt;'; echo $lang; echo '&lt;br&gt;'; print_r($months);*/ //$data=new stdClass(); /*$data-&gt;sunshine[]-&gt;lat=$lat; $data-&gt;sunshine[]-&gt;lan=$lang;*/ $data[$kkk]['lat']=$lat; $data[$kkk]['lan']=$lan; //$sunshines=array(); foreach($months as $m=&gt;$sunshine) { $sunshines=array(); $sumD = 0; // $iteration= ($m+1)*30+1; $iteration= 31; for($n=1;$n&lt;=$iteration;$n++) { $J = ($m+1)*$n; $P = asin(.39795*cos(.2163108 + 2*atan(.9671396*tan(.00860*($J-186))))); $value=(sin(0.8333*pi/180) + sin($lat*pi/180)*sin($P))/(cos($lat*pi/180)*cos($P)); /* $value ? ($value &gt; 1 and 1) : $value; $value ? ($value &lt; -1 and -1): $value;*/ $D = 24 - ((24/pi) * acos($value)); $sumD = $sumD + $D; } $sunshinesdata=(($sumD/30)*(float)($sunshine)*.01); //echo '&lt;pre&gt;'; //print_r($sunshines);die; $data[$kkk]['sunshine'][$m]=$sunshinesdata; $sunshines=''; } //echo '&lt;pre&gt;'; //print_r($data); } //die; return $data; } </code></pre>
[]
[ { "body": "<p>The first thing that comes to mind is that if you expect a lot of duplicate values you can cache. So, for example, in this loop:</p>\n\n<pre><code>for($n=1;$n&lt;=$iteration;$n++) {\n $J = ($m+1)*$n; \n $P = asin(.39795*cos(.2163108 + 2*atan(.9671396*tan(.00860*($J-186)))));\n $value=(sin(0.8333*pi/180) + sin($lat*pi/180)*sin($P))/(cos($lat*pi/180)*cos($P));\n $D = 24 - ((24/pi) * acos($value));\n $sumD = $sumD + $D;\n}\n</code></pre>\n\n<p>You could do:</p>\n\n<pre><code>$P_cache = array();\nfor ($n=1; $n &lt;= $iteration; $n++) {\n $J = ($m + 1) * $n;\n if (array_key_exists($J, $P_cache)) {\n $P = $P_cache[$J];\n } else {\n $P = asin(...);\n ...\n }\n}\n</code></pre>\n\n<p>Doing this in a few places would trade-off memory for some performance gains. Also, since this is a site for code review, I'd also list a few points that could do with some improvement:</p>\n\n<ul>\n<li>Variable names need to be more descriptive $J could be $location_index or anything more descriptive.</li>\n<li>Use functions more take all those complex trigonometric computations and put them in a function. It will make your code cleaner and easier to review, and help us give you performance tips better.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T22:19:19.273", "Id": "5102", "ParentId": "5098", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T15:46:17.330", "Id": "5098", "Score": "2", "Tags": [ "php" ], "Title": "Running a loop on a .dat file in a minimum possible time" }
5098
<p>I'm currently writing a mesh generator class, and I'm making a method that generates vertices, normals and texcoords for a cube. But, as you can see, it's incredibly complicated and hard to follow. Is anyone willing to help me making this shorter?</p> <pre><code>public static void GenerateCube(float size, out Vector3[] vertices, out Vector2[] texCoords, out Vector3[] normals) { List&lt;Vector3&gt; vertexList = new List&lt;Vector3&gt;(); List&lt;Vector2&gt; texCoordList = new List&lt;Vector2&gt;(); List&lt;Vector3&gt; normalList = new List&lt;Vector3&gt;(); for (int i = 0; i &lt;= 2; i++) { Vector3 normal = i == 0 ? Vector3.UnitZ : (i == 1 ? -Vector3.UnitY : Vector3.UnitX); float ninety = (float)(Math.PI / 2); Matrix4 matrix = i == 0 ? Matrix4.Identity : (i == 1 ? Matrix4.CreateRotationX(ninety) : Matrix4.CreateRotationY(ninety)); Vector3 vertex1a = new Vector3(-1, -1, 1); Vector3 vertex2a = new Vector3(-1, 1, 1); Vector3 vertex3a = new Vector3(1, 1, 1); Vector3 vertex4a = new Vector3(1, -1, 1); Vector3 vertex1b = new Vector3(-1, -1, 1); Vector3 vertex2b = new Vector3(1, -1, 1); Vector3 vertex3b = new Vector3(1, 1, 1); Vector3 vertex4b = new Vector3(-1, 1, 1); vertex1a = Vector3.Transform(vertex1a, matrix); vertex2a = Vector3.Transform(vertex2a, matrix); vertex3a = Vector3.Transform(vertex3a, matrix); vertex4a = Vector3.Transform(vertex4a, matrix); vertex1b = Vector3.Transform(vertex1b, matrix); vertex2b = Vector3.Transform(vertex2b, matrix); vertex3b = Vector3.Transform(vertex3b, matrix); vertex4b = Vector3.Transform(vertex4b, matrix); for (int j = -1; j &lt;= 1; j += 2) { Vector3 vertex1, vertex2, vertex3, vertex4; if (j == -1) { vertex1 = vertex1a; vertex2 = vertex2a; vertex3 = vertex3a; vertex4 = vertex4a; } else { vertex1 = vertex1b; vertex2 = vertex2b; vertex3 = vertex3b; vertex4 = vertex4b; } //Triangle 1 normalList.Add(normal * j); texCoordList.Add(new Vector2(0, 0)); vertexList.Add(vertex1 * j); normalList.Add(normal * j); texCoordList.Add(new Vector2(0, 1)); vertexList.Add(vertex2 * j); normalList.Add(normal * j); texCoordList.Add(new Vector2(1, 1)); vertexList.Add(vertex3 * j); //Triangle 2 normalList.Add(normal * j); texCoordList.Add(new Vector2(0, 0)); vertexList.Add(vertex1 * j); normalList.Add(normal * j); texCoordList.Add(new Vector2(1, 1)); vertexList.Add(vertex3 * j); normalList.Add(normal * j); texCoordList.Add(new Vector2(1, 0)); vertexList.Add(vertex4 * j); } } vertices = vertexList.ToArray(); texCoords = texCoordList.ToArray(); normals = normalList.ToArray(); for (int i = 0; i &lt; vertices.Length; i++) vertices[i] *= size; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T23:34:57.210", "Id": "7631", "Score": "3", "body": "Well any time you see repeated code like that, it almost always means that you should throw that in a function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T00:25:17.667", "Id": "7633", "Score": "0", "body": "p.s., What exactly is a `Matrix4`? I'm assuming this is an XNA project and `Matrix4` is an alias for the `Matrix` type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T14:37:51.950", "Id": "7640", "Score": "0", "body": "It's an OpenTK project, a Matrix4 is simply a class holding 16 floats in a 4x4 matrix." } ]
[ { "body": "<p>You should consider creating a Triangle3D and Rectangle3D classes with associated operations like <code>.Transform(Matrix4 matrix)</code>. Work with these higher level classes.</p>\n\n<p><code>ninety</code> should be a global member of the class and a <code>const</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T10:39:00.253", "Id": "5109", "ParentId": "5103", "Score": "1" } }, { "body": "<p>Im not familiar with XNA or have any experience working with matrixes, vectors and that kind of stuff. But i've made som basic refactorings to make it abit easier to read and maintain.</p>\n\n<pre><code>public static void GenerateCube(float size, out Vector3[] vertices, out Vector2[] texCoords, out Vector3[] normals)\n{\n var vertexList = new List&lt;Vector3&gt;();\n var texCoordList = new List&lt;Vector2&gt;();\n var normalList = new List&lt;Vector3&gt;();\n\n const float ninety = (float)(Math.PI / 2);\n\n for (var i = 0; i &lt;= 2; i++)\n {\n var normal = CreateVector(i);\n var matrix = CreateMatrix(i, ninety);\n\n var vectorsA = CreateVectorsA();\n var vectorsB = CreateVectorsB();\n\n vectorsA.ForEach(x =&gt; Vector3.Transform(x, matrix));\n vectorsB.ForEach(x =&gt; Vector3.Transform(x, matrix));\n\n for (var j = -1; j &lt;= 1; j += 2)\n {\n var vectors = j == -1 ? vectorsA.ToArray() : vectorsB.ToArray();\n\n var someCalculations = CalculateSomething(j, normal);\n normalList.AddRange(someCalculations);\n\n AddTextureCoordinates(texCoordList);\n AddVertexes(j, vertexList, vectors);\n }\n }\n\n vertices = vertexList.ToArray();\n texCoords = texCoordList.ToArray();\n normals = normalList.ToArray();\n\n SetVectorSize(vertices, size);\n }\n\n private static void SetVectorSize(IList&lt;Vector3&gt; vertices, float size)\n {\n for (var i = 0; i &lt; vertices.Count; i++)\n {\n vertices[i] *= size;\n }\n }\n\n private static Vector3 CreateVector(int i)\n {\n return i == 0 ? Vector3.UnitZ : (i == 1 ? Vector3.UnitY : Vector3.UnitX);\n }\n\n private static Matrix4 CreateMatrix(int i, float ninety)\n {\n return i == 0 ? Matrix4.Identity : (i == 1 ? Matrix4.CreateRotationX(ninety) : Matrix4.CreateRotationY(ninety));\n }\n\n private static void AddVertexes(int j, ICollection&lt;Vector3&gt; vertexList, IList&lt;Vector3&gt; vectorsArray)\n {\n //Triangle 1\n vertexList.Add(vectorsArray[0] * j);\n vertexList.Add(vectorsArray[1] * j);\n vertexList.Add(vectorsArray[2] * j);\n\n //Triangle 2\n vertexList.Add(vectorsArray[0] * j);\n vertexList.Add(vectorsArray[2] * j);\n vertexList.Add(vectorsArray[3] * j);\n }\n\n private static void AddTextureCoordinates(ICollection&lt;Vector2&gt; texCoordList)\n {\n //Triangle 1\n texCoordList.Add(new Vector2(0, 0));\n texCoordList.Add(new Vector2(0, 1));\n texCoordList.Add(new Vector2(1, 1));\n\n //Triangle 2\n texCoordList.Add(new Vector2(0, 0));\n texCoordList.Add(new Vector2(1, 1));\n texCoordList.Add(new Vector2(1, 0));\n }\n\n private static IEnumerable&lt;Vector3&gt; CalculateSomething(int j, Vector3 normal)\n {\n var someCalculation = normal * j;\n return Enumerable.Repeat(someCalculation, 6);\n }\n\n private static List&lt;Vector3&gt; CreateVectorsB()\n {\n return new List&lt;Vector3&gt;\n {\n new Vector3(-1, -1, 1),\n new Vector3(1, -1, 1),\n new Vector3(1, 1, 1),\n new Vector3(-1, 1, 1)\n };\n }\n\n private static List&lt;Vector3&gt; CreateVectorsA()\n {\n return new List&lt;Vector3&gt;\n {\n new Vector3(-1, -1, 1),\n new Vector3(-1, 1, 1),\n new Vector3(1, 1, 1),\n new Vector3(1, -1, 1)\n };\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T06:07:34.707", "Id": "7733", "Score": "0", "body": "I'd like to make a suggestion that you use the rule of three. The `var j=-1 .. j+=2` could be written flat with some comments. It only iterates twice and (IMHO) seems unnecessary. +1 still great refactoring here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T11:23:30.433", "Id": "5111", "ParentId": "5103", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T22:44:57.017", "Id": "5103", "Score": "8", "Tags": [ "c#", "graphics", "coordinate-system" ], "Title": "Shorten up Mesh Generator Class" }
5103
<p>Like many, I started out with procedural programming. Of course, when learning a functional language, old habits may die hard, so I wrote a fairly trivial little thing which takes an integer and returns a list of the english-language representation.</p> <p>A few days later, I re-wrote it to try to take advantage of tail recursion in the main order-of-magnitude function; I freely admit that no attempt has been made to add tail-recursion to the calculation of numbers less than 1000, but since those have a fixed maximum depth of 3 (and a maximum of 5 calls in any case) I opted not to worry about it for now.</p> <p>Any notes and criticisms, please lob them at me, that I may learn to do things in a less procedural way.</p> <pre><code>-module(titoa). -export([itoa/1]). itoa(0) -&gt; "zero"; itoa(N) when is_float(N) -&gt; no_float_support; itoa(N) when N &lt; 0 -&gt; "negative " ++ itoa(abs(N)); itoa(N) when is_integer(N) -&gt; itoa_render(N); itoa(_) -&gt; severe_error. itoa_render(N) when N &gt;= 1100, N &lt; 10000, N rem 100 == 0, N rem 1000 /= 0 -&gt; itoa_render(N, ["", "hundred"], 100, []); itoa_render(N) when N &gt;= 1000 -&gt; itoa_render(N,["", "thousand","million","billion","trillion","quadrillion","quintillion", "sextillion","septillion","octillion","nontillion","dectillion" ],1000, [] ); itoa_render(N) when N &gt;= 100, N rem 100 == 0 -&gt; itoa_render(N div 100) ++ " hundred"; itoa_render(N) when N &gt;= 100 -&gt; Hun_diff = N rem 100, itoa_render(N - Hun_diff) ++ [32 | itoa_render(Hun_diff)]; itoa_render(N) when N &gt; 19, N rem 10 == 0 -&gt; lists:nth(N div 10 - 1, [ "twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety" ]); itoa_render(N) when N &gt; 19 -&gt; Ten_diff = N rem 10, itoa_render(N - Ten_diff) ++ "-" ++ itoa_render(Ten_diff); itoa_render(N) when N &gt; 0 -&gt; lists:nth(N, [ "one","two","three","four","five","six","seven","eight","nine", "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen", "seventeen","eighteen","nineteen" ]); itoa_render(_) -&gt; []. % 0 itoa_render(0, _, _, After) -&gt; After; itoa_render(_, [], _, _) -&gt; overflow; itoa_render(N, [Magnitude | Remaining_Magnitudes], Factor, After) -&gt; This_OOM = itoa_render(N rem Factor), This_Rep = if This_OOM == [] -&gt; []; Magnitude == [] -&gt; This_OOM; true -&gt; This_OOM ++ [32 | Magnitude] ++ if After == [] -&gt; []; true -&gt; [32] end end, itoa_render(N div Factor, Remaining_Magnitudes, Factor, This_Rep ++ After). </code></pre>
[]
[ { "body": "<p>At first glance, you're trying to be a bit cute here and it's making your code more complex than necessary. For example, why not handle 11 and 12 as part of the teens and why not just type out the teen and decade names in full rather than having extra logic to append a not-quite common suffix (\"teen\" and \"ty\")?</p>\n\n<p>For <code>n &lt; 1000</code> you have the following rules (let <code>&lt;n&gt;</code> mean \"<code>n</code> in words\", <code>%</code> mean modulo, and <code>//</code> mean integer division):</p>\n\n<pre><code>if 100 &lt;= n then &lt;n // 100&gt; \" hundred\" ++ \n (if n % 100 == 0 then \"\" else \" and \" ++ &lt;n % 100&gt;)\nif 20 &lt;= n then {\"\", \"twenty\", ..., \"ninety\"}[n // 10] ++ \n (if n % 10 == 0 then \"\" else \" \" ++ &lt;n % 10&gt;)\notherwise {\"zero\", \"one\", \"two\", ..., \"ten\", \"eleven\", ..., \"nineteen\"}[n]\n</code></pre>\n\n<p>Now you only need to deal with the orders of magnitude (\"thousand\", \"million\", etc.).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T06:18:08.880", "Id": "7669", "Score": "1", "body": "I'll grant you the bit about the splitting of 12-19, and the \"teen\" and \"ty\". However, could you please help me understand why doing it with if clauses is more efficient than using Erlang's guard syntax, and furthermore, what about the tail recursion -- did I implement it correctly or will it not work?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T22:40:22.637", "Id": "7715", "Score": "0", "body": "Just three quick points. First, there should be no efficiency difference between using if-then-elses or guards -- they're the same pig wearing different dresses. Second, where you write `itoa_render(N - Hun_diff) ++ [32 | itoa_render(Hun_diff)];`, you're clearly not being tail recursive since you have a recursive call in a constructor argument in a function argument. Third, you probably shouldn't worry about efficiency too much here since this algorithm is O(log n) anyway! My point was more about clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T23:27:58.350", "Id": "7720", "Score": "0", "body": "And a valid point it is, clarity. I know the 0-999 calculators aren't tail recursive (\"I freely admit that no attempt has been made to add tail-recursion to the calculation of numbers less than 1000\"), but the concept of tail recursion is fairly new to me, so largely I just wanted to be sure that I had managed to get it going in that one place, or if I failed to grasp it and thus failed to implement it. I am going to rewrite it using explicit ifs and see if that increases clarity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T01:19:12.703", "Id": "7721", "Score": "0", "body": "Tail recursion typically looks something like this: `f(x) = if isBaseCase(x) then a else f(g(x))`. Anything else, such as `f(x) = if isBaseCase(x) then a else h(f(g(x)))` is not tail recursive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T01:56:21.997", "Id": "7725", "Score": "0", "body": "I was going to post it, but I'm electing not to now; I must've done something wrong, because it seems larger and more convoluted. I suppose I have a fair bit more learning to do." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T01:37:52.003", "Id": "5126", "ParentId": "5104", "Score": "1" } }, { "body": "<ol>\n<li><a href=\"http://books.google.com/books?id=Qr_WuvfTSpEC&amp;lpg=PA47&amp;dq=erlang%20programming%20defensive%20programming&amp;pg=PA47#v=onepage&amp;q=erlang%20programming%20defensive%20programming&amp;f=false\" rel=\"nofollow\">Defensive programming is not recommended in Erlang</a>, which means you could/should remove the <code>no_float_support</code> and <code>severe_error</code> clause.</li>\n<li><p>Using lists:nth is generally bad practice since it has a <code>O(n)</code> complexity and this means using your list like an array. For fixed-size lists, use tuples instead. Here's an example:</p>\n\n<pre><code>element(N div 10 - 1,\n {twenty\",\"thirty\",\"forty\",\"fifty\",\"sixty\",\"seventy\",\"eighty\",\"ninety\"}\n);\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-01T09:01:37.773", "Id": "9581", "ParentId": "5104", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-01T23:44:02.647", "Id": "5104", "Score": "5", "Tags": [ "beginner", "erlang" ], "Title": "Take a number and return English language representation" }
5104
<p>Could someone please review my code? It seems too convoluted. I am just starting to learn to go from blog to hosting.</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head&gt; &lt;style id="page-skin-1" type="text/css"&gt;&lt;!-- /* ----------------------------------------------- ----------------------------------------------- */ /* Variable definitions ==================== &lt;Variable name="bgcolor" description="Page Background Color" type="color" default="#fff"&gt; &lt;Variable name="textcolor" description="Text Color" type="color" default="#333"&gt; &lt;Variable name="linkcolor" description="Link Color" type="color" default="#58a"&gt; &lt;Variable name="pagetitlecolor" description="Blog Title Color" type="color" default="#666"&gt; &lt;Variable name="descriptioncolor" description="Blog Description Color" type="color" default="#999"&gt; &lt;Variable name="titlecolor" description="Post Title Color" type="color" default="#666"&gt; &lt;Variable name="bordercolor" description="Border Color" type="color" default="#ccc"&gt; &lt;Variable name="sidebarcolor" description="Sidebar Title Color" type="color" default="#999"&gt; &lt;Variable name="sidebartextcolor" description="Sidebar Text Color" type="color" default="#666"&gt; &lt;Variable name="visitedlinkcolor" description="Visited Link Color" type="color" default="#999"&gt; &lt;Variable name="bodyfont" description="Text Font" type="font" default="normal normal 100% Georgia, Serif"&gt; &lt;Variable name="headerfont" description="Sidebar Title Font" type="font" default="normal normal 78% 'Trebuchet MS',Trebuchet,Arial,Verdana,Sans-serif"&gt; &lt;Variable name="pagetitlefont" description="Blog Title Font" type="font" default="normal normal 200% Georgia, Serif"&gt; &lt;Variable name="descriptionfont" description="Blog Description Font" type="font" default="normal normal 78% 'Trebuchet MS', Trebuchet, Arial, Verdana, Sans-serif"&gt; &lt;Variable name="postfooterfont" description="Post Footer Font" type="font" default="normal normal 78% 'Trebuchet MS', Trebuchet, Arial, Verdana, Sans-serif"&gt; &lt;Variable name="startSide" description="Side where text starts in blog language" type="automatic" default="left"&gt; &lt;Variable name="endSide" description="Side where text ends in blog language" type="automatic" default="right"&gt; */ /* Use this with templates/template-twocol.html */ body { background:#3e006a; margin:0; color:#80ff00; font:x-small Georgia Serif; font-size/* */:/**/small; font-size: /**/small; text-align: center; } a:link { color:#9fff3f; text-decoration:none; font-size/* */:/**/small; font-size: /**/small; } a:visited { color:#9fff3f; text-decoration:none; font-size/* */:/**/small; font-size: /**/small; } a:hover { color:#80FF00; text-decoration:underline; } a img { border-width:0; } /* Header ----------------------------------------------- */ #header-wrapper { width: 850px; align: center; border: 1px solid #c1a1ff; margin-left: 45px; margin-right: 0px; margin-top: 10px; margin-bottom: 10px border:1px solid #80FF00; align: center } #header-inner { background-position: center; margin-left: 0px; margin-right: 0; } #header { margin: 5px; border: 1px solid #80FF00; text-align: center; color:#80FF00; } #header h1 { margin:5px 5px 0; padding:0px 0px line-height:1.2em; text-transform:uppercase; letter-spacing:.2em; font: normal normal 220% Verdana, sans-serif; } #header a { color:#80FF00; text-decoration:none; } #header a:hover { color:#80FF00; } #header .description { margin:0 5px 5px; padding:0 0px 0px; max-width:870px; text-transform:uppercase; letter-spacing:.2em; line-height: 1.4em; font: normal normal 78% Verdana, sans-serif; color: #ca80ff; } #header img { margin-left: auto; margin-right: auto; } /* Outer-Wrapper ----------------------------------------------- */ #outer-wrapper { width: 1000px; margin:0 auto; padding:1px; text-align:LEFT; font: normal normal 99% Verdana, sans-serif; } #main-wrapper { width: 950x; align: left; word-wrap: break-word; /* fix for long text breaking sidebar float in IE */ overflow: } #sidebar-wrapper { width: 0px; float: RIGHT; word-wrap: break-word; /* fix for long text breaking sidebar float in IE */ overflow: hidden; /* fix for long non-text content breaking IE sidebar float */ } /* Headings ----------------------------------------------- */ h2 { margin:1.5em 0 .75em; font:normal normal 77% Verdana, sans-serif; line-height: 1.4em; text-transform:uppercase; letter-spacing:.2em; color:#e5c0ff; } /* Posts ----------------------------------------------- */ h2.date-header { margin:1.5em 0 .5em; } .post { margin:.5em 0 1.5em; padding-bottom:1.5em; } .post h3 { margin:.25em 0 0; padding:0 0 4px; font-size:140%; font-weight:normal; line-height:1.4em; color:#80FF00; } .post h3 a, .post h3 a:visited, .post h3 strong { display:block; text-decoration:none; color:#80FF00; font-weight:normal; } .post h3 strong, .post h3 a:hover { color:#80ff00; } .post p { margin:0 0. 0em; line-height:1.6em; } .post-footer { margin: 0em 0; color:#e5c0ff; text-transform:uppercase; letter-spacing:.1em; font: normal normal 77% Verdana, sans-serif; line-height: 1.4em; } .comment-link { margin-left:.6em; } .post img { padding:4px; border:1px solid #80FF00; } .post blockquote { margin:1em 20px; } .post blockquote p { margin:.75em 0; } /* Comments ----------------------------------------------- */ #comments h4 { margin:1em 0; font-weight: bold; line-height: 1.4em; text-transform:uppercase; letter-spacing:.2em; color: #e5c0ff; } #comments-block { margin:1em 0 1.5em; line-height:1.6em; } #comments-block .comment-author { margin:.5em 0; } #comments-block .comment-body { margin:.25em 0 0; } #comments-block .comment-footer { margin:-.25em 0 2em; line-height: 1.4em; text-transform:uppercase; letter-spacing:.1em; } #comments-block .comment-body p { margin:0 0 .75em; } .deleted-comment { font-style:italic; color:gray; } #blog-pager-newer-link { float: left; } #blog-pager-older-link { float: right; } #blog-pager { text-align: center; } .feed-links { clear: both; line-height: 2.5em; } /* Sidebar Content ----------------------------------------------- */ .sidebar { color: #FFFFFF; line-height: 1.5em; } .sidebar ul { list-style:none; margin:0 0 0; padding:0 0 0; } .sidebar li {align: left margin:0; padding-top:0; padding-right:0; padding-bottom:.25em; padding-left:15px; text-indent:-15px; line-height:1.5em; } .sidebar .widget, .main .widget { margin:0 0 1.5em; padding:0 0 1.5em; } .main .Blog { border-bottom-width: 0; } /* Profile ----------------------------------------------- */ .profile-img { float: right; margin-top: 0; margin-right: 50px; margin-bottom: 5px; margin-left: 0; padding: 10px; border: 1px solid #80FF00; } .profile-data { align: left margin:0; text-transform:uppercase; letter-spacing:.1em; font: &lt;font color="#FFFFFF" size="1"&gt;; font-weight: bold; line-height: 1.6em; } .profile-datablock { float: right; margin-left: 100px; } .profile-textblock { align: left margin-left: 100px; Font: &lt;font color="#FFFFFF" size="1"&gt; margin-left: 100px; line-height: 1.6em; } .profile-link { float: right; margin-left: 100px; font: &lt;font color="#FFFFFF" size="1"&gt;; text-transform: uppercase; letter-spacing: .1em; } /* Footer ----------------------------------------------- */ #footer 1{ width:400px; clear:both; margin:0 auto; font: &lt;font color="#E1C4FF" size="1"&gt;; padding-left:2px; line-height: 1.6em; text-transform:uppercase; letter-spacing:.1em; text-align: center; } #footer 2 { width:200px; clear:both; margin:0 auto; font: &lt;font color="#E1C4FF" size="1"&gt;; padding-right:1px; line-height: 1.6em; text-transform:uppercase; letter-spacing:.1em; text-align: center; } /** Page structure tweaks for layout editor wireframe */ body#layout #header { margin-left: 0px; margin-right: 0px; } --&gt;&lt;/style&gt; &lt;meta content="revealTrans(Duration=1.0,Transition=3)" http-equiv="Page-Enter" /&gt; &lt;meta content="revealTrans(Duration=2.0,Transition=2)" http-equiv="Page-Exit" /&gt; &lt;meta content="revealTrans(Duration=1.0,Transition=3)" http-equiv="Site-Enter" /&gt; &lt;meta content="revealTrans(Duration=2.0,Transition=2)" http-equiv="Site-Exit" /&gt; &lt;meta content="Spanish interpreter,translator,interpreter,California and federal court certified interpreter,federal court interpreter, [federal court interpreter] Los Angeles certified interpreter,California court interpreter,California court interpreter,[California court interpreter],Federal spanish interpreter,[Federal spanish interpreter] certified spanish interpreter, [certified spanish interpreter] Federal court certified spanish interpreter,[Federal court certified spanish interpreter] California certified spanish interpreter &amp;quot;California certified spanish interpreter&amp;quot; [California certified spanish interpreter] Los Angeles certified spanish interpreter,[Los Angeles certified spanish interpreter] Los Angeles federal spanish interpreter [Los Angeles federal spanish interpreter],Federal Court Certified Spanish Interpreter, California Federal Court Certified Spanish Interpreter, certified court interpreter, Spanish court interpreter,translating,interpreter,interpreting,interpretation,conference interpreter,conference interpreting,conference interpretation,simultaneous interpreter,simultaneous interpreting,simultaneous interpretation,consecutive interpreter,consecutive interpreting,Oz6F8Tkmp57T7vqDcvEty3FX8z0,consecutive interpretation," name="keywords" /&gt; &lt;meta content="Teri Szucs provides professional Spanish language interpreting and translation services for legal, medical, and other professional needs, including conferences, broadcasting, trials and depositions. Teri Szucs is federally certified and forms part of the select group of Spanish interpreters in Los Angeles who are also certified by the United States." name="description" /&gt; &lt;meta content="index,follow" name="robots" /&gt; &lt;meta content="1 days" name="revisit-after" /&gt; &lt;meta content="text/html; charset=utf-8" http-equiv="Content-Type" /&gt; &lt;script type="text/javascript"&gt;(function() { var a=window;function c(b){this.t={};this.tick=function(b,i,d){d=d!=void 0?d:(new Date).getTime();this.t[b]=[d,i]};this.tick("start",null,b)}var e=new c;a.jstiming={Timer:c,load:e};try{var g=null;a.chrome&amp;&amp;a.chrome.csi&amp;&amp;(g=Math.floor(a.chrome.csi().pageT));g==null&amp;&amp;a.gtbExternal&amp;&amp;(g=a.gtbExternal.pageT());g==null&amp;&amp;a.external&amp;&amp;(g=a.external.pageT);g&amp;&amp;(a.jstiming.pt=g)}catch(h){};a.tickAboveFold=function(b){var f=0;if(b.offsetParent){do f+=b.offsetTop;while(b=b.offsetParent)}b=f;b&lt;=750&amp;&amp;a.jstiming.load.tick("aft")};var j=!1;function k(){j||(j=!0,a.jstiming.load.tick("firstScrollTime"))}a.addEventListener?a.addEventListener("scroll",k,!1):a.attachEvent("onscroll",k); })();&lt;/script&gt; &lt;meta content="true" name="MSSmartTagsPreventParsing" /&gt; &lt;meta content="Microsoft FrontPage 6.0" name="generator" /&gt; &lt;!--[if IE]&gt; &lt;script&gt; (function() { var html5 = ("abbr,article,aside,audio,canvas,datalist,details," + "figure,footer,header,hgroup,mark,menu,meter,nav,output," + "progress,section,time,video").split(','); for (var i = 0; i &lt; html5.length; i++) { document.createElement(html5[i]); } try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} })(); &lt;/script&gt; &lt;![endif]--&gt; &lt;meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /&gt; &lt;script type="text/javascript"&gt;(function() { var a=window;function c(b){this.t={};this.tick=function(b,i,d){d=d!=void 0?d:(new Date).getTime();this.t[b]=[d,i]};this.tick("start",null,b)}var e=new c;a.jstiming={Timer:c,load:e};try{var g=null;a.chrome&amp;&amp;a.chrome.csi&amp;&amp;(g=Math.floor(a.chrome.csi().pageT));g==null&amp;&amp;a.gtbExternal&amp;&amp;(g=a.gtbExternal.pageT());g==null&amp;&amp;a.external&amp;&amp;(g=a.external.pageT);g&amp;&amp;(a.jstiming.pt=g)}catch(h){};a.tickAboveFold=function(b){var f=0;if(b.offsetParent){do f+=b.offsetTop;while(b=b.offsetParent)}b=f;b&lt;=750&amp;&amp;a.jstiming.load.tick("aft")};var j=!1;function k(){j||(j=!0,a.jstiming.load.tick("firstScrollTime"))}a.addEventListener?a.addEventListener("scroll",k,!1):a.attachEvent("onscroll",k); })();&lt;/script&gt; &lt;meta content="true" name="MSSmartTagsPreventParsing" /&gt; &lt;link href="http://federalcourtinterpreter.blogspot.com/favicon.ico" rel="icon" type="image/x-icon" /&gt; &lt;link href="http://federalcourtinterpreter.blogspot.com/" rel="canonical" /&gt; &lt;link rel="alternate" type="application/atom+xml" title="Federal and California Court Certified Spanish Interpreter - Atom" href="http://federalcourtinterpreter.blogspot.com/feeds/posts/default" /&gt; &lt;link rel="alternate" type="application/rss+xml" title="Federal and California Court Certified Spanish Interpreter - RSS" href="http://federalcourtinterpreter.blogspot.com/feeds/posts/default?alt=rss" /&gt; &lt;link rel="service.post" type="application/atom+xml" title="Federal and California Court Certified Spanish Interpreter - Atom" href="http://www.blogger.com/feeds/8126847722872063846/posts/default" /&gt; &lt;link rel="openid.server" href="http://www.blogger.com/openid-server.g" /&gt; &lt;!--[if IE]&gt; &lt;script&gt; (function() { var html5 = ("abbr,article,aside,audio,canvas,datalist,details," + "figure,footer,header,hgroup,mark,menu,meter,nav,output," + "progress,section,time,video").split(','); for (var i = 0; i &lt; html5.length; i++) { document.createElement(html5[i]); } try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} })(); &lt;/script&gt; &lt;![endif]--&gt; &lt;title&gt;template&lt;/title&gt; &lt;link rel="Stylesheet" type="text/css" href="Css/Style.css" &lt;style type="text/css"&gt; &lt;/head&gt; &lt;body style="text-align: center"&gt; &lt;blockquote&gt; &lt;blockquote&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p&gt;&lt;/p&gt; &lt;div id="outer-wrapper"&gt; &lt;div id="wrap2"&gt; &lt;div id="header-wrapper"&gt; &lt;div class="header section" id="header"&gt; &lt;div class="widget Header" id="Header1"&gt; &lt;div id="header-inner"&gt; &lt;div class="titlewrapper"&gt; &lt;h1 class="title"&gt;Federal and California Court Certified Spanish Interpreter &lt;/h1&gt;&lt;/div&gt; &lt;div class="descriptionwrapper"&gt; &lt;p class="description"&gt; &lt;span&gt;Teri Szucs has made her love of languages her career. My Interpretations offers professional interpretation services in California, out of state and abroad. Teri is federally certified and forms part of a select group of interpreters also certified by the United States Courts.&lt;/span&gt;&lt;/p&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; &lt;div id="navibar-wrapper"&gt; &lt;div class="navibar_section section" id="navibar_section"&gt; &lt;span class="Apple-style-span" style="color: rgb(0, 0, 0); font-family: Georgia, serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-align: -webkit-center; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; "&gt; &lt;div align="center"&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px"&gt;&amp;nbsp;&lt;/p&gt; &lt;/span&gt; &lt;span class="Apple-style-span" style="color: #80FF00; font-style: normal; font-variant: normal; font-weight: 700; letter-spacing: normal; line-height: normal; orphans: 2; text-align: -webkit-center; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px"&gt; &lt;/div&gt;&lt;/span&gt; &lt;div class="widget HTML" id="HTML12"&gt; &lt;div class="widget-content"&gt;&amp;nbsp;&lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;span class="widget-item-control"&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;/span&gt; &lt;div class="clear"&gt;&lt;/div&gt;&lt;/div&gt; &lt;/div&gt; &lt;body&gt; &lt;style&gt; &lt;!-- p { margin:0; padding:0; } --&gt; &lt;/style&gt; &lt;p&gt;&lt;/p&gt; &lt;p&gt;&lt;/p&gt;&lt;/div&gt; &lt;span class="Apple-style-span" style="color: rgb(0, 0, 0); font-family: Georgia, serif; font-size: 16px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: 2; text-align: -webkit-center; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-decorations-in-effect: none; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; "&gt; &lt;div align="center"&gt; &lt;table border="2" cellpadding="3" cellspacing="3" height="37" id="table9"&gt; &lt;tr&gt; &lt;td align="center" height="27"&gt; &lt;p align="center" style="margin-top: 0px; margin-bottom: 0px; "&gt; &lt;font&gt;&lt;i&gt; &lt;font class="Apple-style-span"&gt; &lt;font style="color: rgb(128, 255, 0); font-weight: 700; "&gt; &lt;u&gt; &lt;a href="http://myinterpretations.com/"&gt; &lt;font color="#80FF00"&gt;Home&lt;/font&gt;&lt;/a&gt;&lt;/u&gt;&lt;/font&gt;&lt;/font&gt;&lt;/i&gt;&lt;/font&gt;&lt;/td&gt; &lt;td height="27"&gt; &lt;p align="center" style="margin-top: 0px; margin-bottom: 0px; "&gt;&amp;nbsp;&lt;/td&gt; &lt;td height="27" style="color: rgb(102, 255, 153); "&gt; &lt;p align="center" style="margin-top: 0px; margin-bottom: 0px; "&gt;&amp;nbsp;&lt;/td&gt; &lt;td height="27"&gt; &lt;p style="margin-top: 0px; margin-bottom: 0px; "&gt; &lt;font&gt;&lt;i&gt; &lt;a class="navitabs" title="TooltipText3" href="new_page_1.htm"&gt; &lt;font style="color: rgb(128, 255, 0); font-weight: 700; "&gt; Contact Teri&lt;/font&gt;&lt;/a&gt;&lt;/i&gt;&lt;/font&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;/div&gt;&lt;/span&gt; &lt;/blockquote&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>It's a start, but there are a number of things that could be improved:</p>\n\n<ul>\n<li>Your CSS and JavaScript should almost always be in separate files.</li>\n<li>Most of your CSS looks okay, but you might find it easier to read if you indented the properties.</li>\n<li>The comments between CSS properties like <code>font-size/* */:/**/small;</code> aren't necessary.</li>\n<li>Your CSS font declaration, <code>font: &lt;font color=\"#E1C4FF\" size=\"1\"&gt;;</code> is incorrect. You should be using <code>color:#E1C4FF; font-size:14px;</code> (or whatever size you need).</li>\n<li>You really don't need most of those meta tags.</li>\n<li>Using inline CSS like <code>&lt;p style=\"margin-top: 0px; margin-bottom: 0px\"&gt;&amp;nbsp;&lt;/p&gt;</code> is almost always discouraged.</li>\n<li>Likewise, you shouldn't need all of those paragraph tags to create a break in your layout. Just set the margin or padding of whatever element you need.</li>\n<li>I've never seen anything like the commented out variable definitions before, but they aren't necessary. Also, explaining that bordercolor means border color is a little redundant. </li>\n<li>You have multiple script tags throughout the header. If you're going to have inline JavaScript, try limiting it to a single tag. </li>\n<li>I'm not sure why you have another body tag in the middle of your HTML, but you only need one. You can also get rid of the font tags and just apply a CSS class if it needs to be different.</li>\n<li>There is a lot of extra markup throughout, including a lot of empty tags. I haven't loaded this in a browser, but I suspect that you could do with a lot less and still get the same effect.</li>\n</ul>\n\n<p>It's great that you're coming here looking to learn. Code like this will only start you on the wrong path and it will be difficult to maintain in the long run, but kudos for seeking improvement. I honestly think you would benefit from relearning the basics of HTML and CSS to start and then eventually adding some JavaScript. Specifically, look for some articles on CSS layouts and best-practices. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T06:04:16.513", "Id": "7635", "Score": "2", "body": "Thank you. You answered a question on stackexchange.com, I wanted to thank you. Now I am self-taught and barely at that. I would like to know how much you would charge me for a lesson so I can apply your answer to my work in progress. Between what I know and what I need I would probably need an hour.Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T04:02:42.580", "Id": "5106", "ParentId": "5105", "Score": "7" } }, { "body": "<p>It looks like your CSS is dynamic, though I can't place the language on sight. Using one codebase for multiple sites is great, but giving a custom look and feel can be a challenge sometimes. In your scenario, every page request has to a) get the style data, b) evaluate the style data, and c) return the style data in the document, adding precious bits to the downstream. That's a lot of unnecessary overhead on both the front and the back end of the request.</p>\n\n<p>What I've done in the past is write the site's style definitions to an external file. They don't change their styles that often, but when they do, just regenerate the stylesheet. At the webroot (or some virtual directory somewhere) I have a folder titled 'sitespecific', with subfolders by site id. Each subfolder has a set structure of subfolder, containing assets specific to that site (images, scripts, css, etc). Then you have a default naming convention for certain files (site.css, header_banner.png, common.js, etc) so that they can easily be referenced:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" type=\"text/css\" href=\"/sitespecific/%siteid%/css/site.css\" /&gt;\n</code></pre>\n\n<p>It gets easy after that. One of the big advantages here is that the web server can now cache requests to the stylesheet. It's no longer dynamically generated on each request, removing the overhead. And housekeeping becomes a little easier. A site cancels, or doesn't make payments, you archive their sitespecific content to a zip file, off server, for the next six months. Flip a bit flag in the db to 'deactivate' them.</p>\n\n<p>The downside? You'll need a way to regenerate every site's stylesheet on command. If you make a change to core styles, or add some new class that requires definition, you have to have a way to push that change to all or your sites.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T22:50:07.883", "Id": "7659", "Score": "0", "body": "Thank you, I am a newby, just learning how to go from blog posts to writing from scratch, in other words, over my head. I have tried to separate the stylesheet and link it using <link... but nothing happens, the new page is white and not styled. Could you dumb down your answer a bit. I have five pages, they all work but they are hardly neat programming." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T12:47:12.377", "Id": "5113", "ParentId": "5105", "Score": "2" } }, { "body": "<p>It appears most of it is location independent and over scoped. For example:</p>\n\n<pre><code>.post h3 {\n\n}\n</code></pre>\n\n<p>I would suggest doing this. It follows B.E.M naming conventions and will be easier for you to read.</p>\n\n<pre><code>.post\n{\n\n}\n\n.post__title\n{\n\n}\n</code></pre>\n\n<p>Remember, think small. Make everything reusable. Skin it with conjoining classes. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-09T05:01:21.270", "Id": "25969", "ParentId": "5105", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T03:00:04.130", "Id": "5105", "Score": "3", "Tags": [ "optimization", "beginner", "html", "css" ], "Title": "Personal home page for a court interpreter" }
5105
<p>What follows is the first almost useful C program I've successfully written since an Intro to Programming class in college. I'm hoping to slowly maybe work my way up to Objective-C/Cocoa development, but figured I'd start by re-teaching myself the basics. I write PHP for a living, so some things, particularly pointers, are kind of tough to get my head around.</p> <p>The below is my attempt at implementing the standard <a href="http://en.wikipedia.org/wiki/Tripcode#Description_of_the_algorithm" rel="nofollow">tripcode algorithm</a>. Here are some particular areas for which I'd like some (ugh) pointers:</p> <ul> <li>There's one compiler warning I couldn't get rid of. The line <code>char *tripped = tripify(argv[x]);</code> in the <code>main</code> function causes "Passing argument 1 of 'tripify' discards qualifiers from pointer target type." What does this mean? I'm guessing maybe it means that <code>argv[x]</code> is a value, instead of a pointer to a value; but if that's the case, why does the code work anyway?</li> <li>Does the <code>static</code> keyword do what I think it does - not initialize the variable on successive function calls, but just reuses the previous value? This is what <code>static</code> does in PHP, but I'm not sure if it's analogous.</li> <li>Is there a better way to do the bit about replacing characters in the salt than how I did it? That bit strikes me as very awkward. Is there an equivalent of PHP's <code>strtr()</code> lurking about somewhere?</li> <li>The actual tripcode algorithm is not very secure. It's a <s>bug</s> feature of the algorithm that I'm well aware of and that's not what I'm asking about here.</li> </ul> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; // crypt() #include &lt;string.h&gt; // strcat(), strncpy() #include &lt;stdlib.h&gt; // calloc() char *tripify (char *code) { char *saltprep = calloc(255, sizeof(char)); // Set saltprep to the code appended with "H.." strcat(saltprep, code); strcat(saltprep, "H.."); // Get the second and third chars of the saltprep to use as salt char *salt = calloc(2, sizeof(char)); strncpy(salt, saltprep + 1, 2); // Replace certain characters in the salt with a corresponding letter static char saltreplacefrom[13] = ":;&lt;=&gt;?@[\\]^_`"; static char saltreplaceto[13] = "ABCDEFGabcdef"; for (char replacex = 0; replacex &lt; 13; replacex++) { if (salt[0] == saltreplacefrom[replacex]) { salt[0] = saltreplaceto[replacex]; } if (salt[1] == saltreplacefrom[replacex]) { salt[1] = saltreplaceto[replacex]; } } // Crypt the code with the salt char *crypted = crypt(code, salt); // Get the last ten characters of the crypted code char *crypted_trimmed = calloc(10, sizeof(char)); strncpy(crypted_trimmed, crypted + 3, 10); // Return return crypted_trimmed; } int main (int argc, const char* argv[]) { if (argc &gt; 1) { for (int x = 1; x &lt; argc; x++) { // Get tripcoded value char *tripped = tripify(argv[x]); // Print input followed by tripcoded value printf("%s: %s\n", argv[x], tripped); } } return 0; } </code></pre>
[]
[ { "body": "<blockquote>\n <p>There's one compiler warning I couldn't get rid of. The line char *tripped = tripify(argv[x]);</p>\n</blockquote>\n\n<p>This means the type you are passing is more constrained then type being used in the function.<br>\nLooking at the types we have:</p>\n\n<ul>\n<li>const char* argv[].</li>\n</ul>\n\n<p>This when you do argv[x] the type is:</p>\n\n<ul>\n<li>const char* argv_x</li>\n</ul>\n\n<p>Notice the const. If we now look at the type of the function:</p>\n\n<ul>\n<li>char *tripify (char *code)</li>\n</ul>\n\n<p>Notice the parameter here does not have a const on it. So you have a pointer where you are not allowed to change any of the characters (probably because they are in private protected memory and trying to change them is going to cause a seg fault). You are passing this to a function that does not promises not to change the values (if it does some platforms will crash (while others it will work happily)).</p>\n\n<p>You have two options:</p>\n\n<p>1) Make a copy of the string before passing (remember to clean up afterwords).</p>\n\n<pre><code>tmp = strdup(argv[x]);\ntripify(tmp);\nfree(tmp);\n</code></pre>\n\n<p>2) Change the type of the function:</p>\n\n<pre><code>char *tripify (const char *code)\n// Note: If your old code does actually change the value of code then you\n// now need to make a copy internally so it can still be mutated.\n</code></pre>\n\n<blockquote>\n <p>Does the static keyword do what I think it does</p>\n</blockquote>\n\n<p>Yes. Unfortunately static keyword is overloaded. So let me be specific. When static is used in a function context (like above) it means the variable has a longevity beyond the end of the function and will maintain its state between calls.</p>\n\n<p>Note. Since both your static variables are read only you should probably make them const. This will prevent accidents. Also do not specify an exact length for the arrays. By leaving them blank the compiler will calculate the correct size this will help in the long run if these arrays are ever modified. (Note they should have been 14 anyway. When you use a string \"Bla\" the compiler is already adding a null terminator { 'B', 'l', 'a', '\\0'} to the string that you forgot to compensate for)</p>\n\n<pre><code>static const char saltreplacefrom[] = \":;&lt;=&gt;?@[\\\\]^_`\";\nstatic const char saltreplaceto[] = \"ABCDEFGabcdef\";\n</code></pre>\n\n<blockquote>\n <p>Is there a better way to do the bit about replacing characters in the salt than how I did it? That bit strikes me as very awkward. Is there an equivalent of PHP's strtr() lurking about somewhere?</p>\n</blockquote>\n\n<p>Yes. C contains all the <a href=\"http://www.edcc.edu/faculty/paul.bladek/c_string_functions.htm\" rel=\"nofollow\">C-String manipulation functions</a> you want (including strstr()). They are in the header file &lt;string.h&gt;</p>\n\n<p>As a final comment I find your code very dense (and the comments meaningless). White space is your friend spread the code out to make it readable. Add comments that explain what you are doing but eching the code is not worth the effort the code is more precise and is reasonable (explain why and overall technique not a line by line).</p>\n\n<h3>Sorry: Here is strtr()</h3>\n\n<pre><code>char* strtr(char const* s, char const* in, char const* out)\n{\n char swaper[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,\n 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F,\n 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,\n 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F,\n 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F,\n 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,\n 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F,\n 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F,\n 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8A, 0x8B, 0x8C, 0x8D, 0x8E, 0x8F,\n 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA7, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF,\n 0xB0, 0xB1, 0xB2, 0xB3, 0xB4, 0xB5, 0xB6, 0xB7, 0xB8, 0xB9, 0xBA, 0xBB, 0xBC, 0xBD, 0xBE, 0xBF,\n 0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7, 0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF,\n 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF,\n 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF,\n 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF };\n\n\n // The swapper array is set up so that swapper['a'] returns 'a' etc.\n // So by default it is the null operation\n\n // This is to add the in/out data into the swapper array.\n // The smallest string will cause the loop to exit.\n for(;*in &amp;&amp; *out; ++in, ++out)\n {\n swaper[*in] = *out;\n }\n\n // Create a duplicate of the array.\n // The php version generates a new string (so this does aswell).\n char* result = strdup(s);\n\n // loop over the string and swap each element.\n // Most of the time the swap will be null operation unless the\n // above loop has changed the default value.\n for(char* loop = result;*loop;++loop)\n {\n *result = swaper[*result];\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T03:39:54.553", "Id": "7664", "Score": "0", "body": "Thanks, that was pretty much the answer I was looking for. I guess I need to keep a sharper eye out on the scope of my variables. One note, though: \"Yes. C contains all the C-String manipulation functions you want (including strstr()). They are in the header file <string.h>\" -- I'm afraid I wasn't making a typo when asking for [strtr](http://jp.php.net/strtr)()… strstr() isn't quite what I'm looking for. I suppose I'm just spoiled by PHP's ridiculous selection of string manipulation functions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T16:21:57.027", "Id": "5117", "ParentId": "5110", "Score": "3" } } ]
{ "AcceptedAnswerId": "5117", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T11:16:20.370", "Id": "5110", "Score": "3", "Tags": [ "c" ], "Title": "Tripcode encoding" }
5110
<p>So this was inspired by: <a href="https://codereview.stackexchange.com/questions/1760/whats-your-opinion-on-a-throw-method">this question</a> But doesn't actually answer it: What do you think of:</p> <pre><code>public class Case&lt;TRes&gt; { public Case(bool condition, Func&lt;TRes&gt; result) { Condition = condition; Result = result; } public bool Condition {get; private set;} public Func&lt;TRes&gt; Result { get; private set; } public static Case&lt;TRes&gt; Default(Func&lt;TRes&gt; value) { return new Case&lt;TRes&gt;(true, value); } } public static class Logic { public static T Match&lt;T&gt; (params Case&lt;T&gt;[] cases) { return cases.First(c =&gt; c.Condition).Result(); } } </code></pre> <p>Which you could invoke:</p> <pre><code>int i = Logic.Match ( new Case&lt;int&gt;(IsCloudy(skyImage), () =&gt; { ChangeWeatherIcon(Icons.Clouds); return 13; }), new Case&lt;int&gt;(a &lt; b, () =&gt; a), Case&lt;int&gt;.Default(() =&gt; {throw new Exception(); }) ); </code></pre> <p>it's purpose isn't quiet to emulate F#'s Match. (Because F# match doens't actually take conditions, it is a stuctural/pattern match) So really its kind of like the trinary operator, meets the nonOrdinal Select statment.</p> <p>Anyone got any idea's on how to make it work cleaner? Maybe getting a way to get rid of the new's and the brackets</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T14:04:47.433", "Id": "7639", "Score": "0", "body": "If we swap Func(T) for T, we get rid of the brackets etc, at the expense of nolonger being able to specify things to be done. (so it would be more like the trinary operator than a If)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T18:46:16.157", "Id": "7694", "Score": "0", "body": "You might be interested in reading [this blog post](http://community.bartdesmet.net/blogs/bart/archive/2008/04/11/pattern-matching-in-c-part-5.aspx) which has been doing something similar. It uses expressions and analyzes them to perform the matching. It's more or less the approach I had in mind. Take a look." } ]
[ { "body": "<p>To be honest, it's pretty much impossible to do elegant pattern matching in a language that doesn't support it (e.g., C#). The problem with what you've written there is it's <em>more</em> complicated than the equivalent if-then-else chain:</p>\n\n<pre><code>if (IsCloudy(skyImage)) {\n ChangeWeatherIcon(Icons.Clouds);\n return 13;\n}\nif (a &lt; b) {\n throw new Exception();\n}\n</code></pre>\n\n<p>Now, I would dearly love to see some later version of C# adopt algebraic data types (a la F#) with pattern matching, but until then I very much doubt you'll be able to do better than if-then-else chains.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T11:15:30.447", "Id": "7680", "Score": "0", "body": "I'm not sure if you realise, but your if/else change is not (at all) equivelent.\nEquivelent is:\n`int i;\nif (IsCloudy(skyImage)\n{\n ChangeWeatherIcon(Icons.Clouds);\n i = 13;\n}\nelse if (a < b)\n i= a;\nelse\n throw new Exception();`\n\nIt would be alot nicer spread over multiple lines" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T23:12:17.463", "Id": "7718", "Score": "1", "body": "You're right, but - meh - that's beside my point, which is that in attempting to do something more elegant than if-then-elses, you've made your code *harder* to read." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T03:01:15.207", "Id": "5128", "ParentId": "5115", "Score": "1" } }, { "body": "<p>I generally agree with Rafe: it's not worth trying to do this in C# for the <em>general</em> case. Using expressions, etc, simply don't cut it, IMHO pattern matching is something that must be built into the language (or use a malleable language like Lisp). The main point of pattern matching is that it's exhaustive (or at least you get a warning if it's not), and therefore total. If you can't guarantee that, then you don't gain anything.</p>\n\n<p>However, I do think it's fruitful to use pattern matching for <em>specific</em> cases. For example, in <a href=\"https://github.com/fsharp/fsharpx\" rel=\"nofollow\">FSharpx</a> we have pattern matching for C# on <a href=\"https://github.com/fsharp/fsharpx/blob/master/tests/FSharpx.CSharpTests/OptionTests.cs\" rel=\"nofollow\">options</a>, <a href=\"https://github.com/fsharp/fsharpx/blob/master/tests/FSharpx.CSharpTests/ListTests.cs\" rel=\"nofollow\">lists</a> and <a href=\"https://github.com/fsharp/fsharpx/blob/master/tests/FSharpx.CSharpTests/ChoiceTests.cs\" rel=\"nofollow\">choices</a> (i.e. anonymous discriminated unions).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T01:21:40.957", "Id": "5188", "ParentId": "5115", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T14:02:43.630", "Id": "5115", "Score": "3", "Tags": [ "c#", "f#" ], "Title": "Using a Function to emulate F# Match in C#" }
5115
<p>I'm working on an android application, but this is basically plain 'ole java. </p> <p>The aim is to do the right thing and not repeat myself.</p> <pre><code>public enum Datafile { ACTIVITIES() { @Override public String filepath() { return "activities.yaml"; } }, OPEN_LOOPS() { @Override public String filepath() { return "open_loops.yaml"; } }; public abstract String filepath(); } </code></pre> <p>Later on, when I want to edit the file I try this</p> <pre><code>File file = getDataFile(Datafile.OPEN_LOOPS); </code></pre> <p>Which calls this...</p> <pre><code>private File getDataFile(Datafile datafile) { File file = null; String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath(); file = new File(baseDir + "/" + datafile.filepath()); return file; } </code></pre> <p>Points for a better name for the enum and good advice regarding who responsibility for the getFileData method (currently all this code is in an Activity) really lies (a new class).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T07:07:18.473", "Id": "7671", "Score": "0", "body": "where is/was your Datafile enum used, other than in getDataFile ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T07:58:33.377", "Id": "7809", "Score": "0", "body": "Sorry, only just read your comment David, it is only used in getDataFile." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T08:06:32.727", "Id": "7811", "Score": "0", "body": "Ok, thanks, then I can +1 Eric Karl's answer :)" } ]
[ { "body": "<p>Enum are a good way to do this in my opinion if this is really static.</p>\n\n<p>Might I suggest you do:</p>\n\n<pre><code>public enum Datafile {\n ACTIVITIES(\"activities.yaml\"),\n OPEN_LOOPS(\"open_loops.yaml\");\n\nprivate String filepath;\n\nprivate Datafile(String filepath) {\n this.filepath = filepath;\n}\n\npublic String getFilepath() {\n return filepath;\n}\n</code></pre>\n\n<p>This is a bit more readable than the overriden methods in each declaration, especially with long enums.</p>\n\n<p>If the values of the filepaths are subject to changes from time to time. I suggest using a properties file. These can be reloaded without recompiling you package, meaning non-developers could maintain them. That is useful in some team setups.</p>\n\n<p>EDIT:\nFor properties, I suggest you read the java properties tutorial: <a href=\"http://download.oracle.com/javase/tutorial/essential/environment/properties.html\">http://download.oracle.com/javase/tutorial/essential/environment/properties.html</a>. There are also a lot of already well written tutorials about them and I could never hope to match their quality here. Also, never having worked on Android, I do not know if google has provided something that is more user friendly.</p>\n\n<p>For small applications, I would go for enums personally, as they are very easy to manage and usually do the job pretty well.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T18:56:02.570", "Id": "7645", "Score": "0", "body": "Thanks, that is more readable. Can you talk a little more about using a properties file, newb here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T22:10:51.433", "Id": "7658", "Score": "0", "body": "I have updated my answer with a link to the properties page of the java tutorial in the hope you find it helpful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T18:48:35.663", "Id": "5120", "ParentId": "5118", "Score": "14" } }, { "body": "<p>If it is truly static, then yes, the enum is probably just fine. However, it's not very flexible. What if your path changes? Change the enum, recompile, and redistribute? Youch!</p>\n\n<p>Or, you can use an XML file as a config. Change? Change it in the XML file and distribute. Smaller file transfers, among other benefits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T08:02:28.130", "Id": "7810", "Score": "0", "body": "I'm leaning toward this answer with regard best-practice. In pratice, the app is only running (i use the term 'run' loosely) in debug mode on my own phone but in the future it couldn't be reasonably redistributed without a config file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T21:09:03.643", "Id": "8103", "Score": "0", "body": "if you code it in javascript you won't have to recompile it ever. what if the file is not needed any more? xml won't fix that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T10:18:36.377", "Id": "5134", "ParentId": "5118", "Score": "5" } }, { "body": "<p>I shot myself in the foot several times when I hard-coded file names etc. </p>\n\n<p>Now I put such \"static\" data usually in property files. That way it can be injected easily, too, e.g. using Guice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T13:11:27.157", "Id": "5168", "ParentId": "5118", "Score": "5" } } ]
{ "AcceptedAnswerId": "5134", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T17:24:54.030", "Id": "5118", "Score": "6", "Tags": [ "java", "android" ], "Title": "Is using java enums to store filepaths good practice" }
5118
<pre><code>class HtmlLogger:ILogger,IDisposable { private System.IO.StreamWriter _file; private bool _disposed; public HtmlLogger() { _disposed = false; _file = new StreamWriter(@"somepath"); _file.Write("&lt;HTML&gt;&lt;BODY&gt;"); } public void Log(string message) { _file.Write("&lt;DIV&gt;{0}&lt;/DIV&gt;", message); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (_file != null) { _file.Write("&lt;/BODY&gt;&lt;/HTML&gt;"); _file.Flush(); _file.Dispose(); } } _file = null; _disposed = true; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T02:41:30.677", "Id": "7728", "Score": "0", "body": "You need to encode messages using HTMLEncode or some sort of message encoding to the HTML format i.e. encode <,>,/,\",',& and related symbols. There are already some methods in .NET actually in System.Web namespace" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T03:33:15.343", "Id": "7729", "Score": "0", "body": "You can use simply Base64 encoding to write log with, and later, you can use javascript in HTML to process DIV nodes as Base64 strings and decode them inline to show the user correct log messages, for example, using jQuery and Base64 plugin." } ]
[ { "body": "<p>In my opinion, you should do anything in <code>Dispose</code> except closing Objects.\nMaybe the user of your Library doesn't call <code>Dispose</code> and just sets the reference null. The closing Tags will never be written, but the starttags would. So it would be an invalid XML file, which is the bad behavior in my opinion.</p>\n\n<p>I would implement a Method for an explicit save, so the class user can save when ever he wants, and can even continue logging after the save. Therefore I also would use <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx\" rel=\"nofollow\">XMLDocument</a>, so I don't have to deal with the correctness of the XML and the File saving.</p>\n\n<pre><code>class HtmlLogger:ILogger,IDisposable \n{\n private System.IO.StreamWriter _file;\n private bool _disposed;\n\n public HtmlLogger()\n {\n _disposed = false;\n _file = new StreamWriter(@\"somepath\");\n _file.Write(\"&lt;HTML&gt;&lt;BODY&gt;\");\n }\n\n ~HtmlLogger{\n Dispose(false);\n }\n\n public void Log(string message)\n {\n _file.Write(\"&lt;DIV&gt;{0}&lt;/DIV&gt;\", message);\n }\n\n public void Dispose()\n {\n Dispose(true);\n }\n\n private void Dispose(bool disposing){\n if(_disposed)\n return;\n\n if(disposing){\n _disposed=true;\n }\n\n if(file != null)\n {\n _file.Flush();\n _file.Close();\n _file= null;\n }\n }\n\n protected virtual void Save()\n {\n if (_file != null)\n {\n _file.Write(\"&lt;/BODY&gt;&lt;/HTML&gt;\");\n _file.Flush();\n }\n }\n }\n}\n</code></pre>\n\n<ol>\n<li>I would add a destructor and flush/close the file in any way, just to be shure, that other Programs can open it again (if it is correct XML then) and no references to the file are stored.</li>\n<li><p>What happens to the XML if somebody calls:</p>\n\n<pre><code>Log(\"&lt;SuperMessage&gt;\");\nLog(\"Ü\");\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T02:40:30.587", "Id": "7727", "Score": "0", "body": "Agreed, you need to encode messages using HTMLEncode or some sort of message encoding to the HTML format i.e. encode <,>,/,\",',& and related symbols" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T20:26:07.103", "Id": "5121", "ParentId": "5119", "Score": "1" } }, { "body": "<p>I think it is good idea to use existing classes, I've already made some of the refacorings along with some design choices. For additional info, please read this book:</p>\n\n<ul>\n<li><a href=\"http://rads.stackoverflow.com/amzn/click/0201633612\" rel=\"nofollow\">Design Patterns</a></li>\n</ul>\n\n<p><strong>EDIT:</strong> I think that explicit command calls (open log, write something and close it) before dispose the log object are much more readable, easy to understand and maintain later, than impementing the dispose pattern in another object (so you will get at least two objects to control lifecycle: custom class, and <code>StreamWriter</code> class - that will break the Einstein rule, - it's just not good to control 2 objects, when you could simply control one). In particular, that is going to be true when the new contracts will be applied later to the code. Disposable pattern is to heavy for such simple task. Additionally, as an advantage of using one object to control, and - consequently, - very simplified logic, it's easier to control log writer object's lifetime. At second, simple class with a good and clead design can be extended easily to supprt for an additional logic and do will not likely contains any of the caveats in the future.</p>\n\n<pre><code>public interface IHTMLLogger\n{\n ILogWriter CreateHTMLLogWriter(string filePath);\n}\n\npublic interface ILogWriter : IDisposable\n{\n void OpenLog();\n void WriteLog(string message);\n void CloseLog();\n}\n\npublic class HtmlLogger : IHTMLLogger\n{\n public class HTMLLogWriter : StreamWriter, ILogWriter\n {\n public HTMLLogWriter(string filePath)\n : base(filePath)\n {\n }\n public void WriteLog(string message)\n {\n base.Write(string.Format(\"&lt;DIV&gt;{0}&lt;/DIV&gt;\", message));\n }\n public void OpenLog()\n {\n base.Write(\"&lt;HTML&gt;&lt;BODY&gt;\");\n }\n public void CloseLog()\n {\n base.Write(\"&lt;/BODY&gt;&lt;/HTML&gt;\");\n }\n }\n\n public ILogWriter CreateHTMLLogWriter(string filePath)\n {\n return new HTMLLogWriter(filePath);\n }\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> As you see, I can easily integrate new encoding logic to encode any string data:</p>\n\n<pre><code>public interface IHTMLEncoder\n{\n string Encode(string message);\n}\n\npublic interface IHTMLLogger\n{\n ILogWriter CreateHTMLLogWriter(string filePath);\n}\n\npublic interface ILogWriter : IDisposable\n{\n void OpenLog();\n void WriteLog(string message);\n void CloseLog();\n}\n\npublic class HtmlLogger : IHTMLLogger\n{\n public class HTMLEncoder : IHTMLEncoder\n {\n public string Encode(string message)\n {\n return Convert.ToBase64String(Encoding.UTF8.GetBytes(message.ToCharArray()));\n }\n }\n public class HTMLLogWriter : StreamWriter, ILogWriter\n {\n private IHTMLEncoder _encoder;\n public HTMLLogWriter(string filePath, IHTMLEncoder encoder)\n : base(filePath)\n {\n _encoder = encoder;\n }\n public void WriteLog(string message)\n {\n base.Write(string.Format(\"&lt;DIV&gt;{0}&lt;/DIV&gt;\", _encoder.Encode(message)));\n }\n public void OpenLog()\n {\n base.Write(\"&lt;HTML&gt;&lt;BODY&gt;\");\n }\n public void CloseLog()\n {\n base.Write(\"&lt;/BODY&gt;&lt;/HTML&gt;\");\n }\n } \n public ILogWriter CreateHTMLLogWriter(string filePath)\n {\n return new HTMLLogWriter(filePath, new HTMLEncoder());\n }\n}\n</code></pre>\n\n<p>Sample:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Configuration;\nusing System.Runtime.Serialization;\nusing System.Security.Permissions;\nusing System.IO;\nusing System.Diagnostics;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n private static IHTMLLogger logger = new HtmlLogger();\n private ILogWriter logWriter;\n\n public Form1()\n {\n InitializeComponent();\n }\n private void Form1_Load(object sender, EventArgs e)\n {\n logWriter = logger.CreateHTMLLogWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"html.log\"));\n logWriter.OpenLog();\n\n this.Location = UserSettings.Default.FormLocation;\n this.Size = UserSettings.Default.FormSize;\n this.textBox1.Text = UserSettings.Default.ProcessPath;\n }\n\n private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n {\n UserSettings.Default.FormLocation = this.Location;\n UserSettings.Default.FormSize = this.Size;\n UserSettings.Default.ProcessPath = this.textBox1.Text;\n UserSettings.Default.Save();\n\n logWriter.CloseLog();\n logWriter.Dispose();\n\n MessageBox.Show(File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, \"html.log\")));\n }\n\n private void textBox1_TextChanged(object sender, EventArgs e)\n {\n UserSettings.Default.ProcessPath = this.textBox1.Text;\n logWriter.WriteLog(this.textBox1.Text);\n }\n }\n\n [SettingsSerializeAs(SettingsSerializeAs.Xml)]\n [Serializable]\n public sealed class UserSettings : ApplicationSettingsBase\n {\n private const string FormLocationProperty = \"FormLocation\";\n private const string FormSizeProperty = \"FormSize\";\n private const string ProcessPathProperty = \"ProcessPath\";\n\n private UserSettings() { }\n\n private static UserSettings _defaultInstance = new UserSettings();\n\n public static UserSettings Default { get { return _defaultInstance; } }\n\n [UserScopedSetting()]\n [DefaultSettingValue(\"0, 0\")]\n public Point FormLocation\n {\n get { return (Point)(this[FormLocationProperty]); }\n set { this[FormLocationProperty] = value; }\n }\n\n [UserScopedSetting()]\n [DefaultSettingValue(\"300, 300\")]\n public Size FormSize\n {\n get { return (Size)this[FormSizeProperty]; }\n set { this[FormSizeProperty] = value; }\n }\n\n [UserScopedSetting]\n [DefaultSettingValue(\"\")]\n public string ProcessPath\n {\n get { return (string)this[ProcessPathProperty]; }\n set { this[ProcessPathProperty] = value; }\n }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T07:41:00.870", "Id": "5132", "ParentId": "5119", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T18:41:56.560", "Id": "5119", "Score": "4", "Tags": [ "c#", ".net", "stream", "logging" ], "Title": "Is calling file write in the dispose acceptable?" }
5119
<p>This simply pulls data from mysql and creates the html to be sent to the page.</p> <pre><code>class view_html extends database { function __construct($type) { parent::__construct(); switch ($type) { case "bookmraks": $this-&gt;bookmarks(); break; case "tweets": $this-&gt;tweets(); break; default: echo "Invalid View Type"; break; } } private function bookmarks() { $email = $_SESSION['email']; $query_return = database::query("SELECT * FROM bo WHERE email='$email' ORDER BY name ASC"); while ($ass_array = mysqli_fetch_assoc($query_return)) { $fav=$this-&gt;fav($ass_array['url']); echo "&lt;img name=\"bo_im\" class=\"c\" src=\"$fav\"/ onerror=\"i_bm_err(this)\"&gt;&lt;a target=\"_blank\" name = \"a1\" class = \"b\" href = \"$ass_array[url]\"&gt;$ass_array[name]&lt;/a&gt;"; } } private function tweets() { $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7"); $time = time(); while ($a = mysqli_fetch_assoc($query_return)) { echo "&lt;div class=\"Bb2b\"&gt;&lt;img class=\"a\" src=\"p/$a[email].jpg\" alt=\"\"/&gt;&lt;a class=\"a\" href=\"javascript:void(0)\"&gt;$a[fname] posted &lt;script type=\"text/javascript\"&gt;document.write(v0($a[time],$time))&lt;/script&gt;&lt;/a&gt;&lt;br/&gt;&lt;p class=\"c\"&gt;$a[message]&lt;/p&gt;&lt;/div&gt;"; } } private function fav($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if(preg_match('/(?P&lt;domain&gt;[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico'; } return false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T23:33:18.320", "Id": "7660", "Score": "0", "body": "Told you you'd be better asking here :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T16:07:06.073", "Id": "7767", "Score": "0", "body": "yep, i like the graph paper background" } ]
[ { "body": "<p>Replace all usages of direct Values.\n<br/>\nTry assiging values first to a named variable and then concating it, so its sustainable in the future like:</p>\n\n<pre><code>return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico'; \n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>$protocol = $pieces['scheme'];\n$domainName = $regs['domain'];\n$faviconName = . '/favicon.ico'; \n$favIconLink = $protocol. '://www.' . $domainName . $faviconName\nreturn $favIconLink;\n</code></pre>\n\n<p>This would make it reusable and readable for other developers, and it reduces comments ;-) Currently you have many of them </p>\n\n<pre><code>$fav=$this-&gt;fav($ass_array['url']);\n</code></pre>\n\n<p><br/>\nI love regex, but once written nobody understands it:</p>\n\n<pre><code>if(preg_match('/(?P&lt;domain&gt;[a-z0-9][a-z0-9\\-]{1,63}\\.[a-z\\.]{2,6})$/i', $domain, $regs)) \n</code></pre>\n\n<p>i would add a comment which explaines detailed what this regex is <strong>suppose</strong> to do. So if there is an Problem with the Regex everybody can check if the regex is doing it's job or if there is a problem in the expression.</p>\n\n<p>Throw an exception in your constructor, so the errormessage can be cought. Now the error Message is displayed in the frontcode.</p>\n\n<pre><code>function __construct($type)\n{\nparent::__construct(); \nswitch ($type) \n {\n case \"bookmraks\":\n $this-&gt;bookmarks();\n break;\n case \"tweets\":\n $this-&gt;tweets();\n break;\n default:\n throw new Exception('Invalid View Type');\n }\n}\n</code></pre>\n\n<p>Last but not least:</p>\n\n<p>try using \"'\" for strings, so its more readable and you make less errors by escaping not escaping closing, whatever</p>\n\n<pre><code> '&lt;div class=\"Bb2b\"&gt;&lt;img class=\"a\" src=\"p/$a[email].jpg\" alt=\"\"/&gt;&lt;a class=\"a\" href=\"javascript:void(0)\"&gt;$a[fname] posted &lt;script type=\"text/javascript\"&gt;document.write(v0($a[time],$time))&lt;/script&gt;&lt;/a&gt;&lt;br/&gt;&lt;p class=\"c\"&gt;$a[message]&lt;/p&gt;&lt;/div&gt;'\n</code></pre>\n\n<p>instead of :</p>\n\n<pre><code> \"&lt;div class=\\\"Bb2b\\\"&gt;&lt;img class=\\\"a\\\" src=\\\"p/$a[email].jpg\\\" alt=\\\"\\\"/&gt;&lt;a class=\\\"a\\\" href=\\\"javascript:void(0)\\\"&gt;$a[fname] posted &lt;script type=\\\"text/javascript\\\"&gt;document.write(v0($a[time],$time))&lt;/script&gt;&lt;/a&gt;&lt;br/&gt;&lt;p class=\\\"c\\\"&gt;$a[message]&lt;/p&gt;&lt;/div&gt;\"\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:19:44.020", "Id": "7647", "Score": "0", "body": "I'm reading line by line. (1) I use mysqli_real_escape_string() (note the i in mysql) in a parent class. Sorry this is not clear from my post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:20:50.463", "Id": "7648", "Score": "0", "body": "Oh sorry, i dind't saw it. -> Edited" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:21:18.603", "Id": "7649", "Score": "0", "body": "(2) I read on php.net I think that adding extra variables is not good practice...I think it is a tradoff for readability/maintainabilyt vs. performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:22:50.427", "Id": "7650", "Score": "0", "body": "not obvious...hard to know how much code to post. (3) Instead of comments I use a Readme, but yes perhaps I should comment more as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:23:12.330", "Id": "7651", "Score": "0", "body": "(2) as far as i know, the variables are altough assigned in the background to do the string concat." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:23:42.487", "Id": "7652", "Score": "0", "body": "(4) throw new Exception..O.K I will add this" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:25:43.293", "Id": "7653", "Score": "0", "body": "sorry again...regarding (1)...I do not need this b.c. this is not input from the user. Normally I used it but not in this case as their is not \"un-certain\" data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:26:51.450", "Id": "7654", "Score": "0", "body": "(5) Defenitley will update this to remove escapes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:28:51.073", "Id": "7656", "Score": "0", "body": "@(1), just wanted you to be safe :-)\nHappy that i could help, please tag as answer if so." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T21:16:07.380", "Id": "5123", "ParentId": "5122", "Score": "1" } }, { "body": "<p>I'd refactor this class into subclasses for bookmarks, favorites, and tweets. Then in each subclass I'd have a similiar API, maybe called render_HTML. Then I'd use the original class as a proxy for these subclasses. I'd also avoid sending the html directly from each class, instead return the html and either use a controller to set a variable equal to the html for your view page, or if you aren't using a mvc framework output the value of return_html directly in your view.</p>\n\n<p>Now we have OK separation of concerns (you could take this even farther and abstracting out your database access but we won't go that far here). Now you can also add new views to render rather easily without having to worry about breaking your view class, and you can do other things with those factored out classes down the road. </p>\n\n<p>Heres some psudo code of what i'm talking about: </p>\n\n<pre><code>class view_html extends database\n {\n function __construct($type){\n parent::__construct(); \n\n this-&gt;type = type;\n }\n\n function render_html(){\n case \"bookmraks\":\n $this-&gt;bookmarks-&gt;render_html();\n break;\n case \"tweets\":\n $this-&gt;tweets-&gt;render_html();\n break;\n default:\n echo \"Invalid View Type\";\n break;\n }\n }\n }\n\nclass bookmarks{\n public function render_html(){\n //query\n //generate html in loop\n\n return html;\n }\n} \n\nclass tweets{\n public function render_html(){\n //query\n //generate html in loop\n\n return html;\n }\n}\n\nclass fav{\n public function render_html(){\n public function render_html(){\n //query\n //generate html in loop\n\n return html;\n }\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T03:41:10.550", "Id": "8655", "Score": "0", "body": "it will take some time to incorporate..will update once I do...thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T13:48:08.387", "Id": "8666", "Score": "0", "body": "Glad I could help, I'll be happy to look at your updates as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T22:29:43.283", "Id": "5124", "ParentId": "5122", "Score": "0" } } ]
{ "AcceptedAnswerId": "5123", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T20:45:07.087", "Id": "5122", "Score": "2", "Tags": [ "php" ], "Title": "MVC Improvement - The View Module - 0 *" }
5122
<p>This class sends "tweet" data to the client in the form of a custom markup language. How can it be improved?</p> <p>It is used in Ajax call and in previous post people have suggested not to echo the result..but this is my primary means of communicating with the server via Ajax responseText.</p> <p>Also <code>&lt;tw_p&gt;</code> is used to denote a pass and is read by the client. The markup looks like this.</p> <p>field 1 | field 2 | field 3 | field 4 || field 1 | field 2 | field 3 | field 4 ||</p> <p>It is called like this - </p> <pre><code>new tweet(); </code></pre> <p>The client knows how render this into xhtml once it receives it.</p> <pre><code>/*tweet*/ class tweet extends post { function __construct() { parent::__construct(); $email=$_SESSION['email']; $flname=$_SESSION['name']; $message=$this-&gt;_protected_arr['f4b']; $time=time(); database::query("INSERT INTO tw VALUES ('$time','$flname','$message','$email')"); $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7"); $b=0; $c='&lt;tw_p&gt;'; while($a=mysqli_fetch_assoc($query_return)) { if($b==0) { $c = $c . $a['email'] . "|" . $a['fname'] . "|" . $a['time'] . "|" . $time . "|" . $a['message']; } else { $c = $c . "||" . $a['email'] . "|" . $a['fname'] . "|" . $a['time'] . "|" . $time . "|" . $a['message']; } $b++; } echo $c; } } </code></pre>
[]
[ { "body": "<p>So, this is the PHP that causes you to have your 'aml' processing <a href=\"https://codereview.stackexchange.com/questions/5939/collection-of-ajax-methods\">here</a>.</p>\n\n<p>I think people must have confused you by saying not to echo. You are correct, you do have to communicate by printing something out. The best way to communicate with Javascript is by using JSON. JSON stands for JavaScript Object Notation.</p>\n\n<p>You should also check for success or failure from the database query. Below is untested code (I have no idea what your database::query returns so my error check may not be appropriate):</p>\n\n<pre><code>$query_return = database::query(\"SELECT * FROM tw ORDER BY time DESC LIMIT 7\");\n\nif ($query_return === false)\n{\n echo json_encode(array('Success' =&gt; false));\n return;\n} \n\n$results = array('Data' =&gt; array(),\n 'Success' =&gt; true);\n\nwhile($row = mysqli_fetch_assoc($query_return))\n{ \n $results['Data'][] = $row;\n}\n\necho json_encode($results);\n</code></pre>\n\n<p>So now you will receive an array of rows from your database that your javascript code can deal with nicely. It will be a valid javascript object so you can check it with:</p>\n\n<pre><code>if (response.Success)\n{\n // Do stuff with response.Data here. Probably a loop over the results.\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T04:44:54.667", "Id": "9169", "Score": "0", "body": "I've seen the code in `class database`. The error check is fine; the query function is pretty much `return $db->query($sql);`, where `$db` is a mysqli object." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T03:11:23.720", "Id": "5955", "ParentId": "5125", "Score": "2" } }, { "body": "<p>I agree with @Paul's answer. Some additions below.</p>\n\n<ol>\n<li><p>Possible <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL injection</a>:</p>\n\n<pre><code>$email=$_SESSION['email'];\n$flname=$_SESSION['name'];\n$message=$this-&gt;_protected_arr['f4b'];\n$time=time();\ndatabase::query(\"INSERT INTO tw VALUES ('$time','$flname','$message','$email')\"); \n</code></pre>\n\n<p>If your <code>name</code> and <code>email</code> session variables are checked before you put them into the session and they could not contain any dangerous characters it's fine. If they could contain you should escape them. (Image a name with an <code>'</code>. It would broke the query.) Anyway, escaping is a good practice, it costs almost nothing and makes the code more reliable and safe. I would escape it.</p></li>\n<li><p>I would rewrite the while loop if you stay with the original code instead of JSON:</p>\n\n<pre><code>$first = true;\nwhile($row = mysqli_fetch_assoc($query_return)) { \n if (!$first) {\n $c .= \"||\";\n }\n $tw = $row['email'] . \"|\";\n $tw .= $row['fname'] . \"|\";\n $tw .= $row['time'] . \"|\";\n $tw .= $time . \"|\";\n $tw .= tw_escape($row['message']);\n $c .= $tw;\n first = false;\n}\n</code></pre>\n\n<p>The <code>$tw</code> variable removes some unnecessary code duplication. Changing the <code>$b</code> to a boolean (<code>$first</code>) makes is easier to read.</p></li>\n<li><p>You should escape at least the <code>message</code> (that's the <code>tw_escape</code> function) in case a message contains <code>|</code>. Consider escaping the <code>$row['fname']</code> too. Don't forget to unescape on the client side. Maybe JSON does it out-of-the-box.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T19:41:06.000", "Id": "9184", "Score": "0", "body": "I'm setting the SESSION variables in my PHP script...therefore I do not have to worry about their contents?...or do I?...I only worry about data coming from the user...Is this correct...are SESSION variables an issue b.c. they might be saved on a cookie on the client side?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T19:42:09.683", "Id": "9185", "Score": "0", "body": "Wow...you are correct...the loop is messy...I will fix this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T19:44:01.630", "Id": "9186", "Score": "0", "body": "I'm updatint | to <|> or similar to make it highly unique so I don't have to worry about escaping..nice catch." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T19:58:06.557", "Id": "9188", "Score": "0", "body": "and thank you for not telling me to use JSON" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T20:19:59.050", "Id": "9192", "Score": "0", "body": "About the SQL injection: I would escape them. It does not hurt and it makes your code more reliable and safe.\n AFAIK session data in PHP stored on the server-side, so the clients are not able to modify it. You should escape (and unescape on the client-side) the `<|>` too. It solves the problem once for all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T20:20:17.847", "Id": "9193", "Score": "0", "body": "Btw, what's the problem with JSON? :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-12T02:59:28.997", "Id": "9202", "Score": "1", "body": "@stack.user.0 JSON is the easiest way to pass data between PHP and Javascript. All you have to do is call the function json_encode. You won't get bugs with it like you could in your custom escaping code. When you receive it in your javascript code it is already a native javascript object rather than a string that you have to regexp. Tell me if you ever see the logic behind my advice, otherwise I give up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-15T02:23:40.300", "Id": "9317", "Score": "0", "body": "all data comes in on packets...these packets have data...that can be thought of as an array of bits...these bits can be thought of as characters, these character can be thought of as a strings....the strings...can be shaped into structure data via a language called markup...b.c. I have the time I am writing my own markup...but yea...if you don't have a few hundred hours to kill I would go with JSON...it is obviously a standard that works well is well understood and there is huge amount of support for it...One day I will use JSON but I just want to learn this way..b.c. I have the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-15T02:28:12.490", "Id": "9318", "Score": "1", "body": "I have no prolem with JSON...I just want to learn the mechanics of markup...parsing....etc..on a lower level..hence writing my own markup and parsers" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-11T09:40:08.030", "Id": "5958", "ParentId": "5125", "Score": "2" } } ]
{ "AcceptedAnswerId": "5958", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-02T23:59:28.927", "Id": "5125", "Score": "2", "Tags": [ "php", "php5" ], "Title": "class - tweet - 0 - to_do" }
5125
<p>I have an application that has a lot of very complex objects that in most cases I only need to access an id value and a name value from. I'd like to reduce the overhead of serializing these large objects to JSON. This is a simple function I created that takes an array of objects and returns an array of structures that contains only two keys, an id and a value. This also needs to be compatible with CF8 servers.</p> <p>I'd like to get some feedback on ways to make the code more expressive and any ways I can optimize this as well.</p> <pre><code>&lt;cffunction name="toKeyValuePairArray" returntype="Array" output="false" access="public"&gt; &lt;cfargument name="theArray" type="Array" required="true" hint="an array of objects" /&gt; &lt;cfargument name="idGetterFunctionName" type="string" /&gt; &lt;cfargument name="valueGetterFunctionName" type="string" /&gt; &lt;cfset var local = structNew() /&gt; &lt;cfset var retArray = [] /&gt; &lt;cfset var obj = {} /&gt; &lt;cfloop array="#arguments.theArray#" index="local.theComponent"&gt; &lt;cfset obj = {} /&gt; &lt;cftry&gt; &lt;cfinvoke component="#local.theComponent#" method="#arguments.idGetterFunctionName#" returnvariable="local.id" /&gt; &lt;cfinvoke component="#local.theComponent#" method="#arguments.valueGetterFunctionName#" returnvariable="local.value" /&gt; &lt;cfset obj.id = local.id /&gt; &lt;cfset obj.value = local.id /&gt; &lt;cfset arrayAppend(retArray,obj) /&gt; &lt;cfcatch&gt;&lt;/cfcatch&gt; &lt;/cftry&gt; &lt;/cfloop&gt; &lt;cfreturn retArray /&gt; &lt;/cffunction&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T06:59:29.877", "Id": "7670", "Score": "0", "body": "I do not see the code to review. To ask a question, there is a http://stackoverflow.com site" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T10:23:56.810", "Id": "7676", "Score": "0", "body": "Thats strange, i can see the code from my iPhone right now. I'll take another look when i get to my computer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T11:57:49.260", "Id": "7681", "Score": "0", "body": "@ArturMustafin I just checked on my computer too and it looks OK. Is this not what you are seeing? [http://ow.ly/i/irvj](http://ow.ly/i/irvj)" } ]
[ { "body": "<p>Ryan,</p>\n\n<p>Here's how I would do it. Since you're making something backwards compatible with CF8, which does not explicitly have the 'Local' scope, and you've already declared it via the 'var', then we'll put all other function local variables within this struct, and only return that which is needed.</p>\n\n<pre><code>&lt;!--- \n * FUNCTION toKeyValuePairArray\n * Method to create a simple object reference array to reduce overhead and improve performance.\n * This assumes that your objects have Getters for their primary properties.\n * (no need to instantiate every object, every time, when all you need is a number or a name)\n * \n * @theArray (array) - an array of objects\n * @idGetterFunctionName - Function name for getter function that pulls the object's id\n * @valueGetterFunctionName - Function name for getter function that pulls the object's name\n ---&gt;\n&lt;cffunction name=\"ToKeyValuePairArray\" returntype=\"array\" output=\"false\" access=\"public\"&gt;\n &lt;cfargument name=\"theArray\" type=\"Array\" required=\"true\" hint=\"an array of objects\" /&gt;\n &lt;cfargument name=\"idGetterFunctionName\" required=\"true\" type=\"string\" hint=\"Function name for getter function that pulls the object's id\" /&gt;\n &lt;cfargument name=\"valueGetterFunctionName\" required=\"true\" type=\"string\" hint=\"Function name for getter function that pulls the object's name\" /&gt;\n\n &lt;cfset var LOCAL = StructNew() /&gt;\n &lt;cfset LOCAL.retArray = ArrayNew(1) /&gt;\n\n &lt;cfloop array=\"#ARGUMENTS.theArray#\" index=\"LOCAL.theComponent\"&gt;\n &lt;cfset LOCAL.tmpObjVals = StructNew() /&gt;\n &lt;cftry&gt;\n &lt;cfinvoke component=\"#LOCAL.theComponent#\" method=\"#ARGUMENTS.idGetterFunctionName#\" returnvariable=\"LOCAL.id\" /&gt;\n &lt;cfinvoke component=\"#LOCAL.theComponent#\" method=\"#ARGUMENTS.valueGetterFunctionName#\" returnvariable=\"LOCAL.value\" /&gt;\n\n &lt;cfset LOCAL.tmpObjVals[\"id\"] = LOCAL.id /&gt;\n &lt;cfset LOCAL.tmpObjVals[\"value\"] = LOCAL.value /&gt;\n\n &lt;cfset ArrayAppend(LOCAL.retArray,Duplicate(LOCAL.tmpObjVals)) /&gt;\n &lt;cfcatch&gt;&lt;!--- Empty Catch ---&gt;&lt;/cfcatch&gt;\n &lt;/cftry&gt;\n &lt;/cfloop&gt; \n\n &lt;cfreturn LOCAL.retArray /&gt;\n&lt;/cffunction&gt;\n</code></pre>\n\n<p>Since we 'var' one core variable (creating our own function local scope, so to speak) we no longer have to declare the temp object at the top of the method, since you reset it at the top of each loop iteration anyway. I also standardized your struct and array initialization across the method, to maintain that backward compatibility (and standardization of form is just good practice).</p>\n\n<p>You aren't really doing any additional processing on the return variables from your 'getter' calls, so I applied them directly to the tempObj, so we don't create any unnecessary variables. You don't have to upper case scope names. I do that to make them stand out better when looking at code. I did uppercase the function names. This is just something I got from college: begin uppercase the function calls, and begin lowercase on variable names, then camel case the remainder.</p>\n\n<p>NOTE: Adjusted some of my code, to work in some of Dan's (good) suggestions. I understand the 'try/catch' conceptually, but I did make them required args so it would throw errors if you didn't have them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T15:21:19.303", "Id": "7761", "Score": "0", "body": "Thanks Steve, some good stuff here. Personally I use local. if I feel that the number of vars I'd have to declare on the top of my function would hinder its readability. Its really just a \"feel\" thing for me. I just don't like having to type local. all the time if I don't have to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T14:32:15.083", "Id": "8004", "Score": "0", "body": "Ryan, call me Cutter. I adjusted my code example, adding back in the lines where you set the cfinvoke returns to the temp object keys. The notation used will preserve the casing of those key names when CF serializes the object into JSON. Unfortunately you can't use that notation in the returnvariable attribute, so you have to jump a few hoops." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T14:11:06.710", "Id": "5140", "ParentId": "5127", "Score": "2" } }, { "body": "<p>A few things:</p>\n\n<ol>\n<li><p>What's the purpose of the try/catch other than hiding an error? Is it understood that you may have objects that don't have the proper ID and Value functions? If so, should those be flagged somehow in your return?</p></li>\n<li><p>I would change your <code>obj</code> variable name, so as not to represent that the returned structures are objects, since they're not :). Perhaps <code>objValues</code> instead?</p></li>\n<li><p>I would change your final <code>arrayAppend</code> to use the <code>Duplicate</code> function to prevent reference issues.</p>\n\n<p><code>&lt;cfset arrayAppend(retArray,Duplicate(obj)) /&gt;</code></p></li>\n</ol>\n\n<p>Other than that, I don't see any issues with the code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T16:01:45.220", "Id": "7687", "Score": "0", "body": "Basically the reason for the try/catch is that I'm going for a completely silent fail, i'll handle any error conditions in the JavaScript function that handles the serialized json response." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T16:04:44.090", "Id": "7688", "Score": "0", "body": "Totally makes sense." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T14:16:28.263", "Id": "5141", "ParentId": "5127", "Score": "2" } }, { "body": "<p>I'll ask the obvious/dumb question. Can you access this information from a database?</p>\n\n<p>A simple query for id and name would be easier to work with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T21:01:05.537", "Id": "7797", "Score": "0", "body": "Bascially this function is a way to standardize array's of objects that may have different column names for the value and id. So in our database schemas ID's are typically named accountID, addressID, etc. Using this function I can pass in an array of any type of object and get back a standardized structure serialized into JSON. Then in my JavaScript I can count on the objects having a id and value property and I don't have to write anything specific to a certian type of object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T15:32:10.807", "Id": "7831", "Score": "0", "body": "Ah, I see what you're doing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T18:52:50.630", "Id": "5176", "ParentId": "5127", "Score": "1" } } ]
{ "AcceptedAnswerId": "5140", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T02:28:23.343", "Id": "5127", "Score": "2", "Tags": [ "coldfusion", "cfml" ], "Title": "Simple function to turn array of objects to array of key value pairs" }
5127
<p>Now I have a bunch of these methods ( you can tell how ugly it looks like):</p> <pre><code>void ConvertUtility::ConvertEdgeIndexList(const list&lt;EdgeIndex&gt; &amp;edgeIndex) { list&lt;EdgeIndex&gt;::const_iterator sit; for(sit=edgeIndex.begin(); sit!=edgeIndex.end(); sit++) { } } void ConvertUtility::ConvertEdgeIndexList(const vector&lt;EdgeIndex&gt; &amp;edgeIndex) { vector&lt;EdgeIndex&gt;::const_iterator sit; for(sit=edgeIndex.begin(); sit!=edgeIndex.end(); sit++) { } } </code></pre> <p>Is there anyway I can aggregate these two functions into one single function?</p>
[]
[ { "body": "<p>How about:</p>\n\n<pre><code>template&lt;typename C&gt;\nvoid ConvertUtility::ConvertEdgeIndexList(C const&amp; edgeIndex)\n{\n typename C::const_iterator sit;\n for(sit=edgeIndex.begin(); sit!=edgeIndex.end(); ++sit)\n { // ^^ Prefer pre-increment on iterators.\n\n }\n}\n</code></pre>\n\n<p>PS. Stackoverflow may be a better site for this type of question.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T05:01:14.230", "Id": "5130", "ParentId": "5129", "Score": "9" } }, { "body": "<p>I would have a function taking a generic iterator range, in the style of the standard algorithms.</p>\n\n<pre><code>template &lt;typename Iterator&gt;\nvoid ConvertUtility::ConvertEdgeIndexList(Iterator start, Iterator end)\n{\n for (Iterator sit = start; sit != end; ++sit)\n {\n\n }\n}\n</code></pre>\n\n<p>If you need a specific type of iterator (e.g. ForwardIterator, or RandomAccessIterator), then the template parameter name is a good place to document that.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T16:55:05.430", "Id": "7690", "Score": "0", "body": "+1: Prefer to use a style that mirrors the behavior of the sTL." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T15:18:02.357", "Id": "5142", "ParentId": "5129", "Score": "9" } } ]
{ "AcceptedAnswerId": "5130", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T03:08:18.253", "Id": "5129", "Score": "10", "Tags": [ "c++" ], "Title": "How to write a method that takes a general iterator as input argument?" }
5129
<p>I'm trying to get my head in the Scala game, and would welcome feedback on the following code, which produces a table from data.</p> <pre><code>class TabulatorTest extends FunSuite with ShouldMatchers { test("format") { Tabulator.format(List( List("head1", "head2", "head3"), List("one", "two", "three"), List("four", "five", "six"))) should be (""" +-----+-----+-----+ |head1|head2|head3| +-----+-----+-----+ | one| two|three| | four| five| six| +-----+-----+-----+ """.trim) } test("format empty") { Tabulator.format(List()) should be ("") Tabulator.format(List(List())) should be (""" ++ || ++ ++ """.trim) } test("uneven rows") { try { Tabulator.format(List( List("head1", "head2", "head3"), List("one", "two"))) fail() } catch { case e: IllegalArgumentException =&gt; } } } </code></pre> <hr> <pre><code>object Tabulator { def format(table: Seq[Seq[Any]]) = table match { case Seq() =&gt; "" case _ =&gt; val cellSizes = for (row &lt;- table) yield (for (cell &lt;- row) yield if (cell == null) 0 else cell.toString.length) val colSizes = for (col &lt;- cellSizes.transpose) yield col.max val rows = for (row &lt;- table) yield formatRow(row, colSizes) formatRows(rowSeparator(colSizes), rows) } def formatRow(row: Seq[Any], colSizes: Seq[Int]) = { val cells = (for ((item, size) &lt;- row.zip(colSizes)) yield if (size == 0) "" else ("%" + size + "s").format(item)) cells.mkString("|", "|", "|") } def formatRows(rowSeparator: String, rows: Seq[String]): String = ( rowSeparator :: rows.head :: rowSeparator :: rows.tail.toList ::: rowSeparator :: List()).mkString("\n") private def rowSeparator(colSizes: Seq[Int]) = colSizes map { "-" * _ } mkString("+", "+", "+") } </code></pre>
[]
[ { "body": "<p>I can't help a lot. Only some syntactic hints:</p>\n\n<pre><code>object Tabulator {\n\n def format(table: Seq[Seq[Any]]) =\n if (table.isEmpty) \"\"\n else {\n def cellSize(cell: Any) =\n cell.toString.length\n\n val cellSizes =\n table map { _ map cellSize }\n val colSizes =\n cellSizes.transpose map { _.max }\n val rows =\n table map formatRow(colSizes)\n\n formatRows(rowSeparator(colSizes), rows)\n }\n\n def formatRow(colSizes: Seq[Int])(row: Seq[Any]) = {\n val cells =\n for ((item, size) &lt;- row zip colSizes) yield\n if (size == 0) \"\" else \"%\"+size+\"s\" format item\n cells mkString (\"|\", \"|\", \"|\")\n }\n\n def formatRows(rowSeparator: String, rows: Seq[String]): String = (\n rowSeparator\n :: rows.head\n :: rowSeparator\n :: rows.tail.toList\n ::: rowSeparator\n :: Nil\n ) mkString \"\\n\"\n\n\n private def rowSeparator(colSizes: Seq[Int]) =\n colSizes map { \"-\"*_ } mkString (\"+\", \"+\", \"+\")\n}\n</code></pre>\n\n<p>I deleted the null-check in cellSize because <code>null</code> is not familiar in Scala. If you definitely need <code>null</code> then restore the check.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:21:34.610", "Id": "7701", "Score": "0", "body": "This is not `null` safe. You shoudl fix `cellSize` to use `Option(cell) map (_.toString.length) getOrElse 0`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:34:15.787", "Id": "7704", "Score": "0", "body": "@DanielC.Sobral: I know that it is not null safe. But in Scala typically nobody uses null. And because I don't know what data the code has to handle I deleted the null-check. There can be null but maybe null is handled before the Tabulator is used? To your second comment: There is formatRow and formatRow **s**" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:38:00.097", "Id": "7705", "Score": "0", "body": "Should I favour `if` over `case` for simple tests? I rather like the shape of the case rather than the annoying brackets and braces in if statements, and the case gives a nicer sense of different function bodies for different arguments like Lisp and Haskell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:40:16.460", "Id": "7706", "Score": "0", "body": "@Antoras - it turns out that the Java objects that this is used to display often have null fields." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:42:31.030", "Id": "7707", "Score": "0", "body": "@Antoras - why define `cellSize` as a nested function, but have others as methods? Aren't I just loosing a place I could customise through subclassing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:43:40.060", "Id": "7708", "Score": "0", "body": "@DanielC.Sobral - what does `Option(cell) map (_.toString.length) getOrElse 0` buy me that `if (cell == null) 0 else cell.toString.length` doesn't (apart from an extra object creation and method call ;-)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:45:00.233", "Id": "7709", "Score": "0", "body": "@Antoras Oh, sorry, I didn't notice the distinction. I'd rename formatRow to formatCols. Easier on the eye. I'll remove the second comment, but I still think the first is relevant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:49:32.957", "Id": "7710", "Score": "0", "body": "@Duncan The short answer is composability, though, perhaps, a better answer would be \"mindset\". The best practice in Scala is to wrap any null-returning API in conversions T => Option[T], for all nullable T. You can then rely on Scala to keep your code correct with respect to optional values." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:54:50.517", "Id": "7711", "Score": "0", "body": "@Daniel - so I should default to `Option(x)` and replace with `if (x == null)` only as an optimisation..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:55:01.127", "Id": "7712", "Score": "0", "body": "@DuncanMcGregor: If prefer if-else over match-case when there are only two cases and there are no data to extract. But that's only my own preference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T21:56:58.643", "Id": "7713", "Score": "0", "body": "@Antoras - I must get used to Nil for the empty list, and I think I like the way that mkString is effectively used as a operator. I don't like the lack of space around arithmetic operators though..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T22:00:38.200", "Id": "7714", "Score": "0", "body": "@Antoras - I do like the simpler map rather than yield for colSizes and rows. I didn't like the verbosity of my nested for, but that did reveal the 2D more than `table map {_ map cellSize }`. Maybe I'll find the latter idiomatic soon." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T14:50:30.053", "Id": "7760", "Score": "0", "body": "@Duncan You should default to calling Option on _any_ data returned by Java that might be `null`. Inside your own code, use `Option` and never test for nulls -- if they happen, it is a bug (you forgot to call `Option` on some Java-returned data)." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T19:34:08.057", "Id": "5147", "ParentId": "5138", "Score": "3" } } ]
{ "AcceptedAnswerId": "5147", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T12:49:25.940", "Id": "5138", "Score": "2", "Tags": [ "scala" ], "Title": "Formatting as a table in Scala" }
5138
<p>Due to software constraints, I cannot use the standard libraries, <code>&lt;math.h&gt;</code>, <code>&lt;algorithm&gt;</code>, templates, <code>inline</code>, or Boost. I am also using standard C (ISO C99) such that <code>array</code> is not a reserved keyword like it is in Visual Studio.</p> <p>Is this the "best" possible implementation of a min function? This needs to be robust and fast. Is there a more efficient C++ implementation?</p> <pre><code>double min(double* array, int size){ // returns the minimum value of array static double val = array[0]; for (int i = 1; i &lt; size; ++i){ val = val &lt;= array[i] ? val : array[i]; } return val; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T18:34:36.913", "Id": "7693", "Score": "0", "body": "Can you elaborate a bit on the software constraints you have to work within? I can understand not using boost but not allowing math.h, algorithms, and templates either? That's ruling out some very useful tools offered by the language as well as reinventing the proverbial wheel as shown by your sample." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T19:23:24.453", "Id": "7695", "Score": "0", "body": "@VictorT.,the short answer is due to certification issues and extreme V&V. Trust me, I wish I didn't have these constraints, but really appreciate the resources SE provides" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T20:22:13.897", "Id": "7696", "Score": "4", "body": "Is there a guarantee that size > 0? Otherwise you just stepped past the end of your array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T20:34:28.650", "Id": "7697", "Score": "0", "body": "@Tux: If this *must* be optimized for efficiency then the onus will be on the caller to provide only valid data, not the other way around." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T20:42:23.473", "Id": "7698", "Score": "0", "body": "@Ed S.: Quote: `This needs to be robust`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T20:49:17.737", "Id": "7699", "Score": "0", "body": "@Tux-D: Yeah, I saw that two. I don't think that the OP meant it that way though, but I'm really guessing. Performance critical functions do not perform a ton of input validation (or any at all) by design. For example, look at the C standard library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T20:56:52.377", "Id": "7700", "Score": "0", "body": "Lets assuming the user knows what the input typedefs are and not worry about type casting, etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T06:45:28.750", "Id": "7736", "Score": "0", "body": "Use C++ inline templates, or you can use uber-macros to emulate templates in C http://forums.xkcd.com/viewtopic.php?f=11&t=44426, http://drdobbs.com/184402989, or the most famous, and were my best searches so far (using google, of cause): BYTE WORM blog post at http://byteworm.com/2010/10/12/container/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T12:51:23.593", "Id": "7750", "Score": "0", "body": "@ArturMustafin, cannot use templates" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T21:33:50.297", "Id": "7800", "Score": "0", "body": "@Artur: The first sentence states that the OP can't use templates..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T09:45:41.403", "Id": "7814", "Score": "0", "body": "@EdS.: I've added code sample in my post to code review. This is the SSE version of the peaks algorithm, compiles for both GCC and VC++. Look may be you will find it helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T09:47:50.247", "Id": "7815", "Score": "0", "body": "In my opinion, SSE implementation is better than \"classic\" CPU inctructions cycle for the big arrays." } ]
[ { "body": "<p>It's not quite the best. There's some things IMHO that is hindering its performance and usefulness.</p>\n\n<p>There's no point in declaring <code>val</code> as a static variable. In fact, you've killed any chance of it being usable in multi-threaded programs.</p>\n\n<p>The body of the loop is performing an assignment in every single iteration when it doesn't need to. If you want it to be its best, you should only be doing so when it is required.</p>\n\n<p>Your overall structure is fine, assuming we can expect well-formed inputs where array is nonempty and size is positive, I'd just change it so it's more like this:</p>\n\n<pre><code>double min(const double *arr, size_t length) {\n // returns the minimum value of array\n size_t i;\n double minimum = arr[0];\n for (i = 1; i &lt; length; ++i) {\n if (minimum &gt; arr[i]) {\n minimum = arr[i];\n }\n }\n return minimum;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T23:26:48.380", "Id": "7719", "Score": "0", "body": "I'm pretty sure any half-decent optimising compiler will remove the redundant assignment in the original code's ternary operator." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T06:05:59.920", "Id": "7732", "Score": "0", "body": "Shouldn't it be `i++` in stead of `++i`? Since you're pre-incrementing and starting at `1`, in the first iteration `i` would already be `2` at the `if` statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T06:12:27.767", "Id": "7734", "Score": "0", "body": "@fireeyedboy: It doesn't really matter which one is used, in the context of a `for` loop, they are exactly the same, increment `i`. The incrementing expression is evaluated between the execution of the body and the condition check and has no other effect on the two." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T06:46:33.973", "Id": "7737", "Score": "0", "body": "Wow, how amateurish of me. I've been programming for years now, and could have sworn I was right. But I just tested this myself, and you are absolutely right. Silly me. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T07:51:14.113", "Id": "7738", "Score": "0", "body": "Out of curiosity, is there a performance reason for moving the `int i` declaration out of the loop?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T07:53:16.190", "Id": "7739", "Score": "1", "body": "@S.L.Barth: It's the C side in me moving the declaration to the beginning of the scope. I tend to think in (old) C more than I do C++ and the relaxed restrictions. No reason at all really." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T14:13:40.590", "Id": "7759", "Score": "0", "body": "Another improvement would be change the typedef of size,i from `int` to `size_t`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T17:51:29.987", "Id": "7773", "Score": "0", "body": "@Elpezmuerto: Yes definitely. We could even go for `const` correctness here and make `array` a `const char *`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T18:57:03.547", "Id": "7779", "Score": "0", "body": "@JeffMercado, why would val be a `const char *`? Is it because array is a `double *`? A technical response would be appreciated" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:06:42.340", "Id": "7780", "Score": "0", "body": "@Elpezmuerto: Oops, I meant `const double *`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:09:32.913", "Id": "7782", "Score": "0", "body": "@JeffMercado, `val` can change its value, hence isn't it `mutable`? Why would we want to declare it as a `const`? Is it because `const double*` means that the pointer is const but not the double[] it is pointing to?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:24:40.653", "Id": "7784", "Score": "1", "body": "@Elpezmuerto: By declaring the type of the array `const double *`, we're stating that the contents of the array could not be changed. i.e., The array is immutable. We can still read the contents and store it on a non-const `double` as long as we don't modify the contents of the array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:42:51.917", "Id": "7786", "Score": "0", "body": "@JeffMercado, I was little confused on what you wear declaring as `const double` but you've updated the answer to properly reflect this. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T09:44:33.743", "Id": "7813", "Score": "0", "body": "I've added code sample in my post to code review. This is the SSE version of the peaks algorithm, compiles for both GCC and VC++. Look may be you will find it helpful." } ], "meta_data": { "CommentCount": "14", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T17:59:19.190", "Id": "5146", "ParentId": "5143", "Score": "20" } }, { "body": "<p>You can use SSE2/SSE3 minps / pminsd or relevant instruction set for your processor/architectoure since it is supported directly in GCC / MASM / TASM (In case MASM or TASM is not supported such SSE2/SSE3 instruction set there are also the .inc files to create macros simulating instruction sets on the web for MASM), create .OBJ file by your favorite linker then link it as usual and use in you favorite IDE. You will get from 4x to 16x performance boost compared to the traditional \"classic\" algorithm. It depend on data size (old compilers treats double not in IEEE format, bout like float in several configurations, on 16x systems, particularly, double means 32 bit data structure, not 64 bit data structure, in modern languages it is correlated to \"double\" and \"long double\" data structures, respectively)</p>\n\n<p>The idea is simple: if you have k elements, [k=4n+p, 4>p=>0], complete it with n-p elements or just load last 4 doubles resetting to 0 last p elements, so you can fast evaluate n candidates. evaluate candidates n times comparing to the accumulator, you will get a minimum.</p>\n\n<p>If your processor supports SSE5 or is a brand new, most likely you also will be using one of the HD instructions, which really handy, because it can find maximum (not minimum yet) in array of double values.</p>\n\n<p>Sample of using SSE to calculate peak values of a float array:</p>\n\n<pre><code>#include &lt;xmmintrin.h&gt;\n\ndouble min(double* array, int size) { \n // returns the minimum value of array \n int i; \n double val = array[0]; \n for (i = 1; i &lt; size; ++i) { \n if (val &gt; array[i]) { \n val = array[i]; \n } \n } \n return val; \n} \n\n#define ARRAY_SIZE 16\n\nfloat m_fArray[ARRAY_SIZE];\n\nvoid x86_sse_find_peaks(float *buf, unsigned nframes, float *min, float *max)\n{\n __m128 current_max, current_min, work;\n\n // Load max and min values into all four slots of the XMM registers\n current_min = _mm_set1_ps(*min);\n current_max = _mm_set1_ps(*max);\n\n // Work input until \"buf\" reaches 16 byte alignment\n while ( ((unsigned long)buf) % 16 != 0 &amp;&amp; nframes &gt; 0) {\n\n // Load the next float into the work buffer\n work = _mm_set1_ps(*buf);\n\n current_min = _mm_min_ps(current_min, work);\n current_max = _mm_max_ps(current_max, work);\n\n buf++;\n nframes--;\n }\n\n // use 64 byte prefetch for quadruple quads\n while (nframes &gt;= 16) {\n //__builtin_prefetch(buf+64,0,0); // for GCC 4.3.2+\n\n work = _mm_load_ps(buf);\n current_min = _mm_min_ps(current_min, work);\n current_max = _mm_max_ps(current_max, work);\n buf+=4;\n work = _mm_load_ps(buf);\n current_min = _mm_min_ps(current_min, work);\n current_max = _mm_max_ps(current_max, work);\n buf+=4;\n work = _mm_load_ps(buf);\n current_min = _mm_min_ps(current_min, work);\n current_max = _mm_max_ps(current_max, work);\n buf+=4;\n work = _mm_load_ps(buf);\n current_min = _mm_min_ps(current_min, work);\n current_max = _mm_max_ps(current_max, work);\n buf+=4;\n nframes-=16;\n }\n\n // work through aligned buffers\n while (nframes &gt;= 4) {\n\n work = _mm_load_ps(buf);\n\n current_min = _mm_min_ps(current_min, work);\n current_max = _mm_max_ps(current_max, work);\n\n buf+=4;\n nframes-=4;\n }\n\n // work through the rest &lt; 4 samples\n while ( nframes &gt; 0) {\n\n // Load the next float into the work buffer\n work = _mm_set1_ps(*buf);\n\n current_min = _mm_min_ps(current_min, work);\n current_max = _mm_max_ps(current_max, work);\n\n buf++;\n nframes--;\n }\n\n // Find min &amp; max value in current_max through shuffle tricks\n\n work = current_min;\n work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(2, 3, 0, 1));\n work = _mm_min_ps (work, current_min);\n current_min = work;\n work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(1, 0, 3, 2));\n work = _mm_min_ps (work, current_min);\n\n _mm_store_ss(min, work);\n\n work = current_max;\n work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(2, 3, 0, 1));\n work = _mm_max_ps (work, current_max);\n current_max = work;\n work = _mm_shuffle_ps(work, work, _MM_SHUFFLE(1, 0, 3, 2));\n work = _mm_max_ps (work, current_max);\n\n _mm_store_ss(max, work);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n float min = FLT_MAX;\n float max = FLT_MIN;\n\n m_fArray[0] = 0;\n m_fArray[1] = 1;\n m_fArray[2] = 2;\n m_fArray[3] = 3;\n m_fArray[4] = 4;\n m_fArray[5] = 3;\n m_fArray[6] = 2;\n m_fArray[7] = 1;\n m_fArray[8] = -1;\n m_fArray[9] = -2;\n m_fArray[10] = -3;\n m_fArray[11] = -4;\n m_fArray[12] = -5;\n m_fArray[13] = -6;\n m_fArray[14] = -7;\n m_fArray[15] = -8;\n\n x86_sse_find_peaks(m_fArray, ARRAY_SIZE, &amp;min, &amp;max);\n\n printf(\"value = %.2f, max = %.2f\\n\", min, max); // output is: value = -8.00, max = 4.00\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T14:09:56.320", "Id": "7828", "Score": "1", "body": "This is great peaks implementation but I am working with `double` and don't want to downcast. If I recall, SSE was originally designed for floats. I've read that SSE can now handle double precision values, but not sure how to change your above code to handle doubles." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T01:53:12.760", "Id": "7841", "Score": "0", "body": "@Elpezmuerto: I will definitely make it a try, would you mind that i will use Visual Studio 11 to compile C++ code, I'm also having a Borland C++, TASM in Windows XP virtual machine under Windows 7?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T18:14:46.657", "Id": "7854", "Score": "0", "body": "sure I am happy with the code current state. Anything beyond this is really for research curiosity and the good for all, etc." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T11:50:30.510", "Id": "5162", "ParentId": "5143", "Score": "6" } }, { "body": "<p><strong>Recommended form for robustness:</strong></p>\n\n<p>Ok, you want robust and fast. If this was needed in production code, I would probably write it like this:</p>\n\n<pre><code>double min(double array[], int size)\n{\n assert(array != NULL);\n assert(size &gt;= 0);\n\n if ((array == NULL) || (size &lt;= 0))\n return NAN;\n\n double val = -DBL_MAX;\n for (int i = 0; i &lt; size; i++)\n if (val &lt; array[i])\n val = array[i];\n return val;\n}\n</code></pre>\n\n<p><em>Looping:</em> I noticed you optimized your loop to begin with <code>val = array[0]</code> initially and <code>i = 1</code> instead of <code>i = 0</code>. This may have saved machine cycles 20 years ago, but these days memory accesses are the biggest bottleneck, and you're stuck with the same number of memory accesses into <code>array[]</code> no matter how you write the loop, so I would try to be as non-clever as possible here and just stick to a more traditional loop.</p>\n\n<p><em>Argument checking:</em> Is it valid to call this function with <code>size</code> of 0? If so, then you also have a bug if you start off with <code>val = array[0]</code> when <code>size</code> is 0, because you might be reading invalid memory depending on where <code>array</code> is pointing. At the very least, it's logically incorrect to examine <code>array[0]</code> when <code>size</code> is 0.</p>\n\n<p><strong>Alternative formulation (not recommended):</strong></p>\n\n<p>Just for fun, if you have a sufficiently large stack and lots of machine cycles to burn, you could write it like this:</p>\n\n<pre><code>double min(double a[], int n)\n{\n if ((a == NULL) || (n &lt;= 0))\n {\n return NAN;\n }\n else if (n == 1)\n {\n return array[0];\n }\n else\n {\n double x = a[0], y = min(&amp;a[1], n-1);\n return x &lt; y? x : y;\n }\n}\n</code></pre>\n\n<p>Or, a recursive binary search using only O(log₂ n) stack space:</p>\n\n<pre><code>inline double min2(double x, double y)\n{\n return x &lt; y? x : y;\n}\n\ndouble min(double a[], int n)\n{\n return (a == NULL) || (n &lt;= 0)? NAN\n : (n == 1)? a[0]\n : min2(min(a, n/2), min(a+n/2, n-n/2));\n}\n</code></pre>\n\n<p>Or, in avoidance of error-checking and in adherence to the principle of maximum terseness:</p>\n\n<pre><code>inline double min2(double x, double y) { return x&lt;y? x:y; }\ndouble min(double a[], int n) { return n==1? a[0] : min2(min(a,n/2),min(a+n/2,n-n/2)); }\n</code></pre>\n\n<p>;-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T17:53:38.673", "Id": "6950", "ParentId": "5143", "Score": "3" } } ]
{ "AcceptedAnswerId": "5146", "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T16:33:07.643", "Id": "5143", "Score": "13", "Tags": [ "c++", "algorithm", "array", "reinventing-the-wheel" ], "Title": "Min / Max function of 1D array in C / C++" }
5143
<p>This week-end, I finally found some time to learn unit testing (it's about time, I know).<br> So I've tried to do this in PHP, with <a href="http://www.phpunit.de/manual/current/en/" rel="nofollow">PHPUnit 3.6</a>.</p> <p>I've wrote a small, simple and useless <a href="https://github.com/G-Qyy/Qyy.G.en.PHP.File" rel="nofollow">class wrapper for files</a>, and a basic unit testing class for it.<br> As I'm a self learner, and nobody around me can help me about that, is it possible for someone to review it, and tell me what is right and wrong, and how I can improve my tests?</p> <ul> <li><a href="https://github.com/G-Qyy/Qyy.G.en.PHP.File" rel="nofollow">Here is the Github repository with all the code</a></li> <li>I paste thereafter the class and the test class</li> </ul> <h3>Qyy.G.en.PHP.File/Qyy_G_en_File.php:</h3> <pre><code>// TODO: doc class Qyy_G_en_File { protected $filename; // TODO: doc function __construct ($filename) { if (!file_exists($filename)) { throw new InvalidArgumentException( 'This file does not exist or permissions are not set correctly: ' .$filename, 404); } $this-&gt;filename = $filename; } // TODO: doc public function GetFilename () { return $this-&gt;filename; } // TODO: doc // http://php.net/manual/en/function.basename.php public function GetBasename () { return basename($this-&gt;GetFilename()); } // TODO: doc // http://php.net/manual/en/function.pathinfo.php public function GetBasenameNoSuffix () { $return = pathinfo($this-&gt;GetFilename(), PATHINFO_FILENAME); if (is_null($return) || empty($return)) { throw new LengthException('This file seems to start with a dot.', 404); } return $return; } // TODO: doc // http://php.net/manual/en/function.pathinfo.php public function GetSuffix () { $return = pathinfo($this-&gt;GetFilename(), PATHINFO_EXTENSION); if (is_null($return) || empty($return)) { throw new LengthException('There is no suffix for this file.', 404); } return $return; } // TODO: doc // http://php.net/manual/en/function.dirname.php public function GetDirname () { return dirname($this-&gt;GetFilename()); } // TODO: doc // http://php.net/manual/en/function.realpath.php public function GetRealpath () { $return = realpath($this-&gt;GetFilename()); if ($return === false) { $lastError = error_get_last(); throw new Exception( 'Unable to determine the real path. ' .'It might be due to a lack of permissions.', 403 , new Exception( 'message: "'.$lastError['message'].'"'.PHP_EOL .'file: "'.$lastError['file'].'"'.PHP_EOL .'line: `'.$lastError['line'].'`'.PHP_EOL, $derniereErreur['type'])); } return $return; } } </code></pre> <h3>Qyy.G.en.PHP.File/UnitTests/Qyy_G_en_FileTest.php:</h3> <pre><code>require_once dirname(__FILE__) . '/../Qyy_G_en_File.php'; /** * Test class for Qyy_G_en_File. */ class Qyy_G_en_FileTest extends PHPUnit_Framework_TestCase { /** * @var Qyy_G_en_File */ protected $object0; /** * @var Qyy_G_en_File */ protected $object1; /** * @var Qyy_G_en_File */ protected $object2; /** * @var array */ protected $filenames; /** * Sets up the fixture. */ protected function setUp() { $this-&gt;filenames = array( '../readme.md', '../.gitignore', '../README', 'foo.bar'); $this-&gt;testNewObject0(); $this-&gt;testNewObject1(); $this-&gt;testNewObject2(); } public function testNewObject0 () { $this-&gt;object0 = new Qyy_G_en_File($this-&gt;filenames[0]); $this-&gt;assertEquals(true, is_a($this-&gt;object0, 'Qyy_G_en_File')); } public function testNewObject1 () { $this-&gt;object1 = new Qyy_G_en_File($this-&gt;filenames[1]); $this-&gt;assertEquals(true, is_a($this-&gt;object1, 'Qyy_G_en_File')); } public function testNewObject2 () { $this-&gt;object2 = new Qyy_G_en_File($this-&gt;filenames[2]); $this-&gt;assertEquals(true, is_a($this-&gt;object2, 'Qyy_G_en_File')); } /** * @expectedException InvalidArgumentException */ public function testNewObject3 () { new Qyy_G_en_File($this-&gt;filenames[3]); } /** * @depends testNewObject0 * @depends testNewObject1 * @depends testNewObject2 */ public function testGetFilename() { for($i = 0; $i &lt;= 2; $i++) { $this-&gt;assertEquals( $this-&gt;filenames[$i], $this-&gt;{'object'.$i}-&gt;GetFilename()); } } /** * @depends testNewObject0 * @depends testNewObject1 * @depends testNewObject2 */ public function testGetBasename() { for($i = 0; $i &lt;= 2; $i++) { $this-&gt;assertEquals( basename($this-&gt;filenames[$i]), $this-&gt;{'object'.$i}-&gt;GetBasename()); } } /** * @depends testNewObject0 */ public function testGetBasenameNoSuffix0 () { $this-&gt;assertEquals('readme', $this-&gt;object0-&gt;GetBasenameNoSuffix()); } /** * @depends testNewObject1 * @expectedException LengthException */ public function testGetBasenameNoSuffix1 () { $this-&gt;object1-&gt;GetBasenameNoSuffix(); } /** * @depends testNewObject2 */ public function testGetBasenameNoSuffix2 () { $this-&gt;assertEquals('README', $this-&gt;object2-&gt;GetBasenameNoSuffix()); } /** * @depends testNewObject0 */ public function testGetSuffix0 () { $this-&gt;assertEquals('md', $this-&gt;object0-&gt;GetSuffix()); } /** * @depends testNewObject1 */ public function testGetSuffix1 () { $this-&gt;assertEquals('gitignore', $this-&gt;object1-&gt;GetSuffix()); } /** * @depends testNewObject2 * @expectedException LengthException */ public function testGetSuffix2 () { $this-&gt;object2-&gt;GetSuffix(); } /** * @depends testNewObject0 * @depends testNewObject1 * @depends testNewObject2 */ public function testGetDirname () { for($i = 0; $i &lt;= 2; $i++) { $this-&gt;assertEquals( dirname($this-&gt;filenames[$i]), $this-&gt;{'object'.$i}-&gt;GetDirname()); } } /** * @depends testNewObject0 * @depends testNewObject1 * @depends testNewObject2 */ public function testGetRealpath () { for($i = 0; $i &lt;= 2; $i++) { $this-&gt;assertEquals( realpath($this-&gt;filenames[$i]), $this-&gt;{'object'.$i}-&gt;GetRealpath()); } } } </code></pre>
[]
[ { "body": "<p>All in all, it looks like you're off to a great start. I'm going to skip around a bit in what I recommend however there are definitely a few things that could be cleaned up.</p>\n\n<pre><code>public function testNewObject3 ()\n{\n // I'm not sure you can define what the exception should\n // describe in the doc-block however you can by using the method\n $this-&gt;setExpectedException('InvalidArgumentException', 'File does not exist');\n new Qyy_G_en_File($this-&gt;_getNonExistantFile());\n}\n\n// I would use something like this to describe a bit more of what the filename means\nprivate function _getNonExistantFile()\n{\n return 'Foo.bar';\n}\n</code></pre>\n\n<p>In your setUp() method, you call several other tests to prepare future tests. With unit testing, you want to keep the tests separate. In your code, if testNewObject2() fails, testGetSuffix1() will also fail, even though it is unrelated.</p>\n\n<p>To reduce code duplication, use private methods for specific needs. Maybe something like this:</p>\n\n<pre><code>public function testNewObjectWithShortExtension()\n{\n new Qyy_G_en_File('read.me');\n}\n\npublic function testGetSuffixWhenShort()\n{\n $Qyy = $this-&gt;_createQyyFile('read.me'); \n $this-&gt;assertEquals('md', $Qyy-&gt;GetSuffix());\n}\n</code></pre>\n\n<p>Also, I would add that some very notable programmers have emphasized the rule of a single assertion per unit test. As such, give some thought to this as well.</p>\n\n<p>Lastly, I would recommend being a bit more descriptive than object0, filename1, etc. Try to give more meaning to the variables. It'll help immensely in 6 months when you look back at your code and sit there wondering what the purpose of this or that was.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T21:11:30.160", "Id": "5239", "ParentId": "5154", "Score": "2" } } ]
{ "AcceptedAnswerId": "5239", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-03T07:55:59.363", "Id": "5154", "Score": "4", "Tags": [ "php", "unit-testing" ], "Title": "Reviewing my unit testing (in PHP)" }
5154
<p>I'm very much a beginner and have put together some JavaScript to control a pair of radio buttons which essentially behave as links.</p> <p>I'm doing this as sort of a self-initiated project, or bit of fun. I know I don't have to use radio buttons, but it's something I just wanted to do.</p> <p>It simply checks the radio button when you hover over it, and at the same time highlights the accompanying text. Or, highlights the text when hovered over, and also checks the accompanying radio button.</p> <p>When the cursor moves out, no longer hovering over, the elements go back to their normal states.</p> <p>I feel like there has to be a much cleaner way of implementing this.</p> <p>Here is my mark up of the two radio buttons:</p> <pre><code>&lt;form name=links&gt; &lt;div id="aaa"&gt; &lt;input type="radio" name="fb" onMouseOut="out_event_01()" onMouseOver="over_event_01()" /&gt; &lt;br /&gt;&lt;span class="sl" id="fb_link" onMouseOut="out_event_03()" onMouseOver="over_event_03()"&gt;Button1&lt;/span&gt; &lt;/div&gt; &lt;div id="bbb"&gt; &lt;input type="radio" name="tw" onMouseOut="out_event_02()" onMouseOver="over_event_02()" /&gt; &lt;br /&gt;&lt;span class="sl" id="tw_link" onMouseOut="out_event_04()" onMouseOver="over_event_04()"&gt;Button2&lt;/span&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>As you can see I have a lot of onMouseOut and onMouseOver events.</p> <p>This is the JavaScript I'm using:</p> <pre><code>function over_event_01() { var links = document.links.fb; links.checked = true; document.getElementById('fb_link').style.color = 'black'; } function out_event_01() { var links = document.links.fb; links.checked = false; document.getElementById('fb_link').style.color = 'rgb(153,153,153)'; } function over_event_02() { var links = document.links.tw; links.checked = true; document.getElementById('tw_link').style.color = 'black'; } function out_event_02() { var links = document.links.tw; links.checked = false; document.getElementById('tw_link').style.color = 'rgb(153,153,153)'; } function over_event_03() { var links = document.links.fb; links.checked = true; document.getElementById('fb_link').style.color = 'black'; } function out_event_03() { var links = document.links.fb; links.checked = false; document.getElementById('fb_link').style.color = 'rgb(153,153,153)'; } function over_event_04() { var links = document.links.tw; links.checked = true; document.getElementById('tw_link').style.color = 'black'; } function out_event_04() { var links = document.links.tw; links.checked = false; document.getElementById('tw_link').style.color = 'rgb(153,153,153)'; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T10:19:28.523", "Id": "7832", "Score": "0", "body": "Have you looked at JQuery? You could probably right this in two or three lines of code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T10:43:38.137", "Id": "7833", "Score": "0", "body": "No i haven't, I'm very new to all this. Thank though, I'll check out JQuery" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T12:45:11.103", "Id": "7834", "Score": "0", "body": "@jakry001 Learn your JavaScript fundamentals before diving into jQuery. They'll help you write much better jQuery code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T09:23:48.417", "Id": "7835", "Score": "0", "body": "plus many more lines of jquery core :)" } ]
[ { "body": "<p>You could probably start by <a href=\"http://en.wikipedia.org/wiki/Indent_style\" rel=\"nofollow\">indenting</a> your code.</p>\n\n<p>My Javascript is a bit rusty, but I would suggest you to rewrite your code so it uses only one function with parameters, instead of 8 functions which all do pretty much the same.</p>\n\n<pre><code>function hover_link(is_over, is_fb)\n{\n var links\n if (is_fb)\n links = document.links.fb;\n else // tw\n links = document.links.tw;\n links.checked = true;\n if (is_over)\n document.getElementById('tw_link').style.color = 'black';\n else // out\n document.getElementById('fb_link').style.color = 'rgb(153,153,153)';\n }\n</code></pre>\n\n<p>You would use it like this:</p>\n\n<pre><code>&lt;form name=links&gt;\n &lt;div id=\"aaa\"&gt;\n &lt;input type=\"radio\" name=\"fb\" onMouseOut=\"hover_link(false, true)\" onMouseOver=\"hover_link(true, true)\" /&gt;\n &lt;br /&gt;&lt;span class=\"sl\" id=\"fb_link\" onMouseOut=\"hover_link(false, false)\" onMouseOver=\"hover_link(true, false)\"&gt;Button1&lt;/span&gt;\n &lt;/div&gt;\n &lt;div id=\"bbb\"&gt;\n &lt;input type=\"radio\" name=\"tw\" onMouseOut=\"hover_link(false, true)\" onMouseOver=\"hover_link(true, true)\" /&gt;\n &lt;br /&gt;&lt;span class=\"sl\" id=\"tw_link\" onMouseOut=\"hover_link(false, false)\" onMouseOver=\"hover_link(true, false)\"&gt;Button2&lt;/span&gt;\n &lt;/div&gt;\n&lt;/form&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T11:32:22.617", "Id": "5161", "ParentId": "5156", "Score": "5" } }, { "body": "<p>Without re-writing all your code I do have a few suggestions for you:</p>\n\n<ul>\n<li>Don't use inline javascript (onMouseeOut, onMouseOver) always use event listeners (I'll show you how the code example below). The reason for this is twofold: first it separates your javascript from your HTML second it makes your code even more maintainable if you change a listener you have one place to look.</li>\n<li>Use classes instead of inline styles (for the same reasons mentioned above)\n<ul>\n<li>this means replace the style=xxx with a css classname (again i'll have an example in the code below)</li>\n</ul></li>\n<li>A lot of your code can be condensed into small reuseable functions since a lot of it is repetitive. </li>\n</ul>\n\n<p>Since you are new to JavaScript I'll avoid some of of the intermediate patterns that I think may apply here such as wrapping this entire functionality in an instantly invoked function expression (IIFE) but you really should read this article by Ben Alman <a href=\"http://benalman.com/news/2010/11/immediately-invoked-function-expression/\" rel=\"nofollow\">http://benalman.com/news/2010/11/immediately-invoked-function-expression/</a></p>\n\n<p>So lets look at how it can be improved with some psudo code. First Lets create one wrapper function that will encapsulate all your functionality. First set some function variables to your links and radios. Then we attach events for most browsers and older versions of IE, then we create two generic functions to handle your mouseenter and mouseleave. These functions will handle the duplicated logic of checking </p>\n\n<pre><code>function overOut(){\n //these variables will be accessable by all the inner functions so we only declare them once\n var fbLinks = document.links.fb,\n twLinks = document.links.tw\n fbLink = document.getElementById('fb_link'),\n twLink = document.getElementById('tw_link');\n\n //check for standard event listener \n if(fbLink.addEventListener){\n //here i'm assuming that fblinks are the links you want to highlight\n fbLink.addEventListener(\"mouseover\",radioOverFunction(this,fbLinks));\n }\n //ie events\n else if(fbLink.attachEvent){\n //here i'm assuming that fblinks are the links you want to highlight\n fbLink.attachEvent(\"mouseover\",radioOverFunction(this,fbLinks));\n }\n\n /***************************************************\n * repeat the above code but for mouseout events *\n ***************************************************/\n\n var radioOverFunction = function(radio,target){\n //in here you would set check the radio and set the classname on the target\n target.className = 'mouseOverClassName';\n };\n\n var radioLeaveFunction = function(radio,target){\n //in here you would set check the radio and set the classname on the target\n target.className = 'standardClassName';\n }\n\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T13:02:13.750", "Id": "5167", "ParentId": "5156", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T09:17:20.647", "Id": "5156", "Score": "3", "Tags": [ "javascript", "beginner", "html", "event-handling" ], "Title": "Mouseover effect for radio buttons" }
5156
<p>It always bugged me that you would have to write your private class members inside the header files in C++. This means that everytime you change you implementation, client code has to be rebuild.</p> <p>I found thise site which describes how to hide implementation detail in C++: <a href="http://www.octopull.demon.co.uk/c++/implementation_hiding.html" rel="nofollow">http://www.octopull.demon.co.uk/c++/implementation_hiding.html</a></p> <p>However I also wanted the code to be generic, so that I didn't have to rewrite the same code for each and every class I create. Here is what I got:</p> <pre><code>#define TL_UTILS_IMPL_DECL(member) \ private: \ class impl; \ impl* member; #define TL_UTILS_IMPL_START(t_class, parent) \ class t_class::impl \ { \ public: \ t_class* parent; \ impl(t_class* self) \ : parent(self) \ {} #define TL_UTILS_IMPL_END() \ }; #define TL_UTILS_IMPL_INIT(member) \ member = new impl(this); #define TL_UTILS_IMPL_TERM(member) \ delete member; #define TL_UTILS_IMPL_PREFIX(t_class) \ t_class::impl:: </code></pre> <p>Example usage:</p> <pre><code>// Header file: class foo { TL_UTILS_IMPL_DECL(m) public: foo(); ~foo(); }; // Source file: TL_UTILS_IMPL_START(foo, p) void bar(); TL_UTILS_IMPL_END() foo::foo() { TL_UTILS_IMPL_INIT(m) // from here on we can use the private // data and methods stored in m m-&gt;bar(); } foo::~for() { TL_UTILS_IMPL_TERM(m) } void TL_UTILS_IMPL_PREFIX(foo) bar() { // do something useful // use p as a pointer to the parent class instance } </code></pre> <p>I always hear that preprocessor macros are dirty and should not be used in C++, and I agree to some degree. However I could not realize what I wanted using templates.</p> <p>So what do you think?</p> <ul> <li>Is the use of preprocessor macros justified here?</li> <li>Is the code safe?</li> <li>Any improvements you can think of?</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T15:49:22.887", "Id": "7762", "Score": "0", "body": "What you are re-inventing here in PIMPL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T16:14:37.893", "Id": "7769", "Score": "0", "body": "I agree with @Tux-D, and my answer reflects some of the drawbacks, referenced here: http://c2.com/cgi/wiki?PimplIdiom" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T16:42:26.850", "Id": "7770", "Score": "0", "body": "@Tux-D: Yes ofcourse this is PIMPL, and I didn't invent it as all as stated. I just wanted to know thought about my implementation." } ]
[ { "body": "<blockquote>\n <p>Is the use of preprocessor macros justified here?</p>\n</blockquote>\n\n<p>To me it seems like overkill. The only non-trivial macro is <code>TL_UTILS_IMPL_START</code>, and that will almost certainly never be useful - usually, the <code>impl</code> class won't need a back-pointer to its wrapper class, but will need other constructor arguments, so you'll usually have to write your own class-specific constructor and initialiser anyway. The other macros are just as verbose as, and much less self-explanatory than, the code they replace.</p>\n\n<blockquote>\n <p>Is the code safe?</p>\n</blockquote>\n\n<p>You need to apply the \"Rule of Three\" - either implement, or remove, the copy constructor and copy assignment operator. I generally use <code>boost::scoped_ptr</code> for the implementation pointer, which sorts this out for me (as well as removing the need for a destructor body).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T17:32:16.077", "Id": "7772", "Score": "0", "body": "+1: Agree. But rather than the adjective overkill I would have used `Obfuscation`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T13:13:57.503", "Id": "5169", "ParentId": "5160", "Score": "3" } }, { "body": "<blockquote>\n <p>It always bugged me that you would have to write your private class\n members inside the header files in C++. </p>\n</blockquote>\n\n<p>This is part of good programming practices. While implementing on these macros (and I agree with @MikeSeymour, that it is overkill), you remember what you are thinking now, but a couple months from now you will have no clue what you were thinking. Also what is immediately evident to you, may not be to another person. If another person can't understand your code or has to spend time deciphering it, that just causes headaches and adds to the development time. Unless you have a damn good reason (and being bugged is not one of them), you really should declare private members in the header.</p>\n\n<blockquote>\n <p>However I also wanted the code to be generic, so that I didn't have to\n rewrite the same code for each and every class I create.</p>\n</blockquote>\n\n<p>If you are focused on generic code, interfaces/templates would be more suitable than a class. If you still want to use OOP, <strong>considering leveraging <a href=\"http://www.cplusplus.com/doc/tutorial/polymorphism/\" rel=\"nofollow\">polymorphism</a> or <a href=\"http://www.cplusplus.com/doc/tutorial/inheritance/\" rel=\"nofollow\">inheritance</a>.</strong> By using these two OOP features, you are able to maintain a generic class and good programming practice. This will also help keep your code safe and manage scope properly. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T13:48:16.570", "Id": "7754", "Score": "0", "body": "One reason would be that client code has to be recompiled every time the implementation changes. I'm not expierienced in writing big software projects but I would imagine build times increasing alot." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T14:03:28.727", "Id": "7756", "Score": "0", "body": "@LukasSchmelzeisen, only the client code that has been modified should be rebuilt. There is no reason to do a clean build every time. Plus one of the advantages of OOP is that individual classes or a group of classes in a module can be tested/rebuilt independent of the entire project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T14:04:59.537", "Id": "7757", "Score": "0", "body": "If you are using OOP as designed, I wouldn't consider recompiling a good enough reason to break good practices and OOP conventions. Remember the phase: **if you are doing something clever, you're probably doing it wrong**" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T13:22:53.613", "Id": "5170", "ParentId": "5160", "Score": "0" } }, { "body": "<p>I certainly sympathize with you about increasing build times. The C++ project I currently work on takes 45 - 60 minutes to build from scratch. But those macros are unreadable. When I see them my eyes glaze over and I don't even want to try to understand what you're doing.</p>\n\n<p><code>void TL_UTILS_IMPL_PREFIX(foo) bar()</code></p>\n\n<p>This line in particular is obnoxious. It looks ugly, it's not at all initially clear why you would do this, and once a developer does figure it out, it'll probably make them angry! =)</p>\n\n<p>Since your concern is compile times, let me suggest a set of strategies that I use to alleviate your problem.</p>\n\n<ol>\n<li>Divide your application into a number of small, focused DLL's.</li>\n<li>Don't expose concrete classes from you DLL. Instead, have your concrete classes implement interfaces, and compile against these interfaces from other DLL's/EXE's.</li>\n</ol>\n\n<p>Check out <a href=\"http://www.codeproject.com/KB/cpp/howto_export_cpp_classes.aspx\" rel=\"nofollow\">this article</a> from CodeProject. Under the heading, Mature Approach: Using an Abstract Interface, for a thorough explanation of point 2.</p>\n\n<p>The end result of these two changes is that all of your DLL's will be able to compile independently of each other. If you keep them small and focused, the cost of recompiling a couple files inside the DLL's isn't too high.</p>\n\n<p>Otherwise, if you really want to use PIMPL, just write the code. Don't bury it in ugly macros.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T17:34:51.640", "Id": "7853", "Score": "0", "body": "+1 Nice article there. I remember reading that some time ago, but some it didn't stick." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T17:30:44.250", "Id": "5210", "ParentId": "5160", "Score": "2" } } ]
{ "AcceptedAnswerId": "5210", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T11:19:23.623", "Id": "5160", "Score": "3", "Tags": [ "c++" ], "Title": "C++: Hiding class implementation detail generic" }
5160
<pre><code>/**************************************************************** VIEW MODULE view, view_database, view_message view_arche_1 (external), view_arche_2 (external) - these are primarily html files ****************************************************************/ /*view*/ class view extends database { } /*view_db*/ class view_db extends view { function __construct($type) { parent::__construct(); $this-&gt;invoke($type); } private function invoke($type) { switch ($type) { case "bookmarks": $this-&gt;html_bookmarks(); break; case "tweets": $this-&gt;html_tweets(); break; default: throw new Exception('Invalid View Type'); break; } } private function html_bookmarks() { $email = $_SESSION['email']; $query_return = database::query("SELECT * FROM bo WHERE email='$email' ORDER BY name ASC"); $html_string=''; while ($ass_array = mysqli_fetch_assoc($query_return)) { $fav=$this-&gt;favicon($ass_array['url']); $html_string = $html_string . "&lt;img name='bo_im' class='c' src='$fav' onerror='i_bm_err(this)'&gt;&lt;a target='_blank' name='a1' class='b' href = $ass_array[url]&gt;$ass_array[name]&lt;/a&gt;"; } echo $html_string; } private function html_tweets() { $query_return = database::query("SELECT * FROM tw ORDER BY time DESC LIMIT 7"); $time = time(); $html_string=''; while ($a = mysqli_fetch_assoc($query_return)) { $html_string = $html_string . "&lt;div class='Bb2b'&gt;&lt;img class='a' src='pictures/$a[email].jpg' alt=''/&gt;&lt;a class='a' href='javascript:void(0)'&gt;$a[fname] posted &lt;script type='text/javascript'&gt;document.write(v0($time,$a[time]))&lt;/script&gt;&lt;/a&gt;&lt;br/&gt;&lt;p class='c'&gt;$a[message]&lt;/p&gt;&lt;/div&gt;"; } echo $html_string; } private function favicon($url) { $pieces = parse_url($url); $domain = isset($pieces['host']) ? $pieces['host'] : ''; if(preg_match('/(?P&lt;domain&gt;[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) { return $pieces['scheme'] . '://www.' . $regs['domain'] . '/favicon.ico'; } return false; } } class view_message extends view { function __construct($type) { $this-&gt;invoke($type); } private function invoke($type) { $this-&gt;message($type); } private function message($type) { $type_message = array( 'empty' =&gt; '&lt;si_f&gt;Please complete all fields.', 'name'=&gt; '&lt;su_f&gt;Only letters or dashes for the name field.', 'email' =&gt; '&lt;si_f&gt;Please enter a valid email.', 'taken' =&gt; '&lt;si_f&gt;Sorry that email is taken.', 'pass' =&gt; '&lt;si_f&gt;Please enter a valid password, 6-40 characters.', 'validate' =&gt; '&lt;si_f&gt;Please contact &lt;a class="d" href="mailto:support@archemarks.com"&gt;support&lt;/a&gt; to reset your password.'); echo $type_message[$type]; } } </code></pre>
[]
[ { "body": "<p>Some random observations:</p>\n\n<ul>\n<li>What does your base class <code>database</code> do? I hope not the stuff it sounds like. Your aim is to separate storage and view logic, not add view logic to your database.</li>\n<li>Having both static and non-static functions in a class should make you suspicious (as this is an indicator this class has one then more objective or is inconsistently written). </li>\n<li>Some functions do <code>echo</code>, some <code>return</code> and some call other functions. Decide for one way ;).</li>\n<li><code>invoke</code> for parameter to function resolving? Have a look at the much cooler magic function <a href=\"http://php.net/manual/en/language.oop5.magic.php\" rel=\"nofollow\"><code>__call</code></a>.</li>\n</ul>\n\n<p>Some suggestions:</p>\n\n<ul>\n<li>It is probably a good idea to move the single view operations into it's own classes. This becomes more important when you add even more operations. </li>\n<li>Unify the way your class is accessed and the return values.</li>\n<li>Views don't extend a database.</li>\n</ul>\n\n<p>Easy to implement way:</p>\n\n<ul>\n<li>Let every view operation be it's own class.</li>\n<li>Define a common interface for all view operations (e.g. <code>ViewOperation</code> with one required function <code>run()</code>).</li>\n<li>Create one main class <code>View</code> that is responsible to resolve view operations to subclasses.</li>\n</ul>\n\n<p>Example implementation:</p>\n\n<pre><code>interface ViewOperation\n{\n public function run();\n}\n\npublic class ControllAdd implements ViewOperation\n{\n private $_types = array('pass' =&gt; '&lt;xx_p&gt;', 'fail' =&gt; '&lt;xx_f&gt;');\n\n public function run()\n {\n $params = func_get_arg(1);\n if(isset($params) &amp;&amp; !empty($params) &amp;&amp; array_key_exists($this-&gt;_types, $params))\n {\n return $this-&gt;_types[$params];\n }\n }\n}\n\npublic class View\n{\n public function __call($name, $arguments)\n {\n // More security required here of course\n require_once './ViewOperartopns/' . $name . '.php';\n\n $instance = new $name;\n return $instance-&gt;run($arguments);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T03:21:31.700", "Id": "8652", "Score": "0", "body": "Thanks...I recently re-structured my code to fit the MVC pattern using this guidline here: http://php-html.net/tutorials/model-view-controller-in-php/ : I'll add in your suggestions as well : Excellent information. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T03:28:44.577", "Id": "8653", "Score": "0", "body": "Why can't I extend a view from my database...if not how than? Here is just my view module..It needs access to the datbase. Theoretcially this should come through the controller...but how do I do this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-01T14:48:07.733", "Id": "8667", "Score": "0", "body": "You sure can, but that'd mix two differenct responsibilites in one class (storage & view). It's the controllers job to pull the data from the database and put it into the view." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T19:06:08.747", "Id": "5199", "ParentId": "5173", "Score": "2" } } ]
{ "AcceptedAnswerId": "5199", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T15:42:57.860", "Id": "5173", "Score": "3", "Tags": [ "php" ], "Title": "MVC Improvement - The View Module - 1" }
5173
<p>Due to software constraints, I cannot use the standard libraries, <code>math.h</code>, <code>algorithm</code>, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.</p> <p>I need to duplicate the <a href="http://www.mathworks.com/help/techdoc/ref/any.html" rel="nofollow">Matlab any function</a> in C / C++ for an array. I currently have written two any functions with different inputs depending on the array size. </p> <ul> <li>Is it possible to write just one <code>any</code> function without using templates? </li> <li>How can I improve performance?</li> </ul> <p>I am striving for <code>const</code> correctness, performance/efficiency, and avoiding implicit type casting. </p> <pre><code>bool any(bool* array, const int N){ // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true bool val; val = array[0] == true; int i = 0; while (val == false &amp;&amp; i &lt; N){ val = array[i++] == true; } return val; } bool any(bool** array, const int nRow, const int nCol){ // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true bool val; val = array[0][0] == true; int i = 0; while (i &lt; nRow &amp;&amp; val == false){ int j = 0; while (j &lt; nCol &amp;&amp; val == false){ val = array[i][j++] == true; } i++; } return val; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:06:43.727", "Id": "7781", "Score": "0", "body": "So I already recommend that `const int N` should be a `size_t`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:51:34.770", "Id": "7787", "Score": "1", "body": "Passing N as a const does not add to const correctness as it is passed by value. Just pass size_t" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T13:24:39.947", "Id": "7819", "Score": "1", "body": "If you must use `== true` to convert a bool to a bool, then remember that the result is still a bool. Therefore, you should write `val = (array[0] == true) == true;`. Or maybe just `val = array[0]`." } ]
[ { "body": "<p>Depending on how you compiler implements it.<br>\nIt may potentially be faster to allcoate a block of zero memory and compare it (This of course will be platform dependent). Some instruction sets allow all the following to be done in one op code (each line). But of course any speed improvements you get have to be weighed against the readability.</p>\n\n<pre><code>bool any(bool* array, size_t N)\n{\n void* comp = alloca(sizeof(bool) * N);\n bzero(comp, sizeof(bool) * N);\n int result = bcmp(array, comp, sizeof(bool) * N);\n\n return result != 0;\n}\n</code></pre>\n\n<p>Personally I think you are way to concerned about micro optimizations.<br>\nThese should be irrelevant to you. The compiler is very good at this kind of macro optimization.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T20:15:43.590", "Id": "7789", "Score": "0", "body": "where do you see macro optimization? I don't have any templates, inlines, or `#define`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T20:19:34.367", "Id": "7790", "Score": "0", "body": "You are worrying about macro optimizations. These are optimizations that the compiler does like peephole, loop-unrolling, etc etc. i.e. Worrying about minor changes in the source to try and make it more efficient." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T20:24:31.460", "Id": "7792", "Score": "0", "body": "I generally agree with you. Unfortunately due to certain software certification issues, I have to worry about minor changes, etc. Please being aware of good software practices techniques is never bad thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T20:25:56.157", "Id": "7793", "Score": "0", "body": "Speaking of good software practices from SO: \"Why is alloca not considered good practice?\" : http://stackoverflow.com/questions/1018853/why-is-alloca-not-considered-good-practice" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T20:48:08.347", "Id": "7794", "Score": "0", "body": "@Elpezmuerto: That's why I used alloca() rather than `bool tmp[N] = {0};` (C99-dynamicallyed size array). The alloca() version makes people look at the code a lot harder to see what is happening, most people are much more blazy about the dynamically sized array but it is just as dangerous and suffers from exactly the same problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T23:12:02.620", "Id": "7802", "Score": "3", "body": "@Tux-D: the usual term for a small, localised optimisation is \"micro-optimisation\" (not \"macro\")." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T00:13:05.173", "Id": "7803", "Score": "0", "body": "@Mike Seymour: dyslexia and fast typing don't mix :-)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:47:46.370", "Id": "5180", "ParentId": "5178", "Score": "1" } }, { "body": "<p>I would suggest having the 2D implementation call the 1D implementation, rather than duplicating the \"any\" logic in both implementations, e.g.</p>\n\n<pre><code>bool any(bool** array, const int nRow, const int nCol){\n // mimics the behavior of Matlab's any() function. Returns true if any element of the array is true\n bool val = false;\n\n for (int i = 0; i &lt; nRow &amp;&amp; val == false; ++i)\n {\n val = any(array[i], nCol); // call 1D version of any\n )\n return val;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T08:56:05.387", "Id": "5208", "ParentId": "5178", "Score": "2" } } ]
{ "AcceptedAnswerId": "5208", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T19:06:18.157", "Id": "5178", "Score": "3", "Tags": [ "c++", "c", "algorithm", "reinventing-the-wheel" ], "Title": "Matlab any function in C / C++" }
5178
<p>So I've been thinking alot about simple/convenient ways to implement simple 2D animation using a bare-bones graphics library I'm using for school (Animation is way out of the scope of the class, I'm just experimenting.)</p> <p>I thought of using a custom function passed to the class to allow the "user" of the code to just write their own code to do whatever they want to the sprite, then return control to the sprite's Update() function. Here's what I have so far:</p> <pre><code>// SpriteStuff.h typedef bool (AnimationStep*)(Sprite* sprite) ANIMATIONSTEP class Sprite { //... ANIMATIONSTEP m_currentAnimation; void BeginAnimation(ANIMATIONSTEP step); void EndAnimation(); void Update(); //... }; void Sprite::BeginAnimation(ANIMATIONSTEP step) { if (step != NULL) m_currentAnimation = step; } void Sprite::EndAnimation() { m_currentAnimation = NULL; } void Sprite::Update() { //... if (m_currentAnimation != NULL) if (!m_currentAnimation(this)) EndAnimation(); //... } // (off in some other code...) void DoAnimateThing() { mySprite-&gt;BeginAnimation(GeneralFallAnimationStep); } bool GeneralFallAnimationStep(Sprite* sprite){ return sprite-&gt;y++ &gt; SOME_LIMIT_SOMEWHERE; } // Could possibly end it early... void CancelAnimationOnThing() { mySprite-&gt;EndAnimation(); } </code></pre> <p>It seems like a pretty simple design that will do what I need, but almost <em>too</em> simple. I'm doing something terribly wrong, huh?</p> <p><strong>EDIT:</strong> So I've gotten some good input on this, but now I'm curious... Any suggestions how controlling the <em>speed</em> of these animations? Can this be done well in the Sprite class, or should that be handled strictly by the <code>ANIMATIONSTEP</code>?</p>
[]
[ { "body": "<p>Too simple? Hardly. That is pretty much a textbook implementation of animation using a callback-based event model. In a production-grade version there would be a few extra null checks and similar to check for programming mistakes, but the basic implemation could be very similar.</p>\n<p>I'm assuming that elsewhere there is a main loop that periodically calls update on each relevant sprite. I'm also assuming that either update takes care of drawing the spite, or that code not shown is responsible for that.</p>\n<h3>One Weakness and Possible Solution</h3>\n<p>One thing though that may be problematic for complicated animations is that your design gives the function no scratch space in which to store any state information (complicated animations may want to know if this is the first or second time the sprite was at coordinate (457,758) for example).</p>\n<p>An easy solution is to add an extra <code>void *</code> to the sprite. This would be an extra pointer the animation function can set to whatever it wants (usually an animation specific structure). Have <code>BeginAnimation</code> set this new pointer to <code>NULL</code>. Document that the pointer must either be left <code>NULL</code>, or allocated with <code>new</code>. <code>EndAnimation</code> would <code>delete</code> the pointer on the animation's behalf if it was not still <code>NULL</code>, since the animation is not given the opertunity to cleanup if <code>EndAnimation</code> is called directly.</p>\n<p>There are cleaner solutions than the above, but the that one is easy to explain, and should work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T22:11:12.840", "Id": "7801", "Score": "0", "body": "Your assumptions are correct; I left them out for brevity. And +1 for adding state. Great idea." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T21:37:37.500", "Id": "5183", "ParentId": "5181", "Score": "3" } }, { "body": "<p>I would say that is the perfect way of doing things if you were programming in C.</p>\n\n<p>But since you tagged this as C++ I would say you are doing it wrong. </p>\n\n<p>Rather than having a pointer to a function I would set an animation object off your sprite. Then you can call the animation step method on this object. Since it is an object it can hold state as required.</p>\n\n<p>Change:</p>\n\n<pre><code>typedef bool (AnimationStep*)(Sprite* sprite) ANIMATIONSTEP\n</code></pre>\n\n<p>Into:</p>\n\n<pre><code>class ANIMATIONSTEP\n{\n public:\n virtual bool animationStep(Sprite* sprite) = 0;\n virtual ~ANIMATIONSTEP() {}\n};\n</code></pre>\n\n<p>Then change:</p>\n\n<pre><code>if (!m_currentAnimation(this)) EndAnimation();\n</code></pre>\n\n<p>Into:</p>\n\n<pre><code>if (!m_currentAnimation-&gt;animationStep(this)) EndAnimation();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T13:42:46.887", "Id": "7820", "Score": "0", "body": "An animation object is indeed a cleaner approach. The existing approach is not \"wrong\" in so far as it works, and is conceptually simple. On advantage of your approach is that adding state is cleaner than my suggestion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T13:49:25.177", "Id": "7821", "Score": "0", "body": "A disadvantage of your approach is that it does not work as-is, since you cannot have an instance of an abstract class in C++, only a reference or a pointer. Using a pointer implies passing ownership of the animation to the sprite. `auto_ptr` could be used, or if availible, `unique_ptr` is preferable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T13:50:51.393", "Id": "7822", "Score": "0", "body": "@Kevin Cathcart: I would still say it is wrong when used in a C++ context. In C it is perfectly valid. It looks simple now because it is unfinished. The trouble with function pointers approach is that to be generic (and thus useful) you also need to pass state information, this will require that you add a `void*` parameter (as not all animation functions will take the same state) stored in the sprite and passed to the animation function for decoding. This breaking of encapsulation is wrong for C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T13:53:55.600", "Id": "7824", "Score": "0", "body": "@Kevin Cathcart: The use of a smart pointer goes without saying for any owned pointer. It works as-as in the same way a function pointer works as-is. If you want to add functionality you have to write the function or the object (if you don't write them you can't use them)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T13:59:47.780", "Id": "7825", "Score": "0", "body": "The alternative is having a public void* member on the Sprite class. (That is admitedly an even worse violation of encapsulation.) I fully agree that in terms of good OO-design, your basic approach is the right approach." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T23:57:53.027", "Id": "5186", "ParentId": "5181", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T20:39:03.993", "Id": "5181", "Score": "5", "Tags": [ "c++" ], "Title": "Animation using function pointers" }
5181
<pre><code>[Bindable] public class ProductsCache { private static var _products:ArrayCollection; public function get products():ArrayCollection{ return _products; } public function set products(value:ArrayCollection):void{ _products = value; } } </code></pre> <p>By the name of the class you see my intentions with this bit of code. I intend to set a "cache" of registries that I intend to use across modules and update accordingly. The get method is used for dropdown lists, the set method after a successful insert statement. </p> <p>This works good for my needs. But I still need your feedback.</p> <p>EDIT: I don't know what voting means here. Is this good code for its purpose? or do I really need to learn factories and dependency injections?</p> <p>I was previously using a singleton for this, but I wasn't comfortable with that, I want to keep the singleton excusively for credential and config data. And use this for the rest of the app functionality.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T07:06:27.797", "Id": "7808", "Score": "0", "body": "Feedback on what? If you should use static variables? If you should do it like that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T14:25:14.683", "Id": "7829", "Score": "0", "body": "Yep. That's important to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T14:26:36.007", "Id": "7830", "Score": "0", "body": "Damn it Jim, state in your question what you want!" } ]
[ { "body": "<p>Using a static variable will have the same effect as using a singleton!</p>\n<p>Imagine if you had two instances of <code>ProductsCache</code>:</p>\n<pre><code>var a: ProductsCache = new ProductsCache();\nvar b: ProductsCache = new ProductsCache();\na.products = someArrayCollection;\nb.products = anotherArrayCollection;\n</code></pre>\n<p>Now, because it's using a static variable, <code>a.products</code> will be <code>anotherArrayCollection</code>.</p>\n<h3>&quot;Do I really need to learn factories and dependency injections?&quot;</h3>\n<p>Yes, please, learn Dependency injection! You won't regret it! I don't think for this particular case you need a Factory pattern, but it never hurts to learn that too.</p>\n<p>Dependency Injection is not that hard actually, the golden rule is: Whenever an object needs your <code>ProductsCache</code>, give them a reference to your <code>ProductsCache</code>. Don't use something like <code>ProductsCache.instance.products</code>. <strong>Tell</strong> objects about the ProductsCache you want them to use, don't let them <strong>ask</strong> a singleton about it. Very easy rule to remember: <strong>Tell, don't ask</strong>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-09T18:47:20.917", "Id": "49362", "ParentId": "5184", "Score": "6" } } ]
{ "AcceptedAnswerId": "49362", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T22:43:54.507", "Id": "5184", "Score": "7", "Tags": [ "actionscript-3", "static" ], "Title": "Getting and setting a static variable" }
5184
<p>I wanted to have a python container in which every element is a key (like in a set), but still supports mapping (like a dict) between the elements. To get a container which supports this idea the elements have to be unique like in a set and the mapping between the elements has to be bidirectional. I couldn't find such thing so I tried to implement it myself.</p> <p>As this is the first data structure I implemented myself in Python I would like to ask if anybody has comments or advices for me.</p> <p><strong>EDIT:</strong> updated version following the recommendations of @Winston and added a better example</p> <pre><code>import copy class Network(object): """ A network is a container similar to a set in which the elements can be mapped to each other (be connected). The Elements in a network are called entities and are unique in the network. Single entities can be inserted into the network by using the method insert(entity). Connections between entities are made using the method connect(entity1, entity2), which automatically inserts the entity/-ies into the network if not existent beforehand. Calling network[entity] returns a subset of the network, containig all the entities connected to the given entity. Removing an entity from the network results in removing all its connections in the network aswell. """ def __init__(self): self._db = {} def __delitem__(self, entity): self.remove(entity) def __getitem__(self, entity): """ Returns a subset of the network, containig all the entities connected to the given entity """ return self._db.__getitem__(entity) def __iter__(self): return self._db.__iter__() def __len__(self): """Returns the number of entities in the network""" return self._db.__len__() def __repr__(self): return self._db.__repr__() def __str__(self): return self._db.__str__() def are_connected(self, entity1, entity2): """Test for a connection between two entities.""" return entity2 in self._db[entity1] #and entity1 in self._db[entity2] def clear(self): """Removes all entities from the network""" self._db.clear() def connect(self, entity1, entity2): """ Connects entity1 and entity2. Automatically inserts the entity/-ies into the network if not existent beforehand.""" self._db.setdefault(entity1, set()).add(entity2) self._db.setdefault(entity2, set()).add(entity1) def connect_many(self, entity, seq): """Connects entity with all entities in seq.""" for e in seq: self.connect(entity, e) def copy(self): """Returns a deep copy of the network""" return copy.deepcopy(self) def entities(self): """Returns a set of the entities in the network.""" return set(self._db.keys()) def get(self, entity, default=None): """Return the set of connected entities of entity if entity is in the network, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.""" return self._db.get(entity, default) def insert(self, entity): """Inserts an entity into the network.""" self._db.setdefault(entity, set()) def isolate(self, entity): """Removes all connections of an entity""" for e in self[entity]: if e != entity: self[e].remove(entity) self._db[entity].clear() def pop(self, entity): """Removes an entity from the network and returns the set of entities it was previously connected with.""" temp = self[entity] self.remove(entity) return temp def remove(self, entity): """Removes an entity and all its connections from the network.""" for e in self[entity]: if e != entity: self[e].remove(entity) del self.db[entity] def setdefault(self, entity): """If entity is in the network, return the set of connected entites. If not, insert entity and return default. default defaults to an empty set.""" return self._db.setdefault(entity, set()) def unique_mapping(self, entity): """If the given entity is mapped to a single other entity this entity is returned, otherwise a ValueError exception is raised.""" entity_set = self._db[entity] if len(entity_set) == 1: return next(iter(entity_set)) else: raise ValueError("The entity '%s' has no unique mapping." % entity) def update(self, netw): """Updates the network with another given network. Equal entities are merged.""" for entity in netw: for e in netw[entity]: self.connect(entity,e) </code></pre> <p>Example usage:</p> <pre><code>&gt;&gt;&gt; friends = Network() &gt;&gt;&gt; friends.connect("Peter","John") &gt;&gt;&gt; friends.connect("Peter","Paul") &gt;&gt;&gt; friends.connect("Steve","John") &gt;&gt;&gt; friends.connect("Bill","Steve") &gt;&gt;&gt; friends.connect("Mark","John") &gt;&gt;&gt; print "%s are friends of John" % ", ".join(friends["John"]) Steve, Peter, Mark are friends of John &gt;&gt;&gt; print "%s is Bills only friend" % friends.unique_mapping("Bill") Steve is Bills only friend </code></pre> <p>Comments/advices about the general implementation of data structures in python and the style of my implementation are as welcome as suggestions regarding the performance, semantics and usage of this container. Basically feel free to critizise or give advice on anything you can come up with. Thanks alot!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T15:59:01.470", "Id": "7851", "Score": "1", "body": "The example confused me a tad, given the class name and behavior of \"network\" I expected to see examples more along the lines of `friends.connect(\"James\", \"Joe\")`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T20:58:16.000", "Id": "7860", "Score": "0", "body": "good point. i changed that to the example you describe which suits the name of the class better." } ]
[ { "body": "<pre><code>class network(object):\n</code></pre>\n\n<p>The python style guide recommends CamelCase for class names</p>\n\n<pre><code> \"\"\"\n A network is a container similar to a set in which\n the elements can be mapped to each other (be connected).\n The Elements in a network are called entities and are\n unique in the network.\n\n Single entities can be inserted into the network by\n using the method insert(entity).\n\n Connections between entities are made using the method\n connect(entity1, entity2), which automatically inserts\n the entity/-ies into the network if not existent beforehand.\n\n Calling network[entity] returns a subset of the network,\n containig all the entities connected to the given entity.\n\n Removing an entity from the network results in removing\n all its connections in the network aswell.\n \"\"\"\n\n def __init__(self):\n self.db = dict()\n</code></pre>\n\n<p>I might call this _db to make it clear that it is private. Empty dictionaries are usually created with <code>{}</code></p>\n\n<pre><code> def __delitem__(self, entity):\n self.remove(entity)\n\n def __getitem__(self, entity):\n \"\"\"\n Returns a subset of the network, containig all the\n entities connected to the given entity\n \"\"\"\n return self.db.__getitem__(entity)\n\n def __iter__(self):\n return self.db.__iter__()\n\n def __len__(self):\n \"\"\"Returns the number of entities in the network\"\"\"\n return self.db.__len__()\n\n def __repr__(self):\n return self.db.__repr__()\n\n def __str__(self):\n return self.db.__str__()\n\n def are_connected(self, entity1, entity2):\n \"\"\"Test for the presence of a connection between entity1 and entity2.\"\"\"\n return entity1 in self.db[entity2] and entity2 in self.db[entity1]\n</code></pre>\n\n<p>Do you actually need to check both?</p>\n\n<pre><code> def clear(self):\n self.db.clear()\n\n def connect(self, entity1, entity2):\n \"\"\"\n Connects entity1 and entity2. Automatically inserts\n the entity/-ies into the network if not existent beforehand.\n \"\"\"\n self.db.setdefault(entity1, set()).add(entity2)\n self.db.setdefault(entity2, set()).add(entity1)\n\n def connect_many(self, entity, seq):\n \"\"\"Connects entity with all entities in seq.\"\"\"\n for e in seq:\n self.connect(entity, e)\n\n def copy(self):\n return self.db.copy()\n\n def entities(self):\n \"\"\"Returns a set of the entities in the network.\"\"\"\n return set(self.db.keys())\n</code></pre>\n\n<p>Why are you returning this as a set? It seems to break symmetry with everything else a dict returns which are lists or generators.</p>\n\n<pre><code> def get(self, entity, default=None):\n return self.db.get(entity, default)\n\n def insert(self, entity):\n \"\"\"Inserts an entity into the network.\"\"\"\n self.db.setdefault(entity, set())\n\n def isolate(self, entity):\n \"\"\"Removes all connections of an entity\"\"\"\n for e in self[entity]:\n if e != entity:\n self[e].remove(entity)\n self.db[entity].clear()\n\n def pop(self, entity):\n temp = self[entity]\n self.remove(entity)\n return temp\n\n def remove(self, entity):\n \"\"\"Removes an entity and all its connections from the network.\"\"\"\n for e in self[entity]:\n if e != entity:\n self[e].remove(entity)\n self.db.__delitem__(entity)\n</code></pre>\n\n<p>Why not <code>del self.db[entity]</code>?</p>\n\n<pre><code> def setdefault(self, entity):\n return self.db.setdefault(entity, set())\n</code></pre>\n\n<p>You are deviating from the dict interface here. Do you have a good reason?</p>\n\n<pre><code> def unique_mapping(self, entity):\n \"\"\"If the given entity is mapped to a single entity this entity is returned\"\"\"\n if len(self.db[entity]) == 1:\n return next(iter(self.db[entity]))\n</code></pre>\n\n<p>You may want to avoid fetching self.db[entity] multiple times</p>\n\n<pre><code> else:\n return False\n</code></pre>\n\n<p>You should throw an exception not return a sentinel value. If you insists on returning a sentinel value use None.</p>\n\n<pre><code> def update(self, netw):\n \"\"\"Updates the network with another given network. Equal entities are merged.\"\"\"\n for entity in netw:\n for e in netw[entity]:\n self.connect(entity,e)\n</code></pre>\n\n<p>You could have this class inherit from dict, and then you'd be able to avoid all of the </p>\n\n<pre><code>def foo(self):\n return self.db.foo()\n</code></pre>\n\n<p>But then you might get methods you don't want as well. Thats a judgment call.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T13:53:37.960", "Id": "7846", "Score": "0", "body": "@eowl, sorry I meant iterator not generator. My point was that keys on a dictionary aren't a set even though they have the same semantics as your entities. Really, it would depend on how your class being used whether or not a set is a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T15:53:28.420", "Id": "7850", "Score": "0", "body": "@eowl, I'm torn between ValueError and a custom error class." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T12:47:24.013", "Id": "5209", "ParentId": "5185", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-04T23:26:31.897", "Id": "5185", "Score": "3", "Tags": [ "python", "performance" ], "Title": "Review for Python mapping container in which every element is a key" }
5185
<p>As I was trying to demystify the Android AsyncTask functionalities, I wrote this sample app to test it. Please review my code and suggest possible improvements:</p> <pre><code>public class AsyncTaskExampleActivity extends Activity implements OnClickListener{ private Boolean success = true; private static AsyncTaskExampleActivity MainActivityInstance; private CallBack c; ProgressDialog progressDialog; Button startAsyncTask; MyAsyncTask aTask; Button cancelAsyncTask; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); startAsyncTask = (Button)findViewById(R.id.button1); cancelAsyncTask = (Button)findViewById(R.id.button2); startAsyncTask.setOnClickListener(this); cancelAsyncTask.setOnClickListener(this); MainActivityInstance = this; //ProgressDialog progressDialog; progressDialog = new ProgressDialog(this.getApplicationContext()); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage("On Progress..."); progressDialog.setCancelable(false); c = new CallBack() { public void onProgress(){ //progressDialog.show(); Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Progress!!", 1000); toast.show(); } public void onResult(Boolean result){ if(result.equals(true)){ Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Bingo...Success!!", 1000); toast.show(); } else { Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Alas!! Failure", 1000); toast.show(); } } public void onCancel(Boolean result){ Toast toast = Toast.makeText(getMainActivity().getApplicationContext(), "Cancelled", 1000); toast.show(); } }; aTask = new MyAsyncTask(c); } static AsyncTaskExampleActivity getMainActivity(){ return MainActivityInstance; } public Boolean getSuccessOrFailureResult(){ return success; } public void onClick(View v){ if(v.equals(startAsyncTask)){ aTask.execute("Start"); } if(v.equals(cancelAsyncTask)){ aTask.cancel(true); } } } </code></pre> <p></p> <pre><code>public class MyAsyncTask extends AsyncTask&lt;String, Integer, Boolean&gt; { private CallBack cb; Boolean running = true; MyAsyncTask(CallBack cb){ this.cb = cb; } protected Boolean doInBackground(String... params){ while(running){ if(isCancelled()){ break; } try{ for (int i = 0; i&lt;5; i++){ if(isCancelled()){ break; } Thread.sleep(10000,0); publishProgress(); } } catch(InterruptedException e){ return false; } return true; } return false; } protected void onProgressUpdate(Integer... progress){ cb.onProgress(); } protected void onPostExecute(Boolean result){ cb.onResult(result); } protected void onCancelled(){ running = false; cb.onCancel(true); } } </code></pre> <p></p> <pre><code>public interface CallBack { public void onProgress(); public void onResult(Boolean result); public void onCancel(Boolean result); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-05T15:12:24.397", "Id": "86015", "Score": "0", "body": "Look at the newly inserted code if(isCancelled()){\n break;\n } in the doInBackground function. This is to ensure that the background thread does not continue to process when the cancel button is pressed.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T01:38:29.440", "Id": "86109", "Score": "0", "body": "Here is the link of my research on Asynctask internals.[Asynctask Internals by Somenath Mukhopadhyay](http://www.slideshare.net/som.mukhopadhyay/asynctaskand-halfsynchalfasyncpattern). Hope you like this..." } ]
[ { "body": "<ul>\n<li>If you rotate the screen, the activity will be restarted, which will restart the task as well (it might even crash because of the ProgressDialog). Eventually, I have found that only services can correctly handle long running operations. But they are more complicated to code.</li>\n<li>You don't follow naming conventions from Android, and several names make no sense at all. For instance <code>AsyncTaskExampleActivity.c</code> should be named <code>AsyncTaskExampleActivity.mCallback</code> </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T02:11:16.640", "Id": "86111", "Score": "0", "body": ". Your first comment is absolutely right . I understand the flaws in the naming convention. Thank you for reviewing the code...." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-23T13:03:43.003", "Id": "7109", "ParentId": "5191", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T08:26:42.733", "Id": "5191", "Score": "4", "Tags": [ "java", "android", "asynchronous" ], "Title": "AsynTask example" }
5191
<p>I have a block of text where several arrays are printed out, with a name and values:</p> <blockquote> <p>VAL1=10 20 30 40 50</p> <p>VAL2=4 8 15 16 23 42</p> </blockquote> <p>I have a function that looks for the value name, and sets an array of these values:</p> <pre><code>bool FetchValueArray(char* source, char* name, char* typeFormat, int count, void* destination, size_t destElementSize) { int i; char *t; t=strstr(source,name); if (t) if (destination != NULL) { for (i = 0;i &lt; count;i++) sscanf(t, typeFormat, (char*)destination + destElementSize * i); return true; } return false; } </code></pre> <p>Called thus:</p> <pre><code>FetchValueArray(source, &quot;VAL1=&quot;, &quot;%d&quot;, 5, val1array, sizeof(val1array[0]); FetchValueArray(source, &quot;VAL2=&quot;, &quot;%d&quot;, 6, val1array, sizeof(val1array[0]); </code></pre> <p>This is from a <a href="https://stackoverflow.com/questions/7651998/void-parameter-called-with-a-fixed-array-value">StackOverflow question</a>. As the answerer wrote, it <em>works</em>, but it's not safe. If I call it with a <code>count</code> that is higher than the size of the array, I will corrupt the memory. I'm trying to wrap my head around this one and having a tough time. How can I have a function that will set values to a fixed array and be &quot;safe&quot;?</p>
[]
[ { "body": "<p>I'm not quite sure what you are asking for, but I guess you are looking for a solution similar to this (not compiled nor tested):</p>\n\n<pre><code>#include &lt;stdio.h&gt; /* sscanf */\n#include &lt;stddef.h&gt; /* NULL */\n#include &lt;stdbool.h&gt; /* C99 bool type */\n\ntypedef enum\n{\n TYPE_CHAR = 'c',\n TYPE_INT = 'd',\n TYPE_FLOAT = 'f',\n // etc\n} Type_t;\n\n\n\n/* I placed destination first to use the same parameter order as standard library\n functions (strstr for example). Note the const correctness for read-only parameters. */\n\nbool FetchValueArray (void* dest, \n const char* source,\n const char* name,\n size_t count,\n Type_t type)\n\n{\n const char* strptr; /* Some string pointer (not sure what it does) */\n BOOL is_found; /* Is the name found? */\n\n if(dest == NULL) /* No need to do anything if this parameter is NULL */\n {\n return false;\n }\n\n\n strptr = strstr(source, name);\n is_found = strptr != NULL; /* Boolean arithmetic */\n\n if(is_found)\n {\n size_t i;\n size_t item_size;\n const char format[2] = {'%', (char)type};\n\n switch(type)\n {\n case TYPE_CHAR: item_size = 1; break;\n case TYPE_INT: item_size = 4; break;\n case TYPE_FLOAT: item_size = 4; break;\n }\n\n for(i=0; i&lt;count; i++)\n {\n sscanf(strptr, format, (char*)dest + item_size*i);\n }\n }\n\n return is_found;\n}\n</code></pre>\n\n<p><strong>EDIT:</strong>\nRegarding array bounds checking. First you have to decide whether this is actually your concern or if you should leave it up the caller. Most commonly, you document every parameter in the .h file and state how the function should be called. If someone still decides to call it with incorrect parameters, it is then their own fault. That's how most C functions work and in this particular case, that's what I would recommend. </p>\n\n<p>Since C does not store the array size together with the array as one single data type, you can't really pass an array size \"safely\" between the caller and a function, the caller is the one with the knowledge about the size, so you simply have to trust the programmer writing the caller.</p>\n\n<p>You could write something like this</p>\n\n<pre><code>bool FetchValueArray(char dest[25], ...\n</code></pre>\n\n<p>but there are still no guarantees by the standard that this is safe. Some compilers will toss a warning if you try to pass anything but a fixed char array of 25 items to this function, but they don't have to. And we'd lose the generic type, so it isn't helpful.</p>\n\n<p>You <em>could</em> do something like this, but I would <em>not</em> recommend it:</p>\n\n<pre><code>#define SIZE 25\n\ntypedef union\n{\n char char_array[SIZE];\n int int_array[SIZE];\n float float_array[SIZE];\n\n} GenericSafeArray_t;\n</code></pre>\n\n<p>This will allocate <code>SIZE*sizeof(float)</code>, since float happend to be the largest type. So it is memory-ineffective and not particularly flexible either.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T14:01:58.650", "Id": "7827", "Score": "0", "body": "I like the enum. I'm still not convinced on safety though. What's to prevent me (or someone else) from calling it with a int[2] as the target and a count of 10?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T06:49:00.483", "Id": "7844", "Score": "0", "body": "@MPelletier Edited my post with an answer." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T13:27:32.517", "Id": "5194", "ParentId": "5192", "Score": "4" } }, { "body": "<p>Now there are some tricks if you have a real array:</p>\n\n<pre><code>int data[5];\nsizeof(data) =&gt; sizeof(int) * 5\nsizeof(data)/sizeof(data[0]) =&gt; Number of elements in the array\n Note this is also safe if the array has zero elements\n As sizeof is evaluated at compile time not run-time.\n</code></pre>\n\n<p>so if you have a real array then you can call your method like this:</p>\n\n<pre><code>int val1array[5];\nFetchValueArray(source, \"VAL1=\", \"%d\",\n sizeof(val1array)/sizeof(val1array[0]), \n val1array,\n sizeof(val1array[0])\n );\n</code></pre>\n\n<p>The trouble is this seems to work and compiles if val1array is a pointer to an array. Unfortunately in this case sizeof(val1array) will return the size of the pointer, and sice you can not pass arrays as arguments to functions in C (they decay into pointers) there is no way to determine the size of the array on the other side of the function.</p>\n\n<p>So (<strong>Rule of Thumb</strong>) if you ever pass an array as a parameter then you should also pass its size using the trick above and pass that information forward with the array at all times.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T16:02:53.767", "Id": "5195", "ParentId": "5192", "Score": "2" } } ]
{ "AcceptedAnswerId": "5194", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T11:01:27.000", "Id": "5192", "Score": "4", "Tags": [ "c", "array", "memory-management" ], "Title": "Array initialization from text string" }
5192
<p>The following is a function that I wrote to display page numbers as they appear in books.</p> <p>If you enter the list <code>[1,2,3,6,7,10]</code>, for example, it would return:</p> <pre><code>1-3,6-7,10 </code></pre> <p>This seemed like a nice example of how the dictionary data type can be used in Python.</p> <p>Is there is an even more code-efficient way to do this?</p> <pre><code>def formatpagelist (numberlist): tempdic={} returnstring='' for number in numberlist: if number-1 in tempdic.keys(): tempdic[number-1]=number elif number-1 in tempdic.values(): for key in tempdic.keys(): if number-1==tempdic[key]: foundkey=key tempdic[foundkey]=number else: tempdic[number]=0 keylist=list(tempdic.keys()) keylist.sort() for key in keylist: if tempdic[key]&gt;0: returnstring+=(str(key)+'-'+str(tempdic[key])+',') else: returnstring+=str(key)+',' return returnstring </code></pre>
[]
[ { "body": "<p>A bit shorter version without using a dictionary:</p>\n\n<pre><code>def formatpagelist(numberlist):\n prev_number = min(numberlist) if numberlist else None\n pagelist = list()\n\n for number in sorted(numberlist):\n if number != prev_number+1:\n pagelist.append([number])\n elif len(pagelist[-1]) &gt; 1:\n pagelist[-1][-1] = number\n else:\n pagelist[-1].append(number)\n prev_number = number\n\n return ','.join(['-'.join(map(str,page)) for page in pagelist])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T17:51:58.747", "Id": "5198", "ParentId": "5196", "Score": "4" } }, { "body": "<p>You could use this one-liner to generate groups of consecutive integers in a list:</p>\n\n<pre><code>from itertools import groupby, count\n\ngroupby(numberlist, lambda n, c=count(): n-next(c))\n</code></pre>\n\n<p>Then to finish it off, generate the string from the groups.</p>\n\n<pre><code>def as_range(iterable): # not sure how to do this part elegantly\n l = list(iterable)\n if len(l) &gt; 1:\n return '{0}-{1}'.format(l[0], l[-1])\n else:\n return '{0}'.format(l[0])\n\n','.join(as_range(g) for _, g in groupby(numberlist, key=lambda n, c=count(): n-next(c)))\n# '1-3,6-7,10'\n</code></pre>\n\n<p>This assumes they are in sorted order and there are no duplicates. If not sorted, add a <code>sorted()</code> call on <code>numberlist</code> beforehand. If there's duplicates, make it a <code>set</code> beforehand.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T00:11:35.367", "Id": "7839", "Score": "0", "body": "You'll never hit that IndexError. If `len(l) == 1` then `l[0] == l[-1]` and you'll never get IndexError" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T01:05:27.883", "Id": "7840", "Score": "0", "body": "Ah, thanks for pointing that out. That was a last minute change and I mixed up one idea for another." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-24T00:38:12.277", "Id": "11105", "Score": "0", "body": "+1 for the enumerate + groupby pattern to group consecutive elements (I think to recall it's somewhere in the docs)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-12T15:59:44.623", "Id": "32746", "Score": "1", "body": "FWIW, the output feature of [intspan](http://pypi.python.org/pypi/intspan) uses this technique." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-03-28T21:53:25.343", "Id": "365958", "Score": "1", "body": "this is a really neat solution :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-14T10:21:44.590", "Id": "434700", "Score": "0", "body": "This is great! what way of thinking made you think of implementing it this way?" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T19:29:23.797", "Id": "5202", "ParentId": "5196", "Score": "18" } }, { "body": "<pre><code>def formatpagelist (numberlist):\n</code></pre>\n\n<p>The python style guide recommends words_with_underscores for function names. </p>\n\n<pre><code> tempdic={}\n</code></pre>\n\n<p>This is a really bad variable name. It tells me nothing about what the variable is used for. It tells me the variable is temporary (like all variables) and that its a dict, which obvious given the {}</p>\n\n<pre><code> returnstring=''\n</code></pre>\n\n<p>This doesn't show up until way later... Why is it here?</p>\n\n<pre><code> for number in numberlist:\n if number-1 in tempdic.keys():\n</code></pre>\n\n<p>This is the same as <code>number - 1 in tempdic:</code> </p>\n\n<pre><code> tempdic[number-1]=number\n elif number-1 in tempdic.values():\n for key in tempdic.keys():\n if number-1==tempdic[key]: foundkey=key\n</code></pre>\n\n<p>If you've got scan over the keys of a dictionary, that is a sign you probably shouldn't be using a dictionary. </p>\n\n<pre><code> tempdic[foundkey]=number\n else:\n tempdic[number]=0\n\n keylist=list(tempdic.keys())\n keylist.sort()\n</code></pre>\n\n<p>This the same thing as <code>keylist = sorted(tempdic)</code></p>\n\n<pre><code> for key in keylist:\n if tempdic[key]&gt;0:\n returnstring+=(str(key)+'-'+str(tempdic[key])+',')\n else: returnstring+=str(key)+','\n</code></pre>\n\n<p>I think putting those on one line makes it harder to read. You are usually better off building a list and then joining the list.</p>\n\n<pre><code> return returnstring\n</code></pre>\n\n<p>Here is another approach: I stole parts from @Jeff, but I wanted to try a different approach.</p>\n\n<pre><code>import collections\n\npages = [1,2,5,6,7,9]\nstarts = collections.OrderedDict()\nends = collections.OrderedDict()\nfor idx, page in enumerate(pages):\n section = page - idx\n starts.setdefault(section, page)\n ends[section] = page\npage_parts = []\nfor section, start in starts.items():\n end = ends[section]\n if start == end:\n page_parts.append(\"{0}\".format(start))\n else:\n page_parts.append(\"{0}-{1}\".format(start, end))\nprint(','.join(page_parts))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T04:03:07.280", "Id": "7842", "Score": "0", "body": "all good points! I really have to learn python naming conventions...And I think you are basically right that using a dictionary is kind of pointless when you have to reverse-search on the values. It is also probably a waste of memory here, since you are storing information when there is actually no need to." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T00:07:54.530", "Id": "5206", "ParentId": "5196", "Score": "1" } }, { "body": "<p>Your use of the dictionary seems to be a way to allow the numbers to arrive out-of-order.\nRather than sort them, you seem to be trying to use a dictionary (and associated hashing) to maximize efficiency.</p>\n\n<p>This doesn't really work out perfectly, since you wind up doing sequential searches for a given value. </p>\n\n<p>Hashing a low:high range (a dictionary key:value pair) to avoid a search doesn't help much. Only they key gets hashed. It does help in the case where you're extending a range at the low end. But for extending a range at the high end, you have to resort to searches of the dictionary values.</p>\n\n<p>What you're really creating is a collection of \"partitions\". Each partition is bounded by a low and high value. Rather than a dictionary, you can also use a trivial tuple of (low, high). To be most Pythonic, the (low,high) pair includes the low, but does not include the high. It's a \"half-open interval\".</p>\n\n<p>Here's a version using a simple <code>set</code> of tuples, relying on hashes instead of bisection.</p>\n\n<p>A binary search (using the <code>bisect</code> module) may perform well, also. It would slightly simplify adjacent range merging, since the two ranges would actually be adjacent. However, this leads to a cost in restructuring the sequence.</p>\n\n<p>You start with an empty set of partitions, the first number creates a trivial partition of just that number.</p>\n\n<p>Each next number can lead to one of three things.</p>\n\n<ol>\n<li><p>It extends an existing partition on the low end or high end. The number is adjacent to exactly one range.</p></li>\n<li><p>It creates a new partition. The number is not adjacent to any range.</p></li>\n<li><p>It \"bridges\" two adjacent partitions, combining them into one. The number is adjacent to two ranges.</p></li>\n</ol>\n\n<p>It's something like this. </p>\n\n<pre><code>def make_ranges(numberlist):\n ranges=set()\n for number in numberlist:\n print ranges, number\n adjacent_to = set( r for r in ranges if r[0]-1 == number or r[1] == number )\n if len(adjacent_to) == 0:\n # Add a new partition.\n r = (number,number+1)\n assert r[0] &lt;= number &lt; r[1] # Trivial, right?\n ranges.add( r )\n elif len(adjacent_to) == 1:\n # Extend this partition, build a new range.\n ranges.difference_update( adjacent_to )\n r= adjacent_to.pop()\n if r[0]-1 == number: # Extend low end\n r= (number,r[1])\n else:\n r= (r[0],number+1) # Extend high end\n assert r[0] &lt;= number &lt; r[1] \n ranges.add( r )\n elif len(adjacent_to) == 2:\n # Merge two adjacent partitions.\n ranges.difference_update( adjacent_to )\n r0= adjacent_to.pop()\n r1= adjacent_to.pop()\n r = ( min(r0[0],r1[0]), max(r0[1],r1[1]) )\n assert r[0] &lt;= number &lt; r[1]\n ranges.add( r )\n return ranges\n</code></pre>\n\n<p>This is a pretty radical rethinking of your algorithm, so it's not a proper code review.</p>\n\n<p>Assembling a string with separators is simpler in Python. For your example of \",\"-separated strings, always think of doing it this way.</p>\n\n<pre><code>final = \",\".join( details )\n</code></pre>\n\n<p>Once you have that, you're simply making a sequence of details. In this case, each detail is either \"x-y\" or \"x\" as the two forms that a range can take.</p>\n\n<p>So it has to be something like </p>\n\n<pre><code>details = [ format_a_range(r) for r in ranges ]\n</code></pre>\n\n<p>In this example, I've shown the format as an in-line <code>def</code>. It can be done as an <code>if-else</code> expression, also.</p>\n\n<p>Given your ranges, the overall function is this.</p>\n\n<pre><code>def formatpagelist (numberlist):\n ranges= make_ranges( numberlist )\n def format_a_range( low, high ):\n if low == high-1: return \"{0}\".format( low )\n return \"{0}-{1}\".format( low, high-1 )\n strings = [ format_a_range(r) for r in sorted(ranges) ]\n return \",\".join( strings )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T13:30:42.257", "Id": "7890", "Score": "0", "body": "thank you. this is a very interesting approach... I think I have to study it to see how it really works. But I like the idea of tuples. Your remark about the advantages of using a dictionary got me to think of another way of doing it without having to sort. I added the new version above." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T14:40:35.993", "Id": "7895", "Score": "0", "body": "@AnthonyCurtisAdler: It's very, very hard to comment on two pieces of code. Please post the second one separately. Also, your algorithm does not *appear* to handle the `[ 1, 2, 4, 5, 3 ]` case correctly. It might -- I didn't test it -- but it's an easy case to miss." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T15:10:39.107", "Id": "7896", "Score": "0", "body": "I posted a new version. I tested it with a long set, and included the test call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T15:20:04.040", "Id": "7897", "Score": "0", "body": "@AnthonyCurtisAdler: \"a long set\"? Large is not a good thing for test cases. Small and specific is a good thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T23:04:17.237", "Id": "7916", "Score": "0", "body": "thank you! --- i really appreciate your comments. I've been learning a lot. I posted a new version which addresses the specific criticisms, and also slightly changes the algorithm to avoid the inefficiency. Though now it converts the set into a list, which means that it will run a sorting procedure. I am also curious if there would be a more efficient way to iterate over the set, such as using an iter() instead of listing the set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T13:32:07.793", "Id": "7933", "Score": "0", "body": "\"using an iter() instead of listing the set\"? They're the same thing. What are you asking? Use `timeit` to measure." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T19:01:44.857", "Id": "5214", "ParentId": "5196", "Score": "0" } }, { "body": "<p>I simplified the solution proposed by @tobigue which seems to work great:</p>\n\n<pre><code>def group_numbers(numbers):\n units = []\n prev = min(numbers)\n for v in sorted(numbers):\n if v == prev + 1:\n units[-1].append(v)\n else:\n units.append([v])\n prev = v\n return ','.join(['{}-{}'.format(u[0], u[-1]) if len(u) &gt; 1 else str(u[0]) for u in units])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T16:08:13.317", "Id": "407989", "Score": "1", "body": "Welcome to Code Review! Bearing in mind that the OP did ask \"_Is there is an even more code-efficient way to do this?_\", this feels more like feedback for an answer, not the original question. Technically, you have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process. Please read [Why are alternative solutions not welcome?](https://codereview.meta.stackexchange.com/a/8404/120114)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-07T15:48:01.543", "Id": "211042", "ParentId": "5196", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T16:05:07.040", "Id": "5196", "Score": "13", "Tags": [ "python", "clustering", "interval" ], "Title": "Grouping consecutive numbers into ranges in Python 3.2" }
5196
<p>This code connects to COM 3 which has a broadband card and sends a command that returns the RSSI value. I use this program to see patterns in signal strength in certain areas.</p> <pre><code>#include &lt;Windows.h&gt; #include &lt;iostream&gt; #include &lt;string&gt; int main() { HANDLE hSerial = CreateFile("COM3",GENERIC_READ | GENERIC_WRITE,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if(hSerial==INVALID_HANDLE_VALUE) std::cout &lt;&lt; "Insert error message"; DCB dcbSerialParams = {0}; dcbSerialParams.DCBlength=sizeof(dcbSerialParams); if (!GetCommState(hSerial, &amp;dcbSerialParams)) std::cout &lt;&lt; "Insert error message"; dcbSerialParams.BaudRate=CBR_9600; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; if (!SetCommState(hSerial,&amp;dcbSerialParams)) std::cout &lt;&lt; "Insert error message"; COMMTIMEOUTS timeouts={0}; timeouts.ReadIntervalTimeout=50; timeouts.ReadTotalTimeoutConstant=50; timeouts.ReadTotalTimeoutMultiplier=10; timeouts.WriteTotalTimeoutConstant=50; timeouts.WriteTotalTimeoutMultiplier=10; if(!SetCommTimeouts(hSerial, &amp;timeouts)) std::cout &lt;&lt; "Insert error message"; while(1) { char szBuff[50+1] = {0}; char wzBuff[14] = {"AT+CSQ\r"}; DWORD dZBytesRead = 0; DWORD dwBytesRead = 0; if(!WriteFile(hSerial, wzBuff, 7, &amp;dZBytesRead, NULL)) std::cout &lt;&lt; "Write error"; if(!ReadFile(hSerial, szBuff, 50, &amp;dwBytesRead, NULL)) std::cout &lt;&lt; "Read Error"; std::string subString = std::string(szBuff).substr(8,3); std::cout &lt;&lt; subString; Sleep(500); } return 0; } </code></pre>
[]
[ { "body": "<p>In all the test that could be an error. Do you really want to continue if there is an error?<br>\nSeems counterproductive to generate an error message and continue running. That will just generate more spurious errors.</p>\n\n<pre><code>if(hSerial==INVALID_HANDLE_VALUE)\n{\n throw std::runtime_error(\"Insert error message\");\n}\n</code></pre>\n\n<p>Then just wrap your code in a try catch block:</p>\n\n<pre><code>try\n{\n ... Code here\n}\ncatch(std::exception const&amp; e)\n{\n std::cerr &lt;&lt; \"Exception: \" &lt;&lt; e.what() &lt;&lt; \"\\n\";\n throw; // re-throw so the OS can provide help if available.\n}\ncatch(...)\n{\n std::cerr &lt;&lt; \"Exception: Unknown ...\\n\";\n throw;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T19:15:45.927", "Id": "5200", "ParentId": "5197", "Score": "1" } }, { "body": "<p>In addition to what's already been said, here's some comments and handy things to keep in mind.</p>\n\n<ul>\n<li><p>Good practice is to always open COM ports with a string looking like \\.\\COM3, otherwise you won't be able to open COM ports above number 10. That's quite a hard bug to catch unless you are aware of it. In C this will look like:</p>\n\n<pre><code>CreateFile(\"\\\\\\\\.\\\\COM3\" ...\n</code></pre></li>\n<li><p>You should always check the nature of the incoming data no matter if <code>ReadFile</code> was successful. There may be junk data and noise on the RS-232, especially at the moment when a classic 9-pin dsub connector is connected/removed. In your case with AT commands it is easy, you must just check if the data is valid ASCII or a null termination. If not, you received some junk data. </p>\n\n<pre><code>if(isalnum(ch) || isspace(ch) || ch=='\\0')\n{\n // ok\n}\nelse\n{\n // error\n}\n</code></pre></li>\n<li><p>If <code>Readfile</code> failed, you might want to add some additional checks, at the very least:</p>\n\n<pre><code>DWORD last_error = GetLastError();\nif(last_error == ERROR_OPERATION_ABORTED)\n{\n // There is nobody sending any longer, close the port?\n}\n</code></pre></li>\n<li><p>Close the ports when you aren't using them any longer. As long as you haven't closed the port with <code>CloseHandle()</code>, you will block other programs from using that port. Windows will probably do that when the program terminates, but good practice is to always clean up your own mess.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T14:56:05.190", "Id": "5284", "ParentId": "5197", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T17:07:57.447", "Id": "5197", "Score": "3", "Tags": [ "c++", "windows", "serial-port" ], "Title": "Serial port communication app" }
5197
<p>I'm refactoring a set of classes which does some price calculations. the calculation is done based on many parameters. The code is :</p> <pre><code>public interface IParcel { int SourceCode { get; set; } int DestinationCode { get; set; } int weight{get;set;} decimal CalculatePrice(); } public abstract class GeneralParcel : IParcel { //implementation of inteface properties //these properties set with in SourceCode &amp; DestinationCode //and are used in CalculatePrice() inside classes that inherit from GeneralParcel protected SourceProvinceCode{get; protected set;} protected DestinationProvinceCode{get;protected set;} //private variables we need for calculations private static ReadOnlyDictionary&lt;int, List&lt;int&gt;&gt; _States_neighboureness; private static ReadOnlyCollection&lt;City&gt; _Citieslist; private static ReadOnlyCollection&lt;Province&gt; _Provinceslist; protected ReadOnlyCollection&lt;City&gt; Citieslist {get { return _Citieslist; }} protected ReadOnlyCollection&lt;Province&gt; ProvincesList {get { return _Provinceslist; }} protected ReadOnlyDictionary&lt;int, List&lt;int&gt;&gt; StatesNeighboureness {get {return _States_neighboureness; }} //constructor code that initializes the static variables //implementation is in concrete classes public abstract decimal CalculatePrice(); } public ExpressParcel : GeneralParcel { public decimal CalculatePrice() { //use of those three static variables in calculations // plus other properties &amp; parameters // for calculating prices } } public SpecialParcel : GeneralParcel { public decimal CalculatePrice() { //use of those three static variables in calculations // plus other properties &amp; parameters // for calculating prices } } </code></pre> <p>Right now, the code uses <strong>"Strategy pattern"</strong> efficiently.</p> <p>my question is that those three static properties, really are not part of parcel object, they are need only for price calculations, so which design pattern or wrapping(refactoring), is suggested?</p> <p>Is having another interface as below necessary (&amp; then wrap those static properties inside it?, even make static that class, because it is basically only some calculations), then how to connect it to IParcel? Doing so, how best to implement <strong>CalculatePrice()</strong> in <strong>SpecialParcel</strong> &amp; <strong>ExpressParcel</strong> classes?</p> <pre><code>public interface IPriceCalculator { decimal CalculatePrice(); } </code></pre>
[]
[ { "body": "<p>Depending on the rest of your design, having a <code>Parcel</code> know how to calculate it's ownworth is perfectly acceptable behaviour. That said, the method of calculation is now tied directly to the parcel class itself (what happens if your local government decides that <code>ExpressParcels</code> under a specific weight should be charged like a <code>GeneralParcel</code> - or worse, some other subclass?).</p>\n\n<p>Also, the three dictionaries likely do <em>not</em> belong in the parcel class at all. I can't imagine that is the only location that type of information is relevant. Shipping/truck routing procedures also come to mind. You should see if this is the case, or if the logic/data is indeed unique.</p>\n\n<p>With that stated, here's some possibilities for refactoring in this situation. You're on the right track with <code>IPriceCalculator</code>; you should modify it to take an <code>IParcel</code> object.</p>\n\n<p>1) Implement <code>IPriceCalculator</code>, store as class (<code>static</code>) variable in <code>IParcel</code> subclasses. </p>\n\n<pre><code>public class GeneralParcel : IParcel {\n\n private static IPriceCalculator calc = new IPriceCalculator() {\n\n public decimal Calculate(IParcel parcel) {\n return weight * .1;\n }\n }\n}\n</code></pre>\n\n<p>This allows price calculators to be shared between classes, looked up from a static factory, etc. However, it doesn't allow easy change of the calculator used for a specific instance of that class (such as, say, applying coupon rules). And you still have to ask the parcel how much it is.</p>\n\n<p>2) Implement <code>IPriceCalculator</code>, store as instance variable in <code>IParcel</code> subclasses.</p>\n\n<pre><code>public class GeneralParcel : IParcel {\n\n private IPriceCalculator calc;\n\n public decimal Price {\n get {\n return calc.Calculate(this);\n }\n }\n\n public GeneralParcel(IPriceCalculator calc) {\n this.calc = calc;\n }\n\n}\n</code></pre>\n\n<p>This allows prices calculators to be shared and swapped out as necessary. The catch is that an individual parcel can't know all the possible restrictions to make the choice, and a calculator shouldn't know about any of the others. Parcel still knows how much it is.</p>\n\n<p>3) Implement <code>IPriceCalculator</code>, lookup from stored cache, store result in <code>IParcel</code> subclasses.</p>\n\n<pre><code>public class GeneralParcel : IParcel {\n\n private decimal price = -1;\n\n public decimal Price {\n get {\n if (price &lt; 0) {\n price = CalculatorLookup.find(this).calculate(this);\n }\n return price;\n }\n }\n\n public GeneralParcel() {\n\n }\n}\n</code></pre>\n\n<p>This of course caches out the information, preventing costly recalcs. However, getting line-item charges may be dificult, and some of the <code>Lookup</code> rules might be interesting.</p>\n\n<p><hr/>\nFinally, my favorite, and the most flexible;</p>\n\n<p>4) Create (and implement) a series of *<em>PriceCalculation</em>*s, store <code>IPriceCalculation</code> in <code>IParcel</code> subclass instances.</p>\n\n<pre><code>public interface IPriceCalculation {\n public decimal Calculate {get;}\n\n public IPriceCalculation AddRule(IPriceCalculation calc, IParcel parcel);\n}\n</code></pre>\n\n<p>impl</p>\n\n<pre><code>public struct BaseFeeCalculation {\n private readonly decimal price;\n\n public decimal Calculate {\n get {\n return price;\n }\n }\n\n private BaseFeeCalculation (IPriceCalculation calc) {\n if (calc == null) {\n price = 5;\n } else {\n price = 5 + calc.Calculate;\n }\n }\n\n public IPriceCalculation AddRule(IPriceCalculation calc, IParcel parcel) {\n return new BaseFeeCalculation(calc);\n }\n\n}\n</code></pre>\n\n<p>I recommend that the calculations be structs, and immutable. You're probably going to want to add other things to them, like the ability to report their individual price (for line items), and not just the total. Additionally, while immutablility will help avoid circular references, you may want to add something to check for existing calculations (probably shouldn't have two <code>BaseFee</code>s, after all).</p>\n\n<p>Parcel basically stays the same; just add a property that returns the <code>IPriceCalculation</code> used.</p>\n\n<p>When adding rules, try something along the lines of the following:</p>\n\n<pre><code>public struct CalculationBuilder {\n\n // You'll need to initialize this somehow, obviously.\n private static readonly IList&lt;IPriceCalculation&gt; calculations;\n\n private CalculationBuilder() {}\n\n private static IPriceCalculation Build(IParcel parcel) {\n IPriceCalculation calc; \n\n foreach(IPriceCalculation calcer : calculations) {\n calc = calc.AddRule(calcer, parcel);\n } \n\n return calc;\n }\n }\n</code></pre>\n\n<p>This works well for anything short of dependent rules (although can be adapted fairly easily for that). Usually, the list of calculations can/should be initialized through a DI/Autowiring framework (like Spring).</p>\n\n<p>Oh, and thank you for using <code>decimal</code>, and not <code>double</code> for your price calculation.</p>\n\n<p>... that was a bit long, wasn't it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T22:52:46.577", "Id": "7838", "Score": "1", "body": "Long, beautiful and Complete. Many thanks, let test and report results. Need special attention." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T05:02:36.427", "Id": "7843", "Score": "1", "body": "Great answer, but if I can make an obvious comment that with the original solution (in the question), it is far easier to \"understand\" instantly what is going on by glancing quickly at the code. This proposed solution is far more complex (and yet also far more powerful). If there is actually only a limited set of parcel types/calcs, then the original (simpler) solution may be fine as is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T15:33:52.273", "Id": "7849", "Score": "0", "body": "@dodgy_coder - I know, which is why Solution 1 and 2 are there. They give a little more flexiblility, without being all that (much) more complex. But the adaptability of solution 4... was just too much to pass up; with a component based `IParcel` I can add a `HolidayWrappingFee` to every parcel type in under 5 minutes (by implementing the new calculation, and adding the component to the parcel), with the existing solution I have to actually modify _everything_." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T16:39:23.433", "Id": "7852", "Score": "0", "body": "I myself prefer solution 4. the project right now is very complex and there are many more development ahead. for example we need to add TNT & DHL support. also we have discount for bulk parcels, there are even discounts for blinds(for under 7Kg parcels), for each type of parcels there are extra service(sending sms | email | ...) & many more things, that i don't mention here, because of simplicity. one important thing is that this project is porting to android after base work done here." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T22:21:08.223", "Id": "5205", "ParentId": "5201", "Score": "13" } } ]
{ "AcceptedAnswerId": "5205", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T19:18:26.270", "Id": "5201", "Score": "9", "Tags": [ "c#", "design-patterns" ], "Title": "best design pattern for refactoring a set of classes that do calculation base on many parameters" }
5201
<p>I've created a simple asynchronous execution engine and I would like some help identifying places it can be improved. The basic function of the system is to monitor MSMQ and Service Broker queues and execute any tasks that come through on them. </p> <p>Here is the code: </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using Castle.Windsor; using ThreadingTasks = System.Threading.Tasks; public class Engine { /// &lt;summary&gt; /// Start's the Engine and spins up appropriate message listeners /// &lt;/summary&gt; public void Start() { _logger.Info("Starting the Engine, calling GetAsync for all queues"); _cancelToken = false; GetAsync(AsyncLaunch.All); } /// &lt;summary&gt; /// Sends the stop message to the engine which will let currently running tasks finish /// and stop future tasks from being picked up. /// &lt;/summary&gt; public void Stop() { _logger.Info("Stopping the Engine"); _cancelToken = true; } protected enum AsyncLaunch { All, MSMQ, ServiceBroker }; /// &lt;summary&gt; /// Starts all appropriate asynchronous Message listeners /// &lt;/summary&gt; /// &lt;param name="async"&gt;&lt;/param&gt; protected void GetAsync(AsyncLaunch async) { if (_cancelToken) return; _logger.Debug("Attempting to get messages to process Asynchronously"); if (SingleThreaded) { _logger.Debug("Engine is running in single-threaded mode and must wait till all tasks finish"); ThreadingTasks.Task.WaitAll(_threadTasks.ToArray()); _threadTasks.Clear(); } if (async == AsyncLaunch.ServiceBroker || async == AsyncLaunch.All) _serviceBroker.GetAsync(x =&gt; RunServiceBrokerJob(x)); if (async == AsyncLaunch.MSMQ || async == AsyncLaunch.All) _msmq.GetManyAsync(x =&gt; RunMSMQJob(x)); } /// &lt;summary&gt; /// Runs the job for the given message and after the job has launched, calls /// GetAsync to get the next ServiceBroker message /// &lt;/summary&gt; protected void RunServiceBrokerJob(TransportMessage msg) { RunJob(msg); GetAsync(AsyncLaunch.ServiceBroker); } /// &lt;summary&gt; /// Runs the job for the given collection of messages and after the job has /// launched, calls GetAsync to get the next MSMQ message /// &lt;/summary&gt; protected void RunMSMQJob(IEnumerable&lt;TransportMessage&gt; msgs) { RunJob(msgs); GetAsync(AsyncLaunch.MSMQ); } /// &lt;summary&gt; /// Initializes and executes the appropriate job for the given collection of messages /// &lt;/summary&gt; /// &lt;param name="msgs"&gt;A collection of messages passed into a Job&lt;/param&gt; protected ThreadingTasks.Task RunJob(IEnumerable&lt;TransportMessage&gt; msgs) { try { var task = ThreadingTasks.Task.Factory.StartNew(() =&gt; { try { _eventSink.Broadcast(msgs); } catch (Exception ex) { _logger.Error(ex, "Error when attempting to run jobs {0} using message types {1} with values {2}", string.Join(",", msgs.Select(x =&gt; x.Id).ToArray()), string.Join(",", msgs.Select(x =&gt; x.Name).Distinct().ToArray()), string.Join(",",msgs.Select(x =&gt; x.ToString()))); } }); if (SingleThreaded) _threadTasks.Add(task); return task; } catch (Exception ex) { _logger.Error(ex, "Error when attempting to invoke Task for a collection of {0} messages with ids {1} of type(s) {2}", msgs.Count(), string.Join(",", msgs.Select(x =&gt; x.Id).ToArray()), string.Join(",", msgs.Select(x =&gt; x.Name).Distinct().ToArray())); } return null; } /// &lt;summary&gt; /// Initializes and executes the appropriate job for the given message /// &lt;/summary&gt; /// &lt;param name="msg"&gt;Message containing information pertinent to the executed Job&lt;/param&gt; protected ThreadingTasks.Task RunJob(TransportMessage msg) { _logger.Info("RunJob was invoked for msg id " + msg.Id); try { var task = ThreadingTasks.Task.Factory.StartNew(() =&gt; { _logger.Debug("Attempting to Run Job with ID: " + msg.Id); try { _eventSink.Broadcast(msg); } catch (Exception ex) { _logger.Error(ex, "Error when attempting to run job {0} using message type {1} with values {2}", msg.Id, msg.GetType(), msg.ToString()); } }); if (SingleThreaded) _threadTasks.Add(task); return task; } catch (Exception ex) { _logger.Error(ex, "Error when attempting to invoke Task for message with id {0} of type {1}", msg.Id, msg.GetType()); } return null; } private void ValidateObjectIsNotNull(object obj, string objectName) { if (obj == null) throw new ArgumentNullException(objectName + " can not be null"); } /// &lt;summary&gt; /// Instantiate a new engine used to access messaging queues and launch Tasks /// &lt;/summary&gt; public Engine(IWindsorContainer container, IEventSink eventSink, IEngineConfiguration config, ILogging logger, IDataAccess&lt;MessageBase&gt; serviceBroker, IDataAccess&lt;TransportMessage&gt; msmq) { _eventSink = eventSink; _config = config; _threadTasks = new List&lt;ThreadingTasks.Task&gt;(); _logger = logger; _container = container; _serviceBroker = serviceBroker; _msmq = msmq; //ThreadCount 0 is unlimited threads if (SingleThreaded || _config.ThreadCount == 0) return; // We need at least 3 threads, otherwise on a single CPU box we are stuck with a single thread // and only two threads might stop one of the job pollers from running int minThreadCount = System.Math.Max(Environment.ProcessorCount, 3); // do not set maxThreadCount less than the minThreadCount int maxThreadCount = System.Math.Max(minThreadCount, _config.ThreadCount); System.Threading.ThreadPool.SetMaxThreads(maxThreadCount, maxThreadCount); } private readonly IEngineConfiguration _config; private readonly IEventSink _eventSink; private readonly IList&lt;ThreadingTasks.Task&gt; _threadTasks; private readonly ILogging _logger; private readonly IWindsorContainer _container; private readonly IDataAccess&lt;MessageBase&gt; _serviceBroker; private readonly IDataAccess&lt;TransportMessage&gt; _msmq; private bool _cancelToken; private bool SingleThreaded { get { return _config.ThreadCount == 1; } } } </code></pre> <p>A couple of issues I have: - If the TPL Tasks blow up, I don't have a good way of getting that information - There is nothing that limits how "greedy" this engine is, meaning it will pull off Tasks even if it's extremely busy, possibly deriving other instances of this engine of work</p> <p>Any suggestions are greatly appreciated, but those are the two primary areas of concern for me. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T05:19:29.277", "Id": "51658", "Score": "0", "body": "Didn't read the whole thing, but GetAsync() is not a good name for that method IMO." } ]
[ { "body": "<ol>\n<li><p><code>GetAsync</code> is a bad name for that method. <code>StartListening</code> seems to express better what it does.</p></li>\n<li><p><code>AsyncLaunch</code> is a bad name for that enum. It seems to describe which target should be listened to so why not call it <code>ListenTarget</code>.</p></li>\n<li><p>enums can be used as flags:</p>\n\n<pre><code>enum ListenTarget\n{\n MSMQ = 1 &lt;&lt; 0,\n ServiceBroker = 1 &lt;&lt; 1,\n All = ~0,\n}\n</code></pre>\n\n<p>Then your testing code becomes:</p>\n\n<pre><code>if (async &amp; AsyncLaunch.ServiceBroker)\n _serviceBroker.GetAsync(x =&gt; RunServiceBrokerJob(x));\n\nif (async &amp; AsyncLaunch.MSMQ)\n _msmq.GetManyAsync(x =&gt; RunMSMQJob(x));\n</code></pre>\n\n<p>plus you can pass in an arbitrary combination of targets (in case you add more later).</p></li>\n<li><p><code>ValidateIsNotNull</code> should be renamed to state more clearly what it does: <code>ThrowIfObjectIsNull</code>.</p></li>\n<li><p>You have a lot of duplicate code in your two <code>RunJob</code> methods. The single message one could be shortened to one line of code <code>RunJobs(new [] { msg })</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T10:42:38.487", "Id": "51670", "Score": "1", "body": "Also declare fields at the top, followed by constructor; had to scroll all the way down to check if `_logger` was `readonly` (kudos for `private readonly` fields)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-07T09:15:08.323", "Id": "32370", "ParentId": "5204", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-05T21:06:58.647", "Id": "5204", "Score": "6", "Tags": [ "c#", ".net" ], "Title": "Trying to create a robust task execution engine" }
5204
<p>As a disclaimer, this is the first function I have <em>EVER</em> written in Lisp or ELisp. Please, bash it as much as you would any other piece, but don't judge me for it please! :)</p> <p>So, I realized I wanted a way to rename files without all the hassle of reopening the file etc. I googled and found a function at <a href="https://stackoverflow.com/questions/384284/can-i-rename-an-open-file-in-emacs">https://stackoverflow.com/questions/384284/can-i-rename-an-open-file-in-emacs</a> (credit Steve Yegge).</p> <p>However, it did not seem to work well with <code>uniquify</code>. Which was a problem. Having two files open and trying to rename the first one to the same name as the second one (for example CMakeLists.txt, which there might be many of) caused it to bail since it only checked the name of the buffer (which wasn't unique yet, as uniquify doesn't do it's thing before something needs uniquifying).</p> <p>The only way I found to force a "re-uniquification" was to close the previous buffer and open the new file. This seems very inelegant...</p> <pre><code>(defun is-unique-name-for-buffer (new-name) (let ((file-name (buffer-file-name)) (dir-name (file-name-directory buffer-file-name))) (let ((new-complete-name (concat dir-name new-name))) (progn (not (string-equal file-name new-complete-name)))))) (defun rename-file-and-buffer (new-name) "Renames both current buffer and file it's visiting to NEW-NAME." (interactive "sNew name: ") (let ((name (buffer-name)) (filename (buffer-file-name)) (dir-name (file-name-directory (buffer-file-name)))) (if (not filename) (message "Buffer '%s' is not visiting a file!" name) (if (not (is-unique-name-for-buffer new-name)) (message "A buffer named '%s' already exists in that location!" new-name) (progn (rename-file (file-name-nondirectory filename) new-name 1) (kill-buffer) (set-buffer (find-file (concat dir-name new-name)))))))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T04:53:45.040", "Id": "53767", "Score": "0", "body": "Do not use `concat` to build absolute file names. Use `expand-file-name`: `(expand-file-name dir-name new-name)`. That way, Emacs handles file names for different systems automatically." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T04:54:58.280", "Id": "53768", "Score": "0", "body": "Not sure what you intend here, but I'm guessing you really want `find-file-noselect`, not `find-file`." } ]
[ { "body": "<p>Judgment circuits deactivated; you have nothing to fear.</p>\n\n<p>I was going to suggest that there must already be a function that you can call to force <code>uniquify</code> a buffer, but <code>M-x apropos RET ^uniq</code> doesn't show any documented functions that would do that for you (take a look and try a few out if you like, you may find a more elegant solution). </p>\n\n<hr>\n\n<p>Lisp (actually, Elisp and Common Lisp; Scheme does its own thing) convention is to end predicate functions with <code>-p</code> or <code>p</code> rather than begin them with <code>is-</code>.</p>\n\n<pre><code>(defun unique-name-for-buffer-p (new-name)\n (let ((file-name (buffer-file-name))\n (dir-name (file-name-directory buffer-file-name)))\n (let ((new-complete-name (concat dir-name new-name)))\n (progn (not (string-equal file-name new-complete-name))))))\n</code></pre>\n\n<hr>\n\n<p>Your predicate seems to be nesting <code>let</code>s only because you need <code>new-complete-name</code> to refer to <code>dir-name</code>. When you're in a situation like that, you can instead use <code>let*</code>. It's the same as <code>let</code> except that its clauses are guaranteed to be evaluated in order (it's still good style to use <code>let</code> when you can, but one <code>let*</code> is better than many nested <code>let</code>s).</p>\n\n<pre><code>(let* ((file-name (buffer-file-name))\n (dir-name (file-name-directory buffer-file-name))\n (new-complete-name (concat dir-name new-name)))\n (progn (not (string-equal file-name new-complete-name))))\n</code></pre>\n\n<hr>\n\n<p>You only need explicit <code>progn</code> when you want to evaluate multiple expressions as one (you use it correctly in your nested <code>if</code>s, but read on). </p>\n\n<pre><code>(defun unique-name-for-buffer-p (new-name)\n (let* ((file-name (buffer-file-name))\n (dir-name (file-name-directory buffer-file-name))\n (new-complete-name (concat dir-name new-name)))\n (not (string-equal file-name new-complete-name))))\n</code></pre>\n\n<hr>\n\n<p>The nested <code>if</code>s in your second function can be expressed as a single <code>cond</code> (which also gets rid of that otherwise legitimate <code>progn</code>).</p>\n\n<pre><code>(defun rename-file-and-buffer (new-name)\n \"Renames both current buffer and file it's visiting to NEW-NAME.\"\n (interactive \"sNew name: \")\n (let ((name (buffer-name))\n (filename (buffer-file-name))\n (dir-name (file-name-directory (buffer-file-name))))\n (cond ((not filename) \n (message \"Buffer '%s' is not visiting a file!\" name))\n ((not (unique-name-for-buffer-p new-name)) \n (message \"A buffer named '%s' already exists in that location!\" new-name))\n (t (rename-file (file-name-nondirectory filename) new-name 1)\n (kill-buffer)\n (set-buffer (find-file (concat dir-name new-name)))))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-19T15:56:49.307", "Id": "7969", "ParentId": "5207", "Score": "8" } } ]
{ "AcceptedAnswerId": "7969", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T08:55:07.427", "Id": "5207", "Score": "8", "Tags": [ "elisp" ], "Title": "ELisp function to allow file renaming in Emacs" }
5207
<p>Due to software constraints, <strong>I cannot use the standard libraries, <code>cmath</code>, <code>algorithm</code>, templates, inline, or boost</strong>. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.</p> <p>Here is the custom <strong>sine, pow and factorial functions</strong> I wrote (assume they are all part of the same namespace and not using <code>cmath</code>). I looking for suggestions to improve robustness and efficiency. For example, both the <code>pow</code> and <code>factorial</code> are constrained by the <code>int i</code> in the for loops.</p> <pre><code>double factorial(double x) { double result = 1; for (int i=1;i&lt;=x;i++) result *= i; return result; } double pow(double x,double y) { double result = 1; for (int i=0;i&lt;y;i++) result *= x; return result; } double sine_taylor(double x,double n) { double sine = x; bool isNeg; isNeg = true; for (double i=3;i&lt;=n;i+=2) { if(isNeg) { sine -= pow(x,i)/factorial(i); isNeg = false; } else { sine += pow(x,i)/factorial(i); isNeg = true; } } return sine; } int main() { const double pi = 3.14159265; double sineTaylor = sine_taylor(pi/2,7); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T18:58:13.420", "Id": "7855", "Score": "0", "body": "Explanation for -1? I don't see a duplicate question, code formatted correctly, and problem statement clearly defined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T19:28:04.550", "Id": "7857", "Score": "0", "body": "Perhaps because you haven't asked a question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T19:31:51.083", "Id": "7858", "Score": "4", "body": "@Ant, I didn't think I had to request for code review at Code Review, anyway I updated looking to increase robustness and efficiency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:06:00.677", "Id": "7868", "Score": "0", "body": "You'd better use a lookup table as most accurate and fast approach" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:49:17.920", "Id": "7903", "Score": "1", "body": "These are solved problems. Crack open the standard library and copy and paste the code you need." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:51:49.923", "Id": "7904", "Score": "0", "body": "@LokiAstari, if I can't use the standard library why would I copy and paste the source code of the standard library? I understand the benefit of using it as a guide but that is not the point of the question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:55:41.373", "Id": "7906", "Score": "1", "body": "There is no point to the question (because it is a well know SOLVED problem). Asking it is silly. There is a difference between not being able to use the standard library and copying code (which just happens to come from the standard library presumably you can still get a copy to look at)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T17:02:51.850", "Id": "7908", "Score": "0", "body": "@LokiAstari, I disagree and moving this to meta: http://meta.codereview.stackexchange.com/q/374/7394" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T04:32:34.677", "Id": "8445", "Score": "0", "body": "@LokiAstari The implementation of the sin function in the standard library for your average PC is `asm(\"FSIN\")`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T05:34:00.763", "Id": "8448", "Score": "1", "body": "@Sjoerd: If you have an FPU. see: http://stackoverflow.com/questions/2284860/how-does-c-compute-sin-and-other-math-functions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T05:50:42.927", "Id": "8449", "Score": "0", "body": "@LokiAstari Nice link!" } ]
[ { "body": "<p>Not being able to use the standard libraries suggests you are doing embedded work. A more typical approach for calculating sine in that situation would be to:</p>\n\n<ul>\n<li>Translate angles from a 360 degree system to a 256 degree system;</li>\n<li>Store sine values for all 256 possible degrees in a lookup table.</li>\n</ul>\n\n<p>You lose a lot of accuracy, but you gain a lot of speed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T19:32:32.893", "Id": "7859", "Score": "0", "body": "Accuracy is very important and this is not necessarily on an embedded system." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:04:45.200", "Id": "7867", "Score": "7", "body": "@Elpezmuerto: Using lookup table for 256 values you can interpolate Sin functions with very high level of accuracy using well known triginometrical equations and, if you accuracy level is really tremendous you can just use the biiger lookup table (65536 values)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T19:31:23.203", "Id": "5215", "ParentId": "5211", "Score": "12" } }, { "body": "<p>The <code>factorial()</code> function is an integral function. It's arguments and return type should be integers, not doubles. By using floating-point arithmetic here, it is also probably not as fast as it should be. Also, your loop may start at <code>2</code>, save yourself the iteration. :)</p>\n\n<p>There's no sense in making <code>y</code> in your <code>pow()</code> function a <code>double</code>. They should be typed based on how you use it in this case so it is absolutely clear. It would also be a good idea to rename it as it is not a standard <code>pow()</code> function (that only works for positive integer exponents). That assumes you're not intending to expose it for use outside your module. If so, you should probably make it <code>static</code> as well (same for <code>factorial()</code>).</p>\n\n<p>Also, the similar arguments with your <code>sine_taylor()</code> function. There's no sense in making your loop variable a <code>double</code>, it should be an integer anyway. With the above two fixes in place, you can easily fix this.</p>\n\n<p>Rather than looping through all the terms, alternating between positive and negative terms, it might be a good idea to help the compiler and processor out here and split these up as separate loops to remove the branches. That way the compiler could possibly unroll this better and you're not potentially confusing the branch predictors.</p>\n\n<p>Try it out like this:</p>\n\n<pre><code>static int factorial(int n)\n{\n int i;\n int result = 1.0;\n for (i = 2; i &lt;= n; i++)\n result *= i;\n return result;\n}\n\nstatic double pow_int(double x, int y)\n{\n int i;\n double result = 1.0;\n for (i = 0; i &lt; y; i++)\n result *= x;\n return result;\n}\n\ndouble sine_taylor(double x, int n)\n{\n int i;\n double result = x;\n for (i = 3; i &lt;= n; i += 4)\n result += pow_int(x, i) / factorial(i);\n for (i = 5; i &lt;= n; i += 4)\n result -= pow_int(x, i) / factorial(i);\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T00:31:37.700", "Id": "7863", "Score": "0", "body": "both the power and the factorial are needlessly computed from scratch each iteration; you should get significant performance gains if you inline both" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T00:46:14.623", "Id": "7864", "Score": "0", "body": "There's plenty of room for more optimizations. Memoization, alternative algorithms, lookup tables, etc. My main focus here was to address other aspects of the existing code without changing the overall structure too much. Most of those changes are not exactly trivial to implement given the restrictions, may or may not be worth it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T07:50:22.917", "Id": "7876", "Score": "0", "body": "What about the inline version? I suppose if you can't optimize something you'd better not doing it, because you will not teach something really interesting, for example, you need to analyze input algorithms and data before you can have a chance to refactor the code. I think, every time you post a message, you have to provide really good examples, not duplicate common student's faults and bad ideas, bla-bla-something about it. If you know somethig, you can show, how-to, otherwize you'd better keep it within yourself." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T14:14:38.593", "Id": "7893", "Score": "0", "body": "Inline is not allowed in my application (software certification issue)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:54:32.933", "Id": "7905", "Score": "0", "body": "@JeffMercado, I agree with @ArturMustafin, feel free to change other aspects of the code. Its better to post the optimized version within the constraints of the problem (no `inline`) and teach why it is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T04:45:44.723", "Id": "8446", "Score": "0", "body": "It's better to have `factorial` return a double. It might be an integer in nature, but `int` only has 16 bits guaranteed (even though it's 32 bits on most implementations). And even 32 bits is not enough to represent factorial(13)! `double` has 56 bits dedicated to precision, so is a bit better, but only good enough for full precision on factorial(20)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T04:48:29.603", "Id": "8447", "Score": "0", "body": "Due to the limited precision on calculating `factorial`, in practice you cannot calculate more than a few terms of your expansion. Not much point in calculating `factorial(27)` if the result is so big that `pow_int(x, i) / factorial(i)` will underflow anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T23:29:46.920", "Id": "8467", "Score": "0", "body": "@Sjoerd: Good point about the precision, I overlooked that and how quickly the factorial grows." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T20:21:19.247", "Id": "5216", "ParentId": "5211", "Score": "6" } }, { "body": "<p>This is the correct answer. By providing the Pi number with accuracy 1e-8, you give me an opportunity to optimize you function to inline:</p>\n\n<pre><code>inline double _sin8(double radians)\n{ \n double x = radians;\n double x2 = x*x;\n double f = 1;\n double s = 0;\n int i = 1;\n\n s += x/f; x *= x2; f *= ++i; f *= ++i;\n s -= x/f; x *= x2; f *= ++i; f *= ++i;\n s += x/f; x *= x2; f *= ++i; f *= ++i;\n s -= x/f; x *= x2; f *= ++i; f *= ++i;\n s += x/f; x *= x2; f *= ++i; f *= ++i;\n s -= x/f; x *= x2; f *= ++i; f *= ++i;\n s += x/f; x *= x2; f *= ++i; f *= ++i;\n s -= x/f; x *= x2; f *= ++i; f *= ++i;\n\n return s;\n}\n</code></pre>\n\n<p>I hope you have done you homework well, as I did in my past:</p>\n\n<pre><code>#include &lt;math.h&gt;\n\ndouble _sin8(double radians); \n\ninline double _sin(double radians, double epsilon, int &amp;count )\n{ \n double x = radians;\n double x2 = x*x;\n double f = 1;\n double s = 0;\n int i = 1;\n\n while (x/f &gt;= epsilon)\n {\n s += x/f; x *= x2; f *= ++i; f *= ++i; \n s -= x/f; x *= x2; f *= ++i; f *= ++i;\n count++;\n }\n\n return s;\n}\n\nint main() \n{ \n double e_x = 0.00000001; // 1e-8, because pi differs from real pi at 8 symbol after decimal point\n\n double e_pi = 3.14159265;\n double m_pi = M_PI;\n\n int n = 10;\n\n double e_dx = e_pi/(2.0*n);\n double m_dx = m_pi/(2.0*n);\n\n for (double e_i=e_pi/2.0, m_i=m_pi; n&gt;=0; e_i-=e_dx, m_i-=m_dx, n--)\n {\n int c = 0;\n double e_f = _sin(e_i, e_x, c);\n double m_f = sin(m_i);\n printf(\"e_pi=%.16e e_f=%.16e c2=%d\\n\", e_pi, e_f, c); \n printf(\"m_pi=%.16e m_f=%.16e\\n\", m_pi, m_f);\n }\n // by the experiment, for the given epsion, we can easily take double _sin8(double) function, because:\n // e(f(x)) &gt;= e(x), for any given f(x) = a0*x^0 + a1*x^1 + ... that's called \"accumuilation of errors\"\n // in my opinion, you'd better go to scool library, i do not think it is good for you to \n // ask community to do your homework. as you see, i got bachelor degree in CS years ago, \n // so we know something about it, and you'd better to discover this knowledge yourself\n}\n</code></pre>\n\n<p>Some mathiematical constants, to remember:</p>\n\n<pre><code>/* Definitions of useful mathematical constants\n* M_E - e\n* M_LOG2E - log2(e)\n* M_LOG10E - log10(e)\n* M_LN2 - ln(2)\n* M_LN10 - ln(10)\n* M_PI - pi\n* M_PI_2 - pi/2\n* M_PI_4 - pi/4\n* M_1_PI - 1/pi\n* M_2_PI - 2/pi\n* M_2_SQRTPI - 2/sqrt(pi)\n* M_SQRT2 - sqrt(2)\n* M_SQRT1_2 - 1/sqrt(2)\n*/\n\n#define M_E 2.71828182845904523536\n#define M_LOG2E 1.44269504088896340736\n#define M_LOG10E 0.434294481903251827651\n#define M_LN2 0.693147180559945309417\n#define M_LN10 2.30258509299404568402\n#define M_PI 3.14159265358979323846\n#define M_PI_2 1.57079632679489661923\n#define M_PI_4 0.785398163397448309616\n#define M_1_PI 0.318309886183790671538\n#define M_2_PI 0.636619772367581343076\n#define M_2_SQRTPI 1.12837916709551257390\n#define M_SQRT2 1.41421356237309504880\n#define M_SQRT1_2 0.707106781186547524401\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T14:16:12.087", "Id": "7894", "Score": "0", "body": "I cannot use `inline` unfortunately" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T07:18:38.123", "Id": "5222", "ParentId": "5211", "Score": "4" } }, { "body": "<p><strong>UPDATE:</strong> (19-March-2015) <a href=\"https://stackoverflow.com/a/14869358/396551\">This answer</a> sounds like an expert answer.</p>\n\n<p><strong>Original answer:</strong></p>\n\n<p>There are books full on how to calculate those functions efficiently and accurately. So it's too much for a short answer here.</p>\n\n<p>I'm hardly an expert, but I can easily spot that your loop starts at the large terms and ends with the small terms. This has a larger accumulated error than going from small to large.</p>\n\n<p>Secondly, subtracting is a very good way to lose a lot of accuracy. It might be better to partially unroll the loop, combining each positive term with the next negative term, and only add the difference between those two. Although that still might result in a large loss of accuracy.</p>\n\n<p>As none of the other answers even touches on those point, you have not been answered by an expert yet. I only know enough to know that I don't know enough.</p>\n\n<p>So clearly work for specialists. And indeed, solved a long time ago.</p>\n\n<p>A quick google found <a href=\"http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html\" rel=\"nofollow noreferrer\">What Every Computer Scientist Should Know About Floating-Point Arithmic</a>.</p>\n\n<blockquote>\n <p>Note – This appendix is an edited reprint of the paper What Every\n Computer Scientist Should Know About Floating-Point Arithmetic, by\n David Goldberg, published in the March, 1991 issue of Computing\n Surveys. Copyright 1991, Association for Computing Machinery, Inc.,\n reprinted by permission.</p>\n</blockquote>\n\n<p>I just googled for that title, betting that someone would have used that title at some point in time. It explains the problem I mentioned above and much more, but I'm not really qualified to judge it. As it is SUN's SPARC documentation, I expect it to be among the best you can find online, although it could be too technical for some.</p>\n\n<p>It's the appendix of some part of SUN's documentation for SPARC. Scanning the <a href=\"http://download.oracle.com/docs/cd/E19957-01/806-3568/\" rel=\"nofollow noreferrer\">full document</a>, In the references is this paper:</p>\n\n<blockquote>\n <p>Tang, Peter Ping Tak, Some Software Implementations of the Functions\n Sin and Cos, Technical Report ANL-90/3, Mathematics and Computer\n Science Division, Argonne National Laboratory, Argonne, Illinois,\n February 1990.</p>\n</blockquote>\n\n<p>I can't find it online using google, so good luck hunting that one!</p>\n\n<p>Drawback of the backwards loop is that one can't use the result of previous step. An even better approach might be a forward loop to calculate the terms. But don't add them, store them in an array, then use a backwards loop to sum them.</p>\n\n<p>That might sound a lot of work, but when the size of the array is fixed at compile time, one can unroll the loop (see Artur Mustafin's answer), and just use 4 local doubles (each one holds the diference between two terms, so that's the same 8 terms he calculates).</p>\n\n<p>Based on my remarks, here is my version. Inlined, loop-unrolled, and parallizable. I usually don't bother with re-using local variables: the compilers nowadays are smart enough to do that for me. I also assume that e.g. <code>/ (10*11)</code> is optimized into a <code>* some_constant</code> where <code>some_constant</code> equals <code>1.0 / 110</code>, assuming the CPU is faster on multiplications than on divisions.</p>\n\n<p>But I bet that the version used by real libraries is even smarter.</p>\n\n<pre><code>double sine_taylor(double x)\n{\n // useful to pre-calculate\n double x2 = x*x;\n double x4 = x2*x2;\n\n // Calculate the terms\n // As long as abs(x) &lt; sqrt(6), which is 2.45, all terms will be positive.\n // Values outside this range should be reduced to [-pi/2, pi/2] anyway for accuracy.\n // Some care has to be given to the factorials.\n // They can be pre-calculated by the compiler,\n // but the value for the higher ones will exceed the storage capacity of int.\n // so force the compiler to use unsigned long longs (if available) or doubles.\n double t1 = x * (1.0 - x2 / (2*3));\n double x5 = x * x4;\n double t2 = x5 * (1.0 - x2 / (6*7)) / (1.0* 2*3*4*5);\n double x9 = x5 * x4;\n double t3 = x9 * (1.0 - x2 / (10*11)) / (1.0* 2*3*4*5*6*7*8*9);\n double x13 = x9 * x4;\n double t4 = x13 * (1.0 - x2 / (14*15)) / (1.0* 2*3*4*5*6*7*8*9*10*11*12*13);\n // add some more if your accuracy requires them.\n // But remember that x is smaller than 2, and the factorial grows very fast\n // so I doubt that 2^17 / 17! will add anything.\n // Even t4 might already be too small to matter when compared with t1.\n\n // Sum backwards\n double result = t4;\n result += t3;\n result += t2;\n result += t1;\n\n return result;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T04:18:42.090", "Id": "5562", "ParentId": "5211", "Score": "8" } }, { "body": "<p><code>factorial</code> begs to be an array (1,2,6,24,120...)\n<code>pow</code> can be optimized a bit... 3^101= 3^64*3^32*3^4*3^1= 3^1*3^32*...*\nby using <a href=\"http://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"nofollow\">exponentiation by squaring</a>.</p>\n\n<p>Problem is that you don't have <code>int</code> as power but still you can to the \"<code>int</code> specialization\" that way. Regarding <code>sin</code> you could manually unroll the <code>for</code> loop and make sure that you have some parallel processing (not multiple threads but that maximum amount of instruction level parallelism is possible). This is highly speculative but let's say that compiler might not be smart enough to optimize</p>\n\n<pre><code> x=(a+b)+(c +d)+(e+f);` \n</code></pre>\n\n<p>in a way that is is faster than</p>\n\n<pre><code>x=a+b+c+d+e+f; \n</code></pre>\n\n<p>so you might want to that explicitly for the taylor sum.</p>\n\n<p>But I would guess that compiler will unroll and do the transformation automatically. Also it <strong>might</strong> be the case that floating point multiplication is faster than division so you might want to do something like having 1/1,1/2,1/6... array for taylor calculation.</p>\n\n<p>If you want to read more about optimization:<br>\n<a href=\"http://www.agner.org/optimize/\" rel=\"nofollow\">http://www.agner.org/optimize/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-09T17:17:10.510", "Id": "5923", "ParentId": "5211", "Score": "0" } } ]
{ "AcceptedAnswerId": "5562", "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T18:52:06.267", "Id": "5211", "Score": "15", "Tags": [ "c++", "c", "mathematics", "reinventing-the-wheel", "floating-point" ], "Title": "Sine function in C / C++" }
5211
Branch of mathematics that studies triangles and the relationships between their sides and the angles between these sides.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T18:52:57.530", "Id": "5213", "Score": "0", "Tags": null, "Title": null }
5213
<p>I'm working on a small program to add or remove certain entries from the Windows registry, and I'm getting all tangled up in IF and TRY conditions. I've spent hours chasing bugs, usually logical ones, trying to accomplish what is conceptually very simple. The more I work on and "improve" the code so that it works in more and more conditions, the more tortured and complicated the IF tests get, until I can't tell which is up and down anymore. Surely there must be a better way! (even for my little brain)</p> <p>This is all I'm trying to do:</p> <p>When asked to install:</p> <p>If our python version and installpath is in registry: do nothing.<br> If our python version and different installpath: do nothing.<br> If our python is not there, add it.</p> <p>When asked to remove:</p> <p>If our python is not there: do nothing<br> If our python version and different installpath: do nothing.<br> If our python version and installpath is in registry: remove. </p> <p>But my code for just the removal part looks like the below (the <a href="http://code.google.com/p/maphew/source/browse/register-python/register-python.py" rel="nofollow">whole thing is here</a>). It works, more or less, but it just doesn't feel right. I don't know what to do to make it cleaner. Your viewpoints are appreciated. Thanks.</p> <pre><code>def remove(): ''' see if any existing registrations match our python version and register ours if not ''' if CurrentUser: match = True if our_version in CurrentUser else False versions = CurrentUser elif AllUsers: match = True if our_version in AllUsers else False versions = AllUsers else: print '\nOur version (%s) not registered to "%s", skipping...' % (our_version, versions[our_version]) try: if match: print '\nVersion matches ours, calling deRegisterPy...' deRegisterPy(pycore_regpath,our_version) except: raise def deRegisterPy(pycore_regpath, version): ''' remove this python install from registry ''' pycore_regpath = pycore_regpath + version # e.g. 'SOFTWARE\Python\Pythoncore\2.7' try: reg = OpenKey(HKEY_LOCAL_MACHINE, pycore_regpath) installpath = QueryValue(reg, installkey) # win32 if installpath == our_installpath: print '\nexisting python matches ours, removing...\n' # print '(%s vs %s)' % (installpath, our_installpath) for subkey in ['\\InstallPath', '\\PythonPath']: DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath + subkey) DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath) print "--- Python %s, %s is now removed!" % (our_version, our_installpath) CloseKey(reg) except EnvironmentError: print 'EnvironmentError', EnvironmentError() raise return except WindowsError: print "Strange, we've hit an exception, perhaps the following will say why:" print WindowsError() raise return CloseKey(reg) # main if args['action']=='install': install() elif args['action']=='remove': remove() </code></pre>
[]
[ { "body": "<pre><code>def remove():\n ''' see if any existing registrations match our python version and register ours if not '''\n\n if CurrentUser:\n</code></pre>\n\n<p>The python style guide reserves CamelCase for class names. If this is a global constant it should be CURRENT_USER. If its not a global constant, it shouldn't be accessed as a global variable.</p>\n\n<pre><code> match = True if our_version in CurrentUser else False\n</code></pre>\n\n<p>Just use <code>match = our_version in CurrentUser</code> </p>\n\n<pre><code> versions = CurrentUser\n elif AllUsers:\n match = True if our_version in AllUsers else False\n versions = AllUsers\n\n\n\n else:\n print '\\nOur version (%s) not registered to \"%s\", skipping...' % (our_version, versions[our_version])\n\n try:\n if match:\n print '\\nVersion matches ours, calling deRegisterPy...'\n deRegisterPy(pycore_regpath,our_version)\n except:\n raise\n</code></pre>\n\n<p>What??? the try..except does nothing if you just raise the error right away</p>\n\n<pre><code>def deRegisterPy(pycore_regpath, version):\n</code></pre>\n\n<p>Python style guide recommends lower_case_with_underscores for functions names</p>\n\n<pre><code> ''' remove this python install from registry '''\n pycore_regpath = pycore_regpath + version # e.g. 'SOFTWARE\\Python\\Pythoncore\\2.7'\n try:\n reg = OpenKey(HKEY_LOCAL_MACHINE, pycore_regpath)\n installpath = QueryValue(reg, installkey) # win32\n</code></pre>\n\n<p>Why are you taking the time to point out that its win32 here?</p>\n\n<pre><code> if installpath == our_installpath:\n print '\\nexisting python matches ours, removing...\\n'\n # print '(%s vs %s)' % (installpath, our_installpath)\n</code></pre>\n\n<p>Don't leave dead code in comments</p>\n\n<pre><code> for subkey in ['\\\\InstallPath', '\\\\PythonPath']:\n DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath + subkey)\n DeleteKey(HKEY_LOCAL_MACHINE, pycore_regpath)\n print \"--- Python %s, %s is now removed!\" % (our_version, our_installpath)\n CloseKey(reg)\n except EnvironmentError:\n print 'EnvironmentError', EnvironmentError()\n</code></pre>\n\n<p>What are you trying to do here? You construct a new EnviromentError object, and then print it. But that's a pointless thing to do</p>\n\n<pre><code> raise\n</code></pre>\n\n<p>If you are just going to raise the error again, not a whole lot of point in printing it anyways\n return</p>\n\n<p>Do you realize that nothing after the raise will be executed, so this return will have no effect?</p>\n\n<pre><code> except WindowsError:\n print \"Strange, we've hit an exception, perhaps the following will say why:\"\n print WindowsError()\n</code></pre>\n\n<p>You seem to be confused about how to catch errors, you want:</p>\n\n<pre><code>except WindowsError as error:\n print error\n</code></pre>\n\n<p>But really you don't need to do that: just let the exceptions fly and python will print them when it exits due to the error</p>\n\n<pre><code> raise\n return\n</code></pre>\n\n<p>Again, the return will never be reached</p>\n\n<pre><code> CloseKey(reg)\n</code></pre>\n\n<p>If an exception occurs, this will never be called. You should put it in a finally block or something</p>\n\n<pre><code># main\nif args['action']=='install':\n install()\nelif args['action']=='remove':\n remove()\n</code></pre>\n\n<p>You should really put logic like this in a main function.</p>\n\n<p>Any my rewrite of your whole linked file. No testing has been done. But it should give you something of an idea of what you can do.</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport sys\nfrom _winreg import *\n\nimport argparse, sys\nimport os.path\n\nPYTHON_VERSION = \"%d.%d\" % sys.version_info[0:2]\n\n# the registry key paths we'll be looking at &amp; using\nPYCORE_REGISTRY_PATH = (\"SOFTWARE\",\"Python\",\"Pythoncore\")\nINSTALL_KEY = \"InstallPath\"\nPYTHON_KEY = \"PythonPath\"\nPYTHONPATH = \";\".join( os.path.join(sys.prefix, sub) for sub in [\"\", \"Lib\", \"DLLs\"])\n\nclass RegisteryKeyNotFound(Exception):\n pass\n\nclass RegisteryKey(object):\n def __init__(self, hive):\n self._key = key\n\n def _path_from(self, segments):\n if not isinstance(segments, tuple):\n segments = (segments,)\n\n return \"\\\\\".join(segments)\n\n def __getitem__(self, segments):\n try:\n subkey = _winreg.OpenKey(self._key, self._path_from(segments))\n except WindowsError:\n # should really check the error\n # to make sure that key not found is the real problem\n raise RegisteryKeyNotFound(path)\n return RegisteryKey(subkey)\n\n def get_or_create(self, segments):\n subkey = _winreg.CreateKey(self._key, self._path_from(segments))\n return RegisteryKey(subkey)\n\n\n def value(self, segments):\n return _winreg.QueryValue(self._key, self._path_from(segments))\n\n def delete(self, segments):\n _winreg.DeleteKey(self._key, self._path_from(segments))\n\n def set_value(self, segments, value):\n _winreg.SetValue(self._key, self._path_from(segments), REG_SZ, value)\n\n def __iter__(self):\n index = 0\n while True:\n try:\n yield RegisteryKey(EnumKey(key, index))\n except WindowsError:\n # add check to make sure correct here was gotten\n break\n else:\n index += 1\n\n def __del__(self):\n _winreg.CloseKey(self._key)\n\nHIVE_LOCAL_MACHINE = RegisteryKey(HKEY_LOCAL_MACHINE)\nHIVE_CURRENT_USER = RegisteryKey(HKEY_CURRENT_USER)\n\ndef get_existing(hive):\n ''' retrieve existing python registrations '''\n\n try:\n key = hive[PYCORE_REGISTRY_PATH]\n except RegisteryKeyNotFound:\n return {}\n\n versions = {}\n for version in key:\n versions[version] = version.value(INSTALL_KEY) # e.g. {'2.7' = 'C:\\\\Python27'}\n\n return versions\n\ndef register_python(version):\n ''' put this python install into registry '''\n try:\n reg = HIVE_LOCAL_MACHINE[PYCORE_REGISTRY_PATH][version]\n except RegisteryKeyNotFound:\n reg = HIVE_LOCAL_MACHINE.get_or_create(PYCORE_REGISTRY_PATH).get_or_create(version)\n reg.set_value(INSTALL_KEY, sys.prefix)\n reg.set_value(PYTHON_KEY, PYTHONPATH)\n print \"--- Python %s is now registered to %s!\" % (PYTHON_VERSION, sys.prefix)\n else:\n print reg.value(INSTALL_KEY)\n\n if reg.value(INSTALL_KEY) == sys.prefix and reg.value(PYTHON_KEY) == PYTHONPATH:\n print \"=== Python %s is already registered!\" % (PYTHON_VERSION)\n else:\n print \"*** Unable to register!\"\n print \"*** You probably have another Python installation!\"\n\ndef deregister_python(version):\n ''' remove this python install from registry '''\n reg = HIVE_LOCAL_MACHINE[PYCORE_REGISTRY_PATH][version]\n install_path = reg.value(INSTALL_KEY)\n if install_path == sys.prefix:\n print '\\nexisting python matches ours, removing...\\n'\n for subkey in ['InstallPath', 'PythonPath']:\n reg.delete(subkey)\n reg.delete()\n print \"--- Python %s, %s is now removed!\" % (PYTHON_VERSION, sys.prefix)\n\ndef install(installed_versions):\n ''' see if any existing registrations match our python version, and if not, register ours '''\n\n print '\\n...installing'\n\n if PYTHON_VERSION in installed_versions:\n print '\\nOur version (%s) already registered to \"%s\", skipping...' % (PYTHON_VERSION, installed_versions[PYTHON_VERSION])\n else:\n print '\\nPutting python from environment into registry...\\n'\n register_python()\n\ndef remove(installed_versions):\n ''' see if any existing registrations match our python version and register ours if not '''\n #print args\n if PYTHON_VERSION in installed_versions:\n deregister_python()\n else:\n print '\\nOur version (%s) not registered, skipping...' % (PYTHON_VERSION)\n\n\n\n# @url http://stackoverflow.com/questions/4042452/display-help-message-with-python-argparse-when-script-is-called-without-any-argum\n# display the usage message when it is called with no arguments\nclass MyParser(argparse.ArgumentParser):\n def error(self, message):\n sys.stderr.write('error: %s\\n' % message)\n self.print_help()\n sys.exit(2)\n\n\n\ndef main():\n parser=MyParser()\n parser.add_argument('action', help='one of \"install\" or \"remove\" ')\n args = parser.parse_args()\n\n current_user_versions = get_existing(HIVE_CURRENT_USER)\n local_machine_versions = get_existing(HIVE_LOCAL_MACHINE)\n\n print '\\nFound in Current User:'\n for key, value in current_user_versions.items():\n print \"\\t%s - %s\" % (key, value)\n print '\\nFound in All Users:'\n for key, value in local_machine_version.items():\n print \"\\t%s - %s\" % (key, value)\n\n all_versions = {}\n all_versions.update(current_user_versions)\n all_versions.update(local_machine_versions)\n\n\n if args.action == 'install':\n install(all_versions)\n elif args.action == 'remove':\n remove(all_versions)\n else:\n print '\\nInvalid action specified. I only understand \"install\" and \"remove\". '\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Some notes:</p>\n\n<ol>\n<li>The _winreg interface is rather low level. You can make code a lot clearer by wrapping it in something more pythonic. I've only taken a first stab at an interface, and it probably could be done a lot better. </li>\n<li>You split out CurrentUser and LocalMachine but treated them pretty much exactly the same. The code can be simplified by merging them into a giant dictionary of versions</li>\n<li>you remove python from LocalMachine but not CURRENT_USER. That seems odd but I've not changed it.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T06:05:01.227", "Id": "7873", "Score": "0", "body": "Small typo but the first line of `def main():` needs an extra space." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T22:00:48.997", "Id": "7913", "Score": "0", "body": "Winston thank you for your advice. I'm sure it took some time. I'll leave more feedback after I've properly digested your advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T10:09:55.797", "Id": "8211", "Score": "0", "body": "after reading through your example several times I finally \"get\" classes in a way I didn't previously. It helps seeing it applied to something I'm familiar with. Thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T10:17:12.060", "Id": "8212", "Score": "0", "body": "re #3, that's a mistake. It supposed to remove from whichever one of LocalMachine or CurrentUser has the python of interest registered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T10:32:44.957", "Id": "8213", "Score": "0", "body": "I committed your version as [classy-reggie.py](http://code.google.com/p/maphew/source/browse/register-python/classy-reggie.py), but haven't been able to get it to work yet. It fails with `Exception NameError: \"global name '_winreg' is not defined\"` (there's more, just not enough room in comment to put it)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T10:57:47.703", "Id": "8214", "Score": "0", "body": "\"You seem to be confused about how to catch errors...\" yup! though now the fog is parting some. And no I didn't realise nothing after raise is touched." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T13:46:25.630", "Id": "8215", "Score": "0", "body": "@mattwilkie, I put little thought into that class. I'd actually go see if someone has written a wrapper on python registry settings that you could use. The error you mention will be because you haven't imported _winreg. You imported everything inside it with `from _winreg import *` but I prefer to use `import _winreg` and explicitly refer to `_winreg.function`. I make no guarantees that the code will work at all." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T13:50:49.350", "Id": "8218", "Score": "0", "body": "@mattwilkie, I also don't know the windows registry well enough to do a really good job at it. There seemed to be an odd duality between keys and values and I'm not sure the best way of handling that. If I were to pursue your project more fully I'd start by researching. Starting with my piece of code may not be the best since its had not testing whatesover. I intended it to show an example, not be a good starting point." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:09:34.963", "Id": "8231", "Score": "0", "body": "changing to straight `import _winreg` fixed the err mentioned, but that minor problem was masking a bigger one in the `__init__` part of `class RegisteryKey`. I *think* it's supposed to be `self._key = hive` instead of `self._key = key`, at least making that change gets us farther down the line of execution before failing with `TypeError: The object is not a PyHKEY object`. I have done a fair bit of searching to locate a windows registry wrapper but came up empty; could be I'm just not using the right language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:17:22.437", "Id": "8233", "Score": "0", "body": "I do appreciate that it's not the reviewers' job to come up with tested, complete alternatives to the problems present. That the focus is on presenting alternate ways of thinking about the challenges, and directions for further research and exploration. It's just hard from the ignorant side of the veil to discriminate between errors which are of the typo variety (e.g. *import x* instead of *from x import*) and those that may be from an actual flaw in understanding the problem or the solution pattern being presented. In any case I thank you much for what you've done to improve my understanding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:28:14.350", "Id": "8235", "Score": "0", "body": "@mattwilkie, glad to help. I'm surprised that nobody has created a useful wrapper of the windows registry. You are correct about the key/hive but I'm not sure why it didn't give you a NameError about that. At any rate, you may find it easier to create a new registry wrapping class then trying to fix my hack job." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:33:31.563", "Id": "8236", "Score": "0", "body": "@mattwilkie, truth be told I constantly put down the wrong variable name when I write code. I catch this when I test my code, but you trying to untangle that may not be worth your effort." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T19:01:32.020", "Id": "8238", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1608/discussion-between-matt-wilkie-and-winston-ewert)" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T01:07:58.390", "Id": "5218", "ParentId": "5217", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-06T23:42:53.520", "Id": "5217", "Score": "3", "Tags": [ "python" ], "Title": "All tangled up in IF and ELIF and TRY" }
5217
<p>I'm trying to implement my own A* pathfinder, but the voices in my head scream of better ways to do this. Probably because I'm exceeding Python's default maximum recursion depth of 1000.</p> <pre><code>class PathFinder(): ## grid is a list of 8 sub-lists, each containing 8 nodes. ## start and goal are tuples representing the grid indexes of my start and goal. def __init__(self, start, goal, grid): ## I don't do anything with these yet, ## just thought they would be good to have. self.goal = goal self.start = start self.grid = grid def find_path(self, start, goal, path=[]): ## My seemingly hackish method of looping through ## the 8 cells surrounding the one I'm on. for row in (-1,0,1): for col in (-1,0,1): if row == 0 and col == 0: continue cell = [start[0]+row,start[1]+col] ## Catching the inevitable exception when I try to examine ## the surroundings of cells that are already on the edge. try: ## Skip if the cell is blocked ("X"). if self.grid[cell[0]][cell[1]] == "X": continue except IndexError: continue path.append(cell) if cell == goal: return path self.find_path(cell, goal, path) def main(): import Gridder2 grid = Gridder2.board() start = (0,0) goal = (0,3) pt = PathFinder(start, goal, grid) print(pt.find_path(start, goal)) return 0 if __name__ == '__main__': main() </code></pre> <p>My <code>find_path</code> function particularly seems like it needs work. Seems like I <em>should</em> be able to calculate a path through an 8x8 grid with a recursion depth of less than 1000.</p> <p>How can I improve this? </p>
[]
[ { "body": "<p>Note: this is a fair distance from being an A* algorithm - perhaps correctly implementing a recursive depth-first search (what your algorithm is currently closest too) would be a good start.</p>\n\n<p>You're right, you should be able to calculate a path through an 8x8 without exceeding the recursion limit. Try tracing your code through as you expect it to execute, or add a print statement to show what cell is being checked each time. (and a raw_input() or something so you can easily read it - I would suggest a debugger but that's a crutch you can do without at this level)</p>\n\n<p>(spoiler) Due to negative indices not raising IndexError's in Python (edited this answer after Winston pointed this out), the path you're trying isn't the one you think it is. And the path that exceeds the recursion limit is probably one that repeatedly tries to stay in the current square, checking over and over what happens if the next node visited is the current square.</p>\n\n<p>If only there were a way to close off some of these execution paths; a way to know that a certain path isn't worth checking out any further, so another branch of execution which probably holds a better solution should be tried instead. A good start is that staying in the same place is never really helpful for a static maze, since that's the position you were just in the middle of checking the solutions for! But there are other instances in which you're about to check a square you should have already figured out isn't worth investigating. Check out any literature on depth-first search for the solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T03:54:23.370", "Id": "7865", "Score": "0", "body": "Not marking them as visited! I had a feeling I was missing something fundamental... I will try this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:03:55.020", "Id": "7866", "Score": "0", "body": "Decided I shouldn't have given it away so easily - it's a fun realization to come to on your own. But in your case, you probably don't quite understand depth-first search yet or are forgetting something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:12:27.740", "Id": "7869", "Score": "0", "body": "@John feel free to open another question if you get stuck again - I didn't actually answer the question in your title with this post, marking nodes as visited won't actually make this a A* search." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:16:02.663", "Id": "7870", "Score": "0", "body": "Well, I was *going* for A*, but I'm very new to pathfinding. I didn't even know this was called a depth-first search. Now that I know what to Google for, I should be a lot better off. :P You answered the question I *meant* to ask, that's the important part." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T03:52:26.983", "Id": "5220", "ParentId": "5219", "Score": "5" } }, { "body": "<pre><code>class PathFinder():\n</code></pre>\n\n<p>Either but object in the () or drop them. Having them there empty makes me feel hollow inside.</p>\n\n<pre><code> ## grid is a list of 8 sub-lists, each containing 8 nodes.\n ## start and goal are tuples representing the grid indexes of my start and goal.\n\n def __init__(self, start, goal, grid):\n ## I don't do anything with these yet, \n ## just thought they would be good to have.\n self.goal = goal\n self.start = start\n self.grid = grid\n\n def find_path(self, start, goal, path=[]):\n</code></pre>\n\n<p>Don't put mutable values like list as your default parameters. Python will not create a new list everytime this function is called, rather it will keep reusing the same list which is probably not what you want</p>\n\n<pre><code> ## My seemingly hackish method of looping through \n ## the 8 cells surrounding the one I'm on.\n for row in (-1,0,1):\n for col in (-1,0,1):\n if row == 0 and col == 0:\n continue\n</code></pre>\n\n<p>I suggest creating a global constant with the 8 directions and doing: <code>for row, col in DIRECTIONS:</code></p>\n\n<pre><code> cell = [start[0]+row,start[1]+col]\n</code></pre>\n\n<p>Don't use lists unless they are actually lists. This should be a tuple. </p>\n\n<pre><code> ## Catching the inevitable exception when I try to examine\n ## the surroundings of cells that are already on the edge.\n try:\n ## Skip if the cell is blocked (\"X\").\n if self.grid[cell[0]][cell[1]] == \"X\":\n continue\n except IndexError:\n continue\n</code></pre>\n\n<p>I suggest a function <code>get_blocked</code> that you pass cell to which check for 'X' and also returns True if the cell is off the side of the map. Also catching IndexError may not be quite what you want because negative numbers are valid indexes, but probably not want you want. I suggest checking in the get_blocked function for inboundedness.</p>\n\n<pre><code> path.append(cell)\n if cell == goal:\n return path\n self.find_path(cell, goal, path)\n\ndef main():\n import Gridder2\n</code></pre>\n\n<p>Usually not a good idea to import anywhere but at the start of a file</p>\n\n<pre><code> grid = Gridder2.board()\n start = (0,0)\n goal = (0,3)\n pt = PathFinder(start, goal, grid)\n</code></pre>\n\n<p>pt?</p>\n\n<pre><code> print(pt.find_path(start, goal))\n</code></pre>\n\n<p>Decide whether the start/goal get passed to the constructor or the find method. Don't do both.</p>\n\n<pre><code> return 0\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>If you are going to return a value from your main function, you should pass it to sys.exit() so that it actually functions as a return code.</p>\n\n<p>And everything Thomas said. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:29:03.483", "Id": "7871", "Score": "0", "body": "All good points, but especially important catch on the negative indices not raising an IndexError, just wrapping around. I won't so confidently assert what the code is doing without executing it next time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T05:01:48.330", "Id": "7872", "Score": "0", "body": "@Thomas, yah, I've hit that enough times to be wary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T18:40:35.827", "Id": "7910", "Score": "0", "body": "It works so much better now and it's more readable too! Thank you very much!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T04:22:29.440", "Id": "5221", "ParentId": "5219", "Score": "6" } } ]
{ "AcceptedAnswerId": "5221", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T03:27:40.240", "Id": "5219", "Score": "5", "Tags": [ "python" ], "Title": "How can I improve my A* algorithm in Python?" }
5219
<pre><code> internal void ShiftSwapInstrument(SwapCurve shiftedCurve, string swapToShift) { if (SwapExists(shiftedCurve, swapToShift)) { var rateToShift = shiftedCurve.Swaps.Single(r =&gt; r.Description() == swapToShift); rateToShift.Rate = rateToShift.Rate + 1 / 10000.0; return; } throw new PdhSwapRateNotFoundException(swapToShift); } private bool SwapExists(SwapCurve shiftedCurve, string swapToShift) { var swap = Array.Find(shiftedCurve.Swaps, r =&gt; r.Description() == swapToShift); return swap == null ? false : true; } </code></pre> <p>The above code is what I've written to handle processing when an item is not found in an array. The exception should 'never' be thrown - it's truly exceptional if it does happen - thus I can use <code>Single</code> without reservation within the <code>if</code>-block.</p> <p>My question is whether my exception handling is correct/feasible when items are not found in my array and is it correct for me to <code>return;</code> when I do?</p> <p><em><strong>Secondary question</em></strong></p> <p>I noted the following about <a href="http://msdn.microsoft.com/en-us/library/d9hy2xwa.aspx" rel="nofollow"><code>Array.Find</code></a> on MSDN</p> <blockquote> <p>Return Value</p> <p>Type: T The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.</p> </blockquote> <p>Am I correct in my understanding, that since <code>SwapCurve</code> &amp; <code>Swaps</code> are reference types the default value will be <code>null</code>?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:33:01.973", "Id": "7882", "Score": "0", "body": "Your code looks too complicated, look to shorter version in my answer, doing exaclty the same." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:38:38.270", "Id": "7883", "Score": "0", "body": "@ArturMustafin - complicated, how so? an excessive call or two is perfectly acceptable to me if it increases readability and understandability. You are correct, in that your version is shorter, but that extra second it takes me to understand the intent of the method six months from now to me is worth the 'complicated' code" } ]
[ { "body": "<p>Your error handling looks correct to me as long as your application is <code>catch</code>ing <code>PdhSwapRateNotFoundException</code> at some point and logging appropriate warning/error to notify user about this.</p>\n\n<p>A slight cosmetic modification to your code could be like:</p>\n\n<pre><code>{\n if (!SwapExists(shiftedCurve, swapToShift))\n throw new PdhSwapRateNotFoundException(swapToShift);\n\n var rateToShift = shiftedCurve.Swaps.Single(r =&gt; r.Description() == swapToShift);\n rateToShift.Rate = rateToShift.Rate + 1 / 10000.0;\n return; // you don't actually need this.\n}\n</code></pre>\n\n<p>And you're correct default value of reference type is <code>null</code>.</p>\n\n<p><strong>Edit:</strong>\nI assume <code>shiftedCurve.Swaps</code> will not be <code>null</code>, otherwise Find will throw an exception. And if you think it could be the case then you may want to update your code to check for <code>shiftedCurve.Swaps == null</code> and handle it appropriately.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:24:26.160", "Id": "7878", "Score": "1", "body": "Cosmetic change looks good" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:30:40.587", "Id": "7880", "Score": "0", "body": "What about readability and performance? and i think that call to SwapExists leads to excessive searches twice: first time in `ShapExists` call, another when the single actual value is changed. You can easily combine these two calls in one call to `SingleOrDefault<T>()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:31:03.877", "Id": "7881", "Score": "0", "body": "re the Edit - `Find` returns the default value which is null. `Swaps` will never be null at this point" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:41:16.060", "Id": "7885", "Score": "0", "body": "@ArturMustafin - Your suggestions makes sense, but the original question was about error handling. You downvoted my answer :-(, np, mate!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:58:00.323", "Id": "7886", "Score": "0", "body": "Array.Find is much faster then SingleOrDefault, so when talking about performance you are wrong!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:20:42.067", "Id": "5224", "ParentId": "5223", "Score": "1" } }, { "body": "<p>My thoughts:</p>\n\n<p><strong>Step1:</strong></p>\n\n<p>You'd better to improve readability of you code since the IL will be exacly the same:</p>\n\n<p><strong>Step2:</strong></p>\n\n<p>Remove excessive method calls by using extenstion method <code>.SingleOrDefault&lt;T&gt;(..)</code>:</p>\n\n<pre><code> internal void ShiftSwapInstrument(SwapCurve shiftedCurve, string swapToShift) \n { \n var rateToShift = shiftedCurve.Swaps.SingleOrDefault(r =&gt; r.Description() == swapToShift)\n if (rateToShift == null) \n { \n throw new PdhSwapRateNotFoundException(swapToShift); \n }\n rateToShift.Rate = rateToShift.Rate + 1 / 10000.0; \n } \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T09:23:46.410", "Id": "5225", "ParentId": "5223", "Score": "1" } } ]
{ "AcceptedAnswerId": "5224", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T07:38:29.727", "Id": "5223", "Score": "3", "Tags": [ "c#", "exception-handling" ], "Title": "Is my error handling feasible when dealing items not found in an array?" }
5223
<p>In a homework, there is an exercise in which I have a script that is used to search for a password.</p> <p>One of the questions is if is possible to make it "more intelligent", and I'm stuck on it.</p> <pre><code>#!/bin/bash space1="a b c d e f g h i j k l m n o p q r s t u v w x y z" if [ $# -le 1 ] then echo "Ussage: " $0 SALT PASSWORD_CODED exit fi for i in $space1 do for j in $space1 do for k in $space1 do variable=$(openssl passwd -crypt -salt "$1" "$i$j$k") if [ "$variable" = $2 ] then echo password found: $i$j$k exit fi done done done </code></pre> <p>If it is possible, I prefer only a clue to help me to discover the answer correct, not the answer itself. I promise to post the result when I get the answer for myself.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T08:16:25.243", "Id": "7954", "Score": "1", "body": "As suggested, you could use common words first or a dictionary, but brute force is brute force. In this case it's only 3 lower case characters, so it should take no time at all. I don't know if there is any other way to make the algorithm more intelligent." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-06T21:57:18.357", "Id": "8841", "Score": "0", "body": "What does \"more intelligent\" mean?" } ]
[ { "body": "<p>There's no real way to speed up the brute-force enumeration of all possible 3-letter passwords. </p>\n\n<p>Perhaps you could use the dictionary. There's a finite list of 3-letter English words. They may be slightly more common.</p>\n\n<p>Also, if you google for \"most common passwords\", some kind of 3-letter version of that list could be tried before anything else.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T17:07:01.010", "Id": "5235", "ParentId": "5226", "Score": "3" } }, { "body": "<p>Look at the man page for openssl <a href=\"http://www.openssl.org/docs/apps/openssl.html\" rel=\"nofollow\">http://www.openssl.org/docs/apps/openssl.html</a></p>\n\n<p>It is the command being executed here:</p>\n\n<pre><code>$(openssl passwd -crypt -salt \"$1\" \"$i$j$k\")\n</code></pre>\n\n<p>Another Clue below.<br>\nOnly roll your curser over it if you need the extra help.</p>\n\n<blockquote class=\"spoiler\">\n <p> Do you need to pass the passwords one at a time.</p>\n</blockquote>\n\n<p>Still have not worked it out!</p>\n\n<blockquote class=\"spoiler\">\n <p> Try: openssl passwd -crypt -salt &lt;salt&gt; &lt;passwd1&gt; &lt;password2&gt; &lt;password3&gt; ....</p>\n</blockquote>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-06T19:46:50.517", "Id": "5840", "ParentId": "5226", "Score": "2" } }, { "body": "<p>If you want to support passwords with 4-5-6-n characters without more loops you could write a <a href=\"http://en.wikipedia.org/wiki/Bijection\" rel=\"nofollow\">bijective function</a> which maps <a href=\"http://en.wikipedia.org/wiki/Bijective_numeration#The_bijective_base-26_system\" rel=\"nofollow\">integers to strings</a>.</p>\n\n<p>Maybe you want to check the homepage of the <a href=\"http://www.openwall.com/john/\" rel=\"nofollow\">John the Ripper password cracker</a>. It has downloadable word lists and maybe you can find some information about how John generates the passwords. Also check the <em>Methods of attack</em> chapter in \n<a href=\"http://www.ibm.com/developerworks/library/s-crack/\" rel=\"nofollow\">Rob Shimonski's Hacking techniques article</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-06T22:58:44.397", "Id": "5842", "ParentId": "5226", "Score": "0" } }, { "body": "<p>The best way to do </p>\n\n<pre><code>space1=\"a b c d e f g h i j k l m n o p q r s t u v w x y z\"\nfor i in $space1; do\n for j in $space1; do\n for k in $space1; do\n echo $i$j$k\n done\n done\ndone\n</code></pre>\n\n<p>in bash is probably : </p>\n\n<pre><code>for i in {a..z}{a..z}{a..z}; do echo $i; done \n</code></pre>\n\n<p>Then, depending on what your homeworks says, it might or might not be what you are looking for.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-18T00:28:02.587", "Id": "22842", "ParentId": "5226", "Score": "2" } } ]
{ "AcceptedAnswerId": "5235", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T10:42:34.757", "Id": "5226", "Score": "7", "Tags": [ "security", "homework", "bash", "openssl" ], "Title": "Making this password search more intelligent" }
5226
<p>HTML is a markup language similar to <a href="http://stackoverflow.com/tags/xml/info">XML</a> that is predominantly used to create web pages.</p> <p>HTML standards, as well as those for many other web technologies, are maintained by the <a href="http://www.w3.org/" rel="nofollow">World Wide Web Consortium</a> (W3C). The current iteration of the language, HTML&nbsp;4, was introduced in 1997, and the next iteration, <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/" rel="nofollow">HTML5</a>, is currently under active development jointly by the W3C and the <a href="http://www.whatwg.org/" rel="nofollow">Web Hypertext Application Technology Working Group</a> (WHATWG). </p> <p><strong>Standards</strong></p> <ul> <li><a href="http://www.w3.org/TR/1999/REC-html401-19991224/" rel="nofollow">HTML&nbsp;4.01 Specification documentation.</a></li> <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/" rel="nofollow">HTML5 at the WHATWG</a></li> <li><a href="http://www.w3.org/TR/html5/" rel="nofollow">HTML5 at the W3C</a></li> <li><a href="http://developers.whatwg.org/" rel="nofollow">HTML5 Developer Edition</a></li> </ul> <p><strong>Useful tools and references</strong></p> <ul> <li><a href="http://validator.w3.org/" rel="nofollow">W3C HTML Validator</a></li> <li><a href="http://reference.sitepoint.com/html" rel="nofollow">SitePoint HTML reference</a></li> <li><a href="http://dev.opera.com/articles/view/1-introduction-to-the-web-standards-cur/" rel="nofollow">The Web Standards Curriculum</a></li> </ul> <h3>Free HTML Books</h3> <ul> <li><a href="http://fortuito.us/diveintohtml5/" rel="nofollow">Dive Into HTML5</a></li> <li><a href="http://www.htmldog.com/" rel="nofollow">HTML Dog Tutorials</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T13:40:16.310", "Id": "5227", "Score": "0", "Tags": null, "Title": null }
5227
HTML (Hyper Text Markup Language) is the standard content markup language of the web. It is an open standard developed and maintained by W3C (World Wide Web Consortium).
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T13:40:16.310", "Id": "5228", "Score": "0", "Tags": null, "Title": null }
5228
<pre><code>def range_find(pageset,upperlimit=1000): pagerangelist=[] for page in range(0,upperlimit): if page in pageset and previouspage in pageset:pagerangelist[-1].append(page) elif page in pageset and not (previouspage in pageset):pagerangelist.append([page]) else: pass previouspage=page pagerangestringlist=[] for pagerange in pagerangelist: pagerangestringlist.append(str(pagerange[0])+('-'+str(pagerange[-1]))*((len(pagerange)-1)&gt;0)) return(','.join(pagerangestringlist)) print(range_find({1,2,5,7,8,11,19,25,29,30,31,39,40,41,42,43,44,56,57,59,60,70,71,72,100,101,103,104,105})) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T15:22:11.620", "Id": "7898", "Score": "0", "body": "(a) Your indentation is wrtong. (b) You didn't reference the previous version of this question. (c) You didn't include the output from your test. (d) You didn't test the `[1, 2, 4, 5, 3]` case which requires merging two partitions. If you require the input to be sorted, please state that clearly or add `sorted` to assure it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:06:48.037", "Id": "7899", "Score": "0", "body": "@S.Lott, where is the indentation wrong? He's passing in a set so order doesn't matter. Your other points are good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:17:21.857", "Id": "7900", "Score": "0", "body": "Since the indentation is *now* fixed, it's no longer wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T17:13:55.540", "Id": "7909", "Score": "0", "body": "@S.Lott, okay, so it was just that he failed to format the code correctly in his post, not that the indentation in the original code was incorrect." } ]
[ { "body": "<pre><code>def range_find(pageset,upperlimit=1000):\n\n pagerangelist=[]\n\n for page in range(0,upperlimit):\n</code></pre>\n\n<p>There is no reason to include the 0. Why don't you calculate the upperlimit by max(pageset)?</p>\n\n<pre><code> if page in pageset and previouspage in pageset:pagerangelist[-1].append(page)\n elif page in pageset and not (previouspage in pageset):pagerangelist.append([page])\n else: pass\n</code></pre>\n\n<p>Don't squish all that stuff onto one line. It makes it harder to read. Having an else: pass case is useless</p>\n\n<pre><code> previouspage=page\n</code></pre>\n\n<p>Since you are counting, just use page - 1 instead of previouspage</p>\n\n<pre><code> pagerangestringlist=[]\n\n for pagerange in pagerangelist:\n\n pagerangestringlist.append(str(pagerange[0])+('-'+str(pagerange[-1]))*((len(pagerange)-1)&gt;0))\n</code></pre>\n\n<p>Too clever. Just use an if. This technique makes it harder to see what is going on. Also pointless extra parens.</p>\n\n<pre><code> return(','.join(pagerangestringlist))\n</code></pre>\n\n<p>Don't put parens around your return statement expressions. </p>\n\n<p>Algorithmwise this may be problematic because it will slower for books with many pages even if you don't use many pages from them. For example</p>\n\n<pre><code>range_find({1, 2, 1000000},100000000)\n</code></pre>\n\n<p>Will spend a long time churning through pages that aren't really of interest.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:08:56.097", "Id": "5230", "ParentId": "5229", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T15:07:41.950", "Id": "5229", "Score": "1", "Tags": [ "python" ], "Title": "Grouping consecutive numbers into ranges in Python 3.2 : New version for set" }
5229
<p>Useful sites to improve your code if you're new to node:</p> <ul> <li><a href="http://nodemanual.org/latest/" rel="nofollow">nodemanual</a> - a collaborative effort the node community. Also acts has a handy meta reference for the API and Mozilla's canonical Javascript Reference/</li> <li><a href="http://docs.nodejitsu.com" rel="nofollow">docs.nodejitsu.com</a> - a collection of how to's written by one of the most innovative node PaaS in the industry.</li> <li><a href="http://nodetuts.com/" rel="nofollow">node tuts</a> - (Video) Pedro Teixeria walks you through creating a nodejs app from hello world to benchmarking. He also covers the often misunderstood subject of Streams.</li> <li><a href="http://nodeup.com/" rel="nofollow">nodeup</a> - (Audio) Podcast brought to you by the finest brains in node universe. I highly recommend the deep dive series.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:18:56.270", "Id": "5232", "Score": "0", "Tags": null, "Title": null }
5232
Node.js is an event based, asynchronous I/O framework that uses Google's V8 JavaScript engine. Node.js is commonly used for heavy client-server JavaScript applications.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:18:56.270", "Id": "5233", "Score": "0", "Tags": null, "Title": null }
5233
<p>I'm wondering if there is a simplier regex I could use in my code to remove the beginning and ending char in a line. Maybe combine some regex's? In this instance, it's a comma at the beginning and ending of a line. My output should be the fields seperated into CSV format.</p> <pre><code>#!/usr/local/bin/perl use strict; use warnings; parse_DPCRS(); sub parse_DPCRS { open ( FILEIN, 'txt_files/AKR_DPCRS.txt' ); open ( FILEOUT, '&gt;txt_files/AKR_DPCRS.csv' ); while (&lt;FILEIN&gt;) { next if /^(\s)*$/; #skip blank lines next if /^\&gt;/; #skip command line that start with &gt; next if /^\s+POINT\sCODE/; #skip header next if /^\s+NODE\sNAME/; #skip header next if /^\s+\=+/; #skip header next if /^\s+CCS\sDPCRS/; #skip pageination footer chomp; #removing trailing newline character s/\s+/,/g; #replace white space with a comma s/^,//; #replace beginning comma with empty s/,$//; #replace ending comma with empty my ( $nodeName, $pointCodeDec ) = split( "," ); print FILEOUT ($nodeName . "," . $pointCodeDec . "\n"); #print "$_\n"; } }; close (FILEOUT); close (FILEIN); exit; </code></pre> <p>Here's a slice of the text file I'm parsing</p> <pre><code>&gt;DISP CCS DPCRS ALL 0 POINT CODE POINT CODE TYPE OF ROUTESET NOTIFY NODE NODE NAME DECIMAL HEX ROUTE MASTER SCCP LOCATION =========== =========== ========== ======= ======== ====== ======== PBVJPRCO01T 1-1-1 010101 FULL PC 119 NO NON-ADJ ROCHNYXA06T 1-6-1 010601 FULL PC 58 NO NON-ADJ NYCNNYDRW17 1-6-2 010602 FULL PC 58 NO NON-ADJ SYRCNYSW01T 1-6-3 010603 FULL PC 22 NO NON-ADJ SYRCNYSWDS0 1-6-15 01060F FULL PC 58 NO NON-ADJ ROCHNYFEDS0 1-6-17 010611 FULL PC 58 NO NON-ADJ NYCMNYHD01T 1-9-11 01090B FULL PC 22 NO NON-ADJ NWRKNJ1001T 1-9-14 01090E FULL PC 22 NO NON-ADJ BSTNMABL01T 1-9-16 010910 FULL PC 22 NO NON-ADJ </code></pre>
[]
[ { "body": "<p>I don't know of a tricky regexp, but wouldn't you be better served by creating the string using a combination of split and join?</p>\n\n<p><a href=\"http://perldoc.perl.org/functions/split.html\" rel=\"nofollow\">http://perldoc.perl.org/functions/split.html</a></p>\n\n<p>The examples in the middle show different combinations to split based on word boundaries.\nThere are also examples that show how to get matching splits for the last and first character.</p>\n\n<p>Hope thIs helps</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T14:50:54.107", "Id": "5254", "ParentId": "5234", "Score": "1" } }, { "body": "<p>I try to run your code, and i don't understand what do you want on exit?\nI'll see first two colums, if what you want you need to use <code>print \"$1,$2\\n\"</code></p>\n\n<p>Try to use this:</p>\n\n<pre><code>#!/usr/bin/perl\n\nwhile (&lt;&gt;) {\n print \"$1,$2,$3,$4,$5,$6,$7\\n\" if /(\\w{11})\\s+(\\d+-\\d+-\\d+)\\s+(\\w{6})\\s+(\\w.*?)\\s+(\\d+)\\s+(\\w.*?)\\s+(\\w.*?)$/gs\n}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>txt2csv.pl txt_files/AKR_DPCRS.txt &gt; txt_files/AKR_DPCRS.csv\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T14:02:44.740", "Id": "5444", "ParentId": "5234", "Score": "1" } }, { "body": "<p>Here is an example of how I might do that.</p>\n\n<pre><code>#!/usr/local/bin/perl\nuse strict;\nuse warnings;\nuse 5.10.1;\n\nmy $input_filename = 'test.in';\nmy $output_filename = 'test.out';\n\nopen my $input, '&lt;', $input_filename;\n\nmy $pack = '';\n\n# throw out everything before \"=====\" line\nwhile( &lt;$input&gt; ){\n if( /^\\s*=[\\s=]+$/ ){\n # use \"=====\" line to calculate lengths and offsets\n\n # split on \\s [=] boundary keeping everything\n my @elem = split /(\\s+)/;\n\n my $pos = 0;\n for (@elem){\n my $length = length $_;\n if( /=/ ){\n $pack .= '@'.$pos.'A'.$length;\n }\n $pos += $length;\n }\n\n last; # stop skipping lines\n }\n}\n# at this point the iterator for $input is after \"=====\" line\n\n{\n open my $output, '&gt;', $output_filename;\n for my $line ( &lt;$input&gt; ){\n say {$output} join ',', unpack $pack, $line;\n }\n close $output;\n}\nclose $input;\n</code></pre>\n\n<p>This code will continue to work if the width of the columns, or number of columns change.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T21:42:22.000", "Id": "6925", "ParentId": "5234", "Score": "1" } }, { "body": "<p>Here is a single regex that removes <code>,</code> (comma) at the beginig or at the end of a string:</p>\n\n<pre><code>$str =~ s/^,+|,+$//g;\n</code></pre>\n\n<p>and here is a benchmark that compares this regex with a double one:</p>\n\n<pre><code>use Benchmark qw(:all);\n\nmy $str = q/,a,b,c,d,/;\nmy $count = -3;\ncmpthese($count, {\n 'two regex' =&gt; sub {\n $str =~ s/^,+//;\n $str =~ s/,+$//;\n },\n 'one regex' =&gt; sub {\n $str =~ s/^,+|,+$//g;\n },\n });\n</code></pre>\n\n<p><strong>The result:</strong></p>\n\n<pre><code> Rate one regex two regex\none regex 597559/s -- -58%\ntwo regex 1410348/s 136% --\n</code></pre>\n\n<p>We can see that two regex are really faster than one regex that combines the two.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-04-01T12:15:50.980", "Id": "24592", "ParentId": "5234", "Score": "2" } } ]
{ "AcceptedAnswerId": "24592", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T16:33:23.530", "Id": "5234", "Score": "5", "Tags": [ "performance", "perl", "regex" ], "Title": "Best way to replace a beginning and end character in Perl using Regular Expression?" }
5234
<p>I don't actually know much about how base32 (or base64) works, but I noticed that there was no official base32 implementation in PHP, so I figured I'd make one.</p> <p>I Googled around a bit to figure out how it works, and found <a href="http://www.garykessler.net/library/base64.html" rel="nofollow">this page</a>. Using the examples at the bottom, I hacked up this base32 class. GitHub project: <a href="https://github.com/NTICompass/PHP-Base32" rel="nofollow">https://github.com/NTICompass/PHP-Base32</a></p> <pre><code>&lt;?php /** * NTICompass' crappy base32 library for PHP * * http://labs.nticompassinc.com */ class Base32{ var $encode, $decode, $type; // Supports RFC 4648 (default) or Crockford (http://www.crockford.com/wrmg/base32.html) function __construct($alphabet='rfc4648'){ $alphabet = strtolower($alphabet); $this-&gt;type = $alphabet; // Crockford's alphabet removes I,L,O, and U $crockfordABC = range('A', 'Z'); unset($crockfordABC[8], $crockfordABC[11], $crockfordABC[14], $crockfordABC[20]); $crockfordABC = array_values($crockfordABC); $alphabets = array( 'rfc4648' =&gt; array_merge(range('A','Z'), range(2,7), array('=')), 'crockford' =&gt; array_merge(range(0,9), $crockfordABC, array('=')) ); $this-&gt;encode = $alphabets[$alphabet]; $this-&gt;decode = array_flip($this-&gt;encode); // Add extra letters for Crockford's alphabet if($alphabet === 'crockford'){ $this-&gt;decode['O'] = 0; $this-&gt;decode['I'] = 1; $this-&gt;decode['L'] = 1; } } private function bin_chunk($binaryString, $bits){ $binaryString = chunk_split($binaryString, $bits, ' '); if($this-&gt;endsWith($binaryString, ' ')){ $binaryString = substr($binaryString, 0, strlen($binaryString)-1); } return explode(' ', $binaryString); } // String &lt;-&gt; Binary conversion // Based off: http://psoug.org/snippet/PHP-Binary-to-Text-Text-to-Binary_380.htm private function bin2str($binaryString){ // Make sure binary string is in 8-bit chunks $binaryArray = $this-&gt;bin_chunk($binaryString, 8); $string = ''; foreach($binaryArray as $bin){ // Pad each value to 8 bits $bin = str_pad($bin, 8, 0, STR_PAD_RIGHT); // Convert binary strings to ascii $string .= chr(bindec($bin)); } return $string; } private function str2bin($input){ $bin = ''; foreach(str_split($input) as $s){ // Return each character as an 8-bit binary string $s = decbin(ord($s)); $bin .= str_pad($s, 8, 0, STR_PAD_LEFT); } return $bin; } // starts/endsWith from: // http://stackoverflow.com/questions/834303/php-startswith-and-endswith-functions/834355#834355 private function startsWith($haystack, $needle){ $length = strlen($needle); return substr($haystack, 0, $length) === $needle; } private function endsWith($haystack, $needle){ $length = strlen($needle); return substr($haystack, -$length) === $needle; } // base32 info from: http://www.garykessler.net/library/base64.html // base32_encode public function base32_encode($string){ // Convert string to binary $binaryString = $this-&gt;str2bin($string); // Break into 5-bit chunks, then break that into an array $binaryArray = $this-&gt;bin_chunk($binaryString, 5); // Pad array to be divisible by 8 while(count($binaryArray) % 8 !== 0){ $binaryArray[] = null; } $base32String = ''; // Encode in base32 foreach($binaryArray as $bin){ $char = 32; if(!is_null($bin)){ // Pad the binary strings $bin = str_pad($bin, 5, 0, STR_PAD_RIGHT); $char = bindec($bin); } // Base32 character $base32String .= $this-&gt;encode[$char]; } return $base32String; } // base32_decode public function base32_decode($base32String){ $base32Array = str_split(str_replace('-', '', strtoupper($base32String))); $binaryArray = array(); $string = ''; foreach($base32Array as $str){ $char = $this-&gt;decode[$str]; if($char !== 32){ $char = decbin($char); $string .= str_pad($char, 5, 0, STR_PAD_LEFT); } } while(strlen($string) %8 !== 0){ $string = substr($string, 0, strlen($string)-1); } return $this-&gt;bin2str($string); } } ?&gt; </code></pre> <p>This code works, I've tested it using <a href="http://online-calculators.appspot.com/base32/" rel="nofollow">this page</a>, and it gives the same result, but I don't think this is the best way of doing base32.</p> <p>Is there a better way to do base32 that's maybe more efficient than what I have?</p>
[]
[ { "body": "<p>Your constructor going through all the work to build both alphabets and then throwing one away seems odd. I'd probably have a Base32 base class, and have the two alphabets be subclasses.</p>\n\n<p>Using the binary conversion does seem problematic. This is especially true since the numbers are already in binary inside the computer. </p>\n\n<p>I can see a few different approaches:</p>\n\n<p>Make an array of 5 bit numbers:</p>\n\n<pre><code>value = 0\nbits_remaining = 0\nwhile more data or bits_remaining:\n while bits_remaining &gt; 5:\n remove first five bits of value and place into array\n value = value &lt;&lt; 8 + ord(next letter in data)\n</code></pre>\n\n<p>Hand code for each 8 byte case:</p>\n\n<pre><code> codes = array(\n (value[0] &amp; 0xfd)) &gt;&gt; 3,\n (value[0] &amp; 0x3) &lt;&lt; 3 | value[1] &amp; (0x7) &gt;&gt; 3,\n ...\n</code></pre>\n\n<p>Since (8 * 5) % 8 = 0 you can chunk your data into eight bit pieces and just hand code the neccesary bitflags to figure out which index should be fetched.</p>\n\n<p>Use GMP</p>\n\n<pre><code> value = gmp_init(0)\n for( letter in data)\n {\n value = gmp_or( gmp_mult( value, gmp_pow(2, 8)), ord(letter))\n }\n gmp_strval(value, 32)\n</code></pre>\n\n<p>(Actually algorithm have not been thought through, but perhaps this might give you an idea of things to try)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T00:43:54.727", "Id": "8147", "Score": "0", "body": "I wasn't really sure how to use bit operators, which is why I did it the way I did. I'll see what I can hack up from this. Thanks :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T22:29:45.907", "Id": "5403", "ParentId": "5236", "Score": "2" } }, { "body": "<p>For <code>base32_decode</code> You can use <a href=\"http://pastebin.com/gw3gC6T7\" rel=\"nofollow\">this</a> </p>\n\n<pre><code>static function base32_decode($s){\n static $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';\n\n $tmp = '';\n\n foreach (str_split($s) as $c) {\n if (false === ($v = strpos($alphabet, $c))) {\n $v = 0;\n }\n $tmp .= sprintf('%05b', $v);\n }\n $args = array_map('bindec', str_split($tmp, 8));\n array_unshift($args, 'C*');\n\n return rtrim(call_user_func_array('pack', $args), \"\\0\");\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T15:22:23.843", "Id": "32533", "Score": "0", "body": "Hmm, this seems like a much quicker way than mine. I don't know much about how `pack` works, but this looks like a neat method." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-08-10T14:16:00.180", "Id": "485024", "Score": "0", "body": "In the spirit of CodeReview, please explain your snippet with the intent to educate. @Zero" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-09T11:42:40.530", "Id": "20322", "ParentId": "5236", "Score": "1" } }, { "body": "<p>Nice, but just a little bit flawed: if the original file ends in a \\0 it is stripped from the decoded file. Removing rtrim isn't an option either, as that adds unwanted \\0</p>\n\n<p>Not sure it it's a flaw of the code or a flaw in rfc4648</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-21T15:02:09.567", "Id": "27637", "ParentId": "5236", "Score": "0" } } ]
{ "AcceptedAnswerId": "5403", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T17:32:52.900", "Id": "5236", "Score": "3", "Tags": [ "php", "algorithm" ], "Title": "base32 implementation in PHP" }
5236
<p>If I had many different Models that could all, through logic encapsulated by an adapter, produce items of type T, then I might maintain a producer/consumer component through the techniques demonstrated in the code.</p> <p>When I came up with this, it seemed novel to overlay a producer onto a linked list - the reflection in the Add() method is the most interesting thing to me, because of the way a new adapter is supported through an additional constructor in the derived class. </p> <p>The concept for reuse is that over time, if I need to place any arbitrary model data in the Producer queue:</p> <ol> <li>add client code: call producer.Add(AnySource) in client</li> <li>create adapter class for typeof(AnySource) to T </li> <li>add constructor: DerivedProdcuer(AnySource) - init enumerator</li> </ol> <p>A couple things I think are interesting and was hoping to hear feedback on - they are original ideas to me (surely unoriginal to others).</p> <ul> <li>the use of reflection in a base class that leverages the polymorphism of "this"</li> <li>the combination a factory method and a collection method - Add(object) both creates a new instance of Producer and adds that instance to a linked list of which it is currently the tail of.</li> </ul> <pre><code>void Main() { Producer&lt;Foo&gt; producer = new EntityProducer&lt;Foo&gt;(); var fooConsumer = new Consumer&lt;Foo&gt;(); fooConsumer.ItemReady += (sender, item) =&gt; { Console.Write(item.Data); }; var modelA = new ModelA(); modelA.Foos.Add(new Foo { Data = 1 }); modelA.Foos.Add(new Foo { Data = 2 }); modelA.Foos.Add(new Foo { Data = 3 }); producer = producer.Add(modelA); var modelB = new ModelB(); modelB.Bars.Add(new Bar { Data = "4" }); modelB.Bars.Add(new Bar { Data = "5" }); modelB.Bars.Add(new Bar { Data = "6" }); producer = producer.Add(modelB); fooConsumer.Consume(producer); } class Producer&lt;T&gt; { protected IEnumerator&lt;T&gt; _enum; Producer&lt;T&gt; _parent; public Producer&lt;T&gt; Add(object obj) { Producer&lt;T&gt; res = null; var constructor = this.GetType().GetConstructor(new [] {obj.GetType()}); res = (Producer&lt;T&gt;)constructor.Invoke(new [] {obj}); res._parent = this; return res; } public IEnumerable&lt;T&gt; Items { get { if(_parent != null &amp;&amp; _parent._enum != null) foreach (var foo in _parent.Items) yield return foo; if(this._enum != null) foreach (var foo in Produce(this._enum)) yield return foo; } } IEnumerable&lt;T&gt; Produce(IEnumerator target) { while(target.MoveNext()) { yield return (T)target.Current; } } } class EntityProducer&lt;Foo&gt; : Producer&lt;Foo&gt; { public EntityProducer() { } public EntityProducer(ModelA modelA) { _enum = modelA.Foos.Cast&lt;Foo&gt;().GetEnumerator(); } public EntityProducer(ModelB modelB) { _enum = new FooAdapter(modelB).Foos.Cast&lt;Foo&gt;().GetEnumerator(); } } class Consumer&lt;T&gt; { public delegate void ItemReadyHandler(Consumer&lt;T&gt; sender, T item); public event ItemReadyHandler ItemReady; void OnItemReady(T item) { if(ItemReady != null) { ItemReady(this, item); } } public void Consume(Producer&lt;T&gt; producer) { foreach (T item in producer.Items) { OnItemReady(item); } } } class Model { } class Entity { } class ModelA : Model { public List&lt;Foo&gt; Foos { get { return _foos; } } readonly List&lt;Foo&gt; _foos = new List&lt;Foo&gt;(); } class Foo : Entity { public int Data { get; set; } } class ModelB : Model { public List&lt;Bar&gt; Bars { get { return _bars; } } readonly List&lt;Bar&gt; _bars = new List&lt;Bar&gt;(); } class Bar : Entity { public string Data { get; set; } } class FooAdapter { readonly ModelB _modelB; public FooAdapter(ModelB modelB) { _modelB = modelB; } public IEnumerable&lt;Foo&gt; Foos { get { foreach (var bar in _modelB.Bars) { int converted; if(!int.TryParse(bar.Data, out converted)) throw new Exception("Conversion error while adapting Bar to Foo"); yield return new Foo { Data = converted }; } } } } </code></pre>
[]
[ { "body": "<p>I think you have unclear vision of what the design patterns are.</p>\n\n<p>Patterns are an idea (design pattern) or code (code pattern) proven by its effectiveness and adopted for usage and proven by practice behavior.</p>\n\n<p>If this is a method, than you have a very strange vision of what the method Add looks like:</p>\n\n<pre><code>public Producer&lt;T&gt; Add(object obj) \n{\n //...\n} \n</code></pre>\n\n<p>You've made an assumption that object is instantiable class with a public constructor. Additionally, you assume that the object being constructed is of a concrete type. On top of all design errors, you assume that the object being constructed will be of type compatible with the generic type T where the method is located (later in code).</p>\n\n<p>Then, you have created too many, too complex and excessive amounts of classes.</p>\n\n<p>Here is the code after the design refactoring, implementing your design/code pattern:</p>\n\n<pre><code>public interface IEntity { }\npublic interface IEntity&lt;T&gt; : IEntity { T Data { get; set; } }\n\nclass Entity&lt;T&gt; : IEntity&lt;T&gt;\n{\n public T Data { get; set; }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n List&lt;IEntity&gt; items = new List&lt;IEntity&gt;();\n items.Add(new Entity&lt;int&gt; { Data = 1 });\n items.Add(new Entity&lt;int&gt; { Data = 2 });\n items.Add(new Entity&lt;int&gt; { Data = 3 });\n items.Add(new Entity&lt;string&gt; { Data = \"4\" });\n items.Add(new Entity&lt;string&gt; { Data = \"5\" });\n items.Add(new Entity&lt;string&gt; { Data = \"6\" });\n items.ForEach((item) =&gt;\n {\n IEntity&lt;string&gt; str = item as IEntity&lt;string&gt;;\n if (str != null)\n {\n Console.Write(str.Data);\n }\n IEntity&lt;int&gt; val = item as IEntity&lt;int&gt;;\n if (val != null) \n {\n Console.Write(val.Data);\n }\n });\n }\n}\n</code></pre>\n\n<p>First, this code is working exactly the same, because, <code>Event</code> pattern can be implemented not only using events, but also using actions, because an event handler is an internal array for actions, associated with a particular event. In your scenario, there is only one event, so it can be implemented using the <code>ForEach&lt;T&gt;</code> extension method.</p>\n\n<p>Second, if your classes differ only on the types of property, it's a good idea to move the code into a generic class. To support both hierarchies you can create a common interface (<code>IEntity</code>) for both classes, then you can totally replace the all appearance with generic implementation.</p>\n\n<p>Lastly, you do not need the producer, because <code>List&lt;T&gt;</code>already implements <code>IEnumerable&lt;T&gt;</code>, which can be effectively used to process (consume) the collection of items by the extension methods in action, applied for each item. </p>\n\n<p>The code you have created does not seems have proven effectiveness, safety and ease of use, so it not likely to be called a pattern. At most I can call your code an erroneous and simple implementation of a producer/consumer pattern, overloaded by generics and code invocation through reflection.</p>\n\n<p>Final code will be very simple and easy to understand:</p>\n\n<pre><code>public interface IEntity { } \npublic interface IEntity&lt;T&gt; : IEntity { T Data { get; set; } } \npublic class Entity&lt;T&gt; : IEntity&lt;T&gt; \n{ \n public T Data { get; set; } \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T20:04:06.297", "Id": "7945", "Score": "1", "body": "you make a few good points but, fankly, your tone is offending - i'm new to design patterns, not design" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T04:46:32.383", "Id": "7951", "Score": "0", "body": "@Gabriel: I'm not a native speaker, i'm sorry if my past make you unhappy. I can remove some parts, but the idea is that we can always benefit from generics, and nowadays there is only a few situations where you need to use non-genetic version of classes, intefaces or methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T18:28:23.347", "Id": "7967", "Score": "0", "body": "Thanks for the clarification. I understand and appreciate the feedback, Artur." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T14:24:26.197", "Id": "8049", "Score": "0", "body": "I would do two things in addition. I would change the signature of `Add(T instance)` into `Add(param T[] instances)` so I could add a collection of entities at once. I also don't see why you need to perform the type check to see if the item is an `int` or a `string` before writing it to the console. Every type has `ToString()` through `object`, so you should be able to remove some code in that section." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-11T16:50:20.347", "Id": "40336", "Score": "0", "body": "+1: Despite the cultural missteps of a non-native speaker, this is very good code." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T16:29:49.373", "Id": "5257", "ParentId": "5237", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T19:42:13.010", "Id": "5237", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "What do you think of this chained producer/consumer/adapter (pattern?)" }
5237
<p>I wrote this palindrome extractor. And even though it works, and I can solve the challenge with it, it feels very Java-like. I was wondering what adjustments I could make in order for it to be more functional.</p> <pre><code>import collection.mutable._ object Level1 { def palindrome(input:String) = input.reverse == input def extractPalindromes(input:String) = { var counter = 0 val palindromes = new ListBuffer[String]() while(counter &lt; input.length) { var localCounter = 2 while((counter + localCounter) &lt; input.length) { //println("counter:"+counter+" localCounter:"+localCounter) val tempString = input.substring(counter, input.length - localCounter) if(palindrome(tempString)) palindromes += tempString localCounter += 1 } counter += 1 } palindromes } def main(args:Array[String]) = { val input = "I like racecars that go fast" extractPalindromes(input).filter(_.length &gt; 4).foreach(println) } } </code></pre>
[]
[ { "body": "<p>Here's a general idea about how I'd probably approach the problem:</p>\n\n<pre><code>def extractPalindromes(input:String) = \n{\n var minLength = 4;\n val palindromes = new ListBuffer[String]()\n if (palindrome(input)) palindromes += input\n if (input.length &gt; minLength) {\n palindromes += extractPalindromes(input.substring(1, input.length-1))\n palindromes += extractPalindromes(input.substring(0, input.length-1))\n }\n palindromes\n}\n</code></pre>\n\n<p>Be warned, however, that I don't normally write Scala, so I've undoubtedly gotten at least a few details wrong. I'm particularly uncertain about the part that tries to concatenate two ListBuffer's together using <code>+=</code> (and minLength should really be a constant or a parameter). The <em>general</em> notion of how it works should be about right though:</p>\n\n<blockquote>\n <p>if the current input is a palindrome, add it to the list<br>\n find palindromes with the first character removed<br>\n find palindromes with the last character removed<br>\n put all those results together and return them</p>\n</blockquote>\n\n<p>Note that rather than generate all the palindromes, then filter out any that are too short, I've written this to only generate those of at least the specified minimum length (4, in this case). As noted above, <code>minLength</code> should really be a constant or a parameter, not a <code>var</code>, but that should be a fairly minor adjustment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T03:42:16.103", "Id": "7923", "Score": "0", "body": "To concatenate two `ListBuffer`s, use `++=` instead of `+=`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T03:43:27.613", "Id": "7924", "Score": "0", "body": "Since your function is recursive, the compiler will ask you for its return type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T03:45:51.480", "Id": "7925", "Score": "0", "body": "Your function will return palindromes of length `minLength - 1` since the call to `input.substring(1, input.length-1)` shortens the string by 2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T03:46:59.573", "Id": "7926", "Score": "0", "body": "Finally, the way you scan the string, duplicate palindromes will be generated since both paths of the recursion will cover part of the same ground." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T22:10:12.713", "Id": "5243", "ParentId": "5241", "Score": "1" } }, { "body": "<p>It can be as simple as:</p>\n\n<pre><code>scala&gt; val str = \"I like racecars that go fast\"\nstr: java.lang.String = I like racecars that go fast\n\nscala&gt; for { i &lt;- 2 to str.size; s &lt;- str.sliding(i) if s == s.reverse} yield s\nres5: scala.collection.immutable.IndexedSeq[String] = Vector(cec, aceca, racecar)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T22:38:49.987", "Id": "7915", "Score": "1", "body": "Oh, and by the way: `.maxBy(_.size)` will give you the longest of those..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-06T14:28:11.697", "Id": "351484", "Score": "0", "body": "Can you please explain why the `for` loop starts from 2, not from 0. I tried in REPL but got the error of \n`java.lang.IllegalArgumentException: requirement failed: size=0 and step=1, but both must be positive`\n\nAnd If I start the `for` loop from 1. It gives the result ` Vector(b, a, n, a, n, a, s, ana, nan, ana, anana)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-01-06T15:46:26.167", "Id": "351501", "Score": "1", "body": "We loop through possible sizes of palindromic sub-expressions. Two is arguably the smallest size that makes sense. When you tried with one, it gave you back single letters. Can you really say that those are palindromes? And as for why zero gives you an error: what should `str.sliding(0)` give you back? Iterating through groups of zero items doesn't make sense, hence the illegal argument exception." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T22:32:19.950", "Id": "5245", "ParentId": "5241", "Score": "12" } }, { "body": "<p>The solutions given are simple but have quadratic complexity. I tried to improve upon it, while keeping it strictly functional.</p>\n\n<p>The solution I came up with is huge, though some of that resulted from breaking it up into smaller pieces for readability. While it is much faster, I'm not sure if that's due to an improved complexity, or just better heuristics detecting when no more palindromes are possible.</p>\n\n<p>I feel like it could be improved, perhaps with some Scalaz tricks. I see a couple places where I could remove some code by using an Scalaz abstraction, but not enough to be worth. On the other hand, I'm not particularly familiar with Scalaz.</p>\n\n<p>So, here it is:</p>\n\n<pre><code>def palindromes(input: String): Set[String] = { \n type PalPointers = (Set[Int], Set[Int]) \n type Candidates = Map[String, PalPointers] \n\n def increment = (_: Int) + 1 \n def decrement = (_: Int) - 1 \n def withinBounds = input.indices contains (_: Int) \n def filterPositions(forwardSet: Set[Int], reverseSet: Set[Int]): PalPointers = { \n val hasReverse = (forward: Int) =&gt; reverseSet exists (forward &lt;=) \n val hasForward = (reverse: Int) =&gt; forwardSet exists (reverse &gt;=) \n (forwardSet filter hasReverse, reverseSet filter hasForward) \n } \n def hasViablePositions = (_: PalPointers) match { \n case (forwardSet, reverseSet) =&gt; forwardSet.nonEmpty &amp;&amp; reverseSet.nonEmpty \n } \n\n def getSolutions(candidates: Candidates): Set[String] = { \n def getEven(candidate: String) = { \n val (forwardSet, reverseSet) = candidates(candidate) \n if ((forwardSet &amp; (reverseSet map decrement)).nonEmpty) Set(candidate + candidate.reverse) \n else Set.empty \n } \n\n def getOdd(candidate: String) = { \n val (forwardSet, reverseSet) = candidates(candidate) \n if ((forwardSet &amp; reverseSet).nonEmpty) Set(candidate + candidate.init.reverse) \n else Set.empty \n } \n\n for { \n candidate &lt;- candidates.keySet \n palindrome &lt;- getEven(candidate) ++ getOdd(candidate) \n } yield palindrome \n } \n\n def findPal(currentSolution: Set[String], currentCandidates: Candidates) : Set[String] = { \n val newCandidates = for { \n (candidate, (leftToRightSet, rightToLeftSet)) &lt;- currentCandidates \n nextCh &lt;- leftToRightSet map increment filter withinBounds map input \n isNextCh = (i: Int) =&gt; withinBounds(i) &amp;&amp; input(i) == nextCh \n forwardSetCandidate = leftToRightSet map increment filter isNextCh \n reverseSetCandidate = rightToLeftSet map decrement filter isNextCh \n palPointers = filterPositions(forwardSetCandidate, reverseSetCandidate) \n if hasViablePositions(palPointers) \n } yield (candidate + nextCh, palPointers) \n\n if (newCandidates.isEmpty) currentSolution \n else findPal(currentSolution ++ getSolutions(newCandidates), newCandidates) \n } \n\n def setup(charPointers: List[(Char, Int)], candidates: Candidates): Candidates = charPointers match { \n case (ch, pos) :: tail =&gt; \n val candidate = ch.toString \n val (forwardSet, reverseSet) = (candidates getOrElse (candidate, (Set.empty, Set.empty): PalPointers)) \n setup(tail, candidates.updated(candidate, (forwardSet + pos, reverseSet + pos))) \n case Nil =&gt; \n candidates map { \n case (key, (forwardSet, reverseSet)) =&gt; key -&gt; filterPositions(forwardSet, reverseSet) \n } filter { \n case (_, positions) =&gt; hasViablePositions(positions) \n } \n } \n\n val initialCandidates = setup(input.zipWithIndex.toList, Map.empty) \n val initialSolutions = getSolutions(initialCandidates) \n findPal(initialSolutions filter (_.length &gt; 1), initialCandidates) \n}\n</code></pre>\n\n<p>I wanted to know how efficient all that set manipulation really was, so I benchmarked it all. My solution is two order of magnitude faster than the one in the question, and three than the accepted solution for the greplin input. Since the big-Oh is different, this would change depending on characteristics of the input and input size.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T23:23:26.720", "Id": "5260", "ParentId": "5241", "Score": "1" } }, { "body": "<p>Improvement on @Zwirb's answer:</p>\n\n<p>If you are only seeking for palindrome of maximum length, it's better to try longest slides first. Laziness (triggered by <code>view</code>) will decrease complexity as well.</p>\n\n<pre><code>(for { i &lt;- (str.size to 2 by -1).view ; s &lt;- str.sliding(i) if s == s.reverse} yield s) headOption\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-16T20:36:50.653", "Id": "6106", "ParentId": "5241", "Score": "3" } }, { "body": "<p>Since we've got a working implementation, we may now optimise it. Each steps will be shown, to mimic a code review session (albeit a schizophrenic one).</p>\n\n<h3>Phase 1 : Limit objects creation.</h3>\n\n<p><code>reverse</code> creates new string. But reversing a view only creates a new (lightweight) view.\nIndeed, replacing <code>str.sliding</code> by <code>str.view.sliding</code> halve process time. For 6 keystrokes, it's not too bad.</p>\n\n<h3>Phase 2 : Refine the algorithm.</h3>\n\n<p>Actually it should be phase 0, but you never know when ideas pop up.<br>\nEach palindrome contains matryoshka-nested palindromes.\nThis means all <code>n</code> sized ones can be detected from <code>n-2</code> sized, just by checking 2 new chars at boundaries.</p>\n\n<p>We introduce an helper</p>\n\n<pre><code>def collectPalindrome(str: String, from: Int, to: Int): List[String] =\n if (str(from) == str(to)) {\n str.slice(from, to+1) :: (if (from &gt; 0 &amp;&amp; to &lt; str.size - 1) collectPalindrome(str, from-1, to+1) else Nil)\n} else Nil\n</code></pre>\n\n<p>No superfluous object creation is involved. So it's a double win !\nSince collected sizes increase by 2, we need 2 passes : </p>\n\n<pre><code>def extractPalindromes (str: String) : List[String] =\n{\n val evenSized: List[String] = ((for (i &lt;- (0 to str.size - 2)) yield collectPalindrome(str,i,i+1)) flatten).toList\n val oddSized: List[String] = ((for (i &lt;- (0 to str.size - 3)) yield collectPalindrome(str,i,i+2)) flatten).toList\n evenSized ++ oddSized\n}\n</code></pre>\n\n<p>Result for genlin input : </p>\n\n<pre><code>Reference (Zwirb) : 233 s\nStopping at longest : 232 s (nb : only extract 1 palindrome)\n So benchmarking proves my claim wrong. \nIdem + .view. : 120 s (nb : only extract 1 palindrome)\nNew algorithm : 0.006 s\n</code></pre>\n\n<h3>Phase 3 : Refactor.</h3>\n\n<p>So we've got a fast, memory friendly and still readable implementation.\nBut we can always improve.</p>\n\n<ul>\n<li>give the helper a more descriptive name : <code>collectIncreasingPalindromes</code></li>\n<li>move bound checking at top. The helper became robuster and more readable.</li>\n<li>hide this helper</li>\n<li>DRY</li>\n<li>document</li>\n<li>finally I prefer to map. Then map + flatten = flatMap</li>\n</ul>\n\n<p>Result :</p>\n\n<pre><code>def extractPalindromes (str: String): List[String] = {\n\n //@brief Collect nested palindromes increasing by 1 char at each end.\n def collectIncreasing(from: Int, until: Int): List[String] =\n if ( from &lt; 0 || until &gt; str.size //Out of bounds\n || str(from) != str(until-1) ) Nil\n else str.slice(from, until) :: collectIncreasing(from-1, until+1)\n\n //@brief Start to collect from given size, for each position\n def collect (n: Int) = (0 to str.size - n) flatMap \n (i =&gt; collectIncreasing (i, i+n))\n\n (collect (2) ++ collect (3)).toList // Even sized then odd sized palindromes\n}\n</code></pre>\n\n<h3>Phase 4 : Parallelize.</h3>\n\n<p>Thanks to functional approach, it should be just a matter of switching to parallel collections.</p>\n\n<h3>Phase 5 : Challenge a friend</h3>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-18T20:48:42.150", "Id": "6148", "ParentId": "5241", "Score": "2" } } ]
{ "AcceptedAnswerId": "5245", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T21:19:55.653", "Id": "5241", "Score": "7", "Tags": [ "scala", "palindrome" ], "Title": "More functional way of writing this palindrome extractor?" }
5241
<p>Basically, I made a simple app for my Android, where it picks a random question for you, and picks specific answers. Only 1 of the answers is correct, while other's aren't.</p> <p>Also, after editing the <code>QBegin</code> method, it started to give me questions but with wrong answers.</p> <pre><code>TextView question; private int qType = -1; private int asked = 0; private void QBegin() { // TODO Auto-generated method stub question = (TextView) findViewById(R.id.question); Random random = new Random(); int qType = random.nextInt(5); switch(qType){ case 0: question.setText("Question 1"); break; case 1: question.setText("Q2"); break; case 2: question.setText("Q3"); break; case 3: question.setText("Q4"); break; case 4: question.setText("Q5"); break; } asked++; //intList.add(qType); getAnswers(qType); /*if(intList.contains(qType) &amp;&amp; asked &lt;= 5){ QBegin(); } else { answerCounter.setText("Congratulations!!! Your score : "+correct); }*/ } private int answer; private void getAnswers(int Type) { Random random = new Random(); // TODO Auto-generated method stub switch(Type){ case 1: if(random.nextInt(4) == 0){ answer = 1; answer1.setText("относительно низкая температура шлаков"); answer2.setText("сложность в управлении"); answer3.setText("малая производительность"); answer4.setText("нету выделения энергии непосредственно в загрузке"); } else if (random.nextInt(4) == 1){ answer = 2; answer1.setText("сложность в управлении"); answer2.setText("относительно низкая температура шлаков"); answer3.setText("малая производительность"); answer4.setText("нету выделения энергии непосредственно в загрузке"); } else if (random.nextInt(4) == 2){ answer = 3; answer1.setText("сложность в управлении"); answer2.setText("малая производительность"); answer3.setText("относительно низкая температура шлаков"); answer4.setText("нету выделения энергии непосредственно в загрузке"); } else if (random.nextInt(4) == 3){ answer = 4; answer1.setText("сложность в управлении"); answer2.setText("малая производительность"); answer3.setText("нету выделения энергии непосредственно в загрузке"); answer4.setText("относительно низкая температура шлаков"); } break; case 2: if(random.nextInt(4) == 0){ answer = 1; answer1.setText("закрытые - плавка под слоем шихты"); answer2.setText("открытые - плавка на воздухе"); answer3.setText("вакуумные - плавка в вакууме"); answer4.setText("компрессорные - плавка под избыточным давлением"); } else if (random.nextInt(4) == 1){ answer = 2; answer1.setText("открытые - плавка на воздухе"); answer2.setText("закрытые - плавка под слоем шихты"); answer3.setText("вакуумные - плавка в вакууме"); answer4.setText("компрессорные - плавка под избыточным давлением"); } else if (random.nextInt(4) == 2){ answer = 3; answer1.setText("открытые - плавка на воздухе"); answer2.setText("вакуумные - плавка в вакууме"); answer3.setText("закрытые - плавка под слоем шихты"); answer4.setText("компрессорные - плавка под избыточным давлением"); } else if (random.nextInt(4) == 3){ answer = 4; answer1.setText("открытые - плавка на воздухе"); answer2.setText("вакуумные - плавка в вакууме"); answer3.setText("компрессорные - плавка под избыточным давлением"); answer4.setText("закрытые - плавка под слоем шихты"); } break; case 3: if(random.nextInt(4) == 0){ answer = 1; answer1.setText("в которой тепло выделяется в результате прохождения тока через проводники с активным сопротивлением"); answer2.setText("в которой используеться активное сопротивление в качестве шихты"); answer3.setText("в которой тепло не передаеться тепло излучением"); answer4.setText("в которой которая делиться на компрессорную печь с активным сопротивлением"); } else if (random.nextInt(4) == 1){ answer = 2; answer1.setText("в которой используеться активное сопротивление в качестве шихты"); answer2.setText("в которой тепло выделяется в результате прохождения тока через проводники с активным сопротивлением"); answer3.setText("в которой используеться активное сопротивление в качестве шихты"); answer4.setText("в которой которая делиться на компрессорную печь с активным сопротивлением"); } else if (random.nextInt(4) == 2){ answer = 3; answer1.setText("в которой используеться активное сопротивление в качестве шихты"); answer2.setText("в которой используеться активное сопротивление в качестве шихты"); answer3.setText("в которой тепло выделяется в результате прохождения тока через проводники с активным сопротивлением"); answer4.setText("в которой которая делиться на компрессорную печь с активным сопротивлением"); } else if (random.nextInt(4) == 3){ answer = 4; answer1.setText("в которой используеться активное сопротивление в качестве шихты"); answer2.setText("в которой используеться активное сопротивление в качестве шихты"); answer3.setText("в которой которая делиться на компрессорную печь с активным сопротивлением"); answer4.setText("в которой тепло выделяется в результате прохождения тока через проводники с активным сопротивлением"); } break; case 4: if(random.nextInt(4) == 0){ answer = 1; answer1.setText("Correct"); answer2.setText("Incorrect"); answer3.setText("Incorrect"); answer4.setText("Incorrect"); } else if (random.nextInt(4) == 1){ answer = 2; answer1.setText("Inorrect"); answer2.setText("Correct"); answer3.setText("Incorrect"); answer4.setText("Incorrect"); } else if (random.nextInt(4) == 2){ answer = 3; answer1.setText("Inorrect"); answer2.setText("Incorrect"); answer3.setText("Correct"); answer4.setText("Incorrect"); } else if (random.nextInt(4) == 3){ answer = 4; answer1.setText("Inorrect"); answer2.setText("Incorrect"); answer3.setText("Incorrect"); answer4.setText("Correct"); } break; case 5: if(random.nextInt(4) == 0){ answer = 1; answer1.setText("Correct"); answer2.setText("Incorrect"); answer3.setText("Incorrect"); answer4.setText("Incorrect"); } else if (random.nextInt(4) == 1){ answer = 2; answer1.setText("Inorrect"); answer2.setText("Correct"); answer3.setText("Incorrect"); answer4.setText("Incorrect"); } else if (random.nextInt(4) == 2){ answer = 3; answer1.setText("Inorrect"); answer2.setText("Incorrect"); answer3.setText("Correct"); answer4.setText("Incorrect"); } else if (random.nextInt(4) == 3){ answer = 4; answer1.setText("Inorrect"); answer2.setText("Incorrect"); answer3.setText("Incorrect"); answer4.setText("Correct"); } break; } } </code></pre>
[]
[ { "body": "<p>The (or at least \"One\") obvious approach would be to move most of your data into arrays, and just use the numbers to select values from those arrays. For example:</p>\n\n<pre><code>private void QBegin() {\n question = (TextView) findViewById(R.id.question);\n String[] types = { \"Question 1\", \"Q2\", \"Q3\", \"Q4\", \"Q5\"};\n Random random = new Random();\n int qType = random.nextInt(types.length);\n\n question.setText(types[qType]);\n asked++;\n getAnswers(qType);\n}\n</code></pre>\n\n<p>Most of <code>getAnswers</code> should end up similar, although I'm afraid I'm lack the ambition to type it all in.</p>\n\n<p>Personally, however, I think I'd move the text of the questions and answers out to a text file (or a database) and write the code as a more or less generic \"engine\" that read and present the questions and answers from the file.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T07:30:58.490", "Id": "7953", "Score": "1", "body": "Good solution, but never use magic numbers, e.g. `random.nextInt(types.length);` is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T14:12:46.393", "Id": "7963", "Score": "0", "body": "@Landei: Good point. Edited." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T22:30:22.970", "Id": "5244", "ParentId": "5242", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T21:39:21.413", "Id": "5242", "Score": "7", "Tags": [ "java", "android", "random" ], "Title": "Random Q&A system" }
5242
<pre><code>def range_find(pageset): pagerangelist=[] for page in list(pageset): if page in pageset and page-1 in pageset:pagerangelist[-1].append(page) elif page in pageset and not (page-1 in pageset):pagerangelist.append([page]) pagerangestringlist=[] for pagerange in pagerangelist: if len(pagerange)==1:pagerangestringlist.append(str(pagerange[0])) else: pagerangestringlist.append(str(pagerange[0])+'-'+str(pagerange[-1])) return ','.join(pagerangestringlist) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T00:20:51.897", "Id": "7918", "Score": "0", "body": "why so many versions? and why haven't you learned to format your posts correctly yet?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T01:10:26.143", "Id": "7919", "Score": "0", "body": "1)I do not understand the point about formatting...I simply cut and paste into the text field. What am I supposed to do? Or is it a question of the title. 2) I created different versions in response to feedback. If I edit the original post, then it would make it hard to understand the original comments. Or am I missing something about the way this web site works?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T02:00:53.790", "Id": "7920", "Score": "1", "body": "The textfield isn't a code box, its a general formatting box. You need to specifically tell it that you have put code in your post by using the toolbar button it gives you. Most people who post here edit their posts if they have new versions." } ]
[ { "body": "<pre><code>def range_find(pageset):\n\n pagerangelist=[]\n\n for page in list(pageset):\n</code></pre>\n\n<p>There is no point in listifying the set just to iterate over it. I think you meant <code>for page in sorted(pageset)</code> to get access to the page in sorted order.</p>\n\n<pre><code> if page in pageset and page-1 in pageset:pagerangelist[-1].append(page)\n elif page in pageset and not (page-1 in pageset):pagerangelist.append([page])\n</code></pre>\n\n<p>You still make it hard to read by putting those on the same line. </p>\n\n<pre><code> pagerangestringlist=[]\n</code></pre>\n\n<p>If you've got multiple words I suggest under scores. I also suggest dropping types like list/set from your names. I'd call this <code>page_range_strings</code>.</p>\n\n<pre><code> for pagerange in pagerangelist:\n\n if len(pagerange)==1:pagerangestringlist.append(str(pagerange[0]))\n else: pagerangestringlist.append(str(pagerange[0])+'-'+str(pagerange[-1])) \n</code></pre>\n\n<p>I'm going to recommend using string formating. It'll be easier to read then concatenating strings.</p>\n\n<pre><code> return ','.join(pagerangestringlist)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T00:25:14.977", "Id": "5249", "ParentId": "5247", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T23:01:16.693", "Id": "5247", "Score": "1", "Tags": [ "python" ], "Title": "Grouping consecutive numbers into ranges in Python 3.2; third version (accepts page numbers as an unsorted set)" }
5247
<p>I deal with hundreds and hundreds of names each week. These names (along with other pedigree information) are stored in a database. Typically, I get these names in all sorts of formats, mainly proper and in all-caps. I needed an easy way to convert the names (especially last names) to their proper format:</p> <ul> <li>McDonald</li> <li>MacDougal</li> <li>Smith-Jones</li> <li>Davis II</li> <li>George IV</li> </ul> <p>The following code properly formats the above examples as well as standard names. Please take a look at my code and suggest areas where I might make it more efficient. I got the idea for this method mainly from <a href="https://stackoverflow.com/questions/2746009/how-can-this-method-to-convert-a-name-to-proper-case-be-improved">this link</a>.</p> <pre><code>public string ConvertToProperNameCase(string input) { bool SuffixProcessed = false; input = input.Trim(); if (String.IsNullOrEmpty(input)) { return String.Empty; } char[] chars = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()).ToCharArray(); for (int i = 0; i + 1 &lt; chars.Length; i++) { if ((chars[i].Equals('\'')) || (chars[i].Equals('-'))) { chars[i + 1] = Char.ToUpper(chars[i + 1]); } } string s = new string(chars); if (((s.ToUpper().StartsWith("MAC") || s.ToUpper().StartsWith("MCC") || s.ToUpper().StartsWith("DE ")) &amp;&amp; s.Length &gt; 4)) { try { s = s.Substring(0, 1).ToUpper() + s.Substring(1, 2).ToLower() + s.Substring(3, 1).ToUpper() + s.Substring(4).ToLower(); } catch { s = s; } } if ((s.ToUpper().StartsWith("MC")) &amp;&amp; s.Length &gt; 3) { try { s = s.Substring(0, 1).ToUpper() + s.Substring(1, 1).ToLower() + s.Substring(2, 1).ToUpper() + s.Substring(3).ToLower(); } catch { s = s; } } if (s.ToUpper().Contains(" III") &amp;&amp; !SuffixProcessed) { try { s = s.Substring(0, s.ToUpper().IndexOf(" III")) + " " + s.Substring(s.ToUpper().IndexOf(" III"), 4).ToUpper(); SuffixProcessed = true; } catch { s = s; } } if (s.ToUpper().Contains(" II") &amp;&amp; !SuffixProcessed) { try { s = s.Substring(0, s.ToUpper().IndexOf(" II")) + " " + s.Substring(s.ToUpper().IndexOf(" II"), 3).ToUpper(); SuffixProcessed = true; } catch { s = s; } } if (s.ToUpper().Contains(" IV") &amp;&amp; !SuffixProcessed) { try { s = s.Substring(0, s.ToUpper().IndexOf(" IV")) + " " + s.Substring(s.ToUpper().IndexOf(" IV"), 3).ToUpper(); SuffixProcessed = true; } catch { s = s; } } return s; } </code></pre> <p>After carefully digesting Winston Ewert's post, here is what I can up with. This code will now handle the following examples:</p> <ul> <li>MACDonald-jOnes</li> <li>FRAnK iV</li> <li>MCCarthy xiv</li> <li>mcTavish-tOMaS jr</li> <li>Robert-ROBERTSON SR</li> </ul> <p><strong>Revised code</strong></p> <pre><code>using System; using System.Windows.Forms; namespace WindowsFormsApplication5 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string[] Names = new string[]{ "MACDonald-jOnes, FRAnK iV", "MCCarthy xiv", " ", "mcTavish-tOMaS jr", "Robert-ROBERTSON SR."}; foreach (string s in Names) Console.WriteLine(string.Format("Original Name: {0}\n Converted Name: {1}", s, ConvertToProperNameCase(s))); } public string ConvertToProperNameCase(string s) { string ReturnValue = string.Empty; if (s.Trim().Length &gt; 0) { try { s = s.ToLower(); bool[] Name = new bool[s.Length]; for (int i = Name.Length; i &lt; Name.Length; i++) { Name[i] = false; } for (int i = 0; i &lt; s.Length; i++) { if (i == 0) { Name[i] = true; } if (s[i].Equals('\'') || s[i].Equals('-') || s[i].Equals(' ')) { Name[i + 1] = true; } } string[] Prefixes = new string[] { "MAC", "MC" }; bool[] b = new bool[1] { true }; foreach (string p in Prefixes) { if (s.ToUpper().Trim().StartsWith(p)) { switch (p.Length) { case 2: b = new bool[] { true, false, true }; break; case 3: b = new bool[] { true, false, false, true }; break; } break; } } for (int i = 0; i &lt; b.Length; i++) { Name[i] = b[i]; } string[] Suffixes = new string[] { "XXIIII", "IIIII", "VIIII", "XVIII", "XXIII", "IIII", "VIII", "XIII", "XVII", "XXII", "XXIV", "III", "VII", "IIX", "XII", "XIV", "XVI", "XIX", "XXV", "XXI", "II", "IV", "VI", "IX", "XI", "XV", "XX", "I", "V", "X" }; foreach (string suf in Suffixes) { if (s.ToUpper().Trim().EndsWith(suf) &amp;&amp; (s.Length &gt; (suf.Length + 1))) { for (int i = s.Length - 1; i &gt; (s.Length - (suf.Length + 1)); i--) { Name[i] = true; } break; } } for (int i = 0; i &lt; s.Length; i++) { if (Name[i] == true) { ReturnValue += s.Substring(i, 1).ToUpper(); } else { ReturnValue += s.Substring(i, 1); } } return ReturnValue; } catch(Exception ex) { MessageBox.Show(ex.Message); return ReturnValue = "Error"; } } else { return ReturnValue = "Empty String"; } } } } </code></pre>
[]
[ { "body": "<pre><code>public string ConvertToProperNameCase(string input)\n{\n bool SuffixProcessed = false;\n</code></pre>\n\n<p>You don't use this variable for a long time, move it closer to where it is used.</p>\n\n<pre><code> input = input.Trim();\n\n if (String.IsNullOrEmpty(input))\n {\n return String.Empty;\n }\n\n char[] chars = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()).ToCharArray();\n</code></pre>\n\n<p>Rather then Title casing now, why don't you make everything lowercase here, selectively uppercase pieces and then have the whole thing TitleCased? That you can assume everything is lowercase throughout this function which will simplify the code.</p>\n\n<pre><code> for (int i = 0; i + 1 &lt; chars.Length; i++)\n {\n if ((chars[i].Equals('\\'')) ||\n (chars[i].Equals('-')))\n {\n chars[i + 1] = Char.ToUpper(chars[i + 1]);\n }\n }\n\n\n string s = new string(chars);\n</code></pre>\n\n<p>Why don't you create an array of bools, the same length as your string. Initially have all values set to false. Set those values to true which should be uppercased. Apply the uppercasing as the last part of the function.</p>\n\n<pre><code> if (((s.ToUpper().StartsWith(\"MAC\") || s.ToUpper().StartsWith(\"MCC\") || s.ToUpper().StartsWith(\"DE \")) &amp;&amp; s.Length &gt; 4))\n {\n try\n {\n s = s.Substring(0, 1).ToUpper() + s.Substring(1, 2).ToLower() + s.Substring(3, 1).ToUpper() + s.Substring(4).ToLower();\n</code></pre>\n\n<p>It would be a lot simpler just to set a flag in the should_uppercase array to true.</p>\n\n<pre><code> }\n catch\n</code></pre>\n\n<p>Don't just catch any error. Catch the specific type of error that will be thrown. Otherwise you might catch something you didn't mean to.</p>\n\n<pre><code> {\n s = s;\n</code></pre>\n\n<p>This statement does nothing.</p>\n\n<pre><code> }\n }\n\n if ((s.ToUpper().StartsWith(\"MC\")) &amp;&amp; s.Length &gt; 3)\n {\n try\n {\n s = s.Substring(0, 1).ToUpper() + s.Substring(1, 1).ToLower() + s.Substring(2, 1).ToUpper() + s.Substring(3).ToLower();\n }\n catch\n {\n s = s;\n }\n }\n</code></pre>\n\n<p>You've done essentially the same thing twice. You should put all of these \"mac, mc, de, mcc\" in a constant array and then loop over it do to that logic.</p>\n\n<pre><code> if (s.ToUpper().Contains(\" III\") &amp;&amp; !SuffixProcessed)\n</code></pre>\n\n<p>What if \" III\" appears somewhere that isn't the end? Do you still want to do this?</p>\n\n<pre><code> {\n try\n {\n s = s.Substring(0, s.ToUpper().IndexOf(\" III\")) + \" \" + s.Substring(s.ToUpper().IndexOf(\" III\"), 4).ToUpper();\n SuffixProcessed = true;\n }\n catch\n</code></pre>\n\n<p>Can this actually happen? If you don't think its going to happen don't catch it as an exception and ignore it. That'll just mask bugs.</p>\n\n<pre><code> {\n s = s;\n }\n\n }\n\n if (s.ToUpper().Contains(\" II\") &amp;&amp; !SuffixProcessed)\n {\n try\n {\n s = s.Substring(0, s.ToUpper().IndexOf(\" II\")) + \" \" + s.Substring(s.ToUpper().IndexOf(\" II\"), 3).ToUpper();\n SuffixProcessed = true;\n }\n catch\n {\n s = s;\n }\n }\n\n if (s.ToUpper().Contains(\" IV\") &amp;&amp; !SuffixProcessed)\n {\n try\n {\n s = s.Substring(0, s.ToUpper().IndexOf(\" IV\")) + \" \" + s.Substring(s.ToUpper().IndexOf(\" IV\"), 3).ToUpper();\n SuffixProcessed = true;\n }\n catch\n {\n s = s;\n }\n }\n</code></pre>\n\n<p>You should at least put these roman numerals in an array so you don't have to duplicate your logic. But what if Louis XIV decides to to use your system? You might want to consider something like checking whether the last word in the name consists only of X,I,V, or something.</p>\n\n<pre><code> return s;\n}\n</code></pre>\n\n<p><strong>Round 2</strong></p>\n\n<pre><code> public string ConvertToProperNameCase(string s)\n {\n string ReturnValue = string.Empty;\n</code></pre>\n\n<p>You don't use ReturnValue until way later (aside from a couple places where you shouldn't be using it) so move it where you actually need it.</p>\n\n<pre><code> if (s.Trim().Length &gt; 0)\n</code></pre>\n\n<p>You end up repeatedly trimming s. Can you just trim it once and be done with it? Do you need to preserve whitespace on either end? </p>\n\n<pre><code> {\n try\n {\n s = s.ToLower();\n\n bool[] Name = new bool[s.Length];\n for (int i = Name.Length; i &lt; Name.Length; i++)\n {\n Name[i] = false;\n }\n</code></pre>\n\n<p>Name may not be the best choice, because the variable doesn't indicate that it is keeping track of cases.</p>\n\n<pre><code> for (int i = 0; i &lt; s.Length; i++)\n {\n if (i == 0)\n {\n Name[i] = true;\n }\n</code></pre>\n\n<p>Just set <code>Name[0] = true;</code> before entering this loop. </p>\n\n<pre><code> if (s[i].Equals('\\'') || s[i].Equals('-') || s[i].Equals(' '))\n {\n Name[i + 1] = true;\n }\n }\n\n string[] Prefixes = new string[] { \"MAC\", \"MC\" };\n bool[] b = new bool[1] { true };\n\n foreach (string p in Prefixes)\n {\n if (s.ToUpper().Trim().StartsWith(p))\n</code></pre>\n\n<p>Your string is lowercased. Change your prefixes so they are lowercase and you won't need to uppercase anything.</p>\n\n<pre><code> {\n switch (p.Length)\n {\n case 2:\n b = new bool[] { true, false, true };\n break;\n case 3:\n b = new bool[] { true, false, false, true };\n break;\n }\n</code></pre>\n\n<p>You should be able to do this without switching on the length. i.e. you should be able to write code that works for anything length. </p>\n\n<pre><code> break;\n }\n }\n\n for (int i = 0; i &lt; b.Length; i++)\n {\n Name[i] = b[i];\n }\n</code></pre>\n\n<p>Rather then writing into another boolean array, write directly into Name[]. In particular if you find a prefix you should set Name[prefix.length] = true; Name[0] will already be true.</p>\n\n<pre><code> string[] Suffixes = new string[] { \"XXIIII\", \"IIIII\", \"VIIII\", \"XVIII\", \"XXIII\", \"IIII\", \"VIII\", \"XIII\", \"XVII\", \"XXII\", \n \"XXIV\", \"III\", \"VII\", \"IIX\", \"XII\", \"XIV\", \"XVI\", \"XIX\", \"XXV\", \"XXI\", \"II\", \"IV\", \"VI\", \n \"IX\", \"XI\", \"XV\", \"XX\", \"I\", \"V\", \"X\" };\n</code></pre>\n\n<p>I don't see any particular pattern to the order here. How can you be sure you haven't missed some? If you put them in numerical order it will be more obvious. I also suggest moving the array outside of the function. I still think it would be cleaner to find the last word and figure out whether it looks like a roman numeral. </p>\n\n<pre><code> foreach (string suf in Suffixes)\n {\n if (s.ToUpper().Trim().EndsWith(suf) &amp;&amp; (s.Length &gt; (suf.Length + 1)))\n</code></pre>\n\n<p>No need for the parents around <code>suf.Length+ 1</code></p>\n\n<pre><code> {\n for (int i = s.Length - 1; i &gt; (s.Length - (suf.Length + 1)); i--)\n</code></pre>\n\n<p>This may be better if you counted forwards rather then backwards. </p>\n\n<pre><code> {\n Name[i] = true;\n }\n\n break;\n }\n }\n\n for (int i = 0; i &lt; s.Length; i++)\n {\n if (Name[i] == true)\n {\n ReturnValue += s.Substring(i, 1).ToUpper();\n }\n else\n {\n ReturnValue += s.Substring(i, 1);\n }\n\n }\n</code></pre>\n\n<p>It may be cleaner to convert to an array of chars, upper case elements in that array, and convert back to a string. Concatenating strings together will not be very good for performance. I think there should also be a specialized method for returning individual characters rather then fetching substrings of length 1.</p>\n\n<pre><code> return ReturnValue;\n }\n catch(Exception ex)\n {\n MessageBox.Show(ex.Message);\n return ReturnValue = \"Error\";\n</code></pre>\n\n<p>I recommend not including GUI related logic in a function like this. This function should worry about handling the name logic and let something else worry about handling UI display.</p>\n\n<pre><code> }\n }\n else\n {\n return ReturnValue = \"Empty String\";\n</code></pre>\n\n<p>Why are you assigning ReturnValue like that? There isn't any point since ReturnValue is a local variable that will be thrown away when the function ends. Just return the \"Empty String\"</p>\n\n<pre><code> }\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T00:41:10.363", "Id": "5250", "ParentId": "5248", "Score": "7" } }, { "body": "<p>Apart from Winstons excellent suggestions I would further seperate the checks and parsing into seperate methods. Maybe even class. Excuse any typos as I had to do this in notepad but hopefully the basic idea is below.</p>\n\n<pre><code>public string ConvertToProperNameCase(string input)\n{\n input = input.Trim();\n\n if (String.IsNullOrEmpty(input))\n {\n return String.Empty;\n }\n\n char[] chars = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(input.ToLower()).ToCharArray();\n\n for (int i = 0; i + 1 &lt; chars.Length; i++)\n {\n if ((chars[i].Equals('\\'')) || (chars[i].Equals('-')))\n {\n chars[i + 1] = Char.ToUpper(chars[i + 1]);\n }\n }\n\n string s = new string(chars);\n\n const string[] prefixes = { \"MAC\", \" MCC\", \"DE \", \"MC\" });\n string s = ParseData(s, prefixes,HasPrefix, ParsePrefix);\n\n private const string[] suffixes = { \" II\", \" III\", \" IV\");\n return ParseData(s, suffixes ,HasSuffix, ParseSuffix);\n} \n\nprivate string ParseData(string input, string[] data, Func&lt;string, string, bool&gt; hasData, Func&lt;string, string, string&gt; getData) \n {\n\n foreach(string item in data)\n {\n if (hasData(input, prefix) \n {\n return getData(input, prefixes);\n }\n }\n\n return input;\n }\n\nprivate bool HasPrefix(string input, string prefix)\n{\n int length = prefix.length + 1;\n return (s.ToUpper().StartsWith(prefix)) &amp;&amp; input.Length &gt; length;\n}\n\nprivate string ParsePrefix(string input, string prefix)\n{\n int length = prefix.length;\n return input.Substring(0, 1).ToUpper() + input.Substring(1, length - 1).ToLower() + s.Substring(length, 1).ToUpper() + s.Substring(length + 1).ToLower(); \n}\n\nprivate string ParseSuffix(string input, string suffix)\n{\n int length = suffix.length;\n return s.Substring(0, input.ToUpper().IndexOf(suffix)) + \" \" + s.Substring(s.ToUpper().IndexOf(suffix), length).ToUpper();\n}\n\nprivate bool HasSuffix(string input, string suffix)\n{\nreturn input.ToUpper().Contains(suffix);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T01:01:09.443", "Id": "7947", "Score": "1", "body": "notepad? I feel for you..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-08T20:43:04.780", "Id": "5258", "ParentId": "5248", "Score": "4" } } ]
{ "AcceptedAnswerId": "5250", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T23:32:32.270", "Id": "5248", "Score": "5", "Tags": [ "c#" ], "Title": "Name proper casing" }
5248
<p>What would you do to improve upon this boilerplate empty stored procedure, being mindful of the delicate balance between length, complexity, performance and clarity?</p> <pre><code>-- ============================================= -- Author: The usual suspects -- Create date: 10/06/2011 -- Description: -- -- Nice long description about the procedure -- -- ============================================= CREATE PROCEDURE [dbo].[My_Stored_Proc] ( -- exampleParam is an example parameter. @exampleParam INT = 30 ) AS BEGIN -- main SET NOCOUNT ON BEGIN TRY DECLARE @crlf varchar(2) SET @crlf = CHAR(13) + CHAR(10) -- *** DO YOUR STUFF HERE *** END TRY BEGIN CATCH -- Error handler DECLARE @ErrorNumber INT DECLARE @ErrorSeverity INT DECLARE @ErrorState INT DECLARE @ErrorProcedure NVARCHAR(4000) DECLARE @ErrorLine INT DECLARE @ErrorMessage NVARCHAR(4000) DECLARE @ErrorDescription NVARCHAR(4000) -- retrieve error info SELECT @ErrorNumber = ERROR_NUMBER(), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE(), @ErrorProcedure = ERROR_PROCEDURE(), @ErrorLine = ERROR_LINE(), @ErrorMessage = ERROR_MESSAGE(); -- build custom error description SELECT @ErrorDescription = @crlf + @crlf + 'Base Error:\t[' + CAST(@ErrorNumber AS VARCHAR) + '] ' + @ErrorMessage + @crlf + @crlf + 'exampleParam:\t' + CAST(@exampleParam AS VARCHAR) + @crlf + 'Application:\t' + APP_NAME() + @crlf + 'User:\t' + SYSTEM_USER + @crlf + 'Database:\t' + DB_NAME() + @crlf + 'Procedure:\t' + @ErrorProcedure + @crlf + 'Line:\t' + CAST(@ErrorLine AS VARCHAR) + @crlf + 'Severity:\t' + CAST(@ErrorSeverity AS VARCHAR) + @crlf + 'State:\t' + CAST(@ErrorState AS VARCHAR); RAISERROR(@ErrorDescription, @ErrorSeverity, 1) RETURN @@ERROR END CATCH END -- main </code></pre> <p>For instance, is there a nice way to move that error handler out of the stored proc so the logic can be shared and not duplicated inside each procedure? Notice it can be nice to include the <em>values of the parameters</em> in that error message (<code>exampleParam</code> above).</p> <p>Do you agree or disagree with my stance on handling transaction rollbacks in stored procs? (lack thereof)</p> <p>Do you have or can you write an example of better <em>boilerplate</em> along with a description of where my approach falls short and why your version might be a better starting point</p> <p>What about <code>SET XACT_ABORT {ON | OFF}</code>? Which option for <code>XACT_ABORT</code> would be a best practice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T07:55:44.070", "Id": "7942", "Score": "3", "body": "I totally agree with the suggestion not to fiddle about with transaction logic in stored procedures. The main reason for this is that if you write a procedure to be agnostic about its calling routine then it becomes much simpler to reuse it. Generally I aim to have one exception handler at the top level - and usually in the work I do this turns out to be client-side code - and this top level routine is resposible for the commit/rollback. I would say your boilerplate is pretty good, but if you apply it to every sp and function you risk overkill." } ]
[ { "body": "<p>All in all it’s a good idea. Have you considered moving your <code>crlf</code> and <code>CATCH</code> logic; or a portion of it; to a reusable function? This would help ensure; wherever it’s used; that it remain consistent and you don’t have the same code all over the place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-19T08:28:51.050", "Id": "6979", "ParentId": "5256", "Score": "5" } } ]
{ "AcceptedAnswerId": "6979", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-07T07:19:56.580", "Id": "5256", "Score": "10", "Tags": [ "sql", "sql-server", "error-handling" ], "Title": "SQL Server stored procedure boilerplate" }
5256
<p>Please give me any comment about these codes. Does it enough to prevent SQL injection? What I have to do to make the code better?</p> <pre><code>&lt;?php /** * Description of MySql * @name MySQL PDO * @version 1.0 * @author Yauri * */ class MySql { private $mPDO; public function __construct($dbHost,$dbName,$dbUser,$dbPass) { try { $this-&gt;mPDO = new PDO("mysql:host=$dbHost;dbname=$dbName", "$dbUser", "$dbPass"); //$this-&gt;mPDO-&gt;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); $this-&gt;mPDO-&gt;setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); } catch(PDOException $e){ die($e-&gt;getMessage()); } } /** * Method for executing query * @param string $query * @data array Used on queryUpdate method * @return array Result of query */ public function query($query){ $exec = $this-&gt;mPDO-&gt;prepare($query); if($data) $exec-&gt;execute($data); else $exec-&gt;execute(); $result = $exec-&gt;fetchAll(); return $result; } /** * Method for selecting data * @param $table string * @param $column array * @return array Result of query */ public function querySelect($table, $column, $where=NULL, $limit=NULL){ if($column!="*"){ $column = $this-&gt;buildColumn($column); } if(isset($where)){ $condition = $this-&gt;BuildWhere($where); $query = "SELECT {$column} FROM {$table} {$condition}"; } else { $query = "SELECT {$column} FROM {$table}"; } if(isset($limit)){ $query .= " LIMIT {$limit}"; } $exec = $this-&gt;mPDO-&gt;prepare($query); if(isset($where)){ $exec-&gt;execute(array_values($where)); } else{ $exec-&gt;execute(); } return $exec-&gt;fetchAll(); } /** * Method for insert * @param string $tableName * @param array $data Specify array keys as database column name * @return boolean */ public function queryInsert($tableName, $data) { $dataString = $this-&gt;buildInsert($data); $query = "INSERT INTO {$tableName} {$dataString}"; $exec = $this-&gt;mPDO-&gt;prepare($query); if($exec-&gt;execute(array_values($data))){ return true; } else{ return false; } } /** * Method for update * @param string $tableName * @param array $data Specify array keys as database column name * @param array $where Specify array keys as database column name */ public function queryUpdate($tableName, $data, $where) { $update = $this-&gt;buildUpdate($data); $condition = $this-&gt;buildWhere($where); $query = "UPDATE ".$tableName." SET {$update} {$condition}"; $exec = $this-&gt;mPDO-&gt;prepare($query); $paramVal = array_merge(array_values($data),array_values($where)); $exec-&gt;execute($paramVal); if($exec-&gt;rowCount()){ return true; } else { return false; } } /** * Method for delete * @param string $tableName * @param array $where You must specify the key as column name */ public function queryDelete($tableName, $where) { $condition = $this-&gt;buildWhere($where); $query = "DELETE FROM {$tableName} {$condition}"; $exec = $this-&gt;mPDO-&gt;prepare($query); $paramVal = array_values($where); $exec-&gt;execute($paramVal); $count = $exec-&gt;rowCount(); if($exec-&gt;rowCount()){ return true; } else { return false; } } /** * Method for build a string for insert query * @param array $data You must specify the key as column name */ private function buildInsert($data) { $length = count($data); $column = " ("; $values = " VALUES ("; foreach($data as $key =&gt; $val) { if($length != 1){ $column .= $key.", "; $values .= "?, "; } else { $column .= $key; $values .= "?"; } $length--; } $column .= ")"; $values .= ")"; return $column.$values; } /** * Method for build a string for update query * @param array $data You must specify the key as column name */ private function buildUpdate($data){ $length = count($data); $updateData = ""; foreach($data as $key =&gt; $val){ if($length!=1) { $updateData .= $key." = ? , "; } else{ $updateData .= $key." = ?"; } $length--; } return $updateData; } /** * Method for build a string for selected column * @param array $column * @return string */ private function buildColumn($column){ $length = count($column); $selectedColumn = ""; foreach($column as $val){ if($length!=1) { $selectedColumn .= $val.", "; } else{ $selectedColumn .= $val; } $length--; } return $selectedColumn; } /** * Method for build a string for query which using condition * @param array $where You must specify the key as column name * @return string */ private function buildWhere($where) { $length = count($where); $condition = " WHERE "; foreach($where as $key =&gt; $val){ if($length!=1) { $condition .= $key." = ? AND "; } else { $condition .= $key." = ?"; } $length--; } return $condition; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T09:36:24.463", "Id": "7955", "Score": "0", "body": "Btw. a little description of what you expect from the code review would not hurt." } ]
[ { "body": "<ul>\n<li>Your <code>BuildInsert</code>-method is the only one which uses <code>mysql_real_escape_string</code>. Why? Why not just use parametrized queries like in your \"select\", \"update\" and \"delete\" cases?</li>\n<li>Your <code>query</code> method uses a variable <code>$data</code> which is not defined. Probably a missing parameter.</li>\n<li><pre><code>if($exec-&gt;execute()){\n return \"Insert into database succeed.\";\n}\nelse{\n return \"Insert into database failed.\";\n}\n</code></pre>\n\n<p>This is bad, don't return a string when a <code>bool</code> would suffice. What if you want to translate your application?</p></li>\n<li>Sometimes you use method names beginning with a lower case like <code>queryInsert</code> and in other cases you start with an upper case like <code>QueryUpdate</code>. Be consistent.</li>\n<li><code>$mQuery</code> - this could be replaced by a local variable. Except you want to extend your class so you can fetch the last query. Otherwise: ditch it.</li>\n<li><code>$mDbHost</code> - not used, ditch it.</li>\n</ul>\n\n<h2>Update</h2>\n\n<ul>\n<li><p>This:</p>\n\n<pre><code>if($exec-&gt;execute(array_values($data))){\n return true;\n}\nelse{\n return false;\n}\n</code></pre>\n\n<p>can be written as:</p>\n\n<pre><code>return $exec-&gt;execute(array_values($data));\n</code></pre></li>\n<li><p>There's also a special case for update and delete which might return a count of affected rows. I would solve it like that:</p>\n\n<pre><code>if($exec-&gt;execute($paramVal)){\n return $exec-&gt;rowCount();\n}\nelse {\n return false;\n}\n</code></pre>\n\n<p>That way you can check if the query failed by using the <code>!==</code> or <code>===</code>-operators e.g.:</p>\n\n<pre><code>$rowsDeleted = $yourpdo-&gt;queryDelete(\"posts\", array(\"PostID\" =&gt; 5));\n// $rowsDeleted might be 0 if the post with id \"5\" does not exist so \n// check with ===\nif($rowsDeleted === false) {\n echo \"There was an error\";\n} else {\n echo \"{$rowsDeleted} rows affected\";\n} \n</code></pre>\n\n<p>The wording for your documentation would be <code>returns the number of rows affected or FALSE on error</code>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T10:40:31.120", "Id": "7957", "Score": "0", "body": "Fixed. Please take a look :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T11:39:57.520", "Id": "7958", "Score": "0", "body": "@n00bi3: okay, i've added two minor points." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T12:17:47.163", "Id": "7959", "Score": "0", "body": "thanks for helping me to write a good code. I've wrote many codes but I'm aware it wasn't a good code. Now I learn to write the good one :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T12:19:43.773", "Id": "7960", "Score": "0", "body": "Oh yeah, how about the SQL injection? Does those codes good safe enough for common SQL injection technique? And what should I change to prevent more attacks?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T17:28:49.950", "Id": "7965", "Score": "0", "body": "@n00bi3: Well the field values are escaped by PDO. The field and table names aren't escaped yet - this should be fixed for good security." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T09:31:27.310", "Id": "5263", "ParentId": "5262", "Score": "2" } } ]
{ "AcceptedAnswerId": "5263", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T07:50:27.403", "Id": "5262", "Score": "2", "Tags": [ "php", "mysql", "pdo" ], "Title": "MySQL PDO class" }
5262
<p>The following function accepts a list of <code>Topic</code> entities, retrieved from a database using LINQ-to-Entities. Each Topic has an <code>Id</code>, <code>Title</code> and <code>ParentId</code>. </p> <p>I want to populate an ASP.NET TreeView control, and so the function is creating a hierarchy of the Topics based on their <code>ParentId</code>. If a Topic has no parent, its <code>ParentId</code> is <code>null</code> and I put it under the 'root'.</p> <pre><code>public TreeNode GenerateTopicsTree(List&lt;Topic&gt; topics) { var s = new Stack&lt;TreeNodeAndId&gt;(); var root = new TreeNode("Topics", "0"); s.Push(new TreeNodeAndId { Id = null, TreeNode = root }); while (s.Count &gt; 0) { var node = s.Peek(); var current = topics.FirstOrDefault(o =&gt; o.ParentId == node.Id); if (current == null) { s.Pop(); continue; } var child = new TreeNode(current.Title, current.Id.ToString()); node.TreeNode.ChildNodes.Add(child); s.Push(new TreeNodeAndId { Id = current.Id, TreeNode = child }); topics.Remove(current); } return root; } struct TreeNodeAndId { public TreeNode TreeNode; public int? Id; } </code></pre> <p>Any improvements?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-08T13:25:56.390", "Id": "119320", "Score": "0", "body": "Any final _solution_ with **full source code** sample application ? _IMHO, better samples for minimize learning curve are real applications with full source code and good patterns_" } ]
[ { "body": "<p>Just a word of advice, creating a mutable struct which is <em>always</em> a bad idea. It <em>must</em> be a class otherwise you're just leaving yourself open to problems and confusion.</p>\n\n<p>You could improve it much more if you don't restrict your methods to use lists of topics. You could then easily apply recursion here and write it in a more functional style with simpler logic.</p>\n\n<pre><code>static TreeNode GenerateTopicsTree(IEnumerable&lt;Topic&gt; topics)\n{\n // shouldn't the root value be null?\n var root = new TreeNode(\"Topics\", null);\n return GenerateTopicSubTree(root, topics);\n}\n\nstatic TreeNode GenerateTopicSubTree(TreeNode root, IEnumerable&lt;Topic&gt; topics)\n{\n // partition the topics to child and non-child topics\n var rootId = GetId(root);\n var childTopics = topics.ToLookup(topic =&gt; topic.ParentId == rootId);\n\n // create and add subtrees to the current node\n var childNodes = childTopics[true].Select(GenerateNode);\n foreach (var childNode in childNodes)\n {\n root.ChildNodes.Add(GenerateTopicSubTree(childNode, childTopics[false]));\n }\n return root;\n}\n\nstatic int? GetId(TreeNode node)\n{\n int id;\n if (Int32.TryParse(node.Value, out id))\n return id;\n return null;\n}\n\nstatic TreeNode GenerateNode(Topic topic)\n{\n return new TreeNode(topic.Title, Convert.ToString(topic.Id));\n}\n</code></pre>\n\n<p>Consider using data binding to create your tree instead. I don't know how it works with ASP.NET so I can't really give you tips on how to do it. But doing so should make this step unnecessary as the framework will generate the tree for you. You'll probably have to create a class to represent the topics organized in a hierarchy but you could use the above code to create that hierarchy.</p>\n\n<hr>\n\n<p>After thinking about this again, I think it would be better to just group them all at once in the beginning instead of partitioning at every step. Here's an alternate implementation:</p>\n\n<pre><code>static TreeNode GenerateTopicsTreeAlt(IEnumerable&lt;Topic&gt; topics)\n{\n var root = new TreeNode(\"Topics\", null);\n\n // group all children together now so we don't need to regroup them again later\n var childTopics = topics.ToLookup(topic =&gt; topic.ParentId);\n return GenerateTopicSubTreeAlt(root, childTopics);\n}\n\nstatic TreeNode GenerateTopicSubTreeAlt(TreeNode root, ILookup&lt;int?, Topic&gt; childTopics)\n{\n // create and add subtrees to the current node\n var rootId = GetId(root);\n var childNodes = childTopics[rootId].Select(GenerateNode);\n foreach (var childNode in childNodes)\n {\n root.ChildNodes.Add(GenerateTopicSubTreeAlt(childNode, childTopics));\n }\n return root;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T21:45:41.047", "Id": "7991", "Score": "0", "body": "Thank you very much for this. I don't know what a mutable struct is but I'll take your word for it! Out of interest, what was the problem with using a `List`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T21:53:27.360", "Id": "7992", "Score": "0", "body": "In your example, your mutable struct was the `TreeNodeAndId` type. It's mutable because you could change the values of the fields. It's bad because when you read a value type, you receive a copy of the value so changes to the copy will not be applied to the actual field. As for the list, it's better to program to an interface. That way you're not restricting yourself to use a list here, but you could instead use an array for example. `IList<>` could be appropriate too but in this case, it really isn't necessary to access items by index." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T21:58:38.987", "Id": "7993", "Score": "0", "body": "You're an absolute legend. I've never seen code like `childTopics[true].Select(GenerateNode)` before so I have learned a lot from your answer. Cheers! (By the way, I've just changed my code to yours and it compiles great.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T22:17:37.150", "Id": "7994", "Score": "0", "body": "Actually, there might be a smarter way to write this. It might be easier and more efficient to just group the topics up front and create the appropriate nodes. I'll update my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T22:28:17.280", "Id": "7996", "Score": "0", "body": "Okay, thanks. In my project I have some structs that just contain value types, is that okay? Or do I need to make all the fields readonly? Or convert to a class?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T22:30:35.830", "Id": "7997", "Score": "0", "body": "If you're just storing related values together, you definitely should make them readonly at the very least. If you need to be able to change their values, make it a class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T09:13:01.660", "Id": "8079", "Score": "0", "body": "Mutable structs are generally a bad idea but it's dangerous to say that it's *always* the case. There are times when mutable structs are appropriate, and a sensible guideline should never be taken as a gospel truth." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T20:51:20.737", "Id": "5293", "ParentId": "5265", "Score": "5" } } ]
{ "AcceptedAnswerId": "5293", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T13:32:17.443", "Id": "5265", "Score": "8", "Tags": [ "c#", ".net", "asp.net", "linq" ], "Title": "Creating a TreeNode hierarchy in C#" }
5265
<p>I wrote a Python method to convert an object and a subset of its attributes into a JSON string with a given field as the key.</p> <p>There's a lot of string concatenation, and I'm not too sure what the best way to do that in Python is.</p> <p>I'm also wondering if <code>attr.replace('"','\"')</code> is sufficient to sanitize input.</p> <pre><code>def to_json_with_key(nodes, key, fields, insertIndex=False): i=0 s="{" for node in nodes: s += '"%s":{' % getattr(node,key) attrs=[] for field in fields: attr = getattr(node,field) if not isinstance(attr,int) and not isinstance(attr,float) and not isinstance(attr,long): attrs.insert(0, '"%s":"%s"' % (field, attr.replace('"','\"') )) else: attrs.insert(0, '"%s":%s' % (field, attr )) if (insertIndex): s+='index:%d,' % i i=i+1 s+=','.join(attrs) + "}," s = s.rstrip(",") + "}" return s </code></pre> <p>Sample input:</p> <blockquote> <pre><code>to_json_with_key(myObj, "title", fields=["length","time_offset"], insertIndex=True) </code></pre> </blockquote> <p>Sample output:</p> <blockquote> <pre><code>{"Introduction_to_Lists":{index:0,"length":128,"time_offset":0, "Pass_by_Reference":{index:1,"length":84,"time_offset":128}} </code></pre> </blockquote>
[]
[ { "body": "<p>Firstly, python includes a json module. Use that rather then writing your own.</p>\n\n<p>However, just to give some comments on your style:</p>\n\n<pre><code>def to_json_with_key(nodes, key, fields, insertIndex=False):\n</code></pre>\n\n<p>python recommend words_with_underscores for parameter names</p>\n\n<pre><code> i=0\n</code></pre>\n\n<p>Rather then manually keeping a count use enumerate</p>\n\n<pre><code> s=\"{\"\n for node in nodes:\n s += '\"%s\":{' % getattr(node,key)\n</code></pre>\n\n<p>You don't check the value to make sure it is json-safe. Building strings by concatenation is not usually a good idea. Either build a list and join it or use StringIO</p>\n\n<pre><code> attrs=[]\n for field in fields:\n attr = getattr(node,field)\n if not isinstance(attr,int) and not isinstance(attr,float) and not isinstance(attr,long):\n</code></pre>\n\n<p>You can pass several types in a tuple to isinstance to check several types at once.</p>\n\n<pre><code> attrs.insert(0, '\"%s\":\"%s\"' % (field, attr.replace('\"','\\\"') ))\n</code></pre>\n\n<p>This won't be sufficient. For example, you could have a \\ at the end of a string. You also need to handle newlines, tabs, and other escaped characters.</p>\n\n<pre><code> else:\n attrs.insert(0, '\"%s\":%s' % (field, attr ))\n</code></pre>\n\n<p>Why insert rather then append?</p>\n\n<pre><code> if (insertIndex):\n</code></pre>\n\n<p>No need for parens</p>\n\n<pre><code> s+='index:%d,' % i\n i=i+1\n\n s+=','.join(attrs) + \"},\"\n s = s.rstrip(\",\") + \"}\"\n</code></pre>\n\n<p>It would be cleaner to join a list of items rather then stripping off stray commas. </p>\n\n<pre><code> return s\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T17:33:41.533", "Id": "5267", "ParentId": "5266", "Score": "7" } } ]
{ "AcceptedAnswerId": "5267", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T17:01:44.690", "Id": "5266", "Score": "2", "Tags": [ "python", "converting", "json" ], "Title": "Converting an object into a JSON string" }
5266
<p>I have this class hierarchy. I want to apply generics to it but don't know how to do. AddWikiTask, ScanTask and RescanTask are subclasses of AbstractWorkerTask. DictionaryScanner has 3 functions to check if all tasks finish. How to prevent duplicate code in 3 those functions?</p> <p>This is class hierarchy</p> <pre><code> public abstract class AbstractWorkerTask&lt;Params, Progress, Result&gt; extends AsyncTask&lt;Params, Progress, Result&gt; implements Workable { ...} class AddWikiTask extends AbstractWorkerTask&lt;String, Void, Pair&lt;Integer, Dictionary&gt;&gt; { ...} class ScanTask extends AbstractWorkerTask&lt;DictionaryBean, Void, Pair&lt;Integer, Dictionary&gt;&gt; { ...} class RescanTask extends AbstractWorkerTask&lt;DictionaryInformation, Void, Pair&lt;Integer, Dictionary&gt;&gt; { ...} </code></pre> <p>This is DictionaryScanner. </p> <pre><code>public final class DictionaryScanner { private final List&lt;RescanTask&gt; rescanTasks = new ArrayList&lt;RescanTask&gt;(); private final List&lt;ScanTask&gt; scanTasks = new ArrayList&lt;ScanTask&gt;(); private final List&lt;AddWikiTask&gt; wikiTasks = new ArrayList&lt;AddWikiTask&gt;(); public boolean didAllRescanTasksFinish() { for (final RescanTask task : rescanTasks) { if (task.isWorking()) { return false; } } return true; } public boolean didAllAddWikiTasksFinish() { for (final AddWikiTask task : wikiTasks) { if (task.isWorking()) { return false; } } return true; } public boolean didAllScanTasksFinish() { for (final ScanTask task : scanTasks) { if (task.isWorking()) { return false; } } return true; } } </code></pre> <p>Edit: And apply generic for this. It's too long. I really don't know how to refactor it.</p> <pre><code>private void setOnPreExecuteForAddWikiTask(final AddWikiTask task, final ProgressDialog progressDialog) { task.setOnPreExecuteListener(new OnPreExecuteListener() { @Override public void onPreExecute() { if (didAllAddWikiTasksFinish()) { progressDialog.show(); } } }); } private void setOnPreExecuteForRescanTask(final RescanTask task, final ProgressDialog progressDialog) { task.setOnPreExecuteListener(new OnPreExecuteListener() { @Override public void onPreExecute() { if (didAllRescanTasksFinish()) { progressDialog.show(); } } }); } private void setOnPreExecuteForScanTask(final ScanTask task) { task.setOnPreExecuteListener(new OnPreExecuteListener() { @Override public void onPreExecute() { if (didAllScanTasksFinish() &amp;&amp; progressBar != null) { progressBar.setVisibility(ProgressBar.VISIBLE); } } }); } </code></pre> <p>If the snippet is not elaborate enough, please let me know.</p>
[]
[ { "body": "<p>You can take the common code in the functions in <code>DictionaryScanner</code> out into a common method:</p>\n\n<pre><code> public boolean didAllRescanTasksFinish() {\n didAllXTasksFinish(rescanTasks);\n }\n\n private boolean didAllXTasksFinish(List&lt;AbstractWorkerTask&gt; tasks) {\n for (final AbstractWorkerTask task : tasks) {\n if (task.isWorking()) {\n return false;\n }\n }\n return true;\n }\n</code></pre>\n\n<p>Otherwise your second block of code is about as simple as you can get, because each listener has different content. If you try to remove the boilerplate you will find it gets much more difficult to understand.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T09:25:37.033", "Id": "5276", "ParentId": "5268", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-09T20:16:28.117", "Id": "5268", "Score": "1", "Tags": [ "java" ], "Title": "Use generic to prevent duplicate code in this case" }
5268
<p>I've written an algebraic notation to use for moves in a game and I'm currently writing code to parse the information from the notation. I'm doing this using regExes. This is coded in HaXe.</p> <p>For example, two functions in the parser would look like this:</p> <pre><code>public function getMoveType(gameText:String):String { var moveTypeRegEx:EReg = ~/MatchThis/; moveTypeRegEx.match(gameText); var moveType:String = moveTypeRegEx.matched(0); //this returns entire string that was matched. return moveType; } public function getPlayerName(gameText:String):String { var playerNameRegEx:EReg = ~/MatchThis/; playerNameRegEx.match(gameText); var playerName:String = playerNameRegEx.matched(0); return playerName; } </code></pre> <ol> <li>How could this be written better to make it more readable or more organized?</li> <li>Would it be better to have a class file GameRegExes, which contains all the regexes I need with getter functions to those regexes?</li> </ol> <p>Please let me know if I'm being too vague.</p>
[]
[ { "body": "<p>The use of regular expressions is an implementation detail.</p>\n\n<p>I think you should continue to structure your API as functions that take a higher level input, such as a game text, and destructure it into the end product that your API's clients want.</p>\n\n<p>That said, you can define a private helper that takes a regular expression and does the work of matching the text and extracting group 0. Then each of your public functions would delegate most of the work to that just providing it with the appropriate regular expression and maybe the index of the group to return.</p>\n\n<pre><code>private function gameTextExtractor(gameText:String, regex:EReg):String\n{\n regex.match(gameText);\n return regex.matched(0);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T03:47:12.693", "Id": "7968", "Score": "0", "body": "Awesome, very simple but helps a lot. Thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T01:43:51.383", "Id": "5271", "ParentId": "5270", "Score": "1" } } ]
{ "AcceptedAnswerId": "5271", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T00:37:57.723", "Id": "5270", "Score": "3", "Tags": [ "regex", "haxe" ], "Title": "Algebraic notation with RegEx" }
5270
<pre><code>#!/bin/bash # Used to add/remove printers from system (lp) # Copyright Fresh Computer Systems Pty Ltd. GREP_OPTIONS='--color=tty' export GREP_OPTIONS sanity() { # Are we root? if [ $EUID != '0' ]; then exitError "You must be root to run this script." 1 fi if [ ! -x /usr/sbin/lpadmin -a ! -x /sbin/lpadmin ]; then # debug #printf " @@@ ERROR: \'lpadmin\' was not found, or is not executable. Quitting.\n\n" exitError " @@@ ERROR: \'lpadmin\' was not found, or is not executable" 1 fi PPD="/usr/share/cups/model/postscript.ppd" PPDGZ="/usr/share/cups/model/postscript.ppd.gz" if [ -f $PPD ]; then POSTSCRIPT="$PPD" elif [ -f $PPDGZ ]; then POSTSCRIPT="$PPDGZ" else exitError " @@@ ERROR: No postscript file found. Please ensure there is a \"$PPD\" or a \"$PPDGZ\" file." 1 fi # ensure sbin is in path PATH=/usr/sbin:/sbin:${PATH} # /etc/hosts file HOSTS="/etc/hosts" if [ ! -w "$HOSTS" ]; then exitError "Hosts file \"$HOSTS\" is not writeable." 1 fi } exitError() { # Provide default exit code '1' if none provided if [ -n "$1" ]; then ERRMSG="$1" ERRCODE="${2-1}" else ERRMSG=" @@@ ERROR: Unspecified Error." ERRCODE="${1-1}" fi ERRMSG="$ERRMSG" printf "\n%s\n" "$ERRMSG" &gt;&amp;2 printf "%s\n\n" "Quitting." &gt;&amp;2 exit ${ERRCODE} } invalidInput() { declare USELESS printf "\nInvalid input.\n" &gt;&amp;2 read -p "Press Any Key To Continue..." USELESS #unset USELESS printf "\n" } ## ## FUNCTIONS ## enterPrinterName() { unset PRINTER_TYPE PRINTER_NAME IPADDRESS IPADDRESS_SED CONNECTION_TYPE REPLY RESULT PORTNAME NAME_EXISTS_IN_HOSTS ADDRESS_EXISTS_IN_HOSTS HOSTACTION RC printf "\n" while true; do read -p "Enter printer name, or [q]uit: " PRINTER_NAME case $PRINTER_NAME in [qQ]) exitError "Aborted by User" 0 ;; ??*) break ;; ""|*) invalidInput #blank line or anything else ;; esac done } checkPrinterExistsInSystem () { if lpstat -v $PRINTER_NAME 1&gt;/dev/null 2&gt;&amp;1; then # Printer already exists in the system #lpstat -v $PRINTER_NAME #printf "Printer already exists in system!\n" &gt;&amp;2 declare EXISTS=0 #true else declare EXISTS=1 #false fi printf "\n" NAME_EXISTS_IN_SYSTEM=$EXISTS return $EXISTS } checkNameExistsInHosts() { declare EXISTS=1 # scan each line from $HOSTS while read LINE; do # Remove comments LINE="${LINE%%#*}" case "$LINE" in *${PRINTER_NAME}*) # printer found EXISTS=0 break #stop looping ;; *) # printer not found : ;; esac done &lt; $HOSTS if [ $EXISTS -eq 0 ]; then printf "Printer \"$PRINTER_NAME\" already exists in \"$HOSTS\"!\n\n" &gt;&amp;2 egrep "^[^#]*$PRINTER_NAME[[:space:]]*" "${HOSTS}" fi printf "\n" NAME_EXISTS_IN_HOSTS=$EXISTS return $EXISTS } checkAddressExistsInHosts() { declare EXISTS=1 while read LINE; do # Remove comments LINE="${LINE%%#*}" case "$LINE" in *${IPADDRESS}*) # address exists in hosts EXISTS=0 #true break ;; *) # address does not exist : ;; esac done &lt; $HOSTS if [ $EXISTS -eq 0 ]; then # address exists, add alias #echo "............. HERE I AM 1 .............. " HOSTACTION=addAliasToHosts printf "IP address \"$IPADDRESS\" already exists in \"$HOSTS\"!\n\n" egrep "^[^#]*$IPADDRESS[[:space:]]*" "${HOSTS}" else # address is NEW, add as a new host #echo "............. HERE I AM 2 .............. " HOSTACTION=addHostToHosts fi ADDRESS_EXISTS_IN_HOSTS=$EXISTS printf "\n" return $EXISTS } getConnectionType() { while true; do # Connection type printf "\nCONNECTION TYPE: 1. LPD (print server) 2. 9100 (network printer)\n\n" read -p "Enter a number, or [q]uit: " REPLY case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; 1) CONNECTION_TYPE="LPD" break ;; 2) CONNECTION_TYPE=9100 break ;; ""|*) invalidInput ;; esac done printf "Connection type selected: \"$CONNECTION_TYPE\".\n\n" if [ "$CONNECTION_TYPE" = "LPD" ]; then # LPD connection requires a portname while true; do read -p "$CONNECTION_TYPE: give portname (e.g. p1), or [q]uit: " REPLY case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; [[:alnum:]]*) PORTNAME="$REPLY" #at least one alphanumeric char break ;; ""|*) invalidInput ;; esac done printf "OK: Portname selected: \"$PORTNAME\".\n\n" fi } getPrinterType() { while true; do # Printer Type read -p "Is it a POSTSCRIPT printer, or [q]uit? [y/n/q] " case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; [yY]) PRINTER_TYPE="postscript" break ;; [nN]) PRINTER_TYPE="raw" break ;; ""|*) invalidInput ;; esac done printf "OK: Printer type selected: \"$PRINTER_TYPE\".\n\n" } getIpAddr() { while true; do read -p "Enter full IP address (e.g. 192.168.111.222) of printer \"$PRINTER_NAME\", or [q]uit: " REPLY case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; *.*.*.*) IPADDRESS="$REPLY" #no robust pattern checking... break ;; ""|*) invalidInput ;; esac done printf "OK: IP address selected: %s\n\n" "$IPADDRESS" } addHostToHosts() { if ! [ -w "$HOSTS" -a -n "$IPADDRESS" -a -n "$PRINTER_NAME" ]; then # debug #printf "\$HOSTS = $HOSTS\n" #printf "\$IPADDRESS = $IPADDRESS\n" #printf "\$PRINTER_NAME = $PRINTER_NAME\n" exitError " @@@ ERROR: Error in function \"$FUNCNAME\" on line \"$LINENO\"." 1 fi # append host to bottom of $HOSTS printf "%-20s%s\n" "$IPADDRESS" "$PRINTER_NAME" &gt;&gt; "${HOSTS}" # show result egrep "\&lt;$IPADDRESS\&gt;" "$HOSTS" ERROR=$? return $ERROR } addAliasToHosts() { if ! [ -w "${HOSTS}" -a -n "$IPADDRESS" -a -n "$PRINTER_NAME" ]; then exitError " @@@ ERROR: Error in function \"$FUNCNAME\" on line \"$LINENO\"." 1 fi # get IPADDRESS line in $HOSTS declare PRINTER_NAME_LINE=$(egrep "^[^#]*\&lt;$IPADDRESS\&gt;" "$HOSTS") ######## #while read LINE; do # # Remove comments # LINE="${LINE%%#*}" # case "$LINE" in # *${IPADDRESS}*) # # address found # declare EXISTS=0 # break #stop looping # ;; # *) # # address not found # declare EXISTS=1 # ;; # esac #done &lt; $HOSTS ######## # store data (aka remove comments) declare DATASTORE=${PRINTER_NAME_LINE%%#*} # append new printer name to ip address declare NEW_PRINTER_NAME_LINE="$DATASTORE $PRINTER_NAME" # store comments (aka remove data) case $PRINTER_NAME_LINE in *#*) declare COMMENTSTORE=${PRINTER_NAME_LINE#*#} # append alias to stored data declare NEW_PRINTER_NAME_LINE="$NEW_PRINTER_NAME_LINE#$COMMENTSTORE" ;; esac # append alias to $HOSTS printf "Appending \"$PRINTER_NAME\" to \"$HOSTS\" as alias using IP address \"$IPADDRESS\".\n\n" sed -r -e "s/$PRINTER_NAME_LINE/$NEW_PRINTER_NAME_LINE/" -i $HOSTS RESULT=$? # show result egrep "\&lt;$IPADDRESS\&gt;" "$HOSTS" return $RESULT } removeFromHosts() { # grab line with printer name declare PRINTER_NAME_LINE=$(egrep "^[^#]*$PRINTER_NAME[[:space:]]*" ${HOSTS}) #printf "\$PRINTER_NAME_LINE = $PRINTER_NAME_LINE\n" case "$PRINTER_NAME_LINE" in *#*) # save comment for later (aka delete data) declare COMMENTSTORE="${PRINTER_NAME_LINE#*#}" declare HASCOMMENT=0 #true ;; *) declare HASCOMMENT=1 #false ;; esac # store data (aka remove all comments) declare DATASTORE="${PRINTER_NAME_LINE%%#*}" #printf "\$DATASTORE = $DATASTORE\n" # delete PRINTER_NAME declare DATASTORE=${DATASTORE/$PRINTER_NAME} #printf "\$DATASTORE = $DATASTORE\n" backupHosts || exit # Do we have a host remaining for this IP address? # REGEX: ipaddress followed by one or more spaces, followed by one or more alphanumeric chars if egrep "^[^#]*[[:digit:]]{0,3}\.[[:digit:]]{0,3}\.[[:digit:]]{0,3}\.[[:digit:]]{0,3}[[:space:]]+[[:alnum:]]+" &lt;&lt;&lt;"${DATASTORE}" &gt;/dev/null 2&gt;&amp;1; then # we still have a hostname/alias if [ $HASCOMMENT -eq 0 ]; then # Comment present. Append it. declare DATASTORE="${DATASTORE}#${COMMENTSTORE}" fi # BUG: TODO: this is erasing ALL occurences of printer_name # should only modify the one we want #sed -r -e "s/$PRINTER_NAME_LINE[[:space:]]*/$NEW_PRINTER_NAME_LINE/g" -i "$HOSTS" sed -r -e "s/^[^#]*$PRINTER_NAME_LINE[[:space:]]*/$DATASTORE/g" -i "${HOSTS}" SED_RESULT=$? else # we have no hostnames/aliases remaining. Delete entire line #printf " ... running sed ... \n" #printf "\$PRINTER_NAME_LINE = $PRINTER_NAME_LINE\n" #printf "\$DATASTORE = $DATASTORE\n" sed -r -e "/^[^#]*$PRINTER_NAME/d" -i "$HOSTS" SED_RESULT=$? fi if [ $SED_RESULT -eq 0 ]; then printf "Ok: Printer \"$PRINTER_NAME\" successfully removed from \"$HOSTS\".\n" else exitError " @@@ ERROR: Fatal error on line \"$LINENO\" in function \"$FUNCNAME\"." 1 fi return $SED_RESULT #printf "...reached end of removeFromHosts...\n" } backupHosts () { printf "Making backup copy of \"$HOSTS\" to \"${HOSTS}.$$\".\n" #printf "cp -v \"${HOSTS}\" \"${HOSTS}.$$\"\n\n" cp "${HOSTS}" "${HOSTS}.$$" RESULT=$? if [ $RESULT -eq 0 -a -f "$HOSTS.$$" ]; then printf "Successfully backed up hosts file.\n\n" else printf "Backup of hosts file was not successful.\n\n" &gt;&amp;2 fi return $RESULT } lpadd() { COMMANDLINE="lpadmin -p ${PRINTER_NAME} -E" if [ -n "${PRINTER_NAME}" -a -n "${PRINTER_TYPE}" -a -n "${CONNECTION_TYPE}" ]; then # PRINTER_TYPE if [ "${PRINTER_TYPE}" = "raw" ]; then # Printer Type: RAW COMMANDLINE="${COMMANDLINE} -m raw" elif [ "$PRINTER_TYPE" = "postscript" ]; then # Printer type: postscript COMMANDLINE="${COMMANDLINE} -P $POSTSCRIPT" else exitError " @@@ ERROR: Invalid Printer Type: \"$PRINTER_TYPE\"." 1 fi # CONNECTION_TYPE if [ "$CONNECTION_TYPE" = "LPD" ]; then if [ -n "${PORTNAME}" ]; then COMMANDLINE="${COMMANDLINE} -v lpd://${PRINTER_NAME}/${PORTNAME}" else exitError "Error: Missing \$PORTNAME." 1 fi elif [ "$CONNECTION_TYPE" = 9100 ]; then COMMANDLINE="${COMMANDLINE} -v socket://${PRINTER_NAME}:9100" else exitError " @@@ ERROR: Invalid Connection Type: \"$CONNECTION_TYPE\"." 1 fi else # debug echo " -------------------------- *** ---------------------------" echo "----------------- SHOULD NEVER BE HERE ------------------" echo " -------------------------- *** ---------------------------" exitError " @@@ ERROR: Serious error. Insufficient values provided. Function \"$FUNCNAME.\"" 1 # debug printf "printer name: %s\nprinter type: %s\nconnection type: %s\nportname: %s\n" \ "$PRINTER_NAME" "$PRINTER_TYPE" "$CONNECTION_TYPE" "$PORTNAME" fi # provide error policy COMMANDLINE="${COMMANDLINE} -o printer-error-policy=retry-job" while true; do printf "About to run this command: \033[1;31m%s\033[0m\n\n" "${COMMANDLINE}" read -p "Are you sure? 'yes' or [q]uit? [yes/q] " REPLY case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; yes|YES) break #yes. doAddPrinter ;; ""|*) invalidInput ;; esac done } doAddPrinter() { declare SUCCESS # backup hosts file backupHosts || exit #if [ "$ADDTOHOSTS" = "alias" ] ; then # addAliasToHosts #else # addHostToHosts #fi # add host, or alias # debug #printf "\$HOSTACTION = $HOSTACTION\n" eval $HOSTACTION # add printer printf "\n" eval $COMMANDLINE #if eval $COMMANDLINE ; then if checkPrinterExistsInSystem; then SUCCESS=0 lpstat -v "$PRINTER_NAME" printf "Printer successfully added.\n\n" else SUCCESS=1 printf "Printer was not successfully added!\n\n" &gt;&amp;2 #exit fi return $SUCCESS } acceptPrinter () { printf "Enabling new printer \"$PRINTER_NAME\"...\n" if which accept &gt;/dev/null 2&gt;&amp;1; then accept $PRINTER_NAME elif which cupsenable &gt;/dev/null 2&gt;&amp;1; then cupsenable $PRINTER_NAME else printf "Could not enable printer. Try running 'accept $PRINTER_NAME' or 'cupsenable $PRINTER_NAME' manually.\n" &gt;&amp;2 false fi RC=$? return $RC } lprm() { while true; do read -p "Are you sure you want to remove printer \"$PRINTER_NAME\"? [yes/q]: " REPLY case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; yes|YES) break ;; ""|*) invalidInput ;; esac done lpadmin -x "${PRINTER_NAME}" # delete printer if checkPrinterExistsInSystem; then # does printer still exist? # printer remains -- bad declare SUCCESS=1 #false else # printer deleted -- good declare SUCCESS=0 #true #FIXME removeFromHosts fi return $SUCCESS } main () { enterPrinterName if checkPrinterExistsInSystem; then lpstat -v ${PRINTER_NAME} printf "\nPrinter \"${PRINTER_NAME}\" already exists in the system.\n" while true; do read -p "[d]elete printer, [r]estart, or [q]uit? [r/s/q]? " REPLY case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; [dD]) if lprm "$PRINTER_NAME"; then printf "OK: Printer \"${PRINTER_NAME}\" successfully removed from the system.\n\n" #break #call checkNameExistsInHosts return 0 else exitError " @@@ ERROR: Failure to remove printer from the system.\n" 1 fi ;; [rR]) return 0 #exit main, start loop again, restart script ;; esac done else # consider deleting completely : #printf "OK: Printer \"${PRINTER_NAME}\" does not exist in the system.\n\n" fi if checkNameExistsInHosts; then while true; do read -p "Are the details correct [y], [r]estart or [q]uit? [y/r/q] " REPLY case $REPLY in [qQ]) exitError "Aborted by User." 0 ;; [yY]) #if ok -&gt; getData() break ;; [rR]) #if not ok -&gt; loop back main printf "OK: Restarting script.\n\n" return 0 #quit main and restart script ;; ""|*) invalidInput ;; esac done else #if name does not exist in hosts, get ip addr getIpAddr if checkAddressExistsInHosts; then while true; do read -p "Add as an alias to \"$HOSTS\", or [q]uit? [y/n/q] " REPLY case $REPLY in [qQnN]) exitError "Aborted by User." 0 ;; [yY]) break #addAliasToHosts ;; ""|*) invalidInput ;; esac done fi fi getConnectionType getPrinterType lpadd doAddPrinter acceptPrinter } ## ## MAIN PROGRAM ## sanity while true; do main done unset GREP_OPTIONS </code></pre>
[]
[ { "body": "<p>To answer your question, yes, it can be improved, but that could be said about any piece of code, right? And perfection is in the eye of the observer, so I'll stick to the things that have proved gotchas for me, and those focus around <a href=\"https://www.gnu.org/s/bash/manual/bash.html#Conditional-Constructs\" rel=\"nofollow noreferrer\">conditional constructs</a>.</p>\n\n<p>As was mentioned in the comments on your <a href=\"https://stackoverflow.com/questions/7682962/could-this-bash-script-be-improved\">original post on SO</a>, <code>[ ]</code> is better than <code>test</code>. But we can go one step further. Some times you'll see scripts that have something similar to this.</p>\n\n<pre><code>if [ x\"$VAR\" = x\"\" ]; then ...; fi\n</code></pre>\n\n<p>This was to avoid a situation where an empty variable could cause a syntax error. Using <code>[[ ]]</code> automatically avoids this an allows you to write more cleanly.</p>\n\n<pre><code>if [[ $VAR == \"\" ]]; then ...; fi\n</code></pre>\n\n<p>This also allows you to have more natural logic operators in your conditional.</p>\n\n<pre><code>if [[ $VAR1 == \"yep\" &amp;&amp; $VAR2 == \"sure\" ]]; then ...; fi\n</code></pre>\n\n<p>There are many other cool things that this buys you too. You can now do regular expression comparisons inline.</p>\n\n<pre><code>if [[ $IP =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then echo \"valid ip\"; fi;\n</code></pre>\n\n<p>The last thing I'll leave you with the <code>(( ))</code>. This is very very handy when you know you are operating on numbers. It allows you, among many other things, to compare numbers as numbers rather than strings (as with <code>[ ]</code> or <code>[[ ]]</code>).</p>\n\n<pre><code>if (( $ZERO == 0 )); then echo \"yep, it's zero\"; fi\n</code></pre>\n\n<p>I'll leave you to explore the <em>recent</em> version of the manual for more cool stuff! :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T20:02:36.550", "Id": "8029", "Score": "0", "body": "Why is `[]` better than `test`? (The majority of projects that I've worked on prefer `test` to `[]` so I'm interested in your rationale.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T20:24:52.073", "Id": "8030", "Score": "0", "body": "@CharlesBailey, Functionally, `[ ]` is the same as `test`, so in that regard it doesn't matter. Many find `[ ]` is easier to read than `test`. But, and this is important, neither compare to the power of `[[ ]]` which should be regularly used in favor of both `[ ]` and `test`. Check out the [documentation on conditional constructs](https://www.gnu.org/s/bash/manual/bash.html#Conditional-Constructs) for more info. (Notice that `[ ]` and `test` aren't even mentioned any more! They're deprecated!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T20:29:35.783", "Id": "8031", "Score": "2", "body": "`[[ ... ]]` isn't in the POSIX standard, though, so you immediately lose compatibility with standard Bourne shells. Can you provide a reference to `test` and `[]` being deprecated, I am very surprised to here that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T21:03:02.587", "Id": "8032", "Score": "0", "body": "@CharlesBailey, The latest version of the Bash manual doesn't reference to the use of `[ ]` and only details `[[ ]]` and since `[[ ]]` encompass the functionality of `[ ]`, that's deprecation by definition! :) Also note: (1) `[[ ]]` was introduced near its present capacity circa Bash-2.0, but has since developed. (2) `[[ ]]` is not in POSIX, but the standard does mention that these characters are used as reserved words in some implementations (i.e. Bash). (3) The original question is about Bash, so it's worth mentioning `[[ ]]` as a good feature to use! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T21:11:42.610", "Id": "8034", "Score": "2", "body": "`test` and `[` are referenced here: https://www.gnu.org/s/bash/manual/bash.html#Shell-Builtin-Commands . They are not marked as deprecated and as bash \"intended to be a conformant implementation of the ieee posix Shell and Tools portion of the ieee posix specification\", nor should they be. I think you were misusing the word \"deprecated\". I always think it's good to warn about non-portable constructs even when they have useful advantages." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T14:43:10.610", "Id": "5323", "ParentId": "5272", "Score": "2" } }, { "body": "<p>Some other minor notes on portability (I know that from your shebang you are using bash but a portable script is usually better :-)</p>\n\n<ul>\n<li><p><code>declare</code> is not portable (you could use subshells <code>( ... )</code> or <code>$( ... )</code> to define local variables</p></li>\n<li><p>here-strings are not portable</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T12:56:51.307", "Id": "6005", "ParentId": "5272", "Score": "0" } }, { "body": "<p>I see only a couple of minor issues.</p>\n\n<hr>\n\n<p>I suggest to flip the parameters of <code>exitError</code>: make the exit code the first and the message the second. As the message tends to get long, the exit code parameter is easy to overlook, which can lead to accidental misuses.</p>\n\n<hr>\n\n<p>No need to quote literal values like <code>'0'</code> here, you can write simply <code>0</code>:</p>\n\n<blockquote>\n<pre><code>if [ $EUID != '0' ]; then\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Instead of declaring a \"useless\" variable here:</p>\n\n<blockquote>\n<pre><code>declare USELESS\nprintf \"\\nInvalid input.\\n\" &gt;&amp;2\nread -p \"Press Any Key To Continue...\" USELESS\n#unset USELESS\nprintf \"\\n\"\n</code></pre>\n</blockquote>\n\n<p>You could just not declare anything at all:</p>\n\n<pre><code>printf \"\\nInvalid input.\\n\" &gt;&amp;2\nread -p \"Press Any Key To Continue...\"\nprintf \"\\n\"\n</code></pre>\n\n<hr>\n\n<p>The handling of printer name input is a bit odd:</p>\n\n<blockquote>\n<pre><code> read -p \"Enter printer name, or [q]uit: \" PRINTER_NAME\n case $PRINTER_NAME in\n [qQ]) exitError \"Aborted by User\" 0\n ;;\n ??*) break\n ;;\n \"\"|*) invalidInput #blank line or anything else\n ;;\n</code></pre>\n</blockquote>\n\n<p>An invalid value is a blank or a single-letter name other than \"q\" or \"Q\".\nIf it's important that the name should not be a single-letter, then it would be better to mention that in the prompt. If it's not so important, then the switch can be simplified a bit:</p>\n\n<blockquote>\n<pre><code> read -p \"Enter printer name, or [q]uit: \" PRINTER_NAME\n case $PRINTER_NAME in\n [qQ]) exitError \"Aborted by User\" 0\n ;;\n \"\") invalidInput\n ;;\n *) break\n ;;\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>This kind of <code>case</code> statement appears at many places:</p>\n\n<blockquote>\n<pre><code> \"\"|*) invalidInput\n</code></pre>\n</blockquote>\n\n<p>When <code>*</code> is one of the values, all other values are unnecessary.</p>\n\n<hr>\n\n<p>Since the script uses <code>/bin/bash</code>, you could simplify <code>&gt;/dev/null 2&gt;&amp;1</code> as <code>&amp;&gt;/dev/null</code>.</p>\n\n<hr>\n\n<p>I'm not a huge fan of flag variables.\nFor example in <code>doAddPrinter</code> you have this:</p>\n\n<blockquote>\n<pre><code>declare SUCCESS\n\n# ... (many many lines)\n\nif checkPrinterExistsInSystem; then\n SUCCESS=0\n lpstat -v \"$PRINTER_NAME\"\n printf \"Printer successfully added.\\n\\n\"\nelse\n SUCCESS=1\n printf \"Printer was not successfully added!\\n\\n\" &gt;&amp;2\n #exit\nfi\nreturn $SUCCESS\n</code></pre>\n</blockquote>\n\n<p>I suggest to not declare <code>SUCCESS</code> at the top and <code>return</code> at the end,\nbut to return in the branches of the final conditional:</p>\n\n<pre><code>if checkPrinterExistsInSystem; then\n lpstat -v \"$PRINTER_NAME\"\n printf \"Printer successfully added.\\n\\n\"\n return 0\nelse\n printf \"Printer was not successfully added!\\n\\n\" &gt;&amp;2\n return 1\nfi\n</code></pre>\n\n<p>If you really want to use the <code>SUCCESS</code> variable, then at least declare it right before it's used, so the reader doesn't need to scroll up to verify the <code>declare</code> or <code>local</code> keywords.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-14T06:12:28.520", "Id": "128331", "ParentId": "5272", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T04:36:09.560", "Id": "5272", "Score": "3", "Tags": [ "bash" ], "Title": "bash script for printer administration" }
5272
<h1>Detecting types in JavaScript sucks</h1> <p><a href="https://stackoverflow.com/questions/4775722/javascript-check-if-object-is-array">This answer</a> discusses the standard way to check the type of a JavaScript object (specifically, an array):</p> <blockquote> <p>The method given in the ECMAScript standard to find the class of Object is to use the toString method from Object.prototype.</p> <pre><code>if( Object.prototype.toString.call( someVar ) === '[object Array]' ) { alert( 'Array!' ); } </code></pre> </blockquote> <p>Why abuse <code>Object.prototype.toString</code>? It turns out that objects created in different frames have <a href="https://stackoverflow.com/questions/4347298/use-of-tostring-instead-of-constructor-in-javascript/4347377#4347377">different constructors</a>.</p> <p><code>typeof</code> only works for objects which are (or have equivalent) primitives, like strings.</p> <h2>Another way?</h2> <p>The above code makes me feel funny inside, and doesn’t have a chance of working for custom types, so I wrote this [<a href="https://gist.github.com/1274551" rel="nofollow noreferrer">Gist</a>]:</p> <pre><code>function isType(object, type){ return object != null &amp;&amp; type ? object.constructor.name === type.name : object === type; } </code></pre> <p>You use it like this:</p> <pre><code>isType([1, 2, 3], Array); isType(null, null); isType('foo', String); </code></pre> <p><code>mauke</code> on ##javascript points out that it fails for objects whose constructors have the same name as the type you're testing against:</p> <pre><code>isType(new (function String(){}), String); </code></pre> <p>I <em>think</em> I like this behavior more than calling every custom type an Object.</p> <h2>To take it one step further</h2> <p>jQuery has a 25-line <code>isPlainObject</code> to tell if something is a plain object (<code>{ foo: 'bar' }</code>).</p> <p>In what cases does the jQuery version behave more-correctly than…</p> <pre><code>isType(thing, Object); </code></pre> <p>?</p> <p><sup>Disclaimer: I haven’t tested this code in a bunch of cases or in a bunch of browsers. The experience concentrated into the jQuery source could blow me back to preschool.</sup></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T04:06:29.180", "Id": "7973", "Score": "0", "body": "One thing to consider: checking to see whether the constructor names are exactly equal (that is, the exact same string) may not work if it's possible for objects to \"drift\" between frames. That's one of the reasons that the big libraries don't do things like that -- each `window` has its own separate \"Array\" constructor, for example, and it's entirely possible that the name \"Array\" is distinct window by window also." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T04:06:41.893", "Id": "7974", "Score": "0", "body": "I thought `constructor` property wasn't reliable in a multi `window` environment too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T04:07:19.603", "Id": "7975", "Score": "0", "body": "`isType(false, Boolean)`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T04:11:25.170", "Id": "7976", "Score": "0", "body": "@Pointy: Excellent point. In my testing, comparing the names does work across frames (unlike comparing the constructors themselves). Have you had a different experience?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T04:13:09.660", "Id": "7977", "Score": "0", "body": "@JohnFlatness: Thanks! Does this edit fix it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T09:02:40.137", "Id": "7978", "Score": "0", "body": "No I haven't tried it but I have had problems with `x instanceof Array` for example" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T14:03:15.350", "Id": "7988", "Score": "0", "body": "@Pointy: Exactly, and that problem is laid out in the second link. Otherwise, it would be great to compare `.constructor` directly or use `instanceof` (if it was OK to go up the prototype chain). I think that comparing the names of the constructors is an OK workaround." } ]
[ { "body": "<p>I could not find anything wrong with your code,\nso per Meta I am going to tell you why it is awesome ;)</p>\n\n<ul>\n<li>Checking <code>.toString()</code> is icky, <code>toString()</code> could easily be replaced/enhanced</li>\n<li>Your solution works across frames</li>\n<li>I was not able to break it.</li>\n</ul>\n\n<p>On a final note, it seems to me that needing to verify the type of an object ( besides assertions ) means you are doing something odd and probably the code should be re-thought.</p>\n\n<p>Still, I am favouriting this question.</p>\n\n<p>UPDATE : Turns out that according to jsperf, your solution is much slower :\\</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-16T19:38:30.957", "Id": "39408", "ParentId": "5278", "Score": "5" } }, { "body": "<p>Alright I'm going to focus on some potential errors with your <code>isType</code> function.</p>\n\n<p>The first obvious issue is you're relying on <code>constructor.name</code> being set. This isn't always the case - for instance consider any class declared <code>var MyClass = function() {}</code>. Now if you run <code>(new MyClass).constructor.name === \"\"</code>. Furthermore, many frameworks provide some class extension/constructs such as <code>Mootools</code> which would invalidate that check. Further issues may present themselves with code minification.</p>\n\n<p>Out of curiosity, I decided to plug your code into the <a href=\"http://underscorejs.org\" rel=\"nofollow noreferrer\">underscore js</a> test suite to see how it would do. I couldn't implement <code>_.isObject</code> as it accepts multiple types as objects. <a href=\"http://jsbin.com/regereyu/4\" rel=\"nofollow noreferrer\">It passes all the tests but the ones for <code>NaN</code> understandably</a>. I excluded the <code>iframe</code> tests as I couldn't get them working on gists or jsbin but they pass as well. Not bad :)!</p>\n\n<p><img src=\"https://i.stack.imgur.com/fVJI0.png\" alt=\"enter image description here\"></p>\n\n<p><strong>Edit</strong> this will also not work for objects created via <code>Object.create</code> unfortunately.</p>\n\n<p><code>isType(Object.create(null), Object)</code> will throw a <code>TypeError</code> as the resulting object will have no <code>constructor</code> property</p>\n\n<p>Similarly it will fail for any Object that has a <code>constructor</code> property... consider</p>\n\n<pre><code>var obj = {\n constructor: \"foo\"\n};\n</code></pre>\n\n<p><strong>Edit 2</strong> It appears this also incorrectly? suggests the <code>arguments</code> object is a Object.</p>\n\n<pre><code>(function() {\n isType(arguments, Object) === true;\n})([1])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-17T05:39:38.293", "Id": "47436", "ParentId": "5278", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T04:01:45.333", "Id": "5278", "Score": "3", "Tags": [ "javascript" ], "Title": "Alternative implementation of isType()" }
5278
<p>So, I wanted to avoid an</p> <pre><code>if (...) { } else if (...) { } else { } </code></pre> <p>scenario to avoid duplicating code. After a little playing, I got the following working (works from the testing i've done). Am wondering if anyone has any feedback on this approach or suggestions on on possible improvement?</p> <p>Sometimes I think I know what I'm doing, sometimes I don't.</p> <pre><code>&lt;?php // define("MEMBER_LIMIT",0); // no member limit defined("MEMBER_LIMIT",100); // limit to 100 ppl in group // $memcount is set via sn SQL query $memcount = 9; // number of people currently in group (let's say). if (!defined("MEMBER_LIMIT") || ((defined("MEMBER_LIMIT") &amp;&amp; MEMBER_LIMIT == 0) || (MEMBER_LIMIT &gt; 0 &amp;&amp; $memcount&gt;0 &amp;&amp; $memcount &lt; MEMBER_LIMIT))) { // will do something } else { // will do something else. } ?&gt; </code></pre>
[]
[ { "body": "<p>How about:</p>\n\n<pre><code>if (!defined(\"MEMBER_LIMIT\") || MEMBER_LIMIT == 0 || $memcount &lt; MEMBER_LIMIT) {\n // will do something\n}\nelse {\n // will do something else.\n}\n</code></pre>\n\n<p>The key is to look for both complementary (multiple items that accomplish the same thing by different means) and contradicting criteria (which would interrupt your desired flow of logic) in if statements</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T09:58:35.923", "Id": "7984", "Score": "0", "body": "If you look into the code, `MEMBER_LIMIT` is always defined." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T09:59:25.420", "Id": "7985", "Score": "0", "body": "Indeed, I thought the user may comment back in the initial line however" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T10:09:41.600", "Id": "7986", "Score": "0", "body": "yes, if i leave 'defined(...)' in there. there are plans to have certain things defined and others not, which i was the !defined(...) check." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T09:54:53.003", "Id": "5281", "ParentId": "5280", "Score": "7" } } ]
{ "AcceptedAnswerId": "5281", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T09:51:13.910", "Id": "5280", "Score": "0", "Tags": [ "php" ], "Title": "Is this IF ok? Or is there a better way?" }
5280
<p>Here is some code to insert a new line escape sequence after a certain number of characters (for fixed width displays)</p> <pre><code> private string spliceNoteText(string text) { StringBuilder sb = new StringBuilder(); int maxWidth = 70; int blockOfText; for (int i = 0; i &lt;= text.Length; i += maxWidth) { if (i &gt;= text.Length) continue; int charsRemaining = text.Length - i; if (charsRemaining &lt;= maxWidth) blockOfText = charsRemaining; else blockOfText = maxWidth; sb.Append(text.Substring(i, blockOfText)); sb.Append("\n"); } return sb.ToString(); } </code></pre> <p>It's is ugly and boring, can it be made prettier or more elegant?</p>
[]
[ { "body": "<p>You could already create the StringBuilder with the text you want to 'splice', rather than building it up again. Then you can just determine how many newline characters you want to add (and you should use <code>Environment.NewLine</code> instead of specifying it explicitly), and insert them in the right place.</p>\n\n<pre><code> private string SpliceNoteText(string text, int maxWidth)\n {\n StringBuilder sb = new StringBuilder(text);\n\n for (int i = 0; i &lt; (sb.Length / maxWidth); i++)\n {\n int insertPosition = i * maxWidth;\n sb.Insert(insertPosition, Environment.NewLine);\n }\n\n return sb.ToString();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T20:59:21.180", "Id": "7990", "Score": "2", "body": "The logic will be off however as you'd have to account for the added newlines if you go forward through the builder. You should go backwards through it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T20:16:41.513", "Id": "8013", "Score": "2", "body": "Inserting characters in a string builder means that you will be copying half the string by average for each insert. Copying strings to a new string builder will scale much better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T16:00:41.867", "Id": "5285", "ParentId": "5283", "Score": "3" } }, { "body": "<p>You can make it reusable by taking a line length parameter, and you can use a regular expression to reduce the code somewhat:</p>\n<pre><code>public static string SpliceNoteText(string text, int lineLength) {\n return Regex.Replace(text, &quot;(.{&quot; + lineLength + &quot;})&quot;, &quot;$1&quot; + Environment.NewLine);\n}\n</code></pre>\n<p>Note that I used <code>Environment.NewLine</code> which gives the newline character combination for the current system, instead of the newline character escape sequence. That's what you would normally do, but it might not apply in your specific case, depending on how you are going to use the string.</p>\n<h3>Edit:</h3>\n<p>The regular expression is of course not as fast as the original code. A simple performance test for splicing a 100000 character string gives:</p>\n<pre><code>Original 0,23 ms.\nRegexp 1,31 ms.\nInsert 15,06 ms.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T20:18:20.730", "Id": "5311", "ParentId": "5283", "Score": "3" } }, { "body": "<p>Could also use linq</p>\n\n<pre><code>public static string SpliceNoteText(string text, int lineLength) \n{\n var segments = (int)Math.Ceiling( (double)text.Length / (double)lineLength);\n return string.Join(Environment.NewLine, \n Enumerable.Range(0,segments\n ).Select(i =&gt; x.Substring(i * maxLength, Math.Min( lineLength, text.Length - i * lineLength ))));\n}\n</code></pre>\n\n<p><strong>Updated</strong></p>\n\n<p>Faster with lookup</p>\n\n<pre><code>public static string SpliceNoteText(string text, int lineLength) \n{\n int k = 0;\n return string.Join(Environment.NewLine, text.ToLookup(c =&gt; k++ / lineLength)\n .Select(e =&gt; new String(e.ToArray())));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:15:06.473", "Id": "5333", "ParentId": "5283", "Score": "0" } }, { "body": "<p>You can avoid creating a bunch of temporary strings (copying all your character data twice) by using StringBuilder to something nearer its full potential.</p>\n\n<pre><code>private static string SpliceNoteText(string text, int maxWidth)\n{\n if (string.IsNullOrEmpty(text)) return text;\n\n int numWraps = (text.Length - 1) / maxWidth;\n StringBuilder sb = new StringBuilder(text.Length + numWraps * Environment.NewLine.Length);\n\n for (int i = 0, off = 0; i &lt; numWraps; i++, off += maxWidth) {\n sb.Append(text, off, maxWidth).Append(Environment.NewLine);\n }\n sb.Append(text, off, text.Length - off);\n\n return sb.ToString();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T19:04:03.090", "Id": "5370", "ParentId": "5283", "Score": "0" } }, { "body": "<p>To splice the string in general, this would be faster and more efficient then using LINQ or other methods.</p>\n\n<pre><code>public static IEnumerable&lt;string&gt; Splice(this string s, int spliceLength)\n{\n if (s == null)\n throw new ArgumentNullException(\"s\");\n if (spliceLength &lt; 1)\n throw new ArgumentOutOfRangeException(\"spliceLength\");\n\n if (s.Length == 0)\n yield break;\n var start = 0;\n for (var end = spliceLength; end &lt; s.Length; end += spliceLength)\n {\n yield return s.Substring(start, spliceLength);\n start = end;\n }\n yield return s.Substring(start);\n}\n</code></pre>\n\n<p>Then to use with your function:</p>\n\n<pre><code>static string SpliceNoteText(string text)\n{\n return String.Join(Environment.NewLine, text.Splice(70));\n}\n</code></pre>\n\n<p>If you'd rather not use a separate (extension) method or use <code>String.Join()</code>, it should be easy to combine them.</p>\n\n<pre><code>static string SpliceNoteText(string text)\n{\n if (text == null)\n throw new ArgumentNullException(\"text\");\n\n if (text.Length == 0)\n return String.Empty;\n const int spliceLength = 70;\n var sb = new StringBuilder();\n var start = 0;\n for (var end = spliceLength; end &lt; s.Length; end += spliceLength)\n {\n sb.Append(text, start, spliceLength).AppendLine();\n start = end;\n }\n sb.Append(text, start, text.Length - start);\n return sb.ToString();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T20:43:50.770", "Id": "5431", "ParentId": "5283", "Score": "0" } } ]
{ "AcceptedAnswerId": "5285", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T14:48:56.977", "Id": "5283", "Score": "6", "Tags": [ "c#", "strings" ], "Title": "Better way to write a string slicer" }
5283
<p>I have the following code, which gets the data from 3 text files and puts them into 3 variables. How can I refactor this to make it smaller?</p> <pre><code>$handle = fopen($template_filename, "r"); if (filesize($template_filename) &gt; 0) { $email_template = fread($handle, filesize($template_filename)); } fclose($handle); // get the subject from a text file $handle = fopen($subject_filename, "r"); if (filesize($subject_filename) &gt; 0) { $subject_template = fread($handle, filesize($subject_filename)); } fclose($handle); // get the footer from a text file $handle = fopen($footer_filename, "r"); if (filesize($footer_filename) &gt; 0) { $footer_template = fread($handle, filesize($footer_filename)); } fclose($handle); </code></pre>
[]
[ { "body": "<p>For one thing, you can use <a href=\"http://us3.php.net/manual/en/function.file-get-contents.php\" rel=\"nofollow\"><code>file_get_contents</code></a>:</p>\n\n<pre><code>$email_template = file_get_contents($template_filename);\n$subject_template = file_get_contents($subject_filename);\n$footer_template = file_get_contents($footer_filename);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T19:31:47.560", "Id": "5292", "ParentId": "5286", "Score": "3" } }, { "body": "<p>Encapsulate the repetitive parts in a function <code>openFile()</code>, open files with <code>file_get_contents</code>, and finally, check for empty file size via strlen in the ternary and return the contents or an error (\"Empty file.\" in this case - would suggest you replace with an error function call or something).</p>\n\n<pre><code>function openFile($filename){\n $contents = file_get_contents($filename);\n return strlen($contents) &gt; 0 ? $contents : \"Empty file.\";\n}\n\n$email_template = openFile($email_filename);\n$subject_template = openFile($subject_filename);\n$footer_template = openFile($footer_filename);\n\n# Test case\necho openFile(\"http://www.google.com\");\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-16T19:49:08.020", "Id": "13725", "ParentId": "5286", "Score": "0" } } ]
{ "AcceptedAnswerId": "5292", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T16:06:20.857", "Id": "5286", "Score": "2", "Tags": [ "php" ], "Title": "Putting data from 3 text files into 3 variables" }
5286
<p>Connection stored in the xml config file.</p> <pre><code>&lt;?xml version='1.0' ?&gt; &lt;database&gt; &lt;connection&gt; &lt;dbtype&gt;mysql&lt;/dbtype&gt; &lt;dbname&gt;shoutbox&lt;/dbname&gt; &lt;host&gt;localhost&lt;/host&gt; &lt;port&gt;3306&lt;/port&gt; &lt;user&gt;admin&lt;/user&gt; &lt;password&gt;admin&lt;/password&gt; &lt;/connection&gt; &lt;/database&gt; </code></pre> <p> <pre><code>class DBWrapper { /** * Stores the database connection object. * * @access protected * @var database connection object */ protected $dbo = NULL; /** * Stores the class instance, created only once on invocation. * Singleton object instance of the class DBWrapper * * @access protected * @static */ protected static $instance = NULL; /** * Stores the database configuration, from the config.xml file * * @access protected */ protected $xml; /** * When the constructor is called (which is called only once - singleton instance) * the connection to the database is set. * * @access protected */ protected function __construct() { $this-&gt;getConnection(); } /** * Grabs the database settings from the config file * * @access private */ private function loadConfig() { $this-&gt;xml = simplexml_load_file("Config.xml"); } /** * Instantiates the DBWrapper class. * * @access public * @return object $instance */ public static function getInstance() { if(!self::$instance instanceof DBWrapper) { self::$instance = new DBWrapper(); } return self::$instance; } /** * Sets up the connection to the database. */ protected function getConnection() { if(is_null($this-&gt;dbo)) { $this-&gt;loadConfig(); list($dsn,$user, $password) = $this-&gt;setDSN(); $this-&gt;dbo = new PDO($dsn,$user,$password); $this-&gt;dbo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } } /** * Constructs the database source name(dsn) after the config file is read. * * @return array */ protected function setDSN() { $dbtype = $this-&gt;xml-&gt;connection[0]-&gt;dbtype; $dbname = $this-&gt;xml-&gt;connection[0]-&gt;dbname; $location = $this-&gt;xml-&gt;connection[0]-&gt;host.":".$this-&gt;xml-&gt;connection[0]-&gt;port; $user = $this-&gt;xml-&gt;connection[0]-&gt;user; $password = $this-&gt;xml-&gt;connection[0]-&gt;password; $dsn = $dbtype.":dbname=".$dbname.";host=".$location; return array($dsn, $user,$password); } /** * Initiates a transaction. */ protected function beginTransaction() { $this-&gt;dbo-&gt;beginTransaction(); } /** * Commits a transaction. */ protected function commitTransaction() { $this-&gt;dbo-&gt;commit(); } /** * Roll back a transaction. */ protected function rollbackTransaction() { $this-&gt;dbo-&gt;rollBack(); } /** * Select rows from the database. * * @param string $table Name of the table from which the row has to be fetched * @param array $columns Name of the columns from the table * @param array $where All the conditions have to be passed as a array * @param array $params For binding the values in the where clause * @param array $orderby Name of the columns on which the data has to be sorted * @param int $start Starting point of the rows to be fetched * @param int $limit Number of rows to be fetched * @exception $ex * @return int $rowcount */ public function select($table, $columns = '*', $where = '', $params = null, $orderby = null, $limit = null, $start = null) { try { $query = 'SELECT '; $query .= is_array($columns) ? implode(",",$columns) : $columns; $query .= " FROM {$table} "; if(!empty($where)) { $query .= " where ".implode(" and ", $where); } if(is_array($orderby)) { $query .= " order by "; $query .= implode(",",$orderby); } $query .= is_numeric($limit) ? " limit ".(is_numeric($start) ? "$start, " : " ").$limit : ""; $sth = $this-&gt;dbo-&gt;prepare($query); $sth-&gt;execute($params); $rows = $sth-&gt;fetchAll(PDO::FETCH_ASSOC); return $rows; } catch(Exception $ex) { $this-&gt;exceptionThrower($ex,true); exit; } } /** * Insert's a row into the database. * * @param string $table Name of the table into which the row has to be inserted * @param array $params For binding the values in the where clause * @exception $ex * @return int $rowcount */ public function insert($table, $params) { try { $bind = "(:".implode(',:', array_keys($params)).")"; $query = "INSERT INTO ".$table. "(" .implode(",", array_keys($params)).") VALUE ".$bind; $this-&gt;beginTransaction(); $sth = $this-&gt;dbo-&gt;prepare($query); $sth-&gt;execute($params); $rowcount = $sth-&gt;rowCount(); $this-&gt;commitTransaction(); return $rowcount; } catch(Exception $ex) { $this-&gt;exceptionThrower($ex,false); exit; } } /** * Delete's a row from the database. * * @param string $table Name of the table into which the row has to be deleted * @param array $where All the conditions have to be passed as a array * @param array $params For binding the values in the where clause * @exception $ex * @return int $rowcount */ public function delete($table,$where=null,$params=null) { try { $query = 'DELETE FROM '.$table; if(!is_null($where)) { $query .= ' WHERE '; $query .= implode(" AND ",$where); } $this-&gt;beginTransaction(); $sth = $this-&gt;dbo-&gt;prepare($query); $sth-&gt;execute($params); $rowcount = $sth-&gt;rowCount(); $this-&gt;commitTransaction(); return $rowcount; } catch(Exception $ex) { $this-&gt;exceptionThrower($ex,false); exit; } } /** * Update's a row in the database. * * @param string $table Name of the table into which the row has to be updated * @param array $set Values to be changed are set as an associative array * @param array $where All the conditions have to be passed as a array * @param array $params For binding the values in the where clause * @exception $ex * @return int $rowcount */ public function update($table, $set ,$where = null, $params = null) { try { $count = 0; $str = ''; $query = "UPDATE {$table} SET "; foreach($set as $key=&gt;$val) { $count += 1; if($count &gt; 1) { $query .= " , "; } if(is_numeric($val)){ $query .= $key ." = ". $val; } $query .= $key ." = '". $val."'"; } echo $query."&lt;br/&gt;"; if(!is_null($where)) { $query .= " where ". implode(" and ", $where); } $this-&gt;beginTransaction(); $sth = $this-&gt;dbo-&gt;prepare($query); $sth-&gt;execute($params); $rowcount = $sth-&gt;rowCount(); $this-&gt;commitTransaction(); return $rowcount; } catch(Exception $ex) { $this-&gt;exceptionThrower($ex,false); exit; } } /** * @param object $ex Incoming exception object * @param bool $isSelect Useful for instantiating a roll back */ private function exceptionThrower($ex, $isSelect = true) { if(!$isSelect) { $this-&gt;rollbackTransaction(); } echo "Exception in the: ".get_class($this). " class. &lt;b&gt;Generated at line number:&lt;/b&gt; ".$ex-&gt;getLine(). "&lt;br/&gt; &lt;b&gt;Exception:&lt;/b&gt; ".$ex-&gt;getMessage(). "&lt;br/&gt;&lt;b&gt;Trace:&lt;/b&gt;".$ex-&gt;getTraceAsString(); } } </code></pre> <p>How to use the class.</p> <pre><code>#Using the file: $db = DBWrapper::getInstance(); #Selecting data $table = "shouts"; $columns = array("id","name","post"); $where = array("email like :email"); $params = array('email' =&gt; 'dan@harper.net'); $result_set = $db-&gt;select($table,$columns,$where, $params); $result_set = $db-&gt;select($table); foreach($result_set as $result) { echo "&lt;b&gt;Post:&lt;/b&gt;".$result['post']."&lt;br/&gt;"; } #Insert $table = "shouts"; $insert = array('name'=&gt;'chaitanya','email'=&gt;'learner@sfo.net','post'=&gt;'Congratulations! You have successfully created a Hello World application!', 'ipaddress'=&gt;$ipaddress); echo "&lt;br/&gt;Count: ".$db-&gt;insert("shouts", $insert); #Update $table = "shouts"; $set = array('name'=&gt;'code learner', 'email'=&gt;'learner@code.com'); $where = array("id = :id"); $values = array('id'=&gt;1); echo $db-&gt;update($table, $set, $where, $values); //$where = array("id IN (:id0,:id1,:id2,:id3)"); //$where = array("id BETWEEN :id0 and :id1"); #Delete $table = "shouts"; $where = array("id = :id"); $values = array('id'=&gt;1); echo $db-&gt;delete($table, $where, $values); </code></pre> <p>I have written a PDO wrapper, am very new to PHP and this is my first try in OOP-PHP. I request to suggest </p> <ul> <li>Changes in the way the class can be implemented in a better way</li> <li>Features to be added</li> </ul>
[]
[ { "body": "<p>Seeing as there are no other answers I will give a quick review. You seem to have done a good job with this class. Here are some things I would do:</p>\n\n<ol>\n<li>Remove the evil singleton. It is valid to have more than one database connection. Don't limit yourself to a single instance. Use Dependency Injection.</li>\n<li>Provide transaction checking: Add an inTransaction property to the class, set it when you start a transaction. Throw an exception if your code tries to start more than one transaction or commit or rollback without being in a transaction.</li>\n<li>Remove the transaction from your methods. An insert or update call may be part of a much wider transaction - it should not be committed without the rest working.</li>\n<li>Get rid of exceptionThrower. Create an Exception_DB class that extends an exception. If you should rollback do so before you throw. There is some really useful information that you could write in this exception class if you pass the DB. PDO has the errorCode and errorInfo which will give you an idea of why your SQL statement is wrong.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-28T02:42:02.123", "Id": "8522", "Score": "0", "body": "Thanks paul for the comments. I will try to implement what you have suggested and get back here again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-25T04:16:53.840", "Id": "5561", "ParentId": "5294", "Score": "3" } } ]
{ "AcceptedAnswerId": "5561", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-10T21:14:34.000", "Id": "5294", "Score": "4", "Tags": [ "php", "pdo" ], "Title": "PDO wrapper class" }
5294
<p>This code is for a simple language quiz. It fetches two words and related audio files via a JSON call, presents the user with an image that matches one of the words, and challenges the user to make the match. My code works but it's a little repetitious and ugly. I'd like to see how the experts would propose rewriting this.</p> <pre><code>function getNewWords() { { var Category = "animals"; var BaseURL = "http://localhost:61741/VocabGame/play?cat="; var URL = BaseURL + Category; $.getJSON(URL, { tagmode: "any", format: "json" }, function (data) { var choiceA = data.nouns[0].Pinyin; var choiceB = data.nouns[1].Pinyin; $('#ChoiceA').html(choiceA); $('#ChoiceB').html(choiceB); var root = "../../Content/Audio/"; var mp31 = root + data.nouns[0].Audio1 + ".mp3"; var ogg1 = root + data.nouns[0].Audio1 + ".ogg"; var mp32 = root + data.nouns[1].Audio1 + ".mp3"; var ogg2 = root + data.nouns[1].Audio1 + ".ogg"; attachMouseEnter(mp31, ogg1, mp32, ogg2); var random = Math.random(); if (random &gt;= 0.5) { correctAnswer = "ChoiceA"; Search(data.nouns[0].English); } else { correctAnswer = "ChoiceB" Search(data.nouns[1].English); } }); } }; function playAudio1(mp31, ogg1) { var mp3_src = mp31; var oga_src = ogg1; $('#jquery_jplayer_1').jPlayer('setMedia', { oga: oga_src, mp3: mp3_src }); $('#jquery_jplayer_1').jPlayer("play"); }; function playAudio2(mp32, ogg2) { var mp3_src = mp32; var oga_src = ogg2; $('#jquery_jplayer_1').jPlayer('setMedia', { oga: oga_src, mp3: mp3_src }); $('#jquery_jplayer_1').jPlayer("play"); }; function attachMouseEnter(mp31, ogg1, mp32, ogg2) { $('#ChoiceA').die('mouseenter.audio1event'); $('#ChoiceA').live('mouseenter.audio1event', function () { playAudio1(mp31, ogg1); }); $('#ChoiceB').die('mouseenter.audio2event'); $('#ChoiceB').live('mouseenter.audio2event', function () { playAudio2(mp32, ogg2); }); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T02:58:52.560", "Id": "7999", "Score": "5", "body": "I can't spot any difference between playAudio1 and playAudio2, so that's a pretty damp area." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T03:18:33.527", "Id": "8000", "Score": "2", "body": "I think this should be moved to Code Review SE..." } ]
[ { "body": "<p>Wouldn't you just remove playAudio2 and rename playAudio1 to playAudio, then in attachMouseEnter, just call playAudio both times.</p>\n\n<pre><code>function attachMouseEnter(mp31, ogg1, mp32, ogg2) {\n$('#ChoiceA').die('mouseenter.audio1event');\n$('#ChoiceA').live('mouseenter.audio1event', function () {\n playAudio(mp31, ogg1);\n});\n\n$('#ChoiceB').die('mouseenter.audio2event');\n$('#ChoiceB').live('mouseenter.audio2event', function () {\n playAudio(mp32, ogg2);\n});\n</code></pre>\n\n<p>Also I would make a function that took an id to attach to, the event name and then mp3, ogg params and then attachMouseEnter would just call this twice passing in the dif mp31, 2 etc</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T03:21:56.300", "Id": "5298", "ParentId": "5297", "Score": "2" } }, { "body": "<p>I think if you generalize the problem to having multiple choices instead of just 2, it would make things a lot simpler. It gives the added flexibility of adding more choices later on if needed, but most importantly, you can cut down explicit references to element A, or element B, or audio A, or audio B, throughout your codebase.</p>\n\n<p>Doing so would mean that you tweak the HTML slightly, and instead of referring to DOM elements directly by their id such as <code>choiceA</code>, or <code>choiceB</code>, you rely on their position or index. The HTML of all choices may then look something like,</p>\n\n<pre><code>&lt;ul&gt;\n &lt;li class=\"choice\"&gt;..&lt;/li&gt;\n &lt;li class=\"choice\"&gt;..&lt;/li&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Keeping that in mind, here are the changes I would suggest. Create an object that represents an audio to avoid worrying about passing mp3/ogg variables all over.</p>\n\n<pre><code>function AudioFile(fileName) {\n var root = \"../../Content/Audio/\";\n this.mp3 = root + fileName + '.mp3';\n this.ogg = root + fileName + '.ogg';\n}\n</code></pre>\n\n<p>Your <code>playAudio1</code> and <code>playAudio2</code> functions are identical. They can accept the <code>AudioFile</code> object, and be combined into one.</p>\n\n<pre><code>function playAudio(audio) {\n var player = $('#jquery_jplayer');\n player.jPlayer('setMedia', {\n oga: audio.ogg,\n mp3: audio.mp3\n });\n player.jPlayer('play');\n}\n</code></pre>\n\n<p>By getting away from two choices, you can treat the number of choices as an array, and attach the required event handler for each item in the array alike. Also it seems like you are rebinding the <code>live</code> events after each AJAX call. That's just a waste of resources. You could explicitly <code>bind</code> after each AJAX call, or attach <code>live</code> handlers on document load or something. Here's the revamped <code>getNewWords</code> and <code>attachMouseEnter</code> methods.</p>\n\n<pre><code>function getNewWords() {\n var Category = \"animals\";\n var BaseURL = \"http://localhost:61741/VocabGame/play?cat=\";\n var URL = BaseURL + Category;\n\n $.getJSON(URL, didGetNewWords);\n\n var containers = $('.choice');\n\n function didGetNewWords(data) {\n data.nouns.forEach(function(noun, index) {\n var container = containers.get(index);\n container.html(noun.Pinyin);\n var audio = new AudioFile(noun.Audio1);\n attachMouseEnter(container, audio);\n });\n\n // Pick a random answer by index\n var answerIndex = Math.floor(Math.random() * data.nouns.length);\n correctAnswer = containers.get(answerIndex).id;\n Search(data.nouns[answerIndex].English);\n }\n}\n\n// Play this audio when this element is hovered over\nfunction attachMouseEnter(element, audio) {\n $(element).bind('mouseenter', function() {\n playAudio(audio);\n });\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T05:00:13.577", "Id": "8002", "Score": "0", "body": "Glad you found it useful. I like @pllee's suggestion about passing the params to the `getNewWords` function as that makes things much more customizable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T03:54:15.737", "Id": "5299", "ParentId": "5297", "Score": "5" } }, { "body": "<p>As mentioned the playAudo functions do the same thing. I don't know any JQuery so correct me if I am wrong but I think something like this is a little more flexible :</p>\n\n<pre><code> function getNewWords(categoryName, categoryValue) {\n\n var baseURL = \"http://localhost:61741/VocabGame/play\", data = {};\n data[categoryName] = categoryValue;\n\n $.post(baseUrl, data,\n function(data, textStatus, jqXHR){\n //process json\n }, \n \"json\");\n }\n\n getNewWords('animals', 'cat')\n</code></pre>\n\n<p>Let JQuery handle all of the parameter logic and prepare for taking in all kinds of data (dogs, cows .etc :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T04:12:51.623", "Id": "5300", "ParentId": "5297", "Score": "1" } } ]
{ "AcceptedAnswerId": "5299", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T02:50:51.297", "Id": "5297", "Score": "5", "Tags": [ "javascript", "jquery", "quiz" ], "Title": "Simple language quiz" }
5297
<p>I am using the following code to add nodes in a treeview. Is there a better or more compact way of doing this by using LINQ?<br /></p> <pre><code>foreach (Plan plan in this.IncomingPlan.Plans) { foreach (Document doc in plan.Documents.Where(d =&gt; d.Name.Equals(this.DocumentName, StringComparison.OrdinalIgnoreCase))) { foreach (Author author in doc.Authors) { TreeNode treeNode = new TreeNode() { Text = author.Name, Type = NodeType.ParentNode, Tag = author }; foreach (Book book in author.Books) { treeNode.Nodes.Add(new TreeNode() { Text = book.Name, Type = NodeType.ChildNode, Tag = book }); } this.treeView.Nodes.Add(treeNode); } } } </code></pre>
[]
[ { "body": "<p>Looks perfectly fine to me. That's the first time I've looked at your code and I was able to see quickly what it does.</p>\n\n<p>There is no need to overly-compact things if it is going to make it a pain for someone else to understand in future.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T08:28:32.233", "Id": "8074", "Score": "0", "body": "**four** nested foreach loops doesn't look that great! This is a good example of the arrowhead anti-pattern" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T05:45:19.003", "Id": "8152", "Score": "0", "body": "@MattDavey, I was also concerned about the nested loops that's why I asked the question :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T13:26:56.360", "Id": "5302", "ParentId": "5301", "Score": "4" } }, { "body": "<p>You can make this more maintainable and more compact by utilizing LINQ here. I'm not sure what <code>TreeNode</code> is in your code, I'm guessing you derived from a WinForms <code>TreeNode</code>.</p>\n\n<p>I'd argue that the node's <code>Type</code> is unnecessary. You can easily determine that if you look at its <code>Level</code>. Level <code>0</code> indicates it is at the root of the tree, otherwise it is greater than 0.</p>\n\n<p>Unfortunately there's no nice way to add a range of nodes to another. You could only add arrays of the nodes. Using a loop would be the best option.</p>\n\n<p>Here, I would flatten the nested loops as far as I can then loop through to add them to the tree. To compact it even more, create a factory method to create the nodes. Even more useful if you have a lot of properties to set.</p>\n\n<pre><code>// create the node for the item\nstatic TreeNode CreateNode&lt;T&gt;(T item, Func&lt;T, string&gt; textSelector)\n{\n return new TreeNode { Text = textSelector(item), Tag = item };\n}\n\nvar authors =\n from plan in this.IncomingPlan.Plans\n from doc in plan.Documents\n where doc.Name.Equals(this.DocumentName, StringComparison.OrdinalIgnoreCase)\n from author in doc.Authors\n select author;\n\nforeach (var author in authors)\n{\n var authorNode = CreateNode(author, a =&gt; a.Name);\n\n foreach (var book in author.Books)\n {\n authorNode.Nodes.Add(CreateNode(book, b =&gt; b.Name));\n }\n\n treeView.Nodes.Add(authorNode);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T08:27:11.003", "Id": "8073", "Score": "0", "body": "Might be handy to write an extension method on TreeNodeCollection which allows you to add an IEnumerable<TreeNode>. It would still loop under the hood but that detail would be abstracted from you :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T08:32:02.837", "Id": "8075", "Score": "0", "body": "I'd also a method BookToTreeNode(Book b) which could be used in a linq projection -- authorNode.Nodes.Add(author.Books.Select(BookToTreeNode))" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T09:45:24.400", "Id": "8082", "Score": "0", "body": "I thought about that at first but decided it is better to not create extension methods for that purpose. It's too bad not all collections support adding ranges (`IEnumerable<T>` in particular) of items but I don't see the compelling need to write an extension method to do so either as it's not something that is needed too often." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T21:00:39.290", "Id": "5312", "ParentId": "5301", "Score": "2" } } ]
{ "AcceptedAnswerId": "5312", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T11:43:44.287", "Id": "5301", "Score": "4", "Tags": [ "c#", "linq" ], "Title": "Is there a better or more compact way of adding items in treeview using LINQ?" }
5301
<p>I'm working on a small project that does mathematical calculations based on selected data in a JTable. The goal is to make the program fairly adaptable for adding new mathematical calculations in the future. For reference, some of the current calculations are: calculating the mean (average) of a set of data; calculating the percentile of each item in a set of input data; calculating the least squares linear regression (best fit linear function) for a set of data points.</p> <p>My current design thought process is that to make things the math utilities flexible, there needs to be a some type of base class for analysis data that serves as input and output to some type of <code>performAnalysis</code> function in a base class for all analysis classes. This lead me to a skeleton design as follows:</p> <pre><code>public enum AnalysisDataType { Scalar, Set, Map } public interface IAnalysisData { AnalysisDataType getType(); } public interface IAnalaysisDataScalar extends IAnalysisData { double getValue(); } public interface IAnalaysisDataSet extends IAnalysisData { int getCount(); IAnalysisData getData(int index); } public interface IAnalaysisDataMap extends IAnalysisData { IAnalysisData getDomain(); IAnalysisData getCodomain(); } public interface IDataAnalysis { AnalysisDataType getInputDataType(); AnalysisDataType getOutputDataType(); IAnalysisData performAnalysis(IAnalysisData inputData); } </code></pre> <p>Then, something for calculating <code>mean</code> would be:</p> <pre><code>public class DataAnalysisMean implements IDataAnalysis { AnalysisDataType getInputDataType() { return AnalysisDataType.Set; } AnalysisDataType getInputDataType() { return AnalysisDataType.Scalar; } IAnalysisData performAnalysis(IAnalysisData intputData) { IAnalysisDataSet inputDataSet = (IAnalysisDataSet)inputData; double sum = 0; for (int i = 0; i &lt; inputDataSet.getCount(); i++) { IAnalysisData dataItem = inputDataSet.getData(i); IAnalysisDataScalar dataItem = (IAnalysisDataScalar)dataItem; sum += dataItem.getValue(); } return new IAnalysisDataScalar() { @Override double getValue() { return sum / inputDataSet.getCount(); } @Override AnalysisDataType getType() { return AnalysisDataType.Scalar; } }; } } </code></pre> <p>I realize a little more work needs to go into "describing" the input and output data items because no where did I mention that the input set contained scalars, but - while I already have an idea how to solve that one - I feel that the whole approach is hackish.</p> <p>The thought behind this approach is that the code using interfacing with these math utilities could query the <code>IDataAnalysis</code> interface to determine what the expected input and output is and can send the appropriate input as needed and parse the results appropriately. This would allow us to just need to drop-in more functionality at a later time without having to add additional controller logic to tie it in.</p> <p>I feel like its wrong for a parent class - or interface in this case - to know about its possible children classes (interfaces) through the <code>AnalysisDataType</code> enum and the <code>getType</code> method. As always with OO programming, surely just another layer of abstraction or some type is needed, though perhaps I'm just missing out on some other design pattern that solves this exact problem.</p> <p>Anyway, if anyone has advice on what I might do to better organize this, I'd much appreciate it. I'd love to hear how wrong my thoughts are and learn a better way.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T14:21:05.890", "Id": "8003", "Score": "0", "body": "Are you coming from a .net background? You might want to look at the [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T14:59:35.497", "Id": "8005", "Score": "0", "body": "Most recently, yes. My question isn't on style as it is on design. I just happen to be using Java, but I think the problem still arises if I were to do the same thing in C#, C++, or another object oriented language." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T15:01:06.870", "Id": "8006", "Score": "0", "body": "That's why I only wrote a comment. Personally I think we should obey the local rules of a language, even if we're just passing through. But as I said, that's a mere comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T15:02:16.993", "Id": "8007", "Score": "0", "body": "True, I'm planning on reading through the document, thanks for the link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T19:51:24.467", "Id": "8011", "Score": "0", "body": "@Bobby: Just out of curiosity, what (if any) about the code in particular would be going against Java's conventions? I'm a bit biased toward .NET but the only thing that I could identify probably would be the added `I` for the interface names. I know it's a common .NET convention and not in Java but it works well for differentiating interfaces and classes. Something I wish Java had adopted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T20:04:23.187", "Id": "8012", "Score": "0", "body": "@JeffMercado: Additionally, Enum-Members should be all caps (they're same class citizens as Constants as far as I know)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T15:31:34.913", "Id": "8051", "Score": "0", "body": "@Bobby, java has no constants per se. Enums are just `static final Object` for most of the part, save serialization and proxying. As for code style, it's a company policy what to adopt. Even big companies still user underscore or m_ for fields in java. While, I don't like that, it's none of my business." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T15:33:14.147", "Id": "8052", "Score": "0", "body": "@Anthony, you can implement the logic in the enum itself by introducing an abstract method and override it. The enum constants are subclass of the base enum if there is a method overriden." } ]
[ { "body": "<p>First, I get some error messages when I put this in the compiler.\nI had to replace the anonymous inner class that is returned by <code>performAnalysis</code> with a helper class. I'm <em>not</em> a fan of helper classes like this, so it would be nice if someone else had a better idea.</p>\n\n<p>Second, I'm thinking generics would solve this quite nicely.\nI agree that the parent class should not need to know it's child classes, but it can obtain this data; see the methods that I have commented out. I have commented them out because I don't like them, but still want to show that it's possible. I'll admit that using <code>.class</code> is a bit tricky when using generics, because of type erasure. However, as long as the generic types are known at compile time, this should not be a problem.</p>\n\n<pre><code>interface IDataAnalysis&lt;InputType extends IAnalysisData, OutputType extends IAnalysisData&gt; {\n\n// public Class&lt;?&gt; getInputDataType( );\n// public Class&lt;?&gt; getOutputDataType( );\n\n OutputType performAnalysis(InputType inputData);\n}\n\npublic class DataAnalysisMean implements IDataAnalysis&lt;IAnalysisDataSet, IAnalysisDataScalar&gt; {\n\n// \n// public Class&lt;?&gt; getInputDataType( ) { return IAnalysisDataSet.class; }\n// public Class&lt;?&gt; getOutputDataType( ) { return IAnalysisDataScalar.class; }\n\npublic IAnalysisDataScalar performAnalysis(IAnalysisDataSet inputData) {\n\n IAnalysisDataSet inputDataSet = (IAnalysisDataSet)inputData;\n double sum = 0;\n\n for (int i = 0; i &lt; inputDataSet.getCount(); i++) {\n IAnalysisData dataItem = inputDataSet.getData(i);\n IAnalysisDataScalar dataItem2 = (IAnalysisDataScalar)dataItem;\n sum += dataItem2.getValue();\n }\n\n return new HelperClass( inputDataSet, sum );\n}\n\nprivate class HelperClass implements IAnalysisDataScalar\n{\n IAnalysisDataSet inputDataSet;\n double sum = 0;\n\n HelperClass( IAnalysisDataSet inputSet, double sum )\n {\n this.inputDataSet = inputSet;\n this.sum = sum; \n }\n\n @Override\n public double getValue() {\n return sum / inputDataSet.getCount();\n }\n\n @Override\n public AnalysisDataType getType() {\n return AnalysisDataType.Scalar;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T13:18:25.877", "Id": "8022", "Score": "0", "body": "That's odd, but not surprising. I don't have a Java IDE in front of me so I was writing the code from pure memory. The idea of templates came to me a little after I posted. I'll play around with the code you provided and see if I can make sense of it (more used to C++ templates and C# style generics than Java)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T16:22:32.547", "Id": "8025", "Score": "0", "body": "There are some subtle differences between C# generics and Java generics, but it shouldn´t be a problem here. Regarding the helper class, it was needed because Java does not support closures. I realized later that there is (probably) no reason to do the division inside the class, so you could use a default implementation of IAnalysisDataScalar to simply wrap the result of the calculation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T08:32:26.483", "Id": "5318", "ParentId": "5303", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T13:27:13.813", "Id": "5303", "Score": "4", "Tags": [ "java" ], "Title": "Super class knowing the type of its children? Surely there is a better way" }
5303
<p>With a <code>DateTime</code> object, it's easy to get, for example, <strong>11 October 2011</strong> by using:</p> <pre><code>d.ToString("d MMMM yyyy"); </code></pre> <p>However, there seems to be no built-in method to get the output <strong>11th October 2011</strong>.</p> <p>So here's a possible extension method.</p> <pre><code>public string ToStringWithOrdinal(this DateTime d) { var sb = new StringBuilder(d.Day); switch (d.Day) { case 1: case 21: case 31: sb.Append("st"); break; case 2: case 22: sb.Append("nd"); break; case 3: case 23: sb.Append("rd"); break; default: sb.Append("th"); break; } sb.Append(" ").Append(d.ToString("MMMM yyyy")); return sb.ToString(); } </code></pre> <p>Can anyone think of any improvements, either to performance or to add functionality for a <code>format</code> parameter, so we can call e.g. <code>d.ToStringWithOrdinal("d^ MMMM");</code>?</p> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T19:08:54.800", "Id": "8010", "Score": "2", "body": "Don't be lured by the false sense of security that using a string builder gives you here. It's only useful if you're really going to be adding a lot of different strings to it. Otherwise it just makes your code more complicated than it has to be. String concatenation really would be the best thing to use for your example in this case. (and by that, I mean, return the full concatenated result, not `str = day; str += \"st\"; ...` but `return day + \"st \" + ...`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-14T08:45:17.270", "Id": "8076", "Score": "0", "body": "@Jeff Mercado +1, I've seen a lot of different suggestions but the general consensus is that it's only worth using a StringBuilder if you're doing 10+ concats.." } ]
[ { "body": "<p>You can simplify it a bit and make a trivial improvement to performance <em>(this will be noticeable if you call this method a lot)</em>.</p>\n\n<pre><code>public static string ToStringWithOrdinal(this DateTime d) {\n switch (d.Day) {\n case 1: case 21: case 31:\n return d.ToString(\"dd'st' MMMM yyyy\");\n case 2: case 22:\n return d.ToString(\"dd'nd' MMMM yyyy\");\n case 3: case 23:\n return d.ToString(\"dd'rd' MMMM yyyy\");\n default:\n return d.ToString(\"dd'th' MMMM yyyy\");\n }\n}\n</code></pre>\n\n<p>As a side note this format doesn't read well to me. Normally I would write it as follows:</p>\n\n<blockquote>\n <p>October 11th 2011</p>\n</blockquote>\n\n<p>Is this format common in the UK?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T18:29:03.617", "Id": "8009", "Score": "0", "body": "Yeah in the UK we normally put the day first. ;) Thanks for your amendment, that is better." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T18:08:36.717", "Id": "5310", "ParentId": "5304", "Score": "5" } } ]
{ "AcceptedAnswerId": "5310", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T14:40:53.427", "Id": "5304", "Score": "5", "Tags": [ "c#", ".net", "strings", "extension-methods" ], "Title": "Convert .NET DateTime to a string using ordinals" }
5304
<p>I've only been coding C# a few weeks and was just hoping for a little constructive criticism of a socket server I've been working on:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; namespace NetworkCommunication { public class TCPSocketServer : IDisposable { private int portNumber; private int connectionsLimit; private Socket connectionSocket; private List&lt;StateObject&gt; connectedClients = new List&lt;StateObject&gt;(); public event SocketConnectedHandler ClientConnected; public delegate void SocketConnectedHandler(TCPSocketServer socketServer, SocketConnectArgs e); public event SocketMessageReceivedHandler MessageReceived; public delegate void SocketMessageReceivedHandler(TCPSocketServer socketServer, SocketMessageReceivedArgs e); public event SocketClosedHandler ClientDisconnected; public delegate void SocketClosedHandler(TCPSocketServer socketServer, SocketEventArgs e); #region Constructors public TCPSocketServer(int PortNumber) : this(PortNumber, 0) { } public TCPSocketServer(int PortNumber, int ConnectionsLimit) { this.portNumber = PortNumber; this.connectionsLimit = ConnectionsLimit; startListening(); } #endregion #region Send Messages public void SendMessage(string MessageToSend, int clientID) { try { byte[] byData = System.Text.Encoding.UTF8.GetBytes(MessageToSend + "\0"); foreach (StateObject client in connectedClients) { if (clientID == client.id) { // Send message on correct client if (client.socket.Connected) { client.socket.Send(byData); } break; } } } catch (SocketException) { } } public void SendMessage(byte[] MessageToSend, int clientID) { try { foreach (StateObject client in connectedClients) { if (clientID == client.id) { // Send message on correct client if (client.socket.Connected) { client.socket.Send(MessageToSend); } break; } } } catch (SocketException) { } } #endregion #region Connection and Listening private void startListening() { try { // Create listening socket connectionSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); connectionSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, this.portNumber); // Bind to local IP Address connectionSocket.Bind(ipLocal); // Start Listening connectionSocket.Listen(1000); // Creat callback to handle client connections connectionSocket.BeginAccept(new AsyncCallback(onClientConnect), null); } catch (SocketException) { } } private void onClientConnect(IAsyncResult asyn) { try { // Create a new StateObject to hold the connected client StateObject connectedClient = new StateObject(); connectedClient.socket = connectionSocket.EndAccept(asyn); if (connectedClients.Count == 0) { connectedClient.id = 1; } else { connectedClient.id = connectedClients[connectedClients.Count - 1].id + 1; } connectedClients.Add(connectedClient); // Check against limit if (connectedClients.Count &gt; connectionsLimit) { // No connection event is sent so close socket silently closeSocketSilent(connectedClient.id); return; } // Dispatch Event if (ClientConnected != null) { SocketConnectArgs args = new SocketConnectArgs(); args.ConnectedIP = IPAddress.Parse(((IPEndPoint)connectedClient.socket.RemoteEndPoint).Address.ToString()); args.clientID = connectedClient.id; ClientConnected(this, args); } // Release connectionSocket to keep listening if limit is not reached connectionSocket.BeginAccept(new AsyncCallback(onClientConnect), null); // Allow connected client to receive data and designate a callback method connectedClient.socket.BeginReceive(connectedClient.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(onReceivedClientData), connectedClient); } catch (SocketException) { } catch (ObjectDisposedException) { } } private void onReceivedClientData(IAsyncResult asyn) { String content = String.Empty; // Receive stateobject of the client that sent data StateObject dataSender = (StateObject)asyn.AsyncState; try { // Complete aysnc receive method and read data length int bytesRead = dataSender.socket.EndReceive(asyn); if (bytesRead &gt; 0) { // More data could be sent so append data received so far dataSender.sb.Append(Encoding.UTF8.GetString(dataSender.buffer, 0, bytesRead)); content = dataSender.sb.ToString(); if ((content.Length &gt; 0) || (content.IndexOf("") &gt; -1)) { String formattedMessage = String.Empty; formattedMessage += content.Replace("\0", ""); // Dispatch Event if (MessageReceived != null) { SocketMessageReceivedArgs args = new SocketMessageReceivedArgs(); args.MessageContent = formattedMessage; args.clientID = dataSender.id; MessageReceived(this, args); } dataSender.sb.Length = 0; } try { dataSender.socket.BeginReceive(dataSender.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(this.onReceivedClientData), dataSender); } catch (SocketException) { } } else { closeSocket(dataSender.id); } } catch (SocketException) { } catch (ObjectDisposedException) { } } #endregion #region Socket Closing public void closeSocket(int SocketID) { foreach (StateObject client in connectedClients.ToList()) { try { if (SocketID == client.id) { client.socket.Close(); client.socket.Dispose(); // Dispatch Event if (ClientDisconnected != null) { SocketEventArgs args = new SocketEventArgs(); args.clientID = client.id; ClientDisconnected(this, args); } connectedClients.Remove(client); break; } } catch (SocketException) { } } } // This does not dispatch an event, this task is to be used when rejecting connections past the limit. // No connection event is sent so no disconnection event should be sent. private void closeSocketSilent(int SocketID) { foreach (StateObject client in connectedClients.ToList()) { if (SocketID == client.id) { try { client.socket.Close(); client.socket.Dispose(); connectedClients.Remove(client); break; } catch (SocketException) { } } } } public void closeAllSockets() { foreach (StateObject client in connectedClients.ToList()) { closeSocket(client.id); } } #endregion public void Dispose() { this.ClientConnected = null; this.ClientDisconnected = null; this.MessageReceived = null; connectionSocket.Close(); } } } </code></pre> <p>Here's a new updated version with the help I was given kindly below. I've added error handling and moved some parts around:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Net; namespace NetworkCommunication { public class TCPSocketServer : IDisposable { private const int MaxLengthOfPendingConnectionsQueue = 1000; private int portNumber; private int connectionsLimit; private Socket connectionSocket; private Dictionary&lt;int, StateObject&gt; connectedClients = new Dictionary&lt;int, StateObject&gt;(); public event SocketConnectedHandler ClientConnected; public delegate void SocketConnectedHandler(TCPSocketServer socketServer, SocketConnectArgs e); public event SocketMessageReceivedHandler MessageReceived; public delegate void SocketMessageReceivedHandler(TCPSocketServer socketServer, SocketMessageReceivedArgs e); public event SocketClosedHandler ClientDisconnected; public delegate void SocketClosedHandler(TCPSocketServer socketServer, SocketEventArgs e); #region Constructor public TCPSocketServer(int PortNumber, int ConnectionsLimit = 0) { // Validate Port Number if (PortNumber &gt; 0 &amp;&amp; PortNumber &lt; 65536) { this.portNumber = PortNumber; } else { throw new InvalidPortNumberException("Ports number must be in the 1-65535 range. Note: 256 and bellow are normally reserved."); } this.connectionsLimit = ConnectionsLimit; startListening(); } #endregion private StateObject GetClient(int clientId) { StateObject client; if (!connectedClients.TryGetValue(clientId, out client)) { return null; } return client; } #region Send Messages public void SendMessage(string MessageToSend, int clientID) { byte[] data = System.Text.Encoding.UTF8.GetBytes(MessageToSend + "\0"); SendMessage(data, clientID); } public void SendMessage(byte[] MessageToSend, int clientID) { StateObject client = GetClient(clientID); if (client != null) { try { if (client.socket.Connected) { client.socket.Send(MessageToSend); } } catch (SocketException) { // Close socket closeSocket(clientID); } } } #endregion #region Connection and Listening private void startListening() { try { // Create listening socket connectionSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); connectionSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, this.portNumber); // Bind to local IP Address connectionSocket.Bind(ipLocal); // Start Listening connectionSocket.Listen(MaxLengthOfPendingConnectionsQueue); // Create callback to handle client connections connectionSocket.BeginAccept(new AsyncCallback(onClientConnect), null); } catch (SocketException) { throw new SocketCannotListenException("Cannot listen on this socket. Fatal Error"); } } private void onClientConnect(IAsyncResult asyn) { // Create a new StateObject to hold the connected client StateObject connectedClient = new StateObject(); try { connectedClient.socket = connectionSocket.EndAccept(asyn); connectedClient.id = !connectedClients.Any() ? 1 : connectedClients.Keys.Max() + 1; connectedClients.Add(connectedClient.id, connectedClient); // Check against limit if (connectedClients.Count &gt; connectionsLimit &amp;&amp; connectionsLimit != 0) { // No connection event is sent so close connection quietly closeSocket(connectedClient.id, true); return; } // Allow connected client to receive data and designate a callback method connectedClient.socket.BeginReceive(connectedClient.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(onReceivedClientData), connectedClient); } catch (Exception) { closeSocket(connectedClient.id, true); } finally { // Perfomed here to not get any exceptions on the main socket caught up in client connection errors. ReleaseConnectionSocket(); } // Dispatch Event at the end as any errors in socket dispatch silent diconnections if (ClientConnected != null) { SocketConnectArgs args = new SocketConnectArgs() { ConnectedIP = IPAddress.Parse(((IPEndPoint)connectedClient.socket.RemoteEndPoint).Address.ToString()), clientID = connectedClient.id }; ClientConnected(this, args); } } private void ReleaseConnectionSocket() { try { // Release connectionSocket to keep listening connectionSocket.BeginAccept(new AsyncCallback(onClientConnect), null); } catch (SocketException) { throw new SocketCannotListenException("Cannot listen on the main socket. Fatal Error"); } } private void onReceivedClientData(IAsyncResult asyn) { // Receive stateobject of the client that sent data StateObject dataSender = (StateObject)asyn.AsyncState; try { // Complete aysnc receive method and read data length int bytesRead = dataSender.socket.EndReceive(asyn); if (bytesRead &gt; 0) { // More data could be sent so append data received so far dataSender.sb.Append(Encoding.UTF8.GetString(dataSender.buffer, 0, bytesRead)); String content = dataSender.sb.ToString(); if (!string.IsNullOrEmpty(content)) { String formattedMessage = content.Replace("\0", ""); // Dispatch Event if (MessageReceived != null) { SocketMessageReceivedArgs args = new SocketMessageReceivedArgs() { MessageContent = formattedMessage, clientID = dataSender.id }; MessageReceived(this, args); } dataSender.sb.Clear(); } try { dataSender.socket.BeginReceive(dataSender.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(this.onReceivedClientData), dataSender); } catch (SocketException) { closeSocket(dataSender.id); } } else { closeSocket(dataSender.id); } } catch (SocketException ex) { // Socket closed at other end if (ex.ErrorCode == 10054) { closeSocket(dataSender.id); } else { closeSocket(dataSender.id); } } } #endregion #region Socket Closing public void closeSocket(int SocketID) { closeSocket(SocketID, false); } // This does not dispatch an event, this task is to be used when rejecting connections past the limit. // No connection event is sent so no disconnection event should be sent. private void closeSocket(int SocketId, bool silent) { StateObject client = GetClient(SocketId); if (client == null) { return; } try { client.socket.Close(); client.socket.Dispose(); if (!silent) { // Dispatch event if (ClientDisconnected != null) { SocketEventArgs args = new SocketEventArgs() { clientID = client.id }; ClientDisconnected(this, args); } } } catch (SocketException) { // Socket is being removed anyway. } finally { connectedClients.Remove(client.id); } } public void closeAllSockets() { var keys = connectedClients.Keys; foreach (int key in keys) { var client = connectedClients[key]; closeSocket(client.id); } } #endregion public void Dispose() { this.ClientConnected = null; this.ClientDisconnected = null; this.MessageReceived = null; connectionSocket.Close(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-29T21:24:52.443", "Id": "159991", "Score": "0", "body": "I'm interested in your async implementation, can you share the client code and eventArgs code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-04T07:57:25.970", "Id": "189399", "Score": "0", "body": "When `EndReceive` returns 0 and you have no more data to send, perhaps you should execute `Shutdown` as part of the graceful termination of the socket connection (https://msdn.microsoft.com/en-us/library/windows/desktop/ms738547(v=vs.85).aspx)." } ]
[ { "body": "<p>My biggest concern is your excessive use of empty try statements. You should either handle any <code>SocketException</code> that may be thrown or let them propagate. As it stands I would not consider this production ready code. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T17:00:46.203", "Id": "8008", "Score": "0", "body": "I have more thoughts which I will add at a convenient time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T10:10:45.073", "Id": "8048", "Score": "0", "body": "I'd love to hear them. I think handling errors is one of my weakest areas." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T16:56:53.867", "Id": "5308", "ParentId": "5306", "Score": "3" } }, { "body": "<p>Your event handling is a bit non-standard. Rather than:</p>\n\n<pre><code>public event SocketConnectedHandler ClientConnected;\npublic delegate void SocketConnectedHandler(TCPSocketServer socketServer, SocketConnectArgs e);\n</code></pre>\n\n<p>it would be more usual (and hence less surprising) to have:</p>\n\n<pre><code>public event EventHandler&lt;SocketConnectArgs&gt; ClientConnected;\n</code></pre>\n\n<p>The downside of the more usual approach, of course, is that you have to cast the <code>object sender</code> to <code>TCPSocketServer</code>, so there's a tradeoff.</p>\n\n<hr />\n\n<p>The way you're using <code>connectedClients</code> indicates that you've got the type wrong. In almost all accesses you're iterating through it checking the elements to see whether their <code>id</code> matches a value. That suggests that it should be an <code>IDictionary&lt;int, StateObject&gt;</code>, or that you should pass the <code>StateObject</code> around rather than the <code>id</code>. You might also need to synchronise access to it - I haven't nailed down whether it's possible for it to be accessed by more than one thread.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T14:08:27.030", "Id": "8961", "Score": "0", "body": "I was just commenting on the container choice myself. It seemed to me that the way that id is assigned makes it equivalent to the items index in the `List` + 1, so you should be able to get the item with just connectedClients[id-1]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T14:11:42.800", "Id": "8963", "Score": "0", "body": "@pstrjds, no, because stuff gets deleted from the list. Although this does mean that it's possible for ids to be reused, which is probably a bug." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T14:15:42.233", "Id": "8964", "Score": "0", "body": "that was my bad, I didn't notice the delete in the close call. I assumed they weren't being removed and missed that little line, and it would could lead to confusion if the ID was reused." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T13:59:07.400", "Id": "5891", "ParentId": "5306", "Score": "6" } }, { "body": "<p>I just noticed this question is a couple weeks old, but never-the-less I will add my two cents.\nI would have your <code>SendMessage</code> overload that takes a string perform the byte conversion that it is doing, but instead of each <code>SendMessage</code> duplicating the code that is walking a list looking for an open connection, I would have the <code>SendMessage</code> with the string just call into the <code>SendMessage</code> that takes a <code>byte[]</code></p>\n\n<pre><code>public void SendMessage(string MessageToSend, int clientID)\n{\n byte[] byData = System.Text.Encoding.UTF8.GetBytes(MessageToSend + \"\\0\");\n SendMessage(byData, clientID);\n}\n\npublic void SendMessage(byte[] MessageToSend, int clientID)\n{\n try\n {\n foreach (StateObject client in connectedClients)\n {\n if (clientID == client.id)\n {\n // Send message on correct client\n if (client.socket.Connected)\n {\n client.socket.Send(MessageToSend);\n }\n break;\n }\n }\n }\n catch (SocketException) { }\n}\n</code></pre>\n\n<p>The code seems a little odd where the new connections are coming in. If you have reached the limit of connections you are going to handle you close the socket that you created and just return. It seems like you could check the limit first and return without doing any of the work to create the state object, add to the list, then check the limit and remove from the list.</p>\n\n<p>Lastly, consider not looping through all connected clients in each method that takes a clientID. You could make your container a <code>Dictionary&lt;int, StateObject&gt;</code> so you can just use the clientID to get the object without walking the list.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T17:00:44.727", "Id": "8984", "Score": "0", "body": "Very nice suggestion, on the dictionary." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T14:06:12.557", "Id": "5893", "ParentId": "5306", "Score": "3" } }, { "body": "<p><strong>I will not comment on the actual TCP functionality itself.</strong><br>\nI am not competent for that.</p>\n\n<h2>Stopping broadcast - on purpose?</h2>\n\n<p>When you are broadcasting to the clients in <code>SendMessage()</code>, it seems like you stop broadcasting if you get problems reaching one of the clients. Is this intended?<br>\nI would move the try/catch inside the foreach, and around the if. Then, in the <code>catch</code>, I would either explicitly <code>break;</code> out of the foreach or leave a comment like <code>// Don't care, ignore and proceed.</code></p>\n\n<h2>Empty try-catches</h2>\n\n<p>As @ChaosPandion suggested, I would not leave empty try-catches.<br>\nI would either handle them, try to refactor the code as not to throw them, or leave a comment with a quick explanation.</p>\n\n<h2>Succinct code</h2>\n\n<p>If you are using C#4.0, I would write the default values like this:</p>\n\n<pre><code> #region Constructors\n // This behaves the same as the other version with two constructors.\n public TCPSocketServer(int PortNumber, int ConnectionsLimit = 0)\n {\n</code></pre>\n\n<h2>Parameters - case</h2>\n\n<p>You use camelCase for local variables, which agrees to what I think is the de facto convention.<br>\nIt seems you use PascalCase for parameters. Shouldn't that be camelCase instead, same as local variables?</p>\n\n<h2>Hungarian notation</h2>\n\n<p>I would avoid <a href=\"http://en.wikipedia.org/wiki/Hungarian_notation\">Hungarian notation</a>.<br>\nI have no real suggestion for <code>byte[] byData</code> though. Maybe just <code>data</code>? <code>encodedData</code>?</p>\n\n<h2>Code duplication</h2>\n\n<p>Code duplication is recipe for disaster. You will update one of the code sections and not the other, and so on...</p>\n\n<p>So I would suggest that the first <code>SendMessage</code> just reuses the second:</p>\n\n<pre><code>public void SendMessage(string MessageToSend, int clientID)\n{\n byte[] data = System.Text.Encoding.UTF8.GetBytes(MessageToSend + \"\\0\");\n SendMessage(data, clientID);\n}\n</code></pre>\n\n<h2>Magic numbers</h2>\n\n<p>I would extract this number to a constant somewhere, and name it appropriately. <code>SocketListenTimeoutMillisec</code>?</p>\n\n<pre><code>// Start Listening\nconnectionSocket.Listen(1000);\n</code></pre>\n\n<h2>Black magic</h2>\n\n<p>People got <a href=\"http://en.wikipedia.org/wiki/Dunking\">dunked</a> for much less than this. :)</p>\n\n<pre><code>content.IndexOf(\"\") &gt; -1\n</code></pre>\n\n<p>Does it do anything, considering that the string has <code>Length</code> > 0? Context:</p>\n\n<pre><code>content = dataSender.sb.ToString();\nif ((content.Length &gt; 0) || (content.IndexOf(\"\") &gt; -1))\n</code></pre>\n\n<h2>Succint code</h2>\n\n<pre><code>String formattedMessage = String.Empty;\nformattedMessage += content.Replace(\"\\0\", \"\");\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>String formattedMessage = content.Replace(\"\\0\", \"\");\n</code></pre>\n\n<h2>Var declarations closer to usage</h2>\n\n<pre><code>String content = String.Empty;\n</code></pre>\n\n<p>could move next to <code>content = dataSender.sb.ToString();</code>, and even be integrated into that line:</p>\n\n<pre><code>string content = dataSender.sb.ToString();\n</code></pre>\n\n<h2>Use StringBuilder better</h2>\n\n<pre><code>// instead of dataSender.sb.Length = 0;\ndataSender.sb.Clear();\n</code></pre>\n\n<h2>useless <code>.ToList()</code></h2>\n\n<pre><code> foreach (StateObject client in connectedClients.ToList())\n</code></pre>\n\n<h2>Linq makes code succint</h2>\n\n<pre><code>foreach (StateObject client in connectedClients.ToList()) {\n if (SocketID == client.id) {\n</code></pre>\n\n<p>can be replaced with</p>\n\n<pre><code>StateObject client = connectedClients.Where( conClient =&gt; conClient.id == SocketID );\nif( client != null ) {\n</code></pre>\n\n<h2>Object constructor</h2>\n\n<pre><code>// Parentheses are optional, if empty.\nSocketMessageReceivedArgs args = new SocketMessageReceivedArgs() {\n MessageContent = formattedMessage,\n clientID = dataSender.id\n};\n</code></pre>\n\n<p>And same for other similar property assignments immediately after the respective constructor.</p>\n\n<hr>\n\n<h1>My proposal of cleaner code</h1>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Net.Sockets;\nusing System.Text;\n\nnamespace NetworkCommunication\n{\n class StateObject { }\n class SocketConnectArgs { }\n class SocketMessageReceivedArgs { }\n class SocketEventArgs { }\n\n public class TCPSocketServer : IDisposable\n {\n // Or whatever the name.\n const int MaxLengthOfPendingConnectionsQueue = 1000;\n\n private int portNumber;\n private int connectionsLimit;\n private Socket connectionSocket;\n private Dictionary&lt;int, StateObject&gt; connectedClients = new Dictionary&lt;int, StateObject&gt;();\n\n public event SocketConnectedHandler ClientConnected;\n public delegate void SocketConnectedHandler(TCPSocketServer socketServer, SocketConnectArgs e);\n public event SocketMessageReceivedHandler MessageReceived;\n public delegate void SocketMessageReceivedHandler(TCPSocketServer socketServer, SocketMessageReceivedArgs e);\n public event SocketClosedHandler ClientDisconnected;\n public delegate void SocketClosedHandler(TCPSocketServer socketServer, SocketEventArgs e);\n\n #region Constructors\n public TCPSocketServer(int portNumber, int connectionsLimit = 0) {\n this.portNumber = portNumber;\n this.connectionsLimit = connectionsLimit;\n startListening();\n }\n #endregion\n\n private StateObject GetClient(int clientId) {\n StateObject client;\n if(!connectedClients.TryGetValue(clientId, out client)) {\n return null;\n }\n return client;\n }\n\n #region Send Messages\n public void SendMessage(string messageToSend, int clientID) {\n byte[] data = System.Text.Encoding.UTF8.GetBytes(messageToSend + \"\\0\");\n SendMessage(data, clientID);\n }\n\n public void SendMessage(byte[] messageToSend, int clientID) {\n StateObject client = GetClient(clientID);\n if (client != null) {\n try {\n if (client.socket.Connected) {\n client.socket.Send(messageToSend);\n }\n } catch (SocketException) {\n // TODO: sending failed; disconnect from client, or?\n }\n }\n }\n #endregion\n\n #region Connection and Listening\n private void startListening() {\n try {\n // Create listening socket\n connectionSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n connectionSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);\n IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, this.portNumber);\n // Bind to local IP Address\n connectionSocket.Bind(ipLocal);\n // Start Listening\n connectionSocket.Listen(MaxLengthOfPendingConnectionsQueue);\n // Creat callback to handle client connections\n connectionSocket.BeginAccept(new AsyncCallback(onClientConnect), null);\n } catch (SocketException) {\n // TODO: if we fail to start listening, is it even ok to continue?\n // Consider that some of the bootstrapping actions might not even have been done.\n // Thus execution will likely crash on next step.\n }\n }\n\n private void onClientConnect(IAsyncResult asyn) {\n try {\n // Create a new StateObject to hold the connected client\n StateObject connectedClient = new StateObject() {\n socket = connectionSocket.EndAccept(asyn),\n id = !connectedClients.Any() ? 1 : connectedClients.Keys.Max() + 1\n };\n\n connectedClients.Add(connectedClient);\n\n // TODO: consider if we can instead do this at the beginning of the method.\n // Check against limit\n if (connectedClients.Count &gt; connectionsLimit) {\n // No connection event is sent so close socket silently\n closeSocket(connectedClient.id, true);\n return;\n }\n\n // Dispatch Event\n if (ClientConnected != null) {\n SocketConnectArgs args = new SocketConnectArgs() {\n ConnectedIP = IPAddress.Parse(((IPEndPoint)connectedClient.socket.RemoteEndPoint).Address.ToString()),\n clientID = connectedClient.id\n };\n ClientConnected(this, args);\n }\n\n // Release connectionSocket to keep listening if limit is not reached\n connectionSocket.BeginAccept(new AsyncCallback(onClientConnect), null);\n\n // Allow connected client to receive data and designate a callback method\n connectedClient.socket.BeginReceive(connectedClient.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(onReceivedClientData), connectedClient);\n } catch (SocketException) {\n // TODO: should we closeSocketSilent()? Or?\n } catch (ObjectDisposedException) {\n // TODO: should we closeSocketSilent()? Or?\n }\n }\n\n private void onReceivedClientData(IAsyncResult asyn) {\n // Receive stateobject of the client that sent data\n StateObject dataSender = (StateObject)asyn.AsyncState;\n\n try {\n // Complete aysnc receive method and read data length\n int bytesRead = dataSender.socket.EndReceive(asyn);\n\n if (bytesRead &gt; 0) {\n // More data could be sent so append data received so far\n dataSender.sb.Append(Encoding.UTF8.GetString(dataSender.buffer, 0, bytesRead));\n if ( dataSender.sb.Length != 0\n &amp;&amp; MessageReceived != null\n ) {\n // TODO: is it possible that multiple messages are in the sb?\n // Consider whether it's necessary to replace with newline.\n dataSender.sb.Replace(\"\\0\", null); // Removes them.\n\n // Dispatch Event\n SocketMessageReceivedArgs args = new SocketMessageReceivedArgs();\n args.MessageContent = dataSender.sb.ToString();\n args.clientID = dataSender.id;\n MessageReceived(this, args);\n\n dataSender.sb.Clear();\n }\n try {\n dataSender.socket.BeginReceive(dataSender.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(this.onReceivedClientData), dataSender);\n } catch (SocketException) { }\n } else {\n closeSocket(dataSender.id);\n }\n } catch (SocketException) {\n // TODO: should we closeSocketSilent()? Or?\n } catch (ObjectDisposedException) {\n // TODO: should we closeSocketSilent()? Or?\n }\n }\n #endregion\n\n #region Socket Closing\n public void closeSocket(int socketID) {\n closeSocket(socketID, false);\n }\n\n /// &lt;param name=\"silent\"&gt;Whether to skip dispatching the disconnection event. Used to cancel the bootstrapping of the client-server connection.&lt;/param&gt;\n private void closeSocket(int socketID, bool silent) {\n StateObject client = GetClient(socketID);\n if (client == null) {\n return;\n }\n try {\n client.socket.Close();\n client.socket.Dispose();\n\n if(!silent) {\n // Dispatch Event\n if (ClientDisconnected != null) {\n SocketEventArgs args = new SocketEventArgs();\n args.clientID = client.id;\n ClientDisconnected(this, args);\n }\n }\n // Moved to finnaly block: connectedClients.Remove(client.id);\n } catch (SocketException) {\n // Don't care. Or?\n } finally {\n connectedClients.Remove(client.id);\n }\n }\n\n public void closeAllSockets() {\n var keys = connectedClients.Keys;\n foreach( int key in keys ) {\n var client = connectedClients[key];\n closeSocket(client.id);\n }\n }\n #endregion\n\n public void Dispose() {\n ClientConnected = null;\n ClientDisconnected = null;\n MessageReceived = null;\n\n connectionSocket.Close();\n }\n }\n}\n</code></pre>\n\n<p>PS: you owe me \"a beer\". :)<br>\n(This was fun to do, though!)</p>\n\n<p><strong>edit</strong>: camelCase for parameters; reduced code duplication; <code>Dictionary&lt;int, StateObject&gt;</code> instead of <code>List</code>; more object constructors.<br>\n<strong>edit2</strong>: <code>StringBuilder</code> methods as suggested by @pstrjds.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T17:28:51.337", "Id": "8989", "Score": "0", "body": "Nice job, there is still duplicate code in the close and closesilent, I feel like that could be handled with either adding a default parameter `bool silent = false` to the close method, or adding a private method that they both call and then the param just needs to be checked whether to raise the event and what to do with an exception." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-09T12:17:07.033", "Id": "9074", "Score": "0", "body": "Thanks. I've improved the answer a bit, using your comment and the great approaches from other answers. (I wonder if it would be polite, or constructive, to make the answer community wiki?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-09T13:00:06.560", "Id": "9075", "Score": "0", "body": "2 things - 1. I think you should call dataSender.sb.Clear() instead of setting length to 0, clear is a convenience method that is equivalent but I feel is clearer and makes reading the code easier later. 2. The StringBuilder class has a replace on it. It seems like the if statement that is checking the ToString() result (called content) could just check the SB and also check if there is an event to raise and only do the replace in the SB if it needs to raise the event. Then clearing the SB can be outside the if since it should be trivial to clear an empty string builder." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-09T13:59:57.687", "Id": "9076", "Score": "0", "body": "@BenGale - is `dataSender.sb` a StringBuilder? @pstrjds - without the code for that class I do not know if it is, and would be assuming; thus I left the correction as a comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-09T15:10:25.133", "Id": "9078", "Score": "1", "body": "sure, I was making the assumption as it is called sb and both Append and ToString are being called on it as well as setting the Length property, based on that I figure it is most likely a string builder and thus things like Replace and others could be called on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-15T17:08:21.837", "Id": "9350", "Score": "0", "body": "You're awesome. I think I might even owe you two beers. Yes sb is a string builder, I've changed that to .clear(). I'm going through updating my code now, and working on some exception handling. I'll post up my new version when I'm done. Thanks for all the help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-16T14:18:59.127", "Id": "9430", "Score": "0", "body": "Had some issues with: id = !connectedClients.Any() ? 1 : connectedClients.Keys.Max() I needed to increment the returned value for the false part or it's conflict with the last record in the dictionary. This sound right or have I missed something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-17T10:59:34.787", "Id": "9455", "Score": "0", "body": "Sounds absolutely right! `id = !connectedClients.Any() ? 1 : connectedClients.Keys.Max()+1` Answer updated to include that change, and also to use StringBuilder methods as suggested by @pstrjds." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-08T16:58:23.140", "Id": "5900", "ParentId": "5306", "Score": "13" } } ]
{ "AcceptedAnswerId": "5900", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T16:07:00.527", "Id": "5306", "Score": "13", "Tags": [ "c#", "networking", "socket", "tcp" ], "Title": "TCP Socket Server" }
5306
<p>I am looking a good way to fill up the elements of a lower triangular matrix from a list.</p> <p>I currently have this:</p> <pre><code>PadRight[#, s] &amp; /@ Prepend[Take[elems, # + {1, 0}] &amp; /@ Partition[Accumulate[Range[0, s - 1]], 2, 1], {}] </code></pre> <p>where <code>elems</code> is the elements-list and <code>s</code> is its length.</p> <p>Perhaps the best way is preallocation plus a clear, procedural <code>Do</code>-loop. What do you think?</p> <p>You can test the above with:</p> <pre><code>s = 5 elems = Range[s(s-1)/2] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-16T11:13:51.907", "Id": "8137", "Score": "0", "body": "Lonely over here, isn't it? I have to remember to visit this site more often. The code doesn't appear to be working as I expect. Would you please include a full, directly executable example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T14:32:18.960", "Id": "8170", "Score": "0", "body": "@Mr.Wizard Lonely indeed, but the question was not really suitable for SO. I added sample values for `s` and `elems`. If you run the code with these and look at the `MatrixForm` of the result, you'll see what I am trying to get: a triangular matrix filled up with the elements from `elems`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T14:47:36.507", "Id": "8172", "Score": "0", "body": "I see now. What is your priority? That is, efficiency, transparent code, terse code, etc.? Honestly what you have looks OK to me just by eye, but clearly you are unhappy with it, so I wonder what you are after." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:23:18.890", "Id": "8190", "Score": "0", "body": "@Mr.Wizard It looked a bit complicated to me. Could you tell what that piece of code is doing just by looking at it? (Without a lot of hard thinking.) There's the procedural alternative along the lines of `Do[ matrix[[i,j]] = ... , {i, 1, s}, {j, 1, i-1}]`. I was wondering if there's something easy to understand which is less procedural. Speed is not a priority, my matrices are smaller than 200 by 200." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T20:10:08.307", "Id": "8191", "Score": "0", "body": "Let me think about that. I agree that the code is not particularly understandable. I think it may be hard to beat the procedural method for transparency. What you have now though is fast; it is related to my [\"Dynamic Partition\"](http://stackoverflow.com/questions/4198961/what-is-in-your-mathematica-tool-bag/5433867#5433867) code, and I tried many forms before settling on that one. Your code can be made a little faster by using `Part` in place of `Take` but that is about all I can find speed wise." } ]
[ { "body": "<p>Here are a few methods for your consideration and feedback.</p>\n\n<hr>\n\n<p>This one uses the core of my <a href=\"https://stackoverflow.com/questions/4198961/what-is-in-your-mathematica-tool-bag/5433867#5433867\">\"Dynamic Partition\"</a> function. It is the fastest method I know for this problem. Also, perhaps refactoring the code like this makes it more intelligible.</p>\n\n<pre><code>dynP[l_, p_] := \n MapThread[l[[# ;; #2]] &amp;, {{0}~Join~Most@# + 1, #} &amp;@Accumulate@p]\n\n#~PadRight~s &amp; /@ {{}} ~Join~ dynP[elems, Range[s-1]]\n</code></pre>\n\n<hr>\n\n<p>This one is slightly shorter, using a different way to construct the indices, but also slightly slower, and perhaps less transparent.</p>\n\n<pre><code>#~PadRight~s &amp; /@ \n Prepend[\n elems~Take~# &amp; /@ \n Array[{1 + # (# - 1)/2, # (# + 1)/2} &amp;, s - 1],\n {}\n ]\n</code></pre>\n\n<hr>\n\n<p>This one is terse, but slow. Legibility is debatable.</p>\n\n<pre><code>SparseArray[Join @@ Table[{i, j}, {i, s}, {j, i - 1}] -&gt; elems, s] // MatrixForm\n</code></pre>\n\n<hr>\n\n<p>Here is one I just came up with, and I am quite pleased with it. I think it may be more understandable than most of the ones above.</p>\n\n<pre><code>Take[FoldList[RotateLeft, elems, Range[0, s - 1]] ~LowerTriangularize~ -1, All, s + 1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T18:54:44.643", "Id": "8237", "Score": "0", "body": "Thanks! I'm a bit slow these days ... I find the last one quite legible, but the \"good\" solution for me in this case is really to use a function like your Dynamic Partitions and just pass the lengths." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-18T20:06:07.440", "Id": "8242", "Score": "0", "body": "@Szabolcs, please see the `FoldList` solution I just added. I like this one best so far, other than possibly the one leveraging dynamicPartition." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T20:15:40.267", "Id": "5430", "ParentId": "5307", "Score": "3" } } ]
{ "AcceptedAnswerId": "5430", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T16:33:39.543", "Id": "5307", "Score": "2", "Tags": [ "matrix", "wolfram-mathematica" ], "Title": "Fill upper triangular matrix from a list" }
5307
<p>I feel like this isn't the most effective nor efficient way of doing things:</p> <pre><code>line.stop(true, true).show('slide', {direction: whichway}, speed-150, function() { title.stop(true, true).fadeIn(speed-200, function() { sub.stop(true, true).show('slide', {direction: whichway}, speed-50, function() { subtext.stop(true, true).show(); paragraph.stop(true, true).slideDown(speed); }); }); }); </code></pre> <p>whichway/speed are dynamic, but other than that it's all stuff that has to be in sync and queued up.</p> <p>Is there a more efficient way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T01:34:02.420", "Id": "8043", "Score": "1", "body": "Apart from indentation/Style I don't think there is any other option short of putting it in your own queue ... and that would seem like overkill for this. Are you looking for style/readability recommendations?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-19T09:57:34.230", "Id": "25582", "Score": "0", "body": "Is this code called more than once? If yes, you should be aware that you are re-creating the 3 callback functions whenever the code is called. Saving the functions into variables and delivering these variables as parameters would fix this; using when, as @LarryBattle suggested, also fixes this." } ]
[ { "body": "<p>For readability, take advantage of jQuery methods that use the jQuery <a href=\"http://api.jquery.com/category/deferred-object/\" rel=\"nofollow noreferrer\">Deferred object</a> to eliminate your deeply nested callback structure.\nExample <a href=\"http://api.jquery.com/jQuery.when/\" rel=\"nofollow noreferrer\">jQuery.when()</a> can turn your code into this.</p>\n\n<pre><code>$.when({}).then(function(){\n return line.stop(true, true).show('slide', {direction: whichway}, speed-150);\n}).then(function() {\n return title.stop(true, true).fadeIn(speed-200);\n}).then(function() {\n return sub.stop(true, true).show('slide', {direction: whichway}, speed-50 );\n}).then(function() {\n subtext.stop(true, true).show();\n return paragraph.stop(true, true).slideDown(speed);\n});\n</code></pre>\n\n<p>Here's another example of using $.when: <a href=\"http://jsfiddle.net/Tp569/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/Tp569/</a></p>\n\n<p>Code from demo.</p>\n\n<p>CSS:</p>\n\n<pre><code>.box{\n width: 10em;\n height: 10em;\n display:none;\n}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code>&lt;div id=\"box1\" class=\"box\"&gt;Box 1&lt;/div&gt;\n&lt;div id=\"box2\" class=\"box\"&gt;Box 2&lt;/div&gt;\n</code></pre>\n\n<p>JS:</p>\n\n<pre><code>$.when({}).then(function(){\n return $(\"#box1\").css(\"backgroundColor\", \"blue\" )\n .fadeIn( \"slow\" ).delay(500).animate({\n opacity: 0.5,\n margin: '50'\n }, \"slow\").delay(1000);\n}).then(function() {\n return $(\"#box2\").css(\"backgroundColor\", \"yellow\" ).fadeIn( \"fast\" );\n});\n</code></pre>\n\n<p>For speed, try out <a href=\"http://daneden.me/animate/\" rel=\"nofollow noreferrer\">animate.css</a>, which is a pure css 3 base animation library.\nIf that's not enough then <a href=\"https://stackoverflow.com/questions/1596429/jquery-best-practice-for-speeding-up-animation\">read this</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-18T18:32:52.027", "Id": "15715", "ParentId": "5309", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T17:52:20.603", "Id": "5309", "Score": "3", "Tags": [ "javascript", "jquery", "animation" ], "Title": "Animation of multiple text elements in sequence" }
5309
<pre><code>function order_ignore_the($a, $b){ // orders sentences ascending alphabetically, ignoring the work &quot;the&quot; $args = func_get_args(); foreach($args as $k=&gt;$v){ $sort = explode(&quot; &quot;,$v); $args[$k] = (strtolower($sort[0]) == &quot;the&quot; ? $sort[1] : $sort[0]); } return strcmp($args[0], $args[1]); } usort($array_of_sentences,'order_ignore_the'); </code></pre>
[]
[ { "body": "<p>I'm not sure what you're doing there, but I think it can get shortened to this.</p>\n\n<pre><code>function order_ignore_the($a, $b) {\n return strcmp(\n strcasecmp(substr($a, 0, 3), \"the\") != 0 ? $a : substr($a, 3),\n strcasecmp(substr($b, 0, 3), \"the\") != 0 ? $b : substr($b, 3)\n );\n}\n</code></pre>\n\n<p>Be warned that this is not tested.</p>\n\n<p><strong>Edit:</strong> Long version with explanation:</p>\n\n<pre><code>function order_ignore_the($a, $b) {\n // Variables for later use\n $checkedA = $a;\n $checkedB = $b;\n\n // Compare the first three letters case-insensitive against \"the\"\n if(strcasecmp(substr($checkedA, 0, 3), \"the\") == 0) {\n // strip the \"the\" from the string\n $checkedA = substr($checkedA, 3);\n }\n // Repeate for $b\n if(strcasecmp(substr($checkedB, 0, 3), \"the\") == 0) {\n $checkedB = substr($checkedB, 3);\n }\n\n // Compare both strings\n return strcmp($checkedA, $checkedB);\n}\n</code></pre>\n\n<p>Yes, it's swapped, I'm checking in the short version if the string does not match \"the\", and here I'm checking if it does match.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T09:33:12.687", "Id": "5320", "ParentId": "5313", "Score": "1" } }, { "body": "<p>With some testing, it should look like the below</p>\n\n<pre><code>function order_ignore_the($a, $b) {\n return strcasecmp(\n strcasecmp(substr($a, 0, 4), \"the \") != 0 ? $a : substr($a, 4),\n strcasecmp(substr($b, 0, 4), \"the \") != 0 ? $b : substr($b, 4)\n );\n}\n</code></pre>\n\n<p>Main differences being:</p>\n\n<ul>\n<li>Widening the search for \"the\" to include the space after. Otherwise, you're matching on things like \"theater\", etc.</li>\n<li>The last substr should likewise have start position 4. Otherwise, you're comparing on the space after \"the\".</li>\n<li>You'll want the main comparison to ignore capitalization, too. </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-17T15:41:06.267", "Id": "84275", "ParentId": "5313", "Score": "2" } }, { "body": "<p>I took a moment to compile a list of <strong>real</strong> movie titles which represent some squirrelly fringe cases.</p>\n<p>I arrived at a one-liner that relies on regex for best accuracy that doesn't fail when the leading <code>The</code> word is not immediately followed by a space. Notice that one real movie title below starts with the word &quot;the&quot;, but the fourth character is not a space, so your exploding technique will not accurately remove it.</p>\n<p>Your custom function explodes on spaces and assumes that all titles will contain at least one space -- this is a falsehood. Your code will generate <code>Warning: Undefined array key 1</code> errors every time it encounters a movie without a space.</p>\n<p>Another problem with your use of <code>explode()</code> is that you are not limiting the generated output to 2 elements. This will lead to incorrect results when comparing <code>The Matrix</code>, <code>The Matrix 2</code>, and <code>The Matrix 3</code>. Effectively, the <code>The</code> words will be stored as <code>[0]</code>, then the word <code>Matrix</code> as <code>[1]</code>, and any/all subsequent characters in the title are doomed to go unused.</p>\n<p>Note, because you are using <code>func_get_args()</code> in your custom function and you never reference <code>$a</code> or <code>$b</code>, you don't actually need to declare them as arguments for your script to run.</p>\n<p>Effectively, the <code>preg_replace()</code> call trims off the qualifying <code>The</code> in the temporary array which is only used for sorting the original array.</p>\n<p>While regex is generally a more expensive technique than non-regex techniques, it never revisits any values because it is not called within the sorting iterations.</p>\n<p>This snippet will deliver a much more accurate sort than the code you have posted.</p>\n<p>Code: (<a href=\"https://3v4l.org/8uDud\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$array = [\n 'The Theory of Everything',\n 'The Mummy Returns',\n 'The Mummy',\n 'Then Came You',\n 'The One',\n 'The',\n 'The 100',\n 'The Matrix',\n 'Theft',\n 'The...',\n '300',\n 'The 300 Spartans',\n 'Mad Max',\n 'Then',\n 'The Martian',\n];\n\narray_multisort(preg_replace('/^the\\b ?/i', '', $array), $array);\nvar_export($array);\n</code></pre>\n<p>Output:</p>\n<pre><code>array (\n 0 =&gt; 'The',\n 1 =&gt; 'The...',\n 2 =&gt; 'The 100',\n 3 =&gt; '300',\n 4 =&gt; 'The 300 Spartans',\n 5 =&gt; 'Mad Max',\n 6 =&gt; 'The Martian',\n 7 =&gt; 'The Matrix',\n 8 =&gt; 'The Mummy',\n 9 =&gt; 'The Mummy Returns',\n 10 =&gt; 'The One',\n 11 =&gt; 'Theft',\n 12 =&gt; 'Then',\n 13 =&gt; 'Then Came You',\n 14 =&gt; 'The Theory of Everything',\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-29T21:18:53.583", "Id": "503871", "Score": "0", "body": "I must have gotten stuck in my own head about using movie titles instead of \"sentences\". Sample data in the question would have helped me. Anyhow, my guidance still sings true." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-27T15:24:36.060", "Id": "255288", "ParentId": "5313", "Score": "1" } } ]
{ "AcceptedAnswerId": "5320", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-10-11T21:21:18.210", "Id": "5313", "Score": "0", "Tags": [ "php", "sorting" ], "Title": "Sort an array of sentences alphabetically, ignoring the first word if it equals 'the' (case insensitive)" }
5313
<p>Any tips on how to improve this simple recursion program?</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; int findSum(int*, const int, int, int); int main() { int length = 5, sum = 0, n = 0; int list[length]; for (n; n &lt; length ; n++ ) { list[n] = n + 1; //initializes array elements to 1,2,3,4,5 } n = 0; cout &lt;&lt; findSum(list, length, n, sum) &lt;&lt; endl; system("pause"); return 0; } int findSum(int list[], const int length, int n, int sum) { if (n == length) //if end of list has been reached, stop recursion { return sum; } else { sum += list[n]; //adds list elements n++; //increments list return findSum(list, length, n, sum); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T23:04:56.817", "Id": "8018", "Score": "0", "body": "Do you want to improve the recursion or do you want a better technique?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T00:30:13.700", "Id": "8020", "Score": "0", "body": "Recursion must be used." } ]
[ { "body": "<p>I think I'd prefer something like this:</p>\n\n<pre><code>int findsum(int const *list, int length) { \n if (0 == length) \n return 0;\n return list[0] + findsum(list+1, length-1);\n}\n</code></pre>\n\n<p>This follows one of the typical recursive formulations -- basically a function that's almost like an inductive proof. Start by establishing a correct value for the simplest possible base case (or some obvious base case anyway), and then establish a pattern that's correct for some some sort of \"Base+1\" type of case.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T22:36:53.870", "Id": "5315", "ParentId": "5314", "Score": "6" } } ]
{ "AcceptedAnswerId": "5315", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-11T22:23:17.633", "Id": "5314", "Score": "4", "Tags": [ "c++", "recursion", "mathematics" ], "Title": "Simple recursive Summing program" }
5314
<p>I want to limit the load so I rewrite the most expensive method and add caching, both memcache and cache-control:</p> <pre><code>class GeoRSS(webapp.RequestHandler): def get(self): start = datetime.datetime.now() - timedelta(days=60) count = (int(self.request.get('count' )) if not self.request.get('count') == '' else 1000) memcache_key = 'ads' data = memcache.get(memcache_key) if data is None: a = Ad.all().filter('modified &gt;', start).filter('published =', True).order('-modified').fetch(count) memcache.set('ads', a) else: a = data template_values = {'a': a, 'request': self.request, 'host': os.environ.get('HTTP_HOST', os.environ['SERVER_NAME'])} dispatch = 'templates/georss.html' path = os.path.join(os.path.dirname(__file__), dispatch) output = template.render(path, template_values) self.response.headers["Cache-Control"] = "public,max-age=%s" % 86400 self.response.headers['Content-Type'] = 'application/rss+xml' self.response.out.write(output) </code></pre> <p>Will this limit the load on my app? Did I prioritize correctly when I see the load on the app:</p> <p><img src="https://i.stack.imgur.com/zlcNl.png" alt="enter image description here"></p>
[]
[ { "body": "<p>You can simplify (and sometimes speed up) things like this</p>\n\n<pre><code>try:\n a = memcache.get('ads')\nexcept KeyError:\n a = Ad.all().filter('modified &gt;',\n start).filter('published =',\n True).order('-modified').fetch(count)\n memcache.set('ads', a)\n</code></pre>\n\n<p>It's (often) slightly faster in Python to avoid the <code>if</code> statement.</p>\n\n<p>After measuring that with <code>timeit</code>, you should rename the variable <code>a</code>. That's a poor name.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-17T18:37:07.097", "Id": "5429", "ParentId": "5317", "Score": "3" } } ]
{ "AcceptedAnswerId": "5429", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T06:04:26.670", "Id": "5317", "Score": "1", "Tags": [ "python", "cache" ], "Title": "Does this function cache correctly?" }
5317
<p>We have several legacy programs (VB6) generating Excel report. They are scheduled tasks running on a server. Yes, violate <a href="http://support.microsoft.com/kb/257757" rel="nofollow">this</a>.</p> <p>As a result, we've got lots of "dead" instances of Excel on the server. I intend to write a program to clean these dead Excels. What is the correct way to kill an idle instance? I know it's not a good practice but it seems to be the easiest way for me.</p> <pre><code>Process[] procs = Process.GetProcessesByName("EXCEL"); List&lt;ProcessInfo&gt; beginProcessInfoList = new List&lt;ProcessInfo&gt;(); foreach (Process p in procs) { if (p.HasExited) continue; try { ProcessInfo pi = new ProcessInfo() { PID = p.Id, TotalProcessorTime = p.TotalProcessorTime }; beginProcessInfoList.Add(pi); } catch (Exception exp) { this.Log(exp.Message); } } Thread.Sleep(TimeSpan.FromSeconds(10)); foreach (Process p in procs) { if (p.HasExited) continue; try { p.Refresh(); if (p.TotalProcessorTime - beginProcessInfoList.Single(pi =&gt; pi.PID == p.Id).TotalProcessorTime == TimeSpan.FromSeconds(0)) { p.Kill(); p.WaitForExit(); this.Log(string.Format("EXCEL started at {0} killed at {1}.", p.StartTime, DateTime.Now)); } } catch (Exception exp) { this.Log(exp.Message); } } </code></pre>
[]
[ { "body": "<p>Your code appears to be correct - however, this can be dangerous because it will kill ALL instances of Excel that are running so you run the risk of killing one of your currently running legacy programs. There are proper ways to clean up Excel resources - see my question <a href=\"https://stackoverflow.com/questions/5627560/killing-excel-exe-process-from-c-in-a-windows-service/5636310#5636310\">here</a> for a C# version. Do you have any ability to update the legacy programs? If so, I would recommend that over this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-23T02:44:01.060", "Id": "9641", "Score": "0", "body": "Yes, we will update the legacy programs but they are many. Before that, we need a workaround to solve the dead instance issue. Thank you =)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T14:22:38.690", "Id": "5322", "ParentId": "5319", "Score": "4" } } ]
{ "AcceptedAnswerId": "5322", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-12T09:24:15.173", "Id": "5319", "Score": "3", "Tags": [ "c#", "scheduled-tasks" ], "Title": "Kill dead instances of Excel on a server" }
5319