body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<blockquote>
<p>Remove an event listener after firing once or any number of times</p>
</blockquote>
<p>This is what I have:</p>
<pre><code>/*jslint browser: true, vars: true, white: true, maxerr: 50, indent: 4 */
(function ()
{
"use strict";
function removeEventListenerAfterFiring(numberOfTimes, callback, useCapture)
{
var count = 0;
return function listener(event)
{
count += 1;
if (count >= numberOfTimes)
{
event.target.removeEventListener(event.type, listener, useCapture);
}
callback();
};
}
function functionName()
{
// Code here.
}
window.addEventListener("DOMContentLoaded", removeEventListenerAfterFiring(1, functionName, false), false);
}());
</code></pre>
<p>Is there anything that could be improved, or is there a better way to do this?</p>
<p>Is it acceptable to specify <code>useCapture</code> twice? Is there a way to detect if <code>useCapture</code> has been specified so that I don't have to pass it to the <code>removeEventListenerAfterFiring</code> function?</p>
|
[] |
[
{
"body": "<p>Consider using <code>event.currentTarget</code> instead of <code>event.target</code>, since your handlers are probably bound to an ancestor element, not the current element.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-13T07:08:21.030",
"Id": "138598",
"ParentId": "7515",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T03:03:26.260",
"Id": "7515",
"Score": "5",
"Tags": [
"javascript",
"event-handling",
"callback"
],
"Title": "Remove an event listener after firing once or any number of times"
}
|
7515
|
<pre><code>$('pre').each(function(index) {
var c = $(this).attr("class");
if (!c) {
return true;
}
// Match only Javascript code snippets
if (!c.match(/brush: js; class-name: 'jsbox'/)) {
return true;
}
var code = $(this).text();
$(this).after($("<button>Run example</button>").click(function() {
run(code);
}));
</code></pre>
<p>I noticed if I didn't have <code>if (!c) {</code> then the loop could abrubtly halt if it found a <code><pre></code> element without a class.</p>
<p>I wonder how to write this more succinctly. I'm also wondering about my matching options, since I've noticed different ways people match / compare strings in Javascript and I wondered what was "de rigueur". </p>
|
[] |
[
{
"body": "<p>Change</p>\n\n<pre><code>var code = $(this).text(); \n</code></pre>\n\n<p>to</p>\n\n<pre><code>var code = $(this).val();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T08:08:08.250",
"Id": "11954",
"Score": "0",
"body": "That's not the problem. The problem is that I want to compress the '!c' lines."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T06:52:58.033",
"Id": "7547",
"ParentId": "7517",
"Score": "2"
}
},
{
"body": "<p>What about this?</p>\n\n<p><a href=\"http://jsfiddle.net/mfJMb/\" rel=\"nofollow\">http://jsfiddle.net/mfJMb/</a></p>\n\n<pre><code>$('pre').each(function(){\n var $t = $(this);\n\n // Match only Javascript code snippets\n if( ( $t.attr(\"class\") || '') .match(/brush: js; class-name: 'jsbox'/) ){\n $t.after($(\"<button>Run example</button>\").click(function(){\n alert( $t.text() );\n }));\n }\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T09:27:17.360",
"Id": "12063",
"Score": "0",
"body": "I like this answer, but you should have copied in the \"TidyUp\" version since I find the `$t` variable name, unconventional."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T13:54:38.760",
"Id": "7639",
"ParentId": "7517",
"Score": "2"
}
},
{
"body": "<p>It looks like whatever library you're using is generating properties and sticking them inside the <code>class</code> attribute, which I've never seen before and seems questionable (why can't they be attributes on the element?). Because they look generated, could you maybe end up with something like this:</p>\n\n<pre><code><pre class=\"class-name: 'jsbox'; brush: js\">\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code><pre class=\"brush: js; [another property]; class-name: 'jsbox'\">\n</code></pre>\n\n<p>If so, then you may want to only look for one property (like <code>brush: js</code>) to determine if you're looking at a JS code snippet.</p>\n\n<p>It's fine to use <code>String.match()</code> for finding a substring but realize that <code>String.indexOf()</code> is preferable if you have no need for regex: <a href=\"https://stackoverflow.com/a/4757501/1100355\">https://stackoverflow.com/a/4757501/1100355</a></p>\n\n<p>So you would end up with something like this:</p>\n\n<pre><code>var c = $(this).attr(\"class\");\nif (!c || c.indexOf('brush: js') < 0) {\n return true;\n}\n\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T14:34:35.653",
"Id": "7640",
"ParentId": "7517",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7640",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T04:30:03.173",
"Id": "7517",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"regex"
],
"Title": "Checking a HTML element's class"
}
|
7517
|
<p><strong>Input:</strong> any integer</p>
<p><strong>Output:</strong> that integer in number format (commas) with a leading <code>a</code> or <code>an</code> as appropriate with the rules of English</p>
<p>After a bit of groping around I hacked out the following PHP function, and am looking for any advice on code structure and optimization. Thank you!</p>
<pre><code>function prefixAAnToNumber($num) {
$prefixAn = array(8, 11, 18, '8', '11', '18');
$verAn = 'an ' . number_format($num);
$verA = 'a ' . number_format($num);
if (in_array($num,$prefixAn)) {
return $verAn;
} else if (strlen($num) > 1) {
$numComma = number_format($num);
if (substr($numComma,0,1) == '8') {
return $verAn;
} else if (in_array(substr($numComma,0,2), $prefixAn) && substr($numComma,2,1) == ',') {
return $verAn;
} else {
return $verA;
}
} else {
return $verA;
}
}
</code></pre>
<p>Example usage:</p>
<pre><code>$num = 11;
for ($i = 0; $i < 10; ++$i) {
echo '<p>'.$num.' -> "';
echo prefixAAnToNumber($num);
echo ' kg shipment"</p>';
$num = $num * 10;
}
</code></pre>
<p>Output:</p>
<pre><code>11 -> "an 11 kg shipment"
110 -> "a 110 kg shipment"
1100 -> "a 1,100 kg shipment"
11000 -> "an 11,000 kg shipment"
110000 -> "a 110,000 kg shipment"
1100000 -> "a 1,100,000 kg shipment"
11000000 -> "an 11,000,000 kg shipment"
110000000 -> "a 110,000,000 kg shipment"
1100000000 -> "a 1,100,000,000 kg shipment"
11000000000 -> "an 11,000,000,000 kg shipment"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T16:31:14.923",
"Id": "11825",
"Score": "0",
"body": "Not a function, but a component made for such jobs: http://php.net/manual/en/class.numberformatter.php"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T21:06:32.127",
"Id": "11918",
"Score": "0",
"body": "\"1,100\" can go either way depending on whether you pronounce it \"thousand one hundred\" or \"eleven hundred\". I'd opt for the second, so my expected function results are different from yours."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T01:32:41.107",
"Id": "11927",
"Score": "0",
"body": "@hvd - you're correct, of course. I chose to interpret it as \"one thousand one hundred\" to simplify my code, even though I'd read it as \"eleven hundred\" in casual speech."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T01:33:35.723",
"Id": "11928",
"Score": "0",
"body": "@hakre - thanks for the link. I assumed something existed already either in the core function set or on `phpclasses.org`, but I wanted to write the function as a learning exercise. I'm glad I did, the answers reveal that my formatting and logic layout still needs a lot of work!"
}
] |
[
{
"body": "<p>Rather than having many return statements I would keep the logic that determines whether it should be 'a' or 'an' together. I think it is actually easier to understand reading the ANDs and ORs than spread out <code>if</code> and <code>else</code> statements.</p>\n\n<p>I prefer not to create temporary variables that are not used for anything - so I wouldn't create <code>$verA</code> and <code>$verAn</code>. I do however create a variable for $numComma. By having this we avoid calling number_format more than is necessary.</p>\n\n<p>This is how it looks my way:</p>\n\n<pre><code>function prefixAAnToNumber($num)\n{\n $prefixAn = array(8, 11, 18, '8', '11', '18');\n $numComma = number_format($num);\n\n if (in_array($num, $prefixAn) ||\n (strlen($num) > 1 &&\n (substr($numComma, 0, 1) == '8' ||\n (in_array(substr($numComma, 0, 2), $prefixAn) &&\n substr($numComma, 2, 1) == ','))))\n {\n return 'an ' . $numComma;\n }\n\n return 'a ' . $numComma;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T11:36:01.033",
"Id": "7528",
"ParentId": "7519",
"Score": "2"
}
},
{
"body": "<p>I don't know if you have noticed but all numbers that start with an <code>an</code> have the numbers in the array before the comma.</p>\n\n<p>So what you can do:</p>\n\n<pre><code>function prefixAAnToNumber($num) {\n $prefixAn = array(8, 11, 18, '8', '11', '18');\n $number = number_format($num);\n $numberSplit = explode(',', $number);\n $a = 'a';\n if(in_array($numberSplit[0], $prefixAn)\n || substr($number,0,1) == '8')\n $a .= 'n';\n return \"$a $number\";\n}\n</code></pre>\n\n<p>Demo: <a href=\"http://codepad.org/bXAnr3Tz\" rel=\"nofollow\">http://codepad.org/bXAnr3Tz</a></p>\n\n<p>Output:</p>\n\n<pre><code>11 -> \"an 11 kg shipment\"\n110 -> \"a 110 kg shipment\"\n1100 -> \"a 1,100 kg shipment\"\n11000 -> \"an 11,000 kg shipment\"\n110000 -> \"a 110,000 kg shipment\"\n1100000 -> \"a 1,100,000 kg shipment\"\n11000000 -> \"an 11,000,000 kg shipment\"\n110000000 -> \"a 110,000,000 kg shipment\"\n1100000000 -> \"a 1,100,000,000 kg shipment\"\n11000000000 -> \"an 11,000,000,000 kg shipment\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T16:02:54.783",
"Id": "7535",
"ParentId": "7519",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T06:05:25.390",
"Id": "7519",
"Score": "1",
"Tags": [
"php"
],
"Title": "function to append \"a\" or \"an\" to the front of a number as appropriate"
}
|
7519
|
<p>Further to the <a href="https://stackoverflow.com/questions/8711239/circle-summation-30-points-interviewstree-puzzle/8712670#8712670">question</a>
I solved it in following way.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <iterator>
#include <stdio.h>
int main ( int argc, char **argv) {
int T; // number of test cases
std::cin >> T;
for ( int i = 0 ; i < T; i++) {
int N; // number of childrens
std::cin >> N;
int M; // number of rounds
std::cin >> M;
long long childrens[50];
for ( int j = 0; j < N; j++ )
std::cin >> childrens[j];
int pos = 0;
for ( int i = 0; i < N ; i++) {
long long childs[50];
for ( int j = 0; j < N; j++ )
childs[j] = childrens[j];
for ( int j = 0; j < M; j++) {
int left = ( pos == 0) ? N - 1 : pos - 1;
int right = ( pos + 1 >= N ) ? 0 : pos + 1;
childs[pos] = (childs[pos] + childs[left] + childs[right])% 1000000007;
pos++;
pos = ( pos >= N ) ? 0 : pos;
}
std::copy(childs ,childs + N ,std::ostream_iterator<long long>(std::cout," "));
std::cout << std::endl;
}
std::cout << std::endl;
}
return 0;
}
</code></pre>
<p>but the <code>M</code> can be <code>10^9</code>, My code is going to take lot of time to finish, What are the various ways I can optize this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T06:47:37.567",
"Id": "11791",
"Score": "0",
"body": "hehe, I'm trying the same problem. I don't know how to solve it."
}
] |
[
{
"body": "<pre><code>#include <iostream>\n#include <algorithm>\n#include <iterator>\n#include <stdio.h>\n\n\nint main ( int argc, char **argv) {\n int T; // number of test cases\n std::cin >> T;\n for ( int i = 0 ; i < T; i++) {\n int N; // number of childrens\n std::cin >> N;\n int M; // number of rounds\n std::cin >> M;\n</code></pre>\n\n<p>Why split this across two lines instead of <code>std::cin >> N >> M;</code>?</p>\n\n<pre><code> long long childrens[50];\n</code></pre>\n\n<p>I missed this in my first submissions and tried using 32 bit integers. It didn't work so well...</p>\n\n<pre><code> for ( int j = 0; j < N; j++ ) \n std::cin >> childrens[j];\n\n int pos = 0;\n for ( int i = 0; i < N ; i++) {\n long long childs[50];\n for ( int j = 0; j < N; j++ ) \n childs[j] = childrens[j];\n for ( int j = 0; j < M; j++) {\n int left = ( pos == 0) ? N - 1 : pos - 1;\n</code></pre>\n\n<p>You can use <code>left = (pos + N - 1) % N</code> which works thanks to modular math.</p>\n\n<pre><code> int right = ( pos + 1 >= N ) ? 0 : pos + 1;\n</code></pre>\n\n<p>You can use <code>right = (pos + 1) % N</code></p>\n\n<pre><code> childs[pos] = (childs[pos] + childs[left] + childs[right])% 1000000007;\n pos++;\n pos = ( pos >= N ) ? 0 : pos;\n</code></pre>\n\n<p>You can use <code>pos = (pos + 1) % N</code></p>\n\n<pre><code> }\n std::copy(childs ,childs + N ,std::ostream_iterator<long long>(std::cout,\" \"));\n std::cout << std::endl;\n }\n std::cout << std::endl;\n }\n return 0;\n}\n</code></pre>\n\n<p>Generally, writing brute force solutions for a site like Interviewstreet is a waste of time. Its not like you can write your brute force solution, and then optimize it so that it will run fast enough. You need to come up with a completely different approach.</p>\n\n<p>Since Interviewstreet is trying to test your abilities I'm not going to share my solution. (Unless you have a solution for the Meeting Point problem, then I'll trade :P) But I will give a hint: think back to linear algebra. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T18:58:20.543",
"Id": "7538",
"ParentId": "7521",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T06:19:31.010",
"Id": "7521",
"Score": "0",
"Tags": [
"c++",
"algorithm"
],
"Title": "Circle Summation (30 Points) InterviewStree Puzzle cont"
}
|
7521
|
<p>I have this module which computes checksums from a list of files in a given directory.
The problem is that my is_changed_file is long and ugly, but my attempts in refactoring failed, so I would like some other point of views...</p>
<pre><code>import hashlib
import logging
# if available use the faster cPickle module
try:
import cPickle as pickle
except ImportError:
import pickle
from os import path
class DirectoryChecksum(object):
"""Manage the checksums of the given files in a directory
"""
def __init__(self, directory, to_hash):
self.directory = directory
self.to_hash = to_hash
self.checksum_file = path.join(self.directory, '.checksums')
self.checks = self._compute()
self.logger = logging.getLogger("checksum(%s): " % self.directory)
def _abs_path(self, filename):
return path.join(self.directory, filename)
def _get_checksum(self, filename):
content = open(self._abs_path(filename)).read()
return hashlib.md5(content).hexdigest()
def _compute(self):
"""Compute all the checksums for the files to hash
"""
dic = {}
for f in self.to_hash:
if self._file_exists(f):
dic[f] = self._get_checksum(f)
return dic
def _file_exists(self, filename):
return path.isfile(self._abs_path(filename))
def is_changed(self):
"""True if any of the files to hash has been changed
"""
return any(self.is_file_changed(x) for x in self.to_hash)
#FIXME: refactor this mess, there is also a bug which impacts on
#the airbus. eggs, so probably something to do with the path
def is_file_changed(self, filename):
"""Return true if the given file was changed
"""
if not self._has_checksum():
self.logger.debug("no checksum is available yet, creating it")
self.write_checksums()
return True
stored_checks = self.load_checksums()
if not self._file_exists(filename):
if filename in stored_checks:
self.logger.debug("file %s has been removed" % filename)
# what if it existed before and now it doesn't??
return True
else:
return False
checksum = self._get_checksum(filename)
if filename in stored_checks:
# if the file is already there but the values are changed
# then we also need to rewrite the stored checksums
if stored_checks[filename] != checksum:
self.write_checksums()
return True
else:
return False
else:
# this means that there is a new file to hash, just do it again
self.write_checksums()
return True
def _has_checksum(self):
return path.isfile(self.checksum_file)
def load_checksums(self):
"""Load the checksum file, returning the dictionary stored
"""
return pickle.load(open(self.checksum_file))
def write_checksums(self):
"""Write to output (potentially overwriting) the computed checksum dictionary
"""
self.logger.debug("writing the checksums to %s" % self.checksum_file)
return pickle.dump(self.checks, open(self.checksum_file, 'w'))
</code></pre>
|
[] |
[
{
"body": "<p>Probably there is no need to refactor the method as it represents quite clear decision tree. Breaking it down into smaller methods will cause readability problems.</p>\n\n<p>Just make sure you have unit tests covering each outcome and that there are no cases, which the code doesn't handle.</p>\n\n<p>If you definitely want to refactor, I propose to add a method like this:</p>\n\n<pre><code>def _check_log_writesums(cond, logmessage, rewrite=True):\n if cond:\n if logmessage:\n self.logger.debug(logmessage)\n if rewrite:\n self.write_checksums()\n return True\n return False\n</code></pre>\n\n<p>Then you can call it like this:</p>\n\n<pre><code> if filename in stored_checks:\n return self._check_log_writesums(stored_checks[filename] != checksum,\n \"\",\n rewrite=True)\n</code></pre>\n\n<p>Maybe the name can be better (_update_checksums or _do_write_checksums).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T11:57:02.570",
"Id": "11989",
"Score": "0",
"body": "Yes well I don't definitively want to refactor, but I found it very strange that I could not easily refactor it...\nWhat is your \"if logmessage\" for?\nI normally just use levels or more specialized loggers that can be filtered more easily..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:05:36.893",
"Id": "12105",
"Score": "0",
"body": "I just wanted to make it optional for \"if stored_checks[filename] != checksum\", because logging is missing in the original code. There is no sense to log empty message"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T18:39:06.533",
"Id": "7595",
"ParentId": "7529",
"Score": "1"
}
},
{
"body": "<p>I felt there was there was a better way to do what i wanted, and after a refactoring I came up with this.</p>\n\n<pre><code>class DirChecksum(object):\n def __init__(self, directory, files_to_hash):\n self.directory = directory\n self.files_to_hash = files_to_hash\n\n def _abs_path(self, filename):\n return path.join(self.directory, filename)\n\n def _get_checksum(self, filename):\n content = open(filename).read()\n return hashlib.md5(content).hexdigest()\n\n def _compute_checksums(self):\n logger.debug(\"computing checksums for %s\" % self.directory)\n ck = {}\n for fname in self.files_to_hash:\n abs_fname = self._abs_path(fname)\n if path.isfile(abs_fname):\n ck[fname] = self._get_checksum(abs_fname)\n\n return ck\n\n @property\n def checksums(self):\n return self._compute_checksums()\n\n def is_changed(self, old_checksums):\n # there was nothing actually previously stored\n if not old_checksums:\n logger.debug(\"checksums were never computed before\")\n return True\n\n actual_checksums = self.checksums\n if len(actual_checksums) != len(old_checksums):\n logger.debug(\"number of files hashed changed\")\n return True\n\n # if _checksums isn't there it means that probably is never been called\n return old_checksums != actual_checksums\n</code></pre>\n\n<p>Which is quite different, because now it doesn't read and write anything on disk, but it takes the dictionary with the checksums as input.\nMuch cleaner now, even if of course can still made better..</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T23:08:18.643",
"Id": "7852",
"ParentId": "7529",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7595",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T13:50:15.787",
"Id": "7529",
"Score": "2",
"Tags": [
"python"
],
"Title": "Python and computing checksums"
}
|
7529
|
<blockquote>
<p>The following is a new question based on answers from here: <a href="https://codereview.stackexchange.com/q/5039/3163">Small PHP Viewer/Controller template</a> </p>
</blockquote>
<p>I have written a small MVC template library that I would like some critiques on.</p>
<p>The library is <a href="https://github.com/maniator/SmallFry/tree/ffa8cd85ef1d71ea3e34b3921621e4090fc98015" rel="nofollow noreferrer">located here</a></p>
<p>If you are looking for where to start, check out the files in the <a href="https://github.com/maniator/SmallFry/tree/ffa8cd85ef1d71ea3e34b3921621e4090fc98015/smallFry/application" rel="nofollow noreferrer"><code>smallFry/application</code></a> directory.</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>
</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>
<hr>
<p>Code examples (all of the code is equal, just on my last question I was asked for some snippets):</p>
<p><a href="https://github.com/maniator/SmallFry/blob/ffa8cd85ef1d71ea3e34b3921621e4090fc98015/smallFry/application/Bootstrap.php" rel="nofollow noreferrer"><code>Bootstrap.php</code></a>:</p>
<pre><code><?php
/**
* Description of Bootstrap
*
* @author nlubin
*/
Class Bootstrap {
/**
*
* @var SessionManager
*/
private $_session;
/**
*
* @var stdClass
*/
private $_path;
/**
*
* @var AppController
*/
private $_controller;
/**
*
* @var Template
*/
private $_template;
function __construct() {
Config::set('page_title', Config::get('DEFAULT_TITLE'));
Config::set('template', Config::get('DEFAULT_TEMPLATE'));
$this->_session = new SessionManager(Config::get('APP_NAME'));
$this->_path = $this->readPath();
$this->_controller = $this->loadController();
$this->_template = new Template($this->_path, $this->_session, $this->_controller); //has destructor that controls it
$this->_controller->displayPage($this->_path->args); //run the page for the controller
$this->_template->renderTemplate(); //only render template after all is said and done
}
/**
*
* @return stdClass
*/
private function readPath(){
$path = isset($_SERVER["PATH_INFO"])?$_SERVER["PATH_INFO"]:'/'.Config::get('DEFAULT_CONTROLLER');
$path_info = explode("/",$path);
$page = (isset($path_info[2]) && strlen($path_info[2]) > 0)?$path_info[2]:'index';
list($page, $temp) = explode('.', $page) + array('index', null);
$args = array_slice($path_info, 3);
$controller = $path_info[1] ?: Config::get('DEFAULT_CONTROLLER');
return (object) array(
'path_info'=>$path_info,
'page'=>$page,
'args'=>$args,
'controller'=>$controller
);
}
/**
* @return AppController
*/
private function loadController(){
Config::set('page', $this->_path->page);
//LOAD CONTROLLER
$modFolders = array('images', 'js', 'css');
//load controller
if(strlen($this->_path->controller) == 0) $this->_path->controller = Config::get('DEFAULT_CONTROLLER');
if(count(array_intersect($this->_path->path_info, $modFolders)) == 0){ //load it only if it is not in one of those folders
$controllerName = "{$this->_path->controller}Controller";
return $this->create_controller($controllerName);
}
else { //fake mod-rewrite
$this->rewrite($this->_path->path_info);
}
//END LOAD CONTROLLER
}
/**
* @return AppController
*/
private function create_controller($controllerName) {
if (class_exists($controllerName) && is_subclass_of($controllerName, 'AppController')) {
$app_controller = new $controllerName($this->_session);
} else {
//show nothing
header("HTTP/1.1 404 Not Found");
exit;
}
return $app_controller;
}
/**
*
* @param array $path_info
*/
private function rewrite($path_info){
$rewrite = $path_info[count($path_info) - 2];
$file_name = $path_info[count($path_info) - 1];
$file = DOCROOT."webroot/".$rewrite."/".$file_name;
include DOCROOT.'/smallFry/functions/mime_type.php'; // needed for setups without `mime_content_type`
header('Content-type: '.mime_content_type($file));
readfile($file);
exit;
}
}
</code></pre>
<p><a href="https://github.com/maniator/SmallFry/blob/ffa8cd85ef1d71ea3e34b3921621e4090fc98015/smallFry/application/AppController.php" rel="nofollow noreferrer"><code>AppController.php</code></a>:</p>
<pre><code><?php
/**
* Description of AppController
*
* @author nlubin
*/
class AppController {
private $pageOn;
protected $name = __CLASS__;
protected $helpers = array();
protected $validate = array();
protected $posts = array();
protected $session;
protected $validator;
protected $template;
/**
*
* @param SessionManager $SESSION
*/
public function __construct(SessionManager $SESSION) {
$this->pageOn = Config::get('page');
$this->session = $SESSION;
$model_name = $this->name;
if(class_exists($model_name) && is_subclass_of($model_name, 'AppModel')){
/**
* @var AppModel $model_name
*/
$this->$model_name = new $model_name();
}
else {
//default model (no database table chosen)
$this->$model_name = new AppModel();
}
/* Get all posts */
$this->posts = $this->$model_name->getPosts();
Config::set('view', strtolower($model_name));
if(!$this->session->get(strtolower($model_name))){
$this->session->set(strtolower($model_name), array());
}
}
private function getPublicMethods(){
$methods = array();
$r = new ReflectionObject($this);
$r_methods = $r->getMethods(ReflectionMethod::IS_PUBLIC);
foreach($r_methods as $method){
if($method->class !== 'AppController'){ //get only public methods from extended class
$methods[] = $method->name;
}
}
return $methods;
}
/**
*
* @param Template $TEMPLATE
*/
public function setTemplate(Template $TEMPLATE){
$this->template = $TEMPLATE;
$model_name = $this->name;
$this->setHelpers();
}
/**
* Function to run before the constructor's view function
*/
public function init(){} //function to run right after constructor
/**
* Show the current page in the browser
*
* @param array $args
* @return string
*/
public function displayPage($args) {
Config::set('method', $this->pageOn);
$public_methods = $this->getPublicMethods();
if(in_array($this->pageOn, $public_methods)) {
call_user_func_array(array($this, $this->pageOn), $args);
}
else {
if(Config::get('view') == strtolower(__CLASS__) ||
!in_array($this->pageOn, $public_methods)){
header("HTTP/1.1 404 Not Found");
}
else {
Config::set('method', '../missingfunction'); //don't even allow trying the page
return($this->getErrorPage(Config::get('view')."/{$this->pageOn} does not exist."));
}
exit;
}
}
/**
*
* @return string
*/
function index() {}
/**
*
* @param string $msg
* @return string
*/
protected function getErrorPage($msg = null) {
$err = '<span class="error">%s</span>';
return sprintf($err, $msg);
}
protected function setHelpers(){
$helpers = array();
foreach($this->helpers as $helper){
$help = "{$helper}Helper";
if(class_exists($help) && is_subclass_of($help, 'Helper')){
$this->$helper = new $help();
$helpers[$helper] = $this->$helper;
}
}
$this->template->set('helpers', (object) $helpers);
}
protected function logout(){
session_destroy();
header('Location: '.WEBROOT.'index.php');
exit;
}
/**
*
* @param array $validate
* @param array $values
* @param boolean $exit
* @return boolean
*/
protected function validateForm($validate = null, $values = null, $exit = true){
$this->validator = new FormValidator(); //create new validator
if($validate == null){
$validate = $this->validate;
}
foreach($validate as $field => $rules){
foreach($rules as $validate=>$message){
$this->validator->addValidation($field, $validate, $message);
}
}
return $this->doValidate($values, $exit);
}
protected function doValidate($values = null, $exit = true){
if(!(!isset($_POST) || count($_POST) == 0)){
//some form was submitted
if(!$this->validator->ValidateForm($values)){
$error = '';
$error_hash = $this->validator->GetErrors();
foreach($error_hash as $inpname => $inp_err)
{
$error .= $inp_err.PHP_EOL;
}
return $this->makeError($error, $exit);
}
}
return true;
}
protected function makeError($str, $exit = true){
$return = $this->getErrorPage(nl2br($str));
if($exit) exit($return);
return $return;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:38:52.543",
"Id": "12247",
"Score": "0",
"body": "@ZaphodBeeblebrox The `Config` is just a holder of global Configuration variables. I do not feel the need to include it here since it is not really important. I **did not** include all of my code in the OP because it would make it waaaay too long. but I want most (to all) of the classes in the [smallFry/application](https://github.com/maniator/SmallFry/tree/ffa8cd85ef1d71ea3e34b3921621e4090fc98015/smallFry/application) directory to be looked at (if possible)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:39:49.903",
"Id": "12248",
"Score": "0",
"body": "@ZaphodBeeblebrox here is the [Config](https://github.com/maniator/SmallFry/blob/ffa8cd85ef1d71ea3e34b3921621e4090fc98015/smallFry/application/Config.php) code if you want to see it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:42:02.477",
"Id": "12250",
"Score": "0",
"body": "@ZaphodBeeblebrox hehe. What is there to criticize about it? :-P Yes, I know it is basically a global class, but it **detached** it from anything meaningful (as it was in the previous question)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:43:55.483",
"Id": "12252",
"Score": "0",
"body": "@ZaphodBeeblebrox haha the only reason I even added a snippet here is because of a comment on my last post. Anyways -- thank you for the help! :-D"
}
] |
[
{
"body": "<p>I think your code is at a point where you need to stop worrying about it. It's not <em>perfect</em>, but it's way past the point of anything obvious. </p>\n\n<p>The one thing I really don't like is your <code>Config</code> class. I get it that <code>static</code> is heplful, but you are abusing it a bit. You could: </p>\n\n<ol>\n<li><p>Consider turning it into a <a href=\"http://php.net/manual/en/language.oop5.patterns.php\" rel=\"nofollow noreferrer\">Singleton</a>, if you are so inclined in static state. <a href=\"https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons\">Singletons are evil</a>, but an improvement upon your code. All <code>static</code> classes are virtually un-testable (in the context of <a href=\"http://en.wikipedia.org/wiki/Unit_testing\" rel=\"nofollow noreferrer\">unit tests</a>) and I can only describe them as a procedural code masquerading as an object. It's a style you don't want to adopt.</p></li>\n<li><p>Consider getting the configuration files from a configuration file, and not requiring the developer to hardcode them. </p>\n\n<p>The simplest way would be <code>ini</code> files, PHP's support via <a href=\"http://php.net/manual/en/function.parse-ini-file.php\" rel=\"nofollow noreferrer\">parse_ini_file()</a> is excellent. That way your configuration class could be used autonomously. </p></li>\n</ol>\n\n<p>And, you seem to have ignored <a href=\"https://codereview.stackexchange.com/questions/5039/small-php-viewer-controller-template\">my advice</a> on prefixing private members with an underscore. That hurts my feelings :)</p>\n\n<p>Further suggestions (that are outside the scope of a code review): </p>\n\n<ol>\n<li><a href=\"https://github.com/sebastianbergmann/phpunit\" rel=\"nofollow noreferrer\">PHPUnit</a> is your best friend! Learn how to write unit tests, framework code especially should be 100% covered by unit tests.</li>\n<li>PHP has support for <a href=\"http://php.net/manual/en/language.oop5.interfaces.php\" rel=\"nofollow noreferrer\">interfaces</a> and you should always <a href=\"https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface\">program to an interface</a>. </li>\n</ol>\n\n<p>I honestly can't find anything else worth mentioning. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:13:59.060",
"Id": "12499",
"Score": "0",
"body": "I had a lot of my parameters prefixed with an underscore. The PHP chatroom suggested that that was an **old** tactic... :-(\n\nI do not rly want to use ini files because I want the users to be able to change the Config easily on the fly.. How would a singleton help?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:15:45.877",
"Id": "12500",
"Score": "0",
"body": "@Neal It would help in the sense that once initialized, you could treat it as a regular object. It could follow an interface, for example. It's a bit more object oriented, if you will, what you have now is procedural code masquerading as a class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:19:02.050",
"Id": "12501",
"Score": "0",
"body": "Hmmmmm Could you give some example code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:19:51.673",
"Id": "12502",
"Score": "0",
"body": "The manual link under singleton has a very good example of a Singleton..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:33:24.710",
"Id": "12503",
"Score": "0",
"body": "@Neal But the most important thing is that your code is good enough. You should consider unit tests and programming to an interface. Skip the singleton if it doesn't make sense, it's not a really good practice anyway - it's just a more object-y way of writing your Config class. Instead you should consider forgetting about static all together, mention \"singleton\" in the PHP chat room and prepare for people shouting at you :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:53:56.280",
"Id": "12504",
"Score": "0",
"body": "I had a singleton for my previous version in a `Database` class that I was bashed for. That is why it is not in this version ^_^"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:57:47.463",
"Id": "12505",
"Score": "0",
"body": "@Neal Yeap, but the all static config _is_ a Singleton essentially, as the problem remains. Read the \"Singletons are evil\" article I linked to, and you'll see that your class suffers from the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T16:00:35.523",
"Id": "12506",
"Score": "0",
"body": "@Neal Ooops I posted the wrong link, sorry, changed that now. The actual link is to a StackOverflow question http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T01:11:16.463",
"Id": "12534",
"Score": "0",
"body": "I wouldn't use a singleton. Just creating one object works very well if you use dependency injection. The other option would be a class with a static property to hold the data. Either of these can be changed easily if you find you want more than one config for any reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T05:09:42.517",
"Id": "12545",
"Score": "0",
"body": "@Paul Did you take a look at the [config class](https://github.com/maniator/SmallFry/blob/ffa8cd85ef1d71ea3e34b3921621e4090fc98015/smallFry/application/Config.php)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T10:37:25.903",
"Id": "12550",
"Score": "0",
"body": "@ZaphodBeeblebrox I have now. I don't see any need for the methods to be static. That only forces the tight coupling for the code that calls it. Changing all of those to non-static would be what I would do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T10:41:54.770",
"Id": "12551",
"Score": "0",
"body": "@Paul yeap, I'd do the same. But the OP has specific needs for the config class, so my advice was to turn the \"all static\" class to a singleton, _at least_..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-12-13T21:40:18.117",
"Id": "31350",
"Score": "0",
"body": "@YannisRizos I have posted a followup question with the newest version of my Framework."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T15:11:20.783",
"Id": "7894",
"ParentId": "7531",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7894",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T14:55:49.853",
"Id": "7531",
"Score": "8",
"Tags": [
"php",
"library"
],
"Title": "Small PHP MVC Template"
}
|
7531
|
<p>This is a framework for a JSON parser I put together last night.</p>
<p>Any comments appreciated.</p>
<ul>
<li>JsonLexer.l: Breaks the input into lexemes</li>
<li>JsonParser.y: Understands the language syntax</li>
<li>JsonParser.h: Header file to bring it all togeter</li>
<li>main.cpp: Test harness so it can be tested.</li>
<li>Makefile: Sinmple build script.</li>
</ul>
<h3>Testing:</h3>
<pre><code>echo '{ "Plop": "Test" }' | ./test
</code></pre>
<h3>JsonLexer.l</h3>
<pre><code>%option c++
%option noyywrap
%{
#define IN_LEXER
#include "JsonParser.tab.hpp"
%}
DIGIT [0-9]
DIGIT1 [1-9]
INTNUM {DIGIT1}{DIGIT}*
FRACT "."{DIGIT}+
FLOAT ({INTNUM}|0){FRACT}?
EXP [eE][+-]?{DIGIT}+
NUMBER -?{FLOAT}{EXP}?
UNICODE \\u[A-Fa-f0-9]{4}
ESCAPECHAR \\["\\/bfnrt]
CHAR [^"\\]|{ESCAPECHAR}|{UNICODE}
STRING \"{CHAR}*\"
WHITESPACE [ \t\n]
%%
\{ {LOG("LEX({)"); return '{';}
\} {LOG("LEX(})"); return '}';}
\[ {LOG("LEX([)"); return '[';}
\] {LOG("LEX(])"); return ']';}
, {LOG("LEX(,)"); return ',';}
: {LOG("LEX(:)"); return ':';}
true {LOG("LEX(true)"); return yy::JsonParser::token::JSON_TRUE;}
false {LOG("LEX(false)"); return yy::JsonParser::token::JSON_FALSE;}
null {LOG("LEX(null)"); return yy::JsonParser::token::JSON_NULL;}
{STRING} {LOG("LEX(String)");return yy::JsonParser::token::JSON_STRING;}
{NUMBER} {LOG("LEX(Number)");return yy::JsonParser::token::JSON_NUMBER;}
{WHITESPACE} {/*IGNORE*/}
%%
</code></pre>
<h3>JsonParser.y</h3>
<pre><code>%skeleton "lalr1.cc"
%require "2.1a"
%defines
%define "parser_class_name" "JsonParser"
%{
#include "JsonParser.h"
#include <stdexcept>
%}
%parse-param {FlexLexer& lexer}
%lex-param {FlexLexer& lexer}
%token JSON_STRING
%token JSON_NUMBER
%token JSON_TRUE
%token JSON_FALSE
%token JSON_NULL
%%
JsonObject : JsonMap {LOG("JsonObject: JsonMap");}
| JsonArray {LOG("JsonObject: JsonArray");}
JsonMap : '{' JsonMapValueListOpt '}' {LOG("JsonMap: { JsonMapValueListOpt }");}
JsonMapValueListOpt : {LOG("JsonMapValueListOpt: EMPTY");}
| JsonMapValueList {LOG("JsonMapValueListOpt: JsonMapValueList");}
JsonMapValueList : JsonMapValue {LOG("JsonMapValueList: JsonMapValue");}
| JsonMapValueList ',' JsonMapValue {LOG("JsonMapValueList: JsonMapValueList , JsonMapValue");}
JsonMapValue : JSON_STRING ':' JsonValue {LOG("JsonMapValue: JSON_STRING : JsonValue");}
JsonArray : '[' JsonArrayValueListOpt ']' {LOG("JsonArray: [ JsonArrayValueListOpt ]");}
JsonArrayValueListOpt : {LOG("JsonArrayValueListOpt: EMPTY");}
| JsonArrayValueList {LOG("JsonArrayValueListOpt: JsonArrayValueList");}
JsonArrayValueList : JsonValue {LOG("JsonArrayValueList: JsonValue");}
| JsonArrayValueList ',' JsonValue {LOG("JsonArrayValueList: JsonArrayValueList , JsonValue");}
JsonValue : JsonMap {LOG("JsonValue: JsonMap");}
| JsonArray {LOG("JsonValue: JsonArray");}
| JSON_STRING {LOG("JsonValue: JSON_STRING");}
| JSON_NUMBER {LOG("JsonValue: JSON_NUMBER");}
| JSON_TRUE {LOG("JsonValue: JSON_TRUE");}
| JSON_FALSE {LOG("JsonValue: JSON_FALSE");}
| JSON_NULL {LOG("JsonValue: JSON_NULL");}
%%
int yylex(int*, FlexLexer& lexer)
{
return lexer.yylex();
}
void yy::JsonParser::error(yy::location const&, std::string const& msg)
{
throw std::runtime_error(msg);
}
</code></pre>
<h3>main.cpp</h3>
<pre><code>#include "JsonParser.tab.hpp"
#include <iostream>
int main()
{
try
{
yyFlexLexer lexer(&std::cin, &std::cout);
yy::JsonParser parser(lexer);
std::cout << (parser.parse() == 0 ? "OK" : "FAIL") << "\n";
}
catch(std::exception const& e)
{
std::cout << "Exception: " << e.what() << "\n";
}
}
</code></pre>
<h3>JsonParser.h</h3>
<pre><code>#ifndef THORSANVIL_JSON_PARSER_H
#define THORSANVIL_JSON_PARSER_H
#ifndef IN_LEXER
#include <FlexLexer.h>
#endif
int yylex(int*, FlexLexer& lexer);
#ifdef DEBUG_LOG
#include <iostream>
#define LOG(x) std::cout << x << "\n"
#else
#define LOG(x) 0 /*Empty Statement that will be optimized out*/
#endif
#endif
</code></pre>
<h2>Makefile</h2>
<pre><code>YACC = bison
LEX = flex
CXX = g++
CXXFLAGS = -DDEBUG_LOG
TARGET = json
LEX_SRC = $(wildcard *.l)
YACC_SRC = $(wildcard *.y)
CPP_SRC = $(filter-out %.lex.cpp %.tab.cpp,$(wildcard *.cpp))
SRC = $(patsubst %.y,%.tab.cpp,$(YACC_SRC)) $(patsubst %.l,%.lex.cpp,$(LEX_SRC)) $(CPP_SRC)
OBJ = $(patsubst %.cpp,%.o,$(SRC))
all: $(OBJ)
$(CXX) -o test $(OBJ) -lFl
clean:
rm $(OBJ) $(patsubst %.y,%.tab.cpp,$(YACC_SRC)) $(patsubst %.l,%.lex.cpp,$(LEX_SRC))
$(TARGET): $(OBJ)
$(CXX) -o $* $(OBJ)
.PRECIOUS: %.tab.cpp
%.tab.cpp: %.y
$(YACC) -o $@ -d $<
.PRECIOUS: %.lex.cpp
%.lex.cpp: %.l
$(LEX) -t $< > $@
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T08:30:14.793",
"Id": "26521",
"Score": "3",
"body": "What is C++ or object oriented about this? Flex & Bison generate C code. The only C++ code that is see is the test code written in main.cpp. Either you call it a C parser or use [flex and bison equivalent for C++](http://code.google.com/p/flexpp-bisonpp/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T15:53:25.740",
"Id": "26532",
"Score": "6",
"body": "@apeirogon: Actually flex and bison both generate C++ classes see `%option c++` and `%skeleton \"lalr1.cc\"`. But this is not really relevant. It is the interface the lexer and scanner present to the world that make the code OO. The current interface is OO allowing you to use parser/lexer independently and in a very OO manor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T15:57:51.273",
"Id": "26533",
"Score": "4",
"body": "@apeirogon: Also the link you provide actually states that those tools have now atrophied while the real flex and bison have continued to be developed. **<quote>** But releases ended in 1993 and flex++ and bison++ fell out of date as C++, gcc, **flex**,and **bison** all evolved **</quote>**. So I think I will stick to using real development tools rather than somebodies abandoned project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-08T16:00:39.880",
"Id": "26535",
"Score": "1",
"body": "The real reason that I put C++ rather than C down is that I don't write C anymore. So the glue code is C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-14T06:27:55.760",
"Id": "27860",
"Score": "1",
"body": "@LokiAstari: May I ask, why do you not write C anymore? The topic interests me, as I see multiple different people both criticize C++ for its weaknesses and praise it for its strengths, many of which seem like valid arguments to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-14T18:10:16.937",
"Id": "27878",
"Score": "0",
"body": "@voithos: Both groups of people are correct. C++ has its good points and its bad. I would love to discuss it but this is not the correct forum (and I am not sure were is (and I am probably not as great an expert as you want (Top ten on this list would be better experts than I: http://stackoverflow.com/tags/c%2b%2b/topusers))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-15T01:45:34.177",
"Id": "27898",
"Score": "0",
"body": "@LokiAstari: Gah! Imbalanced parentheses! (Jokes aside, I understand. However, you said top ten... guess who's #10 on that list...? :D)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-01-06T22:03:28.173",
"Id": "32324",
"Score": "0",
"body": "@LokiAstari, you may want to look at [ANTLR](http://www.antlr.org) as alrternative to lex/yacc/flex/bison"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-09T19:48:50.457",
"Id": "97250",
"Score": "0",
"body": "The code looks good: nothing to add or remove."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-30T13:57:54.963",
"Id": "136745",
"Score": "0",
"body": "I think `{DIGIT1}{DIGIT}*` is **not** going to handle `0`. So it should be `{DIGIT1}{DIGIT}*|0`. BTW, will it handle negative integer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-30T17:54:35.633",
"Id": "136806",
"Score": "0",
"body": "@Nawaz: You will notice that the parser reads `NUMBER` which handles the `0/Float/Int` and negative issues separately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-30T19:23:44.047",
"Id": "136818",
"Score": "0",
"body": "Ohh... I saw that now."
}
] |
[
{
"body": "<p>I've hesitated for quite a while, but decided there are a few points worth commenting on.</p>\n\n<p>The first and most obvious is that (by design) this simply doesn't do much. It can log the types of statements encountered in the JSON you give to it, but that's all. To be of much real use, you'd normally want to create something at least vaguely AST-like, storing the JSON input data as a set of nodes with attributes describing the data in the nodes.</p>\n\n<p>Alternatively, you could build some sort of call-back style framework where the parser called a specific function when each type of input was detected, and it would be up to the client code to decide how to store the data (and which data to store).</p>\n\n<p>As it stands right now, however, the most it can produce is a description of the overall structure of the input file. If that's really all you want, I think it's worth considering whether you're trying to produce output to be read by people or by the machine for further processing.</p>\n\n<p>If you want human-readable output, I think I'd prefer that somewhat more processing be done on the data before it was printed out. For example, as it stands now, an array like <code>[1, 2, 3, 4]</code> would produce a line of output for the JSON array, another for the value-list, and another for each item in the array.</p>\n\n<p>If I'm going to read the file, I think I'd generally prefer those log entries coalesced into something like <code>Array (4 Numbers)</code>. Given that the intent is for this to parse JSON, it's probably sufficient specify \"JSON\" in one place in the output, rather than prefixing <em>every</em> single line of output with \"JSON\". In short, as it stands right now, this produces output that's extremely verbose, leading to very low information density, so the reader needs to read and digest a great deal of output to understand even a relatively small amount of input--in fact, I'm pretty sure it would usually be easier to read the input file directly.</p>\n\n<p>If your primary intent is to produce output for the computer to read for further processing, it's less necessary to go to extra work to coalesce the information, but still useful to keep the information compact. Given the small number of possibilities in a JSON file, I'd probably assign a single letter to each of the strings the parser can now produce, and just write those out. Alternatively, do some coalescing here as well, so repetitions of the same pattern are signaled by the pattern (in parentheses if it's more than one letter) followed by a number in brackets. For example, a map of 4 string/number pairs followed by an array of 6 numbers might come out something like: <code>M(SN)[4]AN[6]</code>. This is still somewhat human readable (if necessary), and a lot quicker for a parser on the receiving end to sort out (not to mention just being a lot less data to store, transmit, etc.)<sup>1</sup></p>\n\n<p>As far as the style of code itself goes, I really have only a few comments, and pretty minor ones at that.</p>\n\n<ol>\n<li><p>Given a list of alternatives like:</p>\n\n<pre><code>production : \n | Alternative1\n | Alternative2\n</code></pre>\n\n<p>I prefer to add a semicolon to signal the end of the list:</p>\n\n<pre><code>production : \n | Alternative1\n | Alternative2\n ;\n</code></pre></li>\n<li><p>This is at a large scale, and may even be out of your control, but I found this code:</p>\n\n<pre><code>try\n{\n yyFlexLexer lexer(&std::cin, &std::cout);\n yy::JsonParser parser(lexer);\n\n std::cout << (parser.parse() == 0 ? \"OK\" : \"FAIL\") << \"\\n\";\n}\ncatch (std::exception const& e)\n{\n std::cout << \"Exception: \" << e.what() << \"\\n\";\n}\n</code></pre>\n\n<p>...somewhat ugly. Combining return values and exceptions like this, and having to respond to both makes it seem rather...disjointed. I'd rather see one style adopted throughout, so you can depend on failure always being signaled by throwing an exception or else that it's always signaled by the return value. As it stands right now, we not only end up with this code being fairly ugly, but we also end up with rather uneven error reporting--errors reported via exception may have fairly detailed error messages, but those reported via return value all produce an identical (and probably unhelpful) \"FAIL\".</p></li>\n</ol>\n\n<hr>\n\n<p><sup>\n1. I haven't tried to work through all the details of ensuring that nested structures would remain unambiguous, but at least offhand it doesn't seem terribly difficult.\n</sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-30T18:08:37.410",
"Id": "136808",
"Score": "1",
"body": "Yep. The LOG() is solely meant for debugging purposes (not for actual output). In the state above it does nothing (deliberately); that's why I used the term Framework. So you need to plug more code in here to make it useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-30T18:09:41.490",
"Id": "136809",
"Score": "3",
"body": "Given point-2 above I definitely agree. The combination of exceptions and returns code is not a good style. It makes the usage horrible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-29T15:04:54.287",
"Id": "55612",
"ParentId": "7536",
"Score": "18"
}
}
] |
{
"AcceptedAnswerId": "55612",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T17:26:31.463",
"Id": "7536",
"Score": "48",
"Tags": [
"c++",
"parsing",
"json",
"lex",
"yacc"
],
"Title": "Yet another C++ JSON parser"
}
|
7536
|
<p>I've taken criticism before on my PHP and have since then taken the improvements into my routine. However, I still believe that I can improve.</p>
<p>I believe that SE is the best place for the best programmers. If any of you are bored enough to tell me what I can do better, I'd appreciate it greatly.</p>
<p>You can see a small project of mine, using pretty basic PHP here:
<a href="https://github.com/OutThisLife/Fae-Studio---Finances" rel="nofollow">https://github.com/OutThisLife/Fae-Studio---Finances</a> -- the site is <a href="http://finance.faestudio.com/" rel="nofollow">http://finance.faestudio.com/</a></p>
<p>Very basic PHP, but I believe it holds most of what I usually do across the board. MySQLi, OO PHP, an MVC-type system.</p>
<p>The MVC-type system was one of the improvements that was suggested. Am I doing it right?</p>
<p>The page that controls the entire project:</p>
<pre><code>require('classes/autoloader.php');
if(isset($_SESSION['uid'])) {
$file = @$_GET['u'] ? $_GET['u'] : 'tasks';
} else {
$file = 'login';
}
$T = new Template($file);
// Load by-page controllers
$T->controller($T->file);
// Set menu
$T->menu = $T->getModule('menu');
$T->pagename = $T->file;
$T->jscall = ucwords($T->file);
$T->render();
</code></pre>
<p>Template Class:</p>
<pre><code>class Template {
public
$file; // filename
private
$template, // placeholder
$data; // stored variables
public function __construct($file) {
$this->template = self::_s('wrapper');
$this->file = $file;
$this->data['LOAD'] = self::_s($this->file);
}
public function __set($key, $val) { $this->data[$key] = $val; }
public function __get($key) { return $this->data[$key]; }
private function replaceAll() {
foreach($this->data AS $key => $val)
$this->template = str_replace( /* {TAGS} are simple variables */
'{'.$key.'}',
$val,
$this->template
);
self::clean();
}
public function fillInData($array) {
foreach($array AS $key => $val) $this->$key = $val;
}
private function clean() {
$regex = '/{([^{|}]\S*)}/'; // all {tags} w/o spaces
$this->template = preg_replace($regex, NULL, $this->template);
}
public function render() {
self::replaceAll();
echo $this->template;
}
public function getModule($file, $dir = 'modules') {
return self::_s($file, $dir);
}
public function _s($file, $type = 'views') { // quick file_get_contents
return file_get_contents($type.'/'.$file.'.php');
}
public function controller($file) {
$filepath = './controllers/'.$file.'.php';
if(file_exists($filepath))
include($filepath);
}
}
</code></pre>
<p>Example of how I am handling my controllers:</p>
<pre><code>global
$T;
$tasks = new Tasks();
$T->num = $tasks->taskCount;
// Pending task HTML output
if(is_array($tasks->pending)): foreach($tasks->pending AS $r):
$T->pending_tasks .= '
<label class="task">
<input type="checkbox" name="done[]" rel="'.$r['id'].'" />
<code>'.@money_format('$%i', $r['cost']).'</code> &mdash;
'.$r['title'].'
</label>'."\n";
endforeach;
else:
$T->pending_tasks = '<label class="task"></label>';
endif;
// Completed task HTML output
if(is_array($tasks->completed)): foreach($tasks->completed AS $r):
$T->completed_tasks .= '
<label class="task complete">
<input type="checkbox" name="done[]" rel="'.$r['id'].'" checked="checked" />
<code>'.@money_format('$%i', $r['cost']).'</code> &mdash;
'.$r['title'].'
</label>'."\n";
endforeach;
else:
$T->completed_tasks = '<label class="task"></label>';
endif;
</code></pre>
<p>Class example:</p>
<pre><code>class Tasks {
private
$db,
$uid;
public
$pending,
$taskCount,
$completed;
public function __construct() {
$this->db = DB::getInstance();
$this->uid = $_SESSION['uid'];
$this->getTasks('pending');
$this->getTasks('completed');
}
private function getTasks($key) {
switch($key):
case 'pending':
$query = '
SELECT id, title, cost
FROM tasks
WHERE (
status IS FALSE
AND uid = \''.$this->uid.'\'
) ORDER BY cost DESC
';
break;
case 'completed':
$query = '
SELECT id, title, cost
FROM tasks
WHERE (
status IS TRUE
AND uid = \''.$this->uid.'\'
) ORDER BY id DESC
LIMIT 7
';
break;
endswitch;
$result = $this->db->query($query);
if(!$result) die($db->error);
else {
while($row = $result->fetch_assoc()) $r[] = $row;
if($key === 'pending')
$this->taskCount = $result->num_rows;
$this->$key = $r;
}
$result->close();
}
}
</code></pre>
<p>The view for the above controller:</p>
<pre><code><header>
<h1>Tasks</h1>
</header>
<div id="main" role="main">
<form id="cev" class="basic_data">
<code><strong>{num}</strong> pending tasks</code>
</form>
<br />
<h2>Pending</h2>
<div id="pending_tasks">
{pending_tasks}
</div>
<div id="add_task">
<span id="add_new_task_link">Add New Task</span>
<form method="post" action="/">
<label for="new_task_title">Title</label>
<input type="text" name="new_task_title" id="new_task_title" />
<br /><br />
<label for="new_task_cost">Amount</label>
<input type="text" name="new_task_cost" id="new_task_cost" />
<br /><br />
<label>&nbsp;</label>
<button type="submit">Create</button>
&nbsp; <a href="#" id="cancel_new_task">Cancel</a>
</form>
</div>
<br />
<h2>Completed</h2>
<div id="completed_tasks">
{completed_tasks}
</div>
</code></pre>
<p></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-04T23:34:06.427",
"Id": "181561",
"Score": "0",
"body": "The title of your post should be the function/purpose of your code."
}
] |
[
{
"body": "<p>I've not reviewed the whole piece of code yet but I spotted two things right away just three lines in. </p>\n\n<pre><code>$file = @$_GET['u'] ? $_GET['u'] : 'tasks';\n</code></pre>\n\n<p>There are two problems with this. The first is the use of @ to suppress errors. This is considered bad practice a lot of a time, because it can hide errors that are needed for you to debug the application. Your live and staging environments should be set up with display_errors off, and in your dev and test servers you want to see errors as they happen. It apparently also hurts performance. </p>\n\n<p>The second, and FAR more serious problem, is you're trusting data input from an outside source, in this case $_GET. </p>\n\n<p>I cannot overstress what a serious error this is, it can leave your system wide open to being hacked, destroyed, forced to expose private data or to trigger a denial of service attack. Probably 9 out of 10 bugs in PHP code (or any code in fact) are down to programmers trusting data to contain what they expect it to. </p>\n\n<p>In this case, all an attacker has to do is type the url of your script and add ?u=/etc/passwd et viola, he now has a list of all the users on your server along with hashes of their passwords. If anyone has chosen a weak password (hint: Someone on your system will choose a weak password), then they can brute force the hash and recover the password, then log into your server with access to all that user's files and with all that user's privilages. If the user in question has high level access (or God forbid is root), then you're really screwed. </p>\n\n<p>Always follow the Fox Mulder principle when you are dealing with input from outside your programs, in otherwords TRUST NO ONE! Never accept that the contents of $_GET, $_POST, $_COOKIE and so on contain nothing that could cause you harm. Always validate all input. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T13:26:38.547",
"Id": "11842",
"Score": "0",
"body": "`Fox Mulder principle` - Nice! Good review, +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T15:22:37.730",
"Id": "11900",
"Score": "0",
"body": "@GordonM: All good stuff :) - but I don't think the risks here are as bad as all that: in the Template class the OP does this in the constructor:\n\n public function _s($file, $type = 'views') {\n return file_get_contents($type.'/'.$file.'.php');\n }\n\nSo by default it's loading variants of views/whatever.php\n\nMaybe I'm missing something but some variant of this seems pretty normal practice in front controller MVC. Probably a good idea to filter for special characters and strip them out of the input string, but I don't see a problem with the basic approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T16:40:06.950",
"Id": "11905",
"Score": "0",
"body": "$_GET is controlled via mod_rewrite and only allows certain variables; in this case, tasks/client/stocks/history. Anything else would be denied by the htaccess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T17:21:54.887",
"Id": "11911",
"Score": "0",
"body": "@TalasanNicholson: Assuming that is a fatal mistake. Don't EVER assume that $_GET contains safe data. A well meaning sysadmin may disable .htaccess files at some point in the future without you knowing, should that happen you'll be wide open."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T21:18:23.993",
"Id": "7541",
"ParentId": "7539",
"Score": "4"
}
},
{
"body": "<p>Some quick thoughts:</p>\n\n<ol>\n<li><p>Overall I think this is mostly quite nice code but has some issues</p></li>\n<li><p>Using global $T in controller? Don't like single letter variable names for this, and why not pass the object into the controller instead of using global to get at it? Dependencies should be injected into the class, it shouldn't go out and grab stuff from wherever it wants.</p></li>\n<li><p>You're building HTML in the controller; I think this should be in the view or in a view helper</p></li>\n<li><p>Don't like this: </p>\n\n<pre><code>$result = $this->db->query($query);\nif(!$result) die($db->error);\n</code></pre>\n\n<p>I don't think you should ever use die() in production code. This will cause a white screen of death for the user - unpleasant - and depending on your error settings could expose the SQL error and information about your query if there's a problem on the production site - unpleasant and a security risk. Surely better to throw an exception, catch it, log an error and display a sensible error screen to the user</p></li>\n<li><p>Inconsistent use of _ in front of private method names. Personally I dislike it, but if you're going to do it, you should do it consistently. And using single letter names again forces one to go and read what the method does to understand what it is, making the code significantly less readable</p></li>\n<li><p>Method names in my opinion are more readable if they're based on verbs; mostly you've made good names but Template->controller might be better if it was loadController or something. More to the point though, why is the template loading a controller in the first place? Shouldn't the controller load the template?</p></li>\n</ol>\n\n<p>I think you might run into problems if you had to add in support for RSS, XML or JSON later on instead of just loading HTML views and replacing data in them</p>\n\n<p>So maybe have a think about the bigger picture of how you've structured this. I think controllers should retrieve data, decide what sort of output to build, and then delegate the building of the output to something else, which could be the HTML template class or something else</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T15:45:02.077",
"Id": "7589",
"ParentId": "7539",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T20:08:05.783",
"Id": "7539",
"Score": "0",
"Tags": [
"php",
"mvc"
],
"Title": "I want to improve my overall PHP"
}
|
7539
|
<p>This is my solution to the codercharts problem <a href="http://codercharts.com/puzzle/word-swap" rel="nofollow">http://codercharts.com/puzzle/word-swap</a> but if keeps failing when I submit the solution because of the <code>cpu_excess_time</code>. Please suggest possible optimisations for this problem, I believe my solution is correct but not optimal.</p>
<pre><code>#!/usr/bin/python
def swap_words(first_word,second_word,word_dict):
wd = word_dict
#if the first word is equal to second ,
# we have got the target word
if first_word == second_word:
return [first_word]
for word in word_dict:
if len(word) == len(first_word) and \
sum([x != y for x,y in zip(list(first_word),list(word))]) == 1:
wd.remove(word)
ret = swap_words(word,second_word,wd)
if ret != False:
ret.append(first_word)
return ret
return False
if __name__ == '__main__':
import sys
filename = sys.argv[1]
first_word = sys.argv[2]
second_word = sys.argv[3]
text = open(filename).read()
word_dict = text.split('\n')
word_list = swap_words(first_word,second_word,word_dict)
for word in reversed(word_list):
print word
</code></pre>
|
[] |
[
{
"body": "<p>Simple optimizations:</p>\n\n<p>By reading the whole file into text, then splitting the text into a word list, you will need enough memory to hold two copies of the file, which might be huge. Look into line-by-line input methods.</p>\n\n<p>Many strings, after a quick check, don't need to be seen ever again.</p>\n\n<p>The off-by-one-letter test does not ALWAYS need to process every letter in the words.</p>\n\n<p>You never actually have to find the target word in the word list to know you have a solution (you know it's in there from the problem description). Some simpler solutions don't even need to consult the word list.</p>\n\n<p>Deeper optimizations:</p>\n\n<p>If you had a way to test which \"next\" words were more likely to lead to a solution, you might be able to defer other alternatives to explore those first, for a faster average solution time.</p>\n\n<p>It MIGHT make more sense to solve the problem working backwards or both ways at once.</p>\n\n<p>It MIGHT be worthwhile to keep stats on different words you find and/or to place words that seem like they might be useful later in some kind of separate structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T05:44:00.470",
"Id": "7546",
"ParentId": "7540",
"Score": "1"
}
},
{
"body": "<p>\"Make it right then make it fast\".</p>\n\n<p>I'm afraid your algorithm is not correct.\nIt fails to trace <code>AA -> BB</code> within this simple dict :</p>\n\n<pre><code>AA\nAB\nAC\nBB\n</code></pre>\n\n<p>Now, let :</p>\n\n<pre><code>s = words size \nN = dict size\nn = numbers of s-sized words in dict\n</code></pre>\n\n<p>It may take <code>s!</code> tries (at worst) to find the good path.<br>\nSo your approach, once backtracking issue fixed, would be roughly <code>O(s! * s * (N + n*s))</code>.<br>\nIf, instead, you check whether new candidates (created by putting 1 letter from target word) belong to dict, complexity melts down to <code>O(s! * s)</code> (approximating hash look-up complexity to constant time).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T08:51:29.810",
"Id": "7548",
"ParentId": "7540",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T21:11:07.320",
"Id": "7540",
"Score": "2",
"Tags": [
"python"
],
"Title": "CoderCharts puzzle optimization"
}
|
7540
|
<p>I started a web project. Now I was wondering if it is secure enough. I followed some tutorials on HTS, but I can't see all holes (if there are any). Can you check my pages and if you can find any hole in it (like XSS or SQL injections). Thanks for helping :)!</p>
<p>My URL is: **</p>
<p>And another security question: is my HTTPS certificate safe enough? (**) And my SMTP/SSH/... services?</p>
<p>You can now login using: user: <code>demo</code>, password: <code>test123</code></p>
<p>User controller code:</p>
<pre><code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller {
public function create() {
setHTTPS();
if ($this->form_validation->run() == false) {
$this->load->view('user/create');
} else {
$this->MUser->create();
$this->load->view('user/email_sent');
}
}
public function login() {
setHTTPS();
if ($this->form_validation->run() == false) {
$this->load->view('user/login');
} else {
$this->MUser->createSession();
$this->MUser->checkLogin();
$this->load->view('user/dashboard');
}
}
public function logout() {
setHTTPS();
if ($this->MUser->login()) {
$this->MUser->logout();
$this->load->view('user/logout');
} else {
$this->load->view('user/logout_failed');
}
}
public function dashboard($username) {
setHTTPS();
$this->MUser->checkLogin();
$this->load->view('/user/dashboard');
}
public function verify($userID, $code) {
setHTTPS();
$safeCode = urldecode($code);
if ($this->MUser->checkVerifyCode($userID, $safeCode)) {
$this->MUser->cleanVerifyCode($userID);
$this->MUser->setActive($userID);
mailSignupComplete($userID);
$this->load->view('user/signup_complete');
} else {
$this->load->view('user/validation_failed');
}
}
public function password($userID = null, $verifier = null) {
setHTTPS();
if ($userID !== null) {
$safeCode = urldecode($verifier);
if ($this->MUser->checkPasswordCode($userID, $safeCode)) {
$this->MUser->updatePassword($userID);
$this->load->view('user/password_succes');
} else {
$this->load->view('user/password_failed');
}
} else {
if ($this->form_validation->run() == false) {
$this->load->view('user/password');
} else {
$this->MUser->addRecoverPasswordEntry();
$this->load->view('user/password_sent');
}
}
}
}
/* End of file user.php */
/* Location: ./application/controllers/user.php */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T05:54:15.580",
"Id": "11838",
"Score": "0",
"body": "I can't scroll down on [this page](https://websilon.org/user/create/). Chrome Canary 18.x."
}
] |
[
{
"body": "<p>Check your MySQL database. If you have another table called \"websiteIsNotSecure\" then you need to sanitize your database inputs. Also, it'd be easier to check security if we had some code to look at. You can't view PHP code, it's all parsed/executed on the server.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T00:45:08.820",
"Id": "11833",
"Score": "0",
"body": "I saw you tries :), no, your `CREATE COLUMN` code was in the table where users are stored. I can't share code due security reasons. But I can tell it runs on CodeIgniter 2.1.0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T02:03:34.283",
"Id": "11834",
"Score": "1",
"body": "Not sharing code 'due to security reasons' always sounds like 'it's very unsecure but i hope noone finds all the holes' (which someone will usually find if he wants to)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T10:40:42.497",
"Id": "11841",
"Score": "0",
"body": "Ok, I'll share my `user` controller. This would be the most vurnable file."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T00:37:06.090",
"Id": "7544",
"ParentId": "7543",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T00:30:20.063",
"Id": "7543",
"Score": "1",
"Tags": [
"php",
"javascript",
"optimization",
"html",
"security"
],
"Title": "My web project security"
}
|
7543
|
<p>I've got a module I use to log around functions that performs external requests.</p>
<pre><code># Functions to track when a block begins and ends
module LogAround
# log at begin and end of a given block
# with a mesage and the given params
def log_around(message, *args)
start_time = Time.now
Rails.logger.info "#{message}(#{args.inspect}) - start"
result = yield
ensure
end_time = Time.now - start_time
Rails.logger.info "#{message}(#{args.inspect}) - end (#{end_time}s)"
result
end
end
</code></pre>
<p>This module is used in this way:</p>
<pre><code>class Wrapper
include LogAround
# TODO: log_around :get_artist
alias_method :_orig_get_artist, :get_artist
# log the external request
def get_artist(*args)
log_around 'Discogs::Wrapper.get_artist', *args do
_orig_get_artist *args
end
end
end
</code></pre>
<p>This solution is much closer to what I want compared with what I had before, but ideally what I'm looking for is a function in <code>LogAround</code> that could be used in this way</p>
<pre><code># this class is already defined by Discogs
# and this is a customization
class Wrapper
include LogAround
log_around :get_artist
end
</code></pre>
<p>and provides the same (or better params list) output, which is:</p>
<pre><code>Discogs::Wrapper.get_artist(["pink floyd"]) - start
Discogs::Wrapper.get_artist(["pink floyd"]) - end (1.919805308s)
</code></pre>
|
[] |
[
{
"body": "<p>You may not define a free message, but I think this may be a solution:</p>\n\n<pre><code>module LogAround\n # log at begin and end of a given block\n # with a mesage and the given params\n def log_around( method_to_log )\n alias_method \"_orig_#{method_to_log}\".to_sym, method_to_log\n\n define_method(method_to_log ){ | *args, &blck | \n start_time = Time.now\n\n puts \"call #{method_to_log} with args #{args.inspect} #{'and a block' if blck} \"\n result = send \"_orig_#{method_to_log}\".to_sym, *args, &blck\n\n end_time = Time.now - start_time\n puts \"called #{method_to_log} with args #{args.inspect} - (#{end_time}s)\"\n result\n }\n end #self.log_around( method_to_log )\nend\n\nclass Wrapper\n\n def test\n puts 'in test'\n sleep 1.2\n end\n\n def test_with_block\n puts 'in test_with_block'\n yield\n end\n\n extend LogAround\n log_around :test\n log_around :test_with_block\nend\n\nWrapper.new.test\nWrapper.new.test_with_block { puts 'inside block' }\n</code></pre>\n\n<p>Remarks:</p>\n\n<ul>\n<li><code>Rails.logger.info</code> is replaced by <code>puts</code></li>\n<li>I <code>extend</code>ed, not <code>include</code>d LogAround (<code>log_around</code> should be a class method, not an instance method).</li>\n<li>not well tested ;)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:45:07.233",
"Id": "11861",
"Score": "0",
"body": "thanks, that's a good solution, and yes, I agree `LogAround` had to be extended and not included"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T01:39:17.283",
"Id": "11872",
"Score": "0",
"body": "Nothing prevents you to include LogAround in this particular case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T15:37:15.640",
"Id": "7550",
"ParentId": "7549",
"Score": "4"
}
},
{
"body": "<p>If you are using Rails (and it seems so, because you used <code>Rails.logger</code>) you can use the <code>alias_method_chain</code> function.</p>\n\n<pre><code># Functions to track when a block begins and ends\nmodule LogAround\n extend ActiveSupport::Concern\n\n # Log before and after its block\n # with a message and the given params\n def log_around(message, *args)\n start_time = Time.now\n Rails.logger.info \"#{message}(#{args.inspect}) - start\"\n result = yield\n ensure\n end_time = Time.now - start_time\n Rails.logger.info \"#{message}(#{args.inspect}) - end (#{end_time}s)\"\n result\n end\n\n module ClassMethods\n def log_around(*methods)\n names = methods.flatten.map(&:to_sym)\n names.each do |name|\n class_eval <<-RUBY\n def #{name}_with_logging(*args, &block)\n log_around(self.class.name + '##{name}') do\n #{name}_without_logging(*args, &block)\n end\n end\n RUBY\n alias_method_chain name, :logging\n end\n end\n end\n\nend\n</code></pre>\n\n<p>Here's an example usage:</p>\n\n<pre><code>class Foo\n include LogAround\n\n def bar\n puts \"hello\"\n end\n log_around :bar\nend\n</code></pre>\n\n<p>It's important to note that <code>log_around</code> may only be called after its argument method (here, <code>bar</code>) has been defined.</p>\n\n<p>It also supports multiple methods.</p>\n\n<pre><code>log_around :foo, :bar, :baz\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-03T08:59:30.563",
"Id": "296824",
"Score": "0",
"body": "Is there a way of mixing it into all project classes without having to manually add the `include` to each file?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T17:21:40.833",
"Id": "7553",
"ParentId": "7549",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T13:39:15.653",
"Id": "7549",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Log around a function call"
}
|
7549
|
<p>I wrote a web files browser. I want to refactor my JavaScript code, but I'm new to JavaScript. </p>
<p>I have some thoughts:</p>
<ol>
<li><p>Split the file into several files:</p>
<ul>
<li><code>FoldersManager.js</code></li>
<li><code>FilesManager.js</code></li>
<li><code>Paginator.js</code></li>
<li><code>GlobalVars.js</code></li>
</ul>
<p>Do you have any other ideas?</p></li>
<li><p>Naming conventions: How should functions\vars names be written?</p></li>
<li><p>I wrote my code flat. How can I refactor it to objects easily?</p></li>
</ol>
<p></p>
<pre><code>var folders_tree;
var data_per_folder = [];
var current_folder = {};
// folder_id: "",
// folder_name: ""
//};
var current_page = 1;
var file_types_lookup = [];
$(function () {
fillFileTypesLookup();
// set topbar_links onClick to alter div content
$(".nav li a").attr({
"onclick": "topbarItem_OnClick(this.href)"
});
// set pagination onClick to alter div file_content
$(".pagination li a").attr({
"onclick": "paginationItem_OnClick(this)"
});
$("#add_folder").click(function () {
$('#new_folder_modal').modal('show');
});
$("#remove_folder").click(function () {
sendDeleteFolderRequestAndUpdateFilesTree();
});
$("#edit_folder").click(function () {
$('#edit_folder_name').val(current_folder.attr('name'));
$('#edit_folder_color').val(current_folder.attr('color'));
$('#edit_folder_description').val(current_folder.attr('description'));
$('#edit_folder_modal').modal('show');
});
//otherwise will create modal with default values.
$('#extra_details_modal').modal({
backdrop: true,
keyboard: true
});
//otherwise will create modal with default values.
$('#new_folder_modal').modal({
backdrop: true,
keyboard: true
});
//set jsTree
$("#jstree").jstree({
"json_data": {
//initial - demo only, usually takes json from the controller
//static data, or function(node, mappingBeforeRequestToserver)
//"data": data,
//combines with data above
"ajax": {
//data: mappingBeforeRequestToserver-function(node about to be open or -1). `this` will be the tree instance)
//url: function(node about to be open as a paramater or -1) retuns the ajax URL (like /get_children/node_2).
//The error and success functions- modifiying the results from the server before populating the tree
type: "GET",
async: true,
url: function (node) {
if (node == -1) {
return 'Manager/GetLocations';
}
// else {
// return 'Manager/GetAttachments';
// }
},
data: function (node) {
if (node == -1) {
return {
'userId': 'a358ab9d-d481-4bdd-8cb2-18ddc8898c78'
};
}
// else {
// return {
// 'userId': 'a358ab9d-d481-4bdd-8cb2-18ddc8898c78',
// 'count': '5',
// 'locationId': node[0].id,
// 'startIndex': '0'
// };
// }
},
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: true,
success: function (msg) {
// alert("succeeded" + msg);
folders_tree = msg;
return msg;
},
error: function (msg) {
// alert(msg);
}
},
"xsl": "flat",
"override_ui": "true",
"real_checkboxes": "true",
},
"plugins": ["themes", "json_data", "ui", "crrm"]
}).bind("select_node.jstree", onSelectFolder);
});
function topbarItem_OnClick(href) {
$(".pill-content>div").hide();
var indexOfHash = href.indexOf("#");
var selected = href.substring(indexOfHash);
$(selected).show();
};
function paginationItem_OnClick(paginationItem) {
//we are already in a page.
//current_folder.attr('id') and current_folder.attr('name') are not undifined
//paginationItem.attr({class : "active"});
var pageNum = paginationItem.text;
current_page = pageNum;
$(".pagination li.active").removeAttr("class");
$("#pagination_" + pageNum).attr("class", "active");
//console.debug(pageNum);
if (data_per_folder[current_folder.attr('id')].data_per_page[pageNum] == undefined) // no data for pageNum
{
fillAttachmentsPerPage(pageNum);
} else {
populatePage(pageNum);
}
};
function onSelectFolder(event, data) {
topbarItem_OnClick('#files');
current_folder = data.rslt.obj;
//current_folder.attr('id') = data.rslt.obj.attr('id');
//current_folder.attr('name') = data.rslt.obj.attr('name');
if (data_per_folder[current_folder.attr('id')] == undefined) //no data for this folder
{
data_per_folder[current_folder.attr('id')] = {
data_per_page: []
};
}
if (data_per_folder[current_folder.attr('id')].data_per_page[1] == undefined) // no data for first page
{
fillAttachmentsPerPage(1);
} else {
populatePage(1);
}
};
function populatePage(pageNum) {
$("#files_gallery")[0].innerHTML = data_per_folder[current_folder.attr('id')].data_per_page[pageNum].attachments_markup;
$("#files #files_header")[0].innerHTML = '<li><a href="/user/messages"><span class="file_item"> attachments for folder (name: ' + current_folder.attr('name') + ' id : ' + current_folder.attr('id') +
' parentId: ' + current_folder.attr('parentId') + ' description : ' +current_folder.attr('description')+')</span></a></li>';
}
function fillFileTypesLookup() {
if (file_types_lookup.length == 0) // no files types in lookup
{
createAjaxRequest("Manager/GetTopAttachmentTypes", null).done(function (res) {
for (var i = 0; i < res.length; i++) {
file_types_lookup[res[i].TypeId] = res[i];
}
});
}
}
function fillAttachmentsPerPage(pageNum) {
createAjaxRequest("Manager/GetAttachments", {
'userId': 'a358ab9d-d481-4bdd-8cb2-18ddc8898c78',
//'3141a957-05e5-4678-9f5d-4cc9f41d1a00',
'count': '16',
//attachments per page
'locationId': current_folder.attr('id'),
'startIndex': (pageNum - 1) * 16
}).done(function (res) {
//res = IEnumerable<Attachment> Attachments, long TotalCount, long LastIndex
var attachments_divs = "";
for (var i = 0; i < res.Attachments.length; i++) {
//attachment_img = '<a><img src="/Images/Browser/file_types/'+res.Attachments[i].AttachmentTypeId +'.png" title= "name: '+ res.Attachments[i].Name+'"/></a>';
attachment_img = '<img src="' + file_types_lookup[res.Attachments[i].AttachmentTypeId].IconUrl + '" title= "name: ' + res.Attachments[i].Name + '" onclick="Attachment_onClick(\'' + res.Attachments[i].AttachmentId + '\')" />';
attachments_divs = attachments_divs + ' <div> ' + attachment_img + ' </div>';
}
data_per_folder[current_folder.attr('id')].data_per_page[pageNum] = {
first_index: 0,
last_index: res.TotalCount,
count: res.LastIndex,
attachments: res.Attachments,
attachments_markup: attachments_divs,
attachment_extraDetails: []
};
populatePage(pageNum);
});
}
function Attachment_onClick(attachmentId) {
if (data_per_folder[current_folder.attr('id')].data_per_page[current_page].attachment_extraDetails[attachmentId] == undefined) {
createAjaxRequest("Manager/GetAttachmentExtraDetails", {
'attachmentId': attachmentId
}).done(function (res) {
//res = AttachmentExtraDetails: Guid AttachmentId, string MessageLink, string AttachmentLink,
// DateTime SentTime, DateTime ArrivalTime, int Size, Guid SenderFriendId, string SenderEmail
var sentTimeStr = new Date(parseInt(res.SentTime.substring(6,19),10)*1000).toString();
var arrivalTimeStr = new Date(parseInt(res.ArrivalTime.substring(6,19),10)*1000).toString();
var sizeStr;
if (res.Size > 1000)
sizeStr = res.Size / 1000+'.'+ (res.Size % 1000) / 100 +' MB';
else
sizeStr = res.Size +' KB';
var attachments_paragraphs = '<p>Attachment Id: ' + res.AttachmentId + '</p> <p>Message Link: ' + res.MessageLink + '</p>'+
'<p>Attachment Link: ' + res.AttachmentLink +'</p> <p>Sent Time: ' + sentTimeStr + '</p> <p>Arrival Time: ' + arrivalTimeStr + '</p>'+
'<p>Size: '+sizeStr+' </p> <p>Sender Friend Id: '+res.SenderFriendId+'</p> <p>Sender Email: '+res.SenderEmail+' </p>';
data_per_folder[current_folder.attr('id')].data_per_page[current_page].attachment_extraDetails[attachmentId] = {attachments_markup : attachments_paragraphs};
fillExtraDetailsModalAndShow(attachmentId);
});
}
if (data_per_folder[current_folder.attr('id')].data_per_page[current_page].attachment_extraDetails[attachmentId] != undefined) { // not the first time
fillExtraDetailsModalAndShow(attachmentId);
}
};
function fillExtraDetailsModalAndShow(attachmentId){
$(".modal-body").html(data_per_folder[current_folder.attr('id')].data_per_page[current_page].attachment_extraDetails[attachmentId].attachments_markup);
$('#extra_details_modal').modal('show');
};
function sendCreateNewFolderRequestAndUpdateFilesTree()
{
if (validateCreateNewFolderDialog())
{
var new_folder_descriptor = {};
new_folder_descriptor.name = $('#new_folder_name').val();
new_folder_descriptor.color = $('#new_folder_color').val();
new_folder_descriptor.description = $('#new_folder_description').val();
new_folder_descriptor.userId = 'a358ab9d-d481-4bdd-8cb2-18ddc8898c78';
new_folder_descriptor.parentId = current_folder.attr('id');
createAjaxRequest("Manager/CreateNewLocation",
{
'name': new_folder_descriptor.name,
'color' : new_folder_descriptor.color,
'userId' : new_folder_descriptor.userId,
'parentId' : new_folder_descriptor.parentId,
'description' : new_folder_descriptor.description
}).done(function (res) {
if (res.IsSucceeded)
{
new_folder_descriptor.locationId = res.LocationId;
createNewFolderInFilesTree(new_folder_descriptor);
$('#new_folder_modal').modal('hide');
}
//TODO: benda else: error
});
}
};
function validateCreateNewFolderDialog()
{
var isValid = false;
if ($('#new_folder_name').val() != "")
{
$('#new_folder_name_div').attr("class", "clearfix");
isValid = true;
}
else
{
//TODO: benda fix css
//$('#new_folder_name').attr("color", "#b94a48");
// $('#folder_name_div').attr("class", "clearfix error");
}
return isValid;
};
function createNewFolderInFilesTree(new_folder_descriptor)
{
$("#jstree").jstree("create", null, "last", {
"data": new_folder_descriptor.name,
"attr": {
"id": new_folder_descriptor.locationId,
"color": new_folder_descriptor.color,
"description": new_folder_descriptor.description,
"parentId" : new_folder_descriptor.parentId,
"name": new_folder_descriptor.name
},
"state": "opened"
}, null, //null instead of delegate like: function(data) {this.attr('id')= this.data},
true); //"skip_rename"
};
function sendDeleteFolderRequestAndUpdateFilesTree()
{
var new_folder_descriptor = {};
new_folder_descriptor.userId = 'a358ab9d-d481-4bdd-8cb2-18ddc8898c78';
new_folder_descriptor.locationId = current_folder.attr('id');
createAjaxRequest("Manager/DeleteLocation",
{
'locationId' : new_folder_descriptor.locationId
}).done(function (isSucceeded) {
if (isSucceeded)
{
deleteFolderInFilesTree();
//current_folder = {};
}
//TODO: benda else: error
});
};
function deleteFolderInFilesTree()
{
$("#jstree").jstree("remove", null);
};
function sendEditFolderRequestAndUpdateFilesTree()
{
var edit_folder_descriptor = {};
edit_folder_descriptor.userId = 'a358ab9d-d481-4bdd-8cb2-18ddc8898c78';
edit_folder_descriptor.locationId = current_folder.attr('id');
edit_folder_descriptor.name = $('#edit_folder_name').val();
edit_folder_descriptor.color = $('#edit_folder_color').val();
edit_folder_descriptor.description = $('#edit_folder_description').val();;
edit_folder_descriptor.parentId = current_folder.attr('parentId');
createAjaxRequest("Manager/EditLocation",
{
'locationId' : edit_folder_descriptor.locationId,
'name': edit_folder_descriptor.name,
'color' : edit_folder_descriptor.color,
'userId' : edit_folder_descriptor.userId,
'parentId' : edit_folder_descriptor.parentId,
'description' : edit_folder_descriptor.description
}).done(function (isSucceeded) {
if (isSucceeded)
{
current_folder = {};
editFolderInFilesTree(edit_folder_descriptor);
$('#edit_folder_modal').modal('hide');
}
//TODO: benda else: error
});
};
function editFolderInFilesTree(edit_folder_descriptor)
{
var editedNode = $("#"+edit_folder_descriptor.locationId);
editedNode.attr('name',edit_folder_descriptor.name);
editedNode.attr('color',edit_folder_descriptor.color);
editedNode.attr('description',edit_folder_descriptor.description);
editedNode.attr('parentId',edit_folder_descriptor.paretnId);
editedNode.attr('id',edit_folder_descriptor.locationId);
$("#jstree").jstree("refresh", null);
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T16:56:24.503",
"Id": "11844",
"Score": "0",
"body": "naming conventions: Use a [styleGuide](https://github.com/Raynos/pd/blob/master/docs/styleGuide.md) of your choice."
}
] |
[
{
"body": "<p>Your thinking is much better. One thing need to attention: don't left global <code>var</code>s. The best practice is to use global objects, and put the global <code>var</code>s into them.</p>\n\n<p>When you make the object's responsibility clear, make sure every function is in the right object. The code will be much easier to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T17:40:36.323",
"Id": "11996",
"Score": "0",
"body": "can you help me with refactoring one of the objects? I want to see the right form"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T02:14:19.017",
"Id": "7630",
"ParentId": "7551",
"Score": "1"
}
},
{
"body": "<p>A couple notes on design:</p>\n\n<ol>\n<li><p>Split the code up into different objects that handle specific tasks. You don't need to split your code up into different files, because it's not that long (yet), but you can split the functionality into objects, like this:</p>\n\n<pre><code>FoldersManager = {\n\n init: function() {\n $(\"#add_folder\").click(function () {\n $('#new_folder_modal').modal('show'); \n });\n\n ...\n }\n\n};\n</code></pre></li>\n<li><p>Put code that manipulates the DOM into a <a href=\"http://api.jquery.com/ready/\" rel=\"nofollow\"><code>$.ready()</code></a> block, which guarantees that the DOM will be ready when your code executes:</p>\n\n<pre><code>$.ready(function() {\n FoldersManager.init();\n FilesManager.init();\n Paginator.init();\n});\n</code></pre></li>\n<li><p>As ericW mentioned, don't use global variables. They can conflict with global variables from another file which could result in hard-to-find bugs. You can stick them inside the new objects using the following pattern:</p>\n\n<pre><code>$.ready(function() {\n FoldersManager.init();\n FilesManager.init();\n Paginator.init();\n});\n\nFoldersManager = (function() {\n\n var folders_tree;\n var data_per_folder = [];\n var current_folder = {};\n\n return {\n\n init: function() {\n $(\"#add_folder\").click(FoldersManager.openAddFolderDialog);\n\n ...\n },\n\n openAddFolderDialog: function() {\n $('#new_folder_modal').modal('show');\n }\n\n };\n\n});\n</code></pre></li>\n</ol>\n\n<p>And some minor things:</p>\n\n<ol>\n<li><p>Why are you doing things like this:</p>\n\n<pre><code>$(\".nav li a\").attr({\n \"onclick\": \"topbarItem_OnClick(this.href)\"\n});\n</code></pre>\n\n<p>You can use the same <code>$.click()</code> function you were using for the anonymous functions:</p>\n\n<pre><code>$(\".nav li a\").click(function() {\n // or change the function to use the href attribute directly\n // instead of taking it as a param\n topbarItem_OnClick($(this).attr('href'));\n});\n</code></pre></li>\n<li><p>This:</p>\n\n<pre><code>if (data_per_folder[current_folder.attr('id')] == undefined)\n</code></pre>\n\n<p>can be simplified to:</p>\n\n<pre><code>if (!data_per_folder[current_folder.attr('id')])\n</code></pre>\n\n<p>See <a href=\"http://james.padolsey.com/javascript/truthy-falsey/\" rel=\"nofollow\">http://james.padolsey.com/javascript/truthy-falsey/</a> for more info.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T22:05:09.977",
"Id": "7653",
"ParentId": "7551",
"Score": "2"
}
},
{
"body": "<p>People will probably throw things at me for this answer, but here goes.</p>\n\n<p>This advice goes mostly for languages like JS, but has some portability.</p>\n\n<p>In a function, you are typically dealing with an object of primary concern, sometimes it is 'this' -- but other times it can be a concern global to the function, or a concern local to a function part....</p>\n\n<p>To make the code more readable, name such objects generically, like <code>o</code>, or <code>it</code>. Make a comment to what that symbol really means/is at its declaration if you have to. Even if you are dealing with a global var like <code>G.some_long_name</code>, create a local shortname for it:</p>\n\n<pre><code>var o=G.some_long_name;\n</code></pre>\n\n<p>There are trade-offs to this method though - finding refs is not as easy with your editor. But compressed code like this is much easier to read, and makes copy/paste code duplication easier.</p>\n\n<p>Next, do something to your parameter names to make them distinguishable from locals. I put a tail on them, and make them generic too when I can, using <code>o_</code> for object, and <code>n_</code> for name, <code>i_</code> for index.</p>\n\n<p>Use unix_style for private functions, and camelCase for public, unless you are extending a core type prototype, then you might want to use <code>String.prototype.Has</code>, instead of <code>String.prototype.has</code> -- depending on if you want to accentuate a source where something might have gone wrong versus having your extension blend in.</p>\n\n<p>Name your class member vars like <code>_member</code>.</p>\n\n<p>Repetitive code like this should be declared as an object, unless it is going to be changing dynamically:</p>\n\n<pre><code>data_per_folder[current_folder.attr('id')]\n</code></pre>\n\n<p>Use</p>\n\n<pre><code>var f_data=data_per_folder[current_folder.attr('id')];\nf_data.something();\n</code></pre>\n\n<p>And here is a cool trick, instead of </p>\n\n<pre><code>$(\".pagination li.active\").each(...\n</code></pre>\n\n<p>How about</p>\n\n<pre><code>var items=\".pagination li.active\".$();\nitems.each(...\nitems.ect(..\n</code></pre>\n\n<p>using </p>\n\n<pre><code>String.prototype.$=function (){return $(''+this);}\n</code></pre>\n\n<p>You can even make a builder to dynamically create/manage the selectors you are using, a type of meta-selector:</p>\n\n<pre><code>String.prototype.$$=function (){\n var me=''+this;\n var s='';\n if (me=='coolbeans'){\n s+=condition?' #something':'#somethingelse';\n // more...\n }\n // magic\n return s.$();// as per above\n}\n// later\nvar dynamicthings='coolbeans'.$$();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T07:19:24.543",
"Id": "8049",
"ParentId": "7551",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7653",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T14:50:27.080",
"Id": "7551",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"beginner"
],
"Title": "Web files browser"
}
|
7551
|
<p>This is in C/C++ (using a c-string as input). I'm curious if my solution could be more efficient than it currently is.</p>
<pre><code>char mostFrequent(char *bytes, int length) {
char holder[26];
for (int i = 0; i < 26; i++) {
holder[i] = 0;
}
for (int i = 0; i < length; i++) {
holder[bytes[i]-97] += 1;
}
char b = 97; // a
int count = holder[0];
for (int i = 1; i < 26; i++) {
if (holder[i] > count) {
count = holder[i];
b = i+97;
}
}
return b;
}
</code></pre>
|
[] |
[
{
"body": "<p>If you are intended to measure the frequency of bytes, as the name of your input string seems to suggest, rather than just lowercase ASCII letters, then your <code>holder</code> array should be 256 elements long. </p>\n\n<p>This also saves you from all the additions and subtractions of the 'magic' number 97. (Seriously, you could have used 'a'.) </p>\n\n<p>Also, your <code>holder</code> array should consist of <code>int</code>s not <code>char</code>s, because if a certain byte appears more than 256 times in your input string the <code>char</code> will wrap around to zero. Also an array of <code>int</code>s will probably perform more efficiently due to memory alignment.</p>\n\n<p></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T11:00:59.133",
"Id": "11987",
"Score": "2",
"body": "To make something int and claim that it will perform faster is premature optimization. If the particular system has an alignment requirement, it is up to the optimizer to store chars at aligned memory locations. On small, 8-bit or 16-bit embedded systems, an int will on the other hand certainly make the code _slower_. Don't make any assumptions about the system used merely because the OP is some sort of Linux penguin :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T17:45:48.983",
"Id": "7554",
"ParentId": "7552",
"Score": "7"
}
},
{
"body": "<p>I think your solution is optimal in terms of efficiency. One alternative would be to eliminate the last loop which iterates through the <code>holder</code> array to find the maximum by keeping a running max, like this:</p>\n\n<pre><code>int currentMaxChar = 0;\nint currentMax = 0;\nfor (int i = 0; i < length; i++) {\n int c = bytes[i]-97;\n holder[c] += 1;\n if(currentMaxChar == c) {\n currentMax = holder[c];\n }\n else {\n if(currentMax < holder[c]) {\n currentMax = holder[c];\n currentMaxChar = c;\n }\n }\n}\n</code></pre>\n\n<p>But because the last loop has a fixed, extremely small number of iterations, I think your code will probably end up being faster, especially with larger input strings (by using fewer comparisons).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T17:49:39.033",
"Id": "7555",
"ParentId": "7552",
"Score": "2"
}
},
{
"body": "<p>I agree with <em>@Mike Nakis</em>, plus:</p>\n\n<p>1, The first loop could be changed to</p>\n\n<pre><code>int holder[26] = {0};\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c\">How to initialize an array in C</a></p>\n\n<p>2, The second loop doesn't check that <code>bytes[i] - 97</code> is lower than <code>0</code> or greater than <code>26</code> which could cause writes out of the array's memory space.</p>\n\n<p>3, The third loop should be extracted out to a function.</p>\n\n<pre><code>char getMaxIndex(int *input, int length) {\n // TODO: check length, it should be > 0\n int maxIndex = 0;\n int maxValue = 0;\n for (int i = 1; i < 26; i++) {\n if (input[i] > maxValue) {\n maxIndex = i;\n maxValue = input[i];\n }\n }\n\n return maxIndex;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>return getMaxIndex(holder, 26) + 97;\n</code></pre>\n\n<p>It improves readability a lot.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T18:03:44.580",
"Id": "7556",
"ParentId": "7552",
"Score": "4"
}
},
{
"body": "<p>Apart from everything that's been said already, you could improve the code by making it more <code>const</code>-correct. This may be different for C, but in C++, you almost certainly want to have</p>\n\n<pre><code>char mostFrequent(char const* bytes, int length) {\n</code></pre>\n\n<p>This will allow your function to be called with string literals without invoking a deprecated conversion (<code>char const*</code> to <code>char*</code>).</p>\n\n<p>In addition to this, if you know you're going to be working with strings, you might as well have it use null-termination, as you can expect it to be present anyway. It also allows for more elegant (in my opinion) expression of the intent, especially if you use <code>'a'</code> instead of <code>97</code>.</p>\n\n<pre><code>char mostFrequent(char const* bytes) {\n // Leaving this array as it is to change the rest of the code less.\n int holder[26] = {};\n\n for (char const* p = bytes; *p; ++p) {\n if (*p >= 'a' && *p <= 'z') // omit this check if you're sure it's true\n ++holder[*p - 'a'];\n }\n\n // With that out of the way, you can also\n // get rid of some of the 97s here:\n\n int indexOfMax = 0;\n for (int i = 1; i < 26; i++) {\n if (holder[i] > holder[indexOfMax])\n indexOfMax = i;\n }\n return 'a' + indexOfMax;\n}\n</code></pre>\n\n<p>As has been said, you should probably pull the last loop into a different function; I'd say you should pull the array into another function, too. You could use <a href=\"https://stackoverflow.com/questions/5205491/whats-this-stl-vs-c-standard-library-fight-all-about\">the standard library</a> if you're using C++, but this is also a perfectly fine piece of C code.</p>\n\n<p>Something that you haven't shown us are the tests you're running on this code. Assuming you've factored some things out, so that your function looks like this:</p>\n\n<pre><code>char mostFrequent(char const* bytes) {\n int holder[26] = {};\n\n populateFromString(holder, 26, bytes);\n\n return 'a' + findIndexOfMaxIn(holder, 26);\n}\n</code></pre>\n\n<p>Now you can easily test each of the functions separately. For example,</p>\n\n<pre><code>void testPopulationWithAlphabet() {\n char holder[26] = {};\n populateFromString(holder, 26, \"abcdefghijklmnopqrstuvwxyz\");\n for (int i = 0; i < 26; ++i)\n assert(holder[i] == 1);\n}\n\nvoid testFindIndexOfMaxWithNoDuplicates() {\n int arr[5] = {0, 1, 6, 2, 3};\n assert(findIndexOfMaxIn(arr, 5) == 6);\n}\n\nvoid testFindMostFrequentCharacterWithNoTies() {\n assert(mostFrequent(\"helloworld\") == 'l');\n}\n</code></pre>\n\n<p>You probably want some kind of testing framework to run these tests in, although just using <code>assert.h</code> (or <code>cassert</code> in C++) may also be enough. Your function may be fairly short, but 12 lines is non-trivial, and you'll spend less time debugging if you split your code up and write tests for it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T23:51:05.843",
"Id": "7613",
"ParentId": "7552",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7554",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T16:52:16.407",
"Id": "7552",
"Score": "8",
"Tags": [
"c++",
"c",
"strings"
],
"Title": "Finding the most frequent character in a string"
}
|
7552
|
<p>I have just started learning about JavaScript and events. I am interested in learning the JavaScript and not jQuery until I am better at JavaScript.</p>
<p>I wrote this code that will show and hide my div because I basically want to be able to use this code in future web development projects but at the moment it will only apply to one element on page but what if I want to have a few pop up boxes. I understand I will have to have the element positioned absolute.</p>
<p>Can I also ask anyone that is good at JavaScript events to check my code to see if it is well written or if it could be improved? I am just a learning.</p>
<p>To make my questions clearer:</p>
<ol>
<li>How would I make this code more usable for more than one element?</li>
<li>Is my code well written or does it look like a noob wrote it?</li>
</ol>
<pre><code><style>
a#button{
background-color: #FFFF00;
display:block;
}
div#menu{
background-color: #000000;
color: #ffffff;
display:none;
}
</style>
<body>
<a id="button" href="#">Click Me</a>
<div id="menu">SUPRISE</div>
<script>
document.addEventListener("click", whereWasClicked, false); // listener for any clicks on the document.
var button = document.getElementById("button");
button.addEventListener("click", displaySuprise, false);
var clicked;
function whereWasClicked(){
clicked = event.target;
//check to see if user clicks outside of the
if (tog = 1 && clicked != menu) {
menu.style.display = "none";
document.getElementById("button").innerHTML = "Click Me";
tog = 0;
}
}
var menu = document.getElementById("menu");
var tog = 0; // set up a toggle so you can display block and then none.
function displaySuprise(){
event.preventDefault();
event.stopPropagation();
if(tog == 0){
menu.style.display = "block";
this.innerHTML = "Opened!";
tog = 1;
} else {
menu.style.display = "none";
this.innerHTML = "Click Me";
tog = 0;
}
// check to see if the user has clicked anywhere off the new element.
}
</script>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T19:43:19.433",
"Id": "11849",
"Score": "0",
"body": "My initial thought is -- you are really doing great. Doesn't look like NOOBs code. Think of using `prototype` to improve modularity of the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T20:33:39.733",
"Id": "11857",
"Score": "0",
"body": "http://jsfiddle.net/uPwNy/14/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T21:29:03.193",
"Id": "11858",
"Score": "0",
"body": "@Raynos when the user clicks away from the element the element should disappear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:50:59.963",
"Id": "11863",
"Score": "0",
"body": "@jamcoupe I know, that's bad design. I fixed it for you. Now when you click the button again it hides itself."
}
] |
[
{
"body": "<p><strong>Item 1:</strong> I'd suggest getting rid of all global variables except <code>tog</code>. They don't look like they are needed and just open you up for a potential conflict with other global variables.</p>\n\n<p><strong>Item 2:</strong> This line of code:</p>\n\n<pre><code>if (tog = 1 && clicked != menu) {\n</code></pre>\n\n<p>should probably be:</p>\n\n<pre><code>if (tog == 1 && clicked != menu) {\n</code></pre>\n\n<p>Comparisons are done with <code>==</code> or <code>===</code>, not with <code>=</code> which is an assignment.</p>\n\n<p><strong>Item 3:</strong> <code>addEventListener()</code> does not exist in versions of IE before IE9, so you will need to use <code>attachEvent()</code> if <code>addEventListener()</code> is not present.</p>\n\n<p><strong>Item 4:</strong> Here's a version I've done that gets rid of all globals except <code>tog</code> (which I renamed <code>menuVisble</code> and made it a boolean. It also uses anonymous functions (less global namespace pollution) for the handlers and makes some other cleanups. You can see it work here: <a href=\"http://jsfiddle.net/jfriend00/MEaPs/\" rel=\"nofollow\">http://jsfiddle.net/jfriend00/MEaPs/</a>.</p>\n\n<pre><code>var menuVisible = false; // set up a toggle so you can display block and then none.\n\n// listener for any clicks on the document.\ndocument.addEventListener(\"click\", function(e) {\n var clicked = e.target;\n var menu = document.getElementById(\"menu\");\n //check to see if user clicks outside of the\n if (menuVisible && clicked != menu) {\n menu.style.display = \"none\";\n document.getElementById(\"button\").innerHTML = \"Click Me\";\n menuVisible = false;\n }\n\n}, false); \n\ndocument.getElementById(\"button\").addEventListener(\"click\", function(e) {\n var menu = document.getElementById(\"menu\");\n e.preventDefault();\n e.stopPropagation();\n if (menuVisible){\n menu.style.display = \"none\";\n this.innerHTML = \"Click Me\";\n menuVisible = false;\n } else {\n menu.style.display = \"block\";\n this.innerHTML = \"Opened!\";\n menuVisible = true;\n }\n}, false);\n</code></pre>\n\n<p><strong>Item 5:</strong> And here's a version with no globals at all. It uses the class of the menu to control and discern visibility. You can see it work here: <a href=\"http://jsfiddle.net/jfriend00/96NfD/\" rel=\"nofollow\">http://jsfiddle.net/jfriend00/96NfD/</a>.</p>\n\n<pre><code>// listener for any clicks on the document.\ndocument.addEventListener(\"click\", function(e) {\n var menu = document.getElementById(\"menu\");\n var menuVisible = menu.className.indexOf(\"hidden\") == -1;\n //check to see if user clicks outside of the\n if (menuVisible && e.target != menu) {\n document.getElementById(\"button\").innerHTML = \"Click Me\";\n menu.className = \"hidden\";\n }\n\n}, false); \n\ndocument.getElementById(\"button\").addEventListener(\"click\", function(e) {\n e.preventDefault();\n e.stopPropagation();\n var menu = document.getElementById(\"menu\");\n var menuVisible = menu.className.indexOf(\"hidden\") == -1;\n if (menuVisible) {\n this.innerHTML = \"Click Me\";\n menu.className = \"hidden\";\n } else {\n this.innerHTML = \"Opened!\";\n menu.className = \"\";\n }\n}, false);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T19:49:20.563",
"Id": "11853",
"Score": "0",
"body": "Thanks for the tips! I know about the pre IE9 problem but I am not going to concern myself over it until I need to (when I am making proper websites.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T19:51:33.070",
"Id": "11854",
"Score": "0",
"body": "It seems that I have to have `tog` as a global variable for it to toggle properly"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T20:02:53.153",
"Id": "11855",
"Score": "0",
"body": "@jamcoupe - Yes, that's why I said to \"get rid of all global variables except `tog`\". You wouldn't technically need tog either if you just examine the object to see if it's visible or not, but that would require writing a little more code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T20:23:56.957",
"Id": "11856",
"Score": "0",
"body": "@jamcoupe - I added two new versions of the code for you to look at."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T21:30:48.573",
"Id": "11859",
"Score": "0",
"body": "your code looks much better and I haven't looked into `.className` yet. but I understand how your code is working! Thanks for your help"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T19:41:14.250",
"Id": "7561",
"ParentId": "7559",
"Score": "3"
}
},
{
"body": "<p>jfriend00's answer is great.</p>\n\n<p>And I think you can rewrite your click-outside function like this for llater reuse.</p>\n\n<pre><code>var clickOutside = function(element, action) {\n return function(e) {\n action(e.target !== element);\n };\n};\n\ndocument.addEventListener(\n \"click\",\n clickOutside(menu, function(isOutside) {\n if(isOutside && menuVisible) {\n // hide your menu\n }\n }),\n false\n);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T21:21:36.303",
"Id": "7562",
"ParentId": "7559",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7561",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T19:34:32.520",
"Id": "7559",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Showing and hiding element, making my code more useful"
}
|
7559
|
<pre><code>List<Route> listOfRoutes = routeStopsService.getAllRoutes();
Set<String> listOfStopNames = new TreeSet<String>();
for(Route route:listOfRoutes){
Set<Stop> stops = routeStopsService.getStops(route);
for(Stop stop:stops)
listOfStopNames .add(stop.getStopName());
listOfStopNames .remove( ((TreeSet<String>) listOfSources).last());
}
</code></pre>
<p>Here I am getting list of stop names for every route, and I am removing the last stop name from every route.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:26:03.863",
"Id": "11860",
"Score": "2",
"body": "can you guarantee that the last one is the one you want to remove? sets aren't necessarily ordered..."
}
] |
[
{
"body": "<p>It is kind of hard to tell by looking at your code, (you have not shown us the definition of <code>listOfSources</code>, and you appear to be doing some stuff which appears to have no purpose in the sample code you provided,) but it appears to me that your approach of removing the last item from the list is not inefficient. Do you have any reasons to believe that it could be made any more efficient?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T21:32:49.363",
"Id": "7563",
"ParentId": "7560",
"Score": "0"
}
},
{
"body": "<p>First of all, you should always use block statements with the <code>for</code> loops. The original formatting of the question was this:</p>\n\n<pre><code>for(Stop stop:stops)\n listOfStopNames .add(stop.getStopName());\n listOfStopNames .remove( ((TreeSet<String>) listOfSources).last());\n</code></pre>\n\n<p>It's hard to read. Readers could think that the <code>remove</code> call is part of the <code>for</code> loop since it's the same indetation level as the line before.</p>\n\n<pre><code>for (final Stop stop : stops) {\n listOfStopNames.add(stop.getStopName());\n}\nlistOfStopNames.remove(listOfSources.last());\n</code></pre>\n\n<hr>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Hungarian_notation#Disadvantages\" rel=\"nofollow\">Hungartion notation</a> is redundant, try to avoid it. A few new names:</p>\n\n<ul>\n<li><code>listOfRoutes</code> -> <code>routes</code></li>\n<li><code>listOfStopNames</code> -> <code>stopNames</code></li>\n<li><code>listOfSources</code> -> <code>sources</code></li>\n</ul>\n\n<hr>\n\n<p>As <em>@luketorjussen</em> already mentioned, downcasting is nasty. If the implementation of <code>listOfSources</code> changes it may return another type and the compiler will not warn you but you'll get exceptions at runtime. At least change the casting to <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html\" rel=\"nofollow\"><code>SortedSet</code></a> instead of the <code>TreeSet</code>. <code>TreeSet</code> implements <code>SortedSet</code> and <code>SortedSet</code> has the required <code>last</code> method.</p>\n\n<hr>\n\n<p>I'd extract out some method for better readability. For further review you should share some code from the <code>routeStopsService</code>, <code>Router</code> and <code>Stop</code> classes.</p>\n\n<pre><code>private Set<String> getStopNamesWithoutLast(final Route route) {\n final Set<String> result = getStopNames(route);\n final String lastStopName = ((SortedSet<String>) sources).last();\n result.remove(lastStopName);\n return result;\n}\n\nprivate Set<String> getStopNames(final Route route) {\n final Set<String> result = new TreeSet<String>();\n final Set<Stop> stops = routeStopsService.getStops(route);\n for (final Stop stop : stops) {\n final String stopName = stop.getStopName();\n result.add(stopName);\n }\n\n return result;\n}\n</code></pre>\n\n\n\n<pre><code>final List<Route> routes = routeStopsService.getAllRoutes();\nfinal Set<String> allStopName = new TreeSet<String>();\nfor (final Route route : routes) {\n final Set<String> stopNames = getStopNamesWithoutLast(route);\n allStopName.addAll(stopNames);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:08:58.107",
"Id": "7569",
"ParentId": "7560",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7569",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T19:36:35.817",
"Id": "7560",
"Score": "1",
"Tags": [
"java",
"collections"
],
"Title": "How to delete last element in java.util.Set efficiently?"
}
|
7560
|
<p>So this is probably a popular problem, and I decided to take a crack at it today using C#.</p>
<p>I came up with the following solution: </p>
<pre><code>private BinaryTree<int>.BinaryTreeNode FindLowestNodes(BinaryTree<int>.BinaryTreeNode node, int depth, ref int biggestDepth) {
this.WriteResult("Entering recursiorn for node.....{0}", node.Value.ToString());
BinaryTree<int>.BinaryTreeNode lowestNode = null;
if (node.Left != null) {
var n = FindLowestNodes(node. Left, depth + 1, ref biggestDepth);
if (n != null) lowestNode = n;
}
if (node.Right != null) {
var n = FindLowestNodes(node.Right, depth + 1, ref biggestDepth);
if (n != null)
lowestNode = n;
}
if (node.Left == null && node.Right == null) {
if (depth > biggestDepth) {
lowestNode = node;
biggestDepth = depth;
}
}
return lowestNode;
}
</code></pre>
<p>This is a recursive function using a <code>depth</code> parameter, and <code>biggestDepth</code> parameter that helps me determine if the node is indeed the lowest since the tree can have multiple depths. What I don't like about passing an int by reference is boxing...</p>
<p>Could this solution be written more efficiently? </p>
<p>Also, would it be easier to parallelize using a functional language like Clojure, or is that not really a factor as long as variables are not passed by reference? </p>
|
[] |
[
{
"body": "<p>Passing an int with the <code>ref</code> keyword does <em>not</em> involve any boxing at all. Do not confuse this with \"passing an int by reference\" (as in, a function with return type <code>Object</code> returning an <code>int</code>,) which is quite a different thing, and it <em>does</em> involve boxing. </p>\n\n<p>Your code seems quite efficient to me, I have nothing to comment on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:27:24.407",
"Id": "11864",
"Score": "0",
"body": "looking at your thumbnail i thought i just got advice from Peter Gibbons from office space :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:32:38.493",
"Id": "11865",
"Score": "0",
"body": "!LOL! yeah, now that you mention it, it is true, my icon kinda looks like him! I know the actor, I did not know his name, (I just looked him up,) and I always thought he might be Greek. With a name like Gibbons he cannot be Greek, of course."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-18T16:48:46.520",
"Id": "14296",
"Score": "0",
"body": "well his actual name is Ron Livingston. also not very Greek sounding"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:17:56.677",
"Id": "7565",
"ParentId": "7564",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7565",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T21:47:14.503",
"Id": "7564",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Find lowest leaf nodes in a binary tree"
}
|
7564
|
<p>I am writing code that has objects having integer member variables where the integer value has a specific constant meaning, which normally means "use an enum".</p>
<p>Suppose the values are the days of the week, Monday = 0, Tuesday = 1, and so on. (In my real case, there are several different "types" involved, some of which have 10-20 possible values.)</p>
<p>The code uses data objects which are auto-generated, and these data objects can only have certain, already specified types (int, string, bool, double), otherwise they could just use enums themselves. The question is, should I use an enum, or a struct with static readonly definitions and implicit casting. I favor the struct version.</p>
<p>Here is an example of using an enum:</p>
<pre><code>enum Days
{
Monday = 0,
Tuesday = 1,
Wednesday = 2,
Thursday = 3,
Friday = 4,
Saturday = 5,
Sunday = 6,
}
</code></pre>
<p>And here is my preferred struct code:</p>
<pre><code>struct Day
{
readonly int day;
public Day(int day)
{
this.day = day;
}
public static implicit operator int(Day value)
{
return value.day;
}
public static implicit operator Day(int value)
{
return new Day(value);
}
public static readonly Day Monday = 0;
public static readonly Day Tuesday = 1;
public static readonly Day Wednesday = 2;
public static readonly Day Thursday = 3;
public static readonly Day Friday = 4;
public static readonly Day Saturday = 5;
public static readonly Day Sunday = 6;
}
</code></pre>
<p>My code frequently involves assigning values to the members of the data object. This means if I use the struct version, I can say for example <code>Day myDay = dataObject.Day</code> rather than <code>Days myDay = (Days)dataObject.Day</code>. With the amount of logic code that will be affected by this, I think the struct version is a win for readability because it removes a <em>lot</em> of explicit casts.</p>
<p>I don't want to just use plain <code>int</code>s in my code because I like function signatures that indicate the purpose of the "int" being passed or returned. But I don't want the messiness that comes from casting enums all over. </p>
<p>I'm asking for arguments against the struct version. Would it disgust you if you found this pattern in code somewhere?</p>
<hr>
<p>Clarification:</p>
<p>For the data objects to allow user types, other code which depends on the data objects would have to know about these types. The two "areas" of code are logically separate, and do not reference each other at all. I suppose a middle layer that separates the data objects from my code would be possible, but since all it would do is convert the enums to ints and back, it would be an awful lot of code to accomplish very little.</p>
<p>Another reason that these values sometimes must be represented as integers is that they are put through arithmetic operations sometimes. This is another place where explicit casting just gets annoying.</p>
<p>Finally, the definition of the possible values (days of week, in this example) is far less likely to change than the logic code. So conciseness and readability in the definition code isn't as valuable as in the logic code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:50:48.760",
"Id": "11866",
"Score": "0",
"body": "What's wrong with `Days.Monday`? How is that not readable? Why wouldn't you want to use the `DayOfWeek` enumeration that's already included in the framework? I don't understand your use-case at all. It's no different than if you had used an enum."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:14:21.447",
"Id": "11867",
"Score": "0",
"body": "`Days.Monday` isn't unreadable, but logic code filled with casts between `Days` and `int` is unreadable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T22:45:36.027",
"Id": "12031",
"Score": "0",
"body": "If all I needed was to define a list of constants, then of course I would prefer to use an enum, but I have run into a situation in the past where I had a set of simple enum-like values, but I also had a need to perform various kinds of operations on those values. Using a struct provided a convenient place to encapsulate the logic of those operations."
}
] |
[
{
"body": "<p>Normally it would disgust me, but you appear to have a valid reason to use it, which stems from the pre-existing disgusting situation that you have to cope with these data objects that use ints.</p>\n\n<p>The only thing I would ask is, why can these data objects not use enums? What is it about their auto-generation that precludes enums from being used? I do not think that enums receive any special handling at the IL level, they are handled just like primitive types are.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:18:49.233",
"Id": "11868",
"Score": "0",
"body": "Added clarification about why the data objects can't have user types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:23:06.697",
"Id": "11870",
"Score": "2",
"body": "I understand. So, the first sentence I wrote in my answer holds. And I think that in your struct you can (and probably should) declare your `int day` as readonly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:25:21.493",
"Id": "11871",
"Score": "0",
"body": "Good point about making the value readonly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:51:41.260",
"Id": "7568",
"ParentId": "7566",
"Score": "4"
}
},
{
"body": "<p>For something that has a small number of predefined values like days of the week, yes, the <code>struct</code> disgusts me. This is precisely what <code>enum</code>s are for. The <code>struct</code> version makes sense for things with large numbers of values that may have a few predefined ones (see <code>Color</code> in the Framework as a good example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:21:47.743",
"Id": "11869",
"Score": "0",
"body": "I do have more than seven possible values. There are also more than one of these \"types\", and more will potentially arise as the project continues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T02:31:51.020",
"Id": "11873",
"Score": "0",
"body": "Forgive me for asking, but what other days are there other than Monday through Sunday?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T14:26:14.337",
"Id": "11895",
"Score": "0",
"body": "The days of week was an example, looks like it was a bad one. My actual code has other values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T16:03:39.467",
"Id": "11901",
"Score": "0",
"body": "Then I retract what I said. `Enums` are not well-suited for open-ended or gargantuan numbers of values of a type and `Color` becomes a very good example to follow."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:16:54.457",
"Id": "7570",
"ParentId": "7566",
"Score": "2"
}
},
{
"body": "<p>Although not something I would recommend doing on a regular basis, I don't think this is necessarily a bad thing to do.</p>\n\n<p>If you <em>are</em> going to do this, why not have the best (or is this the worst?) of both worlds? Use a private enum inside the struct to define the valid values. There are a few advantages to doing this, such as:</p>\n\n<ol>\n<li><p>Easy to do validation. My code (below) protects against <code>Day x = 7;</code>, which is invalid.</p></li>\n<li><p>Easy to implement parsing.</p></li>\n<li><p>Easy to implement ToString in such a way as to output the names of the days, as an enum would.</p></li>\n<li><p>Ability to override the Equals method to allow comparison with an Int32 value.</p></li>\n</ol>\n\n<p>My version of the original code, modified to use a private enum, shown below:</p>\n\n<pre><code>struct Day\n{\n // let's make this enum private to the struct,\n // in order to avoid mass confusion and hysteria.\n enum DayValue\n {\n Monday = 0,\n Tuesday = 1,\n Wednesday = 2,\n Thursday = 3,\n Friday = 4,\n Saturday = 5,\n Sunday = 6,\n }\n\n readonly DayValue day;\n\n Day(DayValue day)\n {\n this.day = day;\n }\n\n public Day(int day)\n {\n // simple validation\n // Hmm, the IsDefined method causes boxing :\\\n if (!Enum.IsDefined(typeof(DayValue), day))\n throw new ArgumentOutOfRangeException(\"day\");\n\n this.day = (DayValue)day;\n }\n\n public static implicit operator int(Day value)\n {\n return (int)value.day;\n }\n\n public static implicit operator Day(int value)\n {\n return new Day(value);\n }\n\n public static bool TryParse(string input, out Day day)\n {\n // Enum makes it easy to do parsing\n DayValue value;\n if (Enum.TryParse<DayValue>(input, out value))\n {\n day = new Day(value);\n return true;\n }\n else\n {\n day = default(Day);\n return false;\n }\n }\n\n public override string ToString()\n {\n // Enum.ToString will provide the name of the value\n return this.day.ToString();\n }\n\n public override bool Equals(object obj)\n {\n if (obj is int)\n return (DayValue)obj == this.day;\n\n return this.day.Equals(obj);\n }\n\n public override int GetHashCode()\n {\n return this.day.GetHashCode();\n }\n\n public static readonly Day Monday = new Day(DayValue.Monday);\n public static readonly Day Tuesday = new Day(DayValue.Tuesday);\n public static readonly Day Wednesday = new Day(DayValue.Wednesday);\n public static readonly Day Thursday = new Day(DayValue.Thursday);\n public static readonly Day Friday = new Day(DayValue.Friday);\n public static readonly Day Saturday = new Day(DayValue.Saturday);\n public static readonly Day Sunday = new Day(DayValue.Sunday);\n}\n</code></pre>\n\n<p>EDIT: Updated to provide overrides for the Equals and GetHashCode methods.</p>\n\n<p>Interestingly, calls to <code>Days.Sunday.Equals(6)</code> and <code>object.Equals(Days.Sunday, 6)</code> return false, assuming that <code>Days</code> is an enum, even if the value of <code>Sunday</code> is actually 6.</p>\n\n<p>A struct allows you to implement this equality logic, which might make sense considering that there are implicit conversions implemented.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T12:37:17.180",
"Id": "12066",
"Score": "0",
"body": "Using an inner enum might sound good at first, but the code is not as simple as my example using a struct. Do you actually gain anything? Bounds checking can be done even without a private enum, if desired. Just put a Min and Max variable at both ends of the list and do the check inside the constructor still."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T13:53:41.987",
"Id": "12068",
"Score": "0",
"body": "@Philip - I certainly agree...the code is more complicated. I realize now that I worded my answer as if suggesting that this is better, but that was not my intention. I am for keeping it simple. Regarding bounds checking, imagine if you are mapping a set of non-consecutive integers (e.g. 3, 17, 29) to enums: now checking valid values can't be done with simply a min and max value. Also, suppose your enum changes (you add a new value). Having an inner enum just requires adding that new value to the enum; the existing validation logic will still work. Parsing is the other benefit gained."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T14:41:41.923",
"Id": "12072",
"Score": "0",
"body": "Good points. In my case, parsing was unnecessary and all of the values were consecutive, but this would be a decent way to do it given those requirements."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T00:01:45.077",
"Id": "7655",
"ParentId": "7566",
"Score": "3"
}
},
{
"body": "<p>It would be nice if there were something \"between\" a <code>struct</code> and an <code>enum</code>, which would be recognized as having an integer type as its underlying representation (like <code>enum</code> does) but could also control what operators should be available and how they should work. One could, for example, specify that it should be possible to add an integer to a day, but not add two days together. <code>Enum</code> would allow both with casting, and neither without casting; a sensible type should allow the first without casting, but not the second.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-20T16:38:16.983",
"Id": "84590",
"ParentId": "7566",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:31:23.383",
"Id": "7566",
"Score": "8",
"Tags": [
"c#",
"enum"
],
"Title": "Enum vs int wrapper struct"
}
|
7566
|
<p>Following on from this request <a href="https://codereview.stackexchange.com/q/7536/507">Yet another C++ Json Parser</a></p>
<p>A friend pointed out that he though a recursive decent parser would be more efficient.<br>
Before I agree I want to test it so I wrote it for testing.</p>
<p>I found the implementation of the parser much more complex than using yacc (but that could be a result of using yacc a few times and not trying to write recursive descent parsers).</p>
<p>Any comments on the implementation appreciated:</p>
<h3>JsonRecParser.h</h3>
<pre><code>#ifndef THORSANVIL_JSON_PARSER_JSON_REC_PARSER_H
#define THORSANVIL_JSON_PARSER_JSON_REC_PARSER_H
#include "JsonRecParser.h"
#include "JsonParser.tab.hpp"
class yyFlexLexer;
using namespace ThorsAnvil::JsonParser;
namespace ThorsAnvil
{
namespace JsonParser
{
class JsonRecParser
{
yyFlexLexer& lexer;
int JsonValueParse(int val);
int JsonMapValueListParse(int val);
int JsonArrayValueListParse(int val);
int JsonMapParse(int val);
int JsonArrayParse(int val);
int JsonObjectParse(int val);
public:
JsonRecParser(yyFlexLexer& lexer)
: lexer(lexer)
{}
int parse();
};
}
}
#endif
</code></pre>
<h3>JsonRecParser.cpp</h3>
<pre><code>#include "JsonParser.tab.hpp"
using namespace ThorsAnvil::JsonParser;
int JsonRecParser::JsonValueParse(int val)
{
switch(val)
{
case '{': return JsonMapParse(lexer.yylex());
case '[': return JsonArrayParse(lexer.yylex());
case yy::JsonParser::token::JSON_STRING: return 0;
case yy::JsonParser::token::JSON_NUMBER: return 0;
case yy::JsonParser::token::JSON_TRUE: return 0;
case yy::JsonParser::token::JSON_FALSE: return 0;
case yy::JsonParser::token::JSON_NULL: return 0;
default: break;
}
return val;
}
int JsonRecParser::JsonMapValueListParse(int val)
{
if ((val == yy::JsonParser::token::JSON_STRING) && ((val = lexer.yylex()) == ':') && ((val = JsonValueParse(lexer.yylex())) == 0))
{
val = lexer.yylex();
switch(val)
{
case '}': return 0;
case ',': return JsonMapValueListParse(lexer.yylex());
default: break;
}
}
return val;
}
int JsonRecParser::JsonArrayValueListParse(int val)
{
if ((val = JsonValueParse(val)) == 0)
{
val = lexer.yylex();
switch(val)
{
case ']': return 0;
case ',': return JsonArrayValueListParse(lexer.yylex());
default: break;
}
}
return val;
}
int JsonRecParser::JsonMapParse(int val)
{
if (val == '}')
{ return 0; /* Empty Map */
}
return JsonMapValueListParse(val);
}
int JsonRecParser::JsonArrayParse(int val)
{
if (val == ']')
{ return 0; /* Empty Array */
}
return JsonArrayValueListParse(val);
}
int JsonRecParser::JsonObjectParse(int val)
{
switch(val)
{
case '{': return JsonMapParse(lexer.yylex());
case '[': return JsonArrayParse(lexer.yylex());
default: break;
}
return val;
}
int JsonRecParser::parse()
{
return JsonObjectParse(lexer.yylex());
}
</code></pre>
<p>All other files are the same.
With this small change to main:</p>
<h3>Changes to main.cpp</h3>
<pre><code> //yy::JsonShiftParser parser(lexer);
ThorsAnvil::JsonParser::JsonRecParser parser(lexer);
</code></pre>
<p>#</p>
|
[] |
[
{
"body": "<p>Recursion generally isn't more efficient, just easier to program and understand. For simpler examples it also leads to much neater code however can be harder to understand if you have multiple levels of recursion jumping around.</p>\n\n<p>Each function call will add stuff to the stack as such it will use more memory and take longer as it has to allocate and initialize that memory, even when using pointers/references. You might also find you run into a depth limit in the form of a <a href=\"http://en.wikipedia.org/wiki/Stack_overflow\" rel=\"nofollow\">stack overflow</a> (like the site name ☺). </p>\n\n<p>With that said for most JSON it wouldn't likely be an issue, unless someone was sending malicious JSON your way which you should assume for any external input.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T02:54:08.047",
"Id": "11936",
"Score": "0",
"body": "I disagree with your arguments: 1) Easier to program? Really have you compared the two versions. 2) Easier to read: Have you read the two examples (admittedly you need to understand BNF for the yacc version but what computer scientist graduate does not). 3) Yes recursion adds stuff to the stack but where do you think the tokens are stored for the shift reduce version. The shift reduce version is just as likely to to overflow (just in a different way)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T04:37:24.037",
"Id": "11945",
"Score": "3",
"body": "@LokiAstari: I think David's comment was meant in general, not specifically to this code -- e.g., a recursive quicksort vs. non-recursive version. It tends to simplify code for problems (like Quicksort) that are defined recursively. A domain-specific language like yacc tends to do more to simplify programming within that domain. The problem is that the domain can be sharply circumscribed (e.g., if your input grammar doesn't fit yacc's lalr(1) limit)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T00:21:41.323",
"Id": "7614",
"ParentId": "7567",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7614",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:36:10.100",
"Id": "7567",
"Score": "4",
"Tags": [
"c++",
"json",
"lex",
"yacc"
],
"Title": "Yet another C++ Json Parser (Recursive)"
}
|
7567
|
<p>The goal of this code is to save a list of 250000 words with a number that indicates its frequency. The 250000 are sorted alphabetically but the frequency is unsorted. The idea is that a user must insert capitalized words, spaces or numbers after each word to lookup in the saved 250000-word list.</p>
<p>The max number of inputs are 1000 word+space+frequency pair per line.</p>
<p>The frequency domain is \$1 <= frequency <= 1000000\$. Every input must result in an output containing a list of the most relevant words \$>=\$ word-frequency entered and also ordered alphabetically in descending order.</p>
<p>How can I finish this code in a more efficient way?</p>
<pre><code>public static void Main()
{
{
var dic = new Dictionary<string, int>();
int counter = 0;
StreamReader sr = new StreamReader("C:\\dicti.txt");
while (true)
{
string line = sr.ReadLine(); // To read lines
string[] ln;
if (line == null) break; // There is no more lines
try
{
ln = line.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
string a = ln[0];
int b = Convert.ToInt32(ln[1]);
dic.Add(a, b);
}
catch (IndexOutOfRangeException) { break; }
}
string[] ln2;
string am, word;
int bm;
do
{
//counter++;
do
{
word = Console.ReadLine();
ln2 = word.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries);
am = ln2[0];
bm = Convert.ToInt32(ln2[1]);
} while (!(am.Length >= 2 && bm >= 1 && bm <= 1000000));
if (true)
{
var aj = (dic.Where(x => x.Value >= bm)
.Where(x => x.Key.StartsWith(am))
.OrderByDescending(d => d.Value).Take(2));
foreach (var p in aj)
{
Console.WriteLine("{0} ", p.Key);
}
}
} while (counter < 1001);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:19:12.347",
"Id": "11874",
"Score": "6",
"body": "What is your question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:21:46.400",
"Id": "11875",
"Score": "0",
"body": "How can I finish this code in a more efficient way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:24:22.277",
"Id": "11876",
"Score": "0",
"body": "WORD FREQUENCY LIST LOOKUP\n ==========================\n \n I.e:\n\n Input:\n SAC 500\n TED 1000\n \n Output:\n SACK\n SACRED\n SACRIFICED\n \n TEDDY\n TEDIOUS\n\n How can I finish this code in a more efficient way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:34:18.057",
"Id": "11879",
"Score": "1",
"body": "`while(true)` is not my style, but I understand it's purpose, but `if(true)` ??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:40:50.983",
"Id": "11880",
"Score": "0",
"body": "Ok it is doing nothing if(true) there, it was there because I have been editing this code a lot and I forget to delete it now I have the free lambda expression in which I think something could be improve but I haven´t figured out yet\n \n var aj = (dic.Where(x => x.Value >= bm)\n .Where(x => x.Key.StartsWith(am))\n .OrderByDescending(d => d.Value).Take(2));\n\n\n foreach (var p in aj)\n {\n Console.WriteLine(\"{0} \", p.Key);\n }"
}
] |
[
{
"body": "<p><code>Dictionary<Y></code> is only efficient if you access the entries through the key. You are enumerating the dictionary with linq. This is very slow. Try to access it like this:</p>\n\n<pre><code>int count;\nif (dic.TryGetValue(am, out count)) {\n // found\n} else {\n // not found\n}\n</code></pre>\n\n<p>You cannot search for keys that start with a text. If you want to do this then look for a more appropriate data structure. A binary tree inserts and looks up fast and sorting happens automatically. However, keep in mind that simple binary trees (not AVL trees) perform badly if items are added in a presorted order. A binary tree would also allow you to search for beginning of words.</p>\n\n<hr>\n\n<p>EDIT:</p>\n\n<p>I have thought things over. It would be possible to work with two collections at the same time. It is a bit complicated to handle, but should be faster.</p>\n\n<p>Let me explain. We are using binary trees, because, unless dictionaries, they are ordered by the key. Let us store the information with the words as key and the frequencies as value in the first binary tree. In the second binary tree, we use the frequency as key. Because several words can have the same frequency, we use a list of words as value. With this approach, we have our information ordered by words and by frequencies at the same time.</p>\n\n<p>Now let us update the frequency of a word, which is already contained in our collections. As an example, let us add 50 to the frequency of the word “TEDDY”:</p>\n\n<ol>\n<li><p>We look up the word in collection 1. We see that the frequency of the word is 100.</p></li>\n<li><p>We look up the words with frequency 100 in collection 2. We find two corresponding words, “TEDDY” and “HOUSE”.</p></li>\n<li><p>We ignore “HOUSE” and remove “TEDDY” from collection 2.</p></li>\n<li><p>We re-insert “TEDDY” in collection 2 with a frequency of 100 + 50 = 150. Because the frequency is used as key, it will probably be inserted at a different place in the tree structure.</p></li>\n<li><p>We update the frequency in collection 1 to 150. Since the key does not change, we can just replace the value “in place”.</p></li>\n</ol>\n\n<p>After these operations, both collections are still ordered by words and by frequencies respectively. Moreover, both look up operations, the remove and the insert operation were fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:13:23.913",
"Id": "11883",
"Score": "0",
"body": "Yes, the problem I got trying to implement binary tree is that I couldn´t find a way to insert the word relating to the value. In such a way that when the input process has finished the lookups are faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:18:52.530",
"Id": "11884",
"Score": "0",
"body": "You could insert items of `KeyValuePair<string, int>` into your tree."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:21:31.853",
"Id": "11885",
"Score": "0",
"body": "Yes, but how then it will be sorted alphabetically and numerically from highest value. When I tryied to order by value it just order it and I lost the alphabetical order configuration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:39:06.670",
"Id": "11886",
"Score": "0",
"body": "You cannot have it sorted in both ways at the same time. Keep the alphabetical order and create a sorted copy when you need it. Possibly with a linq query. It is not very fast, but at least inserting and searching words is fast. Until now, you used `dic` in a very slow way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T14:49:37.620",
"Id": "11897",
"Score": "0",
"body": "I added a new solution to my answer, which operates with two collections and should be fast for all the requested operations."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:07:03.603",
"Id": "7572",
"ParentId": "7571",
"Score": "2"
}
},
{
"body": "<p>Here's a suggestion: there's no reason why list of words has to be stored in a simple list. If you build a tree where each node has 26 potential sub nodes, one for each letter of the alphabet, the obvious solution runs in under two seconds on my system, while your code takes about 50.</p>\n\n<pre><code>class WordsByPrefix\n{\n public string Prefix;\n public WordsByPrefix[] Letters = new WordsByPrefix[26];\n public int Freq = 0;\n\n public void AddWord(string word, int freq)\n {\n if (word.Length == Prefix.Length)\n this.Freq = freq;\n else\n {\n var letter = word[Prefix.Length];\n if (Letters[letter - 'A'] == null)\n Letters[letter - 'A'] = new WordsByPrefix { Prefix = Prefix + letter };\n Letters[letter - 'A'].AddWord(word, freq);\n }\n }\n\n public void LoadWords(ICollection<WordsByPrefix> list)\n {\n if (Freq > 0)\n list.Add(this);\n foreach (var letter in Letters)\n if (letter != null)\n letter.LoadWords(list);\n }\n}\n\nroot = new WordsByPrefix();\nroot.Prefix = String.Empty;\n</code></pre>\n\n<p>To load words into the tree, call <code>root.AddWord(word, freq);</code>. To select words from the tree, start from <code>root</code>, and for each letter, look up <code>node.Letters[letter - 'A']</code>. Call <code>LoadWords</code> on the result to get a list of all those combinations of letters that are valid words (have a nonzero <code>Freq</code>).</p>\n\n<p>Note: ensure that all characters are from <code>'A'</code> to <code>'Z'</code> or things will break.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T00:29:07.137",
"Id": "11887",
"Score": "0",
"body": "I don´t understand how the automatic 1000 queries will be managed by the 26 array A-Z. I don´t have to count the words because each input is accompained with its frequency already."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T10:07:26.757",
"Id": "11893",
"Score": "0",
"body": "Yes, I got that. In your second loop, when you're reading from `Console.In`, look up each word. For example, if the input is `SAC 500`, look up `root.Letters['S'-'A'].Letters['A'-'A'].Letters['C'-'A']`, call `LoadWords`, and filter the results based on `Freq`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T19:40:02.523",
"Id": "75481",
"Score": "0",
"body": "@MarioMindell you may want to look up the [trie](http://en.wikipedia.org/wiki/Trie) data structure for more information related to this answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T23:56:55.440",
"Id": "7573",
"ParentId": "7571",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T22:15:28.983",
"Id": "7571",
"Score": "2",
"Tags": [
"c#",
"homework",
"lookup"
],
"Title": "Alphabetically-sorted word lookup"
}
|
7571
|
<p>Below is an implementation of a typical <code>Logger</code> interface that uses <code>syslog()</code> as the default means to store messages and falls back to <code>error_log()</code> if that does not work. This is the first time I've used <code>syslog</code> and just want to ensure that my code is logical and there isn't something about <code>syslog</code> that I'm not aware of that could come back and bite me. The code does work, messages are appearing in <code>syslog</code> as appropriate.</p>
<ul>
<li><a href="https://github.com/cspray/SprayFire" rel="nofollow">Project github repo</a></li>
<li><a href="https://github.com/cspray/SprayFire/blob/master/libs/SprayFire/Logger/Log.php" rel="nofollow">Source code for Logger interface</a></li>
<li><a href="https://github.com/cspray/SprayFire/blob/master/libs/SprayFire/Core/CoreObject.php" rel="nofollow">Source code for extended class</a></li>
</ul>
<pre><code><?php
/**
* @file
* @brief Holds a class that implements error logging to an OS or system logger.
*/
namespace SprayFire\Logger;
/**
* @brief A SprayFire.Logger.Log implementation that will attempt to log a message
* to syslog and as a fallback will log the message to whatever option is set in
* the error_log php.ini directive.
*
* @uses SprayFire.Logger.Log
* @uses SprayFire.Core.CoreObject
*/
class SystemLogger extends \SprayFire\Core\CoreObject implements \SprayFire\Logger\Log {
/**
* @brief A flag to tell if fallback should be used.
*
* @property $syslogOpened
*/
protected $syslogOpened = false;
/**
* @param $syslogIdent
*/
public function __construct($syslogIdent = 'SprayFire') {
$this->syslogOpened = \openlog($syslogIdent, \LOG_NDELAY, \LOG_USER);
}
/**
* @param $syslogSeverity The timestamp for the \a $message being logged
* @param $message The message to be logged
* @return true if the message was logged, false if not
*/
public function log($syslogSeverity, $message) {
$loggedtoSyslog = $this->logToSyslog($syslogSeverity, $message);
if (!$loggedtoSyslog) {
return $this->logToErrorLog($message);
}
return $loggedToSyslog;
}
/**
* @param $syslogSeverity The severity of the syslog message to store
* @param $message The message to store in syslog
* @return true if the message was logged into syslog, false if it wasn't
* @see http://www.php.net/syslog
*/
protected function logToSyslog($syslogSeverity, $message) {
if ($this->syslogOpened) {
return \syslog($syslogSeverity, $message);
}
return false;
}
/**
* @param $message The message to log with error_log
* @return true if logged, false if not
* @see http://php.net/manual/en/function.error-log.php
*/
protected function logToErrorLog($message) {
$message = \date('M-d-Y H:i:s') . ' := ' . $message;
return \error_log($message);
}
/**
* @brief Ensures that the syslog is properly closed if it was opened.
*/
public function __destruct() {
if ($this->syslogOpened) {
\closelog();
}
}
}
</code></pre>
<p>One question that I would have is how to unit test this? How would I disable <code>syslog</code> to ensure the fallback is called? Or is there some other way to do it?</p>
|
[] |
[
{
"body": "<p>You need a <code>SysLog</code> interface and a <code>SysLogImpl</code> implementation class.</p>\n\n<pre><code>public interface SysLog {\n public bool openlog(string $ident, int $option ,int $facility);\n public bool syslog (int $priority, string $message);\n public bool closelog (void);\n}\n</code></pre>\n\n<p><code>SysLogImpl</code> just delegate the calls to the <code>openlog</code>, <code>syslog</code> and <code>closelog</code> PHP functions.</p>\n\n<pre><code>public class SysLogImpl implements SysLog {\n public bool openlog(string $ident, int $option, int $facility) {\n return openlog($ident, $option, $facility);\n }\n\n public bool syslog(int $priority, string $message) {\n return syslog($priority, $message);\n }\n\n public bool closelog (void) {\n return closelog();\n }\n} \n</code></pre>\n\n<p>It's important that this class should be just a thin facade without any logic since this class usually doesn't have any test or just has a few integration tests.</p>\n\n<p>In production code pass a <code>SysLogImpl</code> instance to the constructor of your <code>SystemLogger</code> class and use this <code>SysLogImpl</code> instance instead of direct PHP calls.</p>\n\n<p>In test code pass a mocked or a custom object which implements the <code>SysLog</code> interface to the <code>SystemLogger</code> class. The passed object should be able to store function calls and emulate responses (as mock objects do).</p>\n\n<p>Maybe you'll need an <code>ErrorLog</code> interface and an <code>ErrorLogImpl</code> implementation class which logs with <code>error_log</code> PHP calls.</p>\n\n<hr>\n\n<p>Another solution is a <a href=\"http://xunitpatterns.com/Test-Specific%20Subclass.html\" rel=\"nofollow\">Test-Specific Subclass</a>. You can extract out the <code>openlog</code> call from the constructor to a separate function and create a subclass of the <code>SystemLogger</code> which overrides this method and returns <code>false</code>.</p>\n\n<hr>\n\n<p>A better and generic design would be creating a common <code>Logger</code> interface and a <code>SyslogLogger</code> and an <code>ErrorLogLogger</code> implementation classes. Both implements <code>Logger</code>. Then the <code>SystemLogger</code> class get one or more <code>Logger</code> instances and try calling their <code>open</code> functions and use that implementation whose <code>open</code> function returns <code>true</code> first.</p>\n\n<p>If you use this the <code>SystemLogger</code> has only one responsibility: managing loggers, while <code>SyslogLogger</code> cares only about <code>syslog</code> and <code>ErrorLogLogger</code> cares only about <code>error_log</code> logging.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T16:14:00.700",
"Id": "11902",
"Score": "0",
"body": "Ok, let's say that I have a common `Logger` interface. Would it make sense for all `Loggers` to have an `openlog()` method? What if the log isn't something that can really be opened? Should it just return `true`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T17:10:50.193",
"Id": "11910",
"Score": "0",
"body": "Yes, just return `true`. It's totally fine, not all resource needs opening (nor closing)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:05:34.760",
"Id": "11915",
"Score": "0",
"body": "Thank you for the detailed answer. I took your advice and looked at the interface for my `Logger`. However, some concerns I have with the API drove me to [ask another question in regards to your answer](http://codereview.stackexchange.com/questions/7600/refactoring-logger-interface-to-open-and-close-logs). If you have the time I would appreciate your feedback."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T12:37:50.900",
"Id": "7586",
"ParentId": "7574",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7586",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T05:12:39.263",
"Id": "7574",
"Score": "2",
"Tags": [
"php",
"unit-testing"
],
"Title": "Logger to syslog with error_log fallback"
}
|
7574
|
<p>Given that it is better to reuse objects than create new ones when developing with Android, is it worth while deleting the contents of a <code>StringBuilder</code> and reusing it?</p>
<pre class="lang-java prettyprint-override"><code>StringBuilder b = new StringBuilder();
//build up a string
b.delete(0, b.length());
//reuse it
</code></pre>
<p>Compared to:</p>
<pre class="lang-java prettyprint-override"><code>StringBuilder b1 = new StringBuilder();
//build up a string
StringBuilder b2 = new StringBuilder();
//create a new one
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T14:23:23.840",
"Id": "11894",
"Score": "1",
"body": "Is this even worth thinking about as long as it is not in a very tight loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T09:22:00.917",
"Id": "11981",
"Score": "0",
"body": "@Bobby - I have about a dozen separate strings of different sizes I need to build up in the one class, some in a loop, some not. Was not sure if it was worth while so that's why I am asking :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T09:59:31.290",
"Id": "11984",
"Score": "1",
"body": "No, I meant this smells a lot like premature optimization. If you start worrying about \"a dozen strings which need to be concatenated\" without *any* profiling, then you've a knot in your brain. And I didn't mean that as an insult but as a heart-warm warning...been there, done that. Rule of thumb: If you concatenate strings in a loop, use a StringBuilder. Second rule of thumb: If you worry about speed, profile first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T10:57:37.453",
"Id": "11986",
"Score": "0",
"body": "No insult taken and point noted. Truthfully, I am not overly concerned about optimization and I am an inexperienced programmer (or could you tell). I simply wanted to know if this would improved performance in some small way. Given that there is no .clear() method for StringBuilders, I half expected some one to say that iterating through the buffer to wipes it's contents is actually more expensive than garbage collecting. Never ask, never know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T11:17:59.383",
"Id": "11988",
"Score": "0",
"body": "That's absolutely true. I think the difference between the two are not only small, but *hardly noticeable*. I just wanted to make sure that you understand that this question is hardly about real-world optimization"
}
] |
[
{
"body": "<p>Yes, of course it is worthwhile, even in the great big world outside of Android.</p>\n\n<p>According to <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow\">the documentation about <code>StringBuilder</code></a>:</p>\n\n<blockquote>\n <p>Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.</p>\n</blockquote>\n\n<p>This means that deletion of the <code>StringBuilder</code>'s contents will result in no memory allocation operation for its internal array of <code>char</code>s (it will just set its length to zero and return, maintaining its last capacity). Plus, you save the <code>StringBuilder</code> object itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-16T06:45:06.960",
"Id": "140715",
"Score": "0",
"body": "thanks ur reply is very helpful for me ,so here i have some question that 1. what is the default capacity of string builder. 2. so what if StringBuilder dynamically resize its buffer that time it will allocate a new memory please confirm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-17T08:17:31.417",
"Id": "140867",
"Score": "0",
"body": "The default initial capacity is 16, but you can set it to whatever you want when invoking the StringBuilder's constructor. Saying that the StringBuilder will dynamically resize its buffer is equivalent to saying that the StringBuilder will allocate new memory."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T08:55:31.060",
"Id": "7581",
"ParentId": "7575",
"Score": "12"
}
},
{
"body": "<p>Reusing doesn't need memory allocation, so it could be faster as <em>@Mike Nakis</em> mentioned. On the other hand it leads to ugly code: you use the same variable for two (or more) different purposes which could confuse readers, make maintenance harder. Unless you have a good reason to do that avoid it. I mean, you have a good reason if a profiling shows that creating new <code>StringBuilder</code> instances is a bottleneck in the application.</p>\n\n<p>If you really have to reuse <code>StringBuilder</code>s, try accessing them with different names with a helper method:</p>\n\n<pre><code>public static StringBuilder reuseForBetterPerformance(final StringBuilder sb) {\n sb.delete(0, sb.length());\n return sb;\n}\n</code></pre>\n\n<p>Client code:</p>\n\n<pre><code>final StringBuilder b = new StringBuilder();\n//build up a string\nfinal StringBuilder c = reuseForBetterPerformance(b);\n//reuse it\nc.append(...)\n</code></pre>\n\n<p>It makes the code a little bit more readable, since the method name says why you're reusing the <code>StringBuilder</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T14:31:21.583",
"Id": "11896",
"Score": "2",
"body": "I don't understand the purpose of final"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T16:14:13.537",
"Id": "11903",
"Score": "0",
"body": "If it wasn't made final then you could create a new one return it, but we want to return the same object but emptied."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T17:25:53.760",
"Id": "11912",
"Score": "3",
"body": "`final` helps readers, because they know that the reference always points to the same instance and it doesn't change later. http://programmers.stackexchange.com/questions/115690/why-declare-final-variables-inside-methods but you can find other questions on Programmers.SE in the topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T09:22:51.197",
"Id": "11982",
"Score": "1",
"body": "That helper function is an excellent compromise. Thanks for the idea."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T11:36:33.120",
"Id": "7585",
"ParentId": "7575",
"Score": "24"
}
},
{
"body": "<p>To add some hard numbers, I wrote a simple test application:</p>\n\n<pre><code>public static void main(String[] args) {\n int iterations = 1000000;\n int secondIterations = 25;\n\n long start = System.currentTimeMillis();\n for (int count = 0; count < iterations; count++) {\n StringBuilder builder = new StringBuilder();\n for (int secondCounter = 0; secondCounter < secondIterations; secondCounter++) {\n builder.append(\"aaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\");\n }\n }\n System.out.println(\"Recreation took: \" + Long.toString(System.currentTimeMillis() - start) + \"ms\");\n\n start = System.currentTimeMillis();\n StringBuilder builder = new StringBuilder();\n for (int count = 0; count < iterations; count++) {\n builder.delete(0, builder.length());\n for (int secondCounter = 0; secondCounter < secondIterations; secondCounter++) {\n builder.append(\"aaassssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss\");\n }\n }\n System.out.println(\"Reuse took: \" + Long.toString(System.currentTimeMillis() - start) + \"ms\");\n}\n</code></pre>\n\n<p>This gives the following output:</p>\n\n<pre><code>Recreation took: 10594ms\nReuse took: 1937ms\n</code></pre>\n\n<p>So, yes, as it seems reusing is indeed faster, at least if you test it in a tight loop with a small memory footprint. But please keep in mind that those numbers were generated by using <strong>1 million</strong> iterations.</p>\n\n<p>Keep two rules in mind:</p>\n\n<ul>\n<li>First go for readability and maintainability.</li>\n<li>Second...run a profiler.</li>\n</ul>\n\n<p>This difference I see here is nothing I'd worry about until I really run into performance problems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-23T18:23:06.127",
"Id": "193209",
"Score": "0",
"body": "Wow, that's 5 times faster. Though I would be willing to bet that most of this difference is due to the fact that your \"recreation\" loop generates 2.2 gigabytes of garbage, so exercises the garbage collector, (to its detriment,) while the \"reuse\" loop produces a lot less garbage, close to nothing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T11:33:28.483",
"Id": "7637",
"ParentId": "7575",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "7585",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T05:26:10.157",
"Id": "7575",
"Score": "26",
"Tags": [
"java",
"optimization",
"performance",
"strings",
"android"
],
"Title": "Reusing StringBuilder or creating a new one?"
}
|
7575
|
<p>I'm currently looking at, from a rather high level, the parallelization of the gravity calculation in an <a href="http://en.wikipedia.org/wiki/N-body_simulation">N-body simulation</a> for approximating a solution to the <a href="http://en.wikipedia.org/wiki/N-body_problem">N-body problem</a>.</p>
<p>The simple form of the algorithm looks something like this:</p>
<pre><code>for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i != j)
bodies[i].ApplyGravityFrom(bodies[j]);
Body::ApplyGravityFrom(Body &other)
{
Vector dr = other.Pos - this->Pos;
double r2 = Dot(dr, dr);
double ir3 = 1 / (r2 * sqrt(r2));
this->Acc += (other.Mass * ir3) * dr;
}
</code></pre>
<p>This simple version has an obvious parallelization over the outer loop:</p>
<pre><code>#pragma omp parallel for
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i != j)
bodies[i].ApplyGravityFrom(bodies[j]);
</code></pre>
<p>However, you're doing twice as many units of work as necessary. It's the case that gravity acting on body i from body j is the same as the gravity acting on body j from body i, but with the opposite sign.</p>
<p>You can calculate gravity pairwise instead:</p>
<pre><code>for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
bodies[i].PairwiseGravity(bodies[j]);
Body::PairwiseGravityBody &other)
{
Vector dr = other.Pos - this->Pos;
double r2 = Dot(dr, dr);
double ir3 = 1 / (r2 * sqrt(r2));
this->Acc += (other.Mass * ir3) * dr;
other.Acc -= (this->Mass * ir3) * dr;
}
</code></pre>
<p>This is the same exact calculation but you're making use of the fact that the force is symmetric, but with a sign flip.</p>
<p>But now parallelizing this loop becomes much harder. But if you treat this problem geometrically, then you can realize that you can actually divide up the work in a special way to never require locks.</p>
<p>First off, you can calculate pairwise forces for the first n / 2 bodies. This is inherently serial. Then, you can calculate the pairwise forces between the bodies [0, n / 2] and [n / 2, n]. Lastly you calculate the pairwise forces for the last n / 2 bodies.</p>
<p>The algorithm then looks like:</p>
<pre><code>void BlockGravity(Body *bodies, int i1, int i2, int j1, int j2)
{
for (int i = i1; i < i2; i++)
for (int j = j1; j < j2; j++)
bodies[i].Pairwise(bodies[j]);
}
void TriangleGravity(Body *bodies, int i1, int i2)
{
for (int i = i1; i < i2; i++)
for (int j = i1 + 1; j < i2; j++)
bodies[i].Pairwise(bodies[j]);
}
void Gravity(Body *bodies, int n)
{
TriangleGravity(bodies, 0, n / 2);
BlockGravity(bodies, n / 2, n, 0, n / 2);
TriangleGravity(bodies, n / 2, n);
}
</code></pre>
<p>The block gravity calculations have the property that none of them ever write into the same memory twice. Every pair used in that calculation is unique. What's special is at this point you can actually continue to subdivide the problem further:</p>
<pre><code>void Gravity(Body *bodies, int n1, int n2)
{
int n = n2 - n1;
if (n > MinBlockSize)
{
int m = n1 + n / 2;
Gravity(bodies, n1, m);
Gravity(bodies, m, n2);
BlockGravity(bodies, m, n2, n1, m);
}
else
TriangleGravity(bodies, n1, n2);
}
</code></pre>
<p>By subdividing the problem, you gain the benefit of cache locality. The smaller problems tend to work on things that close to each other, whereas the naive version would continuously flush the cache as it iterated over the whole array. I included a minimum size for subdivision since at some point subdividing the problem any further won't get any benefits</p>
<p>So far, this does the same amount of work as simply calling <code>TriangleGravity(bodies, 0, n)</code>. There is an opportunity for parallelism in the recursive calls to <code>Gravity</code>, as well as the block computation. I'll post this once I fully test it.</p>
<p>Does there seem to be any logical flaws in this? I'll try to throw up an image visually demonstrating what it does, because seeing it on paper helps A LOT.</p>
<hr>
<p><strong>Update</strong></p>
<p>Here's some performance data for the scaling with adjusting the <code>MinBlockSize</code> parameter. These tests were performed for n = 4096 with fully parallelism being exploited within the recursive calls.</p>
<pre><code>BlockSize \ Timing (milliseconds)
1 - 201 (Overkill)
2 - 144
4 - 123
8 - 106
16 - 101
32 - 110
64 - 101 (Optimal Performance)
128 - 108
256 - 124
512 - 147
1024 - 195
2048 - 293
4096 - 407 (Same as naive)
</code></pre>
|
[] |
[
{
"body": "<p>You seem to be making the problem more complex:</p>\n\n<p>I would take a step back to your original algorithm:</p>\n\n<pre><code>#pragma omp parallel for\nfor (int i = 0; i < n; i++)\n for (int j = i + 1; j < n; j++)\n bodies[i].PairwiseGravity(bodies[j]);\n</code></pre>\n\n<p>Your problem (as you stated) that the parallelism is uneven (the lower outer loops is doing more work than the higher values of the outer loop).</p>\n\n<p>But why not combine the two loops.</p>\n\n<pre><code>#pragma omp parallel for\nfor (int i = 0; i < ((n*(n-1))/2; i++)\n bodies[src(i,n)].PairwiseGravity(bodies[dst(i,n)]);\n</code></pre>\n\n<p>Each loop is completely independent.<br>\nAll you have to do is calculate how the functions src() and dst() work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T17:03:55.890",
"Id": "11909",
"Score": "0",
"body": "The code I posted improves performance significantly without parallelism. For n = 1024, the naive algorithm takes approximately 2.5 milliseconds to execute. Using MinBlockSize = 64 the same calculation takes 0.84 milliseconds to execute. The cache effects aren't to be underestimated. I added the definition of `PairwiseGravity`, and you'll see the only issue with what you suggest is that it would be extremely easy to have two threads writing into the same memory at once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T03:12:33.587",
"Id": "11938",
"Score": "0",
"body": "If for n = 1024 and time of 2.5 milliseconds you probably should not even be considering threading. But your technique stills seems a bit costly (in terms of maintenance and initial creation) for such a small gain (admittedly 3 fold increase is good but will it still scale for a data set size that would actually take significant time). If you actually did some real work (meant in terms of the functions work(Not a comment on your code)) then you should be considering a technique called `map reduce`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T03:14:25.953",
"Id": "11939",
"Score": "0",
"body": "That's a tiny problem size. Most things I'm working on are for far larger n, and this grows to `O(n^2)` so a more realistic `n = 10000` would take 250 milliseconds per iteration. On my application currently, I've actually managed to get fully linear speed up with every core added. A previous version with a simpler threading scheme had worse performance and started degrading as the problem size increased. One of the big issues is the data stored in these simulations isn't small -- it's on the order of 1 KB per body (e.g. n = 10,000 -> 10 MB data)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T03:16:22.177",
"Id": "11940",
"Score": "0",
"body": "My main reason for posting here was to figure out if I did this appropriately :) I actually had a bug in my implementation that was posted, I'll update this shortly to account for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T03:19:38.287",
"Id": "11941",
"Score": "0",
"body": "So you are threading I thought you just said you were not! OK. Now that we are getting down to it. Maybe if you provided more detail about the actual work being done then we can consider a proper technique like `Map Reduce`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T03:33:00.133",
"Id": "11944",
"Score": "0",
"body": "Sorry for the confusion. I meant that the purely serial algorithm described above achieved a 3x speedup over the standard version. I have a lot of testing to do, but it seems like throwing the parallelization on top of that is adding a decent performance boost. There's also a lot of minor details I've left out as they're irrelevant to the algorithm I'm describing above. There are extensions possible which allow me to hierarchically subdivide space and compute forces in `O(n log n)` time, and they integrate very nicely with the above code if I can get it working."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T09:59:19.607",
"Id": "7584",
"ParentId": "7578",
"Score": "2"
}
},
{
"body": "<p>There is no logical flow; this approach is known, and indeed it benefits from better cache locality, and is very suitable for parallelism, especially with work-stealing-based frameworks.</p>\n\n<p>Note that you can calculate forces between the first N/2 bodies and the last N/2 bodies (i.e. the triangles) in parallel, then you might process the block. When processing the block, you might also apply recursion and split it in 4 sub-blocks (rather than by rows or cols). These 4 sub-blocks can be split into two pairs along diagonals of the original block; in each pair, sub-blocks don't share data and can be processed in parallel:</p>\n\n<pre><code>void BlockGravity(Body *bodies, int i1, int i2, int j1, int j2)\n{\n int i_mid=(i1+i2)/2, j_mid=(j1+j2)/2;\n { // This pair can be processed in parallel\n BlockGravity(bodies, i1, i_mid, j1, j_mid);\n BlockGravity(bodies, i_mid, i2, j_mid, j2);\n }\n // Synchronize here\n { // This pair can also be processed in parallel\n BlockGravity(bodies, i1, i_mid, j_mid, j2);\n BlockGravity(bodies, i_mid, i2, j1, j_mid);\n }\n}\n</code></pre>\n\n<p>Another description of this algorithm (with pictures) is here: <a href=\"http://software.intel.com/en-us/blogs/2010/07/01/n-bodies-a-parallel-tbb-solution-parallel-code-a-fresh-look-using-recursive-parallelism/\" rel=\"nofollow\">http://software.intel.com/en-us/blogs/2010/07/01/n-bodies-a-parallel-tbb-solution-parallel-code-a-fresh-look-using-recursive-parallelism/</a>, and subsequent posts in that series contain a parallel implementation sketch using <a href=\"http://threadingbuildingblocks.org\" rel=\"nofollow\">Intel's TBB</a> as well as performance measurements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-26T10:25:40.360",
"Id": "8317",
"ParentId": "7578",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T08:34:01.773",
"Id": "7578",
"Score": "15",
"Tags": [
"c++",
"multithreading",
"locking",
"cache",
"lock-free"
],
"Title": "Lock-free cache oblivious n-body algorithm"
}
|
7578
|
<p>I have a table in a SQL Server database, which holds information of some images, and the relevant gallery of them. The columns are like:</p>
<p><code>ImageId</code>, <code>GalleryId</code>, <code>Order</code></p>
<p>I have a unique key on <code>GalleryId-Order</code> columns, that is, each image should have a unique order in its gallery.</p>
<p>A business requirement is to change the place (order) of an image, inside the gallery. For example, image at the order of 16, might be replaced at the new order 7. However, all the images should shift, if necessary, to provide space for this sorting operation. In this example, images with the order 7, 8, 9, ..., 15 should shift forward one level, so that the place 7 would become empty for the mentioned image.</p>
<p>I've written a procedure for this:</p>
<pre><code>create procedure MoveImage(@imageId int, @newOrder int)
as
begin
-- Finding the related gallery
declare @galleryId int;
select @galleryId = GalleryId
from Images
where ImageId = @imageId
-- Finding the count of images inside this gallery
declare @mediaCount int;
select @mediaCount = COUNT(ImageId)
from Images
where GalleryId = @galleryId
-- Finding the current order of the image
declare @currentOrder int;
select @currentOrder = [Order]
from Images
where ImageId = @imageId
-- Temporary shifting the current media to one order above all, to bypass the 'Each Media Should Have a Unique Order in its Gallery' unique index
update Images
set [Order] = @mediaCount + 1
where ImageId = @imageId
-- Shifting all media of the gallery between the current order and the new order, one order forward, or backward
if @newOrder < @currentOrder
begin
update Images
set [Order] = [Order] + 1
where GalleryId = @galleryId and [Order] >= @newOrder and [Order] <= @currentOrder
end
else
begin
update Images
set [Order] = [Order] - 1
where GalleryId = @galleryId and [Order] <= @newOrder and [Order] >= @currentOrder
end
-- Inserting the image at the specified order
print @newOrder
update Images
set [Order] = @newOrder
where ImageId = @imageId
end
go
</code></pre>
<p>It works, just fine (at least as much as I've tested it). However, I don't feel Okay with this procedure, I think it might become easier and more effective. Can anyone improve this T-SQL code?</p>
<p><strong>PS:</strong> parameters are checked before being passed to this procedure, so presume that there is nothing wrong with parameters, like negative <code>@newOrder</code>, etc.</p>
|
[] |
[
{
"body": "<p>Little merging, since you have an index on GalleryId, [Order]:</p>\n\n<pre><code>create procedure MoveImage(@imageId int, @newOrder int)\nas\nbegin\n declare @mediaCount int;\n declare @galleryId int;\n declare @currentOrder int;\n\n -- Finding the related gallery\n -- Finding the count of images inside this gallery\n -- Finding the current order of the image\n select TOP 1\n @galleryId = i1.GalleryId, \n @mediaCount = COUNT(i2.ImageId),\n @currentOrder = i1.[Order]\n from Images i1\n JOIN Images i2\n ON i1.GalleryId = i2.GalleryId\n where i1.ImageId = @imageId \n GROUP BY i1.GalleryId, i1.[Order]\n\n -- Temporary shifting the current media to one order above all, to bypass the 'Each Media Should Have a Unique Order in its Gallery' unique index\n update Images\n set [Order] = @mediaCount + 1\n where ImageId = @imageId\n\n -- Shifting all media of the gallery between the current order and the new order, one order forward, or backward\n if @newOrder < @currentOrder\n begin\n update Images \n set [Order] = [Order] + 1\n where GalleryId = @galleryId and [Order] >= @newOrder and [Order] <= @currentOrder\n end\n else\n begin\n update Images \n set [Order] = [Order] - 1\n where GalleryId = @galleryId and [Order] <= @newOrder and [Order] >= @currentOrder\n end\n\n -- Inserting the image at the specified order\n print @newOrder\n update Images\n set [Order] = @newOrder\n where ImageId = @imageId\nend\ngo\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T08:58:31.703",
"Id": "7582",
"ParentId": "7580",
"Score": "1"
}
},
{
"body": "<p>There is a much, much, <strong>much</strong> easier way to do this. You can use real values for order, so when you want to move the row from position 16 to position 7 you give it an order value which is the average between the order values of rows 6 and 7.</p>\n\n<p>The precision of real numbers is <strong>huge</strong>, and I presume that the re-orderings of images in your database will be happening at human reaction speeds, so you probably won't run into precision problems during the remainder of the expected lifetime of the universe. But if you are really insecure about the possibility of precision problems, you can rectify your table every once in a while, by reading the rows sorted by their order, and writing them into a new table, re-assigning the order values by copying them from an integer identity field. Then you delete the old table and rename the new table to the old name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T23:05:47.270",
"Id": "11973",
"Score": "0",
"body": "+1 for the real numbers. It's worth to mention it that this way it's enough to update only one record. (On the other hand, table renaming is bad - I suppose it doesn't support transactionts, nor concurrent orderings/access.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T23:09:20.570",
"Id": "11974",
"Score": "1",
"body": "@palacsint Yes, you are right, I really did not need to mention that. The renumbering could be achieved in-place anyway, without copying to a new table."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T09:03:21.127",
"Id": "7583",
"ParentId": "7580",
"Score": "5"
}
},
{
"body": "<p>I would consider changing the structure of your table to use a self-referencing foreign key that refers to the previous item.</p>\n\n<p>This makes it trivial to change the position of an item within the sequence, or to insert/remove items.</p>\n\n<p>In order to query the items in the correct order, you would need to use a recursive Common Table Expression.</p>\n\n<p>Below is an example table structure along with a recursive CTE:</p>\n\n<pre><code>create table #Data\n(\n DataID int not null primary key,\n Value varchar(50) not null,\n ParentDataID int references #Data (DataID) -- optionally put a unique constraint on this column in order to enforce only one child record\n)\n\n-- sorted order is 1, 4, 7, 9, 2, 5, 3, 8, 6\ninsert into #Data values\n (1, 'One', null),\n (2, 'Two', 9),\n (3, 'Three', 5),\n (4, 'Four', 1),\n (5, 'Five', 2),\n (6, 'Six', 8),\n (7, 'Seven', 4),\n (8, 'Eight', 3),\n (9, 'Nine', 7)\n ,(101, 'One Hundred One', null),\n (102, 'One Hundred Two', 109),\n (103, 'One Hundred Three', 105),\n (104, 'One Hundred Four', 101),\n (105, 'One Hundred Five', 102),\n (106, 'One Hundred Six', 108),\n (107, 'One Hundred Seven', 104),\n (108, 'One Hundred Eight', 103),\n (109, 'One Hundred Nine', 107)\n\n;\n\n\nwith SortedData (DataID, Value, RootID, OrderNumber) as\n(\n select\n DataID,\n Value,\n DataID,\n 1\n from #Data\n where\n ParentDataID is null\n or ParentDataID = DataID\n\n union all\n\n select\n #Data.DataID,\n #Data.Value,\n SortedData.RootID,\n SortedData.OrderNumber + 1\n from #Data\n inner join SortedData on\n SortedData.DataID = #Data.ParentDataID\n)\nselect *\nfrom SortedData\norder by RootID, OrderNumber\n</code></pre>\n\n<p>(<strong>EDIT:</strong> I've rearranged the content of my answer. Code examples that used to be here are now at the bottom, because I feel that the easier approach is to use the trigger that I've written, shown below)</p>\n\n<p>The code below is for an \"instead of insert, update, delete\" trigger on the table that will automatically perform the necessary \"shifting\" operations when records are inserted/updated/deleted.</p>\n\n<p>Note that I've changed the name of the table in my example from <code>#Data</code> to <code>SortableData</code>, because triggers cannot be added to temporary tables.</p>\n\n<p><strong>EDIT:</strong> The original trigger code was unable to handle contiguous rows being added/moved/removed from the sequence. I've now revised the trigger code to handle those scenarios</p>\n\n<pre><code>create trigger trig_SortableData on SortableData instead of insert, update, delete as begin\n\n-- first, store a list of records that are to come after the records that are being added/moved\ndeclare @ChildData table\n(\n ChildDataID int,\n ParentDataID int\n)\n;\n\nwith DeletedSorted (DataID, ParentDataID, RootDataID) as\n(\n select\n DataID,\n ParentDataID,\n ParentDataID\n from Deleted\n where\n not exists (\n select 1\n from Deleted d\n where\n d.DataID = Deleted.ParentDataID\n )\n\n union all\n\n select\n Deleted.DataID,\n Deleted.ParentDataID,\n DeletedSorted.RootDataID\n from Deleted\n inner join DeletedSorted on\n DeletedSorted.DataID = Deleted.ParentDataID\n),\nInsertedSorted (DataID, ParentDataID, LeafDataID) as\n(\n select\n DataID,\n ParentDataID,\n DataID\n from Inserted\n where\n not exists (\n select 1\n from Inserted i\n where\n i.ParentDataID = Inserted.DataID\n )\n\n union all\n\n select\n Inserted.DataID,\n Inserted.ParentDataID,\n InsertedSorted.LeafDataID\n from Inserted\n inner join InsertedSorted on\n Inserted.DataID = InsertedSorted.ParentDataID\n)\n-- insert those records into the table variable along with the last DataID of the records being added/moved\ninsert into @ChildData\nselect\n SortableData.DataID,\n isnull(DeletedSorted.RootDataID, InsertedSorted.LeafDataID)\nfrom SortableData\ninner join InsertedSorted on\n InsertedSorted.ParentDataID = SortableData.ParentDataID\nleft outer join DeletedSorted on\n DeletedSorted.DataID = SortableData.ParentDataID\nwhere\n not exists (\n select 1\n from Inserted\n where\n Inserted.DataID = SortableData.DataID\n )\n\n-- and disengage those records from their current parent\n-- Performing this update may be necessary if there is a unique constraint on ParentDataID\nupdate d set\n d.ParentDataID = null\nfrom SortableData d\ninner join @ChildData c on\n c.ChildDataID = d.DataID\n\n\n-- next, update any records that are being moved/deleted; put them after their new parent record\nupdate d set\n d.ParentDataID = Inserted.ParentDataID\nfrom SortableData d\ninner join Deleted on\n Deleted.DataID = d.DataID\nleft outer join Inserted on\n Inserted.DataID = d.DataID\n;\n\nwith DeletedSorted (DataID, ParentDataID, RootDataID) as\n(\n select\n DataID,\n ParentDataID,\n ParentDataID\n from Deleted\n where\n not exists (\n select 1\n from Deleted d\n where\n d.DataID = Deleted.ParentDataID\n )\n\n union all\n\n select\n Deleted.DataID,\n Deleted.ParentDataID,\n DeletedSorted.RootDataID\n from Deleted\n inner join DeletedSorted on\n DeletedSorted.DataID = Deleted.ParentDataID\n),\nInsertedSorted (DataID, ParentDataID, LeafDataID) as\n(\n select\n DataID,\n ParentDataID,\n DataID\n from Inserted\n where\n not exists (\n select 1\n from Inserted i\n where\n i.ParentDataID = Inserted.DataID\n )\n\n union all\n\n select\n Inserted.DataID,\n Inserted.ParentDataID,\n InsertedSorted.LeafDataID\n from Inserted\n inner join InsertedSorted on\n Inserted.DataID = InsertedSorted.ParentDataID\n)\n-- and revise those records that used to come after those records being moved in order to close the gap\nupdate d set\n d.ParentDataID = isnull(InsertedSorted.LeafDataID, DeletedSorted.RootDataID)\nfrom SortableData d\ninner join DeletedSorted on\n DeletedSorted.DataID = d.ParentDataID\nleft outer join InsertedSorted on\n InsertedSorted.ParentDataID = DeletedSorted.RootDataID\nwhere\n not exists (\n select 1\n from Deleted\n where\n Deleted.DataID = d.DataID\n )\n\n-- and then actually remove those records that are being deleted\ndelete from SortableData\nwhere\n exists (\n select 1\n from Deleted\n where\n Deleted.DataID = SortableData.DataID\n )\n and not exists (\n select 1\n from Inserted\n where\n Inserted.DataID = SortableData.DataID\n )\n\n\n-- finally, insert any new records\ninsert into SortableData\nselect *\nfrom Inserted\nwhere\n not exists (\n select 1\n from Deleted\n where\n Deleted.DataID = Inserted.DataID\n )\n\n-- and re-attach records to come after the added/moved records\nupdate d set\n d.ParentDataID = c.ParentDataID\nfrom SortableData d\ninner join @ChildData c on\n c.ChildDataID = d.DataID\n\nend\n</code></pre>\n\n<p>I've tested this trigger out with the following commands:</p>\n\n<pre><code>insert into SortableData values (10, 'Ten', 4)\nupdate SortableData set ParentDataID = 1 where DataID = 5\ndelete from SortableData where DataID = 8\ndelete from SortableData where DataID = 6\ninsert into SortableData values (6, 'Six', 3)\n</code></pre>\n\n<p>I've also tested the following commands to add/move/remove multiple contiguous records in the sequence:</p>\n\n<pre><code>insert into SortableData values (10, 'Ten', 4), (11, 'Eleven', 10), (12, 'Twelve', 11)\n\ndelete from SortableData where DataID in (5,3)\n\nupdate d set\n d.ParentDataID = u.ParentDataID\nfrom SortableData d\ninner join (\n select 9 as DataID, 1 as ParentDataID\n union all select 2, 8\n union all select 8, 9\n) u on\n u.DataID = d.DataID\n</code></pre>\n\n<p>Also, below is a line to add a unique constraint on the <code>ParentDataID</code> column; this ensures that the non-null values are unique, but allows multiple nulls. This allows you to store multiple sequences in the table; each record with a null <code>ParentDataID</code> field is a root.</p>\n\n<pre><code>create unique index uq_SortableData_ParentDataID on SortableData (ParentDataID) where ParentDataID is not null\n</code></pre>\n\n<p><hr>\nThe code examples below are from previous versions of my answer. These demonstrate how to insert, move, and remove a single record in a sequence. However, I would prefer to use the trigger shown above because it makes these complex operations unnecessary.</p>\n\n<p>Below is some code that demonstrates inserting a new record into an arbitrary position. Similar code would be needed in order to change the position of an existing record. Alternatively, the code shown below could possibly be modified and implemented as an \"instead of insert\" trigger.</p>\n\n<pre><code>-- @DataID, @Value, and @ParentDataID should be parameters of the insert command\n-- They are defined here as variables for the sake of testing\ndeclare @DataID int\ndeclare @Value varchar(50)\ndeclare @ParentDataID int\n\n-- These values will insert a new record, \"Ten\", after the record \"Four\"\nset @DataID = 10\nset @Value = 'Ten'\nset @ParentDataID = 4\n\n-- This code assumes that there is a unique constraint on ParentDataID\ndeclare @ChildDataID int\n\n-- first, update the current record that comes after \"Four\"\n-- set ParentDataID to null so that we can put the new record in its place (the unique constraint makes this necessary)\n-- also capture the DataID of this record in the @ChildDataID variable\n-- The unique constraint on ParentDataID ensures that this update statement will only affect one record.\n-- If there is not a unique constraint on ParentDataID, then this approach could corrupt the data.\nupdate #Data set\n @ChildDataID = DataID,\n ParentDataID = null\nwhere\n ParentDataID = @ParentDataID\n\n-- insert the new record.\ninsert into #Data values (@DataID, @Value, @ParentDataID)\n\n-- now update the previous record again; set the ParentDataID to the DataID of the newly inserted record\n-- this ensures that the record that used to come after \"Four\" will now come after the newly inserted record\nupdate #Data set\n ParentDataID = @DataID\nwhere\n DataID = @ChildDataID\n</code></pre>\n\n<p>Below is an example of moving a record to a different position within the sequence. In this case, it is moving record \"Five\" to come after record \"One\":</p>\n\n<pre><code>-- Move record \"Five\" to come after \"One\"\n\n-- @DataID and @ParentDataID should be parameters of the update command\n-- They are defined here as variables for the sake of testing\ndeclare @DataID int\ndeclare @ParentDataID int\n\n-- These values will move the record \"Five\" to come after the record \"One\"\nset @DataID = 5\nset @ParentDataID = 1\n\n-- This code assumes that there is a unique constraint on ParentDataID\ndeclare @ChildDataID int\n\n-- first, update the current record that comes after \"One\"\n-- set ParentDataID to null so that we can put the new record in its place (the unique constraint makes this necessary)\n-- also capture the DataID of this record in the @ChildDataID variable\n-- The unique constraint on ParentDataID ensures that this update statement will only affect one record.\n-- If there is not a unique constraint on ParentDataID, then this approach could corrupt the data.\nupdate #Data set\n @ChildDataID = DataID,\n ParentDataID = null\nwhere\n ParentDataID = @ParentDataID\n\ndeclare @OriginalParentDataID int\n\nupdate #Data set\n @OriginalParentDataID = ParentDataID,\n ParentDataID = @ParentDataID\nwhere\n DataID = @DataID\n\n-- update the record that comes after the record being moved\n-- this record must now come after the record after which the record being moved originally came.\nupdate #Data set\n ParentDataID = @OriginalParentDataID\nwhere\n ParentDataID = @DataID\n\nupdate #Data set\n ParentDataID = @DataID\nwhere\n DataID = @ChildDataID\n</code></pre>\n\n<p>Finally, this last code example demonstrates removing a record from the sequence. In this case, it is removing record \"Eight\":</p>\n\n<pre><code>-- Remove record \"Eight\"\n\n-- @DataID should be a parameter of the delete command\n-- It is defined here as a variable for the sake of testing\ndeclare @DataID int\n\n-- This value will remove the record \"Eight\"\nset @DataID = 8\n\ndeclare @OriginalParentDataID int\n\nupdate #Data set\n @OriginalParentDataID = ParentDataID,\n ParentDataID = null\nwhere\n DataID = @DataID\n\n-- update the record that comes after the record being moved\n-- this record must now come after the record after which the record being moved originally came.\nupdate #Data set\n ParentDataID = @OriginalParentDataID\nwhere\n ParentDataID = @DataID\n\ndelete from #Data where DataID = @DataID\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T19:44:09.347",
"Id": "7626",
"ParentId": "7580",
"Score": "0"
}
},
{
"body": "<p>I believe there are a few significant suggestions which are currently missing from answers so far:</p>\n\n<ol>\n<li>You need to be using a transaction for this... if the data end up failing part-way through your procedure you will have corrupt data.</li>\n<li>you can actually do the whole thing in a single update, with no messing around with temporary ID's, etc. (Assuming auto-commit, then this will not need a transaction)</li>\n<li>seriously, who had the bright idea of calling the column <code>Order</code>.... should be shot.</li>\n</ol>\n\n<p>If you want to perform the update as a single operation you can have the following procedure:</p>\n\n<pre><code>create procedure MoveImage(@imageId int, @newOrder int)\nas\n begin\n -- plan your transaction logic here - with auto-commit you may still\n -- want to keep a read-lock on the rows affected......\n\n declare @movesrc as int\n declare @movetgt as int\n declare @shift as int\n\n set @movesrc = (select [Order] from Images where ImageId = @imageId)\n set @movetgt = @newOrder\n set @shift = sign(@movesrc - @movetgt)\n\n update Images\n set [Order] = case [Order]\n when @movesrc then @movetgt\n else [Order] + @shift\n end\n where (@movesrc > @movetgt and [Order] between @movetgt and @movesrc)\n or (@movesrc < @movetgt and [Order] between @movesrc and @movetgt)\n\n select * from Images order by [Order]\n\n end\n;\n</code></pre>\n\n<p>I have built this up in <a href=\"http://www.sqlfiddle.com/#!6/18d14/4\" rel=\"nofollow\">the sqlfiddle here</a> so you can see it working.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T11:13:34.827",
"Id": "65023",
"Score": "0",
"body": "such a nice answer. Thank you for mentioning missing points. But, what's wrong with the word **Order**? Because I'm the culprit ;)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-09T11:19:53.087",
"Id": "65024",
"Score": "0",
"body": "Since `ORDER` is a reserved word in all databases (as part of `ORDER BY`) it will always have to be escaped. Escaping values all over the place makes the query/code very hard to read. It does not add any value by keeping it `Order` when a different name, like `ImageOrder` will be easily readable, and just as useful. Even `IOrder` or `Position` would be better. Choosing names is what programmers do, and choosing names that make things easy is what better programmers do."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T18:12:42.520",
"Id": "38709",
"ParentId": "7580",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T08:47:47.193",
"Id": "7580",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"t-sql",
"sorting"
],
"Title": "Shifting records in SQL Database while sorting with algorithm"
}
|
7580
|
<p>What do you think of <a href="http://websilon.org/" rel="nofollow">http://websilon.org/</a>? Are there things that can be improved? Is there something missing? See the source of the webpages for code.</p>
<pre><code><!DOCTYPE HTML>
<html><head>
<title>Websilon - Mathematical Knowledge Base</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta name="robots" content="index, follow" />
<meta name="keywords" content="websilon, mathematics, math, knowlegde" />
<meta name="description" content="Websilon - Mathematical knowledge base" />
<meta http-equiv="Content-Language" content="en" />
<meta name="rating" content="safe for kids" />
<meta name="copyright" content="Websilon.org" />
<meta name="publisher" content="Websilon.org" />
<meta name="author" content="Websilon.org" />
<link rel="shortcut icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<link rel="stylesheet" href="/css/page/1.css" />
<meta name="viewport" content="initial-scale=1.0; maximum-scale=1.0; user-scalable=yes;" />
<script src="/module/jquery/js/jquery-1.6.2.min.js" /></script>
<script src="/module/jquery/js/jquery-ui-1.8.16.custom.min.js" /></script>
<link rel="stylesheet" href="/module/jquery/css/smoothness/jquery-ui-1.8.16.custom.css" />
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
extensions: ["tex2jax.js"],
jax: ["input/TeX","output/HTML-CSS"],
tex2jax: {inlineMath: [["$","$"]]}
});
</script>
<script type="text/javascript" src="/module/mathjax/MathJax.js"></script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-28191597-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<style>
.menu {
margin: 0;
padding: 0;
}
.menu .content {
width: 98%;
padding: 0;
margin: 1%;
margin-top: 0;
margin-bottom: 0;
}
.menu .content button {
margin-right: 10px;
}
.menu {
display: none;
width: 100%;
height: 50px;
line-height: 50px;
background-color: #333333;
color: #FFFFFF;
font-size: 80%;
}
.menu ul {
display: none;
margin: 0;
padding: 0;
width: 200px;
position: absolute;
left: 0;
top: 50px;
border-top: 0;
font-size: 90%;
z-index: 99999;
background-color: #252525;
}
.menu ul li a:active,
.menu ul li a:hover,
.menu ul li a:link,
.menu ul li a:visited,
.menu ul li {
padding: 0px 20px;
text-decoration: none;
color: #AFAFAF;
}
.menu ul li {
padding: 0;
}
.menu ul li:hover > a {
color: #FFFFFF;
}
.menu ul li:hover {
background-color: #0B5ED9;
}
.menu ul li a {
display: block;
}
.menu > li a:active,
.menu > li a:hover,
.menu > li a:link,
.menu > li a:visited,
.menu > li {
font-size: 120%;
text-decoration: none;
color: #FFFFFF;
}
.menu > li:hover {
background-color: #666666;
}
.menu > li {
position: relative;
float: left;
}
.menu > li > a {
display: block;
padding: 15px;
padding-top: 0;
padding-bottom: 0;
height: 50px;
width: 100%;
}
.menu > li:hover > ul {
display: block;
}
.menu li {
list-style-type: none;
}
hr {
width: 100%;
border: 1px solid #CCCCCC;
border-bottom: 0;
}</style>
<script>
function TopMenu(selector) {
var mainClass = this;
var environment = selector;
$(selector).css('z-index', 999999);
$(window).scroll(function(e) {
if ($(window).scrollTop() > 0) {
$(selector).css({
position: 'fixed',
top: '0'
});
} else {
$(selector).css({
position: 'static'
});
}
});
$(selector).css('display', 'none');
$(selector).ready(function() {
if (typeof(mainClass.onLoad) == 'function') {
mainClass.onLoad($(this));
}
$(selector).css('display', 'block');
});
/**
* Get the height of the menu.
*
* @return Menu height (int, pixels)
*/
this.getHeight = function() {
return parseInt($(selector).outerHeight());
}
}</script>
<ul class="menu">
<li><a href="/">Home</a></li>
<li><a href="#">Me</a>
<ul>
<li><a href="http://websilon.org/users/1/kevin/">Dashboard</a></li>
<li><a href="/user/edit/">Settings</a></li>
<li><a href="/user/logout/">Log out</a></li>
</ul>
</li>
<li><a href="#">Talk</a>
<ul>
<li><a href="/talk/">Discussions</a></li>
<li><a href="/talk/create/">New discussion</a></li>
</ul>
</li>
<li><a href="#">Knowledge</a>
<ul>
<li><a href="/kb/">Overview</a></li>
<li><a href="/kb/create/">Create</a></li>
</ul>
</li>
</ul>
<script>
TopMenu('.menu');
</script>
<div id="content">
<h1>Websilon.org</h1>
<p>
Websilon is an open knowledge platform. It's a dynamic study environment. Books are static; if there is new knowledge, it will take a while before you can read it in books.
</p>
<p>
Now we are in developing stage. You can partly use it and share some knowledge. If you would like to join or give ideas, please visit the <a href="/talk/view/1">Development</a> discussion.
</p>
</div>
</body>
</html>
</code></pre>
|
[] |
[
{
"body": "<p>Don't mix up html, css and javascript. Put the css and javascript into separate files and externally reference them from the html files, this will:</p>\n\n<ol>\n<li>clean up your html files</li>\n<li>allow the browser to cache the css and javascript so the files don't have to be re-downloaded for each page visit in your site</li>\n</ol>\n\n<p>Don't use <code><a></code> elements if you don't want to link something:</p>\n\n<pre><code><li><a href=\"#\">Talk</a>\n</code></pre>\n\n<p>Instead, I'd suggest to link to <em>/talk/</em>, or, if that is not reasonable, use the <code><span></code> tag. Links to <code>#</code> are to use when you want to link to the top of the current page.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T14:01:01.450",
"Id": "11992",
"Score": "0",
"body": "Thanks :). Problem is that these pages are auto-generated by Codeigniter and my view files. So seperating the Javascript/CSS files will be hard. And those links; when you visit the website with a smartphone, and you touch the menu button, then you will go to that page, right? So they will not be able to see the submenu that now will appear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T18:24:45.127",
"Id": "11999",
"Score": "0",
"body": "Then don't use `<a>`. ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T15:31:13.060",
"Id": "7588",
"ParentId": "7587",
"Score": "5"
}
},
{
"body": "<p>On top of what Yogu said, I would also recommend moving you move as many of the <code><script></code> references to the bottom of your page just before your ending body tag. This will ensure that your view/html data loads before your Javascript, essentially speeding up the time it takes the user's browser to appear to load the page.</p>\n\n<p><strong>*Edit:</strong> ANeves is correct, this method has been surpassed by asyncronously loading script files via such scripts as <a href=\"http://www.yepnopejs.com\" rel=\"nofollow\">yepnopejs</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T09:17:50.727",
"Id": "11956",
"Score": "1",
"body": "I disagree, instead of booting scripts to the end of pages we should link to external files and use the `async` and `defer` attributes of the script tag: http://developers.whatwg.org/scripting-1.html#the-script-element"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-06T10:35:37.257",
"Id": "13609",
"Score": "0",
"body": "You're correct, my answer has been corrected."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T19:05:14.413",
"Id": "7596",
"ParentId": "7587",
"Score": "1"
}
},
{
"body": "<p>Not much more to say but, I only see ul-elements using the menu-class.</p>\n\n<p>Is this really supposed to work? If not, then you can remove some excessive CSS.</p>\n\n<pre><code>.menu ul li\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:51:13.213",
"Id": "7605",
"ParentId": "7587",
"Score": "1"
}
},
{
"body": "<p>You could add some exceptions to better deal with ie, such as using Chrome Frame:</p>\n\n<pre><code><script src=\"//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js\"></script>\n <script>window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})</script>\n</code></pre>\n\n<p>or </p>\n\n<pre><code><!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->\n<!--[if lt IE 7]> <html class=\"no-js ie6 oldie\" lang=\"en\"> <![endif]-->\n<!--[if IE 7]> <html class=\"no-js ie7 oldie\" lang=\"en\"> <![endif]-->\n<!--[if IE 8]> <html class=\"no-js ie8 oldie\" lang=\"en\"> <![endif]-->\n<!-- Consider adding an manifest.appcache: h5bp.com/d/Offline -->\n<!--[if gt IE 8]><!--> <html class=\"no-js\" lang=\"en\"> <!--<![endif]-->\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T14:29:34.777",
"Id": "7710",
"ParentId": "7587",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T15:01:56.383",
"Id": "7587",
"Score": "3",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "New web project"
}
|
7587
|
<p>This is a subtle question about design in which I want to find the most elegant and appropriate solution. </p>
<p>I have an enumeration representing a French card deck (see code below). With it I need to do certain things, such as displaying the elements in a table. I'll want to display the elements starting with ACE (the highest) down to deuce. The problem is that I don't want my UI part of the code to know which one is the highest and use a descending iterator. Should I have a method in my enumeration, something like "EnumSet descending()" ? I don't want to initialise the constants with integers that indicates their values, since in poker the cards don't have a numerical value per se, just an order. Probably it's just fine if users of this enum are supposed to know that an ACE has the highest value and display values accordingly to what they want, but just wondering if there is a better solution.</p>
<pre><code>public enum Rank {
DEUCE ("2"),
THREE ("3"),
FOUR ("4"),
FIVE ("5"),
SIX ("6"),
SEVEN ("7"),
EIGHT ("8"),
NINE ("9"),
TEN ("10"),
JACK ("J"),
QUEEN ("Q"),
KING ("K"),
ACE ("A");
private String symbol;
Rank (String symbol ) {
this.symbol = symbol;
}
/**
* Returns a string representation of this rank which is the full name
* where the first letter is capitalised and the rest are lowercase
*/
@Override public String toString () {
//only capitalize the first letter
String s = super.toString();
return s.substring (0, 1).toUpperCase() + s.substring(1).toLowerCase();
}
public String getSymbol () {
return this.symbol;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I think you <em>should</em> add a numeric field indicating the order of a card relative to the other cards. You do not need to use it for anything other than sorting. </p>\n\n<p>Also, instead of taking the identifier of the enum value and doing uppercase and lowercase tricks with it in order to turn it into something presentable to the user, you should just store the name, too, as a separate string in the enum. </p>\n\n<p>So, it would look like this: <code>ACE( \"A\", \"Ace\", 0 )</code> (where 0 indicates lowest order for sorting.)</p>\n\n<p>Furthermore you can also add one more number, the 'weight' of a card, to use in calculations which determine whether a card beats another. In general, enums in java are very powerful, so powerful that you pretty much end up not having to use the switch statement with enums anymore, because you can include a big part of an enum's functionality within the enum itself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T21:34:27.393",
"Id": "11920",
"Score": "0",
"body": "Thanks for the answer Mike. However I'm not sure about adding a numerical field for sorting. Enum provides you with the sorting and comparison capability already. It would feel like you are stepping over the Enum mechanisms, but, on the other hand, it would indicate explicitly which element is the greatest, so there might be a point in doing it that way."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T19:12:45.820",
"Id": "7597",
"ParentId": "7593",
"Score": "3"
}
},
{
"body": "<p>One way to do it: </p>\n\n<pre><code>Rank[] values = Rank.values();\nfor (int i = values.length - 1; i >= 0; i--)\n ... values[i];\n</code></pre>\n\n<p>However that is slightly dangerous because it relies on the implicit ordering you used in the declaration.</p>\n\n<p>Otherwise:</p>\n\n<pre><code>for (Rank rank : Rank.getBackwardIterator())\n ... rank\n</code></pre>\n\n<p>where in Rank:</p>\n\n<pre><code>private List<Rank> backwardList = Arrays.asList(ACE, ..., TWO); \n\npublic Iterator<Rank> getBackwardIterator() {\n return backwardList.iterator();\n}\n</code></pre>\n\n<p>On a more general note, cards really do have an ordering. You are using it to print them out backward, but I guess you'll use the ordering in many other places, so you should probably do as was suggested by Mike Nakis and put a hard numerical value in Rank. Alternatively, you can just make sure you define the cards are declared in the right order and make use of the default (enum.compareTo()).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T00:29:16.853",
"Id": "12423",
"Score": "0",
"body": "Hi toto2, thanks for your answer. Cards do have an order but it's not so clear about numerical values (in poker). It's not a very important question and it's a very small nuance, but it would seem a breach of encapsulation knowing which one is the highest and which one is the lowest. I like that idea of adding a method with an explanatory name. That is a good solution. Not \"getBackward\" possibly, but something like \"fromHighest\", or similar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T00:41:24.133",
"Id": "12424",
"Score": "0",
"body": "I'm not a poker specialist, but I think a pair of 3's beats a pair of 2's. It would just be natural for your enum to include that information."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T16:18:43.677",
"Id": "7843",
"ParentId": "7593",
"Score": "1"
}
},
{
"body": "<p>Probably not, because the value of the cards can vary from game to game. Some games treat ace as low, others treat ace as high. Blackjack lets the player choose whether to count an ace as 1 or 11, and all face cards as 10.</p>\n\n<p>If you only intend to use this enum for a particular game, feel free to do whatever is pragmatic. However, if you intend to model playing cards in general, then avoid hard-coding assumptions into the enum itself.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T22:43:39.470",
"Id": "37995",
"ParentId": "7593",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T18:20:54.730",
"Id": "7593",
"Score": "5",
"Tags": [
"java",
"playing-cards",
"enum"
],
"Title": "Should I design my enumeration in some way that indicates what the highest value is?"
}
|
7593
|
<p>I'm a beginner in Java so I would appreciate a review of following simple class - in fact it's my first real usage of enums.</p>
<p>The background: I'm parsing MySQL internal client-server protocol. One of the fields in server greeting and client authorization packet is "Client capabilities" which is 32 bit integer encoding 18 boolean flags ( if anyone is interested: <a href="http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Handshake_Initialization_Packet" rel="nofollow">http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Handshake_Initialization_Packet</a>)</p>
<p>I've read that the most 'java way' to implement such thing will be using EnumSet class.</p>
<p>I'll welcome any suggestions and other solutions - my needs are:</p>
<ol>
<li>I must be able to parse flags from 4 bytes big endian buffer</li>
<li>To encode flags back to 4 bytes big endian buffer</li>
<li>To check if some arbitrary flag is set</li>
</ol>
<p>here's the code:</p>
<pre><code>public class ClientCapabilities
{
public enum Flag {
CLIENT_LONG_PASSWORD (1<<0),
CLIENT_FOUND_ROWS (1<<1),
CLIENT_LONG_FLAG (1<<2),
CLIENT_CONNECT_WITH_DB (1<<3),
CLIENT_NO_SCHEMA (1<<4),
CLIENT_COMPRESS (1<<5),
CLIENT_ODBC (1<<6),
CLIENT_LOCAL_FILES (1<<7),
CLIENT_IGNORE_SPACE (1<<8),
CLIENT_PROTOCOL_41 (1<<9),
CLIENT_INTERACTIVE (1<<10),
CLIENT_SSL (1<<11),
CLIENT_IGNORE_SIGPIPE (1<<12),
CLIENT_TRANSACTIONS (1<<13),
CLIENT_RESERVED (1<<14),
CLIENT_SECURE_CONNECTION (1<<15),
CLIENT_MULTI_STATEMENTS (1<<16),
CLIENT_MULTI_RESULTS (1<<17);
public final int weight;
Flag(Integer weight) {
this.weight = weight;
}
}
private final int originalInt;
private final EnumSet<Flag> flags = EnumSet.noneOf(Flag.class);
public ClientCapabilities(int capabilities)
{
originalInt = capabilities;
for (Flag f : Flag.values()) {
if ((capabilities & f.weight) > 0) {
flags.add(f);
}
}
}
public int getAsInt()
{
return originalInt;
}
public EnumSet<Flag> getFlags()
{
return flags;
}
@Override
public String toString() {
return flags.toString();
}
//only tests ahead - TestNG, not JUnit!
@Test
public static void testDecodingClientCapabilities()
{
byte[] exampleBuffer = new byte[] { (byte) 0x85, (byte) 0xa6, (byte) 0x03, (byte) 0x00 };
EnumSet<Flag> expectedEnumSet = EnumSet.of(
Flag.CLIENT_LONG_PASSWORD,
Flag.CLIENT_LONG_FLAG,
Flag.CLIENT_LOCAL_FILES,
Flag.CLIENT_PROTOCOL_41,
Flag.CLIENT_INTERACTIVE,
Flag.CLIENT_TRANSACTIONS,
Flag.CLIENT_SECURE_CONNECTION,
Flag.CLIENT_MULTI_STATEMENTS,
Flag.CLIENT_MULTI_RESULTS
);
ClientCapabilities capabilities = new ClientCapabilities(
PacketByteBuffer.readIntFromFourBytes(exampleBuffer,0));
Assert.assertEquals(capabilities.getFlags(), expectedEnumSet);
}
@Test
public static void testEncodingClientCapabilities()
{
byte[] exampleBuffer = new byte[] { (byte) 0x85, (byte) 0xa6, (byte) 0x03, (byte) 0x00 };
byte[] targetBuffer = new byte[] { 0, 0, 0, 0, 0};
ClientCapabilities capabilities = new ClientCapabilities(
PacketByteBuffer.readIntFromFourBytes(exampleBuffer,0));
PacketByteBuffer.writeIntToFourBytes(targetBuffer, 1, capabilities.originalInt);
Assert.assertEquals(targetBuffer[1], (byte) 0x85);
Assert.assertEquals(targetBuffer[2], (byte) 0xa6);
Assert.assertEquals(targetBuffer[3], (byte) 0x03);
Assert.assertEquals(targetBuffer[4], (byte) 0x00);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Looks fine to me. The only thing I have to notice is that <code>if ((capabilities & f.weight) > 0)</code> should instead be <code>if ((capabilities & f.weight) != 0)</code>. The reason for this is that if you were using bit #31 (the 32nd bit) then the expression <code>capabilities & f.weight</code> would yield a negative number, so it would not pass the test for <code>> 0</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T19:16:13.420",
"Id": "7598",
"ParentId": "7594",
"Score": "2"
}
},
{
"body": "<p>It looks fine. Some notes about the tests:</p>\n\n<p>Test methods should be in another class (<code>ClientCapabilitiesTest</code>) and in a separate source tree. For example, Maven projects usually store sources under <code>src/main/java</code> and test sources under <code>src/test/java</code>. (<a href=\"http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html\" rel=\"nofollow\">Introduction to the Standard Directory Layout</a>).</p>\n\n<hr>\n\n<p>The <a href=\"http://www.junit.org/apidocs/org/junit/Assert.html#assertEquals%28long,%20long%29\" rel=\"nofollow\">first parameter of <code>assertEquals</code> is the expected value</a> and the second is the actual one, so you should change</p>\n\n<pre><code>assertEquals(targetBuffer[1], (byte) 0x85);\n</code></pre>\n\n<p>to</p>\n\n<pre><code>assertEquals((byte) 0x85, targetBuffer[1]);\n</code></pre>\n\n<p>JUnit error messages assumes this order.</p>\n\n<hr>\n\n<p>Create more tests which helps <a href=\"http://xunitpatterns.com/Goals%20of%20Test%20Automation.html#Defect%20Localization\" rel=\"nofollow\">defect localization</a>. A parameterized test class would be fine:</p>\n\n<pre><code>import static org.junit.Assert.assertEquals;\n\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.EnumSet;\n\nimport org.junit.Assert;\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 ClientCapabilitiesTest {\n\n private final byte[] input;\n private final EnumSet<Flag> expected;\n\n @Parameters\n public static Collection<Object[]> data() {\n // TODO: add more cases\n final Object[][] data = new Object[][] {\n { new byte[] { (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00 },\n EnumSet.of(Flag.CLIENT_LONG_PASSWORD) },\n { new byte[] { (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00 }, \n EnumSet.of(Flag.CLIENT_FOUND_ROWS) },\n { new byte[] { (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00 },\n EnumSet.of(Flag.CLIENT_LONG_PASSWORD, Flag.CLIENT_FOUND_ROWS) },\n { new byte[] { (byte) 0x85, (byte) 0xa6, (byte) 0x03, (byte) 0x00 },\n EnumSet.of(Flag.CLIENT_LONG_PASSWORD, \n Flag.CLIENT_LONG_FLAG, \n Flag.CLIENT_LOCAL_FILES,\n Flag.CLIENT_PROTOCOL_41, \n Flag.CLIENT_INTERACTIVE, \n Flag.CLIENT_TRANSACTIONS,\n Flag.CLIENT_SECURE_CONNECTION, \n Flag.CLIENT_MULTI_STATEMENTS, \n Flag.CLIENT_MULTI_RESULTS) } };\n return Arrays.asList(data);\n }\n\n public ClientCapabilitiesTest(final byte[] input, final EnumSet<Flag> expected) {\n this.input = input;\n this.expected = expected;\n }\n\n @Test\n public void testDecodingClientCapabilities() {\n final ClientCapabilities capabilities = new ClientCapabilities(\n PacketByteBuffer.readIntFromFourBytes(input, 0));\n\n Assert.assertEquals(expected, capabilities.getFlags());\n }\n}\n</code></pre>\n\n<p>I'd add one case for every flag and some cases with multiple enabled flags.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T22:50:18.223",
"Id": "11922",
"Score": "0",
"body": "Thanks for the answer, but I forgot to mention that tests are in TestNG (and it seems they have opposite expected-actual parameter order)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:29:59.153",
"Id": "7602",
"ParentId": "7594",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7602",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T18:31:14.033",
"Id": "7594",
"Score": "3",
"Tags": [
"java",
"enum"
],
"Title": "Boolean flags encoded as integer implemented with EnumSet"
}
|
7594
|
<p>For practice, I've implemented Sieve of Eratosthenes in Java by thinking about <a href="http://en.wikipedia.org/wiki/File%3aSieve_of_Eratosthenes_animation.gif" rel="nofollow">this visual animation</a>.</p>
<p>I would like to hear some suggestions for improvements, especially how to make it more efficient and readable (sometimes there are trade offs) and how to follow good Java conventions. Also, suggestions on issues from naming conventions to proper javadoc are welcome as well. I'm just trying to improve my programming skills.</p>
<p>Incidently, the <code>sieveOfEratosthenes</code> method below is big O(?).</p>
<pre><code>/**
* returns a boolean array for prime numbers
* @param max the maximum value to search for primes
* @return boolean array of integers with primes true
*/
public boolean[] sieveOfEratosthenes(int max){
boolean[] primeCandidates = new boolean[max]; //defaults to false
for(int i=2; i<max; i++ ){primeCandidates[i]=true;}
for(int i=2; i<Math.sqrt(max);i++){
if(primeCandidates[i] == true){
//all multiples of i*i, except i, are not primeCandidates
for(int j = i + i; j<max; j=j+i){
primeCandidates[j]=false;
}
}
}
return primeCandidates;
}
/**
* print the index number for all true in given array
* @param a boolean array
*/
public void printTrue(boolean[] arr){
for(int i=0; i<arr.length; i++){
if(arr[i]==true){
System.out.print(i + ", ");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Input checking is missing. You should throw an <code>IllegalArgumentException</code> if <code>max</code> is less than zero instead of the <code>NegativeArraySizeException</code>. </p>\n\n<p>Result of <code>Math.sqrt(max)</code> doesn't change, so maybe it's would worth to extract out to a local variable but maybe the JVM already optimize this for you.</p>\n\n<p>Anyway, it's fine. I made some renaming and formatting, here is the result:</p>\n\n<pre><code>public boolean[] sieveOfEratosthenes(final int max) {\n if (max < 0) {\n throw new IllegalArgumentException(\"max cannot be less than zero: \" + max);\n }\n final boolean[] primeCandidates = new boolean[max]; // defaults to false\n for (int i = 2; i < max; i++) {\n primeCandidates[i] = true;\n }\n\n final double maxRoot = Math.sqrt(max);\n for (int candidate = 2; candidate < maxRoot; candidate++) {\n if (primeCandidates[candidate]) {\n for (int j = 2 * candidate; j < max; j += candidate) {\n primeCandidates[j] = false;\n }\n }\n\n }\n return primeCandidates;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T12:00:35.220",
"Id": "11990",
"Score": "4",
"body": "I'd additionally rename the first `i` to `idx`, remove the `== true` check and rename `j`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T21:38:12.037",
"Id": "7606",
"ParentId": "7599",
"Score": "11"
}
},
{
"body": "<p>Since there are fewer primes, you could use a list of some kind to hold the prime numbers.</p>\n\n<p>For every prime number n greater than 3,</p>\n\n<p><code>n mod 6 = 1</code> or <code>n mod 6 = 5</code>.</p>\n\n<p>If you could somehow not check other numbers for prime, you might save on some primeness checking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T22:46:45.423",
"Id": "7608",
"ParentId": "7599",
"Score": "-1"
}
},
{
"body": "<p>You asked about big O notation. I believe your implementation is O(n ln ln n).</p>\n\n<p>(See this Stack Overflow discussion: <a href=\"https://stackoverflow.com/questions/5649068/why-is-sieve-of-eratosthenes-more-efficient-than-the-simple-dumb-algorithm\">\"Why is Sieve of Eratosthenes more efficient than the simple “dumb” algorithm?\"</a>)</p>\n\n<p>By the way, instead of testing for:</p>\n\n<pre><code>i < Math.sqrt(max)\n</code></pre>\n\n<p>it is usually faster to test for:</p>\n\n<pre><code>i * i < max\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-02T13:12:25.080",
"Id": "174381",
"Score": "1",
"body": "Actually `i*i < max` is slower than `i < Math.sqrt(max)` in practice because the JIT can deduce that `Math.sqrt(max)` is constant and move it out of the iteration (easy). It's harder for the compiler to remove the multiplication in your example. At any rate the fastest code to regardless of optimization is just: `int sqrt_max = (int)Math.sqrt(max); for(...; i < sqrt_max; ...)`. Your example is useful when you're not repeatedly looping and testing the condition. For example seeing which of two vectors is longer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T01:38:34.690",
"Id": "7628",
"ParentId": "7599",
"Score": "6"
}
},
{
"body": "<p>To chip in an extra observation: <code>boolean[]</code> is memory-inefficient. In standard VMs it uses a byte per entry. For storing large arrays of Booleans, it's generally a good idea to prefer <code>java.util.BitSet</code>.</p>\n\n<p><code>BitSet</code> also has methods to clear and set large chunks of consecutive bits which work on a backing <code>int[]</code> and give a major speed-up – although that's probably not significant here, since you're unlikely to find that</p>\n\n<pre><code>for(int i=2; i<max; i++ ){primeCandidates[i]=true;}\n</code></pre>\n\n<p>is a bottleneck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T20:17:48.623",
"Id": "71493",
"Score": "1",
"body": "`BitSet` is a great way to save memory, but it *definitely* slows it down. Any speed improvement gained from the ability to set/clear chunks is outweighed by making the `get()` call every time you look at an entry. In my sieve, using `BitSet` took about 40% longer for large sieves."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-13T23:21:04.617",
"Id": "71516",
"Score": "0",
"body": "@Geobits, interesting. I didn't profile, but I would have expected that the JIT would take care of that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-07T00:21:21.840",
"Id": "99060",
"Score": "0",
"body": "@Geobits, yes, that's interesting. Do you have any timing values that I could compare with? I wrote an implementation of this algorithm using a BitSet and it will find all of the primes up to the maximum integer - 2 in about 40 seconds. I thought this was pretty good, but maybe I was just being naive?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T12:28:47.157",
"Id": "36635",
"ParentId": "7599",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>The following line </p>\n\n<blockquote>\n<pre><code>for(int i=2; i<max; i++ ){primeCandidates[i]=true;}\n</code></pre>\n</blockquote>\n\n<p>is very badly written without proper formatting. The correct way is to give space after <code>)</code> and also both side of any operator such as <code>=</code>,<code>+</code> for better readability.</p>\n\n<pre><code>for(int i = 2; i < max; i++) {\n primeCandidates[i] = true;\n}\n</code></pre>\n\n<p>However what are you trying to accomplish can be done in one line</p>\n\n<pre><code>java.util.Arrays.fill(primeCandidates, true);\n</code></pre></li>\n<li><p>Secondly since the default value for any boolean array is <code>false</code> I would take that advantage and change my code accordingly (borrowing <a href=\"https://codereview.stackexchange.com/a/7606/26200\"><em>palacsint's code</em></a>)</p>\n\n<pre><code>/**\n * Returns a boolean array with non-prime numbers as true.\n *\n */\n\npublic boolean[] sieveOfEratosthenes(final int max) {\n if (max < 0) {\n throw new IllegalArgumentException(\"max cannot be less than zero: \" + max);\n }\n final boolean[] compositeCandidates = new boolean[max];\n\n final double maxRoot = Math.sqrt(max);\n for (int candidate = 2; candidate < maxRoot; candidate++) {\n if (!compositeCandidates[candidate]) {\n for (int multiples = 2 * candidate; multiples < max; multiples += candidate) {\n compositeCandidates[multiples] = true;\n }\n }\n\n }\n return compositeCandidates;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T20:05:01.947",
"Id": "85001",
"Score": "0",
"body": "There is no \"correct\" code style, it's a matter of convention (and I personally find a different style mor readable). The thing one wants to look out for is *consistency*."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T19:28:07.580",
"Id": "44292",
"ParentId": "7599",
"Score": "1"
}
},
{
"body": "<p>There is is a mistake in the initial code that is changed in all the reply's but never mentioned.</p>\n\n<pre><code>for(int i=2; i<Math.sqrt(max);i++){\n if(primeCandidates[i] == true){\n //all multiples of i*i, except i, are not primeCandidates\n for(int j = i + i; j<max; j=j+i){\n primeCandidates[j]=false;\n }\n }\n</code></pre>\n\n<p>The inner for loop is incorrect you should be getting the square of i not the sum. It should read:</p>\n\n<pre><code>for(int j = i * i; j<max; j=j+i){\n</code></pre>\n\n<p>not:</p>\n\n<pre><code>for(int j = i + i; j<max; j=j+i){\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-13T23:01:52.573",
"Id": "164479",
"Score": "0",
"body": "Well, it's an efficiency problem, not a bug in terms of correctness."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-13T22:48:42.587",
"Id": "90694",
"ParentId": "7599",
"Score": "2"
}
},
{
"body": "<p>Because 2 is the only even prime number, you can eliminate about half of the loop iterations by incrementing i by 2 in the comparison loop instead of 1 (++). Set all non-2 even bits false initially, set the 2 bit to true, and use the initial set-to-true loop to set odd bits to true:</p>\n\n<pre><code>boolean[] primeCandidates = new boolean[max]; //defaults to false\nprimeCandidates[2]=true;\n//2 is the only even prime number, so set only odd primeCandidates to true\nfor (int i = 3; i < max; i += 2) {\n primeCandidates[i] = true;\n}\nint limit = (int)Math.sqrt(max);\n//because all non-2 primes are odd, skip checking even numbers\nfor (int i = 3; i < limit; i+=2){\n ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-16T14:08:01.180",
"Id": "138843",
"ParentId": "7599",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T19:20:59.177",
"Id": "7599",
"Score": "12",
"Tags": [
"java",
"optimization",
"algorithm",
"primes",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes"
}
|
7599
|
<p>I asked a <a href="https://codereview.stackexchange.com/questions/7574/logger-to-syslog-with-error-log-fallback">question about an implementation of a logger using <code>syslog</code> and <code>error_log</code> as fallback</a> that made me re-evaluate my <code>Logger</code> interface. Before it simply forced a <code>log($timestamp, $message)</code> to be implemented but after reading over the answer to the question I'm not sure that this is the best API possible to work with all the different logging options available.</p>
<p>Here's my new interface that allows logs to be opened and closed.</p>
<pre><code><?php
/**
* @file
* @brief Holds the interface to be implemented by objects responsible for logging
* messages and data.
*/
namespace SprayFire\Logger;
interface Logger {
/**
* @brief We have left the parameters for this method blank on purpose; the
* implementations should be responsible for passing the appropriate arguments.
*
* @details
* It should be noted that if your implementation defines the method signature
* with parameters you may assign a default value to that parameter and your
* implementation will satisfy this method signature.
*
* @return true if log opened, false if didn't
*/
public function openLog();
/**
* @param $timestamp the timestamp for the given message
* @param $message The string message that should be appended to the end
* of the log
* @return true if the message was logged, false if it didn't
*/
public function log($timestamp, $message);
/**
* @return true if the log was closed, false if it didn't.
*/
public function closeLog();
}
</code></pre>
<p>My problem is keeping the interface generic enough while allowing the various different options needed in opening a log to be satisfied. For example, <code>NullLogger</code> wouldn't really need any parameters passed to <code>openLog()</code> where as <code>SysLogLogger</code> would probably need some parameters passed. How would I accomplish this?</p>
<p><strong>What I'm thinking now</strong></p>
<p>That parameters will be passed as variable arguments to the function and the implementation uses <code>func_get_args()</code> to retrieve the necessary information to open the log, if necessary.</p>
<p>Alternatively, the implementation could simply define the parameters needed and ensure there are default values for all parameters. This would ultimately supply the needs of the interface while still communicating to the user that parameters are needed.</p>
<p><strong>What I could be doing</strong></p>
<p>I could declare the parameter passed to <code>openLog()</code> as an array that holds the appropriate option information. This means though that I would need to create an array for every Logger, whether it is needed or not. I'm not one to micro-optimize but at the same time I don't want to be creating unused/needless resources.</p>
<p>I could declare the three parameters passed to <a href="http://www.php.net/manual/en/function.openlog.php" rel="nofollow noreferrer"><code>openlog</code></a> in <code>Logger::openLog</code>, and then declare default values for those in the method signature signaling that you could simply not provide these arguments. But, this really doesn't "feel" right, you'd also be signaling to the user that you could pass arguments to say, <code>NullLogger</code>, that might actually influence the way the implementation works and it really wouldn't.</p>
<p>I'm not sure what would be the best solution here and would appreciate any feedback on the interface's API and the solutions proposed.</p>
|
[] |
[
{
"body": "<blockquote>\n <p><code>NullLogger</code> wouldn't really need any parameters passed to \n <code>openLog()</code> where as <code>SysLogLogger</code> would probably need some \n parameters passed. How would I accomplish this?</p>\n</blockquote>\n\n<p>Pass these parameters to the constructor, store in a private field and use it in the <code>openLog</code> (or any other) function.</p>\n\n<p>If you use <code>func_get_args()</code> you wouldn't be able to replace the logging system without modifying the client code.</p>\n\n<p><a href=\"http://www.slf4j.org/\" rel=\"nofollow\">SLF4J</a> is a great example for a logging framework. Check it's <a href=\"http://www.slf4j.org/apidocs/org/slf4j/Logger.html\" rel=\"nofollow\">Logger interface</a>. It contains some methods but none of them depend on any implementation. Logback, Log4j, JCL and other implementations implements this simple interface and their external configuration determines the details.</p>\n\n<p>A note: maybe <code>timestamp</code> shouldn't be passed to the <code>log</code> function, it should be the internal of the logger implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-26T23:44:29.943",
"Id": "13032",
"Score": "0",
"body": "Ultimately I really liked the SLF4J logging implementation you linked and is the reason I accepted your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:47:23.663",
"Id": "7603",
"ParentId": "7600",
"Score": "2"
}
},
{
"body": "<p>When you have a log object the Log in the method name seems redundant.</p>\n\n<pre><code> // Option 1\n $log = new Logger();\n $log->openLog();\n\n // Option 2 \n $log = new Logger();\n $log->open();\n</code></pre>\n\n<p>I think the second is clearer and it also removes confusion between openlog and openLog.</p>\n\n<p>The main function of a logger is to log messages. I would argue that you could do away with the open and close methods all-together. Whether the appropriate resources are opened can be handled internally in the Logger class. The Logger class is also in a good position to know whether resources should be freed after the writing of a log is done.</p>\n\n<pre><code>private $isOpen;\n\nprivate function open()\n{\n \\openlog(); // etc.\n $this->isOpen = true;\n}\n\npublic function log($message) // I agree with palacsint on removing timestamp.\n{\n if (!$this->isOpen)\n {\n $this->open();\n }\n\n // Write your log message.\n}\n</code></pre>\n\n<p>Quite often you find that you don't need to close. For syslog closelog is optional. I wouldn't bother calling it. Let it close for itself. The same would go for logging to a file. Open it once, and then lock/write/unlock. I don't see a need to close the file unless you are doing something exotic with massive amounts of open files. If so, make is so that your logger opens and closes it on each write.</p>\n\n<pre><code> // lock/write/unluck\n flock($file, LOCK_EX);\n fwrite($file, $message);\n flock($file, LOCK_UN);\n</code></pre>\n\n<p>I would be interested as to any reasons to have open and close logic to be controlled from outside of the logger. In my own framework I have not run into any problems without open and close methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T02:28:43.900",
"Id": "7620",
"ParentId": "7600",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7603",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:03:52.433",
"Id": "7600",
"Score": "2",
"Tags": [
"php",
"api"
],
"Title": "Refactoring Logger interface to open and close logs"
}
|
7600
|
<p>What do you say about the code structure below? This is one of the recommended ways of writing JS code in my education.</p>
<p>What is the pros and cons with writing code this way?
Can you recommend any better and maybe more elegant ways of writing code?</p>
<pre><code>var DESKTOP = DESKTOP || {};
DESKTOP.Init = DESKTOP.Init || {};
DESKTOP.Windows = DESKTOP.Windows || {};
DESKTOP.desktop = DESKTOP.desktop || {};
DESKTOP.Windows = function(width, height){
this.width = width;
this.height = height;
};
DESKTOP.Windows.prototype.buildWindow = function(){
// code here...
};
DESKTOP.Windows.prototype.showMenu = function(text){
// code here...
};
DESKTOP.Windows.bgChange = function(width, height){
DESKTOP.Windows.call(this, width, height);
this.content = 'the content';
this.title = 'the title'
};
DESKTOP.Windows.bgChange.prototype = new DESKTOP.Windows();
DESKTOP.Windows.bgChange.prototype.loadImages = function(){
// code here...
};
DESKTOP.Desktop = function(){
// code here...
};
</code></pre>
<p>and so on...</p>
|
[] |
[
{
"body": "<p>Oh gosh... that looks horrible, whoever is teaching you has no idea of JS whatsoever.</p>\n\n<p>I'll give you a quick start on \"good\" structure.</p>\n\n<p>A bit on naming:</p>\n\n<pre><code>UPPERCASE = Constant\nUpperCamelCase = Class\neverythingElse = method / function / variable\n</code></pre>\n\n<p>Write a helper for defining namespaces, everything else will become unmaintainable soon.</p>\n\n<pre><code>namespace('Desktop.Windows');\n\nDesktop.Init = function() {\n\n};\n\nDesktop.Windows.prototype = {\n\n buildWindow: function() {\n\n\n },\n\n showMenu: function() {\n\n }\n\n};\n</code></pre>\n\n<p>No idea what <code>bgChange</code> is supposed to be, a sub-class?</p>\n\n<p>If you want to have \"sub class\" behavior:</p>\n\n<pre><code>namespace('foo.Base');\nfoo.Base = function(a, b, c) {\n\n};\n\n// Write your self a generic extend(a, b, c...) function which copies the values from b, c... onto a\nextend(foo.prototype, {\n\n show: function() {\n\n },\n\n other: function() {\n\n }\n\n});\n\n\nnamespace('foo.Extended');\nfoo.Extended = function(a, b, c, d) {\n\n foo.Base.call(this, a, b, c);\n // use d\n\n};\n\nextend(extended.prototype, foo.prototype, {\n\n // \"Overwrite\"\n show: function() {\n foo.Base.prototype.show.call(this, ...); // \"super call\"\n }\n\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T20:38:41.130",
"Id": "11970",
"Score": "0",
"body": "Is it really possible to write: \"namespace('Desktop.Windows');\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:29:18.100",
"Id": "12122",
"Score": "0",
"body": "If you provide a function called \"namespace\" which abstracts away the creation, sure ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:49:29.297",
"Id": "7604",
"ParentId": "7601",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7604",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T20:28:32.597",
"Id": "7601",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Desktop windows code"
}
|
7601
|
<p>I am creating a simple server that accepts a <code>int</code> and returns the value received twice:</p>
<pre><code>public class MyServer{
private static int port = 1234;
public static void main(String args[]){
try{
ServerSocket serversock=new ServerSocket(port);
while(true){
Socket socket=serversock.accept();
new Thread(new MyClass(socket)).start();
}
}catch(IOException e){}
}
}
class MyClass implements Runnable{
Socket socket;
public MyClass(Socket s){socket = s;}
public void run(){
try{
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
int x = in.readInt();
out.write(2*x);
socket.close();
}
catch(IOException e){}
}
}
</code></pre>
<p>My question is about redesigning the code. Are there any weaknesses in the design?
If yes, then what changes would make the code better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T15:18:13.817",
"Id": "12626",
"Score": "0",
"body": "NEVER catch exceptions and eat them silently, as you are doing: `catch(IOException e){}` At least put `e.printStackTrace();` between the braces."
}
] |
[
{
"body": "<p>The ugly part that sticks out is that you are silently ignoring the exceptions... You should do some cleanup and close the sockets at least.</p>\n\n<p>Improving a bit on the performance side, you are starting a new thread to execute a very small task, thus wasting a lot of time to start-up threads. You could instead submit the <code>Runnable</code>s to an <code>ExecutorService</code>, provided that receiving a number from the client does not depend on user input (otherwise you will block the thread pool if the first few clients don't send anything)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T05:42:34.857",
"Id": "11948",
"Score": "0",
"body": "Thankx for the valuable suggetion\ni am new to this, i am implementing Executerservice \nas\n\nExecutorService es = newCachedThreadPool();\n es.execute(new Double(socket));\n\nin place of \n new Thread(new Double(socket)).start();\n\nis this okay!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T08:33:55.500",
"Id": "11955",
"Score": "0",
"body": "@Rex, yes, the cached thread pool creates a number of initial threads and then recycles them when there are new tasks to execute. If you want to specify a fixed number of threads to use you can use newFixedThreadPool();"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T17:33:50.623",
"Id": "11968",
"Score": "1",
"body": "@Tudor newCachedThreadPool will actually only create threads on demand. It will start with 0 threads."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T22:38:27.690",
"Id": "7610",
"ParentId": "7609",
"Score": "6"
}
},
{
"body": "<p>If you really are planning on creating a thread for each incoming request just use and <code>Executors.newCachedThreadPool()</code>. As long as the incoming requests arent very often, this ExecutorService will create a new thread when you submit to it, but if a thread is idle and not being used, the service will reuse the thread instead of creating a new one.</p>\n\n<p>Edit: Here is the example using your code.</p>\n\n<pre><code>public class MyServer{\n\n private static int port = 1234;\n\n\n public static void main(String args[]){\n try{\n final ExecutorService service = Executors.newCachedThreadPool();\n ServerSocket serversock=new ServerSocket(port);\n while(true){\n Socket socket=serversock.accept();\n service.submit(new MyClass(socket));\n }\n }catch(IOException e){}\n }\n }\n\n class MyClass implements Runnable{\n\n Socket socket;\n\n public MyClass(Socket s){socket = s;}\n\n public void run(){\n try{\n DataInputStream in = new DataInputStream(socket.getInputStream());\n DataOutputStream out = new DataOutputStream(socket.getOutputStream());\n int x = in.readInt();\n out.write(2*x);\n socket.close();\n }\n catch(IOException e){}\n }\n}\n</code></pre>\n\n<p>With this you have the possibility of thread reuse.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T22:49:52.250",
"Id": "7611",
"ParentId": "7609",
"Score": "8"
}
},
{
"body": "<p>In addition to <a href=\"https://codereview.stackexchange.com/users/8996/tudor\">Tudor's</a> response, you also shouldn't write infinite loops - that's just silly. For servers that are intended to run for an unknown amount of time (possibly endlessly), I do</p>\n\n<pre><code>while (keepServerRunning) { // where 'keepServerRunning' is a simple boolean variable\n ...\n</code></pre>\n\n<p>...and then use a <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29\" rel=\"nofollow noreferrer\">shutdown hook</a> to set the value to <code>false</code> which allows the server (and the JVM) to exit normally, without having to kill the task via <code>kill -9</code> or a force close.</p>\n\n<p>While it's theoretically possible that a service will run forever, it's just not good practice to pretend like that happens in reality. Clean up after yourself, and provide your apps a simple, clean way to exit normally whenever possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T23:49:41.540",
"Id": "7612",
"ParentId": "7609",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "7611",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-08T22:31:17.317",
"Id": "7609",
"Score": "12",
"Tags": [
"java",
"multithreading",
"server"
],
"Title": "Concurrent programming with a simple server"
}
|
7609
|
<p>I've got my answer working (up until a <a href="http://www.nairaland.com/nigeria/topic-791297.0.html#msg9490894" rel="nofollow">7-digit answer</a> is requested, anyway), and would like some help </p>
<ol>
<li>returning the correct answer</li>
<li>speeding up the results</li>
</ol>
<p>I was thinking of storing the values of the possible palindromes before beginning my calculations, but I know it wouldn't speed things up anyhow. I've also read around that <a href="http://mathsuniverse.blogspot.com/2009/04/all-about-palindrome-numbers.html" rel="nofollow">the <em>'divide by 11'</em></a> trick isn't always reliable (see comment #2...<code>900009 / 11 = 81819</code>).</p>
<p>My code skims the top 10% of both the inner and outer loop before it decrements the outer loop by one, and repeats until the <em>first result</em> is found. This works fine, until the answer for 7-digit numbers is requested.</p>
<pre><code>"""http://projecteuler.net/problem=4
Problem 4
16 November 2001
A palindromic number reads the same both ways. The largest palindrome
made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
def main(n):
"""return the largest palindrome of products of `n` digit numbers"""
strstart = "9" * n
multic = int(strstart)
multip = multic -1
top = multic
while multic > top * .9:
while multip > multic * .9:
multip -= 1
if isPalin(multic * multip):
return multic, multip, multic*multip
multip = multic
multic -= 1
def isPalin(n):
n = str(n)
leng = len(n)
half = n[:leng/2]
if n[leng/2:] == half[::-1]:
return True
return False
if __name__ == '__main__':
main(3)
</code></pre>
<p>How's my approach here?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T00:59:54.577",
"Id": "11926",
"Score": "0",
"body": "what makes you think your code is broken for 7 digit numbers?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T02:13:13.557",
"Id": "11933",
"Score": "2",
"body": "The point of the Euler Project is that you should figure out the solution *yourself*, not get it from a forum..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T20:36:36.730",
"Id": "11969",
"Score": "0",
"body": "@Guffa: He did, he's just asking how to make it better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T22:16:37.143",
"Id": "11972",
"Score": "0",
"body": "@sepp2k: Most questions are designes so that you easily can get the correct result for small values, the tricky part is to make it work for large numbers, and using something other than brute force so that it doesn't take ages. So, he did the easy part..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T00:51:36.410",
"Id": "11975",
"Score": "0",
"body": "@Guffa is there a pattern for palindromes? I tried looking them up, but all I got was a rule that said most of the time, a palindrome / 11 will make another palindrome, and another that said summing the reverse of two numbers will eventually produce one...is there something you could share with me?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T04:45:05.687",
"Id": "11980",
"Score": "0",
"body": "@Guffa, you may be interested in voicing your opinions here: http://meta.codereview.stackexchange.com/questions/429/online-contest-questions"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T13:52:48.507",
"Id": "12168",
"Score": "0",
"body": "The assumption that checking the top 10% of the 'current range' will yield the top result is false. For 7 digits numbers, that yields the number 94677111177649 (composed from 9999979 and 9467731), while using a 1% spectrum yields the larger number 99500822800599 (composed from 9999539 and 9950541). Though I've no good idea on how to define the proper spectrum, or good ideas for another halting condition."
}
] |
[
{
"body": "<p>The way you use ranges is not particularly pythonic, as far as I can judge. I think something like this would be preferred:</p>\n\n<pre><code>def main(n):\n start = 10**n - 1\n for i in range(start, 0, -1):\n for j in range(start, i, -1):\n if is_palindrome(str(i*j)):\n return i, j, i*j\n return \"Not found!\"\n</code></pre>\n\n<p>I would also make <code>is_palindrome</code> recursive, although I am not sure it is faster</p>\n\n<pre><code>def is_palindrome(s):\n # Empty string counts as palindromic\n return not s or s[0] == s[-1] and is_palindrome(s[1:-1])\n</code></pre>\n\n<p>As for optimisations -- you could convert it into a list of numbers yourself, thereby skipping some error check that str() may be doing (however, as Winston Ewert has pointed out, this is unlikely to be faster). You could also try not creating a string at all like this:</p>\n\n<pre><code>from math import log\n\ndef is_palindrome(i):\n if i < 10:\n return True\n magnitude = 10**int(log(i, 10))\n remainder = i % magnitude\n leftmost = i / magnitude\n rightmost = i % 10\n return leftmost == rightmost and is_palindrome(remainder / 10)\n</code></pre>\n\n<p>I don't know if this is actually faster or not. You should probably get rid of the single-use variables, seeing as I am not sure they will be inlined.</p>\n\n<p>Alternative non-recursive solutions:</p>\n\n<pre><code>from math import log\n\ndef is_palindrome_integer_iterative(i):\n magnitude = 10**int(log(i, 10))\n while i >= 10:\n leftmost = i / magnitude\n rightmost = i % 10\n if leftmost != rightmost:\n return False\n magnitude /= 10\n i = (i % magnitude) / 10\n return True\n\ndef is_palindrome_string_iterative(s):\n for i in range(len(s)/2):\n if s[i] != s[-(i+1)]:\n return False\n return True\n</code></pre>\n\n<p>These are nowhere near as elegant as the recursive one, in my opinion, but they very well may be faster. I've <a href=\"http://ideone.com/IpgrD\" rel=\"nofollow\">profiled all <s>five</s> six with the inputs 53435 and 57435</a> (takes too long on ideone, but is fine locally) and got the following results:</p>\n\n<pre><code> 53435 57435\nOriginal 1.48586392403 1.48521399498\nString recursive 1.64582490921 0.965192079544\nInteger recursive 3.38510107994 3.06183409691\nInteger iterative 2.0930211544 2.07299590111\nString iterative 1.47460198402 1.44726085663\nWinston's version 1.31307911873 1.29281401634\n</code></pre>\n\n<p>Therefore, apparently, it is possible to write something a little faster to what you have, but not by a lot; profiling with a larger set of inputs is needed to really be sure, too. If false inputs are indeed significantly faster to compute with the recursive variant, you may be better off using it as most of the results are not going to be palindromes.</p>\n\n<p>EDIT: I've added the function provided by Winston to the results.</p>\n\n<p>EDIT2: More functions and their running times can be found <a href=\"http://ideone.com/IBNcX\" rel=\"nofollow\">here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T01:49:49.770",
"Id": "11929",
"Score": "0",
"body": "Recursion in python is going to be slow. So I gotta recommend not doing that. Also `str` is implemented in C and is going be much faster then anything you implement in Python."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T02:46:43.147",
"Id": "11935",
"Score": "0",
"body": "Your comparison seems a little unfair, `is_palin_orig` has to convert its integer input to a string, but you've give `is_palin_strrec` the string version for free. Also, you could include the suggested version from my post. But some things are unclear to me: why is the recursive version faster then the iterative version? Not what I'd expect."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T03:23:07.130",
"Id": "11942",
"Score": "0",
"body": "I've got a couple more variations that might be of interest: http://pastebin.com/FPfb6DUL. Interestingly, running the benchmarks on PyPy instead of CPython produces quite different results. In particular, your recursive version is 3 times faster then any other method I've tried."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T04:44:05.343",
"Id": "11946",
"Score": "0",
"body": "Oh, good that you saw that; I've added a link with the new functions and with all int-to-string conversion being done on the spot. That does even out the results quite a bit. I'm getting about the same difference in PyPy (0.3 against 0.11). I suspect that this is due to tail recursion optimisation, but I'm not sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T15:17:42.520",
"Id": "11964",
"Score": "0",
"body": "`is_palin_winston` now calls `str` twice. You should probably take on of them out. I'll guess that PyPy has TCO and also doesn't actually copy the string when a slice is made."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T15:35:16.673",
"Id": "11965",
"Score": "0",
"body": "Fixed. :) That's why I shouldn't gather data in the middle of the night..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T01:50:35.503",
"Id": "11978",
"Score": "0",
"body": "Your recursive validation approach for confirming a palindromic number earns +1 for style, but if I'm going to convert to strings I'm going all the way, and getting it over with as quickly as possible. Also, you set the outer loop's lower bound to zero. That was good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T13:35:51.523",
"Id": "12167",
"Score": "1",
"body": "Trying some of these on various lengths numbers, it seems like the shortest (admittedly dirtiest) way to do this is also significantly faster than everything else: `return num_string == num_string[::-1]`. The optimisation that @WinstonEwert wrote that only compares the first and latter half starts to outperform this simplest form once you hit ~100 digit numbers. Results obtained from Python2.6 (regular CPython)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T15:16:47.703",
"Id": "12171",
"Score": "0",
"body": "@Elmer, now I feel dumb for not thinking of such an obvious simple form."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T01:16:45.113",
"Id": "7616",
"ParentId": "7615",
"Score": "2"
}
},
{
"body": "<pre><code>def main(n):\n \"\"\"return the largest palindrome of products of `n` digit numbers\"\"\"\n strstart = \"9\" * n\n multic = int(strstart)\n</code></pre>\n\n<p>Firstly, for two such short lines you'd do better to combine them. <code>multic = int(\"9\" * n)</code>. However, even better would be to avoid generating strings and then converting to ints. Instead, use math. <code>multic = 10**n - 1</code></p>\n\n<pre><code> multip = multic -1\n</code></pre>\n\n<p>Guessing what multip and multic mean is kinda hard. I suggest better names.</p>\n\n<pre><code> top = multic\n\n while multic > top * .9:\n</code></pre>\n\n<p>You should almost always use for loops for counting purposes. It'll make you code easier to follow.</p>\n\n<pre><code> while multip > multic * .9:\n multip -= 1\n if isPalin(multic * multip):\n return multic, multip, multic*multip\n multip = multic\n multic -= 1\n\ndef isPalin(n):\n</code></pre>\n\n<p>Use underscores to seperate words (the python style guide says so) and avoid abbreviations.</p>\n\n<pre><code> n = str(n)\n leng = len(n)\n</code></pre>\n\n<p>This assignment doesn't really help anything. It doesn't make it clearer or shorter, so just skip it</p>\n\n<pre><code> half = n[:leng/2]\n if n[leng/2:] == half[::-1]:\n return True\n return False \n</code></pre>\n\n<p>Why split the slicing of the second half in two? Just do it all in the if. Also use <code>return n[...] == half[..]</code> no need for the if.</p>\n\n<pre><code>if __name__ == '__main__':\n main(3) \n</code></pre>\n\n<p>Here is my quick rehash of your code:</p>\n\n<pre><code>def main(n):\n \"\"\"return the largest palindrome of products of `n` digit numbers\"\"\"\n largest = 10 ** n - 1\n for a in xrange(largest, int(.9 * largest), -1):\n for b in xrange(a, int(.9 * a), -1):\n if is_palindrome(a * b):\n return a, b, a * b\n\ndef is_palindrome(number):\n number = str(number)\n halfway = len(number) // 2\n return number[:halfway] == number[:-halfway - 1:-1]\n\nif __name__ == '__main__':\n print main(3) \n</code></pre>\n\n<p>Your link on 7-digit numbers is to a post discussing integer overflow in Java. Integer overflow does not exist in Python. You simply don't need to worry about that.</p>\n\n<p>The challenge asks the answer for a 3 digit problem, so I'm not sure why you are talking about 7 digits. Your code is also very quick for the 3 digits so I'm not sure why you want it faster. But if we assume for some reason that you are trying to solve the problem for 7 digits and that's why you want more speed:</p>\n\n<p>My version is already a bit faster then yours. But to do better we need a more clever strategy. But I'm not aware of any here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T00:53:29.760",
"Id": "11976",
"Score": "0",
"body": "`multic` = `multicand`; `multip` = `multiplier`. Would it be better if I changed the names to `mc` and `mp`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T01:20:52.900",
"Id": "11977",
"Score": "0",
"body": "Thanks for the `10**n` bit, and pointing out the string at the top of the method. Those were leftovers form an earlier approach. Do you know of a pattern to [generate palindromes *mathematically*](http://math.stackexchange.com/questions/97752/generating-numeric-palindromes)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T02:13:12.703",
"Id": "11979",
"Score": "1",
"body": "@Droogans, no `mc` and `mp` don't help. Use `multiplier` and `multicand` you aren't paying per letter you use in your variable name. Use full words and avoid abbreviations"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T01:17:21.040",
"Id": "7617",
"ParentId": "7615",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7617",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T00:31:08.417",
"Id": "7615",
"Score": "3",
"Tags": [
"python",
"optimization",
"project-euler",
"palindrome"
],
"Title": "Project Euler, #4: Incorrect Results on 7-digit numbers"
}
|
7615
|
<p>I have this recursive function that searches an object tree structure:</p>
<pre><code>dataSearcher = (dataElement, identifierToFind) ->
if dataElement.identifier == identifierToFind
return dataElement
else
for childDataElement in dataElement.children
found = dataSearcher childDataElement, identifierToFind
if found then return found
</code></pre>
<p>Which I then call thus:</p>
<pre><code>foundDataElement = dataSearcher @options.nodeData, identifier
</code></pre>
<p>It works just fine so I am happy about that, but I am pretty new to CoffeeScript and would like feedback on the way I structured it. The loop I used seems a bit old school, so could I have used a comprehension here instead? Any other feedback would be great as I am still getting my head into the CoffeeScript idiom.</p>
<p>Please let me know if I should edit with more context code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T18:34:38.337",
"Id": "11930",
"Score": "2",
"body": "You could make the `for` a comprehension, but it wouldn't cut the visit short when a match was found, so while this is less \"functional\" it's just as good. The real test of code is this: which do you expect to be able to read six months from now? I'd remove the 'else', but that's my Haskell training talking: you've got a guard condition at the top of your function, not an alternative, but that's how *I* read things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-07T14:42:24.590",
"Id": "11931",
"Score": "1",
"body": "side note: the functional abstraction for what you are doing is `mapDetect` (see https://gist.github.com/1222480 for a underscore implementation). In a lazy language it would be `(head . filter predicate)`."
}
] |
[
{
"body": "<p>I'd prefer writing it like this:</p>\n\n<pre><code>dataSearcher = (element, identifier) -> \n return element if element.identifier is identifier\n for child in element.children\n found = dataSearcher child, identifier\n return found if found\n</code></pre>\n\n<p>Changes:</p>\n\n<ul>\n<li>guard style instead of <code>else</code> (one less level of indentation)</li>\n<li>postfix <code>if</code> (probably a question of style)</li>\n<li><code>is</code> instead of <code>==</code></li>\n<li>shorter variable names</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T23:29:35.077",
"Id": "11932",
"Score": "0",
"body": "That is the sort of thing I am looking for...I am pretty clear I am still writing my coffeescript in a js idiom. Good coaching."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T19:18:49.217",
"Id": "7619",
"ParentId": "7618",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "7619",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-06T15:47:07.810",
"Id": "7618",
"Score": "4",
"Tags": [
"beginner",
"recursion",
"search",
"coffeescript"
],
"Title": "Searching an object tree structure"
}
|
7618
|
<p>I've been working on a JS/HTML5 Game Engine. Right now I'm calling it DimSumJs, because like <a href="http://en.wikipedia.org/wiki/Dim_sum" rel="nofollow">DimSum</a>, isn't a full meal, my framework still runs too slowly to make a full game (it can only run about 400 "objects" despite before slowing down, it becomes very noticeable around 500 "objects"). It uses <code>div</code>s inside an iframe.</p>
<p>Any advice is welcome! Please don't tell me to use an already made game engine. This is sort of a project of mine and I want to actually finish it.</p>
<p>Just view resources with Google Chrome and you should be able to find the dimsum.js file</p>
<pre><code>//DimSumJS - Open Source Game Engine
//DimSumJS (C) Ruochen Tang
//Can be used commerically, but please give credit
//Constants
var RIGHTKEY = 37;
var UPKEY = 38;
var LEFTKEY = 39;
var DOWNKEY = 40;
var SPACEKEY = 32;
var MASTER_WIDTH = 480;
var MASTER_HEIGHT = 600;
var Game = window.frames[0].document.body;
var GameWindow = window.frames[0];
var gl = setInterval("gameLoop();",15);
//Global Vars
var keyDown = new Array();
for (var i = 0; i < 256; i++){
keyDown[i] = false;
}
var gameState = 0;
//Settings
Game.style.backgroundColor = "#000";
//Key
processKeyEvent = function(event){
// MSIE hack
if (window.event)
{
event = window.event;
}
keyDown[event.keyCode] = true;
};
releaseKey = function(event){
// MSIE hack
if (window.event)
{
event = window.event;
}
keyDown[event.keyCode] = false;
}
Game.onkeydown = processKeyEvent;
Game.onkeyup = releaseKey;
var GameObjects = new Array();
function GameObject(xx, yy, w, h, i, inc, gs, name, img){
GameObjects.push(this);
this.width = w;
this.height = h;
this.index = i;
this.currIndex = 0;
this.increment = inc;
this.currInc = 0;
this.x = xx;
this.y = yy;
this.depth = 0;
this.objType = name;
this.image = img;
this.xScale = 1;
this.yScale = 1;
this.scaleString = "scale(" + this.xScale + "," + this.yScale + ")";
this.speed = 0;
this.direction = 0;
this.gravity = 0;
this.gravityDirection = 0;
this.active = true;
this.visible = true;
this.bindToRoom = false;
this.text = "";
this.color = "#FFF";
this.gameState = gs;
this.div = document.createElement("div");
this.div.className=this.objType;
this.div.style.position="absolute";
this.div.style.left= this.x + "px";
this.div.style.top= this.y + "px";
this.div.style.width= this.width + "px";
this.div.style.height= this.height + "px";
this.div.style.backgroundImage = "url(images/" + this.image + ")";
this.div.style[getTransformProperty(this.div)] = this.scaleString;
Game.appendChild(this.div);
this.isDiv = true;
this.classChanged = false;
this.move = move;
this.anim = anim;
this.setScale = setScale;
this.checkCollisionAt = checkCollisionAt;
this.objectAt = objectAt;
this.objectTypeAt = objectTypeAt;
this.toggleActive = toggleActive;
this.extend = extend;
this.unextend = unextend;
this.isType = isType;
this.update = update;
function move(xx,yy){
this.x += xx;
this.y += yy;
}
function anim(){
this.currInc += 1;
if (this.currInc >= this.increment){
this.currInc -= this.increment;
this.currIndex += 1;
if (this.currIndex >= this.index){
this.currIndex -= this.index;
}
}
}
function extend(type) {
this.objType += " " + type;
this.classChanged = true;
}
function unextend(type) {
this.objType = this.objType.replace( /(?:^|\s)type(?!\S)/ , '' );
this.classChanged = true;
}
function isType(type) {
return ((' ' + this.objType + ' ').indexOf(' ' + type + ' ') > -1);
}
function setScale(xx,yy){
this.xScale = xx;
this.yScale = yy;
this.scaleString = "scale(" + this.xScale + "," + this.yScale + ")";
}
function checkCollisionAt(xx,yy,other){
//Check For Collision
xx += this.x;
yy += this.y;
if ((xx + this.width > other.x) && (xx < other.x + other.width) && (yy + this.height > other.y) && (yy < other.y + other.height)){
return true;
}
else{
return false;
}
}
function objectAt(xx,yy,solid){
//Loop All Objects
for (var i = 0; i < GameObjects.length; i++){
if (GameObjects[i] != this && this.isDiv){
if (this.checkCollisionAt(xx,yy,GameObjects[i])){
console.log(i);
return true;
}
}
}
return false;
}
function objectTypeAt(xx,yy,type){
//Loop All Objects
for (var i = 0; i < GameObjects.length; i++){
if (GameObjects[i] != this && GameObjects[i].isType(type) && this.isDiv){
if (this.checkCollisionAt(xx,yy,GameObjects[i])){
return true;
}
}
}
return false;
}
function toggleActive(a){
this.visible = a;
this.update();
this.active = a;
}
function update(){
if ((this.active == false || this.gameState != gameState) && this.isDiv){
this.isDiv = false;
Game.removeChild(this.div);
return;
}
else if(!this.isDiv){
this.isDiv = true;
Game.appendChild(this.div);
}
this.div.style.display = "inline";
if (this.speed != 0){
this.x += this.speed*Math.cos(this.direction*Math.PI/180);
this.y += this.speed*Math.sin(this.direction*Math.PI/180);
}
if (this.bindToRoom == true){
if (this.x < 0){
this.x = 0;
}
if (this.y < 0){
this.y = 0;
}
if (this.x > MASTER_WIDTH-this.width){
this.x = MASTER_WIDTH-this.width;
}
if (this.y > MASTER_HEIGHT-this.height){
this.y = MASTER_HEIGHT-this.height;
}
}
if (!this.visible && this.isDiv){
this.isDiv = false;
Game.removeChild(this.div);
return;
}
if (this.classChanged){
this.div.className = this.objType;
}
this.div.style.zIndex = this.depth;
this.div.style.color = this.color;
this.div.innerHTML = this.text;
this.div.style.left= this.x + "px";
this.div.style.top= this.y + "px";
this.div.style[getTransformProperty(this.div)] = this.scaleString;
this.div.style.backgroundPosition = this.currIndex * this.width +"px 0";
}
}
function getTransformProperty(element) {
// Note that in some versions of IE9 it is critical that
// msTransform appear in this list before MozTransform
// By ZachAstronaut
var properties = [
'transform',
'WebkitTransform',
'msTransform',
'MozTransform',
'OTransform'
];
var p;
while (p = properties.shift()) {
if (typeof element.style[p] != 'undefined') {
return p;
}
}
return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T11:05:55.027",
"Id": "25197",
"Score": "0",
"body": "Have you tried setting the objects to null once your done using them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T12:37:32.677",
"Id": "25198",
"Score": "0",
"body": "I'm looking for the best way to do so, right now I'm deactivating them, so they just take up memory, but none of their functions are called. Wouldn't setting to null just change the where the reference variable is pointing, or is it different in javascript?"
}
] |
[
{
"body": "<p>The biggest improvement i could give is getting rid of all the if oftype</p>\n\n<p>replace with :</p>\n\n<pre><code>var enem1 = [];\nfunction enem1Step()\n{\n this.anim(); \n if (this.y > MASTER_HEIGHT){\n this.x = random()*(MASTER_WIDTH-64);\n this.y = -128;\n this.speed = 4 + random()*4;\n }\n if (this.objectTypeAt(0,0,\"bullet\")){\n this.hp--;\n }\n if (this.hp <= 0){\n this.x = random()*(MASTER_WIDTH-64);\n this.y = -128;\n this.speed = 4 + random()*4;\n this.hp = 25;\n return 100;\n }\n return 0;\n}\nfor (var i = 0; i < 50; i++){\n var currentEnem = enem1[i] = new GameObject(random()*(MASTER_WIDTH-64),-random()*MASTER_HEIGHT,16,16,2,8,1,\"enem1\", \"enemyship1.png\");\n currentEnem.speed = 4 + random()*4;\n currentEnem.direction = 80 + random()*20;\n currentEnem.hp = 25;\n currentEnem.extend(\"enem\");\n currentEnem.step = enem1Step;\n}\n</code></pre>\n\n<p>etc. (for stars and bullets and enem2)</p>\n\n<p>then </p>\n\n<pre><code>for(var i=0,currentObject = null; currentObject = GameObjects[i]; i++){\n\n if (currentObject.active ){\n currentObject.update();\n if( currentObject.step)\n {\n score += currentObject.step();\n }\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T12:39:24.820",
"Id": "11961",
"Score": "0",
"body": "Thanks, I'll try this when I get home from school. I'm glad you took a look at the game's source code, as well as the js file. I guess I implemented my own class wrong!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T00:48:44.967",
"Id": "12144",
"Score": "0",
"body": "My isType usage has gone down a huge amount! Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T06:20:49.600",
"Id": "7622",
"ParentId": "7621",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T04:13:06.200",
"Id": "7621",
"Score": "3",
"Tags": [
"javascript",
"optimization",
"html"
],
"Title": "Help optimize my HTML/JS game engine"
}
|
7621
|
<p>I wrote <a href="http://en.wikipedia.org/wiki/Nim">Nim Game</a> in Haskell. Since I'm just learning any review comments are highly appreciated.</p>
<pre><code>module Nim where
import Char
import List
import Maybe
--Domain
--Nim is a mathematical game of strategy
--in which two players take turns removing objects from distinct heaps.
--On each turn, a player must remove at least one object, and may remove
--any number of objects provided they all come from the same heap.
--Read more at http://en.wikipedia.org/wiki/Nim
--
type Board = [Int] --number of objects in each heap
type Heap = Int --Heap id
type Turn = (Int, Int) --heap and number of objects to remove
--Build new board according to old one and turn.
applyTurn :: Turn -> Board -> Board
applyTurn t b = map
(\ (i, v) -> if (i == fst t) then v - snd t else v)
(zip [1..] b)
--Check if board is empty. When it is, game is over.
empty :: Board -> Bool
empty b = all (<= 0) b
--Returns tupples of (heap index, number of object in the heap).
indexedHeaps :: Board -> [(Heap, Int)]
indexedHeaps b = zip [1..] b
--Returns heaps that contains one or more objects.
availableHeaps :: Board -> [Heap]
availableHeaps b = map fst (filter (\ (_, h) -> h > 0) (indexedHeaps b))
--Return number of objects in the heap.
availableObjectsByHeap :: Board -> Heap -> Int
availableObjectsByHeap b h = snd (head (
filter (\ (i, _) -> i == h) (indexedHeaps b)))
--IO Utils
--
--Read Int from console. There could be validation using predicate.
promtInt :: String -> (Int -> Bool) -> IO Int
promtInt msg p = do
putStr (msg ++ "> ")
c <- getChar
ignored <- getLine
let x = ((ord c) - ord('0'))
if(p x)
then return x
else promtInt msg p
--Read Int from console. Int should be in range.
promtIntFromRange :: String -> (Int, Int) -> IO Int
promtIntFromRange msg (from, to) = promtInt newMsg p where
newMsg = msg ++ "[" ++ show from ++ ";" ++ show to ++"]"
p v = v >= from && v <= to
--Read Int from console. Int should be in set.
promtIntFromSet :: String -> [Int] -> IO Int
promtIntFromSet msg s = promtInt newMsg p where
newMsg = msg ++ show s
p v = isJust (find (== v) s)
--Print each string from new line.
putAllStr :: [String] -> IO()
putAllStr [x] = do putStrLn x
putAllStr (x:xs) = do
putAllStr [x]
putAllStr xs
--Game specific IO
--
--Dialog for inputing turn data.
readTurn :: Board -> IO(Turn)
readTurn b = do
heap <- promtIntFromSet "heap" (availableHeaps b)
objects <- promtIntFromRange "number"
(1, (availableObjectsByHeap b heap))
return (heap, objects)
--Displays board in user friendly interface.
showBoard :: Board -> IO()
showBoard b = do
putAllStr (map stringify (indexedHeaps b)) where
objectsAtHeap n = concat(replicate n "*")
heapIndex i = "[" ++ show i ++ "]"
stringify (i, n) = heapIndex i ++ objectsAtHeap n
--Game
--
--Actually game.
play :: IO(Board)-> IO(Board)
play b = do
board <- b
if (empty board)
then return []
else do
showBoard board
t <- readTurn board
play (return (applyTurn t board))
--Runner function.
nim :: IO()
nim = do
ignored <- play (return [1, 2, 3, 1])
putStrLn "done"
</code></pre>
|
[] |
[
{
"body": "<p>These variations seem more direct and make better use of standard functions and idioms</p>\n\n<pre><code>--Build new board according to old one and turn.\napplyTurn :: Turn -> Board -> Board\napplyTurn (heap, removed) b = \n let (before, (at:after)) = splitAt (heap-1) b\n in before ++ ((at-removed):after)\n\n--Returns heaps that contains one or more objects.\navailableHeaps :: Board -> [Heap]\navailableHeaps b = [fst x | x <- indexedHeaps b, (snd x) > 0]\n</code></pre>\n\n<p>I'm still learning Haskell, too. There MAY be a more usual way of getting the nth element than head (drop (n-1) list).</p>\n\n<pre><code>--Return number of objects in the heap.\navailableObjectsByHeap :: Board -> Heap -> Int\navailableObjectsByHeap b h = head (drop (h-1) b)\n</code></pre>\n\n<p>I broke up your showBoard into putBoard and my showBoard to further isolate the pure code. This also makes a better analogy with \"show\" which does formatting but not IO</p>\n\n<pre><code>--Format board for user friendly interface.\nshowBoard :: Board -> [String]\nshowBoard b = map stringify (indexedHeaps b) where\n objectsAtHeap n = concat(replicate n \"*\")\n heapIndex i = \"[\" ++ show i ++ \"]\"\n stringify (i, n) = heapIndex i ++ objectsAtHeap n\n\n--Displays board in user friendly interface.\nputBoard :: Board -> IO()\nputBoard b = do \n putAllStr (showBoard b)\n</code></pre>\n\n<p>I just changed showBoard to putBoard, below.</p>\n\n<pre><code>--Game\n--\n--Actually game.\nplay :: IO(Board)-> IO(Board)\nplay b = do \n board <- b\n if (empty board)\n then return [] \n else do \n putBoard board\n t <- readTurn board\n play (return (applyTurn t board))\n</code></pre>\n\n<p>Aside from that, \"prompt\" is usually spelled with one more 'p' than \"tuples\" has.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T09:46:47.797",
"Id": "11983",
"Score": "0",
"body": "Thanks a lot. It's very good answer, but unfortunately I can accept only one."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T00:23:47.400",
"Id": "7627",
"ParentId": "7623",
"Score": "5"
}
},
{
"body": "<p>First, here's an overview on style and idiom without changing anything too significantly.</p>\n\n<pre><code>import Data.Char \nimport Data.List\nimport Data.Maybe\n</code></pre>\n\n<p>Switching to the current names for these modules. The non-hierarchical names exist only for compatibility. </p>\n\n<pre><code>type Board = [Integer] -- number of objects in each heap\ntype Heap = Integer -- Heap id\ntype Turn = (Integer, Integer) -- heap and number of objects to remove \n</code></pre>\n\n<p>There's really no reason to use <code>Int</code> except for number-crunching with small integers. Not that it's likely to matter here, but getting in the habit of using <code>Integer</code> by default means you don't have to worry about bugs due to, say, a counter in a long-running program exceeding the maximum size of <code>Int</code>. Mystery bugs that only occur on large data sets or after running for a long time are <em>not fun</em> to track down.</p>\n\n<p>The only problem is that some standard functions take only <code>Int</code> arguments for no good reason, rather than any integral type. This is a misfeature of the standard libraries and not one you should emulate.</p>\n\n<pre><code>applyTurn :: Turn -> Board -> Board\napplyTurn (heapId, removed) board = zipWith decHeap [1..] board\n where decHeap idx n | idx == heapId = n - removed\n | otherwise = n\n</code></pre>\n\n<p>Several things here: </p>\n\n<ul>\n<li>Pattern matching on the turn instead of using <code>fst</code> and <code>snd</code>, as well as better names for everything.</li>\n<li>Zipping lists and then mapping a function over that is what <code>zipWith</code> is for.</li>\n<li>Replacing the lambda with a function in the <code>where</code> clause, and using guards on that rather than an <code>if</code> expression.</li>\n</ul>\n\n<p>I've left the algorithm unchanged for now. It could be improved, as Paul Martel shows, but using lists for this purpose at all is really not ideal. I'll return to this point later.</p>\n\n<pre><code>availableHeaps :: Board -> [Heap]\navailableHeaps b = [heapId | (heapId, count) <- indexedHeaps b, count > 0]\n</code></pre>\n\n<p>A slightly different way of writing the same list comprehension Paul Martel used. Many Haskell programmers prefer using map, filter, &c. directly; doing so, it would look like this instead:</p>\n\n<pre><code>availableHeaps b = map fst . filter ((> 0) . snd) $ indexedHeaps b\n</code></pre>\n\n<p>But I think the list comprehension is clearer in this case.</p>\n\n<pre><code>availableObjectsByHeap :: Board -> Heap -> Integer\navailableObjectsByHeap board heapId = board !! (fromInteger heapId - 1)\n</code></pre>\n\n<p>The <code>(!!)</code> function gives zero-based indexing into a list, so we adjust to account for heap numbers starting from 1. It takes an <code>Int</code> argument, as noted above. Using <code>(!!)</code>--or any sort of indexing into a list--continues to be less than ideal, and a sign that some other data structure should be used.</p>\n\n<p>I'll be correcting the spelling of \"prompt\" as I go, incidentally.</p>\n\n<p>Now, we could try the following to tidy up <code>promptInt</code>:</p>\n\n<pre><code>promptInt :: String -> (Integer -> Bool) -> IO Integer\npromptInt msg p = do \n putStr (msg ++ \"> \")\n x <- readLn -- Don't actually do this!\n if p x\n then return x \n else promptInt msg p\n</code></pre>\n\n<p>Unfortunately, this is a distinct <em>disimprovement</em>. Using <code>readLn</code> raises an exception when it can't parse the user input, which makes it needlessly awkward to use. Rather than messing with catching exceptions, we'll whip up a replacement using the <code>reads</code> function, which returns a list of possible parses, and use <code>Maybe</code> to indicate success vs. failure.</p>\n\n<pre><code>-- Why doesn't this exist in the Prelude?\nmaybeRead :: (Read a) => String -> Maybe a\nmaybeRead str = listToMaybe [x | (x, \"\") <- reads str]\n\nmaybeReadLn :: (Read a) => IO (Maybe a)\nmaybeReadLn = fmap maybeRead getLine\n</code></pre>\n\n<p>Now, we can fix <code>promptInt</code> correctly:</p>\n\n<pre><code>promptInt :: String -> (Integer -> Bool) -> IO Integer\npromptInt msg p = do \n putStr (msg ++ \"> \")\n mx <- maybeReadLn\n case mx of\n Just x | p x -> return x\n _ -> promptInt msg p\n</code></pre>\n\n<p>Using the standard <code>Read</code> instance instead of doing calculations with <code>ord</code> makes it easier to see what's going on here. The predicate has also been combined with the pattern match, so the default pattern handles both parse failures and invalid inputs.</p>\n\n<pre><code>promptIntFromRange :: String -> (Integer, Integer) -> IO Integer\npromptIntFromRange msg (from, to) = promptInt newMsg inRange \n where newMsg = concat [msg, \"[\", show from, \";\", show to, \"]\"]\n inRange v = v >= from && v <= to\n</code></pre>\n\n<p>It's more typical to have <code>where</code> begin a new line, in order to clearly distinguish a <code>where</code> clause from a multi-line expression. Using <code>concat</code> tends to be tidier than repeated <code>(++)</code>, and again improving a name--for an arbitrary predicate <code>p</code> makes sense, but here we have a specific predicate, and should indicate such.</p>\n\n<pre><code>promptIntFromSet :: String -> [Integer] -> IO Integer\npromptIntFromSet msg s = promptInt (msg ++ show s) (`elem` s)\n</code></pre>\n\n<p>This can all be done in-line, since the standard library already has a function for your predicate.</p>\n\n<pre><code>putAllStr :: [String] -> IO ()\nputAllStr xs = mapM_ putStrLn xs\n</code></pre>\n\n<p>You'll probably reinvent large sections of the standard library at various points while learning Haskell. Figuring out that you've done so is half the fun.</p>\n\n<pre><code>printBoard :: Board -> IO ()\nprintBoard board = putAllStr $ showHeaps board\n\nshowHeaps :: Board -> [String]\nshowHeaps board = map showIdxHeap (indexedHeaps board)\n\nshowIdxHeap :: (Heap, Integer) -> String\nshowIdxHeap (heapId, n) = heapIndex ++ objects\n where heapIndex = concat [\"[\", show heapId, \"]\"]\n objects = genericReplicate n '*'\n</code></pre>\n\n<p>As Paul Martel did, I've separated the string representation of the board from the printing. Note that <code>String</code> is simply <code>[Char]</code>, so replicating <code>'*'</code> suffices. The use of <code>genericReplicate</code> here is because of using <code>Integer</code> rather than <code>Int</code>.</p>\n\n<pre><code>play :: Board -> IO Board\nplay board | empty board = return []\n | otherwise = do printBoard board\n t <- readTurn board\n play $ applyTurn t board\n\nnim :: IO () \nnim = do play [1, 2, 3, 1]\n putStrLn \"done\"\n</code></pre>\n\n<p>There's no reason for <code>play</code> to take an <code>IO Board</code>, so I've removed the superfluous <code>return</code> and binding steps. This also allows using guards for the <code>empty</code> check, removing the conditional expression.</p>\n\n<hr>\n\n<p>Ok. With that out of the way, time to revisit the earlier remarks about data structures. Lists in Haskell are sequential in nature, so indexing into them or replacing a single element is clumsy and inefficient at best. We'd like something more suitable here, and a good default choice is the <code>Data.Map</code> module. </p>\n\n<pre><code>import qualified Data.Map as Map\n\ntype HeapId = Integer\ntype Turn = (HeapId, Integer)\ntype Board = Map.Map HeapId Integer\n</code></pre>\n\n<p>The module is imported qualified to avoid name clashes with various list functions. I've also renamed <code>Heap</code> to <code>HeapId</code> to be more explicit about what it represents.</p>\n\n<pre><code>applyTurn :: Turn -> Board -> Board\napplyTurn (heapId, removed) board = Map.adjust (subtract removed) heapId board\n\nempty :: Board -> Bool\nempty b = Map.null $ availableHeaps b\n\navailableHeaps :: Board -> Board\navailableHeaps b = Map.filter (> 0) b\n</code></pre>\n\n<p>Converting the game state functions to use <code>Data.Map</code>. They're much simpler this way, and some functions I've eliminated entirely.</p>\n\n<pre><code>nim :: IO () \nnim = do play $ Map.fromList (zip [1..] [1, 2, 3, 1])\n putStrLn \"done\"\n</code></pre>\n\n<p>Initializing the game doesn't need to change much, but note the construction using <code>Map.fromList</code>, assigning specific keys to each heap by counting from 1.</p>\n\n<pre><code>promptHeapSize :: String -> Board -> IO (HeapId, Integer)\npromptHeapSize msg board = do \n heapId <- promptInt msg' (`Map.member` board)\n case Map.lookup heapId board of\n Nothing -> promptHeapSize msg board\n Just sz -> return (heapId, sz)\n where msg' = msg ++ show (Map.keys board)\n</code></pre>\n\n<p>Here I've replaced <code>promptIntFromSet</code> with a smarter function that makes sure the requested heap number is valid, and returns the number of objects as well.</p>\n\n<pre><code>readTurn :: Board -> IO Turn\nreadTurn b = do \n (heapId, heapSz) <- promptHeapSize \"heap\" b\n objects <- promptIntFromRange \"number\" (1, heapSz)\n return (heapId, objects)\n\nshowHeaps :: Board -> [String]\nshowHeaps board = map showIdxHeap (Map.assocs board)\n</code></pre>\n\n<p>Only a couple very minor changes here.</p>\n\n<pre><code>runNextTurn :: Board -> IO Board\nrunNextTurn b = do \n printBoard board\n t <- readTurn board\n play $ applyTurn t board\n\nplay :: Board -> IO Board\nplay board | empty board = return board\n | otherwise = runNextTurn board >>= play\n</code></pre>\n\n<p>I split <code>play</code> into two functions--one that does a single turn, and one that loops until the game is done. This doesn't really change anything, but makes it easier if you want to have more complicated interaction than the same loop every time.</p>\n\n<p>The complete program using <code>Data.Map</code>, along with some other minor changes I made along the way, <a href=\"https://gist.github.com/1588045\">can be found here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T09:59:54.507",
"Id": "11985",
"Score": "1",
"body": "Thanks a lot for so detailed review. It's shows places where I don't know syntax/standard library. So I can go further. Also it's good diff between my and professional Haskell code. I believe this comment will make from me much better programmer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T00:54:18.163",
"Id": "13987",
"Score": "1",
"body": "Wow, that's an excellent code review! I'm only wondering why, in the second part of your answer, haven't you decided to write `empty` and `availableHeaps` in a pointfree form? Arguably it would render the functions even easier to read: `availableHeaps = Map.filter (> 0)` and `empty = Map.null . availableHeaps`, or even: `empty = Map.null . Map.filter (> 0)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-13T01:27:06.807",
"Id": "13989",
"Score": "0",
"body": "@Bolo: Mostly hypercorrection for my usual coding style, which heavily uses pointless forms. I try not to inflict that on people new to the language. ;] But yes, I agree, in those two cases the point-free way is probably better in general."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T09:25:54.300",
"Id": "7636",
"ParentId": "7623",
"Score": "10"
}
},
{
"body": "<p>Here's a simpler way to write the list-based <em>availableHeaps</em>, using <em>findIndices</em> from Data.List:</p>\n\n<pre><code>availableHeaps' :: Board -> [Heap]\navailableHeaps' = findIndices (> 0)\n</code></pre>\n\n<p>Of course the Map version by McCann is more appropriate for the Nim data structure, but it's always good to become familiar with the standard list functions too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T18:00:10.493",
"Id": "11998",
"Score": "0",
"body": "Thanks for the point. It's always good to be familiar with standard API)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T17:16:17.890",
"Id": "7642",
"ParentId": "7623",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7636",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-09T10:24:39.313",
"Id": "7623",
"Score": "9",
"Tags": [
"haskell",
"game"
],
"Title": "Nim Game in Haskell"
}
|
7623
|
<p>I'm trying to compare my own implementation with another solution of <a href="http://projecteuler.net/problem=1" rel="nofollow">Project Euler problem #1</a>, which uses a list comprehension:</p>
<pre><code>module Progression1 (sumProgressions) where
import Prelude
sumProgressions :: Integer -> Integer -> Integer -> Integer
sumProgressions d1 d2 limit =
sum [n | n <- [1 .. limit], (n `mod` d1) == 0 || (n `mod` d2) == 0]
</code></pre>
<p>Mine is directly inspired by user nicocarlos' PHP solution on the PE site. It avoids using hard-coded constants, instead computing most of the values (with as much algebraic simplification as possible):</p>
<pre><code>module Progression2 (sumProgressions2) where
aN :: Integer -> Integer -> Integer -> Integer
pSum :: Integer -> Integer -> Integer -> Integer
sumProgressions2 :: Integer -> Integer -> Integer -> Integer
aN a1 d n = a1 + (n - 1) * d -- Calculating the value of the Nth term
pSum 0 d lim = pSum d d lim -- a1 == 0 produces invalid pSum() result
pSum a1 d lim =
let n1 = (lim `div` d) -- Using simplified method for finding n
n2 = ((lim - a1) `div` d + 1) -- Use non-simplified formula for calculation
in if (a1 == d)
then (d * n1 * (n1 + 1)) `div` 2 -- Assumes n1 is simplified
else (n2 `div` 2) * (a1 + aN a1 d n2) -- Non-simplified calculation
sumProgressions2 d1 d2 lim = let d3 = d1 * d2
in (pSum d1 d1 lim) + (pSum d2 d2 lim) - (pSum d3 d3 lim)
</code></pre>
<p>I'm new to Haskell and inexperienced with functional programming; I'd like suggestions for improving this code's performance and style. </p>
<p>Currently <a href="http://hackage.haskell.org/package/criterion" rel="nofollow">criterion</a> is showing <a href="http://pastebin.com/TzthfrXt" rel="nofollow">similar mean benchmark times</a> for each solution, calculated for <code>d1 = 3</code>, <code>d2 = 5</code>, <code>limit = 100000-1</code>. </p>
<hr>
<h2>Updated with current code:</h2>
<p>This solves the bug mentioned in the accepted answer, and takes much of its advice on style (as well as discarding the simplified algebra.)</p>
<pre><code>-- Using arithmetic progression formula for the Nth element aN, we can determine
-- the value aN = a1 + (N - 1) * d. Rearranging yields N = (aN - a1) / d + 1.
-- Calculates N, then the last aN, and uses it to find S = (N / 2) * (start + last)
pSum 0 diff limit = pSum diff diff limit
pSum start diff limit = truncate ((fromIntegral n / 2) * fromIntegral(start + last))
where n = (limit - start) `div` diff + 1
last = start + (n - 1) * diff
-- Add the sums of two progressions and subtract sum of similar elements
sumProgressions2 :: Integer -> Integer -> Integer -> Integer
sumProgressions2 diff1 diff2 limit =
(pSum 0 diff1 limit) + (pSum 0 diff2 limit) - (pSum 0 diff3 limit)
where diff3 = lcm diff1 diff2
</code></pre>
|
[] |
[
{
"body": "<p>I'll leave the question open, but here are some other attempts. Credit goes to <a href=\"https://stackoverflow.com/users/46642/r-martinho-fernandes\">RMartinhoFernandes</a> for <code>solution3</code>, which requires his <a href=\"http://hg.tumtumtree.me/pointfree/src\" rel=\"nofollow noreferrer\">Pointfree module</a> for the <code>/\\</code> combinator.</p>\n\n<pre><code>sumProgressions3 :: Integer -> Integer\nsumProgressions3 limit = solve [1 .. limit]\nmultipleOf n = (== 0) . (`mod` n)\nmultipleOf3Or5 = uncurry (||) . ((multipleOf 3) /\\ (multipleOf 5))\nsolve = sum . filter multipleOf3Or5\n</code></pre>\n\n<p>And <code>solution4</code> is a completely in-lined version of the simplified formula in my question:</p>\n\n<pre><code>sumProgressions4 :: Integer -> Integer -> Integer -> Integer\nsumProgressions4 d1 d2 lim = let d3 = d1 * d2\n in d1 * (lim `div` d1) * (1 + (lim `div` d1)) `div` 2 \n + d2 * (lim `div` d2) * (1 + (lim `div` d2)) `div` 2 \n - d3 * (lim `div` d3) * (1 + (lim `div` d3)) `div` 2\n</code></pre>\n\n<p>I've <a href=\"http://pastebin.com/duVFXV6n\" rel=\"nofollow noreferrer\">repeated the benchmarks</a> on my machine with the same parameters as above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T01:12:47.223",
"Id": "12704",
"Score": "1",
"body": "You can use `(&&&)` from `Control.Arrow` instead of `(/\\)`. Also, pointful version is much nicer in this case."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T05:45:42.447",
"Id": "7632",
"ParentId": "7629",
"Score": "3"
}
},
{
"body": "<h2>Correctness:</h2>\n\n<p>Many reviewers will not bother to comment on code that is not correct. \nI might have kept this brief, myself, except that it was only in the process of considering optimization that I discovered that this code contains two bugs that prevent correct answers. </p>\n\n<p>It shares one of those bugs with the simpler sumProgressions. The benefit of the simplicity of sumProgressions is that the bug has fewer places to hide there.\nHint: Why does sumProgressions 3 5 1000 give the same answer as sumProgressions 3 5 1001?</p>\n\n<p>Nothing about this bug changes my comments below about style or optimization, so I might have pointed it out and moved on, even if I had caught it up front.</p>\n\n<p>The more serious bug is unique to sumProgressions2. \nHint: Why does sumProgressions 3 6 20 give a different answer from sumProgressions2 3 6 20?</p>\n\n<p>If I had noticed this earlier, my answer might have ended here.</p>\n\n<p>But it seemed a shame to throw the rest of this away, so, (mostly) ignoring the cases in which the code fails...</p>\n\n<h2>Style:</h2>\n\n<p>I don't see the benefit to the function type declarations all at the top separated from their implementations where they could have had some minor self-documentation effect. </p>\n\n<p>You seem to be following the Haskell tradition of using one-letter symbols and minimal explanatory comments, as if it was obvious from the context that a1 is the first element of a progression and d is its delta and n is the number of elements. To me, these things were not all obvious, especially when n is either n1 or n2 and the '1' in n1 has nothing to do with the '1' in a1. I think that n' and n would have been a more idiomatic naming than n1 and n2, since they are variants of each other. Function header comments describing the input arguments would not have been out of place, nor would spelling out \"delta\" and \"limit\", but that may be an \"m o\" (meaning \"minority opinion\" -- obviously).</p>\n\n<p>The formulas used in pSum are sufficiently complicated and their syntax not quite algebraic, so their intent is obscured. A comment explaining the intent in plain language like \"multiplying ... first and last elements...\" or pure algebra would help.</p>\n\n<p>Since both aN and pSum are short and used only within pSum and sumProgressions2, respectively, I'd have opted for defining them under a where clause. In the case of pSum, that allows lim to be referenced in the parent scope so it doesn't need to be explicitly passed. This makes the structure of the code more readable, making it clear that aN and pSum serve sumProgressions2 and sumProgressions2 only. I'm guessing (mostly from the presence of a1) that this may not have been your intent, in which case you should have made that intent clear by exporting these functions or showing other uses within the module.</p>\n\n<p>In fact, the purpose of a1 is confounded by the fact that a1 is only ever passed the same value as d by the 3 callers of pSum, and since pSum isn't exported from the module, those seem to be the only cases. From that perspective, a1 is only used once, in an equality test that always passes, so it seems that you could eliminate it and with it half the complexity of pSum. </p>\n\n<p>Even if your intent is to provide pSum as a useful function outside of sumProgressions2, the usage of pSum in sumProgressions2 is so specialized and falls so cleanly into the \"simplified\" case that it still warrants its own separate truly simplified pSum function that takes no a1 argument.</p>\n\n<p>Whether the existence of another more general pSum implementation is justified and whether its a1 == d case is worth optimizing -- or (as I suspect) similar simplification applies equally to the general case -- is outside the scope of the current problem.</p>\n\n<p>Yet I think that there is a point to be made here about over-generalization.\nYou could argue that you are doing a good thing by providing and using a more general solution that does not require a1 to equal d, but I don't think that argument holds up. It sounds like the same argument that justifies writing sumProgressions2 as a general solution that does not depend on the values 3, 5, and 1000. But consider the following:</p>\n\n<pre><code>sumProgressions3_5_1000 3 5 1000 = correctAnswerForEuler1\nsumProgressions3_5_1000 d1 d2 lim = let d3 = d1 * d2\n in (pSum d1 d1 lim) + (pSum d2 d2 lim) - (pSum d3 d3 lim)\n</code></pre>\n\n<p>or even</p>\n\n<pre><code>sumProgressions3 3 d2 lim = specialCaseOptimizedFor3 d2 lim\nsumProgressions3 d1 d2 lim = let d3 = d1 * d2\n in (pSum d1 d1 lim) + (pSum d2 d2 lim) - (pSum d3 d3 lim)\n</code></pre>\n\n<p>Do you consider these to have the same benefits of generality as your original solution?\nTo me, <code>if (a1==d)</code> in pSum defeats the purpose of the generalized solution just as much as this last example does. Your pSum just hard-codes for an arbitrary argument relationship rather than for an arbitrary argument value, but it's still arbitrary hard-coding for an arbitrary case.</p>\n\n<p>There is danger in over-generalization. Testing and correctness is more difficult for a general function than for a more constrained or hard-coded function. Case in point, the bug triggered by arguments 3 6 20 does not effect cases like 3 5 1000. Also, optimization may be completely different when targeting all cases vs. average or typical cases vs. the special case that is going to be exercised in the benchmark. Case in point, it was only in considering an optimization that would benefit cases like 3 6 20 while slightly penalizing cases like 3 5 1000 that I discovered that I wasn't really optimizing this new case at all -- I was correcting it. And given the context/contest, I wasn't sure that optimizing or correcting the 3 6 20 case was really \"in scope\". I decided that what was in scope was a style critique along the lines of:</p>\n\n<blockquote>\n <p>The good work of substituting code that works in many general cases for code that only needs to handle a specific case may not be worthwhile unless the code is correct for the general case or guards against the cases it does not handle correctly. </p>\n</blockquote>\n\n<p>You've got a good solution to the problem of sumProgressions2 3 5 1000 disguised as a faulty solution to the problem of sumProgressions2 d1 d2 limit. So, technically, you'd be in better shape if you had been less ambitious.</p>\n\n<h2>Optimization:</h2>\n\n<p>There's not much to say here, except that the correction for the 3 6 20 case (arguably out of scope and counter-productive to the optimization of the 3 5 1000 solution) was originally mis-identified as a missing optimization. As it turns out, there seem to be multiple edge cases that require either more processing or less processing than 3 5 1000.</p>\n\n<p>Eliminating a1 from pSum would help to focus the effort on the calculation of n1 and its use rather than on dead code.\nAs far as I can see, there's no better formulation -- no reason to prefer <code>(n*n+n)</code> over <code>n*(n+1)</code> or to prefer <code>(lim - (lim `mod` d))*(n+1)</code> over <code>d*(lim `div` d)*(n+1)</code>, given that <code>n+1</code> requires <code>(lim `div` d)</code> to be calculated in either case. But I could be wrong, and easily proven wrong by some quick benchmarks. So, your solution seems optimal within the current structure of sumProgressions2 as 3 calls to pSum.</p>\n\n<p>The only other way I could see to further optimize the code would be IF there was an alternative way of expressing the third call to pSum so that it eliminated some operations in favor of re-using sub-expressions from the first two pSum calls. I don't know if this is possible. What I'm imagining is something like a reformulation of the pSum functions, especially the one used in the 3rd call, that took advantage of a fact like <code>(d1*d2)*(d1*d2) == (d1*d1)*(d2*d2)</code> (assuming that result to be useful) to reuse <code>(d1*d1)</code> and <code>(d2*d2)</code> values calculated already in the first two (reformulated) pSum calls. I don't know enough about Haskell internal optimizations to know if it can access function results \"recently memoized\" in called \"sibling\" functions. If not, I'd guess you would pass the useful sub-expressions like (d1*d1) from sumProgressions2 into the pSum calls. This whole idea could turn out to be too ugly for serious consideration, so you might be better off where you are.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:47:01.827",
"Id": "12211",
"Score": "1",
"body": "+1 just because you obviously took a LONG time to provide a thorough answer (hope that doesn't make me a bad netizen)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T18:44:40.680",
"Id": "7644",
"ParentId": "7629",
"Score": "10"
}
},
{
"body": "<p>The solutions posted so far seem a bit overcomplicated to me, so I thought I'd share my solution:</p>\n\n<pre><code>sum_of_first_n_numbers n = n * (n + 1) `div` 2\n\nsum_of_multiples max factor = sum_of_first_n_numbers (max `div` factor) * factor\n\nsolution = sum_of_multiples 999 3 + sum_of_multiples 999 5 - sum_of_multiples 999 15\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T03:51:54.807",
"Id": "12225",
"Score": "2",
"body": "+1 for \"so far ... overcomplicated\" and a clean solution, tho' just a little terse for my taste -- 999 and 15 appear out of nowhere to save the day -- it makes for a great happy ending, but it's not a very reassuring story."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T23:22:52.587",
"Id": "7729",
"ParentId": "7629",
"Score": "3"
}
},
{
"body": "<p>I know this isn't code golf, but may I point out that you don't need fancy operators to express <code>(mod x 3 == 0) && (mod x 5 == 0)</code>:</p>\n\n<pre><code>sum $ filter ((>1).(`gcd` 15)) [1..999]\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-30T20:20:15.857",
"Id": "8466",
"ParentId": "7629",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7644",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T02:05:13.633",
"Id": "7629",
"Score": "7",
"Tags": [
"performance",
"beginner",
"haskell",
"functional-programming",
"programming-challenge"
],
"Title": "Finding the sum of all the multiples of 3 or 5 below 1000, using list comprehension"
}
|
7629
|
<p>Usually, people would create two extra-threads in order to read the standard output and error respectively. However, the following code would allow to handle a Process outputs without those threads (it is arguably a little bit more difficult to decode the characters if you are using something else than a single-byte encoding and if you can't buffer the output in memory).</p>
<p>Although the following code seems to work, it is different enough from the "standard" solution, that I'm wondering if anyone can find am issue with it.</p>
<pre><code>public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(args);
Process process = processBuilder.start();
InputStream outputStream = null, errorStream = null;
ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream();
try {
outputStream = process.getInputStream();
errorStream = process.getErrorStream();
byte[] tmp = new byte[1024];
while (true) {
int outputBytes = readAvailablOnce(outputStream, outputBuffer, tmp);
int errorBytes = readAvailablOnce(errorStream, errorBuffer, tmp);
if (outputBytes == 0 && errorBytes == 0) {
try {
process.exitValue();
break;
} catch (IllegalThreadStateException e) {
// keep on looping
}
}
}
readAvailableAll(outputStream, outputBuffer, tmp);
readAvailableAll(errorStream, errorBuffer, tmp);
} finally {
closeQuietly(outputStream);
closeQuietly(errorStream);
}
System.out.println(outputBuffer.toString("ASCII"));
System.err.println(errorBuffer.toString("ASCII"));
System.err.println("exit code: " + process.exitValue());
}
private static void closeQuietly(InputStream in) {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// ignored
}
}
}
private static int readAvailablOnce(
InputStream inputStream, OutputStream outputStream, byte[] buffer)
throws IOException {
int bytesRead = 0;
if (inputStream.available() > 0) {
bytesRead = inputStream.read(buffer);
outputStream.write(buffer, 0, bytesRead);
}
return bytesRead;
}
private static void readAvailableAll(
InputStream inputStream, OutputStream outputStream, byte[] buffer)
throws IOException {
if (inputStream.available() > 0) {
int bytesRead = 0;
while ((bytesRead = inputStream.read(buffer)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Is <code>inputStream.available()</code> a blocking method?</p>\n\n<p>The process might send an error message while your are blocked (possibly forever) in the standard output <code>available()</code> waiting for something that will never arrive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T02:30:31.273",
"Id": "12426",
"Score": "2",
"body": "Although it is not explicitly stated by the Javadoc `InputStream.available()` has to be non-blocking (and is, in practice) otherwise its purpose would be rather thin: \"returns the number of bytes that can be read from this input stream without blocking\"."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T16:40:59.740",
"Id": "7844",
"ParentId": "7631",
"Score": "4"
}
},
{
"body": "<p>I've found nothing too, but it looks little bit weird. Anyway, some notes:</p>\n\n<ol>\n<li><p>You shouldn't define two variables at the same line:</p>\n\n<pre><code>InputStream outputStream = null, errorStream = null;\n</code></pre>\n\n<p>It's hard to read and find the declaration if you need that.</p></li>\n<li><p>Apache Commons IO also has <a href=\"http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#closeQuietly%28java.io.InputStream%29\" rel=\"nofollow\"><code>closeQuietly</code></a> too.</p></li>\n<li><p>I'd create a separate <code>byte[] tmp</code> array for every method (inside the <code>readAvailablOnce</code> and <code>readAvailableAll</code> methods). Passing the same buffer array to every method looks premature optimization (which is usually bad).</p>\n\n<pre><code>private static int readAvailablOnce(final InputStream inputStream, \n final OutputStream outputStream) throws IOException {\n final byte[] buffer = new byte[1024];\n ...\n}\n...\n</code></pre></li>\n<li><p>Instead of the <code>readAvailableAll</code> you could use the <a href=\"http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#copyLarge%28java.io.InputStream,%20java.io.OutputStream%29\" rel=\"nofollow\"><code>IOUtils.copy</code></a>. It does the same.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T07:20:39.717",
"Id": "12591",
"Score": "0",
"body": "Thanks!\n\n2. Agreed. I didn't use IOUtils for the clarity of my example (I use it in my actual code).\n3. Reuse of a buffer to avoid unnecessary and repetitive (we are in a loop) memory allocations is not at all premature. Not making things more readable though. Also, it could be argued that smart JIT + GC could do as well (I wonder...).\n4. Agreed (with same remark about buffer reuse). The test of isAvailable() is kinda extra here as we can assume that because the process ended, the outputs are readily available (i.e. the OS is not waiting to fetch more contents in either)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T23:58:02.573",
"Id": "7876",
"ParentId": "7631",
"Score": "2"
}
},
{
"body": "<p>I'm concerned that you have implemented a very tight loop which will execute very quickly and place very high load on the system until the executing process terminates. This could be a big problem if this is being used to wait for a long running process to complete. The JVM will attempt to repeat those instructions within the <code>while(true)</code> loop as fast as it can.</p>\n\n<p>Have you run this code and observed any load issues. Try executing a simple batch script which just does a <code>sleep 60</code>. I've not executed this code, just what I'd expect from looking at it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T02:14:08.277",
"Id": "49113",
"ParentId": "7631",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7844",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T02:46:24.593",
"Id": "7631",
"Score": "11",
"Tags": [
"java",
"io"
],
"Title": "Handle Java Process outputs without extra-threads"
}
|
7631
|
<p>I have started to reading up on electronics and embedded software. Lately I have been looking at IC's, particularly shift registers. I thought a good way of learning more about serial communication and shift registers was to implement the internal logic of a shift register. </p>
<p>The one I have chosen is the <a href="http://www.electrokit.com/productFile/download/1526" rel="nofollow">74HC595</a>. </p>
<p>I have done this so that it will be similar to working with setting different CPU pins to HIGH or LOW. Imagine that each of the functions manipulating the IC is the value of a CPU pin connected to the IC. </p>
<p>Of course this can be simplified by a easy to use wrapper, so you could just call a function saying which pin to set to LOW or HIGH on the register. But that's not the main point.</p>
<p><strong>ic_example.c:</strong></p>
<pre><code>#include <stdio.h>
#include "../src/ic/ic_74hc595.h"
int main()
{
struct ic_74hc595 ic = {0, 0, LOW, LOW, LOW};
/* Initial value check. Should be 0 */
printf("ic value: %u\n", ic.value);
/* Set the first bit to 1. */
ic_set_stcp(&ic, HIGH);
ic_set_ds(&ic, HIGH);
ic_set_stcp(&ic, LOW);
printf("ic value: %u\n", ic.value);
/* Iterate to third bit */
ic_set_shcp(&ic, HIGH);
ic_set_shcp(&ic, LOW);
ic_set_shcp(&ic, HIGH);
ic_set_shcp(&ic, LOW);
/* Set it to 1 */
ic_set_stcp(&ic, HIGH);
ic_set_ds(&ic, HIGH);
ic_set_stcp(&ic, LOW);
printf("ic value: %u\n", ic.value);
/* Iterate to last bit */
ic_set_shcp(&ic, HIGH);
ic_set_shcp(&ic, LOW);
ic_set_shcp(&ic, HIGH);
ic_set_shcp(&ic, LOW);
ic_set_shcp(&ic, HIGH);
ic_set_shcp(&ic, LOW);
ic_set_shcp(&ic, HIGH);
ic_set_shcp(&ic, LOW);
ic_set_shcp(&ic, HIGH);
ic_set_shcp(&ic, LOW);
/* Set it to 1 */
ic_set_stcp(&ic, HIGH);
ic_set_ds(&ic, HIGH);
ic_set_stcp(&ic, LOW);
printf("ic value: %u\n", ic.value);
/* Reset */
ic_set_mr(&ic, LOW);
printf("ic value %u\n", ic.value);
return 0;
}
</code></pre>
<p><strong>ic_74hc595.h:</strong></p>
<pre><code>#ifndef IC_74HC595_H_
#define IC_74HC595_H_
#include <stdint.h>
#define HIGH 1
#define LOW 0
typedef _Bool bit;
/**
* The 74HC595 ic's internal state representation.
*
* value - The 8-bit value which represents the paralell out data
* i - The current bit which is iterated to
* shcp - The shift clock input, which is used to iterate the 8 bits. Each time it switches from LOW (0) to HIGH (1) it iterates one bit.
* stcp - The register clock input, which is used to tell the register to accept data. LOW (0) means it doesn't accept data, HIGH (1) means it does accept data.
* ds - Serial data, which is used to tell which value the current bit should have; LOW (0) or HIGH (1).
*/
struct ic_74hc595{
uint8_t value;
uint8_t i;
bit shcp;
bit stcp;
bit ds;
};
void ic_set_shcp(struct ic_74hc595 *ic, bit shcp);
void ic_set_stcp(struct ic_74hc595 *ic, bit stcp);
void ic_set_ds(struct ic_74hc595 *ic, bit ds);
void ic_set_mr(struct ic_74hc595 *ic, bit mr);
#endif
</code></pre>
<p><strong>ic_74hc959.c:</strong></p>
<pre><code>#include "ic_74hc595.h"
/**
* Changes the shcp clock to the given value
*
* @param ic
* The ic to change state and value of
*
* @param shcp
* The shift clock input
*/
void ic_set_shcp(struct ic_74hc595 *ic, bit shcp)
{
if (ic->shcp == LOW && shcp == HIGH) {
ic->shcp = HIGH;
ic->i++;
}else if (ic->shcp == HIGH && shcp == LOW){
ic->shcp = LOW;
}
}
/**
* Changes the stcp clock to the given value
*
* @param ic
* The ic to change state and value of
*
* @param stcp
* The register clock input
*/
void ic_set_stcp(struct ic_74hc595 *ic, bit stcp)
{
if (ic->stcp != stcp) {
ic->stcp = stcp;
}
}
/**
* Gives the current bit a new value if stcp is HIGH.
*
* @param ic
* The ic to change state and value of
*
* @param ds
* The data input
*/
void ic_set_ds(struct ic_74hc595 *ic, bit ds)
{
if (ic->ds != ds) {
ic->ds = ds;
}
if (ic->stcp == LOW) {
return;
}
ic->value |= (ds << ic->i);
}
/**
* Resets the internal state if mr is LOW.
*
* @param ic
* The ic to change state and value of
*
* @param mr
* The master reset value
*/
void ic_set_mr(struct ic_74hc595 *ic, bit mr)
{
if (mr == LOW) {
ic->value = 0;
ic->i = 0;
ic->shcp = LOW;
ic->stcp = LOW;
ic->ds = LOW;
}
}
</code></pre>
<p><strong>Compilation command is used:</strong> </p>
<pre><code>gcc ./examples/ic_simulator.c ./src/ic/ic_74hc595.c -o ic_simulator -Wall -pedantic
</code></pre>
<p>What I would like feedback on: </p>
<ul>
<li>The implementation of the IC's logic. Is it correct?</li>
<li>The state of my code. Is it readable? Am I implementing the bit type the right way? Etc.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T15:57:24.190",
"Id": "11993",
"Score": "1",
"body": "Pretty general question but is :\nvoid setVal (Object foo, Value bar) { if (foo->value != bar) foo->value = bar; }\nreally better than :\nvoid setVal (Object foo, Value bar) { foo->value = bar; }\n? I don't see any real point in your case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T16:36:49.063",
"Id": "11994",
"Score": "0",
"body": "You are totally right. I missed it when refactoring from another solution I had from the beginning. Setting the value straight away instead will also produce less inustructions, thus be faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T17:49:09.943",
"Id": "11997",
"Score": "0",
"body": "Also, you can make the logic of ic_set_shcp simpler :\nif (ic->shcp != shcp){\n ic->shcp = shcp;\n if (shcp == HIGH) {ic->i++;}\n}\nBut I'm not sure it's its worth adding an answer for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-03T09:37:19.187",
"Id": "195014",
"Score": "0",
"body": "\"CPU pins\"? You mean pins on the shift-register package?"
}
] |
[
{
"body": "<p>OK. Looking at this as a code maintainer and not understanding what the underlying logic of the chip does (which is what will happen in real life).</p>\n\n<p>The function names look a bit generic.<br>\nYou may want to prefix them with the name of the chip (C unlink C++ does not provide function overloading). So that you can provide similar functions to a set of chips.</p>\n\n<p>From reading the docs this looks good (though I must admit I am not 100% sure).<br>\nBut a general maintainer is going to look and wonder why half the code paths do nothing. </p>\n\n<pre><code>void ic_set_shcp(struct ic_74hc595 *ic, bit shcp)\n{\n if (ic->shcp == LOW && shcp == HIGH) {\n ic->shcp = HIGH;\n ic->i++;\n }else if (ic->shcp == HIGH && shcp == LOW){\n ic->shcp = LOW;\n }\n}\n</code></pre>\n\n<p>So I think the function deserves more documentation (especially why the non state change if <code>ic->shcp == shcp</code>).</p>\n\n<p>Can the next function just not be simplified (I may be missing something in which case a comment):</p>\n\n<pre><code>void ic_set_stcp(struct ic_74hc595 *ic, bit stcp)\n{\n if (ic->stcp != stcp) {\n ic->stcp = stcp;\n }\n}\n</code></pre>\n\n<p>Is this not the same as:</p>\n\n<pre><code>void ic_set_stcp(struct ic_74hc595 *ic, bit stcp)\n{\n ic->stcp = stcp;\n}\n</code></pre>\n\n<p>OK Reading the function table (page 3) in the linked document:<br>\n<code>FUNCTION TABLE See note 1.</code></p>\n\n<p>I see a set of input and a set of outputs. I also see that the outputs depend on a change in the state of the inputs. As a result I would expect my the functions to mirror this table (maybe this is a bit low level?).</p>\n\n<p>Thus I would have expected an interface like this:</p>\n\n<pre><code> typedef enum { Low, NoCharge, High, HighImpedence} PinState; \n typedef enum { Q0, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q7Dash} OutputPinID;\n struct ic_74hc595 { /* Internal definition */ };\n\n /*\n * The return value of ic_74hc595_change_inputs() returns an encoded form of the\n * output pins. You can use ic_74hc595_decodeOutputValue() on this returned value\n * to decode individual pins.\n */\n void ic_74hc595_power_up(ic_74hc595* ic);\n int ic_74hc595_change_inputs(ic_74hc595* ic,\n PinState SH_CP, PinState ST_CP, \n PinState OE, PinState MR, PinState DS);\n PinState ic_74hc595_decodeOutputValue(int QSlots, OutputPinID pin);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T20:15:29.220",
"Id": "7649",
"ParentId": "7638",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7649",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T12:22:34.020",
"Id": "7638",
"Score": "4",
"Tags": [
"c"
],
"Title": "74HC595 IC software implementation"
}
|
7638
|
<pre><code>mysql> select count(username) from users where no_tweets > 50;
+-----------------+
| count(username) |
+-----------------+
| 282366 |
+-----------------+
1 row in set (5.41 sec)
mysql> select sum(no_tweets) from users where no_tweets > 50;
+----------------+
| sum(no_tweets) |
+----------------+
| 38569853 |
+----------------+
1 row in set (1.75 sec)
</code></pre>
<p>I have that many users, who have collectively tweeted that many tweets. My aim is to store them in a file and then find out what a user generally tweets about (for starters, my aim is to run vanilla LDA and see if it works well on short documents), but the problem is that I ran the python code like an hour back and it has still not finished even 2% of users. I have posted the python code below.</p>
<pre><code>'''
The plan is : Find out all users from the users database who have more than 50 tweets
Create a file for them in the directory passed as an argument with the same name as the username and write all the tweets in them
'''
def fifty(cursor):
''' Find all users and return , all of them having more than 50 tweets'''
cursor.execute("select username from users where no_tweets>50")
return cursor.fetchall()
def connect():
''' Cursor for mySQLdb'''
conn = MySQLdb.connect(host="localhost",user="rohit",passwd="passwd",db="Twitter")
return conn.cursor()
def tweets(cursor,name):
''' All tweets by a given user'''
cursor.execute("select tweets from tweets where username='"+name+"'")
return cursor.fetchall()
import sys,os,MySQLdb
directory = sys.argv[1] #Directory to write the user files
cursor = connect()
rows = fifty(cursor) #Find all users who have more than 50 tweets
for i in rows:#For all users
data = open(os.path.join(directory,i[0]),'w') #Open a file same as their name
allTweets = tweets(cursor,i[0]) #Find all tweets by them
for j in allTweets:
data.write(j[0]+"\n") #Write them
data.close()
</code></pre>
<p>The problem is that the code is running too slow and at this rate, it will take more than a day for it to finish writing all files. So some way that would make it faster would be great. So yeah, that is the question.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:32:13.970",
"Id": "12004",
"Score": "1",
"body": "And your question is...?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:34:56.443",
"Id": "12005",
"Score": "0",
"body": "Did not realize that I had not put the question in there . Apologies. Made the necessary changes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:36:03.217",
"Id": "12006",
"Score": "0",
"body": "This really isn't a \"just go and fix my code for me\" place. If you just want someone to go do the work for you you should hire a dev."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:38:18.673",
"Id": "12007",
"Score": "2",
"body": "If I had written no code at all and asked for help from someone to literally write the code , that would have made sense. I thought SO is a place where mistakes by people who are learning , like me, are corrected by those who can correct them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:38:18.877",
"Id": "12008",
"Score": "0",
"body": "My gut feeling is that performance is slow due to I/O. That can't be avoided, but perhaps you could look into the [subprocess](http://docs.python.org/library/subprocess.html) module."
}
] |
[
{
"body": "<p>You want better performance? </p>\n\n<p>if you want really better performance you should try to use some of the compiled code languages (like C). Because interpreted language takes much more time.</p>\n\n<p>For example, if you take a simple loop, you will notice the difference</p>\n\n<p>int i = 0;\nint j = 0;</p>\n\n<pre><code>for(i = 0; i < 1500000; i++){\n for(j = 0; j < 10000; j++){\n\n }\n}\n</code></pre>\n\n<p>It's like 50x faster with C comparing to Python.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:36:49.267",
"Id": "12009",
"Score": "4",
"body": "That won't help *at all*. The OP's post is I/O-bound, not CPU-bound. Changing the language won't change that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:38:43.960",
"Id": "12010",
"Score": "0",
"body": "Yes it does help, compiled language are much better to perform these tasks that takes a lot of time and computer consuming."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:39:24.740",
"Id": "12011",
"Score": "0",
"body": "There's only so many bits you can slam onto hardware at a time. No programming language can change that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:41:21.527",
"Id": "12012",
"Score": "0",
"body": "@Makoto -- often, there are tricks you can do to reduce the amount of work to be done. The expensive part of a query is often making the query itself: creating it, parsing it, optimizing it. The OP had a quarter-million unnecessary queries he can get rid of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:45:07.183",
"Id": "12013",
"Score": "1",
"body": "@Malvolio: Yes, the query is expensive, and that can be optimized. That still doesn't change the ~40 million tweets that are being written to disk on the basis of an individual's name. If we assume that each tweet is on average 80 characters long, then that's on the order of 6GB worth of data being written to disk."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:55:57.100",
"Id": "12019",
"Score": "0",
"body": "My laptop can save 6GB to disk in 15 seconds. It's not that."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:35:29.597",
"Id": "7646",
"ParentId": "7645",
"Score": "-3"
}
},
{
"body": "<p>Yikes, you're running almost 3,000,000 individual queries. If you could do 4 a second (and you probably cannot) that is <em>still</em> a day!</p>\n\n<p>How about just</p>\n\n<pre><code>select username, tweets from tweets order by username\n</code></pre>\n\n<p>Then of course you have to do some fancy footwork to switch from one file to the next when the user changes.</p>\n\n<p>It should only take a few hours to run.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:41:56.040",
"Id": "12015",
"Score": "0",
"body": "I guess I will have to make necessary change so that I select only those users who have more than 50 tweets in the other table ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:47:06.207",
"Id": "12016",
"Score": "0",
"body": "`select t.username, tweets from tweets t, (select username from tweets group by username having count(*) > 50) e where e.username = t.username order by t.username` -- but if you think *most* people have more than 50 (seems likely, since the average is 500), you might be better off just creating the files for everybody and deleting the small ones later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:55:41.203",
"Id": "12018",
"Score": "0",
"body": "I thought of the creating all files earlier. But , only 3% of users have more than 50 tweets ~ ( 282366 / 6161529 ). So had to chuck that. Thanks ! Thanks again !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T20:05:46.693",
"Id": "12022",
"Score": "0",
"body": "And I actually have two tables. One is (username,tweets) and other is (username,no_tweets) . I stored them separately as username would be a primary key in the 2nd table. Plus would help for future reference"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T20:15:15.463",
"Id": "12025",
"Score": "0",
"body": "mysql> select t.tweets tweets,u.username username from tweets t,users u where t.username=u.username and u.no_tweets > 50 order by t.username;\nIs this one correct ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T01:58:42.910",
"Id": "12032",
"Score": "0",
"body": "Looks good to me. Try it out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T05:39:34.517",
"Id": "12039",
"Score": "0",
"body": "When I ran it from cursor.execute , it gave an error :( Incorrect key for the table it seems :("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T05:41:26.293",
"Id": "12040",
"Score": "0",
"body": "And this happened after 4 hours of running, so I suspect something else went wrong altogether"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T09:32:26.177",
"Id": "12064",
"Score": "0",
"body": "Well, what was the error?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T09:59:22.673",
"Id": "12065",
"Score": "0",
"body": "The error was InternalError: (126, \"Incorrect key file for table '/var/tmp/mysql.ms5v75/#sql_6cd_1.MYI'; try to repair it\") <-- I think my root ran outta memory . I have asked MySQL to store everything on my /home directory , but , this query, I ran using IPython. So I think it was writing everything into that . Could that be the prob ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:14:31.167",
"Id": "12078",
"Score": "0",
"body": "[Out of file space](http://stackoverflow.com/questions/2090073/mysql-incorrect-key-file-for-tmp-table-when-making-multiple-joins). You can't be shocked about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T22:22:44.203",
"Id": "12137",
"Score": "0",
"body": "The weird part is that I have given /home/crazyabtliv/mysql as my defacto path. Then why did MySQLdb try and store things somewhere else :("
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:35:44.163",
"Id": "7647",
"ParentId": "7645",
"Score": "8"
}
},
{
"body": "<p>On the database side of things, make sure you have an index on the <code>username</code> field of the tweets table, if you don't MySQL will perform a full disk read on each query, taking minutes at a time (in a good scenario).</p>\n\n<p>If you're using a transactional database, using transactions (that is, closing them) is a good idea. Assuming python2.6 (or do an <code>from __future__ import with_statement</code> for 2.5), this is almost trivially easy.</p>\n\n<p>Also, the username in the where should be escaped so that unfortunate twitterhandles don't mess up your query, or your database:</p>\n\n<pre><code>import os\nimport operator\nimport sys\nimport MySQLdb\n\ndef Connect():\n return MySQLdb.connect(host='localhost', user='rohit', passwd='bloodline', db='Twitter')\n\ndef FiftyPlus(conn):\n with conn as cursor:\n cursor.execute('SELECT username FROM users WHERE no_tweets > 50')\n return map(operator.itemgetter(0), cursor.fetchall())\n\n\ndef Tweets(conn, name):\n with conn as cursor:\n cursor.execute('SELECT tweets FROM tweets WHERE username = %s', (name,))\n return map(operator.itemgetter(0), cursor.fetchall())\n\n\ndef WriteUserTweets(base_dir, username, tweets):\n with file(os.path.join(base_dir, username), 'w') as user_tweet_log:\n for tweet in tweets:\n user_tweet_log.write(tweet + '\\n')\n\n\ndef main():\n root_dir = sys.argv[1]\n conn = Connect()\n for user in FiftyPlus(conn):\n tweets = Tweets(conn, user)\n WriteUserTweets(root_dir, user, tweets)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:51:56.967",
"Id": "12017",
"Score": "0",
"body": "I have an index on username. Thanks ! I will need to dig up something on transactional databases :( Will do"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:59:36.983",
"Id": "12020",
"Score": "1",
"body": "Also, depending on your filesystem, you'll want to find a way to store the files in more than one directory. All flavors of ext (linux) and windows filesystems (and I've no reason to believe it'll be better on a Mac) start to give horrible performance once a directory accumulates over 50,000 files."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T20:04:12.780",
"Id": "12021",
"Score": "0",
"body": "Sigh . Okay :) Will do that then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T02:03:44.947",
"Id": "12033",
"Score": "0",
"body": "I rate that question 2-1-1. Two wins: proper handling of the username (although not required at all in my, ahem, superior solution, it's still a good idea in the abstract), and breaking up the files into subdirectories; one miss: username was already indexed; and one mistake: using a transaction in an *unchanging* database only slows things down."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:46:26.480",
"Id": "7648",
"ParentId": "7645",
"Score": "5"
}
},
{
"body": "<p>Am i missing something here or why don't you do it in one simple query and let MySQL write the file?</p>\n\n<pre><code>SELECT \nu.username,\nt.tweets\nINTO OUTFILE 'plus50tweets.txt'\nFROM\ntweets t\nINNER JOIN users u ON u.username=t.username\nWHERE u.no_tweets > 50\nORDER BY u.username\n</code></pre>\n\n<p>(untested. see also <a href=\"http://dev.mysql.com/doc/refman/5.0/en/select-into.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.0/en/select-into.html</a>)</p>\n\n<p>That will still be rather slow without any indexing and keys; so use users.username as your primary key, and add an index on users.no_tweets. Add another (non-primary) key on tweets.username. If that doesn't help, set the foreign keys in tbl tweets to the users table.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T02:36:47.187",
"Id": "7659",
"ParentId": "7645",
"Score": "1"
}
},
{
"body": "<p>Do not use a database for this. Use files.</p>\n\n<p>A single file with one tweet per line showing User Name, Tweet Text and whatever other information you have.</p>\n\n<p>You need to sort the file by user. Use the OS-level <code>sort</code> program, don't write your own.</p>\n\n<p>Once the tweets are sorted by user, you simply read and count.</p>\n\n<pre><code>def group_by_user( iterable ):\n tweet_iter= iter(iterable)\n first= next(tweet_iter)\n group= [ first ]\n user= first.user\n for tweet in tweet_iter:\n if tweet.user != user:\n yield user, group\n user= tweet.user\n group = []\n group.append(tweet)\n yield user, group\n\nTweet = namedtuple( 'Tweet', ['user','text',etc.] )\n\ndef make_named_tuples( raw_tweets ):\n for tweet in raw_tweets:\n yield Tweet( tweet.split('\\t') ) # or whatever\n\nwith open( some_file ) as source:\n for user, group in group_by_user( iterable )\n if len(group) > 50: \n # Open and write to a file.\n</code></pre>\n\n<p>This does not involve the <strong>huge</strong> overheads of a database.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:43:18.637",
"Id": "7675",
"ParentId": "7645",
"Score": "1"
}
},
{
"body": "<p>As others have mentioned, this code is likely I/O bound. Let's bring down the time it takes to perform all the tweets queries:</p>\n\n<h2>Improving read performance: parallel queries</h2>\n\n<p>Assuming the hardware running your MySQL database is capable, you can greatly improve the performance of the overall process by running multiple queries in parallel. I'm partial to <a href=\"http://gevent.org\" rel=\"nofollow noreferrer\">gevent</a> for this sort of thing, but the <code>threading</code> module from the Python standard lib should be more than sufficient. What we want to do is have multiple queries being performed at once, so that we are spending less time overall waiting for responses. To do this we take this code:</p>\n\n<pre><code>for i in rows:#For all users\n data = open(os.path.join(directory,i[0]),'w') #Open a file same as their name\n allTweets = tweets(cursor,i[0]) #Find all tweets by them\n for j in allTweets:\n data.write(j[0]+\"\\n\") #Write them \n data.close()\n</code></pre>\n\n<p>And instead do something like this:</p>\n\n<pre><code>def save_tweets(users):\n ''' For each username in the queue, retrieve all of their tweets and save them to disk ''' \n cursor = connect()\n while True:\n username = users.get()\n with open(os.path.join(directory, username),'w') as output:\n for tweet in tweets(cursor, username):\n output.write(row[0] + '\\n')\n users.task_done()\n\nfrom queue import Queue\nfrom threading import Thread\nuser_queue = Queue()\n# Perform at most 10 queries at the same time.\nmax_connections = 10\nfor i in max_connections:\n t = Thread(target=save_tweets, args=(user_queue,))\n t.daemon = True\n t.start()\n\nfor row in rows:#For all users\n user_queue.put(row[0])\nuser_queue.join() # Wait for all tasks to be completed\n</code></pre>\n\n<p>Now, somebody is bound to point out that you should use the <a href=\"http://docs.python.org/library/multiprocessing.html\" rel=\"nofollow noreferrer\">multiprocessing</a> module instead of <code>threading</code>, and they may be right. If you find that the Python process for this script (<strong>not</strong> MySQL) is using 100% of the CPU time on one core, then you should consider using multiprocessing. Luckily it's a near drop-in replacement for the <code>threading</code> module, so the code will need very little change to adapt to it. Either way, this should get you into the position where you're pushing your database server to it's limits.</p>\n\n<h2>Alternative, use the powers of SQL</h2>\n\n<p>Another approache that might be fun to try is using the <code>GROUP_CONCAT</code> function (found in <a href=\"https://stackoverflow.com/questions/149772/how-to-use-group-by-to-concatenate-strings-in-mysql\">this answer</a>) to perform all of the work in a single query like so:</p>\n\n<pre><code>SELECT user, GROUP_CONCAT(tweet SEPARATOR '\\n') as tweet_data, count(*) as tweet_count\nFROM tweets WHERE tweet_count > 50\nGROUP BY user;\n</code></pre>\n\n<p>However, given the amount of data you're dealing with, you'll probably just make your database server start swapping data in and out of memory and drive it's performance into the ground. (Unless your server happens to have +8GB of RAM, which according to Makotos estimates should be enough to hold the entire working set in memory) </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T07:13:41.910",
"Id": "8048",
"ParentId": "7645",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T19:26:53.443",
"Id": "7645",
"Score": "5",
"Tags": [
"python",
"mysql",
"performance"
],
"Title": "40 million tweets from 200k users"
}
|
7645
|
<p>I have created a piece of code for a live pagination, but I don't like the code. It works it does the job, but I guess I could done it better.</p>
<pre><code>$('.show-content').livequery(function() {
$(this).find('.page-me:not(:first)').hide();
var totalPage = $(this).find('.page-me').length;
for (var i = 0; i <= totalPage - 1; i++) {
$('.modal-pagination').append('<a href="#" id="' + i + '">Page ' + (i + 1) + '</a>')
}
$('.modal-pagination a').live('click', function() {
var thePag = $(this).attr('id');
$('.show-content').find('.page-me').hide();
$('.show-content').find('.page-me:nth(' + thePag + ')').show();
return false;
});
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T21:34:48.623",
"Id": "12026",
"Score": "1",
"body": "livequery is the devil and needs to die in fire"
}
] |
[
{
"body": "<p>The code looks fine to me. The only things I would personally change is the use of the <code>live()</code> method (which has been deprecated, and was slow anyway) to<code>delegate()</code> and the use of the <code>:nth()</code> selector, which again I believe is not very fast - although I've not specifically tested it. In place of that I'd use <code>eq()</code>.</p>\n\n<pre><code>$('.modal-pagination').delegate('a', 'click', function(e) {\n e.preventDefault();\n var thePag = $(this).attr('id');\n $('.show-content').find('.page-me').hide().eq(thePag -1).show();\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T21:41:56.337",
"Id": "12027",
"Score": "0",
"body": "Thanks a lot! Please remove `thePag -1` I have taken care of that in the loop, I will accept it asap."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T21:30:33.360",
"Id": "7651",
"ParentId": "7650",
"Score": "3"
}
},
{
"body": "<pre><code>var toArray = [].slice.call.apply([].slice]);\nvar contentShow = toArray(document.getElementsByClassName('contentShow'));\ncontentShow.forEach(function doStuff(element) {\n var pageMe = toArray(element.getElementsByClassName('page-me')),\n modalPagination = toArray(document.getElementsByClassName));\n\n pageMe.unshift();\n pageMe.forEach(function hideElement(element, index) {\n element.classList.add('hidden');\n modalPagination.forEach(function addLink(modal) {\n var link = document.createElement(\"a\");\n link.id = index;\n link.textContent = 'Page ' + (index + 1);\n modal.appenChild(link);\n });\n });\n\n modalPagination.forEach(function delegateClick(element) {\n element.addEventListener('click', function handleClick() {\n if (this.tagName !== 'a') return;\n\n var thePage = this.id; \n\n var showContent = toArray(document.getElementsByClassName('show-content'));\n showContent.forEach(function doStuffWithPageMe(element) {\n var pageMe = toArray(element.getElementsByClassName('page-me'));\n for (var i = 0, len = pageMe.length; i < len; i++) {\n var page = pageMe[i];\n if (i % thePage === 0) {\n pageMe.classList.remove('hidden'); \n } else {\n pageMe.classList.add('hidden');\n }\n }\n });\n } \n });\n});\n</code></pre>\n\n<p>The code is ugly because your logic is ugly. You need to fix your logic and also probably fix your HTML.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T21:47:58.500",
"Id": "12028",
"Score": "2",
"body": "LOL you just **had to** make it complicated :-P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T21:51:20.483",
"Id": "12029",
"Score": "2",
"body": "@Neal No, I made the complexity jQuery hides be shown in plain sight. If you don't see what the _code really does_ you would still be disillusioned into thinking the code isn't bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T22:00:02.017",
"Id": "12030",
"Score": "0",
"body": "OMG :)))) you really got me good here :))) and yes, you are right sir. PS: OMG!!!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T21:46:59.150",
"Id": "7652",
"ParentId": "7650",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7651",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-10T21:17:14.827",
"Id": "7650",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"pagination"
],
"Title": "Pagination using livequery in jQuery"
}
|
7650
|
<p>I need help refactoring code for my PHP template engine. I just have this feeling that the code is too disorganized and can be improved performance-wise. My main concerns are running a preg_match on every line in the file and hard-coding functionality for conditional and repeat blocks. </p>
<pre><code><?php
class Template extends Component
{
private static $actions = array(); // Template actions
private $data = array(); // Template data
private $path = null; // Path to template file
private $in_block = false; // In conditional block
private $execute_block = false; // Whether to execute block
private $repeat_block = false; // In repeat block
private $repeat_data = null; // Repeat data
private $repeat_start = 0; // Start of repeat index
private $repeat_end = 0; // End of repeat index
private $repeat_buffer = array(); // Stores repeated code
// Registers a template action, makign it available to use inside a template
public static function registerAction($action_name, $function_handler)
{
if (!is_callable($function_handler))
trigger_error(sprintf('Function %s does not exist in Template::registerAction', $function_handler), E_USER_ERROR);
self::$actions[$action_name] = $function_handler;
}
// Runs a template action and returns the result
public function executeAction($action, $arguments)
{
if (array_key_exists($action, self::$actions))
{
// If there is just one argument being passed, then don't pass an array
if (count($arguments) == 1)
$arguments = $arguments[0];
return call_user_func_array(self::$actions[$action], array($arguments, $this));
}
}
// Initializes the Template component
public function __construct($path, $data = null)
{
$this->path = $path;
if (is_array($data))
$this->data = $data;
}
// Adds or modifies an entry in the template data
public function set_data($key, $value)
{
$this->data[$key] = $value;
}
// Returns an entry in the template data
public function get_data($key)
{
return $this->data[$key];
}
// Returns all template data
public function all_data()
{
return $this->data;
}
// Starts a conditional block
public function startBlock($execute)
{
$this->in_block = true;
$this->execute_block = $execute ? true : false; // Only allow boolean values
}
// Starts a repeat block
public function startRepeatBlock($repeat_data)
{
// If data does not exist, then do not execute the block
if (empty($this->data[$repeat_data]) || count($this->data[$repeat_data]) == 0)
return;
$this->repeat_data = $repeat_data;
$this->repeat_block = true;
$this->repeat_end = is_array($this->data[$repeat_data][0]) ? count($this->data[$repeat_data]) : 1;
}
// Ends a conditional or repeat block. If latter, then executes all code in repeat buffer.
public function endBlock()
{
$this->in_block = false;
$this->execute_block = false;
// If a repeat block ended, then process the entire block
if ($this->repeat_block)
{
$data = $this->data[$this->repeat_data];
$final = '';
// If there are no arrays in the array, then change it into that form
if (!is_array($data[0]))
$data = array($data);
// Begin processing
while ($this->repeat_start < $this->repeat_end)
{
$entry = $data[$this->repeat_start++];
// Set the appropriate variables
foreach ($entry as $key => $value)
{
$key = $this->repeat_data . '[' . $key . ']';
$this->data[$key] = $value;
}
// Process the entire block once
foreach ($this->repeat_buffer as $arr)
{
if (count($arr) == 3)
{
list($before, $after, $entry) = $arr;
$line = $before . $this->processEntry($entry) . $after;
}
else
{
$line = $arr;
}
$final .= $line;
}
}
// Reset the repeat variables
$this->repeat_block = false;
$this->repeat_data = null;
$this->repeat_start = 0;
$this->repeat_end = 0;
$this->repeat_buffer = array();
// Return the final result result
return $final;
}
}
// Returns whether the current line of code is allowed to be executed or not
public function canExecute()
{
return !$this->in_block || ($this->in_block && $this->execute_block);
}
// Renders the template, displaying it to the user
public function render()
{
echo $this->content();
}
// Returns the final, parsed template data
public function content()
{
if (!file_exists($this->path))
return;
/* 0 = before, 1 = entry #1, 2 = entry #2, 3 = after */
$content = file_get_contents($this->path);
$pattern = '/^(.*)\<\%\s*(.+)\s*\%\>(.*)$/';
$lines = explode("\n", $content);
$javascript = false;
foreach ($lines as $line)
{
// Pattern match the line
preg_match($pattern, $line, $matches);
$result = '';
// If there are no matches, then don't parse it and add the raw string to output
if (count($matches) == 0)
{
// Only add if the "block conditions" are correct and repeat mode is off
if ($this->canExecute() && !$this->repeat_block)
$final .= $line;
// If repeat block mode is on, then add it to the repeat buffer
if ($this->repeat_block)
$this->repeat_buffer[] = $line;
continue;
}
// Parse the matches and run the appropriate action
$before = $matches[1];
$after = $matches[3];
$entry = $matches[2];
$return = '';
// If the entry signals a block end of "end()" then close the block
if (trim($entry) == "end()")
$final .= $this->endBlock();
// Only run the entry if it is in an executable block
if (!$this->canExecute())
continue;
// If this is a repeating block, then don't process, instead "record" the line
if ($this->repeat_block)
{
$this->repeat_buffer[] = array($before, $after, $entry);
continue;
}
// Process the entry
$return = $this->processEntry($entry);
// Add the processed line to the final result if not empty
$result = $before . $return . $after;
if (!empty($result)) $final .= $result . "\n";
}
return $final;
}
// Processes a special block
public function processEntry($entry)
{
// If "()" exists in the entry, then it's a function call
if (strpos($entry, ')') !== false)
{
list($function, $arguments) = explode('(', $entry, 2);
$arguments = array_map('trim', explode(',', substr($arguments, 0, strlen($arguments) - 2)));
return $this->executeAction($function, $arguments);
}
// Otherwise, assume it's a variable
return html($this->data[clean($entry)]);
}
}
/* Define some basic template actions */
function TemplateAction_raw($string, $obj)
{
return html_entity_decode($obj->get_data($string), ENT_QUOTES);
}
function TemplateAction_multiline($string, $obj)
{
return nl2br(html($obj->get_data($string)));
}
function TemplateAction_json($data, $obj)
{
return json_encode($obj->get_data($data));
}
function TemplateAction_include($location, $obj)
{
$path = SNIPPETS . $location . '.php';
$template = (new Template($path, $obj->all_data()));
return $template->content();
}
function TemplateAction_setTitle($title, $obj)
{
$obj->set_data('page_title', $title);
}
function TemplateAction_title($_, $obj)
{
$title = $obj->get_data('page_title'); // For some reason I need a separate variable
if (empty($title))
return Config::read('HTML.default_title');
return html(Config::read('HTML.title_prefix') . $obj->get_data('page_title') . Config::read('HTML.title_postfix'));
}
function TemplateAction_flash($_, $obj)
{
return html($obj->get_data('flash_message'));
}
function TemplateAction_no_flash($_, $obj)
{
$obj->startBlock(strlen($obj->get_data('flash_message')) == 0);
}
function TemplateAction_iterate($string, $obj)
{
$obj->startRepeatBlock($string);
}
/* Register template actions */
Template::registerAction('raw', 'TemplateAction_raw');
Template::registerAction('multiline', 'TemplateAction_multiline');
Template::registerAction('json', 'TemplateAction_json');
Template::registerAction('include', 'TemplateAction_include');
Template::registerAction('setTitle', 'TemplateAction_setTitle');
Template::registerAction('title', 'TemplateAction_title');
Template::registerAction('flash', 'TemplateAction_flash');
/* Register template blocks */
Template::registerAction('no_flash', 'TemplateAction_no_flash');
/* Register the one and only repeat block */
Template::registerAction('iterate', 'TemplateAction_iterate');
?>
</code></pre>
|
[] |
[
{
"body": "<p>Once I saw a similar templating engine, and it was so unnecessarily complex that I replaced it with something stupidly simple:</p>\n\n<pre><code>function php_as_template( $_t_filename, $_t_vars = null ){\n // make local variables from values in $_t_vars\n if( $_t_vars ) foreach( $_t_vars as $_t_k => &$_t_v) $$_t_k =& $_t_v;\n ob_start();\n include $_t_filename;\n $_t_result = ob_get_contents();\n ob_end_clean();\n return $_t_result;\n}\n</code></pre>\n\n<p>Usage example:</p>\n\n<pre><code>echo php_as_template('hello.php',array('a'=>'Hello','b'=>array('World!')));\n</code></pre>\n\n<p><code>hello.php</code>:</p>\n\n<pre><code><h1><?php echo $a; ?><?php echo $b[0]; ?></h1>\n\n\n<?php\n\nfunction php_as_template( $_t_, $_t_vars = null ){\n // make local variables from values in $_t_vars\n if( $_t_vars ) foreach( $_t_vars as $_t_k => &$_t_v) $$_t_k =& $_t_v;\n ob_start();\n $_t_ = '?'.'>'.$_t_;\n $_t_ = preg_replace_callback( '/<\\%\\s*(.+?)\\s*\\%\\>/', 'pattern_callback', $_t_ );\n echo 'PROCESSED TEMPLATE: '.str_replace( \"\\n\",\"<br>\",htmlspecialchars( $_t_ ));\n eval( $_t_ );\n $_t_result = ob_get_contents();\n ob_end_clean();\n return $_t_result;\n}\n\nfunction pattern_callback( $matches ){\n global $template_functions;\n $s = $matches[1];\n if( preg_match('/^(\\w+)\\s*\\((.*)\\)/', $s, $m )){ // start of function call\n if( array_key_exists( $m[1], $template_functions )){ // function exists\n return '<?php echo call_user_func_array('\n .'$GLOBALS[\"template_functions\"][\"'.$m[1].'\"], array('.$m[2].')); ?>';\n }\n }\n}\n\n$template_functions = array(\n//'action name called in template' => anything call_user_func_array accepts\n 'json' => array('TemplateActions','json') // static class function\n ,'dump' => 'var_dump' // plain func\n);\n\nclass TemplateActions {\n static function json( $data ){ return json_encode( $data ); }\n}\n\n\n$a = 'Hello';\n$b = array('World!');\n$template = '\n <h1> <?php echo $a; ?> <?php echo $b[0]; ?> </h1><br>\n The JSON is:<br>\n <% json( array(1,$a,$b) ) %><br>\n <% dump( array(1,$a,$b) ) %>\n';\necho php_as_template( $template ,compact('a','b'));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T01:41:58.133",
"Id": "12216",
"Score": "0",
"body": "Yes, that is a very simple template engine. But what if i want more advanced functionality? For example in my engine I have template actions which are basically \"functions\" that can be called inside of the templates. How would I go about implementing that without making things overly complex?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T09:27:51.307",
"Id": "12237",
"Score": "0",
"body": "See new example, hopefully it helps."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:45:12.853",
"Id": "7719",
"ParentId": "7656",
"Score": "3"
}
},
{
"body": "<p>For a standard (W3C) and complete (with PHP registered functions) <em>template engine</em>, see this tutorial for use \"XSLT 1.0 + PHP\" templating: \n<a href=\"http://en.wikibooks.org/wiki/PHP_Programming/XSL/registerPHPFunctions\" rel=\"nofollow\">http://en.wikibooks.org/wiki/PHP_Programming/XSL/registerPHPFunctions</a></p>\n\n<p>To build your \"every no standard\" template engine, a good start point is the \"smallest PHP template engine\": <a href=\"https://code.google.com/p/smallest-template-system/wiki/PHP\" rel=\"nofollow\">https://code.google.com/p/smallest-template-system/wiki/PHP</a></p>\n\n<p>PS: if you reply comments here, we can extend this answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-02T11:32:36.680",
"Id": "25731",
"ParentId": "7656",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7719",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T01:35:17.223",
"Id": "7656",
"Score": "2",
"Tags": [
"php"
],
"Title": "PHP Templating Engine"
}
|
7656
|
<p>I created a PHP class to handle building SQL query strings. I need advice on how to make the code more efficient. </p>
<pre><code><?php
/**
* Example:
*
* $query = new SQLQuery();
* $query->select('*')->from('users')->where(array('banned' => 0))->order('id' => 'asc')->limit(1);
* $result = $query->execute();
*
**/
requireComponent('Database');
define('SQLQUERY_INSERT', 1);
define('SQLQUERY_UPDATE', 2);
define('SQLQUERY_DELETE', 3);
define('SQLQUERY_SELECT', 4);
define('SQLQUERY_REPLACE', 5);
define('SQLQUERY_CUSTOM', 6);
class SQLQuery extends Component
{
private $type = null; // Query type
private $from = null; // Table name
private $select = array(); // Selected fields
private $where = array(); // Where conditions
private $order = array(); // Order conditions
private $fields = array(); // Insert fields
private $where_condition = null; // Where condition (AND, OR)
private $join_table = null; // Joined table
private $join_on = null; // Join constraint
private $limit = 0; // Row limit
private $custom_sql = null; // Explicit SQL code
private $custom_args = array(); // Explicit SQL arguments
// Initializes an SQLQuery object with an optional preset table name
public function __construct($table_name = null)
{
if ($table_name !== null)
$this->from = $table_name;
}
// Wraps a string in backticks
private function bwrap($s)
{
return surround('`', $s);
}
// Returns the SQL code for a SELECT clause
private function getSelectClause()
{
$append = ($this->fields == '*') ? $this->fields : implode(',' , array_map(array($this, 'bwrap'), is_array($this->fields) ? $this->fields : array($this->fields)));
return 'SELECT ' . $append;
}
// Returns the SQL code for an UPDATE clause
private function getUpdateClause()
{
$sql = 'UPDATE ' . $this->bwrap($this->from) . ' SET ';
$fields = array();
foreach ($this->fields as $key => $value)
{
$value = strcmp_is($value, 'null') ? 'NULL' : '"' . sql($value) . '"';
$fields[] = $this->bwrap($key) . ' = ' . $value;
}
return $sql . implode(',', $fields);
}
// Returns the SQL code for a DELETE clause
private function getDeleteClause()
{
return 'DELETE';
}
// Returns the SQL code for a WHERE clause
private function getWhereClause()
{
if (count($this->where) == 0)
return '';
$operators = array('< ', '> ', '<=', '>=', '!=', '<>');
$fields = array();
foreach ($this->where as $key => $value)
{
// Check first two characters of $value to search for operators
$op = $value[0] . $value[1];
$op_exists = in_array($op, $operators);
$joiner = $op_exists ? $op : (($value == null) ? 'IS' : '=');
$value = empty($value) ? 'NULL' : '"' . sql(trim($op_exists ? str_replace($op, '', $value) : $value)) . '"';
$fields[] = $this->bwrap($key) . ' ' . $joiner . ' ' . $value;
}
return 'WHERE ' . implode(' ' . $this->where_condition . ' ', $fields);
}
// Returns the SQL code for a FROM clause
private function getFromClause()
{
return 'FROM ' . $this->bwrap($this->from);
}
// Returns the SQL code for a JOIN clause
private function getJoinClause()
{
if (!$this->join_table || !$this->join_on)
return '';
return sprintf('INNER JOIN %s ON (%s.%s = %s.%s)', $this->join_table, $this->from, $this->join_on[0],
$this->join_table, $this->join_on[1]);
}
// Returns the SQL code for an ORDER BY clause
private function getOrderByClause()
{
if (count($this->order) == 0)
return '';
$allowed = array('asc', 'desc');
$fields = array();
foreach ($this->order as $key => $value)
{
if (in_array(strtolower($value), $allowed))
$fields[] = $this->bwrap($key) . ' ' . strtoupper($value);
}
return 'ORDER BY ' . implode(',', $fields);
}
// Returns the SQL code for a LIMIT clause
private function getLimitClause()
{
return ($this->limit > 0) ? 'LIMIT ' . $this->limit : '';
}
// Builds a query string for a SELECT operation
private function buildSelectQueryString()
{
return implode(' ', array($this->getSelectClause(), $this->getFromClause(), $this->getWhereClause(),
$this->getJoinClause(), $this->getOrderByClause(), $this->getLimitClause()));
}
// Builds a query string for an INSERT operation
private function buildInsertQueryString()
{
// No easy way to do it in one line
$values = array_values($this->fields);
$count = count($values);
for ($c = 0; $c < $count; $c++)
{
if ($values[$c] == 'NOW()')
$values[$c] = 'NOW()';
else
$values[$c] = '"' . sql($values[$c]) . '"';
}
$sql = 'INSERT INTO ' . $this->bwrap($this->from) . ' ';
$sql .= '(' . implode(',', array_map(array($this, 'bwrap'), array_keys($this->fields))) . ') VALUES ';
$sql .= '(' . implode(',', array_values($values)) . ')';
return $sql;
}
// Builds a query string for a replace operation
private function buildReplaceQueryString()
{
return 'REPLACE' . substr($this->buildInsertQueryString(), 6);
}
// Builds a query string for an UPDATE operation
private function buildUpdateQueryString()
{
return implode(' ', array($this->getUpdateClause(), $this->getWhereClause(), $this->getLimitClause()));
}
// Builds a query string for a DELETE operation
private function buildDeleteQueryString()
{
return implode(' ', array($this->getDeleteClause(), $this->getFromClause(), $this->getWhereClause(),
$this->getLimitClause()));
}
// Returns the finalized query string for the appropriate query type
public function buildQueryString()
{
switch ($this->type)
{
case SQLQUERY_SELECT:
return $this->buildSelectQueryString();
break;
case SQLQUERY_UPDATE:
return $this->buildUpdateQueryString();
break;
case SQLQUERY_INSERT:
return $this->buildInsertQueryString();
break;
case SQLQUERY_REPLACE:
return $this->buildReplaceQueryString();
break;
case SQLQUERY_DELETE:
return $this->buildDeleteQueryString();
break;
case SQLQUERY_CUSTOM:
return $this->custom_sql;
break;
}
trigger_error('Could not call SQLQuery::buildQueryString because of bad query type', E_USER_ERROR);
}
// Executes the SQL query and returns the results
public function execute()
{
// Build query string
$query_string = $this->buildQueryString();
// Log SQL query if needed
if (!Logger::busy() && Config::read('Logger.log_sqlqueries') && componentExists('Logger'))
{
Logger::log(sprintf('SQL query executed: %s', $query_string), LOGGER_CATEGORY_SQLQUERY);
}
// Note: Since prepared statements technically aren't being used in this case,
// the inputs must be escaped beforehand
return ($this->type != SQLQUERY_CUSTOM) ?
call_user_func_array(array('Database', 'query'), array($query_string)) :
call_user_func_array(array('Database', 'query'), array_merge(array($this->custom_sql), $this->custom_args));
}
// Ignores all other parameters and runs explicitly specified SQL code
public function explicit()
{
$args = func_get_args();
$this->type = SQLQUERY_CUSTOM;
$this->custom_sql = array_shift($args);
$this->custom_args = $args;
return $this;
}
// Initializes a SELECT query with selected fields
public function select($fields)
{
$this->type = SQLQUERY_SELECT;
$this->fields = $fields;
return $this;
}
// Initializes an INSERT query with starting fields
public function insert($fields)
{
$this->type = SQLQUERY_INSERT;
$this->fields = $fields;
return $this;
}
// Initializes a REPLACE query with starting fields
public function replace($fields)
{
$this->type = SQLQUERY_REPLACE;
$this->fields = $fields;
return $this;
}
// Initializes an UPDATE query with updated fields
public function update($fields)
{
$this->type = SQLQUERY_UPDATE;
$this->fields = $fields;
return $this;
}
// Initializes a DELETE query
public function delete()
{
$this->type = SQLQUERY_DELETE;
$this->fields = array();
return $this;
}
// Sets the FROM field
public function from($from)
{
$this->from = $from;
return $this;
}
// Sets the WHERE field
public function where($fields)
{
$this->where = $fields;
$this->where_condition = $fields['_condition'];
unset($this->where['_condition']);
return $this;
}
// Sets the WHERE field with AND condition
public function whereAnd($fields)
{
return $this->where(array_merge($fields, array('_condition' => 'AND')));
}
// Sets the WHERE field with OR condition
public function whereOr($fields)
{
return $this->where(array_merge($fields, array('_condition' => 'OR')));
}
// Sets the JOIN field
public function join($table, $on)
{
$this->join_table = $table;
$this->join_on = $on;
return $this;
}
// Sets the ORDER BY field
public function order($by)
{
$this->order = $by;
return $this;
}
// Sets the LIMIT field
public function limit($limit)
{
if ($limit > 0)
$this->limit = $limit;
return $this;
}
}
?>
</code></pre>
<p>Also another thing - how can I handle WHERE conditions? Like WHERE conditions should support AND, OR, and nested ANDs and ORs, and also a variety of operators (<, >, >=, <=, !=) and LIKE, NOW(), etc. There's just so many of them though, and I can't think of a way to implement all that without resorting to ugly hacks. </p>
|
[] |
[
{
"body": "<p>I usually prefer to use existing solutions, can you look at the PHP Doctrine Query Builder, which has its own DQL language inspired by HQL (Hibernate Query Language), while its focused on objects it may provide useful pointers at <a href=\"https://github.com/doctrine/dbal/tree/master/lib/Doctrine/DBAL/Query\" rel=\"nofollow\">https://github.com/doctrine/dbal/tree/master/lib/Doctrine/DBAL/Query</a> </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-17T10:06:33.467",
"Id": "10091",
"ParentId": "7657",
"Score": "0"
}
},
{
"body": "<p>I usually use an existing solution too, but it is good practice to write your own. In your specific problem I would use a separate class for expression. Something like the <a href=\"https://github.com/onPHP/onphp-framework/blob/master/core/Logic/BinaryExpression.class.php\" rel=\"nofollow\">Expression class of onPHP</a>. You can make one class for binary expression and other classes for special expressions like \"equals\", \"in\", etc. For difficult expressions with a lot of logic you can also write expression chains with logical links such as \"and\" and \"or\". One more advice, check the type in special methods, for example: If you have an \"order\" for an <code>insert</code> query, throw an exception and you will need less tests.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-11-13T09:42:09.177",
"Id": "18529",
"ParentId": "7657",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T01:42:46.043",
"Id": "7657",
"Score": "4",
"Tags": [
"php",
"sql"
],
"Title": "PHP SQLQuery class"
}
|
7657
|
<p>Below is the code for a database class that wraps around a small set of the features that the <code>mysqli</code> extension provides. I'm looking for ways to improve its efficiency. Which parts of the code seem hack-ish and how can I make it more structured and organized?</p>
<pre><code>class Database extends Component
{
private static $mysqli = null; // MySQLi object
/* Connect to the database */
public static function init()
{
if (Config::read('Database.enable'))
{
if (!self::connect(Config::read('Database.connections')))
trigger_error('Database::connect() failed : Unable to connect to database', E_USER_ERROR);
}
}
/* Close the database connection upon script determination */
public function __destruct()
{
if (self::$mysqli)
self::$mysqli->close();
}
/* Returns the type label (i, d, s, b) of an array of MySQLi input parameters */
private static function getTypeLabel(array $args)
{
$return = '';
foreach ($args as $input)
{
if (is_int($input))
$return .= 'i';
else if (is_double($input) || is_float($input))
$return .= 'd';
else if (is_string($input))
$return .= 's';
else
$return .= 'b';
}
return $return;
}
/* Returns whether the MySQL connection has been established */
public static function connected()
{
return is_resource(self::$mysqli);
}
/* Returns the MySQL connection resource */
public static function obj()
{
return self::$mysqli;
}
/* Pass an array of login credentials and attempts to connect to the database */
public static function connect($db_list)
{
foreach ($db_list as $db)
{
self::$mysqli = @(new mysqli($db['host'], $db['user'], $db['pass'], $db['db']));
if (mysqli_connect_errno())
{
self::$mysqli = null;
continue;
}
break;
}
return self::$mysqli !== null;
}
/**
* Execute a query given a query string and passed parameters. Returns
* the result array or the number of affected rows if it is an update, insert
* or delete query. Returns null and triggers error if query failed.
* This function basically combines executeQuery() and prepareQuery()
* Example:
*
* $result = DB::query('SELECT * FROM my_table WHERE id = ?', $id);
* $num_rows = $result['num_rows'];
* foreach ($result['rows'] as $row)
* {
* echo $row['field'];
* }
*
**/
public static function query($query)
{
// If there is no connection to the MySQL server, then return null
if (!self::$mysqli)
return null;
if ($query = self::$mysqli->prepare($query))
{
$results = array();
// Build args array and call mysqli_stmt::bind_param
if (func_num_args() > 1)
{
$fga = func_get_args(); // For ASO servers (PHP 5.0.2), this is necessary
$args = array_merge(array(func_get_arg(1)), array_slice($fga, 2));
$args_ref = array();
$args_ref[0] = self::getTypeLabel($args);
foreach ($args as $k => &$arg)
$args_ref[] =& $arg;
call_user_func_array(array($query, 'bind_param'), $args_ref);
}
// Execute query
$query->execute();
// Most likely due to syntax errors
if ($query->errno)
{
trigger_error(self::$mysqli->error, E_USER_ERROR);
return null;
}
// If the query was insert, update or delete, then return affected rows
if ($query->affected_rows > -1)
return $query->affected_rows;
// Build results array and call mysqli_stmt::bind_result
$params = array();
$meta = $query->result_metadata();
while ($field = $meta->fetch_field())
$params[] =& $row[$field->name];
call_user_func_array(array($query, 'bind_result'), $params);
// Fetch results and store them in returned array
while ($query->fetch())
{
$r = array();
foreach ($row as $key => $value)
$r[$key] = $value;
$result[] = $r;
}
$query->close();
return count($result) > 1 ? $result : $result[0];
}
trigger_error(self::$mysqli->error, E_USER_WARNING);
return null;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks like you are trying to write object oriented code, however this is completely procedural. Remove <code>static</code> everywhere and use dependency injection if you want to make this OO.</p>\n\n<p>Static code is hard to test. It is the equivalent a namespaced function.</p>\n\n<p>The real benefit I see with OO is encapsulation and implementation hiding. This allows a program to be split into objects that can interact while sharing a small public interface (and hiding a lot of implementation details in protected and private methods). The problem with static is that it opens up all of the implementation details globally. It stops you being able to look at an object and just be worried about its public interface.</p>\n\n<p>Calling a static function binds the calling code tightly to a specific implementation. <code>Database::query</code> is a much tighter binding than having injected a database object and then calling <code>$this->db->query</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T01:38:17.750",
"Id": "12215",
"Score": "0",
"body": "If I used dependency injection to make those components actual objects instead of just static instances, what would be the practical benefit, besides making my code more OO?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T01:50:31.097",
"Id": "12217",
"Score": "0",
"body": "I updated my answer with some of the benefits that I see."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T02:11:27.380",
"Id": "12219",
"Score": "0",
"body": "Interesting. But can't you also declare a variable in an object as private static? Then you can't access it from outside the class scope, but you can use public static methods to access the data. Would that adequately solve the problem of opening up the implementation details?\n\nAlso, considering PHP is a loosely typed language, would the binding really matter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T02:24:47.797",
"Id": "12220",
"Score": "0",
"body": "Trying to access an objects details is looking at it slightly the wrong way. Think of the object as being responsible for its area of responsibility (including its state data). Now the object may do something that it has responsibility over or describe some of its state to you in response to a method call. It is not the caller who does these things, it is the object. That is why you would use a get method rather than accessing it via static. The responsibility for the state data belongs with the object. Having control at the caller seems good at first, but it binds the calling code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T03:22:55.033",
"Id": "7660",
"ParentId": "7658",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7660",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T01:48:23.660",
"Id": "7658",
"Score": "3",
"Tags": [
"php",
"sql",
"mysqli"
],
"Title": "PHP Database class"
}
|
7658
|
<p>In page load I'm saving a query string int value in a viewstate. Then I save it to my DB. Here is the code I use to retrieve viewstate value and validating it:</p>
<pre><code>protected int CurrentCom
{
get
{
if (ViewState["CurrentCom"] == null)
return 0;
else
{
int temp;
if (int.TryParse(ViewState["CurrentCom"].ToString(), out temp))
return temp;
else return 0;
}
}
set { ViewState["CurrentCom"] = value; }
}
</code></pre>
<p>Is there a better way to make this shorter?</p>
|
[] |
[
{
"body": "<p>I'm not too familiar with C#, but the else branch looks unnecessary, since if <code>ViewState[\"CurrentCom\"] == null</code> is <code>true</code> the method returns with <code>0</code>.</p>\n\n<pre><code>if (ViewState[\"CurrentCom\"] == null) {\n return 0;\n}\nint currentCom;\nif (int.TryParse(ViewState[\"CurrentCom\"].ToString(), out currentCom)) {\n return currentCom;\n}\nreturn 0;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T12:03:53.683",
"Id": "7665",
"ParentId": "7663",
"Score": "0"
}
},
{
"body": "<p>I usually do like this:</p>\n\n<pre><code>return (int)(ViewState[\"CurrentCom\"] ?? 0);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T15:38:29.167",
"Id": "12073",
"Score": "0",
"body": "cool ! where was this all this time ? thank you Mattias"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T17:15:49.113",
"Id": "12084",
"Score": "0",
"body": "I would usually do `return ViewState[\"CurrentCom\"] as int? ?? 0`, but this feels much better. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T14:57:56.737",
"Id": "7669",
"ParentId": "7663",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "7669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T11:22:15.247",
"Id": "7663",
"Score": "4",
"Tags": [
"c#",
"casting"
],
"Title": "Is this a proper way to check a viewstate of type int?"
}
|
7663
|
<p><strong>Usage example</strong></p>
<pre><code>var qm = new QueueMessage("foo", 99);
var ba = ByteArraySerializer<QueueMessage>.Serialize(qm));
</code></pre>
<p><strong>Class that performs the serialization / deserialization</strong></p>
<pre><code>using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Codingoutloud
{
public static class ByteArraySerializer<T>
{
public static byte[] Serialize(T m)
{
var ms = new MemoryStream();
try
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, m);
return ms.ToArray();
}
finally
{
ms.Close();
}
}
public static T Deserialize(byte[] byteArray)
{
var ms = new MemoryStream(byteArray);
try
{
var formatter = new BinaryFormatter();
return (T)formatter.Deserialize(ms);
}
finally
{
ms.Close();
}
}
}
}
</code></pre>
<p><strong>Example of an object we would serialize</strong></p>
<pre><code>using System;
namespace Codingoutloud
{
[Serializable]
public class QueueMessage
{
public QueueMessage() {}
public QueueMessage(string name, int id)
{
Name = name;
Id = id;
}
public string Name { get; set; }
public int Id { get; set; }
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T18:43:04.467",
"Id": "12093",
"Score": "1",
"body": "It should be noted that this only (de)serializes serializable objects, so it won't necessarily work for any _arbitrary_ unknown object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T15:31:56.823",
"Id": "12173",
"Score": "0",
"body": "Good point Jeff! Will work for unknown types as long as they are serializable."
}
] |
[
{
"body": "<p>Your methodology is solid on the generics front. Highly recommend using <code>using</code> statements rather than <code>try..finally</code>s. I also converted the methods to extension methods.</p>\n\n<pre><code>namespace Codingoutloud\n{\n using System.IO;\n using System.Runtime.Serialization.Formatters.Binary;\n\n public static class ByteArraySerializer\n {\n public static byte[] Serialize<T>(this T m)\n {\n using (var ms = new MemoryStream())\n {\n new BinaryFormatter().Serialize(ms, m);\n return ms.ToArray();\n }\n }\n\n public static T Deserialize<T>(this byte[] byteArray)\n {\n using (var ms = new MemoryStream(byteArray))\n {\n return (T)new BinaryFormatter().Deserialize(ms);\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:39:07.740",
"Id": "12180",
"Score": "0",
"body": "Great edits @Jesse C. Slicer - thanks - esp the asymmetric types on the extension methods."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:55:40.093",
"Id": "7677",
"ParentId": "7673",
"Score": "11"
}
},
{
"body": "<p>You should make sure that the object is Serializable.</p>\n\n<p>A type that is serializable will return <code>true</code> for: </p>\n\n<pre><code>m.GetType().IsSerializable\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-04T23:42:55.773",
"Id": "13548",
"Score": "0",
"body": "thank you - good comment. I think that could be enforced with a Diagnostics.Debug.Assert or a CodeContract (from .NET 4)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T23:45:55.510",
"Id": "7875",
"ParentId": "7673",
"Score": "1"
}
},
{
"body": "<p>It's possible to serialize \"unserializable\" types via reflection, including private unserialized members and properties, though its a pain to deal with arbitrary type, you can certainly deal with all the common types easily, and provide for delegates to serialize/deserialize custom types.\nThe main thing for dealing with \"unknown\" types is to find out if they support a Set method - if not, you can't deserialize them, so no point to serialize them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-10-11T04:15:42.363",
"Id": "205345",
"ParentId": "7673",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7677",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-11T16:01:45.973",
"Id": "7673",
"Score": "9",
"Tags": [
"c#",
"generics",
"serialization"
],
"Title": "Serialize C# objects of unknown type to bytes using generics"
}
|
7673
|
<p>Here is my controller class for my MVC pattern with all the <code>includes</code> removed. From what I know of the MVC pattern it is good to have a small controller class. Mine is just a collection of public static functions which accept requests and send data to the client.</p>
<p>Regarding <code>send()</code>. I'm just wrapping the echo command for sending text from an Ajax call. This is for consistency and to have all text exiting the same point in code.</p>
<p>I have a ControlEntry (Snippet 2) which help decouple Super Globals and direct entry into the Control, so the two kind of work in Tandem.</p>
<p>Pull_Pic just pulls a path and inserts it into HTML for display.</p>
<p><strong>Snippet 1</strong></p>
<pre><code><?php
class Control
{
public static function ajax($ajax_type)
{
Session::start();
switch($ajax_type)
{
case 'ControlBookmark_add':
$control_bookmark_instance = new ControlBookmark('remove');
$control_bookmark_instance->add();
break;
case 'ControlBookmark_delete':
$control_bookmark_instance = new ControlBookmark('remove');
$control_bookmark_instance->delete();
break;
case 'ControlTweet_add':
$control_tweet_instance = new ControlTweet('remove');
$control_tweet_instance->add();
break;
case 'ControlSignIn':
$control_signin_instance = new ControlSignIn('remove');
$control_signin_instance->invoke();
break;
case 'ControlSignUp':
new ControlSignUp();
break;
case 'ControlTryIt':
new ControlTryIt();
break;
case 'ControlSignOut':
Session::finish();
new ControlSignOut();
break;
default:
throw new Exception('Invalid ajax_type');
}
}
public static function reload() // Because reload may be triggered by File Upload (second control path)
{
if (session_id() == "")
{
Session::start();
}
if((Session::status())==='bookmarks')
{
include 'class.ViewBookmarks.php';
}
else
{
include 'class.ViewMain.php';
}
}
public static function upload($fileType, $fileName)
{
Session::start();
$fileInstance = new UploadedFile($fileType, $fileName);
$fileInstance->createImages();
Session::updatePic();
self::reload();
}
public static function send($textStream)
{
echo $textStream;
}
}
**Snippet 2**
new ControlEntry();
class ControlEntry
{
public function __construct()
{
if(isset( $_FILES['ufile']['tmp_name']) )
{
if( ( $_FILES['ufile']['tmp_name']) != '' )
{
Control::upload( $_FILES['ufile']['type'], $_FILES['ufile']['tmp_name'] );
}
else
{
Control::reload();
}
}
else if( isset($_POST['ajax_type']) )
{
Control::ajax( $_POST['ajax_type'] );
}
else
{
Control::reload();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It looks like you are trying to write object oriented code, however this is completely procedural. Remove static everywhere and use dependency injection if you want to make this OO.</p>\n\n<p>Static code is hard to test. It is the equivalent of a namespaced function.</p>\n\n<p>Even your new objects that you create are the equivalent of calling a function.</p>\n\n<pre><code> case 'ControlBookmark_add': \n new ControlBookmark('add');\n break;\n</code></pre>\n\n<p>I'd recommend one of the following:</p>\n\n<ul>\n<li>Spend a long while learning how to write real object oriented code.</li>\n<li>Give up and convert to procedural code. Skipping all of the wasted classes and <code>new</code>'s</li>\n</ul>\n\n<p>Some people may disagree that I would suggest moving away from object oriented code, but your code is so far away from object oriented that it makes sense to me.</p>\n\n<p><strong>Response to the Edit</strong></p>\n\n<p>It does look a bit better now. It would be a good experience for you to unit test this with PHPUnit. I think you would find it very hard with the <code>static</code> and <code>new</code>. That would give you a motivation to change it further. However, I'm guessing the testing this code will receive will be based on seeing the page on the browser, which is okay for a lot of people.</p>\n\n<p>One comment on the edited version:</p>\n\n<pre><code>// Do you really need the 'remove' parameter to your constructor?\n// Especially when you call the add method on it?\n// Also, objects aren't that special I wouldn't bother with _instance.\n$control_bookmark = new ControlBookmark();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T02:57:52.570",
"Id": "12154",
"Score": "0",
"body": "Thinking about things as if they were hardware is the exact reason that you should write procedural code. Remove all of the classes, they are only getting in your way. If you wanted to write OO you would need to break your system into real world objects and your design would require a lot of change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T03:06:14.920",
"Id": "12156",
"Score": "1",
"body": "Whoever gave my answer a -1, please give your own answer to the OP. I love OO so much that I created the most OO PHP framework in existence. I didn't make my suggestions without thinking about the history of the OP and the code they are working with. Maybe your answer could make me see the error of my ways."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T17:17:28.837",
"Id": "12183",
"Score": "1",
"body": "I disagree. State is not a major part of OO. I would say it was creating real objects that are able to interact while hiding much of their implementation from each other. This allows a program to be split into chunks for each object. Whether an object has a lot of state depends on what the object is. This page http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-concepts/ is a good read and it also hints that PHP is not likely to have many statefull objects. However, I think it depends on each object."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T18:09:40.907",
"Id": "7680",
"ParentId": "7676",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "7680",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:48:05.673",
"Id": "7676",
"Score": "4",
"Tags": [
"php"
],
"Title": "MVC Controller Class"
}
|
7676
|
<p>I'm developing a Rails-based web interface/API for a large, vendor-supplied, legacy Oracle database. One of the constraints is that I can't change the schema other than adding views, because it still has to support the vendor's application.</p>
<p>The table for customer data has a limited number of columns, and extended attributes are stored in customer_def_field_value. These attributes are defined in customer_def_field_def.</p>
<p>so I end up with the classes:</p>
<pre><code>class FieldDef < ActiveRecord::Base
set_table_name 'customer_def_field_def'
set_primary_key :customer_def_field_def_id
set_sequence_name 's_customer_def_field_def'
alias_attribute :field_def_id, :customer_def_field_def_id
has_many :field_values
def symbol
self.title.parameterize('_').to_sym
end
end
class FieldValue < ActiveRecord::Base
set_table_name 'customer_def_field_value'
set_primary_keys :cust_id, :customer_def_field_def_id
set_sequence_name :autogenerated
alias_attribute :field_def_id, :customer_def_field_def_id
belongs_to :customer, :foreign_key => :cust_id
belongs_to :field_def, :foreign_key => :customer_def_field_def_id
end
</code></pre>
<p>In order to get associations on Customer for each of the 'custom fields', I have this code in the Customer class:</p>
<pre><code>FieldDef.find_each do |field|
has_one field.symbol, :class_name => 'FieldValue', :foreign_key => :cust_id, :conditions => proc{ "customer_def_field_def_id = #{field.id}"}
accepts_nested_attributes_for field.symbol
delegate :field_value, :to => field.symbol, :prefix => true
delegate :field_value=, :to => field.symbol, :prefix => true
attr_accessor ('set_' + field.symbol.to_s).to_sym
end
</code></pre>
<p>This works like a charm, but it queries the DB every time a Customer is instantiated in order to generate the method definitions. </p>
<p>It hasn't been a performance issue... <em>yet.</em></p>
<p>New custom field types aren't added very often, so I think I might be able to do this in an initializer rather than in my model, and just restart the application if new fields have to be added... but I wanted to get some feedback. Thanks!</p>
|
[] |
[
{
"body": "<p>I think the query of the database would only happen once in production mode (the class would get cached, in development mode, the class gets reloaded every request that references a Customer object). You can confirm this by setting:</p>\n\n<pre><code>config.log_level = :debug\n</code></pre>\n\n<p>in your production.rb file and seeing if the query runs more than once. It might be worth having an after_save callback for FieldDef that does the same thing as the \"FieldDef.find_each do |field|\" block you have so you don't have to restart the server when new FieldDefs are created.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T05:48:00.223",
"Id": "12430",
"Score": "0",
"body": "Thanks... I'll give this a try. I especially like the idea of using the `after_save` callback to avoid server restarts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T14:16:53.587",
"Id": "12496",
"Score": "0",
"body": "You're absolutely right. The query to generate the associations is only run the first time, when the class is cached. Sadly, the `after_save` callback won't save me from restarting periodically, as new custom fields are usually added from the vendor's application. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T03:23:05.830",
"Id": "7854",
"ParentId": "7682",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7854",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:10:31.763",
"Id": "7682",
"Score": "7",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Dynamic association generation in ActiveRecord"
}
|
7682
|
<p>Currently, in my project I have one class that is dedicated to the all of the queries for the IBM i and converts it into usable models for my .NET code. There is already 12 methods in this class and there <em>will</em> be many, many more to come. This is for a tool that pulls data from our IBM i and pushes it to our internet database server.</p>
<p>Should I split this class up? Should I make it a partial class and put the code across multiple files? Should I do multiple classes?</p>
<p>Just wondering what the best practice is on something like that.</p>
<p>Currently this is the framework I have in place</p>
<pre><code>class IbmIDatabase
{
private DateTime ZERO_DATE = new DateTime(1900, 1, 1, 0, 0, 0);
private string _connString = String.Empty;
SystemCodeRepository scr = new SystemCodeRepository();
/// <summary>
/// Initializes a new instance of the <see cref="IbmIDatabase"/> class.
/// </summary>
public IbmIDatabase()
{
}
#region System Codes
/// <summary>
/// Gets all system codes.
/// </summary>
/// <returns></returns>
public IEnumerable<SystemCode> GetAllSystemCodes()
{
}
#endregion System Codes
#region Citations
/// <summary>
/// Gets all citations.
/// </summary>
/// <returns></returns>
public IEnumerable<ParkingTicket> GetAllCitations()
{
}
#endregion Citations
#region Queue
/// <summary>
/// Gets the queued records.
/// </summary>
/// <returns></returns>
public IEnumerable<QueuedRecord> GetQueuedRecords()
{
}
/// <summary>
/// Marks the queue as processed.
/// </summary>
/// <param name="id">The id.</param>
public void MarkQueueAsProcessed(int id)
{
#endregion Queue
#region Utility Bill Customer
/// <summary>
/// Gets the utility bill customer.
/// </summary>
/// <param name="id">The customer id.</param>
/// <returns></returns>
public Customer GetUtilityBillCustomer(int id)
{
}
/// <summary>
/// Gets the utility bill customer.
/// </summary>
/// <returns></returns>
public IQueryable<Customer> GetUtilityBillCustomer()
{
}
#endregion
#region Utility Bill Details
/// <summary>
/// Gets the customer history.
/// </summary>
/// <param name="id">CustomerId</param>
/// <returns></returns>
public IQueryable<BillHistory> GetCustomerHistory(int id)
{
}
/// <summary>
/// Gets the customer history.
/// </summary>
/// <returns></returns>
public IQueryable<BillHistory> GetCustomerHistory()
{
}
#endregion
#region Utility Bill Payment Details
/// <summary>
/// Gets the customer payment history.
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
public IQueryable<BillPaymentHistory> GetCustomerPaymentHistory(int id)
{
}
/// <summary>
/// Gets the customer payment history.
/// </summary>
/// <returns></returns>
public IQueryable<BillPaymentHistory> GetCustomerPaymentHistory()
{
}
#endregion
#region Utility Bill Summary
/// <summary>
/// Gets the customer summary.
/// </summary>
/// <param name="id">CustomerId</param>
/// <returns></returns>
public IEnumerable<BillSummary> GetCustomerSummary(int id)
{
}
/// <summary>
/// Gets the customer summary.
/// </summary>
/// <returns></returns>
public IQueryable<BillSummary> GetCustomerSummary()
{
}
#endregion
}
</code></pre>
<p>Within each method can be quite a few lines of code (up to many 100 or so?). I left one of the longest ones so far in the sample code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:29:46.607",
"Id": "12099",
"Score": "1",
"body": "Please post some code (according to the FAQ)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:40:52.330",
"Id": "12101",
"Score": "0",
"body": "Sorry, I missed that. I thought I was within the guidelines since it as a best practice question."
}
] |
[
{
"body": "<p>This class has a well defined role and by keeping it intact you are satisfying the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\">Single Responsibility Principle</a>. So, I would leave it like that. Perhaps you might want to look into how you could refactor some common code out of each method and into a separate utility class, but that's all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:14:49.173",
"Id": "12108",
"Score": "0",
"body": "Even if I have 40 methods in one file? That just seems like a maintenance nightmare in the long run."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:20:04.510",
"Id": "12115",
"Score": "0",
"body": "Why? because of a lot of scrolling up and down? I believe that maintenance gets hampered by spaghetti code, bad/improper dependencies, unclear class roles, state duplication, etc, and not by how many functions you group inside a single file. You should have 100 functions in the class if that is what is required of your class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:22:33.463",
"Id": "12117",
"Score": "1",
"body": "I was just thinking if I use the partial class ability in C#, I could break things apart a bit. Then I would have the files `IbmIDatabase.cs` and `IbmIDatabase.Utilities.cs` and it would be obvious that for utilities related methods, you go in to that file."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:25:38.403",
"Id": "12120",
"Score": "0",
"body": "The partial class feature of C# is primarily intended to aid the development of tools like the Visual Studio Forms Designer. But in any case, if you feel it will simplify things for you, fine. I would not do it because when I am looking for something I would rather have one file to scan rather than two. But that's a matter of personal preference. Keep in mind that you can also use the #region directive to group methods within a single file and collapse/expand the groups as you please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T21:10:31.123",
"Id": "12133",
"Score": "1",
"body": "@MikeWills - break your classes up based on responsibilities, not LOC. If it takes 40 methods to implement one responsibility, then so be it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-03-16T21:39:03.123",
"Id": "37005",
"Score": "0",
"body": "@MikeNakis nails it with this answer. If you are worried about too much scrolling just install addon like Resharper and then you can jump between functions with ALT + \\."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:10:51.727",
"Id": "7686",
"ParentId": "7683",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "7686",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:26:21.247",
"Id": "7683",
"Score": "6",
"Tags": [
"c#",
"classes"
],
"Title": "Should I split class or keep it all in one?"
}
|
7683
|
<p>Parallism is achieved by using a simple call to <code>tbb::parallel_invoke()</code>. However I can't break a speedup factor of x2 (after ~3-4 parallel HW threads), although 8 parallel HW threads are used. Advice on this is highly appreciated.</p>
<pre><code>template<class In>
void insertion_sort(In b, In e) { // pretty standard insertion sort for smaller pieces
for(auto i = b; i != e; ++i) {
auto key = *i;
auto j = i - 1;
for(; j != b - 1 && *j > key; --j)
*(j + 1) = *j;
*(j + 1) = key;
}
}
template <class In>
void merge(In b, In m, In e) { // this is the merger, doing the important job
std::vector<typename In::value_type> left(b, m);
std::vector<typename In::value_type> right(m, e);
// guards for the two ranges
left.push_back(std::numeric_limits<typename In::value_type>::max());
right.push_back(std::numeric_limits<typename In::value_type>::max());
auto itl = std::begin(left);
auto itr = std::begin(right);
while (b != e) {
if(*itl <= *itr)
*b++ = *itl++;
else
*b++ = *itr++;
}
}
template <class In>
void merge_sort(In b, In e) { // serial merge_sort, used for pieces smaller < 500
if(b < e - 1) {
auto dis = std::distance(b, e) / 2;
In m = b + dis;
if(dis > 10) {
merge_sort(b, m);
merge_sort(m, e);
merge(b, m, e);
}
//switch to insertion sort for pieces < 10
else
insertion_sort(b,e);
}
}
template <class In>
void merge_sort_parallel(In b, In e) { // merge_sort parallel
if(b != e - 1) {
auto dis = std::distance(b, e);
In m = b + dis / 2;
if(dis > 500) {
tbb::parallel_invoke([&] () { merge_sort_parallel(b, m); },
[&] () { merge_sort_parallel(m, e); });
}
else {
merge_sort(b, m);
merge_sort(m, e);
}
merge(b, m, e);
}
}
</code></pre>
<p>If something is not understandable, please ask.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:13:30.943",
"Id": "12107",
"Score": "1",
"body": "What is the type and size of the data set that you used in your benchmarks which failed to yield a 2x speedup?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:18:01.220",
"Id": "12113",
"Score": "0",
"body": "@MikeNakis very simple `int`s"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:22:05.863",
"Id": "12116",
"Score": "0",
"body": "Yes, and _how many_?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:26:46.967",
"Id": "12121",
"Score": "0",
"body": "@MikeNakis up to 1 billion, so I think that basic thread overhead is not the case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:32:40.297",
"Id": "12123",
"Score": "0",
"body": "Right. That's what I was getting at. But 1 billion is plenty. Then again, you may still be incurring a lot of thread overhead if you are spawning too many threads to sort very small chunks of that array. So, how about trying a much larger value there where you say `if(dis > 500)`? Say, 50000 or 500000?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:46:02.340",
"Id": "12125",
"Score": "0",
"body": "@MikeNakis I did that to check where the performance wall is, and that didn't help, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:54:08.147",
"Id": "12128",
"Score": "0",
"body": "I see. Hmmm. Hopefully someone else more experienced than me might be able to shed some light on this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T23:14:43.463",
"Id": "12143",
"Score": "1",
"body": "If you have 500 as your cut off for parallelism and you start with 1 Billion integers then you are spawning 2^21 (approx) `threads Jobs` to do parallel work. Is there not some overhead to build and maintain this list? I would limit it to 4 times as many jobs as you have HW threads (a complete guess as a starting point). So lets say 32 then I would make it stop doing parallel sorts after 4 (maybe 5) recursive levels of calling the parallel version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T16:48:10.037",
"Id": "12454",
"Score": "0",
"body": "@LokiAstari Just to make this clear right here, I tested it and it didn't help."
}
] |
[
{
"body": "<p>Maybe you're at a memory bandwidth limit. I've done similar experiments with Java threads on an 8 core machine (2 quad core Xeons). Non-memory tasks scaled very well, but memory intensive tasks did not. Try something more computation just to see if memory is a limiting factor for you, too.</p>\n\n<p>Or, in the same spirit, try to make your code less memory intensive by using a higher optimization level or hand-optimizing. For instance, the inner merge loop appears to do three memory reads each iteration when it could do one (plus one write).</p>\n\n<pre><code> typename In::value_type kl = *itl++;\n typename In::value_type kr = *itr++;\n while (b != e) {\n if(kl <= kr) {\n *b++ = kl;\n kl = *itl++;\n }\n else {\n *b++ = kr;\n kr = *itr++;\n }\n }\n</code></pre>\n\n<p>UPDATE: I tried experimenting with the code myself on 8 cores and found:</p>\n\n<ol>\n<li><p>In debug build, the insertion sort will trigger some asserts because <code>b-1</code> can go off the end of the base vector. I just used <code>std::sort()</code> instead of insertion sort.</p></li>\n<li><p>My above code suggestion doesn't make any difference. Either the compiler or the CPU must already be avoiding the extra fetching I was trying to get rid of.</p></li>\n<li><p>It did make a difference to avoid the <code>push_back</code> calls in <code>merge()</code>. Apparently they cause a reallocation of the vectors. Instead of using a sentinel, I added bounds checking to the merge loop. I guess an alternative would be to use <code>reserve</code> to make the vectors big enough before the copy and append.</p></li>\n<li><p>I also tried parallelizing merge to see if it really was an issue doing it serially. I could only see to split the work into two parts (not recursively) by merging n/2 elements from the beginning and n-n/2 elements from the end in parallel. That didn't make any difference in total timing values, which further supports memory access being the bottleneck (though an error on my part is quite likely).</p></li>\n</ol>\n\n<p>Below is the parallel merge code:</p>\n\n<pre><code> template <class In>\n void merge_partial(In itl, In itle, In itr, In itre, In b, In e, int n, bool le) {\n auto itm = b;\n for (;n != 0;n--){\n if( le ? (*itl <= *itr) : (*itl >= *itr)) {\n *itm++ = *itl++;\n if (itl == itle) { // all the rest from the right\n for (;n != 0;n--)\n *itm++ = *itr++;\n break;\n }\n }\n else {\n *itm++ = *itr++;\n if (itr == itre) { // all the rest from the left\n for (;n != 0;n--)\n *itm++ = *itl++;\n break;\n }\n }\n }\n }\n</code></pre>\n\n<p>...</p>\n\n<pre><code> if(dis > 500) {\n tbb::parallel_invoke([&] () { merge_sort_parallel(b, m); },\n [&] () { merge_sort_parallel(m, e); });\n std::vector<typename In::value_type> left(b, m);\n std::vector<typename In::value_type> right(m, e);\n auto n = std::distance(b, e);\n\n auto itl = std::begin(left);\n auto itle = std::end(left);\n auto itr = std::begin(right);\n auto itre = std::end(right);\n tbb::parallel_invoke(\n [&] () { merge_partial(itl, itle, itr, itre, b, e, n / 2, true); },\n [&] () { merge_partial(reverse_iterator<In>(itle), reverse_iterator<In>(itl),\n reverse_iterator<In>(itre), reverse_iterator<In>(itr), \n reverse_iterator<In>(e), reverse_iterator<In>(b),\n n - n / 2, false); });\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T17:37:03.177",
"Id": "12184",
"Score": "0",
"body": "I do indeed believe it is a cache/memory bandwidth problem. I checked the Intel tbb book, where they have a small chapter about cache and there they do explicitly mention that merge sort is, due to his out of place nature, probably not as good as quicksort for parallism."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-23T10:11:24.973",
"Id": "12821",
"Score": "0",
"body": "thanks, for late edit. Concerning 1), yes I think it should be `auto i = b + 1` in the first loop, that should avoid the potential overtheedge case. Concerning 2), that is indeed quite a bottleneck, didn't think about that in the first place, thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T03:24:45.417",
"Id": "12919",
"Score": "1",
"body": "Note that for larger n, the cache lines for threads might coincide. For ints, which are smaller than cache lines, the serial version automatically performs some pre-fetching, where the parallel version has a chance to trash the pre-fetched values or force single writes that might have been combined in the serial version. Some care to ensure that either threads do not start at the same cache line or wait some time to give the other threads time to move to different cache lines, might help performance. But that's just a theoretical thought, I haven't tried it out yet."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-26T20:28:58.077",
"Id": "13013",
"Score": "0",
"body": "@Sjoerd I would be highly interested in a deeper explanation - mabye in a speratore answer?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T04:38:12.740",
"Id": "7701",
"ParentId": "7684",
"Score": "3"
}
},
{
"body": "<p>It's due to the algorithm itself. After all the stuff you do in parallel, you call merge in serial.</p>\n\n<pre><code>merge(b, m, e);\n</code></pre>\n\n<p>No matter how fast you sort the fragments, there's one big serial merge at the end that only uses one core. In addition, halves get merged on only 2 cores, quarters get merged on only 4 cores, etc.</p>\n\n<p>See this question on Stack Overflow for more detail:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/3969813/which-parallel-sorting-algorithm-has-the-best-average-case-performance\">https://stackoverflow.com/questions/3969813/which-parallel-sorting-algorithm-has-the-best-average-case-performance</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T22:07:59.840",
"Id": "12290",
"Score": "0",
"body": "That happens in the last parts and is like you said a constant(well, not really) factor. However I included them in my calculations and they won't put efficiency up that much. One can observe them quite well from taskmanager."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T14:21:29.820",
"Id": "12327",
"Score": "0",
"body": "If you find and fix other problems, you'll get a somewhat better speed-up, but I think that the algorithm is the biggest limiting factor. If you add more cores, the serial portion will take a higher percentage of the overall time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T04:11:35.200",
"Id": "12543",
"Score": "0",
"body": "That serial portion is only n steps out of n*log2(n) steps. In other words, instead of the ideal n/8 + n/8 + n/8 + n/8 + ... + n/8 steps (repeated log2(n) times), you have n + n/2 + n/4 + n/8 + ... + n/8, which is still about 5x the non-parallel speed (for n=2^20)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T17:35:23.073",
"Id": "12569",
"Score": "0",
"body": "@xan I don't follow your math, but it sounds like you're not thinking about it the right way. Serial takes O(n log n). A perfect algorithm would take O(n/k log n) across k cores. The serial merge at the end takes O(n). How big is O(n) compared to O(n/k log n)? It depends on both n and k obviously - so saying 5x is simplistic. Notice that the slowdown is worse with more cores, and it's more complex when it comes to the size of the collection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T18:05:14.710",
"Id": "12573",
"Score": "0",
"body": "@Craig. I'm thinking about it in terms of the original question involving parallel mergesort for big n and k=8. The 5x speed-up estimate for parallelizing the algorithm (if memory wasn't a bottleneck) comes from using n=2^20 and k=8. Instead of n*log2(n) = 20n steps, the parallel version would take have 4n steps because 4n = n + n/2 + n/4 + n/8 + ... + n/8. The \"...\" is 15 more n/8 terms. 20n to 4n is the 5x speed-up. Bigger n would give a bigger theoretical speed-up, and, sure, it's more complicated if k also varies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T23:25:39.350",
"Id": "12582",
"Score": "0",
"body": "What about the \"ideal\" portion that happens in parallel? That doesn't take n/8 time, it takes n/8 log n/8. If log n is 20 then log n/8 is 17."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T21:58:11.353",
"Id": "7787",
"ParentId": "7684",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:41:52.993",
"Id": "7684",
"Score": "14",
"Tags": [
"c++",
"multithreading",
"c++11",
"sorting",
"mergesort"
],
"Title": "Parallel Merge Sort"
}
|
7684
|
<p>A few days ago I saw <a href="https://stackoverflow.com/questions/8776954/is-there-any-big-advantages-of-having-its-c-developping-applications-running-o">this question</a> on Stack Overflow.</p>
<p>I have tried to make a little demo to show the speed advantage of using 64-bit memory operations compared to 32-bit ones. So I wrote this code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#define MEGABYTES 1024 * 1024
#define MEMORY_SIZE 100
#define LOOPS_START 100
#define LOOPS_STOP 10001
int main (int argc, const char * argv[])
{
clock_t start, stop;
int64_t* big_pile = malloc(MEGABYTES * MEMORY_SIZE * sizeof(char));
for (int loops = LOOPS_START; loops < LOOPS_STOP; loops += 100)
{
start = clock();
for (int i = 0; i < loops; i++)
{
for (int pos = 0; pos < MEGABYTES * MEMORY_SIZE * sizeof(char) / sizeof(int64_t); pos++) {
big_pile[pos] = big_pile[pos] ^ big_pile[pos];
}
}
stop = clock();
double elapsed = (double)(stop - start) / CLOCKS_PER_SEC * 1000;
double average = elapsed / loops;
printf("Loops:\t%i\tElapsed time:\t%f\tAverage:\t%f\n", loops, elapsed, average);
}
free(big_pile);
}
</code></pre>
<p>I compile it under XCode on a MacBook Air running OSX Lion. This allow me to change the build target to 32- or 64-bit. When I run the program (and verify that the program is actually running in the correct <em>bit-mode</em>) I see no real difference in time.</p>
<p>Is this the right way to measure performance difference between 32- and 64-bit?
Is XCode/the compiler playing tricks on me?
Is there anything else wrong?</p>
<p><strong>Note</strong> Sorry for the C. C isn't my native tongue ;-)</p>
<hr>
<h2>Solution findings</h2>
<p>Writing 100 MB memory executing in 64-bit mode using 64-bit integer pointers takes ~47 seconds. Exceuting in 32-bit mode using 64-bit integer pointers takes ~70 seconds. Executing in 32-bit mode using 32-bit integer pointers takes ~90 seconds.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T17:48:26.513",
"Id": "12508",
"Score": "0",
"body": "There may be applications where this kind of loop is the \"bottleneck\". All the serious apps I've seen have call stacks ending, nearly all the time, deep in system code, 3rd-party libraries, or I/O. 64-bitness is totally irrelevant in such code. All it really does is allow addressing memory beyond 4G, or allow random access in humungous files, giving people one less reason not to write piggy code."
}
] |
[
{
"body": "<p>You are using <code>int64_t</code>, so most of your code gets compiled into the same machine code regardless of the bitness of the target. Also, A^A = 0, so the compiler might be optimizing your entire for loop with a single call to <code>memset</code> with zero.</p>\n\n<p>I would recommend that you move different values around instead of xoring the same values together, and I would recommend that you use int32_t for the 32-bit version, and int64_t for the 64-bit version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:38:10.350",
"Id": "12124",
"Score": "0",
"body": "Thank you for the answer. There is a huge difference running with int32_t instead of int64_t when compiled for 32-bit. The obvious (but maybe wrong) assumption is that the compiler don't really do a lot to optimize the code for 64-bit(?). When using a shit-operation instead of the xor there is HUGE differences between the 32- and 64-bit versions no matter what int-type I use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:52:21.207",
"Id": "12126",
"Score": "2",
"body": "(I hope you meant _shift_ operation.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:52:40.163",
"Id": "12127",
"Score": "0",
"body": "That's great. Can you please post your findings for the benefit of those who might read this post in the future?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:54:20.290",
"Id": "12129",
"Score": "0",
"body": "haha - SHIFT-operation - yes ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T21:10:06.227",
"Id": "12132",
"Score": "0",
"body": "I have added the solution findings."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:17:30.550",
"Id": "7689",
"ParentId": "7685",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7689",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T20:02:43.777",
"Id": "7685",
"Score": "3",
"Tags": [
"c",
"performance"
],
"Title": "Comparing 32- and 64-bit"
}
|
7685
|
<p>I am toying with a simple class to inherit from to manage my dynamic resources. I am fairly new to C++, so my "implementation" might be suboptimal. Suggestions how to improve functionality are welcome. There are plenty of <code>cout</code>s for orientation purposes, so feel free to ignore those.</p>
<p>The idea of <code>UObject</code> is to organize objects in a parent hierarchy so that when an element leaves the scope he picks up all dynamic resources without having to worry about forgetting to type <code>delete</code> and get a memory leak.</p>
<p>The <code>UObject</code> is minimalistic; all it will feature in its complete state will be a pointer to a container of children. The <code>std::string name</code> is too just for orientation and will later on be dropped. When a <code>UObject</code> is created, its resource pointer is set to 0. Every time another object is parented, the dynamic resource is created and children put there. When the <code>UObject</code> "dies" it checks whether is has children, and if so, kills them all one by one. The children kill their own children and so on every dynamic resource if picked up along the way.</p>
<p>Header:</p>
<pre><code>class UObject
{
public:
UObject(UObject *parent, const std::string &xname);
~UObject();
std::list<UObject*> *children;
private:
void adopt(UObject *child);
void createRes();
std::string name;
};
</code></pre>
<p>Implementation:</p>
<pre><code>UObject::UObject( UObject *parent /*= 0*/, const std::string &xname) : name(xname)
{
std::cout << "Creating " << name << " Looking for parent... ";
if (parent)
{
parent->adopt(this);
}
else
{
std::cout << "no parent ";
}
children = NULL;
std::cout << name << " created \n" << std::endl;
}
UObject::~UObject()
{
if (children)
{
std::cout << "Children found, deleting... \n";
while(!children->empty())
{
delete children->front();
children->pop_front();
std::cout << "child deleted" << std::endl;
}
delete children;
std::cout << name << " Resource deleted" << std::endl;
}
else
{
std::cout << "No children to delete ";
}
std::cout << name << " has been deleted \n" << std::endl;
}
void UObject::adopt( UObject *child )
{
if (!children)
{
createRes();
}
children->push_back(child);
std::cout << "Child adopted by " << name << std::endl;
}
void UObject::createRes()
{
children = new std::list<UObject*>;
std::cout << "Resource created \n";
}
</code></pre>
<p>A simple test:</p>
<pre><code>int main()
{
UObject obj1(0, "GRANDFATHER");
UObject *pobj2 = new UObject(&obj1, "SON1");
UObject *pobj3 = new UObject(&obj1, "DAUGHTER1");
UObject *pobj4 = new UObject(&obj1, "DAUGHTER2");
UObject *pobj5 = new UObject(pobj2, "GRANDSON1");
UObject *pobj6 = new UObject(pobj3, "GRANDSON2");
UObject *pobj7 = new UObject(pobj3, "GRANDSON3");
UObject *pobj8 = new UObject(pobj2, "GRANDDAUGHTER1");
UObject *pobj9 = new UObject(pobj3, "GRANDDAUGHTER2");
}
</code></pre>
<p>And the console output to indicate all dynamic resources are gone without a single <code>delete</code>:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Creating GRANDFATHER Looking for parent... no parent GRANDFATHER created
Creating SON1 Looking for parent... Resource created
Child adopted by GRANDFATHER
SON1 created
Creating DAUGHTER1 Looking for parent... Child adopted by GRANDFATHER
DAUGHTER1 created
Creating DAUGHTER2 Looking for parent... Child adopted by GRANDFATHER
DAUGHTER2 created
Creating GRANDSON1 Looking for parent... Resource created
Child adopted by SON1
GRANDSON1 created
Creating GRANDSON2 Looking for parent... Resource created
Child adopted by DAUGHTER1
GRANDSON2 created
Creating GRANDSON3 Looking for parent... Child adopted by DAUGHTER1
GRANDSON3 created
Creating GRANDDAUGHTER1 Looking for parent... Child adopted by SON1
GRANDDAUGHTER1 created
Creating GRANDDAUGHTER2 Looking for parent... Child adopted by DAUGHTER1
GRANDDAUGHTER2 created
Children found, deleting...
Children found, deleting...
No children to delete GRANDSON1 has been deleted
child deleted
No children to delete GRANDDAUGHTER1 has been deleted
child deleted
SON1 Resource deleted
SON1 has been deleted
child deleted
Children found, deleting...
No children to delete GRANDSON2 has been deleted
child deleted
No children to delete GRANDSON3 has been deleted
child deleted
No children to delete GRANDDAUGHTER2 has been deleted
child deleted
DAUGHTER1 Resource deleted
DAUGHTER1 has been deleted
child deleted
No children to delete DAUGHTER2 has been deleted
child deleted
GRANDFATHER Resource deleted
GRANDFATHER has been deleted
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:13:04.590",
"Id": "12109",
"Score": "0",
"body": "Why a special class for this purpose? What's wrong with using `std::unique_ptr` (or containers thereof) where needed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:13:42.023",
"Id": "12110",
"Score": "9",
"body": "\"Simple, lightweight, **deterministic** “garbage collection”\" - RAII. Read up on it, single most important idiom in C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:15:20.123",
"Id": "12111",
"Score": "0",
"body": "@KennyTM: Ah I did have that lingering doubt.Please mark it the appropriate migration."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:19:10.797",
"Id": "12112",
"Score": "2",
"body": "Simple, light-weight deterministic memory management **is** C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T00:58:32.170",
"Id": "12146",
"Score": "1",
"body": "If you're going to derive from `UObject` (and I see little point if you aren't) you should make the destructor virtual."
}
] |
[
{
"body": "<p>I would agree with the commenters that smart pointers or other forms of RAII are a more traditional solution and generally to be preferred.</p>\n\n<p>And the virtual destructor <em>is</em> critical, otherwise your derived classes' destructors will never be called -- just the <code>UObject</code> destructor and deallocator.</p>\n\n<p>But let's try to look at this approach \"on its merits\".</p>\n\n<p>An obvious practical downside of the <code>UObject</code> approach is that it not only allows you to skip explicit deletes, it forces you to do so to prevent double deletion. So, each dependent <code>UObject</code> regardless of its fruitful lifetime has to persist in memory until the root object goes out of scope. That transient memory bloat seems like it would limit the usefulness of this approach. In any case, you'd probably want to have a private <code>operator delete</code> to prevent accidents.</p>\n\n<p>Actually, since only heap-allocated objects need a parent, it would seem to make more sense to have the passed parent pointer and the \"adopt\" call in a custom operator new rather than in the constructor. That takes it completely out of the root <code>UObject</code> constructor code path and allows the parent pointer to be asserted non-null for dependent (heap allocated) objects.</p>\n\n<p>Since the entire hierarchy for a given root object is reclaimed essentially at once, the only point to having a hierarchy at all seems to be so that new <code>UObject</code>s can be added by attaching themselves to any visible <code>UObject</code>, so they do not need visibility to the root <code>UObject</code>. In situations where the root object remains visible, there is no benefit to using other <code>UObject</code>s as parents, so the root object may as well be a specialized \"memory pool\" object that implements the adopt and chained deletion. So <code>UObject</code>s would only have to implement a constructor (or <code>operator new</code>). </p>\n\n<p>But even if this \"transitivity\" effect of being able to lose sight of the root object is desired, it doesn't require any kind of <code>std::list</code> fan-out. It could be implemented more efficiently with a single <code>UObject*</code> member that implemented a singly-linked list. Each child <code>UObject</code> could simply insert itself into the chain after its parent and before its youngest sibling (if any). The root object would just have to iterate over the linked list and extract and clear the link (to avoid recursive stack depth issues) before calling delete.</p>\n\n<p>Another factor that distinguishes this solution from the traditional solutions is that it establishes memory management relationships that are managed completely independently of other \"application domain specific\" inter-object references. This appears to be the intent of the approach, that memory resource dependencies be tracked separately and generically in a base class cued solely by constructor calls and unaffected by the dynamics of application domain specific object relationships.</p>\n\n<p>One downside is that <code>UObject</code>s would likely need to avoid being referenced by pointer members of long-lived non-<code>UObject</code>s or by <code>UObject</code>s with longer-lived root objects. The other downside is that a hierarchy of <code>UObject</code>s may well have other relationships whose pointer representations would be largely redundant with their <code>UObject</code> relationships. The corresponding upside to \"smart pointers\" is that the same pointer representation often does double duty as a reference to \"related application information\" and a reference to \"associated memory resources\", which is why they translate \"application domain relationship\" changes into memory management actions. Commensurate memory management is tailored in as a cross-cutting aspect of each dynamic reconfiguration of the objects.</p>\n\n<p><code>UObject</code>s that share a root can freely reference each other through containers of pointers without lifetime issues, but any pointers to the containers from <code>UObject</code>s would still need to be memory managed using traditional methods or the containers used would need to be grafted into the <code>UObject</code> hierarchy as templated subtypes, which might prove clumsy.</p>\n\n<p>BTW, speaking of containers and traditional memory management methods, the piecemeal <code>pop_front</code> deconstruction of a <code>std::list</code> is a little wasteful considering that the list is at end-of-life. A simple iterator would have served, followed by <code>delete</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T09:23:03.113",
"Id": "12165",
"Score": "0",
"body": "Well, isn't the UObject essentially an implementation of RAII? I have plenty to add to my response so I will post an answer, comment space will not suffice... Please see my answer and feel free to elaborate further."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T05:48:40.253",
"Id": "7704",
"ParentId": "7688",
"Score": "4"
}
},
{
"body": "<pre><code> std::list<UObject*> *children;\n</code></pre>\n\n<p>There's not much point in having a pointer to your list. Just put your list in your object. That'll simplify the code because it will be deleted and created automatically. Also, you should probably use a std::vector<>, They std::vector will be faster for anything except inserting/deleting in the middle of the list which you don't do anyways.</p>\n\n<pre><code> std::cout << \"Children found, deleting... \\n\";\n while(!children->empty())\n {\n delete children->front();\n children->pop_front();\n std::cout << \"child deleted\" << std::endl;\n }\n delete children;\n std::cout << name << \" Resource deleted\" << std::endl;\n</code></pre>\n\n<p>Since you are destroying the container anyway, emptying it as you go through it not useful. Instead use a for loop with iterators to delete all the entires.</p>\n\n<p>What are you missing is a way to delete part of your tree. You might say close a window. You want that Window and all its children to be deleted. But that window has a parent. How do you delete that window?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T15:43:27.880",
"Id": "12174",
"Score": "0",
"body": "By calling a delete method I guess. The class is still in the making, there will be additional member functions. Emptying the list upon deletion is pointless indeed. I will investigate migrating the UObject to use a std:vector if the container meets my requirements. For UObject I do not need insertion in the end, but there are UParent and UPolygamist which can be arranged, removed and so on, and as children are aware of their parent in contrast to UObject which is fixed and static and blind as a child, only able to see its own children."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T15:55:13.787",
"Id": "12175",
"Score": "0",
"body": "Even without a delete method I can still create either dynamic UObjects and call delete to kill it and its children or simply have the lifetime managed by the local scope, nevertheless there will also be a method to delete an entire branch."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T15:35:38.953",
"Id": "7711",
"ParentId": "7688",
"Score": "2"
}
},
{
"body": "<p>First let's get to some basics here.</p>\n\n<p>If your plan is to derive anything from UObject it will need a virtual destructor. At present I don't see anything being derived from it, and if needs be you could use a recurring template pattern here so you don't need all your classes to inherit from a single one, which can become a nightmare in multiple-inheritence issues.</p>\n\n<p>In that case you would create a template of some kind of tree that has children:</p>\n\n<p><code>class MyClassA : public TreeObject<MyClassA></code></p>\n\n<p>where TreeObject handles all the parent-child relationships while MyClassA has specifics to how this class is used, and this is called the \"recurring template pattern\". Note that TreeObject template does not need a virtual destructor but would probably have a protected destructor, and MyClassA will only need a virtual destructor itself if it is going to be a base class, i.e. have virtual functions and other classes deriving from it that will be in this tree.</p>\n\n<p>You also need to enforce the \"rule of 3\", i.e. you have overloaded the destructor so you need to handle copy-construction and assignment, and my guess is that your objects will be non-copyable.</p>\n\n<p>Another of your noticeable issues is that your child objects must be created \"on the heap\", i.e. with new. They should therefore also almost certainly have a protected destructor which will automatically enforce this.</p>\n\n<p>My next issue is what happens if you want to destroy a child node because it does not seem possible to mark it deleted in the parent. </p>\n\n<p>My final issue is how you take care of destroying the parent. As we have determined, child nodes can only be destroyed by their parents but this node doesn't have any parents. </p>\n\n<p>Of course, given we have decided that we are going to give the class a protected destructor, we won't be calling \"delete\" on the child but we can give it a method <code>destroy()</code> which will know what to do, i.e. it will be able to inform its parent that it is being deleted and should be removed from the list (but not deleted). Of course this will be a linear action on the parent to find this child.</p>\n\n<p>Note that this is quite hard to handle properly even with smart-pointers. For example, one thing you certainly cannot do is have the parent have a collection of shared_ptr of the children and the children have shared_ptr to the parent or you have a circular reference. A better way to manage it would be a node class that manages the parent-child relationship, and could even contain the list iterator that hosts the child so that when if a child is deleted on its own, it would \"know\" the list node that its parent must remove. The good thing about list nodes is that (1) their iterators remain valid even when you modify the list and (2) they are constant time to remove even when they are in the middle of the list.</p>\n\n<p>Therefore if you are going to delete child nodes, std::list is actually quite a decent collection to use on the parent this time.</p>\n\n<p>In essence, what you are creating is a tree. C++ doesn't have a standard tree collection. (It has <code>std::set</code> and <code>std::map</code> that are implemented with trees but does not expose its tree structure). </p>\n\n<p>A generic tree was proposed on boost back in 2005:</p>\n\n<p><a href=\"http://lists.boost.org/Archives/boost/2005/02/80775.php\" rel=\"nofollow\">http://lists.boost.org/Archives/boost/2005/02/80775.php</a></p>\n\n<p>and it might be worthwhile looking at the discussion that took place in there. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T11:21:38.593",
"Id": "7916",
"ParentId": "7688",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T19:10:08.050",
"Id": "7688",
"Score": "4",
"Tags": [
"c++",
"memory-management"
],
"Title": "Simple, lightweight deterministic \"garbage collection\""
}
|
7688
|
<p>I have a module that builds swing tables based on an <code>Object[][]</code>, then I have another module that queries an SQLite database and returns a <code>ResultSet</code>.</p>
<p>I have written a method that converts the <a href="http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html" rel="nofollow"><code>ResultSet</code></a> to an <code>ArrayList<Object[]></code> first, then further into an <code>Object[][]</code>. The reason I do it this way is because you cannot get the row count from the <code>ResultSet</code> without iterating over it.</p>
<p>I'm wondering if there is a more efficient way to build my <code>Object[][]</code> from the <code>ResultSet</code> without having to iterate over the data twice.</p>
<p>Here is the method that performs the conversion:</p>
<pre><code>public Object[][] executeQuery(String query) throws SQLException{
ResultSet rs = getResultSet(query);
ResultSetMetaData rsMetaData = rs.getMetaData();
int columnCount = rsMetaData.getColumnCount();
ArrayList<Object[]> result = new ArrayList<Object[]>();
Object[] header = new Object[columnCount];
for (int i=1; i <= columnCount; ++i){
Object label = rsMetaData.getColumnLabel(i);
header[i-1] = label;
}
while (rs.next()){
Object[] str = new Object[columnCount];
for (int i=1; i <= columnCount; ++i){
Object obj = rs.getObject(i);
str[i-1] = obj;
}
result.add(str);
}
int resultLength = result.size();
Object[][] finalResult = new Object[resultLength][columnCount];
finalResult[0] = header;
for(int i=1;i<resultLength;++i){
Object[] row = result.get(i);
finalResult[i] = row;
}
return finalResult;
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, you could just call the <a href=\"http://docs.oracle.com/javase/6/docs/api/java/util/List.html#toArray%28T%5B%5D%29\"><code>toArray</code></a> method of your list to transform the list into an array. Or even better, you could make the table model use a <code>List<Object[]></code> rather than an <code>Object[][]</code>, which would avoid the unnecessary conversion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:10:49.963",
"Id": "12118",
"Score": "0",
"body": "+1 `toArray` does the same thing as the posted code, but better. You can actually get the row count by doing another query first, but it's definitely not worth it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:16:19.907",
"Id": "12119",
"Score": "0",
"body": "Yeah, I looked at using another query to get the row count, but I came to the same conclusion."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:06:58.810",
"Id": "7692",
"ParentId": "7690",
"Score": "10"
}
},
{
"body": "<p>I agree with <em>@JB Nizet</em>, some other notes about the current implementation:</p>\n\n<ol>\n<li><p>Use the <code>List</code> interface as reference type instead of the implementation type. I mean change</p>\n\n<pre><code>ArrayList<Object[]> result = ...\n</code></pre>\n\n<p>to</p>\n\n<pre><code>List<Object[]> result = ...\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/2279030/type-list-vs-type-arraylist-in-java\">Type List vs type ArrayList in Java</a></p></li>\n<li><p>I'd change the indexing in the for loops:</p>\n\n<pre><code>for (int i = 0; i < columnCount; ++i) {\n final Object label = metaData.getColumnLabel(i + 1);\n header[i] = label;\n}\n</code></pre>\n\n<p>I think <code>for (i = 0; i < max; i++)</code> style looks more familiar for most programmers.</p></li>\n<li><p>I'd extract out a <code>getHeaders</code> method:</p>\n\n<pre><code>private Object[] getHeaders(final ResultSetMetaData metaData) throws SQLException {\n final int columnCount = metaData.getColumnCount();\n final Object[] header = new Object[columnCount];\n for (int i = 0; i < columnCount; ++i) {\n final Object label = metaData.getColumnLabel(i + 1);\n header[i] = label;\n }\n return header;\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T21:54:59.497",
"Id": "7874",
"ParentId": "7690",
"Score": "3"
}
},
{
"body": "<p>I think there is a bug where we lose the first record of data</p>\n\n<blockquote>\n<pre><code>int resultLength = result.size();\n</code></pre>\n</blockquote>\n\n<p>should be <code>int resultLength = result.size()+1;</code></p>\n\n<blockquote>\n<pre><code>Object[] row = result.get(i);\n</code></pre>\n</blockquote>\n\n<p>should be <code>Object[] row = result.get(i-1);</code> </p>\n\n<p>Here's the fix:</p>\n\n<pre><code>int resultLength = result.size()+1;\nObject[][] finalResult = new Object[resultLength][columnCount];\nfinalResult[0] = header;\nfor(int i=1;i<resultLength;++i){\n Object[] row = result.get(i-1);\n finalResult[i] = row;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-05T14:54:17.003",
"Id": "168487",
"Score": "1",
"body": "ResultSet is 1 based."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-07T04:10:12.673",
"Id": "59339",
"ParentId": "7690",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7692",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T16:02:59.017",
"Id": "7690",
"Score": "7",
"Tags": [
"java",
"collections",
"jdbc"
],
"Title": "Module for building swing tables"
}
|
7690
|
<p><strong>Table Structure</strong></p>
<blockquote>
<p>ApprovalOrder int </p>
<p>EntityCode varchar </p>
<p>CostCentre varchar</p>
<p>DelegationCode varchar </p>
<p>ProjectCode varchar</p>
<p>RoleGroup varchar</p>
<p>Position varchar</p>
<p>DelegationText varchar</p>
<p>DelegationAmount money</p>
<p>Active bit</p>
</blockquote>
<p><strong>Query / Explanation</strong> </p>
<p>The purpose is to pull all records for a delegation chain and add a new record at the beginning of the approval chain. RowID is used when talking with an external system and is a required part of the returned results.</p>
<p>I'm wondering if there's a better way that I could have constructed this query instead of the approach I took below? Beyond that I'm definitely interested in general performance / formatting suggestions.</p>
<pre><code>/* Define ye values */
declare @role_group as int = 55
declare @position as char(55) = 'Asset Analyst'
declare @delegation_text as int = null
declare @delegation_amount as int = 0
declare @entity as int = 1410
declare @project_code as int = 10022
declare @delegation_code as varchar(10) = 'NC'
select top 1
'1' + cast(@entity as varchar(10)) + @delegation_code as 'RowID' ,
1 as 'ApprovalOrder' ,
@entity as 'EntityCode',
CostCentre as 'CostCentre',
@delegation_code as 'DelegationCode' ,
@project_code as 'ProjectCode' ,
@role_group as 'RoleGroup' ,
@position as 'Position',
@delegation_text as 'DelegationText' ,
@delegation_amount as 'DelegationAmount' ,
Active
from
workflow.delegation_engine
where
EntityCode = @entity
and ProjectCode = @project_code
and DelegationCode = @delegation_code
union
select
de.RowID ,
cast(de.ApprovalOrder as int) + 1 as 'ApprovalOrder' ,
de.EntityCode ,
de.CostCentre ,
de.DelegationCode ,
de.ProjectCode ,
de.RoleGroup ,
de.Position ,
de.DelegationText ,
de.DelegationAmount ,
de.Active
from
(
select
cast(de.ApprovalOrder + 1 as varchar(4))
+ cast(de.EntityCode as varchar(8))
+ cast(de.DelegationCode as varchar(12)) as 'RowID' ,
ApprovalOrder ,
EntityCode ,
CostCentre ,
DelegationCode ,
ProjectCode ,
RoleGroup ,
Position ,
DelegationText ,
DelegationAmount ,
Active
from
workflow.delegation_engine de
) de
where
de.EntityCode = @entity
and de.ProjectCode = @project_code
and de.DelegationCode = @delegation_code
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:00:31.187",
"Id": "12147",
"Score": "0",
"body": "I like the formatting style (i.e. the indentation and separation of each condition onto its own line), but (without trying to execute it) I don't see the purpose of the subquery."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:04:51.753",
"Id": "12148",
"Score": "0",
"body": "@Dr.Wily'sApprentice Ah, a bi-product of cutting it down for posting. The full query orders by RowID and the only way to do that (to the best of my knowledge) is by using the sub-query"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:06:49.537",
"Id": "12149",
"Score": "0",
"body": "You can do `order by 1, 2, 3` to say \"order by the first column, then the second, then the third\". You should be able to use that to order by your calculated column so that you don't have to use the subquery. Also, I would suggest considering adding an actual \"RowID\" [computed column](http://msdn.microsoft.com/en-us/library/ms191250.aspx) to the table schema."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:27:36.663",
"Id": "12151",
"Score": "0",
"body": "@Dr.Wily'sApprentice That's a very good point actually - hadn't considered that, had the rigid idea in my head that I had to sort by RowID. Thank-you."
}
] |
[
{
"body": "<p>My suggestion is to create a \"RowID\" <a href=\"http://msdn.microsoft.com/en-us/library/ms191250.aspx\" rel=\"nofollow\">computed column</a> on the workflow.delegation_engine table.</p>\n\n<pre><code>ALTER TABLE workflow.delegation_engine ADD [RowID] AS\n cast(de.ApprovalOrder + 1 as varchar(4))\n + cast(de.EntityCode as varchar(8))\n + cast(de.DelegationCode as varchar(12))\n</code></pre>\n\n<p>Your comment indicates that you might be ordering the query on this column. In that case, you might also want to <a href=\"http://msdn.microsoft.com/en-us/library/ms189292.aspx\" rel=\"nofollow\">apply an index on this column</a>. I haven't tried this out, so I don't know for sure whether an index on this column is allowed, but I think it does satisfy all of the requirements.\n<hr>\nAlso, you might want/need to pad your values with leading zeros in order to ensure that your calculated RowID is unique. In that case, you might want to try the following:</p>\n\n<pre><code> right('0000' + cast(de.ApprovalOrder + 1 as varchar(4)), 4)\n + right('00000000' + cast(de.EntityCode as varchar(8), 8)\n + right('000000000000' + cast(de.DelegationCode as varchar(12), 12)\n</code></pre>\n\n<p>This would provide uniqueness and would preserve ordering (i.e. ApprovalOrder 10 comes after ApprovalOrder 2). If you don't care about ordering, then you might not need the leading zeros; you could just insert delimiters to ensure uniqueness.</p>\n\n<pre><code> cast(de.ApprovalOrder + 1 as varchar(4))\n + '|' + cast(de.EntityCode as varchar(8))\n + '|' + cast(de.DelegationCode as varchar(12))\n</code></pre>\n\n<p>This would protect against a scenario where one row has ApprovalOrder: 1, EntityCode: 'ABC', DelegationCode: 'DEF' and another row has ApprovalOrder: 1, EntityCode: 'AB', DelegationCode: 'CDEF'. In that case, the RowID for both rows would be '2ABCDEF'. Adding the delimiters ensures that the first row would have RowID: '2|ABC|DEF' and the second row would have RowID: '2|AB|CDEF'.</p>\n\n<p><hr>\nAlternatively, if you can't or don't want to put a \"RowID\" computed column on the table, then you should be able to just structure the query as shown below. Note that I've included an \"order by\" clause that was left out of the original query. Comments indicate that the reason for the subquery in the original query was to order by the \"RowID\" column. The <code>order by 1</code> clause in the query below accomplishes the same result.</p>\n\n<pre><code>select\n cast(de.ApprovalOrder + 1 as varchar(4))\n + cast(de.EntityCode as varchar(8))\n + cast(de.DelegationCode as varchar(12)) as 'RowID' ,\n cast(de.ApprovalOrder as int) + 1 as 'ApprovalOrder' ,\n de.EntityCode ,\n de.CostCentre ,\n de.DelegationCode ,\n de.ProjectCode ,\n de.RoleGroup ,\n de.Position ,\n de.DelegationText ,\n de.DelegationAmount ,\n de.Active \nfrom\n workflow.delegation_engine de\nwhere \n de.EntityCode = @entity\n and de.ProjectCode = @project_code\n and de.DelegationCode = @delegation_code\norder by\n 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:26:45.463",
"Id": "12150",
"Score": "0",
"body": "I agree on both points and have raised this with the dba team previously. Unfortunately this hasn't happened yet so my plan is to implement my code using this query, then refer to them for performance issues (knowing that their first point of call will be indexes, only made possible by making this a computed column). Office politics - blargh!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:30:26.613",
"Id": "12152",
"Score": "0",
"body": "@Michael - I understand your pain! Well, a potential alternative is to create a view that includes the RowID column. I believe that an index can be applied to a view, so that might be another way to circumvent performance issues without modifying the actual table structure."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:17:45.887",
"Id": "7697",
"ParentId": "7694",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "7697",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T22:30:01.850",
"Id": "7694",
"Score": "5",
"Tags": [
"performance",
"sql",
"sql-server",
"t-sql"
],
"Title": "Adding a new record to the beginning of the approval chain from the delegation chain"
}
|
7694
|
<p>This is my first attempt at writing something in JavaScript besides a few Project Euler problems I did first. It's intended to be a library used client side and server side (both of which I know very little about). I've read Crockford's <em>Javascript: The Good Parts</em>, but nothing else. I have the most current experience with Python. </p>
<p>I'd appreciate any feedback (especially style concerns), I know there's a terrifically large amount of stuff to address, so if that's overwhelming, I have these immediate concerns:</p>
<ul>
<li>By using closure with my <code>country</code> object, am I wasting memory, and hence should be using prototypical inheritance?</li>
<li>My JSONify code seems redundant, I assume there's a more correct way to do this?</li>
<li>Mixing private instance variables like "countries" and public instance variables looks ugly. Is that how it's supposed to be done?</li>
</ul>
<p><a href="https://github.com/thomasballinger/jsrisk/commit/766011c6a485e231476d325118f0f12ef8f745b9" rel="nofollow">Full code available</a>, link is to the commit which brings that code up to date with what I've posted here. There's a larger object (250 lines) I would love to post if that's not excessive, but for now here's the smaller object. (50 lines)</p>
<pre><code>var country = function(name, connected_to){
// variables in constructor signature are private
// These are private variables that weren't in the constructor signature
var helper = function(player, num_troops){
// These are public methods
return {
'get_name' : function(){return name},
'get_troops' : function(){return num_troops;},
'get_owner' : function(){return player;},
'get_touching_names' : function(){return connected_to},
'is_owned_by' : function(in_player){return in_player == player},
'is_touching' : function(to){
if (!(typeof to === 'string')){
to = to.get_name();
}
for (var i = 0; i < connected_to.length; i++){
if (connected_to[i] === to){
return true;
}
}
return false;
},
'set_state' : function(in_player, in_num_troops){
player = in_player;
num_troops = in_num_troops;
},
'toString' : function(){
return '[country '+name+']';
},
'get_ascii' : function(){
return name + ' owned by ' + player + ' with '+ num_troops +
'\n connected to ' + connected_to;
},
'jsonify' : function(){
var j = {
'name' : name,
'player' : player,
'num_troops' : num_troops,
'connected_to' : connected_to
}
return j;
},
'dejasonify' : function(j){
name = j.name;
player = j.player;
num_troops = j.num_troops;
connected_to = j.connected_to;
}
};
};
return helper(null, null)
};
</code></pre>
|
[] |
[
{
"body": "<p>If you stop worrying about "privates" everything becomes much cleaner.</p>\n<blockquote>\n<p>By using closure with my "country" object am I wasting memory, and hence should be using prototypical inheritance?</p>\n</blockquote>\n<p>The closure is a small performance hit. For a board game it won't matter. But if you decide not to use local variables in closures (AKA "privates") then you can get rid of the closure and use a constructor function / prototype.</p>\n<p>One benefit of doing that is that it will give tools like eclipse, webkit inspector, etc. a clue as to how things are represented in your code so they can annotate stuff for you, provide pop-up help, autocompletion, things like that.</p>\n<blockquote>\n<p>My jsonify code seems redundant, I assume there's a more correct way to do this?</p>\n<p>Mixing private instance variables like "countries" and public instance variables looks ugly, is that how it's supposed to be done?</p>\n</blockquote>\n<p>Getting rid of "privates" and making these all properties would be the easiest way to fix both of these issues. In that case the <code>get_*</code> functions could also go.</p>\n<p>A few other points:</p>\n<ul>\n<li><p>Usually javascript identifiers are written as camelCase, not underscore_separated.</p>\n</li>\n<li><p>The quotes around the property names in the object literal are not needed for character sequences that would otherwise be valid identifiers.</p>\n</li>\n<li><p><code>to</code> is a confusing variable name, try to find something more descriptive. I changed it to <code>country</code> in the example below.</p>\n</li>\n</ul>\n<hr />\n<p>I would probably write it something like this:</p>\n<pre><code>function Country (name, connectedTo){\n this.name = name;\n this.connectedTo = connectedTo;\n // other constructor stuff...\n}\n\nCountry.prototype = {\n \n // default properties\n \n numTroops: 0,\n\n player: null,\n \n // functions\n \n isOwnedBy: function(inPlayer){\n return inPlayer == this.player;\n },\n isTouching: function(country){\n // best to avoid typeof if possible\n if (country.name){ \n country = country.name;\n }\n // this performs somewhat better than evaluating foo.length every iteration\n for (var i = 0, len = this.connectedTo.length; i < len; i++){\n if (this.connectedTo[i] === country){\n return true;\n }\n }\n return false;\n },\n setState: function(inPlayer, inNumTroops){\n this.player = inPlayer;\n this.numTroops = inNumTroops;\n },\n toString: function(){\n return '[country '+this.name+']';\n },\n getAscii: function(){\n return this.name + ' owned by ' + this.player + ' with '+ this.numTroops +\n '\\n connected to ' + this.connectedTo;\n }\n};\n</code></pre>\n<hr />\n<p>If <code>setState</code> is only called once per object, you might consider making that code part of the constructor and getting rid of <code>setState</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T02:30:17.890",
"Id": "12153",
"Score": "0",
"body": "Thanks! Coming from Python, I can certainly get into not worrying about keeping things private."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T03:04:48.597",
"Id": "12155",
"Score": "0",
"body": "Yeah, in general you shouldn't worry about it. You could use this approach together with a closure if you want, just return `Country` from the closure and assign the result to a variable with the same name. But you'd generally only do that if you were building an API or something where you wanted to keep some things out of your objects to avoid confusing users. Of course, functional programming (essentially functions returning functions) is another case where you need closures."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T03:34:21.777",
"Id": "12158",
"Score": "0",
"body": "I'll continue to use closure with my larger object I didn't post which implements the game, but it'll be prettier now thanks to this answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T03:47:29.900",
"Id": "12159",
"Score": "0",
"body": "Ah, and I'm use `JSON.stringify` instead of a custom jsonify method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T04:24:58.310",
"Id": "12160",
"Score": "0",
"body": "Yeah, but your jsonify didn't convert it to a json string... I thought you were just preparing an object to be stringified by `JSON.stringify`. But doing it this way you don't need to prepare an object, because instances of Country already have all the properties you want, so you can just stringify them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T04:25:06.047",
"Id": "12161",
"Score": "0",
"body": "https://github.com/thomasballinger/jsrisk/commit/4f80c6a7dd14ab67667411c63886b12788b56939\nhttps://github.com/thomasballinger/jsrisk/commit/c9e9ce66f08eceb7362a5063b198d39dd28d3d3a these two commits inspired by, and dedicated to, GGG"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:53:52.363",
"Id": "7698",
"ParentId": "7696",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7698",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T01:00:30.703",
"Id": "7696",
"Score": "4",
"Tags": [
"javascript",
"game"
],
"Title": "Risk board game - best practices, private vs public variables and methods"
}
|
7696
|
<pre><code>public double getValueWithPercentage(double number, double percentage)
{
return number + ((percentage / 100.0) * number);
}
</code></pre>
<p>Are there any tricks to optimize this simple code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T23:49:37.733",
"Id": "12162",
"Score": "5",
"body": "What lead you to believe that this method may need optimising?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T23:53:08.430",
"Id": "12163",
"Score": "1",
"body": "are you talking about performance optimization, or precision increase? which are the variable ranges?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T20:27:05.017",
"Id": "12196",
"Score": "0",
"body": "I think it's worth noting a few things. 1. Multiplication is faster than division. 2. Bitshifting, or Bitwise operations, will not be faster since [most compilers perform this for you](http://stackoverflow.com/questions/1168451/is-shifting-bits-faster-than-multiplying-and-dividing-in-java-net) 3. Unless you are working with VERY large numbers, aka BigInteger, you won't see improvements with multiplication algorithms like [Schönhage–Strassen](http://en.wikipedia.org/wiki/Sch%C3%B6nhage%E2%80%93Strassen_algorithm)."
}
] |
[
{
"body": "<p>Since floating-point divide is sometimes a little slower than multiply (and never faster, AFAIK), I'd write your function like this:</p>\n\n<pre><code>public double getValueWithPercentage(double number, double percentage)\n{\n return number * (1 + percentage * 0.01);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T23:53:42.570",
"Id": "7703",
"ParentId": "7702",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "7703",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-11T23:46:38.253",
"Id": "7702",
"Score": "6",
"Tags": [
"java",
"optimization"
],
"Title": "Can this simple percentage calculator be further optimized?"
}
|
7702
|
<p>I've been struggling with concurrent programming in Haskell for a while. It's so hard to reason about, especially when exceptions come into the picture.</p>
<p>As a learning exercise, I implemented a simple chat server. Clients connect using telnet on port 1337, and start typing text. Each message is broadcast to all connected clients. Clients are distinguished by an incrementing counter.</p>
<p><sub>Requires the <a href="http://hackage.haskell.org/package/stm-linkedlist">stm-linkedlist</a> package</sub></p>
<pre><code>import Control.Concurrent
import Control.Concurrent.STM
import Control.Exception as E hiding (handle)
import Control.Monad
import Network
import Data.STM.LinkedList (LinkedList)
import System.IO
import qualified Data.STM.LinkedList as LL
type Client = TChan String
main :: IO ()
main = do
clients <- LL.emptyIO
sock <- listenOn (PortNumber 1337)
let loop n = do
(handle, host, port) <- accept sock
putStrLn $ "Accepted connection from " ++ host ++ ":" ++ show port
_ <- forkIO $ serve clients handle n
loop $! n+1
in loop 0
serve :: LinkedList Client -> Handle -> Integer -> IO ()
serve clients handle n = do
hSetBuffering handle LineBuffering
send_chan <- newTChanIO
receiver <- myThreadId
let sendLoop = forever $
atomically (readTChan send_chan) >>= hPutStrLn handle
receiveLoop = forever $ do
line <- hGetLine handle
broadcast $ "<client " ++ show n ++ ">: " ++ line
broadcast message =
atomically $ LL.toList clients >>= mapM_ (flip writeTChan message)
start = do
node <- atomically $ LL.append send_chan clients
sender <- forkIO $ sendLoop `onException` killThread receiver
return $ do
atomically $ LL.delete node
killThread sender
in bracket start (\finish -> finish) (\_ -> receiveLoop)
</code></pre>
<p>One hurdle is that I can't send and receive simultaneously in the same thread. Thus, I'm forced to send and receive in separate threads.</p>
<p>In the code below, I spawn two threads per client:</p>
<ul>
<li><p>A "receive" thread, which gets lines from the client and broadcasts them.</p></li>
<li><p>A "send" thread, which reads this client's <a href="http://hackage.haskell.org/packages/archive/stm/latest/doc/html/Control-Concurrent-STM-TChan.html">TChan</a> (written to by "receive" threads) and sends each message to the client.</p></li>
</ul>
<p>Using a <code>TChan</code>, rather than having other threads write directly to this thread's <code>Handle</code>, has two benefits:</p>
<ul>
<li><p>If sending produces an exception, it doesn't kill the innocent sending client's thread. It only kills the "send" thread of the target client.</p></li>
<li><p>It keeps message text from getting interleaved.</p></li>
</ul>
<p>When the "receive" thread hits an exception, its finalizer removes the client's send channel from the linked list and kills the "send" thread. When the "send" thread hits an exception, it kills the "receive" thread, causing its finalizer to be invoked.</p>
<hr>
<p>Is this a good approach? Is there a better way to organize network code like this?</p>
|
[] |
[
{
"body": "<blockquote>\n <p>One hurdle is that I can't send and receive simultaneously in the same thread. Thus, I'm forced to send and receive in separate threads.</p>\n</blockquote>\n\n<p>Naturally. This is because \"send\" and \"receive\" for a chat server behave asynchronously, and block on different events. Haskell's threads are lightweight, so you can write your code using blocking calls and multiple threads, and rest assured that behind the scenes Haskell is using <code>epoll</code>.</p>\n\n<p>You could modify the chat server so that the client is required to give a special command in order to read new messages, in that case only one thread would be needed, since all messages from you to the client would depend directly on that particular client's input. But then it wouldn't feel much like a chat program.</p>\n\n<blockquote>\n <p>[Haskell] so hard to reason about, especially when exceptions come into the picture.</p>\n</blockquote>\n\n<p>Exceptions are best avoided in Haskell, but you seem to have been able to reason about them fairly well. Did you have any specific issues reasoning about your code? I think it might be fair to replace [Haskell] with [Concurrent programming]; exceptions and concurrency are inherently at odds, in any language.</p>\n\n<blockquote>\n <p>Is this a good approach? Is there a better way to organize network code like this?</p>\n</blockquote>\n\n<p>I think it's pretty good. I don't do much networking code so take my opinion with a grain of salt.</p>\n\n<p>Clearly this is just some simple example code, but you might want to consider allowing the client to send a special message to stop interacting with the server, so that disconnecting is not entirely dependent on exceptions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:34:55.473",
"Id": "7717",
"ParentId": "7705",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T06:03:55.540",
"Id": "7705",
"Score": "12",
"Tags": [
"multithreading",
"haskell"
],
"Title": "Simple chat server in Haskell"
}
|
7705
|
<p><a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> is a free collection of mathematical programming problems of varying difficulty. Only the solution of a problem needs to be submitted, so the challenge is language agnostic. As a general rule (although it is not enforced in any way), a program shouldn't take longer than one minute to solve a problem. Often problems deal with huge numbers in order to make brute force solutions impossible. The page contains a forum for discussions.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:23:58.017",
"Id": "7715",
"Score": "0",
"Tags": null,
"Title": null
}
|
7715
|
Project Euler is a collection of mathematical programming problems of varying difficulty.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:23:58.017",
"Id": "7716",
"Score": "0",
"Tags": null,
"Title": null
}
|
7716
|
<p>This file takes a user picture upload and converts two pictures which are named according to the Session ID.</p>
<p>Right now he biggest drawback is that you cannot crop the image at upload time like you can on popular sites like Facebook. </p>
<p>However I'm just looking for overall constructive criticism on the structure of the class. The paths to save the files to are constants.</p>
<p>I thought about breaking it up in to two classes but I want to stick with just one.</p>
<pre><code> <?php
/**
* Module : Model
* Name : Upload
* Input : File Information
* Output : Resized Files in .jpg format
* Notes :
resizeMove() - resizes the picture to $maxMedium and $maxSmall and moves the file to a permanent location.
makeDimensions() - calculates the dimensions of the new images so that there is not distortion if possible.
getImage() - creates a php image for manipulation.
updateSessionAndDb - updates the mysql table - move out.
*/
class Upload
{
private $originalWidth,
$originalHeight,
$newWidth,
$newHeight,
$maxMedium = 50,
$maxSmall = 20;
private $src = NULL;
private
$fileType,
$fileName,
$sessionId,
$path_medium,
$path_small;
function __construct($fileType, $fileName)
{
$this->sessionId = Session::get('id');
$this->path_medium = Constant::PICTURES . "$this->sessionId.jpg";
$this->path_small = Constant::PICTURES . "$this->sessionId-1.jpg";
$this->fileType = $fileType;
$this->fileName = $fileName;
}
private function createImages()
{
if(move_uploaded_file($this->fileName, $this->path_medium))
{
if($this->getImage($this->path_medium))
{
list($this->originalWidth,$this->originalHeight)=getimagesize($this->path_medium);
$this->resizeMove($this->maxMedium,$this->path_medium);
$this->resizeMove($this->maxSmall,$this->path_small);
imagedestroy($this->src);
}
}
}
private function resizeMove($max, $path)
{
$this->makeDimensions($max);
$image_true_color = imagecreatetruecolor($this->newWidth, $this->newHeight);
imagecopyresampled($image_true_color, $this->src, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->
originalWidth, $this->originalHeight);
imagejpeg($image_true_color, $path);
imagedestroy($image_true_color);
}
private function makeDimensions($max)
{
$this->newWidth=$this->originalWidth;
$this->newHeight=$this->originalHeight;
if(($this->originalWidth > $this->originalHeight) && ($this->originalWidth > $max))
{
$this->newWidth = $max;
$this->newHeight = ($max / $this->originalWidth) * $this->originalHeight;
}
elseif($this->originalHeight > $this->originalWidth && $this->originalHeight > $max)
{
$this->newHeight = $max;
$this->newWidth = ($max / $this->originalHeight) * $this->originalWidth;
}
elseif ($this->originalWidth > $max)
{
$this->newWidth = $this->newHeight = $max;
}
}
private function getImage($path)
{
$type_creators = array(
'image/gif' => 'imagecreatefromgif',
'image/pjpeg' => 'imagecreatefromjpeg',
'image/jpeg' => 'imagecreatefromjpeg',
'image/png' => 'imagecreatefrompng');
if(array_key_exists($this->fileType, $type_creators))
{
$this->src = $type_creators[$this->fileType]($path);
return true;
}
return false;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>With this piece of code you are almost beginning to write good OO. Its good to see you are trying to hide implementation details from other classes.</p>\n\n<p>However, what you have here is a constructor that does everything. The constructor should do no more than initialize the object. Have faith that once you have created your object you can then call its public methods to let the object do what needs to be done.</p>\n\n<p>Think about what an \"Upload\" object is? The resize move could be a good interace to the rest of the system (that is the essence of uploading)? What else should an \"Upload\" object be responsible for? Make those things that the object should be responsible for public methods so that other objects can call them.</p>\n\n<p>Updating the session here seems a little odd is that part of uploading?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T18:02:49.857",
"Id": "12188",
"Score": "0",
"body": "The 5 assignments I make to my private member variables in the constructor I consider initialization. It is even commented as such in the code...so I'm guessing you don't consider this intitialization....why not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T01:31:00.597",
"Id": "12214",
"Score": "0",
"body": "No, those 5 assignments are perfect. Its just the instantiate method that I don't think should exist and be called."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T01:43:49.517",
"Id": "12301",
"Score": "0",
"body": "I used to do things like that too, but this is not about a matter of preference. By having no callable methods this boils down to a fancy way of calling a function. Look at it closely, the way you have it - it is completely procedural. It is just the equivalent of a function call (and if you are going to write it like that just use a function rather than pretending to have real objects). You are not gaining any of the benefits of OO. The benefit of OO is not to use 1 line where you could use 2. The benefit is breaking the program into components with objects."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T17:41:11.793",
"Id": "7721",
"ParentId": "7718",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7721",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T16:35:36.410",
"Id": "7718",
"Score": "3",
"Tags": [
"php"
],
"Title": "Image Upload Class"
}
|
7718
|
<p>I am writing a few python functions to parse through an xml schema for reuse later to check and create xml docs in this same pattern. Below are two functions I wrote to parse out data from simpleContent and simpleType objects. After writing this, it looked pretty messy to me and I'm sure there is a much better (more pythonic) way to write these functions and am looking for any assistance. I am use lxml for assess to the etree library.</p>
<pre><code>def get_simple_type(element):
simple_type = {}
ename = element.get("name")
simple_type[ename] = {}
simple_type[ename]["restriction"] = element.getchildren()[0].attrib
elements = element.getchildren()[0].getchildren()
simple_type[ename]["elements"] = []
for elem in elements:
simple_type[ename]["elements"].append(elem.get("value"))
return simple_type
def get_simple_content(element):
simple_content = {}
simple_content["simpleContent"] = {}
simple_content["simpleContent"]["extension"] = element.getchildren()[0].attrib
simple_content["attributes"] = []
attributes = element.getchildren()[0].getchildren()
for attribute in attributes:
simple_content["attributes"].append(attribute.attrib)
return simple_content
</code></pre>
<p>Examples in the schema of simpleContent and simpleTypes (they will be consistently formatted so no need to make the code more extensible for the variety of ways these elements could be represented in a schema):</p>
<pre><code><xs:simpleContent>
<xs:extension base="xs:integer">
<xs:attribute name="sort_order" type="xs:integer" />
</xs:extension>
</xs:simpleContent>
<xs:simpleType name="yesNoOption">
<xs:restriction base="xs:string">
<xs:enumeration value="yes"/>
<xs:enumeration value="no"/>
<xs:enumeration value="Yes"/>
<xs:enumeration value="No"/>
</xs:restriction>
</xs:simpleType>
</code></pre>
<p>The code currently creates dictionaries like those show below, and I would like to keep that consistent:</p>
<pre><code>{'attributes': [{'type': 'xs:integer', 'name': 'sort_order'}], 'simpleContent': {'extension': {'base': 'xs:integer'}}}
{'yesNoOption': {'restriction': {'base': 'xs:string'}, 'elements': ['yes', 'no', 'Yes', 'No']}}
</code></pre>
|
[] |
[
{
"body": "<p>Do more with literals:</p>\n\n<pre><code>def get_simple_type(element):\n return {\n element.get(\"name\"): {\n \"restriction\": element.getchildren()[0].attrib,\n \"elements\": [ e.get(\"value\") for e in element.getchildren()[0].getchildren() ]\n }\n }\n\ndef get_simple_content(element):\n return { \n \"simpleContent\": {\n \"extension\": element.getchildren()[0].attrib,\n \"attributes\": [ a.attrib for a in element.getchildren()[0].getchildren() ]\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-30T14:17:29.627",
"Id": "10493",
"ParentId": "7725",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "10493",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T21:06:39.923",
"Id": "7725",
"Score": "0",
"Tags": [
"python",
"parsing",
"xml"
],
"Title": "Python xml schema parsing for simpleContent and simpleTypes"
}
|
7725
|
<p>I have a Rectangle class, of which I have 5-6 vectors for each instance. The main vectors are the center and color of the object, while the secondary vectors represent more or less the north, south, east, and west directions of the rectangle itself. These vectors are used to detect collision by "pointing" outside of the sides of the rectangle to detect collision. I may end up creating more fields of the NW, SW, NE, SE, equivalents as well, but I'd like to know if this is actually a good implementation before I do this. The only <code>Vec2f</code> I have allocated as a pointer is the <code>mWidthHeight</code> vector, which of course is just a representation of the width and the height (x = width, y = height) of the rectangle. </p>
<p>Will this allocate too much memory if there are thousands of these on the screen, or is this an OK (at least) implementation?</p>
<p><strong>Rect.h</strong> </p>
<p><em>Note</em> - I'm debating with the idea of making the N, S, E, W vectors pointers to memory. Is that a good idea, or no?</p>
<pre><code>#pragma once
#include <QGLWidget>
#include <GL/glext.h>
#include <cmath>
#include <QDebug>
#include "Shape.h"
#include "Vec3f.h"
#include "rand.h"
const int DEFAULT_SQUARE_WIDTH = 5;
const int DEFAULT_SQUARE_HEIGHT = 5;
typedef enum {
V2D_NORTH,
V2D_SOUTH,
V2D_EAST,
V2D_WEST
} V2D_DIRECTION;
class Rectangle : public Shape
{
public:
Rectangle(
Vec2f center = Vec2f(),
Vec2f widthheight = Vec2f(DEFAULT_SQUARE_WIDTH, DEFAULT_SQUARE_HEIGHT),
float radius = 0,
Vec3f color = Vec3f()
);
~Rectangle();
inline Vec2f* getWidthHeight() const {
return mWidthHeight;
}
inline Vec2f getDirection(V2D_DIRECTION dir) const {
switch(dir) {
case V2D_NORTH:
return mNorth;
case V2D_SOUTH:
return mSouth;
case V2D_EAST:
return mEast;
case V2D_WEST:
return mWest;
}
}
virtual void Collide( Shape &s );
virtual void Collide( Rectangle &r );
virtual void Collide ( Circle &c );
virtual bool Intersects( const Shape& s ) const;
virtual bool Intersects( const Rectangle& s ) const;
virtual bool IsAlive( void ) const;
virtual float Mass( void ) const;
protected:
virtual void Draw( void ) const;
Vec2f* mWidthHeight;
Vec3f mColor;
private:
Vec2f mNorth;
Vec2f mSouth;
Vec2f mEast;
Vec2f mWest;
void InitDirections();
};
</code></pre>
|
[] |
[
{
"body": "<p>Your constructor arguments and defaults are unusual.\nWhat does radius mean for a Rectangle?\nShould there be an argument for initializing mass?\nI suggest:</p>\n\n<pre><code> static const Vec2f& defaultCenter();\n static const Vec2f& defaultSquareDimensions();\n static const Vec3f& defaultColor();\n\n Rectangle(\n const Vec2f& center = defaultCenter(),\n const Vec2f& widthheight = defaultSquareDimensions(),\n // Assuming rotation angles are supported...\n const Vec2f orientation = defaultOrientation(),\n const Vec3f& color = defaultColor()\n );\n</code></pre>\n\n<p>and/or maybe:</p>\n\n<pre><code> Rectangle(\n const Vec3f& color,\n const Vec2f& center = defaultCenter(),\n const Vec2f& widthheight = defaultSquareDimensions(),\n // Assuming rotation angles are supported...\n const Vec2f orientation = defaultOrientation()\n );\n\n\n\n inline const Vec2f& getWidthHeight() const {\n return mWidthHeight;\n }\n</code></pre>\n\n<p>The static methods can return \"static objects\" that are constructed once each instead of always constructing new temps.</p>\n\n<p>I can't tell what the return value of the following function represents. \nWhat is the north direction vector of a rectangle?\nCan you give examples for different rectangles?\nCan you explain how you would use the returned vector?</p>\n\n<pre><code> inline Vec2f getDirection(V2D_DIRECTION dir) const {\n switch(dir) {\n case V2D_NORTH:\n return mNorth;\n\n case V2D_SOUTH:\n return mSouth;\n\n case V2D_EAST:\n return mEast;\n\n case V2D_WEST:\n return mWest;\n\n }\n }\n</code></pre>\n\n<p>This seemed missing?</p>\n\n<pre><code> virtual bool Intersects( const Circle& s ) const;\n</code></pre>\n\n<p>There should be some good reason not to make these private:</p>\n\n<pre><code> Vec2f mCenter;\n</code></pre>\n\n<p>There seems to be no reason to make this a pointer.\nThere might be an argument for making it const.</p>\n\n<pre><code> Vec2f mWidthHeight;\n Vec2f mOrientation;\n</code></pre>\n\n<p>If rectangles tend to come in a small selection of colors, \nyou may be better off storing an index into a central \npallette vector or possibly a pointer into a pool of shared colors.</p>\n\n<p>There might be an argument for making this const if they don't change color.</p>\n\n<pre><code> Vec3f mColor;\n</code></pre>\n\n<p>The following seem expensive to store and maintain and they also seem like they may be at least partly redundant? If they are redundant (derivable from a smaller set of parameters)\nyou should probably run benchmarks on code that stores these values \nand code that calculates them on the fly as needed.</p>\n\n<pre><code>private:\n Vec2f mNorth;\n Vec2f mSouth;\n Vec2f mEast;\n Vec2f mWest;\n void InitDirections();\n</code></pre>\n\n<p>It may be that there is a better way to express orientation and/or these other values that is more useful in finding intersections.\nIt seems strange to me to be considering even more of these vectors for NW, etc. but I'm not even sure yet what they mean.</p>\n\n<p>To speed up intersection, I thought you MIGHT also want to store \nan additional widthheight representing the bounding box -- the smallest x/y\naligned rectangle that contains this rectangle in its current orientation.</p>\n\n<p>SO MUCH depends on how your actual intersect logic uses all of these values.\nStoring them all and more MIGHT be worthwhile.</p>\n\n<p>CPU vs. memory trade-offs can be very tricky to predict.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:37:02.003",
"Id": "12209",
"Score": "0",
"body": "An afterthought: A single mDirections[V2D_MAX-1] member indexed by V2D_DIRECTIONS would neatly replace mNorth, mSouth, etc.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T12:42:55.283",
"Id": "12479",
"Score": "1",
"body": "WRT using pointers, this will likely make the members a little slower to process, AND will more than double their memory footprint UNLESS you had some way of sharing the actual Vec2f objects among (typically 2 or more) rectangles -- attached rectangles moving in formation? -- OR if somehow most of the Vec2f pointers could typically be kept null."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:01:22.893",
"Id": "7730",
"ParentId": "7727",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-12T21:53:24.537",
"Id": "7727",
"Score": "6",
"Tags": [
"c++",
"memory-management",
"computational-geometry"
],
"Title": "Is this a good algorithm for 2D collision, or will it allocate too much memory?"
}
|
7727
|
<p>I wrote a function (<code>get_last_word_of</code>) that takes a C string and a destination buffer, and then copies the last word into the buffer. The code was originally C++, and was changed into C later.</p>
<pre><code>#include <assert.h>
#include <stdio.h>
#include <string.h>
// Check whether the two values are equal, and print an error if they are not.
void AssertEq(int lhs, int rhs, int line) {
if (lhs != rhs)
printf("Fail: %d != %d (line %d)", lhs, rhs, line);
}
#define ASSERT_EQ(lhs, rhs) do { AssertEq(lhs, rhs, __LINE__); } while (0);
// Given a valid C string pointer, find the index of the last character that
// is not whitespace. If str points to an empty string, return -1.
int find_index_of_last_nonwhitespace(char const* str) {
assert(str && "str must point to a valid C string");
int const length = strlen(str);
// We subtract 1 to skip the null terminator. Seeing as we check p >= str
// before we do anything else, this should be okay even for a str that is empty.
char const* p = str + length - 1;
while (p >= str && *p == ' ')
--p;
return p - str;
}
// Return the index of the beginning last word in the given C string. If the string
// is empty, return 0.
int find_index_of_beginning_of_last_word(char const* str) {
assert(str && "str must point to a valid C string");
int end_of_last_word = find_index_of_last_nonwhitespace(str);
// Subtract 1 so that we have the index of the first letter
char const* p = str + end_of_last_word;
while (p >= str && *p != ' ')
--p;
return p - str + 1; // To compensate for this being the index prior to the word.
}
// Given a destination buffer and a source C string pointer, copy the source
// into the destination until a space or the end of the string is hit.
// The buffer must be large enough to store the word and a \0 character after it.
// If dest == src, simply truncate after the first word.
void wordcpy(char* dest, char const* src) {
assert(src && "src must point to a valid C string");
assert(dest && "dest must point to a valid buffer");
char* d = dest;
char const* s = src;
for ( ; *s != '\0' && *s != ' '; ++s, ++d)
*d = *s;
*d = '\0';
}
// Given a pointer to a C string, and a pointer to an output buffer that is at least
// as large as the last word in the input plus one, copy the last word of the input
// into the output buffer.
void get_last_word_of(char const* input, char* output) {
assert(input && "input must be a valid C string");
assert(output && "output must be a valid buffer");
int index_of_last_word = find_index_of_beginning_of_last_word(input);
wordcpy(output, input + index_of_last_word);
}
int main() {
ASSERT_EQ(find_index_of_last_nonwhitespace("Test "), 3);
ASSERT_EQ(find_index_of_last_nonwhitespace("Test"), 3);
ASSERT_EQ(find_index_of_last_nonwhitespace("Te st "), 4);
ASSERT_EQ(find_index_of_last_nonwhitespace("Te st"), 4);
ASSERT_EQ(find_index_of_last_nonwhitespace(""), -1);
ASSERT_EQ(find_index_of_last_nonwhitespace(" "), -1);
ASSERT_EQ(find_index_of_beginning_of_last_word("Test"), 0);
ASSERT_EQ(find_index_of_beginning_of_last_word("Test "), 0);
ASSERT_EQ(find_index_of_beginning_of_last_word("Test test"), 5);
ASSERT_EQ(find_index_of_beginning_of_last_word("Test test "), 5);
ASSERT_EQ(find_index_of_beginning_of_last_word(""), 0);
ASSERT_EQ(find_index_of_beginning_of_last_word(" "), 0);
char buf[100];
wordcpy(buf, "Hello");
ASSERT_EQ(strcmp(buf, "Hello"), 0);
wordcpy(buf, "Hello ");
ASSERT_EQ(strcmp(buf, "Hello"), 0);
wordcpy(buf, " ");
ASSERT_EQ(strcmp(buf, ""), 0);
return 0;
}
</code></pre>
<p>I'm primarily interested in:</p>
<ol>
<li>What inputs (if any) could cause these functions to perform undefined behaviour?</li>
<li>Are there enough comments?</li>
<li>Is the <code>ASSERT_EQ</code> macro safe to use, and is there any way to let it be used with types other than <code>int</code>? (I used templates in C++, but am at a loss in C.)</li>
<li>Would there be a significant advantage to using <code>size_t</code> instead of <code>int</code> here?</li>
<li>Are the tests sufficient? Are there any cases I missed? Are some unnecessary?</li>
</ol>
<p>Any further nitpicking is of course welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:32:18.427",
"Id": "12208",
"Score": "0",
"body": "`assert(input && \"input must be a valid C string\");` will never fail. If input is false, the string will evaluate to true, no?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:39:40.803",
"Id": "12210",
"Score": "0",
"body": "That's why it's `&&`, not `||`. If `input` is false, the string will never evaluate at all (and even if it does, `false && true` is still `false`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:49:42.457",
"Id": "12212",
"Score": "0",
"body": "Oops, you're right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T01:00:33.260",
"Id": "12213",
"Score": "0",
"body": "OK. Asked and answered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T02:30:42.577",
"Id": "12222",
"Score": "1",
"body": "Been awhile for me and C, but we used to always wrap macro arguments in the replacement part of the macro in parentheses. Why? I think maybe it was in case the argument involved a comma operator, or some such ugliness."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T02:37:01.207",
"Id": "12223",
"Score": "0",
"body": "Whoops! I had actually done that in the first version, and then forgot when I was changing it around a little. Indeed, and it's not just the comma operator -- for example, if `lhs` was `a ? b` and `rhs` was `c : d`, this would give a rather weird error. Thanks for the note. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T03:11:01.483",
"Id": "12224",
"Score": "0",
"body": "So, what does this have to do with defensive programming?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T04:14:47.893",
"Id": "12226",
"Score": "0",
"body": "@Mike Good catch. Either \"defensive programming\" doesn't mean \"promoting your favorite programming language by bashing all rivals\", or somebody has wandered off topic. or? maybe I mean &&."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T04:31:37.870",
"Id": "12229",
"Score": "0",
"body": "Well, the code was half as a reaction to the first chapter of `Code Craft` (which is called *On the Defensive* and covers http://en.wikipedia.org/wiki/Defensive_programming ). (The other half was an IRC question about some code provided by a teacher (can link, but it doesn't look anything like this piece).) PS: Sorry for not accepting an answer yet, still thinking about them -- both are great. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T08:35:29.380",
"Id": "12232",
"Score": "0",
"body": "A maybe silly question but what would be the difference between :\n #define ASSERT_EQ(lhs, rhs) do { AssertEq(lhs, rhs, __LINE__); } while (0);\nand\n #define ASSERT_EQ(lhs, rhs) { AssertEq(lhs, rhs, __LINE__); }\n?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T08:37:29.830",
"Id": "12233",
"Score": "0",
"body": "@Josay: In the second case, the trailing `;` would not be required and would even be warned about on some compilers with some flags set."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T08:57:34.127",
"Id": "12234",
"Score": "0",
"body": "@AntonGolov It's not required in the first case neither, is it ?\n'ASSERT_EQ(strcmp(buf, \"Hello\"), 0);' for instance, will get substituted by\n'do { AssertEq(strcmp(buf, \"Hello\"), 0, __LINE__); } while (0);;' where the second semicolon is (obviously) pointless. Am I missing something ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T09:04:20.033",
"Id": "12235",
"Score": "0",
"body": "@Josay: That's another mistake in the code, it shouldn't have been there. Thanks. :)"
}
] |
[
{
"body": "<p>Found some inputs that could cause wordcpy to perform undefined behaviour. See below.</p>\n\n<p>Enough comments? Pretty close, though some needed tweaking. \nWhat IS lacking is some definition of what is meant by \"word\", \"space\", \"whitespace\" especially as they relate to the presence of punctuation, tabs, newlines, etc.</p>\n\n<p>As for ASSERT_EQ, I'm pretty sure you need separate per-type macros, functions, and format strings in C.</p>\n\n<p>size_t would probably be cleaner for all lengths and offsets, but I don't know of any specific environments where int would be an actual issue. </p>\n\n<p>Are the tests sufficient? Cases missed? I added a few and suggested the shape of a few more. </p>\n\n<p>Are some unnecessary? You never know when you'll break an edge case.</p>\n\n<p>I didn't compile anything, so consider all mods to be c-like pseudo code.</p>\n\n<pre><code>#include <assert.h>\n#include <stdio.h>\n#include <string.h>\n\n// Check whether the two values are equal, and print an error if they are not.\nvoid AssertEq(int lhs, int rhs, int line) {\n if (lhs != rhs)\n</code></pre>\n\n<p>OP had printf(...</p>\n\n<pre><code> fprintf(stderr, \"Fail: %d != %d (line %d)\", lhs, rhs, line);\n}\n\n#define ASSERT_EQ(lhs, rhs) do { AssertEq(lhs, rhs, __LINE__); } while (0);\n\n\n// Given a valid C string pointer, find the index of the last character that\n</code></pre>\n\n<p>OP had ...If str points to an empty string, return -1.</p>\n\n<pre><code>// is not whitespace. If str points to an empty or all-whitespace string, return -1.\nint find_index_of_last_nonwhitespace(char const* str) {\n assert(str && \"str must point to a valid C string\");\n\n int const length = strlen(str);\n\n // We subtract 1 to skip the null terminator. Seeing as we check p >= str\n // before we do anything else, this should be okay even for a str that is empty.\n char const* p = str + length - 1;\n</code></pre>\n\n<p>OP had while (p >= str && *p == ' ')</p>\n\n<pre><code> while (p >= str && isspace(*p))\n --p;\n\n return p - str;\n}\n</code></pre>\n\n<p>OP had ...index of the beginning last word ... is empty, return 0.</p>\n\n<pre><code>// Return the index of the beginning of the last word in the given C string. If the string\n// is empty or all whitespace, return 0.\n</code></pre>\n\n<p>Design Note: It seems a little strange that you get the same 0 result for inputs \"abc\" and \" \"</p>\n\n<pre><code>int find_index_of_beginning_of_last_word(char const* str) {\n assert(str && \"str must point to a valid C string\");\n\n int end_of_last_word = find_index_of_last_nonwhitespace(str);\n</code></pre>\n\n<p>OP had // Subtract 1 so that we have the index of the first letter</p>\n\n<p>(Comment removed -- no subtraction in sight)</p>\n\n<p>Suggestion: add a reassuring comment around here about what happens for an empty/blank input.</p>\n\n<pre><code> char const* p = str + end_of_last_word;\n</code></pre>\n\n<p>OP had while (p >= str && *p != ' ')</p>\n\n<pre><code> while (p >= str && ! isspace(*p))\n --p;\n\n return p - str + 1; // To compensate for this being the index prior to the word.\n}\n</code></pre>\n\n<p>Needs buffer overlap validation -- passed a dest pointer between src+1 and the last character in the first word of src, this will loop forever trashing memory.</p>\n\n<pre><code>// Given a destination buffer and a source C string pointer, copy the source\n// into the destination until a space or the end of the string is hit.\n// The buffer must be large enough to store the word and a \\0 character after it.\n// If dest == src, simply truncate after the first word.\nvoid wordcpy(char* dest, char const* src) {\n assert(src && \"src must point to a valid C string\");\n assert(dest && \"dest must point to a valid buffer\");\n\n char* d = dest;\n char const* s = src;\n</code></pre>\n\n<p>Do we really mean \"space\" or general \"white space\" including \\n \\t, etc.? Up until now, I had been assuming \"white space\" as defined by isspace, so I'm following through, here.</p>\n\n<p>OP had for ( ; *s != '\\0' && *s != ' '; ++s, ++d)</p>\n\n<pre><code> for ( ; *s != '\\0' && ! isspace(*s); ++s, ++d)\n *d = *s;\n\n *d = '\\0';\n}\n</code></pre>\n\n<p>Consistency in argument ordering (and argument naming? dest/output src/input) \nbetween wrdcpy and this function might reduce caller confusion and might improve readability.</p>\n\n<pre><code>// Given a pointer to a C string, and a pointer to an output buffer that is at least\n// as large as the last word in the input plus one, copy the last word of the input\n// into the output buffer.\nvoid get_last_word_of(char const* input, char* output) {\n assert(input && \"input must be a valid C string\");\n assert(output && \"output must be a valid buffer\");\n\n int index_of_last_word = find_index_of_beginning_of_last_word(input);\n wordcpy(output, input + index_of_last_word);\n}\n\nint main() {\n ASSERT_EQ(find_index_of_last_nonwhitespace(\"Test \"), 3);\n ASSERT_EQ(find_index_of_last_nonwhitespace(\"Test\"), 3);\n ASSERT_EQ(find_index_of_last_nonwhitespace(\"Te st \"), 4);\n ASSERT_EQ(find_index_of_last_nonwhitespace(\"Te st\"), 4);\n ASSERT_EQ(find_index_of_last_nonwhitespace(\"\"), -1);\n ASSERT_EQ(find_index_of_last_nonwhitespace(\" \"), -1);\n\n ASSERT_EQ(find_index_of_beginning_of_last_word(\"Test\"), 0);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\"Test \"), 0);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\"Test test\"), 5);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\"Test test \"), 5);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\"\"), 0);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\" \"), 0);\n</code></pre>\n\n<p>Add:</p>\n\n<pre><code> ASSERT_EQ(find_index_of_beginning_of_last_word(\" Test \"), 1);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\" Test\"), 1);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\" Test \"), 2);\n ASSERT_EQ(find_index_of_beginning_of_last_word(\" Test\"), 2);\n</code></pre>\n\n<p>Suggestion: (Re)initialize buf before each test to a distinctive pattern like 'XXXXXX...'\nand validate that buf[strlen(buf)+1] is still 'X'.</p>\n\n<pre><code> char buf[100];\n wordcpy(buf, \"Hello\");\n ASSERT_EQ(strcmp(buf, \"Hello\"), 0);\n wordcpy(buf, \"Hello \");\n ASSERT_EQ(strcmp(buf, \"Hello\"), 0);\n wordcpy(buf, \" \");\n ASSERT_EQ(strcmp(buf, \"\"), 0);\n</code></pre>\n\n<p>Test the claim made in the wordcpy comment that it will just null out the first space when dest == src.</p>\n\n<pre><code> strcpy(buf, \"\");\n strcpy(buf+strlen(buf)+1, \"XYZ\");\n wordcpy(buf, buf);\n ASSERT_EQ(strcmp(buf, \"\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \"XYZ\"), 0);\n\n strcpy(buf, \" \");\n strcpy(buf+strlen(buf)+1, \"XYZ\");\n wordcpy(buf, buf);\n ASSERT_EQ(strcmp(buf, \"\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \"\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+2, \"XYZ\"), 0);\n\n strcpy(buf, \" \");\n strcpy(buf+strlen(buf)+1, \"XYZ\");\n wordcpy(buf, buf);\n ASSERT_EQ(strcmp(buf, \"\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \" \"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+3, \"XYZ\"), 0);\n\n strcpy(buf, \"ABC\");\n strcpy(buf+strlen(buf)+1, \"XYZ\");\n wordcpy(buf, buf);\n ASSERT_EQ(strcmp(buf, \"ABC\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \"XYZ\"), 0);\n\n strcpy(buf, \"ABC XYZ\");\n wordcpy(buf, buf);\n ASSERT_EQ(strcmp(buf, \"ABC\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \"XYZ\"), 0);\n\n strcpy(buf, \"ABC XYZ\");\n wordcpy(buf, buf);\n ASSERT_EQ(strcmp(buf, \"ABC\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \" XYZ\"), 0);\n</code></pre>\n\n<p>Try strange offsets.</p>\n\n<pre><code> strcpy(buf, \"ABC XYZ\");\n wordcpy(buf, buf+2);\n ASSERT_EQ(strcmp(buf, \"C\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \"C XYZ\"), 0);\n\n strcpy(buf, \"ABC XYZ\");\n wordcpy(buf, buf+2);\n ASSERT_EQ(strcmp(buf, \"C\"), 0);\n ASSERT_EQ(strcmp(buf+strlen(buf)+1, \"C XYZ\"), 0);\n</code></pre>\n\n<p>Fix the forever loop before trying these strange offsets.</p>\n\n<pre><code> strcpy(buf, \"ABC XYZ\");\n // Until fixed, this will trash memory with \"ABABAB...\n // wordcpy(buf+2, buf); \n // Assuming this will be caught and do nothing.\n ASSERT_EQ(strcmp(buf, \"ABC XYZ\"), 0);\n</code></pre>\n\n<p>Also, both to show that it works as intended AND to give examples of what you intend, add tests for handling of non-alphabetics, especially common cases like punctuation, tabs, and newlines.</p>\n\n<p>Suggestion: test get_last_word_of</p>\n\n<pre><code> return 0;\n\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T09:27:52.600",
"Id": "12238",
"Score": "0",
"body": "Wow, I hadn't realised just how much I was promising with \"simply truncate\"! I think I'll simply leave that part out; it wasn't my intention to guarantee that much. Thank you for the feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T02:57:10.787",
"Id": "7736",
"ParentId": "7731",
"Score": "4"
}
},
{
"body": "<p>Leaving aside philosophical issues like why do you bother with a language which today is only used for programming micro-controllers the size of a contact lens, and why would you ruin a something written in C++ by converting it to C, I must say that it is a well written piece of code, authored by someone who has a good understanding of what he is doing. (Then again, of course, you really cannot accomplish anything in C unless you have a good understanding of what you are doing.) Notwithstanding that, there are a few issues.</p>\n\n<ol>\n<li>As GregS pointed out, macro arguments need parentheses.</li>\n<li><code>find_index_of_last_nonwhitespace()</code> does not really do what its name says, nor what the comment above it says, because when we say \"whitespace\" we don't only mean the space character. You need to use <code>isspace()</code> from <code>ctype.h</code> to tell if a character is whitespace or not, and this applies to all places in the code that compare against the space character.</li>\n<li>The <code>If dest == src, simply truncate after the first word</code> comment looks like it has been added after the fact, in order to describe what the code will actually do, rather than to specify a requirement for the code. I would suggest that you replace it with a comment saying <code>If dest == src, the behavior is undefined</code>, because if you ever decide to implement that function differently in the future, you don't want to have to do tricks in order to precisely emulate the bizarre functionality of the old version, do you?</li>\n<li>Obviously, <code>get_last_word_of</code> will fail if it is ever given to parse some text containing a word larger than some buffer, and the way it is written precludes the possibility of ever having any control over this so as to prevent it from happening, because the size of the output buffer is not passed as a parameter. In the test code, you would have a failure if you used a word longer than 100 characters. You might say, \"you gotta be kidding, who would ever write a word longer than 100 characters?\" One answer is, my son did, when he was 1.5 years old, and got a hold of my computer while I was in the kitchen, and he typed his first word document by holding the z key down for a couple of minutes and watching the 'z's fly by on the screen. If Microsoft Word was using your code, it would have crashed. Another answer is that this is precisely the kind of stuff that buffer overrun exploits are made of: the hacker will intentionally give the kind of input that the programmer did not expect.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T16:52:14.213",
"Id": "12263",
"Score": "1",
"body": "Some people just enjoy coding in C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:02:56.270",
"Id": "12266",
"Score": "0",
"body": "Well, of course, everyone is entitled to have their own little perversions."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T03:23:07.127",
"Id": "7739",
"ParentId": "7731",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7736",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:11:20.007",
"Id": "7731",
"Score": "3",
"Tags": [
"c",
"strings"
],
"Title": "Defensive programming in C"
}
|
7731
|
<p>My application is for the use of comparing a product sold by several merchants on a daily basis. A process runs to load the current values of data for each store and enters it into a database along with any previous data. Later I plan to create graphs and such off of the history of data.</p>
<pre><code>SELECT `a`.`part_number`, GROUP_CONCAT(`a`.`seller_id` ORDER BY `price` ASC), GROUP_CONCAT(`b`.`part_id` ORDER BY `price` ASC), GROUP_CONCAT(`b`.`price` ORDER BY `price` ASC)
FROM `parts`
LEFT JOIN (
SELECT *
FROM (
SELECT *
FROM `parts_data` AS `tmp_a`
ORDER BY `date_added` DESC
) AS `tmp_b`
GROUP BY `part_id`
) AS `b`
ON `a`.`part_id` = `b`.`part_id`
GROUP BY `a`.`part_number`
</code></pre>
<p>To explain the query a little, I need to select the most recent price information for several <em>part IDs</em> and group them together with a selected <em>part number</em> for comparison. Also, upon concatenation the grouped items are sorted by price to be highest to lowest.</p>
<p>Each part number also can have any number of item IDs associated with it so there is no implication of how many companies are being watched.</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>part_number | column1 | column2 | column3
++++++++++++++++++++++++++++++++++++++++++++++++
| seller:A1 | seller:A3 | seller:A6
153231 | id:x423 | id:x534 | id:x902
| cost:23 | cost:34 | cost:57
++++++++++++++++++++++++++++++++++++++++++++++++
| seller:A3 | seller:A1 | seller:A6
345123 | id:x313 | id:x631 | id:x652
| cost:78 | cost:86 | cost:99
++++++++++++++++++++++++++++++++++++++++++++++++
| seller:A5 | seller:A1 |
231756 | id:x663 | id:x291 |
| cost:35 | cost:52 |
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T04:50:24.450",
"Id": "12230",
"Score": "0",
"body": "The above is horrid in my eyes, but achieves exactly as I need. The nested selects with ORDER and GROUP work appropriately and the query returns the grouped data in the example. Given that this query works, how can it be optimized since MySQL does not allow an ORDER BY to occur before a GROUP BY?"
}
] |
[
{
"body": "<p>The <code>ORDER BY</code> inside the inner-most sub-select is pointless - it's going to get thrown out. Also, you should <em>never</em> rely on MySQL's behaviour of selecting a 'random' value for non-grouped columns - <em>always</em> explicitly specify the transformation that needs to happen on the data. You should also review what you think your <code>Company</code> columns are, as I am going to pretty much guarantee that the company isn't the same for every cell in the column.</p>\n\n<p><hr/>\nEDIT:</p>\n\n<p>Actually, I was thinking your <code>ORDER BY</code> in the <code>GROUP_CONCAT()</code> was just fine - I have issues with how you're doing your <em>inner-most</em> <code>SELECT... ORDER BY</code> (that you then do a <code>GROUP BY</code> off of, without specifying your transforms).<br>\nAssuming that the tuple [<code>parts_data.part_id</code>, <code>parts_data.date</code>] is unique (although, that's the <code>date</code> of what? Insert, update, your birthday? Please name more descriptively), here's how I would have structured this (in a system without CTEs and OLAPs): </p>\n\n<pre><code>SELECT `a`.`part_number`, GROUP_CONCAT(`a`.`seller_id` ORDER BY `b`.`price` ASC), \n GROUP_CONCAT(`b`.`part_id` ORDER BY `b`.`price` ASC), \n GROUP_CONCAT(`b`.`price` ORDER BY `b`.`price` ASC)\nFROM `parts` as `a`\nLEFT JOIN (`parts_data` as `b`\n INNER JOIN (SELECT `part_id`, MAX(`date`) AS `date`\n FROM `parts_data`\n GROUP BY `part_id`) as `c`\n ON `b`.`part_id` = `c`.`part_id` \n AND `b`.`date` = `c`.`date`)\nON `a`.`part_id` = `b`.`part_id`\nGROUP BY `a`.`part_number`\nORDER BY `a`.`part_number` \n</code></pre>\n\n<p>Please note that I do not in fact have a MySQL instance to test against. I also don't know if this will be faster for your database (please note we now have a self-join). However, it's <em>much</em> clearer what you're expecting the system to do, meaning it's easier to maintain. </p>\n\n<p><hr/>\nEDIT: </p>\n\n<p>Here's an alternate version, which <em>may</em> be slightly faster. I don't work with MySQL (and I have some fairly serious hardward backing me up on DB2), so I'm not up on all the ins and outs.</p>\n\n<pre><code>SELECT `a`.`part_number`, GROUP_CONCAT(`a`.`seller_id` ORDER BY `b`.`price` ASC), \n GROUP_CONCAT(`b`.`part_id` ORDER BY `b`.`price` ASC), \n GROUP_CONCAT(`b`.`price` ORDER BY `b`.`price` ASC)\nFROM `parts` as `a`\nLEFT JOIN (SELECT `b`.`part_id`, `b`.`price`\n FROM `parts_data` as `b`\n WHERE NOT EXISTS (SELECT '1'\n FROM `parts_data` as `c`\n WHERE `c`.`part_id` = `b`.`part_id`\n AND `c`.`date` > `b`.`date`)) as `b`\nON `b`.`part_id` = `a`.`part_id`\nGROUP BY `a`.`part_number`\nORDER BY `a`.`part_number`\n</code></pre>\n\n<p>You may want to try removing the <code>ORDER BY a.part_number</code> clause, and see if that helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T04:15:45.460",
"Id": "12227",
"Score": "0",
"body": "I updated the example table to reflect this more appropriately, but the sellers are not defined by the columns. I admit this was confusing originally, but the change not should help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T04:17:43.060",
"Id": "12228",
"Score": "0",
"body": "The ORDER BY is not thrown out when the query is run. Without it I receive the first records that match from that table which are the oldest. The use of the ORDER BY is to select the table sorted newest to oldest and then pass that to the next table which uses those records to group on the part id. I don't know how I could prove it to you, but that is just the reality of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T04:51:41.390",
"Id": "12231",
"Score": "0",
"body": "I made a modification to the query to resolve the non-grouped columns issue, but it require yet another nested select. This query works and alter/removing and of the ORDER or GROUP cause wrong results."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T18:25:39.997",
"Id": "12274",
"Score": "0",
"body": "I ran your query and on average I received 17.5000 sec as the average with a high of 37.9568. However, for my two variations, I had .0119 with the ORDER BY in the GROUP_CONCAT and .0283 when opting to do an extra SELECT instead of the ORDER BY in the GROUP_CONCAT. These result are base on two days of data amounting to just 730 records (365 unique products). Any ideas why your query would result in such a way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T19:24:54.113",
"Id": "12277",
"Score": "0",
"body": "Indicies, or rather, a lack thereof, most probably. You're going to want one on `[part_id, date]` if you don't have it already. I'm assuming MySQL has some sort of ExplainPlan generator - see what that outputs."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T01:09:53.380",
"Id": "7733",
"ParentId": "7732",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T00:18:46.630",
"Id": "7732",
"Score": "2",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "Comparing products sold by several merchants"
}
|
7732
|
<p>I'm writing a small PHP framework to help me develop Web applications. The framework is split into numerous components, each of which are automatically loaded according to the configuration settings. This is my component base class:</p>
<pre><code>class Component {
public static void init() {}
}
</code></pre>
<p>When I create new components, I extend them from Component. For example, I have an Authenticator component that handles user login, logout and some other related functions. Here's an example of the code:</p>
<pre><code>class Authenticator extends Component {
public static void login($u, $p) {}
public static void logout() {}
...
}
</code></pre>
<p>As you can see my methods are static, so when it comes time to use the component, I can easily call the component's functions using Authenticator::METHOD() in the scope of my controller class. There is no need to create an instance of the components since they are in a static context. </p>
<p>But should I make them more OO (eg: make the methods non-static) using DI or some other means? What would be the advantages of this? And considering how I have several components, how would I do this without making things overly complex?</p>
|
[] |
[
{
"body": "<p>The OO equivalent of this is one of:</p>\n\n<pre><code>interface Component {\n public function init();\n}\n\nclass Authenticator implements Component {\n}\n\n// OR\n\nabstract class Component {\n abstract public function init();\n}\n\nclass Authenticator extends Component {\n}\n</code></pre>\n\n<p>Yes, you will have to create objects without using static. Its really not so bad though.</p>\n\n<p>What are the benefits? I created my own framework that is pure OO. So here is an example of what OO code looks like with dependency injection. I'll describe what it does afterwards so that you get an idea of some of the benefits.</p>\n\n<pre><code><?php\nclass Page_XML_Site_Locations extends Page_XML_Site\n{\n public function contentMain()\n {\n $model = $this->app->getModelDB(\n 'Model_DB_Joint',\n array('Table_Name' => 'Location',\n 'Table_References' => $this->app->getTableReferences(\n array('References' => array(\n 'Image_List_ID' => array(\n 'Child_Field' => 'List_ID',\n 'References' => array(\n 'Image_ID' => array(\n 'Child_Field' => 'ID',\n 'Table_Name' => 'Image')),\n 'Table_Name' => 'Image_List'),\n 'Map_ID' => array(\n 'Child_Field' => 'Map_ID',\n 'Table_Name' => 'Map')),\n 'Table_Name' => 'Location'))));\n\n $processing = $this->app->getProcessingNone();\n $settings = $this->app->getSettings();\n\n $data = $this->app->getData(\n array('Image_List_ID' => $this->app->getNew(\n 'Data_Image_List',\n array('Dir' => $settings['Web']['DB_Storage'] .\n 'img/location/',\n 'Empty_Image' => $settings['Web']['No_Photo'],\n 'Formats' => array('W_Min'),\n 'Image' => $this->app->getShared('Image'),\n 'Image_Sizes' => $this->app->getShared('Image_Sizes'),\n 'References' => array(\n 'Image_ID' => $this->app->getData()),\n 'Translator' => $this->tr)),\n 'Map_ID' => $this->app->getNew(\n 'Data_Map',\n array('References' => array(),\n 'Sensor' => 'false',\n 'Size' => '320x320'))));\n\n $view = $this->app->getView('View_XML_Locations',\n array('Data' => $data,\n 'Image_Format' => 'W_Min'));\n\n $controller = $this->app->getController();\n $controller->execute();\n }\n}\n// EOF\n</code></pre>\n\n<p>$this->app is my application container responsible for creating and retrieving resources. It is a dependency injection container. There are no calls to new or evil getInstance singletons. All of the objects are managed via the container.</p>\n\n<p>Distinct objects are created (model, processing, settings, data, view, controller). They stand alone (except data which is only created for injection into the view). I don't have to worry about their interface to each other. It is all handled by my event manager and controller. The objects each handle their own area. The Model gets joint data from its referenced tables. The processing handles any POST or GET requests. Everything does its job (which produces a list of stores in the correct language with their details, images and maps for finding them). There is nothing complex to worry about with who is calling who.</p>\n\n<p>That is the top level view. What did I have to do to complete that page?</p>\n\n<ul>\n<li>Model, Processing, Settings, Controller - Nothing, that is straight from the framework.</li>\n<li>Data_Image_List - calculate the image file name from the DB table and constructor settings.</li>\n<li>Data_Map - calculate the google static map string from the DB table and constructor settings.</li>\n<li>View - This is where most of the work goes. Loop through the data, writing the elements.</li>\n</ul>\n\n<p>If you don't like the look of the code that I use with my framework then you should probably ignore my suggestions.</p>\n\n<p>What will your Authenticator component do? How tightly will it be coupled to the rest of your system? Can it stand alone allowing you to kepp all your logic for each part of your system distinct?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T03:20:24.477",
"Id": "7737",
"ParentId": "7734",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7737",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T01:51:07.577",
"Id": "7734",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"static"
],
"Title": "Component functions - static vs. OO?"
}
|
7734
|
<p>For fun, I made a function queue in JavaScript. I named it <a href="https://github.com/NTICompass/tinyq">tinyq</a>. You can add functions to it, and each function is passed the next function in the queue. You can also pass parameters to the functions, and they can return values.</p>
<pre><code>function q(){
var Q = [], t = this;
this.length = 0;
this.add = function (f){
Q.push(f);
this.length++;
};
this.run = function(){
var n = Q.shift();
this.length = Q.length;
if(typeof n === 'function'){
var a = Array.prototype.slice;
return n.apply(window,[function(){
return t.run.apply(t, a.call(arguments));
}].concat(a.call(arguments)));
}
};
}
</code></pre>
<p>Here's a simple example of its use.</p>
<pre><code>var Q = new q;
Q.add(function(next, A, B){
return A + ": "+ next(B);
});
Q.add(function(next, C){
return C + "123";
});
console.log(Q.length); // 2
console.log(Q.run("Test", "ABC")); // "Test: ABC123"
</code></pre>
<p>So, what do you think of my function queue? Any improvements, or anything I'm doing wrong?</p>
<p>P.S. I was also trying to make this small, any suggestions on making it smaller?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-30T05:30:08.207",
"Id": "13210",
"Score": "1",
"body": "I feel like I'm not really understanding the purpose behind this. It seems like really complicated function composition. I realize the sample is purposely simple, so how else could this be used in a way more complicated than functional composition?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-30T15:22:36.403",
"Id": "13222",
"Score": "0",
"body": "@jdmichal: To be honest, I just wrote this for fun, with no reason for its existence. Is there a better way to do function composition that would still work with a queue?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T01:56:06.267",
"Id": "13272",
"Score": "0",
"body": "No worries; just trying to wrap my brain around the intended functionality. :) I'll add an answer to show how I would do simple function composition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-11T20:00:20.370",
"Id": "44502",
"Score": "1",
"body": "Hi @RocketHazmat I just came up with my own `Queue` implementation a few days ago when answering an SO question. Here is my CR OP: http://codereview.stackexchange.com/q/28380/3163 ^_^ Have fun with it!"
}
] |
[
{
"body": "<p>I'm still trying to wrap my head around what exactly is happening in that <code>apply</code>/<code>call</code> mass :-)</p>\n\n<p>But that may be a hint, that those three lines aren't really well readable. I'm aware you want to keep it small, but unless the code needs to be really, really fast (which I doubt it does) I would prefer readability over shortness.</p>\n\n<p>In that line, I would prefer to have long, more expressive variable names. It be better to use complete words instead of <code>Q</code>, <code>t</code>, <code>n</code>, <code>a</code> etc.</p>\n\n<p>If in the end, shortness is still important, then use a JavaScript compressor.</p>\n\n<p>BTW, you should keep JavaScript naming conventions in mind, too. Constructor functions (\"classes\") should be named with capital letters (<code>Q</code> instead of <code>q</code>) and fields should use small letters (<code>q</code> instead of <code>Q</code>).</p>\n\n<p>Just out of interest: Can you give a concrete use case for this kind of queue?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:56:42.867",
"Id": "12256",
"Score": "0",
"body": "I really don't have a real use case right now, this is just something I made for fun. I was trying to make a queue like jQuery's `.queue` with more features. Yeah, the `.apply`/`.call` thing is the heart of this script, and I agree it looks odd. I can try to explain it. `a.call(arguments)` turns the arguments \"array\" into a real array, so I can pass it to `apply`. `n.apply` calls the next function in the queue, and `t.run.apply` is a reference to `run` which when called triggers the next function in the queue."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T10:09:01.457",
"Id": "7743",
"ParentId": "7735",
"Score": "8"
}
},
{
"body": "<p>I'm not entirely sure where queue semantics are coming into play here. If you just walked up to me and told me you had a function queue for JavaScript, I would expect that I could add a bunch of functions to it, and then it would call them in sequence. But that's not what I'm seeing here.</p>\n\n<p>What I am seeing is a really weirdly formed function composition. Here's how I would do the sample given:</p>\n\n<pre><code>// Create function to show a value with a label.\n// Note that it takes a value function, rather than a pure value.\n// It also takes any number of arguments for that function, as an array.\nvar showWithLabel = function (label, valueFunction, valueArguments) {\n return (label + \": \" + valueFunction.apply(undefined, valueArguments));\n};\n\n// Create a function to append \"123\" onto a string.\nvar append123 = function (string) {\n return (string + \"123\");\n};\n\n// Simple call to execute them together.\nshowWithLabel(\"Test\", append123, [\"ABC\"]);\n\n// Actually composite them into a new function.\n// This function is the equivalent of the run function.\nvar composite = function (label, value) {\n return showWithLabel(label, append123, [value]);\n};\n\n// Now call the composite.\ncomposite(\"Test\", \"ABC\");\n</code></pre>\n\n<p>Please comment and discuss here. I want to have a conversation about this, because I feel like there's probably some functionality I'm not understanding about the queue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T02:08:51.167",
"Id": "13273",
"Score": "0",
"body": "This queue can support adding functions and calling them in sequence. Just remove all parameters (except `next`) and it'll work that way. I added the parameter thing for fun. Guess it really doesn't have much real use. This is a neat example, btw. Nice and simple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T02:15:44.847",
"Id": "13274",
"Score": "1",
"body": "Oh, I see. You can call `run` multiple times and it will keep reducing the queue down. I must admit that I also don't see much use for that, and I have done a pretty good amount of browser JavaScript coding. Interesting idea though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T03:27:38.140",
"Id": "13277",
"Score": "0",
"body": "You can call `run` to run the next item and reduce the queue. Each item is passed `next`. Calling `next` will also call the next function and reduce the queue. Both `run` and `next` can pass parameters to the function in the queue that's being ran."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-31T02:06:48.417",
"Id": "8483",
"ParentId": "7735",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8483",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T02:43:00.837",
"Id": "7735",
"Score": "6",
"Tags": [
"javascript",
"queue"
],
"Title": "Custom JavaScript function queue"
}
|
7735
|
<p>I am working on an app for iPhone and iPod Touch that has to show complex mathematical equations like algebraic, integration, summation formulas along with some text.</p>
<p>For that I have used Quartz2D and below is what I have created. Can anyone please verify if this is the correct procedure to draw an equation?</p>
<p>I have to show lots of text with inline equations (and that too dynamic) - I am sure using this procedure will be a task to make that thing dynamic.</p>
<p>P.S. - I just need verification of my below procedure or if there is a more feasible solution - please guide me to that.</p>
<pre><code>- (void)drawRect:(CGRect)rect
{
// Left hand side Starts --
float xaxis = 3.0f;
// Before bracket
NSString *textString = @"L";
[textString drawAtPoint:CGPointMake(xaxis, 50.) withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:20]];
// Opening bracket
xaxis += 12.0f;
textString = @"(";
[textString drawAtPoint:CGPointMake(xaxis, 30.) withFont:[UIFont fontWithName:@"Helvetica" size:50]];
textString = @"N";
xaxis += 12.0f;
[textString drawAtPoint:CGPointMake(xaxis, 50.) withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:20]];
// Numerator part
unichar oneChar[] = {0x2206};
xaxis += 31.0f;
textString = getTextString(oneChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 37.) withFont:[UIFont fontWithName:@"Helvetica" size:22]];
unichar twoChar[] = {0x03C9};
xaxis += 15.0f;
textString = getTextString(twoChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 15.0f;
textString = @"k";
[textString drawAtPoint:CGPointMake(xaxis, 48.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
// Line
CGContextRef myContext = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(myContext, 2);
CGContextSetStrokeColorWithColor(myContext, [UIColor blackColor].CGColor);
CGContextMoveToPoint(myContext, 45, 65);
CGContextAddLineToPoint(myContext, 110, 65);
CGContextStrokePath(myContext);
// Denominator part
xaxis -= 40.0f;
unichar threeChar[] = {0x03C9};
textString = getTextString(threeChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 64.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 15.0f;
textString = @"res";
[textString drawAtPoint:CGPointMake(xaxis, 74.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
xaxis += 18.0f;
unichar fourChar[] = {0x0028};
textString = getTextString(fourChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 64.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 5.0f;
unichar fiveChar[] = {0x03B8};
textString = getTextString(fiveChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 64.) withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:20]];
xaxis += 15.0f;
textString = @")";
[textString drawAtPoint:CGPointMake(xaxis, 64.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
// Closing bracket
xaxis += 8.0f;
textString = @")";
[textString drawAtPoint:CGPointMake(xaxis, 30.) withFont:[UIFont fontWithName:@"Helvetica" size:50]];
// Equal to sign
xaxis += 15.0f;
unichar sixChar[] = {0x003D};
textString = getTextString(sixChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 50.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
// Right hand side Starts --
// Numerator part
xaxis += 15.0f;
textString = @"sin";
[textString drawAtPoint:CGPointMake(xaxis, 42.) withFont:[UIFont fontWithName:@"Helvetica" size:17]];
xaxis += 20.0f;
textString = @"2";
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
// Inner opening bracket
xaxis += 10.0f;
textString = @"(";
[textString drawAtPoint:CGPointMake(xaxis, 37.) withFont:[UIFont fontWithName:@"Helvetica" size:22]];
xaxis += 8.0f;
textString = @"N";
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:20]];
xaxis += 18.0f;
unichar sevenChar[] = {0x03C0};
textString = getTextString(sevenChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 40.) withFont:[UIFont fontWithName:@"Helvetica" size:17]];
xaxis += 12.0f;
unichar eightChar[] = {0x2206};
textString = getTextString(eightChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 36.) withFont:[UIFont fontWithName:@"Helvetica" size:21]];
xaxis += 15.0f;
unichar nineChar[] = {0x03C9};
textString = getTextString(nineChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 15.0f;
textString = @"k";
[textString drawAtPoint:CGPointMake(xaxis, 47.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
xaxis += 8.0f;
textString = @"/";
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica" size:24]];
xaxis += 8.0f;
unichar tenChar[] = {0x03C9};
textString = getTextString(tenChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 15.0f;
textString = @"res";
[textString drawAtPoint:CGPointMake(xaxis, 48.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
xaxis += 18.0f;
textString = @"(";
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 5.0f;
unichar elevenChar[] = {0x03B8};
textString = getTextString(elevenChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:20]];
xaxis += 12.0f;
textString = @")";
[textString drawAtPoint:CGPointMake(xaxis, 38.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
// Inner closing bracket
xaxis += 6.0f;
textString = @")";
[textString drawAtPoint:CGPointMake(xaxis, 37.) withFont:[UIFont fontWithName:@"Helvetica" size:22]];
// Line
CGContextSetLineWidth(myContext, 2);
CGContextSetStrokeColorWithColor(myContext, [UIColor blackColor].CGColor);
CGContextMoveToPoint(myContext, 138, 65);
CGContextAddLineToPoint(myContext, 318, 65);
CGContextStrokePath(myContext);
// Denominator part
xaxis -= 175.0f;
textString = @"N";
[textString drawAtPoint:CGPointMake(xaxis, 65.) withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:20]];
xaxis += 18.0f;
textString = @"2";
[textString drawAtPoint:CGPointMake(xaxis, 63.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
xaxis += 8.0f;
textString = @"sin";
[textString drawAtPoint:CGPointMake(xaxis, 68.) withFont:[UIFont fontWithName:@"Helvetica" size:17]];
xaxis += 20.0f;
textString = @"2";
[textString drawAtPoint:CGPointMake(xaxis, 63.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
// Inner opening bracket
xaxis += 10.0f;
textString = @"(";
[textString drawAtPoint:CGPointMake(xaxis, 64.) withFont:[UIFont fontWithName:@"Helvetica" size:22]];
xaxis += 8.0f;
unichar twelveChar[] = {0x03C0};
textString = getTextString(twelveChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 68.) withFont:[UIFont fontWithName:@"Helvetica" size:17]];
xaxis += 12.0f;
unichar thirteenChar[] = {0x2206};
textString = getTextString(thirteenChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 65.) withFont:[UIFont fontWithName:@"Helvetica" size:21]];
xaxis += 15.0f;
unichar fourteenChar[] = {0x03C9};
textString = getTextString(fourteenChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 67.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 15.0f;
textString = @"k";
[textString drawAtPoint:CGPointMake(xaxis, 75.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
xaxis += 8.0f;
textString = @"/";
[textString drawAtPoint:CGPointMake(xaxis, 64.) withFont:[UIFont fontWithName:@"Helvetica" size:24]];
xaxis += 8.0f;
unichar fifteenChar[] = {0x03C9};
textString = getTextString(fifteenChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 67.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 15.0f;
textString = @"res";
[textString drawAtPoint:CGPointMake(xaxis, 75.) withFont:[UIFont fontWithName:@"Helvetica" size:12]];
xaxis += 18.0f;
textString = @"(";
[textString drawAtPoint:CGPointMake(xaxis, 66.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
xaxis += 5.0f;
unichar sixteenChar[] = {0x03B8};
textString = getTextString(sixteenChar, 1);
[textString drawAtPoint:CGPointMake(xaxis, 66.) withFont:[UIFont fontWithName:@"Helvetica-Oblique" size:20]];
xaxis += 12.0f;
textString = @")";
[textString drawAtPoint:CGPointMake(xaxis, 66.) withFont:[UIFont fontWithName:@"Helvetica" size:20]];
// Inner closing bracket
xaxis += 6.0f;
textString = @")";
[textString drawAtPoint:CGPointMake(xaxis, 64.) withFont:[UIFont fontWithName:@"Helvetica" size:22]];
// Extra text for information
xaxis = 6.0f;
textString = @"Above is the example of an equation drawn using";
[textString drawAtPoint:CGPointMake(xaxis, 120.) withFont:[UIFont fontWithName:@"Helvetica" size:14]];
xaxis = 6.0f;
textString = @"Quartz2D";
[textString drawAtPoint:CGPointMake(xaxis, 140.) withFont:[UIFont fontWithName:@"Helvetica" size:14]];
}
static NSString *getTextString(unichar chars[], int charLength)
{
NSString *uniString = [NSString stringWithCharacters:chars length: charLength];
return uniString;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-13T19:12:10.673",
"Id": "239973",
"Score": "0",
"body": "Take a look at the code here: https://github.com/kostub/iosMath That will help you with rendering math equations using CoreText."
}
] |
[
{
"body": "<p>These questions may be relevant:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4340478/rendering-mathematical-formulas-on-an-idevice\">https://stackoverflow.com/questions/4340478/rendering-mathematical-formulas-on-an-idevice</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/13243539/tradeoff-between-latex-mathml-and-xhtmlmathml-in-an-ios-app\">https://stackoverflow.com/questions/13243539/tradeoff-between-latex-mathml-and-xhtmlmathml-in-an-ios-app</a></p>\n\n<p>As for the rendering, Quartz2D is one approach. Or, my preference, you could go for an HTML/CSS based approach, as mentioned at the above question. The use of <a href=\"http://www.texify.com/\" rel=\"nofollow noreferrer\">Texify</a> looks tempting!</p>\n\n<p>If you take entirely your own approach for the rendering (e.g. using Quartz2D), I imagine a robust solution to maths rendering will involve three distinct parts that need to interact:</p>\n\n<ol>\n<li><p>a representation of the equation</p></li>\n<li><p>a layout engine to decide how to position elements on the page</p></li>\n<li><p>an engine that actually displays the items as decreed by (2) -- be it Quartz2D, HTML/CSS, or something else</p></li>\n</ol>\n\n<p>Food for thought on representing an equation: </p>\n\n<p>You can represent an expression as a tree structure. Each node is composed of both:</p>\n\n<ol>\n<li><p>some sort of operator (be it binary, such as '+', '=' or '*', or unary, e.g. 'sin', square root, etc.)</p></li>\n<li><p>links to child nodes which are the operands to its operator.</p></li>\n</ol>\n\n<p>So the nodes form a recursive structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-20T18:37:55.387",
"Id": "11048",
"ParentId": "7738",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T03:21:30.670",
"Id": "7738",
"Score": "3",
"Tags": [
"objective-c",
"ios"
],
"Title": "Display complex mathematical equations in iOS 5.0 devices"
}
|
7738
|
<p>I am starting to write a plugin that is aiming to validate a piece of mark up against requirements of schema.org.</p>
<p>I was hoping if I could get some more tips on how to improve the structure of my code. <em>Is this how you would go about this if you were to do it?</em></p>
<pre><code> $.fn.hasAttr = function(name) {
return this.attr(name) !== undefined;
};
$.fn.outerHTML = function(s) {
return $(this).clone().wrap('<div>').parent().html();
};
$.fn.getOpeningTag = function (s) {
return $(this).outerHTML().slice(0, $(this).outerHTML().indexOf(">") + 1)
}
$.fn.validateSchema = function(options) {
var defaults = {
// for a list of international postcode regex see: http://www.thalesjacobi.com/Regex_to_validate_postcodes
// The one used in the example is from the UK
localPostCodeFormat: new RegExp("^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$"),
utilities : {
missAtrr : function (target, attrName) {
if (!target.hasAttr(attrName)){
defaults.returnError(target, "The element " + target.getOpeningTag() + " is missing the required attribute " + attrName);
}
},
isValidPostCode : function (target) {
if (!defaults.localPostCodeFormat.test(target.text())) {
defaults.returnError(target, target.getOpeningTag() + " does not have a valid post code");
}
}
},
returnError : function (target, errorMessage) {
var errorContainer = $('<span class="schemaError"></span>');
target.before(errorContainer);
errorContainer.css({
'color' : 'red',
'border': 'solid 1px red'
}).text(errorMessage);
} // more utils to be added
};
// Extend our default options with those provided.
var opts = $.extend(defaults, options);
var schemaElements = {
postalAddress : $(this).find('[itemtype*=PostalAddress]'),
itemProps : $(this).find("[itemprop]"),
emptyProps : $(this).find("[itemprop='']"),
postCode : $(this).find("[itemprop=postalCode]"),
email : $(this).find("[itemprop=email]"),
outofplaceChild : $(this).find("[itemscope]").siblings("[itemprop]")// more dom refs to be added
}
// validation stuff
//
// PostalAddress should have itemsscope
if (schemaElements.postalAddress){
defaults.utilities.missAtrr(schemaElements.postalAddress, "itemscope");
}
// No itemscope can be left empty
if (schemaElements.emptyProps){
$.each(schemaElements.emptyProps, function () {
defaults.returnError($(this), $(this).getOpeningTag() + " can not be left without a value");
});
}
// postcode should match the post code format of that country
if (schemaElements.postCode){
defaults.utilities.isValidPostCode(schemaElements.postCode);
}
// No itemprop can exist without having a itemscope parent
if (schemaElements.outofplaceChild){
$.each(schemaElements.outofplaceChild, function () {
defaults.returnError($(this), $(this).getOpeningTag() + " Does not have a itemscope parent");
});
}
// more rules to be added
};
$(function(){
$('body').validateSchema();
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T10:36:22.950",
"Id": "12659",
"Score": "0",
"body": "I haven't used code review before? Is the no response due to much lower traffic compared to stack or I am doing something wrong? Do people expect me to start a bounty to make this worth while?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T13:53:37.703",
"Id": "12668",
"Score": "4",
"body": "i added a bounty for you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T18:16:17.567",
"Id": "12683",
"Score": "1",
"body": "There are lots of [unanswered jQuery questions](http://codereview.stackexchange.com/questions/tagged/jquery). A jQuery expert could get lots of rep here :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-24T19:16:07.273",
"Id": "12894",
"Score": "0",
"body": "@XGreen, I am in the same boat, just added +50 to a basic question of best practices. I don't think there are enough people using this site to get questions from all but the most popular programming languages/tools answered."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-24T21:23:36.150",
"Id": "12907",
"Score": "0",
"body": "Yes the action is pretty much only in stackoverflow, the ux and here are not very active. seand has put 100 down for this and that is why I am waiting to see a bit more, even though the answers these guys have given are also good."
}
] |
[
{
"body": "<p>This will return <code>false</code> for <code>attr</code> in such an object <code>{'attr': undefined}</code>:</p>\n\n<pre><code>$.fn.hasAttr = function(name) { \n return this.attr(name) !== undefined;\n};\n</code></pre>\n\n<p>If this is not exactly what you want, have a look at related posts (<a href=\"https://stackoverflow.com/questions/135448/how-do-i-check-to-see-if-an-object-has-an-attribute-in-javascript\">one</a>, <a href=\"https://stackoverflow.com/questions/455338/how-do-i-check-if-an-object-has-a-key-in-javascript\">two</a>) and search for much more.</p>\n\n<hr>\n\n<p>This (and similars) will always evaluate to <code>true</code>, if <code>schemaElements</code> object has the <code>postalAddress</code> key:</p>\n\n<pre><code>if (schemaElements.postalAddress){\n defaults.utilities.missAtrr(schemaElements.postalAddress, \"itemscope\");\n}\n</code></pre>\n\n<p>here's an example session from Chrome developer console:</p>\n\n<pre><code>var rules = {'a': $('html').find('#idontexist')};\nrules.a;\n// []\nif (rules.a) {console.log(true)} else {console.log(false)};\n// true\n</code></pre>\n\n<hr>\n\n<p>Be consistent with <code>;</code> at the end of the lines.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T16:43:00.353",
"Id": "8004",
"ParentId": "7745",
"Score": "4"
}
},
{
"body": "<p>You could replace <code>.fn.getOpeningTag</code> with:</p>\n\n<pre><code>$.fn.getOpeningTag = function (s) {\n if( this[0] && this[0].nodeType === 1 ) {\n return \"<\" + this[0].tagName.toLowerCase() + \">\";\n }\n};\n</code></pre>\n\n<p>I saw 600x <a href=\"http://jsperf.com/performance-increase2\" rel=\"nofollow\">performance improvement</a> in chrome</p>\n\n<hr>\n\n<p>These are methods on jQuery objects so doing <code>$(this)</code> is redundant, <code>this</code> will already be a jQuery object.</p>\n\n<hr>\n\n<p>Do not put stuff like <code>validateSchema</code>, in <code>jQuery.fn</code>. It is not a method that operates on a collection DOM elements, make it class that is consists of many small methods. That way you avoid the 9000 configuration options pattern.</p>\n\n<pre><code>function SchemaValidation() {\n\n}\n\nSchemaValidation.prototype = { ... };\n\nvar schemaValidation = new SchemaValidation( a, b, c );\nschemaValidation.addElements( e, f, g );\nschemaValidation.validate();\n</code></pre>\n\n<p>Of course you don't have to do it that way but for god's sake do not have it as a jQuery method, it doesn't make any sense. Especially in this case you aren't even using the jQuery object the method is called on. Well, technically you are but that's superfluous.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T13:31:34.363",
"Id": "8057",
"ParentId": "7745",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "8057",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T11:24:49.870",
"Id": "7745",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"microdata"
],
"Title": "Schema.org Microdata validation plugin"
}
|
7745
|
<p>A design pattern is a description or template that helps solve a reoccurring problem, which can be used in many different situations.</p>
<p>It is common to classify design patterns into the following categories:</p>
<ul>
<li><strong>Creational design patterns</strong> deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design patterns solve this problem by somehow controlling object creation.</li>
<li><strong>Structural design patterns</strong> ease the design by identifying a simple way to realize relationships between entities.</li>
<li><strong>Behavioral design patterns</strong> identify common communication patterns between objects and realize these patterns. By doing so, these patterns increase flexibility in carrying out this communication.</li>
<li><strong>Concurrency patterns</strong> deal with the multi-threaded programming paradigm.</li>
</ul>
<p>Related to design patterns, are <a href="http://en.wikipedia.org/wiki/Architectural_pattern" rel="nofollow">architectural patterns</a>. These are often concepts which solve and delineate some essential cohesive elements of a software architecture.</p>
<p><a href="http://en.wikipedia.org/wiki/Design_pattern_(computer_science)" rel="nofollow">Wikipedia Article for Design Patterns</a></p>
<p><a href="http://www.vincehuston.org/dp/" rel="nofollow">'Before' and 'After' refactoring examples</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T11:45:21.413",
"Id": "7746",
"Score": "0",
"Tags": null,
"Title": null
}
|
7746
|
A design pattern is a general reusable solution to a commonly occurring problem in software design.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T11:45:21.413",
"Id": "7747",
"Score": "0",
"Tags": null,
"Title": null
}
|
7747
|
<p>Scheme follows a minimalist design philosophy specifying a small standard core with powerful tools for language extension. Its compactness and elegance have made it popular with educators, language designers, programmers, implementors, and hobbyists. The main feature of scheme when compared to common lisp is its hygienic macro system which allows writing macros without variable capture. Scheme also provides continuations as a programming feature, and requires proper tail recursion. The scheme update process is called RnRS where n is the version</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T11:58:26.963",
"Id": "7748",
"Score": "0",
"Tags": null,
"Title": null
}
|
7748
|
Scheme is a functional programming language in the Lisp family, closely modeled on lambda calculus with eager (applicative-order) evaluation.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T11:58:26.963",
"Id": "7749",
"Score": "0",
"Tags": null,
"Title": null
}
|
7749
|
<p><a href="http://www.mysql.com" rel="nofollow">MySQL</a> is a <em>relational database management system</em> that runs as a server providing multi-user access to a number of databases.</p>
<h2>Deprecation of <code>mysql_</code> functions</h2>
<p>PHP functions that start with <code>mysql_</code> have been deprecated as of PHP 5.5.0. If you are in a position to do so, please consider updating your code to use the <a href="http://www.php.net/manual/en/book.mysqli.php" rel="nofollow"><code>mysqli_</code></a> or <a href="http://www.php.net/manual/en/ref.pdo-mysql.php" rel="nofollow">PDO</a> extensions instead.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:06:34.157",
"Id": "7750",
"Score": "0",
"Tags": null,
"Title": null
}
|
7750
|
MySQL is an open-source, relational database management system. If your PHP code uses MySQLi, use the MySQLi tag instead.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:06:34.157",
"Id": "7751",
"Score": "0",
"Tags": null,
"Title": null
}
|
7751
|
<p>In computer science, program or software <a href="http://en.wikipedia.org/wiki/Optimization_%28computer_science%29" rel="nofollow">optimization</a> is the process of modifying a system to make some aspect of it work more efficiently or use fewer resources. In general, a computer program may be optimized so that it executes more rapidly, or is capable of operating with less memory storage or other resources, or draw less power<sup><a href="http://en.wikipedia.org/wiki/Optimization_%28computer_science%29" rel="nofollow">Wikipedia</a></sup>. Other resources may include disk access, communication bandwidth, video performance and user interface responsiveness.</p>
<p><a href="/questions/tagged/performance" class="post-tag" title="show questions tagged 'performance'" rel="tag">performance</a> is a subset of <a href="/questions/tagged/optimization" class="post-tag" title="show questions tagged 'optimization'" rel="tag">optimization</a>. Use the <a href="/questions/tagged/performance" class="post-tag" title="show questions tagged 'performance'" rel="tag">performance</a> tag when your concern is specifically about optimizing the run-time of a program ('Performance Optimization').</p>
<p>Apart from the software itself, other areas that are commonly optimized are:</p>
<ul>
<li>disk space usage</li>
<li>memory usage</li>
<li>network/database connections</li>
<li>etc.</li>
</ul>
<p>Additionally, it is common for programs to solve <a href="http://en.wikipedia.org/wiki/Combinatorial_optimization" rel="nofollow">combinatorial optimization</a> problems:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Cutting_stock_problem" rel="nofollow">Cutting stock problem</a></li>
<li><a href="http://en.wikipedia.org/wiki/Knapsack_problem" rel="nofollow">Knapsack algorithm</a></li>
<li><a href="http://en.wikipedia.org/wiki/Traveling_salesman_problem" rel="nofollow">Traveling Salesman Problem</a></li>
<li>etc.</li>
</ul>
<p>Common places in software that are optimized are:</p>
<ul>
<li>Design or <a href="http://en.wikipedia.org/wiki/Algorithmic_efficiency" rel="nofollow">algorithm efficiency</a>.</li>
<li>Source code level. For example <a href="http://en.wikipedia.org/wiki/Duff%27s_device" rel="nofollow">Duff's Device</a>.</li>
<li>Build level or optimizer flags, often trading build time for run-time efficiency. </li>
<li>Compile level; choosing the <em>best</em> compiler.</li>
<li>Assembly level. The best <em>machine</em> mapping to a problem</li>
<li>Run time. Examples include <em>virtual machine</em> parameters and <a href="http://en.wikipedia.org/wiki/Profile-guided_optimization" rel="nofollow">profile guided optimization</a>.</li>
</ul>
<p>A common cited peril of optimizing is <em>premature optimization</em>. Optimization often has consequences in regard to program <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="nofollow">complexity</a> and <a href="http://en.wikipedia.org/wiki/Maintainability" rel="nofollow">maintainability</a>. In contrast, the most dramatic effect on optimization is at the <strong>Design Level</strong> via <a href="http://en.wikipedia.org/wiki/Algorithmic_efficiency" rel="nofollow">algorithm efficiency</a>; this is the earliest stage of development leading to a paradox.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:07:09.647",
"Id": "7752",
"Score": "0",
"Tags": null,
"Title": null
}
|
7752
|
DO NOT USE THIS TAG. It is in the process of being eliminated. If your question is just about performance, use the [performance] tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:07:09.647",
"Id": "7753",
"Score": "0",
"Tags": null,
"Title": null
}
|
7753
|
<p>Multi-threading is a common model to implement SM in multi-cored machines, where threads share memory through shared variables. In this model in parallel programming a processor can create multiple threads that will be executed in parallel. Each thread has its own stack, variables and ID, considered private state. For every thread there is a unique heap shared by all, considered shared memory.</p>
<p>In order to allow a volume of work to be most effectively and safely divided into multiple concurrent streams of execution, a number of critical areas need to be addressed. </p>
<ul>
<li><strong>Scheduling</strong>: ensure worker tasks are able to progress independently and effectively (e.g. deadlock/livelock avoidance).</li>
<li><strong>Publication</strong>: ensure data altered in one thread is only visible to others as expected.</li>
<li><strong>Synchronization</strong>: ensure critical regions are protected from multiple concurrent updates causing data loss/corruption.</li>
</ul>
<p>The underlying tenet of concurrent processing is Amdahl's law (<a href="http://upload.wikimedia.org/wikipedia/commons/e/ea/AmdahlsLaw.svg" rel="nofollow noreferrer">graph</a>). This law governs the diminishing amount of throughput that can be achieved by greater numbers of concurrent processors/cores. Therefore the overall aim of multi-threading is to minimize the amount of serial execution (exclusive locking) within any concurrent system.</p>
<h1>Books</h1>
<ul>
<li><a href="http://www.albahari.com/threading/" rel="nofollow noreferrer">"Threading in C#"</a> (free e-book)</li>
<li><a href="http://www.javaconcurrencyinpractice.com/" rel="nofollow noreferrer">"Java Concurrency in Practice"</a></li>
<li><a href="http://www.manning.com/williams/" rel="nofollow noreferrer">"C++ Concurrency in Action"</a></li>
<li><a href="http://rads.stackoverflow.com/amzn/click/032131283X" rel="nofollow noreferrer">"Principles of Concurrent and Distributed Programming"</a></li>
<li><a href="http://rads.stackoverflow.com/amzn/click/032143482X" rel="nofollow noreferrer">"Concurrent Programming on Windows"</a></li>
<li><a href="http://shop.oreilly.com/product/9780596007829.do" rel="nofollow noreferrer">Java Threads, By Scott Oaks, Henry Wong</a></li>
</ul>
<h1>More information:</h1>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Multithreading_%28computer_architecture%29" rel="nofollow noreferrer">Multithreading (computer architecture)</a> (Wikipedia)</li>
<li><a href="https://en.wikipedia.org/wiki/Multithreading_%28software%29#Multithreading" rel="nofollow noreferrer">Multithreading (software)</a> (Wikipedia)</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:27:57.303",
"Id": "7754",
"Score": "0",
"Tags": null,
"Title": null
}
|
7754
|
Multi-threading is how work performed by a computer can be divided into multiple concurrent streams of execution (generally referred to as threads).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:27:57.303",
"Id": "7755",
"Score": "0",
"Tags": null,
"Title": null
}
|
7755
|
<p>I'm trying to improve the quality/efficiency of my coding (having only been learning jQuery for a couple of months).</p>
<p>I have a function which loops through all <code>$('.loop-bar')'</code>s and applies a jQueryUI slider to each. Each loop bar is a range slider which controls the portion of each song (playing via a custom player i have developed using soundmanager 2).</p>
<p>There's a lot of other stuff it is doing at the same time such as adjusting the progress bar width, resetting it, adding data to the DOM in order to perform loop checks etc.</p>
<p>However it strikes me that I am having to declare an awful lot of variables. Are there any shortcuts/ways I can improve this?</p>
<p>For those of you with a high level of jquery experience, have i fallen into any common pitfalls, does the performance look optimal (it performs absolutely fine in real world but could it be improved?).</p>
<pre><code>function initLoopSliders(oTable) {
oTable.find('.loop-bar').each(function () {
var $this = $(this);
var $seekbar = $this.parent().siblings('.player-timeline').find('.seek-bar');
var $seekhead = $('#seekhead');
var $widthgauge = $seekbar.siblings('ol');
var sliderwidth = $widthgauge.width();
var $datastore = $this.closest('td');
var soundID = $datastore.find('.playable').data('playable').sID;
var $progressbar = $datastore.find('.position');
var $body = $('body');
var $righthandle;
var $lefthandle;
var $songdata = $datastore.data('data');
var $fullduration = $datastore.attr('alt');
$this.parent().width(sliderwidth);
$this.slider({
range: true,
min: 0,
max: sliderwidth,
values: [0, sliderwidth],
start: function (event, ui) {
$body.attr('looping', soundID).attr('searching', 'true');
$lefthandle = $this.find('.loop-start');
$righthandle = $this.find('.loop-end');
soundManager.stop(soundID);
$progressbar.width(0);
},
slide: function (event, ui) {
loopstart = rectime($songdata.loopstart);
loopend = rectime($songdata.loopend);
left = ui.values[0];
seekheadLeft = $seekbar.offset().left;
rightwidth = sliderwidth - ui.values[1];
width = sliderwidth - left;
newwidth = width - rightwidth;
$seekbar.css({
left: left + 'px',
width: newwidth + 'px'
});
$seekhead.css({
left: seekheadLeft + 'px',
width: newwidth + 'px'
});
$songdata.loopduration = $fullduration * (newwidth / sliderwidth);
$songdata.relativeduration = newwidth / sliderwidth;
$songdata.loopstart = Math.round(($fullduration / sliderwidth) * ui.values[0]);
$songdata.loopend = Math.round(($fullduration / sliderwidth) * ui.values[1]);
$lefthandle.text(loopstart);
$righthandle.text(loopend);
$datastore.data('data', $songdata);
},
stop: function (event, ui) {
$body.attr('searching', 'false');
if (ui.values[0] == 0 && ui.values[1] == sliderwidth) {
$object = $(this).find('a');
soundManager.play(soundID);
hideLoopHandle2($object);
$body.attr('looping', '');
}
else {
from = Number(($datastore.data('data').loopstart) * 1000);
to = Number(($datastore.data('data').loopend) * 1000);
playFromTo(from, to, soundID);
}
}
});
}); //end each
// Add hoverintent to handles
$('.loop-bar').find('a').hoverIntent({
sensitivity: 10,
// How sensitive the hoverIntent should be
interval: 10,
// How often in milliseconds the onmouseover should be checked
over: showLoopHandle,
// Function to call when mouseover is called
timeout: 500,
// How often in milliseconds the onmouseout should be checked
out: hideLoopHandle // Function to call when mouseout is called
});
} // end
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>it performs absolutely fine in real world</p>\n</blockquote>\n\n<p>And </p>\n\n<blockquote>\n <p>have i fallen into any common pitfalls</p>\n</blockquote>\n\n<p>Yes, you have. It's called premature optimization. The code looks fine, it's not hard to understand. You are just missing a couple comments to explain what the function is for.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-21T16:38:02.237",
"Id": "8164",
"ParentId": "7756",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "8164",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:31:38.830",
"Id": "7756",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"jquery-ui",
"audio"
],
"Title": "Audio scrubber slider bar"
}
|
7756
|
<p>LINQ is a .NET-based DSL (Domain Specific Language) for querying data sources such as databases, XML files, or in-memory object lists. All these data sources can be queried using the exact same readable and easy-to-use syntax - or rather, syntaxes, because LINQ supports two notations:</p>
<p>Inline LINQ or query syntax, where queries are expressed in a SQL-like language, with dialects in both C# and VB.NET.</p>
<p>Fluent LINQ or query operators, where queries are expressed as lambda expressions and can be linked (LINQed?) using a fluent syntax. This is also called <em>method chaining</em>.</p>
<p><strong>Some examples:</strong></p>
<p><em>Query syntax (C#)</em></p>
<pre><code>var result =
from product in dbContext.Products
where product.Category.Name == "Toys"
where product.Price >= 2.50
select product.Name;
</code></pre>
<p><em>Query Syntax (VB.NET)</em></p>
<pre><code>Dim result = _
From product in dbContext.Products _
Where product.Category.Name = "Toys" _
Where product.Price >= 2.50 _
Select product.Name
</code></pre>
<p><em>Fluent syntax</em></p>
<pre><code>var result = dbContext.Products
.Where(p => p.Category.Name == "Toys" && p.Price >= 250)
.Select(p => p.Name);
</code></pre>
<p>This query would return the name of all products in the "Toys" category with a price greater than or equal to 2.50.</p>
<p><strong>Flavors</strong></p>
<p>LINQ comes in many flavors, the most notable are</p>
<ul>
<li><em>LINQ to Objects</em> - For querying collections of POCO (<strong>P</strong>lain <strong>O</strong>ld <strong>C</strong>LR <strong>O</strong>bjects)</li>
<li><em>LINQ to SQL</em> - For querying SQL databases</li>
<li><em>LINQ to Entities</em> - For querying SQL databases through Entity Framework</li>
<li><em>LINQ to XML</em> - For querying XML documents</li>
</ul>
<p>There are other implementations of LINQ which can be found on the Internet, such as LINQ to SharePoint, LINQ to Twitter, LINQ to CSV, LINQ to Excel, LINQ to JSON, and LINQ to Google.</p>
<p><strong>More reading:</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb397926.aspx" rel="nofollow"><strong>MSDN: LINQ</strong></a></li>
<li><a href="https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b" rel="nofollow"><strong>101 LINQ samples</strong></a></li>
<li><a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="nofollow"><strong>Wikipedia</strong></a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:37:48.410",
"Id": "7757",
"Score": "0",
"Tags": null,
"Title": null
}
|
7757
|
Language INtegrated Query (LINQ) is a Microsoft .NET Framework component that adds native data querying capabilities to .NET languages.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:37:48.410",
"Id": "7758",
"Score": "0",
"Tags": null,
"Title": null
}
|
7758
|
<p>A late-binding, message-based, object-oriented language that is a strict superset of C and is primarily used for programming primarily on Apple's Mac OS X and iOS platforms. Objective-C can also be used on other platforms that support gcc or clang.</p>
<p><a href="http://en.wikipedia.org/wiki/Objective-C" rel="nofollow noreferrer">Objective-C</a> was created primarily by <a href="http://en.wikipedia.org/wiki/Brad_Cox" rel="nofollow noreferrer">Brad Cox</a> and Tom Love in the early 1980s at their company <a href="http://en.wikipedia.org/wiki/Stepstone" rel="nofollow noreferrer">Stepstone</a>. It is now primarily developed by <a href="http://en.wikipedia.org/wiki/Apple_Inc." rel="nofollow noreferrer">Apple, Inc</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:38:51.107",
"Id": "7759",
"Score": "0",
"Tags": null,
"Title": null
}
|
7759
|
This tag should be used only on questions that are about Objective-C features or depend on code in the language. The tags [cocoa] and [cocoa-touch] should be used to ask about Apple's frameworks or classes. Use the related tags [ios] and [osx] for issues specific to those platforms.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:38:51.107",
"Id": "7760",
"Score": "0",
"Tags": null,
"Title": null
}
|
7760
|
ASP.NET MVC 3 is the third major version of Model-View-Controller extension for developing web applications in a .NET framework
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T12:39:38.470",
"Id": "7762",
"Score": "0",
"Tags": null,
"Title": null
}
|
7762
|
<p>This works well, but can anybody see any faults in this code? If so, could you suggest ways in which I can fix it?</p>
<pre><code>CREATE PROC ValidateUser
(
@Email NVARCHAR(100),
@PasswordHash NVARCHAR(128)
)
AS
IF EXISTS ( SELECT 1
FROM dbo.[User]
WHERE [Email] = @Email
AND PasswordHash = @PasswordHash )
SELECT 'True'
ELSE
SELECT 'False'
</code></pre>
|
[] |
[
{
"body": "<p>The only \"fault\" I see is that you return \"magic strings\" as your result - those are always a bit hard to use, and can cause issues (if you misspell a string).</p>\n\n<p>This is a <strong>boolean check</strong> - you get back True or False - but I would return the <strong>boolean</strong> values - not strings:</p>\n\n<pre><code>CREATE PROC ValidateUser\n (@Email NVARCHAR(100),\n @PasswordHash NVARCHAR(128))\nAS \n IF EXISTS (SELECT *\n FROM dbo.[User]\n WHERE [Email] = @Email AND PasswordHash = @PasswordHash) \n SELECT 1\n ELSE \n SELECT 0\n</code></pre>\n\n<p>Or the other option would be to just return some column from the users table - if that user exists and the password hash matches, you get back a value - otherwise you get NULL:</p>\n\n<pre><code>CREATE PROC ValidateUser\n (@Email NVARCHAR(100),\n @PasswordHash NVARCHAR(128))\nAS \n SELECT UserID \n FROM dbo.[User]\n WHERE [Email] = @Email AND PasswordHash = @PasswordHash) \n</code></pre>\n\n<p>So if the user e-mail and password hash match and exist, then you get back the <code>UserID</code> - otherwise you get NULL. That's also a nice, clear, yes-or-no kind of answer</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T16:09:27.397",
"Id": "12262",
"Score": "2",
"body": "Good suggestions! However, in the second query it might be safer to have a `TOP 1` clause and to eventually return `UserId` as an output parameter."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T05:57:32.867",
"Id": "7766",
"ParentId": "7765",
"Score": "7"
}
},
{
"body": "<p>I would not make this a proc but a function and I woult not return a string. That sort of is all.</p>\n\n<p>Oh, and on top it is simply useless - just pull the hash anyway. There is no logic in there to start with.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T05:57:35.737",
"Id": "7767",
"ParentId": "7765",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "7766",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T05:53:16.113",
"Id": "7765",
"Score": "5",
"Tags": [
"sql",
"validation"
],
"Title": "Validating a user"
}
|
7765
|
<p>I want to prevent double form submissions within a small window, then allow the form to be submitted again.</p>
<p>I wrote this script after looking at several examples, but the global variable is bugging me. I'd welcome any suggestions on improving it.</p>
<pre><code>var aLockedForms= [];
jQuery.fn.preventDoubleSubmit= function() {
jQuery( this ).submit( function() {
if ( this.beenSubmitted )
return false;
this.beenSubmitted= true;
aLockedForms.push( this );
setTimeout( function() {
var domTarget= aLockedForms.shift();
domTarget.beenSubmitted= false;
} ,
1984 );
});
};
</code></pre>
<p>After the DOM is loaded, I run the following:</p>
<pre><code>$( "form" ).preventDoubleSubmit();
</code></pre>
|
[] |
[
{
"body": "<p>Regarding the global variable, you're already using jQuery so why not just attach an attribute or class to the form?</p>\n\n<pre><code>jQuery.fn.preventDoubleSubmit=function(duration) {\n duration = duration || 1984;\n jQuery( this ).submit( function() {\n if ( this.hasClass(\"locked\") ) return false;\n jQuery(this).addClass(\"locked\");\n that = this;\n setTimeout(function() {\n jQuery(that).removeClass(\"locked\");\n }\n , duration );\n });\n};\n</code></pre>\n\n<p>You may want to change the class name to something a little more unique, but that should work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:53:31.220",
"Id": "12254",
"Score": "0",
"body": "The this reference goes a bit strange in setTimeout."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:56:24.863",
"Id": "12255",
"Score": "0",
"body": "I edited to alias `this` as `that`, see if that works for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:49:57.047",
"Id": "7771",
"ParentId": "7769",
"Score": "3"
}
},
{
"body": "<p>You could wrap the entire thing in an anonymous function that you immediately execute:</p>\n\n<pre><code>(function() {\n var aLockedForms = [];\n\n ...\n)();\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> I want to clarify that this is something you can do to eliminate global variables in the future. <a href=\"https://codereview.stackexchange.com/a/7771/8891\">Adam Tuttle's answer</a> is better in this case because it eliminates the variable entirely by properly utilizing the closure inside <code>setTimeout</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T15:29:29.823",
"Id": "7772",
"ParentId": "7769",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7771",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T14:35:22.230",
"Id": "7769",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Prevent Double Form Submit within X seconds"
}
|
7769
|
<p>Here is the code I wrote for the problem at <a href="http://www.interviewstreet.com/recruit/challenges/solve/view/4e1491425cf10/4efa210eb70ac">http://www.interviewstreet.com/recruit/challenges/solve/view/4e1491425cf10/4efa210eb70ac</a> where we need to to print the substring at a particular index from the lexicographicaly-sorted union of sets of substrings of the given set of strings...</p>
<pre><code>import itertools
N = int(raw_input())
S = set()
for n in xrange(N):
W = raw_input()
L = len(W)
for l in xrange(1,L+1):
S=S.union(set(itertools.combinations(W, l)))
print set(itertools.combinations(W, l))
print S
M = int(raw_input())
S = sorted(list(S))
print S
for m in xrange(M):
Q = int(raw_input())
try:
print "".join(S[Q-1])
except:
print "INVALID"
</code></pre>
<p>but it gives me a Memory Error meaning that my code takes up more than 256Mb during execution.</p>
<p>I think the culprit is <code>S=S.union(set(itertools.combinations(W, l)))</code>, but can't really think of a more efficient method for harvesting a unique set of substrings from the given set of strings...</p>
<p>Can you suggest an optimal alternative?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T04:28:43.087",
"Id": "12588",
"Score": "1",
"body": "For starters, type this at the python prompt `>>> import itertools` `>>> for i in itertools.combinations(\"ABCDE\",3):` `... print i`. Getting just what you want? Then you may want to review your definition of substring (and/or contiguous)."
}
] |
[
{
"body": "<p>To successfully pass all test cases you need to implement something more sophisticated like <a href=\"http://en.wikipedia.org/wiki/Suffix_tree\" rel=\"nofollow\">suffix tree</a>. That will allow you to solve this task in O(n) time using O(n) space.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T02:57:40.650",
"Id": "7979",
"ParentId": "7773",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7979",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T15:40:04.423",
"Id": "7773",
"Score": "6",
"Tags": [
"python",
"optimization",
"strings",
"memory-management"
],
"Title": "Memory issues with Find Strings Problem on InterviewStreet"
}
|
7773
|
<p>I recently dived into Ruby, so I want to improve this code. Is this good enough?</p>
<pre><code>def ranksystem
logfile = IO.readlines("some_logfile.log")
logfile.each do |value|
value.gsub!(/[\n]+/, "")
end
logfile.delete("")
logcount = Hash.new(0)
logfile.each do |v|
logcount[v] += 1
end
logarray = logcount.sort_by {|k,v| v}.reverse
finalreturn = ""
logarray.each_with_index do |value, index|
finalreturn = finalreturn + "Rank #{index+1} : #{value[1]} (#{value[0]})\n"
end
finalreturn
end
</code></pre>
<p>This code reads each line in log file like this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>apple
orange
apple
apple
apple
apple
orange
orange
banana
banana
</code></pre>
</blockquote>
<p>and converts like this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Rank 1 : 4 (apple)
Rank 2 : 3 (orange)
Rank 3 : 2 (banana)
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>\"Cool\" enough? It seems fine, if procedural. Depends what you mean by cool.</p>\n\n<p>I might combine a few steps. I'd also refactor and not put everything into one method, since each separate \"chunk\" does very distinct, and different, things. Separation makes testing easier.</p>\n\n<p>The below isn't necessarily any better (and the chunk that creates the report may actually be worse--I'm not sure; it'd be less efficient), but it provides some alternate avenues to explore further.</p>\n\n<pre><code>def get_log_lines name\n logfile = IO.readlines(name)\n logfile.collect { |l| l.gsub(/\\n+/, \"\")}.reject { |l| l == \"\" }\nend\n\ndef ranksystem\n loglines = get_log_lines \"some_logfile.log\"\n logcount = Hash[loglines.group_by {|l| l}.collect {|k, v| [v.size, k]}]\n i = 0\n logcount.keys.sort.reverse.collect { |n| i += 1; \"Rank #{i}: #{n} (#{logcount[n]})\" }.join(\"\\n\")\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T19:13:08.443",
"Id": "7783",
"ParentId": "7774",
"Score": "4"
}
},
{
"body": "<p>Your function would be better if it accepted an argument for the filename.</p>\n\n<p>I think that you are on the right track with <code>logcount = Hash.new(0)</code> and <code>logcount[v] += 1</code>. However, you would be better off instantiating <code>logcount</code> <em>before</em> starting to process the file. That way, <code>logcount</code> is your only data structure. You don't have to construct an array using <code>IO#readlines</code>, and you can discard empty lines on the fly.</p>\n\n<p>The block passed to <code>sort_by</code> could be smarter. The parameters could be more meaningfully named. Sort by <code>-count</code> instead of <code>count</code> to get the list in descending order without having to call <code>reverse</code>.</p>\n\n<p>To build the result string, use <code>Array#join</code>.</p>\n\n<pre><code>def ranksystem(file)\n logcount = Hash.new(0)\n\n File.new(file).each_line do |line|\n line.chomp!\n logcount[line] += 1 unless line.empty?\n end\n\n # Note: .each_with_index.map requires Ruby >= 1.8.7\n # (see http://stackoverflow.com/a/4697573)\n logcount.to_a\n .sort_by { |line, count| -count }\n .each_with_index\n .map { |value, index| \"Rank #{index+1} : #{value[1]} (#{value[0]})\" }\n .join(\"\\n\")\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-31T07:25:13.553",
"Id": "79162",
"ParentId": "7774",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "7783",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T16:08:52.270",
"Id": "7774",
"Score": "5",
"Tags": [
"ruby",
"sorting",
"io"
],
"Title": "Ranking lines of a file according to number of occurrences"
}
|
7774
|
<p>Here are 3 methods which handle my ajax calls. </p>
<p>I loop until pass b.c. I've had problems with the Ajax Object working as expected. This is noted <a href="http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_23421667.html" rel="nofollow">here</a></p>
<pre><code>/**
* Ajax
*/
var Ajax = ( function ()
{
var Ajax = function (element)
{
this.object = this.create();
};
Ajax.prototype.create = function()
{
var request;
try
{
request = new window.XMLHttpRequest();
}
catch( error )
{
try
{
request = new window.ActiveXObject( "Msxml2.XMLHTTP" );
}
catch( error )
{
try
{
request = new window.ActiveXObject( "Microsoft.XMLHTTP" );
}
catch( error )
{
request = false;
}
}
}
return request;
};
Ajax.prototype.use = function( param, ajax_func )
{
var GATEWAY = 'class.ControlEntry.php';
var self = this;
this.object.open( "POST", GATEWAY, true );
this.object.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
this.object.setRequestHeader( "Content-length", param.length );
this.object.setRequestHeader( "Connection", "close" );
this.object.onreadystatechange = function()
{
if( this.readyState === 4 )
{
if( this.status === 200 )
{
ajax_func( this.responseText );
return true;
}
else
{
self.invoke( param, ajax_func );
return false;
}
}
};
this.object.send( param );
return true;
};
Ajax.prototype.invoke = function( param, ajax_func )
{
var state = false,
count = 1;
while( state === false && count <= 5 )
{
if( count !== 1 )
{
alert( 'Ajax Object Use Failed | Try Again ');
}
state = this.use( param, ajax_func );
count++;
}
return state;
};
return Ajax;
} () );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T16:53:18.470",
"Id": "12264",
"Score": "0",
"body": "What's your question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:15:16.773",
"Id": "12269",
"Score": "0",
"body": "First question would be how do I not loop my ajax...has anyone else had an issue with the 12030 error code...showing up about 10% of the time..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T09:45:37.793",
"Id": "12323",
"Score": "0",
"body": "It seems to me that if the AJAX request has a genuine failure (maybe the path doesn't exist, or there's a network issue, or some kind of error on the server); then you'll be stuck in an endless loop. Maybe you should limit the number of times that you call ajaxRepeat. Also, I don't much like the names of your functions; it's not very clear what each one does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T14:16:07.883",
"Id": "12326",
"Score": "0",
"body": "This code doesn't work, it does not belong here ([faq](http://codereview.stackexchange.com/faq)). This is troubleshooting that belongs on SO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T03:21:39.440",
"Id": "12369",
"Score": "0",
"body": "'issue with the 12030 error code...showing up about 10% of the time' - This is softawre, working 90% of the time doesn't cut it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T09:09:58.117",
"Id": "12402",
"Score": "0",
"body": "Yes, your code looks much nicer now. Probably the next step is to work out where the 12030 errors are coming from. Is there any particular URL that's making them happen? Or does it happen for lots of different URLs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T18:44:56.997",
"Id": "17472",
"Score": "0",
"body": "@Paul - please direct you comments to Microsoft."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T18:46:35.403",
"Id": "17473",
"Score": "0",
"body": "@David - I posted the link stating that this is a known issue with IE above."
}
] |
[
{
"body": "<p>This is the real bad practice.</p>\n\n<ol>\n<li>The Ajax is Asynchronous, you never know how the response will back.</li>\n<li>Javascript is the single thread language, so that means in one time period just can run one function. in your repeatUseAjax function, you try to loop send ajax. the result will be you will send 5 times ajax call every time when the ajax response failure.And you will never know when the response suceess. what about first failure other success? what about always failure?loop forever?</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-18T18:44:38.197",
"Id": "17471",
"Score": "0",
"body": "I do not try and loop \"send ajax\". If ajax responds with a fail ( it has completed )..then I make another request."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T01:58:52.407",
"Id": "7906",
"ParentId": "7776",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T16:47:47.447",
"Id": "7776",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Ajax Object - 12030 Loop Fix?"
}
|
7776
|
<p>I am about to start a very large project in Ruby. To get myself in the Ruby mindset I have been doing all of my homework and other side work in Ruby. I am hoping that some of you who know Ruby very well can look at this small program I have written and point out areas that aren't written in a Ruby-like fashion. Any and all tips and criticisms would be appreciated.</p>
<p>This program is a menu-based Caesar Cipher with encryption and decryption.</p>
<pre><code>KEY = 3
$caesar_map = {}
#initializes the caesar_map and reads input from the user
#starting point of the program
def init()
#create empty hashes
plain_alphabet = {}
cipher_alphabet = {}
#fill in the alphabet hashes with the letter and its position
#in the english alphabet
"a".upto("z") {|x| plain_alphabet[x] = ((x[0] - "a"[0]) % 26) }
"A".upto("Z") {|x| cipher_alphabet[x] = ((x[0] - "A"[0]) % 26) }
#fill in the caesar_map, maps every letter KEY positions
#to the right in the alphabet
plain_alphabet.each do |k,v|
$caesar_map[k] = cipher_alphabet.index((v+KEY) % 26)
#puts "key: #{k} mapped value: #{cipher_alphabet.index((v+3) % 26)}"
end
#special case, I want spaces to be maintained in the messages
$caesar_map[" "] = " "
#print menu
choice = -1
while(choice != 3)
puts "What would you like to do?"
puts "\n1. Encrypt a message"
puts "\n2. Decrypt a message"
puts "\n3. Exit\n"
choice = Integer(gets.chomp)
if(choice == 1)
puts "Please enter a message you would like to Encrypt\n"
message = gets.chomp
encrypt(message)
elsif(choice == 2)
puts "Please enter a message you would like to Decrypt\n"
message = gets.chomp
decrypt(message)
elsif(choice == 3)
abort("Exiting...")
else
puts "You didn't enter a valid choice. Enter a number between 1..3\n"
end
end
end
#encrypts a plaintext message using the caesar cipher
def encrypt(plaintext)
#make sure the message is in lowercase
plaintext.downcase!
ciphertext = ""
#fill in the ciphertext with mapping information in the caesar_map
plaintext.split("").each do |c|
ciphertext += $caesar_map[c]
end
#print the encrypted ciphertext
puts "\n plaintext: #{plaintext}\nciphertext: #{ciphertext}\n\n"
end
#decrypts a ciphertext message using the caesar cipher
def decrypt(ciphertext)
#make sure the ciphertext is in uppercase
ciphertext.upcase!
plaintext = ""
#fill in the plaintext with mapping information in the caesar_map
ciphertext.split("").each do |c|
plaintext += $caesar_map.index c
end
#print the decrypted plaintext
puts "\n ciphertext: #{ciphertext}\n plaintext: #{plaintext}\n\n"
end
#start the program
init()
</code></pre>
|
[] |
[
{
"body": "<p>I'd initialize with something closer to this (although I might inline the two arrays):</p>\n\n<pre><code>plain_alphabet = ('a'..'z').to_a\ncipher_alphabet = ('A'..'Z').to_a.rotate KEY\n$caesar_map = Hash[plain_alphabet.zip cipher_alphabet]\n</code></pre>\n\n<p>The en/decryption (which could likely be handled by the built-in <code>tr</code> method) might look more like:</p>\n\n<pre><code>plaintext.split(\"\").inject(\"\") {|s, c| s << $caesar_map[c]}\n</code></pre>\n\n<p>I'd put the whole thing in a class, too; skip the global.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T18:03:01.890",
"Id": "12271",
"Score": "0",
"body": "oh wow, that is a lot simpler. Then I dont have to maintain the position, because the array with already be mapped to the right letter"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T18:05:00.990",
"Id": "12272",
"Score": "0",
"body": "@HunterMcMillen I don't know why you'd need to; it's a simple substitution--what do you need the position for? I could just be missing something. Ninja edit!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T22:37:17.560",
"Id": "12292",
"Score": "0",
"body": "Could you elaborate on why you would place this in a class? It seems too small of a program to specialize in any way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T23:28:58.463",
"Id": "12297",
"Score": "1",
"body": "@HunterMcMillen Why *wouldn't* you? But to elaborate, it has class-like behavior, encryption is a general-purpose concept with multiple implementations, has multiple potential extension points, etc. Why is everything you did encapsulated in methods except for a constant and a global? Clearly you saw the need for *some* encapsulation--would putting a `class Foo` around it have been significantly different? For a trivial extra effort it could have been a module/mixin or class with better encapsulation and semantics."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:58:04.573",
"Id": "7780",
"ParentId": "7777",
"Score": "5"
}
},
{
"body": "<p>Some points about making your code look more like idiomatic Ruby:</p>\n\n<ul>\n<li><p>Use <code>nil</code>.</p>\n\n<pre><code>choice = -1\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>choice = nil\n</code></pre></li>\n<li><p>Don't wrap your conditional in brackets:</p>\n\n<pre><code>while(choice != 3)\nif(choice == 1)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>while choice != 3\nif choice == 1\n</code></pre></li>\n<li><p>Instead of initializing a variable to an empty array, use <code>map</code> to convert one array directly into the new form and use <em>that</em> to initialize your variable:</p>\n\n<p><strike>Instead of this:</strike> Hashes != arrays, sorry. The principal still applies, even if this example isn't equivalent:</p>\n\n<pre><code> #create empty hashes\n plain_alphabet = {}\n cipher_alphabet = {} \n\n\"a\".upto(\"z\") {|x| plain_alphabet[x] = ((x[0] - \"a\"[0]) % 26) }\n\"A\".upto(\"Z\") {|x| cipher_alphabet[x] = ((x[0] - \"A\"[0]) % 26) }\n</code></pre>\n\n<p>do this:</p>\n\n<pre><code>plain_alphabet = (\"a\"..\"z\").map { |x| (x[0] - \"a\"[0]) % 26 }\ncipher_alphabet = (\"A\"..\"Z\").map { |x| (x[0] - \"A\"[0]) % 26 }\n</code></pre>\n\n<p>And instead of this:</p>\n\n<pre><code>ciphertext = \"\"\n\n#fill in the ciphertext with mapping information in the caesar_map\nplaintext.split(\"\").each do |c|\n ciphertext += $caesar_map[c]\nend\n</code></pre>\n\n<p>do this:</p>\n\n<pre><code>ciphertext = plaintext.split(\"\").map { |c| $ceasar_map[c] }.join\n</code></pre></li>\n<li><p>Use <code>case</code> when appropriate; rewrite your if/elsif/elsif/else as:</p>\n\n<pre><code>case choice\nwhen 1:\n # ...\nwhen 2:\n # ... \nwhen 3:\n # ...\nelse\n # ...\nend\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T18:00:28.137",
"Id": "7781",
"ParentId": "7777",
"Score": "5"
}
},
{
"body": "<pre><code>KEY = 3 \n$caesar_map = {}\n</code></pre>\n\n<p>In Ruby, like most languages, global variables are often a sign of bad design. In this making <code>$caesar_map</code> global makes it difficult to use your caeser cipher with different keys (though your program isn't layed out to support that anyway (and you even made <code>KEY constant</code>)) because in order to do that you'd have to override the global variable each time you want to use a different key.</p>\n\n<p>I would recommend to create a class which takes the key as a parameter and then creates the map as a parameter. So you could create multiple instances with different keys and then use their <code>encode</code> and <code>decode</code> methods without them affecting each other.</p>\n\n<p>Except that pre-calculating the mappings between characters seems completely unnecessary to me, so that's not even necesarry. You could just write <code>encode</code> and <code>decode</code> so that they take the key as a parameter and just do the translation without a map. This way you could call the methods without having to initialize any global data structures or objects. And you could just implement <code>decode</code> by calling <code>encode</code> with a negative key, which greatly simplifies your implementation and gets rid of code duplication.</p>\n\n<hr>\n\n<p>Further your <code>encode</code> and <code>decode</code> methods should return string rather than printing their results. It is a good design practice to seperate the places that do IO from the places that calculate stuff. That makes it easier to reuse your logic-methods.</p>\n\n<p>Also you shouldn't call your <code>init</code> method <code>init</code>. That name suggests that all it does is initializing somethign (say <code>$caesar_map</code>), but in fact it does everything. A more appropriate name might be <code>main</code>. Or you could just get rid of the method altogether.</p>\n\n<hr>\n\n<pre><code>\"a\".upto(\"z\") {|x| plain_alphabet[x] = ((x[0] - \"a\"[0]) % 26) }\n\"A\".upto(\"Z\") {|x| cipher_alphabet[x] = ((x[0] - \"A\"[0]) % 26) }\n</code></pre>\n\n<p>As I already said, you don't really need to precalculate anything, so this becomes superfluous, but here's some comments for when you write similar code in the future:</p>\n\n<p><code>\"a\"[0]</code> returns <code>\"a\"</code> in ruby 1.9, so you should use <code>.bytes[0]</code> instead of just <code>[0]</code> for 1.9 compatibility. Also the <code>% 26</code> is completely unnecessary here as the number will already be between 0 and 26.</p>\n\n<p>And as has already been pointed out by Dave, using <code>map</code> or other higher-order functions for things like this is a lot more idiomatic. When you want to build hashes like this, you might also take advantage of the fact that <code>Hash.new</code> takes a block.</p>\n\n<hr>\n\n<pre><code>$caesar_map[\" \"] = \" \"\n</code></pre>\n\n<p>You special case \" \", but nothing else. If the string contains anything except letters or spaces, your method will break.</p>\n\n<hr>\n\n<pre><code>choice = Integer(gets.chomp)\n</code></pre>\n\n<p>This will throw an exception when the user enters a non-number. You might perhaps catch that exception and give the user something a bit more friendly than an exception-message.</p>\n\n<hr>\n\n<pre><code>#make sure the message is in lowercase\nplaintext.downcase!\n</code></pre>\n\n<p>Returning the result with the same case as the original had (instead of lower casing the input string and then using upper case letters in the translation) seems much preferable.</p>\n\n<hr>\n\n<pre><code>plaintext.split(\"\").each do |c|\n ciphertext += $caesar_map[c]\nend\n</code></pre>\n\n<p>Building strings up imperatively like this is often not very idiomatic ruby. In this case I'd use <code>gsub</code>:</p>\n\n<pre><code>plaintext.gsub(/[a-zA-Z]/) do |c|\n $caesar_map[c]\nend\n</code></pre>\n\n<p>Since this only replaces letters and leaves everything else as-is, this also gets rid of your problem of not supporting non-letters (and gets rid of the need to special-case \" \" in the map).</p>\n\n<p>If you follow my advice from earlier and get rid of the global map, you'll have to adjust the above appropriately, of course.</p>\n\n<hr>\n\n<pre><code>$caesar_map.index c\n</code></pre>\n\n<p>Note that using <code>Hash#index</code> is <code>O(n)</code>, so this is terribly inefficient (same goes for when you used it earlier in <code>init</code>). If you follow my advice and don't use a map, this will be much more inefficient.</p>\n\n<hr>\n\n<p>In summary, here's how I'd implement the en- and decoding:</p>\n\n<pre><code># Shifts a given letter by key places in the alphabet, wrapping around after \"z\",\n# keeping the case in tact.\n# Do not call with anything that's not a letter between a and z (or A and Z)\ndef shift_letter(letter, key)\n case letter\n when \"a\"..\"z\"\n base = \"a\".bytes[0]\n when \"A\"..\"Z\"\n base = \"A\".bytes[0]\n end\n\n # Set letter_index to the index of the given letter (i.e. 0 for A or a, 1 for b etc.)\n letter_index = letter.bytes[0] - base\n\n # Calculate the index of the mapped letter\n mapped_index = (letter_index + key) % 26\n\n # Convert index back to letter\n (base + mapped_index).chr\nend\n\n# Encrypts a plaintext message using the Caesar Cipher\ndef encode(plaintext, key)\n # Replace each letter in the string with the result of shifting\n # that letter by key places\n plaintext.gsub(/[a-zA-Z]/) do |c|\n shift_letter(c, key)\n end\nend\n\n# Decrypts a ciphertext message using the Caesar Cipher\ndef decode(ciphertext, key)\n encode(ciphertext, -key)\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T14:33:23.613",
"Id": "12404",
"Score": "0",
"body": "(The upper case letters are the translate-to, not translate-from, hence the to_lower.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T15:25:15.823",
"Id": "12405",
"Score": "0",
"body": "@DaveNewton Right, good point. Doing it that way still seems strange to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T15:37:30.357",
"Id": "12408",
"Score": "0",
"body": "Agreed; it threw me as well."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T02:59:12.217",
"Id": "7790",
"ParentId": "7777",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7781",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:35:06.150",
"Id": "7777",
"Score": "4",
"Tags": [
"ruby",
"caesar-cipher"
],
"Title": "Menu-based Caesar Cipher with encryption and decryption"
}
|
7777
|
<p>Quoting the wikipedia <a href="http://en.wikipedia.org/wiki/Structure_and_Interpretation_of_Computer_Programs" rel="nofollow">page</a>:</p>
<blockquote>
<p>Structure and Interpretation of Computer Programs (SICP) is a textbook published in 1984 about general computer programming concepts from MIT Press written by Massachusetts Institute of Technology (MIT) professors Harold Abelson and Gerald Jay Sussman, with Julie Sussman. It was formerly used as the textbook of MIT introductory programming class and at other schools.</p>
<p>Using a dialect of the Lisp programming language known as Scheme, the book explains core computer science concepts, including abstraction, recursion, interpreters and metalinguistic abstraction, and teaches modular programming.</p>
</blockquote>
<p>The book is available <a href="http://mitpress.mit.edu/sicp/full-text/book/book.html" rel="nofollow">online</a>, with accompanying video <a href="http://groups.csail.mit.edu/mac/classes/6.001/abelson-sussman-lectures/" rel="nofollow">lectures</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:48:34.520",
"Id": "7778",
"Score": "0",
"Tags": null,
"Title": null
}
|
7778
|
Structure and Interpretation of Computer Programs (SICP) is a classic textbook for learning how to program. The language used in the book is Scheme, a dialect of Lisp.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T17:48:34.520",
"Id": "7779",
"Score": "0",
"Tags": null,
"Title": null
}
|
7779
|
<p>I'm having a hard time creating a design (due to my lack of experience). I need a little of help to create the Model.</p>
<p>It's a mathematics system. I've created an <code>IProblem</code> interface with a function <code>IsCorrect</code>, this function helps me to know if the result is correct or not (by parameter). It also has a function <code>CreateAnswer()</code> because some problems have 1, 2 or many answers.</p>
<pre><code>public interface IProblem
{
bool IsCorrect(IAnswer answer);
IAnswer CreateAnswer();
}
</code></pre>
<p><code>IAnswer</code> is an interface which contains the answer, it can be a string, integer, decimal, several, multiple choice, etc..</p>
<pre><code>public interface IAnswer
{
}
public class IntegerAnswer : IAnswer
{
public int Number { get; set; }
}
public class StringAnswer : IAnswer
{
public string Number { get; set; }
}
public class DecimalAnswer : IAnswer
{ ... }
public class MultipleChoiceAnswer : IAnswer
{ ... }
</code></pre>
<p>Here is a concrete Problem:</p>
<pre><code>public class BinaryProblem : IProblem, IEquatable<BinaryProblem>
{
private int _number1;
private int _number2;
public int Number1
{
get { return _number1; }
set { _number1 = value; }
}
public int Number2
{
get { return _number2; }
set { _number2 = value; }
}
public BinaryProblem(int number1, int number2)
{
this.Number1 = number1;
this.Number2 = number2;
}
public bool IsCorrect(IAnswer answer)
{
IntegerAnswer integerAnswer = (IntegerAnswer)answer;
return integerAnswer.Number == _number1 + _number2;
}
public IAnswer CreateAnswer()
{
return new IntegerAnswer();
}
public override string ToString()
{
return _number1 + " + " + _number2;
}
public override bool Equals(object obj)
{
if (obj is BinaryProblem)
return this.Equals(obj);
else
return false;
}
public bool Equals(BinaryProblem other)
{
return this.Number1 == other.Number1 &&
this.Number2 == other.Number2;
}
}
</code></pre>
<p>And to run this:</p>
<pre><code> // Binary problem test
BinaryProblem binary = new BinaryProblem(4, 5);
IntegerAnswer answer = (IntegerAnswer)binary.CreateAnswer();
answer.Number = 9;
binary.IsCorrect(answer);
</code></pre>
<p>I realized it is necessary to store the correct answer. For example, if it's a problem where the stated question is: convert decimal to fraction.</p>
<p><img src="https://i.stack.imgur.com/WXOsE.jpg" alt="enter image description here"></p>
<p>My limitation here is that I need to know the result at the moment the problem is created. I'm convinced that the Answer doesn't belong to the problem, but also, the class needs to know the correct answer when it is created. Because 0.111 it's confusing, it can be 1/9 or 111/1000, so I prefer to store the correct answer in some place.</p>
<p>So, where should I modify the model?</p>
<p>I created a factory where one can create problems, which contains values of necessary properties and the correct answer. I'd like to know if the performance or OOP rules are correct, or if there are things to do to improve the factory.</p>
<p>I've modified the answers by a generic class.</p>
<p>This is the interface for my factories:</p>
<pre><code>public interface IFactory<T> where T : IProblem
{
T CreateProblem();
}
</code></pre>
<p>My base class factory:</p>
<pre><code>public abstract class Factory<T> : IFactory<T> where T : IProblem
{
protected const int DEFAULT_SIZE = 20;
protected const int MAX_SIZE = 100;
protected static Random rnd;
protected static LinkedListNode<T> actualNode;
protected static LinkedList<T> problems;
public virtual int TotalProblemsPossible { get; set; }
protected Factory(Levels level)
{
Initialize();
ConfigureLevels(level);
FirstTime();
}
public virtual void FirstTime()
{
if (rnd == null) rnd = new Random(MAX_SIZE);
if (problems == null)
{
problems = new LinkedList<T>();
Generate(problems);
}
actualNode = problems.First;
}
public virtual T CreateProblem()
{
if (actualNode.Next == null)
{
Generate(problems);
}
actualNode = actualNode.Next;
return actualNode.Value;
}
private void Generate(LinkedList<T> problems)
{
for (int i = 0; i < DEFAULT_SIZE; i++)
{
T newProblem;
int bucles = 0;
do
{
if (bucles == 50) throw new InvalidOperationException();
newProblem = Generate();
bucles++;
} while (problems.Contains(newProblem));
problems.AddLast(newProblem);
}
}
protected virtual void Initialize()
{
}
protected abstract T Generate();
protected abstract void ConfigureLevels(Levels level);
}
</code></pre>
<p>And a particular factory. At this factory case, I create a class called Bound which contains limits for a number, and gets some numbers randomly to create the problem.</p>
<pre><code>public class BinaryProblemFactory : Factory<BinaryProblem>
{
private Bound<int> Bound { get; set; }
public BinaryProblemFactory(Levels level)
: base(level)
{
}
protected override void Initialize()
{
Bound = new Bound<int>();
base.Initialize();
}
protected override void ConfigureLevels(Levels level)
{
switch (level)
{
case Levels.Easy:
this.Bound.Min = 10;
this.Bound.Max = 100;
break;
case Levels.Normal:
this.Bound.Min = 50;
this.Bound.Max = 200;
break;
case Levels.Hard:
this.Bound.Min = 100;
this.Bound.Max = 10000;
break;
}
}
protected override BinaryProblem Generate()
{
BinaryProblem problem;
int number1 = rnd.Next(Bound.Min, Bound.Max);
int number2 = rnd.Next(Bound.Min, Bound.Max);
Answer<int> correctValue = new Answer<int>(number1 + number2);
problem = new BinaryProblem(number1, number2, correctValue);
return problem;
}
}
</code></pre>
<p>The idea is to do something similar with each problem type I want to add to the program. What do you think?</p>
<p>For testing:</p>
<pre><code> BinaryProblemFactory factory = new BinaryProblemFactory(Levels.Normal);
List<BinaryProblem> problemList = new List<BinaryProblem>();
for (int i = 0; i < 50; i++)
{
BinaryProblem binary2 = (BinaryProblem)factory.CreateProblem();
problemList.Add(binary2);
}
</code></pre>
<p><a href="http://www.mediafire.com/?nj7nxdc4ategn0w" rel="nofollow noreferrer">Here is the current project</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T20:11:24.060",
"Id": "12278",
"Score": "1",
"body": "Not a direct answer to your question, but you should override the `bool Equals(object)` method instead of (or in addition to) providing you own typed Equals method. Also, you should override the `int GetHashCode()` method. This will ensure that your object's instances are treated correctly when they are compared by things like the standard .NET collection classes."
}
] |
[
{
"body": "<p>Firstly, do you really need it to be that generic? You support arbitrary types and numbers of answers. But unnecessary genericness just make the design overly complicated. If you are only going to every have a single number answer, then just write code to do that. </p>\n\n<p>Secondly, you store the answers on the Problem object. But the answers given are not a property of the problem. It makes more sense to have the problem take in the answers as a parameter to the IsCorrect() function. </p>\n\n<p>Thirdly, your problem interfaces don't appear very useful. It seems that I get access and presumably modify the given answers, and then check if the answers are correct. But what about finding out what the problem is? There's not much point in an interface if you are just going to have to cast down to the actual class to do any work. </p>\n\n<p>Fourthly, your provide getters/setters on the numbers and such for the problem. Do you really need them? Are you really changing the problems after they are created?</p>\n\n<p>Fifthly, an obvious way to use OOP here would be to one class for each operator (multiple, divide, add, subtract, etc). </p>\n\n<p>The way I'd approach this:</p>\n\n<pre><code>interface IProblem\n{\n String GetQuestion();\n bool CheckAnswer(int answer);\n}\n\nclass BinaryOperatorProblem : IProblem\n{\n int number1, number2;\n BinaryOperatorProblem(int number1, int number2);\n}\n\nclass AdditionProblem\n{\n String GetQuestion()\n {\n return \"%d + %d\" % (number1, number2);\n }\n\n bool CheckAnswer(int answer)\n {\n return answer == number1 + number2;\n }\n}\n</code></pre>\n\n<p>Notes: I don't do C# so above syntax is mostly guesses. I also don't know much about your problem, so you mileage will vary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T05:26:35.123",
"Id": "12393",
"Score": "0",
"body": "Well, I really need to store the values which the student wrote. Yes, I agree with that the generic interface is causing much trouble.\n\nSo do you think is better to maintain another interface for the answers or results?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T05:55:26.380",
"Id": "12396",
"Score": "0",
"body": "And some problems will need several answers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T18:56:34.137",
"Id": "12411",
"Score": "0",
"body": "@DarfZon, if you need multiple answers I'd pass the answer as an array instead. Without a better idea what you are doing I'm not sure where I'd store the answers, but I wouldn't store them with the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T19:15:56.930",
"Id": "12413",
"Score": "0",
"body": "okay, by the momment, I've uploaded the project in mediafile (check the post, below).\n\nThe idea which I have, is to store the problem and answers in a single class, where I plan later to serialize.\n\nI'm not ready to do that yet, but that's the idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T20:40:31.317",
"Id": "12417",
"Score": "0",
"body": "@DarfZon, but why do you want them in the same class? They are distinct concepts, don't necessarily have a one-to-one relationship, so it doesn't make any sense to me to put in them in one class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T21:14:54.083",
"Id": "12418",
"Score": "0",
"body": "well, maybe I'm wrong.. so according to your model, how can I save the answers values?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T22:30:02.747",
"Id": "12420",
"Score": "0",
"body": "@DarfZon, as part of an answers class? I'm not sure where you see a problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T23:01:31.913",
"Id": "12421",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/2217/discussion-between-darf-zon-and-winston-ewert)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T22:59:30.510",
"Id": "12466",
"Score": "0",
"body": "I've updated the model"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T00:36:12.777",
"Id": "12469",
"Score": "0",
"body": "@DarfZon, the correct answer is perfectly fine to store as part of the question. The correct answer is a property of the question. Its just the answers that the students give that isn't a property of the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T21:45:29.097",
"Id": "12636",
"Score": "0",
"body": "I've added in the code project a factory, where creates the problem and pass the correct answer. Can you check it out if the solution is good or am I breaking some OOP principles?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-29T03:15:37.360",
"Id": "13164",
"Score": "0",
"body": "Excuse me Winston, can you take a look at this post: http://codereview.stackexchange.com/questions/8401/how-to-add-a-random-feature-for-a-factory-design ? Is a part of my project. Sorry if I'm very bothersome."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T04:45:30.107",
"Id": "7834",
"ParentId": "7784",
"Score": "4"
}
},
{
"body": "<p>Declaring the interfaces as below might proof useful:</p>\n\n<pre><code>public interface IProblem<T>\n{\n bool IsCorrect(IAnswer<T> answer);\n IAnswer<T> CreateAnswer();\n}\n\npublic interface IAnswer<T>\n{\n T Value { get; set; }\n}\n\npublic class Answer<T> : IAnswer<T>\n{\n public T Value { get; set; }\n}\n</code></pre>\n\n<p>This would allow for the following implementation:</p>\n\n<pre><code>public class BinaryProblem : IProblem<int>, IEquatable<BinaryProblem>\n{\n private int _number1;\n private int _number2;\n\n // .....\n\n public bool IsCorrect(IAnswer<int> answer)\n {\n return answer.Value == _number1 + _number2;\n }\n\n public IAnswer<int> CreateAnswer()\n {\n return new Answer<int>();\n }\n\n //....\n}\n</code></pre>\n\n<p>And can save you a ton of descendants, reduce the amount of knowledge you need within an <code>IProblem</code> implementation, while still offering the possibility of creating very specialized <code>IAnswer</code> implementations. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T16:42:20.623",
"Id": "12507",
"Score": "0",
"body": "thanks for the advise. I started doing this, but generics was causing much trouble because, I guess later I need to put all those answers into an array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T21:45:59.783",
"Id": "12637",
"Score": "0",
"body": "the project is updated! please read the edit and prefer download it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T12:18:52.267",
"Id": "12665",
"Score": "0",
"body": "@DarfZon: No offense, but this is not a \"let's-build-a-project-together\" forum. If you have a specific piece of code that you want reviewed, feel free to post it in a separate question. If you have a problem, feel free to post it on the appropriate forum. But this one question is not supposed to be a continuing saga of your project."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-20T17:35:05.777",
"Id": "12681",
"Score": "0",
"body": "All right Willem, I'll bear in mind next time."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-17T08:44:12.327",
"Id": "7880",
"ParentId": "7784",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7834",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T18:10:28.270",
"Id": "7784",
"Score": "7",
"Tags": [
"c#",
"quiz",
"abstract-factory"
],
"Title": "Factory for mathematics Q&A"
}
|
7784
|
<p>The Javascript libraries have pretty complicated functions to calculate an element's offset on the page. I wrote the following function that works in all the places I need it, and I've tested a few edge cases as well. It adds the element's <code>offsetTop</code> to its parent's <code>offsetTop</code> all the way up the DOM to the <code>document</code>. Can someone give me an example of where this <em>wouldn't</em> work?</p>
<p>This demo shows its results compared to jQuery's <code>offset().top</code> function.</p>
<p>Demo: <a href="http://jsfiddle.net/ThinkingStiff/5aGqM/" rel="nofollow">http://jsfiddle.net/ThinkingStiff/5aGqM/</a></p>
<pre class="lang-js prettyprint-override"><code>window.Object.defineProperty( Element.prototype, 'documentOffsetTop', {
get: function () {
return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
}
} );
</code></pre>
<p>UPDATE:<br>
I was looking for places where traversing up the DOM and adding the offset doesn't work in current browsers. As @Akkuma pointed out, <code>Object.defineProperty</code> doesn't work in earlier IEs.</p>
|
[] |
[
{
"body": "<p>For starters, this doesn't work in IE7 or IE8. I'm assuming you knew that, although you never mentioned compatibility if any you were aiming for.</p>\n\n<p>I rewrote what you made, to work in IE7 & IE8, so you can see where it fails. It is available at <a href=\"http://jsfiddle.net/Akkuma/Xem3B/\" rel=\"nofollow\">http://jsfiddle.net/Akkuma/Xem3B/</a></p>\n\n<p>You'll find the following not working correctly in IE8 compared to the latest Chrome Dev 18 static, static (static wrapped), fixed/absolute (side), absolute/relative/static (absolute/relative wrapped), relative, and fixed/absolute (bottom).</p>\n\n<p>In jQuery they do several different compatibility checks for whether a browser adds the border, for relative/static/fixed positioning, whether the browser subtracts the borders for overflows that are something other than visible. It appears modern browsers should support your approach just fine.</p>\n\n<p>Your code appears to work fine in IE9, so if you aren't supporting IE8 & 7 your code should be good to go. However, if you take a look at jQuery's code you'll find they do not have to recursively traverse up the tree to calculate the offset in modern browsers that support <code>getBoundingClientRect</code>. The trade off is obviously one of simplicity (your own code) vs performance. I haven't verified which is faster, but I would expect jQuery's approach to keep getting faster the deeper the element is in the tree compared to your documentOffsetTop.</p>\n\n<p><strong>Update:</strong> If you haven't seen it, here is an older explanation from John Resig on it and what additional things they had to do (note this is from 2008, so the links are broken and I'm sure they may have modified it more) <a href=\"http://ejohn.org/blog/getboundingclientrect-is-awesome/\" rel=\"nofollow\">http://ejohn.org/blog/getboundingclientrect-is-awesome/</a>. Additionally, here is the <a href=\"https://developer.mozilla.org/en/DOM/element.getBoundingClientRect#Returns\" rel=\"nofollow\">Mozilla documentation</a> detailing how to properly use it cross-browser.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-19T10:06:13.540",
"Id": "12612",
"Score": "0",
"body": "Ooooh, getBoundingClientRect. I like. I was less concerned with the wrapper (window.Object.defineProperty which I guess is the IE problem, but I only target the latest browsers anyway), and more concerned with whether traversing up the DOM works in all cases. It looks like getBoundingClientRect is preferred way. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T19:22:23.633",
"Id": "7935",
"ParentId": "7785",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7935",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T19:36:45.130",
"Id": "7785",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Where will this .offsetTop() function fail?"
}
|
7785
|
<p>I am currently developing a new breed of 3D engine for my upcoming thesis and I really liked the C# properties, but now I am on C++11 for obvious reasons. Since I couldn't find it elsewhere, I tried to write my own property mechanism that shall nicely integrate with C++.</p>
<p>I'd appreciate expert feedback on my class (or at least people who know C++11 much better than I do); after all I am working with C++ for just a few weeks now.</p>
<p>The usage of my <code>PROPERTY<T></code> class is like this:</p>
<pre><code>struct MyClass{
PROPERTY<int> myProp;
}
MyClass m = MyClass();
m.myProp *= 3;
int val = m.myProp;
</code></pre>
<p>And all the other stuff you can think of...</p>
<p>While it is rather easy to accomplish the obvious (see above) of such a mechanism, it gets a little more complicated if you also want to take into account lambda expressions as well as rare constructs (where all three operator template parameters are of a different type) along the lines of:</p>
<pre><code>PROPERTY<NgMatrix> myMat;
PROPERTY<NgVector3> myVec;
PROPERTY<NgVector4> res = myMat * myVec;
</code></pre>
<p>This obviously requires the *operator already to be implemented on <code>NgMatrix4</code>. The property mechanism just forwards them.</p>
<p>I posted the update below, since there are quite a lot of changes. If no one has an idea how to get rid of using member variables for storing the getter/setter, I will drop this approach. It just has too much memory footprint as it is now. But maybe someone still has use for this class and for me it was also a chance to further play around with C++.</p>
<p>Adding accessors was easier said than done, but here it is:</p>
<pre><code>template<class T, class TGetter = boost::function<T& ()>, class TSetter = boost::function<void (T)>>
struct PROPERTY
{
template<class X, class Y, class Z> friend struct PROPERTY; // makes this a friend to all instanciations
private:
TGetter m_Getter;
TSetter m_Setter;
T m_ValueIfNoAccessors;
T& get()
{
if(!m_Getter.empty())
return m_Getter();
else
return m_ValueIfNoAccessors;
}
const T& get() const
{
if(!m_Getter.empty())
return m_Getter();
else
return m_ValueIfNoAccessors;
}
void set(T newValue)
{
if(!m_Setter.empty())
m_Setter(newValue);
else
m_ValueIfNoAccessors = newValue;
}
typename typedef PROPERTY<T, TGetter, TSetter> prop_type;
public:
PROPERTY() : m_Getter(), m_Setter(), m_ValueIfNoAccessors() { set(T()); }
PROPERTY(T initValue) : m_Getter(), m_Setter(), m_ValueIfNoAccessors() { set(initValue); }
PROPERTY(TGetter getter) : m_Getter(getter), m_Setter(), m_ValueIfNoAccessors() { set(T()); }
PROPERTY(TGetter getter, TSetter setter) : m_Getter(getter), m_Setter(setter), m_ValueIfNoAccessors() { set(T()); }
operator T() { return get(); }
template<class X, class Y, class Z>
prop_type& operator=(PROPERTY<X,Y,Z>& other)
{
set(other.get());
return *this;
}
template<class TI>
prop_type& operator=(const TI& other)
{
set(other);
return *this;
}
/*
This operator was introduced for simplifying access to call operators:
PROPERTY<boost::function<int (int)>> myFunc;
myFunc(345); // ERROR!
myFunc()(345); // now is valid...
*/
T& operator()() { return get(); }
const T& operator()() const { return get(); }
/*
Beaware of the fact, that anyone really wanting to change the backing value
of a property sure can, by simply doing:
PROPERTY<T> myProp;
T* myRef = myProp.operator->();
So do not rely on Getter/Setter safety in case of any security critical scenario.
*/
T* operator->() { return &get(); }
const T* operator->() const { return &get(); }
template<class TI> prop_type& operator/=(TI newValue) { set(get() / newValue); return *this; }
template<class TI> prop_type& operator+=(TI newValue) { set(get() + newValue); return *this; }
template<class TI> prop_type& operator-=(TI newValue) { set(get() - newValue); return *this; }
template<class TI> prop_type& operator*=(TI newValue) { set(get() * newValue); return *this; }
template<class TI> auto operator/(TI newValue) const -> decltype(T() / TI()) { return get() / newValue; }
template<class TI> auto operator+(TI newValue) const -> decltype(T() + TI()) { return get() + newValue; }
template<class TI> auto operator-(TI newValue) const -> decltype(T() - TI()) { return get() - newValue; }
template<class TI> auto operator*(TI newValue) const -> decltype(T() * TI()) { return get() * newValue; }
};
</code></pre>
<p>Please note that copy-constructor as well as other semantics like that are currently not reflected correctly! You need to add them, but the look very similar to the existing assignment operator.</p>
<p>Now you can use properties the "usual" way in a class, at least if you don't take initialization into account:</p>
<pre><code>struct CTestClass
{
private:
float m_AspectRatio;
int m_Left;
int m_Right;
public:
PROPERTY<float> AspectRatio;
PROPERTY<int> Left;
PROPERTY<int> Right;
CTestClass()
{
AspectRatio = PROPERTY<float>(
[&]() -> float& { return m_AspectRatio; },
[&](float newValue) { m_AspectRatio = newValue; });
Left = PROPERTY<int>(
[&]() -> int& { return m_Left; },
[&](int newValue) { m_Left = newValue; });
Right = PROPERTY<int>(
[&]() -> int& { return m_Right; },
[&](int newValue) { m_Right = newValue; });
}
};
</code></pre>
<p>Accessing these properties look like this and seems "normal":</p>
<pre><code>CTestClass myClass = CTestClass();
myClass.AspectRatio = 1.4;
myClass.Left = 20;
myClass.Right = 80;
myClass.AspectRatio = myClass.AspectRatio * (myClass.Right - myClass.Left);
</code></pre>
<p><strong>EDIT:</strong></p>
<p>It is also possible to overload properties this way, even though it gets a little more cumbersome. You would just need the original setter/getter implemented as class member functions (virtual of course). And the just call them from inside the lambda expressions. Now if you want to override the property of a super class, just override the corresponding setter/getter member function and the original property will be redirected to your new implementation.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T20:53:46.847",
"Id": "12280",
"Score": "3",
"body": "How is this different than having a public field? What's the point?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T20:57:23.907",
"Id": "12281",
"Score": "1",
"body": "The point are accessors... You get notified when you access a property. But like I said, currently the class does not provide the getter/setter mechanism! But that is trivial to add... What I care about now is the operator integration and possible issues and drawbacks of integration with usual code I may have overlooked so far!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T20:59:22.240",
"Id": "12282",
"Score": "3",
"body": "Ok, so how is it different than having public getter/setter member functions, which is what this will end up having? Why bother with the extra layer of indirection? What is it getting you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T21:02:31.550",
"Id": "12283",
"Score": "5",
"body": "There is not really another layer of indirection, since it is hidden and will be optimized away by modern compilers anyway. Many people, including me, find the use of getter/setter member functions quite disgusting and this is why there are languages, as C#, which provide properties. So the \"need\" of properties is not really something to discuss within this thread ;)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T21:06:00.707",
"Id": "12284",
"Score": "0",
"body": "You can think of properties as member variables, calling the getter/setter in the background, without you noticing it..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T21:07:01.037",
"Id": "12285",
"Score": "0",
"body": "I know what properties are. ;-] Perhaps you should implement your accessors before calling this an alternative to getter/setter member functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T21:08:56.963",
"Id": "12286",
"Score": "0",
"body": "Ok, perhaps this was not too clever ;). But I thought everyone would understand what I am willing to do, obviously I was mistaking. I will try to add them as soon as possible..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T21:12:20.737",
"Id": "12287",
"Score": "3",
"body": "The biggest favour you can do yourself, which you'll appreciate perhaps only after a few years, is to forget everything you learnt when doing C# and embrace C++ as a new and very different language."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T21:18:05.260",
"Id": "12288",
"Score": "1",
"body": "I know that C++ is something totally different ;). It is just that properties are such a nice thing and then also easy to implement on compiler side (and they are already there in Visual C++, BTW)... It is not that I really need them but I thought it shall be possible somehow :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T23:14:49.453",
"Id": "12295",
"Score": "0",
"body": "Applying idioms of languages A to language B is counter-productive. Learn the idioms of language B. Having get/set methods on your class is an indication your design is wrong. They cause tight coupling and decrease encapsulation (as you are exposing the internal representation). If you change the internal representation the tight coupling will force you to implement these methods even if there is no good reason too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T23:21:32.097",
"Id": "12296",
"Score": "0",
"body": "@Loki: Yes, there is also something called overengineering ;)... While I agree that properties are not always a good thing, one being the one you pointed out, they are still useful. Or let's say they are eye-candy, but I favor pretty code. Depending on what you want to write, you just have properties in classes and there is no way that any of them will change in the near future. But of course one can expose internals that may change at anytime and in that particular case, the design is wrong, indeed... Properties are not an idiom of C# ;). They are already in C++ but not cross-platform"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T23:31:52.073",
"Id": "12298",
"Score": "1",
"body": "It seems you are aware of the problems: this is just memory overhead (and looks like more coding effort) for no other gain than a tiny bit of syntactic sugar: `a.b = 10;` vs `a.b(10);` and `a.b` vs `a.b()` (getters/setters don't really require more than a set of parenthesis, you don't even need to use the words get and set.) - And since it relies on implicit conversions, it is probably going to mess up template type deduction somewhere and cause completely unnecessary headaches."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T23:45:57.610",
"Id": "12299",
"Score": "0",
"body": "@Uncle: Yes that is the downside when a compiler does not support such elemental constructs. Visual C++ does, so does the intel compiler but unfortunately, I must support GCC as well... And even then dropping GCC support just for the sake of eye candy would be too much ;). There seems to be no obvious way to get rid of the additional memory without compiler support..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-20T01:38:00.957",
"Id": "14349",
"Score": "4",
"body": "Everywhere I go looking into accomplishing this very thing, existing C++ developers are saying that this approach is useless or wrong. Well that's not the case at all. As a person who knows languages that provide this feature as well as C++, this is a nice feature to have and doesn't break any rules. The most common objection I see is that it somehow breaks encapsulation. That's nonsense, since as someone accurately pointed out here it's essentially the same as just having a public get/set for a protected member. It's simply a different style, syntactic sugar and nothing more."
}
] |
[
{
"body": "<p>The idea of encapsulating your properties with a template is not bad, but, you are are missing the power of properties' accessors. There is not much difference on using properties without been able to override them.</p>\n\n<p>Accessors allow a property to \"communicate\" with its containning class,\nand to add extra functuonality if the are declared \"virtual\".</p>\n\n<p>In the following example, I try to implement \"property\" with inheritance & method pointers, instead of templates. I consider the template techique much better.</p>\n\n<p>Please ignore the direct implementation of properties, and check, how the property, interacts with the container class and its members, and viceversa, in the accessors methods. Take a look to the class code related to the accesors.</p>\n\n<p>(The example may not run, I didin't have the real code at hand, so I coded from memory)</p>\n\n<pre><code>// ------------\n// \"properties.hpp\"\n// ------------\n\n// dummy class to contain properties\nclass PropertyBaseClass\n{\npublic:\n PropertyBaseClass() ; \n ~PropertyBaseClass() ;\n} ;\n\nclass PROPERTY\n{\nprotected:\n PropertyBaseClass* Container;\npublic:\n PROPERTY(PropertyBaseClass* AContainer) { Container = AContainer; }\n ~PROPERTY() { Container = NULL ; }\n} ;\n\n// real class with properties\nclass PropertyClass\n{\nprotected:\n List<PROPERTY> Properties;\npublic:\n PropertyBaseClass() { Properties = List<PROPERTY>(); }\n ~PropertyBaseClass() { Properties = NULL; }\n} ;\n\ntypedef\n int (PROPERTY::*IntegerGetter)();\n\ntypedef\n (PROPERTY::*IntegerSetter)(int AValue);\n\nclass IntegerPROPERTY\n{\nprotected:\n PropertyBaseClass* Container;\n\n int Data;\n\n IntegerGetter getter();\n IntegerSetter setter();\npublic:\n PROPERTY(PropertyBaseClass* AContainer) ;\n ~PROPERTY() ;\n\n int getValue() ;\n void setValue(int AValue) ;\n} ;\n\n// ------------\n\n// ...\n\n\n// ------------\n// \"properties.cpp\"\n// ------------\n\nclass PROPERTY\n{\nprotected:\n PropertyBaseClass* Container;\npublic:\n PROPERTY(PropertyBaseClass* AContainer) { Container = AContainer; }\n ~PROPERTY() { Container = NULL ; }\n} ;\n\nIntegerPROPERTY::IntegerPROPERTY(PropertyBaseClass* AContainer, IntegerGetter AGetter, IntegerSetter ASetter)\n{\n this.Container = AContainer;\n this.getter = AGetter;\n this.setter = ASetter;\n}\n\nIntegerPROPERTY::~IntegerPROPERTY()\n{\n this.Container = NULL;\n}\n\nint IntegerPROPERTY::getValue()\n{\n int Result = 0;\n\n if (this.getter != NULL)\n {\n Result = this.getter();\n }\n\n return Result;\n}\n\nvoid IntegerPROPERTY::setValue(int AValue)\n{\n if (this.setter != NULL)\n {\n this.setter(AValue);\n }\n}\n\n// ------------\n\n// ...\n\n\n// ------------\n// \"Example1.cpp\"\n// ------------\n\n// inherits from \"PropertyClass\",\n// not from \"PropertyBaseClass\"\nclass Area: PropertyClass\n{\npublic:\n IntegerPROPERTY* X1;\n IntegerPROPERTY* Y1;\n IntegerPROPERTY* X2;\n IntegerPROPERTY* Y2;\nprotected:\n int PX1;\n int PY1;\n int PX2;\n int PY2;\n\n virtual int getX1(); \n virtual void setX1(int AValue);\n\n virtual int getY1(); \n virtual void setX1(int AValue);\n\n virtual int getX2(); \n virtual void setX2(int AValue);\n\n virtual int getY2(); \n virtual void setY2(int AValue);\n\n int Width();\n int Height();\npublic:\n Area() ;\n\n virtual Prepare();\n} ;\n\nvoid Area::Prepare()\n{\n X1 = new IntegerPROPERTY(&this, &Area::getX1, &Area::setX1);\n Y1 = new IntegerPROPERTY(&this, &Area::getY1, &Area::setY1);\n X2 = new IntegerPROPERTY(&this, &Area::getX2, &Area::setX2);\n Y2 = new IntegerPROPERTY(&this, &Area::getY2, &Area::setY2);\n}\n\nint Area::getX1()\n{\n int Result = PX1; \n return Result;\n}\n\nvoid Area::setX1(int AValue)\n{\n PX1 = AValue;\n}\n\nint Area::getX2()\n{\n int Result = PX2; \n return Result;\n}\n\nvoid Area::setX2(int AValue)\n{\n PX2 = AValue;\n}\n\nvoid Area::setY1(int AValue)\n{\n PY1 = AValue;\n}\n\nint Area::getY2()\n{\n int Result = PY2; \n return Result;\n}\n\nvoid Area::setY2(int AValue)\n{\n PY2 = AValue;\n}\n\nint Area::Width()\n{\n //int Result = (PX2 - PX1); \n\n int Result = (this->X2->getter() - X1->getter()); \n return Result;\n}\n\nint Area::Height()\n{\n //int Result = (PY2 - PY1);\n\n int Result = (this->Y2->getter() - Y1->getter()); \n return Result;\n}\n\nint main(...)\n{\n Area MyArea = new Area();\n MyArea->Prepare();\n\n MyArea->X1->setter(3);\n MyArea->X2->setter(5);\n MyArea->Y1->setter(23);\n MyArea->Y2->setter(25);\n\n cout << \"X1: \" << MyArea->X1->getter(); \n cout << \"Y1: \" << MyArea->Y1->getter(); \n cout << \"X2: \" << MyArea->X2->getter(); \n cout << \"Y2: \" << MyArea->Y2->getter(); \n cout << \"X2: \" << MyArea->Width(); \n cout << \"Y2: \" << MyArea->Height(); \n\n return 0;\n}\n\n// ------------\n</code></pre>\n\n<p>Take a look to the <strong>Width</strong> and <strong>Height</strong> functions. They depend on the value of the properties, but, are part of the class.</p>\n\n<p>I add a second example, its the same previous code, plus using a descendant container class, that validates that the first coordinate is always lesser than the second coordinate, by overriding the accesors.</p>\n\n<pre><code>// ------------\n// \"Example2.cpp\"\n// ------------\n\n// inherits from \"PropertyClass\",\n// not from \"PropertyBaseClass\"\nclass Area: PropertyClass\n{\npublic:\n IntegerPROPERTY* X1;\n IntegerPROPERTY* Y1;\n IntegerPROPERTY* X2;\n IntegerPROPERTY* Y2;\nprotected:\n int PX1;\n int PY1;\n int PX2;\n int PY2;\n\n virtual int getX1(); \n virtual void setX1(int AValue);\n\n virtual int getY1(); \n virtual void setX1(int AValue);\n\n virtual int getX2(); \n virtual void setX2(int AValue);\n\n virtual int getY2(); \n virtual void setY2(int AValue);\n\n int Width();\n int Height();\npublic:\n Area() ;\n\n virtual Prepare();\n} ;\n\nclass ValidArea: Area\n{\nprotected:\n virtual void setX1(int AValue);\n virtual void setX1(int AValue);\n virtual void setX2(int AValue);\n virtual void setY2(int AValue);\npublic:\n Area() ;\n\n virtual Prepare();\n} ;\n\nvoid Area::Prepare()\n{\n X1 = new IntegerPROPERTY(&this, &Area::getX1, &ValidArea::setX1);\n Y1 = new IntegerPROPERTY(&this, &Area::getY1, &ValidArea::setY1);\n X2 = new IntegerPROPERTY(&this, &Area::getX2, &ValidArea::setX2);\n Y2 = new IntegerPROPERTY(&this, &Area::getY2, &ValidArea::setY2);\n}\n\nvoid ValidArea::setX1(int AValue)\n{\n if (AValue > PX2)\n {\n PX1 = PX2; \n PX2 = AValue; \n }\n else\n {\n PX1 = AValue; \n }\n}\n\nvoid ValidArea::setX2(int AValue)\n{\n if (AValue < PX1)\n {\n PX1 = PX2; \n PX2 = AValue; \n }\n else\n {\n PX1 = AValue; \n }\n}\n\nvoid ValidArea::setY1(int AValue)\n{\n if (AValue > PY2)\n {\n PY1 = PY2; \n PY2 = AValue; \n }\n else\n {\n PY1 = AValue; \n }\n}\n\nvoid ValidArea::setY2(int AValue)\n{\n if (AValue < PX1)\n {\n PX1 = PX2; \n PX2 = AValue; \n }\n else\n {\n PX1 = AValue; \n }\n}\n\nint main(...)\n{\n Area MyArea = new Area();\n MyArea->Prepare();\n\n MyArea->X1->setter(3);\n MyArea->X2->setter(5);\n MyArea->Y1->setter(23);\n MyArea->Y2->setter(25);\n\n cout << \"X1: \" << MyArea->X1->getter(); \n cout << \"Y1: \" << MyArea->Y1->getter(); \n cout << \"X2: \" << MyArea->X2->getter(); \n cout << \"Y2: \" << MyArea->Y2->getter(); \n cout << \"X2: \" << MyArea->Width(); \n cout << \"Y2: \" << MyArea->Height(); \n\n return 0;\n}\n</code></pre>\n\n<p>In these examples, the properties, wheter templates or inheritance, have fields that represent each property accesors. The real accessors are in the class, as it happens with other O.O. languages like C#, Object Pascal, VB.Net.</p>\n\n<p>I usually use accessors that are protected or public, never private, and always virtual.</p>\n\n<p>I agree that accessors are complex, and add some \"overheard\" to the programs, but, in most of the scenarios, are very be useful.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T22:32:02.380",
"Id": "12291",
"Score": "0",
"body": "Thanks for your code but I think this is not what I want. I know there are plenty of approaches like yours around in the web but I really wanted something that feels like C# properties, otherwise I'd really rather just use member functions as getter/setter... But thanks for reminding me that C# properties can be virtual. That is indeed another flaw of my implementation above... Hmm. Damn. Oh well seems to be easy to fix, just put references to virtual member functions into the lambda expressions..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T22:38:44.433",
"Id": "12293",
"Score": "0",
"body": "@thesaint The idea wasn't that you use my code, but, that you consider using accessors. The idea of my code was to show an example or why accessors are useful. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T22:40:19.887",
"Id": "12294",
"Score": "0",
"body": "Ok, what do you mean by accessors? My code above also has the getter/setter, so maybe I am just overlooking something in your code?!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T15:20:47.493",
"Id": "12331",
"Score": "0",
"body": "@thesaint Cool. I overlook you made an update, with the accesor methods implemented with closures. You may want to try make a test where your class has a function that use your properties like the Width or Height example, and will be ready ;-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T22:16:06.097",
"Id": "7788",
"ParentId": "7786",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-13T20:49:45.873",
"Id": "7786",
"Score": "20",
"Tags": [
"c++",
"c++11",
"properties"
],
"Title": "C#-like class properties"
}
|
7786
|
<p>Use this tag for code that is to be compiled as <a href="http://en.wikipedia.org/wiki/C%2B%2B11" rel="nofollow noreferrer">C++11</a>, published as ISO/IEC 14882:2011 in September 2011.</p>
<ul>
<li>Predecessor: C++03</li>
<li>Successor: C++14</li>
</ul>
<p>Some of the main improvements of C++11, compared to C++03, include:</p>
<ul>
<li>an expanded standard library</li>
<li>type inference using the <code>auto</code> keyword</li>
<li>lambda expressions, as in <code>[](int x) { return x * x; }</code></li>
<li>a range-based <code>for</code> loop, as in <code>for (auto &x : my_array) ...</code></li>
<li>move constructors</li>
<li>constructor chaining</li>
<li>a more natural syntax for the initialization of objects</li>
<li>multithreading support</li>
<li>generic programming support</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-14T04:38:29.450",
"Id": "7791",
"Score": "0",
"Tags": null,
"Title": null
}
|
7791
|
Code that is written to the 2011 version of the C++ standard, sometimes known by its pre-publication name of "C++0x". Use in conjunction with the 'c++' tag.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2012-01-14T04:38:29.450",
"Id": "7792",
"Score": "0",
"Tags": null,
"Title": null
}
|
7792
|
<p>When invoking a Web Service from C# (where the external service might be WCF, ASMX, Java, etc. - you just don't know), it is common practice to point your modern development tool of choice (Visual Studio in my case) at the service's WSDL to generate a proxy class for calling the service. You can also create a proxy "by hand" using <strong><code>CreateChannel</code></strong>. This code review posting is to seek feedback on a simple proxy class built using <strong><code>CreateChannel</code></strong>. A couple of supporting classes are shown for completeness & context.</p>
<p><strong>Interface for Service & Proxy:</strong></p>
<p>This interface is also passsed to ChannelFactory.</p>
<pre><code>public interface IService
{
ServiceResponse DoSomething(ServiceRequest request);
}
</code></pre>
<p><strong>Example usage:</strong></p>
<pre><code>var proxy = new ServiceProxy("http://123.45.67.89/foo");
var request = new ServiceRequest { Number = 33, Name = "Larry Bird" };
ServiceResponse response = proxy.DoSomething(request);
</code></pre>
<p><strong>Code of interest:</strong> - <em><strong>Any comments/improvements/feedback appreciated</strong></em></p>
<p><em>For readers wondering about the use of <code>factory.Abort</code> in the finally block, see <a href="http://social.msdn.microsoft.com/forums/en-US/wcf/thread/b95b91c7-d498-446c-b38f-ef132989c154/" rel="nofollow">answer to this question</a>. Regarding the following casting business (which appears twice): <code>((IClientChannel)service).Close();</code> see MSDN document on <a href="http://msdn.microsoft.com/en-us/library/ms734681.aspx" rel="nofollow">How To: Use the ChannelFactory</a> which demonstrates its use. The two are hacks that appear to be related and date from early WCF/Indigo days.</em></p>
<pre><code>public class ServiceProxy : IService
{
public string EndpointUrl { get; set; }
public ServiceProxy(string endpointUrl) { EndpointUrl = endpointUrl; }
public ServiceResponse DoSomething(ServiceRequest request)
{
Contract.Requires(request != null);
Contract.Requires(! String.IsNullOrEmpty(EndpointUrl));
var endpointAddress = new EndpointAddress(EndpointUrl);
ChannelFactory<IService> factory = null;
IService service = null;
try
{
// Just picking a simple binding here to focus on other aspects
Binding binding = new BasicHttpBinding();
#if DEBUG // boost timeouts, otherwise can cause lots of timeouts in the debugger
binding.SendTimeout = binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
#endif
factory = new ChannelFactory<IService>(binding);
service = factory.CreateChannel(endpointAddress);
if (service == null)
{
throw new CommunicationException(
String.Format("Unable to connect to service at {0}", endpointUrl));
}
ServiceResponse response = service.DoSomething(request);
((IClientChannel)service).Close();
service = null;
factory.Close();
factory = null;
return response;
}
finally
{
if (service != null) ((IClientChannel)service).Close();
if (factory != null) factory.Abort();
}
}
}
</code></pre>
<p><strong>Supporting Objects (for completeness)</strong></p>
<p>Not much of interest in ServiceRequest and ServiceResponse classes, other than this is the prevailing style of calling services - one object in, one object out.</p>
<pre><code>public class ServiceRequest // stuff we send to the service
{
public int Number { get; set; }
public string Name { get; set; }
}
public class ServiceResponse // stuff we get back from the service
{
public int SomeStat { get; set; }
public string SomeString { get; set; }
}
</code></pre>
|
[] |
[
{
"body": "<p>Instead of wrapping the proxy creation in a concrete service proxy implementation, I'd write a concrete service factory instead which in turn uses the ChannelFactory. The service factory class could also use an interface for creation, so you can have multiple concrete factories.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Factory_pattern\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Factory_pattern</a></p>\n\n<p>That way your code can continue to depend on the interface only, and you can change the way the proxy is created without writing concrete proxies. You could also have a \"local service factory\" which doesn't go over the wire.</p>\n\n<p>Usage would be something like this instead:</p>\n\n<pre><code>var service = ServiceFactory.Create(\"http://127.0.0.1/svc\");\nvar result = service.DoSomething(request);\n// if you need cleanup..\nServiceFactory.Release(service);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-25T11:44:20.667",
"Id": "8278",
"ParentId": "7793",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T05:07:58.520",
"Id": "7793",
"Score": "3",
"Tags": [
"c#",
"wcf"
],
"Title": "How to improve WCF client proxy based on CreateChannel (not generated from WSDL) in C#"
}
|
7793
|
<p>This code allows me to save some settings from my small app to the text file which later I can retrieve by using substring and delimiter.</p>
<p>I wonder if there's any better way of doing this. If not, how could I make my code better or more efficient? </p>
<p>This is my code:</p>
<pre><code>using System;
using System.IO;
namespace NameSpace
{
class LastUsed
{
private static string dir = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Folder\";
private static string file = dir + @"\Settings.txt";
private string text;
public void CheckFileStatus()
{
if (!Directory.Exists(dir))
{
DirectoryInfo directory = Directory.CreateDirectory(dir);
}
if (!File.Exists(file))
{
using (FileStream fileStream = File.Create(file))
{
}
}
}
public bool EmptyFile()
{
FileInfo fileInfo = new FileInfo(file);
if (fileInfo.Length == 0) return true;
else return false;
}
private void SetFileText(string writeText)
{
using (StreamWriter streamWriter = new StreamWriter(file))
{
streamWriter.Write(writeText);
}
}
private string GetFileText()
{
using (StreamReader streamReader = File.OpenText(file))
{
return streamReader.ReadLine();
}
}
public string Text
{
set
{
text = value;
SetFileText(text);
}
get
{
return GetFileText();
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><code>LastUsed</code> is an awful name for a class. The name of a class should always be a noun. No exceptions.</p>\n\n<p>Read-only fields should be marked as read-only using the <code>readonly</code> keyword.</p>\n\n<p><code>CheckFileStatus</code> is an awful name for a function. It does not give any hints as to what it means by 'File Status', nor any hints as to what it means by 'Checking' it. Looking inside, I see that it performs operations that change the state of the system, so 'Check' is an awful choice of a name for what it does. When a function begins with 'Check' it is supposed to return <code>bool</code> and to perform absolutely nothing that would change any state anywhere at all. No exceptions.</p>\n\n<p><code>EmptyFile</code> is not a good name for a function that checks whether a file is empty, because it may be confused with a function that actually empties the file. Call it <code>IsEmpty</code> instead, and make it a property, not a function.</p>\n\n<p>This is lame:</p>\n\n<pre><code>if (fileInfo.Length == 0) return true;\nelse return false;\n</code></pre>\n\n<p>Replace it with this:</p>\n\n<pre><code>return fileInfo.Length == 0;\n</code></pre>\n\n<p>In the SetFileText/GetFileText functions, <code>streamWriter.Write()</code> is not symmetrical to <code>streamReader.ReadLine()</code>. Consider either using <code>streamReader.ReadToEnd()</code>, (the preferred solution,) or using <code>streamWriter.WriteLine()</code> and also asserting that the text to be written does not already contain any <code>Eoln</code>s, because if it does, then <code>GetFileText()</code> will <strong>not</strong> return the same string that was given on <code>SetFileText()</code>.</p>\n\n<p>The functions <code>CheckFileStatus()</code> and <code>EmptyFile()</code> expose implementation details of the class. These implementation details should not have to be exposed for a class which simply acts as a repository for a single string. It should be possible to rewrite the class to read/write the string from the Windows Registry, or from application.config, without having to change the interface of the class. So, replace those methods with some method which abstracts their usage.</p>\n\n<p>And, by the way, why are you doing all this instead of just using the Windows Registry or application.config ?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T13:48:00.913",
"Id": "12324",
"Score": "0",
"body": "First of all thanks for pointing out a few things. This code I have created was basically just for learning how I could store my setting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T13:55:40.033",
"Id": "12325",
"Score": "0",
"body": "PS. I don't quite understand \"It should be possible to rewrite the class to read/write the string from the Windows Registry, or from application.config, without having to change the interface of the class. So, replace those methods with some method which abstracts their usage.\" Could you please point me somewhere where I could read about it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T14:28:15.747",
"Id": "12328",
"Score": "1",
"body": "It is just an object oriented software engineering principle called [Encapsulation](http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)): the interface of a class (the functionality that it makes publicly available) should not expose any implementation details. For accessing the Windows Registry, see [MSDN: How to: Create a Key In the Registry (Visual C#)](http://msdn.microsoft.com/en-us/library/h5e7chcf.aspx) For information about application.config, see [MSDN: Using Settings in C#](http://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T07:58:06.110",
"Id": "7805",
"ParentId": "7794",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "7805",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T05:15:06.610",
"Id": "7794",
"Score": "1",
"Tags": [
"c#",
"performance"
],
"Title": "Is there any flaws in my code which let me to save settings to a file?"
}
|
7794
|
<p>This is a small web application that I have created using the Flask framework. </p>
<p>I am looking for best practices feedback, as well as design pointers. I am not confident that my design choices have been very good, or rather that they were the best they could have been, but I would like some feedback regardless on where I can improve and expand as I'm new to Python.</p>
<p>To begin, I'd like to review where I process my XML configuration file. The file is validated, and then a database is populated with the information. I feel like it could be improved, however, not included is validation and safety-checking of the user-supplied (really admin supplied) HTML from the XML doc.</p>
<pre><code>from lxml import etree
import time, datetime
from time import mktime
from contestassist.database import db_session
from contestassist.contest import Contest
from contestassist.question import Question
from contestassist.config import Config
import sqlalchemy
import sys
class XMLParser:
def __init__(self, xml_file):
self.xml_file = xml_file
self.time_format = "%Y-%m-%d %H:%M:%S"
def ProcessTemplate(self):
#parser = etree.XMLParser(dtd_validation=True)
parser = etree.XMLParser()
xmldoc = etree.parse(self.xml_file, parser)
contests = xmldoc.getroot()
#validate against DTD
dtd = open(Config.DTDPATH, 'r')
dtdObj = etree.DTD(dtd)
if dtdObj.validate(contests) is False:
print "Supplied XML file is not correctly formatted"
print(dtdObj.error_log.filter_from_errors()[0])
sys.exit()
for contest in contests.getchildren():
contest_id = self.parseContestInfo(contest)
self.parseContestQuestions(contest, contest_id)
def parseContestInfo(self, contestNodes):
title = contestNodes.xpath('title')
self.title_data = title[0].text
description = contestNodes.xpath('description')
self.description_data = description[0].text
#Here we carefully extract the time from our xml node into a datetime object
#in a couple steps. First we get the string from the node, then a time struct using strptime and a format string
#then we create a datetime from the struct.
start = contestNodes.xpath('start')
start_node = start[0].text
t_struct = time.strptime(start_node, self.time_format)
self.start_datetime = datetime.datetime.fromtimestamp(mktime(t_struct))
end = contestNodes.xpath('end')
end_node = end[0].text
t_struct = time.strptime(end_node, self.time_format)
self.end_datetime = datetime.datetime.fromtimestamp(mktime(t_struct))
#create contest and insert it into the database
contest = Contest(self.title_data, self.description_data, self.end_datetime, self.start_datetime)
try:
db_session.add(contest)
db_session.commit()
except sqlalchemy.exc.IntegrityError, exc:
reason = exc.message
if reason.endswith('is not unique'):
print "%s already exists" % exc.params[0]
db_session.rollback()
#return the ID of this contest, so we can use it in the next function
return contest.id
def parseContestQuestions(self, contestNodes, contest_id):
#get a list of questions for our contest
questions = contestNodes.xpath('questions/question')
#loop through these questions, grab the appropriate data
#and then create question entries in the database
for question in questions:
points_temp = question.xpath('point-value')
p_value = points_temp[0].text
text_temp = question.xpath('question-text')
q_text_value = text_temp[0].text
answer_temp = question.xpath('question-answer')
q_answer = answer_temp[0].text
#create question object, and attach it to the contest with the id contest_id
question = Question(p_value, q_text_value, q_answer, contest_id)
try:
db_session.add(question)
db_session.commit()
except sqlalchemy.exc.IntegrityError, exc:
reason = exc.message
if reason.endswith('is not unique'):
print "%s already exists" % exc.params[0]
db_session.rollback()
</code></pre>
<p>I have a couple areas where I'd like to focus on:</p>
<ol>
<li><code>user.py</code> - Here, I'd like some critique on my class design choices. This class is used to store user information in the database. It provides some utility functions specific to the Flask framework and its plug-ins. It works with SQL Alchemy, so I can retain user info in a database. Am I storing user credentials poorly? How do the <code>authenticate</code>/<code>name_exists</code>/<code>email_exists</code> functions look?</li>
<li><code>flaskapp.py</code> - this is where I do my app's route handling, build/process forms, etc. Most views are rendered with a list of dictionaries as an argument (containing for example questions, users, etc as part of the application). Is that bad design for a web application? Do I process forms in a decent manner? is there a way I can better organize all these routes? This file got sort of big fast. </li>
</ol>
<p>Any feedback is appreciated. I would love to hear feedback in any areas, not necessarily what is named in the tags.</p>
|
[] |
[
{
"body": "<h1>Opening files using <code>with</code></h1>\n\n<p>It's not a great idea to open a file just using something like this:</p>\n\n<blockquote>\n<pre><code>dtd = open(Config.DTDPATH, 'r')\n</code></pre>\n</blockquote>\n\n<p>If your program unexpectedly exits, or crashes, resources that are taken up by the opened file aren't freed. This can be bad in some situations. The <em>proper</em> way to open a file would to be using a context manager, or <code>with</code>, like this:</p>\n\n<pre><code>with open(Config.DTDPATH, \"r\") as dtd:\n ...\n</code></pre>\n\n<p>By using a context manager, resources will be <em>properly</em> freed even if your program crashes or unexpectedly exits.</p>\n\n<hr>\n\n<h1>Explicit inheritance from <code>object</code></h1>\n\n<p>In addition, classes in pre-Python 3.x should explicitly inherit from <code>object</code>, like this:</p>\n\n<pre><code>class XmlParser(object):\n ...\n</code></pre>\n\n<p>When your class doesn't you can get weird behavior like this:</p>\n\n<blockquote>\n<pre><code>>>> class Spam: pass\n...\n>>> type(Spam())\n<type 'instance'>\n</code></pre>\n</blockquote>\n\n<p>Versus normal behavior like this:</p>\n\n<blockquote>\n<pre><code>>>> class Spam(object): pass\n...\n>>> type(Spam())\n<class '__main__.Spam'>\n</code></pre>\n</blockquote>\n\n<hr>\n\n<h1>Nitpicks/Style</h1>\n\n<p>Python has an official style guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>. I'd highly recommend that you read it, as it has some very valuable information. You do have a few style violations though, so here's a small list of them:</p>\n\n<ul>\n<li>Function names should be in <code>snake_case</code>, not <code>PascalCase</code>, or <code>camelCase</code>.</li>\n<li>Variable names should be in <code>snake_case</code> as well.</li>\n<li>Constants should be in <code>UPPER_SNAKE_CASE</code></li>\n<li>The <code>XMLParser</code> class should be named <code>XmlParser</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-28T00:53:00.807",
"Id": "105867",
"ParentId": "7796",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T06:10:52.327",
"Id": "7796",
"Score": "6",
"Tags": [
"python",
"beginner",
"flask"
],
"Title": "Contest assist web app"
}
|
7796
|
<p>I just started Python a few days ago, and I haven't programmed much before. I know my code is terrible; however, I would like someone to look it over. What I'm trying to do is create a photo "loop" that changes my Windows 7 login screen. I had a batch file doing it, but even though my code is crappy it does the job way better.</p>
<p>I'm using two separate scripts, and if possible I would like to combine them. Renamer.py only runs when new photos are added. It sets up the file names for LoginChanger.py. <code>LoginChanger</code> is picky in the filenames, but <code>Renamer</code> doesn't change the photos in a loop. So I have to use <code>Renamer</code>, then <code>LoginChanger</code> to loop the photos.</p>
<p><strong>Renamer.py</strong></p>
<pre><code>#-------------------------------------------------------------------------------
# Name: Renamer
# Purpose: Renames all .jpg's in a dir from 0 - n (where "n" is the number of .jpg's.)
# This is to be used in conjunction with loginchanger.py
# Author: Nathan Snow
#
# Created: 13/01/2012
# Copyright: (c) Nathan Snow 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import os
count = 0
count2 = 0
list1 = []
list2 = []
for filename2 in os.listdir('.'):
if filename2.endswith('.jpg'):
list1.append(filename2)
while count < len(list1):
os.rename(filename2, str(count)+"old.jpg")
count += 1
for filename3 in os.listdir('.'):
if filename3.endswith('.jpg'):
list2.append(filename3)
while count2 < len(list2):
os.rename(filename3, str(count2)+".jpg")
count2 += 1
</code></pre>
<p><strong>LoginChanger.py</strong></p>
<pre><code>#-------------------------------------------------------------------------------
# Name: LoginChanger
# Purpose: This is to be used after renamer.py. This loops the properly named
# .jpg's in a "circle" first to last, 2-1, 3-2, ..., and changes
# 0 to BackgroundDefault.jpg.
# Author: Nathan Snow
#
# Created: 13/01/2012
# Copyright: (c) Nathan Snow 2012
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import os
count = 0
list1 = []
list2 = []
list3 = []
for filename in os.listdir('.'):
if filename.endswith('.jpg'):
list3.append(filename)
list3len = len(list3)
list3len = list3len - 1
if filename.startswith('BackgroundDefault'):
os.rename('BackgroundDefault.jpg', str(list3len)+'.jpg')
for filename2 in os.listdir('.'):
if filename2.endswith('.jpg'):
list1.append(filename2)
while count < len(list1):
jpg = str(count)+'.jpg'
oldjpg = str(count)+'old.jpg'
os.rename(str(jpg), str(oldjpg))
count += 1
for filename4 in os.listdir('.'):
if filename4.startswith('0'):
os.rename('0old.jpg', 'BackgroundDefault.jpg')
count = 1
count2 = 0
for filename3 in os.listdir('.'):
if filename3.endswith('.jpg'):
list2.append(filename3)
while count < len(list2):
newjpg = str(count2)+'.jpg'
oldjpg = str(count)+'old.jpg'
os.rename(str(oldjpg), str(newjpg))
count2 += 1
count += 1
print ('Created new login background')
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Your variable names are pretty bad: <code>filename1</code>, <code>filename2</code>, <code>filename3</code>, ... is bad, use something more meaningful.</li>\n<li>There is no need to use different loop variables in consecutive loops. Use <code>filename</code> everytime.</li>\n<li>You need to move the <code>#!/usr/bin/env python</code> shebang line to the first line of the file or it won't work at all.</li>\n<li>You have unnecessary <code>str()</code> calls in <code>os.rename(str(oldjpg), str(newjpg))</code> - both variables are already strings.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T22:04:37.467",
"Id": "7817",
"ParentId": "7809",
"Score": "3"
}
},
{
"body": "<p>You could avoid continuously renaming all files by overwriting just <code>BackgroundDefault.jpg</code> file instead e.g., <code>change-background.py</code>:</p>\n\n<pre><code>#!/usr/bin/env python\nimport bisect\nimport codecs\nimport os\nimport shutil\n\nBG_FILE = u'BackgroundDefault.jpg'\ndb_file = 'change-background.db'\ndb_encoding = 'utf-8'\n\n# read image filenames; sort to use bisect later\nfiles = sorted(f for f in os.listdir(u'.')\n if f.lower().endswith(('.jpg', '.jpeg')) and os.path.isfile(f)) \ntry: files.remove(BG_FILE)\nexcept ValueError: pass # the first run\n\n# read filename to use as a background from db_file\ntry:\n # support Unicode names, use human-readable format\n with codecs.open(db_file, encoding=db_encoding) as f:\n bg_file = f.read().strip()\nexcept IOError: # the first run\n bg_file = files[0] # at least one image file must be present\n\n# change background image: copy bg_file to BG_FILE\ntmp_file = BG_FILE+'.tmp'\nshutil.copy2(bg_file, tmp_file)\n# make (non-atomic) rename() work even if destination exists on Windows\ntry: os.remove(BG_FILE)\nexcept OSError: # in use or doesn't exist yet (the first run)\n if os.path.exists(BG_FILE):\n os.remove(tmp_file)\n raise\nos.rename(tmp_file, BG_FILE)\n\n# write the next filename to use as a background\nnext_file = files[bisect.bisect(files, bg_file) % len(files)]\nwith codecs.open(db_file, 'w', encoding=db_encoding) as f:\n f.write(next_file)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T03:08:21.940",
"Id": "12367",
"Score": "0",
"body": "I copied this and it worked the first time. Then it said it couldn't change the background image because the file was already there. I had to remove a \")\" from \"files = sorted(glob.glob(u'*.jpg')))\" to get it to work as well. I really appreciate the help though, Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T04:18:05.540",
"Id": "12391",
"Score": "0",
"body": "@Jedimaster0: I've fixed the code. I don't use Windows so it is untested."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-15T00:37:19.897",
"Id": "7823",
"ParentId": "7809",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "7823",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T19:29:00.193",
"Id": "7809",
"Score": "5",
"Tags": [
"python",
"image"
],
"Title": "Photo changer loop"
}
|
7809
|
<pre><code><?php
/**
* Module : Control
* Name : ControlSigin
* Input : Text Array
* Output : Pass or Fail(w/responseText)
* Notes :
* Call :
$instanceControlSignIn = new ControlSignIn();
$instanceControlSiginIn->invoke();
*/
class ControlSignIn extends Post
{
private $databaseObject;
private $textObject;
private $messageObject;
public function __construct()
{
parent::__construct();
$this->databaseObject = new Database();
$this->textObject = new Text($this->_postProtected);
$this->messageObject = new Message();
}
public function invoke()
{
if(Constant::VALIDATE_ON==true)
{
$continue = $this->checkInput();
}
else
{
$continue = true;
}
if($continue==true)
{
if($this->validatePass())
{
$this->setSessionVariables();
Control::send(Mark::pass);
}
else
{
$this->messageObject->display('validate');
return false;
}
}
}
private function checkInput()
{
if(!$this->textObject->checkEmpty())
{
$this->messageObject->display('empty');
return true;
}
if(!$this->textObject->checkPattern('email'))
{
$this->messageObject->display('email');
return false;
}
if(!$this->textObject->checkPattern('pass'))
{
$this->messageObject->display('pass');
return false;
}
return true;
}
private function validatePass()
{
$result=$this->databaseObject->_pdoQuery('single', 'signin_pass',array($this->_postProtected['email']));
$pass=crypt($this->_postProtected['pass'], $result['pass']);
$result=$this->databaseObject->_pdoQuery('single', 'signin_validate',array($this->_postProtected['email'], $pass));
return (count($result)==2) ? true : false;
}
private function setSessionVariables()
{
$result=$this->databaseObject->_pdoQuery('single', 'pull_session',array($this->_postProtected['email']));
Session::activate($result['picture'],$result['id'],$result['name'],'bookmarks');
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T20:28:24.503",
"Id": "12343",
"Score": "0",
"body": "Again, what is your question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T11:18:20.313",
"Id": "12445",
"Score": "0",
"body": "@stack.user.0 You should move it out, because OOP is all about areas of responsibility. Each class should have only one. If you move session storage out into its own class you have the opportunity of reusing that class in other projects, and you can test each of your classes independently of each other."
}
] |
[
{
"body": "<p>Without a question there's no way to give a definitive answer. Still, here's a few comments you might want to take on board. </p>\n\n<ul>\n<li><p>You're instantizing your dependencies in your constructor. This means that your class is now irrevocably coupled to those dependencies. This makes testing and reuse very difficult, as it's basically impossible to test your class in isolation and if you move the class over to another project then you'll have to move all the dependencies over as well. You should use dependency injection instead and pass your dependencies to the constructor instead. </p></li>\n<li><p>It looks like you're statically invoking some static methods as well. You should avoid doing this for the same reasons that you should inject dependencies. A static dependency is still a dependency, and your class will now be coupled to those classes whose static methods you're using. Furthermore, static methods tend to be frowned upon as they represent global state. For reasons I'm sure you're familiar with, global state is a Bad Thing. You'll be better off passing in instances of objects instead. </p></li>\n<li><p>Your header comment is non-standard. Good to see you're including comments at all, but there are various automated tools out there (DocBlox for example) that are capable of generating documentation files for you, but only if your comments are in the right format. If you look at the documentation for those tools they'll give you a rundown of how to format a comment and what tags are available to you. IDEs like Netbeans and Eclipse can also use the docblocks to provide you with pop-up help, they'll show your comment when you type the class name so you'll be reminded of what it does. </p></li>\n<li><p>Aside from your header comment (which is good), you don't comment your code at all. You should at the very least put a docblock comment at the start of all your methods to tell you what they do so that they can be documented by tools like DocBlox and so that you'll get help on your class from your IDE. You should also provide a running commentary in plain-English comments as to what's going on in your code. </p></li>\n</ul>\n\n<p>One last tip. You can abbreviate the code at the start of your invoke() method as follows: </p>\n\n<pre><code> $continue = Constant::VALIDATE_ON==true?\n $this->checkInput():\n true;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T07:58:40.513",
"Id": "12443",
"Score": "0",
"body": "@stack.user.0 Please do not ignore the good review you have received. You can only fight against the logic of dependency injection and avoiding static so much. Just because your code works does not mean you should ignore thoughtful suggestions like these. (I am pre-empting an \"I don't need that, it does all it needs to type of response.\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-18T02:55:32.173",
"Id": "12537",
"Score": "0",
"body": "@stack.user.0 That link suggest creating a static method in a container. I'm sure I have told you static is bad many times. This time is no different. Apart from that the advice is ok. (Again, the reason not to use static is that it couples the code tightly with a particular implementation. XXX::method vs $obj->method with static you now need an XXX object, with $obj you only need an object that has method.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-16T07:42:29.077",
"Id": "7864",
"ParentId": "7810",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "7864",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-01-14T19:47:33.703",
"Id": "7810",
"Score": "1",
"Tags": [
"php"
],
"Title": "Control Signin Class - Remove Dependencies"
}
|
7810
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.