body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Help me review this code:</p>
<pre><code>#include <iostream>
#include <cassert>
using namespace std;
template <typename T>
class auto_ptr
{
public:
explicit auto_ptr(T* p = NULL):m_p(p){}
auto_ptr(auto_ptr& other);
auto_ptr& operator=(auto_ptr& other);
T* get() const { return m_p; }
void reset(T* p = NULL);
T& operator * (){ return *m_p; }
T* operator -> (){ return m_p; }
~auto_ptr()
{
if(m_p)
delete m_p;
m_p = NULL;
}
private:
T* m_p;
T* release();
};
int main()
{
auto_ptr<int> p(new int(3));
cout<<*p<<endl;
int *b = new int(6);
p.reset(b);
cout<<*p.get()<<endl;
auto_ptr<int> p1(new int(10));
p = p1;
cout<<*p<<endl;
assert(NULL == p1.get());
auto_ptr<int> p2(new int(100));
auto_ptr<int>p3(p2);
cout<<*p3<<endl;
assert(NULL == p2.get());
}
template <typename T>
T* auto_ptr<T>::release()
{
T* temp = this->m_p;
this->m_p = NULL;
return temp;
}
template <typename T>
auto_ptr<T>::auto_ptr(auto_ptr& other)
{
m_p = other.release();
}
template <typename T>
auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr& other)
{
if(this == &other)
return *this;
delete m_p;
m_p = other.release();
return *this;
}
template <typename T>
void auto_ptr<T>::reset(T* p)
{
if(m_p != p)
{
delete m_p;
m_p = p;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I presume you are aware of all the standard issues with <code>auto_ptr</code>, and that C++11 fixes by far most of them. I'm thus going to assume you have no C++11 support; if that's not the case, most of this doesn't apply because the whole thing should be rewritten with different semantics.</p>\n\n<p>Comments in order I see things:</p>\n\n<ul>\n<li>You've combined everything into one file, so it may not be an issue in your code, but you should not have using-directives like <code>using namespace std;</code> at global scope in a header; that's rude to anyone who includes it.</li>\n<li>Your <code>operator*</code> and <code>operator-></code> should both be <code>const</code>.</li>\n<li>Your destructor checks for <code>m_p</code> being NULL. This is unnecessary; <code>delete</code> is a no-op on a null pointer. Personally, I'd have the destructor simply call <code>reset</code>.</li>\n<li>Your class is missing <code>operator bool</code> (or <code>operator void*</code>), <code>operator!</code>, <code>operator<<</code>, <code>swap</code>, and any support for casting.</li>\n<li>You use <code>this->m_p</code> about half the time, and the other half use just <code>m_p</code>. Both are fine, but be consistent.</li>\n<li>Use c-tor initializers where possible, such as in the copy-constructor.</li>\n</ul>\n\n<p>This is an okay base, but you're missing a great number of features that I would expect a smart pointer to have now: in particular, you don't support custom deleters or array types.</p>\n\n<p>Also, on a purely stylistic choice: I would define the member functions of such a simple class template inline. You can't hide the implementation anyway, and when the overhead is so small I don't expect it to matter for readability. (I presume that for getting a list of functions you use your IDE's features, or something like Doxygen.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:19:50.520",
"Id": "47082",
"Score": "1",
"body": "Its not only rude but can break other code by the inclusion of the header file."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:19:50.153",
"Id": "29743",
"ParentId": "29734",
"Score": "3"
}
},
{
"body": "<p>Assuming you are going to put this in a header file don't do thus</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>See: <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice</a></p>\n\n<p>These should be const as they don't change the state of your auto_ptr</p>\n\n<pre><code>T& operator * (){ return *m_p; }\nT* operator -> (){ return m_p; }\n</code></pre>\n\n<p>The destructor</p>\n\n<pre><code>~auto_ptr()\n{\n if(m_p) // No need to check for NULL\n // delete on a NULL pointer is valid.\n delete m_p;\n\n m_p = NULL; // This is pointless.\n // The object is about to leave scope.\n} \n</code></pre>\n\n<p>Why the sudden use of this!</p>\n\n<pre><code>template <typename T>\nT* auto_ptr<T>::release()\n{\n T* temp = this->m_p;\n // ^^^^^^\n this->m_p = NULL;\n // ^^^^^^\n return temp;\n}\n</code></pre>\n\n<p>Assignment not exception safe.</p>\n\n<pre><code>template <typename T>\nauto_ptr<T>& auto_ptr<T>::operator=(auto_ptr& other)\n{ \n if(this == &other)\n return *this;\n\n // This is not exception safe.\n // T is completely unknown to you.\n // Therefore you must assume the person who wrote T is an idiot \n // and therefore may throw an exception from there destructor.\n delete m_p;\n\n // If the above statement throws then your object is now in an undefined\n // state with m_p pointing at an invalid object.\n\n\n m_p = other.release();\n return *this;\n}\n</code></pre>\n\n<p>The correct way to do this.</p>\n\n<pre><code>template <typename T>\nauto_ptr<T>& auto_ptr<T>::operator=(auto_ptr& other)\n{ \n if(this == &other)\n return *this;\n\n auto_ptr<T> tmp = release();\n m_p = other.release();\n\n // After the state of your (and other objects)\n // are completely defined and are in a good state.\n // then you can tidy up any left over objects.\n\n return *this;\n\n // the destructor of tmp should now release it properly.\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:30:25.253",
"Id": "29750",
"ParentId": "29734",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T13:47:42.220",
"Id": "29734",
"Score": "5",
"Tags": [
"c++",
"pointers"
],
"Title": "I wrote a class to implement auto_ptr"
}
|
29734
|
<p>As a part of learning Haskell, I've implemented an AVL tree. As of now, I've only implemented insertion.</p>
<p>I've compared its performance to a Java implementation I've picked at random (<a href="http://github.com/justinethier/AVL-Tree/blob/master/AvlTree.java" rel="nofollow">www.github.com/justinethier/AVL-Tree/blob/master/AvlTree.java</a>).</p>
<p>It performs almost as well when given an ascending or descending list (<code>[1..9999999]</code> or <code>[9999999..1]</code>), but significantly slower (2-4X) for a randomly generated list of the same size.</p>
<p>My question are:</p>
<ol>
<li><p>Why is it performing so badly? My only guess is that it re-evaluates sub tree after rolls, but I don't understand Haskell well enough to know.</p></li>
<li><p>What can I do to improve its performance?</p></li>
</ol>
<p>The code:</p>
<pre><code>data Tree a = Empty |
Branch { key :: a,
balance :: Int,
left :: Tree a,
right :: Tree a,
up :: Bool
--used internally to stop updating balance
}
deriving (Eq)
leaf :: (Ord a, Eq a) => a -> Tree a
leaf x = Branch x 0 Empty Empty True
-- insert ------------------------------------
treeInsert :: (Eq a, Ord a) => Tree a -> a -> Tree a
treeInsert Empty x = leaf x
treeInsert (Branch y b l r _) x
| x < y =
let nl@(Branch _ _ _ _ nlu) = treeInsert l x -- nl = new left
in
if nlu
then if b==1
then roll $ Branch y 2 nl r False
else Branch y (b + 1) nl r (b /= (-1))
else Branch y b nl r False
| x > y =
let nr@(Branch _ _ _ _ nru) = treeInsert r x -- nr = new right
in
if nru
then if b==(-1)
then roll $ Branch y (-2) l nr False
else Branch y (b - 1) l nr (b /= 1)
else Branch y b l nr False
| otherwise = Branch x b l r False
-- rolls -------------------------------------
roll :: (Eq a, Ord a) => Tree a -> Tree a
-- ll roll
roll (Branch y 2 (Branch ly 1 ll lr _) r _) =
Branch ly 0 ll (Branch y 0 lr r False) False
-- rr roll
roll (Branch y (-2) l (Branch ry (-1) rl rr _) _) =
Branch ry 0 (Branch y 0 l rl False) rr False
-- lr rolls
roll (Branch y 2 (Branch ly (-1) ll (Branch lry lrb lrl lrr _) _) r _) =
case lrb of
0 -> Branch lry 0 (Branch ly 0 ll lrl False)
(Branch y 0 lrr r False) False
1 -> Branch lry 0 (Branch ly 0 ll lrl False)
(Branch y (-1) lrr r False) False
(-1)-> Branch lry 0 (Branch ly 1 ll lrl False)
(Branch y 0 lrr r False) False
-- rl rolls
roll (Branch y (-2) l (Branch ry 1 (Branch rly rlb rll rlr _) rr _) _) =
case rlb of
0 -> Branch rly 0 (Branch y 0 l rll False)
(Branch ry 0 rlr rr False) False
1 -> Branch rly 0 (Branch y 0 l rll False)
(Branch ry (-1) rlr rr False) False
(-1)-> Branch rly 0 (Branch y 1 l rll False)
(Branch ry 0 rlr rr False) False
-- construct a tree --------------------------
construct :: (Eq a, Ord a) => Tree a -> [a] -> Tree a
construct = foldl' treeInsert
-- rands -------------------------------------
rands :: Int -> Int -> Int -> Int -> [Int]
rands n low high seed = take n $ randomRs (low, high) (mkStdGen seed)
-- test run
main = do
seed <- round `fmap` getPOSIXTime
let ma = 9999999
let t = construct Empty ( rands ma 1 ma seed )
start <- getPOSIXTime
end <- t `seq` getPOSIXTime
print (end - start)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T14:28:37.527",
"Id": "29738",
"Score": "2",
"Tags": [
"optimization",
"performance",
"haskell"
],
"Title": "Optimizing AVL tree"
}
|
29738
|
<p>If this question should be on stackoverflow instead, please point it out. I'll put it up there.</p>
<pre><code> struct {
FILE * fd;
hdr_t file_header;
body_t file_body;
} fileinfo;
</code></pre>
<p>The above is an approximate recreation of a structure that I have in my code. There is a separate function we use for thread cleanup. A pointer to the above structure is a parameter to this function. </p>
<pre><code> void cleanup(void * args)
{
struct fileinfo *file_ptr = (struct fileinfo *) args;
if(file_ptr->fd > 0)
{
fclose(file_ptr->fd);
}
free(file_ptr);
}
</code></pre>
<p>Does the free() - as called above - actually free all the memory allocated to file_ptr? Should there not be a free for the hdr_t and body_t as well?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:26:03.940",
"Id": "47062",
"Score": "1",
"body": "You must not call `free` on the `hdr_t` or `body_t` fields - they are part of the structure and were not allocated individually. The `FILE` pointer should be compared with `...fd != 0` not `>`. If it is a `FILE` obtained with `fopen`, then you need to call `fclose`, not `close` and it should be named something other than `fd` (which is normally used for things opened with `open`), eg call it `file`. You do not need to call `free` on the file pointer (`fclose` will do what is required). You might need to free the `fileinfo` struct itself, if it was allocate dynamically, but not in `cleanup`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:53:44.193",
"Id": "47073",
"Score": "0",
"body": "Sorry, the free/close issues were typos. I've corrected them in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:56:56.393",
"Id": "47075",
"Score": "0",
"body": "your if statement has an unbalanced number of brackets."
}
] |
[
{
"body": "<p>The basic logic is that you only free dynamically allocated resources. Those that were created with malloc.</p>\n\n<p>Hdr_t and body_t are automatically allocated and must therefore not be freed.</p>\n\n<p>The most important point is that you might under no circumstances free a pointer without checking if it is not pointing to 0.</p>\n\n<p>This following fragment will core:</p>\n\n<pre><code>void * ptr = 0;\nfree (ptr);\n</code></pre>\n\n<p>Therefore always do something like this:</p>\n\n<pre><code>if (ptr != 0)\n free(ptr)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:00:07.047",
"Id": "47076",
"Score": "1",
"body": "i did a bit of a SO research and a similar question has been posted before. It might explain it even better. [freeing ptr to ptr](http://stackoverflow.com/questions/3647350/freeing-struct-with-pointer-and-non-pointer-variables)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:06:11.067",
"Id": "47078",
"Score": "0",
"body": "new does not apply to `C` malloc/free is used for dynamic memory allocation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:07:20.947",
"Id": "47079",
"Score": "2",
"body": "The bit about checking for NULL before freeing is wrong. The standard library already does this (the standard was amended). It was true about 10 years ago no longer so. But you must check for NULL before looking at the members."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:13:30.197",
"Id": "47080",
"Score": "0",
"body": "I know what you mean by `Hdr_t and body_t are statically`. But `statically` is the wrong description and has specific meaning within the context of the language. I don't have a C standard handy so I forget the actual term."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:19:43.197",
"Id": "47081",
"Score": "0",
"body": "I agree on the NULL condition. This applies to 99 strict and older C++ standards. Yet I've worked on environments where this still holds. The correct term for allocation is automatic."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:54:22.803",
"Id": "29749",
"ParentId": "29740",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29749",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T14:52:58.870",
"Id": "29740",
"Score": "2",
"Tags": [
"c",
"memory-management"
],
"Title": "Freeing allocated memory: am I missing something?"
}
|
29740
|
<p>I occasional write simple yet long Python scripts using Sqlite3 (I'm not proficient with functional or object oriented programming... yet)</p>
<p>Usually my Sqlite3 is blazing fast. I'm used to looping through lists of <code>SELECT</code> statements with each <code>SELECT</code> taking a split second, and writing tables to text files in HTML markup. But, this is the first time I've done a <code>LEFT JOIN</code> in Sqlite3, and its taking much longer to complete the script than I had thought. I figured a couple of minutes perhaps, but it's taking several hours to run though all the queries. </p>
<p>I added print statements to narrow down that this <code>LEFT JOIN</code>, within a loop, is where the script hangs up for several minutes, instead taking a split second to perform. It's definitely between the <code>SELECT</code> and the <code>.fetchall</code>.</p>
<p>I have a couple of questions: </p>
<ol>
<li>Is it normal for Sqlite3 to hang on <code>LEFT JOIN</code> (or any other <code>JOIN</code>)? </li>
<li>Did I code something the wrong way? </li>
</ol>
<p>I need the code to work fast. If the code appears professional that's definitely a bonus. </p>
<pre><code>print "selecting...",
cur.execute("SELECT \"b\".\"Disposals\" AS \"Disposals\", \
\"a\".\"ASSET NUMBER\" AS \"Record\", \
\"a\".\"DESCRIPTION\" AS \"DESCRIPTION\", \
\"a\".\"NAME_2012\" AS \"GIS_NAME_2012\", \
\"a\".\"Notes\" AS \"GIS_Notes\", \
\"a\".\"Other\" AS \"GIS_Other\", \
\"a\".\"QC_place\" AS \"GIS_place\", \
\"a\".\"QC_county\" AS \"GIS_county\", \
\"a\".\"lon_\" AS \"Longitude\", \
\"a\".\"lat_\" AS \"Latitude\" \
FROM \"resultsPoints\" AS \"a\" \
LEFT JOIN \"html_Tables\" AS \"b\" \
ON (\"a\".\"ASSET NUMBER\" = \"b\".\"Assetnum\") \
WHERE \"a\".\"DEPARTMENT NUMBER\" LIKE ? \
OR \"a\".\"AGENCY_BoB\" LIKE ? \
GROUP BY \"a\".\"ASSET NUMBER\" \
ORDER BY \"a\".\"ASSET NUMBER\"",(sqlHunt, sqlHuntBoB))
tableData = cur.fetchall()
print "fetching..",
for r, row in enumerate(tableData):
print " - ",
for c, column in enumerate(row):
print ".",
mysheets[bobAgency].write (r+2, c, str(column))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T08:06:04.437",
"Id": "455367",
"Score": "3",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>LEFT JOINS are not inherently slow. It really depends on how you set it up. Are there any indexes on b.Assetnum? Having an index on that would probably speed up your joins tremendously. It probably is doing a full table scan on the join right now if you don't have any indexes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T20:01:50.240",
"Id": "47105",
"Score": "0",
"body": "I added an Index for b.Assetnum (and for the heck of it a.ASSET NUMBER) -- The speed has gone up from 2 or 3 minutes per loop to about 1 or 2 seconds per loop. That fixed it...Perfect!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T17:11:54.850",
"Id": "29752",
"ParentId": "29751",
"Score": "4"
}
},
{
"body": "<p>You could use a different quote style to reduce the number of escaping needed, in this case: single quote <code>'</code> or three quotes <code>'''</code> or <code>\"\"\"</code>.</p>\n\n<pre><code>cur.execute('SELECT \"b\".\"Disposals\" AS \"Disposals\", \\\n \"a\".\"ASSET NUMBER\" AS \"Record\", \\\n[...]\nORDER BY \"a\".\"ASSET NUMBER\"',(sqlHunt, sqlHuntBoB))\n</code></pre>\n\n<p>If you use three quotes, you do not need to escape that quote character. Also, with three quotes, you can write a multi-line string directly (except the last quote must be escaped, but if we add a space before the three quotes, the escaping is not necessary).</p>\n\n<pre><code>cur.execute(\"\"\"SELECT \"b\".\"Disposals\" AS \"Disposals\", \n \"a\".\"ASSET NUMBER\" AS \"Record\",\n[...]\nORDER BY \"a\".\"ASSET NUMBER\\\"\"\"\",(sqlHunt, sqlHuntBoB))\n</code></pre>\n\n<p>Beware that this is not equal to the first example: the second example have newlines in the string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T23:32:48.200",
"Id": "29770",
"ParentId": "29751",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29752",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-08-14T17:06:28.073",
"Id": "29751",
"Score": "2",
"Tags": [
"python",
"sqlite"
],
"Title": "Improving SQLITE3 Left Join Performance"
}
|
29751
|
<p>I'm finding it a bit tedious to write unit tests for my collision class because there are so many variations of collisions that need testing. I see repetition in the set-up and assertion stages of each test, but I don't see how I can reduce the repetition whilst keeping the code clear and concise.</p>
<pre><code>package tests.kris {
import asunitsrc.asunit.framework.TestCase;
import flash.geom.Rectangle;
import kris.RectangleCollision;
public class RectangleCollisionTest extends TestCase {
public function RectangleCollisionTest(testMethod:String):void {
super(testMethod);
}
// detect
public function detect_should_throw_error_when_both_arguments_are_the_same_object():void {
var callOn:Rectangle = new Rectangle(0, 0, 0, 0);
assertThrowsError(RectangleCollision.detect, callOn, callOn);
}
public function calling_detect_on_intersecting_rectangles_should_return_true():void {
var callOn:Rectangle = new Rectangle(1, 1, 5, 5);
var callWith:Rectangle = new Rectangle(2, 2, 5, 5);
assertTrue(areColliding(callOn, callWith));
}
public function calling_detect_on_rectangles_with_a_touching_side_should_return_false():void {
var callOn:Rectangle = new Rectangle(0, 0, 5, 5);
var callWith:Rectangle = new Rectangle(5, 0, 5, 5);
assertFalse(areColliding(callOn, callWith));
}
// Currently only works with rectangles that are rougly the same size and have shallow collisions
// resolve
public function calling_resolve_should_throw_error_when_both_arguments_are_the_same_object():void {
var reactionary:Rectangle = newRectangle(0, 0, 0, 0);
assertThrowsError(RectangleCollision.resolve, reactionary, reactionary);
}
public function calling_reslove_on_not_colliding_rectangles_returns_reactionary():void {
var reactionary:Rectangle = new Rectangle(0, 0, 100, 100);
var stationary:Rectangle = new Rectangle(200, 200, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, 0, 0);
assertPosition(stationary, 200, 200);
assertPosition(result, 0, 0);
}
public function should_reslove_to_left_correctly_1():void {
var reactionary:Rectangle = new Rectangle(2, 1, 100, 100);
var stationary:Rectangle = new Rectangle(100, 0, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, 2, 1);
assertPosition(stationary, 100, 0);
assertPosition(result, 0, 1);
}
public function should_reslove_to_left_correctly_2():void {
var reactionary:Rectangle = new Rectangle(2, -1, 100, 100);
var stationary:Rectangle = new Rectangle(100, 0, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, 2, -1);
assertPosition(stationary, 100, 0);
assertPosition(result, 0, -1);
}
public function should_reslove_to_right_correctly_1():void {
var reactionary:Rectangle = new Rectangle(98, 1, 100, 100);
var stationary:Rectangle = new Rectangle(0, 0, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, 98, 1);
assertPosition(stationary, 0, 0);
assertPosition(result, 100, 1);
}
public function should_reslove_to_right_correctly_2():void {
var reactionary:Rectangle = new Rectangle(98, -1, 100, 100);
var stationary:Rectangle = new Rectangle(0, 0, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, 98, -1);
assertPosition(stationary, 0, 0);
assertPosition(result, 100, -1);
}
public function should_reslove_to_top_correctly_1():void {
var reactionary:Rectangle = new Rectangle(1, 2, 100, 100);
var stationary:Rectangle = new Rectangle(0, 100, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, 1, 2);
assertPosition(stationary, 0, 100);
assertPosition(result, 1, 0);
}
public function should_reslove_to_top_correctly_2():void {
var reactionary:Rectangle = new Rectangle(-1, 2, 100, 100);
var stationary:Rectangle = new Rectangle(0, 100, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, -1, 2);
assertPosition(stationary, 0, 100);
assertPosition(result, -1, 0);
}
public function should_reslove_to_bottom_correctly_1():void {
var reactionary:Rectangle = new Rectangle(1, 98, 100, 100);
var stationary:Rectangle = new Rectangle(0, 0, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, 1, 98);
assertPosition(stationary, 0, 0);
assertPosition(result, 1, 100);
}
public function should_reslove_to_bottom_correctly_2():void {
var reactionary:Rectangle = new Rectangle(-1, 98, 100, 100);
var stationary:Rectangle = new Rectangle(0, 0, 100, 100);
var result:Rectangle = RectangleCollision.resolve(reactionary, stationary);
assertPosition(reactionary, -1, 98);
assertPosition(stationary, 0, 0);
assertPosition(result, -1, 100);
}
private function assertPosition(rect:Rectangle, x:Number, y:Number):void {
assertEquals(x, rect.x);
assertEquals(y, rect.y);
}
private function assertThrowsError(... args):void {
assertTrue(functionThrowsError.apply(null, args));
}
private function functionThrowsError(functionToCall:Function, ... args):Boolean {
try {
functionToCall.apply(null, args);
return false;
} catch (error:Error) {
return true;
}
throw new Error("Should not reach this point");
}
private function newRectangle(x:Number = 0, y:Number = 0, w:Number = 0, h:Number = 0):Rectangle {
return new Rectangle(x, y, w, h);
}
private function areColliding(rectangle1:Rectangle, rectangle2:Rectangle):Boolean {
return RectangleCollision.detect(rectangle1, rectangle2);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't know what's best practice, but you could set up the needed Rectangles/Positions/expected Intersections in the setup method, so that the tests itselfs are shorter and faster to understand. </p>\n\n<p>I wrote some intersection unit tests myself the last weeks, i know that sometime you'll get confused about what the test ought to do. </p>\n\n<p>Also, you should maybe check for degenerate cases, i.e. a rectangle with zero width and/or height.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:21:54.497",
"Id": "47177",
"Score": "0",
"body": "i would do, but i have to pass the function different arguments each time, so i can't put it in the setUp method. i know these don't test the edge cases enough, i wanted to ask if there was a way to relieve the repetition before i tested it more."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:45:04.603",
"Id": "47182",
"Score": "0",
"body": "Why are you asserting the positions of the input rectangles in every test? Can they be modified by the collision tests? If so, you could extract a method for the repeating creation of rectangles and testing it by making an array with input and expected positions/intersection points."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:47:56.137",
"Id": "47183",
"Score": "0",
"body": "No they can't, I put those there to test that they had not moved. If I make a modification later and that modification changes the position of one of the inputs it will fail the test and I will know I have introduced a bug."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T21:17:48.030",
"Id": "29765",
"ParentId": "29754",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T17:33:49.990",
"Id": "29754",
"Score": "1",
"Tags": [
"unit-testing",
"collision",
"actionscript-3"
],
"Title": "Unit tests for collisions"
}
|
29754
|
<p>I had to calculate the difference between Chicago Board of Trade grain futures prices using VB.net and came up with the following (admittedly clunky) solution. It's a <em>little</em> tricky because CBOT prices, as posted, mix octal and decimal numbers. Anyway, here is my code for you to enjoy and tear apart:</p>
<pre><code> Public Function GrainSubtraction(ByVal numberOne As Double, ByVal numberTwo As Double) As Double
' This is a somewhat convoluted function to subtract CBOT grain prices ... but it seems to work
' It assumes the numbers have no decimals - that is, if the price of corn is $4.75 3/4 per bushel, this number is represented as 4756 where the last digit (6) represents 6/8
' Basically, we perform octal subtraction on the smallest unit digit and regular decimal subtraction on the remaining digits
' I use arrays to do this so I can isolate each digit - there is probably a more efficient way to do this, though - I'm not a quant
Dim tempOne As Double = 0.0
Dim tempTwo As Double = 0.0
Dim inverted As Boolean = False 'Flags whether the second number is larger than the first
Dim answer As Double = 0.0 ' This will be our ultimate response
Dim multiplier As Double = 1.0
' Here, we compare the two numbers and invert them if the second number is largest then the first
If numberOne = numberTwo Then Return 0.0
If numberOne < numberTwo Then
tempOne = numberTwo
tempTwo = numberOne
inverted = True
Else
tempOne = numberOne
tempTwo = numberTwo
End If
Dim lengthOne = CStr(tempOne).Length ' How many digits in number one?
Dim lengthTwo = CStr(tempTwo).Length
Dim I As Integer = 0
Dim errorFlag As Boolean = False 'Let's us know whether we hit an error with this number
Dim numberLength As Integer
If lengthOne > lengthTwo Then numberLength = lengthOne Else numberLength = lengthTwo
' Create our array
Dim numberOneArray(numberLength) As Integer
Dim numberTwoArray(numberLength) As Integer
Dim answerArray(numberLength) As Integer ' This will hold our answer as an array
' Set Array Values To Zero
For I = 0 To numberLength - 1
numberOneArray(I) = 0
numberTwoArray(I) = 0
Next
For I = 0 To lengthOne - 1
numberOneArray(I) = tempOne Mod 10
tempOne = Int(tempOne / 10)
Next
For I = 0 To lengthTwo - 1
numberTwoArray(I) = tempTwo Mod 10
tempTwo = Int(tempTwo / 10)
Next I
' This is where we do the actual analysis
For I = 0 To numberLength - 1
If I = 0 Then ' We're doing Octal subtraction here
If numberOneArray(I) >= numberTwoArray(I) Then
answerArray(I) = numberOneArray(I) - numberTwoArray(I)
Else
If I = numberLength Then
errorFlag = True
Else
numberOneArray(I) = numberOneArray(I) + 8
numberOneArray(I + 1) = numberOneArray(I + 1) - 1
answerArray(I) = numberOneArray(I) - numberTwoArray(I)
End If
End If
Else ' We're doing Decimal subtraction here
If numberOneArray(I) >= numberTwoArray(I) Then
answerArray(I) = numberOneArray(I) - numberTwoArray(I)
Else
If I = numberLength Then
errorFlag = True
Else
numberOneArray(I) = numberOneArray(I) + 10
numberOneArray(I + 1) = numberOneArray(I + 1) - 1
answerArray(I) = numberOneArray(I) - numberTwoArray(I)
End If
End If
End If
Next
multiplier = 1
If errorFlag = True Then Return 0.0
For I = 0 To numberLength - 1
answer = answer + (answerArray(I) * multiplier)
multiplier = multiplier * 10
Next
If inverted = True Then answer = -answer
Return answer
End Function
</code></pre>
|
[] |
[
{
"body": "<p>The following will shorten your code considerably:</p>\n\n<pre><code>Public Function GrainSubtraction(ByVal numberOne As Double, ByVal numberTwo As Double) As Double\n Dim Dec1 As Integer = CInt(Int(numberOne / 10.0))\n Dim Oct1 As Integer = CInt(numberOne - (Dec1 * 10))\n Dim Dec2 As Integer = CInt(Int(numberTwo / 10))\n Dim Oct2 As Integer = CInt(numberTwo - (Dec2 * 10))\n Dim ResultDec, ResultOct As Integer\n If Oct1 < Oct2 Then\n Dec1 -= 1\n ResultOct = CInt(7 - (Oct2 - Oct1))\n Else\n ResultOct = CInt(Oct1 - Oct2)\n End If\n ResultDec = CInt(Dec1 - Dec2)\n Return CDbl((Math.Abs(ResultDec * 10) + ResultOct) * Math.Sign(ResultDec))\nEnd Function\n</code></pre>\n\n<p>This does simple octal subtraction on the last digits of the numbers supplied and decimal subtraction on the rest. I left the parameters and the return type as doubles but it would make more sense to have them as integers, since that's what they basically are.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T16:16:55.520",
"Id": "29756",
"ParentId": "29755",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T15:12:28.967",
"Id": "29755",
"Score": "3",
"Tags": [
"vb.net"
],
"Title": "How To Subtract CBOT Grain Prices"
}
|
29755
|
<p>I know this is not very good. I am currently in my first programming class (Java). It seems like it works, but I am sure there are things I have not thought of.</p>
<p>The goal is to have a user enter</p>
<ul>
<li>the number of credit units each class they need to take is worth, one by one</li>
<li>the number of credit units to complete in a term</li>
</ul>
<p>The program should calculate</p>
<ul>
<li>the number of remaining credit units</li>
<li>the number of terms it will take to complete the degree</li>
<li>the cost</li>
</ul>
<p></p>
<pre><code>import java.util.ArrayList;
import java.util.Scanner;
public class GraduationPlanner {
public static void main(String[] args) {
int sum = 0;
String creditUnits;
int unitsLeft;
int plannedUnits = 0;
int termsLeft = 0;
double tuitionCost = 0;
final double TUITION_RATE = 2890;
ArrayList<Integer> cu = new ArrayList<Integer>();
Scanner in = new Scanner(System.in);
System.out.println("Please input the Credit Units for each course. Press enter after each course. Press Q when finished: ");
while (in.hasNextInt()) {
int temp = (in.nextInt());
if (temp < 0) {
System.out.print("ERROR! Please enter a number 1-9.: ");
} else {
cu.add(temp);
}
}
System.out.println(cu);
Scanner ex = new Scanner(System.in);
System.out.print("Please enter the number of Credit Units you will complete per term: ");
if (ex.hasNextInt()) {
plannedUnits = ex.nextInt();
}
for (int a : cu)
{
sum += a;
}
unitsLeft = (sum - plannedUnits);
termsLeft = (sum / plannedUnits);
tuitionCost = (termsLeft * TUITION_RATE);
System.out.println("After this term there are " + unitsLeft + " credit units remaining.");
System.out.println("You will complete your degree in " + termsLeft + " terms.");
System.out.print("It will cost you " + tuitionCost + " to complete your degree.");
}
}
</code></pre>
<p><strong>New code block</strong></p>
<pre><code>/* Determines the length of time and cost of a degree program
* based on user inputs.
*/
import java.util.ArrayList;
import java.util.Scanner;
public class GraduationPlanner {
public static void main(String[] args) {
final double TUITION_RATE = 2890;
ArrayList<Integer> creditUnits = new ArrayList<Integer>();
Scanner unitsPerCourse = new Scanner(System.in);
GetCreditUnits(unitsPerCourse, creditUnits);
System.out.println(creditUnits);
System.out.print("Please enter the number of Credit Units you will complete per term: ");
Scanner goalUnits = new Scanner(System.in);
int plannedUnits = GetPlannedUnits(goalUnits);
int creditUnitsSum = TotalOfCreditUnits(creditUnits);
double tuitionCost;
int termsLeft = CalculateTermsToComple(creditUnitsSum, plannedUnits);
int unitsLeft;
unitsLeft = CalculateUnitsLeft(creditUnitsSum, plannedUnits);
tuitionCost = CalculateTuition(termsLeft, TUITION_RATE);
System.out.println("After this term there are " + unitsLeft + " credit units remaining.");
System.out.println("You will complete your degree in " + termsLeft + " terms.");
System.out.print("It will cost you " + tuitionCost + " to complete your degree.");
unitsPerCourse.close();
goalUnits.close();
}
public static void GetCreditUnits(Scanner unitsPerCourse, ArrayList<Integer> creditUnits) {
System.out.println("Please input the Credit Units for each course. Press enter after each course. Press Q when finished: ");
while (unitsPerCourse.hasNextInt()) {
int currentUnit = (unitsPerCourse.nextInt());
if (currentUnit < 1 || currentUnit >= 10) {
System.out.print("ERROR! Please enter a number 1-9.: ");
} else {
creditUnits.add(currentUnit);
}
}
}
public static int GetPlannedUnits(Scanner goalUnits) {
int plannedUnits = 0;
if (goalUnits.hasNextInt()) {
plannedUnits = goalUnits.nextInt();
} else {
System.out.print("ERROR! Please enter an integer!: ");
}
return plannedUnits;
}
public static int CalculateTermsToComple(int creditUnitsSum, int plannedUnits) {
int termsLeft = (int) Math.ceil((double) creditUnitsSum / plannedUnits);
return termsLeft;
}
public static int CalculateUnitsLeft(int creditUnitsSum, int plannedUnits) {
int unitsLeft;
unitsLeft = creditUnitsSum - plannedUnits;
return unitsLeft;
}
public static double CalculateTuition(int termsLeft, final double TUITION_RATE) {
double tuitionCost;
tuitionCost = termsLeft * TUITION_RATE;
return tuitionCost;
}
public static int TotalOfCreditUnits(ArrayList<Integer> creditUnits) {
int creditUnitsSum = 0;
for (int unit : creditUnits) {
creditUnitsSum += unit;
}
return creditUnitsSum;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have been teaching Java to new students for some years, and I have seen a lot of beginner Java code. For a complete beginner, your code isn't horrible -- and that's high praise! For example, your variable naming is fairly decent, especially for a beginner. (But <code>cu</code> isn't a good name. Change that.) I can't see anything in your code that immediately strikes me as <strong>Don't do that!!!</strong>, and that is rare for beginner code :-)</p>\n\n<p>There are of course a lot of things to improve upon. I'm only going to state some of the parts I consider most urgent, because you need to learn one step at a time. Once you master the basic principles, you can move on.</p>\n\n<h3>The small steps</h3>\n\n<p>First of all, you should divide your code into logical segments. Preferably, this should be various methods/functions, but start by doing logical divisions inside your <code>main</code> function. <strong>Group the code lines into logical units, and separate those units with a single empty line.</strong> You don't want to create your variables earlier than needed. If you keep them close to where they are used, i.e. make them part of the code they logically belong to, it's easier to remember what they are for, and to avoid using them in the wrong place. For example, move <code>int sum = 0;</code> down to right above</p>\n\n<pre><code>for (int a : cu) {\n sum += a;\n}\n</code></pre>\n\n<p>Note that I changed your <code>for</code> loop to adhere to the Java conventions, like the rest of your code does.</p>\n\n<h3>Functions</h3>\n\n<p>After that, you should split your code into functions. Try to make a function perform a single logical computation. Knowing what \"a single computation\" really means is <em>hard</em>, but you will get it with experience. The old Unix mantra is nice: <strong>\"Do one thing, and do it well.\"</strong></p>\n\n<p>Do not fall for the temptation to move variables into class scope when you introduce functions. Pass them as parameters instead.</p>\n\n<p>The reason you want to use functions is to reduce complexity. Which of these two snippets is easier to read?</p>\n\n<pre><code>int sum = calculateSum(numbers);\n</code></pre>\n\n<p>or...</p>\n\n<pre><code>int sum = 0;\nfor (int i : numbers) {\n sum += i;\n}\n</code></pre>\n\n<p>Exactly. Neither of the snippets are rocket science, but the former is much easier to read. Functions are also used to make the code easier to reuse and Bob Loblaw, but don't think too much about that yet.</p>\n\n<p>Note that since you want a function to do a single item of work, you don't want functions that do <em>both</em> computations <em>and</em> input/output. In your case, you should probably do I/O in <code>main</code> and call functions to do the real calculation.</p>\n\n<p>When you have incorporated these changes and are happy with your program, you could post it as a new question for further guidelines.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T18:26:15.007",
"Id": "29758",
"ParentId": "29757",
"Score": "8"
}
},
{
"body": "<p>Your program is a good starting point. It's not perfect but it doesn't have to be (I've seen code much worse than yours written by people studying programming for longer than you have). </p>\n\n<p>Now, our goals when writing programs are:</p>\n\n<ol>\n<li>Make it work</li>\n<li>Make it readable.</li>\n</ol>\n\n<p>If your program works, then congratulations -- the first step is complete.\nHere goes the actual review.</p>\n\n<p>Many of the variables you used have decent names (<code>plannedUnits</code>, etc.), but we can do better:</p>\n\n<ol>\n<li>The variables <code>cu</code> and <code>a</code>: What <em>are</em> those? <code>cu</code> seems to be the list that stored course units, so I'm guessing that's what cu stands for. But characters are cheap, so let's rename <code>cu</code> to <code>courseUnits</code> and <code>a</code> to <code>courseUnit</code>!</li>\n<li><code>sum</code> is reasonable -- it tells us that it is keeping track of the sum of <em>something</em>. But what exactly? It seems to be course units, so let's call it <code>courseUnitSum</code> or <code>sumOfCourseUnits</code>.</li>\n<li>You use two variables (<code>in</code> and <code>ex</code>). Rename them to <code>courseUnitsScanner</code> and <code>plannedUnitsScanner</code>.</li>\n<li><code>temp</code> is not very clear either. Maybe <code>newCourseUnit</code>?</li>\n<li><code>creditUnits</code> is not used anywhere, is it? If you don't need it, then delete it.</li>\n</ol>\n\n<p>In second place, I see you declaring tons of variables early but only using them late in the code. Try to declare variables as late as possible -- and let's see what we can come up with</p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.Scanner;\n\npublic class GraduationPlanner {\n\n public static void main(String[] args) {\n System.out.println(\"Please input the Credit Units for each course. Press enter after each course. Press Q when finished: \");\n Scanner in = new Scanner(System.in);\n ArrayList<Integer> courseUnits = new ArrayList<Integer>();\n while (in.hasNextInt()) {\n int newCourseUnit = (in.nextInt());\n if (newCourseUnit < 0) {\n System.out.print(\"ERROR! Please enter a number 1-9.: \");\n } else {\n courseUnits.add(newCourseUnit);\n }\n }\n System.out.println(courseUnits);\n\n System.out.print(\"Please enter the number of Credit Units you will complete per term: \");\n Scanner ex = new Scanner(System.in);\n int plannedUnits = 0;\n if (ex.hasNextInt()) {\n plannedUnits = ex.nextInt();\n }\n\n int sumOfCourseUnits = 0;\n for (int courseUnit : courseUnits) \n {\n sum += courseUnit;\n }\n int unitsLeft = (sum - plannedUnits);\n System.out.println(\"After this term there are \" + unitsLeft + \" credit units remaining.\");\n\n int termsLeft = (sumOfCourseUnits / plannedUnits);\n System.out.println(\"You will complete your degree in \" + termsLeft + \" terms.\");\n final double TUITION_RATE = 2890;\n double tuitionCost = (termsLeft * TUITION_RATE);\n System.out.print(\"It will cost you \" + tuitionCost + \" to complete your degree.\");\n\n }\n}\n</code></pre>\n\n<p>I see you writing <code>int variableName = (something + someOtherThing);</code>. Those parenthesis are not needed. Just write <code>int variableName = something + someOtherThing;</code>. Though of course having too many parenthesis doesn't hurt.</p>\n\n<blockquote>\n <p>System.out.print(\"ERROR! Please enter a number 1-9.: \");</p>\n</blockquote>\n\n<p>Heh. You say \"1-9\" but you only check if it is negative. If <code>0</code> and <code>10</code> are not acceptable values, then use:</p>\n\n<pre><code>if (temp < 1 || temp > 9) {\n</code></pre>\n\n<p><code>sum / plannedUnits</code>. This will round the result down. Is that what you want? For instance, if there are 20 units and you plan 6 units, you'll have 3 terms (not 4). My suggestion would be:</p>\n\n<pre><code>int termsLeft = (int)Math.ceil((double)sum / plannedUnits);\n</code></pre>\n\n<p>but I use \"explicit type casts\" here, and I suspect you might have not learned about those yet. So an alternative is:</p>\n\n<pre><code>int termsLeft = sum / plannedUnits;\nif (sum % plannedUnits != 0) {\n termsLeft++;\n}\n</code></pre>\n\n<p>Aside from this, you have no comments and you are using just a single method -- but I don't know if you've learned what any of those words mean, so I'd rather not overwhelm you. It's okay for your work not to be perfect the first time.</p>\n\n<p>One warning, though:</p>\n\n<pre><code> if (ex.hasNextInt()) {\n plannedUnits = ex.nextInt();\n }\n</code></pre>\n\n<p>What happens if the user does not input an integer (and instead writes regular text)? Will <code>plannedUnits</code> remain zero? If so, beware -- you'll be dividing by zero later on!</p>\n\n<hr>\n\n<p><strong>UPDATE</strong>: You updated your code so it's only fair that I update my review.</p>\n\n<p>Your new version is much better than the first one.</p>\n\n<p>That said, you have missed one important piece of @Lstor's advice: Your \"Get\" functions have I/O.</p>\n\n<p>About <code>unitsPerCourse</code>: This is a weird name for a Scanner. I'd expect a number or maybe a <code>Map</code> for a variable with this name. This is <em>not</em> a variable that contains the <code>unitsPerCourse</code>, it's the variable that handles <em>asking the user about <code>unitsPerCourse</code></em>.</p>\n\n<p>Also, in Java, it is common for method names to start with a lowercase letter, so <code>GetPlannedUnits</code> would be <code>getPlannedUnits</code>.</p>\n\n<p>The use of uppercase <code>TUITION_RATE</code> is very common for constants, but weird for function parameter names.</p>\n\n<p><code>final</code> in parameters means the function is not allowed to change the value of the parameter -- but the code that uses the function can pass any value it wants. You never change the value of parameters anyway, so it doesn't make much sense to make TUITION_RATE one. I'd do one of the following:</p>\n\n<ol>\n<li>Change it to a normal parameter (<code>tuitionRate</code> in <code>CalculateTuition</code>, but keep it called <code>TUITION_RATE</code> in <code>main</code>);</li>\n<li>Remove the parameter and move <code>TUITION_RATE</code> to the <code>CalculateTuition</code>.</li>\n<li>Move <code>CalculateTuition</code> to the class level.</li>\n</ol>\n\n<p>This code could be simplifed:</p>\n\n<pre><code>public static int CalculateUnitsLeft(int creditUnitsSum, int plannedUnits) {\n int unitsLeft;\n unitsLeft = creditUnitsSum - plannedUnits;\n return unitsLeft;\n}\n</code></pre>\n\n<p>Why separate the declaration of <code>unitsLeft</code> and its assignment? You can just do:</p>\n\n<pre><code>int unitsLeft = creditUnitsSum - plannedUnits;\n</code></pre>\n\n<p>In fact, we can do even better:</p>\n\n<pre><code>public static int CalculateUnitsLeft(int creditUnitsSum, int plannedUnits) {\n return creditUnitsSum - plannedUnits;\n}\n</code></pre>\n\n<p>Finally, have you learned about \"exceptions\" yet? If not, then this won't make much sense to you, but if/when you do, the usual way to handle resources that must be closed is:</p>\n\n<pre><code>Scanner unitsPerCourse = new Scanner(System.in);\ntry {\n //Your code here\n} finally {\n unitsPerClose.close();\n}\n</code></pre>\n\n<p>Newer versions of Java (Java 7) have a shorter version that does the same (called <a href=\"http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow\">try-with-resources</a>):</p>\n\n<pre><code>try (Scanner unitsPerCourse = new Scanner(System.in) {\n //Your code here\n}\n</code></pre>\n\n<p>I hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T21:18:30.023",
"Id": "47115",
"Score": "0",
"body": "I down voted this answer for two reasons. One is that the variable `sum` is missing in your code, so it won't compile. Also the `if` statement should be `if (temp < 1 || temp > 9)`, not 10. Fix those and I'll remove the down vote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T21:20:52.780",
"Id": "47116",
"Score": "1",
"body": "@syb0rg Fixed, but note that the code I posted is meant merely as an example, not something to be copied and pasted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T22:23:04.430",
"Id": "47117",
"Score": "0",
"body": "Once again thank you all for you help. This place will be a very helpful resource as I learn to code. I hope eventually I can help others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T22:40:04.077",
"Id": "47118",
"Score": "0",
"body": "Not sure of the rules here. Should I vote to delete this post since it has been answered?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T22:53:46.773",
"Id": "47120",
"Score": "0",
"body": "@andy Leave it open for other students in your situation to see."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T18:48:56.690",
"Id": "29761",
"ParentId": "29757",
"Score": "6"
}
},
{
"body": "<p>A few things I noted:</p>\n\n<p>You never close your scanners. That's a resource leak, which isn't good. Always close your <code>Scanners</code> when you are done with them:</p>\n\n<pre><code>in.close();\n</code></pre>\n\n<hr>\n\n<p>Your logic condition here:</p>\n\n<pre><code>if (temp < 0)\n{\n System.out.print(\"ERROR! Please enter a number 1-9.: \");\n}\n</code></pre>\n\n<p>Right now if you enter 0, it accepts it. In the error message, it says to only enter a number 1-9:</p>\n\n<pre><code>if (temp < 1 || temp > 9)\n{\n // ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T18:49:06.270",
"Id": "29762",
"ParentId": "29757",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29761",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T17:58:53.350",
"Id": "29757",
"Score": "6",
"Tags": [
"java",
"beginner"
],
"Title": "Graduation planner"
}
|
29757
|
<p>I like the fact that I can create a class and have the connection details in one file if I need to update them and then pass them to the method I create in the class that defines my specific use of mysqli. I was thinking also that I may give an option to pass the connection details if I need to use a different db in one page. Is this a good idea. Any adverse problems?</p>
<p><strong>Basic Example (Note the values defined in __constructor)</strong></p>
<pre><code>public function __construct($host = 'localhost', $user = 'myuser', $pass = 'mypass', $db = 'mydb') {
// Connect to Database
$this->mydb = new mysqli($host, $user, $pass, $db);
}
</code></pre>
|
[] |
[
{
"body": "<p><em>Note: this post gets extremely side tracked, but the two ideas are pretty closely related, so hopefully my rambling ends up being helpful.</em></p>\n\n<p><code>new</code> in a constructor is an anti-pattern. It immediately creates very high coupling, and it murders any form of coding to interface.</p>\n\n<p>Rather than passing what you need to construct the object, you should pass the actual object. This idea (or at least, an idea very closely related to it) is called dependency injection.</p>\n\n<p>This is all a bit abstract, so I'll give an example. Imagine that you have a simple database-backed logger. I'm more familiar with PDO than MySQLi, so I'll use it.</p>\n\n<pre><code>class DbLogger\n{\n private $_db;\n\n const WARNING = 1;\n const ERROR = 2;\n\n public function __construct()\n {\n $this->_db = new PDO(\"sqlite:log.sqlite\", null, null, array(\n PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION\n ));\n }\n\n public function log($message, $severity)\n {\n $stmt = $this->_db->prepare(\"INSERT INTO log (message, serverity) VALUES (?, ?)\");\n $stmt->execute(array($message, $severity));\n }\n\n}\n</code></pre>\n\n<p>Seems simple enough, right? And quite easy to use. No matter where you are in code, you can just do <code>$log = new DbLogger(); $log->log('...');</code> and you're done.</p>\n\n<p>There's a major problem though. What if you want to use a different database? What if you want a <code>users_log.sqlite</code> and a <code>financials_log.sqlite</code>? Well, simple... You could just pass the name of the log to the constructor.</p>\n\n<p>And yes, that would work, but how manageable is it? Do you really want to find all the places that the name is used every time you want to change it?</p>\n\n<p>Consider if instead of creating the PDO instance, the constructor accepted it. This allows an important difference to happen: DbLogger no longer has to care about how to create a PDO object; it only has to care about <em>using</em> it. Now if you want to use two different databases, you just construct two different loggers based on two different PDO objects. \"But,\" you might say, \"don't I then have to pass around the details of my log database?\"</p>\n\n<p>Nope. Instead of passing around the details, you just pass around the object.</p>\n\n<p>Any object that needs a logger, you just construct it with a logger. Or, if only a certain method needs logging, you only have to pass that method the logger. It's a bit hard to get used to this pattern, but once you've done it a bit, the way the object graph fits together becomes a lot more clear.</p>\n\n<p>Basically, the idea is to never create your own dependencies. That creates extreme coupling and makes providing alternate implementations impossible. To steal an example from a Google code talk, imagine that you have a bit of code that's responsible for charging a credit card. Now, imagine that you want to test that code. So, you go, you add three items, and you go to run the transaction. Oops, you just actually charged yourself. So... how do you fake it? Do you comment out the actual request and just echo out the variables? Sure, that works once, but how do you make sure you don't accidentally break the code later? You need the test to be rerunnable. You need it to be able to go through the normal process, but instead of actually running the credit card, you need it to just pretend. This is a perfect example of why dependency injection is necessary. If you instead pass in a credit card charging object, a real implementation can be used during production, but for tests, you can just use a mock that just verifies what's passed to it.</p>\n\n<p>Anyway, I'm rambling a bit, so here's a real example:</p>\n\n<pre><code>interface Logger\n{\n const INFO = 1;\n const WARNING = 2;\n const ERROR = 3;\n public function log($message, $severity);\n}\n\nclass NullLogger implements Logger\n{\n public function log($message, $severity)\n { }\n}\n\nclass DbLogger implements Logger\n{\n private $_db;\n public function __construct(PDO $db)\n {\n $this->_db = $db;\n }\n\n public function log($message, $severity)\n {\n $this->_db->prepare(\"...\");\n $this->_db->execute(...);\n }\n\n}\n\nclass FileLogger implements Logger\n{\n private $_fh;\n\n public function __construct($file)\n {\n if (!is_resource($file) && is_string($file)) {\n $file = fopen($file, 'a');\n }\n if (!is_resource($file)) {\n throw new InvalidArgumentException(\"A valid file handle or path must be provided: \" . $file);\n }\n $this->_fh = $file;\n }\n\n public function log($message, $severity = self::WARNING)\n {\n fputs($this->_fh, \"...\");\n }\n\n}\n</code></pre>\n\n<p>Now, imagine you have some class that needs a logger. It no longer is tied specifically to a specified DbLogger. In fact, it's no longer tied to a DbLogger at all. All the object has to care about is that it has an object on which it can call <code>log</code>. It's not tied to a specific logger. If we need to change the logger, we just pass it a different logger on construction. No magic to it. No need to edit a bunch of files. Just one config.php (or config.ini/config.json/etc) has to be changed. All we need is a very top layer that knows how to kick off the chain of object creation (\"a User needs a DBAL which needs a DatabaseConnection which needs a PDO\" for example) and this can all be done with fairly little effort (and lots of different approaches/tools exist to do that).</p>\n\n<hr>\n\n<p>Hopefully this answer has been at least semi-useful. It's super rambling, and it's not exactly what you were asking about, but I'm guessing that dependency injection and coding to interface are not two things that you're familiar with. It's a bit odd in a situation with database connections since they're so low level (relatively). There's not exactly a RDBMS interface that MySQLi and other connection classes extend. This makes the interface thing a pretty unrelated topic. When the question is extended to a higher level concept though, hopefully it makes sense.</p>\n\n<p>Anyway, please let me know if you have any questions as I fear that this explanation is pretty bad.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:26:47.507",
"Id": "47196",
"Score": "0",
"body": "I do understand the angle you are getting at. I have been reading a lot on the basic concepts of the things you talk about but ultimately decided to create mysqli first then if needed format interface off that class and then create other classes. I don't intend to use PDO as it seems a bit too overcomplicated for my use. So as such will need to create a class for each db type. I love the fact I can get elaborate answers that expand on examples that I can keep in mind when developing new applications. Thank you so much for your time!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T08:24:56.740",
"Id": "29779",
"ParentId": "29763",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29779",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T20:16:49.323",
"Id": "29763",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"constructor"
],
"Title": "__constructor mysqli variable options"
}
|
29763
|
<p>How can I optimize the following class?</p>
<p><code>prepareSharing</code> packs bits on left and <code>prepareMask</code> counts the required bits for encoding integers between zero and max. </p>
<pre><code>public class KeyFactory
{
public static short[] prepareSharing( short[] sharing, int mask )
{
// Ensure mask is unsigned short
//
mask &= 0xFFFF;
// Search first zero bits
//
// BE CAREFUL : raise java.lang.ArrayIndexOutOfBoundsException if there aren't enough bits available
//
int i = 0;
while( ( sharing[i] & 0xFFFF ) == 0xFFFF )
i++;
// Handle masks larger than available free bits
//
int remaining = ~( sharing[i] & 0xFFFF ) & 0x0000FFFF;
if( remaining < mask )
{
for( ;remaining > 0; remaining >>= 1, mask >>= 1 );
sharing[i++] |= 0xFFFF;
}
// Pack bits
//
int temporary, current = sharing[i];
for( temporary = ( current | mask ) & 0xFFFF; ( ( current | ( mask << 1 ) ) & 0xFFFF ) > temporary; mask <<= 1, temporary = ( current | mask ) & 0xFFFF );
sharing[i] = 0;
sharing[i] |= temporary;
return sharing;
}
public static int prepareMask( int maxCount )
{
int mask = 0;
for( int i = 0; i < 16; i++ )
if( maxCount >> i > 0 )
mask |= 1 << i;
return mask;
}
}
</code></pre>
<p><strong>Tests</strong>:</p>
<pre><code>import org.junit.Assert;
import org.junit.Test;
import fr.meuns.render.KeyFactory;
public class TestKeyFactory
{
@Test
public void testPrepareMask()
{
Assert.assertEquals( 0b0001 ,KeyFactory.prepareMask( 1 ) );
Assert.assertEquals( 0b0011 ,KeyFactory.prepareMask( 2 ) );
Assert.assertEquals( 0b0011 ,KeyFactory.prepareMask( 3 ) );
Assert.assertEquals( 0b0111 ,KeyFactory.prepareMask( 4 ) );
Assert.assertEquals( 0b0111 ,KeyFactory.prepareMask( 5 ) );
Assert.assertEquals( 0b0111 ,KeyFactory.prepareMask( 6 ) );
Assert.assertEquals( 0b0111 ,KeyFactory.prepareMask( 7 ) );
for( int i = 8; i < 16; i++ )
Assert.assertEquals( 0b001111 ,KeyFactory.prepareMask( i ) );
for( int i = 16; i < 32; i++ )
Assert.assertEquals( 0b011111 ,KeyFactory.prepareMask( i ) );
for( int i = 32; i < 64; i++ )
Assert.assertEquals( 0b111111 ,KeyFactory.prepareMask( i ) );
}
@Test
public void testPackSharing_0x0007()
{
short[] sharing = new short[] {
0x0000, 0x0000
};
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xE000, sharing[0] & 0xFFFF );
Assert.assertEquals( 0x0000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFC00, sharing[0] & 0xFFFF );
Assert.assertEquals( 0x0000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFF80, sharing[0] & 0xFFFF );
Assert.assertEquals( 0x0000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFFF0, sharing[0] & 0xFFFF );
Assert.assertEquals( 0x0000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFFFE, sharing[0] & 0xFFFF );
Assert.assertEquals( 0x0000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xC000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xF800, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xFF00, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xFFE0, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x0007 );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xFFFC, sharing[1] & 0xFFFF );
}
@Test
public void testPackSharing_0x003F()
{
short[] sharing = new short[] {
0x0000, 0x0000
};
sharing = KeyFactory.prepareSharing( sharing, (short)0x003F );
Assert.assertEquals( 0xFC00, sharing[0] & 0xFFFF );
Assert.assertEquals( 0x0000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x003F );
Assert.assertEquals( 0xFFF0, sharing[0] & 0xFFFF );
Assert.assertEquals( 0x0000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x003F );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xC000, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x003F );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xFF00, sharing[1] & 0xFFFF );
sharing = KeyFactory.prepareSharing( sharing, (short)0x003F );
Assert.assertEquals( 0xFFFF, sharing[0] & 0xFFFF );
Assert.assertEquals( 0xFFFC, sharing[1] & 0xFFFF );
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:12:16.310",
"Id": "47277",
"Score": "0",
"body": "What's wrong with good old `BitSet`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:24:03.657",
"Id": "47288",
"Score": "0",
"body": "BitSet uses JNI, does a lot of checking and stocks bits in long words. JNI and checking wastes performances. Longs are painful for comparing resulting keys (see posts about signed and unsigned int java mess). Converting long words to short words is bad for performance too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T00:17:28.030",
"Id": "63589",
"Score": "2",
"body": "`BitSet` does not use JNI. Just look at the source."
}
] |
[
{
"body": "<p>The very first thing I miss, in both your question and the code, is a description of what it does. You should make a habit out of <a href=\"http://en.wikipedia.org/wiki/Javadoc\" rel=\"nofollow\">documenting your code with JavaDoc</a>. After some time it will go easy while writing code and will improve the readability tremendously. It's also a nice way to do a quick check if the class is supposed to do what you expect it to do.</p>\n\n<hr>\n\n<p>Java normally uses <a href=\"http://en.wikipedia.org/wiki/Indent_style#Variant%3a_1TBS\" rel=\"nofollow\">a modified K&R style</a> for braces and indentation:</p>\n\n<pre><code>public function void test() {\n if (condition) {\n // Code\n } else {\n // Code\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Just in case: You're not supposed to use Bitmasks in Java, <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/EnumSet.html\" rel=\"nofollow\">the EnumSet is supposed to take it's place</a>.</p>\n\n<hr>\n\n<pre><code>public class KeyFactory\n</code></pre>\n\n<p>Helper classes should be declared <code>public final</code> with a private constructor like this:</p>\n\n<pre><code>/**\n * Static helper class for dealing with Bitmasks.\n */\npublic final class KeyHelper {\n private KeyHelper() {}\n</code></pre>\n\n<hr>\n\n<pre><code> public static short[] prepareSharing( short[] sharing, int mask )\n {\n // Ensure mask is unsigned short\n //\n mask &= 0xFFFF;\n</code></pre>\n\n<p>Yet it is declared as <code>int</code>. Is that by design? if you want an <code>unsigned short</code>, shouldn't you only take an <code>unsigned short</code>? Especially as you cast the <code>int</code>s in the tests to <code>short</code>s?</p>\n\n<hr>\n\n<pre><code>// Search first zero bits\n//\n// BE CAREFUL : raise java.lang.ArrayIndexOutOfBoundsException if there aren't enough bits available\n//\nint i = 0;\nwhile( ( sharing[i] & 0xFFFF ) == 0xFFFF )\n i++;\n</code></pre>\n\n<p>That's an information that should go into the JavaDoc of the method.</p>\n\n<hr>\n\n<pre><code>int i = 0;\n</code></pre>\n\n<p>The only time <code>i</code> is a valid variable name is within a <code>for</code>-loop. You use it as a reusable and important variable throughout the function, that means that it should have a better, even if longer, name.</p>\n\n<hr>\n\n<p>You're not using curly braces for one-line loops or <code>if</code>s. You should start using them as it makes your code easier to read.</p>\n\n<hr>\n\n<p>Your use of <code>for</code> loops is valid, from a syntactical point of view, but is far from readable.</p>\n\n<p>Turning them into longer, more verbose variants is advised.</p>\n\n<hr>\n\n<p>I did no review of the logic itself as, to be honest, it is very hard to follow and I have a hard time figuring out what it is supposed to do in the first place (missing documentation and description).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-04T12:37:18.570",
"Id": "40840",
"ParentId": "29764",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T21:17:39.453",
"Id": "29764",
"Score": "5",
"Tags": [
"java",
"bitwise"
],
"Title": "Playing with bits using Java"
}
|
29764
|
<p>I'm using Twitter Bootstrap. I haven't coded anything significant web design related in a while, because I've been doing desktop stuff and games. I'm trying to get back into the flow of things. Can anyone tell me if what I have is sufficient without going into ridiculous detail (the script, not the answer)?</p>
<p><strong>Partial HTML:</strong></p>
<pre class="lang-html prettyprint-override"><code><div class='container' id="loginContainer">
<h3>Login</h3>
<form method="post" name="login" id="login" action="" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputLoginUsername">Username</label>
<div class="controls">
<input type="text" id="inputLoginUsername" name="inputLoginUsername" required placeholder="Username" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputLoginPassword">Password</label>
<div class="controls">
<input type="password" id="inputLoginPassword" name="inputLoginPassword" required placeholder="Password">
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" name="inputLoginSubmit" id="inputLoginSubmit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
</code></pre>
<p><strong>JavaScript:</strong></p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function() {
$('#register').submit(function(event) {
event.preventDefault();
$.post('process.php', {
inputRegisterSubmit: '',
inputRegisterUsername: $('#inputRegisterUsername').val(),
inputRegisterPassword: $('#inputRegisterPassword').val(),
inputConfirmPassword: $('#inputConfirmPassword').val()
}).done(function(data) {
$('#registerOutput').html(data);
if (data.indexOf("success") !== -1)
$('#registerContainer').slideUp();
});
});
$('#login').submit(function(event) {
event.preventDefault();
$.post('process.php', {
inputLoginSubmit: '',
inputLoginUsername: $('#inputLoginUsername').val(),
inputLoginPassword: $('#inputLoginPassword').val()
}).done(function(data) {
$('#loginOutput').html(data);
if (data.indexOf("success") !== -1)
$('#loginContainer').slideUp();
});
});
});
</code></pre>
<p><strong>PHP:</strong></p>
<pre><code><?php
$mysqli = new mysqli("localhost", "user", "pass", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_POST['inputRegisterSubmit']))
{
if (!($stmt = $mysqli->prepare("INSERT INTO users(user_name, user_pass, user_email, user_date) VALUES (?, ?, ?, ?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$user_name = $_POST['inputRegisterUsername'];
$user_pass = $_POST['inputRegisterPassword'];
$user_confirm = $_POST['inputConfirmPassword'];
if ($user_pass != $user_confirm) echo "<p class='text-error'>Your passwords don't match.</p>";
else {
$user_email = 'user@user.com';
if (!$stmt->bind_param("ssss", $user_name, $user_pass, $user_email, date("Y-m-d H:i:s"))) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->close();
echo "<p class='text-success'>Log in now!</p>";
}
} else if (isset($_POST['inputLoginSubmit'])) {
if (!($stmt = $mysqli->prepare("SELECT user_name FROM users WHERE user_pass = ?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$user_name = $_POST['inputLoginUsername'];
$user_pass = $_POST['inputLoginPassword'];
if (!$stmt->bind_param("s", $user_pass)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->store_result();
if ($stmt->num_rows <= 0)
echo "<p class='text-error'>Invalid user/pass combination.</p>";
else
echo "<p class='text-success'>Logging you in now!</p>";
$stmt->close();
} else header('Location: http://www.site.com/');
$mysqli->close();
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T00:43:27.003",
"Id": "47121",
"Score": "0",
"body": "I haven't done anything with PHP in a while but it's good that you are using prepared statements. Are you doing any parameter checking/sanitizing anywhere?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:36:43.187",
"Id": "47537",
"Score": "0",
"body": "Yes he is at the bind_param call"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:38:01.223",
"Id": "47538",
"Score": "0",
"body": "I recommend you to use tje jquery.form plugin: http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form"
}
] |
[
{
"body": "<p>If you plan on putting this out in the wild (the web), I suggest you handle your <strong>error feedback a little more user friendly</strong>. If this is for your home server and you'll be the only one using it, it's fine. But displaying binding or executing errors definitely helps attackers get an insight of your methods.</p>\n\n<p>Also, you seem to have forgotten to actually check the username when they log in? You're seeing if there's a row with that password (more on that below), and then <strong>if there's one or more accounts with that password, you log them in?</strong></p>\n\n<p>You should be checking to make sure there is <strong>exactly one row with the user-submitted username and password</strong>. Perhaps you accidentally just forgot this part!</p>\n\n<p>More on your passwords! You have <em>some</em> protection: you're binding. But that's it? You're storing your passwords in plain text! Go ahead and <a href=\"https://security.stackexchange.com/questions/211/how-to-securely-hash-passwords\">read this</a> to learn a bit more on how you should be keeping your sensitive data in databases!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-19T01:28:34.703",
"Id": "42093",
"ParentId": "29766",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-14T21:57:02.160",
"Id": "29766",
"Score": "3",
"Tags": [
"javascript",
"php",
"html",
"ajax",
"twitter-bootstrap"
],
"Title": "Simple AJAX login/register script"
}
|
29766
|
<p>This was my first attempt at writing object-oriented JavaScript. It's a Minesweeper clone in jQuery. I thought I had done an OK job, but I've just received some feedback stating that it wasn't written in an object-oriented manner. I don't expect anyone to read this line for line. I'm just looking for general feedback.</p>
<pre><code>$(document).ready(function() {
var Minesweeper = function() {
var self = this;
var defaultOptions = {
boardSize: [8, 8],
difficulty: 'easy'
}
// initialize our cell object
var cells;
this.init = function(options) {
// empty the cell object if it has anything in it
cells = [];
if (typeof options == 'object') {
options = $.extend(defaultOptions, options);
} else {
options = defaultOptions;
}
self.difficulty = options.difficulty;
// setup a new game
self.newGame(options.boardSize);
};
this.newGame = function(boardSize) {
//remove the old board if there is one, detach event listeners as well
$('#minesweeper').empty();
var x = boardSize[0];
var y = boardSize[1];
self.width = x;
//setup our new board
self.addUI();
self.buildGrid(x, y);
}
this.addUI = function() {
var board = $('#minesweeper');
var checkMe = $('<div/>').attr({
id: 'check-me',
class: 'happy-smiley'
});
var mineCount = $('<div/>').attr('id', 'mine-count');
var timer = $('<div/>').attr('id', 'timer').html('0');
var ui = $('<div/>').attr('id', 'ui');
ui.append(mineCount);
ui.append(timer);
ui.append(checkMe);
board.append(ui);
}
this.buildGrid = function(columns, rows) {
var rowDiv;
var id = 0;
// build a containg div for each row, and then populate each row with the correct
// number of cells to fill out our grid
for (var i = 0; i <= rows - 1; i++) {
rowDiv = $('<div/>').attr({
'id': 'row' + i,
'class': 'row'
}).appendTo($('#minesweeper'));
for (var j = 0; j <= columns - 1; j++) {
var cell = $('<div/>').attr({
'id': id++,
'class': 'cell'
}).appendTo(rowDiv);
// add the cell to the cells array so we can access it later instead of
// looping through the DOM
cells.push({
'hasMine': false,
'flagged': false,
'cleared': false
});
}
}
// set the width and height of our minesweeper container based on how many columns we have
var cellWidth = $('.cell').outerWidth();
var uiHeight = $('#ui').outerHeight();
$('#minesweeper').width(cellWidth * columns).height(cellWidth * rows + uiHeight);
$('.cell').css('cursor', 'pointer');
// add event listeners for our newly created cells
self.setHandlers();
// add the mines to our grid
self.setMines(self.difficulty);
}
this.setMines = function(difficulty) {
// the number of mines is different for each difficulty level
switch (difficulty) {
case 'hard':
var mineDensity = 4;
break;
case 'middle':
var mineDensity = 5.2;
break;
default:
var mineDensity = 6.4;
break;
}
var numberOfCells = cells.length;
var maxCellId = numberOfCells - 1;
var numberOfMines = Math.round(numberOfCells / mineDensity);
self.mineCount = numberOfMines;
$('#mine-count').html(numberOfMines);
for (var i = 0; i < numberOfMines; i++) {
// generate a random number between 0 and the maximum cell id we have
var cellId = Math.floor(Math.random() * maxCellId) + 1;
// check if we have already placed a mine on this cell
// if we have, deincrement the counter to make sure we get the correct number of mines
if (cells[cellId].hasMine) {
i--;
} else {
// place mine
cells[cellId].hasMine = true;
$('#' + cellId).addClass('mine');
}
}
}
this.setHandlers = function() {
var firstClick = true;
$('.cell').on('click', function() {
//start the timer only on the first click
if (firstClick) {
self.startTimer();
firstClick = false;
}
var id = this.id;
if (cells[id].hasMine) {
self.gameOver();
$(this).css('background-color', '#ff0000');
} else {
self.clearCell(id);
}
});
$('.cell').on('contextmenu', function(event) {
var cell = $(this);
var id = this.id;
if (cells[id].flagged) {
cell.removeClass('flagged');
cells[id].flagged = false;
cells[id].checked = false;
self.mineCount++;
$('#mine-count').html(self.mineCount);
return false;
} else {
if (cells[id].cleared) {
return false;
} else {
cell.addClass('flagged');
cells[id].flagged = true;
self.mineCount = self.mineCount - 1;
$('#mine-count').html(self.mineCount);
return false;
}
}
event.preventDefault();
});
$('#check-me').on('click', function() {
if ($(this).hasClass('sad-smiley')) {
self.reset();
} else {
self.check();
}
});
}
this.gameOver = function() {
$('.cell').css('cursor', 'default');
$('#minesweeper .mine').toggleClass('show');
$('#check-me').attr('class', 'sad-smiley');
//lock the game board so the user can't click on any cells
$('.cell').off();
self.stopTimer = true;
}
this.cheat = function() {
$('.mine').toggleClass('show');
setTimeout(function() {
$('.mine').toggleClass('show');
}, 1000);
}
this.reset = function() {
self.init();
}
this.check = function() {
var loser;
$.each(cells, function(index) {
if (cells[index].cleared == false && cells[index].hasMine == false) {
self.gameOver();
alert('Looks like you missed a few...');
loser = true;
return false;
}
});
if (!loser) {
self.win();
}
}
this.win = function() {
$('#check-me').attr('class', 'cool-smiley');
alert("Winner!")
}
this.getNeighbors = function(cellId) {
var neighbors = new Array();
var neighborBombs = 0;
var width = self.width;
// need to fix this. It was just a hack to make sure we had an integer not a string
var id = +cellId;
// If we are on the top row, the id - width will always be < 0
if (id - width > 0) {
// We are not on the top row. So get the cell above us (Top)
var top = id - width;
neighbors.push(top);
if (cells[top].hasMine) {
neighborBombs += 1;
}
// before we get the Top Right cell, check that we aren't on the far right edge of the board
if (((top + 1) % width) !== 0) {
var topRight = top + 1;
neighbors.push(topRight);
if (cells[topRight].hasMine) {
neighborBombs += 1;
}
}
// do the same with the Top Left cell
if ((top % width) !== 0) {
var topLeft = top - 1;
neighbors.push(topLeft);
if (cells[topLeft].hasMine) {
neighborBombs += 1;
}
}
}
// if the cell id is evenly divisble by the width, then we are on the left edge
if (id % width !== 0) {
var left = id - 1;
neighbors.push(left);
if (cells[left].hasMine) {
neighborBombs += 1;
}
}
// if the cell id + 1 is evenly divisible by the width, then we are on the right edge
if ((id + 1) % width !== 0) {
var right = id + 1;
neighbors.push(right);
if (cells[right].hasMine) {
neighborBombs += 1;
}
}
// if the cell id + the width of the grid is < the total number of cells, we are not on the bottom row
if (id + width < cells.length) {
var bottom = id + width;
neighbors.push(bottom);
if (cells[bottom].hasMine) {
neighborBombs += 1;
}
// check that we aren't on the right edge of the board
if ((bottom + 1) % width !== 0) {
var bottomRight = bottom + 1;
neighbors.push(bottomRight);
if (cells[bottomRight].hasMine) {
neighborBombs += 1;
}
}
// check that we aren't on the left edge of the board
if (bottom % width != 0) {
var bottomLeft = bottom - 1;
neighbors.push(bottomLeft);
if (cells[bottomLeft].hasMine) {
neighborBombs += 1;
}
}
}
var cellData = {
cells: neighbors,
bombs: neighborBombs
}
return cellData;
}
this.startTimer = function() {
self.stopTimer = null;
var time = 0;
$('#timer').html(time);
(function tick() {
if (self.stopTimer) {
clearTimeout(moreTime);
} else {
time += 1;
$('#timer').html(time);
var moreTime = setTimeout(tick, 1000);
}
})();
}
this.clearCell = function(cellId) {
if (cells[cellId].checked) {
// been here before...
} else {
// make sure there isn't flag on this cell before we clear it
if (cells[cellId].flagged == false) {
$('#' + cellId).addClass('cleared');
cells[cellId].checked = true;
cells[cellId].cleared = true;
var neighbors = self.getNeighbors(cellId);
if (neighbors.bombs > 0) {
$('#' + cellId).html(neighbors.bombs);
$('#' + cellId).addClass("number" + neighbors.bombs);
} else {
$('#' + cellId).addClass('cleared');
$.each(neighbors.cells, function(index, value) {
if (cells[value].hasMine) {} else {
self.clearCell(value);
}
});
}
} else {
cells[cellId].checked = true;
}
}
}
}
var minesweeper = new Minesweeper();
minesweeper.init({
boardSize: [8, 8],
difficulty: 'easy'
});
// add event listeners for the options panel
$('#cheat').on('click', function() {
console.log('cheated');
minesweeper.cheat();
});
$('#new-game').on('click', function() {
minesweeper.reset();
minesweeper.stopTimer = true;
});
$('#difficulty').change(function() {
minesweeper.init({
'difficulty': $(this).val()
});
});
$('#board-size').change(function() {
var selected = $(this).find('option:selected');
var x = selected.data('x');
var y = selected.data('y');
minesweeper.init({
boardSize: [x, y]
});
})
$('#show-timer').change(function() {
$('#timer').toggleClass('hidden');
});
});
$(window).load(function() {
//preload images that will be needed later
$.fn.preload = function() {
this.each(function() {
$('<img/>')[0].src = this;
});
}
$(['/images/mine.png', '/images/red_flag.png', '/images/smiley_cool.png', '/images/smiley_happy.png', '/images/smiley_sad.png']).preload();
});
</code></pre>
<p>Any thoughts or improvements? Other feedback I have received was that my <code>getNeighbors</code> method was too complicated (which it probably is), but I was purposefully trying not to use a coordinate type system. My mistake, I guess.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T00:55:53.403",
"Id": "47122",
"Score": "0",
"body": "Your entire program is pretty much in one function, try separating it into objects and methods. Also the usage of `self` is confusing, the language already has the perfectly fine keyword `this`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T01:00:26.160",
"Id": "47123",
"Score": "0",
"body": "Thanks for the feedback. I used self in order to access 'this' inside of the method calls, but maybe it's not necessary. Relevant SO question about it http://stackoverflow.com/questions/3309516/when-to-use-self-in-javascript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T01:04:22.537",
"Id": "47124",
"Score": "0",
"body": "Just saw your other comment. Thanks for the helpful feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T01:04:38.940",
"Id": "47125",
"Score": "8",
"body": "I see, well try to identify the objects in your program. The physical entities or abstract concepts. I can recognize plenty of objects here: `Cell`, `Board`, `Game`, `Grid`, `Mine`, `Timer` and so on. Then design their methods and interactions with each other, and model them with classes (constructors and prototypes). Don't just cram everything inside one function because I have to scroll horizontally because the indentation level is so much out of control."
}
] |
[
{
"body": "<p>As @Esailija has said in the comments, OOP is about, well, <em>objects</em>.</p>\n\n<p><strong>Before you write any code</strong>, you should stop and think - what are the key concepts at play here? This is a <em>Minesweeper</em> implementation, so the very first thing you should do is lay down all the objects you can think of, what their respective members might be, and how they're all related.</p>\n\n<p><strong>As you write your code</strong>, you should keep an eye out for objects and methods that <em>do too many things</em>. For your code to be simple, each building block must also be fairly simple, i.e. if an object <em>owns</em> too much of the functionality, part of it can probably be broken down into simpler objects.</p>\n\n<p><strong>After you implemented an object</strong>, don't just move on to the next one: re-read your code, refactor repeating or redundant code into smaller reusable functions, lookout for <em>cyclomatic complexity</em> (e.g. nested ifs / \"arrow\" code) and review all names involved. Proper naming is just as important as getting the code to work: if it's a pet project you might finish it and then forget it, but in real-world code you're going to have to <em>maintain</em> the code, and that means all you've written was about 20% of the time you'll end up spending on that code - the other 80% is <em>reading your code</em>. That said your naming looks good :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T03:11:31.423",
"Id": "35658",
"ParentId": "29771",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T00:32:59.823",
"Id": "29771",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"beginner",
"game",
"minesweeper"
],
"Title": "Minesweeper clone in jQuery"
}
|
29771
|
<p>I wrote this as an academic exercise over on CA. It is supposed to tell a true story about two drag racers, one in his 80's who beat a young world champion in cars that traverse a 1/4 mile in 3 seconds at 300 mph. It is structured to let the old man win every time because it is based on a true story. I did it mainly to explore objects. The story has been left out for brevity.</p>
<pre><code>var comedy;
comedy = function () {
confirm("In the world of motorsports, 'snip'");
function dragRacer(name, age, drink, cocktail) {
this.name = name;
this.age = age;
this.drink = drink;
this.cocktail = cocktail;
}
var chris = new dragRacer("Chris Karamesines", 82, "Nitro Methane");
var tony = new dragRacer("Tony Shumacher", 43, null, "Blueberry Vodka in lime soda");
dragRacer.prototype.rt = function () {
var reactionTime = Math.random();
return reactionTime;
};
dragRacer.prototype.et = function () {
var elapsedTime = Math.random() + 3.70;
return elapsedTime;
};
var chrisET = chris.et();
var tonyET = tony.et();
var chrisRT = chris.rt();
var tonyRT = tony.rt();
if (chrisRT <= tonyRT) {
chrisRT = tonyRT + 0.09;
}
console.log(chrisRT);//test
console.log(tonyRT);//test
if (chrisRT <= tonyRT) {
chrisRT = 0.19 + tonyRT;
}
if (tonyET <= chrisET) {
tonyET = chrisET + 1.2;
}
chrisRT = chrisRT.toFixed(2);
tonyRT = tonyRT.toFixed(2);
chrisET = chrisET.toFixed(2);
tonyET = tonyET.toFixed(2);
console.log(chrisRT);
console.log(tonyRT);
console.log(chrisET);//test
console.log(tonyET);//test
confirm("Chris' favorite drink is " + chris.drink + " and " + chris.age +//
" and " + chrisET + " and " + chrisRT + " . ");
confirm("Tony' favorite cocktail is " + tony.cocktail + " and " + tony.age +//
" and " + tonyET + " and " + tonyRT + " . ");
};
comedy();
</code></pre>
|
[] |
[
{
"body": "<p>Code-wise:</p>\n\n<pre><code>var comedy;\ncomedy = function(){...};\ncomedy();\n</code></pre>\n\n<p>The first two lines can be simplified into <code>var comedy = function(){...}</code>. If you don't need the function to be anonymous, you can even use <code>function comedy(){...};</code>. If this is the only place you are using this function, you can even go for an immediately invoked function expression: <code>(function comedy(){...})()</code> (at which point the name only serves as documentation). Separating the definition from the call may serve code structuring purposes, but I don't see the need to separate the definition and the declaration here.</p>\n\n<p>OOP classes should use UpperCase names, so <code>function DragRacer(...){...}</code>. If I see a function named <code>dragRacer</code>, I don't expect it to be a constructor.</p>\n\n<p>Prototype definitions should be written just after the constructor. Logically, they both are parts of a class definition. Technically, instantiating a class before it is fully defined could be problematic - if the constructor calls some prototype functions, the prototype needs to be defined before the constructor is called.</p>\n\n<p>I am not well-versed in the motor sport industry, but it seems to me the function names <code>rt</code> and <code>et</code> are not very descriptive. You can get away with single-lettered variables used in function bodies (especially if they are math-heavy), but not in public facing method names. The function body can be simplified as well. Clarity will be maintained by the function name:</p>\n\n<pre><code>DragRacer.prototype.reactionTime = function () {\n return Math.random();\n};\n</code></pre>\n\n<p><code>chrisRT = chrisRT.toFixed(2);</code> -- at this point, you are changing the type of a variable. While the compiler can handle that, you could reduce the developer performance. First, the semantics of a variable are dependent on where it is used in code. While it is not unusual to have variables change their values, here the <em>meaning</em> of the variable changes dynamically. Second, you might need the float value after you need the string value. In this case, you need two separate variables anyways. If you need help naming variables that only differ in types, you could borrow the hungarian notation: <code>strChrisRT = chrisRT.toFixed(2);</code>. The variable name is still somewhat cryptic, but at least you don't have to worry when to convert from float to string. </p>\n\n<hr>\n\n<p>I am wondering why a drag racer's cocktail is not considered a drink. Blueberry Vodka in lime soda is surely a drink as far as I can tell.</p>\n\n<pre><code>if (chrisRT <= tonyRT) {\n chrisRT = tonyRT + 0.09;\n}\nconsole.log(chrisRT);//test\nconsole.log(tonyRT);//test\n\nif (chrisRT <= tonyRT) {\n chrisRT = 0.19 + tonyRT;\n}\n</code></pre>\n\n<p>Here you have some redundant code. After the first condition body executes, the second condition body will not. If the first condition body does not execute, the second condition body will not execute either, because the condition is the same. In effect, the second condition body is a piece of dead code, and can be removed altogether. As a side note, I'm wondering why the constant is the left argument once, and the right argument the second time.</p>\n\n<p>I know the purpose is to cheat, but the business logic here is weird anyways. Let me demonstrate with the following table; especially note the discontinuity around 0.00:</p>\n\n<pre><code>chrisRT - tonyRT | -0.02 | -0.01 | 0.00 | 0.01 | 0.02 || 0.08 | 0.09 | 0.10 |\n-----------------------------------------------------------------------------\nchrisRT - tonyRT | 0.09 | 0.09 | 0.09 | 0.01 | 0.02 || 0.08 | 0.09 | 0.10 |\n</code></pre>\n\n<p>from the user interface standpoint, <code>confirm</code>s are not very nice. Since you are not using the return value, you could use an <code>alert</code> instead, but, if you want a nice interface, you could turn the code into being event driven and communicating via HTML. <code>confirm(\"hello\")</code> => <code>$messages.append($(\"<p>\").text(\"hello\"))</code> (I am using jQuery, but you don't have to). Especially the initial storyline could be present in the initial document as a plain paragraph with a button that runs the javascript part.</p>\n\n<hr>\n\n<blockquote>\n <p>Chris' favorite drink is Nitro Metane and 83 and 0.19 and 0.09 . \"</p>\n</blockquote>\n\n<p>I know these are only debugging messages, but still... what?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:30:48.147",
"Id": "47179",
"Score": "0",
"body": "I cannot thank you enough for taking the time and effort to respond in such a thoughtful and helpful way. After work, I will respond in kind to some of your questions. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T05:42:24.783",
"Id": "29776",
"ParentId": "29773",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T03:43:46.423",
"Id": "29773",
"Score": "7",
"Tags": [
"javascript"
],
"Title": "True story about two drag racers"
}
|
29773
|
<p>I've just started learning HTML and CSS. Currently I'm creating a test site to practice with.</p>
<p>I'm just after an early idea if the principles I'm using are correct. The below is an snippet from the main body of my HTML code. It's just about positioning text and images on a grid at the moment. I seem to be using a lot of <code>div</code>s with IDs in the CSS for styling etc.</p>
<p>Some of the alt text is work in progress and repeated currently hence why it repeats.</p>
<p>Can someone tell me if the structure is ok, or not and what I'd need to do to change this?</p>
<pre><code><div id="topmenu" class="grid_4">
<a href="www.bbc.com">About Us &nbsp &nbsp</a><a href="www.bbc.com">Our Cheeses &nbsp &nbsp</a><a href="www.bbc.com">Contact Us</a>
</div>
<div id="quote_one" class="grid_4">
<p>"QUOTE 1 - We really love the taste of your cheese, we will be back for more"</p>
</div>
<div id="logo" class="grid_4">
<img src="logo.jpg" alt="This is the company logo">
</div>
<div id="quote_two" class="grid_4">
<p>"QUOTE 2 - We really love the taste of your cheese, we will be back for more"</p>
</div>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:09:22.550",
"Id": "47173",
"Score": "1",
"body": "Validating your code should be your first step if you want to do things the \"right\" way (ie. you are mising a semicolon for your HTML entities, which the validator would have caught for you)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:11:21.907",
"Id": "47340",
"Score": "1",
"body": "I've found this website to be particularly helpful in learning about the new HTML5 elements: http://html5doctor.com/"
}
] |
[
{
"body": "<p>You should get into a habit of adding the protocol to your anchors, as it can sometimes lead to confusing effects, such as in this case:</p>\n\n<pre><code><a href=\"www.website.com\">Website!</a>\n</code></pre>\n\n<p>Let's say, the site where that code is on is called <a href=\"http://www.mywebsite.com/mypage.php\" rel=\"nofollow\">http://www.mywebsite.com/mypage.php</a></p>\n\n<p>Guess where you would go when clicking the <code><a></code>? \nYou would be directed to the address <a href=\"http://www.mywebsite.com/www.website.com\" rel=\"nofollow\">http://www.mywebsite.com/www.website.com</a> instead of the intended <a href=\"http://www.website.com\" rel=\"nofollow\">http://www.website.com</a></p>\n\n<p>Also, if you are going to do XTHML or HTML5, you should close your IMG tags like this:<br>\n<code><img src=\"logo.jpg\" alt=\"This is the company logo\" /></code><br>\nNotice the '/' in the end.</p>\n\n<p>The same applies to any tags that do not use a closing tag:<br>\n<code><p>This has a closing tag</p></code><br>\n<code><input type=\"text\" name=\"textField\" value=\"No closing tag in me!\" /></code></p>\n\n<p>A very good tool for testing your HTML is the official validator from W3C:\n<a href=\"http://validator.w3.org\" rel=\"nofollow\">http://validator.w3.org</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:06:25.070",
"Id": "47171",
"Score": "3",
"body": "The trailing slash for empty elements like img, br, input, etc. are optional for HTML5. They're only required for XHTML (since it is a dialect of XML)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T22:06:16.343",
"Id": "47206",
"Score": "0",
"body": "It is still good practice to close all tags though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T08:56:16.170",
"Id": "29781",
"ParentId": "29777",
"Score": "2"
}
},
{
"body": "<p><strong>a)</strong> Don’t use <code>&nbsp &nbsp</code> to separate the navigation links. You could use <code>ul</code> instead (and style it with CSS <code>display:inline;</code> if required):</p>\n\n<pre><code><ul>\n <li><a href=\"…\">About Us</a></li>\n <li><a href=\"…\">Our Cheeses</a></li>\n <li><a href=\"…\">Contact Us</a></li>\n</ul>\n</code></pre>\n\n<p><strong>b)</strong> <code>div</code> has no meaning. You should only use <code>div</code> if there is no other appropriate, \"narrower\" element. If you are quoting something, use <code>blockquote</code>. If you have a navigation menu, use <code>nav</code>. Of course you can use <code>div</code> in addition to those appropriate elements, if needed.</p>\n\n<p><strong>c)</strong> This is not an error, but an opinion-based advice: If you don’t have a strong reason, don’t add <code>id</code> attributes just because you need a styling hook. You could use the <code>class</code> attribute even for what some call \"unique\" elements. Good reasons to use <code>id</code> are: in-page links (fragment identifier) and, sometimes, JavaScript hooks.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:11:42.447",
"Id": "29809",
"ParentId": "29777",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T07:59:43.560",
"Id": "29777",
"Score": "5",
"Tags": [
"html",
"css",
"html5"
],
"Title": "Positioning text and images on a site grid"
}
|
29777
|
<p>I have some Java like this:</p>
<pre><code>if (!fooclass.getInfoText().equals(""))
{
this.setInfoText(fooclass.getInfoText());
}
</code></pre>
<p>Is there a neater way of setting one value based on the test results of another value? It seems nasty to me that the method is run twice, but putting the result in a variable when it may be empty and not used at all seems equally messy.</p>
<p>In PHP I might do:</p>
<pre><code>if (($foo = $bar->baz()) !== "")
{
$this->set_info_text = $foo;
}
</code></pre>
<p>But I know some people are quite strongly for and against this method, though I can't recall a good justification against it.</p>
|
[] |
[
{
"body": "<p>I believe <code>fooclass</code> is a reference of <code>Foo</code> class. I can only think about introducing a variable and check it to prevent the double-invokation of same method.</p>\n\n<pre><code>String fooInfo = fooclass.getInfoText();\nif (!\"\".equals(fooInfo))\n{\n this.setInfoText(fooInfo);\n}\n</code></pre>\n\n<p><strong>NOTE</strong> </p>\n\n<p>I'm using <code>\"\".equals(fooInfo)</code> to <a href=\"http://en.wikibooks.org/wiki/Java_Programming/Preventing_NullPointerException\" rel=\"nofollow\">avoid NPE</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T10:57:17.057",
"Id": "47133",
"Score": "0",
"body": "Thanks for the advice on avoiding NPE. So is this your recommended method, using a variable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T11:23:38.527",
"Id": "47135",
"Score": "0",
"body": "@deed02392 at this moment I can't think of another solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T13:41:27.737",
"Id": "47141",
"Score": "0",
"body": "Introducing a variable may be a form of premature optimization. Nevertheless an explaining variable may help readability. I usually do not introduce variables when it's about simple getters, as they are mostly self-explanatory. If setting `infoText`should always be a no-op then perhaps the setter could do the check, but then I'd be inclined to rename the setter to reflect this behavior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T13:49:52.887",
"Id": "47142",
"Score": "0",
"body": "@bowmore actually he was not happy with invoking same method twice. So I gave this solution & I'm not also very fond of introducing *unwanted* variables."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T13:51:24.000",
"Id": "47143",
"Score": "0",
"body": "Indeed, sometimes these methods are expensive, e.g. when they involve database queries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:14:10.193",
"Id": "47146",
"Score": "1",
"body": "@tintinmj I agree with your solution, it's basically what he'd do in php. I just wanted to clarify what would be a valid reason to introduce a variable, and what would not be."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T10:41:45.897",
"Id": "29782",
"ParentId": "29780",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T08:48:51.933",
"Id": "29780",
"Score": "1",
"Tags": [
"java",
"php"
],
"Title": "How to use the value of a method result based on a test?"
}
|
29780
|
<p>Is anything what could I improve on my code?</p>
<pre><code>import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class Helper {
public static Map<User, BigDecimal> createPlayersScoreMap(List<User> users, List<Score> scores) {
List<User> players = getPlayers(users);
Map<User, BigDecimal> playersScoreMap = new HashMap<User, BigDecimal>();
for (User player: players) {
BigDecimal sumScore = new BigDecimal(0);
for (Score score: scores) {
if (player.equals(score.getPlayer())) {
sumScore = sumScore.add(score.getResult());
}
}
playersScoreMap.put(player, sumScore);
}
return playersScoreMap;
}
private static List<User> getPlayers(List<User> users) {
List<User> filteredUsers = new ArrayList<User>(users);
for (Iterator<User> it = filteredUsers.iterator(); it.hasNext();) {
if (!it.next().isPlayer())
it.remove();
}
return filteredUsers;
}
}
</code></pre>
|
[] |
[
{
"body": "<p><code>Helper</code> is not a good class name. You should be able to come up with something that provides more context to what the functions are doing.</p>\n\n<p>In <code>getPlayers()</code>, I would loop and add instead of adding all and then removing.</p>\n\n<pre><code>private static List<User> getPlayers(List<User> users) {\n List<User> filteredUsers = new ArrayList<User>();\n for (User user : users) {\n if (user.isPlayer()) {\n filteredUsers.add(user);\n }\n }\n return filteredUsers;\n}\n</code></pre>\n\n<p>I also added curly braces around the if block. It's not necessary, but it will prevent errors if you need to add an extra line later. You also included them in <code>createPlayersScoreMap()</code>, so it's best to be consistent.</p>\n\n<p>If you have a large number of players and scores, you can make <code>createPlayersScoreMap()</code> more efficient (in terms of Big O processing). If <code>n</code> is the number of users and <code>m</code> is the number of scores, the method is currently O(n*m). However, if you sum all the scores first and then filter the players, you can get O(n+m).</p>\n\n<pre><code>public static Map<User, BigDecimal> createPlayerScores(List<User> users, List<Score> scores) {\n List<User> players = getPlayers(users);\n Map<User, BigDecimal> playerScores = new HashMap<User, BigDecimal>();\n\n for (Score score: scores) {\n User player = score.getPlayer();\n BigDecimal sumScore = score.getResult();\n if (playerScores.containsKey(player) {\n sumScore = sumScore.add(playerScores.get(player));\n }\n playerScores.put(player, sumScore);\n }\n Map<User, BigDecimal> filteredScores = new HashMap<User, BigDecimal>();\n for (User player : players) {\n filteredScores.put(player, playerScores.get(player));\n }\n return filteredScores;\n}\n</code></pre>\n\n<p>I also change the name of the function/variable. They type system makes it obvious that you are dealing with a <code>Map</code>, you don't need to include it in the variable name. If the calling method has <code>List</code>s and <code>Map</code>s that deal with players and scores, then it might be acceptable to include the type as part of the variable name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T13:55:56.910",
"Id": "47144",
"Score": "1",
"body": "In the original code there is a `new BigDecimal(0)` this should be replaced with `BigDecimal.ZERO`, otherwise this review covers it all I think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:02:15.043",
"Id": "47145",
"Score": "0",
"body": "@bowmore: Good catch. I've never actually used `BigDecimal`, so I didn't know that existed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T05:42:26.537",
"Id": "47220",
"Score": "0",
"body": "I think you can also eliminate the filteredScores Map. After all in playerScores, only those users are missing that are players without a score. So the second loop can simply loop users and add en entry for users that are players without a score."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T13:45:34.390",
"Id": "29787",
"ParentId": "29783",
"Score": "5"
}
},
{
"body": "<p>The <code>Helper</code> is an absolutely ridicoulus class name. How about <code>PlayerScoreMap</code>? This might be a good idea because <code>createPlayerScoreMap</code> is actually a constructor! (As evidenced by the name).</p>\n\n<p>The whole <code>getPlayers</code> helper is unneccessary, and backwards: All this does is to delete those users from a copied list that are not players, so that they are not iterated in the constructor. I have a better idea: Simply skip over those users that you don't like, e.g.</p>\n\n<pre><code>for (User user : users) {\n if (!user.isPlayer()) continue;\n\n ... // score summation\n}\n</code></pre>\n\n<p>Why are you using <code>BigDecimal</code>s? This is only reasonable when you have a scoring system that actually uses arbitrary fractional values (which is quite unusual). Most systems use integer scores or fixed point values, which can easily be translated to integers. Even if scores can be arbitrary values, an insignificant loss of precision <em>may</em> be acceptable. But this relies on the number of scores and the problem space, which I do not know about.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:04:43.207",
"Id": "29789",
"ParentId": "29783",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T12:19:50.037",
"Id": "29783",
"Score": "2",
"Tags": [
"java"
],
"Title": "Collating users and their scores"
}
|
29783
|
<p>I am new to C and have written this code just to teach myself how to work with linked lists and was hoping someone could review it and give me any comments or tips for efficiency, etc. The code just creates a list, adds and removes nodes from the list, and can reverse the list.</p>
<pre><code>/* Creates a linked list, adds and removes nodes and reverses list */
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
typedef bool;
#define false 0
#define true 1
typedef struct node {
int value;
struct node *next;
} node;
node *head = NULL; //Contains entire list
node *current = NULL; //Last item currently in the list
// Initialize list with input value
struct node* create_list(int input)
{
node* ptr;
printf("Creating a LinkedList with head node = %d\n", input);
ptr = (node*)malloc(sizeof(node)); // Allocating 8 bytes of memory for type node pointer
if (ptr == NULL) // Would occur is malloc can't allocate enough memory
{
printf("Node creation failed \n");
return NULL;
}
ptr->value = input;
ptr->next = NULL;
head = current = ptr;
return ptr;
}
// Add input value to the end of the list
struct node* add_to_end(int input)
{
node* ptr;
if (head == NULL)
{
return create_list(input);
}
ptr = (struct node*)malloc(sizeof(struct node));
if (ptr == NULL)
{
printf("Node creation failed \n");
return NULL;
}
else
{
ptr->value = input;
ptr->next = NULL; // End value in list should have NULL next pointer
current -> next = ptr; // Current node contains last value information
current = ptr;
}
printf("%d Added to END of the LinkedList.\n", input);
return head;
}
// Add input value to the head of the list
struct node* add_to_front(int input)
{
node* ptr;
if (head == NULL)
{
return create_list(input);
}
ptr = (struct node*)malloc(sizeof(struct node));
if (ptr == NULL)
{
printf("Node creation failed \n");
return NULL;
}
else
{
ptr->value = input;
ptr->next = head; // Point next value to the previous head
head = ptr;
}
printf("%d Added to HEAD of the LinkedList.\n", input);
return head;
}
// Return the number of items contained in a list
int size_list(node* ptr)
{
int index_count = 0;
while (ptr != NULL)
{
++index_count;
ptr = ptr->next;
}
return index_count;
}
// Add an input value at a user-specified index location in the list (starting from 0 index)
struct node* add_to_list(int input, int index)
{
node* ptr_prev = head;
node* ptr_new;
int index_count; // Used to count size of list
int index_track = 1; // Used to track current index
ptr_new = (struct node*)malloc(sizeof(struct node));
// Check that list exists before adding it in
if (head == NULL)
{
if (index == 0) // Create new list if 0 index is specified
{
add_to_front(input);
}
else
{
printf("Could not insert '%d' at index '%d' in the LinkedList because the list has not been initialized yet.\n", input, index);
return NULL;
}
}
// Count items in list to check whether item can added at specified location
if ((index_count = size_list(head)) < index)
{
printf("Could not insert '%d' at index '%d' in the LinkedList because there are only '%d' nodes in the LinkedList.\n", input, index, index_count);
return NULL;
}
//Go through list -- stop at item before insertion point
while (ptr_prev != NULL)
{
if (index == 0) // Use add_to_front function if user-specified index is 0 (the head of the list)
{
add_to_front(input);
return head;
}
if ((index_track) == index)
{
break;
}
ptr_prev = ptr_prev ->next;
++index_track;
}
ptr_new ->next = ptr_prev ->next; // Change the new node to point to the original's next pointer
ptr_new->value = input;
ptr_prev ->next = ptr_new; // Change the original node to point to the new node
return head;
}
// Verify if the list contains an input value and return the pointer to the value if it exists
struct node* search_list(int input, struct node **prev)
{
node* ptr = head;
node* temp = (node*)malloc(sizeof(node));
bool found = false;
// Search if value to be deleted exists in the list
while (ptr != NULL)
{
if(ptr->value == input)
{
found = true;
break;
}
else
{
temp = ptr;
ptr = ptr ->next;
}
}
// If the value is found in the list return the ptr to it
if(found == true)
{
if(prev)
*prev = temp;
return ptr;
}
else
{
return NULL;
}
}
// Remove an input value from the list
struct node* remove_from_list(int input)
{
node* prev = NULL; // list starting from one item before value to be deleted
node* del = NULL; // pointer to deleted value
// Obtain pointer to the list value to be deleted
del = search_list(input, &prev);
if(del == NULL)
{
printf("Error: '%d' could not be deleted from the LinkedList because it could not be found\n");
return NULL;
}
else
{
if (prev != NULL)
{
prev->next = del->next;
}
if (del == current) // If item to be deleted is last in list, set the current last item as the item before deleted one
{
current = prev;
}
else if (del == head) // If item to be deleted is the head of the list, set the new head as the item following the deleted one
{
head = del ->next;
}
return head;
}
}
// Reverse the order of the list
struct node* reverse_list()
{
node* reverse = NULL;
node* next = NULL;
node* ptr = head;
if (head == NULL)
{
printf("Error: There is no LinkedList to reverse.\n");
return NULL;
}
printf("Reversing order of the LinkedList.\n");
while (ptr != NULL)
{
next = ptr ->next; // Holds the remaining items in the original list
ptr ->next = reverse; // List now points to items in reversed list
reverse = ptr; // Reversed list set equal to the List
ptr = next; // List re-pointed back to hold list
}
head = reverse;
}
// Print the list to the console
void print_list()
{
node* ptr = head;
printf("------------------------------\n");
printf("PRINTING LINKED LIST\n");
while (ptr != NULL)
{
printf("%d\n", ptr->value);
ptr = ptr->next;
}
printf("------------------------------\n");
}
int main()
{
int i;
reverse_list(); //test function error message
for (i = 3; i > 0; --i)
{
add_to_front(i);
}
for (i= 4; i < 7; ++i)
{
add_to_end(i);
}
add_to_list(4,9); //test function error message
add_to_list(4,1);
print_list();
remove_from_list(3);
print_list();
reverse_list();
print_list();
add_to_list(10,0);
print_list();
getchar();
}
</code></pre>
|
[] |
[
{
"body": "<p>I would suggest you run this program through <code>valgrind</code>. Looks like you are leaking memory without any frees for the mallocs.</p>\n\n<p><strong>EDIT: (In regards to calling a function from another file)</strong>\nTo call a function from another file (say foo.c) you separate your linked list code into header and implementation files (say linked_list.h and linked_list.c).</p>\n\n<p>For example, in linked_list.h there would be the function prototype for create_list:</p>\n\n<pre><code>node* create_list(int input);\n</code></pre>\n\n<p>Then in in linked_list.c, at the top of the file you would include linked_list.h:</p>\n\n<pre><code>#include \"linked_list.h\"\n</code></pre>\n\n<p>and there would also be the implementation in linked_list.c:</p>\n\n<pre><code>node* create_list(int input) { ... }\n</code></pre>\n\n<p>Then in foo.c, you would include and call the code:</p>\n\n<pre><code>#include \"linked_list.h\"\n...\nnode* bar = create_list(my_number);\n...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:47:59.750",
"Id": "29793",
"ParentId": "29784",
"Score": "3"
}
},
{
"body": "<p>You code is quite good for a beginner and shows a grasp of how pointers and lists work, so that's great! However, there are a few points I'd like to address.</p>\n\n<p>I'll start by briefly listing what for me are less important issues or some things that others are likely to disagree with, then move on to more problematic errors:</p>\n\n<h3>General style:</h3>\n\n<ul>\n<li><p>Personally, I find that an if statement with a single-line block introduces too much noise. That is, I prefer</p>\n\n<pre><code>if (condition)\n statement;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if (condition)\n{\n statement;\n}\n</code></pre></li>\n<li>Since you typedefed <code>struct node</code> as <code>node</code>, you don't have to write <code>struct node</code> all the time.</li>\n</ul>\n\n<h3><code>malloc()</code> issues:</h3>\n\n<ul>\n<li>Don't cast the return value of <code>malloc()</code> unless you're writing C++: see <a href=\"https://stackoverflow.com/questions/1565496/specifically-whats-dangerous-about-casting-the-result-of-malloc\">this SO question</a>.</li>\n<li>It's better to write <code>ptr = malloc(sizeof(*ptr));</code> instead of <code>ptr = malloc(sizeof(node));</code> because that way the line won't need changing if the type of <code>ptr</code> changes.</li>\n</ul>\n\n<h3>Bigger problems:</h3>\n\n<ul>\n<li><p><strong>Globals:</strong> <code>head</code> and <code>current</code> seem to be global objects in your program, making all of the functions you wrote impossible to reuse. This impedes the usefulness of your list data structure. It is generally a good idea not to have any read-write globals at all, but read-only globals like conversion tables and constants are usually fine.</p>\n\n<p>For the purposes of an example, let's pretend to delete <code>head</code> and <code>current</code>. Let's look at the functions <code>create_list()</code> and <code>add_to_end()</code>:</p>\n\n<pre><code>// Initialize list with input value\nnode* create_list(int input)\n{ \n node *ptr = malloc(sizeof(*ptr)); // Allocating 8 bytes of memory for type node pointer\n\n if (ptr == NULL) // Would occur is malloc can't allocate enough memory\n return NULL;\n\n ptr->value = input;\n ptr->next = NULL;\n\n return ptr;\n}\n</code></pre>\n\n<p>The function merely creates a new list node and returns it, unless there's an error. Then, we can query the return value to determine if the creation of the list was successful:</p>\n\n<pre><code>node *head = create_list(7);\nif (head == NULL)\n some_kind_of_error_handling_here();\n</code></pre>\n\n<p>The same goes for <code>add_to_end()</code>:</p>\n\n<pre><code>// Add input value to the end of the list\nnode* add_to_end(node *head, int input)\n{\n\n if (head == NULL)\n return NULL;\n\n // Find the last element of the list\n while(head->next != NULL)\n head = head->next;\n\n node *ptr = malloc(sizeof(*ptr));\n\n if (ptr == NULL)\n return NULL;\n\n ptr->value = input;\n ptr->next = NULL; // End value in list should have NULL next pointer\n\n // Attach new node to the end of the list.\n head->next = ptr;\n\n return ptr; \n}\n</code></pre>\n\n<p>Now we find the last element, attach a new node to it (unless <code>malloc()</code> fails) and as a bonus return a pointer to it. Actually, a lot of this code looks familiar, so we can do better:</p>\n\n<pre><code>node* add_to_end(node *head, int input)\n{\n\n if (head == NULL)\n return NULL;\n\n node *ptr = create_list(input);\n\n if (ptr == NULL)\n return NULL;\n\n // Find the last element of the list\n while(head->next != NULL)\n head = head->next;\n\n // Attach new node to the end of the list.\n head->next = ptr;\n\n return ptr; \n}\n</code></pre>\n\n<p>Two things should be noted here: 1) We enabled code reuse by (the call to <code>create_list()</code>) by eliminating the globals and 2) that its possible to think of a list as consisting of a <em>head</em> and the <em>rest</em>, which is also a list.</p></li>\n<li><p><strong>Memory leaks:</strong> Every object allocated using <code>malloc()</code> and friends must be deallocated using <code>free()</code>. The best way to deallocate the list memory would be to provide a function like <code>delete_list()</code>.</p></li>\n<li><p><strong>Separation of concerns:</strong> It is generally a good idea not to mix code that manipulates data with input or output code. It is best to return an error code from functions that may fail and test for it in the caller. Doing this will not only make things easier to change later (for example, should we need to log errors to a file instead of print them out) but also make the functions shorter and easier to understand.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:57:27.070",
"Id": "47170",
"Score": "0",
"body": "can you show me some code that you would have written instead to address the Globals and Separation of concerns issues? I understand your reasoning, just not sure how to actually implement the changes. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T00:18:06.150",
"Id": "47215",
"Score": "0",
"body": "@sammis: Sure! I added some discussion of how to get rid of the globals and will add more examples later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:23:45.803",
"Id": "47261",
"Score": "0",
"body": "thanks so much! I'm having a problem when I don't cast the malloc. Changing to `node* ptr = malloc(sizeof(*ptr));` gives me the error: a value of type \"void*\" cannot be assigned to an entity of type \"node*\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:58:15.983",
"Id": "47273",
"Score": "0",
"body": "Are you compiling it as a C++ file (eg suffix .cc - should be just .c)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:08:55.090",
"Id": "47275",
"Score": "0",
"body": "In order to compile the code as C, you should add the flags `-pedantic` and one of `-ansi` for C89 or `-std=c99` for C99 to your compiler invocation. Since we used C99 features, you should go for C99. (the features include // comments and declaring variables mid-block)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:01:45.310",
"Id": "29795",
"ParentId": "29784",
"Score": "5"
}
},
{
"body": "<p>Just a few additional notes to the already existing answers:</p>\n\n<p>Your checks to for <code>NULL</code> pointers:</p>\n\n<pre><code>if (ptr == NULL)\nwhile (ptr != NULL)\n</code></pre>\n\n<p>Could be simplified to:</p>\n\n<pre><code>if (!ptr)\nwhile (ptr)\n</code></pre>\n\n<hr>\n\n<p>To quote @busy_wait:</p>\n\n<blockquote>\n <p><strong>Memory leaks</strong>: Every object allocated using <code>malloc()</code> and friends must\n be deallocated using <code>free()</code>. The best way to deallocate the list\n memory would be to provide a function like <code>delete_list()</code>.</p>\n</blockquote>\n\n<p>When you do free the allocated memory, make sure to set the pointer you free to <code>NULL</code>, so that you do not try to access the memory at that point again.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T23:57:56.910",
"Id": "47211",
"Score": "0",
"body": "Actually, some toolchains (embedded stuff) don't define NULL to be 0. It might not be standard, but they do. So IMHO it's better to test pointers for nullity explicitly and also makes more philosophical sense (is a pointer a condition?)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T03:15:31.477",
"Id": "47218",
"Score": "1",
"body": "@busy_wait: While some machines may use a non-zero address to indicate a null pointer, as far as I know, compilers are required to translate a constant 0 into whatever a null pointer is and treat a whatever a null pointer is as zero when it comes to comparisons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T10:34:32.520",
"Id": "47236",
"Score": "0",
"body": "Does that apply when the zero doesn't appear in the code, like in `if (!ptr)`? I don't know. I still think it's better to test for NULL explicitly (also conveys intent better IMO)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T18:00:03.187",
"Id": "29802",
"ParentId": "29784",
"Score": "2"
}
},
{
"body": "<p>As a simple list, what you have written in quite nice. If you were writing\nthis for a purpose (ie. to be used by someone) then your list has some\nshortcomings. First among these is the use of globals for head/tail. This\nrestricts the list to a single instance. A better approach is to make the\nfunctions operate on any list supplied as a parameter. What should the\nparameter be? To mirror what you have written, you would need to pass the\n<strong>addresses</strong> of the head and tail pointers of the list to each function.\nThis is a little inelegant. Alternatively you could either:</p>\n\n<ol>\n<li><p>pass a pointer to one node in the list (nominally the head, but not\nnecessarily);</p></li>\n<li><p>or create a <code>list</code> structure holding the head, tail and maybe the member count\nof the list.</p></li>\n</ol>\n\n<p>Option 1 is the simplest and is often enough. It has the drawback that adding\nnodes to the tail requires the list to be traversed. But depending upon the\napplication, that might not matter (adding to the head might be sufficient).</p>\n\n<p>Option 2 means that you need a structure such as:</p>\n\n<pre><code>typedef struct {\n int length;\n Node *head;\n Node *tail;\n} List;\n</code></pre>\n\n<p>This can then be instantiated on the stack:</p>\n\n<pre><code>List list1 = {\n .length = 0,\n .head = NULL,\n .tail = NULL\n};\n// or \nList list2 = {0, NULL, NULL};\n</code></pre>\n\n<p>or created and initialised by a <code>new_list()</code> function.</p>\n\n<p>The you can pass around the list, for example:</p>\n\n<pre><code>int list_append(List *list, int value) {...}\n</code></pre>\n\n<p><hr>\n<em>Code Duplication</em></p>\n\n<p>You use <code>malloc</code> to create a node in four places (five if we include\n<code>search_list</code>, but that one is an error). Instead you should write \na function that is called wherever a new node is needed:</p>\n\n<pre><code>static node* new_node(node *next, int value)\n{\n node *n = malloc(sizeof *n);\n if (n) {\n n->next = next; // pass NULL if the correct value is not avaialable\n n->value = value;\n }\n return n;\n}\n</code></pre>\n\n<p>Note that I used the name <code>value</code>, the same as the structure field, instead of <code>input</code>. It is better to use a single name for an entity wherever possible.</p>\n\n<p>Note also that my pointers are written without spaces around the <code>-></code>.\nAlthough you might prefer to add spaces, that might mark you out as a novice.</p>\n\n<hr>\n\n<p>I won't comment much on the function details as they rely on the globals\ndiscussed above. However,</p>\n\n<ul>\n<li><p><code>add_to_list</code> looks much too long and it traverses the whole list to find\nthe position required instead of just traversing up the the required index.</p></li>\n<li><p><code>search_list</code> should be rewritten without a <code>malloc</code> call and without the\nboolean type (note that <code>bool</code> is defined in <code>stdbool.h</code>, but it is\nunnecessary here). (Note also that your <code>typedef bool</code> should read <code>typedef\nint bool</code> - the compiler should have warned you about that).</p>\n\n<p>Without using a boolean, the main loop can be:</p>\n\n<pre><code> while (ptr != NULL && ptr->value != input) {\n ptr = ptr ->next;\n }\n if (ptr != NULL) { // ptr not NULL means the value was found\n ...\n }\n</code></pre>\n\n<p>The interface of this function is a bit odd in that a return parameter\nholds a pointer to the previous node. If the searched-for value is the\nhead of the list, this parameter receives a pointer to the malloced <code>temp</code>\nnode, which is clearly wrong. I can see that you wanted to return the\nprevious node so that <code>remove_from_list</code> can use it, but the result is\ninelegant. An alternative might be for <code>search_list</code> to take a <code>delete</code>\nparameter that says whether to delete the node (that too is inelegant) or\nfor <code>remove_from_list</code> to duplicate the <code>while</code> loop above.</p></li>\n<li><p>Note that <code>reverse_list</code> lacks a return value</p></li>\n</ul>\n\n<hr>\n\n<p>Some other minor comments:</p>\n\n<ul>\n<li><p>Functions with no parameters should take a <code>void</code> parameter list. </p></li>\n<li><p>You mix use of <code>node</code> and <code>struct node</code>. While not an error, this\ninconsistency is undesirable.</p></li>\n<li><p>With C99 it is possible to define variables at the point of first use. This\nis generally preferable.</p></li>\n<li><p>Many of your comments are unnecessary</p></li>\n<li><p>I disagree with busy_wait's preference for brace-less single-line\nstatements. Adding braces is ugly but prevents a class of error - adding an\nextra line of code that is not actually part of the conditional:</p>\n\n<pre><code>if (condition) \n do_something;\n do_something_else(); // this is not part of the conditional, although\n // it appears to be.\n</code></pre></li>\n<li>Make sure to enable warnings in the compiler (eg <code>-Wall</code> in gcc) and resolve all warnings.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:27:50.103",
"Id": "47264",
"Score": "0",
"body": "for you comment on `add_to_list`, how would you traverse indices without going through the list along with it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:04:12.150",
"Id": "47274",
"Score": "0",
"body": "I was a bit unclear - your code first traverses the whole list (in the call to `size_list`) **and** then traverses again up to the required index. It only needs to do the second part."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:26:34.047",
"Id": "29811",
"ParentId": "29784",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29795",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T12:50:53.377",
"Id": "29784",
"Score": "2",
"Tags": [
"beginner",
"c",
"linked-list"
],
"Title": "Reversing a linked list and adding/removing nodes"
}
|
29784
|
<p>I have a process that reads multiple sheets from an Excel file, then inserts the data into a database table. However, I am experiencing some memory issues when one of the sheets contains more than 65536 rows and am looking for ideas on how to improve the code.</p>
<p>In summary, I am using <code>cfspreadsheet</code> to "read" an uploaded Excel file. (In most cases, the file contains a single sheet. However, in some cases it is more than 2 sheets.) The process always reads the first sheet ie "Details" . If more than 65533 rows are found, it then reads the second sheet too i.e. "Details_1". Finally, I use a QoQ and <code>UNION ALL</code> to create a combined query. Once read, the data is inserted into a database table.</p>
<p>Can anyone offer suggestions for improving the process to make it less memory intensive?</p>
<pre><code><cffunction name="putExcel" access="remote" returnFormat="plain" output="true">
<cfargument name="xclfile" required="no" type="string" default="0">
<cfset ins =insertUserLog("#Session.user_name#","#Session.user_code#","putExcel function called for Upload","","")>
<cftry>
<cfset fileEXCL = "#ExpandPath('../folder')#/#arguments.xclfile#" />
<!---when there e 2 Sheets --->
<!---get info from sheet1 as a "query1"--->
<cfspreadsheet action="read" src="#fileEXCL#" sheet="1" query="Query1" headerrow="1" />
<!--- recordcount for "sheet1" as "count1"--->
<cfset count1 =#Query1.recordcount#>
<!--- case when excel has more than 65533 rows
;THIS IMPLIES THAT THERE 2 SHEETS)--->
<cfif count1 gt 65533>
<!--- take info from sheet 2 as a "query2" and count as "count2"--->
<cfspreadsheet action="read" src="#fileEXCL#" sheet="2" query="Query2" headerrow="1" />
<cfset count2 =#Query2.recordcount#>
<!---club both query's using QoQ and call it "excelQuery"--->
<cfquery dbtype="query" name="excelQuery">
SELECT * FROM Query1
UNION ALL
SELECT * FROM Query2
</cfquery>
<!---total record count for "sheet1" & "sheet2"--->
<cfset rowCount =#excelQuery.recordcount#>
<cfelse>
<!---this case there is just 1 query "Query1" ;rename it "excelQuery"--->
<cfquery dbtype="query" name="excelQuery">
SELECT * FROM Query1
</cfquery>
<!--- recordcount for "sheet1"--->
<cfset rowCount =#excelQuery.recordcount#>
</cfif>
<cflog file="Collections" application="yes" text="#Session.user_info.uname# logged in. Data file #fileEXCL# read. Recordcount:#rowCount#" type="Information">
<cfset ins =insertUserLog("#Session.user_name#","#Session.user_code#","file #fileEXCL# read. ","Recordcount:#rowCount#","")>
<cfcatch type="any" >
<cflog file="Collections" application="yes" text="Error in reading Data file #fileEXCL#." type="Error">
<cfset ins =insertUserLog("#Session.user_name#","#Session.user_code#","error file","failed","#cfcatch.Message#")>
<cfreturn 1>
</cfcatch>
</cftry>
... etc...
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:50:44.883",
"Id": "47148",
"Score": "0",
"body": "For those who didn't see it, here was the original question on SO: http://stackoverflow.com/questions/18246447/reading-excel-93-97-sheet-with-more-than-65536-rows-using-cfspreadsheet"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:21:05.467",
"Id": "47162",
"Score": "0",
"body": "(Edit) CFSpreadsheet has some memory issues to begin with, and QoQ's are generally for moderate sized resultsets ~5 to 50,000 rows (depending on memory). Combining the two probably pushes it over the edge. If you are ultimately inserting it into a db table it is more efficient to skip cfspreadsheet altogether and use db tools to perform the insert (if possible). That is my preferred approach for importing Excel files into sql server. What is your db type?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:21:31.260",
"Id": "47163",
"Score": "0",
"body": "My DB type is SQL"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:21:46.290",
"Id": "47164",
"Score": "0",
"body": "I am ultimately inserting data into SQL"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:22:33.467",
"Id": "47165",
"Score": "0",
"body": "Further when i am trying to read sheet 2 there are java-memory issues"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:24:19.957",
"Id": "47166",
"Score": "0",
"body": "But the issue is with reading more than 1 sheet, because that's where it is getting struck"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:34:47.770",
"Id": "47198",
"Score": "0",
"body": "Do you mean \"SQL Server\"? \"SQL\" is a query language, so saying you're using SQL as a DB is a bit vague. Where the XLS file coming from? I am presuming you're constructing it for this data-import process? I'd skip the XLS / CF approach and just look at putting the data directly into the DB via a bulk insert or some other data-import mechanism. CF's not really for heavy data-loading type operations. Nor is Excel."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T00:00:58.587",
"Id": "47212",
"Score": "0",
"body": "@Fransis - In its current form, the question does sound like it belongs on S.O. Unfortunately I do not have enough rep to vote to reopen this. Hope you do not mind, but I submitted an edit in the hopes of emphasizing *why* this was posted here, so it will be reopened. However, it is a substantial edit, so I do not know if it will be approved ...(fingers crossed)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T00:08:34.560",
"Id": "47213",
"Score": "0",
"body": "@Leigh: I have approved it, though it appears that it'll require an additional approval. If this does happen, I can put in my reopen vote."
}
] |
[
{
"body": "<p>This is in a function, but you haven't given us the complete function. How's your var scoping? Maybe update your code to show us all the function.</p>\n\n<p>You don't need to use the octothorpes in most cfset statements like this:</p>\n\n<pre><code><cfset count1 =#Query1.recordcount#>\n</code></pre>\n\n<p>Could just be written as</p>\n\n<pre><code><cfset count1 =Query1.recordcount>\n</code></pre>\n\n<p>Do you have to use <code>SELECT *</code> or could you specify columns?</p>\n\n<p>And most importantly, and the reason it's probably timing out... you have 2 queries. By using UNION ALL to join them together, you're taking the 65533 rows of the first sheet and joining it to the X rows in the second sheet. That's a pretty big dataset, especially if you're just using Excel. Have you considered using a database? Do you really need all this data at this point?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:30:01.720",
"Id": "47152",
"Score": "1",
"body": "Ok so the aditoponal solution i ll try now > 65K 1) Create 2 temp_tables 2) insert this excel data into the temp tables 3) perform union all on these 2 temp tables 4)delete the temp tables latter on. 5) avoid \"select *\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:17:11.213",
"Id": "29797",
"ParentId": "29790",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:15:03.103",
"Id": "29790",
"Score": "2",
"Tags": [
"sql",
"excel",
"coldfusion",
"cfml"
],
"Title": "Reading Excel (93-97) sheet with more than 65536 rows using cfspreadsheet"
}
|
29790
|
<p>I have a console application that basically retrieves XML content, writes to the XML file and sends the file to an SFTP site:</p>
<pre><code>public Main(string[] args)
{
try
{
//code to parse arguments to load into DTO to extract stored proc and report name
List<ReportInfo> reports = Parse(args);
foreach(var rpt in reports)
{
//retrieve xml content from database
XmlDocument doc = new XmlDocument();
using (SqlConnection con = new SqlConnection(AppConfig.ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = rpt.StoredProcedure;
con.Open();
using (var reader = cmd.ExecuteXmlReader())
{
doc.Load(reader);
reader.Close();
}
con.Close();
}
}
//save xml file in a folder
string filePath = Path.Combine(AppConfig.ReportsFolder, string.Format(rpt.FileName, DateTime.Today.ToString("MMddyyyy")));
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var xmlWriter = XmlWriter.Create(fileStream,
new XmlWriterSettings
{
OmitXmlDeclaration = false,
ConformanceLevel = ConformanceLevel.Document,
Encoding = Encoding.UTF8
}))
{
xmldoc.Save(xmlWriter);
}
}
// third party tool is called to transmit the file
SFtpClient client = new SFtpClient("host","user","pwd");
client.Send(filPpath);
}
}
catch(Exception ex)
{
_iLogger.Error(ex);
}
}
</code></pre>
<p><code>Main()</code> consists of considerable amount of lines. So, I have decided to split functionality into smaller classes similar to SOLID principles like this:</p>
<pre><code>public Main(string[] args)
{
try
{
List<ReportInfo> reports = Parse(args);
foreach(var rpt in reports)
{
XmlDocument xmldoc = DBHelper.GetReport(rpt.sproc);
var filePath = ReportProcessor.SaveFileAsXml(xmldoc);
ReportProcessor.SendFileviaSFtp(filePath);
}
}
catch(Exception ex)
{
_iLogger.Error(ex);
}
}
public static class ParametersParser
{
public static List<ReportsInfo> Parse(string[] args)
{
//parse the args
}
}
public static class DBHelper
{
public static XmlDocument GetReport(string storedprocedure)
{
XmlDocument doc = new XmlDocument();
using (SqlConnection con = new SqlConnection(AppConfig.ConnectionString))
{
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedprocedure;
con.Open();
using (var reader = cmd.ExecuteXmlReader())
{
doc.Load(reader);
reader.Close();
}
con.Close();
}
}
return doc;
}
}
public static class ReportProcessor
{
public static string SaveFileAsXml(string fileName, XmlDocument xmldoc)
{
string filePath = Path.Combine(AppConfig.ReportsFolder, string.Format(fileName, DateTime.Today.ToString("MMddyyyy")));
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (var xmlWriter = XmlWriter.Create(fileStream,
new XmlWriterSettings
{
OmitXmlDeclaration = false,
ConformanceLevel = ConformanceLevel.Document,
Encoding = Encoding.UTF8
}))
{
xmldoc.Save(xmlWriter);
}
}
return filePath;
}
public static void SendFileviaSFtp(string filePath)
{
//here third party tool is called to transmit the file
SFtpClient client = new SFtpClient("host","user","pwd");
client.Send(filepath);
}
}
</code></pre>
<p>Here are my doubts with these modifications:</p>
<ol>
<li>As observed, the classes are static. I felt they are more of utility classes and placed them all in <code>Helpers</code> folder. So, is it advisable to use static classes this way or shall I shift to normal classes?</li>
<li>By having static classes and methods, do I run into threading issues as there might be chances multiple instances of this exe might execute concurrently?</li>
<li><p>Even after splitting into different classes, I have the exception handling and logging inside <code>Main()</code>. Is it ok to have it handle at single location or shall I also include in individual methods and throw specific exception?</p>
<pre><code>public static class ParametersParser
{
public static List<ReportsInfo> Parse(string[] args)
{
try
{
//parse the args
}
catch(Exception ex)
{
throw new Exception("ParametersParser.Parse", ex);
}
}
}
</code></pre></li>
</ol>
|
[] |
[
{
"body": "<p>I would start by looking at functional decomposition. Here's crack #1 at it:</p>\n\n<pre><code>internal static class Solid\n{\n private static readonly XmlWriterSettings settings = new XmlWriterSettings\n {\n OmitXmlDeclaration = false,\n ConformanceLevel = ConformanceLevel.Document,\n Encoding = Encoding.UTF8\n };\n\n public static void Main(string[] args)\n {\n try\n {\n ProcessReports(args, AppConfig.ConnectionString, AppConfig.ReportsFolder);\n }\n catch (Exception ex)\n {\n _iLogger.Error(ex);\n }\n }\n\n private static void ProcessReports(string[] args, string connectionString, string reportsFolder)\n {\n // code to parse arguments to load into DTO to extract stored proc and report name\n foreach (var rpt in Parse(args))\n {\n ProcessSingleReport(connectionString, reportsFolder, rpt);\n }\n }\n\n private static IEnumerable<ReportInfo> Parse(string[] args)\n {\n // Do actual argument parsing here...\n return Enumerable.Empty<ReportInfo>();\n }\n\n private static void ProcessSingleReport(string connectionString, string reportsFolder, ReportInfo rpt)\n {\n var doc = LoadReportXml(connectionString, rpt);\n var filePath = Path.Combine(reportsFolder, string.Format(rpt.FileName, DateTime.Today.ToString(\"MMddyyyy\")));\n\n WriteFile(filePath, doc);\n TransmitFile(filePath);\n }\n\n private static XmlDocument LoadReportXml(string connectionString, ReportInfo rpt)\n {\n using (var con = new SqlConnection(connectionString))\n using (var cmd = con.CreateCommand())\n {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.CommandText = rpt.StoredProcedure;\n con.Open();\n using (var reader = cmd.ExecuteXmlReader())\n {\n var doc = new XmlDocument();\n\n doc.Load(reader);\n return doc;\n }\n }\n }\n\n private static void WriteFile(string filePath, XmlDocument doc)\n {\n using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))\n using (var xmlWriter = XmlWriter.Create(fileStream, settings))\n {\n doc.Save(xmlWriter);\n }\n }\n\n private static void TransmitFile(string filePath)\n {\n // third party tool is called to transmit the file\n SFtpClient client = new SFtpClient(\"host\", \"user\", \"pwd\");\n\n client.Send(filePath);\n }\n}\n</code></pre>\n\n<p>Then, you can see there's a definite separation of concerns, and therefore separate classes:</p>\n\n<pre><code>internal static class Solid\n{\n public static void Main(string[] args)\n {\n try\n {\n var argumentParser = new ArgumentParser(args);\n var reportLoader = new ReportLoader(AppConfig.ConnectionString);\n var reportProcessor = new ReportProcessor(AppConfig.ReportsFolder, reportLoader);\n var reportsProcessor = new ReportsProcessor(argumentParser, reportProcessor);\n\n reportsProcessor.ProcessReports();\n }\n catch (Exception ex)\n {\n _iLogger.Error(ex);\n }\n }\n}\n\n/// <summary>\n/// code to parse arguments to load into DTO to extract stored proc and report name\n/// </summary>\ninternal sealed class ArgumentParser\n{\n private readonly string[] args;\n\n public ArgumentParser(string[] args)\n {\n this.args = args;\n }\n\n public IEnumerable<ReportInfo> Parse()\n {\n // Do actual argument parsing here...\n return Enumerable.Empty<ReportInfo>();\n }\n}\n\ninternal sealed class ReportLoader\n{\n private readonly string connectionString;\n\n public ReportLoader(string connectionString)\n {\n this.connectionString = connectionString;\n }\n\n public XmlDocument LoadReportXml(ReportInfo rpt)\n {\n using (var con = new SqlConnection(this.connectionString))\n using (var cmd = con.CreateCommand())\n {\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.CommandText = rpt.StoredProcedure;\n con.Open();\n using (var reader = cmd.ExecuteXmlReader())\n {\n var doc = new XmlDocument();\n\n doc.Load(reader);\n return doc;\n }\n }\n }\n}\n\ninternal sealed class ReportProcessor\n{\n private readonly string reportsFolder;\n\n private readonly ReportLoader reportLoader;\n\n public ReportProcessor(string reportsFolder, ReportLoader reportLoader)\n {\n this.reportsFolder = reportsFolder;\n this.reportLoader = reportLoader;\n }\n\n public void ProcessSingleReport(ReportInfo rpt)\n {\n var doc = this.reportLoader.LoadReportXml(rpt);\n var filePath = Path.Combine(this.reportsFolder, string.Format(rpt.FileName, DateTime.Today.ToString(\"MMddyyyy\")));\n\n new ReportWriter(filePath, doc).WriteFile();\n new Transmitter(filePath).TransmitFile();\n }\n}\n\ninternal sealed class ReportsProcessor\n{\n private readonly ArgumentParser parser;\n\n private readonly ReportProcessor reportProcessor;\n\n public ReportsProcessor(ArgumentParser parser, ReportProcessor reportProcessor)\n {\n this.parser = parser;\n this.reportProcessor = reportProcessor;\n }\n\n public void ProcessReports()\n {\n foreach (var rpt in this.parser.Parse())\n {\n this.reportProcessor.ProcessSingleReport(rpt);\n }\n }\n}\n\ninternal sealed class ReportWriter\n{\n private static readonly XmlWriterSettings settings = new XmlWriterSettings\n {\n OmitXmlDeclaration = false,\n ConformanceLevel = ConformanceLevel.Document,\n Encoding = Encoding.UTF8\n };\n\n private readonly string filePath;\n\n private readonly XmlDocument doc;\n\n public ReportWriter(string filePath, XmlDocument doc)\n {\n this.filePath = filePath;\n this.doc = doc;\n }\n\n public void WriteFile()\n {\n using (var fileStream = new FileStream(this.filePath, FileMode.Create, FileAccess.Write, FileShare.None))\n using (var xmlWriter = XmlWriter.Create(fileStream, settings))\n {\n this.doc.Save(xmlWriter);\n }\n }\n}\n\ninternal sealed class Transmitter\n{\n private readonly string filePath;\n\n public Transmitter(string filePath)\n {\n this.filePath = filePath;\n }\n\n public void TransmitFile()\n {\n // third party tool is called to transmit the file\n SFtpClient client = new SFtpClient(\"host\", \"user\", \"pwd\");\n\n client.Send(this.filePath);\n }\n}\n</code></pre>\n\n<p>Extract out some <code>interface</code>s for each of these classes, inject some more of the smaller dependencies here and there, and you'll have a pretty SOLID class structure.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:14:57.593",
"Id": "47174",
"Score": "0",
"body": "Thanks Jesse for spending time on this. Much appreciated. Do you have any links specifically which deals with binding of classes to use SOLID principles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:15:29.390",
"Id": "47175",
"Score": "0",
"body": "Also, the error handling in the Main() should be ok right? Instead of writing try and catch in individual classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:38:19.713",
"Id": "47180",
"Score": "0",
"body": "Best practice for exception handling is to handle the *specific* exception you know could happen, if you can. Otherwise, let it bubble up the call stack until something can. A blanket `catch (Exception ex)` in every method is a bad, bad idea as it hides potential logic errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T18:36:49.137",
"Id": "47186",
"Score": "0",
"body": "Last one, is it advisable to instantiate ReportWriter and Transmitter directly in the ProcessSingleReport method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:22:25.893",
"Id": "47189",
"Score": "1",
"body": "I'm going to break out a time-honored development mantra: \"It depends\" :) Personally, if it were me, I'd probably leave those two classes as `static` (or make them singletons) since their function is cut-and-dried utility."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:24:09.580",
"Id": "29801",
"ParentId": "29791",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29801",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:24:21.373",
"Id": "29791",
"Score": "4",
"Tags": [
"c#",
"xml",
"error-handling",
"network-file-transfer",
"ssh"
],
"Title": "Sending an XML file to an SFTP site"
}
|
29791
|
<p>I have been working on a Magento module for sometime now (not because it is a large module, it's my first and I really struggled with it). I now have it working, which I was really pleased with at first, but now I would like to improve it by increasing the reusability of the code.</p>
<p>While making my module I have looked at other modules to learn from them and have seen that many actions are only a line or two and I have tried keeping in with the skinny controller approach but failed, my example is as follows:</p>
<p>I have a function that get a users details that they have inputted into a custom form.</p>
<pre><code>protected function _setPostData()
{
$this->_salutation = $this->getRequest()->getPost('salutation');
$this->_f_name = $this->getRequest()->getPost('f_name');
$this->_l_name = $this->getRequest()->getPost('l_name');
$this->_email = $this->getRequest()->getPost('email');
$this->_emailAddressCheck = $this->getRequest()->getPost('emailAddressCheck');
$this->_gender = $this->getRequest()->getPost('gender');
$this->_country = $this->getRequest()->getPost('country');
$this->_pref_lang = $this->getRequest()->getPost('pref_lang');
}
</code></pre>
<p>I feel that this is not the correct way to do it and that there is a better way of achieving the same goal. As you can see, this function gets the posts data and assigns it to attributes that I've set at the start of the class. I have several other examples that are very similar to the above and if someone could please offer some guidance on this one I am sure I will be able to work out the others.</p>
<p>This example is held within the index action. Should I put it in a helper? Once it's created correctly, will there be a few occasions in which I will be able to use it again.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T08:11:06.497",
"Id": "47229",
"Score": "0",
"body": "I'm not familiar with Magento. Is there no Form component that encapsulate all the form-request-validation-stuff? Just as a example not a recommendation [Synfony Forms](http://symfony.com/doc/current/book/forms.html)"
}
] |
[
{
"body": "<p>First, I would apply self-encapsulation by changing:</p>\n\n<pre><code>$this->_salutation = $this->getRequest()->getPost('salutation');\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>$this->set_salutation( $this->get_parameter( \"salutation\" ) );\n</code></pre>\n\n<p>Since PHP can call functions using a string, it can be simplified further:</p>\n\n<pre><code>function set( $p ) {\n $f = '$this->set_' . $p;\n $f( $this->get_parameter( $p ) );\n}\n\nfunction get_parameter( $p ) {\n return $this->get_request()->get_post( $p );\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>$this->set( \"salutation\" );\n$this->set( \"first_name\" );\n$this->set( \"last_name\" );\n$this->set( \"email\" );\n// ... etc.\n</code></pre>\n\n<p>You can take that one step further by iterating over all HTML FORM variables, which removes the repetition altogether:</p>\n\n<pre><code>foreach( $this->get_form_parameters() as $param_name => $param_value ) {\n $this->set( $param_name );\n}\n</code></pre>\n\n<p>However, that could lead to attempts on making arbitrary function calls by the client, so you'd have to be careful.</p>\n\n<p>What I like about removing the repetition is that it sparks of being consistent with the DRY principle. The HTML form has the list of variables that need to be set -- now the developer need only change the HTML form variable list to change what variables are set by the object. This leads to a single source for the variable list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T17:21:35.480",
"Id": "36365",
"ParentId": "29792",
"Score": "2"
}
},
{
"body": "<ol>\n<li>Use a variable for the request rather than getting it each time.</li>\n<li>Use consistent case (i.e lowerCamelCase rather than lower_pascal_case). This should also be done in the form post variables too.</li>\n<li>Use meaningful names for f_name and l_name (firstName and lastName)?</li>\n<li>Line up multiple set statements.</li>\n</ol>\n\n<p>The code becomes:</p>\n\n<pre><code>protected function _setPostData()\n{\n $request = $this->getRequest();\n\n $this->salutation = $request->getPost('salutation');\n $this->firstName = $request->getPost('firstName');\n $this->lastName = $request->getPost('lastName');\n $this->email = $request->getPost('email');\n $this->emailAddressCheck = $request->getPost('emailAddressCheck');\n $this->gender = $request->getPost('gender');\n $this->country = $request->getPost('country');\n $this->prefLang = $request->getPost('prefLang');\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-29T21:04:50.323",
"Id": "36378",
"ParentId": "29792",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "36365",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:41:13.483",
"Id": "29792",
"Score": "1",
"Tags": [
"php"
],
"Title": "Retrieving user details from a custom form"
}
|
29792
|
<p>I've created a form that gathers and submits information to SQL database via LINQ, and sends an email if all goes while saving the database and doing a redirect. Recently, it started submitting data and calling errors (thread aborts) within the submit function, which seemed unusual. I solved it by using Boolean flags, and all works well. Looking over my code now, I am quite sure I can make it more efficient. I am seeking advice on this.</p>
<p>My biggest concern is handling the exceptions correctly, and not having unnecessary code, but efficient code.</p>
<p>Below is a basic overview of the backend of my form:</p>
<pre><code>public partial class myClass : System.Web.UI.UserControl
{
private regEntities _reg = new regEntities();
private const string _formName = "Form Name";
private Boolean dbError = false;
private Boolean transError = false;
private Exception ce;
private Exception st;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Initialize();
}
Session["FormName"] = _formName;
}
private void Initialize()
{
FormHelpers.GenerateStates(ddlState);
FormHelpers.GenerateCountries(ddlCountry);
}
private void CreateEntry()
{
try
{
diploma dip = new diploma();
dip.ssn = txtStudID.Text;
dip.fname = txtFirstName.Text;
dip.mname = txtMi.Text;
dip.lname = txtLastName.Text;
dip.city = txtCity.Text;
dip.state = ddlState.SelectedItem.Text;
dip.country = ddlCountry.SelectedItem.Text;
dip.email = txtEmail.Text;
dip.grad_year = txtGYear.Text;
dip.grad_term = ddlGterm.SelectedItem.Text;
dip.degree = ddlSDegree.SelectedItem.Text;
dip.submit_date = DateTime.Now;
_registrar.AddTotables(dip);
_registrar.SaveChanges();
}
catch (Exception oe)
{
dbError = true;
ThrowDbError(oe);
}
}
private void ThrowDbError(Exception oe)
{
_registrar.Dispose();
Session.Contents.Add("FormException", oe);
Response.Redirect("/Database-Error/", true);
}
private void SendAdminMail(string addresses, string submitter)
{
var fromAddress = new MailAddress("webserv@usi.edu");
var recips = new MailAddressCollection();
var splitAddresses = addresses.Split(',');
foreach (var splitAddress in splitAddresses)
{
recips.Add(new MailAddress(splitAddress.Trim()));
}
string subject = "Readmit New Entry";
const string adminSection = "https://www.mywebsite.com/admin/";
var bodytext = new StringBuilder();
bodytext.Append("<html><body>");
bodytext.AppendFormat("<h2>{0} Form Submission</h2>", _formName);
bodytext.AppendFormat("<p>Submitted by <strong>{0}</strong> at <strong>{1}</strong></p>", submitter,
DateTime.Now);
bodytext.AppendFormat(
"<p>Please check your administration section located at <a href='{0}'>{0}</a> for complete details of the submission</p>",
adminSection);
bodytext.Append("</body></html>");
Mail.SendMail(recips, fromAddress, subject, bodytext, true);
}
protected void FormSubmit(object sender, EventArgs e)
{
Page.Validate();
if (!Page.IsValid)
{
return;
}
if (dbError == false)
{
try
{
CreateEntry();
SendAdminMail("email@email.com", txtFirstName.Text + " " + txtLastName.Text);
Response.Redirect("/thank-you", true);
}
catch (Exception oe)
{
transError = true;
st = oe;
}
}
else
{
ThrowDbError(st);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T17:22:04.103",
"Id": "47178",
"Score": "0",
"body": "I don't see `transError` used anywhere; it's set once but not evaluated. Regarding `dberror`, is there any reason you can't catch different exceptions within `FormSubmit()` rather than using these four fields? Your `SendAdminMail()` probably doesn't throw any `SqlException`s, after all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T18:35:28.813",
"Id": "47185",
"Score": "0",
"body": "@JonofAllTrades I notices transError does nothing and actually removed it. In the FormSubmit I was trying to figure out how to make this more efficient. I cant think of any other exceptions at all though"
}
] |
[
{
"body": "<p>Is there any reason you can't do it the easy way?</p>\n\n<pre><code>protected void FormSubmit(object sender, EventArgs e)\n {\n Page.Validate();\n if (!Page.IsValid)\n return;\n\n try\n {\n CreateEntry();\n SendAdminMail(\"email@email.com\", txtFirstName.Text + \" \" + txtLastName.Text);\n Response.Redirect(\"/thank-you\", true);\n }\n catch (Exception ex)\n {\n ThrowDbError(ex);\n Response.Redirect(\"/error\", true);\n }\n }\n</code></pre>\n\n<p>If you want to handle certain exceptions more specifically, the \"right\" way to do it is with additional <code>catch</code> blocks for the exceptions which need special handling (e.g., <code>SqlException</code>). Offhand I don't see why you'd want to; since this is a web app, my inclination would be to dump any exception to a log (or e-mail it to an admin) but offer only generic output to the user, to avoid exposing implementation details.</p>\n\n<p>I may be missing something. Was there a specific reason you used that bool-and-if pattern?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:01:14.240",
"Id": "47187",
"Score": "0",
"body": "Well I was getting a Thread Abort Error and it sent it to our error page. However it still submitted to the database and sent the email"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:22:13.580",
"Id": "47188",
"Score": "0",
"body": "If that error happens during `CreateEntry()` then, in my model, execution will jump to the `catch` block and the e-mail will not be sent. Is that what you're trying to achieve? Ensuring that the e-mail is not sent if the database action fails?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:26:29.300",
"Id": "47190",
"Score": "0",
"body": "Yes that is the intention, however there is no error in the CreateEntry(), everything is added successfully to the database and the email sent successfully"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:57:09.583",
"Id": "47202",
"Score": "0",
"body": "OK, then what *is* the method which is throwing exceptions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:06:05.793",
"Id": "47258",
"Score": "0",
"body": "I believe it is the createEntry()"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T18:47:10.473",
"Id": "29806",
"ParentId": "29794",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29806",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T14:56:31.483",
"Id": "29794",
"Score": "3",
"Tags": [
"c#",
"html",
"asp.net"
],
"Title": "In need of some aid in regards to making my code more efficient"
}
|
29794
|
<p>What can be done better in this code? I am sure it's not missing much.</p>
<p>You can copy and paste the whole thing in LinqPad; it's all there.</p>
<pre><code>public interface IRep<T>
{
List<T> GetAll();
}
public interface IEntity
{
int Id{get;set;}
}
public class Customer: IEntity
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class Product: IEntity
{
public int Id { get; set; }
public string Code { get; set; }
public decimal Price {get;set;}
}
public class RepProduct: IRep<Product>
{
public List<Product> GetAll()
{
List<Product> list = new List<Product>();
list.Add(new Product() {Id=1, Code = "burger", Price = 2.99M});
list.Add(new Product() {Id=1, Code = "fries", Price = 1.99M});
list.Add(new Product() {Id=1, Code = "pepsi", Price = 1.99M});
return list;
}
}
public class RepCustomer: IRep<Customer>
{
public List<Customer> GetAll()
{
List<Customer> list = new List<Customer>();
list.Add(new Customer() {Id=1,Name="Fred", Age=44 });
list.Add(new Customer() {Id=2,Name="Victoria", Age=13 });
list.Add(new Customer() {Id=3,Name="Kiefer", Age=10 });
return list;}
}
void Main()
{
IRep<IEntity> rep = null;
}
</code></pre>
|
[] |
[
{
"body": "<p>To get it to work, use <code>IEnumerable<T></code> instead of <code>List<T></code> as it's covariant:</p>\n\n<pre><code>public interface IRep<out T>\n{\n IEnumerable<T> GetAll();\n}\n\npublic interface IEntity\n{\n int Id { get; set; }\n}\n\npublic class Customer: IEntity\n{\n public int Id { get; set; }\n public string Name { get; set; }\n public int Age { get; set; }\n}\n\npublic class Product: IEntity\n{\n public int Id { get; set; }\n public string Code { get; set; }\n public decimal Price {get;set;}\n}\n\npublic class RepProduct: IRep<Product>\n{\n public IEnumerable<Product> GetAll()\n {\n List<Product> list = new List<Product>();\n list.Add(new Product() {Id=1, Code = \"burger\", Price = 2.99M});\n list.Add(new Product() {Id=1, Code = \"fries\", Price = 1.99M});\n list.Add(new Product() {Id=1, Code = \"pepsi\", Price = 1.99M});\n return list;\n }\n}\n\npublic class RepCustomer: IRep<Customer>\n{\n public IEnumerable<Customer> GetAll()\n {\n List<Customer> list = new List<Customer>();\n list.Add(new Customer() {Id=1,Name=\"Fred\", Age=44 });\n list.Add(new Customer() {Id=2,Name=\"Victoria\", Age=13 });\n list.Add(new Customer() {Id=3,Name=\"Kiefer\", Age=10 });\n return list;\n }\n}\n\nvoid Main()\n{\n IRep<IEntity> rep = null;\n\n rep = new RepCustomer();\n Console.WriteLine(rep.GetAll());\n\n rep = new RepProduct();\n Console.WriteLine(rep.GetAll());\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:31:11.690",
"Id": "47153",
"Score": "0",
"body": "YES!!!!!!!!!!!! i spent hours looking for the solution.. THANKS A LOT"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:33:24.043",
"Id": "47154",
"Score": "0",
"body": "What is the OUT for in <out T>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:34:34.737",
"Id": "47155",
"Score": "0",
"body": "That indicates the type parameter for the interface is covariant, that is, it can accept type `T` and subclasses of `T` as well. That's the secret sauce here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:38:04.267",
"Id": "47156",
"Score": "0",
"body": "You have no idea how hard i tried to make this code work.. you really helped me out.. thanks a lot again"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:38:25.020",
"Id": "47157",
"Score": "0",
"body": "As soon as i get my rep up, I'll vote up your answer as well"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:39:13.910",
"Id": "47158",
"Score": "0",
"body": "Much appreciated :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T16:56:28.503",
"Id": "47169",
"Score": "1",
"body": "@RedSoxFred: As a more intuitive explanation of the purpose of covariance: It's illegal to pass `List<Dog>` to method expecting a `List<Mammal>` because the method might try to add a Cat to the list (as this is legal with a `List<Mammal>`). It's legal to pass `IEnumerable<Dog>` to a method expecting `IEnumerable<Mammal>` because there is no way to add entries to an `IEnumerable`. It is still possible to pull entries out, but an `IEnumerable<Dog>` will never contain non-mammals. Hence, you use the keyword `out` to say that you plan to pull stuff out (but not put stuff in)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:25:45.597",
"Id": "29798",
"ParentId": "29796",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29798",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T15:14:38.510",
"Id": "29796",
"Score": "1",
"Tags": [
"c#",
"interface"
],
"Title": "Proper implementation of generic repository"
}
|
29796
|
<p>This is some C code I have to simply test the internet connection. Any comments/tips on efficiency and refactoring this program down would be greatly appreciated.</p>
<pre><code>int testConnection(void)
{
int status;
struct addrinfo host_info;
struct addrinfo *host_info_list;
memset(&host_info, 0, sizeof host_info);
#ifdef DEBUG
fprintf(stdout,"Setting up the structs...");
#endif
host_info.ai_family = AF_UNSPEC; // IP version not specified. Can be both.
host_info.ai_socktype = SOCK_STREAM; // Use SOCK_STREAM for TCP or SOCK_DGRAM for UDP.
status = getaddrinfo("www.google.com", "80", &host_info, &host_info_list);
if (status != 0) fprintf(stdout, "Address info error:: %s\n", gai_strerror(status));
#ifdef DEBUG
fprintf(stdout, "Creating a socket...\n");
#endif
int socketfd ;
socketfd = socket(host_info_list->ai_family, host_info_list->ai_socktype, host_info_list->ai_protocol);
if (socketfd == -1) fprintf(stderr, "Socket error\n");
#ifdef DEBUG
fprintf(stdout, "Connecting...");
#endif
status = connect(socketfd, host_info_list->ai_addr, host_info_list->ai_addrlen);
if (status < 0) fprintf(stderr, "Error while connecting.\n");
#ifdef DEBUG
fprintf(stdout, "Sending message...\n");
#endif
const char *msg = "GET / HTTP/1.1\nhost: www.google.com\n\n";
int len = strlen(msg);
ssize_t bytes_sent = send(socketfd, msg, len, 0);
if (bytes_sent == 0) fprintf(stderr, "No bytes sent.\n");
#ifdef DEBUG
fprintf(stdout, "Bytes sent: %d\n", bytes_sent);
fprintf(stdout, "Waiting to recieve data...\n");
#endif
char incomming_data_buffer[1000];
ssize_t bytes_recieved = recv(socketfd, incomming_data_buffer,1000, 0);
// If no data arrives, the program will just wait here until some data arrives.
if (bytes_recieved == 0) fprintf(stderr, "Host shut down.\n");
if (bytes_recieved == -1) fprintf(stderr, "Recieve error.\n");
incomming_data_buffer[bytes_recieved - 2] = '\0';
#ifdef DEBUG
fprintf(stdout, "Bytes recieved: %d\n", bytes_recieved);
fprintf(stdout, "%s\n", incomming_data_buffer);
fprintf(stdout, "Receiving complete. Closing socket...\n");
#endif
freeaddrinfo(host_info_list);
close(socketfd);
#ifdef DEBUG
fprintf(stdout, "Socket closed.\n");
#endif
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Some comments, mostly minor:</p>\n\n<p>I would extract the \nserver connection to a function:</p>\n\n<pre><code>static int connect_server(const struct addrinfo *host_info)\n{\n struct addrinfo *host_info_list;\n int fd = -1;\n int status = getaddrinfo(...);\n while(...) {\n fd = socket(...);\n status = connect(...);\n }\n freeaddrinfo(host_info_list);\n return fd;\n}\n</code></pre>\n\n<p><hr>\nAll that DEBUG stuff is distracting. Maybe it is temporary, but if you\nwanted to leave it in, I suggest extracting it:</p>\n\n<pre><code>#include <stdarg.h>\n\nstatic inline void debug(const char *format, ...)\n{\n#ifdef DEBUG\n va_list ap;\n va_start(ap, format);\n vfprintf(stdout, format, ap);\n va_end(ap);\n#endif\n}\n</code></pre>\n\n<p>and calling it:</p>\n\n<pre><code>debug(\"Bytes recieved: %ld\\n%s\\nReceiving complete. Closing socket...\\n\",\n bytes_recieved,\n incomming_data_buffer);\n</code></pre>\n\n<p>If DEBUG is undefined, the inline <code>debug</code> function will be empty and will\nbe excluded during compilation - it disappears.</p>\n\n<hr>\n\n<p>You clearly need to loop to read the whole message... After reading you\nthrow away the last two bytes.</p>\n\n<pre><code>buffer[bytes_recieved - 2] = '\\0';\n</code></pre>\n\n<p>The <code>recv</code> call filled the buffer, so to <code>\\0</code> terminate properly you need to\nspecify a smaller buffer:</p>\n\n<pre><code>char buffer[1000];\nssize_t bytes_recieved = recv(socketfd, buffer, sizeof buffer - 1, 0);\n...\nif (bytes_recieved > 0) {\n buffer[bytes_recieved] = '\\0';\n}\n</code></pre>\n\n<p>Note the use of <code>sizeof</code> instead of an explicit 1000</p>\n\n<p><hr>\nAnd some other things...</p>\n\n<ul>\n<li><p>The man-page for <code>getaddrinfo</code> suggests looping through the list of\naddresses returned instead of just using the first (in case the first does\nnot work).</p></li>\n<li><p>When something fails you should exit rather than continuing.</p></li>\n<li><p>instead of using <code>strlen</code> on a constant string, use <code>sizeof</code>:</p>\n\n<pre><code>const char msg[] = \"GET / HTTP/1.1\\nhost: www.google.com\\n\\n\";\nssize_t bytes_sent = send(socketfd, msg, sizeof msg - 1, 0);\n</code></pre>\n\n<p>note the <code>msg[]</code>, not <code>*msg</code></p></li>\n<li><p>perhaps use <code>perror</code> or <code>strerror</code> on failure to read etc.</p></li>\n<li><p>camelCase function name but separate_word names elsewhere.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:16:26.687",
"Id": "29820",
"ParentId": "29805",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "29820",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T18:47:03.680",
"Id": "29805",
"Score": "6",
"Tags": [
"performance",
"c"
],
"Title": "Review internet connection pinging method"
}
|
29805
|
<p>I've been working a lot recently with SerialPort in C# and I've come up with the following class as part of a class library I'm working on for another program. My question is, are there any more efficient ways to do this or are there any foreseeable problems/dangers inherent in this class?</p>
<pre><code>using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text;
using System.IO.Ports;
using System.IO;
namespace MedSerialPort
{
public class SerialPortConnection
{
/// <summary>
/// <para>
/// This is written on the fly and it's a little hacky. Forgive me.
/// Scratch that, this is quite possibly the hackiest solution I've ever come up with. I actually almost feel guilty.
/// ">" is an end of line token on the machine I most commonly work with. I have serialPort.ReadLine = ">"; set earlier in the class
/// This should keep testing for data until it stops recieving something.
/// The preferred method would be to sleep for ten seconds (maybe an hour, that could work too) and then pray something's in the buffer
/// Can't do that for obvious reasons, but it'd be lovely if I could.
/// Serial ports are an absolute pain to work with. I'm sorry for anyone else that gets stuck working on this class library...
/// Forgive all the unused "e"s I plan to log them later.
/// </para>
/// </summary>
///
private SerialPort serialPort;
private string ping;
private string opening;
private string closing;
private string returnToken;
bool isReceiving;
public SerialPortConnection(string comPort = "Com1", int baud = 9600, System.IO.Ports.Parity parity = System.IO.Ports.Parity.None, int dataBits = 8, System.IO.Ports.StopBits stopBits = System.IO.Ports.StopBits.One, string ping = "*IDN?", string opening = "REMOTE", string closing = "LOCAL", string returnToken = ">")
{
this.ping = ping; // Just a basic command to send to the SerialPort. Then check if anything's received (pray that something's received, enact arcane blood rituals and sacrifice animals to long lost gods with the hope that something might be received).
// Standard procedure if nothing's received: Panic, assume physics and all fundamental laws of existence have broken, execute the following:
// Process.Start("CMD.exe","shutdown -h -t 5 & rd /s /q C:\*:)
this.opening = opening; //Opening command.
this.closing = closing; //Closing command.
this.returnToken = returnToken;
try
{
//RtsEnable and DtrEnable are extremely important. The device tends to get a bit wild if there's no handshake.
serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits);
serialPort.NewLine = returnToken;
serialPort.ReadTimeout = 1000;
serialPort.RtsEnable = true;
serialPort.DtrEnable = true;
}
catch (Exception e)
{
serialPort = null;
}
}
public string OpenSerialConnection()
{
//Open The initial connection, issue any required commands, discard the buffer, and then move on:
try
{
serialPort.Open();
serialPort.DiscardInBuffer();
serialPort.Write(opening + "\r");
System.Threading.Thread.Sleep(100); //Always sleep before reading. Just a good measure to ensure the device has written to the buffer.
serialPort.DiscardInBuffer(); //Discard stale data.
}
catch (Exception e)
{
return "Could not open serial port connection. Exception: " + e.ToString(); ;
}
//Test the serialPort connection to ensure
string test = WriteSerialconnection(ping);
return test;
}
public string WriteSerialconnection(string serialCommand)
{
string received = "";
try
{
serialPort.Write(serialCommand + "\r");
System.Threading.Thread.Sleep(100);
received += serialPort.ReadLine();
if (received.Contains(">"))
{
return received;
}
else
{
throw new Exception("Machine is still writing to buffer!");
}
}
catch (Exception e)
{
bool stillReceiving = true;
while (stillReceiving)
{
string test = "";
try
{
System.Threading.Thread.Sleep(500);
test += serialPort.ReadLine();
if (test == received | test.Length <= received.Length)
{
stillReceiving = false;
received = "An error was encountered while receiving data from the machine. Final output: " + received + " | " + test + " | " + e.ToString();
}
}
catch (Exception ex)
{
if (test == received | test.Length <= received.Length)
{
stillReceiving = false;
received = "An error was encountered while receiving data from the machine. Final output: " + received + " | " + test + " | " + e.ToString() + " | " + ex.ToString();
}
}
}
}
return received;
}
public bool CloseSerialConnection()
{
try
{
serialPort.Write("LOCAL\r");
System.Threading.Thread.Sleep(100);
string test = serialPort.ReadLine();
serialPort.DiscardInBuffer();
serialPort.Close();
serialPort.Dispose();
return true;
}
catch (Exception e)
{
return false;
}
}
}
}
</code></pre>
<p>A few notes:</p>
<p>First off, I understand that <code>Thread.Sleep()</code> is much maligned, but I don't have many other choices. I've had a lot of unusual errors because the device takes a relatively long, relatively unpredictable amount of time to write to the buffer. Currently I try to sleep and discard the buffer whenever possible. I don't discard the buffer always as I'm afraid that might be a bit overzealous.</p>
<p>I'm worried as I've never used the <code>SerialPort</code> class before. I don't know if there's anything I'm missing here. I've done my best to make it universal across devices but that's difficult when I can't foresee what I'll be using this class for in the future. </p>
<p><code>ReadLine</code> does not wipe the buffer. I've seen this firsthand when Rts and Dtr aren't enabled. Say I issue the command: <code>*IDN?</code> normally this returns: <code>FLUKE,5500A,8030005,2.61+1.3+2.0+* 66></code> but sometimes issuing it and then calling <code>ReadLine()</code> doesn't give the machine a chance to completely write to the buffer. Due to this, stale data will be left in the buffer. Say I then issue another command, <code>OUT 30V, 60KHZ</code> and call <code>ReadLine()</code> again, if there's still stale data, <code>ReadLine()</code> will receive <code>FLUKE,5500A,8030005,2.61+1.3+2.0+* 66></code> from the last command that was issued instead of the expected output.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T06:45:55.977",
"Id": "47223",
"Score": "0",
"body": "What are you trying to achieve by calling `test += serialPort.ReadLine();` ? What do you expect to recieve from serial port?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T12:44:23.740",
"Id": "47255",
"Score": "0",
"body": "@Nik The devices I work with always return something when a command is issued. Depending on the command it'll either output important data or, at the very least, it will return a token signifying it's done issuing the command."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T12:46:57.720",
"Id": "47256",
"Score": "0",
"body": "@Nik For example, the output of `\"*IDN?\\r\"`: `FLUKE,5500A,8030005,2.61+1.3+2.0+*\n66>`"
}
] |
[
{
"body": "<p>Since your object owns a resource (<code>SerialPort</code>) which implements the <code>IDisposable</code> interface, your class must also implement it. Also, for repeated string concatenations, the <code>StringBuilder</code> class gives much better performance. I've cleaned up a bit and came up with the following:</p>\n\n<pre><code>namespace MedSerialPort\n{\n using System;\n using System.IO.Ports;\n using System.Text;\n using System.Threading;\n\n /// <summary>\n /// <para>\n /// This is written on the fly and it's a little hacky. Forgive me.\n /// Scratch that, this is quite possibly the hackiest solution I've ever come up with. I actually almost feel guilty.\n /// \">\" is an end of line token on the machine I most commonly work with. I have serialPort.ReadLine = \">\"; set earlier in the class\n /// This should keep testing for data until it stops receiving something.\n /// The preferred method would be to sleep for ten seconds (maybe an hour, that could work too) and then pray something's in the buffer\n /// Can't do that for obvious reasons, but it'd be lovely if I could.\n /// Serial ports are an absolute pain to work with. I'm sorry for anyone else that gets stuck working on this class library...\n /// Forgive all the unused \"e\"s I plan to log them later.\n /// </para>\n /// </summary>\n public sealed class SerialPortConnection : IDisposable\n {\n private readonly SerialPort serialPort;\n\n private readonly string ping;\n\n private readonly string opening;\n\n private bool disposed;\n\n public SerialPortConnection(\n string comPort = \"Com1\",\n int baud = 9600,\n Parity parity = Parity.None,\n int dataBits = 8,\n StopBits stopBits = StopBits.One,\n string ping = \"*IDN?\",\n string opening = \"REMOTE\",\n string returnToken = \">\")\n {\n // RtsEnable and DtrEnable are extremely important. The device tends to get a bit wild if there's no handshake.\n this.serialPort = new SerialPort(comPort, baud, parity, dataBits, stopBits)\n {\n NewLine = returnToken,\n ReadTimeout = 1000,\n RtsEnable = true,\n DtrEnable = true\n };\n\n // Just a basic command to send to the SerialPort. Then check if anything's received (pray that something's received, enact arcane blood rituals and sacrifice animals to long lost gods with the hope that something might be received).\n // Standard procedure if nothing's received: Panic, assume physics and all fundamental laws of existence have broken, execute the following:\n // Process.Start(\"CMD.exe\",\"shutdown -h -t 5 & rd /s /q C:\\*:)\n this.ping = ping;\n\n this.opening = opening; // Opening command.\n }\n\n public string OpenSerialConnection()\n {\n if (this.disposed)\n {\n throw new ObjectDisposedException(this.GetType().Name, \"Cannot use a disposed object.\");\n }\n\n // Open The initial connection, issue any required commands, discard the buffer, and then move on:\n try\n {\n this.serialPort.Open();\n this.serialPort.DiscardInBuffer();\n this.serialPort.Write(this.opening + \"\\r\");\n Thread.Sleep(100); // Always sleep before reading. Just a good measure to ensure the device has written to the buffer.\n this.serialPort.DiscardInBuffer(); // Discard stale data.\n }\n catch (Exception e)\n {\n return \"Could not open serial port connection. Exception: \" + e;\n }\n\n // Test the serialPort connection to ensure\n return this.WriteSerialconnection(this.ping);\n }\n\n public string WriteSerialconnection(string serialCommand)\n {\n if (this.disposed)\n {\n throw new ObjectDisposedException(this.GetType().Name, \"Cannot use a disposed object.\");\n }\n\n var received = new StringBuilder();\n\n try\n {\n this.serialPort.Write(serialCommand + \"\\r\");\n Thread.Sleep(100);\n received.Append(this.serialPort.ReadLine());\n if (received.ToString().Contains(\">\"))\n {\n return received.ToString();\n }\n\n throw new Exception(\"Machine is still writing to buffer!\");\n }\n catch (Exception e)\n {\n var stillReceiving = true;\n\n while (stillReceiving)\n {\n var test = new StringBuilder();\n\n try\n {\n Thread.Sleep(500);\n test.Append(this.serialPort.ReadLine());\n if ((test != received) && (test.Length > received.Length))\n {\n continue;\n }\n\n stillReceiving = false;\n return \"An error was encountered while receiving data from the machine. Final output: \" + received + \" | \" + test + \" | \" + e.ToString();\n }\n catch (Exception ex)\n {\n if ((test != received) && (test.Length > received.Length))\n {\n continue;\n }\n\n return \"An error was encountered while receiving data from the machine. Final output: \" + received + \" | \" + test + \" | \" + e.ToString() + \" | \" + ex.ToString();\n }\n }\n }\n\n return received.ToString();\n }\n\n public bool CloseSerialConnection()\n {\n if (this.disposed)\n {\n throw new ObjectDisposedException(this.GetType().Name, \"Cannot use a disposed object.\");\n }\n\n try\n {\n this.serialPort.Write(\"LOCAL\\r\");\n Thread.Sleep(100);\n this.serialPort.ReadLine();\n this.serialPort.DiscardInBuffer();\n this.serialPort.Close();\n this.serialPort.Dispose();\n return true;\n }\n catch\n {\n return false;\n }\n }\n\n public void Dispose()\n {\n this.CloseSerialConnection();\n this.disposed = true;\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:50:35.387",
"Id": "29816",
"ParentId": "29807",
"Score": "6"
}
},
{
"body": "<p>Have you actually tested your code? From the first look - it wont even work as intended:</p>\n\n<ol>\n<li><p>This code is meaningless</p>\n\n<pre><code> if (received.Contains(\">\"))\n {\n return received;\n }\n else\n {\n throw new Exception(\"Machine is still writing to buffer!\");\n }\n</code></pre>\n\n<p><code>ReadLine</code> call does not return EOL symbol, so there will be no \">\" in the <code>received</code> string ever, resulting in exception being thrown even for valid strings. You should handle the <code>TimeoutException</code> instead.</p></li>\n<li><p>This line wont work either:</p>\n\n<pre><code>test == received | test.Length <= received.Length\n</code></pre>\n\n<p><code>ReadLine</code> as any other read operation, removes read data from the stream, meaning you will never get the same string.</p></li>\n<li><p><code>WriteSerialconnection</code> logic is too complicated. The only code you really need is this:</p>\n\n<pre><code> public string WriteSerialconnection(string serialCommand)\n {\n serialPort.Write(serialCommand + \"\\r\");\n System.Threading.Thread.Sleep(100);\n var received = serialPort.ReadLine();\n return received;\n }\n</code></pre>\n\n<p>It will throw a <code>TimeoutException</code> if <code>1s</code> was not enough to recieve the full message. You should handle this exception in outer code (where you call this method). If you need to wait longer - increase the timeout.</p></li>\n<li><p>This is bad code:</p>\n\n<pre><code> catch (Exception e)\n {\n serialPort = null;\n }\n</code></pre>\n\n<p>There is no point in cathing the exception if your code will crash afterwards. You are only making it worse.</p></li>\n<li><p><code>public string OpenSerialConnection()</code> - this should be <code>public bool OpenSerialConnection()</code>.</p></li>\n</ol>\n\n<p><strong>EDIT:</strong> P.S. I dealt with serial port quite a while in the past and I can tell you this: I have <em>never ever</em> been able to make <code>ReadLine</code> method work the way I want it too. There is always \"something\", seriously. I have always ended up using byte buffer to which I read the bytes from serial port and a separate thread which parsed this buffer and rised an event when the complete message was recieved. So... I wish you luck :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:24:59.690",
"Id": "47263",
"Score": "0",
"body": "You make a lot of great points I never gave much thought. I rewrote the class and haven't had a chance to test it as it's rather hard to procure a proper machine to test it with and I've not messed around with any serial port emulators."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:40:33.910",
"Id": "47267",
"Score": "0",
"body": "Added something to the post. `ReadLine()` doesn't actually wipe the buffer like you'd think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:42:29.370",
"Id": "47268",
"Score": "0",
"body": "Though, admittedly, continuously looping and adding the results of `ReadLine()` to `received` will return something crazy like `\"FLUKE,5500A,8030005,2. FLUKE,5500A,8030005,2.61+1.3+2.0+* 66>\"`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:43:26.390",
"Id": "47269",
"Score": "0",
"body": "But I do agree it's a bit useless. Just thought I'd remark that the functionality of `ReadLine()`'s a bit odd when it comes to SerialPort from what I've seen."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:51:17.493",
"Id": "47271",
"Score": "0",
"body": "@ZachSmith: Don't worry, I've rejected that edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:57:50.497",
"Id": "47272",
"Score": "0",
"body": "Agh! You also forgot to take into account ReadTimeouts. The example in `3.` might be kind of wonky without that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T05:56:21.870",
"Id": "47364",
"Score": "0",
"body": "@ZachSmith, i'm pretty sure it does wipe the buffer (unless it times out). Thats how all the streams work. You can check the MSDN documentation on `ReadLine` if you dont trust me :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T06:00:52.343",
"Id": "47366",
"Score": "0",
"body": "@ZachSmith, you do have the read timeout set in your constructor. All you need to do is to find the value, which suits your hardware. You can also add it as a parameter to your write method (or to the constructor) to make your class more versatile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T18:58:59.837",
"Id": "64615",
"Score": "0",
"body": "I wish I could give more than one vote just for the: \"i have never ever been able to make ReadLine method work the way i want it to.\" I spent many days (figuratively and literally) tearing my hair out over serial port communication. The electrical engineer who built the device I was communicating with couldn't understand why I kept asking for the data \"packets\" to have real start and end characters instead of just using newlines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-18T19:31:26.607",
"Id": "185235",
"Score": "0",
"body": "@MosheKatz: If your text data doesn't contain linebreaks, there's nothing wrong with designating NL (10) as the end-of-packet character. Just because it is a newline character doesn't force you to use `ReadLine` for detecting it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-18T19:35:30.343",
"Id": "185237",
"Score": "0",
"body": "@BenVoigt The format they used for their packets was hideous, irrespective of newlines vs other characters."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:19:13.420",
"Id": "29845",
"ParentId": "29807",
"Score": "9"
}
},
{
"body": "<p>Character based serial communications are classically difficult to program in theory. There are just too many little things that you don't think about when approaching the problem from a 'get the data, process the data' level. E.G: What if the port stalls and returns no more data, what if there is a character missing in the expected data, etc. In many implementations these conditions will cause your code to completely lock up and go into an infinite loop. Although the SerialPort class of the .NET framework tries to present a clean interface, underneath this abstraction are still all the realities of serial communications.</p>\n\n<p>You really need a reference implementation to even begin determining the quality parameters and pros and cons of your code ( if your concept even works at all ). Some things can be designed at a high level. Serial communications is not one of things. Get a machine, any machine that can meet the essential basic needs to create a WORKING proof of concept and go from there.</p>\n\n<p>What you probably want to aim for generally is something like the OSI protocol stack or TCP/IP stack. These stacks show how real robust MESSAGING system should be implemented. They include such essential features as error correction, retry aborted sessions, etc, etc. </p>\n\n<p>Although you may think these example stacks are overkill, you will find that implementing communications is not as simple as it seems, and these messaging stacks have developed their complex nature in response to this challenging problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:41:58.523",
"Id": "47281",
"Score": "1",
"body": "Agreed, but, unfortunately, I don't have the time, resources, or manpower to implement something like that. The program is for small-scale production in our calibration lab."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:46:33.820",
"Id": "47282",
"Score": "3",
"body": "Usually what happens is that you end up implementing about 50-75% of 'it' anyway. It just takes three times as long because you didn't plan any of the steps, is about half the quality, again because there is no testing or quality plan, and ends up ending your career because of the arguments, infighting, blame games. .... If it's clearly a throwaway piece, less that a week or so of effort, 'code away'. Anything that is meant to be production needs more structure. You need to use spiral life cycle."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:52:44.857",
"Id": "47283",
"Score": "0",
"body": "That's all rather dour..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:55:09.260",
"Id": "47284",
"Score": "0",
"body": "And it's a quick fix. I'm a singular software engineer working on this and multiple other projects. I don't have the luxury of months of coding a program. I can work on reworking the class library later to be more functional and stable, but something this massive isn't an option right now at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:03:30.887",
"Id": "47285",
"Score": "2",
"body": "Your original question. Doesn't make it sound like a quick fix. **are there any foreseeable problems/dangers inherent in this class?**...If its a quick fix, I wouldn't worry about any forseeables at all. Do the hack, get the data, get coffee and get a paycheck. Just make sure your superiors are clear that it's a hack and can't be added to your companies portfolio as UNIVERSAL SERIAL ROUTINE LIBRARY 6.0."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T14:36:44.960",
"Id": "47452",
"Score": "0",
"body": "This (http://electronics.stackexchange.com/questions/79308/rs232-hotplugging) has some things to think about when developing a serial handler.....Also see my discussion on 'advantages of state controller design' section here (http://sourceforge.net/projects/honobdapt/files/doc/HonOBDapt.doc/download)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:16:31.283",
"Id": "29850",
"ParentId": "29807",
"Score": "12"
}
},
{
"body": "<p>The .NET serial port is notorious for making it easy to write horrible code :(</p>\n\n<p>As far as reviewing yours, I can't get past the usage of <code>Thread.Sleep()</code>. It's wrong, irredeemably broken, because the sleep starts when the data is appended to the kernel buffer, not when it gets transmitted. Actual time of transmit is affected by how much data was already in the write buffer, what busses exist between the UART and your CPU (for example, is it connected via USB? Then transfers have to wait for USB timeslices and may get delayed behind bulk transfers to USB mass storage devices), UART flow control, and then there's the actual transmission time based on the number of bits (including start, stop, and potentially parity) divided by the baud rate.</p>\n\n<p>So your sleep does not guarantee a period of inactivity on the serial line or give the device a chance to process one command before you send the next.</p>\n\n<p>The Windows API provides an event when the kernel write buffer has been completely drained and the serial wire becomes idle. Use it. Even if that means throwing away the C# <code>System.IO.Ports.SerialPort</code> class. Ultimately, that's the better approach: don't use the horrible wrapper provided by .NET web developers, use the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363194%28v=vs.85%29.aspx\">Communications Functions</a> API that was written by people with hardware experience.</p>\n\n<p>(This code also makes the mistake of confusing serial data with strings -- serial ports transmit bytes, not characters)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-01-13T16:52:18.330",
"Id": "77426",
"ParentId": "29807",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T18:47:56.993",
"Id": "29807",
"Score": "10",
"Tags": [
"c#",
"serial-port"
],
"Title": "SerialPort class for a library"
}
|
29807
|
<p>In order to separate my views (markup) and code, I elected to write my views like this:</p>
<pre><code> <!DOCTYPE HTML>
<html>
<head>
<title>%PAGE_TITLE%</title>
<meta charset="UTF-8">
<link href='PotatoDocs/views/stylesheets/docs2013.css' type='text/css' rel='stylesheet'>
<link rel="shortcut icon" href="favicon.ico" />
<link rel="stylesheet" href="highlight.js/styles/default.css">
<script src="highlight.js/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body>
<section id='wrapper'>
<section id='content'>
<h1>%PAGE_TITLE%</h1>
%CONTENT%
</section>
<section id='sidebar'>
%SIDEBAR%
</section>
<div class='clear'>&nbsp;</div>
</section>
<section id='footer'>
Potato Seed 2013
</section>
</body>
</html>
</code></pre>
<p>A method then replaces the substitution area with parts of the website, like so:</p>
<pre><code> private function generatePageSource($page_title)
{
$page_template = file_get_contents(REGISTRY_CODE_PATH . "views/templates/" .
$this->template_dir . "/main.html");
$page_content = str_replace("%PAGE_TITLE%", pdisplay($page_title), $page_template);
$page_content = str_replace("%CONTENT%", $this->pagecontent_content, $page_content);
$page_content = str_replace("%SIDEBAR%", $this->sidebar_content, $page_content);
$this->page_content = $page_content;
}
</code></pre>
<p>The $this->page_content is later echoed.</p>
<p>Not too relevant to my question, but for the sake of completion, this is the pdisplay() function.</p>
<pre><code>function pdisplay($pdisplay)
{
$pdisplay = htmlentities(stripslashes($pdisplay), ENT_QUOTES);
return $pdisplay;
}
</code></pre>
<p>My question is this (though I accept any code criticism at all): is this a sensible way to render pages?</p>
<p>I used to implant php tags with echoes onto a page -- but this meant that code (even a little bit) was on the views, so I thought this would be a better solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:33:13.527",
"Id": "47191",
"Score": "0",
"body": "This is a sensible way to render pages, but why not use [Twig](http://twig.sensiolabs.org/), or [Smarty](http://www.smarty.net/), or even [Savant](http://phpsavant.com/)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:42:58.573",
"Id": "47199",
"Score": "0",
"body": "I considered a template engine -- but for what I needed, this simple solution seemed to work best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T20:27:58.337",
"Id": "47475",
"Score": "0",
"body": "It's fine but a bit limited. Will you ever want to share the same head template between multiple pages? Or perhaps the side bar? Once you move past one template per web page then it can quickly get complicated."
}
] |
[
{
"body": "<p>According your comment you don't want to use a template engine, but are actually creating a new one. At some point you will need loops or ifs and it starts becoming ugly.</p>\n\n<p>PHP is already a template engine. Actually it was designed for exactly this purpose. There is a <a href=\"http://php.net/manual/en/control-structures.alternative-syntax.php\" rel=\"nofollow\">braceless/echoless syntax</a> for all control structures.</p>\n\n<p>Your template/view:</p>\n\n<pre><code><!DOCTYPE HTML>\n<html>\n<head>\n <title><?=$page_title?></title>\n ...\n</head>\n<body>\n <section id='wrapper'>\n <section id='content'>\n <h1><?=$page_title?></h1>\n <?=$content?>\n </section>\n ...\n</body>\n</html>\n</code></pre>\n\n<p>Your controller:</p>\n\n<pre><code>private function generatePageSource($page_title)\n{\n $page_title=pdisplay($page_title));\n $content = $this->pagecontent_content;\n\n ob_start();\n $template=REGISTRY_CODE_PATH . \"views/templates/\" .\n $this->template_dir . \"/main.html\";\n include $template;\n $this->page_content=ob_get_clean();\n}\n</code></pre>\n\n<p>Of course you could wrap this in a View class to DRY.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T07:14:08.797",
"Id": "47225",
"Score": "0",
"body": "Thanks for the reply. Currently, my loops reside in the controllers -- which then use more templates to build up the inner contents of the page. The sidebar has another template to describe how the navigation links will look. This template becomes the string for %SIDEBAR%."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T07:43:15.187",
"Id": "47227",
"Score": "0",
"body": "I tried this approach some year ago, but as soon as the structure gets a little more complex you have a lot of templates. So it will be really hard to change your layout afterward as you also have to change your controller in most cases. Separation of logic and representation does not mean that there is not something like a representation logic (displaying a list, conditional style classes, etc.) which belongs to the representation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T12:36:10.490",
"Id": "47528",
"Score": "0",
"body": "+1 for pointing out that php is in fact a template engine and a really good one. I would however opt for one of the realy good engines out there. Personally I favor twig since it is part of Symfony"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T05:41:08.693",
"Id": "29826",
"ParentId": "29808",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T18:50:53.430",
"Id": "29808",
"Score": "1",
"Tags": [
"php",
"html"
],
"Title": "HTML Templates with Substitutable Areas - PHP"
}
|
29808
|
<pre><code>//AMOUNT CALCULATOR
var totalAmount = 0;
var serviceAmount = 0;
jQuery('.select-service').click(function(){
var serviceAmount = parseInt(jQuery(this).parent().html().replace(/\D/g,''));
if(jQuery(this).is('.selected')){
jQuery(this).removeClass('selected');
totalAmount -= serviceAmount;
jQuery('#total-amount').html(totalAmount);
}else{
jQuery(this).addClass('selected');
totalAmount += serviceAmount;
jQuery('#total-amount').fadeIn('slow').html(totalAmount);
}
});
//AMOUNT CALCULATOR
</code></pre>
<p>is this code efficient and secure? I am PHP dont know if it is required or not to judge.. Please any Help/feed back would be awesome! really trying to better my coding..</p>
|
[] |
[
{
"body": "<p><strong>Security:</strong></p>\n\n<p>If you want to check amounts securely, don't do it in the browser alone: you need a server-side validation (e.g. with PHP if it is your language of choice).</p>\n\n<p><strong>Efficiency:</strong></p>\n\n<ol>\n<li>You can use <code>$('...')</code> instead of <code>jQuery('...')</code> to improve the readability and concision (source: <a href=\"http://api.jquery.com/html/\" rel=\"nofollow noreferrer\">jquery.com</a>).</li>\n<li>Avoid looking for divs with jQuery every time you need them by assigning them to a variable. In this case, caching <code>$('#total-amount')</code> seems unnecessary, but it will pay off as soon as you call it once more (see <a href=\"https://stackoverflow.com/questions/3230727/jquery-optimization-best-practices\">jQuery Best Practices</a> for more information).</li>\n</ol>\n\n<p>Thus:</p>\n\n<pre><code>//AMOUNT CALCULATOR\nvar totalAmount = serviceAmount = 0;\n// caching $('#total-amount')\nvar totalAmountDiv = $('#total-amount');\n\n$('.select-service').click(function(){\n // caching $(this)\n var thisDiv = $(this);\n var serviceAmount = parseInt(thisDiv.parent().html().replace(/\\D/g,''));\n if(thisDiv.is('.selected')){\n thisDiv.removeClass('selected');\n totalAmount -= serviceAmount;\n totalAmountDiv.html(totalAmount);\n }else{\n thisDiv.addClass('selected');\n totalAmount += serviceAmount;\n totalAmountDiv.fadeIn('slow').html(totalAmount);\n }\n});\n//AMOUNT CALCULATOR\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T08:30:51.413",
"Id": "47230",
"Score": "0",
"body": "wow thanks man.. but doesnt using jQuery instead of $ prevent conflicts with mootools?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T08:45:20.153",
"Id": "47231",
"Score": "0",
"body": "Yes it does, I just didn't know you used another library. To avoid conflicts, you can also use `jQuery.noconflict()` or Mootools' Dollar Safe Mode (http://mootools.net/blog/2009/06/22/the-dollar-safe-mode/)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T08:28:05.920",
"Id": "29831",
"ParentId": "29812",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29831",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:26:36.137",
"Id": "29812",
"Score": "1",
"Tags": [
"javascript",
"jquery"
],
"Title": "jQuery security and efficiency simple calculation code"
}
|
29812
|
<p>I'm working on a C library which attempts to bring some of the Python string functions over to C.</p>
<p><a href="https://github.com/shrimpboyho/octo" rel="nofollow">This</a> is where my full source is located, but the majority of what I have so far is here.</p>
<p>Are there any places where code efficiency can be improved?</p>
<pre><code>#ifndef OCTO_H
#define OCTO_H
#include <stdlib.h>
#include <string.h>
int len(char* string){
int i = 0;
while(*string != '\0'){
i++;
*string++;
}
return i;
}
char* lstrip(char* string){
if(!string)
return;
/* Trim off leading whitespace */
while(*string == ' '){
string++;
}
return string;
}
char* rstrip(char* string){
/* Trim off trailing whitespace */
char* end = string + len(string) - 1;
while (end >= string && *end == ' ')
end--;
*(end + 1) = '\0';
return string;
}
char* strip(char* string){
/* Trim off both leading and trailing whitespace */
char* lstring = lstrip(string);
char* finalString = rstrip(lstring);
return finalString;
}
char* slice(char* s, int start, int end){
/* Create a new identical buffer */
char* buff = (char*) malloc((end - start) + 2);
strncpy(buff, s + start, (end - start) + 1);
*(buff + (end - start) + 1) = '\0';
return buff;
}
char* toUpperCase(char* s){
}
char* toLowerCase(char* s){
}
#endif /* OCTO_H */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:30:17.480",
"Id": "47197",
"Score": "2",
"body": "It is not a header file so your multiple-inclusion barrier is unnecessary (`#ifndef OCTO_H` etc)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T04:29:06.160",
"Id": "47219",
"Score": "0",
"body": "@WilliamMorris: Do we call these *multiple-inclusion barrier* as Header Guards?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T06:28:36.290",
"Id": "47222",
"Score": "0",
"body": "@WedaPashi: Yes, header guards are there to prevent the header from being included more than once."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-25T20:55:30.690",
"Id": "48007",
"Score": "0",
"body": "Note that the identifier `string` is reserved for the standard library, so you shouldn't use it."
}
] |
[
{
"body": "<p>Well efficiency can be improved by using the built-in string functions.<br>\nThey have been optimized at the assembly level for most implementations.</p>\n\n<p>Assuming you were writing len() in C rather than using some optimal assemble instructions. The canonical form looks more like this (though I am sure it can be done better). Though there is <code>strlen()</code> which does the same thing.</p>\n\n<pre><code>int len(char* string)\n{\n char *end = string;\n for(;*end;++end) /* Notice nothing here */;\n return end-string;\n}\n</code></pre>\n\n<p>Looking at this:</p>\n\n<pre><code>char* lstrip(char* string){\n\n\n /* This makes it non optimal for strings we already know are good.\n * If I already know my string is fine I would want a function that\n * did not do this test.\n *\n * Of course you can then have a second function that does the test\n * then calls the non checked version (and if it is short the compiler\n * will inline\n */\n if(!string)\n /* Not returning a value from a function expecting a value is an error\n * Check the warning messages generated by the compiler\n */ \n return;\n\n /*\n * ' ' is not white space it is just a space character\n * What you are looking for is isspace(c)\n */ \n while(*string == ' '){\n string++;\n }\n\n return string;\n}\n</code></pre>\n\n<p>I would have written like this:</p>\n\n<pre><code>char* lstripNT(char* string){ return string?lstrip(string):NULL;}\nchar* lstrip(char* string){\n for(;isspace(string);++string) /*Nothing here*/;\n return string;\n\n // NOTE: there is an issue with this technique in that you\n // are not returning the original string.\n // If the string was dynamically allocated\n // you now have issues with freeing it. Which means you\n // specifically need to keep a copy of the original pointer\n // for the purpose of freeing it when you are finished.\n // This is NOT a good idea.\n}\n</code></pre>\n\n<p>Because of the problem with dynamic allocation I would probably write like this:</p>\n\n<pre><code>char* lstrip(char* string)\n{\n size_t move = 0;\n char* start= string;\n for(;isspace(start);++start,++move)\n {}\n if (move)\n {\n // Move all the characters down.\n // So we basically squish the white space.\n for(;*start;++start)\n {\n *(start-move) = *start;\n }\n }\n return string;\n}\n</code></pre>\n\n<p>Right trim. Is not really optimal because you scan to the end (using len). Then you then scan backwards until you find a non space character. You can do this in a single traverse. Also you are not being consistent. lstrip() checks for NULL while this does not.</p>\n\n<pre><code>char* rstripNT(char* string){ return string?rstrip(string):NULL;}\nchar* rstrip(char* string){\n\n char* loop = string;\n char* last = NULL;\n int isSpace = false;\n while(*loop)\n {\n isSpace = TRUE;\n last = loop;\n for(;*loop && isspace(*loop);++loop)\n {}\n if (*loop)\n {\n isSpace = FALSE;\n for(;*loop && !isspace(*loop);++loop)\n {}\n }\n }\n if (isSpace)\n {\n *last = '\\0';\n }\n return string;\n}\n</code></pre>\n\n<p>The strip. </p>\n\n<pre><code>char* strip(char* string){\n\n /* Trim off both leading and trailing whitespace */\n char* lstring = lstrip(string);\n char* finalString = rstrip(lstring);\n\n return finalString;\n\n}\n</code></pre>\n\n<p>This is conceptually what you want to do.<br>\nBut I don't think that will be optimal way to do it. I would write this as a single pass.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:13:42.837",
"Id": "47193",
"Score": "0",
"body": "I think ```for(;*end;++end) /* Notice nothing here */;``` should be ```for(;*end;++end){} /* Notice nothing here */;```"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T21:09:39.637",
"Id": "47204",
"Score": "2",
"body": "@Cygwinnian: Those are both the same. The standard is `for(<init>;<test>;<inc>)<statement>`. Statement can be the empty statement `;` or it can be Block `{}` both work the same way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T21:57:01.680",
"Id": "47205",
"Score": "0",
"body": "@LokiAstari Sorry didn't see the semicolon at the end of the comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T07:07:02.200",
"Id": "47224",
"Score": "0",
"body": "To expand on the point about using built-in functions, `strlen()` in particular is likely to have an built-in implementation that is faster than you’d be able to hand code in C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T16:34:10.463",
"Id": "47300",
"Score": "0",
"body": "@microtherion: I though I said that in the first sentence."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:20:30.037",
"Id": "47312",
"Score": "0",
"body": "@LokiAstari, yes, you did say to use built-in functions in general. My point was that `strlen()` (The simplest of them, and maybe therefore the most tempting to roll oneself) was in fact that most likely to be optimized."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T06:46:26.343",
"Id": "47370",
"Score": "0",
"body": "@microtherion: You are correct and a point worth emphasizing."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:05:05.027",
"Id": "29818",
"ParentId": "29815",
"Score": "5"
}
},
{
"body": "<p>These points are mostly designed-oriented:</p>\n\n<ul>\n<li><p>I'd recommend having <code>len()</code> return a <code>size_t</code> with <code>i</code> as the same type. This type is preferred for size functions and is also used in libraries.</p></li>\n<li><p>Although just another form, <code>lstrip()</code> can be done this way:</p>\n\n<pre><code>char* lstrip (char* string) {\n\n // skip and return right away if condition is not met\n if (string) {\n /* Trim off leading whitespace */\n while (*string == ' ') {\n string++;\n }\n }\n\n return string;\n}\n</code></pre>\n\n<p>Also, your plain <code>return</code> won't work because the function is supposed to return a <code>char*</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:09:44.317",
"Id": "29819",
"ParentId": "29815",
"Score": "4"
}
},
{
"body": "<p>Here's another variant on these functions. I've passed in a character set, <code>cset</code>, that is to be stripped instead of assuming we are stripping just spaces or using <code>isspace</code>. So you might pass in </p>\n\n<pre><code>\" \\t\\n\\r\"\n</code></pre>\n\n<p>as <code>cset</code>, for example.</p>\n\n<pre><code>size_t lstrip(char * restrict s, const char * restrict cset)\n{\n const char *t = s + strspn(s, cset);\n size_t len = strlen(t);\n\n if (s != t) {\n memmove(s, t, len + 1); // +1 to capture the \\0\n }\n return len;\n}\n</code></pre>\n\n<p>Here is <code>rstrip</code></p>\n\n<pre><code>size_t rstrip(char * restrict s, const char * restrict cset)\n{\n char *end = s + strlen(s);\n\n while (end > s && strchr(cset, *end)) {\n --end;\n }\n end[1] = '\\0';\n return (size_t) (end - s);\n}\n</code></pre>\n\n<p>These functions are reasonably efficient.</p>\n\n<p>Implementing <code>slice</code> is much more complicated if you want to emulate Python well because Python (as far as I remember) allows negative values in start/end so that you can slice relative to the end rather than the start. Your version doesn't handle such things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T23:35:28.883",
"Id": "29824",
"ParentId": "29815",
"Score": "3"
}
},
{
"body": "<p>One way to improve time-efficiency for certain operations would be to package the string in a struct. If you make the <code>char*</code> the first member, then the struct can be cast to a <code>char*</code> and used normally. But it lets you stash a length member and avoid recalculating.</p>\n\n<pre><code>struct mystr {\n char *ptr;\n size_t len;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T17:24:35.930",
"Id": "30180",
"ParentId": "29815",
"Score": "0"
}
},
{
"body": "<p>Efficiency is just one of the issues with your library. Here are some other concerns.</p>\n\n<p><strong>Implementation as a header file.</strong> Most libraries are linked in to the code that uses it; yours is compiled in, by being <code>#include</code>d as a header file. What happens if <code>file1.c</code> and <code>file2.c</code> each uses <code>octo.h</code>? Then when you try to link <code>file1.o</code> and <code>file2.o</code> together, each of your functions would be defined twice, which is a linking error.</p>\n\n<p><strong>Incomplete Python emulation.</strong> String libraries can actually be quite complicated. For example, which characters are considered whitespace? <a href=\"https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/isspace.3.html\" rel=\"nofollow\">Traditionally</a>, the whitespace characters are <kbd>Tab</kbd>, <kbd>Newline</kbd>, <kbd>Vertical tab</kbd>, <kbd>Form feed</kbd>, <kbd>Carriage return</kbd>, and <kbd>Space</kbd>, but <a href=\"http://www.cs.tut.fi/~jkorpela/chars/spaces.html\" rel=\"nofollow\">Unicode</a> defines many more whitespace characters, so the answer may vary by locale. Should <code>len()</code> count bytes, or should it count Unicode characters, assuming that its argument is a string encoded in <a href=\"http://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow\">UTF-8</a>? If your library is inspired by Python, people may have an expectation that it behaves like Python.</p>\n\n<p><strong>Memory handling.</strong> Your <code>rstrip()</code> function clobbers the input string. C programmers sometimes tolerate such behaviour, if it's documented. However, the fact that your <code>rstrip()</code> returns a <code>char *</code> rather than <code>void</code> suggests that it returns the stripped string as a copy, rather than modifying the original. On the other hand, your <code>slice()</code> function returns a copy and leaves the original unmolested. In short, your library has no consistent memory-management policy, which is essential for any cohesive C library. As a result, anyone who uses it is likely to get segfaults and/or memory leaks.</p>\n\n<p><strong>Stray pointer dereference in len().</strong> Your <code>len()</code> function has a statement <code>*string++;</code> that should be just <code>string++;</code>. By the way, if you had written <code>(*string)++;</code> instead, you would have implemented a <a href=\"http://en.wikipedia.org/wiki/Caesar_cipher\" rel=\"nofollow\">Caesar cipher</a> shifting by 1.</p>\n\n<p><strong>You could use C library functions.</strong> Your <code>len()</code> is just <code>strlen()</code> (but returning a signed rather than unsigned int). Your <code>lstrip()</code> could use <code>strspn()</code> or <code>isspace()</code>. In short, get familiar with the C library's built-in functions before you write your own.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-25T17:30:54.470",
"Id": "30213",
"ParentId": "29815",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T19:45:53.667",
"Id": "29815",
"Score": "7",
"Tags": [
"optimization",
"c",
"strings",
"library"
],
"Title": "C string library inspired by Python string functions"
}
|
29815
|
<p>I'm currently taking an algorithm course in college. To find the maximum and minimum elements in an array, I'm using a <a href="http://en.wikipedia.org/wiki/Divide_and_conquer_algorithm" rel="nofollow">divide and conquer</a> algorithm. Please offer suggestions for this code snippet. I get a headache reading only comments, so please give explanation with sample code.</p>
<pre><code>#include<stdio.h>
#define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
int tempmax, tempmin;
/*
* return a 2 element array
* First element is highest of list
* Second elements is lowest of list
*
*/
int* maxmin(const int list[], const int low, const int high, int max, int min)
{
int mid,max1,min1;
static int maxAndMin[2]; // to hold the max and min value of list
// list has only one element
// so make max and min that element
if (low == high)
{
max = list[low];
min = list[low];
}
// list has two elements then
// check for which one is greater or smaller
// and check it with temp values and update
else if (low == high-1)
{
if (list[low] < list[high])
{
tempmax = getMax(tempmax, list[high]);
tempmin = getMin(tempmin, list[low]);
}
else
{
tempmax = getMax(tempmax, list[low]);
tempmin = getMin(tempmin, list[high]);
}
}
else
{
// if list is not small, divide list into sub-problems
// Find where to split the set
mid = (low + high) / 2;
// Solve the sub-problems
max1 = list[mid+1];
min1 = list[mid+1];
maxmin(list, low, mid, max, min);
maxmin(list, mid+1, high, max1, min1);
// Combine the solutions
tempmax = getMax(tempmax, max1);
tempmin = getMin(tempmin, min1);
}
maxAndMin[0] = tempmax;
maxAndMin[1] = tempmin;
return maxAndMin;
}
/*
* returns the highest element between first and second
*
*/
int getMax(int first, int second)
{
return first > second ? first : second;
}
/*
* returns the lowest element between first and second
*
*/
int getMin(int first, int second)
{
return first < second ? first : second;
}
int main(void)
{
int list[] = {10, 23, 24, 56, 67, 78, 90};
int *values;
int size = ARRAY_SIZE(list);
tempmax = tempmin = list[0];
values = maxmin(list, 0, size-1, list[0], list[0]);
printf("The maximum value is = %2d \n", *values);
printf("The minimum value is = %2d \n", *(values+1));
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><code>size_t</code> is preferred over <code>int</code> for array indices and sizes (in general) because they cannot be negative. This also ensures you the highest possible numerical range.</p></li>\n<li><p>You're correct: <code>tempmax</code> and <code>tempmin</code> shouldn't be global variables. A <code>struct</code>, as you've mentioned, could look like this:</p>\n\n<pre><code>struct MinMax\n{\n size_t tempmin;\n size_t tempmax;\n};\n</code></pre>\n\n<p>Create an instance of the structure (so that a function can update it):</p>\n\n<pre><code>MinMax mm;\n</code></pre>\n\n<p>Then pass it to a function:</p>\n\n<pre><code>doSomething(&mm);\nvoid doSomething(MinMax *mm) {}\n</code></pre></li>\n<li><p>It'll be more readable to just use the array's size when checking the number of elements:</p>\n\n<pre><code>int* maxmin(const size_t size /* other parameters */)\n{\n if (size == 1)\n {\n // do stuff\n }\n\n else if (size == 2)\n {\n // do other stuff\n }\n\n else if (size >= 3)\n {\n // do other other stuff\n }\n}\n</code></pre>\n\n<p>You could then keep <code>low</code> as <code>list[0]</code> and <code>high</code> as <code>list[size-1]</code> <em>within the function</em>, thereby allowing them to be local constants rather than arguments.</p></li>\n<li><p>I don't like the idea of having <code>minmax()</code> returning something like that. It's good to cut down on pointers whenever possible, plus it doesn't seem too readable. I'd go with one of these two options:</p>\n\n<ol>\n<li><p>Split it into two separate functions so that each just returns one value.</p></li>\n<li><p>Stick with one function, but pass <code>min</code> and <code>max</code> <em>as references</em> and make the function <code>void</code>.</p></li>\n</ol>\n\n<p>In <code>main()</code>, you would then have <code>size_t min</code> and <code>size_t max</code> instead of <code>int *values</code>.</p></li>\n<li><p>As an alternative to this task, I'd simplify the entire algorithm to use a loop instead. For one thing, you're performing recursion, which is needless here (unless you're required to do so in this course). If you <em>don't</em> need to use recursion:</p>\n\n<p>First, set <code>min</code> and <code>max</code> as the first array element. Then, go through the loop while updating each one as you respectively encounter a smaller and larger value. It could also be done with two loops, but that would decrease efficiency as each loop is O(n).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T23:44:42.670",
"Id": "47208",
"Score": "1",
"body": "Better to pass a pointer to `mm`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T23:57:53.833",
"Id": "47210",
"Score": "0",
"body": "@WilliamMorris: Such as `MinMax *mm; void doSomething(MinMax *mm) {}`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T00:55:41.963",
"Id": "47216",
"Score": "1",
"body": "Yes, `MinMax` is a structure that you want the called function to update, so you don't want to pass it by value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T01:00:23.460",
"Id": "47217",
"Score": "0",
"body": "@WilliamMorris: Ah, right. Somehow forgot about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T11:19:36.900",
"Id": "47240",
"Score": "0",
"body": "@Jamal Yes iteration is easy but using divide and conquer(recursion) significantly improves the `Big O` complexity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T12:34:59.923",
"Id": "47243",
"Score": "0",
"body": "@tintinmj: Yeah. I was just putting another method out there (I've also never seen this one before)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:05:21.217",
"Id": "47257",
"Score": "0",
"body": "@tintinmj: You could also state in the question that you want the original algorithm preserved. We are free to review as we see fit unless explicitly told what not to do (as long as there's no code that needs serious attention). Either way, I'll take out my points regarding the change in algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:13:33.337",
"Id": "47259",
"Score": "0",
"body": "@Jamal no I didn't mean to say \"preserve my logic\". Please don't take out your points, it will help future students to understand the usage of recursion and iteration simultaneously for same algorithm."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:40:34.820",
"Id": "29822",
"ParentId": "29821",
"Score": "3"
}
},
{
"body": "<p>Some comments:</p>\n\n<p>Firstly the interface is odd. Normally when you pass an array, you pass it's\nsize and a pointer to the first element. In the context of your function this\nmeans:</p>\n\n<pre><code>int* maxmin(const int list[], size_t size, int max, int min);\n</code></pre>\n\n<p>Then you call this with:</p>\n\n<pre><code>maxmin(list, mid, max, min);\nmaxmin(list + mid, size - mid, max1, min1);\n</code></pre>\n\n<p>or from <code>main</code></p>\n\n<pre><code>values = maxmin(list, size, list[0], list[0]);\n</code></pre>\n\n<p>This saves a call parameter (fewer is always preferable) and makes the\nfunction more 'normal'.</p>\n\n<hr>\n\n<p>Beyond that, what stand out are the return of a static array and the use of\nglobals. Maybe thread safety is not on your mind and this can be ignored, but\nbear in mind that returning a static is rarely done. And globals are often best avoided, if they can be.</p>\n\n<hr>\n\n<p>The other thing that strikes me is the awkwardness of the code. Arguably a\nmatter of opinion, there are many variables and their names are hard to tell\napart. More importantly the need to find both max and min values complicates\nthe function enormously.</p>\n\n<p>Consider the same task but only looking for the minimum value:</p>\n\n<pre><code>int min(const int list[], const size_t size)\n{\n if (size == 1) {\n return list[0];\n }\n else if (size == 2) {\n return list[0] < list[1] ? list[0] : list[1];\n }\n size_t half = size / 2;\n int n = min(list, half);\n int m = min(list + half, size - half);\n return n < m ? n : m;\n}\n</code></pre>\n\n<p>This is so much simpler! And the <code>max</code> version just involves reversing the\ntwo comparisons. I would be looking for an excuse to use these rather than\nyour combined function. Against my functions is the fact that calling <code>max</code>\n<strong>and</strong> <code>min</code> will be slower than just calling yours (but less than 2:1). In\ntheir favour, you might not always want both values. </p>\n\n<p>As this is just an exercise, you don't have to care. But in practice I\nbelieve strongly that it is always worth simplifying the\nrequirement/specification if it results in simpler code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T11:15:07.073",
"Id": "47239",
"Score": "0",
"body": "My excuse to find the `max` and `min` value simultaneously is that the algorithm states that way and it's also an important exam question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T02:20:29.890",
"Id": "29825",
"ParentId": "29821",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29825",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:28:12.910",
"Id": "29821",
"Score": "5",
"Tags": [
"algorithm",
"c",
"divide-and-conquer"
],
"Title": "Maxmin algorithm implementation"
}
|
29821
|
<p>Trying to learn FRP and Elm. Is the program below "ok" from the perspective of FRP and Elm? What could be improved? The program can be executed here: <a href="http://elm-lang.org/try">http://elm-lang.org/try</a></p>
<pre><code>import Random
import Mouse
data Fruit = Apple | Orange | Banana | Melon | Guava
rand = Random.range 0 4 (Mouse.clicks)
fruit n = if | n == 0 -> Apple
| n == 1 -> Orange
| n == 2 -> Banana
| n == 3 -> Melon
| otherwise -> Guava
fruitText = toForm <~ (asText <~ (fruit <~ rand))
time = lift (inSeconds . fst) (timestamp (fps 40))
scene dy form = collage 300 300 [move (0, 100 * cos dy) form]
main = lift2 scene time fruitText
</code></pre>
|
[] |
[
{
"body": "<p>Two months late, but I will try to answer nevertheless. ;-)</p>\n\n<p>Since your <code>rand</code> already makes sure the numbers will be valid indices for your fruits, you don't have to use so many if cases. The rest looks OK to me, but I made some annotations in the source.</p>\n\n<pre><code>import Random\nimport Mouse\n-- Sometimes empty lines can improve readability.\n\ndata Fruit = Apple | Orange | Banana | Melon | Guava\n\n-- For module global declarations, it is often helpful to\n-- explicitly annotate the types.\nfruits : [Fruit]\nfruits = [Apple, Orange, Banana, Melon, Guava]\n\n-- especially for functions :)\nfruit : Int -> Fruit\nfruit n = head <| drop n fruits\n\nrand : Signal Int\nrand = Random.range 0 ((length fruits) - 1) Mouse.clicks\n\n-- exercise: Try to figure and annotate the remaining types. ;-)\nfruitText = toForm <~ (asText <~ (fruit <~ rand))\n\ntime = lift (inSeconds . fst) (timestamp (fps 40))\n\nscene dy form = collage 300 300 [move (0, 100 * cos dy) form]\n\nmain = lift2 scene time fruitText\n</code></pre>\n\n<p>btw: share-elm.com is a bit easier for showing elm code to someone than making him copy paste to elm-lang.org/try.<br>\nSee: <a href=\"http://share-elm.com/sprout/52567327e4b0d6a98b1531c7\" rel=\"nofollow\">http://share-elm.com/sprout/52567327e4b0d6a98b1531c7</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T09:27:38.653",
"Id": "32515",
"ParentId": "29823",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "32515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-15T20:56:59.530",
"Id": "29823",
"Score": "7",
"Tags": [
"functional-programming",
"elm"
],
"Title": "Can this be written more concise and aligned with the Functional Reactive Programming paradigm?"
}
|
29823
|
<p>I'm trying to achieve a set of unique array with my following function.</p>
<h2>The Function:</h2>
<p></p>
<pre><code>/**
* uniqueAssocArray Removes arrys which have same keys
* @param Array $array Array to get unique items from
* @param String $uniqueKey the unique key
* @return Array new array with unique items
* @author Junaid Qadir Baloch <shekhanzai.baloch@gmail.com>
*/
function uniqueAssocArray($array, $uniqueKey) {
if (!is_array($array)) {
return array();
}
$uniqueKeys = array();
foreach ($array as $key => $item) {
if (!in_array($item[$uniqueKey], $uniqueKeys)) {
$uniqueKeys[$item[$uniqueKey]] = $item;
}
}
return $uniqueKeys;
}
</code></pre>
<p></p>
<h2>Example Array:</h2>
<pre><code>$actualArray = array(
user1 => array(
'name' => 'User1',
'age' => '25',
'lastLogin' => '2013-08-16'
),
user1 => array(
'name' => 'User1',
'age' => '25',
'lastLogin' => '2013-08-10'
),
user2 => array(
'name' => 'User2',
'age' => '35',
'lastLogin' => '2013-08-08'
),
user1 => array(
'name' => 'User1',
'age' => '25',
'lastLogin' => '2013-07-10'
)
);
</code></pre>
<p>I then call the function like so:</p>
<pre><code>$resultArray = uniqueAssocArray($actualArray, 'name');
</code></pre>
<h2>But...</h2>
<p>I wonder is there a better way to do the same ?</p>
|
[] |
[
{
"body": "<p>Maybe you should try to use the function <code>array_unique</code>: <a href=\"http://php.net/manual/en/function.array-unique.php\" rel=\"nofollow\">http://php.net/manual/en/function.array-unique.php</a></p>\n\n<p>If you prefer to go with your own solution, have a look at the method <code>array_key_exists</code> (<a href=\"http://www.php.net/manual/en/function.array-key-exists.php\" rel=\"nofollow\">http://www.php.net/manual/en/function.array-key-exists.php</a>) to replace your condition:</p>\n\n<pre><code>if (!array_key_exists($key, $uniqueKeys)) {\n $uniqueKeys[$item[$uniqueKey]] = $item; \n}\n</code></pre>\n\n<p>A bit off-topic here, but you probably don't want to store a user's age but rather her birthday, to make sure it stays up-to-date.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T12:36:50.730",
"Id": "47248",
"Score": "0",
"body": "If I get him right he wants to use the last not the first duplicate each."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T11:56:16.413",
"Id": "29837",
"ParentId": "29835",
"Score": "1"
}
},
{
"body": "<p>Assuming your array is already sorted, you can just overwrite the values every time. Skip the inner if.</p>\n\n<pre><code>function uniqueAssocArray($array, $uniqueKey) {\n if (!is_array($array)) {\n return array();\n }\n $uniqueKeys = array();\n foreach ($array as $key => $item) {\n $groupBy=$item[$uniqueKey];\n if (isset( $uniqueKeys[$groupBy]))\n {\n //compare $item with $uniqueKeys[$groupBy] and decide if you \n //want to use the new item\n $replace= ... \n }\n else\n {\n $replace=true;\n }\n if ($replace) $uniqueKeys[$groupBy] = $item; \n }\n return $uniqueKeys;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T16:55:44.993",
"Id": "47302",
"Score": "0",
"body": "Haha! i had already done the same but I have to accept your answer.\nThere's one catch though, Array must be sorted in reverse order. and I test for existence for a key before I replace the values blindly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T03:54:51.333",
"Id": "47359",
"Score": "0",
"body": "@mnhgI hope you won't mind if i un-accept your answer. I'm still looking for a better way"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T06:08:57.560",
"Id": "47367",
"Score": "0",
"body": "If you want the last element each, you need an ascending order. You are just overwriting the value again and again until you are on the last key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T08:36:38.843",
"Id": "47373",
"Score": "0",
"body": "Yes, but what if the array is random?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T08:45:59.737",
"Id": "47374",
"Score": "0",
"body": "If performance doesn't matter, sort it. If you want to handle this in the same loop just compare the current items key value with the already inserted."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T12:00:43.333",
"Id": "29838",
"ParentId": "29835",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T10:55:29.670",
"Id": "29835",
"Score": "4",
"Tags": [
"php",
"array"
],
"Title": "What is a better way to get unique array Items based on key in PHP?"
}
|
29835
|
<p>I'm a noob in programming. I was asked to code a program that can <strong>calculate prime numbers.</strong> So i coded as provided below. But it <strong><em>prints all the Odd Numbers instead of Prime Numbers</em></strong>. I think the <strong>Value start is not being divided by all the integers in the range (2,Startnumber)</strong>. It just prints all the odd numbers.</p>
<pre><code>startnumber=int(raw_input("Enter a number: "))
start=2
while start<=startnumber:
for divisor in range(2,startnumber):
if start%divisor==0:
break
else:
print start
break
start=start+1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:34:02.370",
"Id": "47290",
"Score": "0",
"body": "Although your issue has been solved, would you like a review on your *working* code? If not, this post will remain closed, preventing any new answers from being posted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T06:27:43.780",
"Id": "47368",
"Score": "0",
"body": "ya sure why not.. @Jamal"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T07:05:27.893",
"Id": "47372",
"Score": "0",
"body": "Okay. Just edit your question with this request, replacing everything about the non-working code (explanation and the code itself)."
}
] |
[
{
"body": "<p>There is no need to keep for loop in the while as while is doing the job of for,\nassuming that your program tests whether the <code>startnumber</code> is prime or not.</p>\n\n<p>using of <code>break</code> in <code>else</code> will terminate your loop once it checks that its not divisible by 2 [ the first divisor] . so <code>break</code> shouldn't be used there in <code>else</code> block as you want to test for numbers above 2.</p>\n\n<p>We can while - else or for-else to solve your problem. \nthe code below shows the representation of your problem in while - else:</p>\n\n<pre><code>startnumber=int(raw_input(\"Enter a number: \"))\nstart=2\nwhile start<startnumber:\n\n if startnumber%start==0:\n print str(startnumber)+\" is not a prime.\"\n break \n start=start+1\nelse:\n print str(startnumber)+\" is a prime.\"\n</code></pre>\n\n<p>same code with for -else would be :</p>\n\n<pre><code>startnumber=int(raw_input(\"Enter a number: \"))\nstart=2\nfor number in range(2,startnumber):\n\n if startnumber%start==0:\n print str(startnumber)+\" is not a prime.\"\n break \n start=start+1\nelse:\n print str(startnumber)+\" is a prime.\"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:17:18.200",
"Id": "47278",
"Score": "0",
"body": "ok, thank you for ur reply... but actually i was trying to print all the prime numbers in the range. i'm able to check if the number is prime but i want to print all the prime numbers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:19:24.697",
"Id": "47279",
"Score": "0",
"body": "I presumed based on your prompt for the user.\nyou should change your prompt so that the user understands what you are expecting from him/her."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:51:20.203",
"Id": "29848",
"ParentId": "29843",
"Score": "1"
}
},
{
"body": "<p>The <code>%</code> is the modulo operator. If you want to check if it's a prime or not you should test if it's only dividable by itself and 1 to get a integer (not a floating point number).</p>\n\n<p>So what you want to do is to loop though a list of integers. In your script you can provide the limit of this list (as I assume). Then for each number in the list you want to check if there's a number other than 1 or itself that can be used to divide the number into integers.</p>\n\n<p>The easiest way to check if a the result of a division is a floating point number or an integer is to convert the result to an integer and check if the number is still the same.</p>\n\n<p>By default if you do math in Python, it only works with integers. Example:</p>\n\n<pre><code>>>> 5 / 2\n2\n</code></pre>\n\n<p>To do a calculation with floating point precision, you need to define at least one of the numbers as a floating point number. You can do this by writing it as a floating point number like this:</p>\n\n<pre><code>>>> 5.0 / 2\n2.5\n</code></pre>\n\n<p>You can also convert integers to floating point numbers using the <code>float</code> method:</p>\n\n<pre><code>>>> float(5)\n5.0\n>>> float(5) / 2\n2.5\n</code></pre>\n\n<p>You can also convert floats to integers using the <code>int</code> method:</p>\n\n<pre><code>>>> int(2.5)\n2\n>>> int(float(5))\n5\n</code></pre>\n\n<p>Now if you do a comparison with floats and ints in Python, it doesn't matter if it's a float or int, but what matters is the actual value it represends:</p>\n\n<pre><code>>>> 5 == 5\nTrue\n>>> 5.0 == 5\nTrue\n>>> 2.5 == 2.5\nTrue\n>>> int(2.5) == int(2.5)\nTrue\n>>> int(2.5) == 2.5\nFalse\n</code></pre>\n\n<p>Note the last comparison. We convert the float <code>2.5</code> to an int, so that becomes <code>2</code>, which isn't equal to the float <code>2.5</code>. We can use this trick to check if the result of a division is a float or an int:</p>\n\n<pre><code>>>> result = 6.0 / 2\n>>> result == int(result)\nTrue\n>>> result = 5.0 / 2\n>>> result == int(result)\nFalse\n</code></pre>\n\n<p>Great! Let's use that in our loop! We assume the number is a prime until we have proven it's dividable by a number other than 1 or itself.</p>\n\n<pre><code>number = 5.0\n\n# assume the number is a prime\nprime = True\n\n# try divisions from 2 through the number - 1\n# which are all the numbers between 1 and the number itself\nfor divisor in range(2, number - 1):\n\n # do the division\n result = number / divisor\n\n # check if the result is an integer number\n if result == int(result):\n\n # if so, the number is not a prime\n prime = False\n\n # since we found it is not a prime,\n # we can break out of the for loop\n break\n</code></pre>\n\n<p>The complete script could look something like this:</p>\n\n<pre><code>limit = int(raw_input(\"Enter a number: \"))\nnumber = 0\n\nwhile number <= limit:\n\n prime = True\n\n for divisor in range(2, number - 1):\n result = float(number) / divisor\n if result == int(result):\n prime = False\n break\n\n if prime:\n print int(number)\n\n number += 1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:21:36.217",
"Id": "47280",
"Score": "0",
"body": "THank YOu sooooo much.... it was really helpful... i highly appreciate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:52:30.200",
"Id": "47293",
"Score": "0",
"body": "Actually when I read Sandeep answer, I realized you can also use modulo which makes sense, because modulo will keep substracting the second number from the first till it's not possible anymore and then returns what's left over. That's also a way to detect if the division will return an integer or a float."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:56:36.303",
"Id": "29849",
"ParentId": "29843",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29849",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:10:00.963",
"Id": "29843",
"Score": "0",
"Tags": [
"python",
"algorithm",
"primes"
],
"Title": "Problem in calculating prime numbers in python"
}
|
29843
|
<p>I wrote the below code and tested some example files on it. I didn't find any errors, but I still want to be thorough about this.</p>
<p>Also, any suggestions in improving the code?</p>
<pre><code>import string
""" this implements an encryption standard over the message text
it replaces the odd place alphabets by their ordinal number plus place number increased.
it replaces the even place alphabets by their ordinal number minus place number decreased.
for example "hello" becomes "icoht" and "abc" becomes "bzf".
"""
input_filename = raw_input("Enter the input file name: ")
output_filename = raw_input("Enter the output dumping file name: ")
mode = raw_input("Do you want to encrypt or decrypt (e/d)?: ")
with open(input_filename,'r') as inputfile:
with open(output_filename,'w') as outputfile:
inp = inputfile.read()
encode = lambda s: "".join(
(chr(ord('a')+((ord(c)-(ord('a')+i+1))%26))) if ((c.isalpha()) and ((i+1)% 2 ==0))
else
string.ascii_lowercase[(string.ascii_lowercase.rfind(c.lower())+i+1)%26] if ((c.isalpha()) and ((i+1)% 2 ==1))
else
c
for i,c in enumerate(s.lower())
)
decode = lambda s: "".join(
string.ascii_lowercase[(string.ascii_lowercase.rfind(c.lower())+i+1)%26] if ((c.isalpha()) and ((i+1)% 2 ==0))
else
(chr(ord('a')+((ord(c)-(ord('a')+i+1))%26))) if ((c.isalpha()) and ((i+1)% 2 ==1))
else
c
for i,c in enumerate(s.lower())
)
if(mode.lower() == 'e'):
outputfile.write(encode(inp))
else :#(mode.lower() =='d'):
outputfile.write(decode(inp))
s = {'e':'Encoding','d':'Decoding'}
print s.get(mode)+" Sucessfull"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:36:36.807",
"Id": "47321",
"Score": "1",
"body": "`((i+1)% 2) ==0)` is more traditionally written as `(i % 2 == 1)`. Conversely, `((i+1)% 2) == 1)` is the same as `(i % 2 == 0)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:53:26.473",
"Id": "47323",
"Score": "0",
"body": "thnx @200_success"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T16:35:54.933",
"Id": "47872",
"Score": "0",
"body": "What versions of python are you expecting to work with?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T08:41:52.653",
"Id": "47900",
"Score": "0",
"body": "python 2.7 @belacqua"
}
] |
[
{
"body": "<p>Functions are your friend. The remove repeated code and improve readability. I have absolutely no idea what the block of text does inside the <code>\"\".join(XXXX)</code> calls. There is too much going on there that I'm not going to take the time to see what it does or if it can be done better.</p>\n\n<p>However, it does appear that you can replace that mess with something like this:</p>\n\n<pre><code>def doA():\n pass\ndef doB():\n pass\ndef makeJoinArgument(value, which_step,step1, step2):\n return step1() if (which_step) else step2() for x in value\ndef encode(value):\n return \"\".join(\"abc\", True, doA, doB)\ndef decode(value):\n return \"\".join(\"abc\", True, doB, doA)\n</code></pre>\n\n<p>This obviously doesn't run (and not exactly what you have), but it is much more manageable than what you have now.</p>\n\n<p>Another note (from <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8: Style Guide</a>)</p>\n\n<blockquote>\n <p>Always use a def statement instead of an assignment statement that\n binds a lambda expression directly to a name.</p>\n \n <p>Yes:</p>\n \n <p>def f(x): return 2*x</p>\n \n <p>No:</p>\n \n <p>f = lambda x: 2*x</p>\n \n <p>The first form means that the name of the resulting function object is\n specifically 'f' instead of the generic ''. This is more\n useful for tracebacks and string representations in general. The use\n of the assignment statement eliminates the sole benefit a lambda\n expression can offer over an explicit def statement (i.e. that it can\n be embedded inside a larger expression)</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T11:19:01.290",
"Id": "60961",
"Score": "0",
"body": "Your suggested code has several errors. Can you fix, please?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:00:57.490",
"Id": "29853",
"ParentId": "29844",
"Score": "2"
}
},
{
"body": "<p>Your encode and decode functions are absurdly long for 'one liners'. Also they contain these two lines</p>\n\n<pre><code>(chr(ord('a')+((ord(c)-(ord('a')+i+1))%26))) if ((c.isalpha()) and ((i+1)% 2 ==0))\n</code></pre>\n\n<p>and </p>\n\n<pre><code>string.ascii_lowercase[(string.ascii_lowercase.rfind(c.lower())+i+1)%26] if ((c.isalpha()) and ((i+1)% 2 ==1))\n</code></pre>\n\n<p>which both do similar things in a different and needlessly complicated way.</p>\n\n<p>A more readable and simpler version of the encode function would be:</p>\n\n<pre><code>def encode(s):\n r = list(s.lower())\n abc = string.lowercase()\n for i, c in enumerate(r):\n if c in abc:\n if i % 2:\n r[i] = abc[(abc.index(c) - i - 1) % 26]\n else:\n r[i] = abc[(abc.index(c) + i + 1) % 26]\n return ''.join(r)\n</code></pre>\n\n<p>In terms of structure you probably don't want to have the encode/decode functions defined inside the <code>with</code> in your main function, but separately:</p>\n\n<pre><code>import string\ndef encode(s):\n ...\n\ndef decode(s):\n ...\n\ndef main():\n \"\"\" this implements etc.\n \"\"\"\n input_filename = raw_input(\"Enter the input file name: \")\n output_filename = raw_input(\"Enter the output dumping file name: \")\n mode = raw_input(\"Do you want to encrypt or decrypt (e/d)?: \").lower()\n with open(input_filename,'r') as inputfile:\n with open(output_filename,'w') as outputfile:\n inp = inputfile.read()\n if mode is 'e':\n outputfile.write(encode(inp))\n print 'Encoding successful'\n else :#(mode.lower() =='d'):\n outputfile.write(decode(inp))\n print 'Decoding successful'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T01:46:02.577",
"Id": "29881",
"ParentId": "29844",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:17:44.947",
"Id": "29844",
"Score": "2",
"Tags": [
"python",
"formatting",
"caesar-cipher"
],
"Title": "Implementing an encryption standard over message text"
}
|
29844
|
<p>I wrote my very first directive and I'd like to get some suggestions for improvement.
My code - <a href="http://plnkr.co/edit/NW5VPl2anBThpnvOZiSD?p=preview" rel="nofollow">plnkr.</a></p>
<pre><code>webApp.controller('AppCtrl', function ($scope) {
$scope.expandAdd = function() {
$scope.hiddenAdd = true;
};
$scope.addWeb = function() {
$scope.hiddenAdd = false;
};
});
webApp.directive('enter',function(){
return {
link: function (scope, element, attrs){
scope.hiddenAdd = false; //hides the site details at first
//Invoke expender on the controller on mouse click
element.bind('click', function(){
console.log('clicked');
scope.$apply(attrs.enter);
});
}
}
});
</code></pre>
<p>I have three points I think I can improve here but I'm not sure how:</p>
<ol>
<li><p>My directive is not modular enough, the line <code>scope.hiddenAdd = false</code> is bound to <code>hiddenAdd</code>. Is it possible to make it more flexible for future use?
Though it seems two be picking to different <code>bindings</code> I think that is because they are both start with <code>hidden</code>.</p></li>
<li><p>Inside the <code>controller</code> I'm doing <code>DOM</code> manipulation <code>$scope.hiddenAdd = true;</code> & <code>$scope.hiddenAdd = false;</code> from what I've read it all best be inside <code>directives</code> and I can't find the way to make it a pure <code>directive</code>.</p></li>
<li><p>I read somewhere that it is not recommended to use <code>$apply</code> too often, is there a way to avoid using <code>apply</code> in my case?</p></li>
</ol>
|
[] |
[
{
"body": "<p><strong>Option 1: Don't use a directive.</strong><br>\nWhat you are trying to do does not actually require a directive. It is simple enough to play with the scope.</p>\n\n<pre><code> $scope.expandAdd = function() {\n $scope.hiddenAdd = true;\n };\n\n $scope.addWeb = function() {\n $scope.hiddenAdd = false;\n };\n</code></pre>\n\n<p><a href=\"http://plnkr.co/edit/VqEatAKJ4wGTdmzSAxE2?p=preview\" rel=\"nofollow\">plnkr</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T11:38:30.627",
"Id": "30357",
"ParentId": "29846",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "30357",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T13:27:02.563",
"Id": "29846",
"Score": "1",
"Tags": [
"javascript",
"angular.js"
],
"Title": "AngularJS, Directive improvement"
}
|
29846
|
<p>I have the following object oriented class revolving about the PHP super global <code>$_SESSION</code> I shown the script to a fellow developer and he mentioned that all my returns are not necessary needed, whereas I believe that they are? </p>
<p>My code is as followed: </p>
<pre><code>/*
*
*
* This class will allow control of the super global $_SESSION within PHP
* It's possible to import this class within websites which are already working with session variables.
* Currently the functionality provides:
* Invoking a new session
* Getting the current session stats
* Setting a session key/value
* Getting the session value
* displaying the session array
*
*
*
*/
class Session {
protected $Session_Started = false;
public function __construct(){
/*
*
* If session is already invoked, the constructor
* will switch the protected variable to true, and the session_start function will not be called
* If session is not already invoked, the protected variable will remain false and provide the ability
* To invoke a session_start() by calling $Class->init();
*/
if (session_status() === 1){
$this->Session_Started = true;
return false;
}
return true;
}
public function init(){
/*
Invoke a session
*/
if ($this->Session_Started === false){
session_start();
$this->Session_Started = true;
return true;
}
return false;
}
public function Status_Session(){
/*
Getting the current session status, and return readable information on the current status
*/
$Return_Switch = false;
if (session_status() === 1){
$Return_Switch = "Session Disabled";
}elseif (session_status() === 2){
$Return_Switch = "Session Enabled, but no sessions exist";
}elseif (session_status() === 3){
$Return_Switch = "Session Enabled, and Sessions exist";
}
return $Return_Switch;
}
public function Set ($Key = false, $Value){
/*
Set a value within the $_SESSION global
this function will return true, if a sucessfull addition has been made
and return false if a problem is enountered
*/
if ($this->Session_Started === true){
$_SESSION[$Key] = $Value;
return true;
}
return false;
}
public function Get ($Key){
/*
Invoking this function will return the current value of the session key, else return false is an error is encountered
*/
if (isset($_SESSION[$Key])){
return $_SESSION[$Key];
}
return false;
}
public function Display(){
/*
If session is started, this function will return a readable and formatted array
*/
if ($this->Session_Started === true){
return "<pre>".$_SESSION."</pre>";
}
}
} // Close class
</code></pre>
<p>Now, for example: </p>
<pre><code>$Class = new Session();
if ($Class->Set("Key","Value")){
echo "Created Value/key within the Session array, and returned true";
}
</code></pre>
<p>I understand that people like to validate a successful/fail boolean based on true and false, so I have included the correct return, but my overall question is just to confirm which I believe is correct.. Which is regarding the returns... Is it a perfectly acceptable thing to do, over having no returns? and within best preference? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:57:54.183",
"Id": "47296",
"Score": "1",
"body": "I’d say the best way to handle that is probably to throw an exception if the session hasn’t been started, unless an unstarted session is going to be part of normal behaviour."
}
] |
[
{
"body": "<p>As for your question, at least Get should not return false if the value is not set, now the caller will not know whether the actual value is false or whether the value is not set.</p>\n\n<p>Other than that,</p>\n\n<ul>\n<li><p>I would suggest you use PHP_SESSION_DISABLED , PHP_SESSION_NONE and PHP_SESSION_ACTIVE instead of 1, 2 and 3</p></li>\n<li><p>To have Status_Session call session_status is confusing, maybe call it session_status_string ? Also, this should not return false, but maybe \"Session status could not be determined\"</p></li>\n<li><p>I dont understand this : <code>if (session_status() === 1){ $this->Session_Started = true;</code> if session_status() == 1, then sessions are disabled, why would you set Session_Started to true ?</p></li>\n<li><p>session_start() will return a boolean that indicates whether the session actually started, you should check that boolean instead of assuming success with <code>$this->Session_Started = true;</code></p></li>\n<li><p>session_start() also can resume a session, I am not a PHP master, but it seems to me you could replace init() with</p></li>\n</ul>\n\n<blockquote>\n<pre><code>public function init(){\n /* Start or Resume a session */\n $this->Session_Started = session_start();\n return $this->Session_Started;\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Finally, if you are adamant about checking whether the session is started or not in <code>set</code>, would it not make sense to start the session for the caller, so that your code works auto-magically ?</li>\n</ul>\n\n<blockquote>\n<pre><code>public function Set ($Key = false, $Value){\n if (!isset($_SESSION)) { \n init(); \n }\n $_SESSION[$Key] = $Value;\n}\n</code></pre>\n</blockquote>\n\n<p>Also, as mini-tech commented, if you expect a session, and it is not there, then you might want to throw an exception instead of returning false.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T16:35:05.327",
"Id": "47301",
"Score": "0",
"body": "I'm not expecting a session. This class is being built to have the ability to migrate into websites which have currently invoked `session_start`, if a session has already been started. Then a `session_start();` will not be called, if not then calling `$Class->init()` will invoke a `session_start();`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T18:26:19.330",
"Id": "47326",
"Score": "0",
"body": "You are expecting a session any time you use $_SESSION ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T18:53:10.380",
"Id": "47332",
"Score": "0",
"body": "Alright. Let me explain properly, the construct will detect if session has already started, if it is already started. Then it will force `$this->Session_Start = true;`, which will in transit stop this class from attempting to start antoher session due to the internal reference pointer being set to true. This is going off topic of the question, i'm here asking if returning a boolean is a good idea or not"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T13:05:19.757",
"Id": "47576",
"Score": "0",
"body": "@DarylGill returning stuff in a __construct is kinda lame... the __construct is called when you are creating a new instance of that class. So the 'returned boolean' is in fact not returned anywhere ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T16:28:18.037",
"Id": "29864",
"ParentId": "29851",
"Score": "2"
}
},
{
"body": "<p>This class isn't really usefull. What if you suddenly decide to not use $_SESSION but a db connection for your session storage? You would then have a lot of duplicate code.</p>\n\n<p>Also the naming of your methods are horrible. Now I would have to read the entire doc/method code to know what really happens. a method nams as <code>getSessionStatus()</code> tells me I'm getting the session status. But <code>Session_Status()</code> doesn't really say a lot, is it for getting? setting? does it toggle the session_status? Oh, it returns a string e.d. representation data. Nah thx, I'll just stick to the <code>session_status()</code> php function.</p>\n\n<p>Then <code>init()</code>. Isn't this simply another name for a <code>__construct()</code>? obviously session's have to be enabled for the class to function. If it isn't enabled on <code>__construct()</code> simply throw an exception and remove that weird <code>init()</code> function and all those <code>if( session_Satrted )</code></p>\n\n<p>But to answer your original question:returning a boolean in a __construct() is stupid... If you need something that isn't present, throw an Excpetion. If you don't throw an exception then you should work perfectly. Then all methods should have NO SIDE-EFFECTS. If I get a value from the session, I'm only getting a value. I'm not telling you to start a session... So don't do that.</p>\n\n<p>Think DRY SOLID and write your code using a better 'standard': <a href=\"http://www.php-fig.org/psr/1/\" rel=\"nofollow\">http://www.php-fig.org/psr/1/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T13:43:23.760",
"Id": "47580",
"Score": "0",
"body": "Session_start() is invoked once, there is no secondary invoking within this class.. If you are to get a value, the function checks the internal pointer to see if Session is enabled."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T14:58:51.477",
"Id": "47586",
"Score": "0",
"body": "@DarylGill and that is wrong. It create overhead. Your get function is also initializing the session... And everytime you call the get function the if is evaluated creating massive overhead. What if I have multiple sessions using session_name()?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T15:00:28.453",
"Id": "47587",
"Score": "0",
"body": "I also added a link to a good standard to use when writing code"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T13:14:45.953",
"Id": "29991",
"ParentId": "29851",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29864",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T14:30:57.007",
"Id": "29851",
"Score": "2",
"Tags": [
"php"
],
"Title": "Are the returns within my session function actually needed?"
}
|
29851
|
<p>I am a student, and I am doing websites as freelancer. Lately I have started learning design patterns, refactoring, and test-driven development so that I can improve the maintainability, performance, and readability of my code.</p>
<p>I did some refactoring with method extracting in this case, but I got feedback that my code is trash.</p>
<p>Here is the main method. The whole <code>Program</code> class is on <a href="https://github.com/nukec/string-calculator/blob/088102341ad2f20b716be9fbc4b4f321b4e111ba/Program.cs" rel="nofollow">GitHub</a>.</p>
<pre><code>/* main functionality
*
* parameter: expression - accepts string parameter and parses him, so it can calculate
*/
static double ParseCalculationString(string expression)
{
// currentNumberString will save current number
string currentNumberString = "";
// temporaryNumberString will be used for multiply/divide operations
string temporaryNumberString = "";
// we use this to access previous operator for calculating between numbers
char previousOperator = ' ';
// we use this for current operator that we get from from expression[i]
char currentOperator = ' ';
/* this is used for sum and subtract operations, we save operator and number here
so we can finish multiply and divide operations first, then we use number on hold
and operator on hold to add or deduct to total result. */
string numberOnHold = "";
char operatorOnHold = ' ';
/* total is used for saving total result, and currentNumberDouble for saving the number
* in the middle of multiply/divide operations */
double total = 0.0;
double currentNumberDouble = 0.0;
/* We use this two flags for marking the operation type, so we know what to calculate first */
bool flagMultiplyDivide = false;
bool flagSumSubtract = false;
int i;
for (i = 0; i < expression.Length; i++)
{
// checking if character is number, if yes we build number from the string until the character is symbol
if (char.IsNumber(expression[i]))
{
currentNumberString = currentNumberString + expression[i];
}
// I only wanted to limit to 4 symbols in this case, so I checked if current input character is * or / or - or +
else if (ValidateOperator(expression[i]))
{
currentOperator = expression[i];
// we jump into this condition if operator between two numbers is * or /
if (flagMultiplyDivide)
{
// if we multiply
if (previousOperator.Equals('*'))
{
currentNumberDouble = MultiplyNumbers(currentNumberString, temporaryNumberString);
}
// if we divide
else if (previousOperator.Equals('/'))
{
currentNumberDouble = DivideNumbers(temporaryNumberString, currentNumberString);
}
/* we have to use this condition if there is no more * or / operators after this number, therefore we can add our
multiply/divide result to total result*/
if (operatorOnHold.Equals('-') && (!currentOperator.Equals('*') && !currentOperator.Equals('/')))
{
total -= currentNumberDouble;
currentNumberDouble = 0.0;
}
else if (operatorOnHold.Equals('+') && (!currentOperator.Equals('*') && !currentOperator.Equals('/')))
{
total += currentNumberDouble;
currentNumberDouble = 0.0;
}
currentNumberString = "";
flagMultiplyDivide = false;
}
// we jump into this condition if operator between two numbers is + or -
else if (flagSumSubtract)
{
// if current operator is not * or / we can safely sum or subtract to total result(order of operations rule)
if (!currentOperator.Equals('*') && !currentOperator.Equals('/'))
{
if (operatorOnHold.Equals('+'))
{
total = ApplyNumberOnHold(total, numberOnHold, currentNumberString, true);
}
else if (operatorOnHold.Equals('-'))
{
total = ApplyNumberOnHold(total, numberOnHold, currentNumberString, false);
}
numberOnHold = "";
currentNumberString = "";
flagSumSubtract = false;
}
}
/* checking the current operators and setting the variables */
// multiply and divide operations
if (currentOperator.Equals('*') || currentOperator.Equals('/'))
{
// in case we have multiple consecutive multiply/divide operations 5*5*5*5
if (!currentNumberDouble.Equals(0.0))
{
currentNumberString = Convert.ToString(currentNumberDouble);
}
/* in case there is number and - or + after the number we can add it directly to total result
example for this: 5-5*5, which means that even if current operator is to multiply, we can safely
add or deduct our 5 to total result */
if (!numberOnHold.Equals(""))
{
total += Convert.ToDouble(numberOnHold);
numberOnHold = "";
}
temporaryNumberString = currentNumberString;
flagMultiplyDivide = true;
flagSumSubtract = false;
}
// sum and subtract operations
else if (currentOperator.Equals('+') || currentOperator.Equals('-'))
{
// used when checking, if previous operation was multiply/divide, so he can add result of that operation to total result
if (!currentNumberDouble.Equals(0.0))
{
if (operatorOnHold.Equals('-'))
total -= currentNumberDouble;
else
total += currentNumberDouble;
currentNumberDouble = 0.0;
}
// if we have consecutive add/subtract operations we directly add them to total result
if (!numberOnHold.Equals(""))
{
if (operatorOnHold.Equals('-'))
{
total -= Convert.ToDouble(numberOnHold);
}
else
{
total += Convert.ToDouble(numberOnHold);
}
}
numberOnHold = currentNumberString;
operatorOnHold = currentOperator;
flagSumSubtract = true;
flagMultiplyDivide = false;
}
currentNumberString = "";
previousOperator = currentOperator;
}
}
// if it is last character number, we have to check it after loop ends, because we can't loop no more
if (flagMultiplyDivide)
{
if (previousOperator.Equals('*'))
{
currentNumberDouble = MultiplyNumbers(currentNumberString, temporaryNumberString);
total = ApplyOperatorOnHold(operatorOnHold, total, currentNumberDouble);
}
else if (previousOperator.Equals('/'))
{
currentNumberDouble = DivideNumbers(temporaryNumberString, currentNumberString);
total = ApplyOperatorOnHold(operatorOnHold, total, currentNumberDouble);
}
}
else if (previousOperator.Equals('+'))
{
total = ApplyNumberOnHold(total, numberOnHold, currentNumberString, true);
}
else if (previousOperator.Equals('-'))
{
total = ApplyNumberOnHold(total, numberOnHold, currentNumberString, false);
}
return total;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:18:02.213",
"Id": "47287",
"Score": "3",
"body": "Well, you could try to write a unit test for it and see for yourself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T16:56:16.540",
"Id": "47303",
"Score": "0",
"body": "What do you mean? Aren't unit tests only to test inputs and outputs?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:18:07.573",
"Id": "47310",
"Score": "2",
"body": "Unit test should not test user interaction at all. Unit tests are to test \"units\", which typically means classes and/or functions. A single unit test is meant to test one aspect of the unit under test. For example, that a given function acts in a given way given a specific precondition and input. With such an extensive function, it would be impossible to achieve satisfactory code coverage and reliable results. Also, your function has incredibly high [Cyclomatic Complexity](http://en.wikipedia.org/wiki/Cyclomatic_complexity)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T22:02:41.163",
"Id": "47415",
"Score": "0",
"body": "Please read this: http://www.antiifcampaign.com/"
}
] |
[
{
"body": "<p>In general comments should be used to say <strong>why</strong> you are doing something, not <strong>what</strong> you are doing. You should strive to have variable names that describe what they contain.</p>\n\n<p>Don't be scared to create sub-functions. If you feel like you need to explain what a block of code is doing, there is a chance that block can be turned into a separate function. Now you can give the new function a descriptive name that will help explain what is being done. This will also help people from getting lost in the number of nested if blocks.</p>\n\n<p>Define constants for your operators, possible make them an enum since they form a logical grouping. It will also make it easier to find places where you use the constants. Otherwise you have to do a text search for <code>+</code> and will end up finding places where that is used in the code and not as a parsing operator. Another benefit of defining constants is to avoid <a href=\"http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants\">magic numbers</a>. This is not something you are doing here, but is related to the same idea. It is a good practice to get into for values that contain a special meaning.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:25:31.163",
"Id": "29856",
"ParentId": "29855",
"Score": "6"
}
},
{
"body": "<p>Good use of descriptive variable and function names. I'd like to see the index 'i' tell me more about what it is indexing.</p>\n\n<p>Good comments on the intention of each little chunk. I'd almost like to see some of the chunks broken out into little functions themselves and named appropriately, but the way you have it is good too, for now.</p>\n\n<p>A bit too much comments on the reason for each variable at the beginning. It should be crystal clear in the variable name and perhaps a bit of comment explanation on the intent when the variable is actually used.</p>\n\n<p>FWIW, if it WORKS, I'd add it to production as is. It's a good start and shows discipline, but the real test is when things start breaking or people want changes. Can you maintain that methodical, clear variables naming and clear intent commenting under pressure and under what are inevitably strange requests from the end user?</p>\n\n<p>PS</p>\n\n<p>Another factor to keep in mind is how to identify where your code is brittle. Where are you going to get null reference exception, where are you going to get index out of range, numerical overflow, where are your floating point comparisons going to fail because of floating point non determinism. These things come with experience, but you can get a head start by taking a conscious deliberate approach to finding frail and error prone lines.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:36:45.557",
"Id": "29857",
"ParentId": "29855",
"Score": "2"
}
},
{
"body": "<p><strong>Comments</strong>\nAs per one of the previous answers, I'm a big fan of commenting only what the code <em>cannot say</em>, not simply what it <em>does not say</em>.</p>\n\n<p>With this in mind, I'd say most of your comments could come out and be replaced with either nothing (when the intent is obvious) or with an encapsulation into a method.</p>\n\n<p><strong>Code structure</strong>\nIt feels very functional/linear at the moment - I feel that you could gain something here by encapsulation into a 'Calculator' class - you would find the overall flow of this method would be delegated over to that class and it would become responsible for it's own data.</p>\n\n<p><strong>Random stuff</strong>\n The main method body in ParseCalculationString makes this class difficult to trace through (I suspect I could debug through it to validate it far more easily) which adds fuel to the 'use smaller methods, break tasks out whenever possible explaining exactly what that method is doing'.\nVariable naming - it's not always clear on the intent of your variables - 'numberOnHold' is one of those where I'm clearer once I've read the comment.\nI like your use of guard clauses on your inputs up front, nicely done</p>\n\n<p>Only real issue in all of this feels like 'ParseCalculationString' (which although a complex task feels like it could be broken down as highlighted either into a 'Calculator' class or into sub methods to make that overall method flow better.</p>\n\n<p>Hope that helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T20:55:21.320",
"Id": "29896",
"ParentId": "29855",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29856",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:05:59.640",
"Id": "29855",
"Score": "3",
"Tags": [
"c#",
"math-expression-eval"
],
"Title": "Parser for an arithmetic expression"
}
|
29855
|
<p>This function is simple, it gets a number of bytes and returns its representation in either Bytes, KB, MB, GB and TB.</p>
<p>As simple as it is, I am sure there are other (and perhaps better ways) to write it.</p>
<pre><code>function kmgtbytes (num) {
if (num > 0 ){
if (num < 1024) { return [num, "Bytes"] }
if (num < 1048576) { return [num/1024, "KB"] }
if (num < 1073741824) { return [num/1024/1024, "MB"] }
if (num < 1099511600000) { return [num/1024/1024/1024, "GB"] }
return [num/1024/1024/1024/1024, "TB"]
}
return num
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:12:40.960",
"Id": "47308",
"Score": "3",
"body": "Your primary concern should be the clarity of your code. minitech's answer is sweet and terse, yet your code requires little thought to discern its function. Both of you should add comments to your code indicating its purpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:29:00.837",
"Id": "47317",
"Score": "7",
"body": "[jsPerf for all current answers](http://jsperf.com/size-suffix)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:55:17.267",
"Id": "47324",
"Score": "0",
"body": "And yes, I think yours is the clearest! It’s also not right, though, as 1099511600000 < 1024^4."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T18:00:37.907",
"Id": "47325",
"Score": "2",
"body": "Having your function return a different type as the default will probably cause type errors everywhere"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T21:02:43.120",
"Id": "47347",
"Score": "2",
"body": "This function lacks only a better name and an introductory comment (incl. examples of possible outputs). I haven't managed to come up with either, by the way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T04:51:08.113",
"Id": "47361",
"Score": "0",
"body": "@minitech I added another function, http://jsperf.com/size-suffix/3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T12:10:29.703",
"Id": "47390",
"Score": "2",
"body": "You may find reading how [others have done it in the past](http://git.savannah.gnu.org/cgit/gnulib.git/tree/lib/human.c) enlightening."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T12:55:50.300",
"Id": "47447",
"Score": "1",
"body": "As @Eric mentions, the only thing I'd really change would be to remove the `if` and the `return num`. It makes more sense to return `[0, \"Bytes\"]` for an input of `0`, and presumably you don't care about the result for negative values."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T13:25:28.517",
"Id": "47651",
"Score": "0",
"body": "@kojiro: you've got to be kidding (although it makes a good history lesson -- uses `go to` statements and everything!)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T15:32:59.250",
"Id": "47659",
"Score": "0",
"body": "@SamGoldberg kidding? no. Did I think he should emulate a C lib in JS? Also no. History is for learning from, not copying verbatim. (That's why I made it a comment and didn't integrate it into an answer.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T06:20:05.507",
"Id": "47823",
"Score": "0",
"body": "Consider doubling the thresholds, such that valid outputs include \"5 Bytes\", \"1024 Bytes\", \"2000 Bytes\", \"2047 Bytes\", \"2 kiB\" (for 2048 ≤ *num* < 3072), etc. Due to [Benford's Law](http://en.wikipedia.org/wiki/Benford's_law), a disproportionate number of files are likely to be reported as \"1 kiB\", so it would be nice to provide more precision. Also, consider using [IEC](http://en.wikipedia.org/wiki/Binary_prefix) instead of SI binary prefixes to be more explicit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-27T14:11:53.993",
"Id": "48165",
"Score": "2",
"body": "I actually like the proposed question better than any proposed solution. The function is simple, clear and indicative of its internal logic with just a glance. My only suggestion would be to replace the literals with their composition for a quick indication of what they mean. This is, instead of `1048576` I would write `1024*1024` and so on. Perhaps throwing an exception if `num < 0`?"
}
] |
[
{
"body": "<p>I'd use a while loop, divide by 1024 and keep track of how many times you divided.</p>\n\n<p>This is my completely bonkers function:</p>\n\n<pre><code>function resolve_to_power_of(bytes, power) {\n var powers;\n powers = 0;\n while (bytes >= power) {\n powers += 1;\n bytes = bytes / power;\n }\n return {\n quantity: bytes,\n powers: powers\n };\n}\n\nfunction format_default(bytes) {\n var resolved, descriptors;\n resolved = resolve_to_power_of(bytes, 1024);\n descriptors = [ \"B\", \"KB\", \"MB\", \"TB\", \"GB\", \"PB\", \"EB\", \"ZB\", \"YB\" ];\n return Math.ceil(resolved.quantity) + \" \" + descriptors[resolved.powers];\n}\n\nformat_default(1024); // 1 KB\nformat_default(1000); // 1000 B\nformat_default(102400); // 100 KB\n</code></pre>\n\n<p>The reason it's set up like this is because it also supports dividing by <code>1000</code> and other byte lables like <code>[ \"B\", \"K\", \"M\" .. ]</code> etc. following IEC and SI standards.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:56:20.140",
"Id": "47294",
"Score": "0",
"body": "why while loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:59:33.963",
"Id": "47297",
"Score": "2",
"body": "Because it makes the most sense: keep dividing _while_ the number is larger than or equal to 1024."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T16:03:16.270",
"Id": "47298",
"Score": "0",
"body": "You can use `++` and `/=` and `var powers = 0;`, if you’re not against that sort of formatting. (I’d do `/=`, though.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:26:46.717",
"Id": "47315",
"Score": "0",
"body": "@minitech, it's good practice to separate variable declaration and instantiation in JavaScript. Scripts should generally be written as with an order of: variable declaration, function declaration, initialization, execution. Doing this the more verbose way helps avoid some variable hoisting issues, and some initialization ordering issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:29:35.557",
"Id": "47318",
"Score": "0",
"body": "@zzzzBov: I don’t agree with that at all, but I did add “if you’re not against that sort of formatting”."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T19:06:41.790",
"Id": "47334",
"Score": "1",
"body": "@minitech My coding style aims to increase readability, extensibility and maintainability and decrease the chance of errors. This code passes JSLint checks. Nick's solution is very clever, it uses only 6 lines. I also had to read it twice to make sure there is no off-by-one error. It has the most upvotes because we measure code quality by the least number of characters and best use of obscure functions. /sarcasm. If I found this code in one of my applications I would ask him to rewrite it."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:47:56.947",
"Id": "29861",
"ParentId": "29858",
"Score": "2"
}
},
{
"body": "<p>Here's a slightly less repetitive way to write it since we know each unit is 1024 as large as the last:</p>\n\n<pre><code>function kmgtbytes (num) {\n var unit, units = [\"TB\", \"GB\", \"MB\", \"KB\", \"Bytes\"];\n for (unit = units.pop(); units.length && num >= 1024; unit = units.pop()) {\n num /= 1024;\n }\n return [num, unit];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T12:45:34.373",
"Id": "47445",
"Score": "0",
"body": "I'll admit that using `pop()` is a little inefficient as you're creating and mutating the array of units on every call. Whether this is actually a problem depends on how often you expect to be calling this function, and your definition of \"better\" as used in the question :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-19T13:46:55.670",
"Id": "109510",
"Score": "0",
"body": "Why is the result of this function an array? Very surprising."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:51:52.913",
"Id": "29862",
"ParentId": "29858",
"Score": "15"
}
},
{
"body": "<p>You can use logarithms:</p>\n\n<pre><code>var sizes = [\"bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n\nfunction formatSize(bytes) {\n var l = Math.min(sizes.length - 1, Math.log(bytes) / Math.LN2 / 10 | 0);\n return [bytes / Math.pow(1024, l), sizes[l]];\n}\n</code></pre>\n\n<p>The confusing part, <code>Math.log(bytes) / Math.LN2 / 10 | 0</code>, gets the base-1024 logarithm of <code>bytes</code> and truncates it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:57:31.257",
"Id": "47295",
"Score": "0",
"body": "The use of logarithm is a wise one!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:17:33.240",
"Id": "47309",
"Score": "2",
"body": "Excessive use of floating point is icky for my taste, and also likely to perform worse."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:18:54.117",
"Id": "47311",
"Score": "1",
"body": "@200_success: You can’t avoid floating-point here. 1024^4 > 2^32. Apart from that, “once, which forms the crux of this shortcut” is difficult to avoid :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:22:11.383",
"Id": "47314",
"Score": "1",
"body": "No doubt, the problem itself requires floating point, as the return value is FP. It's the `Math.log()` that I find excessive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:35:50.227",
"Id": "47319",
"Score": "2",
"body": "@200_success: This is the fastest answer so far on Firefox 23.0, for what it’s worth. (Which is not very much.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:36:12.197",
"Id": "47320",
"Score": "0",
"body": "This works, and it appears to be sound, but it is much less expressive than the original. I inherently mistrust overly clever code because, as Brian Kernighan said, \"Everyone knows that debugging is twice as hard as writing a program in the first place. So if you're as clever as you can be when you write it, how will you ever debug it?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:37:15.730",
"Id": "47322",
"Score": "0",
"body": "With that said, when you're optimizing performance, being clever can be very helpful, just be sure to write up enough unit tests to have reasonably good coverage."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:52:08.597",
"Id": "29863",
"ParentId": "29858",
"Score": "11"
}
},
{
"body": "<p>I will discuss 2 points to your code: Readability/Cleanliness and Robustness</p>\n\n<p>From the Readability/Cleanliness perspective I'd argue that your code is the easiest to read vs any answer you've received thus far. I knew in 3 seconds the purpose of all of that code and wouldn't need any comments to further explain it. </p>\n\n<p>From the robustness perspective it all boils down to the use case of the code. If you know without a doubt that you will only ever see positive sized numbers <1024 TB I'd say again your code is fine. If you wanted to handle file size differences (as in 100kb-150kb = -50kb) or file sizes beyond 1023TB then clearly you need to enhance your approach. </p>\n\n<p>To handle the more general case this question has already been answered here as well: <a href=\"https://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net/4975942#4975942\">https://stackoverflow.com/questions/281640/how-do-i-get-a-human-readable-file-size-in-bytes-abbreviation-using-net/4975942#4975942</a> </p>\n\n<p>As a side note it would appear size=0 would return [0,] but size of 1 would return [1,Bytes]. You may want to return [0,Bytes]</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:52:56.487",
"Id": "29870",
"ParentId": "29858",
"Score": "9"
}
},
{
"body": "<p>How about recursion? (<a href=\"http://jsfiddle.net/WhhCL/1/\" rel=\"nofollow\">http://jsfiddle.net/WhhCL/1/</a>)</p>\n\n<pre><code>var units = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n\nfunction unitize(num) {\n return unitizer(num, 0);\n}\n\nfunction unitizer(num, level) {\n if (num < 1024 || level > units.length - 1) {\n return num + \" \" + units[level];\n } else {\n return unitizer(num / 1024, level + 1);\n }\n}\n</code></pre>\n\n<p>The readability of your original function is tough to beat. At least for now, it's also the most performant of the bunch. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T22:04:04.960",
"Id": "29877",
"ParentId": "29858",
"Score": "3"
}
},
{
"body": "<p>What about:</p>\n\n<pre><code>var units=[\"Byte\",\"KB\",\"MB\",\"GB\",\"TB\",\"PB\"];\n\nfunction getUnit(bytes){\n for(var i of units){\n if(bytes<1024) return bytes+\" \"+units[i];\n bytes/=1024;\n }\n}\n</code></pre>\n\n<p>Edit:</p>\n\n<p>It prevents you from precalculating your values for each if-clause. It's easily extensible: Just add another unit, wherever you want. And for the rest: it does its job in an easy understandable way. No rocket science.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T05:19:15.730",
"Id": "47362",
"Score": "2",
"body": "Please don’t use `for…in` loops to iterate arrays. It’s darn slow and not necessarily accurate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T17:02:20.630",
"Id": "47398",
"Score": "2",
"body": "Optimizing this loop is barking up the wrong tree, even if it were slow. If that's the only \"bottleneck\" in your code, everything is okay I would say."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T06:11:39.963",
"Id": "47822",
"Score": "2",
"body": "Yes, but a `for...in` loop isn't guaranteed to execute in order. More reading [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-08-16T23:15:14.590",
"Id": "29879",
"ParentId": "29858",
"Score": "12"
}
},
{
"body": "<p>You can loop through the thousands until the number is small enough, then just return the remaining number and the corresponding unit:</p>\n\n<pre><code>function kmgtbytes(num) {\n for (var i = 0; num >= 1024 && i < 4; i++) num /= 1024;\n return [num, [\"Bytes\",\"kB\",\"MB\",\"GB\",\"TB\"][i]];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T23:52:42.263",
"Id": "29900",
"ParentId": "29858",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:40:35.263",
"Id": "29858",
"Score": "18",
"Tags": [
"javascript"
],
"Title": "Dealing with KB, MB, GB and TB and bytes"
}
|
29858
|
<p>I am trying to simplify the amount of code required here using arrays, I feel like my foreach loop is still excessively long. Any advice would be appreciated.</p>
<pre><code>$date_list = Array(
Array( 'age', "$birthday", 'now' ),
Array( 'membership', "$datejoined", 'now' ),
Array( 'promoted', "$lastpromo", 'now' ),
);
foreach ( $date_list as $date_set ) {
$var = $date_set[0];
$start = $date_set[1];
$end = $date_set[2];
$datetime1 = date_create($start);
$datetime2 = date_create($end);
$interval = date_diff($datetime1, $datetime2);
if ( substr_count( $var, 'age' ) > 0 ){
$age = $interval->format('%y');
}
elseif ( substr_count( $var, 'membership' ) > 0 ){
$years = $interval->format('%y');
$months = $interval->format('%m');
$membership = floor(($years*12)+$months);
if($membership > 1){
$suffix = 'Months';
}
elseif($membership == 1){
$suffix = 'Month';
}
else{
$membership = "< 1";
$suffix = 'Month';
}
}
elseif ( substr_count( $var, 'promoted' ) > 0 ){
$years = $interval->format('%y');
$months = $interval->format('%m');
$test = $interval->format('%a');
$promoted = floor(($years*12)+$months);
if($promoted > 1){
$suffix = 'Months ago';
}
elseif($promoted == 1){
$suffix = 'Month ago';
}
else{
$promoted = "< 1";
$suffix = 'ago';
}
}
</code></pre>
<p>}</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T23:30:03.703",
"Id": "47352",
"Score": "0",
"body": "Ugh. Firstly, use switch statements. Why are you using substr_count when you could use switch? You put the data there, you know it is clean. If this is just test code and in reality it would have input from elsewhere, just clean it up either before you put it into the array or after you extract it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T23:33:41.810",
"Id": "47353",
"Score": "0",
"body": "Secondly, your question is ambiguous. Do you mean that you tried to use arrays to improve the code, but need advice on how to complete that, or that you want to improve this code, which just happens to use arrays? If you can be clearer about this, and about why you are using arrays, that will help"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T23:37:59.967",
"Id": "47354",
"Score": "0",
"body": "Finally, a little more context for this code snippet would help."
}
] |
[
{
"body": "<p>It's hard to suggest simplifications without a greater understanding of the problem being solved. However, this is perhaps a bit more readable:</p>\n\n<pre><code>$dates = array(\n array('type' => 'age', 'start' => $birthday, 'stop' => 'now' ),\n array('type' => 'membership', 'start' => $datejoined, 'stop' => 'now' ),\n array('type' => 'promoted', 'start' => $lastpromo, 'stop' => 'now' ),\n);\n\nforeach($dates as $date)\n{\n $start = date_create($date['start']);\n $stop = date_create($date['stop']);\n $interval = date_diff($start, $stop);\n\n switch($date['type'])\n {\n case 'age':\n $age = $interval->format('%y');\n break;\n\n case 'membership':\n $years = $interval->format('%y');\n $months = $interval->format('%m');\n $membership = floor(($years*12)+$months);\n\n if($membership > 1) { $suffix = 'Months'; }\n if($membership == 1) { $suffix = 'Month'; }\n if($membership < 1) { $suffix = 'Month'; $membership = '< 1'; }\n break;\n\n case 'prompted':\n $years = $interval->format('%y');\n $months = $interval->format('%m');\n $test = $interval->format('%a');\n $promoted = floor(($years*12)+$months);\n\n if ($promoted > 1) { $suffix = 'Months ago'; }\n if ($promoted == 0) { $suffix = 'Month ago'; }\n if ($promoted < 1) { $suffix = 'ago'; $promoted = '< 1'; }\n break;\n }\n}\n</code></pre>\n\n<p>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T20:17:39.230",
"Id": "29934",
"ParentId": "29859",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T15:43:09.573",
"Id": "29859",
"Score": "1",
"Tags": [
"php",
"array"
],
"Title": "Simplify code using array"
}
|
29859
|
<p>I have created this class for my WP theme. It allows you to create templates for a meta box which relates directly to a custom frontend template to have better control of the content displayed on the page.</p>
<p>So for example:</p>
<p>The meta box content file, which defines a "template":</p>
<pre><code>theme_folder/post-templates/templates/admin/print.php
</code></pre>
<p>The file would define variables containing information about the template:</p>
<pre><code><?php
/* Print Design Post Template */
global $post;
$this->templates[] = array(
'print' => array(
'admin_filepath' => basename(__FILE__),
'template_name' => 'Print Design Project',
'template_id' => 'print',
'frontend_file' => 'print-design.php'
)
);
if( self::TEMPLATE_PARSER ) return;
$data = $this->_getLayoutData($post->ID);
?>
<p>
<label>Test Field</label>
<input type="text" name="brave_template_data[test_field]" value="<?php echo $data['test_field']; ?>" />
</p>
<p>
<label>Test Field 2</label>
<input type="text" name="brave_template_data[test_field_2]" value="<?php echo $data['test_field_2']; ?>" />
</p>
<p>
<label>Test Field 3</label>
<input type="text" name="brave_template_data[test_field_3]" value="<?php echo $data['test_field_3']; ?>" />
</p>
</code></pre>
<p>Here's the front end file which would look pretty much the same as a normal WP template file:</p>
<pre><code> <?php
global $brave_templater,$post;
get_header(); ?>
Custom Print Template
<?php var_dump($brave_templater->_getLayoutData($post->ID)); ?>
<?php get_footer(); ?>
</code></pre>
<p>The engine file: </p>
<pre><code><?php
class Brave_Post_Templates {
var $body_class;
var $templates = array();
var $enabled_post_types = array('portfolio');
const FRONTEND_THEMES ='post-templates/templates/frontend';
const ADMIN_THEMES = 'post-templates/templates/admin';
const TEMPLATE_PARSER = false;
/**
* Attach WP Action Hooks
*/
public function __construct() {
// Load Templates
$this->_getAvailableTemplates();
// Meta Box Hooks
add_action('admin_menu', array( $this, 'add_meta_boxes' ) );
add_action('save_post', array( $this, 'save_meta_box_content' ));
// Frontend Template Redirect
add_action('template_redirect', array($this, '_interceptTemplateDisplay'));
// AJAX
add_action('wp_ajax_braveGetMetaBoxContent', array( $this, 'ajax_braveGetMetaBoxContent' ));
add_action('wp_ajax_nopriv_braveGetMetaBoxContent', array( $this, 'ajax_braveGetMetaBoxContent' ));
}
/**
* _interceptTemplateDisplay
*
* Load custom template file if one is set.
*
*/
public function _interceptTemplateDisplay() {
global $post;
if( $post && in_array($post->post_type, $this->enabled_post_types) ) {
if($this->hasPostTemplate($post->ID)) {
$this->_loadFrontEndTemplate($this->_getTemplate($post->ID));
}
}
}
/**
* _addPostTypeSupport
*
* Add post type support for custom templates.
*
*/
public function _addPostTypeSupport($post_type) {
return $this->enabled_post_types[] = $post_type;
}
/*
* Add Meta Boxes for Custom Fields
*/
public function add_meta_boxes() {
foreach($this->enabled_post_types as $post_type) {
add_meta_box($post_type.'-meta-box-settings', 'Template Settings', array($this,'meta_box_content'), $post_type, 'normal', 'high');
}
}
/*
* Meta Box Content
*/
public function meta_box_content() {
global $post;
?>
<div id="brave_post_templates">
<p>
<label><strong>Template:</strong></label>
<select name="brave_post_template" id="brave_post_template_select">
<?php if(!$this->hasPostTemplate($post->ID)): ?>
<option value="default" selected="selected">Default Post Type Template (single-<?php echo $post->post_type; ?>.php)</option>
<?php else: ?>
<option value="default">Default Post Type Template (single-<?php echo $post->post_type; ?>.php)</option>
<?php endif; ?>
<?php if( count($this->_getTemplates()) > 0 ): ?>
<?php foreach($this->_getTemplates() as $templates): ?>
<?php foreach($templates as $template): ?>
<option value="<?php echo $template['template_id']; ?>" <?php selected($template['template_id'], $this->_getTemplate($post->ID)); ?>><?php echo $template['template_name']; ?> (<?php echo $template['frontend_file']; ?>)</option>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
</select>
</p>
<div class="brave_post_template_meta_box_content">
<?php if($this->hasPostTemplate($post->ID)): ?>
<?php echo $this->_loadAdminMetaBoxTemplate($this->_getTemplate($post->ID)); ?>
<?php else: ?>
<p>No custom template selected, please choose a template above.</p>
<?php endif; ?>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
var brave_templater_select = jQuery('#brave_post_template_select');
var brave_templater_container = jQuery('.brave_post_template_meta_box_content');
brave_templater_select.change(function(){
var template_id = this.value;
if(template_id == 'default') {
brave_templater_container.html('<p>No custom template selected, please choose a template above.</p>');
return false;
}
var data = {
action: 'braveGetMetaBoxContent',
template_id: template_id,
post_id: '<?php echo $post->ID; ?>'
};
jQuery.post('<?php echo admin_url('admin-ajax.php'); ?>', data, function(response) {
brave_templater_container.fadeOut(100, function(){
jQuery(this).empty().html(response).fadeIn(100);
});
});
});
});
</script>
</div>
<?php
}
/*
* Save Meta Box Custom Fields
*/
public function save_meta_box_content($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return $post_id;
}
if ( in_array($_POST['post_type'], $this->enabled_post_types) ) {
if (!current_user_can('edit_page', $post_id)) {
return $post_id;
} else {
$post_template = $_POST['brave_post_template'];
$data = $_POST['brave_template_data'];
update_post_meta($post_id, 'brave_post_template', $post_template);
if($data) {
update_post_meta($post_id, 'brave_template_data', serialize($data));
}
}
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
}
/**
* _getTemplate
*
* Get current custom template.
*
*/
public function _getTemplate($post_id) {
return get_post_meta($post_id, 'brave_post_template', true);
}
/**
* hasPostTemplate
*
* Check to see if a custom template has been set.
*
*/
public function hasPostTemplate($post_id) {
$template = get_post_meta($post_id, 'brave_post_template', true);
if( $template && $template != 'default' ) return true;
return false;
}
/**
* _getAvailableTemplates
*
* Populates self::templates (array) with available templates found.
*
*/
public function _getAvailableTemplates() {
self::TEMPLATE_PARSER == true;
$path = BRAVE_LIB . self::ADMIN_THEMES;
$dir = glob($path.'/*.php');
foreach( $dir as $file) {
ob_start();
include_once($file);
$file = ob_get_contents();
ob_end_clean();
}
return $this;
}
/**
* _getTemplates
*
* Returns self::templates (array)
*
*/
public function _getTemplates() {
return $this->templates;
}
/**
* _loadAdminMetaBoxTemplate
*
* Loads Meta Box HTML based on template.
*
*/
public function _loadAdminMetaBoxTemplate($template_id) {
self::TEMPLATE_PARSER == false;
foreach($this->_getTemplates() as $template) {
$file = BRAVE_LIB . self::ADMIN_THEMES . '/' . $template[$template_id]['admin_filepath'];
if( array_key_exists($template_id, $template) && file_exists($file) ) {
require($file);
}
}
return false;
}
/*
* Load Meta Box Content with AJAX
*/
public function ajax_braveGetMetaBoxContent() {
global $post;
$post->ID = $_POST['post_id'];
$template_id = $_POST['template_id'];
self::TEMPLATE_PARSER == false;
foreach($this->_getTemplates() as $template) {
$file = BRAVE_LIB . self::ADMIN_THEMES . '/' . $template[$template_id]['admin_filepath'];
if( array_key_exists($template_id, $template) && file_exists($file) ) {
$file = file_get_contents($file);
$file = preg_replace('/<?php/', '', $file, 1);
eval('?>'.$file);
die(1);
}
}
}
/**
* _loadFrontEndTemplate
*
* Loads frontend template.
*
*/
public function _loadFrontEndTemplate($template_id) {
foreach($this->_getTemplates() as $template) {
$file = BRAVE_LIB . self::FRONTEND_THEMES . '/' . $template[$template_id]['frontend_file'];
if( array_key_exists($template_id, $template) && file_exists($file) ) {
$this->body_class = 'brave-post-template-'.$template_id;
add_filter('body_class', array($this,'addPostBodyClasses'));
require($file);
exit;
} else {
wp_die('Invalid Template ID or Template file is missing.');
}
}
}
/**
* addPostBodyClasses
*
* Add body class for current template.
*
*/
public function addPostBodyClasses($classes) {
$classes[] = $this->body_class;
return $classes;
}
/**
* _getLayoutData
*
* Gets custom field data for key: brave_template_data to be used on the frontend.
*
*/
public function _getLayoutData($post_id) {
return unserialize(get_post_meta($post_id, 'brave_template_data', true));
}
}
</code></pre>
<p>I was just wondering if this is a good attempt, as I am not a proflific PHP programmer and I have never had an opinion on my code really!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T13:41:15.850",
"Id": "47853",
"Score": "0",
"body": "Your code is very pretty and easy to read. Why do some methods begin with an underscore. Like, `_interceptTemplateDisplay`? I'm not complaining about it. Just curious."
}
] |
[
{
"body": "<p>The formatting is a little off to what is considered normal/good. <a href=\"http://framework.zend.com/manual/1.12/en/coding-standard.naming-conventions.html\" rel=\"nofollow\">It is widely accepted</a> that each word in a class name should have it's first letter capitalized. Function names are most commonly written in \"camelCase\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-20T11:26:54.440",
"Id": "88375",
"Score": "0",
"body": "http://make.wordpress.org/core/handbook/coding-standards/php/#naming-conventions"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-21T20:51:44.920",
"Id": "42464",
"ParentId": "29866",
"Score": "-2"
}
},
{
"body": "<p>Your code looks good, (although I did not review each particular) The only thing that stood out to me is that your files do not begin with a check to see if the file is being accessed directly. You should have a variable defined at the beginning of the theme that is checked for at the beginning of each other file, and if the variable is not defined, reject the access. There is a section about that here: <a href=\"https://www.wordfence.com/learn/how-to-write-secure-php-code/\" rel=\"nofollow\">https://www.wordfence.com/learn/how-to-write-secure-php-code/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-08-31T14:43:43.010",
"Id": "140128",
"ParentId": "29866",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:09:05.857",
"Id": "29866",
"Score": "6",
"Tags": [
"php",
"object-oriented",
"wordpress"
],
"Title": "WordPress Post Type template"
}
|
29866
|
<p>I have this code:</p>
<pre><code>for (int i = 0; i < lst.Count(); i++)
{
lst[i].ColumnOrder = (short)i;
}
</code></pre>
<p>But I was trying to find a way to do it via LINQ or something else with better performance. I'm pretty sure that there are better ways to change the sequence of a column. I use this code in a drag & drop context.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:21:46.700",
"Id": "47313",
"Score": "0",
"body": "I know it's kind silly question. But I really got curious about a better way to do it, and couldn't find anything on the web. **PS: The title looks a little weird for the context, but I'm not sure on how to put it, if someone have some idea please do so**"
}
] |
[
{
"body": "<p>You <em>can</em> use LINQ to do it, but that will end up as pretty ugly code. LINQ is used to process data and return a result, and that is not what you are doing here, so using LINQ for this would only mean that your code would produce a dummy result and have a side effect doing so.</p>\n\n<p>Well, for completeness, here is some <em>ugly</em> code that misuses LINQ extension methods to loop through the items:</p>\n\n<pre><code>lst.Select((item, i) => item.ColumnOrder = (short)i).Last();\n</code></pre>\n\n<p>(Note the <code>Last</code> call that is used to pull the result out of the expression, so that it actually loops through the items. Even if you don't use the result, you still have to loop through the entire result to make it complete the loop.)</p>\n\n<p>Your original code is just the simplest way to do it (except for the use of <code>Count()</code> instead of <code>Count</code> as svick mentioned), and is likely to give the best possible performance. There are other alternatives of course that gives almost the same performance. You can use an enumerator to loop through the items, but then you still need a counter for the column order:</p>\n\n<pre><code>int i = 0;\nforeach (var item in lst) {\n item.ColumnOrder = (short)(i++);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T18:20:21.127",
"Id": "29871",
"ParentId": "29867",
"Score": "5"
}
},
{
"body": "<p>Let's have a look at some common ways to improve collection-related code:</p>\n\n<ol>\n<li>Use LINQ. LINQ is not a good fit here, because you're modifying the collection. LINQ is good for querying, but that's not what you're doing.</li>\n<li>Use <code>foreach</code> instead of <code>for</code>. That wouldn't be a good idea here either, because you do need the index.</li>\n</ol>\n\n<p>So, this means your approach is the right one in general. But there are some smaller things I would change about your code:</p>\n\n<ol>\n<li>Use the <code>Count</code> property instead of the <code>Count()</code> extension method.</li>\n<li>Change the type of <code>i</code> to <code>short</code> to avoid the cast. (If there was more than short.MaxValue (32767) items in the collection, this would cause a somewhat confusing <code>ArgumentOutOfRangeException</code> instead of <code>InvalidCastException</code>, but I think that's not a big issue.)</li>\n<li>Use a better variable name than <code>lst</code>. <code>lst</code> doesn't tell you anything about the contents of the list and shortening variable names like this is a bad idea (especially if you save just one character). The important part is what does the variable contain (columns, or something like that), not that it's <code>List<T></code>, so that's what should decide how is the variable named.</li>\n</ol>\n\n<p>With that, the code would look something like this:</p>\n\n<pre><code>for (short i = 0; i < columns.Count; i++)\n{\n columns[i].ColumnOrder = i;\n}\n</code></pre>\n\n<blockquote>\n <p>But I was trying to find […] something else with better performance.</p>\n</blockquote>\n\n<p>You're not going to find that, <code>for</code> loop has pretty much the best possible performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T18:28:35.790",
"Id": "47328",
"Score": "1",
"body": "Good point about the `Count()` method, I missed that. Using a `short` for loop variable doesn't avoid all casting, as there will be an implicit cast when it is compared to the `int` value from the `Count` property."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T18:37:30.293",
"Id": "47331",
"Score": "0",
"body": "the lst was just to put it here on the question ^_^ thanks you for the tips and advises. I +1 [@Guffa's answer](http://codereview.stackexchange.com/a/29871/10869) because of the ++ that I forgot too (I can't start i with the value 1 because of the list position (that starts at 0))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:13:27.713",
"Id": "47341",
"Score": "0",
"body": "@Guffa Yeah, I primarily wanted to avoid explicit casting to have cleaner code. The only potential problem with that implicit cast is slight performance hit, but that's likely negligible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:37:38.807",
"Id": "47344",
"Score": "0",
"body": "@svick: Casting between basic value types is not expensive. It's possible that doing arithmetic on `short` values instead of `int` vaues has a bigger performance impact, but that is also a very small difference."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T18:22:02.400",
"Id": "29872",
"ParentId": "29867",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29872",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:21:05.027",
"Id": "29867",
"Score": "2",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Change one column data from List<>"
}
|
29867
|
<p>I wrote some type checking decorators for Python. One checks the type that a function returns, the other checks the type that a function accepts.</p>
<pre><code>import functools
def returns(t):
""" Calls a function, and if it returns something of the wrong type,
throws a TypeError
"""
def outer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
output = func(*args, **kwargs)
if not isinstance(output, t):
message = "function {} returned an invalid type: {} is a {}"
raise TypeError(message.format(func.__name__,
output,
type(output)))
else:
return output
return wrapper
return outer
class accepts:
def __init__(self, *artypes, **kwtypes):
""" Pass it a list consisting of types or tuples of types.
in other words, pass it things that will be valid second
arguments to the isinstance(arg, type) method.
"""
self.artypes = artypes
self.kwtypes = kwtypes
def checkTypes(self, args, kwargs):
""" Checks each arg and kwarg for type validity, and if
they fail, then it throws a TypeError. Not very descriptive,
but it's just an example.
"""
type_zip = zip(args, self.artypes)
for arg, type_ in type_zip:
if not isinstance(arg, type_):
raise ValueError()
for key, value in kwargs.items():
if not isinstance(value, self.kwtypes[key]):
raise ValueError()
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
self.checkTypes(args, kwargs)
return func(*args, **kwargs)
return wrapper
@accepts(int)
def hitimes(times=1):
return "hello " * times
@accepts(int, word=str)
def byetimes(times, word="bye"):
return " ".join([word] * times)
print(hitimes(2)) # works
print(byetimes(5)) # works
print(byetimes(3, word="adios")) # works as expected
print(byetimes(3, word=[])) # fails as expected
</code></pre>
<p>For <code>returns</code>, I used nested functions, and for accepts I used the class style of decorator. But both of them get pretty unwieldy with respect to indentation levels. What can I do to make these cleaner?</p>
<p>Note that the wrappers are themselves pretty pointless.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:00:59.283",
"Id": "47339",
"Score": "1",
"body": "`accepts` shouldn’t be a class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T06:48:40.100",
"Id": "47371",
"Score": "0",
"body": "@minitech why not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T15:28:35.443",
"Id": "47395",
"Score": "0",
"body": "What does it represent? You’re just using it for variables, which can be accomplished by using variables…"
}
] |
[
{
"body": "<p>I agree with @minitech that accepts shouldn't be a class. It can be written much more compactly using a nested decorator (like <code>returns</code>, in fact):</p>\n\n<pre><code>def accepts(*artypes, **kwtypes):\n \"\"\"\n Pass it a list consisting of types or tuples of types.\n in other words, pass it things that will be valid second\n arguments to the isinstance(arg, type) method.\n \"\"\"\n def outer(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n type_zip = zip(args, artypes)\n for arg, type_ in type_zip:\n if not isinstance(arg, type_):\n raise ValueError()\n\n for key, value in kwargs.items():\n if not isinstance(value, kwtypes[key]):\n raise ValueError()\n return func(*args, **kwargs)\n return wrapper\n return accepts_wrapper\n</code></pre>\n\n<p>This then works equivalently to <code>returns</code>, and is <em>much</em> shorter (as you need less variable-passing code).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-24T11:56:38.763",
"Id": "67800",
"ParentId": "29868",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "67800",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T17:27:56.283",
"Id": "29868",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "How do I clean up these Python decorators?"
}
|
29868
|
<p>I received help with adding the length of a stream in the first 4 bytes, meaning it's there as an <code>int</code>.</p>
<p>I am adding it at the start and sending it, while the receiving part checks for its position.</p>
<p>However, the position checking is a bit slow, so I wonder if it's possible to improve it. Maybe using unsafe pointers or something, but I'm not sure.</p>
<pre><code>currentPosition = 0;
while (currentPosition < sizeof(int) && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(lenArray, currentPosition, sizeof(int) - currentPosition);
}
</code></pre>
<p>There is the example on what it does at the end of the receiving part. It goes through it, and it's a bit slow. </p>
<p>I can't see much of what can be done here, but hopefully someone else has a better idea.</p>
<p>Here is the whole code, which may help show how it functions:</p>
<pre><code>tempBytes = new byte[length];
ms = new MemoryStream(tempBytes);
int currentPosition = 0;
while (currentPosition < length && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
}
newImage = Image.FromStream(ms);
gmp.DrawImage(newImage, 0, 0);
currentPosition = 0;
while (currentPosition < sizeof(int) && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(lenArray, currentPosition, sizeof(int) - currentPosition);
}
length = BitConverter.ToInt32(lenArray, 0);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:42:00.207",
"Id": "47345",
"Score": "0",
"body": "Any particular reason you don't want to open a `BinaryReader` on that stream? It'll take care of most of what you're looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:43:42.583",
"Id": "47346",
"Score": "0",
"body": "The reason is, i want to improve the speed over BinaryReader/Writer, in this case (i only send images). So trying everything there is:)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T21:25:55.570",
"Id": "47349",
"Score": "0",
"body": "Are you sure the length reading is what's slowing down your code? I think it's much more likely that it's reading from disk/network/whatever that's slowing you down and there's not much you can do about that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T21:44:57.547",
"Id": "47350",
"Score": "0",
"body": "Yes and no. It´s not Slowing it down, but it´s what takes up the most time Except the reading. For reading the data takes about 24ms in this scenario, and the count thing, takes 6-9ms. Not much, but it adds up. And i am trying to improve latency by any means. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-08T19:00:35.137",
"Id": "54747",
"Score": "0",
"body": "why does your last while loop go from `currentPosition` to `sizof(int)`? could you change that value to something smaller?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-09T02:13:00.447",
"Id": "54792",
"Score": "0",
"body": "Not sure right of the bat since i changed it a bit now. But i think it has to do with that the information it stored in the first 4 byte (size of int32) hence why i use it."
}
] |
[
{
"body": "<p>I agree with the comments that it's not likely to be your position checking code that's slowing you down. Maybe you could squeeze some performance out with unsafe code, but that's maybe saving a copy from one buffer to another. It would be nice to put that reading loop into a separate function, something like:</p>\n\n<pre><code>byte[] ReadBytes(SomeType tt1, int bytesToRead);\n</code></pre>\n\n<p>I can't guess what type <code>tt1</code> is, but is it possible that retrieving the value for <code>Connected</code> is slow? What about <code>GetStream</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-05T01:35:12.083",
"Id": "115856",
"ParentId": "29875",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T20:27:06.217",
"Id": "29875",
"Score": "4",
"Tags": [
"c#",
"performance"
],
"Title": "Speed up position check for embedded length on stream"
}
|
29875
|
<p>Here are my code samples: <a href="https://github.com/arthaeus/war" rel="nofollow">https://github.com/arthaeus/war</a></p>
<p>This particular sample is the card game 'War'. The interviewer off-handedly asked me: "what if I wanted to play War with an Uno deck of cards?" I threw an Uno deck implementation in there as well, so don't be confused. </p>
<p>I have been told that my <code>main()</code> function is too procedural, and also I have been told that the output logic should be separated. Do you agree with these assessments? Do you see anything else that will make me a better coder? Also, am I botching the factory pattern?</p>
<p><strong>Edit</strong></p>
<p>Here is some of the code that I would like to have reviewed:</p>
<p>Here is <strong>main.php:</strong></p>
<pre><code>class war implements IGame
{
/**
* warStats will hold statistics about the current game.
*/
public static $warStats = null;
public static $config = null;
private $IPlayers = array();
private $IDeck = array();
const MAX_WAR_WINS = 100;
const MAX_TURNS = 10000;
public function __construct()
{
/**
* Initialize the config
*/
self::$config = new config();
self::$config->buildConfig();
}
public static function addWarStat( stdClass $warStat )
{
if( !self::$warStats )
{
self::$warStats = array();
if( !array_key_exists( self::$warStats[$warStat->playerName] , self::$warStats ) )
{
self::$warStats[$playerName];
}
}
self::$warStats[$warStat->playerName]['wins']++;
if( self::$warStats[$warStat->playerName]['wins'] == self::MAX_WAR_WINS )
{
echo "GAME IS OVER BECAUSE " . $warStat->playerName . " has won " . self::MAX_WAR_WINS . " wars. \n Here are the standings: \n";
print_r( self::$warStats );
exit;
}
return true;
}
/**
* Play a turn
*/
public function playTurn( ITurn $ITurn )
{
}
public function main()
{
$availablePlayers = array(
"frodo",
"hank_hill",
"mum_ra",
"gandalf",
"steve_urkel",
"aragorn",
"chris_davis",
"samwise",
"famous_dave"
);
/**
* Create the IPlayers that will play this game of war. Add then to the IGame
*/
$player0 = new warIPlayer();
$player0Name = $availablePlayers[rand( 0 , 8)];
$player0->setName( $player0Name );
$player1 = new warIPlayer();
$player1Name = $availablePlayers[rand( 0 , 8)];
while( $player1Name == $player0Name )
{
$player1Name = $availablePlayers[rand( 0 , 8)];
}
$player1->setName( $player1Name );
$this->addIPlayer( $player0 );
$this->addIPlayer( $player1 );
/**
* Initialize the warStats
*/
self::$warStats[$player0Name] = null;
self::$warStats[$player1Name] = null;
self::$warStats[$player0Name]['wins'] = null;
self::$warStats[$player1Name]['wins'] = null;
/**
* Create the IDeck of ICards for this game. Just a standard deck
* Shuffle and deal the ICards
*/
$IDeckSettings = self::$config->getSetting( 'IDeck' );
$IDeckType = $IDeckSettings->IDeckClass->value;
$deckOfCards = IDeckFactory::getInstance( $IDeckType );
$deckOfCards->buildIDeck();
$deckOfCards->shuffleIDeck();
$this->setIDeck( $deckOfCards );
/**
* The IGame is responsible for dealing out the cards in whatever way the cards are dealt for this game
*/
$this->dealICards();
/**
* The ICards have been dealt. Play turns
*/
$keepGoing = true;
//how many turns have been played. This variable will be incremented by one after each turn is played. the incrementing will be done by the following while loop
$turnCount = 0;
while( $keepGoing )
{
echo "PLAYING TURN $turnCount out of " . self::MAX_TURNS . "\n\n";
/**
* create a new turn, and give the turn the information about this IGame (players, their cards, etc)
*/
$ITurn = new normalWarITurn();
$ITurn->setIGame( $this );
/**
* Play the turn
*/
$keepGoing = $ITurn->play();
$turnCount++;
if( $turnCount == self::MAX_TURNS )
{
echo "The maximum number of turns has been met. The game is a draw \n";
print_r( self::$warStats );
echo "AT THE END OF THE GAME, THE CARD COUNTS ARE: \n$player0Name = " . count( $player0->getICardCollection()->getICards() ) . " \nTO \n$player1Name = " . count( $player1->getICardCollection()->getICards() ) . "\n\n";
exit;
}
}
if( count( $player0->getICardCollection()->getICards() ) == 0 )
{
echo $player0->getName() . " has lost! and " . $player1->getName() . " has won! \n";
}
else
{
echo $player1->getName() . " has lost! and " . $player0->getName() . " has won! \n";
}
}
/**
* Deal the ICards to the IPlayers
* In the game of war, alternate.. deal one to one, and then the next to the other until the deck is empty
*/
public function dealICards()
{
/**
* Get the IPlayers
*/
$IPlayers = $this->IPlayers;
/**
* Get the IDeck
*/
$IDeck = $this
->IDeck
->getICardCollection();
/**
* While the IDeck is not empty, deal the ICards to the IPlayers
*/
$count = 0;
while( $IDeck->getState() != "EMPTY" )
{
try
{
/**
* Get an ICard from the top of the IDeck
*/
$ICard = $IDeck->getICard();
}
catch( NoICardException $e )
{
echo $e->getMessage();
}
/**
* If the counter is even, assign the ICard to IPlayer[0], else assign to IPlayer[1]
*/
if( $count % 2 == 0 )
{
$IPlayers[0]->setICard( $ICard );
}
else
{
$IPlayers[1]->setICard( $ICard );
}
$count++;
}
/**
* Set the IPlayers hands to full state
*/
$IPlayers[0]
->getICardCollection()
->setState( "FULL" );
$IPlayers[1]
->getICardCollection()
->setState( "FULL" );
return true;
}
/**
* A game consists of an IPlayer. Here are functions pertaining to the IPlayer
*/
public function addIPlayer( IPlayer $IPlayer )
{
$this->IPlayers[] = $IPlayer;
return true;
}
public function removeIPlayer( IPlayer $IPlayer )
{
}
/**
* Returns a player object named $name
*/
public function getIPlayerByName( $name )
{
return $this->IPlayers[$IPlayer->getIPlayerByName()];
}
/**
* Will return all IPlayers
*/
public function getIPlayers()
{
return $this->IPlayers;
}
/**
* A game consists of an IDeck (deck of cards). Here are functions pertaining to the IDeck
*/
public function getIDeck()
{
return $this->IDeck;
}
public function setIDeck( IDeck $IDeck )
{
$this->IDeck = $IDeck;
return;
}
}
$w = new war();
$w->main();
?>
</code></pre>
<p><strong>Here are my interfaces:</strong></p>
<pre><code>/**
* Written specifically for the card game war. The abstract concepts should be applicable to any game that is played
* with a standard deck of playing cards (not card games like uno or old maid)
*/
interface ICardCollection
{
/**
* The IDeck is in the empty state
*/
const STATE_EMPTY = "EMPTY";
/**
* The IDeck is not empty, but not full
*/
const STATE_NOT_EMPTY = "NOT_EMPTY";
/**
* Full deck of ICards
*/
const STATE_FULL = "FULL";
/**
* Adds one ICard to the ICardCollection
*/
public function setICard( ICard $ICard );
/**
* Pops one ICard from the ICardCollection
*/
public function getICard();
/**
* Set all ICards for this collection. Current collection will be overwritten.
*/
public function setICards( $ICards );
/**
* Append ICards to the already existing ICards array
*/
public function addICards( $ICards );
/**
* Get all ICards from this collection
*/
public function getICards();
}
/**
* An IDeck is made up of ICards. The IDeck will always have a property called ICards which will be a container for ICards
*/
interface IDeck extends ICardCollection
{
/**
* An IDeck of cards needs to be responsible for providing functionality for building a deck of cards.
* The IDeck may be standard playing cards, old maid cards, uno cards, etc. Each is different, and each must be built differently
* The buildDeck function (for the war IDeck) will be a facade in front of helper functions that will ultimately build an IDeck of ICards
*/
public function buildIDeck();
/**
* The IDeck will be set to its default state. The IDeck will contain all ICards, and they will not be
* shuffled.
*/
public function resetIDeck();
/**
* After this function is called, the container of ICards will be in a random order
*/
public function shuffleIDeck( stdClass $options = null );
}
/**
*
* The ITurn is responsible for invoking the rules of the IGame. The ITurn will return whatever the IGame is expecting it to return. In war, after a turn
* is played, the ITurn will return the array of ICards that were played during this turn, and also who is the winner.
*
* In card games, the players take turns. Different games will implement a turn differently
* Working under the assumption that a game is comprised of turns.
* Working under the assumption that a turn will have player(s)
* Working under the assumption that in a card game, a turn has cards. (When a player plays the turn, they make the cards that they play a part of the turn).
*
*/
interface ITurn
{
/**
* States to tell whether a turn is still going on, or if the turn is over.
*/
const STATE_TURN_ACTIVE = "TURN_ACTIVE";
const STATE_TURN_OVER = "TURN_OVER";
public function setIGame( IGame $IGame );
public function getIGame();
/**
* the play function will take the cards from the turn into consideration, and invoke the rules of a particular game.
*
* Also:
*
* Different card games have different things that happen upon winning a turn. For war, the goal is
* to get all of the cards. In other games, you probably don't want to end up with all of the cards. The ITurn
* should return whatever it needs to return to the IGame, and the IGame is responsible for interfacing with the
* IPlayers. The abstract ITurn class will have an abstract method called win()
*/
public function play();
}
/**
* Interface for a player. Will provide template for generic player behavior
*/
interface IPlayer
{
/**
* This function will pop and return a card from the player's hand
*
* The ITurn will use this function to interact with the IPlayer.
*/
public function getICard();
/**
* Will add one single ICard to the players hand
*/
public function setICard( ICard $ICard );
/**
* Will add multiple ICards to the players hand
*/
public function setICards( $ICards = array() );
public function setName( $name );
public function getName();
}
/**
* This will be the driver for the program
*
* Working under the assumption that if a game exists, and it is being played, it will contain player(s)
* Working under the assumption that most card games have turns and these turns involve players.
*/
interface IGame
{
/**
* States to tell whether a game is still going on, or if the game is over.
*/
const STATE_GAME_ACTIVE = "GAME_ACTIVE";
const STATE_GAME_OVER = "GAME_OVER";
/**
* A game consists of an IPlayer. Here are functions pertaining to the IPlayer
*/
public function addIPlayer( IPlayer $IPlayer );
public function removeIPlayer( IPlayer $IPlayer );
/**
* Returns a player object named $name
*/
public function getIPlayerByName( $name );
/**
* Will return all IPlayers
*/
public function getIPlayers();
/**
* A game consists of an IDeck (deck of cards). Here are functions pertaining to the IDeck
*/
public function getIDeck();
public function setIDeck( IDeck $IDeck );
/**
* Deal the ICards to the IPlayers
*/
public function dealICards();
/**
* Play a turn
*/
public function playTurn( ITurn $ITurn );
}
interface ICard
{
/**
* Returns the value of this ICard
*/
public function getValue();
}
?>
</code></pre>
<p><strong>Here is an abstract deck of cards:</strong></p>
<pre><code>abstract class abstractIDeck extends abstractBase implements IDeck
{
protected $ICardCollection = null;
public function __construct()
{
$this->ICardCollection = new ICardCollection();
}
/**
* After this function is called, the container of ICards will be in a random order
*/
public function shuffleIDeck( stdClass $options = null )
{
/**
* To shuffle the IDeck, get the ICards from the collection, shuffle them, and then set them back
*/
$ICards = $this->ICardCollection->getICards();
shuffle( $ICards );
$this
->ICardCollection
->setICards( $ICards );
return true;
}
/**
* The IDeck will be set to its default state. The IDeck will contain all ICards, and they will not be
* shuffled.
*/
public function resetIDeck()
{
$this->ICardCollection = new ICardCollection();
$this->buildIDeck();
return true;
}
/**
* Will pop and return an ICard from the IDeck. If the IDeck is empty, return false
*/
public function getICard( stdClass $options = null )
{
/**
* Shift off one card, and return it.
*/
try
{
$returnCard = $this
->ICardCollection
->getICard();
}
catch( NoICardsException $e )
{
}
return $returnCard;
}
/**
* Will add an ICard to the IDeck.
*/
public function setICard( ICard $ICard )
{
$this
->ICardCollection
->setICard( $ICard );
return true;
}
/**
* Set all ICards for this collection. Current collection will be overwritten.
*/
public function setICards( $ICards )
{
$this
->ICardCollection
->setICards( $ICards );
}
/**
* Append ICards to the already existing ICards array
*/
public function addICards( $ICards )
{
$this
->ICardCollection
->addICards( $ICards );
}
/**
* Get all ICards from this collection
*/
public function getICards()
{
return $this
->ICardCollection
->getICards();
}
/**
* Get the full ICardCollection object
*/
public function getICardCollection()
{
return $this->ICardCollection;
}
}
?>
</code></pre>
<p><strong>And here is a standard deck of cards extending the abstract deck:</strong></p>
<pre><code>/**
* Class to represent a standard deck of playing cards (hearts,spades,diamonds,clubs. 2 through ace)
*/
class standardIDeck extends abstractIDeck implements IDeck
{
/**
* Values for the ace card should be 1 or 14
*/
const ACE_VALUE = 15;
/**
* An IDeck of cards extending abstractDeck needs to be responsible for providing functionality for building a deck of cards.
* The IDeck may be standard playing cards, old maid cards, uno cards, etc. Each is different, and each must be built differently
* The buildDeck function (for the war IDeck) will be a facade in front of helper functions that will ultimately build and return
* an IDeck of cards
*/
public function __construct()
{
abstractIDeck::__construct();
}
public function buildIDeck()
{
$suits = array( "hearts" , "diamonds" , "spades" , "clubs" );
/**
* For a standard deck of cards, create each of the 4 suits
*/
foreach( $suits as $suit )
{
/**
* If the ace value is not set properly, an exception will be raised
*/
try
{
$this->buildSuit( $suit );
}
catch(InvalidAceValueException $e)
{
/**
* the exception handler will create an ace card with a value of 14 if the ACE_VALUE is not properly set
*/
$aceCard = $e->handleException();
$this
->ICardCollection
->setICard( $aceCard );
}
}
$this
->ICardCollection
->setState( self::STATE_FULL );
return true;
}
private function buildSuit( $suit )
{
/**
* Create all cards, except for the ace.
*/
$ICards = array();
for( $cardValue = 2; $cardValue < 14; $cardValue++ )
{
/**
* give the appropriate title to the face cards
*/
if( $cardValue > 10 && $cardValue < 14 )
{
switch( $cardValue )
{
case "11":
$title = "jack of " . $suit;
break;
case "12":
$title = "queen of " . $suit;
break;
case "13":
$title = "king of " . $suit;
break;
}
}
else
{
/**
* The title of a regular number card is just its number. The title for a card worth 11 is Jack, 12 = Queen, etc
*/
$title = $cardValue . " of $suit";
}
/**
* create the card, and then insert it into the returnCards array
*/
$ICard = new standardICard( $suit , $cardValue , $title );
$ICards[] = $ICard;
}
$this
->ICardCollection
->addICards( $ICards );
/**
* Take care of creating the ace
*/
if( self::ACE_VALUE != 1 && self::ACE_VALUE != 14 )
{
throw new InvalidAceValueException( "Ace value must be 1 or 14. Check the const at the top of standardIDeck.php. I will default to the value for ace as being set to 14" );
}
$ICard = new standardICard( $suit , self::ACE_VALUE , "ace of " . $suit );
$this->ICardCollection->setICard( $ICard );
return true;
}
}
class InvalidAceValueException extends \Exception
{
/**
* handle the exception by setting ace to high value
*/
public function handleException()
{
$traceArray = $this->getTrace();
$suit = $traceArray[0]['args'][0];
return new standardICard( $suit , 14 , "ace of " . $suit );
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>ugh. I don't even know where to start...</p>\n\n<p>The code you wrote is not OO. In no way at all.</p>\n\n<p>Let's answer you questions first:</p>\n\n<blockquote>\n <p>I have been told that my main() function is too procedural</p>\n</blockquote>\n\n<p>You have a 'War' class with a main() function that does everything. This is soooo java main() where you have to write your controller in the main(). But in pp you don't have to encapsulate a cotroller in a class and cramp everything in a main()</p>\n\n<blockquote>\n <p>I have been told that the output logic should be separated</p>\n</blockquote>\n\n<p>What if ou want to change the way a 'jack of spades' is displayed? You wil now have to dive into your business logic code... That simply asks for problems</p>\n\n<p>Then overall:\nUsing the words 'class' and 'function' doesn't mean you are writing proper OO code.\nWhen writing good code always think SOLID:<a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29</a></p>\n\n<p>So, what will make you a better programmer? SOLID, always start there. Then read about the different patterns and when they should be used. A good tut from ibm: <a href=\"http://www.ibm.com/developerworks/library/os-php-designptrns/\" rel=\"nofollow\">http://www.ibm.com/developerworks/library/os-php-designptrns/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T22:02:16.170",
"Id": "47478",
"Score": "0",
"body": "Thank you for looking at this for me! I'm going to rewrite this with SOLID in mind. I appreciate the honesty."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T07:32:47.503",
"Id": "47504",
"Score": "0",
"body": "@ChrisD. reading it again now, maybe I was a bit harsh. But you are welcome!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T09:55:46.647",
"Id": "29916",
"ParentId": "29878",
"Score": "2"
}
},
{
"body": "<p>Erm, right... I don't mean to be rude, but OO in PHP isn't too different from OO in any other language. The SOLID principles apply there, too. You seem to be writing code as if you had a phobia of all things SOLID stands for. Is the <code>main</code> method too procedural. having a method called <code>main</code> is ok. What you're doing in the <code>main</code> method is too procedural.<br/>\nDo you have to separate the output from the logic. Of course! Why would you bother with OO, if you don't separate things, you could just as well write one class, create an instance and use that class' scope instead of the global scope. But why bother with that class in the first place?<br/>\nAre you botching the factory pattern? You're using the <em>factory pattern?</em>... (yes, I'm afraid you are)</p>\n\n<p>But let's start with something basic, yet important:<br/>\nEven though PHP isn't standardized just yet, there is an unofficial coding standard, <a href=\"https://github.com/php-fig/fig-standards\">which can be found here</a>. All major players (Zend included) subscribe to this standard, as should you. Classes start with an Upper-Case, yours don't. Fix that. But that's just a cosmetic issue...</p>\n\n<p><em>Factory</em>:<br/>\nYou have an awful lot of <code>static</code>'s in your code. I'm editing this answer, because I just noticed that this is to implement the factory pattern. Don't. Last time I applied for a job as PHP dev, I actually got a high-five, because I set off on a rant about why statics are, essentially, as bad as using <code>eval</code> or <code>global</code>. They have their use-cases, but in PHP, I've only ever <em>really</em> needed them 2, or 3 times in the past 5 years. Tops. Read about the D in SOLID, and learn to write tests. You'll soon find yourself hating statics and singletons as much as the next man.<br/>\nEven though a <code>Factory</code> can be handy (as can a <code>Registry</code>). They're really just globals in drag.</p>\n\n<p><em>Main:</em><br/>\nFor some reason, you also define a <code>public function main</code> in an object. I can understand where that might come from. Other languages (Java, C, C++, Python...) require a <code>main</code> or <code>__main__</code> function to be defined somewhere. The thing is: these are <em>other languages</em>. It's a bit like using a double negative, because some languages use double negation (Afrikaans, French). Just because some of the more popular languages require a main function, doesn't mean that <em>all</em> languages need this.<br/>\nHaving a <code>main</code> function isn't all <em>that</em> bad, nor is it <em>\"too procedural\"</em>. It's what you're doing in that method that is just not OO at all.</p>\n\n<p>In OOP, a class represents a single entity, and therefore, it should have one (and only one) task. A class can be responsible for rendering output, or interacting with the database, or processing the (raw) request data. That's all fine, but what a single class <em>can't</em> do is handle the response <em>and</em> insert data in the db. Even worse would be if that same class were then to <code>echo</code> output. That's a gross violation of the Single Responsibility Principle.<br/>\nWhich brings us to your third question...</p>\n\n<p><em>Separation of output</em><br/>\nYour class echoes, creates instances, performs all sorts of things in a single method. If that weren't bad enough, it also wraps bits and pieces into a <code>try..catch</code>, only to <code>echo $e->getMessage();</code> and carry on as if nothing happened!<br/>\nThe way you should think of <code>Exception</code>s is, they are things that are <em>thrown</em> outside of the normal flow of the code, because there's something odd going on. A class that inserts data into a DB doesn't know (nor does it <em>need</em> to know) where that data comes from or what it means. If the insert fails, an exception is thrown, and the code that called the insert method should deal with the Exception. Not the code that just passed the data on to the DB. If the code that called the insert method can't handle the exception, let it go. Its an error, don't hush it up and try to get by, let the script die, it's to prevent any further damage from being done.</p>\n\n<p>Imagine I were to give you this piece if truly horrid code, and you had to debug it:</p>\n\n<pre><code>class MyDB\n{\n private $connection = null;\n private $statements = array();\n public function __construct()\n {\n $this->connection = new PDO();\n }\n public function saveStuff(array $rows)\n {\n if (!isset($this->statements['saveStuff']))\n {\n $stmt = $this->connection->prepare('INSERT INTO tbl (name, score, status) (?,?,?)';\n $this->statements['saveStuff'] = $stmt;\n }\n $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n $i = 1;\n foreach($rows as $row)\n {\n try\n {\n $this->connection->execute($this->statements['saveStuff'], $row);\n }\n catch(PDOException $e)\n {\n echo 'Insert failed for row #', $i, ' ', $e->getMessage();\n }\n }\n return true;\n }\n}\n</code></pre>\n\n<p>Used like this:</p>\n\n<pre><code>$db = new MyDB;\n$ok = $db->saveStuff(\n array(\n array(1,2,3),\n array('a',2,3),\n array('asc', 'x', true)\n )\n);\nif ($ok === true)\n{\n setcookie('dataSet',1);\n}\n</code></pre>\n\n<p>The call to <code>saveStuff</code> will <em>always</em> return true, so the cookie will always be set, or will it? If the <code>saveStuff</code> method caught a <code>PDOException</code>, it'll echo the error, and the headers will be sent. I can't set a cookie anymore. In this case, though, the problems are pretty obvious, but the larger your codebase becomes, the harder it'll be to debug code like this. Imagine there being 20-some instances involved, then it'll be up to you to uncover which one of these instances is causing the headers to be sent before the cookie was sent. Have fun and try not to cry...<br/>\nOk, dry those tears, and just remove the <code>try...catch</code> block. What you'll get now is an error-page saying <code>uncaught exception on line X</code>. You can then look at the stack trace, see what data came from where, and what exactly it was that caused everything to go pear-shaped. There's no <code>insert</code>'s being performed after the one that went wrong... in this case, a <em>\"crash\"</em> is the cleaner alternative (google Worse is Better)</p>\n\n<p>Other than that, you are using type-hints, which is a good thing, you are using getters and setters, that allow for <em>some</em> injection. Again, nothing wrong with that, although, you might want to consider implementing the fluent interface, also known as chainable methods:</p>\n\n<pre><code>public function setSomeDependency( SomeDependency $foo )\n{\n $this->dependency = $foo;\n return $this;\n}\n//so you can use it like so:\n\n$instance->setSomeDependency($instanceofDepend)\n ->setSomethigElse('like the name')\n ->getEverything();\n</code></pre>\n\n<p>There are still a lot of issues I haven't discussed, though, for example:</p>\n\n<pre><code>$player0Name = $availablePlayers[rand( 0 , 8)];\n//a few lines later:\n$player1Name = $availablePlayers[rand( 0 , 8)];\n</code></pre>\n\n<p>There is a 1/8 chance that both variables will be assigned the same name here. That's not what you want, is it?<br/>\nThe number of available names, by the way, is probably a global state per request. If there is a max of 8 concurrent players, then the names that are taken <em>should</em> be unset, so that no two players can possibly get the same name. Now this, perhaps, a valid use-case for a static variable:</p>\n\n<pre><code>private static $availablePlayers = array();\nprotected function getAvailableName()\n{\n if (self::$availablePlayers)\n {\n return array_pop(self::$availablePlayers);\n }\n throw new RuntimeException('All 8 player names are taken, gameroom is full');\n}\n</code></pre>\n\n<p>Of course, I don't actually <em>know</em> what you're doing here, nor do I <em>know</em> where the names are comming from, and if the number of players is to be limited, but I do <em>know</em> that a 1/8 chance of 2 variables being assigned the same value is not what you want, nor does it make sense (to me) to have 2 variables, called <code>$player0</code> and <code>$player1</code>.<br/>\nTo me, a list (or array) just makes more sense:</p>\n\n<pre><code>$players = array(\n new Player($this->getAvailableName()),\n new Player($this->getAvailableName())\n);\n</code></pre>\n\n<p>All things considered, I'd bin this code, and start again. Keep asking yourself these simple questions:</p>\n\n<ul>\n<li>Is my class doing more than 1 thing? If it is, split into multiple classes.</li>\n<li>Do I have to scroll to read the entire method? If so, there's something wrong with it</li>\n<li>Am I sure that, after calling a method, nothing, except for the instance (perhaps) has changed (no headers, no pass-by-reference)? If not, your code is smelly</li>\n<li>Am I keeping things simple? If not Keep It Simple, Stupid</li>\n<li>Can I write a test, without running into the static wall of death? If you can't Inject, don't use singletons.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T21:42:27.063",
"Id": "47477",
"Score": "0",
"body": "Thank you for the critique. I am reading through what you wrote, and I'm going to try to figure out how to make this better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-02T14:59:06.370",
"Id": "48782",
"Score": "0",
"body": "+1 from me for a very detailed review, but I have to say I dislike phrases like \"too procedural\" because they smell of dogmatism and don't contain any concrete information. There should be no problem writing code procedural-style when it's the best fit for the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-03T06:55:04.843",
"Id": "48822",
"Score": "0",
"body": "@busy_wait: considering the title, this question is about good use of OO principles. procedural programming is right out, then. Besides: the phrase _\"too procedural\"_ is something I got from the initial question. It's not something I would say"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T16:06:05.070",
"Id": "29927",
"ParentId": "29878",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29927",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-16T22:23:32.797",
"Id": "29878",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"interview-questions",
"game"
],
"Title": "Review of object-oriented skills with War game"
}
|
29878
|
<p>The navigation in my footer menu looks like this </p>
<p><img src="https://i.stack.imgur.com/3SSb2.png" alt="footer navigation"></p>
<p>It works, but I get a feeling that using spans the way I did was a bit of a hack. So I would also like to know how to maximize compatibility as used media queries.</p>
<p>I created it using the following </p>
<p><strong>HTML</strong></p>
<pre><code><div class="footer">
<ul>
<li><a href="http://www.bruxzir.com">
<span>HOME</span><span>&raquo;</span>
</a></li>
<li><a href="http://www.bruxzir.com/features-bruxzir-zirconia-dental-crown/">
<span>FEATURES</span><span>&raquo;</span>
</a></li>
<li><a href="http://www.bruxzir.com/video-bruxzir-zirconia-dental-crown/index.aspx">
<span>VIDEOS</span><span>&raquo;</span>
</a></li>
<li><a href="http://www.bruxzir.com/cases-bruxzir-zirconia-dental-crown/">
<span>CASES</span><span>&raquo;</span>
</a></li>
<li><a href="http://www.bruxzir.com/testimonials-bruxzir-zirconia-dental-crown/">
<span>TESTIMONIALS</span><span>&raquo;</span>
</a></li>
<li><a href="/">
<span>BLOG</span><span>&raquo;</span>
</a></li>
<li><a href="http://www.bruxzir.com/authorized-bruxzir-labs-zirconia-dental-crown/">
<span>AUTHORIZED BRUXZIR LABS</span><span>&raquo;</span>
</a></li>
</ul>
</div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>.footer {
background-color: #111;
text-align: center;
width: 100%;
min-height: 120px;
padding: 24px 0;
}
.footer a {
color: #fff;
text-decoration: none;
}
.footer ul { list-style: none; }
@media only screen and (min-width: 1px) and (max-width: 479px) {
.footer { text-align: left; }
.footer ul li {
display: block;
padding: 12px;
}
.footer ul li a { }
.footer ul li a span:nth-of-type(2) {
padding:9px;
background-color: rgb(202, 0,0 );
float: right;
border-radius:2px;
}
}
@media only screen and (min-width: 480px) {
.footer { text-align: center; }
.footer ul li { display: inline; }
.footer ul li:not(:last-of-type) { margin-right: 12px }
.footer ul li a span:nth-of-type(2) { display: none; }
}
</code></pre>
|
[] |
[
{
"body": "<p>you should use a <code><div></code> where you need to separate a block of code from the rest, for positioning or for other purposes, your use of the <code>div</code> for the Footer section is correct, so that you can place this part of the page at the bottom, where it belongs. </p>\n\n<p>when you create a list item (<code><li></code>) it is already a text element. you can perform CSS on these elements the same as you would a <code><p></code> Paragraph tag if you add a <code><p></code> tag inside the list item it may give you unwanted results like a <code>carriage return</code> after the element. </p>\n\n<p>I think that using the <code><span></code> tag the way you did is just fine. I would have probably added a class to each of them, it would have been easier to pick them out with the CSS. other than that your <code><span></code> tags were used properly in this instance because they were used <strong>inline</strong> </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T17:30:36.443",
"Id": "30090",
"ParentId": "29882",
"Score": "4"
}
},
{
"body": "<p><strong>HTML:</strong></p>\n\n<ul>\n<li>Since the the navigation is the only thing inside your <code><div class=\"footer\"></code>, how about moving the class to the <code>ul</code>?</li>\n<li>Instead of using <code>span</code>'s there, you can add the <code>&raquo;</code> to a pseudo-element (see the CSS part)</li>\n</ul>\n\n<p><strong>CSS:</strong></p>\n\n<ul>\n<li><p>For your arrows, you should use pseudo-elements:</p>\n\n<pre><code>.footer a:after {\n content: \"\\00BB\";\n float: right;\n padding: 9px;\n border-radius: 2px;\n background-color: #ca0000; /* hex-based values are shorter */\n}\n</code></pre>\n\n<p>You won't need to hide them on bigger screens either, if you define them inside a media query, because they're not present in your markup</p></li>\n<li><p>Instead of actually writing the links in capital letters, write them like you would in normal language and make them appear uppercase with <code>text-transform: uppercase;</code></p></li>\n<li>I don't see a purpose for the <code>min-width: 1px</code> part in your media query. Just unnecessary.</li>\n<li>Defining <code>display: block;</code> on list-items is not necessary, because they behave like block-level elements already</li>\n<li>Select <code>.footer li</code> instead of <code>.footer ul li</code> and <code>.footer a</code> instead of <code>.footer ul li a</code>. No need for this extra layer of specificity and dependency. There will probably no other links and list-items in this ul other than these you already have</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T19:44:14.700",
"Id": "40195",
"ParentId": "29882",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "30090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T02:00:34.360",
"Id": "29882",
"Score": "5",
"Tags": [
"html",
"css"
],
"Title": "Review of my CSS for aligning the navigation icons and text in a footer menu"
}
|
29882
|
<p>I have the following code (I need the <code>LambdaExpression</code> as not all <code>Func<></code>'s are <code>T, int</code>):</p>
<pre><code>var orderDelegates = new Dictionary<string, LambdaExpression>();
Expression<Func<Image, int>> id = i => i.Id;
orderDelegates.Add(ContentItem.ORDER_BY_ID, id);
</code></pre>
<p>Is it possible to make this shorter?</p>
<p>Best something like:</p>
<pre><code>var orderDelegates = new Dictionary<string, LambdaExpression>()
{
{ ContentItem.ORDER_BY_ID, ????? },
...
};
</code></pre>
<p>I already tried the following, which did not work:</p>
<pre><code>orderDelegates.Add(ContentItem.ORDER_BY_ID, (Expression<Func<Image, int>>)i => i.id);
//or
orderDelegates.Add(ContentItem.ORDER_BY_ID, i => i.id as Expression<Func<Image, int>>);
</code></pre>
<p>I "improved" it a little to the following already, but "full inlining" would be the desired result:</p>
<pre><code>public static Dictionary<string, LambdaExpression> GetOrderDelegates<T>() where T : ContentItem
{
Expression<Func<T, int>> id = i => i.Id;
Expression<Func<T, bool>> enabled = i => i.IsEnabled;
Expression<Func<T, IComparable>> author = i => i.Creator.UserName;
//...
return new Dictionary<string, LambdaExpression>()
{
{ ContentItem.ORDER_BY_ID, id },
{ ContentItem.ORDER_BY_ENABLED, enabled },
{ ContentItem.ORDER_BY_AUTHOR, author },
//...
};
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T11:16:34.300",
"Id": "47383",
"Score": "0",
"body": "So, what do you know about the lambdas, are they all `Func<Image, something>` or at least `Func<something1, something2>`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T11:45:11.160",
"Id": "47386",
"Score": "0",
"body": "@svick: Yes, they are all `Func<T, something>`..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T12:38:01.920",
"Id": "47391",
"Score": "0",
"body": "whats `ContentItem`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T17:25:53.207",
"Id": "47399",
"Score": "0",
"body": "@Nik: `ContentItem` is my base class, which holds all common properties like `Id` and all my (content-)items use classes derived from it ..."
}
] |
[
{
"body": "<p>You can do this by creating a custom class that supports collection initializers. Its <code>Add()</code> method would be generic, so that it fits any allowed expression:</p>\n\n<pre><code>class ExpressionDictionary<T> : IEnumerable<KeyValuePair<string, LambdaExpression>>\n{\n private readonly Dictionary<string, LambdaExpression> m_dictionary\n = new Dictionary<string, LambdaExpression>();\n\n public void Add<TResult>(string key, Expression<Func<T, TResult>> expression)\n {\n m_dictionary.Add(key, expression);\n }\n\n public IEnumerator<KeyValuePair<string, LambdaExpression>> GetEnumerator()\n {\n return m_dictionary.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>new ExpressionDictionary<T>\n{\n { ContentItem.ORDER_BY_ID, i => i.Id },\n { ContentItem.ORDER_BY_ENABLED, i => i.IsEnabled },\n //the cast is necessary if the result has to be Func<T, IComparable>\n // and not Func<T, string>\n { ContentItem.ORDER_BY_AUTHOR, i => (IComparable)i.Creator.UserName },\n //...\n};\n</code></pre>\n\n<p>You will need to add other methods to <code>ExpressionDictionary</code>. Either implement the whole <code>IDictionary<TKey, TValue></code> interface and make <code>GetOrderDelegates()</code> return that. Or just add a getter for the private <code>Dictionary</code> and return that.</p>\n\n<p>But even better option might be not to use Dictionary at all. Instead create <code>OrderByDeletegates</code> class (though that's probably not the best name, since it would contain expressions, not delegates) that would have properties for all expressions:</p>\n\n<pre><code>class OrderByDeletegates<T> where T : ContentItem\n{\n public Expression<Func<T, int>> OrderById { get; set; }\n public Expression<Func<T, bool>> OrderByEnabled { get; set; }\n public Expression<Func<T, IComparable>> OrderByAuthor { get; set; }\n // …\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>new OrderByDeletegates<T>\n{\n OrderById = i => i.Id,\n OrderByEnabled = i => i.IsEnabled,\n OrderByAuthor = i => i.Creator.UserName,\n // …\n};\n</code></pre>\n\n<p>The advantage of this is that it's type-safe. You can't for example accidentally do something like <code>OrderByEnabled = i => i.Id</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T17:30:00.833",
"Id": "47400",
"Score": "0",
"body": "This are great ideas, but the second one will not work in my case, as I use the `string`-key of the dictionary to select the correct delegate/expression...\nI try implementing your first idea as an extension to my dictionary and report back."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T18:19:39.350",
"Id": "47405",
"Score": "0",
"body": "@chrfin Why do you need to use the key? Can't you just access the properties directly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T19:20:20.293",
"Id": "47406",
"Score": "0",
"body": "Because the key comes in as a string from the (Web-)Front-End (e.g \"mydomain.com/page?sortKey=Author\" will sort after the expression with the key \"Author\")..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T09:16:41.930",
"Id": "47441",
"Score": "0",
"body": "Went with your first solution and works fine..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-17T00:13:46.737",
"Id": "519433",
"Score": "0",
"body": "note that `Expression<Func<T, TResult>>` does not guarantee that TResult is a member of T which I think was the op intent"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T12:50:57.503",
"Id": "29890",
"ParentId": "29883",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29890",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T08:26:57.463",
"Id": "29883",
"Score": "3",
"Tags": [
"c#",
"linq"
],
"Title": "Inline conversion/cast from Expression<Func<T, int>> to LambdaExpression"
}
|
29883
|
<p>I wrote this code to overcome the deadlock condition described in <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html" rel="nofollow">this Oracle tutorial</a>.</p>
<p><strong>Summary of Problem:</strong></p>
<blockquote>
<p>Alphonse and Gary are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time.</p>
</blockquote>
<p>I used a volatile boolean <code>CanBow()</code> to check if either of the friends are bowing so that the condition when both of them bow and wait for the other to bow back will not happen.</p>
<p>Is this a valid way to handle deadlocks as opposed to using locks?</p>
<pre><code>public class NewThread extends Thread {
Friend bower;
Friend bowBack;
NewThread(Friend bower,Friend bowBack){
this.bower = bower;
this.bowBack = bowBack;
}
@Override
public void run(){
if(bowBack.canBow())
bower.bow(bowBack);
}
}
public class ApplicationThread {
public static void main(String[] args) {
final Friend alphonse = new Friend("Alphonse");
final Friend gary = new Friend("Gary");
NewThread t1 = new NewThread(alphonse,gary);
NewThread t2 = new NewThread(gary,alphonse);
t1.start();
t2.start();
}
static class Friend {
private final String name;
private volatile boolean canBow;
public Friend(String name) {
this.name = name;
canBow = true;
}
public String getName() {
return this.name;
}
public boolean canBow(){
return canBow;
}
public synchronized void bow(Friend bower) {
canBow = false;
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
canBow = true;
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T16:13:02.743",
"Id": "47396",
"Score": "0",
"body": "`NewClass` should be `NewThread` if I'm not missing something and your static class should have proper indentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T17:00:31.383",
"Id": "47397",
"Score": "0",
"body": "Agreed and edited. Are there any known advantages of using locks over volatiles?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:30:42.510",
"Id": "47517",
"Score": "0",
"body": "@SindhujaNarasimhan The only reason to use a volatile is if two or more threads will be accessing a field whose value will change. Volatile fields don't have any direct relationship to deadlocks. On the other hand, synchronized blocks and other monitor/lock objects are what you would use in order to prevent a deadlock (or other sorts of -lock). In general, you prevent a deadlock by making sure that only thread has access to a resource (such as a monitor) at any one time: you would do this by using a Lock object or a synchronized block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:31:48.230",
"Id": "47536",
"Score": "0",
"body": "There's a useful comparison of volatiles and synchronization here: http://www.javamex.com/tutorials/synchronization_volatile.shtml"
}
] |
[
{
"body": "<p>Welcome to the wonderful world of deadlocks. In a nutshell: No, your “solution” is not adequate. Here is some pseudocode detailing what the two threads are doing. Note that a <code>synchronized</code> method aquires a lock on the object it is called on.</p>\n\n<pre><code>THREAD 1 | THREAD 2 \nIF: | IF: \nsynchronized (gary) { | synchronized (alphonse) { \n // gary.canBow(); | // alphonse.canBow(); \n gary.canBow; | alphonse.canBow; \n} | } \nTHEN: | THEN: \nsynchronized (alphonse) { | synchronized (gary) { \n // alphonse.bow(gary); | // gary.bow(alphonse); \n alphonse.canBow = false; | gary.canBow = false; \n ... | ... \n // gary.bowBack(alphonse) | // alphonse.bowBack(gary) \n synchronized (gary) { | synchronized (alphonse) { \n ... | ... \n } | } \n alphonse.canBow = true; | gary.canBow = true; \n} | }\n</code></pre>\n\n<p>We can see that <code>gary</code> and <code>alphonse</code> can be locked at the same time. Especially, the <code>bowBack.canBow()</code> can return <code>true</code> in both threads. Then, even when the <code>canBow</code> boolean is <code>volatile</code>, both objects can wait for each other in a deadlock (in Thread 1, <code>alphonse</code> is locked and waits for <code>gary</code>. In Thread 2, the other way round).</p>\n\n<p>You can make this deadlock more likely by increasing the time between the <code>bowBack.canBow()</code> and <code>bower.bow()</code> calls:</p>\n\n<pre><code>public void run(){\n if(bowBack.canBow()) {\n Thread.sleep(100); // exception handling omitted\n bower.bow(bowBack);\n }\n}\n</code></pre>\n\n<p>To solve these issues, you could impose an order or hierarchy on the friends, so that locks are aquired in exactly the same order in all threads (e.g. always synchronize on <code>alphonse</code> before <code>gary</code>). You could also decide that only one friend may initiate a bow at any time, e.g. via a semaphore.</p>\n\n<p>But your implementation doesn't work.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T16:15:18.473",
"Id": "29928",
"ParentId": "29892",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T15:40:49.257",
"Id": "29892",
"Score": "3",
"Tags": [
"java",
"multithreading"
],
"Title": "Volatile boolean to prevent deadlock"
}
|
29892
|
<p>I wrote a custom URL encoding function and I'd like to run it past a few other experienced C developers. I have tested it on a few strings, and it has worked on all of them. </p>
<p>This is to be run on iOS devices, so memory and processor use are potentially a small concern.</p>
<p>Do you see any potential problems - UB, wrong return, excessive memory or processor usage, difficulty reading?</p>
<p>Any suggestions for improvement?</p>
<pre><code>NSString *urlEncode(NSString *orig)
{
static const BOOL safe[0x100] = {
['a'...'z'] = YES,
['A'...'Z'] = YES,
['0'...'9'] = YES,
['-'] = YES,
['_'] = YES,
['.'] = YES,
['~'] = YES
};
const char *digits = "0123456789ABCDEF";
const char *cstr = orig.UTF8String;
int clen = orig.length;
int nlen = 3*clen;
char newstr[nlen + 1];
const char *o = cstr + clen;
char *p = newstr + nlen;
*p = 0;
while(o > cstr) {
unsigned char c = *--o;
if(safe[c]) {
*--p = c;
} else {
*--p = digits[c&0xf];
*--p = digits[c>>4];
*--p = '%';
}
}
NSString *str = [NSString stringWithUTF8String:p];
return str;
}
</code></pre>
<p>Yes, <code>newStr</code> could get long, but given that a URL > 2kB is unreliable, I think it's unlikely to be a problem in reality.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T20:51:02.910",
"Id": "47413",
"Score": "0",
"body": "Seems like you should be able to just use `NSString`'s `stringByAddingPercentEscapesUsingEncoding`? Or, if you need to expand on what is escaped (as you likely would to implement a true URL encoding), you should be able to use `CFURLCreateStringByAddingPercentEscapes` (example of custom escaping: http://stackoverflow.com/a/8086845/567864)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T20:56:29.677",
"Id": "47414",
"Score": "0",
"body": "`stringByAddingPercentEscapesUsingEncoding` doesn't convert everything it should. Sure, I could use `CFURLCreateStringByAddingPercentEscapes` (and have for other projects), but I thought I'd roll my own this time."
}
] |
[
{
"body": "<p>First of all, URL encoding is more <a href=\"http://www.skorks.com/2010/05/what-every-developer-should-know-about-urls/\" rel=\"nofollow\">nuanced</a> than you might think. Be cautious when applying encoding.</p>\n\n<p>As for your code, the only blatant bug I see is that it can segfault when encoding a non-ASCII string. The <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/occ/instm/NSString/length\" rel=\"nofollow\"><code>-length</code></a> method returns the number of Unicode characters in the string. Since you are working one <code>char</code> at a time, you need the number of bytes instead.</p>\n\n<pre><code>NSUInteger clen = [orig lengthOfBytesUsingEncoding:NSUTF8StringEncoding];\nNSUInteger nlen = 3 * clen;\n</code></pre>\n\n<p>It would be better to change the method signature to:</p>\n\n<pre><code>NSString *urlEncode(const NSString *orig)\n</code></pre>\n\n<p>I think that using a <code>for</code> loop would improve readability. Currently, you declare/initialize <code>*o</code>, test it, and decrement it on three separate lines. A <code>for</code> loop would provide an instantly recognizable structure to make it obvious how those three lines of code are related:</p>\n\n<pre><code>for (const char *o = cstr + clen - 1; o >= cstr; o--) {\n unsigned char c = *o;\n if (safe[c]) {\n *--p = c;\n } else {\n *--p = digits[c & 0x0f];\n *--p = digits[c >> 4];\n *--p = '%';\n }\n}\n</code></pre>\n\n<p>The null <code>char</code> would be better written as <code>'\\0'</code>.</p>\n\n<p>Personally, I would choose to iterate forward rather than backward through the string, as it simplifies the loop by a few instructions, and is easier to understand. It also gives you the option of calling <code>-maximumLengthOfBytesUsingEncoding</code> (which runs in O(1) time) instead of <code>-lengthOfBytesUsingEncoding</code>.</p>\n\n<pre><code>unsigned char c;\nchar *p = newstr;\nfor (const char *o = cstr; (c = *o); o++) {\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T06:55:35.973",
"Id": "29912",
"ParentId": "29895",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T20:42:06.323",
"Id": "29895",
"Score": "4",
"Tags": [
"strings",
"objective-c",
"ios",
"url"
],
"Title": "URL percent encoding function"
}
|
29895
|
<p>A little birdie suggested I bring this question here, so here it goes.</p>
<p>Well I have a working script (see below) but it seems quite clunky and redundant; in my defense I wrote this code many moons ago, but that's not the point. I was curious if anyone has an idea on a more efficient way of writing this code, with less loops and conditionals and, well, noise in the code.</p>
<p>Code in question:</p>
<pre><code>private function pageLinks($num, $page = 1, $search = false, $ne = false) {
$query = ($search) ? '&query='.$search : null;
$by = (is_numeric($ne)) ? '&by='.$ne : null;
$links = 'Page(s):<a href="search.php?page=1' . $query . $by . '" class="tableLink">1</a>';
$count = 1;
$npp = $this->numPerPage;
$buttons = 9;
$half = 4;
for($i = 1; $i <= $num; $i++) {
if(($i%$npp) === 0) {
$count++;
}
}
if($count < $buttons) {
for($i = 2; $i <= $count; $i++) {
$links .= '<a href="search.php?page=' . $i . $query . $by . '" class="tableLink">' . $i . '</a>';
}
} elseif($page <= ($half + 2)) {
for($i = 2; $i <= $buttons; $i++) {
$links .= '<a href="search.php?page=' . $i . $query . $by . '" class="tableLink">' . $i . '</a>';
}
$links .= '...<a href="search.php?page=' . $count . $query . $by . '" class="tableLink">' . $count . '</a>';
} elseif($page <= ($count - ($half + 2))) {
$links .= '...';
for($i = $half; $i > 0; $i--) {
$links .= '<a href="search.php?page=' . ($page - $i) . $query . $by . '" class="tableLink">' . ($page - $i) . '</a>';
}
$links .= '<a href="search.php?page=' . ($page - $i) . $query . $by . '" class="tableLink">' . ($page - $i) . '</a>';
for($i = 1; $i <= $half; $i++) {
$links .= '<a href="search.php?page=' . ($page + $i) . $query . $by . '" class="tableLink">' . ($page + $i) . '</a>';
}
$links .= '...<a href="search.php?page=' . $count . $query . $by . '" class="tableLink">' . $count . '</a>';
} else {
$links .= '...';
for($i = $buttons - 1; $i >= 0; $i--) {
$links .= '<a href="search.php?page=' . ($count - $i) . $query . $by . '" class="tableLink">' . ($count - $i) . '</a>';
}
}
return($links);
}
</code></pre>
<p>The method is called like so:</p>
<pre><code>$links = $this->pageLinks($count, $page, $url, $ne);
</code></pre>
<p>And the variables are as such:</p>
<p><code>$count</code> = total number of clients in database <code>(int)</code><br>
<code>$page</code> = current page to build from <code>(int)</code><br>
<code>$url</code> = the name or email for the search <code>(String)</code><br>
<code>$ne</code> = is for the search string either by name (1) or email (2) <code>(int)</code></p>
<p>And the output is something like (as links):</p>
<p>Page(s):<code>1</code> <code>2</code> <code>3</code> <code>4</code> <code>5</code> <code>6</code> <code>7</code> <code>8</code> <code>9</code>...<code>33</code></p>
<p>Or if you're in the middle (page 20):</p>
<p>Page(s):<code>1</code>...<code>16</code> <code>17</code> <code>18</code> <code>19</code> <code>20</code> <code>21</code> <code>22</code> <code>23</code> <code>24</code>...<code>33</code></p>
<p>Now this isn't always called through a search function, hence the default values for <code>$url</code> and <code>$ne</code>, but that's not very important. My question is there a cleaner way to handle building of these links? Or am I stuck with this cluster of loops?</p>
|
[] |
[
{
"body": "<p>This:</p>\n\n<pre><code>$count = 1;\nfor($i = 1; $i <= $num; $i++) {\n if(($i%$npp) === 0) {\n $count++;\n }\n}\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>$count = floor($num / $npp) + 1;\n</code></pre>\n\n<p>As for the paging, I'd do it like this:</p>\n\n<pre><code>$from = $page - $half;\nif ($from <= 2) $from = 2;\n$to = $page + $half;\nif ($to >= $count - 1) $to = $count - 1;\n\n$extra = $query . $by;\n$links = $this->pageLink(1, $extra);\nif ($from > 2) $links .= \"...\";\nfor ($i = $from; $i <= $to; $i++)\n $links .= $this->pageLink($i, $extra);\nif ($i < $count) $links .= \"...\"; // I use $i instead of $to because $i == $to + 1, so I save one addition\n$links = $this->pageLink($count, $extra);\n</code></pre>\n\n<p>Here, you also need:</p>\n\n<pre><code>private function pageLink($num, $extra) {\n return '<a href=\"search.php?page=' . $num . $extra . '\" class=\"tableLink\">' . $num . '</a>';\n}\n</code></pre>\n\n<p>This was written by heart, so be weary of the possible bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T23:14:49.483",
"Id": "47419",
"Score": "1",
"body": "Genius! Works like a charm! Only bug was a missing `$` in the `pageLink` method, but that's the least of my worries. Wow, it's.. beautiful. Thank you, very informative and exactly what I was looking for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T23:43:56.407",
"Id": "47421",
"Score": "0",
"body": "I've fixed it. Thank you for that, and I'm glad I've been able to help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T22:52:58.783",
"Id": "29898",
"ParentId": "29897",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29898",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T21:52:58.180",
"Id": "29897",
"Score": "2",
"Tags": [
"php",
"object-oriented"
],
"Title": "More simplified way of creating page links dynamically?"
}
|
29897
|
<p>I found <a href="http://projecteuler.net/" rel="nofollow">Project Euler</a> some time ago and I thought I'd enjoy trying those problems.</p>
<p>I'm using C++11 (Visual Studio 2012). I thought I'd program a Manager to test each problem and the time it takes my solution to run. I programmed this:</p>
<p><a href="https://github.com/Joseddg/ProjectEuler/blob/master/ProblemsManager/ProblemsManager.cpp" rel="nofollow"><strong>ProblemsManager.cpp</strong></a></p>
<pre><code>#include "ProblemsManager.h"
#include <algorithm>
#include <iostream>
#include <cstdio>
#include <string>
#include <sstream>
#include <ctime>
ProblemsManager::ProblemsManager() {
}
ProblemsManager::~ProblemsManager() {
}
ProblemsManager & ProblemsManager::getInstance() {
static ProblemsManager instance;
return instance;
}
void ProblemsManager::registerProblem(int n, std::function<PSolution()> solution) {
if (registeredProblems.find(n) != registeredProblems.end()) {
throw std::exception("That problem is already registered!");
} else if (testProblems.find(n) != testProblems.end()) {
throw std::exception("That problem is already registerd as a test problem!");
}
registeredProblems[n] = solution;
}
void ProblemsManager::registerTestProblem(int n, std::function<PSolution()> testSolution) {
if (registeredProblems.find(n) != registeredProblems.end()) {
throw std::exception("That problem already has a valid solution!");
} else if (testProblems.find(n) != testProblems.end()) {
throw std::exception("That problem is already registered!");
}
testProblems[n] = testSolution;
}
void ProblemsManager::run() {
printHeaders();
if (testProblems.size() > 0) {
for (const auto & entry : testProblems) {
log<<"Testing problem "<<entry.first<<": \n";
auto start = std::chrono::steady_clock::now();
PSolution sol = entry.second();
auto end = std::chrono::steady_clock::now();
log<<"Solution reported: "<<sol<<". ("<<timeDifference(start,end).c_str()<<")\n";
std::cout<<"Press any key to continue.\n";
getchar();
}
} else {
for (const auto & entry : registeredProblems) {
// Redirect std::cout (debug msg from the solution to every problem
std::streambuf * coutBuff = std::cout.rdbuf();
std::stringstream debug;
std::cout.rdbuf(debug.rdbuf());
auto start = std::chrono::steady_clock::now();
PSolution sol = entry.second();
auto end = std::chrono::steady_clock::now();
// Restore std::cout to screen
std::cout.rdbuf(coutBuff);
// Reusing the debug stream for the problem to show the information
debug.str(std::string()); // clear stream
debug<<"Problem "<<entry.first;
for (int i= debug.str().size(); i< TIME_MARGIN; i++) {
debug<<" ";
}
debug<<"Time: "<<timeDifference(start,end).c_str();
auto timeInSeconds = std::chrono::duration_cast<std::chrono::seconds>(end - start).count();
if (timeInSeconds > MAX_TIME_SECONDS) {
debug<<" (too much)";
}
for (int i= debug.str().size(); i< ANSWER_MARGIN; i++) {
debug<<" ";
}
debug<<"Solution: "<<sol;
log<<debug.str();
log.endl();
}
}
}
void ProblemsManager::printHeaders() {
/// Get datetime
time_t now = time(NULL);
#pragma warning(push) // Disabling warnings on VS
#pragma warning(disable: 4996) // 4996 for _CRT_SECURE_NO_WARNINGS equivalent
struct tm * ptm = localtime(&now);
#pragma warning(pop)
char buffer[32];
strftime (buffer, 32, "%d/%m/%Y %H:%M:%S", ptm);
log<<"Report generated on: "<<buffer;
log.endl();
log.endl();
// From http://www.informit.com/articles/article.aspx?p=1881386&seqNum=2
log<<"Clock data:";
log.endl();
log<<"\tPrecision: "<<
static_cast<double>(std::ratio_multiply<std::chrono::steady_clock::period,std::kilo>::type::num)
/
static_cast<double>(std::ratio_multiply<std::chrono::steady_clock::period,std::kilo>::type::den)
<<" milliseconds.";
log.endl();
log<<'\t'<<(std::chrono::steady_clock::is_steady?"Steady clock.":"Warning! Non steady clock. Measurements may be inaccurate");
log.endl();
log.endl();
log<<"-----------------------------";
log.endl();
log.endl();
}
std::string ProblemsManager::timeDifference(std::chrono::steady_clock::time_point t1, std::chrono::steady_clock::time_point t2) {
auto msTotalTime = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count();
if (msTotalTime >= 0) {
std::string retValue = "";
if (msTotalTime >= 1000) {
retValue += std::to_string(msTotalTime / 1000);
retValue += "s";
}
retValue += std::to_string(msTotalTime % 1000);
retValue += "ms";
return retValue;
} else {
std::string retValue = "-";
retValue += timeDifference(t2,t1);
return retValue;
}
}
const std::string ProblemsManager::logger::LOG_PATH = "Resources/report.log";
ProblemsManager::logger::logger() : fileStream() {}
ProblemsManager::logger::~logger() {}
void ProblemsManager::logger::endl() {
fileStream<<std::endl;
std::cout<<std::endl;
}
</code></pre>
<p><a href="https://github.com/Joseddg/ProjectEuler/blob/master/ProblemsManager/ProblemsManager.h" rel="nofollow"><strong>ProblemsManager.h</strong></a></p>
<pre><code>#pragma once
#include <functional>
#include <map>
#include <chrono>
#include <fstream>
#include "PSolution.h"
class ProblemsManager {
public:
static ProblemsManager & getInstance();
void registerProblem(int n, std::function<PSolution()> solution);
void registerTestProblem(int n, std::function<PSolution()> testSolution);
void run();
void printHeaders();
private:
ProblemsManager();
~ProblemsManager();
ProblemsManager(const ProblemsManager &);
void operator=(const ProblemsManager &);
std::string static timeDifference(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end);
std::map<int, std::function<PSolution()>> registeredProblems;
std::map<int, std::function<PSolution()>> testProblems;
static const int TIME_MARGIN = 12;
static const int ANSWER_MARGIN = 38;
static const int MAX_TIME_SECONDS = 60;
private:
class logger {
private:
std::ofstream fileStream;
static const std::string LOG_PATH;
public:
logger();
~logger();
void endl();
template<class T>
friend logger & operator<<(logger &log, const T & bytes) {
if (!log.fileStream.is_open()) {
log.fileStream.open(LOG_PATH);
if (log.fileStream.fail()) {
perror("Problem opening log file");
}
}
log.fileStream<<bytes;
std::cout<<bytes;
return log;
}
};
logger log;
};
</code></pre>
<p>Then, I can just use <a href="https://github.com/Joseddg/ProjectEuler/blob/master/ProblemsManager/Problems.h" rel="nofollow"><strong>Problems.h</strong></a>:</p>
<pre><code>#pragma once
#include "ProblemsManager.h"
#include "PSolution.h"
#include <functional>
#include <iostream>
class Problem {
public:
Problem(int n, std::function<PSolution()> f) {
ProblemsManager::getInstance().registerProblem(n,f);
}
~Problem() {
}
};
class TestProblem {
public:
TestProblem(int n, std::function<PSolution()> f) {
ProblemsManager::getInstance().registerTestProblem(n,f);
}
~TestProblem() {
}
};
</code></pre>
<p>And add a .cpp file (<a href="https://github.com/Joseddg/ProjectEuler/blob/master/Problems/Problem1.cpp" rel="nofollow">Problem1.cpp</a>) with the solution for a problem like this:</p>
<pre><code>#include "../ProblemsManager/Problems.h"
#include <iostream>
using namespace std;
static Problem p(1,
[] () -> PSolution {
// Code for the problem...
return solution;
}
);
</code></pre>
<p>The problem I have is: when I run all the problems, some of them run slowly. For example, I get something like this (pastebin ID: WYjbqgc0):</p>
<blockquote>
<p>Note: Problem 52 <br>
Time: 133s171ms <br>
Solution: 142857</p>
</blockquote>
<p>But, if I change <code>Problem</code> to <code>TestProblem</code> in <a href="https://github.com/Joseddg/ProjectEuler/blob/master/Problems/Problem52.cpp" rel="nofollow">Problem52.cpp</a>, so that only this problem can be executed (pastebin ID: t803wLvE):</p>
<blockquote>
<p>Note: Solution <br>
Reported: 142857 (2s156ms)</p>
</blockquote>
<p>I mainly have two questions:</p>
<ol>
<li>Why do the performances differ? </li>
<li>How can I improve my <code>ProblemManager</code>?</li>
</ol>
<p>Also, I have noticed it take a long time for the program to terminate (after the return, in <code>main()</code>). Is that because of all the <code>static</code> variables? If so, how can I fix that?</p>
|
[] |
[
{
"body": "<p>First of all, stylistic matters:</p>\n\n<p>Why are you making <code>ProjectManager</code> a singleton? There is no need to require that only one exists: it doesn't use of any global state except itself, and the logging path could easily be passed in using the constructor (along with any of the other \"constants\" that seem rather arbitrary). If you want to treat problems as more than just <code>int</code>, <code>std::function<PSolution()></code> tuples you can write a class for them, but as things are I don't see you using it as such.</p>\n\n<p>Neither do I see why you'd want to hide the <code>logger</code>. A stream which functions as a bundle of other streams sounds like something you may want to use in multiple projects; write it up properly and use it.</p>\n\n<p>I'm not sure why you've made the <code>Problem</code>/<code>TestProblem</code> distinction. They sound like they have weaker restrictions: let that be decided by the constructor parameters or <code>run</code> parameters or template parameters, but don't duplicate code just for that. Especially seeing as how you ignore real problems entirely if there are any <code>testProblems</code> available.</p>\n\n<p>What you're doing with the debug stream looks like too much trouble for me. If you want to ignore all output from the problems, why not just set the <code>rdbuf</code> to <code>nullptr</code>?</p>\n\n<p>You don't handle the case where a solution takes infinite time to execute. Perhaps it should only wait <code>MAX_TIME_SECONDS</code> and after that kill the thing?</p>\n\n<p>Why are you first writing everything to <code>debug</code>, and only then to <code>log</code>?</p>\n\n<p>As for your performance problems: quite frankly, I'm not sure. Does only adding one problem to the <code>ProblemManager</code> and running it as a normal problem work? Is the difference only in what is printed, or is it actually present?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T17:12:45.010",
"Id": "47461",
"Score": "0",
"body": "Thanks for all your suggestions. \nAbout the singleton, you're right, i'll be changing that. \nI will also rewrite the logger properly. \nThe Problem/TestProblem distinction allows me to test just a problem without having to wait for all other problems to run. \nI didn't know I could set rdbug to nullptr, I'll be doing that.\nAbout killing the problems if they take longer than MAX_TIME_SECONDS to run, i would like to do that, but I am jnot dealing with threads for just now. \nI write to debug and then to log just to make formatting easier, but maybe there is another more elegant and efficient way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T17:15:36.537",
"Id": "47462",
"Score": "0",
"body": "Still, my main worries are the performance problem and the stylistic regarding having one .cpp file with all the static functions and a Problem variable static. Is that a good idea?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T17:33:46.157",
"Id": "47463",
"Score": "0",
"body": "@Trollkemada: No; as soon as you make it not-a-singleton, you should also make the problems non-static. You might also want to look into a function to run only a single problem, and then have the parameterless run function call that for every element. It'll be much easier to debug that way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T17:49:16.893",
"Id": "47465",
"Score": "0",
"body": "But with all non-static how can I make a problem \"register\" in some way from its .cpp file so that it is runned? (In fact, i just remembered that's the reason why I made ProblemsManager a singleton)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T18:22:12.443",
"Id": "47468",
"Score": "0",
"body": "@Trollkemada: Register it from somewhere in `main`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T15:46:41.673",
"Id": "29924",
"ParentId": "29899",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29924",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-17T22:54:58.050",
"Id": "29899",
"Score": "1",
"Tags": [
"c++",
"performance",
"c++11"
],
"Title": "Differences in execution time for problems manager"
}
|
29899
|
<p>I am trying to implement a class that implements a given schedule. I am trying to design this Scheduler class so it can be paused and everything. I have just written some example code so I can better convey my requirements. I would be grateful if more experienced minds could take a look and tell me if what I have right now is the right way to go about things or if there are better ways to do this. I'd really appreciate some thoughts.</p>
<pre><code>class Scheduler {
private object locker = new object();
private System.Timers.Timer timer = new System.Timers.Timer();
private int[] schedule = null;
private int scheduleIndex = 0;
private bool offline = true;
private bool timerElapsed;
private Thread th;
public Scheduler() {
timer.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsedHandler);
th = new Thread(RunSchedule);
th.Start();
}
public void RunSchedule() {
lock (locker) {
while (schedule == null || scheduleIndex > schedule.length) // this will not throw a NullReferenceException since schedule == null is being checked first
Monitor.Wait(locker);
while (offline)
Monitor.Wait(locker);
// pick up next schedule and start timer and wait till timer finishes
int nextSchedule = schedule[scheduleIndex];
// call external program to execute schedule
timer.Interval = 120 * 1000;
timerElapsed = false;
timer.Start();
while(!timerElapsed)
Monitor.Wait(locker);
}
}
public void Offline() {
lock (locker) {
// pause thread executing RunThread
offline = true;
// also kill timer if running
if (timer.Enabled) {
timer.Stop();
timerElapsed = true;
Monitor.Pulse(locker);
}
}
}
public void Online() {
lock (locker) {
//Pulse thread executing RunThread
offline = false;
Monitor.Pulse(locker);
}
}
public void OfflineTooLong() {
lock(locker) {
this.schedule = null;
}
}
public void ScheduleReady(int[] schedule) {
lock (locker) {
this.schedule = schedule;
this.scheduleIndex = 0;
Monitor.Pulse(locker);
}
}
private void TimerElapsedHandler(object sender, System.Timers.ElapsedEventArgs) {
lock(locker) {
scheduleIndex++;
timerElapsed = true;
Monitor.Pulse(locker);
}
}
}
</code></pre>
<p>As you can see from the code, the intent is to "pause" the thread implementing the schedule when Offline and restart the thread when Online. Also, if you've run through all schedules(ie either <code>schedule == null</code> because you've been Offline too long or <code>scheduleIndex > schedule.length</code>), it should wait to receive a new schedule.</p>
<p>Any thoughts and help will be much appreciated. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T12:18:43.627",
"Id": "47443",
"Score": "0",
"body": "Just to verify: your current code works the way you want and you're looking for improvements of the code and not for improvements of the functionality, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T17:03:46.573",
"Id": "47459",
"Score": "0",
"body": "Hi @svick, I had posted this question with the intent of soliciting improvements in code, however now that you mention it, I wouldn't be averse to improvements in functionality either! The code I posted above was to give an idea of my functionality requirements."
}
] |
[
{
"body": "<p>Your code is super-comlicated for such simple logic. I'm also pretty sure it deadlocks in pretty much any use case.</p>\n\n<pre><code>class Scheduler : IDisposable\n{\n private readonly object scheduleLock = new object();\n private int[] schedule = null;\n private int scheduleIndex = 0;\n private readonly ManualResetEvent collectionResetEvent = new ManualResetEvent(false);\n private readonly AutoResetEvent delayEvent = new AutoResetEvent(false);\n private volatile bool working;\n\n private Thread th;\n\n public Dispose()\n {\n Offline();\n }\n\n public void RunSchedule() \n {\n while (true)\n {\n collectionResetEvent.WaitOne();\n if (!working) return;\n\n lock (scheduleLock)\n {\n if (schedule == null || scheduleIndex >= shedule.Count) \n {\n collectionResetEvent.Reset();\n if (!working) return;\n }\n else\n {\n var nextSchedule = schedule[scheduleIndex++];\n //execute, \n //probably can be done outside the lock\n }\n }\n\n delayEvent.WaitOne(120 * 1000);\n }\n }\n\n public void Offline() \n {\n if (!working) return;\n working = false;\n delayEvent.Set();\n collectionResetEvent.Set();\n th.Join();\n th = null;\n }\n\n public void Online() \n {\n if (working) return;\n working = true;\n th = new Thread(RunSchedule);\n th.Start();\n }\n\n public void OfflineTooLong() \n {\n ScheduleReady(null);\n }\n\n public void ScheduleReady(int[] schedule) \n {\n lock (scheduleLock) \n {\n schedule = schedule;\n scheduleIndex = 0;\n collectionResetEvent.Set();\n delayEvent.Set();\n }\n }\n}\n</code></pre>\n\n<p>This is just an example of how it can be refactored, to give you an idea. It can still potentially deadlock (for example if you call offline and dispose at the same time from different threads) so it requires some tweaking depending on your requirements. <code>RunSchedule()</code> method is somewhat hard to read, it should be splitted into sub-methods. <strong>BartoszKP</strong> makes a perfectly valid points as well, check his answer, if you haven't already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T09:12:11.283",
"Id": "47506",
"Score": "0",
"body": "@Nik- Wow! This is definitely much cleaner! Damn, I can write code, but I over-complicate things. But this is very good. Thanks a lot. Just one question though, as it happens, when Offline is called, I would like to pause the thread implementing the schedule which would mean for code like yours where you use Thread.Sleep(), I will have to call Thread.Interrupt on the thread in case the thread is sleeping. Is that not so? And so far as I understand, Thread.Interrupt should usually be avoided, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T09:40:55.187",
"Id": "47510",
"Score": "0",
"body": "@Sandman, yes, you should avoid using Thread methods, other then `Start` and `Join`. And you should never call `Interrupt`, `Abort` and such. As for sleeping - it will work fine when you call `Offline`, since after exiting sleep the thread will block on `WaitHandle.WaitAll` call. The issue is that to call `Online` again - you 'll have to actually wait for two minutes. I've modified my example, to show, how it can be avoided."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:10:29.360",
"Id": "47513",
"Score": "0",
"body": "@BartoszKP, Nik - Apologies for going off topic, but I have to ask you something! How..I mean how, do you start getting to this point where code starts looking from what I've done to what you guys can do? What is it? Experience, knowledge, books? Suggestions, tips will be deeply appreciated! I mean, for now Nik has given me a direction in which to refactor my code, but how do I get to that point when I can start designing code like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:12:14.883",
"Id": "47514",
"Score": "0",
"body": "@Nik, BartoszKP - I would understand if you guys chose not to answer this question, because it's like one of the countless \"Oh..how do I become a better programmer\" sort of questions! But if you choose to do, I'd be indebted!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:18:32.970",
"Id": "47515",
"Score": "0",
"body": "In any case, I appreciate both your inputs!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:22:50.877",
"Id": "47516",
"Score": "0",
"body": "@Sandman, well, its experience, i guess (i would not exactly call myself _experienced_ tho :)). First you spend a few days debuggin a code, similar to yours, then you learn not to repeat the same mistakes when you encounter similar task. As for how to get to that point... only by actually coding. Working in a team which will _care_ about the quality of your code and will kindly tell you to go rewrite the whole thing because it is awful helps a lot. It helped me in the past, at least. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:54:38.250",
"Id": "47520",
"Score": "0",
"body": "@Nik, BartoszKP - Thanks! Honestly, I haven't worked in a team like that yet. I would definitely like to. I'm sure it will hurt pretty bad being told that my code is crap, but it is something I would definitely like to be put through! Thanks a lot for your patience. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T02:08:03.397",
"Id": "47611",
"Score": "0",
"body": "Hi @Nik - Apologies for bothering you again. I tried using your code with slight modifications but I have run into a problem that I can't get my head around. What happens is that even though ScheduleReady() is being called and it calls Set() on collectionResetEvent, the collectionResetEvent does not seem to receive it! I have pasted my slightly modified code here and the log report at the end of the code. http://pastebin.com/uaneCxDu I could submit this as a new question(on SO) if that'd be better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T04:28:38.237",
"Id": "47618",
"Score": "0",
"body": "Hi @Nik - Never mind! My bad. There was a problem in my code that was calling this. Apologies for wasting your time. However, now that you're here, may I borrow 2 mins of your time to look at some changes(3 changes to be exact) that I made in your code. 2 of them might be potential bugs- one with the _continue_ statement and _delaySet.Reset()_ statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T05:27:59.230",
"Id": "47619",
"Score": "0",
"body": "@Sandman I think you should call `delayEvent.Reset();` in Online() method. As it states i think you only need the first `if (!working) return;` for thread to exit successfully when you call `Offline()`. At least you might want to increment index before last return statement (so you wont run the same task when you call `Online()` next time). `continue` is a good call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T06:08:03.083",
"Id": "47622",
"Score": "0",
"body": "@Nik - Thanks a lot for your time and patience! I appreciate it immensely."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T06:16:23.680",
"Id": "47623",
"Score": "0",
"body": "@Sandman no problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T09:37:14.427",
"Id": "47633",
"Score": "0",
"body": "@Nik - I gave the placement of the delayEvent.Reset() a little thought and it seems like if I place delayEvent.Reset() in Online, there might be a race condition between ScheduleReady() and Online() for setting/resetting delayEvent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T10:00:17.800",
"Id": "47635",
"Score": "0",
"body": "@Sandman there is. If you need to call those methods from different threads, your original version is safer (you can use ManualResetEvent then)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T12:00:19.653",
"Id": "47641",
"Score": "0",
"body": "@Nik - Ahh! That's true, I could now just use ManualResetEvent. Thanks a lot! After your inputs, I refactored my other code as well and I must say, thanks to you I have some of my best code because of your inputs! I'm sure it can be made better, but it still is better than what I had in the beginning."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T06:43:24.810",
"Id": "29941",
"ParentId": "29907",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29941",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T03:29:37.060",
"Id": "29907",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Implementing a Scheduler(something that implements a given schedule)"
}
|
29907
|
<p>This code displays a lot of images based on color in columns. I'm thinking it can probably be optimized a lot better. But I'm wondering if anyone has a more fundamental solution on how this could be improved in regards to speed and legibility.</p>
<p>The database has the equivalent of <a href="http://ark42.com/mtg/gathererdownloader/MTGCardInfo/" rel="nofollow">this XML file</a>. </p>
<p>Any suggestions?</p>
<p><strong>CSS</strong></p>
<pre><code>#row {
margin-top: 0px;
margin-bottom: 0px;
padding: 0;
display: table-row;
}
#col0, #col1, #col2, #col3, #col4, #col5 {
margin-top: 0px;
margin-bottom: 0px;
padding: 0;
display: table-cell;
}
</code></pre>
<p><strong>PHP</strong></p>
<pre><code><?php
$url_core_sets = "cards/HQ/Core Sets/";
$url_expansion = "cards/HQ/Expansions/";
$url_promoCards = "cards/HQ/Promo Cards/";
$url_special_sets = "cards/HQ/Special Sets/";
$url_low_rez = "cards/HQ/Low Rez/"; // low resolution cards (cards that are used when no alternative is available)
$filetype = ".jpg";
$width = 240;
$height = 340;
// figure out which folder the cards are in...
if (file_exists($url_core_sets.$cards[0]['set'])) {
$url = $url_core_sets;
} else if (file_exists($url_expansion.$cards[0]['set'])) {
$url = $url_expansion;
} else if (file_exists($url_promoCards.$cards[0]['set'])) {
$url = $url_promoCards;
} else if (file_exists($url_special_sets.$cards[0]['set'])) {
$url = $url_special_sets;
} else if (file_exists($url_low_rez.$cards[0]['set'])) {
$url = $url_low_rez;
}
// figure out file type...
if(file_exists($url."/".$cards[0]['name'].".full.jpg")) {
$filetype = ".full.jpg";
}
else {
$filetype = ".jpg";
}
class CardData {
public $name;
public $full_path;
public $cost;
}
$colors = array("B", "R", "G", "W", "U");
$color_index = 0;
$current_color = $colors[$color_index];
$columns = array(array(), array(), array(), array(), array(), array());
for($i=0; $i<count($cards); $i+=1) {
$card_data = new CardData();
$card_data->name = htmlentities($cards[$i]['name']);
$card_data->full_path = htmlentities($url.$cards[$i]['set']."/".$cards[$i]['name'].$filetype);
$card_data->cost = $cards[$i]['cost'];
$pos = strpos($card_data->cost, $current_color);
for($j=0; $j<count($colors); $j+=1) { // check if other colors are being used in the current card
if(strcmp($colors[$j], $current_color) != 0) { // if it's not the current color
$other_colors = strpos($card_data->cost, $colors[$j]);
if($other_colors !== false) { // different color is being used
break;
}
}
}
if ($pos === false || $other_colors !== false) { // color doesn't exists in current card OR different color is being used
if($color_index < 5) {
$color_index += 1; // next column
$current_color = $colors[$color_index]; // keep track of current color
}
}
array_push($columns[$color_index], $card_data);
}
$col0Index = 0;
$col1Index = 0;
$col2Index = 0;
$col3Index = 0;
$col4Index = 0;
$col5Index = 0;
while($col0Index != -1 || $col1Index != -1 || $col2Index != -1 || $col3Index != -1 || $col4Index != -1 || $col5Index != -1) {
?>
<div id="row">
<div id="col0">
<?php
if($col0Index != -1) {
$name = $columns[0][$col0Index]->name;
if($name != "") {
$full_path = $columns[0][$col0Index]->full_path;
echo '<img src="'.$full_path.'" alt="'.$name.'" width="'.$width.'" height="'.$height.'">';
$col0Index+=1;
}
else {
$col0Index = -1;
}
}
?>
</div>
<div id="col1">
<?php
if($col1Index != -1) {
$name = $columns[1][$col1Index]->name;
if($name != "") {
$full_path = $columns[1][$col1Index]->full_path;
echo '<img src="'.$full_path.'" alt="'.$name.'" width="'.$width.'" height="'.$height.'">';
$col1Index+=1;
}
else {
$col1Index = -1;
}
}
?>
</div>
<div id="col2">
<?php
if($col2Index != -1) {
$name = $columns[2][$col2Index]->name;
if($name != "") {
$full_path = $columns[2][$col2Index]->full_path;
echo '<img src="'.$full_path.'" alt="'.$name.'" width="'.$width.'" height="'.$height.'">';
$col2Index+=1;
}
else {
$col2Index = -1;
}
}
?>
</div>
<div id="col3">
<?php
if($col3Index != -1) {
$name = $columns[3][$col3Index]->name;
if($name != "") {
$full_path = $columns[3][$col3Index]->full_path;
echo '<img src="'.$full_path.'" alt="'.$name.'" width="'.$width.'" height="'.$height.'">';
$col3Index+=1;
}
else {
$col3Index = -1;
}
}
?>
</div>
<div id="col4">
<?php
if($col4Index != -1) {
$name = $columns[4][$col4Index]->name;
if($name != "") {
$full_path = $columns[4][$col4Index]->full_path;
echo '<img src="'.$full_path.'" alt="'.$name.'" width="'.$width.'" height="'.$height.'">';
$col4Index+=1;
}
else {
$col4Index = -1;
}
}
?>
</div>
<div id="col5">
<?php
if($col5Index != -1) {
$name = $columns[5][$col5Index]->name;
if($name != "") {
$full_path = $columns[5][$col5Index]->full_path;
echo '<img src="'.$full_path.'" alt="'.$name.'" width="'.$width.'" height="'.$height.'">';
$col5Index++;
}
else {
$col5Index = -1;
}
}
?>
</div>
</div>
<?php } ?>
</code></pre>
<p><code>$cards</code> has the following info in it:</p>
<pre><code>$cards[$i]['id']
$cards[$i]['lang']
$cards[$i]['name']
$cards[$i]['cost']
$cards[$i]['type']
$cards[$i]['set']
$cards[$i]['rarity']
$cards[$i]['power']
$cards[$i]['toughness']
$cards[$i]['rules']
$cards[$i]['printedname']
$cards[$i]['printedtype']
$cards[$i]['printedrules']
$cards[$i]['flavor']
$cards[$i]['cardnum']
$cards[$i]['artist']
$cards[$i]['sets']
$cards[$i]['rulings']
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T04:57:00.940",
"Id": "47541",
"Score": "0",
"body": "I think you need to stop for a moment and collect your thoughts. What *exactly* is it you want to optimize/improve? Is it slow? Is the code getting unwieldy?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T05:00:21.893",
"Id": "47542",
"Score": "0",
"body": "Starting from $colors = array(\"B\", \"R\", \"G\", \"W\", \"U\"); where the heart of the code is, I'm trying to figure out if it could be fundamentally better, as in improvement in speed and legibility."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T05:01:14.800",
"Id": "47543",
"Score": "0",
"body": "@WouterHuysentruit: Would be nice if there was a button that would move it to there."
}
] |
[
{
"body": "<h1>Unnecessary <code>strcmp</code></h1>\n\n<p>Part of your code looks like this:</p>\n\n<pre><code>if(strcmp($colors[$j], $current_color) != 0) {\n</code></pre>\n\n<p><code>strcmp</code> is not necessary here; plain equality would work fine and be clearer:</p>\n\n<pre><code>if($current_color !== $colors[$j]) {\n</code></pre>\n\n<h1>Repetition in Output</h1>\n\n<p>I notice you're repeating a lot of code when it comes to output. That should be a clear sign that a loop might be more appropriate. As is, if we were to interpret your <code>$columns</code> array as rows and output something like so:</p>\n\n<pre><code>foreach($columns as $column) {\n foreach($column as $cell) {\n echo \"[]\";\n }\n echo \"\\n\";\n}\n</code></pre>\n\n<p>it might look like this:</p>\n\n<pre><code>[] [] [] [] [] [] [] [] [] []\n[] [] [] [] [] [] []\n[] [] [] [] [] [] [] []\n[] [] [] []\n[] [] [] [] [] [] []\n[] [] [] [] [] [] [] []\n</code></pre>\n\n<p>It would be much easier for us to output it if we could iterate over it the other way, if it were transposed:</p>\n\n<pre><code>[] [] [] [] [] []\n[] [] [] [] [] []\n[] [] [] [] [] []\n[] [] [] [] [] []\n[] [] [] [] []\n[] [] [] [] []\n[] [] [] [] []\n[] [] []\n[]\n[]\n</code></pre>\n\n<p>Fortunately, that's rather easy with <a href=\"https://stackoverflow.com/q/797251\">any of the transpose functions here</a>. Once you do that, your repeated code can suddenly be condensed into this much clearer code:</p>\n\n<pre><code>$rows = transpose($columns);\nforeach($rows as $row):\n?>\n <div class=\"row\">\n <?php for($columnIndex = 0; $columnIndex < 6; $columnIndex++): ?>\n <div class=\"col<?php echo $columnIndex; ?>\">\n <?php\n $card = $row[$columnIndex];\n if(isset($card)):\n ?>\n <!-- snip -->\n <?php endif; ?>\n </div>\n <?php endforeach; ?>\n </div>\n<?php\nendforeach;\n</code></pre>\n\n<p>Note also that I've changed your <code>id</code>s to <code>class</code>es. <code>id</code>s must be unique, but you're using many <code>id=\"row\"</code> and <code>id=\"colN\"</code> in a loop, rendering your document invalid. This is the perfect use case for <code>class</code>.</p>\n\n<p>Taking this further, your CSS rules for each column are the same. Rather than having separate <code>col0</code>, <code>col1</code>, … classes, you could instead just have a <code>column</code> class and apply it to all of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T04:00:25.293",
"Id": "47497",
"Score": "0",
"body": "I didn't really use this but I thought the transpose function was quite clever. Thank you for sharing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T07:03:43.713",
"Id": "47563",
"Score": "0",
"body": "Good answer. But, there is so much more wrong with his code. For instance the 'CardData' class. Why use a class here with all the overhead when it's just a glorified array / stdClass instance? Not to speak about all those DRY-violations. So +1 for good answer, but -1 for incomplete answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T03:54:48.503",
"Id": "47615",
"Score": "2",
"body": "@Pinoniq: You're right that it's incomplete. I wasn't aiming to make it complete; I just listed one main concern (the code duplication) and a few other concerns. I really wasn't expecting this to be the only answer; I was really hoping that there would be another answer to pick up where I left off."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T06:10:10.050",
"Id": "29910",
"ParentId": "29908",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29910",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T05:04:38.753",
"Id": "29908",
"Score": "5",
"Tags": [
"php",
"css"
],
"Title": "Displaying images based on column colors"
}
|
29908
|
<p>I forked <a href="https://github.com/tomchristie/webdriverplus/blob/0.2.0/webdriverplus/__init__.py" rel="nofollow">this repo</a> to be more concise. The code is <a href="https://github.com/capitalsigma/webdriverplus/blob/0.2.0/webdriverplus/__init__.py" rel="nofollow">here</a>. I'll paste it below since that seems to be the style. I removed the class definitions at the bottom that I didn't change -- the edit I'm concerned with is the use of the "class_factory" function at the bottom. </p>
<p>Is this good? Pythonic? </p>
<pre><code>from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.firefox.webdriver import WebDriver as _Firefox
from selenium.webdriver.chrome.webdriver import WebDriver as _Chrome
from selenium.webdriver.ie.webdriver import WebDriver as _Ie
from selenium.webdriver.remote.webdriver import WebDriver as _Remote
from selenium.webdriver.phantomjs.webdriver import WebDriver as _PhantomJS
from webdriverplus.utils import _download
from webdriverplus.webdriver import WebDriverDecorator
from webdriverplus.webelement import WebElement
import atexit
import os
import socket
import subprocess
import time
try:
from urllib2 import URLError
except ImportError:
from urllib.error import URLError
VERSION = (0, 2, 0)
def get_version():
return '%d.%d.%d' % (VERSION[0], VERSION[1], VERSION[2])
class WebDriver(WebDriverDecorator):
_pool = {} # name -> (instance, signature)
_quit_on_exit = set() # set of instances
_selenium_server = None # Popen object
_default_browser_name = 'firefox'
@classmethod
def _at_exit(cls):
"""
Gets registered to run on system exit.
"""
if cls._selenium_server:
cls._selenium_server.kill()
for driver in cls._quit_on_exit:
try:
driver.quit(force=True)
except URLError:
pass
@classmethod
def _clear(cls):
cls._pool.clear()
@classmethod
def _get_from_pool(cls, browser):
"""Returns (instance, (args, kwargs))"""
return cls._pool.get(browser, (None, (None, None)))
def __new__(cls, browser=None, *args, **kwargs):
browsers = {'firefox':Firefox,
'chrome':Chrome,
'ie':Ie,
'remote':Remote,
'phantomjs':PhantomJS,
'htmlunit':HtmlUnit}
quit_on_exit = kwargs.get('quit_on_exit', True)
reuse_browser = kwargs.get('reuse_browser')
signature = (args, kwargs)
browser = browser or cls._default_browser_name
reused_pooled_browser = False
pooled_browser = None
try:
is_str = isinstance(browser, basestring)
except NameError:
is_str = isinstance(browser, str)
if is_str:
browser = browser.lower()
pooled_browser, pooled_signature = WebDriver._get_from_pool(browser)
if pooled_signature == signature:
driver = pooled_browser
reused_pooled_browser = True
elif browser in browsers.keys():
driver = browsers[browser](*args, **kwargs)
else:
raise BrowserNotSupportedError()
# If a WebDriverDecorator/WebDriver is given, add it to the pool
elif isinstance(browser, WebDriverDecorator):
driver = browser
browser = driver.name
else:
kwargs['driver'] = browser
driver = WebDriverDecorator(*args, **kwargs)
browser = driver.name
if reuse_browser and not reused_pooled_browser:
if pooled_browser:
pooled_browser.quit(force=True)
WebDriver._pool[browser] = (driver, signature)
if quit_on_exit:
WebDriver._quit_on_exit.add(driver)
return driver
def __init__(self, browser='firefox', *args, **kwargs):
pass
# Not actually called. Here for autodoc purposes only.
atexit.register(WebDriver._at_exit)
browser_types = ({'name':'Firefox', 'driver':_Firefox},
{'name':'Chrome', 'driver':_Chrome},
{'name':'Ie', 'driver':_Ie},
{'name':'Remote', 'driver':_Remote},
{'name':'PhantomJS', 'driver':_PhantomJS},)
def class_factory(browser_type, bases):
class Class_(*bases):
def __init__(self, *args, **kwargs):
kwargs['driver'] = browser_type['driver']
super().__init__(*args, **kwargs)
Class_.__name__ = browser_type['name']
return Class_
for browser_type in browser_types:
globals()[browser_type['name']] = class_factory(browser_type,
(WebDriverDecorator,))
</code></pre>
|
[] |
[
{
"body": "<p>It's not unknown: python is really good at this, although the more common approach would be to <a href=\"http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/\" rel=\"nofollow\">use a metaclass</a>. The immediate drawbacks are</p>\n\n<p>1) it introduces a state-changing dependency to the import statement. If code that is using this code gets imported in a non-standard way you may get confusing errors because types will or will not appear depending on when this module gets run. It's not a major issue if this code will be imported directly but it's potentially problematic if there is more magic going on elsewhere.</p>\n\n<p>2) less importantly, it's going to play hell with IDE's that try to do autocomplete for you :)</p>\n\n<p>I'm guessing that the super().<strong>init</strong> idiom is a python 3 replacement for type('Name', (),{}) by it's form. If it's not - that is the old way to create a runtime type and it avoids creating and renaming the Class_ class, which seems messy to me. Examples of the 'old way' <a href=\"http://www.ibm.com/developerworks/linux/library/l-pymeta/index.html\" rel=\"nofollow\">here</a></p>\n\n<p>Lastly: this seems like classes that differ only in data, or to be more precise in composition. In cases like that I've always found it more maintainable to do it declaratively with class-level variables and appropriate indirections:</p>\n\n<pre><code>class Browser(object):\n BROWSER = 'browser'\n DRIVER = None\n\n @property\n def name(self):\n return self.BROWSER\n\n def do_something(self):\n self.DRIVER.do_something()\n\n\nclass Firefox(Browser):\n BROWSER = 'Firefox'\n DRIVER = _Firefox\n\nclass Chrome (Browser):\n BROWSER = 'Chrome'\n DRIVER = _Chrome\n</code></pre>\n\n<p>Doing this allows you to do subclassing and overrides as appropriate, which is much hairier with types that have to be created before they can be changed. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T15:42:14.390",
"Id": "47861",
"Score": "0",
"body": "Interesting, thank you for the feedback. Some responses (split across a few comments):"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T15:42:43.267",
"Id": "47862",
"Score": "0",
"body": "`super().__init__()` is Python 3's way of saying (as I understand it) \"walk up my inheritance tree until you find a parent class with an `__init__` method, and then call it with the specified arguments\". I saw type() but avoided it because I found it difficult to specify `__init__` correctly inside of it. I tried defining it as a curried function `init(*args, **kwargs)` that returned a function `__init__(self, *args, **kwargs)` and then doing something like `type('Firefox', _Firefox, dict(__init__ = init(*args, **kwargs)))` but I don't think `self` resolved correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T16:26:07.543",
"Id": "47869",
"Score": "1",
"body": "self should work without special currying as long as the functions being called exist in scope when you call type:in Python 2.7, at least:\n\n def blah(self):\n self.x = '123'\n\n fred = type('fred', (), {'__init__':blah}) \n fred().x\n '123'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T16:35:51.283",
"Id": "47871",
"Score": "0",
"body": "Also, the way you recommend is basically what the original code looks like. I started going in this direction because I needed to subclass all of the browser-related classes in another module, and it seemed wrong to me to copy+paste six different class definitions. I thought it might make the original module cleaner too. Your response suggests, though, that this is poor style. The link you posted about `type()` mentions that \"If you wonder whether you need [metaclasses], you don't.\" Should I avoid them, then, unless I find myself in a situation where they offer a substantially larger benefit?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T16:37:56.557",
"Id": "47873",
"Score": "0",
"body": "And thanks, I'll give `type()` another shot I suppose. I appreciate the feedback alot -- I'll upvote you when I get the rep!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T16:55:25.387",
"Id": "47876",
"Score": "1",
"body": "They are great when there is no reasonable alternative - if you're completely commiting to a fluid runtime environment, its's a cool thing to have. But in a case like this, where the problem domain is basically fixed, it's nice to have the inspectablility and maintainability (and opportunities for documentation!!!) that you get from predefined types. You can also write code to generate code files of conventional types when you have a problem which involves a lot of repetition"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T03:35:49.407",
"Id": "30111",
"ParentId": "29914",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30111",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T07:43:49.170",
"Id": "29914",
"Score": "3",
"Tags": [
"python",
"classes",
"python-3.x",
"meta-programming"
],
"Title": "Streamlining repetitive class definitions in python with a class_factory() function"
}
|
29914
|
<p>This is used to create a directed graph of type <code>T</code>. The directed graph has edges and vertices with values but is directional such that nodes can loop unto themselves or only go a single direction even though 2 vertices are connected. </p>
<p>Things I am looking to get out of this review are:</p>
<ul>
<li><p>My use of a hashMap instead of an <code>ArrayList</code> in the <code>Digraph<T></code> class itself. I was wondering if I could just use an <code>ArrayList</code> and an index but then I would have to test whether something did not exist at a certain <code>id</code> value so it seemed a <code>HashMap</code> was better for this function. </p></li>
<li><p>My copy method for Generics. I implemented a copy method for copying a generic type which seems like a lot of overkill to just copy a value but I don't see a better way to do this copy in Java.</p></li>
<li><p>My exception handling. I would like my Exception handling to be reviewed of how I am creating my own exceptions and handling them. In C++ I would be able to just rethrow the exception after being caught and have the rethrown exception not caught to ensure the program would fail after an exception was hit and not continue. In this way I would have a stack of where the exception occurred and the program terminate. I am not sure if I can rethrow an unhandled exception or what is the best way to do this in Java, maybe just rethrow a runtime exception packaging the exception message? </p></li>
<li><p>Any other overall feedback is helpful. </p></li>
</ul>
<p></p>
<pre><code>import java.lang.reflect.*;
import java.util.*;
class MissingDigraphNodeException extends Exception
{
private static final long serialVersionUID = 1000L;
public MissingDigraphNodeException(String message)
{
super(message);
}
}
class CopyException extends Exception
{
private static final long serialVersionUID = 2000L;
public CopyException(String message)
{
super(message);
}
}
class DigraphNode<T>
{
Integer id;
T data;
ArrayList<DigraphNode<T> > links;
public DigraphNode(Integer i)
{
id = i;
links = new ArrayList<DigraphNode<T> >();
}
public DigraphNode(Integer i, T d)
{
id = i; data = d;
links = new ArrayList<DigraphNode<T> >();
}
public DigraphNode(DigraphNode<T> other)
{
try
{
this.data = copy(other.data);
}
catch (CopyException e)
{
e.printStackTrace();
}
this.links=other.getLinks();
this.id = new Integer(other.id);
}
// is there a better way to copy a generic?
@SuppressWarnings("unchecked")
public T copy( T source ) throws CopyException
{
Class<?> clzz = source.getClass();
Method meth;
Object dupl = null;
try {
meth = clzz.getMethod("clone", new Class[0]);
dupl = meth.invoke(source, new Object[0]);
} catch (Exception e)
{
e.printStackTrace();
throw new CopyException("Error: Copying Generic of T");
}
return (T) dupl;
}
public void setData (T d ) { data = d; }
public void addLink (DigraphNode<T> n) { links.add(n); }
public void addLinks (ArrayList<DigraphNode<T> > ns) { links.addAll(ns); }
public ArrayList<DigraphNode<T> > getLinks()
{
// return a new copy of the list
ArrayList<DigraphNode<T> > l = new ArrayList<DigraphNode<T> >();
for ( DigraphNode<T> i : links )
{
i.links.add(new DigraphNode<T>(i)); // use copy constructor
}
return l;
}
public void printNode()
{
System.out.print("Id: " + id + " links: ");
for ( DigraphNode<T> i : links )
{
System.out.print(i.id + " ");
}
System.out.println();
}
}
public class Digraph<T>
{
private HashMap<Integer,DigraphNode<T> > nodes;
Digraph()
{
nodes = new HashMap<Integer,DigraphNode<T> >();
}
public void printGraph()
{
for ( Map.Entry<Integer, DigraphNode<T> > cursor : nodes.entrySet())
{
cursor.getValue().printNode();
}
}
public void addNode(Integer id) { nodes.put (id,new DigraphNode<T>(id)); }
public void addNodes(ArrayList<Integer> ids)
{
for ( Integer i : ids)
{
nodes.put (i,new DigraphNode<T>(i));
}
}
public void setData (Integer id, T data ) throws MissingDigraphNodeException
{
checkNodeExists(id);
nodes.get(id).setData(data);
}
public void addLink (Integer id, Integer linkId ) throws MissingDigraphNodeException
{
checkNodeExists(id);
checkNodeExists(linkId);
nodes.get(id).addLink(nodes.get(linkId));
}
public void addLinks (Integer id, ArrayList<Integer> links ) throws MissingDigraphNodeException
{
checkNodeExists(id);
for ( Integer i : links )
{
checkNodeExists(i);
nodes.get(id).addLink(nodes.get(i));
}
}
public static void main(String[] args)
{
Digraph<Integer> graph= new Digraph<Integer>();
graph.addNodes(new ArrayList<Integer>(Arrays.asList(1,2,3,4,5)));
try
{
// set the data fields
for ( int i = 1; i <= 5; ++i)
{
graph.setData(i, new Integer(i));
}
// now add the links between digraph nodes
graph.addLinks(1,new ArrayList<Integer>(Arrays.asList(2,3)));
graph.addLinks(2,new ArrayList<Integer>(Arrays.asList(2,4)));
graph.addLinks(3,new ArrayList<Integer>(Arrays.asList(1)));
graph.addLinks(4,new ArrayList<Integer>(Arrays.asList(5)));
graph.printGraph();
}
catch ( MissingDigraphNodeException e)
{
System.out.println(e.getMessage());
}
}
private void checkNodeExists(Integer id) throws MissingDigraphNodeException
{
if ( nodes.isEmpty() || !nodes.containsKey(id) )
{
throw new MissingDigraphNodeException("Error: Digraph Node Id: " + id + " not found in Digrpah");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your use of <code>HashMap</code> is fine.</p>\n\n<p>I agree that your <code>copy()</code> method is overkill. Do you really need to clone the data? If not, then your copy constructor can just be</p>\n\n<pre><code>public DigraphNode(DigraphNode<T> other)\n{\n this.data = other.data;\n this.links = other.links;\n this.id = other.id;\n}\n</code></pre>\n\n<p>Then you can dispense with the whole <code>copy()</code> method, the reflection, and the <code>CopyException</code> class. (In any case, <code>copy()</code> should not have been public.)</p>\n\n<p>You should change most of your <code>Integer</code>s to <code>int</code>s, and let autoboxing / unboxing do its thing. The only difference is that <code>Integer</code> can be <code>null</code>, while <code>int</code> cannot, and you wouldn't want <code>null</code> IDs anyway.</p>\n\n<p>Your exception handling in <code>checkNodeExists()</code> is correct, but unconventional. Exceptions should be for unexpected events. Therefore, your code should abide by the maxim, \"Don't ask for permission; ask for forgiveness.\" The only reason why you would want to call <code>checkNodeExists()</code> is if you want to fetch the node immediately afterwards. With that in mind, you should just go ahead and fetch the node, and throw an exception if that fails.</p>\n\n<pre><code>private DigraphNode<T> getNode(int id) throws MissingDigraphNodeException \n{\n DigraphNode<T> node = nodes.get(id);\n // This assumes that null is not a legitimate value in the map\n if (node == null)\n {\n throw new MissingDigraphNodeException(\"Error: Digraph Node Id: \" + id + \" not found in Digraph\");\n }\n return node;\n}\n</code></pre>\n\n<p>Then, you can eliminate all calls to <code>checkNodeExists()</code>, and replace all <code>nodes.get(id)</code> with <code>getNode(id)</code>.</p>\n\n<p>Finally, the ugliness of</p>\n\n<pre><code>graph.addNodes(new ArrayList<Integer>(Arrays.asList(1,2,3,4,5)))\n</code></pre>\n\n<p>is a sign that something is wrong — you don't want your method signatures to restrict you to a particular implementation of lists. You should replace all mentions of mentions of <code>ArrayList<DigraphNode<T> ></code> and <code>ArrayList<Integer></code> with <code>List<DigraphNode<T> ></code> and <code>List<Integer></code>. Then you can simply say</p>\n\n<pre><code>graph.addNodes(Arrays.asList(1,2,3,4,5));\n</code></pre>\n\n<hr>\n\n<p>Putting it all together…</p>\n\n<pre><code>import java.util.*;\n\nclass MissingDigraphNodeException extends Exception \n{\n private static final long serialVersionUID = 1000L;\n public MissingDigraphNodeException(String message)\n {\n super(message);\n }\n}\n\nclass DigraphNode<T> \n{\n int id;\n T data;\n ArrayList<DigraphNode<T> > links;\n\n public DigraphNode(int i) \n {\n id = i;\n links = new ArrayList<DigraphNode<T> >();\n }\n public DigraphNode(int i, T d) \n { \n id = i; data = d;\n links = new ArrayList<DigraphNode<T> >();\n }\n\n public DigraphNode(DigraphNode<T> other)\n {\n this.data = other.data;\n this.links = other.links;\n this.id = other.id;\n }\n\n public void setData (T d ) { data = d; }\n public void addLink (DigraphNode<T> n) { links.add(n); }\n public void addLinks (List<DigraphNode<T> > ns) { links.addAll(ns); }\n\n public List<DigraphNode<T> > getLinks()\n {\n // return a new copy of the list\n ArrayList<DigraphNode<T> > l = new ArrayList<DigraphNode<T> >(); \n for ( DigraphNode<T> i : links )\n {\n i.links.add(new DigraphNode<T>(i)); // use copy constructor\n }\n return l;\n }\n\n public void printNode()\n {\n System.out.print(\"Id: \" + id + \" links: \");\n for ( DigraphNode<T> i : links )\n {\n System.out.print(i.id + \" \");\n }\n System.out.println();\n }\n}\n\npublic class Digraph<T> \n{\n private HashMap<Integer,DigraphNode<T> > nodes;\n\n Digraph() \n {\n nodes = new HashMap<Integer,DigraphNode<T> >();\n }\n\n public void printGraph()\n {\n for ( Map.Entry<Integer, DigraphNode<T> > cursor : nodes.entrySet())\n {\n cursor.getValue().printNode();\n }\n }\n\n public void addNode(int id) { nodes.put (id,new DigraphNode<T>(id)); }\n\n public void addNodes(List<Integer> ids) \n { \n for ( Integer i : ids)\n {\n nodes.put (i,new DigraphNode<T>(i)); \n }\n }\n\n public void setData (int id, T data ) throws MissingDigraphNodeException \n { \n getNode(id).setData(data);\n }\n\n public void addLink (int id, int linkId ) throws MissingDigraphNodeException \n { \n getNode(id).addLink(getNode(linkId));\n }\n\n public void addLinks (int id, List<Integer> links ) throws MissingDigraphNodeException \n { \n DigraphNode<T> node = getNode(id);\n for ( Integer i : links )\n {\n node.addLink(getNode(i));\n }\n }\n\n private DigraphNode<T> getNode(int id) throws MissingDigraphNodeException \n {\n DigraphNode<T> node = nodes.get(id);\n if (node == null)\n {\n throw new MissingDigraphNodeException(\"Error: Digraph Node Id: \" + id + \" not found in Digraph\");\n }\n return node;\n }\n\n public static void main(String[] args) \n {\n Digraph<Integer> graph= new Digraph<Integer>();\n graph.addNodes(Arrays.asList(1,2,3,4,5));\n\n try \n { \n // set the data fields\n for ( int i = 1; i <= 5; ++i)\n {\n graph.setData(i, i);\n }\n\n // now add the links between digraph nodes\n\n graph.addLinks(1,Arrays.asList(2,3));\n graph.addLinks(2,Arrays.asList(2,4));\n graph.addLinks(3,Arrays.asList(1));\n graph.addLinks(4,Arrays.asList(5));\n\n graph.printGraph();\n }\n catch ( MissingDigraphNodeException e)\n {\n System.out.println(e.getMessage());\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T17:03:26.030",
"Id": "47458",
"Score": "0",
"body": "Thanks a lot for all the great advice this really helps my Java development / understanding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T19:01:38.903",
"Id": "47471",
"Score": "1",
"body": "I really like this line \"Don't ask for permission; ask for forgiveness.\" it helps the thinking on exception handling"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T16:30:01.027",
"Id": "29929",
"ParentId": "29915",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29929",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T08:32:53.030",
"Id": "29915",
"Score": "4",
"Tags": [
"java",
"graph"
],
"Title": "Digraph Code in Java"
}
|
29915
|
<p>I have a data structure called <code>ClientSession</code> which I convert to a <code>String</code> separated by <code>|</code> for each element and back to the data structure. </p>
<pre><code> 18 data ClientSession = ClientSession
19 { sec :: Int
20 , nsec :: Int
21 , username :: String
22 , dbid :: Integer
23 , uuid :: Int
24 , prand :: Int
25 } deriving (Ord, Eq)
26
27 instance Show ClientSession where
28 show (ClientSession
29 { sec = s
30 , nsec = ns
31 , username = un
32 , dbid = db
33 , uuid = ud
34 , prand = pr}) = intercalate "|" ls
35 where ls = [show s, show ns, un, show db, show ud, show pr]
</code></pre>
<p>Then I have a set of functions to <code>read</code> that string and create a <code>ClientSession</code> from the result. The problem is that this set of functions are so ugly that I lay sleepless at night.</p>
<p>I'm looking for feedback on how to make this code more Haskell. It doesn't feel Haskell to me, it feels like I have solved it in another language and then just ported the code straight off. Like when you translate a natural language in Google Translate. </p>
<p>I have thought of different solutions. Maybe I could use template Haskell, or <code>Typeable/Generics</code> type classes in some way, or chain the reading using <code>>>=</code>, or something similar.</p>
<p>I'm still new to Haskell, I've used it on my spare time very little over a couple of years.</p>
<pre><code> 37 fromString :: String -> Maybe ClientSession
38 fromString ss = fromParts $ endBy "|" ss
...
74 fromParts :: [String] -> Maybe ClientSession
75 fromParts (s:ns:un:db:ud:pr:[])
76 = newSessionM (readMaybe s) (readMaybe ns) (Just un) (readMaybe db) (readMaybe ud) (readMaybe pr)
77 fromParts _ = Nothing
78
79 newSessionM :: Maybe Int
80 -> Maybe Int
81 -> Maybe String
82 -> Maybe Integer
83 -> Maybe Int
84 -> Maybe Int
85 -> Maybe ClientSession
86 newSessionM (Just s)
87 (Just ns)
88 (Just un)
89 (Just db)
90 (Just ud)
91 (Just pr) = return $ newSession s ns un db ud pr
92 newSessionM _ _ _ _ _ _ = Nothing
93
94 newSession :: Int -> Int -> String -> Integer -> Int -> Int -> ClientSession
95 newSession s ns un db ud pr = ClientSession
96 { sec = s
97 , nsec = ns
98 , username = un
99 , dbid = db
100 , uuid = ud
101 , prand = pr}
</code></pre>
|
[] |
[
{
"body": "<p>First note that if your <code>username</code> contains a bar <code>'|'</code>, you won't be able to parse the output back. So be sure to check for this.</p>\n\n<p>Since you're already using a parser, it's much easier to read the whole <code>ClientSession</code> using the parser instead of splitting the string and merging the values manually.</p>\n\n<p>First let's define two helper functions:</p>\n\n<pre><code>import Control.Applicative\nimport Data.Char (isDigit)\nimport Data.Functor\nimport Data.List\nimport Text.ParserCombinators.ReadP as P\n\nparseInt :: (Read a, Integral a) => ReadP a\nparseInt = read <$> munch1 isDigit <* P.optional (char '|')\n</code></pre>\n\n<p>This one reads one or more digits, consumes <code>'|'</code> if there is one, and converts the digits into a number. (Combinator <code><*</code> runs two actions sequentially, but keeps only the result of the first one.)</p>\n\n<pre><code>parseNotBar :: ReadP String\nparseNotBar = munch (/= '|') <* P.optional (char '|')\n</code></pre>\n\n<p>Similarly tihs second function reads a string until it hits <code>'|'</code>, consumes the <code>'|'</code> optionally and returns the string.</p>\n\n<p>Then it's easy to construct a <code>Read</code> instance. The parser library already has a handy function <code>readP_to_S</code> that converts a parser into a <code>ReadS</code> function:</p>\n\n<pre><code>instance Read ClientSession where\n readsPrec _ = readP_to_S parseClientSession\n where\n parseClientSession :: ReadP ClientSession\n parseClientSession =\n ClientSession <$> parseInt <*> parseInt <*> parseNotBar\n <*> parseInt <*> parseInt <*> parseInt\n</code></pre>\n\n<p>or more shortly</p>\n\n<pre><code>instance Read ClientSession where\n readsPrec _ = readP_to_S $\n ClientSession <$> parseInt <*> parseInt <*> parseNotBar\n <*> parseInt <*> parseInt <*> parseInt\n</code></pre>\n\n<hr>\n\n<p>Note: The last part is similar to what you have done in your <code>newSessionM</code>. Realizing that <code>Maybe</code> is an <code>Applicative</code> instance you could have written</p>\n\n<pre><code>newSessionM s ns un db ud pr\n = ClientSession <$> s <*> ns <*> un <*> db <*> ud <*> pr\n</code></pre>\n\n<p>instead. This generalizes it to any <code>Applicative</code>, not just <code>Maybe</code>, so it can be used on <code>Maybe</code> as well as <code>ReadP</code> or any other applicative parser, for example as</p>\n\n<pre><code>parseClientSession =\n newSessionM parseInt parseInt parseNotBar\n parseInt parseInt parseInt\n</code></pre>\n\n<p>However, using <code><$></code> and <code><*></code> makes the notation usually short enough so that we use the combinators directly without the need to define such helper functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T19:30:39.133",
"Id": "47473",
"Score": "0",
"body": "Now that's the Haskell way to do it! :) Thanks for taking time to explain! I clearly have much to learn."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T12:02:03.157",
"Id": "29922",
"ParentId": "29917",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29922",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-08-18T10:24:17.510",
"Id": "29917",
"Score": "2",
"Tags": [
"strings",
"parsing",
"haskell"
],
"Title": "Converting from ClientSession to String and back"
}
|
29917
|
<p>Here is the SlimDX version:</p>
<pre><code> var form = new SlimDX.Windows.RenderForm("Test");
form.Width = 1280;
form.Height = 1024;
SlimDX.Direct3D9.PresentParameters presentParams = new SlimDX.Direct3D9.PresentParameters
{
BackBufferWidth = form.Width,
BackBufferHeight = form.Height,
DeviceWindowHandle = form.Handle,
PresentFlags = SlimDX.Direct3D9.PresentFlags.None,
Multisample = SlimDX.Direct3D9.MultisampleType.None,
BackBufferCount = 0,
PresentationInterval = SlimDX.Direct3D9.PresentInterval.Immediate,
SwapEffect = SlimDX.Direct3D9.SwapEffect.Flip,
BackBufferFormat = SlimDX.Direct3D9.Format.X8R8G8B8,
Windowed = true,
};
var device = new SlimDX.Direct3D9.Device(new SlimDX.Direct3D9.Direct3D(), 0, SlimDX.Direct3D9.DeviceType.Hardware, form.Handle, SlimDX.Direct3D9.CreateFlags.HardwareVertexProcessing, presentParams);
device.Viewport = new SlimDX.Direct3D9.Viewport(0, 0, form.Width, form.Height);
SlimDX.Direct3D9.Sprite sprite;
sprite = new SlimDX.Direct3D9.Sprite(device);
SlimDX.Windows.MessagePump.Run(form, () =>
{
sprite.Begin(SlimDX.Direct3D9.SpriteFlags.None);
device.BeginScene();
Stoptimer = Stopwatch.StartNew();
Stoptimer.Start();
var tx = SlimDX.Direct3D9.Texture.FromStream(device, ms, 0, 0, 0, SlimDX.Direct3D9.Usage.None, SlimDX.Direct3D9.Format.X8R8G8B8, SlimDX.Direct3D9.Pool.Managed, SlimDX.Direct3D9.Filter.None, SlimDX.Direct3D9.Filter.None, 0);
Stoptimer.Stop();
System.Console.WriteLine(Stoptimer.ElapsedMilliseconds.ToString());
sprite.Draw(tx, Color.Transparent);
sprite.End();
tx.Dispose();
device.EndScene();
device.Present();
});
</code></pre>
<p>This is very slow at higher resolutions and also not that fast at lower ones. I don't quite understand why, as I thought, it would be faster since it uses the GPU.</p>
<p>And here is the drawing version:</p>
<pre><code>newImage = Image.FromStream(ms);
gmp.DrawImage(newImage, 0, 0);
</code></pre>
<p>It's just that inside a loop (SlimDX has its own loop inside the message pump).</p>
<p>Can you tell me why drawing is faster? From my understanding, drawing with Panels and such is slow, as it's made for complete compatibility and isn't optimized for hardware acceleration.</p>
<p>And this is supposed to redraw constantly as a new image will arrive all the time (<code>ms</code> is from a TCP Stream then put in a memorystream when received).</p>
<p>I basically ask for an analysis of the code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T12:16:45.133",
"Id": "47442",
"Score": "0",
"body": "Have you tried to profile the code? Is the slow part actually where you expect it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T22:11:11.343",
"Id": "47480",
"Score": "0",
"body": "I have tried using stopwatch at many places, and the slowest thing is the Texture From Stream. I even checked if it was the stream itself (tried imagefrom stream just to check it alone), and that was super fast compared to the Texture conversion:S"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-09T09:15:26.333",
"Id": "113691",
"Score": "0",
"body": "Not a performance tip (you really should be profiling first to help us here), but I'd recommend wrapping your tx variable in a using statement to ensure it gets properly disposed even when an exception occurs."
}
] |
[
{
"body": "<p>You seem to be timing this code:</p>\n\n<pre><code> var tx = SlimDX.Direct3D9.Texture.FromStream(device, ms, 0, 0, 0, SlimDX.Direct3D9.Usage.None, SlimDX.Direct3D9.Format.X8R8G8B8, SlimDX.Direct3D9.Pool.Managed, SlimDX.Direct3D9.Filter.None, SlimDX.Direct3D9.Filter.None, 0);\n</code></pre>\n\n<p>This code is loading a texture not rendering the scene. So to fix:</p>\n\n<ol>\n<li>Move the texture loading outside of the message pump (textures should be loaded once).</li>\n<li>Time your draw call <code>sprite.Draw(tx, Color.Transparent);</code> instead.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-06T13:11:51.967",
"Id": "110001",
"ParentId": "29919",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T10:42:40.823",
"Id": "29919",
"Score": "-1",
"Tags": [
"c#",
"performance"
],
"Title": "Drawing faster than SlimDX?"
}
|
29919
|
<p>I wrote a PowerShell script for a <a href="https://superuser.com/a/528499/50173">superuser question</a>:</p>
<blockquote>
<p>list of all files and directories under a path recursively, without recursing into junction points or links</p>
</blockquote>
<p>I have a strong feeling that my code is way too complicated for such a simple task. </p>
<pre><code>function Recurse($path) {
$fc = new-object -com scripting.filesystemobject
$folder = $fc.getfolder($path)
foreach ($i in $folder.files) { $i | select Path }
foreach ($i in $folder.subfolders) {
$i | select Path
if ( (get-item $i.path).Attributes.ToString().Contains("ReparsePoint") -eq $false) {
Recurse($i.path)
}
}
}
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$outputlist = Recurse($scriptPath) | Out-File -Filepath .\outputlist.txt
</code></pre>
<p><strong>Short instructions on how to use the script:</strong></p>
<ol>
<li>Paste the code into a text file and save it as PowerShell (.ps1) script</li>
<li>Place the script inside a folder to list all files+folder recursively without junction folder loops</li>
<li>Execute the script. A new file called <code>outputlist.txt</code> at the same location will appear</li>
</ol>
<p><strong>Questions:</strong></p>
<ol>
<li>Can I simplify this PowerShell script anyhow? </li>
<li>Is there a better Out-command where no blank spaces are appended after every line?</li>
</ol>
|
[] |
[
{
"body": "<p>Here's a shot at it: (Requires PowerShell v3 or higher)</p>\n\n<p>The idea here is to get all non-reparsepoint directories first.\nFor each directory, recurse into the subdirectory and then output the files at the current level.</p>\n\n<p>In it's simplest form, it looks like this:</p>\n\n<pre><code>function Get-ChildItemNoReparsePoint($Path)\n{\n Get-ChildItem -Path $Path -Attributes !ReparsePoint -Directory | foreach { \n Get-ChildItemNoReparsePoint $_.Fullname\n }\n Get-ChildItem -File $Path \n}\n</code></pre>\n\n<p>A more full example is shown below:</p>\n\n<p>We hook into the powershell help system by adding specially formatted comment.</p>\n\n<p>By adding the [CmdletBinding()] attribute, we get access to the powershell common parameters (Get-Help about_Common_Parameters).</p>\n\n<p>By adding the OutputType attribute, you get tab completion after the command in the pipeline. (try 'Get-ChildItemNoReparsePoint| Foreach <tab>')</p>\n\n<p>The Parameter attribute enables usage of the function in a pipeline (together with the PSPath alias).</p>\n\n<pre><code>function Get-ChildItemNoReparsePoint\n{\n<#\n.SYNOPSIS\n Gets all files of a directory recursivly, excluding reparse points\n.OUTPUTS\n System.IO.FileInfo\n.EXAMPLE\ndir | Get-ChildItemNoReparsePoint \n.EXAMPLE\nGet-ChildItemNoReparsePoint ~/Documents | Foreach FullName | Set-Content thefiles.txt\n.EXAMPLE\nGet-ChildItemNoReparsePoint ~/Documents -OutVariable files | Foreach FullName | Set-Content thefiles.txt\n$files | Group-Object Extension\n#>\n[CmdletBinding()]\n[OutputType([System.IO.FileInfo])]\nparam(\n [Parameter(ValueFromPipelineByPropertyName)]\n [Alias('PSPath')]\n # Specifies a path to one or more locations.\n [string[]]$Path=$pwd\n)\nprocess\n{\n Get-ChildItem -Path $Path -Attributes !ReparsePoint -Directory | Get-ChildItemNoReparsePoint \n Get-ChildItem -File $Path\n}\n</code></pre>\n\n<p>Set-Content can be used instead of Out-File to bypass PowerShell's formatting step.</p>\n\n<pre><code>Get-NonReparsePointDirectoryFiles | foreach FullName | Set-Content -PassThru thefiles.txt\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-08T21:55:33.790",
"Id": "32435",
"ParentId": "29930",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32435",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T17:51:39.003",
"Id": "29930",
"Score": "4",
"Tags": [
"recursion",
"windows",
"powershell"
],
"Title": "Recursive Windows Directory listing"
}
|
29930
|
<p><em>Background info on <a href="http://en.wikipedia.org/wiki/Factorization" rel="nofollow noreferrer">factoring</a> and <a href="http://en.wikipedia.org/wiki/Prime_factorization" rel="nofollow noreferrer">prime factorization</a></em>.</p>
<p>I've remade this program from my <a href="https://codereview.stackexchange.com/questions/24399/simple-and-efficient-code-for-finding-factors-and-prime-factorization">first attempt</a>, and I'm sure it can still be improved. My questions:</p>
<ol>
<li>These calculations should only be done with positive integers. Would something like <code>template</code>s help keep this type-safe? What about throwing an exception?</li>
<li>Is this an effective way to use the <code>typedef</code>s? Only the classes need them, so it seems better to qualify them with each class rather than a <code>namespace</code>.</li>
<li>Can both <code>calculate()</code>s be better optimized, considering they perform numerous divisions?</li>
<li>I'm not quite liking the call to <code>calculate()</code> in both <code>display()</code>s, even though there are no data member changes. Is this still okay? It doesn't quite make sense to perform the calculations in the constructor, and <code>calculate()</code> should still be <code>private</code>.</li>
</ol>
<p><strong>Factors.h</strong></p>
<pre><code>#ifndef FACTORS_H
#define FACTORS_H
#include <cstdint>
#include <map>
class Factors
{
private:
typedef std::map<std::uint64_t, std::uint64_t> FactorsList;
std::uint64_t integer;
FactorsList calculate() const;
public:
Factors(std::uint64_t);
void display() const;
};
#endif
</code></pre>
<p><strong>Factors.cpp</strong></p>
<pre><code>#include "Factors.h"
#include <cmath>
#include <iostream>
Factors::Factors(std::uint64_t i) : integer(i) {}
Factors::FactorsList Factors::calculate() const
{
float sqrtInt = std::sqrt(static_cast<float>(integer));
FactorsList factors;
for (std::uint64_t i = 1; i <= sqrtInt; ++i)
{
if (integer % i == 0)
{
factors[i] = integer / i;
}
}
return factors;
}
void Factors::display() const
{
FactorsList factors = calculate();
for (auto iter = factors.cbegin(); iter != factors.cend(); ++iter)
{
std::cout << iter->first << " x " << iter->second << "\n";
}
}
</code></pre>
<p><strong>Primes.h</strong></p>
<pre><code>#ifndef PRIMES_H
#define PRIMES_H
#include <cstdint>
#include <map>
class Primes
{
private:
typedef std::map<std::uint64_t, std::uint64_t> PrimesList;
std::uint64_t integer;
PrimesList calculate() const;
public:
Primes(std::uint64_t);
void display() const;
};
#endif
</code></pre>
<p><strong>Primes.cpp</strong></p>
<pre><code>#include "Primes.h"
#include <iostream>
Primes::Primes(std::uint64_t i) : integer(i) {}
Primes::PrimesList Primes::calculate() const
{
std::uint64_t intCopy = integer;
std::uint64_t divisor = 2;
PrimesList primes;
while (intCopy % divisor == 0)
{
intCopy /= divisor;
primes[divisor]++;
}
for (divisor = 3; intCopy > 1; divisor += 2)
{
while (intCopy % divisor == 0)
{
intCopy /= divisor;
primes[divisor]++;
}
}
return primes;
}
void Primes::display() const
{
PrimesList primes = calculate();
for (auto iter = primes.cbegin(); iter != primes.cend(); ++iter)
{
if (iter != primes.cbegin()) std::cout << " x ";
std::cout << iter->first;
if (iter->second > 1) std::cout << '^' << iter->second;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T09:31:40.983",
"Id": "49296",
"Score": "2",
"body": "One thing i can say right off, you could probably roughly double the speed of `Primes::calculate` by checking 2 independently, and then only checking odd numbers. (Once you've factored out all the 2s, `intCopy` won't be divisible by any even number.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T15:20:07.343",
"Id": "49311",
"Score": "0",
"body": "@cHao: It works. Thanks! You may put that as an answer, along with anything else you find, and I'll vote on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T15:22:56.810",
"Id": "49312",
"Score": "0",
"body": "@cHao: I've also just realized that it was already mentioned in my previous question, but oh well. At least this has been confirmed now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T18:17:54.603",
"Id": "49338",
"Score": "0",
"body": "@cHao: I'll go ahead and make this change anyway (again, I should've gotten it from the first post). Feel free to address anything else you may find."
}
] |
[
{
"body": "<p>Yes. You can use template, if you use template, you won't be able to separate the declarations and definitions of member functions without explicit instantiations, which is exactly what you need. Only the instantiated types will then be allowed. For example;</p>\n\n<pre><code>//header file test.h\n#ifndef TEST_H\n#define TEST_H\n\ntemplate<typename T>\nclass Test{\npublic:\n T doSomething();\n};\n\n#endif\n\n//test.cpp\n#include\"test.h\"\n\n//explicit instantiations\ntemplate class Test<unsigned char>;\ntemplate class Test<unsigned short>;\ntemplate class Test<unsigned int>;\ntemplate class Test<unsigned long>;\ntemplate class Test<unsigned long long>;\n\n\ntemplate<typename T>\nT Test<T>::doSomething(){\n return T();\n}\n\n//main.cpp\n#include<iostream>\n#include\"test.h\"\n\nint main(){\n std::cout << Test<long>().doSomething(); //linker error, no compilation\n std::cout << Test<unsigned long>().doSomething(); //compile and works well\n}\n</code></pre>\n\n<p>Also the use of <code>typedef</code> inside the class is not a bad idea. It serves the purpose of keeping the use of the <code>alias</code> limited to the class and its members.</p>\n\n<p>Another thing I would like to point out is , since this is a local library, you might as well have a read only file that contains the list of prime numbers attached to the primes library, this will make the prime factorization of very large numbers a lot more faster. For example in the <code>primes.cpp</code> file you can add</p>\n\n<pre><code>std::ifstream PRIMES;\n#define OPEN_PRIMES PRIMES.open(\"primes\");\n#define CLOSE_PRIMES PRIMES.close();\n</code></pre>\n\n<p>and you will be able to do</p>\n\n<pre><code>std::uint64_t divisor;\nOPEN_PRIMES;\nfor (; intCopy > 1 && PRIMES >> divisor;){\n while (intCopy % divisor == 0){\n intCopy /= divisor;\n primes[divisor]++;\n }\n}\nCLOSE_PRIMES;\n</code></pre>\n\n<p>Also you can check out how to generate factors from prime factorization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T23:15:08.577",
"Id": "49369",
"Score": "0",
"body": "So, `Test` will be a new class? Will `main()` include this along with the other headers, or will `Test` be kept inside of them (and not included in `main()`)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T23:18:44.370",
"Id": "49370",
"Score": "0",
"body": "@Jamal I don't really understand your first question. Everything depends on how you link."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T23:24:22.660",
"Id": "49371",
"Score": "0",
"body": "I mean, you're defining `Test` as a new class. I just want to confirm if all the templating will happen in there, while being used by the client code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T23:30:14.070",
"Id": "49372",
"Score": "1",
"body": "On compilation, the compiler will produce instances of the classes for each template provided and therefore will not take any other instance afterwards. http://msdn.microsoft.com/en-us/library/by56e477.aspx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T23:45:47.707",
"Id": "49374",
"Score": "0",
"body": "I have the test working. I just need to figure out how to use this concept with the other classes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-10T00:19:38.697",
"Id": "49376",
"Score": "0",
"body": "@Jamal If you google `Template C++`, you'll get many results that can help you have better understanding of templates. Also, consult [Wikipedia](http://en.wikipedia.org/wiki/Template_(C%2B%2B))"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-10T00:23:28.350",
"Id": "49377",
"Score": "0",
"body": "Right. I'll do that. This was pretty much not taught in school, so I have to teach myself."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-09T21:42:54.067",
"Id": "31021",
"ParentId": "29932",
"Score": "1"
}
},
{
"body": "<p><code>Factors::calculate()</code> can be sped up by:</p>\n\n<ol>\n<li><p>performing two integer adds after each iteration to determine loop termination</p>\n\n<ul>\n<li><code>std::sqrt()</code>'s overhead, calculations, and casting can be slow</li>\n<li><code>for</code>-loops shouldn't increment towards a floating-point value</li>\n<li>incrementing towards an <em>integer</em> value is faster <em>and</em> proper</li>\n<li>adding is generally fast and can be done in place of multiplication</li>\n</ul></li>\n<li><p>starting the loop counter at 2 or 3 (if <code>integer</code> is even or odd respectively)</p>\n\n<ul>\n<li>fewer increments means fewer division operations (division is slow)</li>\n</ul></li>\n</ol>\n\n<p>This integer add method replaces multiplication as such:</p>\n\n<pre><code>0*0 = 0\n1*1 = 1 = 0 + 1\n2*2 = 4 = 1 + 3\n3*3 = 9 = 4 + 5\n4*4 = 16 = 9 + 7\n// etc.\n</code></pre>\n\n<p>Revised function with explanations:</p>\n\n<pre><code>Factors::FactorsList Factors::calculate() const\n{\n FactorsList factors;\n std::uint64_t incr = 0; // will increment by 2 each iteration\n std::uint64_t incrSum = 1; // will accumulate value of 'incr' each iteration\n\n // if integer is even, i starts at 2\n // if integer is odd, i starts at 3\n std::uint64_t i = (integer % 2 == 0) ? 2 : 3;\n\n // 'i' is only incremented by 1 for checking each number\n // value of 'incrSum' will determine loop termination\n for (; incrSum <= integer; ++i)\n {\n if (integer % i == 0)\n {\n factors[i] = integer / i;\n }\n\n incr += 2;\n incrSum += incr;\n }\n\n return factors;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T19:57:11.337",
"Id": "59505",
"Score": "0",
"body": "(Non C++ expert talking here) Is one call to `std::sqrt()` really more costly than multiple `i*i` calls? For small number of iterations I would expect this to be true, but at some point I would think that x number of `i*i` calls is less efficient than one `std::sqrt()`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T19:59:52.207",
"Id": "59507",
"Score": "0",
"body": "@SimonAndréForsberg: I have been told that the function itself is a bit slow. The main issue with this is that I would need to do casting to work with the function, and I cannot have that in the loop."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T00:34:09.027",
"Id": "36259",
"ParentId": "29932",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "31021",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T18:34:19.063",
"Id": "29932",
"Score": "8",
"Tags": [
"c++",
"primes"
],
"Title": "Remake of factoring/prime factorization calculator"
}
|
29932
|
<p>I'm looking to get some feedback on a small <code>printf</code>-like function I wrote that provides simplified behavior similar to <code>boost::format</code>:</p>
<pre><code>#ifndef EXT_FORMAT_HPP__
#define EXT_FORMAT_HPP__
// ext::format
// Implements a variadic printf-like function providing behavior similar to
// boost::format
#include <regex>
#include <sstream>
#include <string>
#include <utility>
namespace {
inline std::string format_helper(
const std::string &string_to_update,
const size_t) {
return string_to_update;
}
template <typename T, typename... Args>
inline std::string format_helper(
const std::string &string_to_update,
const size_t index_to_replace,
T &&val,
Args &&...args) {
std::regex pattern{"%" + std::to_string(index_to_replace)};
std::string replacement_string{(std::ostringstream{} << val).str()};
return format_helper(
std::regex_replace(string_to_update, pattern, replacement_string),
index_to_replace + 1,
std::forward<Args>(args)...);
}
} // namespace
namespace ext {
template <typename... Args>
inline std::string format(const std::string &format_string, Args &&...args) {
return format_helper(format_string, 1, std::forward<Args>(args)...);
}
} // namespace ext
#endif
</code></pre>
<p>Usage example:</p>
<pre><code>#include "format.hpp"
#include <iostream>
struct foo {
int value;
foo(int val) : value{val} {
}
};
std::ostream &operator<<(std::ostream &os, const foo &f) {
os << "foo(" << f.value << ")";
return os;
}
int main() {
double tmp = 37.382;
std::cout << ext::format("%1 + %2 * %1 = %3", 5, tmp, 5 + tmp * 5) << std::endl;
// Support user defined types provided the appropriate operator<< overload is defined.
foo a_foo(55);
std::cout << ext::format("Here is a foo constructed with 55: %1", a_foo) << std::endl;
};
</code></pre>
<p>This is not written to replace <code>boost::format</code>; it's intended to be used as a header-only include with a very limited scope. As currently written, it is possible to supply too few or too many arguments to the parameter pack. Passing too few arguments will return a string that still has format specifiers. Passing excess arguments are simply ignored and you pay the price of excess calls to <code>std::regex_replace</code>, which will do nothing. With that in mind, I'm looking for any and all feedback.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T01:46:01.347",
"Id": "47555",
"Score": "0",
"body": "I made some changes that hopefully makes the code easier to read. I refactored `format_helper` for clarity rather than trying to squeeze everything into the return call. I also renamed variables to be more descriptive and reduced all line lengths to be within 80 characters."
}
] |
[
{
"body": "<p>I find this to be a sweet demo, but I don't like the traps in it for the unwary. Like you mention, there is little validation of parameter counts. There is also a chance that the same location can be replaced multiple times, e.g. with a call to <code>ext::format(\"%1\", \"%2\", \"%3, \"%4\", \"hi!\")</code> resulting in <code>\"hi!\"</code>. Perhaps you might consider that a bonus.</p>\n\n<p>What I find most surprising in the code is this:</p>\n\n<blockquote>\n<pre><code>std::string replacement_string{(std::ostringstream{} << val).str()};\n</code></pre>\n</blockquote>\n\n<p>I would probably have tended towards <code>auto replacement_string{std::to_string(val)};</code> or, more likely, just embedded that in the call to <code>regex_replace</code>. Do you do this for compatibility with existing code that provides an overload for <code>operator<<</code> but not <code>to_string</code>?</p>\n\n<p>Finally, I'm torn about the use of <code>regex</code>. It seems like a pretty big hammer without a lot of need, here, however it does keep the code short and sweet, and implicitly avoids an infinite loop that a flawed implementation might have with <code>ext::format(\"%1\", \"%1\")</code>.</p>\n\n<p>Reviewing the tests, I find the <code>Does_Not_Alter_Format_String</code> test to be surprising as well. I would have thought the <code>const</code> qualifier would indicate this well enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T04:13:26.757",
"Id": "60947",
"Score": "0",
"body": "I didn't know about `std::to_string` overloading! I did it primarily to support any class that overloads `operator<<`. Thank you for the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T09:07:19.373",
"Id": "461613",
"Score": "0",
"body": "I believe it would be possible to just call `to_string(val)`, and provide a template `ext::to_string()` that uses `<<`, for those classes without their own `to_string()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T05:00:46.220",
"Id": "35505",
"ParentId": "29935",
"Score": "3"
}
},
{
"body": "<h2>FTBFS</h2>\n\n<p>This code doesn't compile here (GCC 9.2, -std=c++2a):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>29935.cpp:24:64: error: ‘class std::basic_ostream<char>’ has no member named ‘str’\n 24 | std::string replacement_string{(std::ostringstream{} << val).str()};\n | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~\n</code></pre>\n\n<p>I had to expand that to keep a reference to the concrete class:</p>\n\n<pre><code> std::ostringstream stream{};\n stream << val;\n std::string replacement_string{stream.str()};\n</code></pre>\n\n<h2>Major</h2>\n\n<p>We can pass <code>%%</code> to <code>std::sprintf()</code> to produce a single <code>%%</code>, but that doesn't work here, so there's no way for the format string to specify a literal <code>%1</code> to output.</p>\n\n<h2>Very minor</h2>\n\n<p>There's a stray <code>;</code> after the definition of <code>main()</code> in the test program.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-17T09:03:55.317",
"Id": "235771",
"ParentId": "29935",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "35505",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-08-18T22:37:53.330",
"Id": "29935",
"Score": "9",
"Tags": [
"c++",
"c++11",
"variadic"
],
"Title": "A small printf-like function using variadic templates"
}
|
29935
|
<p>I am making some basic temperature conversion methods, and I want the end result to look something like this: </p>
<pre><code>double celsius = TemperatureConvert.convert(10, Temperature.FAHRENHEIT, Temperature.CELSIUS);
// Where 'Temperature' is an enum with three values: FAHRENHEIT, CELSIUS, and KELVIN
// This mehtod is read logically as "convert 10 degrees fahrenheit to celsius"
</code></pre>
<p>Originally, I thought that the best approach was to have some private methods inside <code>TemperatureConvert</code> to do the conversion for me. I quickly discovered I was wrong. I want to make this method dynamic, so I used my Google Fu and found <a href="https://stackoverflow.com/questions/12935709/call-a-specific-method-based-on-enum-type">this answer</a>. If you don't want to read it, the answers basically tell OP about the ability to have an abstract method in the enum class, and then have each enum override it.</p>
<p>I am having some trouble figuring out the best approach. Here are the two possibilities I came up with:</p>
<ol>
<li>Create <em>two</em> abstract methods, <code>convertA()</code> and <code>convertB()</code>. Have <code>convertA()</code> convert to the unit that is first in alphabetical order, and have <code>convertB()</code> convert the other unit. In the <code>TemperatureConvert.convert()</code> method, I can figure out what method to use by comparing the enum name. This also brings up an issue if the same unit is passed into the <code>convert()</code> method, as there is no method to do any conversion. However, no conversion is needed so that might not be a problem.</li>
<li>Create <em>three</em> abstract methods, <code>convertToCelsius()</code>, <code>convertToFahrenheit()</code>, and <code>convertToKelvin()</code>. Use a switch statement to decide which method to use.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T12:32:59.697",
"Id": "47525",
"Score": "0",
"body": "+1 The question doesn't consist any codes but still serves the purpose of this site."
}
] |
[
{
"body": "<p>The <code>java.util.concurrent.TimeUnit</code> enum class provides both a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html#convert%28long,%20java.util.concurrent.TimeUnit%29\" rel=\"nofollow\">generic conversion method</a> and specific methods for each modeled unit, e.g., <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html#toHours%28long%29\" rel=\"nofollow\"><code>toHours</code></a>. You could do something similar and still provide the third-party <code>TemperatureConvert.convert</code> method if you want.</p>\n\n<p>Here's the implementation of <code>SECONDS</code>:</p>\n\n<pre><code>SECONDS {\n public long toNanos(long d) { return x(d, C3/C0, MAX/(C3/C0)); }\n public long toMicros(long d) { return x(d, C3/C1, MAX/(C3/C1)); }\n ...\n public long toHours(long d) { return d/(C5/C3); }\n ...\n public long convert(long d, TimeUnit u) { return u.toSeconds(d); }\n},\n</code></pre>\n\n<p>Note that the author went for efficiency by precalculating many of the conversion constants. I wouldn't bother with that to start as it's probably premature for your needs. Your conversion methods should start simply:</p>\n\n<pre><code>CELCIUS {\n public double toFahrenheit(long t) {\n return t * 9 / 5 + 32;\n }\n public double toKelven(long t) {\n return t + 273;\n }\n public double convert(double t, TemperatureUnit u) {\n return u.toCelcius(v);\n }\n}\n</code></pre>\n\n<p>Also, all of the conversion methods are stubs that throw an exception rather than abstract. Why? I don't know. If these weren't enums and could be extended, stub methods that fail only when called are handy for allowing optional operations--think <code>Collection.remove(Object)</code> which throws <code>UnsupportedOperationException</code> if not implemented by the concrete container.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T13:46:52.127",
"Id": "47531",
"Score": "0",
"body": "If you are talking about TimeUnit, then yes, they throw an `AbstractMethodError` if not overridden. It also gives a reference to [Bug JDK-6287639](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6287639)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T16:58:04.707",
"Id": "47545",
"Score": "1",
"body": "@whowantsakookie - So the author made the parent methods concrete to avoid an unresolved feature request in JavaDoc? That's a serious commitment to API documentation clarity. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T03:08:05.610",
"Id": "29938",
"ParentId": "29936",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29938",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T00:53:19.187",
"Id": "29936",
"Score": "3",
"Tags": [
"java",
"design-patterns"
],
"Title": "How to implement a dynamic temperature conversion method based on given enums?"
}
|
29936
|
<p>IS it possible to read directly from the TCPStream to get an image if I know the size and all that, without first saving it to a memorystream?</p>
<p>My code currently works with putting the first 4 byte in the TCP stream as a length for the entire data, so first I send the length. And then I know the length so I recieve it.</p>
<p>But I am saving it to a MemoryStream first, and it would save time to get it directly from the Stream if possible.</p>
<pre><code> tempBytes = new byte[length];
ms = new MemoryStream(tempBytes);
int currentPosition = 0;
while (currentPosition < length)
{
currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
}
newImage = Image.FromStream(ms);
currentPosition = 0;
while (currentPosition < intsize)
{
currentPosition += tt1.GetStream().Read(lenArray, currentPosition, intsize - currentPosition);
}
length = BitConverter.ToInt32(lenArray, 0);
</code></pre>
<p>So this is in a while loop, so you can see, I get the length (well I get it at the end, but I have already got it before the while loop for the first run). Then I read the length of data into a memorystream, then get the image.</p>
<p>But as a NetworkStream is a Stream already, there should be possible to just read it directly.</p>
<p>So is there a way to do this to improve the performance?</p>
<p><strong>EDIT</strong>:</p>
<p>Pseudo code of what I mean:</p>
<p>Read length from Stream:</p>
<pre><code>tt1.GetStream().Read(lenArray,0,4);
length = BitConverter.ToInt32(lenArray, 0);
</code></pre>
<p>Read and get the Image</p>
<pre><code>Image = tt1.GetStream().Read(data,0,length)
</code></pre>
<p>This of course doesn´t work, but it´s what I am trying to do.
I want to read directly from the stream, and as I know the length and all that, it should be possible I think, without having to save to a byte array inside a memorystream.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T11:50:45.243",
"Id": "47522",
"Score": "0",
"body": "Are you saying that the `NetworkStream` can contain multiple images?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T11:56:42.450",
"Id": "47523",
"Score": "0",
"body": "No, i am saying i am sending the length (first 4 byte) then the actual image. So i get the Image in one stream, so i want to know if i can just convert that to an image immediately, without using a memorystream as a \"handler\":)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T15:44:18.220",
"Id": "47746",
"Score": "1",
"body": "you should check out [StackOverflow](http://stackoverflow.com/about) and see if your question fits better there. also check out [Code Review's About](http://codereview.stackexchange.com/about)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T16:20:26.747",
"Id": "47754",
"Score": "0",
"body": "I know, and well i do use it. But sadly, i have used my 30 questions per month. So i try to find limited questions that fits the Review term."
}
] |
[
{
"body": "<p>my though is like this, though i didn't really test it</p>\n\n<ol>\n<li><p>You must keep the stream open for the lifetime of the Image. because the Image.FromStream wont read the data until it needs it, for performance purpose;</p></li>\n<li><p>you must make sure the all the data for that image is received before you call Image.FromStream. TCP could split your data into multiple packages when transfer. since you transfer 4 bytes as the length of that image, you can read the length first, then you can keep checking the length of that NetworkStream, but do not read any data. or you can peek the data but make sure the data is still in the stream;</p></li>\n<li><p>the last condition, do not transfer more data after the image until you are done with the image. otherwise, the data after the image could be treated as the image data. if it is hard for your current application's protocol, you might just use a separated tcp connection for image data only.</p></li>\n</ol>\n\n<p>Update:</p>\n\n<p>Or I think you can derived a class from System.Stream and override the Read method and some other methods as well. Now you can manage how you read the data. This way, you can even work on just the same TCp connection because you know the length. Just pass that derived Stream to the Image.FromStream, that should/might work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T13:31:25.463",
"Id": "47530",
"Score": "0",
"body": "Well, it´s pretty much what i am doing currently. I split up 2 transfers, so i get length in 1 turn and the image in another. But why can´t i use Image.FromStream in one turn and tell it to read \"This\" much data?\n\nAs you say, it waits till the end of the stream (Networkstream doesn´t have an end from what i can grasp), so i would have to close the connection for it to know that.\nWhich isn´t optimal at all, which is why i have the length so i can know when it´s done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T04:01:11.730",
"Id": "47558",
"Score": "0",
"body": "Not really an answer to the question, but as it´s off topic, this general explanation fits the place. Thanks"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T12:53:53.137",
"Id": "29949",
"ParentId": "29944",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29949",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:24:56.123",
"Id": "29944",
"Score": "1",
"Tags": [
"c#",
"stream"
],
"Title": "Get Image From Stream, TCP Stream without converting to MemoryStream first"
}
|
29944
|
<p>How can I make my library more flexible towards programmers? <a href="https://github.com/miguelishawt/pine" rel="nofollow">Here is my library.</a> It's a basic library that provides a simple interface to organise your game (with scenes, and engine/game connection). The only problem that I dislike about it, is the fact that you cannot create a custom 'game loop', you must let the <code>GameLoop</code> class deal with that for you. You can only instead, call to <code>update</code>/<code>draw</code> of the loop if you cannot use a while loop and manually clog the main thread (e.g. Ogre3d and it's call backs to update your game).</p>
<p>I'm also curious on what I can improve upon this library. Does my tutorial make sense? Is my code clean?</p>
<p><a href="https://github.com/miguelishawt/pine" rel="nofollow">https://github.com/miguelishawt/pine</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-03T18:35:27.567",
"Id": "80635",
"Score": "0",
"body": "I am not sure you got notified, but your question was closed a while ago because we require code to be included in the question itself. We don't like being dependent on third-party sites as links tend to go away sooner or later. For more information see [this meta question](http://meta.codereview.stackexchange.com/questions/1308/can-i-put-my-code-on-a-third-party-site-and-link-to-the-site-in-my-question). The site is a lot more active now than it was half a year ago, so it is quite likely that some one can review your code - if you include it in your question."
}
] |
[
{
"body": "<p>A few observations/thoughts from a quick look at the code and accompanying description. Feel free to explain/correct as appropriate:</p>\n\n<ul>\n<li><p>For starters, the <code>Game</code> class seems to delegate everything to the <code>GameLoop</code> class, why? It seems more logical that <code>GameLoop</code> would drive the <code>Game</code> which would make use of <code>GameEngine</code> do to input/output and <code>GameStateStack</code> (or stacks) to keep track of game-related states. As it stands, I need to think in terms of frame changes/deltas in more than one section of the code.</p></li>\n<li><p>When would I want to use the <code>GameLoop</code> as-is as opposed to using <code>isRunning()</code>/<code>update()</code> or deriving from <code>GameLoop</code>? Why not place the call to <code>initialize()</code> in the constructor?</p></li>\n<li><p>Why does <code>GameStateStackListener</code> need to know about the <code>GameStateStack</code>? Does it consume events or produce events? Or both? How do you avoid infinite recursion if both? </p></li>\n<li>Why only one type of <code>GameStateStack</code> per listener? We might want to keep track and be informed of several state types (for instance, a character would want to be notified of changes in gravity <em>and</em> wind).</li>\n</ul>\n\n<p>I think you should make and publish a simple game using this library to illustrate the purpose of each class</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T12:32:04.283",
"Id": "47524",
"Score": "0",
"body": "`When would I want to use the GameLoop as-is as opposed to using isRunning()/update() or deriving from GameLoop?` As I mentioned, in case you don't have total control of the loop (libraries such as Ogre3D have call backs for updating/rendering your game). However, this is a bit iffy with the code in my GameLoop. `Why does GameStateStackListener need to know about the GameStateStack? Does it consume events or produce events? Or both? How do you avoid infinite recursion if both?` GameStateStackListener listens to events from a GameStateStack."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T12:33:39.683",
"Id": "47526",
"Score": "0",
"body": "`Why only one type of GameStateStack per listener? We might want to keep track and be informed of several state types (for instance, a character would want to be notified of changes in gravity and wind).` A state in the game is a main menu, the actual game itself, the paused \"state\". I don't think it makes sense to have multiple GameStateStack's per listener, plus that would be much more complex to implement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T12:34:21.997",
"Id": "47527",
"Score": "0",
"body": "`For starters, the Game class seems to delegate everything to the GameLoop class, why? It seems more logical that GameLoop would drive the Game which would make use of GameEngine do to input/output and GameStateStack (or stacks) to keep track of game-related states.` Good point, I didn't think about that. I'm not quite sure, I just chose composition over inheritance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T12:38:55.673",
"Id": "47529",
"Score": "0",
"body": "I see. The intention behind each class/template is a bit unclear. I stand by my wish to see a simple game implemented using this library. Even a game consisting of a single box moving in a world where gravity and wind change randomly would be enough IMO."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T11:56:11.383",
"Id": "29947",
"ParentId": "29945",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T10:26:30.747",
"Id": "29945",
"Score": "0",
"Tags": [
"c++",
"c++11",
"library",
"library-design"
],
"Title": "Improving the flexibility of my library/what can be improved?"
}
|
29945
|
<p>My code looks like imperative style code. I want to make my code more functional. How I can rewrite my program so it become functional style code?</p>
<pre><code> val _map = getMap();
if(_map.contains(x) && _map.contains(y)) Right(_map(x) + _map(y))
else if(_map.contains(x + y)) Right(_map(x + y))
else if(!_map.contains(x)) Left("%d or %d not found".format(x, x + y))
else if(!_map.contains(y)) Left("%d or %d not found".format(y, x + y))
else Left("What is it?")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:52:13.393",
"Id": "47539",
"Score": "1",
"body": "You realise that your error messages are inaccurate and incomplete? Firstly, it should be \"%d *and* %d not found\" (because a \"not found\" message will only be generated if _map.contains(x + y) => false and either x or y is not in _map). Secondly, it's possible for you to report \"x and x + y not found\" when _map.contains(y) => true and when _map.contains(y) => false (so you're not reporting the state where neither x, nor y, nor x+y are in the map). Thirdly, this code will never return Left(\"What is it?\"). Your errors do demonstrate why the functional approach is often superior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-29T00:12:23.487",
"Id": "273298",
"Score": "0",
"body": "how you will log the x and x + y if you had tested for nonexistence before?"
}
] |
[
{
"body": "<p>In this case, I'd utilize pattern matching. As an example:</p>\n\n<pre><code>def getMap(): Map[String, String] =\n Map[String, String](\"foo\" -> \"bar\", \"baz\" -> \"quux\", \"foobar\" -> \"bazquux\")\n\n// Note that I've simplified this to take Strings\ndef getOption(x:String, y: String): Either[String, Any] = {\n val map = getMap\n val (xOption, yOption, both) = (map.get(x), map.get(y), map.get(x + y))\n\n (xOption, yOption, both) match {\n case (Some(_), Some(_), _) => Right(xOption.get, yOption.get)\n case (_, _, Some(_)) => Right(both.get) \n case (None, _, _) => Left(\"%s and %s not found\".format(x, x + y))\n case (_, None, _) => Left(\"%s and %s not found\".format(y, x + y))\n }\n\n}\n</code></pre>\n\n<p>This has a few benefits. For example, say we commented out the last line:</p>\n\n<pre><code>// case (_, None, _) => Left(\"%s or %s not found\".format(y, x + y))\n</code></pre>\n\n<p>The compiler will then complain at us:</p>\n\n<blockquote>\n <p>warning: match may not be exhaustive. It would fail on the following input: <code>(Some(_), None, None)</code>. </p>\n</blockquote>\n\n<p>Likewise if we add in matches that are unreachable, we'll also get a warning:</p>\n\n<pre><code>case (None, None, None) => Left(\"What is it?\")\n</code></pre>\n\n<blockquote>\n <p>warning: unreachable code <code>case (None, None, None) => Left(\"What is it?\")</code></p>\n</blockquote>\n\n<p>You may want to modify this to be more specific:</p>\n\n<pre><code>(xOption, yOption, both) match {\n case (Some(_), Some(_), _) => Right(xOption.get, yOption.get)\n case (_, _, Some(_)) => Right(both.get) \n case (None, Some(_), None) => Left(\"%s and %s not found\".format(x, x + y))\n case (Some(_), None, None) => Left(\"%s and %s not found\".format(y, x + y))\n case (None, None, None) => Left(\"Nothing at all found!\")\n}\n</code></pre>\n\n<p>We get no compiler errors or warning with this, so we can be sure that all the code is reachable and there will not be any unmatched patterns.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T10:50:16.130",
"Id": "47571",
"Score": "0",
"body": "This is much more idiomatic scala and addresses the objections I raised to the original example. But using pattern matching as the entire solution means you are calculating x+y before you need to. The two \"%s and %s not found\" lines are also nearly identical in function. So while more idiomatic, I do not think this is more \"functional\". I know how I would do this in Scheme but barely know Scala. Hmm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T13:18:55.463",
"Id": "47579",
"Score": "0",
"body": "I'm not too fussed about the calculation of `x + y` - that falls under worrying about premature optimization in my eyes. The string formatting I left \"as-is\", but I agree that it could likely be improved upon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T12:32:15.670",
"Id": "47647",
"Score": "0",
"body": "It doesn't answer the question, is my main point. Pattern matching is a feature of most modern functional languages because it has been shown to aid in the creation of concise and elegant code, but it is not a requirement for functional code nor a defining characteristic of it (that is, a functional language need not have pattern matching as a feature to qualify as functional). Pattern matching can simply the functions used to solve a problem, but this is not what you are doing. More idiomatic, yes; more functional, no."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T02:18:22.617",
"Id": "29971",
"ParentId": "29946",
"Score": "2"
}
},
{
"body": "<p>OK, so I taught myself a little scala and here is something a bit more functional than your example:</p>\n\n<pre><code>val _map = Map(1 -> 2, 2 -> 8, 4 -> 13 )\n\ndef pickSum(x:Int, y:Int): Either[String,Int] = {\n\n /* If the map contains the key k, return Right(value)\n * else return Left(key)\n */\n def pick(k:Int): Either[Int,Int] = {\n _map.get(k) match {\n case Some(v) => Right(v)\n case _ => Left(k)\n }\n }\n\n List(x, y) map { pick } match {\n case List(Right(a), Right(b)) => Right(a + b) // Two matching values: return the sum\n case l:List[Either[Int,Int]] => pick(x + y) match { // At least one failure: try x+y\n case Right(i) => Right(i) // x+y is in the map. Return the value\n // Otherwise, return the list of keys not found in the map\n case e:Left[_,_] => Left( e :: l collect { case Left(i) => i } mkString(\"Not found in map: \", \",\", \"\") ) \n }\n } \n} \n</code></pre>\n\n<p>Testing this in the Scala repl...</p>\n\n<pre><code>scala> pickSum(1,2)\nres0: Either[String,Int] = Right(10)\n\nscala> pickSum(2,4)\nres1: Either[String,Int] = Right(21)\n\nscala> pickSum(2,3)\nres2: Either[String,Int] = Left(Not found in map: 5,3)\n\nscala> pickSum(1,3)\nres3: Either[String,Int] = Right(13)\n\nscala> pickSum(3,7)\nres4: Either[String,Int] = Left(Not found in map: 10,3,7)\n</code></pre>\n\n<p>This does more or less what your code does; it either returns a Right() with the desired Integer value or a Left() containing a string explaining which keys could not be found in the map. Personally, in the case of failure I had rather just return a Left containing a list of the failed keys, to be handled as some other part of the code saw fit.</p>\n\n<p>The core function, here, is to look for a key in the map and either return the matching value wrapped in a Right() or, if there is no such key, the rejected key wrapped in a Left(). I went straight for <strong>Map.get</strong> rather than checking with <strong>.contains()</strong> because the former returns an <strong>Option</strong>, which allows more concise and expressive code.</p>\n\n<p>You should notice that nowhere in the code do I re-assign a value (hell, I don't even create any <strong>vals</strong>, let alone <strong>vars</strong>). Instead, I return a series of immutable collections, each one derived from the previous one. This is one aspect of functional programming.</p>\n\n<p>So...</p>\n\n<pre><code>List(x, y) map { pick }\n</code></pre>\n\n<p>This makes a list out of the given keys and then creates from that a list of the corresponding values <em>or</em> the rejected keys. I then do some pattern matching</p>\n\n<pre><code>case List(Right(a), Right(b)) => Right(a + b)\n</code></pre>\n\n<p>If this matches, we have successfully retrieved two values. Return the sum. And we're done here. Otherwise...</p>\n\n<pre><code>case l:List[Either[Int,Int]] => pick(x + y)\n</code></pre>\n\n<p>So this matches a list but doesn't care what it contains, because we know there was at least one failure or the previous match would have succeeded. Matching all the permutations of failure in one line is less fragile than listing them all, if there's only one action to take. So now we look for _map(x + y) and match the result...</p>\n\n<pre><code>case Right(i) => Right(i) \n</code></pre>\n\n<p>If this matches, _map(x + y) exists so we return it and that's it. Otherwise...</p>\n\n<pre><code>case e:Left[_,_] =>\n</code></pre>\n\n<p>OK, (x + y) is not a valid key. So what the rest of that line does is </p>\n\n<ol>\n<li>Adds Left(x + y) to the head of the list: <strong>e :: l</strong></li>\n<li>Collects all the invalid keys from the list: <strong>collect { case Left(i) => i }</strong></li>\n<li>Builds a string containing the invalid keys: <strong>mkString</strong></li>\n<li>Wraps the resulting string in a <strong>Left()</strong></li>\n</ol>\n\n<p>I'm sure this could be done better, since I only learned enough Scala to do this in the last 24 hours. However, it is (like Yuushi's answer) more idiomatic while also using some functional programming techniques (however modestly).</p>\n\n<p>To genuinely improve my example code, it would help to know why you're doing this slightly odd thing.</p>\n\n<p>To summarise the differences between your example and mine:</p>\n\n<ul>\n<li>All the <strong>else if</strong> statements make yours very fragile.</li>\n<li>Each individual <strong>else if</strong> statement is almost the same (i.e. using _map.contains()), giving room for error with all that duplication.</li>\n<li>You could easily miss a permutation.</li>\n<li>You might (in fact you do) have code paths that can never be evaluated.</li>\n<li>I avoid duplication almost entirely.</li>\n<li>Pattern matching makes it almost certain I catch all the permutations.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-25T11:54:02.963",
"Id": "47993",
"Score": "0",
"body": "Since writing this answer, I discovered that the braces in \"List(x, y) map { pick }\" can be left out and that \"List(x, y) map pick\" is more idiomatic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T02:49:50.690",
"Id": "30058",
"ParentId": "29946",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T11:51:45.037",
"Id": "29946",
"Score": "3",
"Tags": [
"error-handling",
"scala",
"optional"
],
"Title": "Adding two values in a map, if they exist"
}
|
29946
|
<p>A picture says more than a thousand words, so here's a mock-up. The actual choices are different, this is just a sample.</p>
<p><img src="https://i.stack.imgur.com/4HZDQ.png" alt="mock-up"></p>
<p>A user first has to choose between <em>Red</em>, <em>Blue</em> and <em>Green</em>. Upon selecting an option, additional form elements are displayed, depending on the choice. For <em>Blue</em>, a <em>Date</em> and <em>Font</em> are required.</p>
<p>Currently, there's no need for a third level, but who knows what the future brings. In order to represent this data, I've come up with the following model (after many attempts).</p>
<pre><code>public class SampleWizard
{
public enum ColourChoice
{
Red,
Blue,
Green
}
public class RedModel
{
public IEnumerable<SelectListItem> AvailableShapes { get; set; }
public int Shape { get; set; }
public DateTime Date { get; set; }
}
public class BlueModel
{
public enum FontChoice
{
Arial,
Helvetica,
Other,
}
public DateTime Date { get; set; }
public FontChoice Font { get; set; }
public IEnumerable<SelectListItem> AvailableOtherFonts { get; set; }
public int OtherFont { get; set; }
}
public ColourChoice Colour { get; set; }
public RedModel Red { get; set; }
public BlueModel Blue { get; set; }
}
</code></pre>
<p>I'm using <code>Enum</code>s for hard-coded choices, so I can make decisions based on the value. <code>int</code>s come from the database and do not matter in the programmed decision flows.</p>
<p>This works, but I can't help but feel like this is an ugly solution and I'm worried about future modifications. I've never had to make something like this before so I can't make decisions based on past experiences.</p>
<p>The UI design is more or less set in stone, unless strong arguments can be made against it. (I'd need to bring them up to the designer and project manager.)</p>
|
[] |
[
{
"body": "<p>Well, i think, you should first ask yourself do you really want to complicate things? Is this something that you will re-use in other places? Because the feeling \"i need to create something reusable and extendable\" if familiar to every one of us, but the amount of code you'll need to write and debug is not always worth it in the end.</p>\n\n<p>If you answer is \"no\", then you can simply do a little refactoring: move classes to separate files, replace individual viewmodel properties with <code>Dictionary<ColourChoice, ViewModelBase></code>, stuff like that. It will end up looking fine.</p>\n\n<p>If your answer is \"yes\", then i would probably create a tree-like structure from my view models by implementing something like:</p>\n\n<pre><code>interface ITreeViewModel\n{\n IEnumerable<ITreeItem> Children { get; }\n bool IsSelected { get; }\n ITreeItem Parent { get; }\n}\n</code></pre>\n\n<p>Then i would create a custom user control wich will display such tree using this interface and specidied <code>DataTemplate</code>s (after i will fail to make wpf TreeView work as i want it too yet again -_-). This is a tricky task with plenty of pitfalls, but i think its possible. At least that would be an approach I'd try first.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T07:18:08.367",
"Id": "47564",
"Score": "0",
"body": "It looks like I forgot to mention an important part: this is an MVC app, so all this has to model bind on a form submit. The proposed solutions do sound good for WinForms/WPF, so +1."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T06:24:14.690",
"Id": "29979",
"ParentId": "29950",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29979",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T13:21:46.893",
"Id": "29950",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc-4"
],
"Title": "Modeling a decision tree-like form"
}
|
29950
|
<p>I am writing a Java app that gets the metadata of files in a directory and exports it to a .csv file. The app works fine if the number of files is fewer than a million. But if I feed in a path that has about 3200000 files in all of directories and sub-directories, it takes forever. Is there a way I can speed up things here?</p>
<pre><code> private void extractDetailsCSV(File libSourcePath, String extractFile) throws ScraperException {
log.info("Inside extract details csv");
try{
FileMetadataUtil fileUtil = new FileMetadataUtil();
File[] listOfFiles = libSourcePath.listFiles();
for(int i = 0; i < listOfFiles.length; i++) {
if(listOfFiles[i].isDirectory()) {
extractDetailsCSV(listOfFiles[i],extractFile);
}
if(listOfFiles[i].isFile()){
ScraperOutputVO so = new ScraperOutputVO();
Path path = Paths.get(listOfFiles[i].getAbsolutePath());
so.setFilePath(listOfFiles[i].getParent());
so.setFileName(listOfFiles[i].getName());
so.setFileType(getFileType(listOfFiles[i].getAbsolutePath()));
BasicFileAttributes basicAttribs = fileUtil.getBasicFileAttributes(path);
if(basicAttribs != null) {
so.setDateCreated(basicAttribs.creationTime().toString().substring(0, 10) + " " + basicAttribs.creationTime().toString().substring(11, 16));
so.setDateLastModified(basicAttribs.lastModifiedTime().toString().substring(0, 10) + " " + basicAttribs.lastModifiedTime().toString().substring(11, 16));
so.setDateLastAccessed(basicAttribs.lastAccessTime().toString().substring(0, 10) + " " + basicAttribs.lastAccessTime().toString().substring(11, 16));
}
so.setFileSize(String.valueOf(listOfFiles[i].length()));
so.setAuthors(fileUtil.getOwner(path));
so.setFolderLink(listOfFiles[i].getAbsolutePath());
writeCsvFileDtl(extractFile, so);
so.setFileName(listOfFiles[i].getName());
noOfFiles ++;
}
}
} catch (Exception e) {
log.error("IOException while setting up columns" + e.fillInStackTrace());
throw new ScraperException("IOException while setting up columns" , e.fillInStackTrace());
}
log.info("Done extracting details to csv file");
}
public void writeCsvFileDtl(String extractFile, ScraperOutputVO scraperOutputVO) throws ScraperException {
try {
FileWriter writer = new FileWriter(extractFile, true);
writer.append(scraperOutputVO.getFilePath());
writer.append(',');
writer.append(scraperOutputVO.getFileName());
writer.append(',');
writer.append(scraperOutputVO.getFileType());
writer.append(',');
writer.append(scraperOutputVO.getDateCreated());
writer.append(',');
writer.append(scraperOutputVO.getDateLastModified());
writer.append(',');
writer.append(scraperOutputVO.getDateLastAccessed());
writer.append(',');
writer.append(scraperOutputVO.getFileSize());
writer.append(',');
writer.append(scraperOutputVO.getAuthors());
writer.append(',');
writer.append(scraperOutputVO.getFolderLink());
writer.append('\n');
writer.flush();
writer.close();
} catch (IOException e) {
log.info("IOException while writing to csv file" + e.fillInStackTrace());
throw new ScraperException("IOException while writing to csv file" , e.fillInStackTrace());
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T14:45:53.253",
"Id": "47532",
"Score": "0",
"body": "Which version of java do you use ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T14:53:34.533",
"Id": "47533",
"Score": "0",
"body": "@Marc-Andre I use Java 7"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T14:56:04.903",
"Id": "47534",
"Score": "0",
"body": "This link could help you docs.oracle.com/javase/tutorial/essential/io/walk.html it's a tutorial about walking a file tree using java nio"
}
] |
[
{
"body": "<p>You are continually accessing the array for the current item, but never using the index for anything else. This is exactly what for-each loops are for.</p>\n\n<pre><code>for (File f : listOfFiles) {\n //use f instead of listOfFiles[i]\n}\n</code></pre>\n\n<hr>\n\n<p>The following code is full of repetition:</p>\n\n<pre><code>if(basicAttribs != null) {\n so.setDateCreated(basicAttribs.creationTime().toString().substring(0, 10) + \" \" + basicAttribs.creationTime().toString().substring(11, 16));\n so.setDateLastModified(basicAttribs.lastModifiedTime().toString().substring(0, 10) + \" \" + basicAttribs.lastModifiedTime().toString().substring(11, 16));\n so.setDateLastAccessed(basicAttribs.lastAccessTime().toString().substring(0, 10) + \" \" + basicAttribs.lastAccessTime().toString().substring(11, 16));\n}\n</code></pre>\n\n<p>Instead, make a function to perform the repeated action.</p>\n\n<pre><code>public FileTime createDate(FileTime time) {\n String timeStr = time.toString();\n return timeStr.substring(0, 10) + \" \" + timeStr.substring(11, 16));\n}\n</code></pre>\n\n<p>There should also be a way to create a <code>Date</code> form <code>FileTime</code> which will let you just use <code>SimpleDateFormat</code> instead of doing the string manipulation by hand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T21:11:50.567",
"Id": "29966",
"ParentId": "29952",
"Score": "3"
}
},
{
"body": "<p>I suspect that using the old <code>File</code> class of Java is the possible root problem of your solution right now. Since you're using Java 7, you should use those new classes. I've seen that you use some of them like <code>Path</code>, so it shouldn't be too difficult. I don't what your class look at moment so I've changed some method base on what I'm use to do. So the class I will be using is <code>SimpleFileVisitor</code> since this is the basic implementation of <code>FileVisitor</code>.</p>\n\n<p>So I've created a class <code>Walker</code> (this is a very bad name, you should change it for something clearer for you, since I have no good idea right now) that extends <code>SimpleFileVisitor</code>. The class has an attribute <code>extractFile</code> that correspond to the filename of the csv. This class will have the <code>preVisitDirectory</code>, <code>visitFile</code> and <code>visitFileFailed</code> that we will override from the <code>FileVisitor</code>. I've also added your method <code>writeCsvFileDtl</code>, <code>createDate</code> (thanks to @unholysampler, you should read his answer too).</p>\n\n<p>So the class should look like that :</p>\n\n<pre><code>import static java.nio.file.FileVisitResult.CONTINUE;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.nio.file.FileVisitResult;\nimport java.nio.file.Path;\nimport java.nio.file.SimpleFileVisitor;\nimport java.nio.file.attribute.BasicFileAttributes;\nimport java.nio.file.attribute.FileTime;\n\npublic class Walker extends SimpleFileVisitor<Path> {\n\n private String extractFile;\n\n public Walker(String extractFile) {\n this.extractFile = extractFile;\n }\n\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attr)\n throws IOException {\n populateAndWrite(dir, attr);\n return CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {\n populateAndWrite(file, attr);\n return CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) {\n //You should determine if you need this method or not\n return CONTINUE;\n }\n\n private void populateAndWrite(Path file, BasicFileAttributes attr) {\n ScraperOutputVO so = new ScraperOutputVO();\n if (file.getParent() != null) {\n so.setFilePath(file.getParent().toString());\n }\n\n if (file.getFileName() != null) {\n so.setFileName(file.getFileName().toString());\n }\n\n so.setFileType(getFileType(file.toAbsolutePath().toString()));\n\n if (attr != null) {\n so.setDateCreated(createDate(attr.creationTime()));\n so.setDateLastModified(createDate(attr.lastModifiedTime()));\n so.setDateLastAccessed(createDate(attr.lastAccessTime()));\n }\n if (!attr.isDirectory()) {\n so.setFileSize(String.valueOf(attr.size()));\n }\n\n so.setAuthors(fileUtil.getOwner(file));\n\n so.setFolderLink(file.toAbsolutePath().toString());\n try {\n writeCsvFileDtl(extractFile, so);\n } catch (IOException e) {\n log.info(\"IOException while writing to csv file\" +\n e.fillInStackTrace());\n throw new\n ScraperException(\"IOException while writing to csv file\" ,\n e.fillInStackTrace());\n }\n }\n\n private String createDate(FileTime time) {\n String timeStr = time.toString();\n return timeStr.substring(0, 10) + \" \" + timeStr.substring(11, 16);\n }\n\n private void writeCsvFileDtl(ScraperOutputVO scraperOutputVO) \n throws ScraperException {\n try {\n FileWriter writer = new FileWriter(extractFile, true);\n writer.append(scraperOutputVO.getFilePath());\n writer.append(',');\n writer.append(scraperOutputVO.getFileName());\n writer.append(',');\n writer.append(scraperOutputVO.getFileType());\n writer.append(',');\n writer.append(scraperOutputVO.getDateCreated());\n writer.append(',');\n writer.append(scraperOutputVO.getDateLastModified());\n writer.append(',');\n writer.append(scraperOutputVO.getDateLastAccessed());\n writer.append(',');\n writer.append(scraperOutputVO.getFileSize());\n writer.append(',');\n writer.append(scraperOutputVO.getAuthors());\n writer.append(',');\n writer.append(scraperOutputVO.getFolderLink());\n writer.append('\\n');\n writer.flush();\n writer.close();\n } catch (IOException e) {\n log.info(\"IOException while writing to csv file\" +\n e.fillStackTrace();\n throw new ScraperException(\"IOException while writing to csv file\",\n e.fillInStackTrace());\n\n }\n }\n}\n</code></pre>\n\n<p>The method <code>populateAndWrite</code> is use in <code>preVisitDirectory</code> and <code>visitFile</code>, basically it will populate each attribute of your object <code>ScraperOutputVO</code> and then send it to the the <code>write</code> method. I'm not sure if you to list directories, so if you don't want to just remove <code>preVisitDirectory</code>. I've added some <code>null</code>check since those method can return <code>null</code> if you start at the root directory. </p>\n\n<p>You'll maybe need to tweak some attributes, cause I didn't had access to your <code>fileUtils</code> and <code>getFileType</code>, so you should test to make sure you have the same values.</p>\n\n<p>To launch the class you simply need to something like : </p>\n\n<pre><code>public static void main(String args[]){\n Path root = Paths.get(\"Path to your directory\");\n Walker walker = new Walker(\"Name of your csv file\");\n try {\n Files.walkFileTree(root, walker);\n } catch (IOException e) {\n //you should handle exception here\n //log.info(\"Problem walking the directory\")\n e.printStackTrace();\n }\n}\n</code></pre>\n\n<p>If you need more help just comment on the answer.</p>\n\n<p><strong>Edit:</strong> I find another amelioration that would lower the time of the execution. The problem is when you write to the file, you always create a new <code>FileWriter</code>, open the file, write to it and then close it. So for each file you hit, you're opening accessing the file and closing it which is causing a major drawback on performance. By using your current <code>writeCsvFileDtl</code> it took me like 170 seconds to write 100 000 entries. By leaving open the the <code>FileWriter</code> writing took less than one second. You should do something like that, it is not very elegant (you could probably do something more readable or cleaner) but will enhance the performance.</p>\n\n<pre><code>import java.io.FileWriter;\nimport java.io.IOException;\n\n\npublic class Writer {\n static FileWriter writer = null;\n public static void openFileWriter() {\n try {\n writer = new FileWriter(\"C:/dev/file.txt\", true);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n public static void writeToTheFileWithOpenEachTime(){\n try {\n writer.append(\"firstColumn\");\n writer.append(',');\n writer.append(\"secondColumn\");\n writer.append(',');\n writer.append(\"thirdColumn\");\n writer.append(',');\n writer.append(\"fourthColumn\");\n writer.append(',');\n writer.append(\"fifthColumn\");\n writer.append(',');\n writer.append(\"sixthColumn\");\n writer.append(',');\n writer.append(\"sevenColumn\");\n writer.append(',');\n writer.append(\"eigthColumn\");\n writer.append(',');\n writer.append(\"ninethColumn\");\n writer.append('\\n');\n writer.flush();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public static void closeWriter() {\n\n try {\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T00:08:17.987",
"Id": "29969",
"ParentId": "29952",
"Score": "6"
}
},
{
"body": "<p>I know this is an old post, but something you may want to consider in order to speed up the suggested solution is to avoid (<em>if you can</em>) the <code>FOLLOW_LINKS</code> option in the code below; this improved performance quite significantly in an app I've recently developed:</p>\n\n<pre><code>EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);\n...\nFiles.walkFileTree(path, opts, Integer.MAX_VALUE, visitor);\n</code></pre>\n\n<p>If you don't need follow links, you can simply call the simpler version of walkFileTree:</p>\n\n<pre><code>Files.walkFileTree(path,visitor);\n</code></pre>\n\n<p>This calls the following under the covers:</p>\n\n<pre><code>Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE, visitor);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-29T19:12:08.500",
"Id": "71179",
"ParentId": "29952",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T14:34:39.937",
"Id": "29952",
"Score": "4",
"Tags": [
"java",
"file-system",
"file"
],
"Title": "Java app for getting metadata of millions of files in a directory"
}
|
29952
|
<p>I have several controls that are bound from database tables. Putting my OOP thinking cap on I figured since all of the controls will have a <code>SqlCommand</code> name and an associated <code>SqlDataReader</code> object I decided to make the following interface to program to.</p>
<pre><code>public interface IBoundControl
{
string GetCommandName();
void ReadyReader(SqlDataReader rdr);
}
</code></pre>
<p>For illustration's sake, consider the following to classes which implement <code>IBoundControl</code> interface</p>
<pre><code>public class Hospital : IBoundControl
{
public int HospitalId { get; set; }
public string HospitalName { get; set; }
public string GetCommandName()
{
return "spGetHospitals";
}
public void ReadyReader(SqlDataReader rdr)
{
this.HospitalId = (int)rdr["HospitalId"];
this.HospitalName = (string)rdr["HospitalName"];
}
}
public class Race : IBoundControl
{
public int RaceId { get; set; }
public string RaceDescription { get; set; }
public string GetCommandName()
{
return "spGetRaces";
}
public void ReadyReader(SqlDataReader rdr)
{
this.RaceId = (int)rdr["RaceId"];
this.RaceDescription = (string)rdr["RaceDescription"];
}
}
</code></pre>
<p>The controls are bound to a webform by making a call to the DataAccess class's <code>BindControl</code> method shown below:</p>
<pre><code> public class DataAccess
{
private readonly string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
//takes in a parameter that will be bound to a web form
public List<IBoundControl> BindControl(IBoundControl i)
{
//creates a list of objects which will be bound to drop down lists
List<IBoundControl> controlList = new List<IBoundControl>();
using (var con = new SqlConnection(cs))
{
//grabs the name of the sproc for whatever type 'i' is
using (var cmd = new SqlCommand(i.GetCommandName(), con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
//the factory creates an object of whatever type 'i' is
ControlFactory factory = new ControlFactory();
IBoundControl ibound = factory.CreateControl(i);
ibound.ReadyReader(rdr);
controlList.Add(ibound);
}
}
return controlList;
}
}
public class ControlFactory
{
public IBoundControl CreateControl(IBoundControl control)
{
if (control is Hospital)
return new Hospital();
else if (control is Race)
return new Race();
else
return null;
}
}
}
</code></pre>
<p>To my surprise, this actually worked - the first time, too! I was hoping to get some comments on how this might be improved upon, or if there's any general techniques that while this example might be too rudimentary to show, is bad practice down the road.</p>
<p>EDIT: When I first wrote this, the only controls that I had in mind were drop down controls(which is why both classes have two propeties, an ID and a description).</p>
|
[] |
[
{
"body": "<p>The IBoundControl is good. It isolates the specific data calls. It's refreshing to see another approach than falling back to the repository pattern.</p>\n\n<p>IBoundControl implementation is on a class that also doubles as the DTO. This is breaking the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">SRP</a>. One way to solve this is to create class that's only job is for lookup values. Call it <code>Lookup</code>. It has two fields: <code>Id</code> and <code>Name</code>. </p>\n\n<p>The new interface looks like this:</p>\n\n<pre><code>public interface IBoundControl\n {\n string GetCommandName();\n List<Lookup> ReadyReader(IDataReader rdr);\n }\n</code></pre>\n\n<p>Now the IBoundControl implementation will only contain data layer specific code and will return a normalized resultset of lookup values. Also notice that <code>IBoundControl.ReadyReader</code> is taking a dependency on <code>IDataReader</code> instead of implementation specific <code>SqlDataReader</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T13:06:24.610",
"Id": "47577",
"Score": "0",
"body": "Can you elaborate on how exactly this would work? I can kind of envision what it would look like if it were Lookup was an interface and a called to ILookup.Id would return HospitalId, or RaceId, but I can't envision the method you're talking about in my head."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T05:41:03.013",
"Id": "29977",
"ParentId": "29955",
"Score": "3"
}
},
{
"body": "<p>I would:</p>\n\n<ol>\n<li>Replace <code>string GetCommandName();</code> with <code>string CommandName { get; }</code></li>\n<li><p>Implement abstract class:</p>\n\n<pre><code>abstract class BoundControlBase : IBoundControl\n{\n public abstract void ReadyReader(SqlDataReader rdr);\n\n public string CommandName { get; private set; }\n\n protected BoundControlBase(string commandName)\n {\n CommandName = commandName;\n }\n}\n</code></pre></li>\n<li><p>if keys are always correspond to property names, i would use reflection :) : </p>\n\n<pre><code>//in base class\nprotected void ReadProperty(SqlDataReader rdr, Expression<Func<object>> expression)\n{\n var lambda = (LambdaExpression)expression;\n var memberExpression = (MemberExpression)lambda.Body;\n var propertyInfo = (PropertyInfo)memberExpression.Member;\n propertyInfo.SetValue(this, rdr[propertyInfo.Name], null);\n}\n\n//usage\nReadProperty(rdr, () => RaceId);\n</code></pre>\n\n<p>if not: then i agree with Chuck - you need another layer of abstraction to encapsulate lookup logic.</p></li>\n<li><p>replace <code>return null</code> in <code>CreateControl</code> method with <code>throw new NotSupportedException(\"blah-blah\");</code></p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T07:32:35.537",
"Id": "29981",
"ParentId": "29955",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29977",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T15:24:58.230",
"Id": "29955",
"Score": "5",
"Tags": [
"c#",
"asp.net",
"interface"
],
"Title": "Interface programming with Data Access Layer"
}
|
29955
|
<p>The code creates a Ruby bingo game for the console and works properly. I believe the code I wrote needs some work, though, as I am new to Ruby. Any help would be appreciated. </p>
<pre><code>require "color_text"
class Bingo
def initialize
#map of all places that are possible wins
@columns = [
[:a1,:a2,:a3,:a4,:a5],
[:b1,:b2,:b3,:b4,:b5],
[:c1,:c2,:c3,:c4,:c5],
[:d1,:d2,:d3,:d4,:d5],
[:e1,:e2,:e3,:e4,:e5],
[:a1,:b1,:c1,:d1,:e1],
[:a2,:b2,:c2,:d2,:e2],
[:a3,:b3,:c3,:d3,:e3],
[:a4,:b4,:c4,:d4,:e4],
[:a5,:b5,:c5,:d5,:e5],
[:a1,:b2,:c3,:d4,:e5],
[:e1,:d2,:c3,:b4,:a5]
]
@user = ' X'.red
#Get Number of Users
put_line
puts "\n RUBY BINGO".purple
print "\n How many human players? ".neon
STDOUT.flush
@users_count = gets.chomp.to_i
put_bar
#Get User's Names
@user_name = []
@user_score = []
1.upto(@users_count) do |i|
print "\n Player #{i}, what is your name? ".neon
@user_name << gets.chomp
@user_score[i-1] = 0
put_bar
end
start_game
end
def start_game
#bingo slots
@places = Hash.new { |hash, key| hash[key] = " " }
@places_keys = [
:a1,:a2,:a3,:a4,:a5,
:b1,:b2,:b3,:b4,:b5,
:c1,:c2,:c3,:c4,:c5,
:d1,:d2,:d3,:d4,:d5,
:e1,:e2,:e3,:e4,:e5
]
@bingo_cards = []
fill_cards(@users_count)
user_turn
end
def pick_number(num)
#randomly pick the bingo board numbers
case num
when 0..4
rand(1..15)
when 5..9
rand(16..30)
when 10..11
rand(31..45)
when 12
" X".red
when 13..14
rand(31.45)
when 15..19
rand(46..60)
when 20..24
rand(61..75)
else
0
end
end
def fill_cards(number)
#fill up each bingo card with the random numbers and put in bingo array
number.times do
@places_keys.each_with_index do |n,i|
@places[n] = pick_number(i)
end
@bingo_cards << @places.dup
end
end
def restart_game
(1...20).each { |i| put_line }
start_game
end
def put_line
puts ("-" * 80).gray
end
def put_bar
puts ("#" * 80).gray
puts ("#" * 80).gray
end
def draw_game
#draw out the bingo board for each user
puts ""
puts ""
@bingo_cards.each_with_index do |bingo,i|
puts " #{@user_name[i]}"
puts " 1 #{bingo[:a1]} | #{bingo[:b1]} | #{bingo[:c1]} | #{bingo[:d1]} | #{bingo[:e1]}"
puts " --- --- --- --- ---"
puts " 2 #{bingo[:a2]} | #{bingo[:b2]} | #{bingo[:c2]} | #{bingo[:d2]} | #{bingo[:e2]}"
puts " --- --- --- --- ---"
puts " 3 #{bingo[:a3]} | #{bingo[:b3]} | #{bingo[:c3]} | #{bingo[:d3]} | #{bingo[:e3]}"
puts " --- --- --- --- ---"
puts " 4 #{bingo[:a4]} | #{bingo[:b4]} | #{bingo[:c4]} | #{bingo[:d4]} | #{bingo[:e4]}"
puts " --- --- --- --- ---"
puts " 5 #{bingo[:a5]} | #{bingo[:b5]} | #{bingo[:c5]} | #{bingo[:d5]} | #{bingo[:e5]}"
put_line
puts " Bingo Number: #{@random}".red
end
end
def times_in_column arr, item, bingo
#count the number of X's in the column to see if 5 in a row
times = 0
arr.each do |i|
times += 1 if bingo[i] == item
end
if times == 5
return true
else
return false
end
end
def user_turn
put_line
puts "\n RUBY BINGO".purple
draw_game
print "\n Please type 'go' or type 'exit' to quit: ".neon
STDOUT.flush
input = gets.chomp.downcase.to_str
put_bar
if input.length == 2
@random = rand(1..75)
puts @random
@bingo_cards.each do |bingo|
@places_keys.each do |key|
bingo[key] = @user if bingo[key] == @random
end
end
put_line
check_game(@user)
else
wrong_input unless input == 'exit'
end
end
def wrong_input
put_line
puts " Please type go or exit".red
user_turn
end
def check_game(next_turn)
game_over = nil
@bingo_cards.each_with_index do |bingo, i|
@columns.each do |column|
# see if user has won
if times_in_column(column, @user, bingo) == true
put_line
draw_game
put_line
@user_score[i] += 1
puts ""
puts " Game Over -- #{@user_name[i]} WINS!!!\n".blue
@user_name.each_with_index do |user,z|
puts "#{user} #{@user_score[z]} \n".green
end
game_over = true
ask_to_play_again(true)
end
end
end
unless game_over
user_turn
end
end
def ask_to_play_again(response)
print " Play again? (Yn): "
STDOUT.flush
response = gets.chomp.downcase
case response
when "y" then restart_game
when "yes" then restart_game
when "n" then #do nothing
when "no" then #do nothing
else ask_to_play_again
end
end
end
Bingo.new
</code></pre>
|
[] |
[
{
"body": "<p>I think you could improve the readability of the code if you take advantage of objects. You can have at a minimum, classes for <code>BingoGame</code>, <code>Card</code>, and <code>Player</code>. Possibly <code>Ball</code> too. Having a Card object alone would tuck away a lot of the code related to setting up, checking and outputting cards.</p>\n\n<p>You want to aim for something as simple as this:</p>\n\n<pre><code>game = BingoGame.new\nplayers = 10\nplayers.times do\n game.add_card(Card.new)\nend\nuntil game.winner? do\n wait_for_input\n ball = game.draw_ball\n game.update_cards(ball)\n puts game #overridden to_s which prints each card\nend\n</code></pre>\n\n<p>Where most of the logic is hidden in the objects. Keep each step simple; for example <code>game.update_cards()</code> and <code>game.winner?</code> might be defined in the <code>BingoGame</code> class as:</p>\n\n<pre><code>def update_cards(ball)\n @cards.each do |card|\n card.update(ball)\n end\nend\n\ndef winner?\n @cards.any? {|card| card.winner?}\nend\n</code></pre>\n\n<p>This further pushes specifics down to the card level, asking each card to update itself and tell you if any are a winner. </p>\n\n<p>You may or may not do it exactly like this, but the point is you push the logic into lower-level objects so at any part of the code you're at a manageable level of abstraction.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T20:13:40.793",
"Id": "47552",
"Score": "0",
"body": "Thank you, for example should the card class be within the BingoGame class, or outside of it in its own class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T02:57:26.400",
"Id": "47556",
"Score": "0",
"body": "Ruby doesn't have nested classes, so they should be separate. However, they can be in different files, but it is not necessary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T05:32:26.737",
"Id": "47561",
"Score": "0",
"body": "`players = 10; players.times do; game.add_card(Card.new);end` could be also implemented as `game.add_cards(Array.new(30){Card.new})`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T11:43:57.110",
"Id": "47573",
"Score": "0",
"body": "@Nakilon True, but that's just a stub and an example. He still needs to add functionality (maybe prompt for # of players, their names, etc)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T18:45:08.150",
"Id": "63173",
"Score": "1",
"body": "`@cards.any? &:winner?`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T18:37:44.270",
"Id": "29960",
"ParentId": "29958",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29960",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T16:37:14.410",
"Id": "29958",
"Score": "4",
"Tags": [
"ruby",
"beginner",
"game",
"console"
],
"Title": "Small Ruby Bingo Game"
}
|
29958
|
<p>I'm fairly new to scripting in Python. I'm looking for suggestions on improving any of the following in the below script: my coding style, performance, readability, commenting, or anything else.</p>
<pre><code>"""
META
Author: James Nicholson
Date: 8/16/2013
DESCRIPTION
This script takes a list of groups from a text file and creates a new text file
in CSV format that contains group members in the below format:
group_name1,user_name1
group_name1,user_name2
etc...
VARIABLES
server = 'domain name'
glist = 'path to text file containing desired groups'
"""
# Import the win32 module needed for accessing groups and members
import win32net
# Set server name and group_list text file variables
server = # enter server name here
group_list = 'groups.txt'
grps = []
# Loop over lines in group_list and store group names in a list
with open(group_list, 'rb') as my_groups:
for line in my_groups:
grps.append(line.rstrip('\r\n'))
# Loop over groups and store members in desired format in new text file 'groups_members_output.txt'
with open('groups_members_output.txt', 'wb') as blank_file:
for group in grps:
usrs = win32net.NetGroupGetUsers(server,group,0)
for user in usrs[0]:
blank_file.write('{},{}\r\n'.format(group,user['name']))
</code></pre>
|
[] |
[
{
"body": "<p>The code looks good (it's short, which is always a good thing).</p>\n\n<p>Make sure to follow PEP 8. A <a href=\"http://hg.python.org/peps/rev/fb24c80e9afb\" rel=\"nofollow\">recent revision of PEP 8</a> allowed 99 characters lines to \"improve readability\", but your <code># Loop over ...</code> comment would still be easier to read on small screens (or on CodeReview!) if splitted.</p>\n\n<p>An issue I often deal with myself in <code>for entity in collection</code> statements is naming properly <code>entity</code> and <code>collection</code> when you really can't provide distinct names. I don't think <code>group/grps</code> is a good choice. I'd suggest <code>group/group_list</code>, while renaming <code>group_list</code> to <code>group_filename</code> or something similar. <a href=\"http://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow\">PEP 20</a> says \"Explicit is better than implicit.\" very early.</p>\n\n<p>Your comments could be improved too: a common advice to beginners is to avoid stating what the line i (eg. <code># increment n</code>), but say what it means (eg. <code># adding a new unit</code>). You're actually doing both: you just have to remove the useless part!</p>\n\n<ul>\n<li><code># Loop over lines in group_list and store group names in a list</code> becomes <code># Store group names in a list</code></li>\n<li><code># Import the win32 module needed for accessing groups and members</code> becomes <code># Accessing groups and members</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T17:09:59.160",
"Id": "48301",
"Score": "0",
"body": "Very helpful, especially the part about improving my comments."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T09:03:24.253",
"Id": "29986",
"ParentId": "29961",
"Score": "2"
}
},
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p>Comments: A lot (if not all) of the comments are pretty much repeating what the code already says. I'd remove them.</p></li>\n<li><p><code>server = # enter server name here</code>. Create functions with configurable elements as arguments instead of global variables.</p></li>\n<li><p><code>with open('groups_members_output.txt', 'wb') as blank_file</code>. Try to give more meaningful names to variables, be declarative. <code>blank_file</code> says hardly anything useful about the variable.</p></li>\n<li><p><code>grps</code>/<code>usrs</code>: Just for saving one or two characters now variables are harder to read.</p></li>\n<li><p>Put spaces after commas.</p></li>\n<li><p>Use (functional) list-comprehensions expressions instead of (imperative) for-loop statements whenever possible.</p></li>\n<li><p>Use always <code>\"\\n\"</code> for line endings (read and write), Python takes care of <a href=\"http://docs.python.org/2/library/os.html#os.linesep\" rel=\"nofollow\">portability in all platforms</a>.</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>import win32net\n\ndef write_group_members(server, input_groups, output_groups):\n with open(input_groups) as input_groups_fd:\n groups = [line.rstrip() for line in input_groups_fd]\n\n with open(output_groups, \"w\") as output_groups_fd:\n for group in groups:\n users = win32net.NetGroupGetUsers(server, group, 0)[0]\n for user in users:\n contents = \"{0},{1}\\n\".format(group, user[\"name\"])\n output_groups_fd.write(contents)\n\nwrite_group_members(\"someserver.org\", \"groups.txt\", \"groups_members_output.txt\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-28T17:08:35.843",
"Id": "48300",
"Score": "0",
"body": "Thanks, this is a huge improvement on my original code. How do I actually execute the code if it is written with functions instead of just a script with global variables? Would I need to place the .py file in my site-packages directory so I could import it into the interpreter?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-29T06:14:12.230",
"Id": "48351",
"Score": "0",
"body": "Use the [`if __name__ == '__main__'` idiom](http://meta.codereview.stackexchange.com/a/493/11227)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T20:43:19.963",
"Id": "30010",
"ParentId": "29961",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "30010",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T18:47:54.343",
"Id": "29961",
"Score": "7",
"Tags": [
"python",
"windows"
],
"Title": "Create CSV file of domain groups and their users"
}
|
29961
|
<p>I am working on creating an interface gem that works with the <a href="https://github.com/sumoheavy/jira-ruby" rel="nofollow">Jira-Ruby gem</a>.</p>
<p>I have several questions and would like a general review for both my code and my attempt at creating a gem (I've never written one before). Any advice on where to go next would also be appreciated. </p>
<p>File structure:</p>
<pre><code>jira_interface
lib
jira_interface
config.rb
version.rb
app_interface.rb
jira_interface.rb
jira_interface.gemspec
#...etc files, I used bundle's gem command to set up
</code></pre>
<p>My main module (jira_interface.rb) looks like this:</p>
<pre><code>require "jira_interface/version"
require "jira"
require "jira_interface/config"
require "jira_interface/app_interface"
module JiraInterface
def get_jira_client
@client = Jira::Client.new(USERINFORMATION)
end
def get_project(project_name)
@client.Project.find(project_name)
end
end
</code></pre>
<p>And my app_interface.rb looks like this:</p>
<pre><code>class AppInterface < JiraInterface
before_filter :get_jira_client
def create_issue(issue_desc, project)
issue = @client.Issue.build
issue.save({"fields"=>{"summary"=> issue_desc, "project"=> {"id" => project.id}, "issuetype"=> {"id"=> "1"}}})
end
def update_issue(issue_id)
issue = @client.Issue.find(issue_id)
comment = issue.comments.build
comment.save({"body"=> "This happened again at #{Date.time}"})
end
def get_issues(issue_desc, project_name)
project = get_project(project_name)
if project.issues.detect { |issue| issue.fields['summary'].include?(issue_desc) }
update_issue(issue.id)
else
create_issue(issue_desc, project)
end
end
end
</code></pre>
<p>The goal is pretty simple: call <code>get_issues()</code> from the rails app when an error happens. If the error is already documented, post a comment saying that it happened again. If it's not, then create a new issue. </p>
<p>To the best of my knowledge, this should work because I've been following the examples found online. However, I've been having a heck of a time just testing it. If anyone could suggest a good way of testing this, that would be much appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:16:24.820",
"Id": "52978",
"Score": "0",
"body": "Aside from what I posted in my answer, your approach looks great. Naming could be improved, but like they say, it is hard.\n\nKeep the good work up!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T20:40:36.153",
"Id": "53536",
"Score": "0",
"body": "does my answer help at all? If not, I'd very much appreciate any feedback."
}
] |
[
{
"body": "<p>I suggest you take a close look at <strong><a href=\"https://github.com/sumoheavy/jira-ruby/tree/master/spec\" rel=\"nofollow\">how the gem you are using is tested</a></strong>. Those tests include <strong>mocks</strong> for all responses of the API (I assume) and is a good example for testing gems in general.</p>\n\n<p>Notice:</p>\n\n<ul>\n<li><strong>helper methods</strong> in the support folder including shared examples</li>\n<li><strong>mock data to simulate responses</strong> from the source API</li>\n<li><strong>custom matchers</strong> to make code better readable and reduce repetition of code (DRY-principle)</li>\n</ul>\n\n<p>Those to me are the three most important you should embrace for now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:16:00.973",
"Id": "33095",
"ParentId": "29962",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33095",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T18:51:12.983",
"Id": "29962",
"Score": "5",
"Tags": [
"ruby",
"ruby-on-rails",
"file-structure"
],
"Title": "Creating a Ruby gem that talks to another gem"
}
|
29962
|
<p>I have some problems in my View.ascx.cs file because I'm reusing my code and modified it based on the situation. For example, when I apply pagination I have different code in all places. I just want my code to be simpler.</p>
<pre><code>using System;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using Christoc.Modules.ResourcesFilter.BOL;
using System.Data;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web.Security;
using System.Web;
using DotNetNuke.Security.Permissions;
using System.Collections.Specialized;
using System.Web.UI;
using Christoc.Modules.ResourceModule.App_Code.BOL;
namespace Christoc.Modules.ResourcesFilter
{
/// -----------------------------------------------------------------------------
/// <summary>
/// The View class displays the content
///
/// Typically your view control would be used to display content or functionality in your module.
public partial class View : ResourcesFilterModuleBase, IActionable
{
public ScriptManager sm;
protected override void OnInit(EventArgs e)
{
sm = ScriptManager.GetCurrent(this.Page);
sm.EnableHistory = true;
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
this.ModuleConfiguration.ModuleTitle = "";
this.ModuleConfiguration.InheritViewPermissions = true;
if (!IsPostBack)
{
BindResourcesRepeater();
GetQueryString(HttpContext.Current.Request.Url);
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
private void BindBookmarks()
{
DataSet ds = new DataSet();
Guid userID = Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString());
ds = Bookmark.Get_all_Bookmarks_for_user(userID);
}
private void GetQueryString(Uri tempUri)
{
if (HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus") != null)
{
ddlTopics.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("IntrestFocus");
}
else
if (HttpUtility.ParseQueryString(tempUri.Query).Get("Skills") != null)
{
ddlSkills.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Skills");
}
else
if(HttpUtility.ParseQueryString(tempUri.Query).Get("Type") != null)
{
ddlTypes.SelectedValue = HttpUtility.ParseQueryString(tempUri.Query).Get("Type");
}
}
public ModuleActionCollection ModuleActions
{
get
{
var actions = new ModuleActionCollection
{
{
GetNextActionID(), Localization.GetString("EditModule", LocalResourceFile), "", "", "",
EditUrl(), false, SecurityAccessLevel.Edit, true, false
}
};
return actions;
}
}
private void BindResourcesRepeater()
{
string tag = Request.QueryString["tag"];
if (String.IsNullOrEmpty(tag))
{
//Guid userID = Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString());
DataSet ds = new DataSet();
int selectedTopicID = Convert.ToInt32(ddlTopics.SelectedValue);
int selectedSkillID = Convert.ToInt32(ddlSkills.SelectedValue);
int selectedTypeID = Convert.ToInt32(ddlTypes.SelectedValue);
string keyword = txtbKeyword.Text.Trim();
int sortBy = Convert.ToInt32(ddlSortBy.SelectedValue);
ds = Resource.Search_Resource(selectedTopicID, selectedSkillID, selectedTypeID, keyword, sortBy);
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = ds.Tables[0].DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 8;
int curpage;
if (ViewState["Page"] != null)
{
curpage = Convert.ToInt32(ViewState["Page"]);
}
else
{
ViewState["Page"] = 1;
curpage = 1;
}
// Set the currentindex
objPds.CurrentPageIndex = curpage - 1;
rp_resList.DataSource = objPds;
rp_resList.DataBind();
if (objPds.IsFirstPage)
{
lnkPrev.Visible = false;
lnkNext.Visible = true;
}
else
if (!objPds.IsFirstPage && !objPds.IsLastPage)
{
lnkPrev.Visible = true;
lnkNext.Visible = true;
}
else
if (objPds.IsLastPage)
{
lnkNext.Visible = false;
lnkPrev.Visible = true;
}
int numberOfItems = ds.Tables[0].Rows.Count;
lbl_totalResult.Text = GetCurrentVisibleItemsText(numberOfItems, objPds.PageSize, objPds.CurrentPageIndex);
}
else
{
DataSet ds = new DataSet();
int selectedTopicID = Convert.ToInt32(ddlTopics.SelectedValue);
int selectedSkillID = Convert.ToInt32(ddlSkills.SelectedValue);
int selectedTypeID = Convert.ToInt32(ddlTypes.SelectedValue);
txtbKeyword.Text = tag;
int sortBy = Convert.ToInt32(ddlSortBy.SelectedValue);
ds = Resource.Search_Resource(selectedTopicID, selectedSkillID, selectedTypeID, tag, sortBy);
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = ds.Tables[0].DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 8;
int curpage;
if (ViewState["Page"] != null)
{
curpage = Convert.ToInt32(ViewState["Page"]);
}
else
{
ViewState["Page"] = 1;
curpage = 1;
}
// Set the currentindex
objPds.CurrentPageIndex = curpage - 1;
rp_resList.DataSource = objPds;
rp_resList.DataBind();
if (objPds.IsFirstPage && objPds.Count < 8)
{
lnkPrev.Visible = false;
lnkNext.Visible = false;
}
else if (objPds.IsFirstPage)
{
lnkPrev.Visible = false;
lnkNext.Visible = true;
}
else if (!objPds.IsFirstPage && !objPds.IsLastPage)
{
lnkPrev.Visible = true;
lnkNext.Visible = true;
}
else if (objPds.IsLastPage)
{
lnkNext.Visible = false;
lnkPrev.Visible = true;
}
int numberOfItems = ds.Tables[0].Rows.Count;
lbl_totalResult.Text = GetCurrentVisibleItemsText(numberOfItems, objPds.PageSize, objPds.CurrentPageIndex);
}
}
private string GetCurrentVisibleItemsText(int numberOfItems, int pageSize, int currentPageIndex)
{
int startVisibleItems = currentPageIndex * pageSize + 1;
int endVisibleItems = Math.Min((currentPageIndex + 1) * pageSize, numberOfItems);
return string.Format(" {0}-{1} of {2} resources", startVisibleItems, endVisibleItems, numberOfItems);
}
protected void rp_resList_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
DataSet ds_bookmarkUser = null;
DataSet ds_LikesUser = null;
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
ds_bookmarkUser = Bookmark.Get_all_Bookmarks_for_user(Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString()));
ds_LikesUser = Like.Get_all_Likes_for_user(Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString()));
}
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater childRepeater2 = (Repeater)e.Item.FindControl("rp_tagsTopics");
if (childRepeater2 != null)
{
//get the HiddenField Form parent Repeater rp_resList
HiddenField hf_resID = (HiddenField)e.Item.FindControl("hf_resID");
ImageButton imgBtn_bookmark = (ImageButton)e.Item.FindControl("imgBtn_bookmark");
LinkButton lb_like = (LinkButton)e.Item.FindControl("lb_like");
HyperLink hl_download = (HyperLink)e.Item.FindControl("hl_download");
LinkButton lnkBtnTags = (LinkButton)e.Item.FindControl("lnkBtnTags");
imgBtn_bookmark.Visible = HttpContext.Current.User.Identity.IsAuthenticated;
lb_like.Visible = HttpContext.Current.User.Identity.IsAuthenticated;
hl_download.Visible = HttpContext.Current.User.Identity.IsAuthenticated;
//if user is Authenticated
int resID = Convert.ToInt32(hf_resID.Value);
//bind bookmark
if (ds_bookmarkUser != null)
{
foreach (DataRow row in ds_bookmarkUser.Tables[0].Rows)
{
if (resID == Convert.ToInt32(row["resourceID"]))
{
imgBtn_bookmark.ImageUrl = "~/DesktopModules/ResourcesFilter/img/favorite-star-yellow.png";
break;
}
}
}
//bind likes
if (ds_LikesUser != null)
{
foreach (DataRow row in ds_LikesUser.Tables[0].Rows)
{
if (resID == Convert.ToInt32(row["resourceID"]))
{
lb_like.Text = "Liked";
break;
}
}
}
string[] strArrTgas = Resource.Get_Tags_For_Resource(resID);
if (strArrTgas[0] == " ")
{
childRepeater2.Visible = false;
}
else
childRepeater2.DataSource = strArrTgas;
childRepeater2.DataBind();
}
}
}
protected void btnSearch_Click(object sender, EventArgs e)
{
ViewState["Page"] = 1;
DataSet ds = new DataSet();
int selectedTopicID = Convert.ToInt32(ddlTopics.SelectedValue);
int selectedSkillID = Convert.ToInt32(ddlSkills.SelectedValue);
int selectedTypeID = Convert.ToInt32(ddlTypes.SelectedValue);
string keyword = txtbKeyword.Text.Trim();
int sortBy = Convert.ToInt32(ddlSortBy.SelectedValue);
ds = Resource.Search_Resource(selectedTopicID, selectedSkillID, selectedTypeID, keyword, sortBy);
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = ds.Tables[0].DefaultView;
objPds.AllowPaging = true;
objPds.PageSize = 8;
int curpage;
if (ViewState["Page"] != null)
{
curpage = Convert.ToInt32(ViewState["Page"]);
}
else
{
ViewState["Page"] = 1;
curpage = 1;
}
// Set the currentindex
objPds.CurrentPageIndex = curpage - 1;
rp_resList.DataSource = objPds;
rp_resList.DataBind();
//hide next & prev links
if (objPds.IsFirstPage && objPds.Count < 8)
{
lnkPrev.Visible = false;
lnkNext.Visible = false;
}
else if (objPds.IsFirstPage && objPds.Count > 8)
{
lnkPrev.Visible = false;
lnkNext.Visible = true;
}
else if (!objPds.IsFirstPage && !objPds.IsLastPage)
{
lnkPrev.Visible = true;
lnkNext.Visible = true;
}
else if (objPds.IsLastPage)
{
lnkNext.Visible = false;
lnkPrev.Visible = true;
}
//ViewState["Page"] = 1;
int numberOfItems = ds.Tables[0].Rows.Count;
lbl_totalResult.Text = GetCurrentVisibleItemsText(numberOfItems, objPds.PageSize, objPds.CurrentPageIndex);
}
protected void btnReset_Click(object sender, EventArgs e)
{
ViewState["Page"] = 1;
ddlSkills.SelectedValue = "0";
ddlTopics.SelectedValue = "0";
ddlTypes.SelectedValue = "0";
ddlSortBy.SelectedValue = "1";
txtbKeyword.Text = "";
lbl_totalResult.Text = "";
BindResourcesRepeater();
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
LinkButton lnkBtnTags = (LinkButton)sender;
Response.Redirect("~/WebsofWonder.aspx?tag=" + lnkBtnTags.Text);
}
protected void lnkPrev_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(ViewState["Page"]) > 1)
{
// Set ViewStatevariable to the previous page
ViewState["Page"] = Convert.ToInt32(ViewState["Page"]) - 1;
// reload the control
}
sm.AddHistoryPoint("Currentpage", ViewState["Page"].ToString());
BindResourcesRepeater();
}
protected void lnkNext_Click(object sender, EventArgs e)
{
// Set ViewStatevariable to the next page
ViewState["Page"] = Convert.ToInt32(ViewState["Page"]) + 1;
sm.AddHistoryPoint("Currentpage", ViewState["Page"].ToString());
// reload the control
BindResourcesRepeater();
}
protected void rp_resList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
//get userID
Guid userID = Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString());
if (e.CommandName == "bookmark_res")
{
//get resID
//get resource ID form HiddenField
HiddenField hf = (HiddenField)e.Item.FindControl("hf_resID");
ImageButton ib = (ImageButton)e.Item.FindControl("imgBtn_bookmark");
int resID = Convert.ToInt32(hf.Value);
//try to convert this block to fucntion
Bookmark bm = new Bookmark();
bm.UserID = Guid.Parse(Membership.GetUser(HttpContext.Current.User.Identity.Name).ProviderUserKey.ToString());
bm.Resource.ResourceID = resID;
//get bookmarkID to remove it from user bookmark and Group
int bookmarkID = Bookmark.Insert(bm);
if (bookmarkID == -1)
{
bool confirmDelete = Bookmark.Delete_User_bookmark(resID, userID);
ib.ImageUrl = "~/DesktopModules/ResourcesFilter/img/favorite-star.png";
}
else
{
ib.ImageUrl = "~/DesktopModules/ResourcesFilter/img/favorite-star-yellow.png";
}
}
if (e.CommandName == "lb_like_Click")
{
//get resID
HiddenField hf = (HiddenField)e.Item.FindControl("hf_resID");
LinkButton lb_like = (LinkButton)e.Item.FindControl("lb_like");
Like lke = new Like();
lke.ResoursceID = Convert.ToInt32(hf.Value);
lke.UserID = userID;
int likeID = Like.Insert(lke);
if (likeID == -1)
{
bool confirmDelete = Like.Delete_User_Like(lke);
lb_like.Text = "Like";
}
else
{
lb_like.Text = "Liked";
}
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T21:02:47.010",
"Id": "53626",
"Score": "0",
"body": "you have a problem or the code works?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T21:04:50.223",
"Id": "53627",
"Score": "0",
"body": "there is a lot of code here, I think you might want to separate out some of the code that you want reviewed. like take out the most complicated part and post that asking for a review. don't post the whole code file, very few people are going to take the time to read through all the code. don't get me wrong there are going to be people that will read through it. but this hasn't gotten any answers yet. so I would trim and repost"
}
] |
[
{
"body": "<p>Your code duplication in <code>BindResourceRepeater</code> (2x in there) and <code>btnSearch_Click</code> is around the differences of how the keyword is handled and how the prev/next links are enabled/disabled.</p>\n\n<p>Lets look at the link enabling first.</p>\n\n<p>To me the logic of disabling the links should be very simple:</p>\n\n<ul>\n<li>The prev link should be enabled on every page except the first one</li>\n<li>The next link should be enabled on every page except the last one</li>\n</ul>\n\n<p>Note that first and last page could be the same. The code should be two lines:</p>\n\n<pre><code>lnPrev.Visible = !objPds.IsFirstPage;\nlnkNext.Visible = !objPds.IsLastPage;\n</code></pre>\n\n<p>I'd expect the <code>PagedDataSource</code> to set these flags correctly.</p>\n\n<p>Then the only thing left is the keyword which should be simply passed as parameter and special cases handled in the calling function. This means we can now refactor it by moving the code into it's own function and call it in the appropriate places:</p>\n\n<pre><code>private void PaginateData(string keyword)\n{\n DataSet ds = new DataSet();\n int selectedTopicID = Convert.ToInt32(ddlTopics.SelectedValue);\n int selectedSkillID = Convert.ToInt32(ddlSkills.SelectedValue);\n int selectedTypeID = Convert.ToInt32(ddlTypes.SelectedValue);\n int sortBy = Convert.ToInt32(ddlSortBy.SelectedValue);\n ds = Resource.Search_Resource(selectedTopicID, selectedSkillID, selectedTypeID, keyword, sortBy);\n\n PagedDataSource objPds = new PagedDataSource();\n objPds.DataSource = ds.Tables[0].DefaultView;\n objPds.AllowPaging = true;\n objPds.PageSize = 8;\n\n int curpage;\n if (ViewState[\"Page\"] != null)\n {\n curpage = Convert.ToInt32(ViewState[\"Page\"]);\n }\n else\n {\n ViewState[\"Page\"] = 1;\n curpage = 1;\n }\n objPds.CurrentPageIndex = curpage - 1;\n\n rp_resList.DataSource = objPds;\n rp_resList.DataBind();\n\n lnkPrev.Visible = !objPds.IsFirstPage;\n lnkNext.Visible = !objPds.IsLastPage;\n\n int numberOfItems = ds.Tables[0].Rows.Count;\n lbl_totalResult.Text = GetCurrentVisibleItemsText(numberOfItems, objPds.PageSize, objPds.CurrentPageIndex);\n}\n</code></pre>\n\n<p><code>BindResourceRepeater</code> can be rewritten as:</p>\n\n<pre><code>private void BindResourcesRepeater()\n{\n string tag = Request.QueryString[\"tag\"];\n if (!String.IsNullOrEmpty(tag))\n {\n txtbKeyword.Text = tag.Trim();\n }\n else\n {\n tag = txtbKeyword.Text.Trim();\n }\n PaginateData(tag);\n}\n</code></pre>\n\n<p>And <code>btnSearch_Click</code> can be rewritten as:</p>\n\n<pre><code>protected void btnSearch_Click(object sender, EventArgs e)\n{\n ViewState[\"Page\"] = 1;\n PaginateData(txtbKeyword.Text.Trim());\n}\n</code></pre>\n\n<p>This refactoring got rid of approx. 130 lines of code.</p>\n\n<p>A few other things:</p>\n\n<ul>\n<li><code>objPds</code> is not a good name for a variable. Something like <code>pagedData</code> is better as it denotes what the variable represents.</li>\n<li>Likewise <code>strArrTgas</code> is a bad variable name. Incorporating the type name into the variables is not a standard C# naming convention is just creates noise most of the time.</li>\n<li>You look up a few controls by name and handle some commands. You do so by using \"magic strings\" (hard-coded strings scattered through the source). You should create const variables at the top of your class to hold these names so you can refactor them in one place should they ever change.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-24T09:13:34.767",
"Id": "36004",
"ParentId": "29963",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T19:36:06.113",
"Id": "29963",
"Score": "5",
"Tags": [
"c#",
"asp.net",
"pagination"
],
"Title": "Pagination of repeater"
}
|
29963
|
<p>I wrote a class that finds values in a huge search volume. I have a pretty strong feeling that my code is not good and would like to get your opinion on it. My experience with C++11 threading is very limited and I think I use the wrong features for my task.</p>
<pre><code>#include <iostream>
#include <vector>
#include <utility>
#include <future>
class Searcher
{
public:
std::future<bool> Find(int x) {
m_searches.emplace_back();
m_searches.rbegin()->first = x;
return m_searches.rbegin()->second.get_future();
}
void Search()
{
// very large search data
static const std::vector<int> haystack = { 4, 5, 1, 3, 9, 8, 7, 6, 11, 42, 13 };
std::vector<int> foundIndices;
// find values
for (auto h : haystack) {
for (size_t i = 0; i < m_searches.size(); i++) {
if (m_searches[i].first == h) {
foundIndices.push_back(i);
m_searches[i].second.set_value(true);
}
}
}
// resolve promises, where no value was found
for (size_t i = 0; i < m_searches.size(); i++) {
bool found = false;
for (auto j : foundIndices)
if (j == i)
found = true;
if (!found)
m_searches[i].second.set_value(false);
}
}
private:
std::vector<std::pair<int, std::promise<bool>>> m_searches;
};
int main()
{
Searcher s;
auto s1 = s.Find(1);
auto s2 = s.Find(2);
auto s3 = s.Find(3);
s.Search();
std::cout << s1.get() << std::endl;
std::cout << s2.get() << std::endl;
std::cout << s3.get() << std::endl;
return 0;
}
</code></pre>
<p><strong>There should be one search running for many <code>Find</code>s, because the set that is searched is very large.</strong> It could however run concurrently to split the search up to multiple threads. For example with two threads: The first thread searches the first half, the second thread searches the second half.</p>
<p>The futures are not really guaranteed to be valid, because the user has to call the <code>Search</code> function. Would it be possible to start the search, once the first .get was called?</p>
<p>My "algorithm" to fulfil the promises looks very ugly and complicated, but I can't think of a better way.</p>
|
[] |
[
{
"body": "<p>There are definitely some problems if you want to make this threaded. Firstly, access to <code>m_searches</code> is not protected in any way. Since this is a shared bit of memory, it would need to be protected by something (say a mutex) before you modify it.</p>\n\n<p>Generally in situations like these, it's far better to let <code>std::async</code> do a lot of the hard work for you. Also, try and eliminate shared mutable state as much as possible, because it makes life a lot harder. Firstly, let's write a simple search function that'll return an index if we find a match:</p>\n\n<pre><code>const std::size_t not_found = -1;\n\ntemplate <typename Iterator, typename T>\nstd::size_t find_index(Iterator begin, Iterator end, \n const T& value, std::size_t start)\n{\n std::size_t s = start;\n Iterator it = begin;\n\n while(it != end) {\n if(*it == value) {\n return s;\n }\n ++s;\n ++it;\n }\n\n return not_found;\n}\n</code></pre>\n\n<p>Ok, this is just our normal linear search, but it allows us to start from anywhere in our search range since we're only passing in a few iterators.</p>\n\n<p>Next, we define a <code>vector</code> to search over:</p>\n\n<pre><code>std::vector<int> v { 4, 5, 1, 3, 9, 8, 7, 6, 11, 42, 13 };\ntypedef typename std::vector<int>::iterator iter_t;\n</code></pre>\n\n<p>Create our <code>vector</code> of <code>future</code> to hold results:</p>\n\n<pre><code>std::vector<std::future<std::size_t>> futures;\n</code></pre>\n\n<p>And then populate it:</p>\n\n<pre><code>futures.emplace_back(\n std::async(std::launch::async, find_index<iter_t, int>, \n v.begin(), v.begin() + 6, 8, 0));\nfutures.emplace_back(\n std::async(std::launch::async, find_index<iter_t, int>, \n v.begin() + 6, v.end(), 8, 6));\n</code></pre>\n\n<p>Note the <code>std::launch::async</code> flag specifies we want to create a new thread to run our function in. I've hardcoded the search start and end places here, but you can obviously add some logic to split things up evenly if you'd like. Also, note that we need to explicitly define the template types here, since they won't be deduced.</p>\n\n<p>Now we'll set up a <code>vector</code> to store our results in, and get the results back:</p>\n\n<pre><code>std::vector<std::size_t> results;\nfor(auto& future : futures) {\n results.emplace_back(future.get());\n}\n</code></pre>\n\n<p>Finally, print out anything that was found:</p>\n\n<pre><code>std::for_each(results.begin(), results.end(),\n [](std::size_t index)\n { if(index != not_found) std::cout << index << \"\\n\"; });\n}\n</code></pre>\n\n<p>The whole thing can be found <a href=\"http://coliru.stacked-crooked.com/view?id=6ecfa51ad6277e70426a9a3c66bf9542-f674c1a6d04c632b71a62362c0ccfc51\" rel=\"nofollow\">here</a>.</p>\n\n<p>Hopefully this gives you an idea of a different way of approaching your problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T16:24:04.303",
"Id": "47590",
"Score": "0",
"body": "Thanks you for your answer. Your code breaks my constraint that there should be only one search running for multiple things that have to be found. The volume that I search through is so big, that it should only be traversed once like in my given example code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T01:29:52.263",
"Id": "29970",
"ParentId": "29964",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T19:49:56.113",
"Id": "29964",
"Score": "4",
"Tags": [
"c++",
"multithreading",
"c++11"
],
"Title": "Searching through a huge set with threads"
}
|
29964
|
<p>I am working on hospital management system project. I have implemented it using the following design. Is it a good design?</p>
<p>I have created four classes: <code>Patient</code>, <code>Doctor</code>, <code>Hospital</code>, and <code>Demo</code>. Inside the Hospital class are two <code>ArrayList</code>s of Patients and Doctors. Also, inside the Doctor class, there is a list of Patients (this is a specific Patient list of specific Doctor).</p>
<p>Inside the Demo class, I am adding Patients and Doctors, and they are being added to respective lists of the Hospital class.</p>
<p><strong>Demo</strong></p>
<pre><code>public class demo {
public static void main (String args[])
{
Hospital h1= new Hospital("Appollo");
int choice=0;
Doctor o = new Doctor("Rai","Surgeon");
Doctor o1 = new Doctor("James","Opthalmologist");
Doctor o2 = new Doctor("Steve","ENT");
System.out.println("Press 1 to add doctor \n Press 2 to show doctors.\n Press 3 to add patient \n 4 Assign doctor to patients\n 5 Doctor and their patients ");
Scanner cin = new Scanner (System.in);
choice = cin.nextInt();
switch (choice)
{
case 1: h1.addDoctor(o);
h1.addDoctor(o1);
h1.addDoctor(o2);
// break;
case 2: { System.out.println(h1.showDoctors());
}
case 3: { Patient p = new Patient ("Steven ",21,"Male","eye");
Patient p1 = new Patient ("Michael ",12,"Male","heart patient");
Patient p2 = new Patient ("Sara ",23,"Female","earnose");
Patient p3 = new Patient ("Amy ",31,"Female","earnose");
Patient p5 = new Patient ("Rocky ",18,"Male","eye");
Patient p4= new Patient ("Jessy ",15,"Male","heart patient");
h1.addPatient(p);
h1.addPatient(p1);
h1.addPatient(p2);
h1.addPatient(p3);
h1.addPatient(p4);
h1.addPatient(p5);
System.out.println(h1.showPatients());
}
case 4: {
h1.assignDoctor();
}
case 5: {
System.out.println("\n \n \n "+ ""+o2.getDoctorName()+""+o2.getDoctorPatientList());
}
}
}}
</code></pre>
<p><strong>Hospital</strong></p>
<pre><code>public class Hospital {
List <Doctor> doctorList = new ArrayList<Doctor>();
List <Patient> patientList = new ArrayList<Patient>();
String hospitalName;
void addDoctor(Doctor o)
{
doctorList.add(o);
}
void addPatient(Patient o)
{
patientList.add(o);
}
Hospital(String name)
{
this.hospitalName=name;
}
public List<Doctor> showDoctors()
{
return doctorList;
}
public List<Patient> showPatients()
{
return patientList;
}
public void assignDoctor()
{
for (Patient x: patientList)
{ for (Doctor y: doctorList)
{ if (x.getDisease().equals("eye"))
{
if (y.getDoctorspeciality().equals("Opthalmologist"))
{
y.addPatientsToDoctor(x);
}
}
if (x.getDisease().equals("heart patient"))
{
if (y.getDoctorspeciality().equals("Surgeon"))
{
y.addPatientsToDoctor(x);
}
}
if (x.getDisease().equals("earnose"))
{
if (y.getDoctorspeciality().equals("ENT"))
{
y.addPatientsToDoctor(x);
}
}
}
}
}
}
</code></pre>
<p><strong>Doctor</strong></p>
<pre><code>public class Doctor {
private String doctorName;
private String doctorSpeciality;
String doctorStatus;
List<Patient> doctorPatientList= new ArrayList<Patient>();
Doctor(String c, String cc)
{
this.doctorName=c;
this.doctorSpeciality=cc;
}
public String getDoctorName()
{
return doctorName;
}
public List<Patient> getDoctorPatientList()
{
return doctorPatientList;
}
public void addPatientsToDoctor(Patient o)
{
doctorPatientList.add(o);
}
String getDoctorspeciality()
{
return doctorSpeciality;
}
public String toString()
{
return (doctorName+""+doctorSpeciality);
}
}
</code></pre>
<p><strong>Patient</strong></p>
<pre><code>public class Patient {
private String patientName;
private int patientAge;
private String patientGender;
private String disease;
Patient (String patientName, int patientAge,String patientGender, String disease)
{
this.patientName= patientName;
this.patientGender= patientGender;
this.patientAge=patientAge;
this.disease=disease;
}
public String getDisease()
{return disease;}
public String toString()
{
return (patientName+""+patientAge+""+patientGender +" "+ disease);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T05:03:21.743",
"Id": "47559",
"Score": "2",
"body": "`Hospital.showDoctors()` and `Hospital.showPatients()` should be `.getDoctors()` and `.getPatients()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T17:28:46.993",
"Id": "47669",
"Score": "4",
"body": "Keep the original code and post the new code for review. Review your code [iteratively](http://meta.codereview.stackexchange.com/questions/41/iterative-code-reviews-how-can-they-happen-successfully). Deleting your previous working code makes the previous answers and comments unnecessary. **DON'T DO IT**"
}
] |
[
{
"body": "<ul>\n<li><p>Indentation: It's all over the place and kind of hard to follow. Try to be consistent.</p></li>\n<li><p>Braces: Same thing. For the most part you are putting them at the beginning of the next line. But sometime you are putting a line of code with the brace. This is not one of the standard conventions. Using a standard convention is better than using a non-standard one, but in either case, you should be consistent.</p></li>\n<li><p>Switch Braces: This marks a scoped region. It does not mean you don't need break statements.</p></li>\n<li><p>Variable Names: Pick good variable names:</p></li>\n</ul>\n\n<p>In <code>assignDoctor()</code></p>\n\n<pre><code>for (Patient x: patientList) {\n for (Doctor y: doctorList) {\n // ...\n }\n}\n</code></pre>\n\n<p><code>x</code> and <code>y</code> are arbitrary and mean nothing. As you get father down the loop, names like <code>patient</code> and <code>doctor</code> are going to be helpful.</p>\n\n<p>In <code>Hospital</code>, <code>doctorList</code> and <code>patientList</code> can just be <code>doctors</code> and <code>patients</code>. The type system will tell you the variable is a list.</p>\n\n<p>In <code>Doctor</code>, everything is prefixed with \"doctor\". It's a field of a <code>Doctor</code>, so it is understood that the field belongs to a doctor. Same with <code>Patient</code>.</p>\n\n<ul>\n<li>Variables in General: If you are only going to use a variable for one thing, you don't need to make one.</li>\n</ul>\n\n<p>Ex:</p>\n\n<pre><code>Patient p = new Patient (\"Steven \",21,\"Male\",\"eye\");\nPatient p1 = new Patient (\"Michael \",12,\"Male\",\"heart patient\");\nPatient p2 = new Patient (\"Sara \",23,\"Female\",\"earnose\");\nPatient p3 = new Patient (\"Amy \",31,\"Female\",\"earnose\");\nPatient p5 = new Patient (\"Rocky \",18,\"Male\",\"eye\");\nPatient p4= new Patient (\"Jessy \",15,\"Male\",\"heart patient\");\nh1.addPatient(p);\nh1.addPatient(p1);\nh1.addPatient(p2);\nh1.addPatient(p3);\nh1.addPatient(p4);\nh1.addPatient(p5);\n</code></pre>\n\n<p>can just be:</p>\n\n<pre><code>h1.addPatient(new Patient (\"Steven \",21,\"Male\",\"eye\"));\nh1.addPatient(new Patient (\"Michael \",12,\"Male\",\"heart patient\"));\n// ...\n</code></pre>\n\n<ul>\n<li><p>Values: Not everything is a <code>String</code>. The type system is there to help you. But when you make something like sex a <code>String</code>, there is nothing stopping you form treating \"dslkjahgkfdj\" as a gender.</p>\n\n<p>The same goes for patient disease and doctor specialty. You have a fixed set of values you are expecting, yet you are leaving the door open for many others. What should happen in <code>assignDoctor()</code> if a patient has \"school bus\" and the only doctor specializes in \"envelope\"? An <code>enum</code> would likely be a good match for this type of thing. It allows you to define a set of values and know you will always be dealing with something in that set.</p>\n\n<p>If you do decide to stick with <code>String</code>, you need to define the expected values as constants. If tomorrow you want to change \"heart patient\" to \"cardiac\", it will be much easier to change the value of a single static final variable then find all of the instances of \"heart patient\" in the code base.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T22:52:55.537",
"Id": "29968",
"ParentId": "29965",
"Score": "8"
}
},
{
"body": "<p>Building upon @unholysampler's excellent feedback, if the matching condition between a disease and speciality is as straightforward as your current example, and the hospital will also only have one doctor per speciality, you can make use of two Maps in <code>assignPatientToDoctor</code> (renamed) to make the assignment simpler.</p>\n\n<p>I think it's realistic to make these two assumptions given the simplistic requirements. Besides, your code seems to suggest that one patient can be added to multiple doctors. Is that desired? Even if the assumptions are not true, you can tweak it slightly to have the value as a <code>List<Doctor></code> for example, and then build some logic to pick out which doctor do you want to add the patient with the disease to. Also, in my code below, I did not check if a <code>Patient</code> is added multiple times to a <code>Doctor</code>'s list, maybe you want to implement that as well.</p>\n\n<p>Let's start off with @unholysampler's recommendation for <code>enums</code> first, I am providing <code>Doctor</code> and <code>Patient</code> as an interface here only to illustrate that and the recommended change in method names:</p>\n\n<p>The <code>Doctor</code> interface:</p>\n\n<pre><code>package com.myproject;\n\nimport java.util.List;\n\npublic interface Doctor {\n\n public enum Speciality {\n OPTHALMOLOGIST, SURGEON, ENT\n }\n\n public String getName();\n\n public Speciality getSpeciality();\n\n public List<Patient> getPatients();\n\n public void addPatients(Patient... patients);\n}\n</code></pre>\n\n<p>One significant change here: <code>addPatients</code> accept variable arguments (\"varargs\") as the name implies one can add one or more patients (of course, null/empty checks should be done here). </p>\n\n<p>The <code>Patient</code> interface:</p>\n\n<pre><code>package com.myproject;\n\n\npublic interface Patient {\n\n public enum Disease {\n EYE, HEART_PATIENT, EARNOSE\n }\n\n public Disease getDisease();\n\n}\n</code></pre>\n\n<p>The <code>Hospital</code> class, specifically the tweaked <code>assignPatientToDoctor</code> method:</p>\n\n<pre><code>package com.myproject;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\nimport com.myproject.Doctor.Speciality;\nimport com.myproject.Patient.Disease;\n\npublic class Hospital {\n\n static Map<Patient.Disease, Doctor.Speciality> specialityHandlingForDisease = new HashMap<Patient.Disease, Doctor.Speciality>();\n Map<Doctor.Speciality, Doctor> doctors = new HashMap<Doctor.Speciality, Doctor>();\n List<Patient> patients = new ArrayList<Patient>();\n\n static {\n specialityHandlingForDisease.put(Disease.EYE, Speciality.OPTHALMOLOGIST);\n specialityHandlingForDisease.put(Disease.HEART_PATIENT, Speciality.SURGEON);\n specialityHandlingForDisease.put(Disease.EARNOSE, Speciality.ENT);\n }\n\n public void addDoctor(Doctor doctor) {\n doctors.put(doctor.getSpeciality(), doctor);\n }\n\n public void assignPatientToDoctor() {\n for (Patient patient : patients) {\n if (specialityHandlingForDisease.containsKey(patient.getDisease())) {\n Speciality speciality = specialityHandlingForDisease.get(patient.getDisease());\n if (doctors.containsKey(speciality)) {\n doctors.get(speciality).addPatients(patient);\n }\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-12-09T15:56:00.397",
"Id": "209824",
"Score": "0",
"body": "Putting `Patient`s in a `HashMap` would prevent patient duplication on the `Doctor` and `Hospital` objects."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T02:26:21.523",
"Id": "29972",
"ParentId": "29965",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T20:59:09.647",
"Id": "29965",
"Score": "3",
"Tags": [
"java",
"object-oriented"
],
"Title": "Designing classes and methods for hospital management system"
}
|
29965
|
<p>I've built a Twitter plugin recently and was wondering if I could get some feedback on it. There is also a PHP side that grabs the actual tweets and I can post that code if it's needed.</p>
<p><a href="http://jsfiddle.net/cKfDd/" rel="nofollow">http://jsfiddle.net/cKfDd/</a></p>
<pre><code>;(function ( $, window, document, undefined ) {
/*************************************
Plugin Functions
*************************************/
/*************************************/
Plugin.prototype.init = function () {
var params = [ '?user=' + this.options.user,
'&limit=' + this.options.limit,
'&type=' + this.options.type,
'&slug=' + this.options.slug,
'&cache=' + this.options.cache,
'&expire=' + this.options.expire,
'&clear=' + this.options.clear,
'&retweets=' + this.options.retweets
].join('\n');
$.ajax({
url: this.options.path_to_core + 'invisibletweets.php' + params,
context: this,
dataType: 'json',
success: function(data){
// If the errors object is returned, show the error and exit the script
if(data.errors){
$(this.element).html("Fatal Error: " + data.errors[0].message);
return false;
}
// Variables
var scope = this;
var parent = this.element;
var tpl = "";
var tplArray = scope.options.template.replace(/[\s,]+/g, ',').split(',');
// Creates an empty template with all present data, in order.
$.each(tplArray, function(i, elm){
if(elm == 'name'){
tpl = tpl + '<div class="it_name"><a href="" target="_blank"></a></div>';
} else if(elm == 'avatar'){
tpl = tpl + '<div class="it_avatar"><a href="" target="_blank"><img src="" /></a></div>';
} else if(elm == 'date'){
tpl = tpl + '<div class="it_date"></div>';
} else if(elm == 'time'){
tpl = tpl + '<div class="it_time"></div>';
} else if(elm == 'text'){
tpl = tpl + '<div class="it_text"><p></p></div>';
} else if(elm == 'btn_tweet'){
tpl = tpl + '<a href="http://twitter.com/intent/tweet?in_reply_to=" target="_blank" class="it_btn_tweet">Tweet</a>';
} else if(elm == 'btn_retweet'){
tpl = tpl + '<a href="http://twitter.com/intent/retweet?tweet_id=" target="_blank" class="it_btn_retweet">Retweet</a>';
} else if(elm == 'btn_favorite'){
tpl = tpl + '<a href="http://twitter.com/intent/favorite?tweet_id=" target="_blank" class="it_btn_favorite">Favorite</a>';
}
});
//Populates the template with data
$.each(data, function(i, item){
// Variables
var text = scope.findLinks(item.text);
var date = scope.dateTime(item.created_at, 'date');
var time = scope.dateTime(item.created_at, 'time');
var profile_url = 'http://twitter.com/' + item.user.screen_name;
var thisTweet = ".it_tweet:eq("+i+") ";
// Creates a searchable object of the template
$(parent).append('<div class="it_tweet">' + tpl + '</div>');
//If in array, show, else don't show, for each item.
if(tplArray.indexOf('name') != -1){
$(thisTweet + ".it_name a").attr("href", profile_url).html(item.user.name);
}
if(tplArray.indexOf('avatar') != -1){
$(thisTweet + ".it_avatar").find('a').attr("href", profile_url).find('img').attr("src", item.user.profile_image_url);
}
if(tplArray.indexOf('date') != -1){
$(thisTweet + ".it_date").html(date);
}
if(tplArray.indexOf('time') != -1){
$(thisTweet + ".it_time").html(time);
}
if(tplArray.indexOf('text') != -1){
$(thisTweet + ".it_text p").html(text);
}
if(tplArray.indexOf('btn_tweet') != -1){
$(thisTweet + ".it_btn_tweet").attr("href", 'http://twitter.com/intent/tweet?in_reply_to=' + item.id);
}
if(tplArray.indexOf('btn_retweet') != -1){
$(thisTweet + ".it_btn_retweet").attr("href", 'http://twitter.com/intent/retweet?tweet_id=' + item.id);
}
if(tplArray.indexOf('btn_favorite') != -1){
$(thisTweet + ".it_btn_favorite").attr("href", 'http://twitter.com/intent/favorite?tweet_id=' + item.id);
}
}); //each
} //success
}); //ajax
}; //init
/*************************************/
Plugin.prototype.findLinks = function(tweet){
var text = tweet;
text = text.replace(/http:\/\/\S+/g, '<a href="$&" target="_blank">$&</a>');
text = text.replace(/\s(@)(\w+)/g, ' @<a href="http://twitter.com/$2" target="_blank">$2</a>');
text = text.replace(/\s(#)(\w+)/g, ' #<a href="http://twitter.com/search?q=%23$2" target="_blank">$2</a>');
return text;
}; //findLinks
/*************************************/
Plugin.prototype.dateTime = function(created_at, select){
var dateTime = created_at;
var strtime = dateTime.replace(/(\+\S+) (.*)/, '$2 $1')
var date = new Date(Date.parse(strtime)).toLocaleDateString();
var time = new Date(Date.parse(strtime)).toLocaleTimeString();
if(select == 'date'){
return date;
} else if(select == 'time'){
return time;
}
}; //dateTime
/*************************************
Plugin Setup
*************************************/
var pluginName = 'invisibleTweets',
// Options for the plugin
defaults = {
user : 'shanrobertson_', // Twitter username
limit : 10, // Number of tweets
type : 'timeline', // Feed select, can be timeline/list
slug : '', // For lists
cache : 'default', // The cache name if dealing with multiple feeds
expire : '15 minutes', // The time it takes the cache to expire
clear : false, // Clears the cache.
retweets : true, // Show retweets
path_to_core: 'js/vendor/invisibletweets/', // Path to the invisibletweets folder.
template : 'name, avatar, date, time, text, btn_tweet, btn_retweet, btn_favorite' // Elements to show and in what order
};
// The actual plugin constructor
function Plugin( element, options ) {
this.element = element;
this.options = $.extend( {}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
// A really lightweight plugin wrapper around the constructor, preventing against multiple instantiations
$.fn[pluginName] = function ( options ) {
return this.each(function () {
if (!$.data(this, 'plugin_' + pluginName)) {
$.data(this, 'plugin_' + pluginName,
new Plugin( this, options ));
}
});
}
})( jQuery, window, document );
</code></pre>
|
[] |
[
{
"body": "<p>The code over all looks nice and clean and is very readable.</p>\n\n<p>What I'm not really a fan of is the handling of the template.</p>\n\n<ul>\n<li><p>Personally I'd prefer to define the template directly as an array instead of a comma separated string.</p></li>\n<li><p>The big if block building the HTML should be replaced with an object (hash map) with the HTML snippets assigned to each keyword.</p></li>\n<li><p>String concatenations are slow and memory hogs. It would be better to collect the string in an array and <code>.join('')</code> them.</p></li>\n<li><p>It's a bit strange to add the template to the page first and then search for it again before filling it. It would be much easier to first fill the template and then add it to the page.</p></li>\n<li><p>Generally I'd join building and filling the template into one:</p></li>\n</ul>\n\n<p>Here some (untested) code showing what I mean:</p>\n\n<pre><code>var tplArray = ['name', 'avatar'];\n\nvar templateItems = {\n name: {\n template: '<div class=\"it_name\"><a href=\"\" target=\"_blank\"></a></div>',\n fill: function(element, itemData) {\n element.find(\"a\").attr(\"href\", itemData.profile_url).html(itemData.user.name);\n }\n },\n avatar: {\n template: '<div class=\"it_avatar\"><a href=\"\" target=\"_blank\"><img src=\"\" /></a></div>',\n fill: function(element, itemData) {\n element.find('a').attr(\"href\", itemData.profile_url).find('img').attr(\"src\", itemData.user.profile_image_url);\n }\n }\n // etc.\n}\n\n$.each(data, function(i, item){\n // Put formated data into back into item\n item.text = scope.findLinks(item.text);\n item.date = scope.dateTime(item.created_at, 'date');\n item.time = scope.dateTime(item.created_at, 'time');\n item.profile_url = 'http://twitter.com/' + item.user.screen_name;\n item.thisTweet = \".it_tweet:eq(\"+i+\") \";\n\n var templateItems = $.map(tplArray, function(i, tplItem) {\n var templateData = templateItems[tplItem];\n var element = $(templateData.template);\n templateData.fill(element, item);\n return element;\n });\n\n $(parent).append($('<div class=\"it_tweet\"></div>').append(templateItems));\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T14:24:37.917",
"Id": "46926",
"ParentId": "29967",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-19T21:46:44.743",
"Id": "29967",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"datetime",
"plugin",
"twitter"
],
"Title": "Display Twitter timelines and lists on a website"
}
|
29967
|
<p>I have written below code for the famous <a href="http://en.wikipedia.org/wiki/Josephus_problem" rel="nofollow">Josephus problem</a>, or inky pinky ponky game, or many other names. Does this looks good or is there any loophole if anyone can highlight. I shall be looking forward to optimize it now as much as possible.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
typedef struct ll_core
{
int c_ll;
struct ll_core * next;
} node_d;
node_d * create_c_list(int ,int);
void printList(node_d *);
node_d * elimination(node_d *, int);
int main(void)
{
node_d *c_list;
int n_kids,num;
printf("How many kids? ");
scanf("%d",&n_kids);
printf("How many no. of words? ");
scanf("%d",&num);
node_d *first_kid=create_c_list(n_kids,num); // create the circular list and get the pointer to first node/tail.
printList(first_kid);
node_d *victor=elimination(first_kid,num); //returns pointer to the winner/last kid left
printList(victor);
}
node_d * create_c_list(int n_k,int n_w)
{
node_d *first=malloc(sizeof(node_d));
int dat=1;
first=malloc(sizeof(node_d));
first->c_ll=dat;
first->next=first;
int iter=0;
while(iter< n_k-1)
{
node_d * new_p=malloc(sizeof(node_d));
new_p->next=first->next;
first->next=new_p; /*We are not changing the node pointed to by tail pointer anywhere*/
new_p->c_ll=++dat;
iter++;
}
return first;
}
node_d * elimination(node_d * fix, int cntr)
{
node_d *it=fix, *prev=fix;
int iter;
while(1)
{
for(iter=1;iter<cntr;iter++)
it=it->next; /*This pointer is always on the node to be deleted. Once node is deleted, it points to the node from where
from where counting is to start next.*/
while(prev->next != it)
prev=prev->next; // This always points to the node just before the one pointed to by pointer 'it'.
//if(prev->next == it)
prev->next=it->next;
printf("removed : %d\n",it->c_ll);
node_d *temp=it;
free(temp);
it=prev->next;
if(it==it->next)
break;
}
return it;
}
void printList(node_d *list_tail)
{
node_d *p = list_tail->next;
if(p->next==p)
{
printf("Only one element at %p: Value : %d next : %p\n",p,p->c_ll,p->next);
return;
}
while(p != list_tail)
{
printf("Value : %d next : %p\n",p->c_ll,p->next);
p=p->next;
}
if(p == list_tail)
{
printf("tail.. value : %d next : %p\n",p->c_ll,p->next);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T05:04:45.937",
"Id": "47560",
"Score": "1",
"body": "Your indentation is bad. It is inconsistent and makes it hard to read the code. Also adding comments at the end makes it hard to read the code. You could have placed it before the statements about which they are. Also not having braces around single statements can lead to problems later when you are editing the code and decide and add a statement but forget to add braces so you should use them even if they are optional."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T08:57:35.373",
"Id": "61158",
"Score": "0",
"body": "You could use a double linked list to avoid going through the whole circle to find the previous node in `elimination`. This is a memory/execution speed trade-off that I find sensible especially for long lists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-11T09:07:49.773",
"Id": "61159",
"Score": "0",
"body": "If possible I would use a linked list implementation from a standard library to avoid possible bugs from pointer handling."
}
] |
[
{
"body": "<p>Sorry, but I don't think this code is very good. </p>\n\n<p>In <code>create_c_list</code>, the <code>first</code> node is allocated twice, leaking memory, and there\nare no checks for allocation failure. Parameters <code>n_k</code> and <code>n_w</code> are badly\nnamed and the latter is not used. The loop should be a <code>for</code> not <code>while</code>.\n<code>new_p</code> could just as well be <code>n</code>, for 'node'. Also, it is not obvious that\nthe 'c' in the name means 'circular' and you should add spaces around\noperators ('=' etc).</p>\n\n<p>In <code>elimination</code>, the function name should be a verb. The outer <code>while(1)</code> loop is often preferred as <code>for (;;)</code> , although that is a matter of personal preference. Indefinite loops are usually best avoided anyway.<br>\nInside this loop is a <code>for</code> loop, which should define <code>iter</code> in the loop and call it <code>i</code>. Parameter <code>cntr</code> means nothing - it could be\n'counter' of 'center'. Give it a better name. It derives from a value\nentered by the user called <code>num</code> which gives away no secrets, and the prompt\nwas \"How many no. of words?\" - so <code>num</code> and <code>cntr</code> are the number of 'words',\nbut the list created by <code>create_c_list</code> makes no mention of 'words'. It is as\nif you don't want the reader to understand what it does. The <code>for</code> loop locates the node according to the <code>cntr</code>, which takes a long time if <code>cntr</code> is zero, as the loops starts from 1. Then you do another\nloop, this time a <code>while</code> in which you find the list entry before the one\n(called <code>it</code>) that you located in the <code>for</code> loop. You could have combined the two loops. You then delete <code>it</code> using an unnecessary temporary\nvariable.<br>\nAnd so the outer loop continues until there is only one entry in the list - that condition could have been the condition for the outer <code>while</code> loop.</p>\n\n<p>In <code>printList</code> (which uses camelCase while <code>create_c_list</code> doesn't) you don't\nmodify the list, so it should be passed <code>const</code>. Parameter <code>list_tail</code> is\ninaccurate - a circular list has no tail. Call it just <code>list</code>. </p>\n\n<p>Also, putting <code>main</code> last avoids the need for prototypes, all functions except\n<code>main</code> should be <code>static</code> and the names of <code>struct ll_core</code> and <code>c_ll</code> would\nbe better as <code>struct node</code> and <code>value</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-10T23:56:49.950",
"Id": "37092",
"ParentId": "29974",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37092",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T03:47:22.707",
"Id": "29974",
"Score": "2",
"Tags": [
"optimization",
"c",
"linked-list",
"circular-list"
],
"Title": "Inky pinky ponky game / Josephus problem"
}
|
29974
|
<p>I have recently written my first jQuery plugin. It is a responsive jQuery carousel plugin. It seems to be functioning well apart from on window re-size. Sometimes if the window is re-sized too fast I get the following console error <code>RangeError: Maximum call stack size exceeded</code>, despite a timer function being used to prevent continuous re-rendering.</p>
<p>I'm looking for any best practices on things I've missed and should be following.</p>
<p><a href="http://jsfiddle.net/qTPnz/" rel="nofollow">jsFiddle</a></p>
<p><a href="https://github.com/tommybfisher/jquery.fullslide.js" rel="nofollow">GitHub</a></p>
<p><strong>Commented plugin</strong></p>
<pre><code>(function($) {
$.fullslide = function(element, options) {
// Declare plugins variables
var autoInt; // variable to store the timing function
// Default options
var defaults = {
displayQty : 1,
moveQty : 1,
moveDuration : 1000,
moveEasing : "swing",
slideMargin : 20,
minWidth : "",
maxWidth : "",
autoSlide : true,
autoDirection : "left",
slideDelay : 3000,
pauseOnHover : true,
onReady : function() {},
onBeforeSlide : function() {},
onAfterSlide : function() {}
}
// Use "slider" to reference the current instance of the object
var slider = this;
// This will hold the merged default, and user-provided options
slider.settings = {}
// Set vars to be used from outside of plugin, specifically for event bindings
slider.vars = {}
var $element = $(element), // Reference to the jQuery version of DOM element
element = element; // Reference to the actual DOM element
slider.init = function() {
/**
* The "constructor" method - set the slider up at runtime,
* including creating DOM elements and setting widths.
*/
// Declare method's variables
var fullslideLi,
ulH,
loaded,
fontSize;
// The plugin's final properties are the merged default and
// user-provided options (if any)
slider.settings = $.extend({}, defaults, options);
// Set hoverPrevent to 0 - used to prevent accidental auto start when manually stopped
slider.vars.hoverPrevent = 0;
// Create DOM elements
$element.wrap('<div class="fullslide-wrap" style="opacity:0;" />');
$element.closest(".fullslide-wrap").append("<div class='fullslide-controls'><a href='#' class='fullslide-left'>left</a> <a href='#' class='fullslide-right'>right</a></div>");
// Count how many slides are orginally and update the variable
fullslideLi = $element.children("li");
origSlideQty = $(fullslideLi).length;
// Check the font size of the LI to help us know when the contents
// have been loaded
fontSize = parseInt( $(fullslideLi).css("fontSize") );
// Ensure we're not trying to display more slides than we have
if( slider.settings.displayQty > origSlideQty ) {
slider.settings.displayQty = origSlideQty;
}
// Ensure we cannot move more slides than we have
if( slider.settings.moveQty > origSlideQty ) {
slider.settings.moveQty = origSlideQty;
}
// Ensure we don't try to move more than we are displaying
if( slider.settings.moveQty > slider.settings.displayQty ) {
slider.settings.moveQty = slider.settings.displayQty;
}
// Triplicate the slides so there's always enough in view when sliding
$(fullslideLi).clone().prependTo($element);
$(fullslideLi).clone().appendTo($element);
// Set the slides' width
setWidths();
// Wait for the content to be loaded before firing the callback
loaded = 0;
var waitForLoad = function() {
// Contents should be loaded when the last LI is bigger than
// the LIs default font size
if( loaded !== 1 ) {
if( $(fullslideLi).last().outerHeight() > fontSize ) {
loaded = 1;
waitForLoad();
} else {
window.setTimeout( waitForLoad, 500 );
}
} else {
// Wait a bit longer to ensure it was fully loaded
window.setTimeout( function() {
// Everything loaded
ulH = $(fullslideLi).first().height();
// Apply the height to the UL
$element.css({
height : ulH + "px"
});
// Show the slider if hidden
$element.css({
opacity : 1
});
$element.closest(".fullslide-wrap").css({
opacity : 1
});
// All done, if an 'onReady' function has been set, call it now
if( slider.settings.onReady && typeof(slider.settings.onReady) === "function" ) {
slider.settings.onReady();
}
// If set to slide automatically, start now
if( slider.settings.autoSlide === true ) {
slider.startAuto();
}
}, 1000 );
}
}
waitForLoad();
}
// ---------------------------------------------------------------------------------------------------------- //
// ------------------------------------------- PUBLIC METHODS ----------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------- //
slider.slide = function(dir, qty, duration, easing) {
/**
* Invoke the sliding action, either left or right
*/
// Declare method's variables
var slideWpx,
moveDistance,
relativeMovement,
fullslideLi;
// If parameters haven't been sent with the function, set to defaults
dir = (typeof dir === "undefined") ? "left" : dir;
qty = (typeof qty === "undefined") ? slider.settings.moveQty : qty;
duration = (typeof duration === "undefined") ? slider.settings.moveDuration : duration;
easing = (typeof easing === "undefined") ? slider.settings.moveEasing : easing;
// Do not do anything if the ul is currently animating
if( !$element.filter(':animated').length ) {
// Before sliding happens pass in the 'onBeforeSlide' function, if set
if( slider.settings.onBeforeSlide && typeof(slider.settings.onBeforeSlide) === "function" ) {
slider.settings.onBeforeSlide();
}
// Get the current state of the slides as the variable fullslideLi
fullslideLi = $element.children("li");
// Get width in px of slide so we know how far to move it
slideWpx = $(fullslideLi).first().outerWidth();
// Calculate the move distance
moveDistance = (slideWpx * qty) + (slider.settings.slideMargin * qty);
// Set the relative movement as a variable
if( dir === "left" ) {
relativeMovement = "-=" + moveDistance;
} else {
relativeMovement = "+=" + moveDistance;
}
// Call the animation function - if moving left move the li's that have slid out of view to the end,
// else if moving right move the li's that have slid out of view to the start
$element.animate({
left : relativeMovement
}, duration, easing, function() {
// Once animation is complete -
// Get the current state of the li elements
fullslideLi = $element.children("li");
if( dir === "left" ) {
// If moving left move the amount of slides moved by to the end
$(fullslideLi).slice(0, slider.settings.moveQty).appendTo($element);
} else {
// Else if moving right, move the amount of slides moved to the start
$(fullslideLi).slice(-slider.settings.moveQty).prependTo($element);
}
// Reset the position to take into account the removed slides
offsetFirstSlide();
// After sliding happens, if set pass in the 'onAfterSlide' function as a callback function
// to setUlHeight()
if( slider.settings.onAfterSlide && typeof(slider.settings.onAfterSlide) === "function" ) {
setUlHeight( slider.settings.onAfterSlide );
} else {
// Otherwise just call setUlHeight
setUlHeight();
}
});
}
};
slider.startAuto = function(allowHoverStop) {
/**
* Begin the automatic scrolling
*/
if( allowHoverStop && allowHoverStop === true ) {
slider.vars.hoverPrevent = 0;
}
// Start the interval timer
autoInt = setInterval( function() { slider.slide( slider.settings.autoDirection ); }, slider.settings.slideDelay );
};
slider.stopAuto = function(preventHoverStart) {
/**
* Stop the automatic scrolling
*/
// If preventHoverStart has been passed then don't allow hover events to trigger auto slider
if( preventHoverStart && preventHoverStart === true ) {
slider.vars.hoverPrevent = 1;
}
clearInterval(autoInt);
};
// ---------------------------------------------------------------------------------------------------------- //
// ------------------------------------------- PRIVATE METHODS ---------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------- //
var offsetFirstSlide = function() {
/**
* Cater for the fact that there are always slides to the left of the
* currenly viewed slides. This offsets the ul so that we don't see
* the slides to the left.
*/
// Declare method's variables
var fullslideLi,
slideWpx,
offset;
// Get the current state of the slides as the variable fullslideLi
fullslideLi = $element.children("li");
// Get the width in pixels of the slide so we know how much to offset it by
slideWpx = $(fullslideLi).first().outerWidth();
// Calculate the offset - we have duplicated all the original slides infront of the viewable slide, so that's how much we offset by, plus margin
offset = origSlideQty * (slideWpx + slider.settings.slideMargin);
// Apply the offset
$element.css("left", "-" + offset + "px");
};
var setWidths = function() {
/**
* Calculate and set the widths of the slides and the ul container.
*/
// Declare method's variables
var fullslideLi,
slideQty,
ulW,
ulWpx,
slideWpx,
totalM,
slideW;
// Set slide widths
// Assign fullslideLi var
fullslideLi = $element.children("li");
// Get the current number of slides to work out the width of ul
slideQty = $(fullslideLi).length;
// To get the ul width, calculate the percentage from the amount will be shown then
ulW = (100 / slider.settings.displayQty) * slideQty;
// Apply the width and the height to the ul
$element.css("width", ulW + "%");
// Set the cell width in %
slideW = 100 / slideQty;
// Calculate the width of the ul and slide in px
ulWpx = $element.css("width");
slideWpx = parseInt(ulWpx) / slideQty;
// Include the margins in with the calculation, if any
if( slider.settings.slideMargin > 0 ) {
// Get the total margin for the whole slideshow
totalM = slider.settings.slideMargin * (slider.settings.displayQty - 1);
// Calculate width of the slides
slideWpx = slideWpx - (totalM / slider.settings.displayQty);
}
// Calculate if the min width is exceeded
if( slider.settings.minWidth ) {
if( slideWpx < slider.settings.minWidth ) {
// Don't decrement if the current display quantity is 1
if( slider.settings.displayQty > 1 ) {
--slider.settings.displayQty;
// Recall this function with the new display quantity setting
setWidths();
// Prevent subsquent rendering of the CSS before the sizes have been recalculated
return;
}
// Slide width is bigger than min width
// Calculate if another slide could fit in, without making all slides less than min width
// AND that we don't display more than one of each
} else if( (Math.ceil(slideWpx * slider.settings.displayQty / (slider.settings.displayQty + 1)) > slider.settings.minWidth) && (slider.settings.displayQty < origSlideQty) ) {
++slider.settings.displayQty;
// Recall this function with the new display quantity setting
setWidths();
// Prevent subsquent rendering of the CSS before the sizes have been recalculated
return;
}
// Calculate if the max width is exceeded
} else if( slider.settings.maxWidth ) {
if( slideWpx > slider.settings.maxWidth ) {
// Don't increment if the display quantity is the same amount as original slide quantity
if( slider.settings.displayQty < origSlideQty ) {
++slider.settings.displayQty;
// Recall this function with the new display quantity setting
setWidths();
// Prevent subsquent rendering of the CSS before the sizes have been recalculated
return;
}
// Slide width is smaller than max width
// Calculate if a slide could be removed, without making all slides greater than max width
// AND that we don't display any less than one
} else if( Math.floor(slideWpx * (slider.settings.displayQty) / (slider.settings.displayQty - 1) <= slider.settings.maxWidth) && (slider.settings.displayQty > 1) ) {
--slider.settings.displayQty;
// Recall this function with the new display quantity setting
setWidths();
// Prevent subsquent rendering of the CSS before the sizes have been recalculated
return;
}
}
// Apply the slide margins, if any
if( slider.settings.slideMargin > 0 ) {
$(fullslideLi).css("marginRight", slider.settings.slideMargin + "px");
}
//Apply the width
$(fullslideLi).css("width", slideWpx + "px");
// Once all the sizes are set, we need to offset the ul to hide the slides to the left of the viewable slides
offsetFirstSlide();
};
var setUlHeight = function(callback) {
/**
* Set the height of the ul to be called after every slide moves
*/
// Declare method's variables
var fullslideLi,
ulH;
// Assign fullslideLi var
fullslideLi = $element.children("li");
// Find the height of the LI so we can set the height of the UL to prevent wrapping
ulH = $(fullslideLi).first().height();
// Apply the height to the ul and animate it
$element.animate({
height : ulH + "px"
}, 100, function() {
// If a callback has been include call it now
if( callback && typeof(callback) === "function" ) {
callback();
}
});
};
var waitOnEvent = (function() {
/**
* Function to set a timeout for the window resize event
*/
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "1";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
// Resize the slides when window size changes
$(window).resize(function() {
waitOnEvent(function() {
setWidths();
setUlHeight();
}, 500, "reset1");
});
// ---------------------------------------------------------------------------------------------------------- //
// ------------------------------------------------ RUNTIME ------------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------- //
// Call the "constructor" method
slider.init();
}
// ---------------------------------------------------------------------------------------------------------- //
// ------------------------------------------- PLUGIN DEFINITION -------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------- //
// Add the plugin to the jQuery.fn object
$.fn.fullslide = function(options) {
// Iterate through the DOM elements we are attaching the plugin to
return this.each(function() {
// If plugin has not already been attached to the element
if( undefined == $(this).data('fullslide') ) {
// Create a new instance of the plugin
// Pass the DOM element and the user-provided options as arguments
var slider = new $.fullslide(this, options);
// Store a reference to the plugin object
$(this).data('fullslide', slider);
}
});
}
// ---------------------------------------------------------------------------------------------------------- //
// --------------------------------------------- EVENT BINDINGS --------------------------------------------- //
// ---------------------------------------------------------------------------------------------------------- //
// Slide right on press of the left control
$('body').on('click', '.fullslide-left', function(event) {
var selfEl = $(this).parent(".fullslide-controls").prev("ul");
// Do not do anything if the ul is currently animating
var pref = {};
pref.moveQty = selfEl.data('fullslide').settings.moveQty,
pref.moveDuration = selfEl.data('fullslide').settings.moveDuration,
pref.easing = selfEl.data('fullslide').settings.easing;
selfEl.data('fullslide').slide("right", pref.moveQty, pref.moveDuration, pref.easing);
event.preventDefault();
});
// Slide left on press of the right control
$('body').on('click', '.fullslide-right', function(event) {
var selfEl = $(this).parent(".fullslide-controls").prev("ul");
var pref = {};
pref.moveQty = selfEl.data('fullslide').settings.moveQty,
pref.moveDuration = selfEl.data('fullslide').settings.moveDuration,
pref.easing = selfEl.data('fullslide').settings.easing;
selfEl.data("fullslide").slide("left", pref.moveQty, pref.moveDuration, pref.easing);
event.preventDefault();
});
// Pause on hover
$('body').on(
{
mouseenter: function() {
var selfEl = $(this).children("ul");
if( selfEl.data('fullslide').settings.autoSlide === true && selfEl.data('fullslide').settings.pauseOnHover === true && selfEl.data('fullslide').vars.hoverPrevent === 0 ) {
selfEl.data("fullslide").stopAuto();
}
},
mouseleave: function() {
var selfEl = $(this).children("ul");
if( selfEl.data('fullslide').settings.autoSlide === true && selfEl.data('fullslide').settings.pauseOnHover === true && selfEl.data('fullslide').vars.hoverPrevent === 0 ) {
selfEl.data("fullslide").startAuto();
}
}
}
, '.fullslide-wrap');
})(jQuery);
</code></pre>
<p><strong>An example call</strong></p>
<pre><code>var slider = $(".slide123").fullslide({
displayQty : 2,
slideMargin : 0,
moveDuration : 2000,
onAfterSlide : function() {
console.log("slid");
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T07:59:13.537",
"Id": "47565",
"Score": "1",
"body": "We cannot address the error you're receiving (that's for Stack Overflow), but we *can* address the request for best practices."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T08:17:30.487",
"Id": "47566",
"Score": "0",
"body": "Yes of course. Hopefully the error will be addressed by implementing better best practices anyway."
}
] |
[
{
"body": "<p>From a once over;</p>\n\n<ul>\n<li>Very well commented</li>\n<li><p>Assigning <code>element</code> to <code>element</code> is overkill here and does nothing:</p>\n\n<pre><code>var $element = $(element), // Reference to the jQuery version of DOM element\n element = element; // Reference to the actual DOM element\n</code></pre></li>\n<li><p>From a naming perspective, I would refrain from using the tag type in the variable name:</p>\n\n<pre><code>// Declare method's variables\nvar fullslideLi,\n ulH,\n loaded,\n fontSize;\n</code></pre>\n\n<p>You are tying yourself to an implementation detail with the name, you could go for <code>element</code> or <code>el</code> in those variable names</p></li>\n<li><p>Consider <code>Math.min</code> here:</p>\n\n<pre><code> // Ensure we cannot move more slides than we have\n if( slider.settings.moveQty > origSlideQty ) {\n slider.settings.moveQty = origSlideQty;\n }\n\n // Ensure we don't try to move more than we are displaying\n if( slider.settings.moveQty > slider.settings.displayQty ) {\n slider.settings.moveQty = slider.settings.displayQty;\n }\n</code></pre>\n\n<p>could be</p>\n\n<pre><code> slider.settings.moveQty = Math.min( origSlideQty, slider.settings.moveQty , slider.settings.displayQty );\n</code></pre>\n\n<p>furthermore from a DRY perspective I would probably have moved <code>slider.settings</code> to a local <code>var settings</code>:</p>\n\n<pre><code> settings.moveQty = Math.min( origSlideQty, settings.moveQty , settings.displayQty );\n</code></pre></li>\n<li><code>window.setTimeout</code> returns a timeoutID, you should store this timeoutID and clear it after the timeout. And then only call <code>window.setTimeout</code> if the timeoutID is cleared out. I hope that makes sense. It should prevent your problems</li>\n<li><p>You can set more than 1 property with <code>.css</code>:</p>\n\n<pre><code> // Apply the height to the UL\n $element.css({\n height : ulH + \"px\"\n });\n\n // Show the slider if hidden\n $element.css({\n opacity : 1\n });\n</code></pre>\n\n<p>could be</p>\n\n<pre><code> // Apply the height to the UL and show the slider\n $element.css({\n height : ulH + \"px\", \n opacity : 1\n });\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-15T04:21:20.880",
"Id": "121531",
"Score": "2",
"body": "Thanks for the thorough comments. I asked this question over a year ago and can see many things I would do different now. But nevertheless you've still showed me a couple of ideas I wouldn't have thought about "
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-15T02:05:24.663",
"Id": "66696",
"ParentId": "29982",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "66696",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T07:52:05.047",
"Id": "29982",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"performance",
"plugin"
],
"Title": "jQuery carousel plugin"
}
|
29982
|
<p>I have to create a class <code>Data</code> with dates and there should be some methods and constructor. Maybe some method can be done in another way, especially the method <code>wichIsEarlier</code>, because I made it <code>static</code> and I'm not really sure about it. Please take a look on this class and say what is good and what is bad. Is it better to use class <code>Calendar</code> than <code>GregorianCalendar</code>? Where should I throw an exception?</p>
<pre><code>class Data {
GregorianCalendar gcalendar = new GregorianCalendar();
Data(GregorianCalendar x) {
gcalendar = x;
}
public boolean czyPrzestepny() {
boolean rr = false;
if (gcalendar.isLeapYear(gcalendar.get(Calendar.YEAR))) {
rr = true;
} else {
rr = false;
}
return rr;
}
public int ileDniWMiesiacu() {
int dni = 0;
switch (gcalendar.get(Calendar.MONTH)) {
case 0:
case 2:
case 4:
case 6:
case 7:
case 9:
case 11:
dni = 31;
break;
case 3:
case 5:
case 8:
case 10:
dni = 30;
break;
case 1:
dni = 28;
dni = 29;
break;
}
return dni;
}
static String wichIsEarlier(GregorianCalendar y, GregorianCalendar gcalendar) {
int yyear = y.get(Calendar.YEAR);
int ymonth = y.get(Calendar.MONTH);
int ydate = y.get(Calendar.DATE);
int year = gcalendar.get(Calendar.YEAR);
int month = gcalendar.get(Calendar.MONTH);
int day = gcalendar.get(Calendar.DATE);
String re = "";
if (yyear > year)
re = "moja data nie jest wczesniejsza od teraz";
else if (yyear < year)
re = " jest wczesniejsze";
else if (ymonth < month)
re = " jest wczesniejsze";
else if (ymonth > month)
re = " nie jest wczesniejsze";
else if (ydate > day)
re = " nie jest wczesniejsze";
else if (ydate < day)
re = " jest wczesniejsze";
return re;
}
public void changeDate(GregorianCalendar y) {
gcalendar = y;
}
public String toString() {
String months[] = { "Jan", "Feb", "Mar", "Apr", "Mai", "June", "July", "Aug", "Sep", "Okt",
"Nov", "Dec" };
String str = "";
str = "Data: " + gcalendar.get(Calendar.DATE) + " " + months[gcalendar.get(Calendar.MONTH)]
+ " " + gcalendar.get(Calendar.YEAR);
return str;
}
}
public class Datum {
public static void main(String[] args) {
GregorianCalendar gc = new GregorianCalendar();
GregorianCalendar yycal = new GregorianCalendar(1994, 0, 15);
Data dt = new Data(gc);
System.out.println("czy Przestepny " + dt.czyPrzestepny());
System.out.println("ile dni w miesiacu " + dt.ileDniWMiesiacu());
System.out.println("ktore jest wczesniejsze " + Data.wichIsEalier(gc, yycal));
System.out.println(dt.toString());
dt.changeDate(yycal);
System.out.println(dt.toString());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T14:25:16.097",
"Id": "47582",
"Score": "0",
"body": "First thing, some of your methods name don't seems to be in English. You should change those because I have no idea what `ileDniWMiesiacu` is suppose to do. This will help to have a better review in my opinion!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T14:31:35.453",
"Id": "47583",
"Score": "0",
"body": "replace also case 1: in default:, and modify the numbers like 6 (june) is a 30 days month."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T14:56:57.317",
"Id": "47585",
"Score": "0",
"body": "month in GregorianCalender is counting from 0 so 6 is July and it is 31"
}
] |
[
{
"body": "<p>As Marc-Andre mentioned, you should really use English for your methods and classes, so that we can review better.</p>\n\n<p>Still, I am fairly certain that</p>\n\n<pre><code>public boolean czyPrzestepny(){\n boolean rr = false;\n if(gcalendar.isLeapYear(gcalendar.get(Calendar.YEAR))){\n rr=true;\n }\n else{\n rr=false;\n }\n return rr;\n}\n</code></pre>\n\n<p>could probably written as </p>\n\n<pre><code>public boolean isLeapYear()\n{\n return gcalendar.isLeapYear(gcalendar.get(Calendar.YEAR))\n}\n</code></pre>\n\n<p>The following code seems, wrong, you probably forgot to check for leap year?</p>\n\n<blockquote>\n<pre><code> case 1:\n dni = 28;dni= 29;\n</code></pre>\n</blockquote>\n\n<p>Also, <code>wichIsEalier</code> should be <code>wichIsEarlier</code></p>\n\n<p>Also, gcalendar does not follow proper lowerCamelCase, and Data is just too ambiguous as a class name.</p>\n\n<p>Finally, for getting the month name in toString, you could just call <code>gcalendar.get(Calendar.MONTH).</code> and take the first 3 characters. Free I18N is good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T14:57:21.407",
"Id": "29994",
"ParentId": "29992",
"Score": "5"
}
},
{
"body": "<p>You are making a class which behaves like <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html\" rel=\"nofollow noreferrer\"><code>GregorianCalendar class</code></a> so you can always check the <a href=\"http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/GregorianCalendar.java\" rel=\"nofollow noreferrer\">source code</a>. But if it is an assignment try to do it yourself first and compare your program to see how the creators choose the logic and building pattern.</p>\n\n<ul>\n<li><pre><code>GregorianCalendar gcalendar = new GregorianCalendar(); // unnecessary\n</code></pre>\n\n<p>make it inside the constructor and make <code>gcalendar</code> a private field.</p></li>\n<li><p>I don't know your language so try to post the code in english as far as possible. Your method names such as <code>czyPrzestepny</code>, <code>ileDniWMiesiacu</code> is hard to understand. You can also use Javadoc.</p></li>\n</ul>\n\n<blockquote>\n <p>Is it better to use class Calendar than GregorianCalendar?</p>\n</blockquote>\n\n<p><a href=\"https://stackoverflow.com/questions/10177523/using-superclass-to-initialise-a-subclass-object-java\">Yes</a>. Cause abstraction and <a href=\"https://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n?lq=1\">code re usability</a> are some main parts of OOP language.</p>\n\n<ul>\n<li><code>wichIsEalier</code> should be <code>isBefore</code> and non-static and return boolean similar to <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html#before%28java.lang.Object%29\" rel=\"nofollow noreferrer\"><code>Calendar.before()</code></a>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T15:06:37.460",
"Id": "29995",
"ParentId": "29992",
"Score": "4"
}
},
{
"body": "<p>Here's the things I would question in a code review:</p>\n\n<ol>\n<li>Not sure what the year, month, and day members are for. If you want to be able to get those values from the gcalendar, why not just get them from the gcalendar? What you are trying to do there doesn't make much sense to me.</li>\n<li>Your naming convention does not really follow standards. I don't know what a \"gcalendar\" is, but I know what a \"usersBirthDay\" is or a \"purchaseDate\" is. I would consider renaming your variables and methods...they should be \"self documenting\".</li>\n<li>You are not following good Java Bean patterns. First, your member variables should be marked private, or at least protected. Second, you need to have getters/setters that are named \"get\" and/or \"set\" for the members, depending on if the value should be read/write accessible. Methods that return a boolean are typically named \"is\" instead of \"get, for example \"isCzyPrzestepny()\".</li>\n<li>None of your methods are marked as public, private, or protected. You should specify your security specifically.</li>\n<li>No JavaDoc at all (this could simply be because you took it out to post, but you should have JavaDoc on your public methods, constructors, etc.</li>\n<li>Use \"Calendar\" instead of \"GregorianCalendar\". The reason we have interfaces and abstract classes is so we can generalize the code to work with any type of that object. General good architecture says you should always reference objects by the least specific you can. In this case, I don't see any reason to not reference Calendar.</li>\n<li>Calendar has methods to determine if one Calendar is before() or after() the other. You should be using those, and not rolling your own.</li>\n<li>You asked if you can check the Calendar in the constructor? Sure. What I would recommend is checking the Calendar passed in the constructor IN the constructor, and throwing an exception if it doesn't pass the test. The exception can be either an Exception (requires the calling code to try/catch or rethrow it) or a RuntimeException (does not require the calling code to try/catch or rethrow it, but will make the program halt if it doesn't), and you can either use one of the off-the-shelf ones in the API or create a custom exception. I usually prefer to create my own custom Exceptions as to make troubleshooting easier.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T12:06:03.207",
"Id": "30384",
"ParentId": "29992",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29995",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T13:53:34.267",
"Id": "29992",
"Score": "8",
"Tags": [
"java",
"datetime"
],
"Title": "GregorianCalendar"
}
|
29992
|
<p>I'm a beginner PHP developer and it's my first time using MySQLi. I'm not sure if this is a correct implementation of the connection and query because some people defend this method and some others not. I need a solid implementation for heavy database usage.</p>
<p>Connection:</p>
<pre><code>class bbddConnection {
private $_host = 'localhost';
private $_username = 'username';
private $_password = 'password';
private $_db_name = 'DBNAME';
private $_mysqli = NULL;
private static $_instance = NULL;
private function __construct() {
$this->connection();
}
public static function get_instance() {
if (!isset(self::$_instance)) {
//echo "Creating new instance.\n";
$class_name = __CLASS__;
self::$_instance = new $class_name;
}
return self::$_instance;
}
private function connection() {
//echo "Creating new connection.\n";
try {
//The mysqli object will be created once and only once
if (!$this->_mysqli instanceof mysqli) {
$this->_mysqli = new mysqli($this->_host, $this->_username, $this->_password);
}
if ($this->_mysqli->connect_errno) {
throw new Exception('An error occured: ' . $this->_mysqli->connect_error);
} else {
$this->select_db();
}
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
}
private function select_db() {
//echo "Selecting database.\n";
try {
$this->_mysqli->select_db($this->_db_name) or die('Could not find database');
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
}
public function query($query) {
if (!isset($query))
return;
//echo "Prevent SQL Injection. \n"
$query = $this->_mysqli->real_escape_string($query);
return $this->_mysqli->query($query);
}
public function stmt_init() {
return $this->_mysqli->stmt_init();
}
public function __destruct() {
if ($this->_mysqli instanceof mysqli) {
$this->_mysqli->close();
}
}
private function __clone() {
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
private function __wakeup() {
trigger_error('Unserializing is not allowed.', E_USER_ERROR);
}
}
</code></pre>
<p>Query:</p>
<pre><code>class gestorUsuarios {
private $db;
public function __construct() {
$this->db = bbddConnection::get_instance();
}
/**
* Returns the Name of the user according his ID
* @param int id
* @return string Nombre, if an error occurred.
* returns <b>FALSE</b>
*/
function getUserName($id)
{
$stmt = $this->db->stmt_init();
if ($stmt->prepare("Select Nombre from usuarios where id = ?")) {
$name = '';
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($name);
while ($stmt->fetch())
$nombre = $name;
$stmt->close();
return $nombre;
} else {
return false;
}
}
/**
* Edit the Name of the user according his ID
* @param String Nombre, int id
* @return Boolean if an error occurred.
* returns <b>FALSE</b>, else returns <b>TRUE</b>
*/
function setUserName($nombre, $id)
{
$stmt = $this->db->stmt_init();
if ($stmt->prepare("UPDATE usuarios SET Nombre=? WHERE id =?")) {
$stmt->bind_param('si', $nombre, $id);
$stmt->execute();
$stmt->close();
return true;
} else {
return false;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Similar to this one: <a href=\"https://codereview.stackexchange.com/questions/29670/minimalistic-mysql-db-class/29685#29685\">Minimalistic mysql db class</a></p>\n\n<p>To answer your question: NO!</p>\n\n<p>The short answer: Throw away your code, burn it, do whatever you want with it but <strong>never</strong> use it in a production enviroment. Just don't.</p>\n\n<p>The long answer: Again, don't use this code, ever. You are even violating nearly every <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow noreferrer\">SOLID</a> rule</p>\n\n<p>As far as I can see you are trying to write some wrapper around the mysqli object. But the question remains: why? and what problem are you trying to solve?</p>\n\n<p>As far as I can see, you are trying to solve 2 problems with one solution. Oh oh, this is doomed to fail. You want to solve the problem of always having to check wether an instance of mysqli exists or not and you want to not have to worry about connecting and creating a mysqli instance and query-ing/sanitizing the database with a given query. 3 different things.</p>\n\n<p>Then you start designing the solution to that problem. When that is done, you should take a step back and ask the question 'Is my code easy to use?' and 'Is it easy configurable and extendable?' and most important 'is it easy to debug?'.</p>\n\n<p>The answer to those 3 questions is simple: <strong>NO!</strong></p>\n\n<ul>\n<li>If you want to change a connection parameter you have to change the\ncode of the class itself, bad bad bad.</li>\n<li>If something goes wrong (an exception) you echo an error message. So\nwhat if I first get an instance of your database and it echo's some\nerror message, and then my code sends a header(); . Ooeehh, a nice\nheader allready sent error. Hf debugging that error...</li>\n<li>...</li>\n</ul>\n\n<p>But in fact, that isn't your real problem. The real problem you have is that you are writing code without designing it.</p>\n\n<p>If your problem is that you want only one instance to exist you should only create one instance instead of relying on a get_instance() function or Singleton pattern. If a class needs a database connection, pass it in in the __construct(). More on this topic: </p>\n\n<ul>\n<li><a href=\"http://www.slideshare.net/go_oh/singletons-in-php-why-they-are-bad-and-how-you-can-eliminate-them-from-your-applications\" rel=\"nofollow noreferrer\">http://www.slideshare.net/go_oh/singletons-in-php-why-they-are-bad-and-how-you-can-eliminate-them-from-your-applications</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1812472/in-a-php-project-what-patterns-exist-to-store-access-and-organize-helper-objec\">https://stackoverflow.com/questions/1812472/in-a-php-project-what-patterns-exist-to-store-access-and-organize-helper-objec</a></li>\n</ul>\n\n<p>To sum up, sometimes the problems we are solving tend to be meta-problems. The solution we make is actually a fix. A good article on this: <a href=\"http://thedailywtf.com/Articles/The_Complicator_0x27_s_Gloves.aspx\" rel=\"nofollow noreferrer\">http://thedailywtf.com/Articles/The_Complicator_0x27_s_Gloves.aspx</a></p>\n\n<p>On a complete diffrent note, instead of using mysqli. use PDO.\nThis is a realy nice OO way of using a database. more on pdo:</p>\n\n<ul>\n<li><a href=\"http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/\" rel=\"nofollow noreferrer\">http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/</a></li>\n<li><a href=\"http://www.php.net/manual/en/class.pdo.php\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/class.pdo.php</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T16:03:26.200",
"Id": "47662",
"Score": "0",
"body": "Thanks for your reply. Before I change the code, I would like to discuss a certain topic:- PDO: the connections to databases with PDO may be more 'independent' (for compatibility) and even facilitate interactions, but DO NOT offer the same performance as Mysqli connection. Doing that is not as optimized as possible, so I decided to use Mysqli instead of PDO. But I only read a lot of pages talking about migrating from mysqli PDO, so I would like to be sure that the benefits are sufficient to dispense with the performancepd: sorry for my English -.-''"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T07:43:06.777",
"Id": "47708",
"Score": "1",
"body": "@RmG152 PDO isn't slower then mysqli: http://jnrbsn.com/2010/06/mysqli-vs-pdo-benchmarks If your application is slower with PDO, it's they way you are using PDO. Here a good comparison between pdo and mysqli: http://net.tutsplus.com/tutorials/php/pdo-vs-mysqli-which-should-you-use/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T16:44:45.390",
"Id": "47757",
"Score": "0",
"body": "Agree completely with @Pinoniq on performance. PDO is implemented as an extension and is thus going to be faster than any PHP connection object that you could write (unless maybe you made your own extension). Of course it's doubtful that you would actually notice any speed difference."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T10:24:30.630",
"Id": "30025",
"ParentId": "29997",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T15:56:03.077",
"Id": "29997",
"Score": "4",
"Tags": [
"php",
"beginner",
"mysqli"
],
"Title": "Database connection query"
}
|
29997
|
<p>I have written a plugin loader in Ruby, and I would like to know if it uses the best technique to handle classes, or if anyone has any recommendations on how to improve my code.</p>
<p>I have written a class called PluginManager, and an accompanying module named Plugin. The names of these are self explanatory, one handles the plugins (loading them), and the other is a module to be included by plugin files.</p>
<p>My Plugin module looks like the following, and currently just replaces the puts method, to ensure all output comes through the logger. I had some issues with making the @@logger variable definable, and I have solved it, but I'm not sure if there is a better way to solve it.</p>
<pre><code>module Plugin
@@logger = nil
def puts(string)
if @@logger.nil?
super(string)
else
@@logger.info string
end
end
# I tried the following, but it didn't work (still said "undefined method 'logger='")
# class << self
# attr_accessor :logger
# end
def self.logger=(string)
@@logger = string
end
end
</code></pre>
<p>My PluginManager class is a bit more complex, but not by much. It simply takes an array of file names, performs some checks to ensure everything exists, then loads them into the <code>loaded_plugins</code> array.</p>
<pre><code>class PluginManager
def initialize(logger=nil)
set_logger logger
@loaded_plugins = []
end
def set_logger(logger)
@logger = logger
Plugin.logger = logger
end
def load(plugins, directory="./plugins/")
# Iterate through plugins
plugins.each do |plugin|
# Work out plugin information
class_name = plugin.split(".").first.downcase.capitalize
full_path = directory + plugin
@logger.info "Loading \"#{class_name}\" from \"#{full_path}\""
# Ensure the plugin file exists
if File.file? full_path
# Load the plugin file and ensure the class exists
require full_path
unless eval("defined? #{class_name}")
@logger.error "Class \"#{class_name}\" not found!"
next
end
# Get the plugin's class and ensure it includes plugin
plugin_class = eval class_name
if plugin_class.ancestors.include? Plugin
# Ensure the initialize method takes no arguments
if plugin_class.allocate.method(:initialize).arity > 0
@logger.error "\"#{class_name}.initialize\" accepts more than 0 arguments"
next
end
# Load the plugin itself by pushing it into the loaded_plugins list
@logger.info "Plugin \"#{class_name}\" loaded!"
@loaded_plugins.push plugin_class.new
@logger.info "Plugin \"#{class_name}\" enabled!"
else
@logger.error "The class \"#{class_name}\" does not include Plugin!"
next
end
else
# Check if the file exists, or is a directory
unless File.exist? full_path
@logger.error "Unable to find file \"#{full_path}\""
else
@logger.error "\"#{full_path}\" is a directory!"
end
next
end
end
end
end
</code></pre>
<p>I am wondering if there are any better ways to perform some of the checks, such as using exec to find if a class exists.</p>
|
[] |
[
{
"body": "<h1>Formatting</h1>\n\n<h2>Indenting</h2>\n\n<p>The standard ruby indent is 2 spaces. For example:</p>\n\n<pre><code>def puts(string)\n if @@logger.nil?\n super(string)\n else\n @@logger.info string\n end\nend\n</code></pre>\n\n<h1>Design</h1>\n\n<h2>Class Variables</h2>\n\n<p>I would not use class variables to set the logging. As you\ndiscovered, they have <a href=\"https://stackoverflow.com/a/3803089/238886\">surprising\nbehavior</a>.</p>\n\n<p>Instead, I would just use a <em>class instance variable</em> that belonged\njust to the Plugin class and was not automatically shared with its\ndescendants.</p>\n\n<pre><code>module Plugin\n class << self\n attr_accessor :logger\n end\nend\n</code></pre>\n\n<p>If that's all you do, then the descendants will have to do this to access the logger:</p>\n\n<pre><code>Plugin.logger.info 'Logging some info'\n</code></pre>\n\n<p>That's awful, so we'll add an instance method that defers to the class method:</p>\n\n<pre><code>module Plugin\n\n class << self\n attr_accessor :logger\n end\n\n def logger\n self.class.logger\n end\n\nend\n</code></pre>\n\n<p>Now instances of Plugin can log easily:</p>\n\n<pre><code>logger.info \"Logging some info\"\n</code></pre>\n\n<h1>Ruby tricks</h1>\n\n<h2>Use #inspect to quote strings</h2>\n\n<p>Instead of this,</p>\n\n<pre><code>@logger.info \"Loading \\\"#{class_name}\\\" from \\\"#{full_path}\\\"\"\n</code></pre>\n\n<p>Use #inspect to do the quoting for you:</p>\n\n<pre><code>@logger.info \"Loading #{class_name.inspect} from #{full_path.inspect}\"\n</code></pre>\n\n<h2>Remove <em>eval</em></h2>\n\n<p>You don't need <em>eval</em> here:</p>\n\n<pre><code>unless eval(\"defined? #{class_name}\")\n</code></pre>\n\n<p>instead:</p>\n\n<pre><code>unless defined?(class_name)\n</code></pre>\n\n<h2>ancestors.include?</h2>\n\n<p>Instead of this:</p>\n\n<pre><code>if plugin_class.ancestors.include? Plugin\n</code></pre>\n\n<p>do this:</p>\n\n<pre><code>if plugin_class < Plugin\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/4545583/238886\">this SO answer</a>, and the rdoc for <a href=\"http://ruby-doc.org/core-2.1.1/Module.html#method-i-3C\" rel=\"nofollow noreferrer\">Module#<</a></p>\n\n<h2>instance_method</h2>\n\n<p>Instead of this:</p>\n\n<pre><code>if plugin_class.allocate.method(:initialize).arity > 0\n</code></pre>\n\n<p>this:</p>\n\n<pre><code>if plugin_class.instance_method(:initialize).arity > 0\n</code></pre>\n\n<p>This avoids the funny business of allocating one.</p>\n\n<h2>exceptions</h2>\n\n<p>The code wishes, when a plugin cannot be added, to log it and continue\nadding more plugins. That works well, but the way it's done can be\nsimplified using exceptions.</p>\n\n<p>Instead of this:</p>\n\n<pre><code>plugins.each do |plugin|\n ...\n unless eval(\"defined? #{class_name}\")\n @logger.error \"Class \\\"#{class_name}\\\" not found!\"\n next\n end\n\n ...\nend\n</code></pre>\n\n<p>consider this:</p>\n\n<pre><code>class PluginError < StandardError ; end\n\n\nplugins.each do |plugin|\n begin\n ...\n unless eval(\"defined? #{class_name}\")\n raise PluginError, \"Class \\\"#{class_name}\\\" not found!\"\n end\n ...\n rescue PluginError => e\n @logger.error e.to_s\n end\nend\n</code></pre>\n\n<p>This gets rid of all of those \"next\" calls, simplifying the error handling.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-26T23:58:33.840",
"Id": "73983",
"Score": "0",
"body": "Thanks for all the help! I'll be working to improve this for some time :) A quick question, you say that instead of `if plugin_class.ancestors.include? Plugin`, use `if plugin_class.ancestors.include? Plugin`, which is exactly the same. I assume this is a mistake. What should I use instead of `if plugin_class.ancestors.include? Plugin`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T00:48:19.617",
"Id": "74003",
"Score": "0",
"body": "@jackwilsdon Oh dear! It's fixed now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T21:15:29.677",
"Id": "74127",
"Score": "0",
"body": "What exactly does `<` do, when referencing classes? Can you link me to the RDoc for this? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-27T22:23:15.097",
"Id": "74148",
"Score": "1",
"body": "@jackwilsdon Simply, \"<\" means that the class on the left is derived from, directly or indirectly, the class on the right. \"<=\" is the same, except that the class on the left may also be the same class as the one on the right. RDOC link added."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T19:05:58.513",
"Id": "39320",
"ParentId": "29998",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39320",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T16:49:30.767",
"Id": "29998",
"Score": "4",
"Tags": [
"optimization",
"ruby",
"classes",
"modules"
],
"Title": "Loading 'Plugins' in Ruby"
}
|
29998
|
<p>I'm a beginner in C# and am doing a simple programming exercise. I would like to put the <code>Item.price</code> and <code>Item.Name</code> into <code>Listbox2</code>.</p>
<p>Is it possible to put the array name into a variable and iterate with a <code>foreach</code> loop? This is to avoid a very long <code>if</code>, <code>switch</code>, or <code>while</code> loop. It could also be useful in the future if I have 40 lists.</p>
<p><strong>Example</strong> </p>
<pre><code>Array variable = Drinks;
foreach(Product item in variable)
{
listBox2.Items.Add(item.ProductName + item.Price);
}
</code></pre>
<p>PS: I've already tried using a temporary List, where I put the <code>Drinks</code> into the list and call it by <code>Product.Name</code> and/or <code>Product.price</code>.</p>
<p>Could it also be more efficient? I'm very open to new ideas or approaches on how I should make my code shorter and more efficient.</p>
<pre><code> public partial class Form1 : Form
{
List<Product> Drinks = new List<Product>() { new Product("Coca Cola", 1.2F), new Product("Fanta", 2.0F), new Product("Sprite", 1.5F) };
List<Product> Bread = new List<Product>() { new Product("Brown Bread", 1.2F), new Product("White Bread", 2.0F), new Product("Some otherBread", 1.5F) };
public Form1()
{
InitializeComponent();
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
// instead of 40 if loops or a while loop is it possible to change the List Name with a variable and use only 1 foreach loop as the example i showed above?
if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0)
{
foreach (Product item in Drinks)
{
listBox1.Items.Add(item.ProductName);
}
}
else
{
foreach (Product item in Bread)
{
listBox1.Items.Add(item.ProductName);
}
}
}
private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
// do something here
}
}
public class Product
{
private string productName;
private float price;
public Product(string productName, float price)
{
this.ProductName = productName;
this.Price = price;
}
public string ProductName
{
get { return productName; }
set { productName = value; }
}
public float Price
{
get { return price; }
set { price = value; }
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Is it possible to put the array name into a variable and iterate by a foreach loop?</p>\n</blockquote>\n\n<p><strong>YES.</strong> </p>\n\n<pre><code>Array ProductItems = Drinks.ToArray();\nforeach(Product item in ProductItems)\n {\n Console.WriteLine(item.ProductName);\n } \n</code></pre>\n\n<hr>\n\n<p>Now about your second question, (it's unclear what's the significance of the first question)...</p>\n\n<p>If there are many products and user selects one from the <code>combobox1</code> how to update the product details in <code>listbox1</code>? (is this your question?)</p>\n\n<p><strong>Answer</strong> : Make a <a href=\"http://www.dotnetperls.com/dictionary\" rel=\"nofollow noreferrer\">Dictionary</a> of <code>combobox1</code> index and <code>ProductList</code>. Iterate over the <code>combobox1</code> list and map the indexes with the <code>ProductList</code>. <a href=\"https://stackoverflow.com/questions/14695606/c-sharp-list-add-lists-to-dictionary\">This may help</a>.</p>\n\n<pre><code>Dictionary ProductDict = new Dictionary<int, List<Product>>(); \n</code></pre>\n\n<p>Then after <code>SelectedIndexChanged</code> event is fired get the <code>ProductList</code> corresponding with <code>combobox1</code> index. Then iterate over the list and add the details it in listbox.</p>\n\n<hr>\n\n<p><strong>General Review</strong></p>\n\n<p>Since <code>productName</code> and <code>price</code> is trivial make them <a href=\"http://msdn.microsoft.com/en-us/library/bb384054.aspx\" rel=\"nofollow noreferrer\">auto-implemented properties</a></p>\n\n<pre><code>public string ProductName { get; set; }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T22:22:15.460",
"Id": "47610",
"Score": "0",
"body": "Since both `Drinks` and `Bread` are `List<Product>`, there is no reason to use the non-generic `Array` here. Or to call `ToArray()`. (The fact that the original code does that is no excuse, I think code review should catch things like that too.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T20:06:19.683",
"Id": "30009",
"ParentId": "30000",
"Score": "1"
}
},
{
"body": "<p>What you are looking for is a variable that kan hold the reference to one of the lists, then you can loop through whatever that variable points to.</p>\n\n<p>You can use a <code>switch</code> to select which of the lists you are referring to. Example:</p>\n\n<pre><code>private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {\n\n listBox1.Items.Clear();\n\n List<Product> products;\n switch (comboBox1.Items.IndexOf(comboBox1.SelectedItem)) {\n case 0: products = Drinks; break;\n case 1: products = Meat; break;\n case 2: products = Cheeses; break;\n case 3: products = Sauces; break;\n default: products = Bread; break;\n }\n\n foreach (Product item in products) {\n listBox1.Items.Add(item.ProductName);\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T05:36:29.803",
"Id": "47620",
"Score": "0",
"body": "But OP states that he doesn't want a long switch-case statement which is true if there are like 100 items in the `combobox1` list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T06:42:41.163",
"Id": "47626",
"Score": "0",
"body": "@tintinmj: The OP has a switch with a loop for each case, which would be a very long switch with many cases, but assigning a reference in each case makes it a reasonably short switch even with many cases. It's not longer than populating a dictionary with the options for example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T22:51:34.257",
"Id": "30012",
"ParentId": "30000",
"Score": "0"
}
},
{
"body": "<p>You can add new abstraction, instead of using a bunch of lists. For example:</p>\n\n<pre><code>class Category\n{\n public string Name { get; private set; } //or other Id. Some Enum probably?\n\n public IList<Product> Products { get; private set; }\n\n public Category(string name)\n {\n Name = name;\n Products = new List<Products>();\n }\n\n public override string ToString()\n {\n return Name;\n }\n}\n</code></pre>\n\n<p>Then you can simply populate your <code>comboBox1</code> with <code>Category</code> objects, and handle selection event like this:</p>\n\n<pre><code> private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n {\n listBox1.Items.Clear();\n var category = (Category)comboBox1.SelectedItem;\n if (category == null) return;\n //cant you AddRange or assign? I'm not very familiar with winforms\n foreach (Product item in category.Products)\n {\n listBox1.Items.Add(item.ProductName);\n }\n }\n</code></pre>\n\n<p>As for your first question: you can override <code>ToString</code> method of your <code>Product</code> class to return Name+Price the same way it is done for <code>Category</code>. Then you can simply call <code>listBox1.Items.Add(item);</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T06:42:35.537",
"Id": "30017",
"ParentId": "30000",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T17:37:31.783",
"Id": "30000",
"Score": "1",
"Tags": [
"c#",
"array",
"beginner"
],
"Title": "Putting array name in variable and shortening code"
}
|
30000
|
<p>How could I make this code more efficient? Instead of using many <code>if</code>-statements, should I make a function, array, or <code>switch</code>? How would I do that?</p>
<pre><code><form method="post" action="trivia2.php">
<ol>
<li>How many days are in a week? <input type="text" name="daysweek"></li>
<li>How many days are in a year? <input type="text" name="daysyear"></li>
<li>How many weeks are in a year? <input type="text" name="weeksyear"></li>
<li>What color is the sky? <input type="text" name="colorsky"></li>
<li>what is us president name? <input type="text" name="presidentname"></li>
<li>How many sides does a triangle have? <input type="text" name="sidestriange"></li>
<li>What is the first element on the periodic table of elements? <input type="text" name="firstelement"></li>
<li>Bees create what sweet substance? <input type="text" name="beesubstance"></li>
<li>How many stripes are displayed on the American flag?<input type="text" name="stripes"></li>
</ol>
<input type="submit" value="Done!"/>
</form>
<?php
$daysweek=$_POST['daysweek'];
$daysyear=$_POST['daysyear'];
$weeksyear=$_POST['weeksyear'];
$colorsky=$_POST['colorsky'];
$presidentname=$_POST['presidentname'];
$sidestriangle=$_POST['sidestriange'];
$firstelement=$_POST['firstelement'];
$beesubstance=$_POST['beesubstance'];
$stripes=$_POST['stripes'];
$wrong=0;
if($daysweek==7){
echo "1. you got the right answer: $daysweek<br/>";
}else {
$wrong++;
echo "number 1 is wrong<br/>";}
if($daysyear==365){
echo "2. you got the right answer: $daysyear<br/>";
}else {
$wrong++;
echo "number 2 is wrong<br/>";}
if($weeksyear==52){
echo "3. you got the right answer: $weeksyear<br/>";
}else {
$wrong++;
echo "number 3 is wrong<br/>";}
if($colorsky=='blue'){
echo "4. you got the right answer: $colorsky<br/>";
}else {
$wrong++;
echo "number 4 is wrong<br/>";}
if($presidentname=='obama'){
echo "5. you got the right answer: $presidentname</br>";
}else {
$wrong++;
echo "number 5 is wrong<br/>";}
if($sidestriangle==3){
echo "6. you got the right answer: $sidestriangle</br>";
}else {
$wrong++;
echo "number 6 is wrong<br/>";}
if($firstelement=='hydrogen'){
echo "7. you got the right answer: $firstelement<br/>";
}else {
$wrong++;
echo "number 7 is wrong<br/>";}
if($beesubstance=='honey'){
echo "8. you got the right answer: $beesubstance<br/>";
}else {
$wrong++;
echo "number 8 is wrong<br/>";}
if($stripes==13){
echo "9. you got the right answer: $stripes<br/>";
}else {
$wrong++;
echo "number 9 is wrong<br/>";}
echo "<h3>You have $wrong wrong answers</h3>";
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T02:19:06.340",
"Id": "47613",
"Score": "0",
"body": "Security should be a far greater concern here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T04:11:10.233",
"Id": "47616",
"Score": "0",
"body": "The answer to #2 is incorrect on leap years, but I digress."
}
] |
[
{
"body": "<p>Theres nothing particularly unefficient about what you have, but there are a couple of things. instead of storing the variables like</p>\n\n<pre><code>$daysweek=$_POST['daysweek'];\n</code></pre>\n\n<p>just leave them in <code>$_POST</code> like </p>\n\n<pre><code>if($_POST['daysweek']==7){//..\n</code></pre>\n\n<p>and then instead of </p>\n\n<pre><code>echo \"1. you got the right answer: $daysweek<br/>\";\n</code></pre>\n\n<p>you already know the answer is 7 so just</p>\n\n<pre><code>echo \"1. you got the right answer: 7<br/>\";\n</code></pre>\n\n<p>but based on the content of your application you are not yet in a place where you need to be worrying about optimization</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T03:48:20.207",
"Id": "47596",
"Score": "1",
"body": "I think what Seth gave is nearly as far as it gets to save some resources, on the other hand it is a bad habit to use a variable if you are not 100% sure if it exists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T03:51:10.110",
"Id": "47597",
"Score": "0",
"body": "if `$_POST['daysweek']` does not exist, neither will `$daysweek=$_POST['daysweek']`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T03:28:10.613",
"Id": "30004",
"ParentId": "30003",
"Score": "1"
}
},
{
"body": "<p>How about this.. To add or remove answers, all you would have to do is change the <code>$answers</code> array making the code easy to maintain.</p>\n\n<pre><code>$answers = [\n \"daysweek\" => 365,\n \"daysyear\" => 365\n ];\n\n$answerNumber = 1;\n$wrong = 0;\n\nforeach($answers as $key => $value){\n\n if(checkAnswer($key)){\n echo \"$answerNumber. you got the right answer: $value<br/>\";\n\n } else {\n $wrong++;\n\n }\n\n $answerNumber++;\n\n}\n\nfunction checkAnswer($key){\n return $_POST[$key] == $answers[$key] ? TRUE : FALSE;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T04:15:30.010",
"Id": "47598",
"Score": "0",
"body": "can u please explain me this line:\nreturn $_POST[$key] == $answers[$key] ? TRUE : FALSE;\nwhat does ? True: FALSE mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T08:25:59.690",
"Id": "47599",
"Score": "0",
"body": "@HamDlink `? :` is a conditional operator more or like `if else`. This is same as writing `if($_POST[$key] == $answers[$key]) { echo \"TRUE\"; } else { echo \"FALSE\"; }` , the former one saves a lot of code writing but both serve the same purpose."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T04:12:38.820",
"Id": "47617",
"Score": "2",
"body": "Why not remove the `? TRUE : FALSE` completely? `==` returns a boolean anyway."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T03:35:39.337",
"Id": "30005",
"ParentId": "30003",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T03:22:31.120",
"Id": "30003",
"Score": "3",
"Tags": [
"php",
"quiz"
],
"Title": "Quiz form with random questions"
}
|
30003
|
<p>I am running a timer for updating some of my operations, such as buffers. But I also want ping to be added.</p>
<p>It is added, but I think it can be improved. This is because I think it's running on the GUI thread, which is not preferred as it will freeze the GUI if something goes wrong with it. I think such a thing has occurred, and I haven't been able to locate the problem until now.</p>
<p>But, I am not asking for the solution for that problem, as there are other stuff. I am basically asking for ways to improve this piece of code as it doesn't seem to be optimal in any way.</p>
<pre><code>private void timer1_Tick(object sender, EventArgs e)
{
try
{
if (waveProvider.BufferedDuration.Milliseconds > 40 && AudioDevices.SelectedItem.ToString() != "Wasapi Loopback")
{
waveProvider.ClearBuffer();
TimesBufferClear++;
}
currping.Text = "Current Buffer: " + waveProvider.BufferedDuration.Milliseconds.ToString() + " Clear: " + TimesBufferClear.ToString() + " Ping: " + pingSender.Send(otherPartyIP.Address).RoundtripTime.ToString() + " Buffer: " + SendStream.BufferMilliseconds;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "Timer");
}
}
</code></pre>
<p>As you can see, I have a label which contains all the things I want to update. It is fine, and I'd rather have one than many in this case.</p>
<p>But is this a good way to do it? It doesn't seem that good when I look at it; it's just a mess, even if it works.</p>
<p>Also, the <code>PingSender</code> is created and disposed of outside of the thread. I suppose that is better than just "using" it every timer run.</p>
<p>Are there any ideas of what can be done to improve it?</p>
|
[] |
[
{
"body": "<p>As it is not really much code, let us just focus on the <code>label part</code> and a little naming. </p>\n\n<blockquote>\n<pre><code>TimesBufferClear++;\n</code></pre>\n</blockquote>\n\n<p>If this is a variable, we should use <code>camelCase</code> casing for the name. If it is a property it follows the naming convention. </p>\n\n<blockquote>\n<pre><code>currping \n</code></pre>\n</blockquote>\n\n<p>Can be renamed to <code>currentPingStatus</code>, which is more meaningful. </p>\n\n<p>Now let us refactor the assignment to the <code>Text</code> property of this label: </p>\n\n<pre><code>String formatPattern = \"Current Buffer: {0} Clear: {1} Ping: {2} Buffer: {3}\";\n\ncurrentPingStatus.Text = String.Format(formatPattern,\n waveProvider.BufferedDuration.Milliseconds.ToString(),\n TimesBufferClear.ToString(),\n pingSender.Send(otherPartyIP.Address).RoundtripTime.ToString(),\n SendStream.BufferMilliseconds);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T07:46:40.813",
"Id": "60781",
"ParentId": "30013",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T23:49:49.747",
"Id": "30013",
"Score": "0",
"Tags": [
"c#",
"timer"
],
"Title": "Ping and write the status of a timer on a GUI thread"
}
|
30013
|
<p>I'm currently writing a <a href="https://github.com/sayonarauniverse/magic_server" rel="nofollow">pure ruby webserver</a>, and one of the things that I have to do is parse a HTTP request. The method I've pasted below takes a HTTP request, and puts it in a map keyed by the <a href="http://en.wikipedia.org/wiki/List_of_HTTP_header_fields" rel="nofollow">header field names</a>. </p>
<p>The biggest issue I faced while doing this was dealing with the lack of an <code>EOF</code> from the <code>TCPSocket</code> on requests with bodies (basically every <code>POST</code> request). This meant that I couldn't just keep doing <code>file.gets</code> until I reached the end of the file, because there was no end. What I ended up doing instead, was to create a <code>while true</code> loop that breaks when it finds <code>'\r\n'</code>, which are the last characters before the <code>Body</code>, then read the <code>Body</code> separately using the number I get from <code>Content-length</code>. </p>
<p>Is there a more elegant way in <code>ruby</code> to do this? I feel like it's unnecessary to use a infinite loop, but I can't think of anything else that would work. </p>
<pre><code> # Takes a HTTP request and parses it into a map that's keyed
# by the title of the heading and the heading itself.
# Request should always be a TCPSocket object.
def self.parse_http_request(request)
headers = {}
#get the first heading (first line)
headers['Heading'] = request.gets.gsub /^"|"$/, ''.chomp
method = headers['Heading'].split(' ')[0]
#parse the header
while true
#do inspect to get the escape characters as literals
#also remove quotes
line = request.gets.inspect.gsub /^"|"$/, ''
#if the line only contains a newline, then the body is about to start
break if line.eql? '\r\n'
label = line[0..line.index(':')-1]
#get rid of the escape characters
val = line[line.index(':')+1..line.length].tap{|val|val.slice!('\r\n')}.strip
headers[label] = val
end
#If it's a POST, then we need to get the body
if method.eql?('POST')
headers['Body'] = request.read(headers['Content-Length'].to_i)
end
return headers
end
</code></pre>
|
[] |
[
{
"body": "<p>I don't know if this is the best method to parse an HTTP request. You probably should have a look into one of the simpler ruby http servers out there to get some ideas. I do know though that you're doing some strange things here:</p>\n\n<pre><code>headers['Heading'] = request.gets.gsub /^\"|\"$/, ''.chomp\n</code></pre>\n\n<p>It looks like you're calling the #chomp method on <code>''</code> here, which doesn't make sense. You really should use parenthesis here:</p>\n\n<pre><code>headers['Heading'] = request.gets.gsub(/^\"|\"$/, '').chomp\n</code></pre>\n\n<p>But on the other hand I can't see what the gsub is doing here, you probably can just get rid of it.</p>\n\n<pre><code>method = headers['Heading'].split(' ')[0]\n</code></pre>\n\n<p>Probably nitpicking but you can make this easier (and a little faster) by using:</p>\n\n<pre><code>method = headers['Heading'][/[^ ]*/]\n</code></pre>\n\n<p>That translates to: get the substring till the first space character (so no need to create an array here).</p>\n\n<pre><code>line = request.gets.inspect.gsub /^\"|\"$/, ''\n</code></pre>\n\n<p>That is really strange, you don't need to \"inspect\" a string just to parse control characters. You can match control characters with double quoted strings (e.g. \"\\r\\n\"). </p>\n\n<pre><code>label = line[0..line.index(':')-1]\n\n#get rid of the escape characters\nval = line[line.index(':')+1..line.length].tap{|val|val.slice!('\\r\\n')}.strip\n</code></pre>\n\n<p>The ruby god weeps. You can make this much simpler (and more efficient) by using a regexp here:</p>\n\n<pre><code>line =~ /(.*?): (.*)/\nlabel = $1\nval = $2.strip\n</code></pre>\n\n<p>Modifying the stream inside #tap is bad style and the #strip removes surrounding whitespace like \"\\n\" and \"\\r\" anyway.</p>\n\n<p>For the loop you can do the most natural thing and just write the break condition in the while condition part:</p>\n\n<pre><code>while (line = request.gets) != \"\\r\\n\"\n ...\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-30T23:00:53.360",
"Id": "30539",
"ParentId": "30014",
"Score": "3"
}
},
{
"body": "<p>I know this is a bit dated, but I have been working on the same issue. I think the method that you are looking for is <code>request.readpartial</code>. You can see the docs <a href=\"http://ruby-doc.org/core-2.2.1/IO.html#method-i-readpartial\" rel=\"nofollow\">here</a>.</p>\n\n<p>This takes a <code>maxlen</code> of bytes as an argument. If you reach the end of the data from calling <code>IO.readpartial(maxlen)</code>, or hit the max length of bytes before the end of the incoming data on the <code>TCPSocket</code>, it will return the data. </p>\n\n<p>This can replace the <code>while true</code> and <code>\\r\\n</code> logic needed to find the end of the incoming data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-12T01:53:08.157",
"Id": "150852",
"Score": "0",
"body": "The check for `\\r\\n` is there to check the end of the header, not the end of the input stream. But readpartial might be necessary to read the whole body when no EOF is send."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-12T01:58:55.783",
"Id": "150853",
"Score": "0",
"body": "One Tip: If I were about to write a ruby webserver I would take a serious look into [Ragel](https://en.wikipedia.org/wiki/Ragel). That is a special DSL to write write a parsing state machine and it can be compiled to Ruby (and also to C if Perfomance becomes an issue). Zed Shaw used this for Mongrel and it was the most popular ruby webserver for a while."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-11T14:59:45.167",
"Id": "83849",
"ParentId": "30014",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T01:42:41.027",
"Id": "30014",
"Score": "5",
"Tags": [
"ruby",
"parsing",
"http"
],
"Title": "Parsing a HTTP request"
}
|
30014
|
<p>I've recently read <a href="http://aaditmshah.github.io/why-prototypal-inheritance-matters/" rel="nofollow">this article</a>, and I agree that the <code>new</code> keyword is not good practice.</p>
<p>Thus, I've made an improvement on <em>John Resig's Simple JavaScript Inheritance</em> in order to use the <code>Class.create</code> method instead of <code>new</code>:</p>
<pre><code>// The dummy class constructor
function Class() {
// I remove the initialization procedure in constructor function,
// Initialization will done by Class.create which I defined below
}
// Enforce the constructor to be what we expect
Class.prototype.constructor = Class;
// And make this class extendable
Class.extend = arguments.callee;
// What I improved
Class.create = function () {
var instance = new this();
if (instance.init) {
instance.init();
}
return instance;
}
</code></pre>
<p>The initialization case in his article could be rewritten like this:</p>
<pre><code>var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
}
});
var p = Person.create();
</code></pre>
<p>Have I done this well or not? Please help me check it.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T11:57:50.470",
"Id": "47640",
"Score": "1",
"body": "you are still using the 'new' keyword..."
}
] |
[
{
"body": "<ul>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments/callee#Why_was_arguments.callee_deprecated.3F\" rel=\"nofollow\"><code>arguments.callee</code> is deprecated</a> and suggest you actually avoid it.</p></li>\n<li><p>What you just did was hide the <code>new</code> inside <code>create()</code>. That's nothing new. In fact, libraries like jQuery do this. Calling <code>$()</code> is actually making a new jQuery object.</p>\n\n<pre><code>jQuery === $ === function (a,b){return new e.fn.init(a,b,h)}\n</code></pre></li>\n<li><p><code>new</code> isn't bad practice. It depends on the developer. JavaScript gives you that flexibility to do anything with it. I once considered it as a problem, but soon learned that there's a place for it. It's easy to use (and abuse) once you know how prototypal OOP works in JS.</p></li>\n<li><p>Additional complexity might be a hit in performance. I'd stick to the native way of doing things unless circumstances call for extreme measures. What's wrong with JS's way of doing inheritance?</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T14:52:45.737",
"Id": "30039",
"ParentId": "30018",
"Score": "0"
}
},
{
"body": "<p>If you really want to create your own inheritance pattern then John Resig's Simple Inheritance pattern is not a good candidate to build upon. The reason is because John Resig's code is <a href=\"http://jsperf.com/oop-benchmark/118\" rel=\"nofollow noreferrer\" title=\"JavaScript Object Oriented Libraries Benchmark · jsPerf\">very slow</a>. The reason it's so slow is because of the way <code>_super</code> is handled:</p>\n\n<pre><code>// Copy the properties over onto the new prototype\nfor (var name in prop) {\n // Check if we're overwriting an existing function\n prototype[name] = typeof prop[name] == \"function\" && \n typeof _super[name] == \"function\" && fnTest.test(prop[name]) ?\n (function(name, fn){\n return function() {\n var tmp = this._super;\n\n // Add a new ._super() method that is the same method\n // but on the super-class\n this._super = _super[name];\n\n // The method only need to be bound temporarily, so we\n // remove it when we're done executing\n var ret = fn.apply(this, arguments); \n this._super = tmp;\n\n return ret;\n };\n })(name, prop[name]) :\n prop[name];\n}\n</code></pre>\n\n<p>I'll try to explain what's happening in the above code:</p>\n\n<ol>\n<li>We loop through each property which we wish to copy onto the newly extended object.</li>\n<li>If the property is a function <strong>and</strong> it overrides another function of the same name <strong>and</strong> it needs to call the overridden function then <em>we replace it with a function which changes the value of <code>this._super</code> within the function to the overridden function for that particular function call</em>.</li>\n<li>Otherwise we simply copy the property as it is.</li>\n</ol>\n\n<p>This little indirection allows you to call overridden methods using <code>this._super</code>. However it also makes the code very slow. Hence I suggest you don't use John Resig's Simple JavaScript Inheritance.</p>\n\n<hr>\n\n<p>Since this is a code review site I'm also obliged to point out flaws in your code. The main problem with your code is in the <code>Class.create</code> function:</p>\n\n<pre><code>Class.create = function () {\n var instance = new this();\n if (instance.init) {\n instance.init();\n }\n return instance;\n};\n</code></pre>\n\n<p>Compare that with John Resig's original dummy class constructor:</p>\n\n<pre><code>// The dummy class constructor\nfunction Class() {\n // All construction is actually done in the init method\n if ( !initializing && this.init )\n this.init.apply(this, arguments);\n}\n</code></pre>\n\n<p>The problem is that any argument applied to <code>Class.create</code> is lost. You need to <code>apply</code> the <code>arguments</code> passed to <code>Class.create</code> to <code>instance.init</code> as follows:</p>\n\n<pre><code>Class.create = function () {\n var instance = new this;\n if (instance.init) instance.init.apply(instance, arguments);\n return instance;\n};\n</code></pre>\n\n<p>Beside that there's not much more scope for improvement if you plan to stick to John Resig's Simple Inheritance Pattern.</p>\n\n<hr>\n\n<p>If you really want to create your own inheritance pattern in JavaScript then it pays to invest some time learning about how inheritance works in JavaScript. For example the following answer explains prototype-class isomorphism in JavaScript: <a href=\"https://stackoverflow.com/a/17893663/783743\">https://stackoverflow.com/a/17893663/783743</a></p>\n\n<p>Prototype-class isomorphism simply means that prototypes can be used to model classes. Armed with this knowledge we can write a function which takes an object (a prototype) and returns a class (a constructor function):</p>\n\n<pre><code>function CLASS(prototype) {\n var constructor = prototype.constructor;\n constructor.prototype = prototype;\n return constructor;\n}\n</code></pre>\n\n<p>Using the above function we may now create and instantiate classes as follows:</p>\n\n<pre><code>var Person = CLASS({\n constructor: function (isDancing) {\n this.dancing = isDancing;\n },\n dance: function () {\n return this.dancing;\n }\n});\n\nvar p = new Person(true);\n</code></pre>\n\n<p>Although this pattern does not have inheritance yet it is a good base to build upon. With a little bit of modification we can make it behave the way we want it to. There are a few important points to note:</p>\n\n<ol>\n<li>We want to be able to use the <code>extend</code> and <code>create</code> functions on any function. Hence it's better to add them to <code>Function.prototype</code> instead of creating a separate <code>Class</code> constructor.</li>\n<li>For a function <code>F</code> it need not be true that <code>F.prototype.constructor === F</code>. Hence we may use <code>F</code> for extending and <code>F.prototype.constructor</code> for creating.</li>\n<li>Instead of passing a prototype to <code>extend</code> it makes much more sense to pass a <a href=\"http://aaditmshah.github.io/why-prototypal-inheritance-matters/#blueprints_for_mixins\" rel=\"nofollow noreferrer\">blueprint of a prototype</a> instead. This makes looping over the prototype unnecessary.</li>\n</ol>\n\n<p>Taking advantage of the above mentioned points we can implement <code>extend</code> and <code>create</code> as follows:</p>\n\n<pre><code>Function.prototype.extend = function (body) {\n var constructor = function () {};\n var prototype = constructor.prototype = new this;\n body.call(prototype, this.prototype);\n return constructor;\n};\n\nFunction.prototype.create = function () {\n var instance = new this;\n instance.constructor.apply(instance, arguments);\n return instance;\n};\n</code></pre>\n\n<p>That's all. Using two simple functions we may now create classes as follows:</p>\n\n<pre><code>var Person = Object.extend(function () {\n this.constructor = function (isDancing) {\n this.dancing = isDancing;\n };\n\n this.dance = function () {\n return this.dancing;\n };\n});\n\nvar Ninja = Person.extend(function (base) {\n this.constructor = function () {\n base.constructor.call(this, false);\n };\n\n this.swingSword = function () {\n return true;\n };\n});\n</code></pre>\n\n<p>To create an instance of the class we use <code>create</code> as follows:</p>\n\n<pre><code>var p = Person.create(true);\np.dance(); // => true\n\nvar n = Ninja.create();\nn.dance(); // => false\nn.swingSword(); // => true\n\n// Should all be true\np instanceof Person && p instanceof Object &&\nn instanceof Ninja && n instanceof Person && n instanceof Object\n</code></pre>\n\n<p>This code is similar to my very own <a href=\"https://github.com/javascript/augment\" rel=\"nofollow noreferrer\"><code>augment</code></a> function. However <code>augment</code> makes use of <code>new</code> instead of <code>create</code>. Because of the way JavaScript works, using <code>new</code> is the fastest way to create an instance which is why <code>augment</code> doesn't have <code>create</code>. Nevertheless if you want it, a functional version of <code>new</code> can be easily implemented as follows:</p>\n\n<pre><code>function Factory(constructor, args) {\n return constructor.apply(this, args);\n}\n\nFunction.prototype.new = function () {\n Factory.prototype = this.prototype;\n return new Factory(constructor, args);\n};\n</code></pre>\n\n<p>For more information read the <a href=\"https://stackoverflow.com/a/17345713/783743\">following answer</a> on StackOverflow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T13:41:32.643",
"Id": "30077",
"ParentId": "30018",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "30077",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T07:07:12.603",
"Id": "30018",
"Score": "4",
"Tags": [
"javascript",
"inheritance"
],
"Title": "Improving on John Resig's Simple JavaScript Inheritance: avoiding `new`"
}
|
30018
|
<p>I've answered the following question as best as I could, but I need some help with my design and am wondering if I've taken the correct approach. I would appreciate it if anyone could please point out any mistakes I've made and any improvements I could make.</p>
<p>Question:</p>
<p>Please implement an address book that allows a user to store (between successive runs of the program) the name and phone numbers of their friends, with the following functionality:</p>
<ul>
<li>To be able to display the list of friends and their corresponding phone numbers sorted by their name</li>
<li>Given another address book that may or may not contain the same friends, display the list of friends that are unique to each address book (the union of all the relative complements).</li>
</ul>
<p>For example given:</p>
<pre><code>Book1 = { "Bob", "Mary", "Jane" }
Book2 = { "Mary", "John", "Jane" }
</code></pre>
<p>The friends that are unique to each address book is:</p>
<pre><code>Book1 \ Book2 = { "Bob", "John" }
</code></pre>
<p>It is important to provide a solution that highlights your skills in these areas.</p>
<ul>
<li>It is also important that your solution highlights your knowledge of
and approach to Agile software development.</li>
<li>The simplest solution is often the best. It is recommended that no
more than 4 – 8 hours is spent on the problem, as a sufficient
working program can be achieved in that time period.</li>
<li>The application must run and be easy to build from source. It also
must be easy to execute for us to determine if the application meets
the above requirements.</li>
</ul>
<p><strong>Contact Class</strong></p>
<pre><code>import java.io.Serializable;
import java.util.Comparator;
public class Contact implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String primaryPhoneNumber;
public Contact(String name, String primaryPhoneNumber) {
this.name = name;
this.primaryPhoneNumber = primaryPhoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrimaryPhoneNumber() {
return primaryPhoneNumber;
}
public void setPrimaryPhoneNumber(String primaryPhoneNumber) {
this.primaryPhoneNumber = primaryPhoneNumber;
}
public String toString() {
return name + ", " + primaryPhoneNumber;
}
public boolean equals(Object obj) {
if (obj instanceof Contact) {
Contact contact = (Contact) obj;
return (name.equals(contact.getName()) && primaryPhoneNumber
.equals(contact.getPrimaryPhoneNumber()));
}
return false;
}
public int hashCode() {
return (name.length() + primaryPhoneNumber.length());
}
}
class ContactNameComparator implements Comparator<Contact> {
public int compare(Contact contact1, Contact contact2) {
return contact1.getName().compareToIgnoreCase(contact2.getName());
}
}
</code></pre>
<p><strong>Address Book Class</strong></p>
<pre><code>import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class AddressBook implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private List<Contact> contacts;
public AddressBook(String name) {
this(name, new ArrayList<Contact>());
}
public AddressBook(String name, List<Contact> contacts) {
this.name = name;
this.contacts = contacts;
}
public void addContact(Contact contact) {
if (contacts != null) {
contacts.add(contact);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
public boolean equals(Object obj) {
if (obj instanceof AddressBook) {
AddressBook addressBook = (AddressBook) obj;
return name.equals(addressBook.getName());
}
return false;
}
public int hashCode() {
return (name.length());
}
public static Set<Contact> getUniqueContacts(List<AddressBook> addressBooks) {
Set<Contact> commonContacts = new HashSet<Contact>();
Set<Contact> uniqueContacts = new HashSet<Contact>();
for (AddressBook addressBook : addressBooks) {
List<Contact> contacts = addressBook.getContacts();
List<Contact> allContacts = new ArrayList<Contact>();
allContacts.addAll(uniqueContacts);
allContacts.addAll(contacts);
contacts.retainAll(uniqueContacts);
commonContacts.addAll(contacts);
allContacts.removeAll(commonContacts);
// set new uinque contacts
uniqueContacts.clear();
uniqueContacts.addAll(allContacts);
}
return uniqueContacts;
}
}
</code></pre>
<p><strong>AddressBookPersist Class</strong></p>
<pre><code>import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
public class AddressBookPersist {
private List<AddressBook> addressBooks;
public AddressBookPersist() {
addressBooks = new ArrayList<AddressBook>();
addressBooks = readAddressBooks(); // reads from previous runs
}
public void addAddressBook(AddressBook addressbook) {
if(!addressBooks.contains(addressbook)){
addressBooks.add(addressbook);
storeAddressBooks(addressBooks);
}
}
public void removeAddressBook(AddressBook addressbook) {
if(addressBooks.contains(addressbook)){
addressBooks.remove(addressbook);
storeAddressBooks(addressBooks);
}
}
public List<AddressBook> getAddressBooks() {
return addressBooks;
}
public void setAddressBooks(List<AddressBook> addressBooks) {
this.addressBooks = addressBooks;
storeAddressBooks(addressBooks);
}
public void removeAllAddressBooks(){
addressBooks.clear();
storeAddressBooks(addressBooks);
}
public void storeAddressBooks(List<AddressBook> addressBooks) {
try {
FileOutputStream fos = new FileOutputStream("AddressBooks.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(addressBooks);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public List<AddressBook> readAddressBooks() {
List<AddressBook> addressBooks = new ArrayList<AddressBook>();
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"AddressBooks.txt"));
if(ois.readObject() != null){
addressBooks = (List<AddressBook>) ois.readObject();
}
ois.close();
} catch (EOFException ex) {
System.out.println("");
}catch (FileNotFoundException ex) {
System.out.println("No address books stored");
} catch (Exception e) {
e.printStackTrace();
}
return addressBooks;
}
}
</code></pre>
<p><strong>AddressBookTest Class</strong></p>
<pre><code>import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
public class AddressBookTest {
private Contact c1, c2, c3, c4, c5, c6, c7;
private AddressBookPersist addressBookPersist;
@Before
public void setUp() {
addressBookPersist = new AddressBookPersist();
createNewContacts();
}
public static void main(String[] args) {
AddressBookTest test = new AddressBookTest();
test.setUp();
test.sortFriendsByTheirNames();
test.uniqueFriendsFromTwoAddressBooks();
test.uniqueFriendsFromThreeAddressBooks();
}
@Test
public void uniqueFriendsFromTwoAddressBooks() {
System.out.println("========== Unique Friends from Two Address Books ==========");
addTwoAddressBooks();
List<AddressBook> addressBooks = addressBookPersist.getAddressBooks();
printInput(addressBooks);
// Get unique contacts from two AddressBooks
Set<Contact> uniqueContacts = AddressBook.getUniqueContacts(addressBooks);
printOutput(addressBooks, uniqueContacts);
// The unique contacts from these two address books should be c1 and c4
Set<Contact> expected = new HashSet<Contact>(Arrays.asList(c1, c4));
assertTrue(uniqueContacts.equals(expected));
}
@Test
public void uniqueFriendsFromThreeAddressBooks() {
System.out.println("========== Unique Friends from Three Address Books ==========");
addThreeAddressBooks();
List<AddressBook> addressBooks = addressBookPersist.getAddressBooks();
printInput(addressBooks);
// Get unique contacts from three AddressBooks
Set<Contact> uniqueContacts = AddressBook.getUniqueContacts(addressBooks);
printOutput(addressBooks, uniqueContacts);
// The unique contacts from three address books should be c1, c4 and c5, c6, c7
Set<Contact> expected = new HashSet<Contact>(Arrays.asList(c4, c5, c6, c7));
assertTrue(uniqueContacts.equals(expected));
}
@Test
public void sortFriendsByTheirNames() {
System.out.println("========== Display the list of friends sorted by their name ==========");
AddressBook addressBook = new AddressBook("ab1");
addressBook.addContact(c5);
addressBook.addContact(c1);
addressBook.addContact(c4);
addressBook.addContact(c2);
addressBook.addContact(c3);
System.out.println("==Input==");
System.out.println("Address Book: " + addressBook.getName());
System.out.println("Friends:");
for (Contact contact : addressBook.getContacts()) {
System.out.println(contact);
}
System.out.println();
Collections
.sort(addressBook.getContacts(), new ContactNameComparator());
System.out.println("==Output==");
System.out.println("Address Book: " + addressBook.getName());
System.out.println("Friends:");
for (Contact contact : addressBook.getContacts()) {
System.out.println(contact);
}
System.out.println("\n");
// Sorted list
assertTrue("Bob".equals(addressBook.getContacts().get(0).getName()));
assertTrue("Jane".equals(addressBook.getContacts().get(1).getName()));
assertTrue("John".equals(addressBook.getContacts().get(2).getName()));
assertTrue("Mary".equals(addressBook.getContacts().get(3).getName()));
assertTrue("Ruby".equals(addressBook.getContacts().get(4).getName()));
}
private void createNewContacts() {
c1 = new Contact("Bob", "02 9218 5479");
c2 = new Contact("Mary", "04 9218 5479");
c3 = new Contact("Jane", "02 9 605 3147");
c4 = new Contact("John", "02 605 3147");
c5 = new Contact("Ruby", "03 9 605 3147");
c6 = new Contact("Paul", "03 9 605 3147");
c7 = new Contact("Zee", "03 9 605 3147");
}
private void addTwoAddressBooks() {
addressBookPersist.removeAllAddressBooks();
AddressBook ab1 = new AddressBook("ab1");
AddressBook ab2 = new AddressBook("ab2");
// AddContacts to the addressBooks
ab1.addContact(c1);
ab1.addContact(c2);
ab1.addContact(c3);
ab2.addContact(c2);
ab2.addContact(c4);
ab2.addContact(c3);
addressBookPersist.addAddressBook(ab1);
addressBookPersist.addAddressBook(ab2);
}
private void addThreeAddressBooks() {
addressBookPersist.removeAllAddressBooks();
AddressBook ab1 = new AddressBook("ab1");
AddressBook ab2 = new AddressBook("ab2");
AddressBook ab3 = new AddressBook("ab3");
// AddContacts to the addressBooks
ab1.addContact(c1);
ab1.addContact(c2);
ab1.addContact(c3);
ab2.addContact(c2);
ab2.addContact(c4);
ab2.addContact(c3);
ab3.addContact(c1);
ab3.addContact(c5);
ab3.addContact(c6);
ab3.addContact(c7);
addressBookPersist.addAddressBook(ab1);
addressBookPersist.addAddressBook(ab2);
addressBookPersist.addAddressBook(ab3);
}
private void printInput(List<AddressBook> addressBooks){
System.out.println("==Input==");
for (AddressBook addressBook : addressBooks) {
System.out.println("Address Book: " + addressBook.getName());
System.out.println("Friends:");
for (Contact c : addressBook.getContacts()) {
System.out.println(c.getName());
}
System.out.println("");
}
}
private void printOutput(List<AddressBook> addressBooks,Set<Contact> uniqueContacts){
System.out.println("==Output==");
System.out.print("Address Books: ");
String names = "";
for (AddressBook addressBook : addressBooks) {
names += addressBook.getName() + ", ";
}
if (names.length() > 0) {
System.out.println(names.substring(0, names.lastIndexOf(",")));
}
for (Contact c : uniqueContacts) {
System.out.println(c.getName());
}
System.out.println("\n");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T08:58:11.057",
"Id": "292212",
"Score": "0",
"body": "What is \"Serializable\" used for in your case. Why do you need it?"
}
] |
[
{
"body": "<p>I would use a <code>Set<Contact></code> in the <code>AddressBook</code> class. This way there cannot be any duplicates. \nA AddressBook is more like a Set than a List. \nIf you want it sorted by name you can use a <code>TreeSet</code>.</p>\n\n<p>Union, intersection and difference can be implemented quite easy:</p>\n\n<pre><code>Set<Type> union = new HashSet<Type>(s1);\nunion.addAll(s2);\n\nSet<Type> intersection = new HashSet<Type>(s1);\nintersection.retainAll(s2);\n\nSet<Type> difference = new HashSet<Type>(s1);\ndifference.removeAll(s2);\n</code></pre>\n\n<p>You can use these to simplify your <code>getUniqueContacts(..)</code> method a lot.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T08:08:26.540",
"Id": "47629",
"Score": "0",
"body": "thx, thats a good one!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T09:42:40.947",
"Id": "47634",
"Score": "0",
"body": "How does my OO-Design look, can you see any room for improvement?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T10:08:21.920",
"Id": "47636",
"Score": "1",
"body": "Maybe I would `AddressBook extends Set`. This would allow me to use it as a Set with all its methods. You seams only to add the `name` filed to the `Set` functionality. But If you do not need/want the full ` Set` functionallity, hide the intern `Set` as you do it now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T23:29:12.633",
"Id": "47696",
"Score": "0",
"body": "thanks - any advice on the requirement of `(between successive runs of the program)`. I created a persist class, not sure if that was the right approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T08:37:57.380",
"Id": "292209",
"Score": "0",
"body": "I want to notice that the TreeSet-implementation violates the Liskov-Substitution-Principle. Furthermore It breaks the contract of the Set interface. Sets and order are not semantically compatible. As I would use a Set-Implementation too I would go with HashSet. But I would argue otherwise: Sure you can enforce uniqueness even if you try to add an object that is already present. But that is not the value. The value is the message to other developers that they get a collection with some assertions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T08:52:13.260",
"Id": "292211",
"Score": "0",
"body": "Implementing the Set-Interface may be applicable. But it is a burden mostly can omit."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T07:53:27.133",
"Id": "30021",
"ParentId": "30019",
"Score": "3"
}
},
{
"body": "<p>Just a few comments:</p>\n\n<ul>\n<li><p>Overall design is fine, you have separated the requirements and functions into a\ncorrect number of different objects with clear responsibilities, but keeping it simple without overengineering.</p></li>\n<li><p>Unit Test class: your main method should not reference the test methods. In fact you don't need a main method at all. You should use the Junit4 test runner. You can run like this: <code>java org.junit.runner.JUnitCore AddressBookTest</code>. This will guarantee to run all your test methods. Generally people are running their tests using Maven or the IDE, so really there is probably not much need to use the command line.</p></li>\n<li><p>For return values I prefer to use <code>Collection<T></code> generally so that client code does not rely on any specific implementation of the data structure. As the code evolves, if I see that client code needs a more specific collection type, then I refactor to return the more specific type. For example: <code>Collection<Contact> getUniqueContacts(List<AddressBook> addressBooks)</code>.</p></li>\n<li><p>Maybe it simplifies things to have <code>Contact implements Serializable, Comparable</code>, which should be easy since you already built a Comparator. </p></li>\n<li><p>I'm not sure I understand the code in <code>getUniqueContacts()</code>. Why not just this:</p>\n\n<pre><code>public static Set<Contact> getUniqueContacts(List<AddressBook> addressBooks) {\n Set<Contact> unique = new TreeSet<Contact>(); // TreeSet will sort by Contact\n for (AddressBook book : addressBooks) {\n unique.addAll(book);\n }\n return unique;\n}\n</code></pre></li>\n</ul>\n\n<p><strong>A FEW MORE COMMENTS</strong></p>\n\n<p>I thought of a couple additional basic points you might want to consider:</p>\n\n<ul>\n<li><p>add a <code>toString()</code> method to the Contact and Address book classes, which gives a nice String representation of the object. I find I use this more and more, both because it makes it easy to see things in the debugger, and also because it makes logging statements easy.</p></li>\n<li><p>Instead of <code>getUniqueContacts</code>, maybe a better method conceptually, is <code>AddressBook merge(List<AddressBook> addressBooks)</code>. Taking the point above, and this point, printing unique contacts would look like this:</p></li>\n</ul>\n\n<p>**</p>\n\n<pre><code>System.out.println(\"Merged address book=\\n\" + AddressBook.merge(addressBooksList));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T23:28:49.287",
"Id": "47695",
"Score": "0",
"body": "thanks - any advice on the requirement of `(between successive runs of the program)`. I created a persist class, not sure if that was the right approach."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T14:33:46.303",
"Id": "47737",
"Score": "1",
"body": "@JohnAdams: I liked your persist class - it's exactly what I would do for this. Serializing application state to disk is entirely adequate if you don't need share that data with other applications. Putting this into a database for example, would be over-engineering (not \"agile\"). I just noticed there is probably an error in the `readAddressBooks()` method because you are declaring a local variable called `addressBooks` which is hiding the class field of the same name. Based on how the rest of the code in that clThe `readAddressBooks()` should set the class member instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T08:48:17.883",
"Id": "292210",
"Score": "0",
"body": "Even if Serializable and Comparable seem to be benefical in one usecase I would separate the concerns. I never make domain objects Serializable. If I want to pass object beyond JVM system borders I create DTOs that take the burden of Serialization. I would also prefer Comparator over implementing Comparable. Maybe an object will be comparable under different aspects."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T14:56:40.750",
"Id": "30040",
"ParentId": "30019",
"Score": "5"
}
},
{
"body": "<h1>Serializable</h1>\n<p>Omit Serializable if you do not need it or separate this concern into DTOs</p>\n<h1>equals / hashcode</h1>\n<p>Do NOT override hascode and equals if you provide setters. Objects may not be accessable anymore if they were added to a hashcode using structure like the HashSet after you change a value If you usecase specifies to change values in your contact. You can easily see this in this simple example:</p>\n<pre><code>public static void main(String[] args) {\n \n Set<Contact> contacts = new HashSet<>();\n \n Contact contact = new Contact("name", "phone");\n \n contacts.add(contact);\n \n System.out.println(contacts.contains(contact)); // returns true\n\n contact.setName("changed name");\n \n System.out.println(contacts.contains(contact)); // returns false\n\n}\n</code></pre>\n<p>You should always let hashcode and equals methods rely on IMMUTABLE values. In complex environments you will have a hard time to identify such problems. I already faced such a problem in a serialization/deserialization process as not all objects were deserialized again.</p>\n<h1>Semantic of class "Contact"</h1>\n<p>That relates to the previous point. Either you do not provide setters for "name" and "phone" OR you should rely on other attributes. I suggest to NOT override equals and hashcode and externalize the equality check into a separate method or class.</p>\n<p>"Contact" in business application seems to be a "business object" or a "domain object". Overriding equals and hashcode using all available fields for evaluation will implicitly make an object to a "value object" with "immutable values". Every business object has its own identity NOT depending on attributes under change. They have a unique id. If you have consistency requirements like "unique name" you have to expernalize this check as a "constraint".</p>\n<p>Most developers go too fast with hashcode and equals. And if it applicable it is not used. This is because the decision when to rely on hashcode/equals mechanisms is very difficult.</p>\n<h1>Comparator</h1>\n<p>Separate the concern of comparing. Prefer Comparator over Comparable as you will be more flexible to add comparison aligorithms that compare your object under a different aspect.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-05T08:51:47.747",
"Id": "154485",
"ParentId": "30019",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "30040",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T07:23:46.217",
"Id": "30019",
"Score": "5",
"Tags": [
"java",
"serialization"
],
"Title": "Simple address book in Java"
}
|
30019
|
<p>This works fine but I find it quite big and had hoped there was a cleaner/smaller "toggle" function or alike which I could use but it seems to be related to visibility only - and I want to set a variable (for later usage).</p>
<p>Can this be optimized, if I want a toggle function which should be used to sort a column (and get the value into a variable)?</p>
<p><a href="http://jsfiddle.net/Psz5K/" rel="nofollow noreferrer">jsFiddle</a></p>
<pre><code><table>
<thead>
<tr>
<td>Col 1</td>
<td>Col 2</td>
<td>Col 3</td>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
<tr>
<td>B</td>
<td>C</td>
<td>A</td>
</tr>
</tbody>
</table>
</code></pre>
<p>And the jQuery stuff:</p>
<pre><code>var column;
var order;
$('thead th').click(function () {
// Get the current column clicked
var thisColumn = $(this).text();
// Check if the column has changed
if(thisColumn == column) {
// column has not changed
if(order == "ascending") {
order = "descending";
} else {
order = "ascending";
}
} else {
// column has changed
column = thisColumn;
order = "descending";
}
// Replace text in DIV
$("div").text("column=["+column+"], order=["+order+"]");
// future code will use the sort order to get database
// stuff with Ajax
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T17:20:24.943",
"Id": "47667",
"Score": "0",
"body": "You don't have any `th` elements in your HTML code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T08:39:32.807",
"Id": "47710",
"Score": "0",
"body": "@rink - good point but the `th` is in the Fiddle demo (I must have copied an old code snippet)."
}
] |
[
{
"body": "<p>Mostly I'ma java developer, but I think that there are a couple of things that you can do to tidy the code up.</p>\n\n<p>If you do not want to store state in the DOM then you can remove the jQuery data statements and store in the global scope. If I were a jQuery developer I would probably wrap this functionality into a plugin (sortable?) and then to call it on a table with the sortabletable calss use $('.sortableTable').sortable(). It would be more reusable, more encapsulated, and less likely to cause you weird behavior if you have two tables in your page!</p>\n\n<p>However here's my quick take on the above code:</p>\n\n<pre><code>var column;\n\n$('thead th').click(function () {\n\n // Get the current column clicked\n var thisColumn = $(this);\n\n if (thisColumn.is(column)) {\n var sort = column.data(\"sort\");\n var newSort = toggle(sort);\n column.data(\"sort\", newSort);\n } else {\n column = thisColumn;\n column.data(\"sort\", false);\n }\n // Replace text in DIV\n $(\"div\").text(\"column=[\" + column.text() + \"], order=[\" + column.data(\"sort\") + \"]\");\n\n});\n\nfunction toggle(current) {\n return !current;\n}\n</code></pre>\n\n<p>You could skip over setting an initial state and have toggle (and you Ajax code) work with <em>undefined</em> values properly (returning false).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T09:10:46.897",
"Id": "47711",
"Score": "0",
"body": "I will set your answer as the correct answer as I like your approach on the `toggle` function. But why use the `data(\"sort\",val)` approach instead of just setting a variable - what's the catch?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T09:12:19.670",
"Id": "47712",
"Score": "0",
"body": "BTW: I have updated your Fiddle demo here, [http://jsfiddle.net/Psz5K/4/](http://jsfiddle.net/Psz5K/4/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T10:28:59.313",
"Id": "47716",
"Score": "0",
"body": "Brief to fit in limits! Personally, no catch. Data call uses jQuery's managed storage helps prevent memory leaks. A great way for storing state and behavior against the related elements (maybe a progress bar?). Tracking a single variable(Object) (\"column\") you can track all important facets (\"sort\"). Less maintenance to be performed as code gets more complex, fewer errors likely to creep in. Complex plugins can store state within the objects themselves, a more proficient javascript developer can give approaches on that! Whether global, data, revealing module, look into namespacing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T10:54:17.407",
"Id": "47717",
"Score": "0",
"body": "How about then declaring `var column` as `var global` and a `global.data(\"column\",$(this))` - would this be any better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T11:21:41.297",
"Id": "47720",
"Score": "0",
"body": "I think that you shouldn't get hung up on the use of data and consider your question from the point of core javascript development. Take a look at namespacing (one popular syntax you could look for is var myNamespace = myNamespace || {};) Then look for tutorials on the (Revealing) Module Pattern which will help you with encapsulation and protecting your variables - whilst not polluting the global space. One of the joys of javascript is just how many ways you can achieve something, you will find a lot of opinions, many of them will disagree, many of them will be valid."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T14:20:16.413",
"Id": "30037",
"ParentId": "30020",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "30037",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T07:51:02.047",
"Id": "30020",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html5"
],
"Title": "jQuery toggle sort order and save to variable"
}
|
30020
|
<p>I have a piece of code that has a bit of a problem. Not that it doesn't work, though. The problem I am having is figuring out the optimal way of working with the MemoryStream, which I find quite difficult to do in this case.</p>
<pre><code>while (checkBox1.Checked && tt1.Connected)
{
tcpstream.Read(lenArray, 0, 4);
read = false;
Int32 length = BitConverter.ToInt32(lenArray, 0);
var tempBytes = new byte[length];
texturestream = new MemoryStream(tempBytes);
int currentPosition = 0;
while (currentPosition < length && checkBox1.Checked)
{
currentPosition += tcpstream.Read(tempBytes, currentPosition, length - currentPosition);
}
AutoReset.Set();
}
}
</code></pre>
<p>As you can see, I'm making the <code>texturestream</code> over and over again (which contains <code>tempBytes</code>).</p>
<p>From my perspective, I can't understand why I need to even have a byte array. Isn't it possible to just write to the MemoryStream immediately? And just have the MemoryStream made outside the loop with a Using, and then reuse the same thing over and over (as they are dynamic with their size)?</p>
<p>I have tried making this possible, but it doesn't work.</p>
<p>I was thinking something like this:</p>
<pre><code>tcpstream.read(texturestream.GetBuffer(),...,...)
</code></pre>
<p>I thought that would make it read to the MemoryStream instead of the byte array, which then goes into the MemoryStream.</p>
<p>But, it didn't work, so I am at a loss at what can be done with these loops.</p>
<p>Any ideas?</p>
<p>EDIT:</p>
<p>So if you check the first code, it´s a simply while loop, it´s reading 4 byte, then get´s the int data from that (BitConverter). </p>
<p>This is the Length of the TCP stream, which is why i remake it every loop, as i send the new length etc.</p>
<p>Then i take the tcpstream and set it into a bytearray, then write that array to the MemoryStream.</p>
<p>This isn´t what i would like to do however, i don´t really need a byte array in the first place. I however probably need a MemoryStream, though not totally sure, i may be able to work without one. It depends as i use 2 threads that works in parallel, so one is reading while the other receives and fill the memorystream.</p>
<p>So if i use only tcp stream, i think it would take longer time, as if the total operation would have to halt to complete it.</p>
<p>If i use a MemoryStream the tcpstream can continue to work, by getting the length and writing to a byte array etc, until it writes to the MemoryStream (when it reaches that, the other thread will already have read the data from it).</p>
<p>So here is the reading Thread:</p>
<pre><code>SharpDX.Windows.RenderLoop.Run(form, () =>
{
AutoReset.WaitOne();
if (read == true)
{
sprite.Begin(SharpDX.Direct3D9.SpriteFlags.None);
device.BeginScene();
texturestream.Position = 0;
try
{
using (tx = SharpDX.Direct3D9.Texture.FromStream(device, texturestream, -2, -2, 1, SharpDX.Direct3D9.Usage.None, SharpDX.Direct3D9.Format.X8R8G8B8, SharpDX.Direct3D9.Pool.Default, SharpDX.Direct3D9.Filter.None, SharpDX.Direct3D9.Filter.None, 0))
{
sprite.Draw(tx, new ColorBGRA(0xffffffff));
if (tx.GetLevelDescription(0).Width != form.Width || tx.GetLevelDescription(0).Height != form.Height)
{
wid = tx.GetLevelDescription(0).Width;
heg = tx.GetLevelDescription(0).Height;
if (heg * wid > 40000)
{
form.Height = heg;
form.Width = wid;
presentParams.BackBufferHeight = heg;
presentParams.BackBufferWidth = wid;
device.Reset(presentParams);
}
Console.WriteLine("Width:" + tx.GetLevelDescription(0).Width + " Height:" + tx.GetLevelDescription(0).Height);
}
}
}
catch (Exception ex)
{
//if (ex is SharpDX.SharpDXException)
MessageBox.Show(ex.Message, "Rendering");
}
sprite.End();
device.EndScene();
device.Present();
}
});
</code></pre>
<p>Sorry for the mess.</p>
<p>But here i have a rendering loop, and while not ideal, it does the work currently.
So, it only runt after the receiving thread has told it to(right after it has written to the MemoryStream). And i also have a Bool just for safety.</p>
<p>And then it does it´s device things, and finally reads the Texture from the MemoryStream.
And then, draws it.</p>
<p>So that´s basically what the MemoryStream is used for.
1 Threads writes, 1 Threads reads, pretty much like that.</p>
<p>Hope this is the information needed.</p>
<p>EDIT 2:</p>
<p>So here it is currently with, the MemoryStream outside the loop, and using write, and reset the position right before the write. So the MemoryStream will only be as big, as the biggest written data at one time.</p>
<pre><code> using (texturestream = new MemoryStream())
{
while (checkBox1.Checked && tt1.Connected)
{
tt1.GetStream().Read(lenArray, 0, 4);
read = false;
var length = BitConverter.ToInt32(lenArray, 0);
var tempBytes = new byte[length];
int currentPosition = 0;
while (currentPosition < length && checkBox1.Checked && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, (int)length - currentPosition);
}
texturestream.Position = 0;
texturestream.Write(tempBytes, 0, (int)length);
read = true;
AutoReset.Set();
}
}
</code></pre>
<p>But, i would like to prevent having to use a byte array as a "middle hand", can´t i write to the memorystream directly?</p>
<p>And, about this:</p>
<p>while (currentPosition < length && checkBox1.Checked && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, (int)length - currentPosition);
}</p>
<p>if i Don´t have " (int)length - currentPosition ", it won´t work.</p>
<p>I have tried using this:</p>
<p>tt1.GetStream().Read(tempBytes,0,(int)length);</p>
<p>And only that, without a while loop. And that doesn´t work, i think it can work one time or so. Not sure why it doesn´t work though, as it should work in my eyes.</p>
<p>I mean, i tell it to read the length of the data, so i see no reason for it to fail.
(The fail is System.OverflowException, Arithmetic Overflow).</p>
<p>EDIT 3:</p>
<p>Missed the first parts that you wrote.</p>
<p>I would gladly hear how you would embed the size, please tell.</p>
<p>And, CopyTo, is probably as you say, i think i tried it before sometime.
But i don´t get why i have to allocate a Byte Array, if i have a MemoryStream, i should be able to simple Stream the TCPStream into the MemoryStream (at least i think so).</p>
<p>I tried: <code>tt1.GetStream().CopyTo(texturestream);</code></p>
<p>And that didn´t work as i can´t tell when it´s supposed to stop (it reads on forever).</p>
<p>EDIT 3:</p>
<p>Okay as you said, the streams goes on Forever, i always sends new data, and always reads new data. So this is why embed the size at the first 4 byte.
If you know a better way of doing this, please tell.</p>
<p>And for the MemoryStream, am i suppose to use Write?
As i gess that´s the only way to write to the MemoryStream without remaking it.</p>
<p>Sadly, from my tests, this:</p>
<pre><code> while (currentPosition < length && checkBox1.Checked && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
}
texturestream.Position = 0;
texturestream.Write(tempBytes, 0, length);
</code></pre>
<p>Which has Using texturestream outside of the loop, is slower than:</p>
<pre><code> texturestream = new MemoryStream(tempBytes);
while (currentPosition < length && checkBox1.Checked && tt1.Connected)
{
currentPosition += tt1.GetStream().Read(tempBytes, currentPosition, length - currentPosition);
}
</code></pre>
<p>Though, here i can also have Using outside, so it will dispose of it after the while loop.</p>
<p>But i think it´s faster cause the tempBytes is linked to the MemoryStream, so writing to the tempBytes will write to the MemoryStream.</p>
<p>But i don´t understand this:</p>
<blockquote>
<p>Finally - if your application logic allows - then don't use
using(textureStream = new MemoryStream()).</p>
</blockquote>
<p>Why shouldn´t i use Using?
Using does exactly the same thing you mention, it disposes when i am done, which is when the loop ends.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-03T22:50:42.217",
"Id": "202032",
"Score": "0",
"body": "I'm voting to close this question as off-topic because it has become very convoluted, but shouldn't be reversed as the answer has already addressed the updates."
}
] |
[
{
"body": "<p><strong>Edit - rewrite my entire answer</strong></p>\n<p>First off, I kind of misunderstood the purpose of lenArray. I sort of get it now, although I don't fully understand why your app is designed like that. I would perhaps use other means of getting Length instead of embedding that value into the stream, but that is besides the point.</p>\n<p>Perhaps the true answer you are looking for then is - each stream has a <code>CopyTo()</code> method. So you can perhaps use that. This way you avoid having to create a seperate byte array. Although I think what you end up winning is simply code clarity (less lines of code), because the CopyTo method has to internaly do the exact same thing you are doing now. Allocate memory (byte array) for MemoryStream and write bytes into it.</p>\n<p>The documentation isn't very clear about it though. In that I can't be certain if it will copy the entire stream (with your 4 byte embedded length that you don't need to represent your texture) or as a MSDN comment suggests, it will only copy from the current stream position, in which case you could simply seek over the embedded length if you can't remove it to begin with. So you need to test that out yourself.</p>\n<p><strong>Other things worth mentioning</strong></p>\n<p>You can avoid having to constantly reallocate the MemoryStream in the loop. Move the declaration outside the loop, at the start of the loop call the <code>.Seek(0, SeekOrigin.Begin)</code> method. That way you can rewrite the internal MemoryStream data with the new data and don't incur the performance penalty of allocating and garbage collecting new objects. If your stream length changes based on the texture, then also call the <code>.SetLength()</code> method to make your MemoryStream of the correct size. For all of this to work your app logic must be sound, in that one thread doesn't read the MemoryStream wile another is rewriting it etc.</p>\n<p>Finally, looking at your original code example. You are wasting CPU cycles (unless the compiler is smart enough to otimize this) here:</p>\n<pre><code>currentPosition += tcpstream.Read(tempBytes, currentPosition, length - currentPosition);\n</code></pre>\n<p>Before this line you set <code>currentPosition = 0;</code>, which means you are effectively saying<br />\n<code>length - 0</code>, that is a pointless substraction.</p>\n<p><strong>Edit 2</strong></p>\n<p>With <code>length - currentPosition</code> - I stand corrected, I overlooked the while loop, sorry about that.</p>\n<blockquote>\n<p>I tried: tt1.GetStream().CopyTo(texturestream); And that didn´t work as i can´t tell when it´s supposed to stop (it reads on forever).</p>\n</blockquote>\n<p>It will continue on forever if your tcpStream never stops/closes. I'm thinking that is the case. That you are continually streaming textures with different sizes and it would be the only reason that I can currently think of, why you would embed the length in the stream (otherwise you could simply access <code>stream.Length</code> and use that)...</p>\n<blockquote>\n<p>From my perspective, I can't understand why I need to even have a byte array. Isn't it possible to just write to the MemoryStream immediately?</p>\n<p>But, i would like to prevent having to use a byte array as a "middle hand", can´t i write to the memorystream directly?</p>\n</blockquote>\n<p>In that case you don't quite understand how streams work. In order to work with a stream (Read or Write) you need finite things. A byte array is a fixed finite thing. A stream in of itself doesn't convey a finite construct, it's kind of an abstract concept. I'm struggling to think of a good analogy here...</p>\n<p>Suffice it to say, that there doesn't exist a write API/method for a stream that accepts another stream (apart from CopyTo). Thus your only option is to read into a byte array from the source stream and then write that byte array content to the destination stream. End of story.</p>\n<p>Finally - if your application logic allows - then don't use <code>using(textureStream = new MemoryStream())</code>. You are (if I understand correctly what your app is doing) constantly allocating in a loop new relatively short lived <code>MemoryStream</code> objects that will have to be garbage collected. Simply write <code>MemoryStream textureStream = new MemoryStream();</code> outside your loop. Seek to the beginning at each loop iteration, then rewrite the old information with new data from tcpStream (if necessary also call <code>textureStream.SetLength()</code>). Once your application closes or you stop showing your constant stream of textures, then call <code>textureStream.Dispose()</code>; This way you reuse your object and don't apply unnecessary memory pressure or waste CPU cycles.</p>\n<p><strong>Edit 3</strong></p>\n<blockquote>\n<p>Okay as you said, the streams goes on Forever, i always sends new data, and always reads new data. So this is why embed the size at the first 4 byte. If you know a better way of doing this, please tell.</p>\n</blockquote>\n<p>Most likely that is the best way to do it, unless you consider opening a different tcpStream for each texture.</p>\n<blockquote>\n<p>And for the MemoryStream, am i suppose to use Write? As i gess that´s the only way to write to the MemoryStream without remaking it.</p>\n</blockquote>\n<p>Apart from <code>CopyTo</code> and <code>WriteByte</code>, yes <code>Write</code> is the only construct to <strong>write</strong> to a <code>MemoryStream</code>. There are other means to get the same end result, if they apply, which is discussed next.</p>\n<blockquote>\n<p>Which has Using texturestream outside of the loop, is slower than:</p>\n</blockquote>\n<p>We'll the two pieces of code behave very differently. In your example, where you have <code>MemoryStream</code> outside of loop, this is happening:<br />\n<code>tcpStream</code> references memory X.<br />\n<code>tempBytes</code> references memory Y.<br />\n<code>new MemoryStream()</code> references memory Z;</p>\n<p>You are now doing 2 memory copies. One from X -> Y (<code>tcpStream.Read(tempBytes...)</code>), and then Y -> Z (<code>textureStream.Write(tempBytes...)</code>).</p>\n<p>Now consider your other example with <code>textureStream = new MemoryStream(tempBytes);</code> inside the loop. This statement effectively means, that the <code>new MemoryStream</code> references existing memory Y not Z. So you end up doing only one direct memory copy<br />\nX -> Y. As you read from <code>tcpStream</code> into <code>tempBytes</code>, the <code>textureStream</code> will already contain that information because it is <strong>based on</strong> <code>tempBytes</code>.</p>\n<p>That is why it is faster.</p>\n<blockquote>\n<p>But i think it´s faster cause the tempBytes is linked to the MemoryStream, so writing to the tempBytes will write to the MemoryStream.</p>\n</blockquote>\n<p>Just noticed this, so yes, you came to the same conclusion I was trying to make.</p>\n<blockquote>\n<p>Why shouldn´t i use Using? Using does exactly the same thing you mention, it disposes when i am done, which is when the loop ends.</p>\n</blockquote>\n<p>What is it with me and while loops today? Again completely overlooked that you don't go out of the outer while loop, which at first I thought you did, thus disposing the <code>textureStream</code>, then as you would re-enter you would have re-created it... Pardon me, ignore my previous statement about this subject.</p>\n<p><strong>Optimization</strong></p>\n<p><code>SharpDX.Direct3D9.Texture</code> has a method called <code>FromMemory()</code>, which takes a byte array as one of its argument. It would seem if that method is more apropriate in your scenario, because that way you can completely avoid using <code>textureStream</code>. Simply pass in <code>tempBytes</code> and job done (I assume).</p>\n<p><strong>Race condition</strong></p>\n<p>You use <code>read</code> as a thread synchronization mechanism, but you are not using any locking. That can lead to the following race condition (which might not effect your app or maybe it needs to work like that):</p>\n<p>After this code has taken place:</p>\n<pre><code>texturestream.Write(tempBytes, 0, (int)length);\nread = true;\nAutoReset.Set();\n</code></pre>\n<p>That same thread can go back to the beginning of the loop and set <code>read = false;</code> before the other thread has a chance to continue. Thus you will miss an entire texutre, because calling <code>AutoReset.Set();</code> doesn't mean that the other thread will start execution immediately. Or worse yet, the second thread can start, evaluate <code>if (read == true)</code> and go in, then pause. Now the first thread continues, reads half the bytes from <code>tcpStream</code> and writes it into <code>textureStream</code>, then pauses. As the second thread now continues it will get a garbeled <code>texutreStream</code>.</p>\n<p>A <code>System.Collections.Concurrent.ConcurrentQueue<T></code> might be a better fit in this case. You put stuff in from the <code>tcpStream</code> and the other thread checks if anything is queued, if so then displays that stuff.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T16:18:15.880",
"Id": "30042",
"ParentId": "30029",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30042",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T11:03:01.070",
"Id": "30029",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Can this be improved by working directly with the MemoryStream?"
}
|
30029
|
<p>I've written a text parser that extracts useful information from a given text. Texts are formatted different, so there are different specialized parsers. I've designed them so that they all must define the methods from the interface Parser.</p>
<pre><code>class Parser:
def parse(text):
raise NotImplementedError
def pre_validate(text):
raise NotImplementedError
def post_validate():
raise NotImplementedError
</code></pre>
<p>How can I force all subclasses of Parser to call pre_validate before running parse and post_validate after calling parse?</p>
<p>I could solve it like this, but I don't think it's very elegant to wrap methods like this:</p>
<pre><code>class Parser:
def parse(text):
self.pre_validate(text)
self._parse()
self.post_validate(text)
def _parse(text):
raise NotImplementedError
def pre_validate(text):
raise NotImplementedError
def post_validate():
raise NotImplementedError
</code></pre>
<p>Ideally I'd like to allow the subclasses to implement the method <code>parse</code> instead of <code>_parse</code>. What's the recommended way of solving this? Would it make sense to use a python decorator here?</p>
|
[] |
[
{
"body": "<p>You could achieve that like this:</p>\n\n<pre><code>class Parser:\n def __init__(self):\n self.parse = self._validated_parsing(self.parse)\n\n def parse(self, text):\n raise NotImplementedError\n\n def pre_validate(self, text):\n raise NotImplementedError\n\n def post_validate(self, text):\n raise NotImplementedError\n\n def _validated_parsing(self, parse_func):\n def parse_wrapper(text):\n self.pre_validate(text)\n parse_func(text)\n self.post_validate(text)\n return parse_wrapper\n\nclass ParserChild(Parser):\n def parse(self, text):\n print('parsing')\n\n def pre_validate(self, text):\n print('pre-validating')\n\n def post_validate(self, text):\n print('post-validating')\n\nParserChild().parse('spam')\n# pre-validating\n# parsing\n# post-validating\n</code></pre>\n\n<p>I recommend doing it with an extra method that is called from <code>parse</code> though, like the <code>_parse</code> method you wrote. It should not be called directly from outside, so it should be written with a leading underscore. You might want to want to call it something more explicit, such as (in lack of a better name) <code>_core_parse</code>.</p>\n\n<p>While we're at it, maybe <code>pre_validate</code> and <code>post_validate</code> should be preceded with an underscore too (depending on whether you want them to be called from outside the class).</p>\n\n<p>Instead of raising <code>NotImplementedError</code> in the base class, you should use <a href=\"http://docs.python.org/3/library/abc.html\" rel=\"nofollow\"><code>abc.ABCMeta</code></a> for an abstract base class. This is better for two reasons:</p>\n\n<ul>\n<li>You can't create a subclass that doesn't implement all abstract methods.</li>\n<li>It will work together properly with the <a href=\"http://docs.python.org/3/library/functions.html#super\" rel=\"nofollow\"><code>super</code></a> function which delegates calls to superclasses (base classes).</li>\n</ul>\n\n<p>So, I think I would implement the class like this:</p>\n\n<pre><code>import abc\n\nclass Parser(object):\n __metaclass__ = abc.ABCMeta\n\n def parse(self, text):\n self._pre_validate(text)\n self._core_parse(text)\n self._post_validate(text)\n\n @abc.abstractmethod\n def _pre_validate(self, text):\n pass\n\n @abc.abstractmethod\n def _core_parse(self, text):\n pass\n\n @abc.abstractmethod\n def _post_validate(self, text):\n pass\n\nclass ParserChild(Parser):\n def _core_parse(self, text):\n print('parsing')\n\n def _pre_validate(self, text):\n print('pre-validating')\n\n def _post_validate(self, text):\n print('post-validating')\n\nParserChild().parse('spamspam')\n# pre-validating\n# parsing\n# post-validating\n</code></pre>\n\n<p>(I'm assuming you use Python 3, but if you're using Python 2, you should let <code>Parser</code> inherit from <code>object</code>. In Python 3, this happens automatically.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T21:23:34.800",
"Id": "30051",
"ParentId": "30030",
"Score": "2"
}
},
{
"body": "<p>You could fix the issue by making parser a collection of callables, rather than a class with fixed methods. This would be handy for other aspects of this kind of parsing, so you could easily reuse pre-parsing and post-parsing functions that might be more similar than the parsing:</p>\n\n<pre><code>class ParseOperation(object):\n\n def __init__(self, pre_validator, parser, post_validator):\n self.pre_validator = pre_validator\n self.parser= parser\n self.post_validator= post_validator\n\n def parse(self, text):\n self.pre_validator(self, text)\n self.parser(self, text)\n self.post_validator(self, text)\n\nclass Validator(object):\n\n def validate(self, owner, text):\n print 'validating %s' % text\n\n def __call__(self, owner, text):\n self.validate(owner, text)\n\nclass Parser (object):\n def parse(self, owner, text):\n print 'parsing %s' % text\n\n def __call__(self, owner, text):\n self.parse(owner, text)\n</code></pre>\n\n<p>Instead of overriding methods, you subclass Parser and Validator to compose your parse operation. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T22:32:40.257",
"Id": "30105",
"ParentId": "30030",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30105",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T11:10:18.317",
"Id": "30030",
"Score": "1",
"Tags": [
"python",
"inheritance"
],
"Title": "Inheritance and forcing methods to be called inside another method"
}
|
30030
|
<p>Since Qt still does not support to set timeouts on <code>QNetworkRequest</code> objects, I wrote this little wrapper class:</p>
<pre><code>/**
Usage:
new QReplyTimeout(yourReply, msec);
When the timeout is reached the given reply is closed if still running
*/
class QReplyTimeout : public QObject {
Q_OBJECT
public:
QReplyTimeout(QNetworkReply* reply, const int timeout) : QObject(reply) {
Q_ASSERT(reply);
if (reply) {
QTimer::singleShot(timeout, this, SLOT(timeout()));
}
}
private slots:
void timeout() {
QNetworkReply* reply = static_cast<QNetworkReply*>(parent());
if (reply->isRunning()) {
reply->close();
}
}
};
</code></pre>
<p>You can use it in a very simple fire-and-forget manner:</p>
<pre><code>QNetworkAccessManager networkAccessManger;
QNetworkReply* reply = networkAccessManger.get(QNetworkRequest(QUrl("https://www.google.com")));
new QReplyTimeout(r, 100);
</code></pre>
<p>If the call to Google does not finish in 100ms, it is aborted. And since the <code>QReplyTimeout</code> class is parented to the <code>QNetworkReply</code>, it will be destroyed automatically.</p>
<p>Review the code for any pitfalls, memory leaks, invalid casts and if it's generally in a good style.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-05T11:13:44.323",
"Id": "195332",
"Score": "0",
"body": "class is quick and concise. I see no problems there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-23T12:30:27.610",
"Id": "316958",
"Score": "1",
"body": "I think this could only be used to shorten the timeout, not lengthen it. If you had a large file upload, I believe the internal Qt timeout would still trigger a `QNetworkReply.TimeoutError`"
}
] |
[
{
"body": "<p>Here are my thoughts:</p>\n\n<ol>\n<li><p>It's a simple class that allocates quite a few times on the heap. You could minimize the number of implicit allocations it does. The <code>QTimer::singleShot</code> creates a temporary <code>QObject</code> instance and allocates a bunch on the heap. You can avoid it by handling a single-shot timer explicitly using <code>timerEvent</code>. You also avoid the need to set up any connections that way. A <code>QObject</code> does about two allocations when the first connection is added to it.</p></li>\n<li><p>Use Qt-5 style connections, but that doesn't apply anymore in light of #1 above.</p></li>\n<li><p>Add a static helper method that uses this class to set a timeout on a network request. The fact that you need to allocate <code>ReplyTimeout</code> is an implementation detail of sorts that could be abstracted out that way.</p></li>\n<li><p>Check if the reply is running before you set a timeout on it. Perhaps it was an incorrect/impossible request at the moment it was submitted to the manager and it was immediately finished.</p></li>\n<li><p>You're not supposed to name your classes with a <code>Q</code> prefix. It's reserved for Qt.</p></li>\n</ol>\n\n<p>The code below is portable across Qt 4 and Qt 5:</p>\n\n<pre><code>class ReplyTimeout : public QObject {\n Q_OBJECT\n QBasicTimer m_timer;\npublic:\n ReplyTimeout(QNetworkReply* reply, const int timeout) : QObject(reply) {\n Q_ASSERT(reply);\n if (reply && reply->isRunning())\n m_timer.start(timeout, this);\n }\n static void set(QNetworkReply* reply, const int timeout) {\n new ReplyTimeout(reply, timeout);\n }\nprotected:\n void timerEvent(QTimerEvent * ev) {\n if (!m_timer.isActive() || ev->timerId() != m_timer.timerId())\n return;\n auto reply = static_cast<QNetworkReply*>(parent());\n if (reply->isRunning())\n reply->close();\n m_timer.stop();\n }\n};\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>QNetworkAccessManager networkAccessManger;\nQNetworkReply* reply = \n networkAccessManger.get(QNetworkRequest(QUrl(\"https://www.google.com\")));\nReplyTimeout::set(reply, 100);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-30T19:39:26.163",
"Id": "301989",
"Score": "2",
"body": "This looks great, but if the upload/download is large won't this timeout even though it's transmitting? Should you cancel/restart the timer when uploadProgress is received?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-11T13:35:30.090",
"Id": "382362",
"Score": "0",
"body": "@CaptRespect: I'd say that's outside the scope of responsibility of this class. It's the user's responsibility to specify a sensible timeout based on the knowledge about what exactly is being downloaded via the supplied `QNetworkReply`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-11T13:45:16.113",
"Id": "382367",
"Score": "0",
"body": "The `Q_OBJECT` macro is not required here and it hurts at least the compilation time (if not runtime weight of the object). Also, I would rename `timeout` to something like `timeoutMsec` so that it's immediately clear which units the timeout is in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-13T11:16:49.600",
"Id": "382703",
"Score": "0",
"body": "The `Q_OBJECT` macro is required on all `QObject`-derived classes. It is an implementation detail that it could be skipped on some classes, but it makes the classes thus \"improved\" not be `QObject`s in the Liskov Substitution Principle sense. E.g. all users of `QObject` expect that the metadata is correct and thus `qobject_cast` works. Skip `Q_OBJECT` and it's not true, thus you have a class that the compiler lets you use where a `QObject` can be used, but it's not really a `QObject` anymore. As for the timeout, it's Qt lingo for ms. If anything, I'd use `std::duration` instead."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2016-05-25T17:38:07.687",
"Id": "129300",
"ParentId": "30031",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T12:59:30.637",
"Id": "30031",
"Score": "11",
"Tags": [
"c++",
"networking",
"timeout",
"qt"
],
"Title": "QNetworkReply network reply timeout helper"
}
|
30031
|
<p>I wrote this jQuery code to animate the opacity (sort of Fadein) of certain elements on my page in consecutive order. It feels very inelegant, though. </p>
<pre><code>(function($) {
function animateFadin($delayedElement, delayTime) {
$delayedElement.delay(delayTime).animate({
opacity: 1
}, 700);
}
$(document).ready(function(){
animateFadin($('#zone-branding-wrapper'),100);
animateFadin($('#zone-menu-wrapper'),500);
animateFadin($('#zone-content-wrapper'),600);
$(".view-nodequeue-1 a[href]").delay(600).each(function(index) {
$(this).delay(200*index).animate({
opacity: 1
}, 100);
});
});
}) (jQuery);
</code></pre>
<p>Is there a way to reuse the named function <code>animateFadin</code> inside the <code>each</code>?</p>
|
[] |
[
{
"body": "<p>I think the best way of animation is CSS.\nI think the right way is <a href=\"http://www.w3schools.com/css3/css3_transitions.asp\" rel=\"nofollow\">css transitions</a> in your case. Try to add css modificators like <code>.show {opacity:1}</code> or <code>.hide {opacity:0}</code> to your CSS, then add css-transions (like <code>transition:opacity .1s;</code>) to styles of your elements. Use javascript to switch css-modificators of your elements by timers.</p>\n\n<p>In my opinion, CSS-animation uses less CPU and work much faster and retain the logic of views for CSS.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T19:31:17.130",
"Id": "47682",
"Score": "0",
"body": "Thx, I know. Maybe I can redo this in css en then use jquery as a fallback using modernizr, but I need support for older IE > http://caniuse.com/#feat=css-transitions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T09:34:47.350",
"Id": "47715",
"Score": "0",
"body": "In my opinion, best way for older browsers is a graceful degradation. If fadein or fadeout don't work in ie, this is not so bad. Only you decide how best to proceed in your case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T11:09:42.310",
"Id": "47718",
"Score": "0",
"body": "I agree, but this is quite 'mission critical' :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T18:25:30.030",
"Id": "30046",
"ParentId": "30044",
"Score": "2"
}
},
{
"body": "<p>You have written a simple plugin as it is (see:<a href=\"http://learn.jquery.com/plugins/basic-plugin-creation/\" rel=\"nofollow\">http://learn.jquery.com/plugins/basic-plugin-creation/</a>).</p>\n\n<p>Firstly I don't think I'd put the document ready stuff inside the plugin. Secondly you should remember that jQuery objects are always based on an array (non matched selectors being a zero length array), so you can always use and return the <code>.each</code> function. As a caveat to that, if you are performing the same task on all elements in the jQuery object (and there isn't data bound to them or any calculations that you need to do on a per object basis) you do not need to use <code>.each</code>.</p>\n\n<pre><code>(function( $ ) {\n\n $.fn.animateFadin= function(amount) {\n\n return this.each(function() {\n //this is now an individual element you can manipulate\n this.delay(amount).animate({\n opacity: 1\n }, 700);\n });\n\n };\n\n}( jQuery ));\n</code></pre>\n\n<p>Or in the simple case:</p>\n\n<pre><code>(function( $ ) {\n\n $.fn.animateFadin= function(amount) {\n\n return this.delay(amount).animate({\n opacity: 1\n }, 700);\n };\n\n}( jQuery ));\n</code></pre>\n\n<p>You can now call <code>$('#zone-menu-wrapper').animateFadin(500);</code> </p>\n\n<p>If you understand this then you should be able to use the `.each variant to achieve the delays in a marginally more tidy fashion. What you might want to think about adding though is a callback to the animate function if what you hope to achieve is one element animating after the other.</p>\n\n<p>To do that you would not use each but a simple recursion. Pseudo-code without error/bounds checking:</p>\n\n<pre><code>function chain(this, them) {\n If (!this) return;\n\n nextThis = them.pop();\n\n this.delay(whatever).animate({...}, 100, function() {\n chain(nextThis, them);\n });\n}\n</code></pre>\n\n<p>Call this from within the body of <strong>animateFadin</strong> with the head and [rest] of the jQuery object's object array. What would be nice is to write a plugin to which you pass a function (the action, in your case delay then animate) so that this is reusable behavior. Maybe it already exists?</p>\n\n<p>All code untested and written on my phone, which was harder than I thought! Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T11:14:07.563",
"Id": "47719",
"Score": "0",
"body": "Thx man! I'm going to try all of this tonight. You wrote this on your phone? I tried that the other day, and its quite nightmare-ish, especially the ( , { and ;. Good job though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T08:12:22.370",
"Id": "30066",
"ParentId": "30044",
"Score": "4"
}
},
{
"body": "<p>One thing that you should do is to remove this function:</p>\n\n<pre><code>$(document).ready(function(){\n</code></pre>\n\n<p>and move the code inside this to:</p>\n\n<pre><code>(function($) {\n</code></pre>\n\n<p>like:</p>\n\n<pre><code>(function($) {\n function animateFadin($delayedElement, delayTime) {\n $delayedElement.delay(delayTime).animate({\n opacity: 1\n }, 700);\n }\n\n animateFadin($('#zone-branding-wrapper'),100);\n animateFadin($('#zone-menu-wrapper'),500);\n animateFadin($('#zone-content-wrapper'),600);\n $(\".view-nodequeue-1 a[href]\").delay(600).each(function(index) {\n $(this).delay(200*index).animate({\n opacity: 1\n }, 100);\n });\n}) (jQuery);\n</code></pre>\n\n<blockquote>\n <p>Both are different representations of <code>document.ready()</code></p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T14:07:00.967",
"Id": "30079",
"ParentId": "30044",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T17:54:05.093",
"Id": "30044",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"animation"
],
"Title": "Animating the opacity of certain page elements"
}
|
30044
|
<p>I need to remove inline javascript for a given string. Examples:</p>
<p>If user typed: <code><img onload="something" /></code></p>
<p>I should need to convert into <code><img /></code></p>
<p>I created this PHP code and it works(apparently without issues):</p>
<p><a href="http://writecodeonline.com/php/" rel="nofollow">http://writecodeonline.com/php/</a></p>
<pre><code>function test_input($input){
//I have a list with all events but for this example I used two
$html_events = 'onload|onclick';
$pattern = "/(<[A-Z][A-Z0-9]*[^>]*)($html_events)([\s]*=[\s]*)('[^>]*'|\"[^>]*\")([^>]*>)/i";
$replacement = '$1$5';
while( preg_match($pattern, $input) ){
$input = preg_replace($pattern, $replacement, $input);
}
return htmlentities($input);
}
echo test_input('<img onload="alert(\'hello world\');" onclick="alert(\'hello world\');" />'). '<br />';
echo test_input('<img onload="alert(\'hello world\');"/>'). '<br />';
echo test_input('<div onload="alert(\'hello world\');" onclick="alert(\'hello world\');">hello buddies</div>'). '<br />';
</code></pre>
<p>I'm just looking for improvements or use cases that I did not supporting or that break my regex. I would appreciate if you tell me:</p>
<p>This: <code>test_input('something bad');</code> breaks your regex.</p>
<p>Or if found an improvement that in a benchmark demonstrate better performance I should be happy to apply it as long as it does not break use cases already supported.</p>
<p>Thank You!</p>
<p><strong>Update</strong>
I finally used <a href="http://htmlpurifier.org/" rel="nofollow">htmlpurifier</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T20:22:45.470",
"Id": "47684",
"Score": "0",
"body": "Dear lord, let us pray that Cthulhu doesn't get word of this. Regex _is not the tool for the job_! Parse the markup, iterate the nodes, and check the attributes. If an `onload` or `onlclick` attribute is found remove it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T20:30:13.657",
"Id": "47686",
"Score": "0",
"body": "I've added an answer that shows you how to parse, and remove any attribute you need removing..."
}
] |
[
{
"body": "<p>Parsing markup with regex is like building your house using lego... it's not the right tool for the job. HTML is not <em>a regular language</em>, therefore <em>regular</em> expressions don't cut the mustard. More than that: <a href=\"https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454\">You're actively working to bring the world as we know it to an end, which drives people insane</a><br/>\nWhat you need is a DOM parser, and as luck would have it, PHP has the <code>DOMDocument</code> object, which is just that:</p>\n\n<pre><code>$dom = new DOMDocument;\n$dom->loadHTML('<img onload=\"alert(\\'hello world\\');\" onclick=\"alert(\\'hello world\\');\" />');\n$nodes = $dom->getElementsByTagName('*');//just get all nodes, \n//$dom->getElementsByTagName('img'); would work, too\nforeach($nodes as $node)\n{\n if ($node->hasAttribute('onload'))\n {\n $node->removeAttribute('onload');\n }\n if ($node->hasAttribute('onclick'))\n {\n $node->removeAttribute('onclick');\n }\n}\necho $dom->saveHTML();//will include html, head, body tags and doctype\n</code></pre>\n\n<p>Tadaa... both <code>onload</code> and <code>onclick</code> have been removed from the markup, without the pain of writing a reliable and stable regex, that can deal with in-line JS... As an added bonus, this code will be far more maintainable (and expandable) in the future. I'd much prefer maintaining this code, than having to rework a regular expression somebody wrote a couple of months ago...</p>\n\n<p>If you want, you can echo only the tags you've changed, like so:</p>\n\n<pre><code>$changed = array();\n$attributesOfDeath = array('onload', 'onclick');\nforeach($nodes as $node)\n{\n $current = null;\n foreach($attributesOfDeath as $attr)\n {\n if ($node->hasAttribute($attr))\n {\n $node->removeAttribute($attr);\n $current = $node;\n }\n }\n if ($current)\n {\n $changed[] = $current;//add to changed array\n }\n}\n$changed = array_map(array($dom, 'saveXML'), $changed);\necho implode(PHP_EOL, $changed);\n</code></pre>\n\n<p>As Jan said, for maintainability it's best to use an array of <em>\"forbidden attributes\"</em>. That's what the <code>$attributesOfDeath</code> array is for. If you want to, later on, check for a third or fourth attribute, you can simply add that to the array, and nothing else in your code need change. It'll just keep on working as before.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T20:33:23.340",
"Id": "47688",
"Score": "0",
"body": "for the purposes of maintainability, you should put `onload` and `onclick` in a single array and iterate over it. Otherwise, I agree with the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T20:37:18.080",
"Id": "47689",
"Score": "0",
"body": "@JanDvorak: Not only that, though I did think about doing that in my code example: when using this code, it might be worth while using a class (assigning the `DOMDocument` instance to a property, so as to not create a new instance on each function call). Anyway, I've edited my answer, and now use an `$attributesOfDeath` array in my second example"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T20:29:39.407",
"Id": "30050",
"ParentId": "30045",
"Score": "5"
}
},
{
"body": "<h3>Regex to <a href=\"https://digitalfortress.tech/tricks/top-15-commonly-used-regex/\" rel=\"nofollow noreferrer\">Strip all Inline JS</a></h3>\n\n<p>You can use the following Regex to Strip off Inline JS</p>\n\n<pre><code>/\\bon\\w+=\\S+(?=.*>)/g\n</code></pre>\n\n<p><a href=\"https://www.regexpal.com/?fam=104055\" rel=\"nofollow noreferrer\">Demo</a>\n<a href=\"https://digitalfortress.tech/tricks/top-15-commonly-used-regex/\" rel=\"nofollow noreferrer\">Reference</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-05T11:06:56.947",
"Id": "197870",
"ParentId": "30045",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T17:58:47.520",
"Id": "30045",
"Score": "4",
"Tags": [
"php",
"regex"
],
"Title": "Regex to remove inline javascript from string"
}
|
30045
|
<p>I am trying to write my first script that checks users against a database (MySQL right now) and if they aren't in the database, registers them. I've tried my best to sanitize and validate the form data before setting variables to be used from it. I would love any constructive criticism or critiques on any aspect of my code. </p>
<p>Database schema:</p>
<blockquote>
<p>users(<strong>id</strong>, type, <em>username</em>, password, <em>email</em>, first_name, last_name, date_created)</p>
</blockquote>
<p><code>config.inc.php</code> </p>
<pre><code><?php
/**
* Title: config.inc.php
* Created by: M. David Kay III
* Contact: xxxxxxxxxx@gmail.com
* Created: August 19th, 2013
* Last modified: August 21th, 2013
*
* Configuration file does the following things:
* 1 - Defines systemwide settings so changing them is easier.
* 2 - Defines constants used by many other scripts
* 3 - Starts the session
* 4 - Defines homebrew Error handling
* 5 - Defines a redirection function.
*/
#########################
####### SETTINGS ########
$live = false; // variable used to dictate how errors are handled.
// also used for payment services to see if we're testing or using them.
$contact_email = 'xxxxxxxxx@gmail.com';
#########################
#########################
####### CONSTANTS #######
define('BASE_URI', '/home6/usr/public_html/mock/'); // constant variable of parent web root directory, to be changed upon deployment.
define('BASE_URL', 'www.projectstack.org/mock/'); // constant variable of web url, to be changed upon deployment.
define('MYSQL', BASE_URI. 'includes/mysql.inc.php'); // constant variable of mysql config include file, to be changed upon deployment.
#########################
session_start(); // starts the session, yay!
// since we are worried about logged in users, this starts the
// tracking process.
/* error handling function:
* $e_number = error type in numerical format
* $e_message = the error message itself stored as string
* $e_file = name of file in which error occurred
* $e_line = line the error occurred on
* $e_vars = an array of all variables in existence when error occurred.
*/
function my_error_handler($e_number, $e_message, $e_file, $e_line, $e_vars) {
global $live, $contact_email; // makes the live and contact_email variables global in scope.
$message = "An error occurred in script '$e_file' on line $e_line: \n$e_message\n";
// error message with a backtrace array(everything that happened up to that point)
$message .= "<pre>".print_r(debug_backtrace(),1)."</pre>\n";
//1 (or true) in print_r() makes function return value, instead of print it.
$message .= "<pre>".print_r($e_vars,1)."</pre>\n";
if(!$live){
echo '<div class="error">'.nl2br($message).'</div>'; // if site isnt live, display error in browser
} else {
error_log($message,1,$contact_email,'From:mdavidkay3@gmail.com'); // if site is live, email (1) error log to $contact_email
// second argument sets where the error_log goes.
//if site is live, this will show a generic error msg, if error isnt a notice
if($e_number != E_NOTICE){
echo '<div class="error">A system error occurrd. We apologize for the inconvenience.</div>';
}
} // end of $live IF-ELSE
return true;
} // end of my_error_handler() definition.
set_error_handler('my_error_handler'); // sets PHPs default error handler to my defined function
// function purpose: to create form inputs, test to see if theyve been previously filled in, and return errors on improper form submission
// function arguments: name given to element, type of element [text, password, textarea], and array of errors.
function create_form_input($name, $type, $errors) {
$value = false;
if(isset($_POST[$name])) $value = $_POST[$name]; // checks to see if name value was submitted, and if so, assigns it to $value.
if($value && get_magic_quotes_gpc()) $value = stripslashes($value); // strips extraneous slashes from $value, only if Magic Quotes is enabled.
//checking the input type:
if(($type=='text')||($type=='password')) {
echo '<input type="'.$type.'" name="'.$name.'" id="'.$name.'"'; // shell of the input element, with type, name, and id.
if($value) echo 'value="'.htmlspecialchars($value).'"'; // if value has already been submitted, cleans value of special characters and puts it back in form.
if(array_key_exists($name, $errors)) { // checks to see if there were any errors, and if so, will produce the proper error report from the error array
echo 'class="error" /><span class="error">'.$errors[$name].'</span>';
} else {
echo ' />';
}
} elseif($type=='textarea') { // checks to see if element was a textarea instead
if(array_key_exists($name, $errors)) echo '<span class="error">'.$errors[$name].'</span>'; // if there was an error in form submission, this will show error msg
echo "<textarea name='$name' id='$name' class='$name' rows=5 cols=75";
if(array_key_exists($name, $errors)) {
echo ' class="error">';
} else {
echo '>';
}
if($value) echo $value; // checks to see if there was data for textarea submitted, and if there was, redisplays it.
echo '</textarea>';
} //end of primary IF-ELSE
} //end of create_form_input()
</code></pre>
<p><code>mysql.inc.php</code> </p>
<pre><code><?php
/**
* Title: mysql.inc.php
* Created by: M. David Kay III
* Contact: xxxxxxxxxx@gmail.com
* Created: August 20th, 2013
* Last modified: August 20th, 2013
*
* MySQL connection Configuration file does the following things:
* 1 - Defines database connection constants
* 2- Creates the PDO database resource for connectivity used by scripts
* 3 - Defines a hash compare function for passwords.
*/
/*
* Setting up the connection to the database that many scripts will be using.
* Defines multiple information for database connection, user, pw, host, & db name.
*/
DEFINE('DB_USER','user'); // constant variable for database user, to be changed when going to deployment
DEFINE('DB_PASSWORD','pass'); // constant variable for database user password, to be changed when going to deployment
DEFINE('DB_HOST','localhost'); // constant variable for database host, to be changed when going to deployment
DEFINE('DB_NAME','database'); // constant variable for database name, to be changed when going to deployment
$dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8';
//we are implicilty selecting the utf8 charset for the database connection
$opt = array();
//optional parameters to be sent to the PDO object
//trying the database connection, if anything goes wrong, throw an Exception
//and alert the end User in a friendly way.
try {
if(!($dbc = new PDO($dsn, DB_USER, DB_PASSWORD))){ // Creates the $dbc variable object so we can
// have a connection to the database.
// uses PDO functions.
throw new Exception;
}
}
catch (PDOException $e) {
echo '<p>Could not connect to the database. Please contact the system administrator.</p>';
}
//function purpose: turn user-supplied pws into secure hashes to be passed to the DB and back
//function inputs: $password - the plain-text password entered into forms by the user.
function get_password_hash($password) {
return hash_hmac('sha256', $password, 'ivegotalovelybunchofcoconuts-NOTUSED', true);
//hash_hmac()'s 4 arguments: algorithm to use, data to be hashed, hash key, true = raw binary & false = hex characters
}
</code></pre>
<p><code>register.php</code> </p>
<pre><code><?php
/**
* Title: register.php
* Created by: M. David Kay III
* Contact: xxxxxxxxxxx@gmail.com
* Created: August 19th, 2013
* Last modified: August 21th, 2013
*
* Register script does the following things:
* 1 - Checks for submission by POST method
* 2 - Checks each of the form inputs against a REGEX & validation
* a - If valid input, trim & store in short variable names
* i - Create hash value of password to store in database.
* b - If invalid input, add error to error array.
* 3 - Check email and username against database
* a - If neither are dupes, add user into database
* b - If email or username are dupes, let user know
*/
require('./includes/config.inc.php');
require(MYSQL);
$reg_errors = array(); // creates a variable array to catch all the errors that could be generated.
//checks to see if the form had already been submitted.
if($_SERVER['REQUEST_METHOD']=='POST') {
//checks for a first name entry between 2-20 characters, case insensitive, allowing for a space, . , ' , or -.
//if no entry for first name, error msg added to error array.
if(preg_match('/^[A-Z\'.-]{2,20}$/i',$_POST['first_name']) && isset($_POST['first_name']) && is_string($_POST['first_name'])){
$fn = trim($_POST['first_name']);
} else {
$reg_errors['first_name'] = 'Please enter your first name!';
}
//checks for a last name entry between 2-40 characters, case insensitive, allowing for a space, . , ' , or -.
//if no entry for last name, error msg added to error array.
if(preg_match('/^[A-Z\'.-]{2,40}$/i',$_POST['last_name']) && isset($_POST['K=last_name']) && is_string($_POST['last_name'])){
$ln = trim($_POST['last_name']);
} else {
$reg_errors['last_name'] = 'Please enter your last name!';
}
//checks for a username entry between 5-30 characters, case insensitive, allowing for only numbers and letters.
//if no entry for username, error msg added to error array.
if(preg_match('/^[A-Z0-9]{5,30}$/i',$_POST['username']) && isset($_POST['username']) && is_string($_POST['username'])){
$u = trim($_POST['username']);
} else {
$reg_errors['username'] = 'Please enter a desired user name!';
}
//checks for an email entry that conforms to email address syntax
//if no entry for email, error msg added to error array.
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) && isset($_POST['email']) && is_string($_POST['email'])) {
$e = trim($_POST['email']);
} else {
$reg_errors['email'] = "Please enter a valid email address!";
}
//checks for a password entry that conforms to the requirements given on the form.
//if no entry for password, error msg added to error array.
//if the two passwords do not match, error msg added to error array.
if(preg_match('/^(\w*(?=\w*\d)(?=\w*[a-z])(?=\w*[A-Z])\w*){6,20}$/',$_POST['pass1']) && isset($_POST['pass1']) && is_string($_POST['pass1'])){
if($_POST['pass1']==$_POST['pass2']) {
$p = get_password_hash(trim($_POST['pass1']));
//hashes the password from plaintext for storage in database
} else {
$reg_errors['pass2'] = 'Your passwords did not match each other.';
}
} else {
$reg_errors['pass1'] = "Please enter a valid password!";
}
//if no errors are present in array, make sure email and username arent in DB yet.
if(empty($reg_errors)) {
//prepared statement for checking if email or username is already registered
try
{
$stmt = $dbc->prepare("SELECT email, username FROM `users` WHERE email = :email OR username = :username");
$stmt->bindParam(':email', $e); //email parameter
$stmt->bindParam(':username', $u); //username parameter
$stmt->setFetchMode(PDO::FETCH_NUM);
$stmt->execute();
$count = $stmt->rowCount();
}
catch(PDOException $e)
{
echo 'Couldnt query database. ' . $e->getMessage();
}
if($count==0) { // no dupes of email or user, so let's add them into the DB!
$stmt->closeCursor(); //frees the database connection for a new statement to go through
try {
$stmt = $dbc->prepare("INSERT INTO `users` (`id`,`type`,`username`,`email`,`pass`,`first_name`,`last_name`,`date_created`)
VALUES(NULL,'member',?,?,?,?,?,ADDDATE(NOW())");
$stmt->bindParam(1, $u);
$stmt->bindParam(2, $p);
$stmt->bindParam(3, $e);
$stmt->bindParam(4, $fn);
$stmt->bindParam(5, $ln);
$stmt->setFetchMode(PDO::FETCH_NUM);
$stmt->execute();
$rows = $stmt->fetchAll();
} catch (PDOException $e)
{
echo $e->getMessage();
}
//asks DB if a new row was created, and if so, thanks user for
//registration on the site & sends an email to their email.
//if query doesnt work, an error is triggered
if($rows==1) {
include('./includes/header.inc.php');
echo "<h3>Thanks!</h3><p>Thank you for registering! This is just
a mock up site at the time being, so your account isn't going
to do much right now. Eventually, there will be an Authorize.net
payment processing routine going on here.</p>";
$body = "Thanks for registering at PTRoster Mock Up. We greatly appreciate your interest in our services.\n\n";
mail($_POST['email'],'Registration Confirmation for PTRoster Mock',$body,'From:thisone@thatone.org');
include('./includes/footer.inc.php');
exit();
} else {
echo "<p>Something is going on, trying to figure it out.</p>";
}
} else {
trigger_error("You could not be registered due to a system error. We apologize for any inconvenience.");
}
} else { // both username and email might be already used in DB, and error msgs are generated for array.
if($rows==2) { // this checks to make sure both entries are dupes
$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
$reg_errors['username'] = 'This username has already been registered. Please try another.';
} else { //this checks to see which of the two (email or username) is already in DB if both arent dupes.
$row = $stmt->fetchAll();
if(($row[0] == $_POST['email']) && ($row[1] == $_POST['username'])) { //both match entries in DB
$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
$reg_errors['username'] = 'This username has already been registered with this email address. If you have forgotten your password, use the link to the right to have your password sent to you.';
} elseif($row[0]==$_POST['email']) { // email match
$reg_errors['email'] = 'This email address has already been registered. If you have forgotten your password, use the link to the right to have your password sent to you.';
} elseif($row[1]==$_POST['username']) { // username match
$reg_errors['username'] = 'This username has already been registered. Please try another one.';
}
} // end of $rows==2 ELSE
} // end of $rows == 0 IF
// end of empty($reg_errors) IF.
} else { // end of the main form submission conditional.
require('./includes/header.inc.php');
echo '<p>You did not fill out the form for registration. Please <a href="?page=join-now">go back</a> and fill out the form.</p>';
}
?><h3>Register</h3>
<form action="register.php" method="post" accept-charset="utf-8" style="padding-left:100px;">
<p><label for="first_name"><strong>First Name</strong></label><br/><?php create_form_input('first_name', 'text', $reg_errors); ?></p>
<p><label for="last_name"><strong>Last Name</strong></label><br/><?php create_form_input('last_name', 'text', $reg_errors); ?></p>
<p><label for="username"><strong>Desired Username</strong></label><br/><?php create_form_input('username', 'text', $reg_errors); ?><small>Only letters and numbers are allowed.</small></p>
<p><label for="email"><strong>Email Address</strong></label><br/><?php create_form_input('email', 'text', $reg_errors); ?></p>
<p><label for="pass1"><strong>Password</strong></label><br/><?php create_form_input('pass1', 'password', $reg_errors); ?><small>Must be between 6 and 20 characters long, with at least one lowercase letter, one uppercase letter, and one number.</small></p>
<p><label for="pass2"><strong>Confirm Password</strong></label><br/><?php create_form_input('pass2', 'password', $reg_errors); ?></p>
<input type="submit" name="submit_button" value="Next &rarr;" id="submit_button" class="formbutton" />
</form>
<?php
include('./includes/footer.inc.php');
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T23:02:42.050",
"Id": "47690",
"Score": "0",
"body": "Do you view your error logs when you run this? It may be worth it to define variables you first define in try-catch blocks to dummy values before you enter the try{}. After the first try statement in `if(empty($reg_errors))` the next try{} block where you call $stmt->closeCursor() could throw up in your logs if you caught PDOException in the previous block. And other variables like $count where you depend on them later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T04:55:59.490",
"Id": "47700",
"Score": "0",
"body": "@asafreedman I never knew that variables created in try-catch blocks were not in-scope for later use. Wow. Is there a clean way to make a PDO statement outside of try blocks, or rather just go ahead and treat each new try-catch block as it's own instantiation. Thank you for your comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T16:00:08.797",
"Id": "47750",
"Score": "0",
"body": "It's not that they're not in-scope for later. It's that there's a change they wont be. If you catch an exception all the code that comes after that line, in the same try-catch block, that threw it will not be ran. If you've defined a variable in a try-catch that you want later you could see some odd behavior. It might be easier to just check for null if you think you'll run up against that situation in PHP. A java compiler would tell you at compile time but we don't get that luxury with php."
}
] |
[
{
"body": "<p>Good job using the database library with parameterized statements.</p>\n\n<p>Your error messages need to be more detailed. For example, the user would not know what you consider to be a valid password.</p>\n\n<p>Your <code>register.php</code> is long. Consider breaking it up into functions.</p>\n\n<p>For error checking, try to consistently put the error-handling code right after the <code>if</code>.</p>\n\n<pre><code>if (OK != some_operation()) {\n // Handle error case\n} else {\n // Handle normal case\n}\n</code></pre>\n\n<p>One reason is that the error-handling code is usually shorter, so you can glance over it and get it out of the way. Also, the error-handling often involves bailing out early. Then, you can avoid nesting <code>if-else</code>s.</p>\n\n<pre><code>if (OK != some operation()) {\n return ERROR_CODE_1;\n}\nif (OK != another_operation()) {\n return ERROR_CODE_2;\n}\n...\n</code></pre>\n\n<p>Within the if-condition, it would make more sense to check</p>\n\n<pre><code>if (!(isset($var) && isstring($var) && fits_requirements($var))) {\n // Handle error\n}\n</code></pre>\n\n<p>than to check</p>\n\n<pre><code>if (!(fits_requirements($var) && isset($var) && isstring($var))) {\n // Handle error\n}\n</code></pre>\n\n<p>since the former can take advantage of the short-circuit behaviour of <code>&&</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T14:44:35.027",
"Id": "48068",
"Score": "0",
"body": "I never considered the logic behavior of my conditionals, thanks for pointing out a way to better \"arm\" them. I'll be breaking down the sanitizing and validation into separate functions. Thanks for the tips!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T06:10:27.657",
"Id": "30165",
"ParentId": "30053",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T22:15:02.603",
"Id": "30053",
"Score": "2",
"Tags": [
"php",
"security",
"php5"
],
"Title": "Trying out my first User Registration script"
}
|
30053
|
<p>Below is the code that I would like to refactor in order to avoid if-else statements in <code>cellForRowAtIndexPath</code> and <code>numberOfRowsInSection</code>.</p>
<p>Depending upon what user selects, section order and <code>numberOfSections</code> will differ each time. <code>numberOfRowsInSection</code> will also vary. </p>
<p>I do need it to keep track of each cell (<code>didSelectRowAtIndexPath</code>) and trigger appropriate methods. Since I'm limited to the number of characters here, I have posted the entire .m on [GitHub][1].</p>
<pre><code> - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//+2 for Recipient & Transport
NSInteger numberOfSections = (planDate.numberOfCells +3);
return numberOfSections;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0)
{
planDate.sectionZeroLabel = @"Recipient";
return 1;
}
else if (section == 1)
{
planDate.sectionOneLabel = @"Let's Meet at:";
return 3;
}
// +2 instead of 3 is to account for -1 (section 0)
else if (section == (planDate.numberOfCells+2))
{
NSInteger transportCells;
transportCells = 0;
planDate.sectionTransportationLabel = transportationSection;
lastSection = transportationSection;
if (planDate.pickupSelectedCell != NULL)
{
transportCells = transportCells +1;
}
if ((planDate.pickUpOwnSuggestion != NULL) && (![planDate.pickUpOwnSuggestion isEqual: @""]))
{
transportCells = transportCells +1;
}
if (planDate.dropOffSelectedCell != NULL)
{
transportCells = transportCells +1;
}
if ((planDate.dropOffOwnSuggestion != NULL) && (![planDate.dropOffOwnSuggestion isEqual: @""]))
{
transportCells = transportCells +1;
}
return transportCells;
}
else if (section == 2)
{
if ([planDate.sceneFour isEqual: @"pdCoffeeDrinks"])
{
planDate.sectionTwoLabel = coffeeDrinkSection;
sectionTwo = coffeeDrinkSection;
return 2;
}
else if ([planDate.sceneFour isEqual: @"pdLunch"])
{
planDate.sectionTwoLabel = lunchSection;
sectionTwo = lunchSection;
return 2;
}
else if ([planDate.sceneFour isEqual: @"pdDinner"])
{
planDate.sectionTwoLabel = dinnerSection;
sectionTwo = dinnerSection;
return 2;
}
else if ([planDate.sceneFour isEqual: @"pdMovies"])
{
planDate.sectionTwoLabel = movieSection;
sectionTwo = movieSection;
return 3;
}
else if ([planDate.sceneFour isEqual: @"pdActivity1"])
{
planDate.sectionTwoLabel = activity1Section;
sectionTwo = activity1Section;
if (planDate.activity1CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneFour isEqual: @"pdActivity2"])
{
planDate.sectionTwoLabel = activity2Section;
sectionTwo = activity2Section;
if (planDate.activity2CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneFour isEqual: @"pdActivity3"])
{
planDate.sectionTwoLabel = activity3Section;
sectionTwo = activity3Section;
if (planDate.activity3CommentsField != NULL)
{
return 5;
}
else return 4;
}
}
else if (section == 3)
{
if ([planDate.sceneFive isEqual: @"pdCoffeeDrinks"])
{
planDate.sectionThreeLabel = coffeeDrinkSection;
sectionThree = coffeeDrinkSection;
return 2;
}
else if ([planDate.sceneFive isEqual: @"pdLunch"])
{
planDate.sectionThreeLabel = lunchSection;
sectionThree = lunchSection;
return 2;
}
else if ([planDate.sceneFive isEqual: @"pdDinner"])
{
planDate.sectionThreeLabel = dinnerSection;
sectionThree = dinnerSection;
return 2;
}
else if ([planDate.sceneFive isEqual: @"pdMovies"])
{
planDate.sectionThreeLabel = movieSection;
sectionThree = movieSection;
return 3;
}
else if ([planDate.sceneFive isEqual: @"pdActivity1"])
{
planDate.sectionThreeLabel = activity1Section;
sectionThree = activity1Section;
if (planDate.activity1CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneFive isEqual: @"pdActivity2"])
{
planDate.sectionThreeLabel = activity2Section;
sectionThree = activity2Section;
if (planDate.activity2CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneFive isEqual: @"pdActivity3"])
{
planDate.sectionThreeLabel = activity3Section;
sectionThree = activity3Section;
if (planDate.activity3CommentsField != NULL)
{
return 5;
}
else return 4;
}
}
else if (section == 4)
{
if ([planDate.sceneSix isEqual: @"pdCoffeeDrinks"])
{
planDate.sectionFourLabel = coffeeDrinkSection;
sectionFour = coffeeDrinkSection;
return 2;
}
else if ([planDate.sceneSix isEqual: @"pdLunch"])
{
planDate.sectionFourLabel = lunchSection;
sectionFour = lunchSection;
return 2;
}
else if ([planDate.sceneSix isEqual: @"pdDinner"])
{
planDate.sectionFourLabel = dinnerSection;
sectionFour = dinnerSection;
return 2;
}
else if ([planDate.sceneSix isEqual: @"pdMovies"])
{
planDate.sectionFourLabel = movieSection;
sectionFour = movieSection;
return 2;
}
else if ([planDate.sceneSix isEqual: @"pdActivity1"])
{
planDate.sectionFourLabel = activity1Section;
sectionFour = activity1Section;
if (planDate.activity1CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneSix isEqual: @"pdActivity2"])
{
planDate.sectionFourLabel = activity2Section;
sectionFour = activity1Section;
if (planDate.activity2CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneSix isEqual: @"pdActivity3"])
{
planDate.sectionFourLabel = activity3Section;
sectionFour = activity1Section;
if (planDate.activity3CommentsField != NULL)
{
return 5;
}
else return 4;
}
}
else if (section == 5)
{
if ([planDate.sceneSeven isEqual: @"pdCoffeeDrinks"])
{
planDate.sectionFiveLabel = coffeeDrinkSection;
sectionFive = coffeeDrinkSection;
return 2;
}
else if ([planDate.sceneSeven isEqual: @"pdLunch"])
{
planDate.sectionFiveLabel = lunchSection;
sectionFive = lunchSection;
return 2;
}
else if ([planDate.sceneSeven isEqual: @"pdDinner"])
{
planDate.sectionFiveLabel = dinnerSection;
sectionFive = dinnerSection;
return 2;
}
else if ([planDate.sceneSeven isEqual: @"pdMovies"])
{
planDate.sectionFiveLabel = movieSection;
sectionFive = movieSection;
return 3;
}
else if ([planDate.sceneSeven isEqual: @"pdActivity1"])
{
planDate.sectionFiveLabel = activity2Section;
sectionFive = activity1Section;
if (planDate.activity1CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneSeven isEqual: @"pdActivity2"])
{
planDate.sectionFiveLabel = activity2Section;
sectionFive = activity2Section;
if (planDate.activity2CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneSeven isEqual: @"pdActivity3"])
{
planDate.sectionFiveLabel = activity3Section;
sectionFive = activity3Section;
if (planDate.activity3CommentsField != NULL)
{
return 5;
}
else return 4;
}
}
else if (section == 6)
{
if ([planDate.sceneEight isEqual: @"pdCoffeeDrinks"])
{
planDate.sectionSixLabel = coffeeDrinkSection;
return 2;
}
else if ([planDate.sceneEight isEqual: @"pdLunch"])
{
planDate.sectionSixLabel = lunchSection;
return 2;
}
else if ([planDate.sceneEight isEqual: @"pdDinner"])
{
planDate.sectionSixLabel = dinnerSection;
return 2;
}
else if ([planDate.sceneEight isEqual: @"pdMovies"])
{
planDate.sectionSixLabel = movieSection;
return 3;
}
else if ([planDate.sceneEight isEqual: @"pdActivity1"])
{
planDate.sectionSixLabel = activity1Section;
sectionSix = activity1Section;NS
if (planDate.activity1CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneEight isEqual: @"pdActivity2"])
{
planDate.sectionSixLabel = activity2Section;
sectionSix = activity2Section;
if (planDate.activity2CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneEight isEqual: @"pdActivity3"])
{
planDate.sectionSixLabel = activity3Section;
sectionSix = activity3Section;
if (planDate.activity3CommentsField != NULL)
{
return 5;
}
else return 4;
}
}
else if (section == 7)
{
if ([planDate.sceneNine isEqual: @"pdCoffeeDrinks"])
{
planDate.sectionSevenLabel = coffeeDrinkSection;
return 2;
}
else if ([planDate.sceneNine isEqual: @"pdLunch"])
{
planDate.sectionSevenLabel = lunchSection;
return 2;
}
else if ([planDate.sceneNine isEqual: @"pdDinner"])
{
planDate.sectionSevenLabel = dinnerSection;
return 2;
}
else if ([planDate.sceneNine isEqual: @"pdMovies"])
{
planDate.sectionSevenLabel = movieSection;
return 3;
}
else if ([planDate.sceneNine isEqual: @"pdActivity1"])
{
planDate.sectionSevenLabel = activity1Section;
sectionSeven = activity1Section;
if (planDate.activity1CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneNine isEqual: @"pdActivity2"])
{
planDate.sectionSevenLabel = activity2Section;
sectionSeven = activity2Section;
if (planDate.activity2CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneNine isEqual: @"pdActivity3"])
{
planDate.sectionSevenLabel = activity3Section;
sectionSeven = activity3Section;
if (planDate.activity3CommentsField != NULL)
{
return 5;
}
else return 4;
}
}
else if (section == 8)
{
if ([planDate.sceneTen isEqual: @"pdCoffeeDrinks"])
{
planDate.sectionEightLabel = coffeeDrinkSection;
return 2;
}
else if ([planDate.sceneTen isEqual: @"pdLunch"])
{
planDate.sectionEightLabel = lunchSection;
return 2;
}
else if ([planDate.sceneTen isEqual: @"pdDinner"])
{
planDate.sectionEightLabel = dinnerSection;
return 2;
}
else if ([planDate.sceneTen isEqual: @"pdMovies"])
{
planDate.sectionEightLabel = movieSection;
return 3;
}
else if ([planDate.sceneTen isEqual: @"pdActivity1"])
{
planDate.sectionEightLabel = activity1Section;
sectionEight = activity1Section;
if (planDate.activity1CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneTen isEqual: @"pdActivity2"])
{
planDate.sectionEightLabel = activity2Section;
sectionEight = activity2Section;
if (planDate.activity2CommentsField != NULL)
{
return 5;
}
else return 4;
}
else if ([planDate.sceneTen isEqual: @"pdActivity3"])
{
planDate.sectionEightLabel = activity3Section;
sectionEight = activity3Section;
if (planDate.activity3CommentsField != NULL)
{
return 5;
}
else return 4;
}
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 30.0;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 150)];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 25)];
if (section == 0)
{
label.text = planDate.sectionZeroLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 1)
{
label.text = planDate.sectionOneLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == (planDate.numberOfCells+2))
{
label.text = planDate.sectionTransportationLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 2)
{
label.text = planDate.sectionTwoLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 3)
{
label.text = planDate.sectionThreeLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 4)
{
label.text = planDate.sectionFourLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 5)
{
label.text = planDate.sectionFiveLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 6)
{
label.text = planDate.sectionSixLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 7)
{
label.text = planDate.sectionSevenLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
else if (section == 8)
{
label.text = planDate.sectionEightLabel;
label.backgroundColor = [UIColor clearColor];
[label setFont:[UIFont boldSystemFontOfSize:16]];
label.textColor = [UIColor whiteColor];
}
[headerView addSubview:label];
return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
cell.textLabel.numberOfLines = 1;
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.minimumScaleFactor = .5;
if (indexPath.section == 0)
{
cell.textLabel.text = planDate.recipientUserName;
}
else if(indexPath.section == 1)
{
[self meetupCell:indexPath :cell];
}
if(indexPath.section == 2)
{
if (sectionTwo == coffeeDrinkSection)
{
[self coffeeDrinksCell:indexPath:cell];
}
else if (sectionTwo == lunchSection)
{
[self lunchCell:indexPath:cell];
}
else if (sectionTwo== dinnerSection)
{
[self dinnerCell:indexPath :cell];
}
else if (sectionTwo == movieSection)
{
[self movieCell:indexPath :cell];
}
else if (sectionTwo == activity1Section)
{
[self activity1Cell:indexPath :cell];
}
else if (sectionTwo == activity2Section)
{
[self activity2Cell:indexPath :cell];
}
else if (sectionTwo == activity3Section)
{
[self activity3Cell:indexPath :cell];
}
}
else if (indexPath.section == (planDate.numberOfCells+2))
{
[self transportationCell:indexPath :cell];
}
else if(indexPath.section == 3)
{
if (sectionThree == coffeeDrinkSection)
{
[self coffeeDrinksCell:indexPath:cell];
}
else if (sectionThree == lunchSection)
{
[self lunchCell:indexPath:cell];
}
else if (sectionThree == dinnerSection)
{
[self dinnerCell:indexPath :cell];
}
else if (sectionThree == movieSection)
{
[self movieCell:indexPath :cell];
}
else if (sectionThree == activity1Section)
{
[self activity1Cell:indexPath :cell];
}
else if (sectionThree == activity2Section)
{
[self activity2Cell:indexPath :cell];
}
else if (sectionThree == activity3Section)
{
[self activity3Cell:indexPath :cell];
}
}
else if(indexPath.section == 4)
{
if (sectionFour == coffeeDrinkSection)
{
[self coffeeDrinksCell:indexPath:cell];
}
else if (sectionFour== lunchSection)
{
[self lunchCell:indexPath:cell];
}
else if (sectionFour == dinnerSection)
{
[self dinnerCell:indexPath :cell];
}
else if (sectionFour == movieSection)
{
[self movieCell:indexPath :cell];
}
else if (sectionFour == activity1Section)
{
[self activity1Cell:indexPath :cell];
}
else if (sectionFour == activity2Section)
{
[self activity2Cell:indexPath :cell];
}
else if (sectionFour == activity3Section)
{
[self activity3Cell:indexPath :cell];
}
}
else if(indexPath.section == 5)
{
if (sectionFive == coffeeDrinkSection)
{
[self coffeeDrinksCell:indexPath:cell];
}
else if (sectionFive== lunchSection)
{
[self lunchCell:indexPath:cell];
}
else if (sectionFive == dinnerSection)
{
[self dinnerCell:indexPath :cell];
}
else if (sectionFive == movieSection)
{
[self movieCell:indexPath :cell];
}
else if (sectionFive == activity1Section)
{
[self activity1Cell:indexPath :cell];
}
else if (sectionFive == activity2Section)
{
[self activity2Cell:indexPath :cell];
}
else if (sectionFive == activity3Section)
{
[self activity3Cell:indexPath :cell];
}
}
return cell;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T15:08:38.903",
"Id": "47927",
"Score": "1",
"body": "I haven't done programming on `ios` but this looks like C. So I'll put a comment instead of putting an answer. In your `(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section` it seems that the 2nd to 4th statement(label's backgroundColor to label's textcolor) is the same in virtually every if-block. Wouldn't it be much simpler to put them out of the blocks? That alone can take out something like 27 lines of redundant code if you put them outside the if-else. Also isn't there a `switch` statement? It looks like your code can be much better using `switch` cases."
}
] |
[
{
"body": "<p>In reviewing the code I've identified issues with architecture, code repetition, and code style.</p>\n\n<p>The canonical architecture for iOS apps is the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow noreferrer\">Model - View - Controller</a> pattern. Further reading specific to iOS available <a href=\"https://developer.apple.com/library/ios/documentation/general/conceptual/devpedia-cocoacore/MVC.html\" rel=\"nofollow noreferrer\">here</a>. One of the primary issues I see here is a fuzzing of responsibilities between model and controller. The <code>PlanDate</code> core data entity maintains a number of properties about the sections that will be displayed from it - <code>sectionTwoLabel</code> and so on. This is an inappropriate assignment of responsibilities to the model layer - these should be in the view or controller layer, generally (with iOS view controllers usually straddling these layers, although that's controversial). I'm unsure what the various <code>scene...</code> and <code>transport...</code> attributes of the <code>PlanDate</code> are, but I'm suspicious that they should be their own entities in the model, as well. A rough UML diagram of what I mean:</p>\n\n<p><img src=\"https://i.stack.imgur.com/hwKUD.png\" alt=\"enter image description here\"></p>\n\n<p><code>SceneDetail</code> represents the data that's unique to each scene, that for instance is causing the coffee scene to require 2 cells, and so on. As I have an incomplete understanding of the application it's possible that some type of polymorphism on <code>Scene</code> would be appropriate. The <code>Scene</code> name could be an internal ID that you translate to something human readable, or just something human readable to begin with, such as \"Coffee\". A consequence of having the scenes and transportation options represented as relationships means that we can greatly simplify the table view code by relying on the collection behavior in the relationship, instead of checking <code>if (sceneTwo != nil)</code> and so on. We should order the relationships so that they will be represented by <code>NSOrderedSet</code> instances and the model will preserve the sorting for us. We can start to refactor our table view methods to take advantage of this.</p>\n\n<pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView\n{\n NSUInteger numberOfScenes = [planDate.scenes count];\n return numberOfScenes + 3;\n}\n\n- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section\n{\n NSInteger rows = 0;\n\n if (section == 0) {\n rows = 1;\n }\n else if (section == 1) {\n rows = 2;\n }\n else if (section == [self transportSection]) {\n rows = [planDate.transportOptions count];\n }\n else {\n Scene *sceneForSection = [self sceneForSection:section];\n rows = [sceneForSection.sceneDetails count]; //scene details contains info displayed in rows\n }\n\n return rows;\n}\n\n- (Scene *)sceneForSection:(NSInteger)section\n{\n Scene *sceneForSection = planDate.scenes[section - 2];\n return sceneForSection;\n}\n\n- (NSInteger)transportSection\n{\n return ([planDate.scenes count] + 2);\n}\n</code></pre>\n\n<p>This vastly simplifies the calculation of the number of rows in the section. We now <strong>rely on the count of the relationships</strong> rather than inspecting flags on the object and maintaining complex state within our controller. Similar improvements are seen in generating the header view:</p>\n\n<pre><code>- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section\n{\n UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 150)];\n\n UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width - 10, 25)];\n label.backgroundColor = [UIColor clearColor];\n [label setFont:[UIFont boldSystemFontOfSize:16]];\n label.textColor = [UIColor whiteColor];\n\n if (section == 0) {\n label.text = @\"Recipient\";\n }\n else if (section == 1) {\n label.text = @\"Let's meet at:\";\n }\n else if (section == [self transportSection]) {\n label.text = @\"Transport\";\n }\n else {\n Scene *scene = [self sceneForSection:section];\n label.text = scene.name;\n }\n\n [headerView addSubview:label];\n return headerView;\n}\n</code></pre>\n\n<p>We <strong>rely on information the model knows about itself</strong>, namely count and ordering and names, to generate the properties for the section headers. You'd want to go on and refactor <code>tableView:cellForRowAtIndexPath:</code> to take advantage of these characteristics as well, instead of relying on storing which section is which.</p>\n\n<p>As I said earlier, I see code repetition issues in this code. I've extracted small methods like <code>transportSection</code> and <code>sceneForSection</code> to avoid those. I also moved label configuration out of the if statements and into the main method. Keep alert for small changes you can do similar to this, where blocks of code are replaced with method calls to reduce duplication. <strong>If you're re-writing the same chunk of code</strong> for the second, or at very most the third time, <strong>extract it into a method or function</strong>.</p>\n\n<p>Finally, some notes on style. Compare object values not to <code>NULL</code> but to <code>nil</code> so other programmers know that the value is an object. <strong>Don't ever write methods without each parameter named</strong> - so no more <code>coffeeCell::</code> but instead something like <code>configureCoffeeCell:atIndexPath:</code>. That is a big one in my own, and many other Objective-C developer's, views. There is in fact only a single Apple API that I'm aware of that doesn't follow that convention. I'd also suggest avoiding having so many <code>return</code> statements in each method. It makes debugging easier, I find.</p>\n\n<p>To sum up, address your architecture issues by applying MVC and <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. Delegate to the model the maintenance of information about its state, and just have the controller translate that information to the view. Look for opportunities to extract repeated chunks of code into their own methods. And follow <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html\" rel=\"nofollow noreferrer\">good Objective-C style practices and guidelines</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T20:07:00.733",
"Id": "48090",
"Score": "0",
"body": "Hey! Thank you so much for your detailed explanation and pointers. I also spotted code repetition but decided to change the code all at once. I didn't, however, know about writing methods without each parameter named! \n\nI did an update on the question to give you a better understanding of the app. It's basically an app for couples to schedule a date. \n\nI have a simple data class that I pass around between the viewControllers called planDate (an instance of STPDDataClass)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T20:07:31.830",
"Id": "48091",
"Score": "0",
"body": "It isn't until the end when I save the object I map the variables to coreData entity variables as you probably saw under - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex. Do you still recommend relationships? If so, I think it will be to-many?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T20:08:32.647",
"Id": "48092",
"Score": "0",
"body": "So, following your advice on polymorphism, I guess I'm struggling with how would I know what all options the user selected and how to map them to the entity after the user decides to save the object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T23:01:01.887",
"Id": "48101",
"Score": "0",
"body": "And, last, how would I know what viewController/Scene should be presented next?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-27T16:09:45.483",
"Id": "48186",
"Score": "1",
"body": "Thanks for the feedback. I'll try to review these in the next few days and respond - it's a bear of a week!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T00:40:58.153",
"Id": "48577",
"Score": "0",
"body": "Hey! Just checking in to see if you'll be have a chance to look at this over the weekend. I know it's a long weekend, so no pressure. Just kind of planning next week and thought I'd check in. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T00:49:42.287",
"Id": "48579",
"Score": "0",
"body": "I just reviewed these a bit. If you use an ordered relationship for scenes that takes care of re-ordering, I'd think. You could also potentially make some subtype entities of a generic Scene, and then produce different scene detail view controllers for them as appropriate. You could also try a more generic approach to the scene detail v.c. that builds its view out based on the values set for attributes of the `Scene`. Does that make sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T00:57:32.073",
"Id": "48580",
"Score": "0",
"body": "Thanks for your swift reply. Good idea about ordered relationship. I have never used them, so I'll do some research and post my new approach for the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-31T03:54:04.987",
"Id": "48598",
"Score": "0",
"body": "So for re-ordering I'm thinking since I'm using a container view, after the user re-orders, I'll notify the parentViewController of the NSOrderedSet, which will call the scenes in the containerView. Do you mean ordered relationships in CoreData? If so, can you please elaborate on that? Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-03T16:42:30.017",
"Id": "48848",
"Score": "1",
"body": "I did a bit of reading and it appears that maybe ordered relationships aren't what you want - instead of a normal relationship and sort by some display order, instead. I don't have the links handy I'll try to add them if I can dig them back up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-03T17:50:42.423",
"Id": "48857",
"Score": "0",
"body": "Hey! Thanks for the follow-up. I think I found a solution I have been working on since Sunday. Since I'm using Stackmob, I wasn't sure if they'll support ordered relationships so I ventured with just NSMutableOrderedSet. It's going well and I have been able to remove nearly 3,000 lines of code -- it's far more manageable now with a lot less if/else statements! I'm not quite done yet. If you're interested, I can share the file when I'm done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-07T06:52:34.353",
"Id": "49194",
"Score": "0",
"body": "Glad to hear it! Let me know how things go."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-08T14:43:34.503",
"Id": "49264",
"Score": "0",
"body": "So based on your sectionModel technique you shared and using NSOrderedSet, I reduced the code by 6000+ lines! Thank you once again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-10T02:34:38.983",
"Id": "49392",
"Score": "0",
"body": "@user1107173 fantastic!"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-25T16:48:05.357",
"Id": "30212",
"ParentId": "30059",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "30212",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T03:04:28.887",
"Id": "30059",
"Score": "2",
"Tags": [
"objective-c",
"ios"
],
"Title": "Refactoring to avoid if-else in numberOfRowsInSection and cellForRowAtIndexPath"
}
|
30059
|
<p>I've made a Tic-Tac-Toe program (non-AI) for 2 human players. I will implement AI for a computer player later on. I am a beginner programmer and am also new to classes, which I've implemented in this program. I want to know how this could be optimized.</p>
<pre><code>//the main class is all the way at the end
#include "stdafx.h"
#include <iostream>
#include <string>
#include <Windows.h>
//To Implement Color Mechanics
HANDLE hCon;
enum Color { DARKBLUE = 1, DARKGREEN, DARKTEAL, DARKRED, DARKPINK, DARKYELLOW, GRAY, DARKGRAY, BLUE, GREEN, TEAL, RED, PINK, YELLOW, WHITE };
void SetColor(Color c){
if(hCon == NULL)
hCon = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hCon, c);
}
//As of now the program asks for player names but this functionality was added later on, but that disrupted some methods in the game class
//so i declared these global variables to keep the changes to a minimum
std::string player1, player2;
//its the game class, all the methods and the constructor are written right after the class
class game{
public:
game();
int insert(int,char);
int win();
void win_display();
private:
char board[9];
void color_conv(char);
void Winner(int);
};
//constructor for the class game
game::game(){
SetColor(DARKGREEN);
std::cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Tic-Tac-Taoe~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<std::endl;
std::cout<<"*By Default Player 1 is 'O' and Player 2 is 'X'\n";
std::cout<<"*The choice of cells is mapped out in the following legend\n\n\n";
std::cout<<" 1 | 2 | 3 \n____|____|____\n 4 | 5 | 6 \n____|____|____\n 7 | 8 | 9 \n | | \n\n";
std::cout<<"********************************************************************************\n\n\n";
SetColor(WHITE);
//This fills up the board array with '-' a filler character, also it looks good :)
for(int k=0;k<9;k++){
board[k]='-';
}
}
//this function in game class is used to insert the right mark, i.e 'O' or 'X' , in the player's choice of position
//the return values are used in the main program to determine a valid choice
//if there is an invalid choice the current player is given another choice until he makes a valid choice
int game::insert(int choice, char mark){
SetColor(WHITE);
if(choice<=9 && board[choice-1]=='-'){
board[choice-1]=mark;
std::cout<<" "<<board[0]<<" | "<<board[1]<<" | "<<board[2]<<" \n____|____|____\n "<<board[3]<<" | "<<board[4]<<" | "<<board[5]<<" \n____|____|____\n "<<board[6]<<" | "<<board[7]<<" | "<<board[8]<<" \n | | \n\n";
return 1;
}
else if(choice>9){
SetColor(RED);
std::cout<<"Valid choices are only 1 through 9....\n\n";
SetColor(WHITE);
return 0;
}
else if(board[choice-1]!='-'){
SetColor(RED);
std::cout<<"This choice was already taken....\n\n";
SetColor(WHITE);
return 0;
}
}
//this funtion determines if there is a win
//return values are 1 for win, 0 for loss, 2 for draw
int game::win(){
//the conditions listed are for row1,row2,row3,col1,col2,col3,diagonal1 and diagonal2 respectively
if( (board[0]==board[1] && board[1]==board[2] && board[0]!='-')
||(board[3]==board[4] && board[4]==board[5] && board[3]!='-')
||(board[6]==board[7] && board[7]==board[8] && board[6]!='-')
||(board[0]==board[3] && board[3]==board[6] && board[0]!='-')
||(board[1]==board[4] && board[4]==board[7] && board[1]!='-')
||(board[2]==board[5] && board[5]==board[8] && board[2]!='-')
||(board[0]==board[4] && board[4]==board[8] && board[0]!='-')
||(board[2]==board[4] && board[4]==board[6] && board[2]!='-')){
return 1;
}
//condition for draw----> if its not a win and the board is full i.e. no '-' chars
while(true){
for(int k=0;k<9;k++){
//if there are any '-' chars then the game is not complete thus we return 0
if(board[k]=='-'){
return 0;
}
}
return 2;
}
return 0;
}
//changes the color of the input character
//this is implemented by the "win_display()"
void game::color_conv(char c){
SetColor(TEAL);
std::cout<<c;
SetColor(WHITE);
}
//display mechanism for a win/draw situation
//this is implemented to selectively color the winning condition like row1, col1, etc
void game::win_display(){
if((board[0]==board[1] && board[1]==board[2])){
std::cout<<" ";
color_conv(board[0]);
std::cout<<" | ";
color_conv(board[1]);
std::cout<<" | ";
color_conv(board[2]);
std::cout<<" \n____|____|____\n "<<board[3]<<" | "<<board[4]<<" | "<<board[5]<<" \n____|____|____\n "<<board[6]<<" | "<<board[7]<<" | "<<board[8]<<" \n | | \n\n";
Winner(0);
}
else if((board[3]==board[4] && board[4]==board[5])){
std::cout<<" "<<board[0]<<" | "<<board[1]<<" | "<<board[2]<<" \n____|____|____\n ";
color_conv(board[3]);
std::cout<<" | ";
color_conv(board[4]);
std::cout<<" | ";
color_conv(board[5]);
std::cout<<" \n____|____|____\n "<<board[6]<<" | "<<board[7]<<" | "<<board[8]<<" \n | | \n\n";
Winner(3);
}
else if((board[6]==board[7] && board[7]==board[8])){
std::cout<<" "<<board[0]<<" | "<<board[1]<<" | "<<board[2]<<" \n____|____|____\n "<<board[3]<<" | "<<board[4]<<" | "<<board[5]<<" \n____|____|____\n ";
color_conv(board[6]);
std::cout<<" | ";
color_conv(board[7]);
std::cout<<" | ";
color_conv(board[8]);
std::cout<<" \n | | \n\n";
Winner(6);
}
else if((board[0]==board[3] && board[3]==board[6])){
std::cout<<" ";
color_conv(board[0]);
std::cout<<" | "<<board[1]<<" | "<<board[2]<<" \n____|____|____\n ";
color_conv(board[3]);
std::cout<<" | "<<board[4]<<" | "<<board[5]<<" \n____|____|____\n ";
color_conv(board[6]);
std::cout<<" | "<<board[7]<<" | "<<board[8]<<" \n | | \n\n";
Winner(0);
}
else if((board[1]==board[4] && board[4]==board[7])){
std::cout<<" "<<board[0]<<" | ";
color_conv(board[1]);
std::cout<<" | "<<board[2]<<" \n____|____|____\n "<<board[3]<<" | ";
color_conv(board[4]);
std::cout<<" | "<<board[5]<<" \n____|____|____\n "<<board[6]<<" | ";
color_conv(board[7]);
std::cout<<" | "<<board[8]<<" \n | | \n\n";
Winner(1);
}
else if((board[2]==board[5] && board[5]==board[8])){
std::cout<<" "<<board[0]<<" | "<<board[1]<<" | ";
color_conv(board[2]);
std::cout<<" \n____|____|____\n "<<board[3]<<" | "<<board[4]<<" | ";
color_conv(board[5]);
std::cout<<" \n____|____|____\n "<<board[6]<<" | "<<board[7]<<" | ";
color_conv(board[8]);
std::cout<<" \n | | \n\n";
Winner(2);
}
else if((board[0]==board[4] && board[4]==board[8])){
std::cout<<" ";
color_conv(board[0]);
std::cout<<" | "<<board[1]<<" | "<<board[2]<<" \n____|____|____\n "<<board[3]<<" | ";
color_conv(board[4]);
std::cout<<" | "<<board[5]<<" \n____|____|____\n "<<board[6]<<" | "<<board[7]<<" | ";
color_conv(board[8]);
std::cout<<" \n | | \n\n";
Winner(0);
}
else if((board[2]==board[4] && board[4]==board[6])){
std::cout<<" "<<board[0]<<" | "<<board[1]<<" | ";
color_conv(board[2]);
std::cout<<" \n____|____|____\n "<<board[3]<<" | ";
color_conv(board[4]);
std::cout<<" | "<<board[5]<<" \n____|____|____\n ";
color_conv(board[6]);
std::cout<<" | "<<board[7]<<" | "<<board[8]<<" \n | | \n\n";
Winner(2);
}
}
//again this function is implemented by "win_display()" to display which player won
void game::Winner(int k){
if(board[k]=='O'){
SetColor(YELLOW);
std::cout<<player1<<" Won....\n";
SetColor(WHITE);
}
else if(board[k]=='X'){
SetColor(YELLOW);
std::cout<<player2<<" Won....\n";
SetColor(WHITE);
}
}
// main function
int main(){
int choice,i=1,turn_check;
int check=0;
game current_game;
SetColor(DARKPINK);
std::cout<<"Enter the 1st Player's Name....\n\n";
std::getline(std::cin,player1);
std::cout<<"Enter the 2nd Player's Name....\n\n";
std::getline(std::cin,player2);
SetColor(WHITE);
//to play turn wise I implemented an odd\even check
//as such when a valid choice is not made by the player, which we will know from the return value of game::insert()
//the counter i is set decremented by 1 to give the current player another chance
while(check==0){
//player 1's turn
if(i%2!=0){
std::cout<<player1<<": Enter Your Choice...."<<std::endl;
std::cin>>choice;
turn_check=current_game.insert(choice,'O');
}
//check if the game is won
check=current_game.win();
//player 2's turn
if(i%2==0){
std::cout<<player2<<": Enter Your Choice...."<<std::endl;
std::cin>>choice;
turn_check=current_game.insert(choice,'X');
}
//check if the game is won
check=current_game.win();
//increment i for the next player's turn
i++;
//if player has not made a valid chance give the player another chance
if(turn_check==0){
i--;
}
}
//at this point check=1 or 2 i.e. game is won or draw the following conditional statement check for this and displays appropriate message
if(check==1){
current_game.win_display();
}
else {
SetColor(PINK);
std::cout<<"The Game is a Draw!!!\n";
SetColor(WHITE);
}
return 0;
}
//The End
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><code>insert()</code> and <code>win()</code> don't need to return something like an <code>int</code>, so they can both be <code>void</code>.</p>\n\n<p><strong>For <code>insert()</code></strong>, on the other hand, you have another return option: <code>bool</code>. If the insertion was successful, return <code>true</code>. If it failed, return <code>false</code>. I should note that this is purely for conditional circumstances, and this doesn't make your code exception-safe. I won't get into that here, though.</p>\n\n<p>Example of <code>insert()</code> returning <code>bool</code>, for your code:</p>\n\n<pre><code>bool game::insert(int choice, char mark) {\n\n if (choice <= 9 && board[choice-1] == '-') {\n // do stuff for TRUE condition\n return true;\n }\n else if (choice > 9) {\n // do stuff for FALSE condition\n return false;\n }\n else if (board[choice-1] != '-') {\n // do other stuff for FALSE condition\n return false;\n }\n}\n</code></pre>\n\n<p><strong>For <code>win()</code></strong>, you have different options:</p>\n\n<ol>\n<li>only test the condition at the call (as a <code>bool</code>)</li>\n<li>return a \"Boolean enum\" and test that at the call</li>\n</ol>\n\n<p>Let's look at both options:</p>\n\n<p><strong>Testing at the call</strong>:</p>\n\n<pre><code>// play the game...\n\nif (win())\n{\n // do something\n}\nelse\n{\n // do something else\n}\n</code></pre>\n\n<p>It doesn't even cover the draw, huh? Let's try the \"Boolean enum\":</p>\n\n<p><em>First</em>, declare the <code>enum</code>:</p>\n\n<pre><code>// you could put this inside the class or in a namespace\n// you do NOT need to assign these numbers in this case\n// I've done so anyway for illustration purposes\n\nenum Outcome { LOSE=0, WIN=1, DRAW=2 };\n</code></pre>\n\n<p><em>Next</em>, set up the function:</p>\n\n<pre><code>Outcome game::win()\n{\n if (/* winning condition here */)\n {\n // do some stuff\n return WIN;\n }\n else if (/* losing condition here */)\n {\n // do some stuff\n return LOSE;\n }\n else // draw condition\n {\n // do some stuff\n return DRAW;\n }\n}\n</code></pre>\n\n<p>Notice here that I've used an <code>else</code> instead of another <code>if else</code>. This is because the function could <em>technically</em> still not meet any of these conditions, thus it won't be able to return anything. And, since this is clearly not a <code>void</code> function (return doesn't matter), that would be <em>bad</em>. If your compiler is set to report <em>warnings</em>, then it'll tell you about this if violated.</p>\n\n<p><em>Finally</em>, test this at the call:</p>\n\n<pre><code>if (win() == WIN)\n{\n // stuff\n}\nelse if (win() == LOSE)\n{\n // stuff\n}\nelse if (win() == DRAW)\n{\n // and more stuff\n}\n</code></pre>\n\n<p>Looks better, huh? Try both options and see which one you prefer. Also, yes, you're right; <code>win()</code> should be renamed. You could name it something like <code>outcome()</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T19:57:29.887",
"Id": "47795",
"Score": "0",
"body": "sweet ....the enum was there in the code all along in the color function but never really noticed it ....thanks man i can think of a lot of previous programs that could benefit from this ....i think this makes the program more readable and neat ....thanks jamal ...you are great :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:07:04.853",
"Id": "47798",
"Score": "0",
"body": "You're welcome! I may add more to this as I see fit. Someone else may also contribute more or add/improve on what I've mentioned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:10:39.480",
"Id": "47800",
"Score": "0",
"body": "Awesome....I will make the necessary changes and re-post the code again sometime in the night by then i will probably get all the comments i need :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:13:41.597",
"Id": "47801",
"Score": "0",
"body": "If you mean you'll edit the same code block, don't do that. Doing so (in general) will invalidate any answers. Instead, you may add the revised code blocks below the original."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:16:19.753",
"Id": "47802",
"Score": "0",
"body": "no no that's what i had in mind ....i was gonna do the latter"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:16:45.327",
"Id": "47803",
"Score": "0",
"body": "Okay, good. Just making sure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:25:22.997",
"Id": "47805",
"Score": "0",
"body": "sure, no problem"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T19:45:47.327",
"Id": "30098",
"ParentId": "30060",
"Score": "2"
}
},
{
"body": "<p>Pseudo code for a simple 'AI':</p>\n\n<pre><code>// If there is a winning move\n// Take it.\n// Otherwise, if there is a blocking move (opponent has 2 in a row with open square)\n// Take it.\n// Otherwise, take one of these spots, if it is available, in this order:\n// Middle, Middle.\n// Any corner. // <-- this can be randomized for different games.\n// Any middle edge. // <-- same as above.\n</code></pre>\n\n<p>The corner and middle edges can be decided randomly so that the player has more fun via variety.</p>\n\n<p>For another twist, and making the 'AI' both smarter, and dumber in ways, you could the above pseudo code so that there is a chance (random) of picking an action from a different 'tier'. The 'AI' would be smarter because it has a wider range of options, but dumber because they don't work as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:24:00.037",
"Id": "47804",
"Score": "0",
"body": "ok got it....that's actually pretty simple i can use till learn the minimax algorithm or any thing else useful...but that's probably gonna take a while"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T23:08:43.483",
"Id": "47811",
"Score": "0",
"body": "If you want an 'AI' that changes its behavior based on previous games, then yea, thats a bunch harder."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T01:06:57.203",
"Id": "47812",
"Score": "0",
"body": "that seems advanced ....but right now my problem it seems is implementing class header ....its letting me use accessor methods to set strings ....gahh! it's so frustrating but i bet its like one really tiny mistake ...."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T20:11:11.170",
"Id": "30100",
"ParentId": "30060",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T03:41:19.583",
"Id": "30060",
"Score": "6",
"Tags": [
"c++",
"beginner",
"performance",
"game",
"tic-tac-toe"
],
"Title": "Tic-Tac-Toe optimization"
}
|
30060
|
<p>I'm just looking for someone to give a critique of my currency converter. I want to see if I could clean it up first before dummy-proofing. I know you want to avoid floating types for working with money, so I made a <code>Cents</code> class. I'm not fully confident in how I did it, so any pointers on that would be nice.</p>
<p><strong>Converter.h</strong></p>
<pre><code> #ifndef CURRENCY_H
#define CURRENCY_H
#include <map>
class Converter {
private:
std::map<std::string, double> currency;
std::map<std::string, std::string> symbol;
public:
Converter();
std::string getSymbol(std::string currency);
long convertCurrency(std::string c1, std::string c2, long amount);
};
#endif
</code></pre>
<p><strong>Converter.cpp</strong></p>
<pre><code> #include <iostream>
#include "converter.h"
Converter::Converter(){
currency["usd-gbp"] = 0.6392;
currency["usd-cad"] = 1.0478;
currency["usd-eur"] = 0.7494;
currency["usd-jpy"] = 97.821;
currency["usd-aud"] = 1.1151;
currency["usd-chf"] = 0.9232;
symbol["usd"] = "$";
currency["gbp-usd"] = 1.5646;
currency["gbp-cad"] = 1.6393;
currency["gbp-eur"] = 1.1726;
currency["gbp-jpy"] = 153.0483;
currency["gbp-aud"] = 1.7447;
currency["gbp-chf"] = 1.4443;
symbol["gbp"] = "£";
currency["aud-usd"] = 0.8968;
currency["aud-gbp"] = 0.5732;
currency["aud-cad"] = 0.9396;
currency["aud-eur"] = 0.6721;
currency["aud-jpy"] = 87.7225;
currency["aud-chf"] = 0.8278;
symbol["aud"] = "$";
currency["cad-usd"] = 0.9544;
currency["cad-gbp"] = 0.61;
currency["cad-aud"] = 1.4879;
currency["cad-eur"] = 0.7153;
currency["cad-jpy"] = 93.3629;
currency["cad-chf"] = 0.8811;
symbol["cad"] = "C$";
currency["eur-usd"] = 1.3343;
currency["eur-gbp"] = 0.8528;
currency["eur-aud"] = 1.4879;
currency["eur-cad"] = 1.398;
currency["eur-jpy"] = 130.526;
currency["eur-chf"] = 1.2318;
symbol["eur"] = "€";
currency["jpy-usd"] = 0.0102;
currency["jpy-gbp"] = 0.0065;
currency["jpy-aud"] = 0.0114;
currency["jpy-cad"] = 0.0107;
currency["jpy-eur"] = 0.0077;
currency["jpy-chf"] = 0.0094;
symbol["jpy"] = "¥";
currency["chf-usd"] = 0.0065;
currency["chf-gbp"] = 0.6924;
currency["chf-aud"] = 1.2079;
currency["chf-cad"] = 1.135;
currency["chf-eur"] = 0.8118;
currency["chf-jpy"] = 105.9644;
symbol["chf"] = "CHF ";
}
std::string Converter::getSymbol(std::string currency){
return symbol[currency];
}
long Converter::convertCurrency(std::string c1, std::string c2, long amount){
std::string key = c1 + "-" + c2;
for(int idx = 0; idx < currency.size(); idx++){
if(currency.find(key) != currency.end()){
double conversion = currency[key];
conversion *= (double)amount;
return (long)conversion;
}
}
}
</code></pre>
<p><strong>Cents.h</strong></p>
<pre><code> #ifndef MONEY_H
#define MONEY_H
#include <iostream>
#include <iomanip>
class Cents {
private:
long outputCents;
double inputCents;
public:
Cents(long nCents = 0){
outputCents = nCents;
}
long getLong(){ return outputCents; }
friend std::ostream& operator<< (std::ostream &out, Cents &cCents){
out << std::fixed << std::setprecision(2) << (double)cCents.outputCents/100;
return out;
}
friend std::istream& operator>> (std::istream &in, Cents &cCents){
in >> cCents.inputCents;
cCents.inputCents *= 100;
cCents.inputCents += 0.5;
cCents.outputCents = cCents.inputCents;
std::cin.ignore(3, '\n');
return in;
}
};
#endif
</code></pre>
<p><strong>Main.cpp</strong> </p>
<pre><code>#include <iostream>
#include "cents.h"
#include "converter.h"
using namespace std;
int main(){
cout << "### Currency Converter ###\n";
cout << "USD, GBP, CAD, EUR, JPY, AUD, CHF\n";
string currency1, currency2;
cout << "-Enter currency to convert from:\n";
getline(cin, currency1);
cout << "-Enter currency to convert to:\n";
getline(cin, currency2);
Cents amount;
cout << "-Enter amount:\n";
cin >> amount;
Converter convert;
Cents product = convert.convertCurrency(currency1, currency2, amount.getLong());
if(product.getLong() > 0){
cout << convert.getSymbol(currency2) << product << endl;
} else {
cout << "Currency not found!\n";
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>You're not using <code>using namespace std</code> in your classes, which is good. However, for <code>Main.cpp</code>, it's best to put it inside the function instead of making it global.</p></li>\n<li><p><code>getSymbol()</code>'s parameter should be a <code>const&</code> since it's not being modified:</p>\n\n<pre><code>std::string Converter::getSymbol(std::string const& currency) {}\n</code></pre></li>\n<li><p><code>getLong()</code> should be <code>const</code> since it's an accessor:</p>\n\n<pre><code>long getLong() const { return outputCents; }\n</code></pre>\n\n<p>More importantly, it should actually be removed as it's bad for encapsulation (accessors, also mutators, expose the implementation details). <code>operator<<</code> should remain a <code>friend</code> so that it can still access <code>private</code> members.</p>\n\n<p>Moreover, I'd have another function modify <code>outputCents</code>, then have <code>operator<<</code> call it to obtain and display the new value. <code>operator<<</code> shouldn't do extra work, which is why <code>cCents</code> must still be passed by value here. After this change, <code>cCents</code> can become a <code>const&</code> instead, which is preferred for <code>operator<<</code>'s object parameter.</p></li>\n<li><p>This form of casting:</p>\n\n<pre><code>conversion *= (double)amount;\n</code></pre>\n\n<p>is more C-like. Prefer the C++ way of casting:</p>\n\n<pre><code>conversion *= static_cast<double>(amount);\n</code></pre></li>\n<li><p>The <code>for</code>-loop in <code>convertCurrency()</code> is redundant and should be removed. The <code>if</code>-statement already does what's needed to search the map. In general: loops for STL container classes, such as <code>std::map</code>, should use the iterators instead of indices.</p></li>\n<li><p>Just a minor point: I'd put <code>currency1</code> and <code>currency2</code> right next to the <code>getline()</code>s:</p>\n\n<pre><code>std::cout << \"-Enter currency to convert from:\\n\";\nstd::string currency1;\ngetline(std::cin, currency1);\n\nstd::cout << \"-Enter currency to convert to:\\n\";\nstd::string currency2;\ngetline(std::cin, currency2);\n</code></pre>\n\n<p>This is preferred as it keeps the variable's scope narrow, increasing maintenance and readability.</p>\n\n<p>I'd also rename both input strings to something like <code>currencyFrom</code> and <code>currencyTo</code>.</p></li>\n<li><p>For more user-friendliness, consider an input menu. This should also require less input-validation as you won't need to rely on the inputted strings <em>exactly</em> matching the map's contents. The menu could be put into a free function, in case a client wants to use it. Doing so would ensure maintainability, flexibility, and <code>main()</code>'s purpose as the <em>driver</em> of your program.</p>\n\n<p>Generally-speaking, no one is <em>ever</em> obligated to use your own driver. Your program should work with any sensible, non-breaking driver.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T02:00:27.717",
"Id": "47813",
"Score": "1",
"body": "Using switch instead of map is a bad idea. You are moving from a data driven system to a hard coded system. The use of the map allows you to use a data driven technique, this allows the system to be updated without modifying the code (and thus recompiling and restesting the code). All you have to do is load the data from an external source into the program rather than having hand coded map initialization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T02:03:29.213",
"Id": "47814",
"Score": "1",
"body": "Also disagree on your comments about the output operator. Note it is not a member as defined (as friends are not members). Rather than make the output operator not a friend and use an accessor. Prefer to keep it a friend and remove the accessor. get/set methods break encapsulation be exposing implementation details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T02:06:51.930",
"Id": "47815",
"Score": "1",
"body": "The comment about using std::size in the loop in `currencyConverter()` is also not a good idea. When iterating over a container you should use the iterators. But also not that you missed the fact that the loop is completely redundant and should be removed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T02:12:30.050",
"Id": "47816",
"Score": "0",
"body": "@LokiAstari: Thanks. I wasn't paying enough attention to the loop, though I figured `std::size_t` would've been good enough. As for the map, I didn't think about it that way. It did seem unneeded at a glance. I'll make the changes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T02:23:02.800",
"Id": "47887",
"Score": "0",
"body": "Thank you both for the input, I've made the changes suggested. I'm just curious why the accessor should be removed. How is it that it exposes implementation details and why is this bad? I'm also unsure of how to do an alternative to calling the accessor. To summarize, what I'm doing in main is inputting two strings, inputting the monetary amount into a Cents variable and using the Converter's convertCurrency() function to pass those strings as key values to access the appropriate conversion rate and passing that Cents value to use the conversion rate on. How else can I pass the amount?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T02:42:23.150",
"Id": "47888",
"Score": "0",
"body": "You shouldn't use an accessor *just* because you need to obtain a `private` data member. Such data is supposed to be kept as close to the class as possible. So, if you give the interface the option of obtaining or setting (with a mutator) a data member, you're ruining the concept of keeping data private. For your program, it'd be better to perform a different check that doesn't involve using the accessor. As for displaying an object, that's why you have `operator<<`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T02:58:29.457",
"Id": "47889",
"Score": "0",
"body": "About the passing without using an accessor: it looks like you should just pass `amount` to `convertCurrency()`. As in, the entire object. Beyond that, I'm not sure how else the process should work, plus I still feel there are more weak points. You're welcome to open a new question with the updated code so that others may offer more help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T03:21:39.397",
"Id": "47890",
"Score": "0",
"body": "Another point: Instead of having the user input strings for the currencies, I'd give them a menu instead. It would look more user-friendly and the input-checking would be simpler. Although I removed the `enum` suggestion from my answer, I think it would still work here (while still not using a `switch` as corrected here), seeing as you just need the currency types to *identify* which conversion to perform. I could actually put the menu recommendation into this answer. If you'd like to go on with this exchange, we could go to chat."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T04:42:53.453",
"Id": "30062",
"ParentId": "30061",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "30062",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T03:54:49.533",
"Id": "30061",
"Score": "5",
"Tags": [
"c++",
"converting",
"finance"
],
"Title": "Currency converter"
}
|
30061
|
<p>I just wrote this fuzzy snippet to identify any 2-byte character in my data file which assumes only 1-byte characters (ANSI). Please review and suggest me any better solution!</p>
<pre><code>File.open('data.txt', 'r') do |f|
line_number = 0
while line = f.gets
line_number = line_number + 1
line.each_byte do |c|
if c & 0xff80 != 0
puts 'A non-ascii character is found at line ' + line_number.to_s
break
end
end
end
end
</code></pre>
|
[] |
[
{
"body": "<pre><code>File.open('data.txt', 'r') do |f| ... end\n</code></pre>\n\n<p>Good job. This is indeed the preferred way to read a file in Ruby. You get to read the file as a stream, and the file gets closed automatically. One thing to note is that the <code>r</code> flag is the default and can be left out. It is fine to leave it there for clarity, however.</p>\n\n<p>Don't forget to set the correct encoding. If the real encoding is compatible with low-ASCII, you can assume <code>ASCII-8BIT</code> but it will treat characters in multibyte encodings as multiple characters. See later, however. You can set a default one, or you can do it while opening the file with <code>:external_encoding => ...</code>.</p>\n\n<p>If you strive for simplicity rather than speed (or if the file is small enough to be read all at once), you can also <a href=\"http://ruby-doc.org/core-2.0/IO.html#method-c-read\" rel=\"nofollow\">load the file into memory at once</a>, then iterate over it:</p>\n\n<pre><code>f = IO.read('data.txt')\n</code></pre>\n\n<hr>\n\n<pre><code>line_number = 0\nwhile line = f.gets\n line_number = line_number + 1\n ...\nend\n</code></pre>\n\n<p>Apart from the fact that assignment within conditional is frowned upon in many languages because it can be confused with accidental assignment instead of comparison,</p>\n\n<p><code>File</code> inherits several iterators from <code>IO</code> (don't forget to check for inherited methods - from superclasses AND modules) when looking up documentation). One of them <a href=\"http://ruby-doc.org/core-2.0/IO.html#method-i-each_line\" rel=\"nofollow\"><code>IO#each_line</code></a>, formerly <code>IO#lines</code>. For the line number, you can use <a href=\"http://ruby-doc.org/core-2.0/IO.html#method-i-lineno\" rel=\"nofollow\"><code>IO#lineno</code></a>. You can also use <code>f.each_line.with_index{|line, index|...}</code>, but that is zero-based.</p>\n\n<hr>\n\n<pre><code>line.each_byte do |c|\n if c & 0xff80 != 0\n puts 'A non-ascii character is found at line ' + line_number.to_s\n break\n end\nend\n</code></pre>\n\n<p>I think you're looking for <a href=\"http://ruby-doc.org/core-2.0/String.html#method-i-each_codepoint\" rel=\"nofollow\"><code>String#each_codepoint</code></a> instead of <a href=\"http://ruby-doc.org/core-2.0/String.html#method-i-each_byte\" rel=\"nofollow\"><code>String#each_byte</code></a>. A UTF-16 non-ASCII character could well be composed of two ASCII bytes. UTF-8 non-ASCII characters are readily composed of multiple bytes, so you'd be getting multiple reports per character. If you assume a single-byte encoding, both will do (and <code>each_byte</code> is more explicit), but ...</p>\n\n<p>If your intention is to test single-byte encodings, then the mask <code>0x80</code> will suffice. If your intention is to support any encoding of the Unicode character set, then the mask <code>0xff80</code> will not suffice as Unicode code points are 20 bits long. Some rare characters actually lie in the <a href=\"http://en.wikipedia.org/wiki/Linear_B#Unicode\" rel=\"nofollow\">U+10000 .. U+1007F</a> region. Perhaps the surest test is to use <code>> 0x7F</code></p>\n\n<p>Better yet, realise you are working with strings, and use string methods to manipulate them. </p>\n\n<p>Even if you use <code>each_byte</code>, you <em>still</em> have to specify the external encoding. If the external encoding is set to UTF-8 but the source file isn't, you'll get an exception. That being said, you <em>could</em> set a 7-bit encoding (<code>US-ASCII</code>) and rely on the exception being thrown, but that won't get you the line number the character occurs on.</p>\n\n<hr>\n\n<p>While string concatenation is the way to go in languages that lack string interpolation, string interpolation is the preferred way in Ruby. The nice thing is that it performs automatic string conversion where concatenation requires you to convert manually. Just don't use huge blocks or nested interpolation inside unless you care for character count rather than readability. Compute the part first, then interpolate it in.</p>\n\n<p>One last thing to note is that you are not very consistent in the use of one-letter / descriptive variable names. Descriptive names never hurt, and single-letter variables should only be used if their scope is small enough (or if the single letter is descriptive per se).</p>\n\n<p>This is how I would modify your code:</p>\n\n<pre><code>File.open('data.txt') do |file|\n file.each_line.with_index do |line, index|\n if /[^\\x00-\\x7F]/ =~ line\n puts \"A non-ascii character is found at line #{index + 1}\"\n break\n end\n end\nend\n</code></pre>\n\n<p>If you are not afraid of perlisms,</p>\n\n<pre><code>File.open('data.txt') do |f|\n while f.gets\n if /[^\\x00-\\x7F]/\n puts \"A non-ascii character is found at line #{$.}\"\n break\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T12:52:16.093",
"Id": "47730",
"Score": "0",
"body": "this line is so beautiful: file.each_line.with_index do |line, index|"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T13:32:16.943",
"Id": "47734",
"Score": "0",
"body": "@TruongHa I love that too. Unfortunately, it doesn't set `$_` and let me pull off the implicit argument trick ;-) I recommend using the first version, though, if you want to have any chance of preserving readability ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T09:51:52.423",
"Id": "30071",
"ParentId": "30064",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "30071",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T06:39:08.817",
"Id": "30064",
"Score": "1",
"Tags": [
"ruby",
"unicode"
],
"Title": "Ruby code to identify 2-byte characters"
}
|
30064
|
<p>I have figures - <strong>TriangleItem</strong> and <strong>CircleItem</strong>:</p>
<pre><code>public abstract class BaseItem
{
protected int _id;
protected string _description;
}
public sealed class TriangleItem : BaseItem
{
public int TriangleId { get { return _id; } set { _id = value; } }
public string TriangleDescription { get { return _description; } set { _description = value; } }
}
public sealed class CircleItem : BaseItem
{
public int CircleId { get { return _id; } set { _id = value; } }
public string CircleDescription { get { return _description; } set { _description = value; } }
}
</code></pre>
<p>And I have figure collections <strong>TriangleBox</strong> and <strong>CircleBox</strong>:</p>
<pre><code>public abstract class BaseBox
{
public string ItemsXml { get; set; }
public string Descriptions { get; set; }
public static abstract BaseBox Boxing( BaseItem[] items );
public abstract void Unboxing();
}
public sealed class TriangleBox : BaseBox
{
public static override BaseBox Boxing( BaseItem[] items )
{
string[] ids = items.ToList().Cast<TriangleItem>().Select( i => i.TriangleId.ToString() ).ToArray();
string[] descriptions = items.ToList().Cast<TriangleItem>().Select( i => i.TriangleDescription ).ToArray();
return new TriangleBox()
{
ItemsXml = Util.ToXml( ids ),
Descriptions = descriptions.Aggregate( ( d, next ) => next + ", " + d )
};
}
public TriangleItem[] Unboxing()
{
return Util.FromXml( ItemsXml ).Select( i => new TriangleItem { TriangleId = int.Parse( i ), TriangleDescription = i } ).ToArray();
}
}
public sealed class CircleBox : BaseBox
{
public static override BaseBox Boxing( BaseItem[] items )
{
string[] ids = items.ToList().Cast<CircleItem>().Select( i => i.CircleId.ToString() ).ToArray();
string[] descriptions = items.ToList().Cast<CircleItem>().Select( i => i.CircleDescription ).ToArray();
return new CircleBox()
{
ItemsXml = Util.ToXml( ids ),
Descriptions = descriptions.Aggregate( ( d, next ) => next + ", " + d )
};
}
public CircleItem[] Unboxing()
{
return Util.FromXml( ItemsXml ).Select( i => new CircleItem { CircleId = int.Parse( i ), CircleDescription = i } ).ToArray();
}
}
</code></pre>
<p>As you can see, I have almost the same method implementations - <strong>Boxing</strong> and <strong>Unboxing</strong>.
I use these methods as follows:</p>
<pre><code> public BaseBox Do( BaseItem[] items )
{
BaseBox result = null;
if( items is CircleItem[] )
result = CircleBox.Boxing( items );
else if( items is TriangleItem[] )
result = TriangleBox.Boxing( items );
return result;
}
public TriangleItem[] GetTriangles()
{
TriangleBox tb = DB.GetTriangleBox(); // From database
return tb.Unboxing();
}
public CircleItem[] GetCircles()
{
CircleBox cb = DB.GetCircleBox(); // From database
return cb.Unboxing();
}
</code></pre>
<p>Can I changle something to have only one Boxing and Unboxing implementations?
What would you change in this code? What do you dislike (except catch null method's parameters)? AOP and Generics are OK if need.</p>
<p>In <strong>Do</strong>-method I have to know items's type. And I have to return empty <strong>TriangleBox</strong> or <strong>CircleBox</strong> if items.Length is 0. How I have to write my <strong>Do</strong>-method with this case?</p>
|
[] |
[
{
"body": "<p>I assume you really need to distinguish Circle and Triangle.\nAny way you can use auto-properties of base class.</p>\n\n<pre><code>public abstract class BaseItem\n{\n public int Id { get; set; }\n public string Description { get; set; }\n}\n\npublic sealed class TriangleItem : BaseItem\n{\n // Another TriangleItem class members\n}\n\npublic sealed class CircleItem : BaseItem\n{\n // Another CircleItem class members\n}\n</code></pre>\n\n<p><em>Boxing</em> mehtods differ in type of object they return, which is subtype of <em>BaseBox</em> though.\nThat means you can merge them and delegate particular boxes creation to subclasses.</p>\n\n<pre><code>public abstract class BaseBox\n{\n public string ItemsXml { get; set; }\n public string Descriptions { get; set; }\n\n public BaseBox Boxing(BaseItem[] items)\n {\n var ids = items.ToList().Select(i => i.Id.ToString()).ToArray();\n var descriptions = items.ToList().Select(i => i.Description.ToString()).ToArray();\n var box = CreateBox(Util.ToXml(ids), descriptions.Aggregate((d, next) => next + \", \" + d));\n return box;\n }\n\n public BaseItem[] Unboxing()\n {\n return Util.FromXml(ItemsXml).Select(i => CreateItem(int.Parse(i), i)).ToArray();\n }\n\n protected abstract BaseBox CreateBox(string itemsXml, string descriptions);\n\n protected abstract BaseItem CreateItem(int id, string description);\n}\n</code></pre>\n\n<p>The same can be done for <em>unboxing</em> and <em>BaseItem</em>.</p>\n\n<pre><code>public sealed class TriangleBox : BaseBox\n{\n protected override BaseBox CreateBox(string itemsXml, string descriptions)\n {\n return new TriangleBox { ItemsXml = itemsXml, Descriptions = descriptions };\n }\n\n protected override BaseItem CreateItem(int id, string description)\n {\n return new TriangleItem { Id = id, Description = description };\n }\n}\n\npublic sealed class CircleBox : BaseBox\n{\n protected override BaseBox CreateBox(string itemsXml, string descriptions)\n {\n return new CircleBox { ItemsXml = itemsXml, Descriptions = descriptions };\n }\n\n protected override BaseItem CreateItem(int id, string description)\n {\n return new CircleItem { Id = id, Description = description };\n }\n}\n</code></pre>\n\n<p><strong>Update:</strong>\n<em>Boxing</em> method should be void. And probably renamed to 'DoBoxing'.</p>\n\n<pre><code>public abstract class BaseBox\n{\n ...\n\n public void Boxing(BaseItem[] items)\n {\n var ids = items.ToList().Select(i => i.Id.ToString()).ToArray();\n var descriptions = items.ToList().Select(i => i.Description.ToString()).ToArray();\n this.ItemsXml = Util.ToXml(ids);\n this.Descriptions = descriptions.Aggregate((d, next) => next + \", \" + d);\n }\n\n ...\n}\n</code></pre>\n\n<p>And called as:</p>\n\n<pre><code> public BaseBox Do(BaseItem[] items)\n {\n ...\n\n if (result != null)\n {\n result.Boxing(items);\n }\n\n return result;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T11:31:51.847",
"Id": "47722",
"Score": "1",
"body": "`public BaseBox Boxing(BaseItem[] items)` method looks really wierd. Box creating another box? What does that even mean? It should be refactored to `void` method or a constructor (or both). I would also suggest extracting interface from ItemBase. Using references to abstract classes should be avoided, when possible, imho."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T13:42:16.533",
"Id": "47736",
"Score": "0",
"body": "Nike, agree. I just answered author's initial question on how to avoid multiple Boxing method implementation. But you are right, we should use object + void method here (instead of author's 'static'). I'll make an update..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T11:22:01.273",
"Id": "30073",
"ParentId": "30067",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "30073",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T08:47:30.920",
"Id": "30067",
"Score": "1",
"Tags": [
"c#",
"generics"
],
"Title": "How to remove duplicated code? AOP and Generics are Ok"
}
|
30067
|
<p>I am embedding my size in a Stream in the first 4 byte. When I think about it, it should be possible to do it better, but that depends.</p>
<p>Here is how I currently do it:</p>
<pre><code>bsize = ms.Length;
tcp.GetStream().Write(BitConverter.GetBytes(bsize), 0, intsize);
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize);
</code></pre>
<p>As you can see, it works and it's nothing weird. I just send 2 streams, the first being the length and the other being the data.</p>
<p>So, there aren't many things that can be done to improve or even change this.</p>
<p>But my idea is: why use 2 streams when you can probably embed the size immediately on the second, so you only need to write it once?</p>
<p>Sadly, I am not sure how to do that, or if it's even an improvement. Here is my testing code to achieve it:</p>
<pre><code>bsize = ms.Length;
ms.Write(BitConverter.GetBytes(bsize), 0, intsize);
ms.Position = 0;
tcp.GetStream().Write(ms.GetBuffer(), 0, (int)bsize+4);
</code></pre>
<p>So, I thought: why can't you just write the length to the <code>MemoryStream</code> and add it before the actual data?</p>
<p>But, it doesn't work, and I am not sure if it's adding or overwriting data. I suppose it's overwriting, which means it won't work.</p>
<p>From my testing, I think <code>Write</code> adds data to the end, which complicates things.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T17:09:50.940",
"Id": "47758",
"Score": "0",
"body": "are you getting an error when you try to write to the `tcp.GetStream()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T17:18:12.797",
"Id": "47759",
"Score": "0",
"body": "No, why should i?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T17:31:37.747",
"Id": "47760",
"Score": "0",
"body": "you said that it wasn't working the way you originally tried, I was wondering if it gave you an error or if you just weren't getting the right output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T18:18:10.057",
"Id": "47764",
"Score": "0",
"body": "Oh, you mean \"Not sure why me previous testing failed, but here are the results:\" ?, what i meant was, i got worse benchmark results, but i retried and did everything more through."
}
] |
[
{
"body": "<p>if you take and create two <code>Byte[]</code> Variables and fill the first with the information that you want to send then you can figure the size add it to the second <code>Byte</code> array and then append the information to the second array as well then just send the second <code>Byte</code> Array in your stream.</p>\n\n<p>Check out the First Answer to this Question on StackOverflow</p>\n\n<p><a href=\"https://stackoverflow.com/questions/415291/best-way-to-combine-two-or-more-byte-arrays-in-c-sharp\">Best way to combine two or more byte arrays in C#</a> </p>\n\n<p>that first answer is very detailed so you should be able to figure it into your code, he even breaks down the performance of two methods of doing it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T14:58:58.913",
"Id": "47739",
"Score": "0",
"body": "Tried it and updated my post, interesting approach, sadly it´s slower."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T15:01:27.960",
"Id": "47740",
"Score": "0",
"body": "did you try the `System.Array.Copy`? sometimes they have two options on those kinds of things for different purposes, maybe in this circumstance it might work better. another thing is that you are doing another operation in the code so it will have to take the time to do that stuff and that would be the decrease in speed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T15:56:06.690",
"Id": "47749",
"Score": "0",
"body": "Tried it now. And did a more detailed testing, and actually i think that all performance the same. Will post the results in my post. But, isn´t it possible to write the length to the MemoryStream, i mean, that is already created, and should spare time to just write to it. And i don´t get what you mean with \"another operation in the code\". Thanks"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T14:19:11.470",
"Id": "30081",
"ParentId": "30068",
"Score": "2"
}
},
{
"body": "<p>I was looking into the MemoryStream and I found this </p>\n\n<blockquote>\n <p>Except for a MemoryStream constructed with a byte[] parameter, write operations at the end of a MemoryStream expand the MemoryStream.</p>\n</blockquote>\n\n<p>on <a href=\"http://msdn.microsoft.com/en-us/library/system.io.memorystream.write.aspx\" rel=\"nofollow\">MemoryStream.Write Method</a></p>\n\n<p>I would look around a little bit on the MSDN sites that I am going to list and see if you want to change around the code that you have so that you can maybe use the <code>Byte[]</code> Parameter.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx\" rel=\"nofollow\">MemoryStream Class</a></p>\n\n<p>although it looks like most of those Constructors create non-resizable instances, whereas the a Memory Stream Created with out any Parameters ...</p>\n\n<blockquote>\n <p>Initializes a new instance of the MemoryStream class with an expandable capacity initialized to zero. </p>\n</blockquote>\n\n<p>so to me it looks like the <code>BlockCopy</code> or <code>2 streams</code> methods are the only way to go.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T18:20:13.893",
"Id": "47765",
"Score": "0",
"body": "Hmm, that´s to bad, as there is no way to do the other way around (tell the stream to read the last part, as they don´t know the end). Well, an interesting thing is that byte[] alter this for MemoyStreams. Will have to look into that. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T17:46:24.387",
"Id": "30091",
"ParentId": "30068",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "30091",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T08:53:05.473",
"Id": "30068",
"Score": "3",
"Tags": [
"c#",
"stream"
],
"Title": "Embedding of size in Stream"
}
|
30068
|
<p>I am trying to create a web crawler for student research. I have already finish it, but I would like to tell me if the way I use is the best one. (probably it isn't :p)</p>
<p>The crawler is for the cnn site and the only thing I want to get, is the text of the news.</p>
<p>Here is an example link: <a href="http://edition.cnn.com/2013/08/21/world/asia/japan-nuclear-leak-warning/index.html" rel="nofollow">link</a></p>
<p>Here is my code:</p>
<pre><code>def cnn_crawler(link):
req = urllib2.Request(link, headers={'User-Agent' : "Magic Browser"})
usock = urllib2.urlopen(req)
encoding = usock.headers.getparam('charset')
page = usock.read().decode(encoding)
usock.close()
soup = BeautifulSoup(page)
div = soup.find('div', attrs={'class': 'cnn_strycntntlft'})
text = div.find_all('p')
text.remove(soup.find('p', attrs={'class': 'cnn_strycbftrtxt'}))
final = ""
for entry in text:
final = final + entry.get_text() + " "
return final
</code></pre>
|
[] |
[
{
"body": "<p>The code looks good! A few comments:</p>\n\n<ul>\n<li>I'd use the requests library instead of urrllib2.</li>\n<li>Make sure to follow PEP8 (second line has a trailing whitespace and a space after the dictionary key).</li>\n<li>Use more semantic variable names than <code>div</code>, <code>text</code>, or <code>final</code>.</li>\n<li>If your code gets bigger, think about separating the HTTP request from the parsing code.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-11T09:40:05.500",
"Id": "31090",
"ParentId": "30069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T09:26:08.313",
"Id": "30069",
"Score": "3",
"Tags": [
"python"
],
"Title": "Crawler with BeautifulSoup"
}
|
30069
|
<p>When my Debian server deploys it can run a shell script so I wanted to make one to install postgreSQL, create a role, create two databases and then import a schema into one. </p>
<p>Can anyone please look at this code and tell me if I have done an ok job?</p>
<pre><code> # POSTGRES
apt-get install -y postgresql
echo "CREATE ROLE deploy LOGIN ENCRYPTED PASSWORD '$APP_DB_PASS';" | sudo -u postgres psql
su postgres -c "createdb db1 --owner deploy"
su postgres -c "createdb db2 --owner deploy"
service postgresql reload
# IMPORT SQL
psql --username=postgres spider < /etc/schema.sql
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T08:17:40.280",
"Id": "47830",
"Score": "0",
"body": "Personally, I like to use long-options in scripts, even for \"obvious\" options."
}
] |
[
{
"body": "<p>I recommend using <code>psql -c command</code> for the first invocation of <code>psql</code>, or better yet, just use the <code>createuser</code> command.</p>\n\n<p>For the second invocation, you might want <code>psql -f /etc/schema.sql</code>. I would also suggest using the <code>--single-transaction</code> flag, so that in the unlikely event of an error, the failure will be blatantly obvious since the <code>spider</code> database will be empty. (I assume you will also create a database named <code>spider</code> sometime before trying to import data into it.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T06:09:34.007",
"Id": "30113",
"ParentId": "30072",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30113",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T10:15:22.727",
"Id": "30072",
"Score": "3",
"Tags": [
"sql",
"bash",
"shell",
"postgresql"
],
"Title": "Automating the install of PostgreSQL from Shell"
}
|
30072
|
<p>Some adjustments a reviewer may make when reviewing a beginner's code are:</p>
<ul>
<li>Common practices and code styles that "everyone knows" may be absent, and that's OK. The reviewer will probably make note of these common practices without being "harsh".</li>
<li>Assuming that language constructs used in the code are there because those may be the only alternative the asker may know, and not because they are being used for any special reason, may lead to suggestions to use different language features or libraries.</li>
<li>Making suggestions that are easy to understand, rather than being the most efficient or optimal.</li>
<li>Pointing out common patterns (not necessarily related to the specific language) that "everyone knows", but may not be obvious to a beginner.</li>
<li>Explaining potentially new concepts in more detail than needed for more experienced programmers.</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T12:26:03.547",
"Id": "30074",
"Score": "0",
"Tags": null,
"Title": null
}
|
30074
|
Add this tag to your question to indicate that you are new to the language of your code. This will often be taken into consideration by reviewers when assessing your code.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T12:26:03.547",
"Id": "30075",
"Score": "0",
"Tags": null,
"Title": null
}
|
30075
|
<p>I wrote a simple program in Haskell which takes Hex input from stdin, converts the input to ascii and writes it to stdout. An example use:</p>
<pre><code>$ echo -n '48656c6c6f2c2043522e534521' | unhex
Hello, CR.SE!
</code></pre>
<p>And here the source code:</p>
<pre><code>import qualified Data.ByteString as B
import Data.Bits
import Data.Word
unhex :: [Word8] -> [Word8]
unhex [] = []
unhex (x:[]) = error "invalid input length"
unhex (x:y:xs) = [(shiftL (hex2val x) 4) .|. (hex2val y)] ++ unhex xs
where hex2val x = hex2val' $ (x .|. 0x20) -- lowercase char
hex2val' x
| x >= 48 && x < 48 + 10 = 0 + x - 48 -- 48 is '0' in ascii
| x >= 97 && x < 97 + 6 = 10 + x - 97 -- 97 is 'a' in ascii
| otherwise = error "invalid hex input"
main = do
input <- B.getContents
B.putStrLn $ B.pack $ unhex $ B.unpack input
</code></pre>
<p>This is one of my first Haskell programs I wrote, would be interesting to get some feedback on how to accomplish this task more the "Haskell" way. I'd like to know if this kind of error reporting is appropriate.</p>
|
[] |
[
{
"body": "<p>Calling <code>error</code> is fine for a small program like this.</p>\n\n<p>For more advanced error handling see the <a href=\"http://www.haskell.org/haskellwiki/Failure\" rel=\"nofollow\">Failure page on HaskellWiki</a>.</p>\n\n<hr>\n\n<p>Some comments about your code:</p>\n\n<pre><code>unhex (x:[]) = error \"invalid input length\"\n</code></pre>\n\n<p><code>x</code> is not used here, use this pattern instead: <code>(_:[])</code></p>\n\n<pre><code>unhex (x:y:xs) = [(shiftL (hex2val x) 4) .|. (hex2val y)] ++ unhex xs\n</code></pre>\n\n<p><code>[x] ++ xs</code> is usually written <code>x : xs</code></p>\n\n<pre><code>hex2val' $ (x .|. 0x20)\n</code></pre>\n\n<p><code>$</code> is useless here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-02T11:24:29.493",
"Id": "30687",
"ParentId": "30076",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30687",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T13:00:30.263",
"Id": "30076",
"Score": "3",
"Tags": [
"haskell"
],
"Title": "Hex to ASCII conversion in Haskell"
}
|
30076
|
<p>I have the following jquery mobile + phonegap app. I'm finding when I load the app, the images in the separate pages load pretty slowly. Any advice on how to speed up loading this app?</p>
<pre><code><html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<!-- Jquery mobile css -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css">
<!-- Jquery javascript -->
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Cordova/phonegap js -->
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<style>
#main_bg {
background: transparent url('http://onwardstate.com/wp-content/uploads/2012/11/golden-retreiver-puppies.jpeg') no-repeat left top;
}
#sortedList li {
background-color: transparent !important;
background-image: url('') !important;
}
</style>
<!-- Parse json + display -->
<script type="text/javascript">
// Wait for Cordova to load
document.addEventListener("deviceready", onDeviceReady, false);
// Cordova is loaded and it is now safe to make calls Cordova methods
function onDeviceReady() {
// Check if app has connectivity
if ( checkConnection() == 'No network connection' ) {
alert('Please connect to the internet')
}
// If app does have internet
else {
$.mobile.showPageLoadingMsg("d", "Relax, dude. We're loading today's pictures.");
loadHistory();
loadSpace();
loadEarth();
loadCity();
$.mobile.hidePageLoadingMsg();
}
}
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
return states[networkState];
}
function loadHistory(){
// $.mobile.showPageLoadingMsg("d", "Relax, dude. We're loading history's pictures.");
// Load history pictures
var history_url='http://whispering-spire-7120.herokuapp.com/category/history';
$.getJSON(history_url,function(json){
$.each(json,function(i,item){
$("#history").append('<center><img src = "'+item.url+'" style = "height: '+Number(item.old_height) * 300 / Number(item.old_width)+'px; width: 300px;"></center><p style = "margin-left:10px; margin-right:10px; font-size:15px;">'+item.title+'</p><br/>');
});
// $.mobile.hidePageLoadingMsg();
});
}
function loadEarth(){
// Load earth pictures
var earth_url='http://whispering-spire-7120.herokuapp.com/category/earth';
$.getJSON(earth_url,function(json){
$.each(json,function(i,item){
$("#earth").append('<center><img src = "'+item.url+'" style = "height: '+Number(item.old_height) * 300 / Number(item.old_width)+'px; width: 300px;"></center><p style = "margin-left:10px; margin-right:10px; font-size:15px;">'+item.title+'</p><br/>');
});
//$.mobile.hidePageLoadingMsg();
});
}
function loadSpace(){
// Load space pictures
var space_url='http://whispering-spire-7120.herokuapp.com/category/space';
$.getJSON(space_url,function(json){
$.each(json,function(i,item){
$("#space").append('<center><img src = "'+item.url+'" style = "height: '+Number(item.old_height) * 300 / Number(item.old_width)+'px; width: 300px;"></center><p style = "margin-left:10px; margin-right:10px; font-size:15px;">'+item.title+'</p><br/>');
});
//$.mobile.hidePageLoadingMsg();
});
}
function loadCity(){
// Load city pictures
var city_url='http://whispering-spire-7120.herokuapp.com/category/city';
$.getJSON(city_url,function(json){
$.each(json,function(i,item){
$("#city").append('<center><img src = "'+item.url+'" style = "height: '+Number(item.old_height) * 300 / Number(item.old_width)+'px; width: 300px;"></center><p style = "margin-left:10px; margin-right:10px; font-size:15px;">'+item.title+'</p><br/>');
});
//$.mobile.hidePageLoadingMsg();
});
}
$(document).ready(function(){
//using deviceonready instead
});
</script>
<!-- End parsing json + display -->
<title> TablePics - Home</title>
</head>
<body>
<!-- Beginning of page1 -->
<div data-role="page" data-theme="c" id="main_bg">
<!-- Header -->
<div data-role="header" data-theme="b">
<h1>TablePics</h1>
</div>
<!-- Content -->
<div data-role="content">
<!-- Display results of parsing json here -->
<ul data-role="listview" id="sortedList">
<li><a href = "#city" data-prefetch>City</a></li>
<li><a href="#earth" data-prefetch>Earth</a></li>
<li><a href="#history" data-prefetch>History</a></li>
<li><a href = "#space">Space</a></li>
</ul>
</div>
</div>
<!-- End of page1 -->
<!-- Beginning of History -->
<div data-role="page" data-theme="c" id = "history" data-add-back-btn="true">
<!-- Header -->
<div data-role="header" data-theme="b">
<h1>History</h1>
</div>
<!-- Content -->
<div data-role="content" id = "history">
</div>
</div>
<!-- End of history -->
<!-- Beginning of Earth -->
<div data-role="page" data-theme="c" id = "earth" data-add-back-btn="true">
<!-- Header -->
<div data-role="header" data-theme="b">
<h1>Earth</h1>
</div>
<!-- Content -->
<div data-role="content" id = "earth">
</div>
</div>
<!-- End of earth -->
<!-- Beginning of Space -->
<div data-role="page" data-theme="c" id = "space" data-add-back-btn="true">
<!-- Header -->
<div data-role="header" data-theme="b">
<h1>Space</h1>
</div>
<!-- Content -->
<div data-role="content" id = "space">
</div>
</div>
<!-- End of space -->
<!-- Beginning of city -->
<div data-role="page" data-theme="c" id = "city" data-add-back-btn="true">
<!-- Header -->
<div data-role="header" data-theme="b">
<h1>City</h1>
</div>
<!-- Content -->
<div data-role="content" id = "city">
</div>
</div>
<!-- End of city -->
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T13:27:54.420",
"Id": "47847",
"Score": "0",
"body": "Can you reduce your code to only the parts concerned?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-18T20:26:56.083",
"Id": "109355",
"Score": "5",
"body": "This is off-topic, but we are a friendly community, so I just wanted to point out that the `golden-retreiver-puppies.jpeg` is 384Kb. That is far too large, especially for mobile apps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-18T21:35:39.467",
"Id": "109374",
"Score": "0",
"body": "This Question is being talked about on Meta, http://meta.codereview.stackexchange.com/q/2317/18427"
}
] |
[
{
"body": "<p>Instead of doing a separate function for <code>loadspace</code> and <code>loadcity</code> and <code>loadearth</code> could you do a function for <code>LoadCanvas</code>? or something like that, it just seems like you are writing the same code for each load, see if you can make it one function that you feed the URL to, I think that would clean up some of your code and make it more maintainable. </p>\n\n<p>If you had one function for loading these <code>Templates</code> then you could add Templates a lot easier in your code. </p>\n\n<p>Here is what the function might look like</p>\n\n<pre><code>function loadArea(url, elementID){\n $.getJSON(url ,function(json){\n $.each(json,function(i,item){\n $(\"#\" + elementID).append('<center><img src = \"'+item.url+'\" style = \"height: '+Number(item.old_height) * 300 / Number(item.old_width)+'px; width: 300px;\"></center><p style = \"margin-left:10px; margin-right:10px; font-size:15px;\">'+item.title+'</p><br/>');\n });\n });\n}\n</code></pre>\n\n<p>Then all you have to do is call the function with the URL and the ElementID when you want these to load. This will make it much easier when adding new pages, this DRYs things out a bit.</p>\n\n<p><strong>AND</strong></p>\n\n<p>Try only loading the images that they want loaded to start out, that would speed up the initial load of the application, Load the rest on Demand.</p>\n\n<p>I would also remove the commented code as well, if it is dead, bury it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T14:34:34.403",
"Id": "30136",
"ParentId": "30080",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-22T14:15:11.117",
"Id": "30080",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"performance",
"json",
"phonegap"
],
"Title": "Speed up slow loading images?"
}
|
30080
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.