body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
VHDL (Very High Speed Integrated Circuit HDL) is a hardware description language (HDL) maintained by the 'VHDL Analysis and Standardization Group (VASG) and standardized as 'IEEE Standard 1076'.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T08:54:32.220",
"Id": "28811",
"Score": "0",
"Tags": null,
"Title": null
}
|
28811
|
<p>Searching is one of the most common and important tasks in Computer Science.</p>
<p>The most basic search algorithm is a linear search (also called "sequential search"). Each item in a collection of data is examined in sequence until the sought item is found.</p>
<p>If the collection in question has already been sorted then a more efficient <a href="/questions/tagged/binary-search" class="post-tag" title="show questions tagged 'binary-search'" rel="tag">binary-search</a> is possible.</p>
<p>Search can become more complex when, rather than finding one instance of a specific item, we want to find all items meeting a certain set of criteria. For instance a <a href="/questions/tagged/sql" class="post-tag" title="show questions tagged 'sql'" rel="tag">sql</a> query can specify extremely complex search criteria, and much of relational database design involves the planning of an efficient way to perform those searches.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T08:58:22.177",
"Id": "28813",
"Score": "0",
"Tags": null,
"Title": null
}
|
28813
|
This tag is for questions about search algorithms, tools, and technologies.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T08:58:22.177",
"Id": "28814",
"Score": "0",
"Tags": null,
"Title": null
}
|
28814
|
<p>From the <a href="http://www.numpy.org/" rel="nofollow">NumPy homepage</a>:</p>
<p>NumPy is the fundamental package for scientific computing with Python. It contains among other things:</p>
<ul>
<li>A powerful N-dimensional array object.</li>
<li>Sophisticated (broadcasting) functions.</li>
<li>Tools for integrating C/C++ and Fortran code.</li>
<li>Useful linear algebra, Fourier transform, and random number capabilities.</li>
</ul>
<p>Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.</p>
<p>NumPy is released under the BSD license, enabling reuse with few restrictions.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T09:02:10.753",
"Id": "28815",
"Score": "0",
"Tags": null,
"Title": null
}
|
28815
|
NumPy is the fundamental package for scientific computing with the programming language Python.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T09:02:10.753",
"Id": "28816",
"Score": "0",
"Tags": null,
"Title": null
}
|
28816
|
<p>A dictionary is commonly implemented as a <a href="http://en.wikipedia.org/wiki/Hash_table" rel="nofollow">hash map</a> which allow <code>O(1)</code> amortized lookup. Alternatively they may be implemented as a sorted list, with lookup requiring a binary search and making the lookup <code>O(log N)</code> amortized instead.</p>
<p>When tagging a question with <a href="/questions/tagged/dictionary" class="post-tag" title="show questions tagged 'dictionary'" rel="tag">dictionary</a>, be sure to tag it with the language being used as well.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T09:06:06.647",
"Id": "28817",
"Score": "0",
"Tags": null,
"Title": null
}
|
28817
|
A dictionary, in computer science, is a data structure that maps keys to values such that given a key its corresponding value can be efficiently retrieved.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T09:06:06.647",
"Id": "28818",
"Score": "0",
"Tags": null,
"Title": null
}
|
28818
|
<p><strong>Arduino</strong> is a single-board microcontroller to make using electronics in multidisciplinary projects more accessible. </p>
<p>The hardware consists of an open-source hardware board designed around an 8-bit Atmel AVR microcontroller, or a 32-bit Atmel ARM. </p>
<p>The software consists of a standard programming language compiler and a boot loader that executes on the microcontroller.</p>
<p><strong>Arduino</strong> boards can be purchased pre-assembled or as do-it-yourself kits. </p>
<p>Hardware design information is available for those who would like to assemble an Arduino by hand. </p>
<p>It was estimated in mid-2011 that over 300,000 official Arduinos had been commercially produced</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T09:07:51.467",
"Id": "28819",
"Score": "0",
"Tags": null,
"Title": null
}
|
28819
|
Arduino is an open-source electronics prototyping platform.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T09:07:51.467",
"Id": "28820",
"Score": "0",
"Tags": null,
"Title": null
}
|
28820
|
<p>I'm currently working through a series of bugs in an application. Our application is written in C#/ASP.NET (on the server) and HTML/CSS/JavaScript (on the client). We are using ELMAH to log any uncaught exceptions in the system so that we may identify it later and fix it, which is what I'm currently doing.</p>
<p>The way ELMAH works is to log any uncaught exception, so once you catch and handle the exception, it can be omitted from ELMAH.</p>
<p><a href="https://stackoverflow.com/questions/17748314/elmah-filtering-exceptions-thrown-to-web-clients-browser">This article</a> closely relates to a question I asked here on Stack Overflow.</p>
<p>To give a little bit of insight into this article, ELMAH logs uncaught exceptions, but sometimes you have certain scenarios where the exception is thrown to the browser and handled there. ELMAH doesn't know that it's being handled elsewhere, so it still logs the exception.</p>
<p>In our application, we use WCF web services to send JSON data back to the client. Say for example one of those services fails and throws an exception, we send that exception back to the browser and handle it there (and as stated, ELMAH still logs it).</p>
<p>So I had this idea, which might only apply to a small set of use cases, but as an idea, I wanted to know what the community thought of it.</p>
<p>As OO programmers know, methods/functions have a return type (or <code>void</code>).</p>
<p><strong>Example</strong></p>
<blockquote>
<pre><code>public void SayHello()
{
Print("Hello");
}
public string GetMyName()
{
return "Joe Bloggs";
}
</code></pre>
</blockquote>
<p>All well and good so far, but what if I wanted my method/function to return either a value, or an exception if one was to occur? I can do this in C# using the dynamic keyword.</p>
<p><strong>Example</strong></p>
<blockquote>
<pre><code>public dynamic GetMyNameOrCryLikeABaby()
{
try
{
return DoSomethingWrong(); // might throw an exception, but should return a string.
}
catch(Exception ex)
{
return ex;
}
}
</code></pre>
</blockquote>
<p>Personally I don't like this approach. I don't think it is a good use of the dynamic keyword, and it involves the developer adding in additional code to check whether the return value was (in this example) a string, or an Exception.</p>
<p>The idea I came up with to get around this was based somewhat on .NET's <code>Nullable<T></code> structure. The idea here being that a ValueType wrapped in a <code>Nullable<T></code> (e.g. <code>Nullable<int></code>) can return null. </p>
<p>The structure below has some interesting characteristics! The aim was to write a structure that could implicitly be cast to the expected type, but could also return an exception, should one occur. This structure is called "Exceptable" meaning it might hold an exception.</p>
<p><strong><code>Exceptable<T></code> Source Code</strong></p>
<pre><code>/// <summary>
/// Represents a generic type that can also hold an associated exception.
/// </summary>
/// <typeparam name="T">The type of this Exceptable object.</typeparam>
public struct Exceptable<T>
{
/// <summary>
/// Gets or sets the value of this object.
/// </summary>
public T Value { get; set; }
/// <summary>
/// Gets or sets an exception that may occur when using this type.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Gets a value indicating whether this object has a value.
/// </summary>
public Boolean HasValue
{
get { return this.Value != null; }
}
/// <summary>
/// Gets a value indicating whether this object has an exception.
/// </summary>
public Boolean HasException
{
get
{
return this.Exception != null;
}
}
/// <summary>
/// Allows implicit casting between a raw type, and an Exceptable type.
/// </summary>
/// <param name="value">The exceptable value to convert to a raw type.</param>
/// <returns>A raw type</returns>
public static implicit operator T(Exceptable<T> value)
{
return value.Value;
}
/// <summary>
/// Allows implicit casting between an Exceptable type and a raw type.
/// </summary>
/// <param name="value">The raw type to convert to an excepable type.</param>
/// <returns>An excepable type.</returns>
public static implicit operator Exceptable<T>(T value)
{
return new Exceptable<T>
{
Value = value
};
}
}
</code></pre>
<p>So as you can see here, it wraps the expected type into <code>Exceptable</code> as a generic type and provides implicit conversion between <code>Exceptable<T></code> and <code>T</code>.</p>
<p><strong>Use Cases</strong></p>
<pre><code>Exceptable<string> name = "Joe Bloggs";
Exceptable<int> age = 26;
public static Exceptable<string> GetMyNameOrCryLikeABaby()
{
Exceptable<string> result = String.Empty;
try
{
result = DoSomethingWrong() // might throw an exception but should return a string.
}
catch(Exception ex)
{
result.Exception = ex;
}
return result;
}
string name = GetMyNameOrCryLikeABaby();
Exceptable<string> nameOrException = GetMyNameOrCryLikeABaby();
</code></pre>
<p>As you can see from the examples above, I can assign values directly to <code>Exceptable<T></code>. I can also use it as a return type for a method, and due to implicit conversion, I can choose whether to return just the associated value of the structure, or the structure itself, in case I want to handle the associated exception.</p>
<p>What do you think?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T13:40:37.247",
"Id": "45319",
"Score": "0",
"body": "Interesting - you seem to have independently re-invented the [error monad](http://www.haskell.org/haskellwiki/Exception#Exception_monad) - well done sir!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T13:46:02.380",
"Id": "45321",
"Score": "0",
"body": "@MattDavey Technically, this is not a monad, since it doesn't have `bind`, or anything similar."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T14:58:34.127",
"Id": "45331",
"Score": "0",
"body": "See [this question](http://stackoverflow.com/q/17705500/298754) and see if it helps."
}
] |
[
{
"body": "<p>I think that you are setting yourself up for horrible spaghetti code down the line if you don't catch and throw exceptions like the Lord intended.</p>\n\n<p>If you absolutely INSIST on returning an error, I would suggest adding two OUT parameters to the methods:</p>\n\n<pre><code>string myFunkyFunction(string arg, out bool hasException, out string exceptionMessage/*or you could pass an actual Exception if that's your cup of tea*/)\n{\n try{\n //code here\n }\n catch(Exception ex)\n {\n hasException = true;\n exceptionMessage = ex.Message;\n }\n\n if(!hasException)\n {\n hasException = false;\n exceptionMessage = \"\";\n }\n return \"something\";\n\n}\n</code></pre>\n\n<p>then, IF there is an exception, do something.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T13:12:22.777",
"Id": "45317",
"Score": "0",
"body": "I think it's a bad idea to use just `string` instead of `Exception`, `Exception` can contain quite a lot useful data. And the `hasException` parameter is not useful, the exception parameter should be `null` if there is no exception (certainly not `\"\"`) and checking that is enough."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T14:34:38.003",
"Id": "45325",
"Score": "0",
"body": "Well, yes, Exception is more useful, which is why I put that in a comment. Also, Visual Studio will complain if you don't assign something to an out parameter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T15:17:01.663",
"Id": "45334",
"Score": "0",
"body": "I meant that having `out Exception exception` would be better than `string`. And you have to assign something, but that something can be `null`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T15:18:09.400",
"Id": "45335",
"Score": "0",
"body": "fair enough. I did mention the option of returning an exception in the comment to the right of the method signature."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T11:44:37.740",
"Id": "28825",
"ParentId": "28824",
"Score": "0"
}
},
{
"body": "<ol>\n<li><p>Doing this instead of working with exceptions the usual way (<code>throw</code> and <code>catch</code>) is a big code smell. I think I would need a really good justification for this and I'm not sure slightly improved logging is that. I would try looking more into other possibilities, like filtering <code>Exception</code>s based on their type, or something like that.</p></li>\n<li><p>This code comes close to reinventing <a href=\"http://www.haskell.org/haskellwiki/Exception#Exception_monad\" rel=\"nofollow noreferrer\">the <code>Exception</code> monad</a>. You might want to study that for some ideas.</p></li>\n<li><p>Your type should protect its invariants. If it's supposed to contain a value or an exception, but not both, you shouldn't allow the user to use the type the wrong way.</p>\n\n<p>A similar principle also applies to reading: if a value is not present, <code>Value</code> should throw an exception, instead of silently returning the default value. The same probably applies to <code>Exception</code>.</p></li>\n<li><p>For a simple type like this, it often makes sense to make it immutable. Also, <a href=\"https://stackoverflow.com/q/441309/41071\"><em>mutable value types are evil</em></a>, you should never use them without a really good reason (and I don't see that reason here).</p></li>\n<li><p>You should be very careful with implicit conversions. An implicit conversion should never lead to loss of information and it should be always valid. In your case, that's not true for the case when <code>Exceptable</code> contains an exception, because then the implicit conversion silently returns the default value.</p>\n\n<p>So, if you want to have a conversion from <code>Exceptable<T></code> to <code>T</code>, it should be explicit and it should throw when an exception is present.</p></li>\n<li><p>You're checking <code>Value</code> against <code>null</code>. This is a bad idea for several reasons:</p>\n\n<ol>\n<li><p>In some cases, <code>null</code> can be a legitimate return value that does not indicate an error. Your type won't handle that correctly.</p></li>\n<li><p>If <code>T</code> is a non-nullable value type, then the default value is not <code>null</code>, so <code>HasValue</code> won't work correctly. If your type is meant to support only reference types, you should make that explicit by adding the constraint <code>where T : class</code> to it.</p></li>\n</ol></li>\n<li><p>The name “exceptable” is not great. Though I'm not sure what would be a better name.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T14:48:34.240",
"Id": "45328",
"Score": "0",
"body": "Thanks for this response. Based on your comments, I'm feeling that there is very little scope to use this...so maybe worth scrapping (but leaving here for future reference)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T16:04:41.127",
"Id": "45341",
"Score": "0",
"body": "@svick - Item #7 - How about \"Exceptionable\" ?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T13:19:29.387",
"Id": "28827",
"ParentId": "28824",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "28827",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T11:03:33.670",
"Id": "28824",
"Score": "4",
"Tags": [
"c#",
"object-oriented",
".net",
"asp.net",
"error-handling"
],
"Title": "OOP methods/functions that can return a value or an exception"
}
|
28824
|
<p>Here is some code I've created to generate and use a list of prime numbers. This is some of the first Common Lisp code I've written, and I'd be grateful for any comments regarding style and its use or misuse of common idioms. I'm not really interested in improving the algorithm, but in making my implementation readable and efficient.</p>
<pre><code> ;;; Estimate the number of primes below a number n
(defun primes-pi (n)
(ceiling (/ n (- (log n) 1))))
;;; (A high) estimate of the number below which there are n primes, this is the
;;; reverse of primes-pi
(defun primes-n (n)
(* n (ceiling (+ (log n) 1))))
;;; Code to generate prime numbers
(defun plist (n)
(let (;; An array of booleams flags for the sieve
(arr (make-array (+ n 1) :element-type 'boolean :initial-element t))
;; The first prime the loop below will handle
(p 3)
;; results is used to build the list of primes
(result nil))
;; 0 isn't prime
(setf (aref arr 0) nil)
;; 1 isn't prime
(setf (aref arr 1) nil)
;; 2 is primes
(push 2 result)
;; Now the special cases are out of the way start sieving for new primes
;; when p is nil the loop has reached the end of the arr array
(do () ((eq nil p))
;; add p to the list of primes
(push p result)
;; Remove all multiples of p from the array
(loop for i from (+ p p) to n by p
do (setf (aref arr i) nil))
;; search forward in the array to the next non nil entry, this will be
;; the next prime.
(setf p (loop for i from (+ 2 p) to n by 2
when (eq t (svref arr i))
return i)))
;; reverse the list to get the primes in ascending order
;; not really needed if only using the list in build-is-prime?
(nreverse result)))
;;; This function creates and returns a closure that allows testing
;;; for primeality of at least the first n prime number
(defun build-is-prime (n)
(let ((prime-table (make-hash-table :size n)))
;; Populate the hash table
(loop for i in (plist (primes-n n)) do
(setf (gethash i prime-table) t))
;; Lambda to test for presence of p in the hash table
(lambda (p)
(gethash p prime-table)
)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-09T04:52:15.840",
"Id": "196241",
"Score": "0",
"body": "Good, but I'm not understanding since you have used very heavy language. It will be easier if you use simple language which can be understood by common people."
}
] |
[
{
"body": "<p>for one thing, <code>(eq nil p)</code> is usually written <code>(not p)</code>. </p>\n\n<p>the variable <code>p</code> participating only in that <code>do</code> should be declared inside it, not outside it in the enclosing <code>let</code>. Everything should be in its proper place. Same with <code>result</code> - make <code>do</code> your last form and use the return clause of <code>do</code> to return the result:</p>\n\n<pre><code>(defun plist (n)\n (let (\n (arr (make-array (+ n 1) :element-type 'boolean :initial-element t))\n )\n (setf (aref arr 0) nil)\n (setf (aref arr 1) nil)\n\n (do ( (p 3) \n (result (list 2))) \n ( (not p) (nreverse result))\n\n (push p result) ; and what if n==2 ??\n ....\n )))\n</code></pre>\n\n<p>Don't mix <code>aref</code>s and <code>svref</code>s, be consistent. Again, the test <code>(when (eq t (svref arr i)) ...)</code> would normally be written just as <code>(when (svref arr i) ...)</code>.</p>\n\n<p>Your <code>do</code> loop is a little buggy: it adds 3 unconditionally, even if <code>n < 3</code>. Reorganize. Or, and since you don't inspect them, no need to mark 0 and 1 as non-primes, just like we don't bother with the evens. Which means we get to declare the array inside the <code>do</code>'s scope too:</p>\n\n<pre><code>(defun plist (n)\n (do ((arr (make-array (+ n 1) :element-type 'boolean :initial-element t))\n (result (list 2))\n (p 3 (+ p 2))) \n ((> p n)\n (nreverse result)) ; return form\n (when (aref arr p)\n (push p result)\n (if (<= p (/ n p)) \n (loop for i from (* p p) to n by (* 2 p)\n do (setf (aref arr i) nil))))))\n</code></pre>\n\n<p>An algorithmic improvement, though you didn't want one: start eliminating multiples of <code>p</code> from <code>(* p p)</code>, not from <code>(+ p p)</code>, and increment by steps of <code>(* 2 p)</code> among odds only, for twice the speed. </p>\n\n<p>Now that the code is short and compact, we see one more possibility for improvement: if we hit the termination condition, no need to recheck it. Finally, add the documentation string there too:</p>\n\n<pre><code>(defun plist (n)\n \"return the list of primes not greater than n. \n build it by means of the sieve of Eratosthenes.\"\n (do ((arr (make-array (+ n 1) :element-type 'boolean :initial-element t))\n (result (list 2))\n (p 3 (+ p 2))) ; a candidate possible prime\n ((> p (/ n p))\n (nconc (nreverse result)\n (loop for i from p to n by 2 if (aref arr i) collect i)))\n (when (aref arr p) ; not marked as composite: p is prime\n (push p result) \n (loop for i from (* p p) to n by (* 2 p) ; mark the multiples\n do (setf (aref arr i) nil)))))\n</code></pre>\n\n<p>I don't find micro-commenting adding much clarity (even the opposite), but YMMV. Variable names like <code>arr</code> and <code>result</code> are self-documenting. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T15:44:05.210",
"Id": "28840",
"ParentId": "28826",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28840",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T12:46:47.657",
"Id": "28826",
"Score": "6",
"Tags": [
"primes",
"common-lisp"
],
"Title": "Generating and using a list of prime numbers"
}
|
28826
|
<p>I'm writing a C++ wrapper library for sockets which will hopefully be cross-platform.</p>
<p>It's basically two headers:</p>
<ul>
<li>mizaru.hpp, which contains the wrapper classes themselves.</li>
<li>trans_layer.hpp, which provides platform agnostic function prototypes. So far they only support Linux and TCP sockets.</li>
</ul>
<p>I think that I'm using a lot of exceptions and am not sure of a better approach for handling errors. I'm also not sure about the general architecture of the library, especially relationship between <code>SyncSocket</code> classes.</p>
<p>My main issue is the error-handling approach, but any advice on how to write cleaner code with better comments is greatly appreciated.</p>
<p>Questions:</p>
<ol>
<li><p>Should I change the way errors are handled? Are there too many exceptions being thrown?</p></li>
<li><p>Is this code considered clean?</p></li>
<li><p>Should I rethink the general architecture of the library, or does it make sense?</p></li>
</ol>
<p><strong>Note</strong>: it is still in early development.</p>
<ul>
<li><a href="https://gist.github.com/ah450/6053871" rel="nofollow">gist containing implementation</a></li>
<li><a href="https://github.com/ah450/mizaru" rel="nofollow">GitHub repo containing everything</a></li>
</ul>
<p>The header files:</p>
<p><strong>mizaru.hpp</strong></p>
<pre><code> #ifndef __MIZARU__HPP__
#define __MIZARU__HPP__
#include <string>
#include <memory>
#include <vector>
#include <mutex>
#include <chrono>
#include "mizaru_exceptions.hpp"
#include "types.hpp"
namespace mizaru
{
class IPv4
{
public:
/**
*@warning param must be in host order.
*/
explicit IPv4 ( unsigned int host_order );
explicit IPv4 ( std::string &string_rep );
explicit IPv4 ( std::string &&string_rep );
uint32_t get() const
{
return data;
}
private:
uint32_t data;
};
/**
*@brief Base class for all sockets.
*@warning must be unlocked before destroyed.
*@sa SyncSocketTCP
*/
class SyncSocket
{
public:
bool try_lock() noexcept;
bool try_read_lock() noexcept;
bool try_write_lock() noexcept;
void lock() noexcept;
void read_lock() noexcept;
void write_lock() noexcept;
void unlock() noexcept;
void read_unlock() noexcept;
void write_unlock() noexcept;
/**
*@brief this is a blocking read function.
*@param[in] remove if false a subsequent read would read the same data.
*@return number of bytes read.
*/
unsigned int read ( byte_buffer &buffer, const unsigned int length, bool remove = true) throw ( SocketClosedException,
SystemException, RemoteHungUpException );
/**
*@brief non blocking read function.
*@param[in] wait_time maximum ammount of time to wait in milliseconds specify zero (or zero_time static member) for truely
* non-blocking.
*@param[in] remove if false a subsequent read would read the same data.
*/
unsigned int read ( byte_buffer &buffer, const unsigned int length, const std::chrono::milliseconds &wait_time,
bool remove = true) throw ( SocketClosedException,
SystemException, RemoteHungUpException );
/**
*@brief blocking write function.
*@return number of bytes written
*/
unsigned int write ( const byte_buffer &buffer) throw ( SocketClosedException, SystemException, BufferTooLargeException,
RemoteHungUpException );
/**
*@brief non-blocking write function.
*@return number of bytes written
*@param[in] wait_time maximum ammount of time to wait in milliseconds specify zero (or zero_time static member) for truely
* non-blocking.
*
*/
unsigned int write ( const byte_buffer &buffer, const std::chrono::milliseconds &wait_time ) throw ( SocketClosedException,
SystemException, BufferTooLargeException,
RemoteHungUpException );
bool poll_read ( const std::chrono::milliseconds &wait_time = zero_time ) throw ( SystemException, SocketClosedException );
bool poll_write ( const std::chrono::milliseconds &wait_time = zero_time ) throw ( SystemException, SocketClosedException );
bool poll_read_write ( const std::chrono::milliseconds &wait_time = zero_time ) throw ( SystemException, SocketClosedException );
virtual ~SyncSocket();
/**
*@brief represents a wait_time of zero
*/
static const std::chrono::milliseconds zero_time;
protected:
SyncSocket ( const IPv4 &ip, const port_t port_number, bool udp ) throw ( SystemException );
SyncSocket ( const SyncSocket &to_copy ) noexcept;
SyncSocket ( SyncSocket && to_move ) noexcept;
native_socket_t handle;
port_t port_number;
IPv4 ip;
std::shared_ptr<bool>closed;
private:
std::shared_ptr<std::recursive_mutex> read_mutex, write_mutex;
};
class SyncSocketTCP : public SyncSocket
{
public:
SyncSocketTCP ( const IPv4 &ip, const port_t port_number, bool keep_alive = false ) throw ( SystemException, AddressException,ConnectionRefusedException,
ConnectionTimedOutException, NetworkUnreachableException,
FirewallException );
SyncSocketTCP ( const SyncSocketTCP &to_copy ) noexcept;
SyncSocketTCP ( SyncSocketTCP &&to_move ) noexcept;
};
class ServSockTCP
{
};
class SyncSockUDP : public SyncSocket
{
public:
};
}
#endif /* __MIZARU__HPP__ */
</code></pre>
<p><code>trans_layer.hpp</code></p>
<pre><code> #ifndef __TRANS_LAYER_HPP__
#define __TRANS_LAYER_HPP__
#include "mizaru.hpp"
/**
*@file trans_layer.hpp
*@brief provides low level interface for creating and manipulating sockets.
*/
namespace mizaru
{
/**
*@namespace trans trans_layer.hpp
*@brief contains all low level socket maniuplation functions.
*/
namespace trans
{
enum Protocol {TCP, UDP};
enum Type {IPv4, IPv6};
enum PollType {POLL_READ, POLL_WRITE, POLL_RW};
/**
*@brief Represents accepted sockets.
*/
struct accepted_socket
{
mizaru::IPv4 ip;
native_socket_t socket;
port_t port;
};
native_socket_t create_socket ( Protocol p, Type t ) throw ( SystemException );
void close_socket ( native_socket_t socket ) noexcept;
bool poll ( native_socket_t socket, PollType type, const std::chrono::milliseconds &wait_time ) throw ( SystemException );
/**
*@return number of bytes read.
*@param[in] remove if not set later calles to read on same socket will return same data
*/
unsigned int read ( native_socket_t socket, byte_buffer &buffer, const unsigned int length, bool remove )
throw ( SystemException, RemoteHungUpException );
/**
*@return number of bytes written.
*/
unsigned int write ( native_socket_t socket, const byte_buffer &buffer ) throw ( SystemException, RemoteHungUpException,
BufferTooLargeException );
/**
*@brief binds a socket to an address.
*not used directly by TCP sockets. UDP sockets will be ready for read after calling this function.
*/
void bind ( native_socket_t socket, const mizaru::IPv4 &ip, const port_t port ) throw ( AddressException, AddressInUseException, SystemException );
/**
*@brief connects a TCP or UDP Socket to a remote address and port.
* TCP will be ready for read/write , UDP for write only
*/
void connect ( native_socket_t socket, const mizaru::IPv4 &ip, const port_t port ) throw ( AddressException, ConnectionRefusedException,
ConnectionTimedOutException, NetworkUnreachableException,
SystemException, FirewallException );
/**
*@brief must be called before accept.
*@sa accept
*@param[in] port network byte order
*@param[in] queue_length listen queue_length
*/
void prep_tcp_for_listen ( native_socket_t socket, const port_t port, int queue_length ) throw ( AddressException, AddressInUseException, SystemException );
/**
*@brief accepts sockets (TCP ONLY).
*@detail acc will contain the representation of a connected (ready for IO) TCP socket handle representing the client
*and the peer's addr and port.
*@warning must be preped for listen
*@sa prep_tcp_for_listen
*/
void accept ( native_socket_t socket, accepted_socket &acc ) throw ( SystemException, FirewallException );
void set_keep_alive ( mizaru::native_socket_t socket ) throw ( SystemException );
}
}
#endif /* __TRANS_LAYER_HPP__ */
</code></pre>
<p>Related header:</p>
<p><strong>types.hpp</strong></p>
<pre><code> #ifndef __TYPES_HPP__
#define __TYPES_HPP__
namespace mizaru
{
typedef std::vector<unsigned char> byte_buffer;
typedef uint16_t port_t;
#ifdef __linux__
typedef int native_socket_t;
#endif
}
#endif /* __TYPES_HPP__ */
</code></pre>
<p><strong>mizaru_exceptions.hpp</strong></p>
<pre><code> #ifndef __MIZARU_EXCEPTIONS_HPP__
#define __MIZARU_EXCEPTIONS_HPP__
#include <stdexcept>
#include <string>
/**
*@file mizaru_exceptions.hpp
*@brief defines various exceptions thrown by Mizaru functions.
*/
namespace mizaru
{
class MizaruException : public std::runtime_error
{
public:
MizaruException ( std::string &msg ) : std::runtime_error ( msg ) {}
};
/**
*@brief This exception indicates a system exception, the specific error
* is platform specific and could indicate something like maximem ammount of files opened
* , process file table overflow , insufficient kernal memory etc.
*/
class SystemException : public MizaruException
{
public:
SystemException ( std::string &msg ) : MizaruException ( msg ) {}
};
class BufferTooLargeException : public SystemException
{
public:
BufferTooLargeException ( std::string &msg ) : SystemException ( msg ) {}
};
class AddressException : public MizaruException
{
public:
AddressException ( std::string &msg ) : MizaruException ( msg ) {}
};
/**
*@brief thrown if local port already in use
*/
class AddressInUseException : public AddressException
{
public:
AddressInUseException ( std::string &msg ) : AddressException ( msg ) {}
};
class ConnectionException : public MizaruException
{
public:
ConnectionException ( std::string &msg ) : MizaruException ( msg ) {}
};
class ConnectionRefusedException : public ConnectionException
{
public:
ConnectionRefusedException ( std::string &msg ) : ConnectionException ( msg ) {}
};
class ConnectionTimedOutException : public ConnectionException
{
public:
ConnectionTimedOutException ( std::string &msg ) : ConnectionException ( msg ) {}
};
class NetworkUnreachableException : public ConnectionException
{
public:
NetworkUnreachableException ( std::string &msg ) : ConnectionException ( msg ) {}
};
class RemoteHungUpException : public ConnectionException
{
public:
RemoteHungUpException ( std::string &msg ) : ConnectionException ( msg ) {}
};
class SocketClosedException : public MizaruException
{
public:
SocketClosedException ( std::string &msg ) : MizaruException ( msg ) {}
};
class FirewallException : public ConnectionException
{
public:
FirewallException ( std::string &msg ) : ConnectionException ( msg ) {}
};
}
#endif /* __MIZARU_EXCEPTIONS_HPP__ */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T14:29:30.863",
"Id": "45324",
"Score": "2",
"body": "I removed the licence notifications, as they are just clutter for this site. Note that by posting content you are releasing it under [cc-by-sa](http://blog.stackoverflow.com/2009/06/attribution-required/). If you don't agree to this, you should delete your post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T04:57:31.890",
"Id": "45374",
"Score": "0",
"body": "Not another one. Use the boost one."
}
] |
[
{
"body": "<p>I don't have time to give any meaningful feedback about your design at the moment. I'll give some general feedback and try to answer your question about your error handling, however.</p>\n\n<h3>General feedback</h3>\n\n<ul>\n<li>Herb Sutter has <a href=\"http://www.gotw.ca/publications/mill22.htm\" rel=\"nofollow noreferrer\">this to say about exception specifications</a>:</li>\n</ul>\n\n<blockquote>\n <p>Moral #1: Never write an exception specification.</p>\n \n <p>Moral #2: Except possibly an empty one, but if I were you I’d avoid even that.</p>\n</blockquote>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/228797/14065\">Don't use double underscores in preprocessor</a> <code>#define</code>s (including include guards). Names that contain double underscores are reserved. Names that begin with an underscore followed by a capital letter are also reserved.</li>\n<li>Sort your <code>#include</code>s alphabetically. <a href=\"http://blog.knatten.org/2010/07/01/the-order-of-include-directives-matter/\" rel=\"nofollow noreferrer\">Include your own headers before standard or library headers headers.</a></li>\n<li>Shouldn't your exception constructors take <code>std::string const&</code> instead of just <code>std::string&</code>?</li>\n<li>Consider using stream operations (<code>op<<</code> and <code>op>></code>) instead of <code>write</code> and <code>read</code> respectively.</li>\n<li>Avoid <code>bool</code> in interfaces / as function parameter. It causes code that is hard to read and hard to use correctly.</li>\n<li>You are using both <code>uint32_t</code> and <code>unsigned int</code> - you should probably be consistent and use only one or the other. Remember to include <code><cstdint></code> when using <code>std::uint32_t</code>. </li>\n</ul>\n\n<h3>Exceptions</h3>\n\n<p>Using exceptions has a <strong>cost</strong>. It's fairly expensive in terms of speed, and should generally only be used for <strong>exceptional circumstances</strong>. Most of your exceptions <em>seem</em> reasonable.</p>\n\n<p>I don't think you should worry about having too many exceptions. There's no particular increased cost of having many exception classes, unless you get to the point where code maintenance costs are increasing or readability is decreasing. You don't seem to be anywhere near that point. As long as your exception hierarchy gives you sufficient granularity while maintaining readability, like it seems your hierarchy does, you'll be fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T04:51:20.583",
"Id": "45371",
"Score": "0",
"body": "Exceptions are slow compared to what? Yes they are slower but if there is an error not significantly compared to normal exiting a function. Now if you use it as normal flow control then yes it is very slow compared to alternatives so don't use as flow control. Using exceptions for errors is fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T04:54:03.907",
"Id": "45372",
"Score": "0",
"body": "The term `expensive should generally only be used for exceptional circumstances` is a silly self referential statement. Use exceptions when you need to pass **control to a non local error handling code**. If error code is local and control does not cross an interface boundary then error codes are fine. But anything that extends past an interface should use exception (apart from exceptional circumstances :-) )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T04:56:24.963",
"Id": "45373",
"Score": "0",
"body": "See: http://programmers.stackexchange.com/a/118187/12917"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T11:12:07.360",
"Id": "45385",
"Score": "0",
"body": "thanks for the clarification about exception specification I misunderstood what they actually do"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T12:34:05.800",
"Id": "45387",
"Score": "0",
"body": "@LokiAstari I think we generally agree on when to use exceptions and when not to (based on your post in Programmers), and I admit that my wording was a bit vague. Thanks for the input :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T15:13:30.790",
"Id": "28837",
"ParentId": "28829",
"Score": "4"
}
},
{
"body": "<p>In Addition to everything @Lstor said:</p>\n\n<p>I don't like this locking design:</p>\n\n<pre><code>bool try_lock() noexcept;\nbool try_read_lock() noexcept;\nbool try_write_lock() noexcept;\n\nvoid lock() noexcept;\nvoid read_lock() noexcept;\nvoid write_lock() noexcept;\n\nvoid unlock() noexcept;\nvoid read_unlock() noexcept;\nvoid write_unlock() noexcept;\n</code></pre>\n\n<p>It looks like a C interface. Its hard to see how you could make that exception safe. What I would expect is to see an interface where you get a locked object and then read and/or write against the locked object.</p>\n\n<p>In this interface. Why are you passing a length? </p>\n\n<pre><code>unsigned int read ( byte_buffer &buffer, const unsigned int length, const std::chrono::milliseconds &wait_time, bool remove = true)\n</code></pre>\n\n<p>Does the <code>byte_buffer</code> type not already have a length!<br>\nWhat does the <code>remove</code> parameter do?<br>\nReally do not specify an exception specification.</p>\n\n<p>This is a bad idea:</p>\n\n<pre><code>bool poll_read ( const std::chrono::milliseconds &wait_time = zero_time ) throw ( SystemException, SocketClosedException );\nbool poll_write ( const std::chrono::milliseconds &wait_time = zero_time ) throw ( SystemException, SocketClosedException );\nbool poll_read_write ( const std::chrono::milliseconds &wait_time = zero_time ) throw ( SystemException, SocketClosedException );\n</code></pre>\n\n<p>You need to provide a polling interface like <code>select</code> or <code>poll</code> or <code>epoll</code>. The above interface limits the number of sockets you can have open to the number of threads. If you want to open thousands of sockets (like a web server) you need something like the above which monitors many connections simultaneously using a single thread.</p>\n\n<p>What is this?</p>\n\n<pre><code>std::shared_ptr<bool>closed;\n</code></pre>\n\n<p>For my opinion on number of exceptions see: <a href=\"https://softwareengineering.stackexchange.com/a/118187/12917\">https://softwareengineering.stackexchange.com/a/118187/12917</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T11:07:16.107",
"Id": "45384",
"Score": "0",
"body": "the read function can be called on an empty vector , length is the number of bytes you want to extract do you think this should change? as for the locking interface I am not sure what you mean could you clarify ? \nthe closed ptr is for copying sockets does that make sense?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T03:41:20.093",
"Id": "45450",
"Score": "0",
"body": "@A.H.: If you want to read 500 bytes. Your vector has to be 500 bytes long. You may as well set this before the call. If you have a generic buffer calling resize() to make this smaller and larger for multiple calls will improve performance as smaller buffers will not deallocate the memory and you can re-use rather than going back to the memory allocation library for more memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T03:47:27.760",
"Id": "45451",
"Score": "0",
"body": "@A.H.: Calling `Lock()` then doing something then calling `Unlock()`. Is C like not C++ like. You should be using RAII to automate this. One approach: When I call lock() on the stream I get back an object that I can then use for reading/writting. When I am finished with the object I let it fall out of scope and its destructor will release the lock on the stream."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T05:15:54.153",
"Id": "28862",
"ParentId": "28829",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28862",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T13:43:24.023",
"Id": "28829",
"Score": "2",
"Tags": [
"c++",
"error-handling",
"linux",
"library",
"socket"
],
"Title": "Wrapper library for sockets"
}
|
28829
|
<p>I've created a simple jQuery plugin to allow developers to quickly create image hover effects with very simple markup. I also created an option to automatically create the mouseover or mouseout versions of the image via TimThumb.</p>
<p><a href="http://concept211.github.io/hovr/" rel="nofollow noreferrer">Here is a link</a>. for more information and a demo.</p>
<pre><code>(function($){
$.fn.hovr = function(options) {
// Default Options
var defaults = {
speed: 'normal',
animateOver: {'opacity': '0'},
animateOut: {'opacity': '1'},
timThumb: false,
timThumbInverse: false,
timThumbPath: 'images/img.php',
timThumbParams: 'f=2'
//http://www.binarymoon.co.uk/2012/02/complete-timthumb-parameters-guide/
};
var options = $.extend({}, defaults, options);
// Create Images
if (options.timThumb) {
this.each(function() {
var strOrig = $(this).prop('src');
var strNew = options.timThumbPath +
'?src=' + strOrig +
'&w=' + $(this).prop('width') +
'&h=' + $(this).prop('height') +
'&' + options.timThumbParams;
if (options.timThumbInverse) {
$(this)
.prop('src', strOrig)
.attr('data-hovr', strNew);
}
else {
$(this)
.prop('src', strNew)
.attr('data-hovr', strOrig);
}
});
}
// Create Rollovers
return this.each(function() {
$(this).hover(
function() {
$(this).stop().animate(options.animateOver, options.speed);
},
function() {
$(this).stop().animate(options.animateOut, options.speed);
}
).each(function() {
var intWidth = ($(this).attr('width')) ? $(this).attr('width') : $(this).prop('width');
var intHeight = ($(this).attr('height')) ? $(this).attr('height') : $(this).prop('height');
var strAlign = ($(this).attr('align')) ? $(this).attr('align') : '';
var strClass = ($(this).attr('class')) ? $(this).attr('class') : '';
var strStyle = ($(this).attr('style')) ? $(this).attr('style') : '';
$(this).wrap('<div class="' + strClass + '" style="position:relative; display:inline-block; ' +
'width:' + intWidth + 'px; height:' + intHeight + 'px; ' +
'float:' + strAlign + '; ' + strStyle + '"></div>');
$(this).before($(this).clone(true))
.attr('style', 'position:absolute; left:auto; top:auto;')
.prop('src', $(this).attr('data-hovr'))
.removeAttr('data-hovr')
.removeAttr('class');
$(this).prev('img')
.attr('style', 'position:absolute; left:auto; top:auto; z-index:10;')
.removeAttr('data-hovr')
.removeAttr('class');
});
});
};
})(jQuery);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T22:16:14.673",
"Id": "46086",
"Score": "0",
"body": "Simple to implement but essential - cache your `$(this)` selector. `var $this = $(this);`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T05:45:14.277",
"Id": "46193",
"Score": "0",
"body": "@JonnySooter could you explain/suggest how to implement it properly? I tried but it ends up breaking my code. thanks!"
}
] |
[
{
"body": "<p>As a rule of thumb, when you use a jQuery selection more than once, you should cache its value. When you do <code>$(\".someElement\")</code>, jQuery now has to go find that element in the DOM, wrap it in the jQuery object and return it. If you save what it returns, then you only do the search once - not every time you use it.</p>\n\n<p>The hard part is caching <code>this</code>. This is relative to where you are in the code, function, callback, etc. and changes to provide context. For example:</p>\n\n<pre><code>var Object = {\n init: function() {\n //this in here references Object\n //You could call this function elsewhere by doing: \"this.init();\"\n },\n\n bindEvents: function() {\n $(\".someElement\").hover(function() {\n //This is a callback function\n //In here \"this\" refers to the element your .hover() was called on - \".someElement\"\n });\n\n //However, outside the callback, \"this\" now refers to Object again\n\n $(\".someOtherElement\").each(function(){\n //This is another callback\n //Here \"this\" refers to the element in question\n });\n }\n}\n</code></pre>\n\n<p>The reason the plugin is breaking when you cache it is because you have to cache it at each point the reference changes. Watch this next example:</p>\n\n<pre><code>var Object = {\n init: function() {\n //Here \"this\" refers to Object\n //You don't need to cache this here because the Object is already saved in a variable\n },\n\n bindEvents: function() {\n $(\".someElement\").hover(function() {\n //In here however, the reference changed\n //In here \"this\" refers to the element your \".hover()\" was called on. ie.: \".someElement\"\n //You would cache it in here\n });\n\n //However, outside the callback, \"this\" now refers to Object again so you don't need to cache it\n\n $(\".someOtherElement\").each(function(){\n //This is another callback\n //The reference has changed again, so now we cache it again\n });\n }\n}\n</code></pre>\n\n<p>From what I could understand from reading your plugin, I've cached your <code>this</code> references for you. I didn't change anything else except for <code>.removeAttr()</code> calls at the end. You can use a space and put in several attributes to be removed at once.</p>\n\n<p>Anyways here's your code:</p>\n\n<pre><code>(function($){\n$.fn.hovr = function(options) {\n\n // Default Options\n var defaults = {\n speed: 'normal',\n animateOver: {'opacity': '0'},\n animateOut: {'opacity': '1'},\n timThumb: false,\n timThumbInverse: false,\n timThumbPath: 'images/img.php',\n timThumbParams: 'f=2'\n //http://www.binarymoon.co.uk/2012/02/complete-timthumb-parameters-guide/\n };\n var options = $.extend({}, defaults, options);\n\n // Create Images\n if (options.timThumb) {\n this.each(function() {\n var $this = $(this),\n strOrig = $this.prop('src'),\n strNew = options.timThumbPath + \n '?src=' + strOrig + \n '&w=' + $this.prop('width') + \n '&h=' + $this.prop('height') + \n '&' + options.timThumbParams;\n\n if (options.timThumbInverse) {\n $this\n .prop('src', strOrig)\n .attr('data-hovr', strNew);\n }\n else {\n $this\n .prop('src', strNew)\n .attr('data-hovr', strOrig);\n }\n });\n }\n\n // Create Rollovers\n return this.each(function() {\n $(this).hover(\n function() {\n $(this).stop().animate(options.animateOver, options.speed);\n },\n function() {\n $(this).stop().animate(options.animateOut, options.speed);\n }\n ).each(function() {\n var $this = $(this),\n intWidth = ($this.attr('width')) ? $this.attr('width') : $this.prop('width'),\n intHeight = ($this.attr('height')) ? $this.attr('height') : $this.prop('height'),\n strAlign = ($this.attr('align')) ? $this.attr('align') : '',\n strClass = ($this.attr('class')) ? $this.attr('class') : '',\n strStyle = ($this.attr('style')) ? $this.attr('style') : '';\n\n $this.wrap('<div class=\"' + strClass + '\" style=\"position:relative; display:inline-block; ' + \n 'width:' + intWidth + 'px; height:' + intHeight + 'px; ' + \n 'float:' + strAlign + '; ' + strStyle + '\"></div>');\n\n $this.before($this.clone(true))\n .attr('style', 'position:absolute; left:auto; top:auto;')\n .prop('src', $this.attr('data-hovr'))\n .removeAttr('data-hovr class');\n\n $this.prev('img')\n .attr('style', 'position:absolute; left:auto; top:auto; z-index:10;')\n .removeAttr('data-hovr class');\n });\n });\n};\n})(jQuery);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-12T21:23:37.627",
"Id": "31167",
"ParentId": "28832",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "31167",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T14:40:19.683",
"Id": "28832",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "Allowing developers to quickly create image hover effects"
}
|
28832
|
<p>I have these if-else statements that I am not able to refactor. I have used them for doing validations on server-side using asp.net.</p>
<p>Would anyone please suggest ways to reduce these statements? Here, validation fields and validation types are <code>enum</code> lists.</p>
<pre><code>else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.FO.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.FW.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationFields.UF.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.O.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.W.ToString(), ValidationTypes.P.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.P.ToString(), ValidationTypes.C.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
else if (CheckNextItem(ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString(), ValidationTypes.C.ToString(), ValidationTypes.U.ToString()))
{
BrkTypeValidator2.ErrorMessage = "'TOP0618 -Invalid combination of Bracket IDs'";
args.IsValid = false;
}
</code></pre>
<p>This is method for <code>Checknextitem</code>:</p>
<pre><code> public static bool CheckNextItem(string Compareitem1, string comnpareitem2, string items1, string items2)
{
var listContains = Compareitem1 == items1 && comnpareitem2 != items2;
return listContains;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T15:52:11.087",
"Id": "45339",
"Score": "0",
"body": "Am I correct in assuming that each bracket 1 ID has only one valid bracket 2 ID? So, for instance, when ID 1 is \"FO\", then ID 2 must be \"P\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T15:55:38.020",
"Id": "45340",
"Score": "0",
"body": "yes upto Id1 has value \"P\" ......"
}
] |
[
{
"body": "<p>If each ID1 can only have one valid corresponding ID2, then I would recommend using a dictionary object to store the valid combinations, like this:</p>\n\n<pre><code>Dictionary<string, string> validIds = new Dictionary<string,string>();\nvalidIds[ValidationFields.FO.ToString()] = ValidationTypes.P.ToString();\nvalidIds[ValidationFields.FW.ToString()] = ValidationTypes.P.ToString();\nvalidIds[ValidationFields.UF.ToString()] = ValidationTypes.P.ToString();\n// ...\n</code></pre>\n\n<p>Then, you can check to see if the currently selected values are valid by simply comparing them to the valid combinations in the dictionary, like this:</p>\n\n<pre><code>if (validIds[ddlBr1Type.SelectedValue.ToString()] != ddlBr2Type.SelectedValue.ToString())\n{\n BrkTypeValidator2.ErrorMessage = \"'TOP0618 -Invalid combination of Bracket IDs'\";\n args.IsValid = false;\n}\n</code></pre>\n\n<p>By doing it that way, you only need the single <code>if</code> statement. Another side benefit is that you can now store the list of valid combinations somewhere else, outside of your code, such as in a configuration file or a database. Then you could load the data from that data source into the dictionary at run-time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T16:04:52.857",
"Id": "45342",
"Score": "0",
"body": "would you pls tell me,where i need to put that dictionary"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T16:11:23.537",
"Id": "45343",
"Score": "0",
"body": "I really can't, without knowing much more about the broader context of your project. In general terms, it would be best to create it and populate it once, when the application starts, but even that suggestion would depend on the type of application and how often the valid combinations may change, if ever. Even though it's not terribly efficient, it should work if you just created and populated it in the same method that was doing the `if` statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T18:41:18.150",
"Id": "45350",
"Score": "0",
"body": "+1 for taking the code right out of my mouth. I use a Dictionary of <Condition,Action> but it's the same result"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T16:00:53.820",
"Id": "28841",
"ParentId": "28838",
"Score": "2"
}
},
{
"body": "<p>Alternatively, if you have only a relatively small number of valid values, you can use tuples and LINQ to perform the comparison.</p>\n\n<p>You would initialize your collection of tuples with the valid values as follows:</p>\n\n<pre><code>_validValues = new []\n {\n new Tuple<string,string> (\"FO\", \"P\"),\n new Tuple<string,string> (\"FW\", \"P\"),\n new Tuple<string,string> (\"UF\", \"P\"),\n new Tuple<string,string> (\"O\", \"P\"),\n new Tuple<string,string> (\"W\", \"P\"),\n new Tuple<string,string> (\"P\", \"C\"),\n new Tuple<string,string> (\"C\", \"U\"),\n };\n</code></pre>\n\n<p>Given how they were used, I made the (perhaps incorrect) assumption that your ValidationTypes and ValidationFields types are enums. If this is incorrect, feel free to substitute the _.ToString values back in.</p>\n\n<p>The validation method could go as follows:</p>\n\n<pre><code>var currentValue = new Tuple<string,string> (ddlBr1Type.SelectedValue.ToString(), ddlBr2Type.SelectedValue.ToString());\n\nargs.IsValid = _validValues.Contains (currentvalue);\nBrkTypeValidator2.ErrorMessage = args.IsValid ? null : ERROR;\n</code></pre>\n\n<p>And, of course, I would use a constant (or better yet, a localized string) for your error message.</p>\n\n<pre><code>private const string ERROR = \"'TOP0618 -Invalid combination of Bracket IDs'\";\n</code></pre>\n\n<p>The nice thing about a collection of tuples over a dictionary is that:</p>\n\n<ul>\n<li>it allows for mutiple valid ddlBr2Type values for a given ddlBr1Type value without getting messy (a dictionary forces you to change-over to IDictionary<TKey,IEnumerable<TValue>>, whereas you just add more tuple values)</li>\n<li>the code reads a bit clearer, as you define the valid set of values and ask if your current combination is contained within that set</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T19:02:58.650",
"Id": "28846",
"ParentId": "28838",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T15:31:28.130",
"Id": "28838",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "How can I make only one if-else statement among all of these?"
}
|
28838
|
<p>I have four methods like these (here are only two of them): </p>
<pre><code> def checkLeft(clickedIndex: Int): Option[Int] = {
val leftIndex = clickedIndex - 1
if (leftIndex >= 0 && clickedIndex % field.width != 0 && isEmptyCell(leftIndex))
Some(leftIndex)
else
None
}
def checkRight(clickedIndex: Int): Option[Int] = {
val rightIndex = clickedIndex + 1
if (rightIndex < field.size && clickedIndex + 1 % field.width != 0 && isEmptyCell(rightIndex))
Some(rightIndex)
else
None
}
</code></pre>
<p>They all have similar structures. How I can reduce code duplication here? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T16:44:41.543",
"Id": "45345",
"Score": "0",
"body": "Does `bottomIndex` depend on `clickedIndex`? And what `something1` depends on?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T16:49:14.343",
"Id": "45346",
"Score": "0",
"body": "@PetrPudlák I edited question with real code. Please review it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T17:02:04.597",
"Id": "45347",
"Score": "0",
"body": "Pretty sure in the second block you'll want parens around `clickedIndex + 1` before the % operator."
}
] |
[
{
"body": "<p>For the LEFT case, you're checking that an index is above the low value of zero; for the RIGHT case, you're checking that it's below the high value of field.size. You can't really reconcile these except by combining them into a method that checks both boundaries - and there's nothing wrong with that. Now you've got </p>\n\n<pre><code>if (inBounds(theIndex) && isEmptyCell(theIndex) && ...)\n Some(theIndex)\n</code></pre>\n\n<p>That ... is questionable to me because you seem to be comparing a different index (clickedIndex or clickedIndex + 1) depending on LEFT or RIGHT.</p>\n\n<p>I think there are errors here that you need to reconcile before going too far down the path of duplication elimination.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T17:07:44.353",
"Id": "28843",
"ParentId": "28842",
"Score": "2"
}
},
{
"body": "<p>One way to do this would be with a trait or abstract class defining the basic behaviour of a check. Then you extend that for the actual checks you want.</p>\n\n<pre><code>trait indexCheck {\n def adjustedIndex( index: Int): Int = index\n def newIndexCondition(index: Int): Boolean = true\n def oldIndexCondition(index: Int): Boolean = true\n def apply( clickedIndex: Int): Option[Int] = {\n val returnIndex = adjustedIndex(clickedIndex)\n if (newIndexCondition(returnIndex) && oldIndexCondition(clickedIndex) && isEmptyCell(returnIndex))\n Some(returnIndex)\n else None\n }\n}\n</code></pre>\n\n<p>Then you create checkLeft and checkRight classes, overriding methods as necessary</p>\n\n<pre><code>class checkLeft extends indexCheck {\n override def adjustedIndex(index: Int): Int = index - 1\n override def newIndexCondition(index: Int): Boolean = {\n index >= 0\n }\n override def oldIndexCondition(index: Int): Boolean = {\n index % field.width != 0\n }\n}\n\naCheck = new checkLeft\naCheck(clickedIndex) // The magic apply method is used here.\n</code></pre>\n\n<p>My example above is probably a little over-specific. It would be more flexible just to have a conditionList onto which could be pushed a sequence of functions returning booleans. But you get the idea.</p>\n\n<p>By the way, I used traits in case you wanted to be able to create classes which did radically different things but also implemented checks. However, if you made <strong>indexCheck</strong> a class rather than a trait, you could do things like building maps of anonymous classes, like this:</p>\n\n<pre><code>val checks:Map[String,indexCheck] = Map(\n \"left\" -> new indexCheck {\n override def adjustedIndex(index: Int): Int = index - 1\n override def newIndexCondition(index: Int): Boolean = {\n index >= 0\n }\n override def oldIndexCondition(index: Int): Boolean = {\n index % field.width != 0\n }\n },\n \"right\" -> new indexCheck {\n override def adjustedIndex(index: Int): Int = index + 1\n override def newIndexCondition(index: Int): Boolean = {\n index < field.size\n }\n override def oldIndexCondition(index: Int): Boolean = {\n Index + 1 % field.width != 0\n }\n }\n)\n</code></pre>\n\n<p>Which gives you a map of anonymous classes, which you can use like this:</p>\n\n<pre><code>checks(\"left\")(SomeValue)\nchecks(\"right\")(SomeOtherValue)\n</code></pre>\n\n<p>or whatever.</p>\n\n<p>Another way to do this would be through higher order functions. That is, methods can return functions just like any other value/object. So you could have a method that took various parameters (some of them would have to be closures) and returned a function that would implement a specific check - a check factory, if you like. I'd need to know more about the parent object to give a useful demo of that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-23T17:46:01.770",
"Id": "30147",
"ParentId": "28842",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T16:24:04.187",
"Id": "28842",
"Score": "4",
"Tags": [
"scala"
],
"Title": "Refactor to reduce code duplication"
}
|
28842
|
<p>I went through lots of tutorial, and almost all of them were quite long, so I came up with my own code:</p>
<pre><code> $page = $_GET['page'];
$pg_count = $page-1;
if ($page == 1) {
$start = 0;
} else {
$start = $pg_count*15;
}
$limit = $page*15;
$query = 'SELECT * FROM table LIMIT '.$start.', '.$limit.'';
foreach($db->query($query) as $row) {
//outputs
}
$stmt = $db->query('SELECT * FROM table');
$row_count = $stmt->rowCount();
$count = ceil($row_count/15);
for ($i=1; $i<=$count; $i++) {
echo '<a href="?page='.$i.'">'.$i.'</a>';
}
</code></pre>
<p>Here i'm displaying 15 results per page.</p>
<p>This small piece of code seems to do the job (new to pdo, sorry if the method of including parameter is wrong).</p>
<p>So basically my question is, is their a much better way to do this?</p>
<p>EDIT:</p>
<p>I couldn't figure out a good approach so I came up with this horrible code:</p>
<pre><code>if ($page != 1) {
if ($page > 5) {
$sdot = '....';
} else {
$sdot = '';
}
echo '<a href="?page=1" class="page" >First</a>'.$sdot ;
}
if ($page < 5) {
for ($i=1; $i<=5; $i++) {
echo '<a href="?page='.$i.'">'.$i.'</a>';
}
} elseif (($page > 5) && ($page < ($count-5))) {
for ($i=($page-2); $i<=($page+2); $i++) {
echo '<a href="?page='.$i.'">'.$i.'</a>';
}
} elseif (($page > ($count-7)) && ($page < ($count-2))) {
for ($i=($page-2); $i<=($page+2); $i++) {
echo '<a href="?page='.$i.'">'.$i.'</a>';
}
} else {
for ($i=($page-2); $i<=$count; $i++) {
echo '<a href="?page='.$i.'">'.$i.'</a>';
}
}
if ($page != $count) {
if ($page < ($count-2)) {
$edot = '....';
} else {
$edot = '';
}
echo $edot.'<a href="?page='.$count.'" class="page">Last</a>';
}
</code></pre>
|
[] |
[
{
"body": "<p>This is a pagination code that I used in one of my old applications. You should change the mysql_ functions to pdo/mysqli here. This is based on a simple table with id, name fields. Change the queries according to your logic.</p>\n\n<pre><code>if (isset($_GET['page'])){\n $page = $_GET['page'];\n}\n\n// get total no. of rows from the table\n$page_query = \"SELECT COUNT(*) as C FROM table\";\n$RSp = MYSQL_QUERY($page_query) or die(mysql_error());\n$rowp = mysql_fetch_array($RSp, MYSQL_ASSOC);\n\n$num_rows = $rowp['C'];\n$rows_per_page = 100; // you can change this to what you want\n$first = 1;\n$last = ceil ($num_rows/$rows_per_page);\n\nif (($page == '') || ($page < $first) || ($page > $last)){\n $page = 1;\n}\n\n$lower_limit = (($page-1)*$rows_per_page);\n$count = 0;\n\n// main query to generate page content based on \n// pagination logic\n$query = \"Select * from table order by name \";\n$query.= \"LIMIT \".$lower_limit.\", \".$rows_per_page;\n\n// generate page content here\n// pagination code at the bottom of the page goes here\n\n<!--This is the main pagination HTML Code-->\n<ul id=\"pagination-clean\">\n<?php\n if ($page == 1){\n?>\n <li class=\"previous-off\">Previous</li>\n<?php\n}\nelse {\n?>\n <li class=\"previous\"><a href=\"?page=<?php echo ($page-1); ?>\">Previous</a></li>\n<?php\n} // end else\nfor ($i = 1; $i<=$last;$i++){\n // This is the query statement for displaying the name of \n // first and last entry of the page \n // on paginated links\n $lower = (($i-1) * $rows_per_page);\n $upper = (($i*$rows_per_page) - 1);\n\n $query_low = \"SELECT Name, SUBSTRING(Name, 1, 2) AS `Name_S` FROM \";\n $query_low.= \"table ORDER BY Name ASC LIMIT \".$lower.\", 1\";\n $RSl = MYSQL_QUERY($query_low) or die(mysql_error());\n $row_low = mysql_fetch_array($RSl, MYSQL_ASSOC);\n $lname = $row_low['Name'];\n $lname_s = $row_low['Name_S'];\n\n $query_up = \"SELECT Name, SUBSTRING(Name, 1, 2) AS `Name_S` FROM \";\n $query_up.= \"table ORDER BY Name ASC LIMIT \".$upper.\", 1\";\n $RSu = MYSQL_QUERY($query_up) or die(mysql_error());\n $row_up = mysql_fetch_array($RSu, MYSQL_ASSOC);\n if (!$row_up){\n $query_up = \"SELECT Name, SUBSTRING(Name, 1, 2) AS `Name_S` FROM \";\n $query_up.= \"table ORDER BY Name ASC LIMIT \".($num_rows-1).\", 1\";\n $RSu = MYSQL_QUERY($query_up) or die(mysql_error());\n $row_up = mysql_fetch_array($RSu, MYSQL_ASSOC); \n }\n $uname = $row_up['Name'];\n $uname_s = $row_up['Name_S'];\n\n if ($i == $page){\n?>\n <li class=\"previous-off\"><?php echo $i .\" (\".$lname_s.\" - \".$uname_s.\")\"; ?></li>\n<?php\n }\n else {\n ?>\n <li><a href=\"?page=<?php echo $i; ?>\" ><?php echo $i .\" (\".$lname_s.\" - \".$uname_s.\")\"; ?></a></li>\n<?php\n }\n } // end for loop\n\n if ($page == $last){\n?>\n <li class=\"next-off\">Next</li>\n<?php\n}\nelse {\n?> \n <li class=\"next\"><a href=\"?page=<?PHP echo ($page+1)?>\">Next</a></li>\n<?php\n }\n?>\n</ul>\n <!-- end pagination code here --> \n</code></pre>\n\n<p>This is the CSS:</p>\n\n<pre><code>#pagination-clean li { border:0; margin:0; padding:0; font-size:11px; list-style:none; /* savers */ float:left; }\n/* savers #pagination-clean li,*/\n#pagination-clean a { border-right:solid 1px #DEDEDE; margin-right:2px; }\n#pagination-clean .previous-off,\n#pagination-clean .next-off { color:#888888; display:block; float:left; font-weight:bold; padding:3px 4px; } \n#pagination-clean .next a,\n#pagination-clean previous a { border:none; font-weight:bold; } \n#pagination-clean .active { color:#000000; font-weight:bold; display:block; float:left; padding:4px 6px; /* savers */ border-right:solid 1px #DEDEDE; }\n#pagination-clean a:link,\n#pagination-clean a:visited { color:#0e509e; display:block; float:left; padding:3px 6px; text-decoration:underline; }\n#pagination-clean a:hover { text-decoration:none; \n</code></pre>\n\n<p>This is a screenshot of what the page looks like:</p>\n\n<p><a href=\"https://imgur.com/3ch21Dm\" rel=\"nofollow noreferrer\">http://imgur.com/3ch21Dm</a></p>\n\n<p>(In addition to the page no., it also displays the first 2 characters of the name field)</p>\n\n<p>See if this helps. Let me know if you have any questions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T19:51:55.100",
"Id": "45353",
"Score": "0",
"body": "Yes it is good, but can you point out improvements in my code, as it also works, and I can add css later on and I have `isset` check on `$_GET['page']`.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T19:54:47.087",
"Id": "45354",
"Score": "0",
"body": "since your code works fine, the only improvement that I can think of would be making rows per page parameter dynamic so that you can easily switch from 15 rows per page to any no. of rows you want. Other improvement could be this part: if (($page == '') || ($page < $first) || ($page > $last)){\n $page = 1;\n}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T19:55:53.310",
"Id": "45355",
"Score": "0",
"body": "what you might also want to do is test your case for different page values and see if it handles all the cases correctly. Other than that it looks good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T20:08:27.220",
"Id": "45356",
"Score": "0",
"body": "Yes, i tested it for 50 values, and yes thanks for next and last thing, and how can I do something like `First 1 2...8 9(current page) 10...81 82 last`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T21:24:32.383",
"Id": "45358",
"Score": "0",
"body": "can you clarify that a bit more ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T21:57:20.320",
"Id": "45359",
"Score": "0",
"body": "never mind... I see what you are saying."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T01:58:28.317",
"Id": "45360",
"Score": "0",
"body": "Like if i have 100 pages, and I'm on 9th page, it should display something like `..7 8 9 10 11..` where 9 is the current page.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T02:00:35.940",
"Id": "45361",
"Score": "0",
"body": "ok... do you wanna give it a shot on your own using your or my code as a starting point? I can give you a hint: the change needs to be made in the for loop and you might have to declare some additional variable and add some more condition checking same as what I did in my code. If you can get it then you might want to reply here tomorrow and I'll see if I can work with you on this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T03:52:58.517",
"Id": "45370",
"Score": "0",
"body": "Yea sure, I'll give it a shot :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T09:48:11.817",
"Id": "45381",
"Score": "0",
"body": "Ok I tried, couldn't figure out, so I came up with a lot of `if` statements(posted the code in the edit of the question). How can you do with adding just one more loop? :o"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T13:13:21.937",
"Id": "45391",
"Score": "0",
"body": "ok... I'll take a look at it as soon as I get a chance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T14:13:56.223",
"Id": "45395",
"Score": "0",
"body": "you wanna give this a shot: http://papermashup.com/easy-php-pagination/ ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T16:08:47.233",
"Id": "45401",
"Score": "0",
"body": "Yes, that looks awesome :) still I would like to know how would you compress those `if` statements to single loop, might help in the future.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T16:18:41.320",
"Id": "45402",
"Score": "0",
"body": "were you able to create what you wanted combining the code from that link and your or my answer? Understand that for an application like this, there would always be a certain minimum no. of if loops that would be needed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T16:35:12.143",
"Id": "45404",
"Score": "0",
"body": "Ok I get your point, thanks for your help :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T16:36:38.940",
"Id": "45405",
"Score": "0",
"body": "yeah try that and if that does not work then you can create another question here and someone can review it too."
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T19:41:10.640",
"Id": "28848",
"ParentId": "28847",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28848",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-22T19:19:28.400",
"Id": "28847",
"Score": "1",
"Tags": [
"php",
"pagination"
],
"Title": "Pagination Review"
}
|
28847
|
<p>I have a question that may be easily answered, but the answer evades me. In regards to numeric operations, how come when I code this:</p>
<pre><code>double celsius = 30;
double fahrenheit = (celsius + 32.0) / (5/9);
</code></pre>
<p>I get an answer:</p>
<pre><code>fahrenheit = infinity;
</code></pre>
<p>But, when I code this:</p>
<pre><code>double fahrenheit = (celsius + 32.0) / (5.0/9); // with a decimal place after 5 or 9
</code></pre>
<p>The answer comes out correctly as 111.6?</p>
<p>Shouldn't the (5/9) automatically become a <code>double</code> without the decimal, or am I incorrect?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T11:06:31.170",
"Id": "45383",
"Score": "0",
"body": "This site is for reviewing working code to make it better. If you don't understand why your code does what it does, you should try to debug it (hint: what is the result of `5/9`?) or ask on Stack Overflow."
}
] |
[
{
"body": "<p>Division by zero gets you infinity.</p>\n\n<p>Note that (5/9) is an int expression, and resolves to int 0!</p>\n\n<p>To fix things, make your literals doubles : </p>\n\n<pre><code>double celsius = 30d;\ndouble fahrenheit = (celsius + 32.0d) / (5d/9d);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T04:32:27.897",
"Id": "28861",
"ParentId": "28860",
"Score": "2"
}
},
{
"body": "<pre><code>Shouldn't the (5/9) automatically become a double without the decimal, or am I incorrect?\n</code></pre>\n\n<p>I think you want an answer to <code>Doesn't</code> instead of <code>shouldn't</code>. No it doesn't become that. </p>\n\n<p>Simply stated <code>int</code> divided by an <code>int</code> can only give an <code>int</code>. So <code>5/9</code> becomes 0 point something which needs to be truncated to make it an integer. Hence <code>0</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T07:54:59.653",
"Id": "28863",
"ParentId": "28860",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T04:21:44.163",
"Id": "28860",
"Score": "0",
"Tags": [
"java"
],
"Title": "Simple Question about Numeric Operations"
}
|
28860
|
<p>I am looking for feedback on a solution to the following problem posed from a book that I'm working through (<em>Java: How To Program</em>, 9<sup>th</sup> Edition):</p>
<blockquote>
<p>Write an application that reads a five-letter word from the user and produces every possible three-letter string that can be derived from the letters of that word. For example, the three-letter words produced from the word "bathe" include "ate," "bet," "tab," "hat," "the," and "tea."</p>
</blockquote>
<p>I have a sneaking suspicion that I've over complicated things. Is my code easy to understand? I'm a rookie coder still going over the basics.</p>
<pre><code>import java.util.Scanner;
public class ThreeLetterStrings {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
System.out.println( "Please enter a five letter word" );
String userInput = sc.nextLine(); // get input
int wordLength = userInput.length(); // get length of string in question
char[] charArray = new char[ wordLength ];
int stem = 0; // stem being the 2nd letter after the first - b(a)the or ba(t)he
int scan = 0; // scan count for while loop
boolean stamp;
for( int i = 0; i < charArray.length; i++ ) // feed string into char array
{
charArray[ i ] = userInput.charAt( i );
}
for( int startLetter = 0; startLetter < wordLength; startLetter++ )
{
for( int stemLetter = 1; stemLetter < wordLength; stemLetter++ )
{
stem = startLetter + stemLetter;
if( stem >= wordLength )
stem = stem - wordLength;
scan = 0; // reset scan count after walk for loop
for( int walk = 0; walk < wordLength - 2; walk++ )
{
System.out.printf( "%c", charArray[ startLetter ] );
System.out.printf( "%c", charArray[ stem ] );
stamp = false; // determines whether a character was printed
while( stamp == false )
{
if( scan == startLetter || scan == stem )
{
scan++;
}
else
{
System.out.printf( "%c", charArray[ scan ] );
stamp = true;
System.out.println();
scan++;
}
} // end while
} // end walk for
} // end stemLetter for
} // end startLetter for
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your program can be simplified to something like this:</p>\n\n<pre><code>System.out.println(\"Please enter a five letter word\"); \nScanner sc = new Scanner(System.in);\nString input = sc.nextLine();\n\nfor (int i = 0; i < input.length(); i++) { // pos. of 1st letter\n for (int j = 0; j < input.length(); j++) { // pos. of 2nd letter\n for (int k = 0; k < input.length(); k++) { // pos. of 3rd letter\n if (i == j || i == k || j == k) continue; // any letter taken twice? -> skip\n System.out.printf(\"%c%c%c\\n\", input.charAt(i), input.charAt(j), input.charAt(k));\n }\n }\n}\n</code></pre>\n\n<p>Some more pointers:</p>\n\n<ul>\n<li>while this works for combinations of three letters, for combinations of more letters (or arbitrary numbers of letters) you should use some sort of recursive function</li>\n<li>you might want to check whether the entered word is actually five letters long</li>\n<li>before printing, you could store the three-letter-words in a <code>Set<String></code> to filter out duplicates</li>\n<li>the question is a bit unclear whether it's about three-letter <em>strings</em> or three-letter <em>words</em>; in the latter case you might want to get some dictionary of valid three-letter words and check whether the combinations are in that list</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T10:47:46.947",
"Id": "45382",
"Score": "0",
"body": "Wow! Great stuff a triple nested loop. This is perfect, thank you tobias_k, this is really much simpler. I'm still a couple of chapters away from recursion and collections; still earning my wings. Thanks again, very helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T09:37:24.823",
"Id": "28868",
"ParentId": "28864",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "28868",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T08:24:55.163",
"Id": "28864",
"Score": "3",
"Tags": [
"java",
"beginner",
"strings"
],
"Title": "Generating three-letter strings from five-letter words"
}
|
28864
|
<p>The 'Do' method is for prepared statements and returns (by fetchall()). I am also using two looping statements. Is there any better way to fetch two tables in one statement or query? If not, what can I do to improve this code?</p>
<pre><code>// 'id' is index in 'userinfo' table and 'id' in 'election' table is a child index(foreign key)
// 'ElectionId' is also the index, but it is not connected with othertable (only 'id' is linked)
<?php
$call = new world();
$get = $call->Do("SELECT Votes, Views, id FROM election WHERE ElectionId = ?", array("electionIdUknwn"));
foreach($get as $show)
{
<div>"Votes is :".$show[0]</div>
$add = $call->Do("SELECT username FROM userinfo WHERE id = ?", array($show[2]) );
foreach($add as $display)
{
<div>"Username is :".$display[0]</div>
}
<div>"Views are :".$show[1]</div>
}
?>
</code></pre>
|
[] |
[
{
"body": "<p><strong>SQL:</strong></p>\n\n<p>This is just a simple <a href=\"http://en.wikipedia.org/wiki/Join_%28SQL%29\" rel=\"nofollow\">join</a>.</p>\n\n<pre><code>SELECT e.Votes, e.Views, e.id, u.username \nFROM election as e, userinfo as u \nWHERE e.id= u.id WHERE e.ElectionId=? \nORDER BY e.id ASC\n</code></pre>\n\n<p>Now you can iterate over all lines and every time e.id is changing you know that you have to display a new group.</p>\n\n<p>Are there really multiple users per Votes and Views pair? I guess Votes and Views are counting columns so your model is kind of strange. Maybe you can find better names, so it is easier to get an idea what you want to do.</p>\n\n<p><strong>PHP:</strong></p>\n\n<ul>\n<li>usually classes are starting with a capital letter.</li>\n<li>usually methods are starting with a lower case letter.</li>\n<li>there is something missing in your output, some <code>echo</code>s?</li>\n<li>it is best practice to skip the <code>?></code> at the end, do avoid sending whitespace in case you will change the page header later.</li>\n<li><code>$call</code> and <code>world</code> are really strange names</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T09:59:53.980",
"Id": "28869",
"ParentId": "28866",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T08:50:59.977",
"Id": "28866",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"mysql",
"array"
],
"Title": "Is there any better way to fetch two tables in one statement or query?"
}
|
28866
|
<p>The file is quite long, 1000 LOC so I want to separate it into smaller files.</p>
<p><a href="https://github.com/anvoz/world-js/blob/v1.0/js/world.core.js" rel="nofollow">https://github.com/anvoz/world-js/blob/v1.0/js/world.core.js</a></p>
<p>Here is a brief version of the code:</p>
<pre><code>(function(window, undefined) {
var WorldJS = window.WorldJS = function() {
// WorldJS Constructor
this.nextSeedId = 1;
this.Statistic = { population: 0 };
this.Knowledge = {
completed: [],
gain: function(world) { /* ... */ }
};
}
WorldJS.prototype.someMethods = function() {};
var Seed = WorldJS.prototype.Seed = function() {
// Seed Constructor
};
Seed.prototype.someMethods = function() {};
})(window);
// Create a world
var world = new WorldJS();
// Create a seed
var seed = new world.Seed();
</code></pre>
<p>Seems like I was right with the <code>Seed</code> class. So I can put <code>Seed</code> in a new file. Like this:</p>
<pre><code>(function(window, undefined) {
var WorldJS = window.WorldJS;
var Seed = WorldJS.prototype.Seed = function() {
// Seed Constructor
};
Seed.prototype.someMethods = function() {};
})(window);
</code></pre>
<p>How can I put the <code>Knowledge</code> property to a new file? Is it a good practice if I change <code>Knowledge</code> to a class just like the <code>Seed</code> class and use a new lowercase property to hold data like this:</p>
<pre><code>world.knowledge = new world.Knowledge();
</code></pre>
|
[] |
[
{
"body": "<p>I don't see the advantage of adding <code>Seed</code> and <code>Knowledge</code> into the prototype of <code>World</code> (unless you've got more code to tell me otherwise). If you don't need anything from the instance at all, then you don't need them in the instance. You can put them like <code>static</code> members instead.</p>\n\n<p>With that, you can do what jQuery did. jQuery's <code>jQuery</code> and <code>$</code> point to a constructor function that builds jQuery objects. That's why you can do <code>jQuery()</code> and <code>$()</code>. </p>\n\n<p>But in JS, functions <em>are objects</em> and like any other object, you can add properties. It's the same reason why you can also do <code>jQuery.each</code> or <code>$.each</code>. Basically they made their constructor their namespace as well.</p>\n\n<p>So you can do the following to <code>World</code>:</p>\n\n<pre><code>(function(window){\n\n var World = window.World = function(){/*World constructor code*/};\n\n World.prototype.someFn = function(){/*...*/};\n\n}(window));\n</code></pre>\n\n<p>And like how non-instance jQuery plugins extend (and yes, you can place this in another file. Just make sure the <code>World</code> library is loaded first):</p>\n\n<pre><code>(function(World){\n\n //This part would be synonymous to $.somePlugin = function(){...}\n var Seed = World.Seed = function(){/*Seed constructor code*/};\n\n Seed.prototype.someFn = function(){/*...*/};\n\n}(World));\n</code></pre>\n\n<p>To use them:</p>\n\n<pre><code>var myWorld = new World(); //Using World as a constructor\nvar mangoSeed = new World.Seed(); //Using World to access the Seed constructor\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T14:03:41.667",
"Id": "45393",
"Score": "0",
"body": "I use prototype for `Seed` because some properties of Seed may different in 2 `WorldJS` instances. However, I completely forgot about the properties of function as you mentioned so your answer is very helpful and may make my code clearer. I will review my code again to see if I can change as you suggest. How about the `Knowledge` property of `WorldJS`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T13:24:55.517",
"Id": "28878",
"ParentId": "28870",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28878",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T10:12:33.870",
"Id": "28870",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Separate a module into smaller parts"
}
|
28870
|
<p>I've solved <a href="http://projecteuler.net/problem=28" rel="nofollow">Project Euler #28</a> using recursion.</p>
<blockquote>
<p>If this 5 × 5 spiral pattern is extended to 1001 × 1001, what would be the sum of the red diagonals?</p>
<p>$$\begin{matrix}
\color{red}{21} & 22 & 23 & 24 & \color{red}{25} \\
20 & \color{red}{7} & 8 & \color{red}{9} & 10 \\
19 & 6 & \color{red}{1} & 2 & 11 \\
18 & \color{red}{5} & 4 & \color{red}{3} & 12 \\
\color{red}{17} & 16 & 15 & 14 & \color{red}{13}
\end{matrix}$$</p>
</blockquote>
<p>Is this a good enough solution, or is there some other way to optimize the code?</p>
<pre><code>static long GetSumofDiagonals(int cubeSize)
{
long sum = 0;
if (cubeSize == 1)
return 1;
else
{
// As the diagonal numbers follows a sequence
// UR = n^2 - 1;
// UL = UR - (n - 1)
// LL = UL - (n -1 )
// LR = LL - (n - 1)
// This works only for odd n
long UpperRight = (long) Math.Pow(cubeSize, 2);
long UpperLeft = UpperRight - (cubeSize - 1);
long LowerLeft = UpperLeft - (cubeSize - 1) ;
long LowerRight = LowerLeft - (cubeSize - 1);
sum = UpperRight + UpperLeft + LowerLeft + LowerRight;
return sum + GetSumofDiagonals(cubeSize - 2);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T14:08:52.953",
"Id": "45394",
"Score": "5",
"body": "Where did you find it? Or do you mean that you wrote it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T06:18:34.740",
"Id": "45453",
"Score": "0",
"body": "@svick I wrote it..but I haven't thought of forming a quadratic equation from it.."
}
] |
[
{
"body": "<p>Performance is okay (linear), but I think the code can be simplified by using a loop instead of recursion, and by going from the inside-out instead of from the outside-in.</p>\n\n<p>Here's how I did it, in pseudo-code:</p>\n\n<pre><code>sum = 1 # running sum\nlast = 1 # last number\ndelta = 2 # delta between numbers\n\nfor layer in 1 to (sidelength - 1) / 2:\n for num in 1 to 4:\n last += delta\n sum += last\n delta += 2 # increases by two with each layer\n\nreturn sum\n</code></pre>\n\n<p>Also, I think this is one of those probems that can actually be calculated directly using pencil and paper, without any loops. Why don't you check out the <a href=\"http://projecteuler.net/thread=28\">problem forum</a> there?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T12:57:32.380",
"Id": "45390",
"Score": "0",
"body": "That's great..I never thought of it!!..to form the quadratic equation and then using a simple loop to solve it. Thanks @tobias_k"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T17:25:01.323",
"Id": "45409",
"Score": "0",
"body": "I cooked up an `O(1)` solution but if someone doesn't want to do maths it is much simpler than the `O(n)` solution that I had used earlier."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T12:33:08.997",
"Id": "28875",
"ParentId": "28873",
"Score": "5"
}
},
{
"body": "<p>There is a very easy solution.</p>\n\n<p>In all cases I'll avoid x = 1 as it is a corner that doesn't fit the pattern.</p>\n\n<p>The pattern of each ring can be generalized easily into an equation considering the rings to be numbered as x = 2, 3, 4, ... , 500</p>\n\n<blockquote>\n <p>(2x - 1)(2x - 1) - (2x - 1) - 2(2x - 1) - 3(2x - 1)</p>\n</blockquote>\n\n<p>The first term is for upper right corner of each ring. The second is for upper left then lower left and finally lower right. I laid it out barely to make it easy to understand but you can certainly make it shorter.</p>\n\n<p>It is actually easier to find an equation by considering the rings to go from x = 3, 5, ..., 1001</p>\n\n<blockquote>\n <p>4(x*x) - 6(x - 1)</p>\n</blockquote>\n\n<p>Running a loop over the range 2 to 1001 with step of 2 and then adding 1 gives you the answer. </p>\n\n<p>You want to simplify it further? You need the formula for summation of series of n^2 and summation of n. That makes this into an <code>O(1)</code> program instead of current <code>O(n)</code>.</p>\n\n<p>For example the first term would become <code>4 * summation(x^2)</code> with summation running from 3 to n with step of 2. Its value is</p>\n\n<blockquote>\n <p>(n * (n + 1) * (n + 2))*(2/3) + 1</p>\n</blockquote>\n\n<p>I am ignoring the implementation details like it should be <code>2.0/3.0</code>.</p>\n\n<p>Similarly the second term is <code>- 6 * summation(x)</code> with summation running from 3 to n with step of 2. Third term is `6(n - 2). I'll leave calculating the second term to you.</p>\n\n<p>Simply adding these 3 terms gives you an <code>O(1)</code> program.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T16:46:03.687",
"Id": "45407",
"Score": "0",
"body": "You should name your intermediate variable something other than `n`, since `n` already has a meaning. Also, the Project Euler challenges are *specifically* to write a program to solve it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T16:59:35.277",
"Id": "45408",
"Score": "1",
"body": "@Bobson If the optimization is done to the last level of `O(1)` by using sum of series then `n` would become exactly what it represents in the problem statement. But for other cases your comment is valid. I solved the problem nearly 2 months ago that's why the logic I presented in the answer is a little messy. I'll clean it up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T18:34:47.913",
"Id": "45421",
"Score": "0",
"body": "@Bobson Is it better now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:00:22.367",
"Id": "45522",
"Score": "0",
"body": "I think so. +1."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T15:35:26.840",
"Id": "28883",
"ParentId": "28873",
"Score": "3"
}
},
{
"body": "<p>A pattern like </p>\n\n<pre><code>if(someCondition) \n{\n return someValue;\n}\nelse\n{\n return someOtherValue;\n} \n</code></pre>\n\n<p>can be simplified by removing the <code>else</code>, because it is redundant: </p>\n\n<pre><code>if(someCondition) \n{\n return someValue;\n}\n\nreturn someOtherValue;\n</code></pre>\n\n<hr>\n\n<p>You should throw an <code>ArguemntException</code> for the case an even value is passed to the method. </p>\n\n<hr>\n\n<p>Also it isn't mentioned in the <a href=\"http://msdn.microsoft.com/en-us/library/ms229002.aspx\" rel=\"nofollow\">naming guidelines</a> you should name variables which are local to a method by using <code>camelCase</code> casing too. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T08:25:12.537",
"Id": "149684",
"Score": "2",
"body": "Not only can you omit the `else`, you can just do: `return someCondition ? someValue : someOtherValue;`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T08:27:31.657",
"Id": "149686",
"Score": "2",
"body": "Right, I just wanted to stay in the code in question. Using a tenary for the code in question would look strange."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T08:28:34.447",
"Id": "149688",
"Score": "0",
"body": "Took a second look and indeed it would be strange. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-05T08:24:16.203",
"Id": "83277",
"ParentId": "28873",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T12:11:23.673",
"Id": "28873",
"Score": "2",
"Tags": [
"c#",
"performance",
"programming-challenge",
"recursion"
],
"Title": "Project Euler 28: sum of spiral diagonals using recursion"
}
|
28873
|
<p>I've got relation in my database as following :</p>
<pre><code>Customer has many Orders
Order has many Parts
Order has many Upc
</code></pre>
<p>So my requirement is to copy all orders from one customer and <code>attach</code> or copy those orders (with their dependencies including parts and upcs) to another customer. With originals customers orders to be left in-tacked, so I'd basically <code>clone</code> orders and dependencies from <code>customer a</code> to <code>customer b</code></p>
<p>Here is what I got so far, but its kinda slow (slowest first):</p>
<p>I'd iterate trough customers orders first and then I'd call <code>copy_order1</code> method to copy order and dependencies to another customer. here is <code>copy_order1</code> (which is in class Customer):</p>
<pre><code>def copy_order1(source_order)
order_attributes = source_order.attributes.merge({:customer_id => self.customer_id})
['id', 'deleted_at'].each{|k| order_attributes.delete k}
ord = Order.create(order_attributes)
source_order.parts.each do |part|
part_attributes = part.attributes.merge({:order_id => ord.id})
['id', 'deleted_at'].each{|k| part_attributes.delete k}
Part.create(part_attributes)
end
source_order.upcs.each do |upc|
upc_attributes = upc.attributes.merge({:order_id => ord.id})
['id', 'deleted_at'].each{|k| upc_attributes.delete k}
Upc.create(upc_attributes)
end
return ord
end
</code></pre>
<p>And there I made slightly faster method called <code>copy_order2</code> :</p>
<pre><code>def copy2(destination_customer)
ActiveRecord::Base.transaction do
Order.includes(:customer, :part, :upc).where(:customer_id => self.id).find_in_batches(:batch_size => 50) do |batch|
batch.each do |order|
new_order = order.dup
new_order.parts << order.parts.each {|part| tmp = part.dup; tmp.id = tmp.order_id = nil; tmp}
new_order.upcs << order.upcs.each {|upcs| tmp = upc.dup; tmp.id = tmp.order_id = nil; tmp}
destination_customer.orders << new_ordert
end
# Save one batch
destination_customer.save!
end
end
end
</code></pre>
<p>Can anyone suggest <code>performance friendly way</code> to do this from your own experience? How would you approach this issue if you had one?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T02:08:28.923",
"Id": "46190",
"Score": "0",
"body": "Wouldn't it be better to simply point the second customer to the same order, rather than introducing duplication and a deep copy? Or do you want the orders to be updated independently after the copy?"
}
] |
[
{
"body": "<p>The #dups are probably unnecessary. If you unset the ID ActiveRecord already \"thinks\" that the object is new, and #save will create a new one in the DB. But the main bottleneck is probably the amount of DB queries generated. The easiest way to gain some performance in such cases is to wrap the whole block into a transaction. The best way would probably use bulk inserts (e.g. with a gem like <a href=\"https://github.com/zdennis/activerecord-import\" rel=\"nofollow\">https://github.com/zdennis/activerecord-import</a>).</p>\n\n<p>But if you've to do so many deep copies you also should rethink if you're using the right approach (or DB) here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-29T09:00:19.810",
"Id": "30423",
"ParentId": "28879",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "30423",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T13:38:15.047",
"Id": "28879",
"Score": "1",
"Tags": [
"ruby",
"performance"
],
"Title": "Ruby on rails with active record perfomance"
}
|
28879
|
<p>I wrote a small script to manipulate fields of a file based on the input of a user. Is there something I could've done better, or perhaps a better refactor? I do know however that I need a way to validate for empty fields.</p>
<pre><code>view_column() {
for i in "$file_name"; do
cat "$i" | awk -v col="$1" '{ print $col }'
done
}
print_menu() {
menu=( 'First' 'Last' 'Email' 'Exit' )
for (( i=0; i<${#menu[@]}; i++ )); do
printf "%2d. %s\n" "$((i+1))" "${menu[$i]}"
done
}
main() {
while true; do
clear
print_menu
read -p 'Enter a choice: ' choice
if (( "$choice" == 4 )); then
break
fi
view_column "$choice"
sleep 1.5
done
}
</code></pre>
|
[] |
[
{
"body": "<p>That's very elegant looking code. bash has a builtin <code>select</code> statement to present a menu to the user and get a response -- \nthe advantage of <code>select</code> is that the user is locked into it until a valid response is obtained. Plus, it seems that printing the menu and reading the response should be together.</p>\n\n<p>My code below is not as beautiful as yours, but it allows you to localize all knowledge about the file structure into a single line: <code>local fields=(...)</code></p>\n\n<pre><code>main() {\n local PS3='Enter a choice: '\n local fields=(First Last Email)\n\n # reverse the fields array: map field names to column numbers\n local -A column\n for (( i=0; i < ${#fields[@]}; i++)); do\n column[${fields[i]}]=$((i+1))\n done\n\n while true; do\n clear\n select choice in \"${fields[@]}\" Exit; do\n # invalid response\n [[ -z $choice ]] && continue\n\n # exit\n [[ $choice = \"Exit\" ]] && return\n\n # do something interesting\n view_column \"${column[$choice]}\"\n sleep 1.5\n break\n done\n done\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T21:00:50.137",
"Id": "45570",
"Score": "0",
"body": "I appreciate the comment, your code looks good as well! I've never tried using PS3 that looks really handy to use for this kind of situation. Could you explain a little bit more what you're doing with: column[${fields[i]}]=$((i+1))"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T19:51:07.113",
"Id": "28945",
"ParentId": "28880",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28945",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T14:01:58.577",
"Id": "28880",
"Score": "4",
"Tags": [
"bash",
"linux",
"shell",
"awk"
],
"Title": "Input Columns with Awk"
}
|
28880
|
<p>I am so sick of WYSIWYG editors being exclusively for the latest browser or being huge with every option under the sun. I tried to make my own, using code I found online as well as a little of my own handy work.</p>
<p>This is what I came up with:</p>
<p><a href="http://jsfiddle.net/spadez/RRBHw/1/" rel="nofollow">http://jsfiddle.net/spadez/RRBHw/1/</a></p>
<pre><code>/*
* WYSIWYG EDITOR BASED ON JQUERY RTE
*/
// define the rte light plugin
(function ($) {
if (typeof $.fn.rte === "undefined") {
var defaults = {
max_height: 350
};
$.fn.rte = function (options) {
$.fn.rte.html = function (iframe) {
return iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML;
};
// build main options before element iteration
var opts = $.extend(defaults, options);
// iterate and construct the RTEs
return this.each(function () {
var textarea = $(this);
var iframe;
var element_id = textarea.attr("id");
// enable design mode
function enableDesignMode() {
var content = textarea.val();
// Mozilla needs this to display caret
if ($.trim(content) === '') {
content = '<br />';
}
// already created? show/hide
if (iframe) {
console.log("already created");
textarea.hide();
$(iframe).contents().find("body").html(content);
$(iframe).show();
$("#toolbar-" + element_id).remove();
textarea.before(toolbar());
return true;
}
// for compatibility reasons, need to be created this way
iframe = document.createElement("iframe");
iframe.frameBorder = 0;
iframe.frameMargin = 0;
iframe.framePadding = 0;
iframe.height = 200;
if (textarea.attr('class')) iframe.className = textarea.attr('class');
if (textarea.attr('id')) iframe.id = element_id;
if (textarea.attr('name')) iframe.title = textarea.attr('name');
textarea.after(iframe);
var doc = "<html><head>" + "</head><body class='frameBody'>" + content + "</body></html>";
tryEnableDesignMode(doc, function () {
$("#toolbar-" + element_id).remove();
textarea.before(toolbar());
// hide textarea
textarea.hide();
});
}
function tryEnableDesignMode(doc, callback) {
if (!iframe) {
return false;
}
try {
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(doc);
iframe.contentWindow.document.close();
} catch (error) {
console.log(error);
}
if (document.contentEditable) {
iframe.contentWindow.document.designMode = "On";
callback();
return true;
} else if (document.designMode !== null) {
try {
iframe.contentWindow.document.designMode = "on";
callback();
return true;
} catch (error) {
console.log(error);
}
}
setTimeout(function () {
tryEnableDesignMode(doc, callback);
}, 500);
return false;
}
function disableDesignMode(submit) {
var content = $(iframe).contents().find("body").html();
if ($(iframe).is(":visible")) {
textarea.val(content);
}
if (submit !== true) {
textarea.show();
$(iframe).hide();
}
}
// create toolbar and bind events to it's elements
function toolbar() {
var tb = $("<div class='rte-toolbar' id='toolbar-" + element_id + "'><div>\
<p>\
<a href='#' class='bold'>Bold</a>\
<a href='#' class='italic'>Italic</a>\
<a href='#' class='unorderedlist'>List</a>\
</p></div></div>");
$('.bold', tb).click(function () {
formatText('bold');
return false;
});
$('.italic', tb).click(function () {
formatText('italic');
return false;
});
$('.unorderedlist', tb).click(function () {
formatText('insertunorderedlist');
return false;
});
$(iframe).parents('form').submit(function () {
disableDesignMode(true);
});
var iframeDoc = $(iframe.contentWindow.document);
var select = $('select', tb)[0];
iframeDoc.mouseup(function () {
setSelectedType(getSelectionElement(), select);
return true;
});
iframeDoc.keyup(function () {
setSelectedType(getSelectionElement(), select);
var body = $('body', iframeDoc);
if (body.scrollTop() > 0) {
var iframe_height = parseInt(iframe.style.height, 10);
if (isNaN(iframe_height)) iframe_height = 0;
var h = Math.min(opts.max_height, iframe_height + body.scrollTop()) + 'px';
iframe.style.height = h;
}
return true;
});
return tb;
}
function formatText(command, option) {
iframe.contentWindow.focus();
try {
iframe.contentWindow.document.execCommand(command, false, option);
} catch (e) {
console.log(e);
}
iframe.contentWindow.focus();
}
function setSelectedType(node, select) {
while (node.parentNode) {
var nName = node.nodeName.toLowerCase();
for (var i = 0; i < select.options.length; i++) {
if (nName == select.options[i].value) {
select.selectedIndex = i;
return true;
}
}
node = node.parentNode;
}
select.selectedIndex = 0;
return true;
}
function getSelectionElement() {
if (iframe.contentWindow.document.selection) {
// IE selections
selection = iframe.contentWindow.document.selection;
range = selection.createRange();
try {
node = range.parentElement();
} catch (e) {
return false;
}
} else {
// Mozilla selections
try {
selection = iframe.contentWindow.getSelection();
range = selection.getRangeAt(0);
} catch (e) {
return false;
}
node = range.commonAncestorContainer;
}
return node;
}
// enable design mode now
enableDesignMode();
}); //return this.each
}; // rte
} // if
$(".rte-zone").rte({});
})(jQuery);
</code></pre>
<p>Can anyone give me some feedback on my work? Is there any room for improving or refactoring? It seems to work in every browser I tried which I am pretty happy with a degrades gracefully if JavaScript is not enabled.</p>
|
[] |
[
{
"body": "<p>Just three quick notes about clean code, not a complete review:</p>\n\n<ol>\n<li><p>You could extract out some functions which would make some comments unnecessary, like:</p>\n\n<pre><code>// IE selections\n// Mozilla selections\n</code></pre>\n\n<p>Just create functions for them, like <code>ieSelections</code> and <code>mozillaSelections</code>.</p></li>\n<li><p>I'd introduce an explanatory variable here:</p>\n\n<pre><code>if (iframe.contentWindow.document.selection) ...\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>var isInternetExplorer = iframe.contentWindow.document.selection;\nif (isInternetExplorer) ...\n</code></pre>\n\n<p>Reference: <em>Chapter 6. Composing Methods</em>, <em>Introduce Explaining Variable</em> in <em>Refactoring: Improving the Design of Existing Code</em> by Martin Fowler:</p>\n\n<blockquote>\n <p>Put the result of the expression, or parts of the expression, \n in a temporary variable with a name that explains the purpose.</p>\n</blockquote>\n\n<p>And <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>G19: Use Explanatory Variables</em>.</p></li>\n<li><p>This comment also seems unnecessary:</p>\n\n<pre><code>// enable design mode now\nenableDesignMode();\n</code></pre>\n\n<p>The name of the function also says that. </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T09:34:06.457",
"Id": "29016",
"ParentId": "28882",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T15:25:13.227",
"Id": "28882",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"html",
"text-editor"
],
"Title": "Custom WYSIWYG Editor"
}
|
28882
|
<p>I've taught myself some basic HTML/CSS over the past few weeks and just finished up my first horizontally scrolling single page site last night. I went for a clean minimal design and achieved the look I was going for, but am absolutely sure I did some things the hard way. Would really appreciate any advice on how I could have made the code cleaner and more efficient. Criticism welcome.</p>
<p><strong>HTML:</strong></p>
<pre><code><!DOCTYPE html><html lang="en"><head><meta charset="utf-8">
<html>
<head>
<title>stan's page</title>
<link rel="stylesheet" type="text/css" href= "fonts.css">
<link rel = "stylesheet" type="text/css" href= "header.css">
</head>
<body>
<div id="header">
<ul>
<li id="home_link"><a href="#home">home</a></li><li id="about_link"><a href="#aboutme">about</a></li><li id="work_link"><a href="#work">work</a></li><li id="contact_link"><a href="#contact">contact</a></li>
</ul>
</div>
<div id="home">
<div id="homeinfo">
<p>hi there</p><br><p>my name's stan</p><br><p>i'm an aspiring developer</p><br><p>it's quite the pleasure to meet you</p>
</div>
<div id="homepic">
<img src ="homepic.jpg">
</div>
</div>
<div id="aboutme">
<h1>about me</h1>
<div id="leftlist">
<ul>
<li>Lorem ipsum dolor sit amet</li>
<li>consectetur adipisicing elit</li>
<li>sed do eiusmod tempor</li>
<li>incididunt ut labore et dolore</li>
</ul>
</div>
<div id="rightlist">
<ul>
<li>magna aliqua</li>
<li>Ut enim ad minim veniam</li>
<li>quis nostrud exercitation ullamco laboris</li>
<li>nisi ut aliquip ex ea commodo consequat</li>
</ul>
</div>
</div>
<div id="work">
<h1>my work thus far</h1>
<img src="lipsum.jpg">
<img src="janblom.jpg">
<img src="reddit.jpg">
<h1>more to come...</h1>
</div>
<div id="contact">
<h1>contact</h1>
<img src="email.png">
<img src="facebook.png">
<img src="twitter.png">
<img src="linkedin.png">
<img src="googleplus.png">
<img src="github.png">
</div>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>#header{
z-index:1;
height:60px;
width:100%;
background-color:#8a6954;
position:fixed;
float:top;
left:0;
top:0;
}
#header ul{
list-style:none;
margin:0;
padding:0;
}
#header li{
width:25%;
display:block;
float:left;
text-align:center;
font-size:50px;
font-family:surrounding;
font-weight:900;
margin-top:5px;
}
#header a{
text-decoration:none;
}
#header a:link{
color:#89B57F;
}
#header a:visited{
color:#7A8FA9;
}
#header a:hover{
color:#465F40;
}
#header a:active{
color:#1D2E45;
}
#home{
position:absolute;
background-color:#355851;
height:700px;
clear:top;
top:0;
left:0;
right:0;
bottom:0;
margin-left:auto;
margin-right:auto;
overflow:hidden;
}
#homeinfo{
position:absolute;
display:block;
top:50%;
left:50%;
padding-right:50px;
margin-top:-200px;
margin-left:-450px;
}
#homeinfo p{
font-family:surrounding;
color:#82A7A0;
font-size:30px;
padding:0;
}
#homepic{
position:relative;
left:50%;
top:50%;
margin-top:-182px;
margin-left:auto;
padding-left:40px;
}
#homepic img{
height:370px;
width:385px;
}
#aboutme{
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
background-color:#7A8FA9;
height:700px;
margin-top:700px;
font-family:surrounding;
}
#aboutme h1{
color:#1D2E45;
text-align:center;
margin-top:150px;
font-size:72px;
color:#1D2E45;
}
#leftlist, #rightlist{
font-size:30px;
list-style:none;
display:block;
color:#1D2E45;
}
#leftlist li{
margin-bottom:2px;
}
#leftlist{
position:absolute;
display:block;
top:50%;
left:50%;
padding-right:50px;
margin-top:-70px;
margin-left:-450px;
}
#rightlist{
position:relative;
left:50%;
top:50%;
margin-top:-314px;
}
#work{
text-align:center;
position:absolute;
top:0;
bottom:0;
right:0;
left:0;
height:700px;
margin-top:1400px;
background-color:#4E7346;
font-family:surrounding;
}
#work h1{
color:#94B58D;
text-align:center;
margin-top:80px;
font-size:72px;
padding-bottom:20px;
}
#work img{
height:250px;
width:400px;
padding-left:15px;
padding-bottom:-40px;
}
#contact{
text-align:center;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
height:700px;
margin-top:2100px;
background-color:#314944;
font-family:surrounding;
}
#contact h1{
color:#8A6954;
margin-top:250px;
font-size:72px;
}
</code></pre>
<p>There's a separate fonts.css file which just imports the fonts from my computer.</p>
|
[] |
[
{
"body": "<p>You've tried to declare both a <code>html</code> and a <code>head</code> element twice:</p>\n\n<pre><code><!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\">\n<html>\n <head>\n <title>stan's page</title>\n ...\n</code></pre>\n\n<p>Here's how it should look:</p>\n\n<pre><code><!DOCTYPE html>\n<html lang=en>\n <head>\n <meta charset=utf-8>\n <title>stan's page</title>\n ...\n</code></pre>\n\n<p>Note that it's no longer required (but still allowed) to quote attributes in HTML5, unless they would otherwise be ambiguous (for instance, if they contain spaces). </p>\n\n<p>You're also using a lot of <code>div</code>s. Since you're using a HTML5 doctype, you could change e.g.</p>\n\n<pre><code><div id=\"header\">\n <ul>\n <li id=\"home_link\"><a href=\"#home\">home</a></li><li id=\"about_link\"><a href=\"#aboutme\">about</a></li><li id=\"work_link\"><a href=\"#work\">work</a></li><li id=\"contact_link\"><a href=\"#contact\">contact</a></li>\n </ul>\n</div>\n</code></pre>\n\n<p>to something like</p>\n\n<pre><code><header>\n <nav> \n <ul>\n <li id=home_link><a href=#home>home</a></li>\n <li id=about_link><a href=#aboutme>about</a></li>\n <li id=work_link><a href=#work>work</a></li>\n <li id=contact_link><a href=#contact>contact</a></li>\n </ul>\n </nav> \n</header>\n</code></pre>\n\n<p>Technically the closing <code></li></code> tag is no longer required, but some people (myself included) prefer to keep it.</p>\n\n<p>Some of your other <code>div</code>s would probably be better of as <code>section</code> or maybe <code>article</code> elements; when to use each of those is often a judgement call as to whether a block can stand on its own or not.</p>\n\n<p><a href=\"http://diveintohtml5.info/semantics.html#new-elements\" rel=\"nofollow\">New Semantic Elements in HTML5</a> From <a href=\"http://diveintohtml5.info\" rel=\"nofollow\">Dive Into HTML5</a> has a good summary of the new elements available to you, and when to use them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T18:23:38.217",
"Id": "45413",
"Score": "1",
"body": "I disagree on the suggestion of the section element. If the content is able to stand on its own, then an article tag is more appropriate. It's also not invalid to use quotes around attributes and they *are* required if the attribute value has a space in it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T18:28:37.447",
"Id": "45416",
"Score": "0",
"body": "@cimmanon on attributes: I thought I was clear that quotes are \"no longer required\" rather than prohibited. I'll clarify my \"ambiguous\" comment to mention spaces."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T18:29:45.617",
"Id": "45418",
"Score": "0",
"body": "Quotes were not required in HTML4 (unless there were spaces involved), either, but I consider it good practice to always include them, just like I consider it good practice to always provide a closing tag for every element even when it is optional."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T18:32:56.997",
"Id": "45420",
"Score": "0",
"body": "@cimmanon but they *were* required (and a lot of people made a lot of fuss about it) in XHTML, and as a result many people erroneously believe they still are. Proponents of HTML5 are often just as opinionated about them being pointless fluff; it's really just a preference thing at this point (as with optional closing tags, as you point out)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:30:20.680",
"Id": "45432",
"Score": "0",
"body": "What was required in XHTML is irrelevant: HTML4 is the predecessor of HTML5."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:31:46.090",
"Id": "45434",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9788/discussion-between-zero-piraeus-and-cimmanon)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T18:21:14.577",
"Id": "28889",
"ParentId": "28887",
"Score": "0"
}
},
{
"body": "<p>The br element is being misused here. If you wish to have your paragraphs spaced farther apart, adjust their margins via CSS.</p>\n\n<p>The text \"more to come...\" appears within an h1 tag, but what is it a headline for? Use the semantically appropriate tag for the content in question, don't choose a tag because of how it looks. Any tag could be styled via CSS to look like an h1.</p>\n\n<p>There is no <code>top</code> value for the <code>float</code> or <code>clear</code> properties (<code>#header</code>) and paddings can't have negative values (<code>#work img</code>). Validating your CSS would have caught this.</p>\n\n<p>Setting fixed dimensions on elements containing text (<code>#header</code>) is a good way to set yourself up for failure. Text is fluid by nature. Even though you feel you have provided the appropriate amount of space, there are many variables that are out of your hands:</p>\n\n<ul>\n<li>The user may not have the font you've specified and is using a fallback font that has slightly different font attributes (maybe you've seen a comparison between Helvetica for Mac vs Windows?)</li>\n<li>The user might have have adjusted their desired font-size for accessibility reasons</li>\n<li>The user might have set a minimum font-size that is larger than your desired font-size</li>\n</ul>\n\n<p>Using relative font-sizes would minimize this problem (but not completely eliminate it):</p>\n\n<pre><code>element {\n font-size: 2em;\n line-height: 1;\n height: 2em;\n}\n</code></pre>\n\n<p>When you float an element, most display types are ignored so there's no reason to specify them (<code>#header li</code>). Floated elements secretly get their display type modified to something that's <em>like</em> but not quite inline-block.</p>\n\n<p>What's the deal with all of the absolutely positioned elements (<code>#home</code>, <code>#aboutme</code>, etc.)? Generally speaking, absolute positioning for layout purposes should be avoided. Just like I mentioned above regarding setting fixed heights on text elements, absolute positioning can really bite you in the butt for pretty much the same reasons.</p>\n\n<p>There's an overuse of id's here. Yes, they are the fastest selector, but its efficiency is greatly exaggerated compared to class or element selectors. Even descendant selectors are not as slow as many people make them out to be.</p>\n\n<p>What <em>really</em> makes <code>#home</code> and <code>#aboutme</code> different? Their positioning (which shouldn't be used anyway) and their background color? When you have a lot of shared styles, they should be shifted to a common selector:</p>\n\n<pre><code>article {\n /* common styles */\n}\n\n#foo {\n background: blue;\n}\n\n#bar {\n background: yellow;\n}\n</code></pre>\n\n<p>Be aware that using a custom font-face for the majority of your copy text is <em>not</em> a good idea from the user's perspective: <a href=\"https://superuser.com/questions/547743/why-dont-websites-immediately-display-their-text-these-days\">https://superuser.com/questions/547743/why-dont-websites-immediately-display-their-text-these-days</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:41:38.523",
"Id": "45439",
"Score": "0",
"body": "Thanks for all the tips cimmanon. So about the absolute positioning. I tried all the others and ended up with a white line on the left and right side of my screen. Only way to resolve it was to use absolute positioning. Any suggestions on how to do this otherwise?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:45:47.933",
"Id": "45440",
"Score": "0",
"body": "Can you provide a [demo](http://cssdeck.com/labs) of the problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:58:53.743",
"Id": "45441",
"Score": "0",
"body": "weird. in the cssdeck it doesn't give me the same issue. i did take a screenshot and you can see on my right monitor how the #home section which i took absolute positioning off of is indented slightly on the right and left compared to the #aboutme http://imgur.com/G2XIuiw"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T20:05:53.570",
"Id": "45442",
"Score": "0",
"body": "i also have a question regarding custom font-faces...i skimmed that article you linked and see they are talking mostly about web fonts. Can i keep the font stored in some way that it is easily accessible by the site for users who do not have the font on their own computer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T20:17:26.577",
"Id": "45443",
"Score": "0",
"body": "The only way you can realistically expect a user to view a custom font that's not installed on their system is with `@font-face`. It doesn't *have* to be hosted by Google, you can host it wherever you want provided you have the licensing to do so (the end result for the user will be the same)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T20:26:31.723",
"Id": "45444",
"Score": "0",
"body": "Cssdeck uses a reset by default, which can cause different results (there is an option to turn it off)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T20:57:35.860",
"Id": "45569",
"Score": "0",
"body": "A reset is exactly what I needed...used the one found here...http://meyerweb.com/eric/tools/css/reset/"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:22:37.727",
"Id": "28894",
"ParentId": "28887",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28894",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T16:54:44.703",
"Id": "28887",
"Score": "4",
"Tags": [
"optimization",
"html",
"css"
],
"Title": "Review on efficiency and correctness appreciated for my first single-page website"
}
|
28887
|
<p>I have a <code>byte</code> array and a <code>List</code> of a custom object <code>ByteRule</code> and I'm needing to loop around and perform an operation on both but only as long as one of both is available, the original method is as follows:</p>
<pre><code>private final List<ByteRule> rules;
@Override
public boolean match(final InetAddress addr)
{
final byte[] bytes = addr.getAddress();
for(int i = 0; i < this.rules.size() && i < bytes.length; i++)
{
final int value = bytes[i] < 0 ? (int) bytes[i] + 256 : bytes[i];
if(!this.rules.get(i).match(value))
{
return false;
}
}
return true;
}
</code></pre>
<p>Obviously the <code>this.rules.get(i)</code> on every iteration is inefficient, however as I need to maintain a counter, an enhanced <code>for</code> loop means keeping a separate counter and performing a check on it every time like so (list declaration skipped for space):</p>
<pre><code>@Override
public boolean match(final InetAddress addr)
{
final byte[] bytes = addr.getAddress();
int counter = 0;
for(final ByteRule rule : this.rules)
{
if(counter + 1 == bytes.length) break; //In case there aren't enough bytes
final int value = bytes[counter] < 0 ? (int) bytes[counter] + 256 : bytes[counter];
if(!rule.match(value))
{
return false;
}
counter++;
}
return true;
}
</code></pre>
<p>Is there a cleaner/more efficient solution to this problem that I'm missing?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T06:36:00.977",
"Id": "45454",
"Score": "0",
"body": "*Obviously the `this.rules.get(i)` on every iteration is inefficient* That is not obvious to me at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T06:44:59.437",
"Id": "45456",
"Score": "1",
"body": "[This](http://stackoverflow.com/a/7401635/2268996) is how you can get rid of the ternary expression. Bitwise AND it with `0xFF`."
}
] |
[
{
"body": "<p>I would be happy with:</p>\n\n<pre><code>@Override\npublic boolean match(final InetAddress inetAddress)\n{\n final byte[] bytes = inetAddress.getAddress();\n int end = Math.min(this.rules.size(), bytes.length);\n for(int i = 0; i < end; i++)\n {\n final int adressPart = bytes[i] & 0xFF; //byte range from -128 to 127, &0xFF makes it unsigned, therefore positive\n if(!this.rules.get(i).match(adressPart))\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>If you think, the <code>this.rules.get(i)</code>, then test it with a profiler. I would be surprised if this line is the reason for any slowdown, because the length of a InetAddress is probably quite limited and most likely implemented as an ArrayList annyway. If it really matters, you can change it to:</p>\n\n<pre><code>@Override\npublic boolean match(final InetAddress inetAddress)\n{\n final byte[] bytes = inetAddress.getAddress();\n ByteRule[] byteRulesArray = rules.toArray(new String[rules.size()]);\n int end = Math.min(this.rules.size(), bytes.length);\n for(int i = 0; i < end; i++)\n {\n final int adressPart = bytes[i] & 0xFF; //byte range from -128 to 127, &0xFF makes it unsigned, therefore positive\n if(!byteRulesArray[i].match(adressPart))\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>or if you even fear the array creation, you can use an iterator:</p>\n\n<pre><code>@Override\npublic boolean match(final InetAddress inetAddress)\n{\n final byte[] bytes = inetAddress.getAddress();\n Iterator<ByteRule> rulesIterator = rules.iterator();\n int end = Math.min(this.rules.size(), bytes.length);\n for(int i = 0; i < end; i++)\n {\n final int adressPart = bytes[i] & 0xFF; //byte range from -128 to 127, &0xFF makes it unsigned, therefore positive\n if(!rulesIterator.next.match(adressPart))\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Hint: In theory, the iterator solution would be faster than the array creation. However in the real world, because of hardware reasons, the array creation will, most likely, be faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T20:35:43.487",
"Id": "45566",
"Score": "0",
"body": "I love the third solution, thank you very much for your help."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:25:10.313",
"Id": "28940",
"ParentId": "28891",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28940",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T18:50:53.097",
"Id": "28891",
"Score": "1",
"Tags": [
"java"
],
"Title": "Iterating over an Array and an Iterable (List)"
}
|
28891
|
<p>Can the metafunction below be implemented more elegantly, with less code? What I have now is not very elegant or smartly written.</p>
<pre><code>#include <type_traits>
namespace detail
{
template <typename T, typename A, typename ...B>
struct max_type
{
typedef typename max_type<
typename std::conditional<(sizeof(A) > sizeof(T)), A, T>::type,
B...
>::type type;
};
template <typename T, typename A>
struct max_type<T, A>
{
typedef typename std::conditional<(sizeof(A) > sizeof(T)), A, T>::type type;
};
}
template <typename A, typename... B>
struct max_type
{
typedef typename detail::max_type<A, A, B...>::type type;
};
</code></pre>
|
[] |
[
{
"body": "<p>How about this? It’s not all that much shorter, but IMHO quite a bit simpler:</p>\n\n<pre><code>#include <type_traits>\n\ntemplate <typename A, typename... B>\nstruct max_type\n{\n typedef typename max_type<A, typename max_type<B...>::type>::type type;\n};\n\ntemplate <typename A>\nstruct max_type<A>\n{\n typedef A type;\n};\n\ntemplate <typename A, typename B>\nstruct max_type<A,B>\n{\n typedef typename std::conditional<(sizeof(A) > sizeof(B)), A, B>::type type;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T06:36:49.307",
"Id": "45455",
"Score": "0",
"body": "Nice, even though I've really wanted a bit less code :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T23:01:05.683",
"Id": "28903",
"ParentId": "28892",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "28903",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:05:09.800",
"Id": "28892",
"Score": "4",
"Tags": [
"c++",
"c++11"
],
"Title": "metafunction to determinate the biggest of all supplied types"
}
|
28892
|
<p>To summarize from a previous question, the user selected a starting date, an ending date, and a region. From these choices, an array of weeks and regions are created, and users enter values ("points") that correspond to a particular week and region. This is what it looks like right now (some parts are hard-coded for testing purposes):</p>
<pre><code>$date_array = Array("01/01/2012", "01/08/2012", "01/15/2012");
$region_array = Array("NYC", "DC");
<form name="test_form" id="test_form" method="post">
<table border="1">
<tr>
<td></td>
<?php
foreach ($date_array as $date)
{
echo "<td>".$date."</td>";
}
?>
</tr>
<?php
foreach ($region_array as $region)
{
echo "<tr>";
echo "<td>".$region."</td>";
foreach ($date_array as $date)
{
echo '<td><input type="text" name='.$region."-value1_".$date.'><input type="text" name='.$region."-value2_".$date.'></td>';
}
echo "</tr>";
}
?>
</table>
<input type="submit" name="submit">
</code></pre>
<p></p>
<p>And the next part:</p>
<pre><code>if (isset($_POST['submit']))
{
foreach ($_POST as $k=>$v)
{
if ($k != "submit") // use even and odd count to differentiate TRP and CPP
{
// split the form input on _
$input = explode("_", $k);
echo "<BR>Region: " . $input[0];
echo "<BR>Date: " . $input[1];
echo "<BR>Value: " . $v;
}
echo "<br/>";
}
}
</code></pre>
<p>So basically, in this example it outputs 12 times:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Region: NYC-value1
Date: 01/01/2012
Value: 500
Region: NYC-value2
Date: 01/01/2012
Value: 5
Region: NYC-value1
Date: 01/08/2012
Value: 600
</code></pre>
</blockquote>
<p>I want to catch the <code>value1</code> and <code>value2</code> while the loop is running, but as it stands it loops through both of them before going onto the next date/region. My idea, as I put in comments, was to have a counter of even and odd numbers and simply tell if it was doing <code>value1</code> or <code>value2</code> based on that.</p>
<p>Is this a good idea or am I missing something fundamentally simpler?</p>
|
[] |
[
{
"body": "<p>Try this:</p>\n\n<pre><code><?php\nif(isset($_POST['submit'])){\n foreach ($_POST as $k=>$v){\n // use even and odd count to differentiate TRP and CPP\n if ($k != \"submit\") {\n // split the form input on _\n $input = explode(\"_\", $k);\n echo \"<BR>Region: \" . $input[0];\n echo \"<BR>Date: \" . $input[2];\n if($input[1] == \"value1\"){\n echo \"<BR>Value 1: \" . $v;\n }\n elseif($input[1] == \"value2\"){\n echo \"<BR>Value 2: \" . $v;\n }\n }\n echo \"<br/>\";\n }\n}\nelse {\n $date_array = Array(\"01/01/2012\", \"01/08/2012\", \"01/15/2012\");\n $region_array = Array(\"NYC\", \"DC\");\n?>\n <form name=\"test_form\" id=\"test_form\" method=\"post\" action=\"\">\n <table border=\"1\">\n <tr>\n <td></td>\n<?php\n foreach ($date_array as $date){\n echo \"<td>\".$date.\"</td>\";\n }\n?>\n </tr>\n<?php\n foreach ($region_array as $region){\n echo \"<tr>\";\n echo \"<td>\".$region.\"</td>\";\n foreach ($date_array as $date){\n echo '<td><input type=\"text\" name='.$region.\"_value1_\".$date.'><input type=\"text\" name='.$region.\"_value2_\".$date.'></td>';\n }\n echo \"</tr>\";\n }\n?>\n </table>\n <input type=\"submit\" name=\"submit\">\n</form>\n<?php\n}\n?>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:38:29.933",
"Id": "45436",
"Score": "0",
"body": "Ah I see, you created an extra \"_\" in the form and made the value inside a conditional clause for which value to display. In the future, I can replace the echo inside of the if statements with database queries. Looks like you did it again, thanks. I'm gonna try to keep learning about web development and thanks to you, I've learned a few nice ways to use the explode() function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:40:17.537",
"Id": "45437",
"Score": "0",
"body": "sure no problem. Glad I could help. PHP has a very good collection of functions when it comes to string manipulation. If you are completely new to PHP/MySQL then you might want to focus next on should be using MySQLi/PDO and parametrized queries, input data validation and security etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:23:45.393",
"Id": "28895",
"ParentId": "28893",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28895",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:07:07.250",
"Id": "28893",
"Score": "2",
"Tags": [
"php",
"html",
"sql",
"form"
],
"Title": "Multiple input fields from PHP table"
}
|
28893
|
<p>This code handles a response from an RSS feed. It organizes and appends to content. If there's a video embeded then separate it from the rest of the content. I would like a review mainly on performance/efficiency but I'm open to any other suggestions as well. That star selector is really nagging me but I don't know of a better way to iterate over all the contained elements.</p>
<pre><code>function getFeed(url, element, callback) {
$.getJSON("https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&callback=?&q="+encodeURIComponent(url), function(response) {
var content = "",
$element = $(element);
for (var i = 0; i < response.responseData.feed.entries.length; i++) {
content = content + response.responseData.feed.entries[i].content; //Join all the feed entries
}
$element.find(".content").html(content).addClass($element.find("embed").length? "withVideo" : "");
$element.find("*").each(function() {
var $this = $(this);
$this.removeAttr("style width align"); //Reset all the crap that comes with the response
if ($this.is("embed")) {
$element.append("<div class='video'></div>");
$this.attr("width", 640).attr("height", 360).parent().appendTo(element + " .video");
};
});
if (typeof callback === 'function') {
callback();
};
});
}
</code></pre>
<p>This is then called like so:</p>
<pre><code>getFeed("http://www.kent.k12.wa.us/site/RSS.aspx?PageID=3854", "#TechExpo", optionalCallback);
</code></pre>
<p>Here's what a response might look like</p>
<pre><code><div width="500" style="whatever"><p>Some text blah blah blah.</p>
<p align="right">Some more text</p>
</div>
<div><h2>Video Title</h2>
<embed src="http://..." width="360" height="202" type="application/x-shockwave-flash"></embed>
<small>Watch the 7th annual Tech Expo highlights.</small></div>
</code></pre>
|
[] |
[
{
"body": "<p>Late reply,</p>\n\n<p>this code is good, I can only find 2 faults:</p>\n\n<ol>\n<li><p>Your code should have error handling for the JSON call, things can go wrong</p></li>\n<li><p>Too much horizontal stretching, I would introduce some sugar for this:</p>\n\n<pre><code>for (var i = 0; i < response.responseData.feed.entries.length; i++) {\n content = content + response.responseData.feed.entries[i].content; //Join all the feed entries\n}\n</code></pre>\n\n<p>could be</p>\n\n<pre><code>var entries = response.responseData.feed.entries;\nfor (var i = 0; i < entries.length; i++) {\n content = content + entries[i].content; //Join all the feed entries\n}\n</code></pre>\n\n<p>Also, I find</p>\n\n<pre><code>$element.find(\".content\").html(content)\n .addClass($element.find(\"embed\").length? \"withVideo\" : \"\");\n</code></pre>\n\n<p>more readable.</p></li>\n</ol>\n\n<p>As for <code>find(\"*\")</code>, it seems to be cleanest way to access all children.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-28T14:00:45.520",
"Id": "48400",
"ParentId": "28896",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T19:53:04.577",
"Id": "28896",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"optimization",
"ajax"
],
"Title": "Improve AJAX response handling function"
}
|
28896
|
<p>I'm developing a class to compare prices. For example, give me products which price are above 50 or under 50. Here's my API:</p>
<pre><code>var indicator = new PriceIndicator(PriceComparison.Above, 50);
var actual = indicator.Apply(listOfProductPrices);
</code></pre>
<p>I managed to design my code for the operator Above and Under comparison:</p>
<pre><code>public abstract class PriceComparison
{
public static readonly UnderPriceComparison Under = new UnderPriceComparison();
public static readonly AbovePriceComparison Above = new AbovePriceComparison();
public abstract bool Evaluate(double price, double valueToCompare);
}
public class AbovePriceComparison : PriceComparison
{
public override bool Evaluate(double price, double valueToCompare)
{
return price > valueToCompare;
}
}
public class UnderPriceComparison : PriceComparison
{
public override bool Evaluate(double price, double valueToCompare)
{
return price < valueToCompare;
}
}
public class PriceIndicator : IBuyIndicator
{
private readonly PriceComparison _comparison;
private readonly int _value;
public PriceIndicator(PriceComparison comparison, int value)
{
_comparison = comparison;
_value = value;
}
public IList<BuyOrder> Apply(IList<int> productPrices)
{
return productPrices.Where(price => _comparison.Evaluate(price, _value))
.Select(b => new BuyOrder(b))
.ToList();
}
}
</code></pre>
<p>Now, I want to manage Range price. I want my API to look as simple as the one above. Ideally, it would be</p>
<pre><code>var indicator = new PriceIndicator(PriceComparison.Range, 50, 100); // Here's the change
var actual = indicator.Apply(listOfProductPrices);
</code></pre>
<p>I don't know how I can design this. What I tried to do so far is to add another Evaluate method in <code>PriceComparison</code>, which takes three parameters: <code>double price, double left, double right</code>. But then, my previous two methods have to implement it and will have to throw <code>IncorrectComparisonException</code> because they can only compare with one value. So I'm not really fan of this design.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T23:20:22.283",
"Id": "45445",
"Score": "0",
"body": "Your code won't compile, there is no `Close` property on `int`. You should post (parts of) your real code, not something you didn't even bother compiling."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T23:21:02.273",
"Id": "45446",
"Score": "0",
"body": "Also, never ever use `double` for prices, that's exactly what `decimal` is for."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T17:53:41.813",
"Id": "45545",
"Score": "0",
"body": "@svick your answer looks so rude. I did remove the Close property from an edit, and you can see in modification historic that I did it but it doesn't appear. Then, the code I posted here is pretty much 98% part of my real code, except for the variable listOfProductPrices and I did take something like 30min to write my question and later re read it many time to fix some mistakes + the help of jamal who was the first to fix some gramatical error. Anyway, it was my first question on codereview, and your answer really hurt me. Then you say, I should use decimal instead of double for price, can you"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T17:56:50.343",
"Id": "45546",
"Score": "0",
"body": "please explain why so it could help me and other people without needed to have to search ourself on the web ? Anyway, I'm not interested by an answer to my code review anymore. I always take the time to post a clear question and there're people like you who says rude thing. It totally destroyed my work day. Thanks for your comment and the -1 by the way."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:40:27.020",
"Id": "45551",
"Score": "1",
"body": "1. I did not downvote your question. 2. From the history, it looks to me like the edit from Jamal overwrote the `Close` change, I tried to fix that now. I also voted to reopen the question. 3. You really should post your real code, it's hard to review code that doesn't make sense and some suggestions based on the altered code might not be applicable to your real code. 4. If you really aren't interested in answers anymore, feel free to delete the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:44:22.163",
"Id": "45552",
"Score": "1",
"body": "Regarding `decimal`: the short version is that `double` is a *binary* floating point type, which means it can't represent numbers like `0.1` exactly (and so for example `0.1 + 0.7 != 0.8`). On the other hand, `decimal` is a *decimal* floating point type, so it can represent decimal fractions exactly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T19:01:45.560",
"Id": "45553",
"Score": "0",
"body": "@JohnSmith: Questions automatically receive a -1 upon closing. As for svick's compiler note, all code should be compiled before posting. This site is only for working code, but underlying errors not found by you nor the compiler _are_ okay even if found by someone else. Seeing as svick fixed the issue, I'll put in my reopen vote as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T19:47:35.573",
"Id": "45554",
"Score": "0",
"body": "@svick tell me that you're sorry for being rude and I'll accept my question to be reopened for answers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T19:57:36.280",
"Id": "45557",
"Score": "0",
"body": "@Jamal Thanks Jamal for your kind and complete answer, I will now always compile my code before posting a new question on codereview.com. It's really different here than in stackoverflow, overthere I always put some half uncompiled code and people never complain. I guess, it was obvious we need to put more effort here as it's about judging the quality of code and people may need to test our code in order to provide the most accurate solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T20:00:42.370",
"Id": "45558",
"Score": "0",
"body": "@JohnSmith: Right. Over there, _errors are solved_. Here, _design is improved_. I'm glad I've helped."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T20:30:34.617",
"Id": "45565",
"Score": "0",
"body": "@svick btw, I tried in unit test 0.1 + 0.7, and you're right, it's not equal to 0.8 ? Why you say it can't represent 0.1 exactly ? What I found on the web is that the main difference between decimal and double is precision and as you said one is binary floating and the other one is decimal floating. Still I don't get why its not equal 0.1+0.7 != 0.8, why it can't represent accurately these values in binary ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T20:55:22.143",
"Id": "45568",
"Score": "0",
"body": "You can't represent 1/3 exactly in decimal fractions, you have to write something like 0.33333. It's very similar with 1/10 and binary fractions. The difference is that you don't have tenths, hundredths, etc., but you have halves, quarters, eights and so on. So, 3/8 can be represented exactly as 0.011, but 1/10 can't."
}
] |
[
{
"body": "<p>Here you go. I made <code>Range</code> inclusive only, but it's easy to modify. I also extracted a few interfaces for easy unit testing and use <code>IEnumerable<T></code> instead of <code>IList<T></code>.</p>\n\n<pre><code>public interface IPriceComparison\n{\n bool Evaluate(decimal price, params decimal[] valuesToCompare);\n}\n\npublic abstract class PriceComparison : IPriceComparison\n{\n private static readonly IPriceComparison under = UnderPriceComparison.Create();\n\n private static readonly IPriceComparison above = AbovePriceComparison.Create();\n\n private static readonly IPriceComparison range = RangePriceComparison.Create();\n\n public static IPriceComparison Under\n {\n get\n {\n return under;\n }\n }\n\n public static IPriceComparison Above\n {\n get\n {\n return above;\n }\n }\n\n public static IPriceComparison Range\n {\n get\n {\n return range;\n }\n }\n\n public abstract bool Evaluate(decimal price, params decimal[] valuesToCompare);\n}\n\npublic sealed class AbovePriceComparison : PriceComparison\n{\n private AbovePriceComparison()\n {\n }\n\n public static IPriceComparison Create()\n {\n return new AbovePriceComparison();\n }\n\n public override bool Evaluate(decimal price, params decimal[] valuesToCompare)\n {\n return (valuesToCompare == null) || (valuesToCompare.Length != 1) || (price > valuesToCompare[0]);\n }\n}\n\npublic sealed class UnderPriceComparison : PriceComparison\n{\n private UnderPriceComparison()\n {\n }\n\n public static IPriceComparison Create()\n {\n return new UnderPriceComparison();\n }\n\n public override bool Evaluate(decimal price, params decimal[] valuesToCompare)\n {\n return (valuesToCompare == null) || (valuesToCompare.Length != 1) || (price < valuesToCompare[0]);\n }\n}\n\npublic sealed class RangePriceComparison : PriceComparison\n{\n private RangePriceComparison()\n {\n }\n\n public static IPriceComparison Create()\n {\n return new RangePriceComparison();\n }\n\n public override bool Evaluate(decimal price, params decimal[] valuesToCompare)\n {\n return (valuesToCompare == null)\n || (valuesToCompare.Length != 2)\n || ((price > valuesToCompare[0]) && (price < valuesToCompare[1]));\n }\n}\n\npublic interface IBuyOrder\n{\n int Price\n {\n get;\n }\n}\n\npublic sealed class BuyOrder : IBuyOrder\n{\n private readonly int price;\n\n private BuyOrder(int price)\n {\n this.price = price;\n }\n\n public static IBuyOrder Create(int price)\n {\n return new BuyOrder(price);\n }\n\n public int Price\n {\n get\n {\n return this.price;\n }\n }\n}\n\npublic interface IBuyIndicator\n{\n IEnumerable<IBuyOrder> Apply(IEnumerable<int> productPrices);\n}\n\npublic sealed class PriceIndicator : IBuyIndicator\n{\n private readonly IPriceComparison comparison;\n\n private readonly decimal[] values;\n\n private PriceIndicator(IPriceComparison comparison, params decimal[] values)\n {\n if (comparison == null)\n {\n throw new ArgumentNullException(\"comparison\");\n }\n\n this.comparison = comparison;\n this.values = values;\n }\n\n public static IBuyIndicator Create(IPriceComparison comparison, params decimal[] values)\n {\n return new PriceIndicator(comparison, values);\n }\n\n public IEnumerable<IBuyOrder> Apply(IEnumerable<int> productPrices)\n {\n return productPrices.Where(price => this.comparison.Evaluate(price, this.values))\n .Select(BuyOrder.Create)\n .ToList();\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:52:25.727",
"Id": "28998",
"ParentId": "28897",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28998",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T20:12:06.417",
"Id": "28897",
"Score": "1",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Comparison with a range"
}
|
28897
|
<p>I am given the following CSV file which I extracted from an excel spreadsheet. Just to give some background information which could be of assistance, it discusses AGI Numbers (think of it as protein identifiers), unmodified peptide sequences for those protein identifiers, and then modified peptide sequences with modifications made on the unmodified sequences, the index/indeces of those modifications, and then the combined spectral count for repeated peptides. The text file is called MASP.GlycoModReader.txt and the information is in the following format below:</p>
<pre><code>AGI,UnMd Peptide (M) = x,Mod Peptide (oM) = Ox,Index/Indeces of Modification,counts,Combined
Spectral count for repeated Peptides
AT1G56070.1,NMSVIAHVDHGKSTLTDSLVAAAGIIAQEVAGDVR,NoMSVIAHVDHGKSTLTDSLVAAAGIIAQEVAGDVR,2,17
AT1G56070.1,LYMEARPMEEGLAEAIDDGR,LYoMEARPoMEEGLAEAIDDGR,"3, 9",1
AT1G56070.1,EAMTPLSEFEDKL,EAoMTPLSEFEDKL,3,7
AT1G56070.1,LYMEARPMEEGLAEAIDDGR,LYoMEARPoMEEGLAEAIDDGR,"3, 9",2
AT1G56070.1,EGPLAEENMR,EGPLAEENoMR,9,2
AT1G56070.1,DLQDDFMGGAEIIK,DLQDDFoMGGAEIIK,7,1
</code></pre>
<p>The output file that needs to result after extracting the above is in the following format below:</p>
<pre><code>AT1G56070.1,{"peptides": [{"sequence": "NMSVIAHVDHGKSTLTDSLVAAAGIIAQEVAGDVR", "mod_sequence":
"NoMSVIAHVDHGKSTLTDSLVAAAGIIAQEVAGDVR" , "mod_indeces": 2, "spectral_count": 17}, {"sequence":
"LYMEARPMEEGLAEAIDDGR" , "mod_sequence": "LYoMEARPoMEEGLAEAIDDGR", "mod_indeces": [3, 9],
"spectral_count": 3}, {"sequence": "EAMTPLSEFEDKL" , "mod_sequence": "EAoMTPLSEFEDKL",
"mod_indeces": [3,9], "spectral_count": 7}, {"sequence": "EGPLAEENMR", "mod_sequence":
"EGPLAEENoMR", "mod_indeces": 9, "spectral_count": 2}, {"sequence": "DLQDDFMGGAEIIK",
"mod_sequence": "DLQDDFoMGGAEIIK", "mod_indeces": [7], "spectral_count": 1}]}
</code></pre>
<p>I have provided my solution below: If anyone has a better solution in another language or can possibly analyze mine and let me know if there are more efficient methods of coming about this, then please comment below. Thank you.</p>
<pre><code>#!/usr/bin/env node
var fs = require('fs');
var csv = require('csv');
var data ="proteins.csv";
/* Uses csv nodejs module to parse the proteins.csv file.
* Parses the csv file row by row and updates the peptide_arr.
* For new entries creates a peptide object, for similar entries it updates the
* counts in the peptide object with the same AGI#.
* Uses a peptide object to store protein ID AGI#, and the associated data.
* Writes all formatted peptide objects to a txt file - output.txt.
*/
// Tracks current row
var x = 0;
// An array of peptide objects stores the information from the csv file
var peptide_arr = [];
// csv module reads row by row from data
csv()
.from(data)
.to('debug.csv')
.transform(function(row, index) {
// For the first entry push a new peptide object with the AGI# (row[0])
if(x == 0) {
// cur is the current peptide read into row by csv module
Peptide cur = new Peptide( row[0] );
// Add the assoicated data from row (1-5) to cur
cur.data.peptides.push({
"sequence" : row[1];
"mod_sequence" : row[2];
if(row[5]){
"mod_indeces" : "[" + row[3] + ", " + row[4] + "]";
"spectral_count" : row[5];
} else {
"mod_indeces" : row[3];
"spectral_count" : row[4];
}
});
// Add the current peptide to the array
peptide_arr.push(cur);
}
// Move to the next row
x++;
});
// Loop through peptide_arr and append output with each peptide's AGI# and its data
String output = "";
for(var peptide in peptide_arr)
{
output = output + peptide.toString()
}
// Write the output to output.txt
fs.writeFile("output.txt", output);
/* Peptide Object :
* - id:AGI#
* - data: JSON Array associated
*/
function Peptide(id) // this is the actual function that does the ID retrieving and data
// storage
{
this.id = id;
this.data = {
peptides: []
};
}
/* Peptide methods :
* - toJson : Returns the properly formatted string
*/
Peptide.prototype = {
toString: function(){
return this.id + "," + JSON.stringify(this.data, null, " ") + "/n"
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T23:24:04.467",
"Id": "45447",
"Score": "2",
"body": "“If anyone has a better solution in another language” That's not what this site is for. This site is specifically for reviewing code you have written (so the “If anyone can analyze mine” part of your question could belong here)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T23:34:29.843",
"Id": "45448",
"Score": "0",
"body": "Okay, well I did include the latter part of the question like you mentioned. And I realized what you've said. I'll keep that in mind. Instead of stating the obvious, maybe actually giving your input would be appreciated too, unless you have none to give."
}
] |
[
{
"body": "<p>I'd say in general I think you have the right idea.<br>\nHowever I'm stuck on:</p>\n\n<pre><code>cur.data.peptides.push({\n \"sequence\" : row[1];\n \"mod_sequence\" : row[2];\n if(row[5]){\n \"mod_indeces\" : \"[\" + row[3] + \", \" + row[4] + \"]\";\n \"spectral_count\" : row[5]; \n } else {\n \"mod_indeces\" : row[3];\n \"spectral_count\" : row[4]; \n }\n})\n</code></pre>\n\n<p>As this doesn't look like valid Javascript to me.<br>\nI'd structure it like this:</p>\n\n<pre><code>// An array of peptide objects stores the information from the csv file\nvar alldata = {\n peptides : []\n};\nvar agi = null;\nfunction Peptide(row) \n{\n this.sequence = row[1];\n this.mod_sequence = row[2];\n if(row[5]){\n this.mod_indeces = [ row[3], row[4] ];\n this.spectral_count = row[5]; \n } else {\n this.mod_indeces= row[3];\n this.spectral_count= row[4]; \n };\n return this;\n}\n\n\n// csv module reads row by row from data \ncsv()\n.from(data)\n.to('debug.csv')\n.transform(function(row, index) { \n if(agi === null)\n {\n agi = row[0];\n }\n\n alldata.peptides.push(new Peptide(row));\n});\n\n// Write the output to output.txt\nfs.writeFile(\"output.txt\", agi + \",\" + JSON.stringify(alldata, null, \" \"));\n</code></pre>\n\n<p>We keep all the data in one object. It seems the output is separated by the <code>AGI</code> and it is a list. No need to deal with strings as its all done as an object with the data inside the Peptide function.<br>\nInstead of keeping count in <code>x</code> its a variable called <code>agi</code> that is initialised to <code>null</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-18T06:09:40.317",
"Id": "35575",
"ParentId": "28899",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T21:44:32.157",
"Id": "28899",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Parsing through CSV file to convert to JSON format file"
}
|
28899
|
<p>Other code review noted problems with commenting and non-C++ code. This post aims to follow up on those issues.</p>
<p>Please check:</p>
<ol>
<li>Comments are appropriate</li>
<li>Code is not C</li>
</ol>
<p>My test file contains:</p>
<blockquote>
<p>one two three four five six seven eight nine</p>
</blockquote>
<pre><code>//This app is an exercise/study: Etude fr1_x
// prints x number of words from file, without newline, as determined by
// short wordCount
// in:
// void printWord(std::vector<std::string> &word)
// the output is connected to a timer.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <unistd.h>
//number of times to repeat output when calling println();
//instead of writing:
//
// println();
// println();
//
//i can write:
//
// println((count)2);
//
//
//also, because println(int i) is already defined
typedef unsigned short count;
//TODO - yank all print[ln] to header
void print(std::string str){
std::cout << str << std::flush;
return;
}
void print(char c){
std::cout << c << std::flush;
return;
}
void print(int i){
std::cout << i << std::flush;
return;
}
void println(std::string str){
std::cout << str << std::endl;
return;
}
void println(){
std::cout << std::endl;
return;
}
void println(count c){
const short maxVal = 10;/*short-term control - might assign neg val to count
i did, just to test it.*/
if(c>maxVal){
println((count)2);//accidental recursion
println("Error:");
println("called 'println(count c) with invalid arg");
println("required: param c<=10");
exit(0);
}
for(int i=0;i<c;i++){
std::cout << std::endl;
}
return;
}
void println(char c){
std::cout << c << std::endl;
return;
}
void println(int i){
std::cout << i << std::endl;
return;
}
void println(short s){
std::cout << s << std::endl;
return;
}
std::string prompt(std::string str){
std::string prompt = (str + ": ");
std::string input;
print(prompt);
std::cin >> input;
return input;
}
std::string getFileName(){
return prompt("\nEnter a file name");
}
//TODO - break it up - too nested - too conditional
void readFile(std::vector<std::string> &word){
const std::string quit("quit");
std::string fileName;
std::string str;
short kontinue = 1;
do{
fileName = getFileName();
kontinue = fileName.compare(quit);
if(kontinue != 0){
std::ifstream file(fileName.c_str(),std::ios::in);
if(!file.is_open()){
continue;
}
//source:Thinking in C++, 2nd ed. Volue 1, Ch. 2: Introducing vector
while(file >> str){
word.push_back(str);
}
file.close();
break;
};
}while(kontinue != 0);
return;
}
void test(std::vector<std::string> &word){
int size = word.size();//could be a problem, maybe use long
println();
for(int i=0;i<size;i++){
print(word[i] + " ");
}
println((count)2);
for(int i=0;i<size;i++){
println(word[i]);
}
return;
}
void slp(){
usleep(1000000);//val will become user input eventually.
return;
}
void carriageReturn(std::string str){
std::string blank;
int strSize = str.length();
for(int i=0;i<strSize;i++){
blank += " ";
}
//inconsistent - not print()
std::cout << "\r" << blank << std::flush << "\r";
return;
}
//TODO - this is suspect - may be too complicated - refactor/simplify
void printWord(std::vector<std::string> &word){
//how many values to print at one time from vector
short wordCount = 4;//this will become user input eventually.
short numRead = 0;
int size = word.size();//could be a problem, maybe use long.
//even better, inspect file to determine needs
int rmndr = size % wordCount;
int stop = (size-rmndr);
int idx = 0;
std::string str;
while(idx < stop){
str += (word[idx++] + " ");
++numRead;
if(numRead == wordCount){
print(str);
slp();
carriageReturn(str);
numRead = 0;
str.clear();
}
}
if(rmndr){
for(int i=stop;i<size;i++){
str += (word[i] + " ");
}
print(str);
slp();
carriageReturn(str);
}
return;
}
int main(){
//TODO - doWhile
std::vector<std::string> word;
readFile(word);
//test(word);
println();
printWord(word);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Comments:</strong></p>\n\n<ul>\n<li><p><em>The top comment block is good</em>. When writing a program, describing it at the top will tell the reader what it is expected to do output.</p></li>\n<li><p><em>Too much whitespace within some blocks</em>. Some of your comment text are too spread-out, adding more lines and reducing readability. Avoid this by making your comments as concise as possible.</p></li>\n<li><p><em>Talking to yourself \"aloud\"</em>. Comments written in the first-person could be rewritten more professionally:</p>\n\n<pre><code>// short-term control - assign negative value to count for testing\n</code></pre></li>\n<li><p><em>\"TODOs\"</em>: They are okay, but should be kept simple:</p>\n\n<pre><code>// TODO - break up nested and conditional parts\n</code></pre></li>\n<li><p><em>\"val will become user input eventually\" and book references</em>: We don't need to know these things. They only help you, not us.</p></li>\n</ul>\n\n<p><strong>Code is not C:</strong></p>\n\n<p>Compared to your previous program revision, <em>this does look more C++-like</em>. @Lstor's main point was to use <code>std::string</code>, which you're now doing in place of <code>char</code> arrays.</p>\n\n<p>I'd recommend getting more familiar with <a href=\"https://en.wikipedia.org/wiki/Standard_Template_Library\" rel=\"nofollow noreferrer\">C++'s STL</a>. <code>std::string</code> is part of this library, and there's much more to explore. Use it whenever possible, and your code will become more C++-like, more concise, and more robust. Here are two starting points:</p>\n\n<ul>\n<li><a href=\"http://en.cppreference.com/w/\" rel=\"nofollow noreferrer\">Use this reference guide which describes each library and its purposes</a></li>\n<li><a href=\"http://rads.stackoverflow.com/amzn/click/0201749629\" rel=\"nofollow noreferrer\">Pick up <em>Effective STL</em> to learn how to use it properly</a></li>\n</ul>\n\n<hr>\n\n<p><strong>Miscellaneous:</strong></p>\n\n<ul>\n<li><p>Your <code>#include</code>s could be sorted alphabetically for organization.</p></li>\n<li><p>Be aware that <code><unistd.h></code> is platform-specific. This is not recommended if your program needs to attain portability.</p></li>\n<li><p>By default, <code>void</code> functions <code>return</code> on their own. It's only necessary when the function may need to end early for whatever reason.</p></li>\n<li><p>The \"print\" functions are unnecessary and just clutter the program. Just use <code>std::cout</code>.</p></li>\n<li><p>In <code>println()</code>'s <code>if</code>-block: It's best to avoid terminating with <code>exit()</code>. Replace it with a <code>return</code> and try to fall back to <code>main()</code> for termination.</p></li>\n<li><p><code>printWord()</code>'s reference parameter should be <code>const</code>. This applies to any non-native data type (such as an object) that will not be modified within the function.</p></li>\n<li><p><code>std::getline()</code> is preferred for a user-inputted <code>std::string</code>:</p>\n\n<pre><code>std::string input;\nstd::getline(std::cin, input);\n</code></pre></li>\n<li><p><code>size()</code> returns an <a href=\"https://stackoverflow.com/questions/409348/iteration-over-vector-in-c/409396#409396\"><code>std::size_type</code></a>, not an <code>int</code>. Correct return types should always be used, and you especially shouldn't mix signed/unsigned types.</p>\n\n<pre><code>std::vector<std::string>::size_type size = word.size();\n</code></pre>\n\n<p>You also don't need to create a variable for this. Just use the <code>word.size()</code> in the <code>for</code>-loop.</p></li>\n<li><p><code>readFile()</code> is hard to follow and could be simplified:</p>\n\n<pre><code>std::vector<std::string> readFile(std::istream& inFile)\n{\n std::vector<std::string> word;\n std::string fileStr;\n\n while (inFile >> fileStr)\n {\n word.push_back(fileStr);\n }\n\n return word;\n}\n</code></pre>\n\n<p>It's best to check the file in <code>main()</code> so that it can terminate if the file isn't found. In this function, an input stream (for the file created in <code>main()</code> is received and an <code>std::vector</code> is returned. This is okay to do because of <a href=\"http://en.wikipedia.org/wiki/Return_value_optimization\" rel=\"nofollow noreferrer\">Return Value Optimization</a>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:20:31.807",
"Id": "45547",
"Score": "1",
"body": "+1, valid points. What do you mean with your last item? `string` is default-constructed to the empty string. Also, I don't agree with the *count* item. *Count* is a noun and is more concrete (and therefore better) than `UShort`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:23:38.203",
"Id": "45548",
"Score": "0",
"body": "@Lstor: It is? I thought I once encountered problems on my own with that, but apparently not. I'll take out the other bulletpoint as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:25:27.833",
"Id": "45549",
"Score": "2",
"body": "Regarding `TODO`: I think it's perfectly valid to keep notes of TODOs in the code. Listing them at the top would make it like a very primitive bug tracker -- keeping them at the code in question makes it metadata. I'd keep them short and sweet, though: `// TODO: Read as input`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T04:19:57.867",
"Id": "45583",
"Score": "2",
"body": "I disagree about book references as a general comment, but think you're correct about this specific comment. In particular, when you're using a complicated algorithm, a book reference is useful. When you're just using standard library elements as designed, book references are noise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T16:34:16.510",
"Id": "45752",
"Score": "0",
"body": "@Jamal, \"Talking to yourself \"aloud\". Comments\" - I think you nailed it. I work/study alone and that is affecting things - I have to adjust my view. Thank you for your time and work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T16:36:50.877",
"Id": "45753",
"Score": "0",
"body": "@Jamal, \"Just use the word.size() in the for-loop\" - I thought using x.size() or x.length() meant the value has to be calculated for every pass of a loop so using a var to store the calculation result is more efficient. Is it not a calculation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T16:45:58.770",
"Id": "45754",
"Score": "0",
"body": "@yas: A bit so, yes. However, `x.size()` can be a bit more _readable_ while it's not very intensive since you're just calling an accessor (thus no extra operations since it's `const`)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T17:03:55.997",
"Id": "28934",
"ParentId": "28900",
"Score": "11"
}
},
{
"body": "<p>I can't help thinking that this seems somewhat...over-engineered. I think I'd consider something on this order as a starting point:</p>\n\n<pre><code>#include <string>\n#include <algorithm>\n#include <sstream>\n#include <iostream>\n\nint main() {\n std::istringstream in(\"one two three four five six seven eight nine\");\n\n std::cout << std::distance(std::istream_iterator<std::string>(in),\n std::istream_iterator<std::string>());\n}\n</code></pre>\n\n<p>Here I've embedded your test input into the program, but the same idea applies equally well to an external file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T18:10:55.373",
"Id": "46482",
"Score": "0",
"body": "\"over-engineering\" caught my attention; I am glad to have reference to the idea - thank you. From : http://stackoverflow.com/questions/1001120/what-is-over-engineering-as-applied-to-software\n\"...Implement things when you actually need them, never when you just foresee that you need them.\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T08:46:48.733",
"Id": "29211",
"ParentId": "28900",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "28934",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T21:47:41.537",
"Id": "28900",
"Score": "6",
"Tags": [
"c++",
"c++11",
"file"
],
"Title": "Printing certain number of words from file"
}
|
28900
|
<p>I have this action and it works but looks rather clunky to me. Is there any way I could improve that?</p>
<pre><code>transMit :: Serialize a => Socket -> POSIXTime -> KEY -> a -> TPSQ -> TMap a -> IO ()
transMit s time key newmsgs q m = do
loopAction <- atomically $ do
mT <- readTVar m
qT <- readTVar q
let (a, b) = key -- extract IPv4 address a and protocolID b from KEY
let mT' = Map.delete key mT
let qT' = PSQ.delete key qT
writeTVar q (PSQ.insert key time qT')
writeTVar m (Map.insert key [newmsgs] mT')
case b of
11 -> return $ case Map.lookup key mT of
Nothing -> return ()
Just messages -> sendq s (B.snoc (S.encode messages) b ) (show a) 4711
72 -> return $ case Map.lookup key mT of
Nothing -> return ()
Just messages -> sendqr s (B.snoc (S.encode messages) b ) (show a) 4711
loopAction
</code></pre>
|
[] |
[
{
"body": "<p>I'm not familiar with the libraries and types you're using here, but I see a few general Haskell things:</p>\n\n<ol>\n<li><p>Instead of <code>loopAction <- atomically $ ...; loopAction</code>, you can use <code>join $ atomically $ ...</code>. This removes the need for the entire outer <code>do</code> block, simplifying the blocks/indentation.</p></li>\n<li><p>You're doing nearly-identical operations on <code>m</code> and <code>q</code>, just with different collection types. I would attempt to extract these to a higher-order function (e.g. one possible abstraction is <code>modifyTVar</code>, which doesn't exist in the library, but you can see how to write it analogously to <code>modifyMVar</code>), and perhaps define an ad-hoc typeclass to make Map and PSQ look the same.</p></li>\n<li><p>Your <code>case b of ...</code> has two nearly identical branches! Unless there's some non-obvious polymorphism, then just combine them:</p>\n\n<pre><code>let send = case b of\n 11 -> sendq\n 72 -> sendqr\nreturn $ case Map.lookup key mT of\n Nothing -> return ()\n Just messages -> send s (B.snoc (S.encode messages) b) (show a) 4711\n</code></pre></li>\n<li><p><code>let mT' = Map.delete key mT</code> is redundant because the following <code>insert</code> will always overwrite that key anyway; just use <code>Map.insert key [newmsgs] mT</code> and never define <code>mT'</code>.</p></li>\n<li><p>Assuming you're using <a href=\"http://hackage.haskell.org/packages/archive/PSQueue/1.1/doc/html/Data-PSQueue.html\" rel=\"nofollow\">Data.PSQueue</a>, and <em>the key already exists in the queue</em>, you can use <code>PSQ.adjust</code> instead of a delete followed by an insert.</p></li>\n</ol>\n\n<p>Taking all of my own advice except the last:</p>\n\n<pre><code>transMit :: Serialize a => Socket -> POSIXTime -> KEY -> a -> TPSQ -> TMap a -> IO ()\ntransMit s time key newmsgs q m =\n join $ atomically $ do\n modifyTVar_ q $ (PSQ.insert key time . PSQ.delete key)\n foo <- modifyTVar m $ \\mT -> (Map.insert key [newmsgs] mT, Map.lookup key mT)\n let (address, protocol) = key\n let send = case protocol of\n 11 -> sendq\n 72 -> sendqr\n return $ case foo of\n Nothing -> return ()\n Just messages -> send s (B.snoc (S.encode messages) protocol) (show address) 4711\n\nmodifyTVar :: TVar a -> (a -> IO (a, b)) -> IO b\nmodifyTVar var f = do\n x <- readTVar var\n (x', r) <- f x\n writeTVar var x'\n return r\nmodifyTVar_ :: TVar a -> (a -> IO a) -> IO ()\nmodifyTVar_ var f = do\n x <- readTVar var\n writeTVar var (f x)\n</code></pre>\n\n<p>Further points about what I did:</p>\n\n<ul>\n<li><p>Note I called a variable <code>foo</code> because I don't know what it makes sense to name it in your application, not because that's a good name.</p></li>\n<li><p>I went and defined both <code>modifyTVar</code> and <code>modifyTVar_</code>; the latter is not needed but allows the action on <code>q</code> to be defined as a simple function composition. This is perhaps an excess of specialized utility functions, but I feel it is reasonable because the experienced Haskell programmer will understand what they do simply from seeing their names.</p></li>\n<li><p>I renamed <code>a</code> and <code>b</code> so the variable names actually communicate what they are; this is better than writing a comment to explain them, and so I removed the comment.</p></li>\n<li><p>I put <code>join $ atomically $ do</code> on a separate line so as to catch the reader's eye that this is not just a plain <code>do</code> block.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T09:38:54.997",
"Id": "45802",
"Score": "0",
"body": "does that lambda look right f I need to adjust \"any\" time there maybe to the current time `writeTVar q (PSQ.adjust (\\time -> time) key qT)` ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:43:48.870",
"Id": "28928",
"ParentId": "28901",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28928",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-07-23T22:04:48.940",
"Id": "28901",
"Score": "1",
"Tags": [
"haskell",
"queue",
"socket",
"serialization"
],
"Title": "Action to transmit queued messages over a socket"
}
|
28901
|
<p>This is my Clojure code for finding prime numbers.</p>
<p>Note: this is an advanced version which starts eliminating from <code>i*i</code> with step <code>i</code>, instead of filtering all list against <code>mod i == 0</code> <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">(Sieve of Eratosthenes)</a>.</p>
<p>It has better asymptotic runtime: <code>O(n log log n)</code> instead of <code>O(n log n)</code> in typical examples of finding primes in Clojure.</p>
<p>What can be done better? Do I use some slow constructions? Can I make it more concise? Gain more performance? Format it better?</p>
<pre><code>(defn primes [n]
(let [mark (fn [i di v]
(if (<= i (count v))
(recur (+ i di) di (assoc v (dec i) di))
v))
step (fn [i ps v]
(if (<= i (count v))
(if (= (v (dec i)) 1)
(recur (inc i) (conj ps i) (mark (* i i) i v))
(recur (inc i) ps v))
ps))]
(->> (repeat 1) (take n) vec (step 2 []))))
(defn -main
[& args]
(println (primes 50)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T07:15:41.310",
"Id": "45599",
"Score": "0",
"body": "it will be `n log (log n)` only if `(assoc v (dec i) di)` is O(1)."
}
] |
[
{
"body": "<p><em>(non-Clojure-specific)</em> Gain performance, sure. Use packed array of odds, where index <code>i</code> represents value <code>2i+1</code>. Then you don't have to deal with evens, which are all non-prime a priori (except the 2 of course). Then you can increment by <code>2*p</code> for a prime <code>p</code> to find its odd multiples twice faster.</p>\n\n<p>For a non-marked index <code>i</code>, the prime <code>p</code> is <code>p = 2*i+1</code>, its square is <code>p*p = (2i+1)(2i+1) = 4i^2 + 4i + 1</code> and <em>its</em> index is <code>(p*p-1)/2 = 2i^2 + 2i = 2i(i+1) = (p-1)(i+1)</code>. For the value increment of <code>2*p</code>, the index increment on 2x-packed array is <code>di = p = 2i+1</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T07:09:06.933",
"Id": "28959",
"ParentId": "28902",
"Score": "2"
}
},
{
"body": "<p>I've played around with your code to try to understand it, frankly. After a long sequence of changes, I ended up with the following:</p>\n\n<pre><code>(defn primes [n]\n (let [mark (fn [i di v]\n (reduce\n (fn [w i] (assoc w i di))\n v\n (range i (count v) di)))\n [answer &_] (reduce\n (fn [[ps v :as both] i]\n (if (= (v i) 1)\n [(conj ps i) (mark (* i i) i v)]\n both))\n (let [init-v (->> (repeat 1) (take n) (vec))]\n [[] init-v])\n (range 2 n))]\n answer))\n</code></pre>\n\n<ul>\n<li>I've got rid of the <code>dec</code>s in all the accesses to the vector <code>v</code>.</li>\n<li>I've captured the <code>recur</code>s, in the <code>mark</code> and <code>step</code> functions,\nin <code>reduce</code>s.</li>\n<li>Since the <code>step</code> function is no longer recursive, I've unwrapped it\ninto its one call.</li>\n</ul>\n\n<p>The new <code>mark</code> function is a little faster. But the <code>step</code> equivalent is going to be slower, since it generates a new pair-vector for every prime. </p>\n\n<p>The main problem here is space - your vector <code>v</code> is the size of your candidate range of numbers. I've come across a cute algorithm that gets round this, though at some cost in speed, spent on laziness. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-10T13:40:44.757",
"Id": "222023",
"ParentId": "28902",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-23T22:38:22.627",
"Id": "28902",
"Score": "1",
"Tags": [
"primes",
"clojure"
],
"Title": "Clojure code for finding prime numbers"
}
|
28902
|
<p>I wrote a little <code>PHP</code> wrapper class for <code>GeoIP</code> which looks like:</p>
<pre><code><?php
class GeoIP {
private $ip;
private $geo_ip_details;
function __construct($ip) {
$this->ip = $ip;
$this->fetch();
}
private function fetch() {
if(filter_var($this->ip, FILTER_VALIDATE_IP)) {
$curl = new Curl();
$json = $curl->get_request("http://freegeoip.net/json/" . $this->ip, true);
$result = json_decode($json);
if($result !== null) {
$this->geo_ip_details = $result;
}
}
}
public function __get($property) {
if(property_exists($this, $property)) {
return $this->$property;
}
}
public function __toString() {
if(isset($this->geo_ip_details) && !empty($this->geo_ip_details)) {
if(isset($this->geo_ip_details->city) && !empty($this->geo_ip_details->city) && isset($this->geo_ip_details->region_name) && !empty($this->geo_ip_details->region_name) && isset($this->geo_ip_details->country_name) && !empty($this->geo_ip_details->country_name)) {
return $this->geo_ip_details->city . ", " . $this->geo_ip_details->region_name . " " . $this->geo_ip_details->country_name;
} else if(isset($this->geo_ip_details->region_name) && !empty($this->geo_ip_details->region_name) && isset($this->geo_ip_details->country_name) && !empty($this->geo_ip_details->country_name)) {
return $this->geo_ip_details->region_name . " " . $this->geo_ip_details->country_name;
} else if(isset($this->geo_ip_details->country_name) && !empty($this->geo_ip_details->country_name)) {
return $this->geo_ip_details->country_name;
}
}
}
}
?>
</code></pre>
<p>Usage is like:</p>
<pre><code>//Constructor, and autocalls fetch()
$geoip = new GeoIP('64.87.28.98');
//Getter of ip property
print_r($geoip->ip);
//Getter of geo_ip_details property
print_r($geoip->geo_ip_details);
//toString of the class
echo $geoip;
</code></pre>
<p>Basically, I am going back and forth on implementation details. Should I expose <code>fetch()</code> publicly, and not automatically call it in the constructor? I.E.</p>
<pre><code>$geoip = new GeoIP('64.87.28.98');
$result = $geoip->fetch();
</code></pre>
<p>Is using a getter a good idea? Should I have a class method called <code>stringify()</code> instead of overriding the <code>__toString</code>?</p>
<p>Also, right now, once you instantiate GeoIP with an ip address, there is no way to pass a new ip address into the existing object. You must instantiate a new GeoIP object. Does making a method:</p>
<pre><code>public function set($ip) {
$this->ip = $ip;
$this->fetch();
}
</code></pre>
<p>Make sense, or simply just do something like: <code>$geoip = new GeoIP('new-ip-address');</code></p>
<p>What is the best practice for object oriented design for this pattern?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T16:36:43.380",
"Id": "45537",
"Score": "0",
"body": "This violates encapsulation. See: http://www.javaworld.com/jw-05-2001/jw-0518-encapsulation.html"
}
] |
[
{
"body": "<ul>\n<li><p>I'm not a fan of magic getters. Without <em>really</em> good documentation, they're just a pain for consumers of your code. For example, when I first looked at your code, I had no idea at all what properties the class exposes. I basically had to follow the cURL request to find out. Proper documentation could fix this, but why not just have proper properties instead (or a getter)?</p></li>\n<li><p>As a general rule of thumb, a class should never successfully construct if it will be left in a useless state. In other words, your constructor shouldn't finish unless the IP request actually went through and the data was retrieved.</p>\n\n<ul>\n<li>If the IP is invalid, throw an exception.</li>\n<li>If the cURL request fails, throw an exception</li>\n</ul></li>\n<li><p>cURL isn't really necessary here (at least not with the way you're using it). Just use <code>file_get_contents(\"http://.../...\");</code></p></li>\n<li><p>Your getter should <code>return null</code> if the property doesn't exist. null will be returned implicitly, but I think the code would be a bit clearer (alternatively, you could throw an exception depending on how you want the class to be used)</p></li>\n<li><p><code>isset($var) && !empty($var)</code> is redundant. <code>!empty($var)</code> is equivalent to <code>isset($var) && $var</code> meaning you can just do <code>!$empty</code>.</p></li>\n<li><p>Your <code>__toString</code> doesn't have a real use at the moment. The return is too unpredictable to reliably use it to print the data. I would either normalize it to always print the same fields in the same format or get rid of it.</p>\n\n<ul>\n<li>I've not a fan of __toString for most classes. Unless a class has a canonical string represenation (like a BigInt would, or a IPAddress, etc), I wouldn't bother having a __toString.</li>\n<li>__toString can ease debugging though, so if you like to use it for that, it might be worth keeping it around</li>\n</ul></li>\n<li><p>I think you need to decouple the data object (the city/state/area code/etc) from the retrieval of it. I would have two classes: <code>GeoIP</code> and <code>GeoIPInformation</code> (or whatever you want to call it).</p>\n\n<ul>\n<li>GeoIP would then have a method <code>public function getInformation($ipAddress);</code> that returns a <code>GeoIPInformation</code>.\n\n<ul>\n<li>if you think there's a chance you'd ever want to have a different method for ipv4 or ipv6 or the ability to lookup host names, you might want to name it <code>getInformationByIPv4</code></li>\n</ul></li>\n<li>If you wanted to go all out, you could code the retriever to an interface. This would remove your ties to freegeoip.net (which might stop existing or working at any time)\n\n<ul>\n<li>A second retriever that immediately comes to mind is the maxmind geoip databases</li>\n<li>Interfaces are good for decoupling, <em><a href=\"https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface\">blah blah blah</a>... ask me if you more details on this.</em></li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p><strong>Update</strong></p>\n\n<p>Dave Jarvis had a very good point with the encapsulation issue. Concepts like a country should be stored as an object, not a simple scalar. This allows the consuming code to interact with the data in a much cleaner way. For example, imagine that one data source returns a 2 letter country code whereas another returns a country name. If the coutnry is a plain string, this presents a problem: how do we know what <code>echo $loc->getCountry();</code> is going to be? Is it going to be a country code? Or a name? Or maybe an ID? Who knows.</p>\n\n<p>But, if instead of leaving it a scalar we turn it into an object, we get the benefit of being able to do <code>echo $loc->getCountry()->getName();</code> and knowing that it will be a proper name. There's an added benefit too of we now have much more data at hand. We are no longer constrained to one small snippet of data about the country. We now have the ability to have the name, code, etc all wrapped up in one convenient object.</p>\n\n<p>Different strategies are possible to create these objects, but for your uses, I would just stick with a simple lookup table or something similar in this situation.</p>\n\n<p>If you wanted to go all out, you could connect it to some kind of data source and then have your code interact with that to load a country. This would be a lot more flexible as the data is no longer part of the code (which tends to be bad), but it's also more complicated, and I'm lazy. If you did go this route, you could create a <code>CountryFinder</code> interface that knows how to create a <code>Country</code> based on a given criteria. You would then inject a <code>CountryFinder</code> implementation into your <code>GeoIP</code> implementations and it would use it.</p>\n\n<p>I've updated my code below to reflect a basic sketch of these updates. I've only demonstrated by encapsulating the IP address and country, but hopefully the idea is clear. (Also, my error handling is pretty terrible in a few places such as the IP address constructor where an exception should be thrown if the argument is invalid).</p>\n\n<p>Oh, and Location should either be named IpLocation to signify that it embodies a Location/IP pair, or it should have the IP address removed from it. (A Location object really has no business having an IP address as an attribute, but as it is actually GeoIP::Location, I might be tempted to leave it.)</p>\n\n<hr>\n\n<p>All in all, I might consider something like this:</p>\n\n<p><em>Note that this is a bit crude -- the error handling is bad, the exceptions should be subclasses, I put half a second of thought into names, etc</em></p>\n\n<pre><code><?php\n\nnamespace GeoIP;\n\ninterface GeoIP\n{\n /**\n * Retrieves geo information for an IP address.\n * @param string|IpAddress $ipAddress Either an IpAddress or an IP address formatted as a string in dotted decimal notation\n * @return \\GeoIP\\Location \n * @throws \\InvalidArgumentException if the IP address is invalidly formatted\n * @throws \\RuntimeException if some kind of network/disk/etc error occurs\n */\n public function getLocationByIpAddress($ipAddress);\n}\n\nclass IpAddress\n{\n\n private $_addr;\n\n public function __construct($addr)\n {\n //You can either guess what $addr is (string, 32 bit int, etc),\n //or you could provide static fromString, fromLong, etc methods.\n //For simplicity, I've assumed it's a decimal dotted string\n $this->_addr = $addr;\n }\n\n public function asDecimalDotString()\n {\n return $this->_addr;\n }\n\n public function asLong()\n {\n $octets = explode(\".\", $this->_addr);\n return ($octets[0] << 24) + ($octets[1] << 16) + ($octets[2] << 8) + $octets[3];\n }\n\n}\n\nclass Location\n{\n private $_ip;\n private $_country;\n\n public function __construct($ip, Country $country)\n {\n $this->_ip = $ip;\n $this->_country = $country;\n }\n\n /**\n * @return IpAddress The IP address that was used in retrieving this geo information\n */\n public function getIpAddress()\n {\n return $this->_ip;\n }\n\n /**\n * @return Country|null the country the IP belongs to or null is one could not be determined\n */\n public function getCountry()\n {\n return $this->_country;\n }\n\n // ...\n\n}\n\ninterface CountryFinder\n{\n public function findByCountryCode($code);\n public function findByCountryName($name);\n}\n\nclass Country\n{\n\n private $_name;\n private $_code;\n private $_population;\n\n public function __construct($name, $code, $population)\n {\n $this->_name = $name;\n $this->_code = $code;\n $this->_population = $population;\n }\n\n public function getName()\n {\n return $this->_name;\n }\n\n public function getCode()\n {\n return $this->_code;\n }\n\n public function getPopulation()\n {\n return $this->_population;\n }\n\n}\n\nclass ArrayLookupCountryFinder implements CountryFinder\n{\n\n private $_countryData = array(\n 'US' => array('name' => 'United States', 'code' => 'US', 'population' => 300000000),\n 'CA' => array('name' => 'Canada', 'code' => 'CA', 'population' => 34500000)\n );\n\n public function __construct(array $countryData = null)\n {\n if ($countryData) {\n $this->_countryData = $countryData;\n }\n }\n\n public function findByCountryCode($code)\n {\n if (isset($this->_countryData[$code])) {\n $country = $this->_countryData[$code];\n return new Country($country['name'], $country['code'], $country['population']);\n } else {\n return null;\n }\n }\n\n public function findByCountryName($name)\n {\n // Yeah...\n return null;\n }\n\n}\n\nclass FreeGeoipNet implements GeoIP\n{\n\n private $_countryFinder;\n\n public function __construct(CountryFinder $countryFinder)\n {\n $this->_countryFinder = $countryFinder;\n }\n\n public function getLocationByIpAddress($ipAddress)\n {\n\n if (!($ipAddress instanceof IpAddress)) {\n $ipAddress = new IpAddress($ipAddress);\n }\n\n $response = file_get_contents(\"http://freegeoip.net/json/\" . $ipAddress->asDecimalDotString());\n if ($response === false) {\n throw new \\RuntimeException(\"Request to freegeoip.net failed\");\n }\n $data = json_decode($response, true);\n if (!is_array($data)) {\n throw new \\RuntimeException(\"Parsing response from freegeoip.net failed: {$response}\");\n }\n /* In a real application, you would likely want to somehow handle if the country code wasn't empty but a\n * country couldn't be found in your data source. I'm lazy though, so I've not done that. */\n return new Location($ipAddress, $this->_countryFinder->findByCountryCode($data['country_code']));\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Usage:</p>\n\n<pre><code>$geoip = new GeoIP\\FreeGeoipNet(new GeoIP\\ArrayLookupCountryFinder());\n\n$location = $geoip->getLocationByIpAddress(\"x.x.x.x\");\n\n$ip = $location->getIpAddress();\n$country = $location->getCountry();\n\necho $ip->asDecimalDotString() . \" (\" . $ip->asLong(). \") \" . \" is in \" . $location->getCountry()->getName() \n . \" which has a population of \" . $location->getCountry()->getPopulation();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T16:40:28.160",
"Id": "45539",
"Score": "1",
"body": "This appears to violate encapsulation. See: http://www.javaworld.com/jw-05-2001/jw-0518-encapsulation.html?page=9"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T22:16:44.380",
"Id": "45573",
"Score": "0",
"body": "@DaveJarvis Which part(s)? If you mean the getters, there's not much of a way to avoid those since it's a value object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T01:28:52.713",
"Id": "45576",
"Score": "1",
"body": "The accessor methods should return immutable objects, not strings. This would help alleviate any dependencies that arise from clients relying on the format of the strings that are returned. You could write `$info->getCountry()->is( \"Canada\" )`, for example. How the country code is stored (2- vs. 3-letter ISO codes) should not be a concern of the client."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T01:32:45.587",
"Id": "45577",
"Score": "0",
"body": "@DaveJarvis Ah, that's a good point. I didn't think about it from that perspective. That would allow a ton of advantages working with the data compared to modeling it as simple scalars. I think your suggestion definitely warrants an answer and not just a comment if you want to post one. Otherwise, I will edit my answer in a bit to reflect your suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T04:10:38.257",
"Id": "45582",
"Score": "0",
"body": "Do update your answer. :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T04:13:39.533",
"Id": "45706",
"Score": "0",
"body": "@DaveJarvis I've done my best to address your concerns. Please look over it and let me know if you have any suggestions about how I've done it. Encapsulation is new to me, so I've likely done it wrong :). (My OOP knowledge is a rather odd and limited mix... lol)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T06:47:08.650",
"Id": "28906",
"ParentId": "28904",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T05:16:02.800",
"Id": "28904",
"Score": "2",
"Tags": [
"php",
"object-oriented"
],
"Title": "PHP review of object oriented GeoIP class"
}
|
28904
|
<p>I have a <code>float</code> in the <code>String strFloat</code>. I wanted to convert it to a rounded integer also stored in a <code>String</code>. This looks awful to me, so please offer some suggestions for improvement.</p>
<pre><code>String strInteger = new Integer(Float.valueOf(strFloat).intValue()).toString()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T04:55:47.157",
"Id": "45590",
"Score": "0",
"body": "Could you please clarify where the float comes from and what is stored in this variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T07:07:59.360",
"Id": "45596",
"Score": "0",
"body": "`Float.valueOf(\"2.99\").intValue() != Math.round(Float.valueOf(\"2.99\"))` You sure you mean *rounded integer*?"
}
] |
[
{
"body": "<p>Instead of creating a new <code>Integer</code> and throwing it away, use <code>String.valueOf()</code> directly.</p>\n\n<pre><code>String strInteger = String.valueOf(Float.valueOf(strFloat).intValue())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T10:00:55.013",
"Id": "45485",
"Score": "0",
"body": "-1 for using float/double in a most likely precise context."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:37:04.187",
"Id": "45510",
"Score": "2",
"body": "@mnhg: Then the OP needs to mention that context. This could also just be interfacing with legacy data, or a simple \"stringified\" application. Additionally, that thing is already called \"float\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T04:32:53.330",
"Id": "45586",
"Score": "0",
"body": "@Bobby Actually it's the other way around. Maybe I'm to critical/pessimistic but I had to deal with to many bad designed interfaces etc. If there is no reason to be inprecise and your language supports a better suitable type, you definitely should go with this type. It will make your live easier. Somebody at sometime will copy/reuse your code, decide that he need a decimal digit or two and it will go down from there. (Only calling it float says nothing. It is a String.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T07:48:15.757",
"Id": "28909",
"ParentId": "28908",
"Score": "4"
}
},
{
"body": "<p>If your float is already a String then you definitely should go with <a href=\"http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html\" rel=\"nofollow\"><code>BigDecimal</code></a>. Creating a real intermediate float only add inaccuracy.</p>\n\n<pre><code>String strInteger = new BigDecimal(strFloat).toBigInteger().toString());\n</code></pre>\n\n<p>Of course you can take advantage of all the arithmetic power of BigDecimal and define a specific rounding mode etc.</p>\n\n<p><strong>EDIT:</strong> Just to prove that the float approach will fail (tested in Java 6):</p>\n\n<pre><code>Float.valueOf( \"1.99999999\" ).intValue()==2 \nFloat.valueOf( \"2.9999999\" ).intValue()==3\nFloat.valueOf( \"393650.99\" ).intValue()==393651\nFloat.valueOf( \"2545818.9\" ).intValue()==2545819\n(and many more)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T21:08:00.753",
"Id": "45571",
"Score": "0",
"body": "If the `String` was created from a `float`, exact precision is already maintained: \"How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type float.\" http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html#toString(float)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T05:06:29.173",
"Id": "45593",
"Score": "0",
"body": "`Float.valueOf( \"1.99999999\" ).intValue()==2` (Java 6)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T20:43:07.057",
"Id": "46408",
"Score": "0",
"body": "You can't generate \"1.99999999\" from a Java float."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-05T07:17:44.083",
"Id": "46451",
"Score": "0",
"body": "There is no use in arguing about it without knowing the context. Maybe it is a float from the database, or a webservice or was converted to string long ago and cut to 10 characters. Expect the worst, especially if it doest cost \"anything\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-18T13:55:03.010",
"Id": "47448",
"Score": "0",
"body": "Without knowing the context, it's hard to say that creating a lot of intermediate `BigDecimal`s and `BigInteger`s doesn't cost anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-08T22:45:18.077",
"Id": "169098",
"Score": "0",
"body": "I believe you have an extra close-paren."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T10:00:14.773",
"Id": "28918",
"ParentId": "28908",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T07:33:45.427",
"Id": "28908",
"Score": "2",
"Tags": [
"java",
"converting",
"integer",
"floating-point"
],
"Title": "Float string to integer string"
}
|
28908
|
<p>I have written a shell script to process my huge data files (each one having around 7,000,000 lines ~ a weeks data in a single file).</p>
<p>Here is a sample of my data file (i.e., input file) structure:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>808 836 204 325 148 983
908 836 203 326 148 986
8 835 204 325 149 984
108 835 204 325 148 984
208 836 204 326 149 984
308 834 203 325 149 985
408 836 204 326 149 983
508 834 203 325 149 985
20130402,123358 0 $GPRMC,123358.000,A,5056.3056,N,00622.5644,E,0.00,0.00,020413,,,A*67
608 834 203 325 150 985
708 834 204 326 150 986
808 836 204 325 151 983
908 835 204 325 153 984
8 816 202 325 153 973
108 836 204 324 156 984
208 835 204 325 157 983
308 834 202 324 158 985
408 835 203 325 158 985
508 836 203 324 160 984
20130402,123359 0 $GPRMC,123359.000,A,5056.3056,N,00622.5644,E,0.01,0.00,020413,,,A*67
608 835 204 325 162 986
708 836 204 324 164 983
808 835 202 324 165 986
908 836 204 324 167 983
8 836 202 324 168 985
108 835 203 325 170 986
208 836 203 324 171 983
</code></pre>
</blockquote>
<p>I have an instrument whose counter provides the data every 0.1 second while the GPS provides its measurement in between every 1 second. For every GPS measurement, I want to extract the above 5 lines and below 5 lines of my instrument record simultaneously. I don't want all 6 elements from my instrument record. From my instrument record, I require only the 5th elements of the above and below 5 lines against each GPS record. In addition, from the GPS record, I want to extract the date (1st element), time (2nd element), latitude and longitude.</p>
<p>From the sample example, I shall obtain this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>20130402 123358 5056.3056 00622.5644 148 149 149 149 149 150 150 151 153 153
20130402 123359 5056.3056 00622.5644 156 157 158 158 160 162 164 165 167 168
</code></pre>
</blockquote>
<p>In order to extract and arrange the data, I have initially written Matlab and IDL code.</p>
<p>I then again wrote a shell script:</p>
<pre class="lang-bsh prettyprint-override"><code>#!/bin/bash
clear
# Program to read *.bin files
# Data directory
DATAPATH='/home/xyz/datasets/2013_04_09/'
# Output data directory
OUTPATH='/home/abc/data_1/'
count=1;
# Read the files sequentially
for file in $DATAPATH*.bin; do
INFILE=$file; # Input file
INFILENAME=`echo $INFILE | awk -F'/' '{print $7}'`
SUFFIX="1.txt"
OUTFILE="$OUTPATH${INFILENAME:0:18}$SUFFIX" # Output file
TEMPFILE="${OUTPATH}tempresult_sed.txt"
awk '{if(length($0) >= 79) print NR,",",$0}' $INFILE | sed 's/ /,/g' > $TEMPFILE
lines=`cat $TEMPFILE | awk -F, '{print $1}'`
lat=`cat $TEMPFILE | awk -F, '{print $10}'`
lon=`cat $TEMPFILE | awk -F, '{print $12}'`
date=`cat $TEMPFILE | awk -F, '{print $4}'`
time=`cat $TEMPFILE | awk -F, '{print $5}'`
array_lines=($lines)
array_time=($time)
array_lat=($lat)
array_lon=($lon)
array_date=($date)
count=${#array_lines[@]} # Number of data records
for i in `seq 1 $count`; do
idx=$(($i-1))
echo ${array_lines[$idx]} ${array_date[$idx]} ${array_time[$idx]} ${array_lat[$idx]} ${array_lon[$idx]} `sed $((${array_lines[$idx]}-5))","$((${array_lines[$idx]}-1))"!d" < $INFILE | awk '{print $5}'` `sed $((${array_lines[$idx]}+1))","$((${array_lines[$idx]}+5))"!d" < $INFILE | awk '{print $5}'`
done > $OUTFILE
rm -f $TEMPFILE # Remove the temporary file
let count++;
done
</code></pre>
<p>In the script for cross-checking, I have included the line number from the input file with <code>${array_lines[$idx]}</code> in the code. I started running my shell script on the server. It took more than two days but still not even a single input file (with 7,000,000 lines) was completed. Until now, around 1.5 million lines were only written to my <code>OUTFILE</code>. Just pulling all the GPS lines (i.e., strings of length = 80) and writing to a <code>TEMPFILE</code> is taking 1 minute while the extraction of the 5th element from above and below 5 lines of the instrument counter data and arranging as specified is taking long.</p>
<p>I really require someone who can suggest/correct my code so that my computation will be faster. I have already posted my script in my <a href="https://stackoverflow.com/questions/17612290/how-to-extract-lines-in-between-a-file-read-a-part-of-a-string-with-linux-shel">previous post</a> but for a different query. So, don't be panic about cross-posting. Please suggest ways in which I can extract the data from my input file structure in very less time of computation from a huge file.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T09:56:24.283",
"Id": "45463",
"Score": "4",
"body": "Sorry but shell script isn't the right tool if you want to get performance. You'll end up spending your time forking to call command like ``awk`` ``sed``. Try out a real programming language such as Perl / Python / C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T10:00:15.233",
"Id": "45464",
"Score": "0",
"body": "@Slaven - I am not having experience with writing Perl scripts."
}
] |
[
{
"body": "<p>The details of your question are entirely unclear to me. I have understood, however, that you have a huge input file which you need to parse and translate into some output. The input is so large that it becomes important to do the parsing and translation in an efficient way.</p>\n\n<p>As you have already seen, spawning subprocesses for every single part of line processing is entirely inefficient (this is what you do in your shell script, when you pipe things around between sed and awk). Also, it seems to me that you read certain parts of the input data multiple times.</p>\n\n<p>You need to use a high-level programming language such as Python (which I really recommend here) and then use an idiom such as</p>\n\n<pre><code>with open('input.txt') as f:\n for line in file:\n your_process_function_for_a_line(line)\n</code></pre>\n\n<p>This way, the data is processed while reading the file. You can create some data structures before starting this loop, e.g. a dictionary in which you want to store your output, and then populate this data structure in the loop outlined above. Or, which would be even better, you could write your output file while reading the input file. The idiom would like like so:</p>\n\n<pre><code>with open('output.txt', 'w') as outfile:\n with open('input.txt') as infile:\n for line in infile:\n # Process input line(s) and perform something to\n # generate a line for the output file.\n if outline:\n outfile.write(outline)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T10:05:27.973",
"Id": "28911",
"ParentId": "28910",
"Score": "2"
}
},
{
"body": "<p>This should be a lot speedier: it only has to read each line in each .bin file a single time:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>for infile in \"$DATAPATH\"/*.bin; do \n outfile=\"$OUTPATH/$(basename \"$infile\" \".bin\")1.txt\" \n awk -F'[ ,]' ' \n NF==16 { \n printf \"%s %s %s %s \", $1,$2,$7,$9\n printf \"%s %s %s %s %s \", prev5,prev4,prev3,prev2,prev1\n for (i=1; i<=5; i++) { getline; printf \"%s \", $5 } \n print \"\" \n next \n } \n { prev5=prev4; prev4=prev3; prev3=prev2; prev2=prev1; prev1=$5 } \n ' <\"$infile\" >\"$outfile\" \ndone \n</code></pre>\n\n<p>You could also see if this perl is faster than the awk:</p>\n\n<pre><code>perl -F'/[\\s,]/' -lane '\n if (@F == 16) {\n @fields = ($F[0], $F[1], $F[6], $F[8], @prev);\n do { $_ = <>; push @fields, (split)[4] } for (1..5);\n print join(\" \", @fields)\n } \n else { push @prev, $F[4]; shift @prev if @prev > 5 }\n'\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T12:33:28.277",
"Id": "28912",
"ParentId": "28910",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-18T09:49:27.873",
"Id": "28910",
"Score": "2",
"Tags": [
"csv",
"linux",
"shell",
"geospatial"
],
"Title": "Processing huge files of GPS data, extracting fields from five lines before and after each timestamp"
}
|
28910
|
<p>I am writing simple code to accept/read a input of lines from a text file, split it into my class variables, sort them and finally display the input in the ordered form. But I have been struggling for the past couple of days to split the read line in appropriate manner.</p>
<pre><code>static void Main(string[] args)
{
List<MyClass> myClassList = new List<MyClass>();
string strpath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\input.txt";
if (File.Exists(strpath))
{
using (var sr = new StreamReader(strpath))
{
string[] strFirst, strSecond;
while (sr.Peek() >= 0)
{
strFirst = Regex.Split(sr.ReadLine().Replace(" ", ""), "([0-9]+)");
strFirst = Regex.Split(sr.ReadLine().Replace("|", ">>"), "([0-9]+)");
myClassList.Add(new MyClass
{
Number = strFirst[1], Name = strFirst[2], Separator = strFirst[1].Split(">>")}
});
}
}
}
myList = GetResults(myClassList);
foreach (MyClass myclass in myList)
{
Console.WriteLine(myclass[i].Number + myclass[i].Name + myclass[i].Separator);
Console.WriteLine(myclass.Name);
}
Console.ReadLine();
}
</code></pre>
<p>Sample input line from text file, which I want to process:</p>
<pre><code>var input = "5 string one | 5.2 string two | 5.2.1 string three\r\n" +
"5 string four >> 5.6 string five >> string six\r\n" +
"1 string seven | 1.1 string eight | 1.1.1 string nine\r\n";
</code></pre>
<p>Output:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>MyClass
Number[0] = 5
Name[0] = string one
Separator[0] = |
Number[1] = 5.2
Name[1] = string two
Separator[1] = |
Number[2] = 5.2.1
Name[2] = string three
Separator[2] =
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T07:51:48.603",
"Id": "45473",
"Score": "0",
"body": "You probably have a problem in ` strFirst = Regex.Split(sr.ReadLine().Replace(\" \", \"\"), \"([0-9]+)\");\nstrFirst = Regex.Split(sr.ReadLine().Replace(\"|\", \">>\"), \"([0-9]+)\");` because the first value or strFirst is never used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T07:54:12.467",
"Id": "45474",
"Score": "0",
"body": "@Tim: yes. the sample input lines are one of the three lines in from a file"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T07:54:59.347",
"Id": "45475",
"Score": "0",
"body": "@C4stor: I do have a problem there, but struggling what to write in order to achieve my resultset. Any suggestion"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T08:04:24.843",
"Id": "45476",
"Score": "0",
"body": "moreover when I do \n`char[] delim = {'|','>' }; \nstrFirst = sr.ReadLine().Split(delim);`\nI get `strFirst[0] = 5 string one & strFirst[1] = 5.1 string two & strFirst[2] = string three` but now i want to further process these indexes into number and strings so that I can store them into my class variable. Hope, it makes sense."
}
] |
[
{
"body": "<p>Try this:</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n //var input = File.ReadAllText(\"input.txt\");\n\n var input = \"5 string one | 5.2 string two | 5.2.1 string three\\r\\n\"+\n \"5 string four >> 5.6 string five >> string six\\r\\n\" +\n \"1 string seven >> 1.1 string eight || 1.1.1 string nine\\r\\n\";\n\n var matches = Regex.Matches(input, @\"([0-9. ]*)(string \\w*)([\\|> $]*)\",\n RegexOptions.Multiline);\n var template = \"Number[{0}] = {1}\\r\\n\" +\n \"Name[{0}] = {2}\\r\\n\" +\n \"Separator[{0}] = {3}\\r\\n\";\n var sb = new StringBuilder();\n sb.AppendLine(\"MyClass\");\n int counter = 0;\n foreach (Match item in matches)\n {\n sb.AppendLine(String.Format(template,\n counter++,\n item.Groups[1].ToString().Trim(),\n item.Groups[2].ToString().Trim(),\n item.Groups[3].ToString().Trim()));\n }\n Console.WriteLine(sb.ToString());\n }\n}\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>MyClass\nNumber[0] = 5\nName[0] = string one\nSeparator[0] = |\n\nNumber[1] = 5.2\nName[1] = string two\nSeparator[1] = |\n\nNumber[2] = 5.2.1\nName[2] = string three\nSeparator[2] =\n\nNumber[3] = 5\nName[3] = string four\nSeparator[3] = >>\n\nNumber[4] = 5.6\nName[4] = string five\nSeparator[4] = >>\n\nNumber[5] =\nName[5] = string six\nSeparator[5] =\n\nNumber[6] = 1\nName[6] = string seven\nSeparator[6] = >>\n\nNumber[7] = 1.1\nName[7] = string eight\nSeparator[7] = ||\n\nNumber[8] = 1.1.1\nName[8] = string nine\nSeparator[8] =\n</code></pre>\n\n<p>Based on the request in your comment, I'm adding ordering of the output. Just replace the <code>foreach</code> statement above with the following lines and make sure you add a <code>using System.Dynamic;</code> to the top of your class file:</p>\n\n<pre><code>List<dynamic> items = new List<dynamic>();\nforeach (Match match in matches)\n{\n dynamic item = new ExpandoObject();\n item.Index = counter++;\n item.Number = match.Groups[1].ToString().Trim();\n item.Name = match.Groups[2].ToString().Trim();\n item.Separator = match.Groups[3].ToString().Trim();\n items.Add(item);\n}\n\nvar sb = new StringBuilder();\nsb.AppendLine(\"MyClass\");\nforeach (var item in items.OrderBy(i => i.Number))\n{\n sb.AppendLine(String.Format(template,\n item.Index,\n item.Number,\n item.Name,\n item.Separator));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T08:48:42.203",
"Id": "45477",
"Score": "0",
"body": "Thanks for your response, but all it does is prints \"MyClass\" at the end. Any reasons?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T08:54:30.790",
"Id": "45478",
"Score": "0",
"body": "Maybe your input file is slightly different then what you posted... I'll update my answer by including the input string in the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T11:06:32.453",
"Id": "45479",
"Score": "0",
"body": "Hi @Alex, could you also update your answer with the result you get? Thanks anyways"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T13:36:12.097",
"Id": "45480",
"Score": "0",
"body": "thanks once again. This goes ok, but I am trying with one more set ok record but does not fit well. Can you try this line and see why is this happening. `4 string 1 string 11 string 111 | 4.6 string 1 string 12 string 121 string 122 | string 1 string 13 string 131 string 132\\r\\n\"` the output should be `Number[0]=4 Name[0]=\"string 1 string 11 string 111\" separator[0]= , Number[1]=4.6 Name[1]=\"string 1 string 12 string 121 string 122\" separator[1]= |, Number[2]= Name[2]=\"string 1 string 13 string 131 string 132 separator[2]=\" `"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T13:44:46.750",
"Id": "45481",
"Score": "0",
"body": "If this goes ok, maybe you should mark my approach as an answer. If you have some other sample data, in a different format, this will modify fundamentally the regular expression, thus, the relevance of the posted answers. You have the option to modify your question and wait for an answer which matches the updated problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T13:54:07.133",
"Id": "45482",
"Score": "0",
"body": "sure mate, it would be my pleasure. Any idea on displaying this list in ascending order by numbers? A Ton Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T14:04:54.577",
"Id": "45483",
"Score": "0",
"body": "You mean by number values (`5.2.1`, `5.6`, `1` etc)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T17:08:55.697",
"Id": "45484",
"Score": "0",
"body": "yes mate, the lines should be compared and sorted with their numbers !!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T08:22:11.153",
"Id": "28915",
"ParentId": "28914",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28915",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-19T07:46:37.290",
"Id": "28914",
"Score": "2",
"Tags": [
"c#",
"strings",
"regex"
],
"Title": "String compare, sort, regex split"
}
|
28914
|
<p>I have a method to replace URL parameters in an URL. It receives url as mandatory parameter and prefix and/or hash as optional parameters. Examples:</p>
<pre><code>url_replace( '/news?b=2', { b: nil } ) # => '/news'
url_replace( '/news?b=2', { b: 3 } ) # => '/news?b=3'
url_replace( '/news?a=b', '/bar' ) # => '/bar?a=b'
url_replace( '/news?a=b&c=d', '/bar', c: nil ) # => '/bar?a=b'
</code></pre>
<p>The method:</p>
<pre><code>def url_replace( target, *args )
uri = URI.parse(URI.escape target)
if hash = args.last.kind_of?(Hash) && args.last
query = uri.query ? CGI.parse(uri.query) : {}
hash.each do |k,v|
v ? query[k.to_s] = v.to_s : query.delete(k.to_s)
end
uri.query = query.any? ? query.map{|k,v| "#{CGI.escape k.to_s}=#{CGI.escape Array(v).join}"}.join('&') : nil
end
prefix = args.first.kind_of?(String) && args.first
uri.path = CGI.escape(prefix) if prefix
CGI.unescape(uri.to_s)
end
</code></pre>
<p>I would like some refactoring or speed optimizations.</p>
<p>Okay, here's the code I ended up with:</p>
<pre><code>def url_replace( target, *args )
uri = URI.parse(URI::DEFAULT_PARSER.escape target)
uri.path = CGI.escape(args.first) if args.first.kind_of?(String)
if args.last.kind_of?(Hash)
query = uri.query ? CGI.parse(uri.query) : {}
args.last.each{ |k,v| v ? query[k.to_s] = v.to_s : query.delete(k.to_s) }
uri.query = query.any? ? URI.encode_www_form(query) : nil
end
CGI.unescape(uri.to_s)
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:33:03.397",
"Id": "45493",
"Score": "0",
"body": "out of curiosity: can you paste a URL that `URI.parse` does not like?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:40:46.157",
"Id": "45494",
"Score": "0",
"body": "URI.parse 'кококо'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:51:37.913",
"Id": "45499",
"Score": "1",
"body": "But `URI` is correct here, you have to escape it first (like any browser does): `URI.parse(URI.escape('кококо'))`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T17:46:06.740",
"Id": "45544",
"Score": "0",
"body": "Thank you, this makes sense. I updated my question with new code."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><code>url_replace( '/news' )</code>: Each language has its formatting rules. In Ruby almost nobody inserts spaces after and before parens. </li>\n<li><code>hash = args.last.kind_of?(Hash) && args.last</code>: I'd strongly discourage this kind of positional arguments, the method signature is severely impaired. Use an options hash instead (note that Ruby 2.0 finally provides keyword arguments).</li>\n<li><code>query.delete(k.to_s)</code>. If you check my other answers you'll see I tend to favour functional programming, so I'd rewrite this using expressions instead of statements. Code is much more clean when they say what things are instead of how you change their value.</li>\n<li>Uses of <code>args.first</code> in the middle of the code: Strive for declarative code, give names to things before you use them when it's not clear what they are.</li>\n<li>I'd accept only strings as keys for the query string, or, if Activesupport is at hand, I'd call <code>stringify_keys</code> or <code>Hash[h.map { |k, v| [k.to_s, v] }]</code> at some point. This way I'd avoid mixing symbols and strings.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>require 'uri'\nrequire 'cgi'\n\ndef url_replace(url, options = {})\n uri = URI.parse(URI.encode(url))\n hquery = CGI::parse(uri.query)\n components = Hash[uri.component.map { |key| [key, uri.send(key)] }]\n new_hquery = hquery.merge(options[:merge_query] || {}).select { |k, v| v }\n new_query = URI.encode_www_form(new_hquery)\n new_components = {path: options[:path] || uri.path, query: new_query}\n new_uri = URI::Generic.build(components.merge(new_components))\n URI.decode(new_uri.to_s)\nend\n\nputs url_replace('/news?a=b&c=d', path: '/bar', merge_query: {\"c\" => nil})\n#=> /bar?a=b\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T07:14:08.380",
"Id": "45597",
"Score": "0",
"body": "Thanks for the tips! I updated my code. I think, it's pretty straightforward and clean considering I like it imperative and tested."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T19:04:37.467",
"Id": "28943",
"ParentId": "28917",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28943",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T09:59:22.347",
"Id": "28917",
"Score": "3",
"Tags": [
"ruby",
"url"
],
"Title": "Replace URL parameters with Ruby"
}
|
28917
|
<p>I did a little function which is listening to hashchanges.</p>
<p>What do you think about?</p>
<pre><code>var onhashchange = function(code) {
var checkHash = function(oldHash, code) {
var hash = window.location.hash;
var hashObject = hash.replace('#/','').split('/');
if (hash !== oldHash)
code(hashObject);
setTimeout(function(){checkHash(hash, code);},100);
}
var oldHash = window.location.hash;
setTimeout(function(){checkHash(oldHash, code);},100);
}
onhashchange(function(evt) {
console.log(evt[0]); // Pagename after #/ - subcategories evt[1]... after slashes /
});
</code></pre>
|
[] |
[
{
"body": "<p>First of and maybe a bit off-topic. The is this feature in all modern browsers now: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange\" rel=\"nofollow\">https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange</a> and the support is good: <a href=\"http://caniuse.com/hashchange\" rel=\"nofollow\">http://caniuse.com/hashchange</a></p>\n\n<p>Then the function. Perosnally I would use an anonymous function without storing it in a var first. I would pass in the hs 'unparsed' and simply pass the hash to the function instead of an array. It is snipplet that checks or the hash changes and should thus not be concerned on what the symbols in the hash mean.</p>\n\n<p>Also, instead of using the setTimeOut and calling it allover your code. Simply use the setInterval function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:41:10.373",
"Id": "28922",
"ParentId": "28919",
"Score": "2"
}
},
{
"body": "<p>You could re-write everything into just this:</p>\n\n<pre><code>window.onhashchange = function locationHashChanged() {\n doWhatYouWantNowThatTheHashHasChanged();\n //or return something\n}\n</code></pre>\n\n<p>And <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange\" rel=\"nofollow\">according to MDN</a>, the browser support is not too bad (IE8+). But if you do need to support IE7 and friends, you can use the <a href=\"https://github.com/cowboy/jquery-hashchange\" rel=\"nofollow\">jQuery plugin</a>.</p>\n\n<p>Also, depending on what you're going to use that for, you'll probably want to <a href=\"https://github.com/browserstate/history.js/wiki/Intelligent-State-Handling\" rel=\"nofollow\">read this article</a> about browser state handling.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:47:17.630",
"Id": "28941",
"ParentId": "28919",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T10:11:52.233",
"Id": "28919",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Simple haschange event"
}
|
28919
|
<p>Here's the situation: I've got several distinct objects, each with their own responsability and (therefore) each their own dependencies. As this is code that will be implemented in 2 existing applications, I've created my own namespaces, interfaces, abstract classes and so on... the works, basically.</p>
<p>IMO, the objects' inheritance chains are pretty tidy, and provide a solid base structure. There is but <em>one</em> thing that's really <em>"pissing me off"</em>, though. The fact that abstract methods don't allow for covariance at all. I'm using 2 abstract classes to <em>force</em> certain methods to occur in the child classes (like an <code>init</code> method, which is called from the abstract class).<br/>
Now as I said, each class has its own responsability, and I want to be able to specifically hint for a specific dependency at the childs level, and still enforce that method using the abstract class's restrictions. Especially since some of these methods shouldn't be public (thus ruling out interfaces, at any rate).</p>
<p>Here's a basic example:</p>
<pre><code>abstract class Base
{
protected $foo = null;
final public function __construct(Granny $init = null)
{
return $this->init($init);
}
abstract protected function init(Granny $dependency = null);
}
</code></pre>
<p>So I've made the constructor final, and Type-hinted <code>Granny</code> which, as the name suggest, is the base class for the <code>Base</code> instance's dependencies.<Br/>
Suppose <code>Granny</code> has a child: <code>Dad</code>, and the classes look like this:</p>
<pre><code>class Granny
{
protected $name = null;
protected $age = null;
public function __construct(array $vals = null)
{
foreach($vals as $name => $val)
{
$name = 'set'.ucfirst($name);
if (method_exists($this, $name))
{
$this->{$name}($val);
}
}
return $this;
}
//basic gettter && setters
public function getAge()
{
return $this->age;
}
public function setAge($age = null)
{
$this->age = $age === null ? null : (int) $age;
return $this;
}
}
class Dad extends Granny
{
//Dad's secret
private $likesMom = null;
public function getLikesMom()
{
return $this->likesMom;
}
public setLikesMom($bool = null)
{
$this->likesMom = $bool === null ? null : !!$bool;
return $this;
}
}
</code></pre>
<p>Now I've yet to see anyone play baseball with their grand mother, so The <code>Ball</code> class, which extends <code>Base</code>, depends on an instance of <code>Dad</code>, which I'll pass to the constructor (<code>Base</code> hints <code>Granny</code>, so it'll accept <code>Dad</code>, too). That dependency will be passed on to the <code>init</code> method, but to be sure the <code>Base::Ball</code> instance receives the correct dependency, I'd like to declare it like this:</p>
<pre><code>class Ball extends Base
{
protected function init(Dad $dependency = null)
{
$this->foo = $dependency;
return $this;
}
}
</code></pre>
<p>Which is where it all comes tumbling down with a fatal error, because the signatures don't match. Which, IMO, is inconsistent behaviour (since the <code>final public function __construct(Granny $foo = null)</code> doesn't complain, so I can't but pass an instance of <code>Granny</code>)<br/>
Anyway I know the code above is said to <em>"violate the contract"</em>, and I still maintain it's utter bull, but I've ended up doing this:</p>
<pre><code>//in Dad:
protected function init(Granny $dad = null)
{
return $this->setDad($dad);
}
//this was already defined => for DI
public function setDad(Dad $dependency = null)
{
$this->foo = $dependency;
return $this;
}
</code></pre>
<p>Just because it's more in-tune with how my code works than the, presumably, more performant:</p>
<pre><code>if ($dad !== null && !$dad instanceof Dad)
{
throw new InvalidArgumentException('You\'ll have to ask Dad to play catch');
}
$this->foo = $dad;
return $this;
</code></pre>
<p>But what I really want to know is: are there any other options I'm not seeing here? I'd love it if there were a sollution that allowed for covariancy, but after some googling, it's not looking good. I've even come to understand that covariant type-hints are deemed unimportant and won't be supported in the (near) future in PHP. They seem to find it more important to add return-type-hints to the method signatures, though...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:55:29.700",
"Id": "45500",
"Score": "0",
"body": "Please check [whats-wrong-with-overridable-method-calls-in-constructors](http://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-calls-in-constructors) and verify how PHP handles this issues."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:58:09.643",
"Id": "45501",
"Score": "0",
"body": "@mnhg: I'm fully aware of the pro's and cons, believe you me. I've written most of the other objects differently (with their own custom constructors), but this is a special case - honestly. I've [checked how PHP handles this](http://www.php.net/~derick/meeting-notes.html#implement-inheritance-rules-for-type-hints) and what I'm trying to do is not possible ATM, I just wanted to know if there's a more elegant approach"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:38:07.843",
"Id": "45525",
"Score": "0",
"body": "Maybe I'm missing something - is there a reason you have the abstract base class hinting `Granny` instead of a higher level object/interface that would be common to all dependencies? Why would `Ball` derive from a class that's dependent on `Granny`? It seems to me you haven't abstracted it *enough*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T07:07:21.700",
"Id": "45595",
"Score": "0",
"body": "@NathanLoding: the abstract class is hinting `Granny`, which is the base class for all sorts of classes, so it's the common to all dependencies. `Ball` derives from `Base`, not `Granny`. The fact is: `Ball` depends on `Dad`, which derives from `Granny`. So `Ball` depends on _a child of `Granny`_, in fact all children of `Base` will depend on a child of `Granny`, so to hint `Granny` in `Base` ensures the constructor accepts all dependencies, but in reality, all children of `Base` will require their own child of `Granny`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T12:51:57.643",
"Id": "45606",
"Score": "2",
"body": "I think you have two options - use the `instanceof` to verify, but I dislike that personally. Or don't make the base class abstract, and instead throw an exception if `init` is called from `Base`. I personally wouldn't worry about someone instantiating `Base`. http://pastebin.com/6zmUruZm"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-24T02:46:42.210",
"Id": "158825",
"Score": "1",
"body": "Rolled back Rev 2 → 1. Please write a comment or answer instead of spoiling the question."
}
] |
[
{
"body": "<p>Ok, apparantly you are a professional programmer so let me look at your code first:</p>\n\n<p>the __construct in the class Granny:</p>\n\n<pre><code>public function __construct(array $vals = null)\n{\n foreach($vals as $name => $val)\n {\n $name = 'set'.ucfirst($name);\n if (method_exists($this, $name))\n {\n $this->{$name}($val);\n }\n }\n return $this;\n}\n</code></pre>\n\n<p>First of, if another programmer needs to use your class he has NO IDEA how to use it. Yes, i need to add in an array of $vals. But this is just bad. I hope I don't have to explain why.. (code maintainability, readibility, ...)</p>\n\n<p>then, return $this; Seriously? what else would a __construct return? void?</p>\n\n<p>then: setAge($age=null). Why would I call setAge() withou passing in an age? And what is the meaning of 'null' not set?</p>\n\n<p>Why are you using init() instead of simply using __construct()? Because know you are simply calling init() in the __construct() of the parent class. Whereas you could and should simply do it this way:</p>\n\n<pre><code><?php\n\nclass Base {\n public function __construct(Granny $granny) {\n //do stuff\n }\n}\n\nClass Ball extends Base {\n public function __construct(Dad $dad) {\n //do stuff\n parent::__construct($dad);//let the parent do his magic\n }\n}\n</code></pre>\n\n<p>Now Ball needs a spcial kind of Granny whereas Base only needs a Granny. If Dad is a Granny nothing is wrong, if Dad isn't a Granny the code will not work because $dad is not a Granny. Problem fixed.</p>\n\n<p>But I bet there is some bewildered reason you didnt think of this easy 101 programming basics...</p>\n\n<p>Maybe now I will have offended you, but be honest, you are doing some really weird things that will not help the guy that comes after you, or joins your project or wants to use your code.\nOr maybe even yourself in 4 month when you come back to the Granny class. You then have no idea what the Granny class needs and what is optional. If it is optional leave it out of the construct. Makes testing a lot easier...</p>\n\n<p>So apologies If I offended you, but saying you are a professional because you work 4 years doesnt say much. I know professionals that have been coding for 4 years and still return $this in a __construct()</p>\n\n<p>OLD POST:</p>\n\n<p>Wow, back to the drawing board! I don't think you understand inheritance at all.</p>\n\n<p>Then fun thing about OO code is that Classes can allready tell you a lot by just looking at ho wthey are declared.\nFor isntance:</p>\n\n<pre><code>class Dog extends Mamal {}\n</code></pre>\n\n<p>Tells me that <code>Dog</code> is <code>Mamal</code>. And that <code>Dog</code> is more specific then <code>Mamal</code>.\nconsider the folowing corerct phrase:</p>\n\n<pre><code>A dog can walk, but not all Mamals can (Dolphins are mamals too)\n</code></pre>\n\n<p>Now, I have a German shepperd class:</p>\n\n<pre><code>class GermanShepperd extends Dog {}\n</code></pre>\n\n<p>Again this is logical and correct.</p>\n\n<p>Now lets look at your code:</p>\n\n<pre><code>class Granny\n</code></pre>\n\n<p>By looking at it I would say the Class Granny is some kind of stand-alone or base class. Not really specific but very abstract since it doesn't extend something.</p>\n\n<pre><code>class Dad extends Granny\n</code></pre>\n\n<p>Aha, <code>Dad</code> is a special case of <code>Granny</code>. Lets look into the class what it can do extra: Ah it can like a <code>Mom</code>. So, a <code>Dad</code> is a <code>Granny</code> that can like a <code>Mom</code>.</p>\n\n<p>Now, you are talking about 'abstract class restrictions'. If the abstract class is giving you restrictions then maybe the abstract class isn't abstract enough.\nIf my <code>Mamal</code> class needs legs to walk. Then my <code>Dolphin</code> with have some big troubles.</p>\n\n<p>So, back to the drawing board it is. Coding isnt about tapping the keyboard and writing code. Coding is an art, and it requires a lot of think work before you code. Draw it on a piece of paper. A Granny is simply a Women that has grandchildren. Not some kind of exotic object that if it can like a Mom it suddenly becomes a Dad.</p>\n\n<p>Lookup <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\">Solid</a> It's a good place to start. Try and stick to the rules. And also, once in a while take a big step back and think 'is the thing I am doing now actually solving my problem?'. Keep it simple. If the problem is not easily solved, chop it into more problems that you can solve. Then past them togeter.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:23:11.857",
"Id": "45503",
"Score": "0",
"body": "Now I must say: it looks like you've been lead astray by the example snippets I gave here. I'm using an abstract class to _ensure the children have certain methods declared_, like an interface, but interfaces require public methods (by their very nature). I assure you the abstract classes don't restrict the children too much, I'm looking for a more elegant way to implement the abstract method _with added restrictions at the child level_. I know all about SOLID, in fact convariant arguments adhere to the Liksov Substitution Principle (soLid)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:27:00.187",
"Id": "45505",
"Score": "0",
"body": "In short: the `Base` class hints `Granny`, but whilst one of `Base`'s children might need `Dad`, yet another might need `Mom`. All I want is `abstract protected function foo(Parent $instance = null);` and in the child define it as `protected function foo(ChildOfParent $instance = null)` to ensure the correct dependency was passed. BTW: I'm a professional developer, and have spent the last 4 years writing nothing but OO code, saying I don't understand inheritance is a bit of an insult, to be honest"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:33:15.627",
"Id": "45507",
"Score": "1",
"body": "You are creating problems before you even started fixing things. Just take a step back and look at the problem you are trying to solve. Can this be solved in one function? yes -> code the function. no? devide it into smaller problems. Do this recursively and you have a good program. Then apply ALL the SOLID rules to your code"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:35:38.153",
"Id": "45508",
"Score": "1",
"body": "If Base hints Granny it means it needs Granny. If then a child needs DAD instead of Granny you simply override the method and ask for a Dad"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:42:10.763",
"Id": "45511",
"Score": "0",
"body": "You do know that `Base` is abstract, right? It can't be instantiated, so I hint at the base model for all dependencies. While `Ball` will needs `Dad`, another child of `Base` might need `Mom`. `init` is an abstract method, BTW: by definition, the child class _has_ to overwrite it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:42:59.967",
"Id": "45512",
"Score": "0",
"body": "So what is the problem then? if Dad is a Granny there is none...And just look at your constructor. *shrug*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:45:48.250",
"Id": "45513",
"Score": "0",
"body": "Come on: _read the question again_: PHP doesn't allow for different type-hints: if the abstract method hints `SomeInterface $param`, the child can't implement that method using `ClassImplementingSomeInterface $param`, eventhough the hinted type @child level _is an instance of the type, hinted at in the abstract class_. Other languages _do_ support this, but PHP doesn't. Since this site is called _code review_ I wanted to make sure there wasn't a more elegant way of tackling the problem as the one I have ATM"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:48:15.790",
"Id": "45514",
"Score": "0",
"body": "What's with the constructor: That's a non-abstract. There, you can hint at the parent, and the child will be accepted, too. It's only when using _abstracts_ you encounter this problem. That's why I said that I find this inconsistent on PHP's part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:06:01.350",
"Id": "45516",
"Score": "0",
"body": "@EliasVanOotegem Sorry I I have offende you, but I have edited my answer with some more review..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:14:28.673",
"Id": "45517",
"Score": "0",
"body": "Ok: Again, this is an example, my real objects are well documented and easier to maintain and understand. Yes, I return `$this` mainly for documentation (IDE code hinting), and I like chainable objects, it's a habbit, doesn't hurt. `null` is there to unset the property. These objects are adaptations of data models, which are mapped to DB tables. If a getter returns null, there is no value specified. To unset a value, call the setter without an argument. I'm using `init`, because there's a lot more going on than my examples show, but that isn't relevant to the question, so I left it out"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:17:18.733",
"Id": "45518",
"Score": "0",
"body": "By declaring my constructor in the abstract class as final, the children cannot specify their own constructor. I can pass `Dad` to the `Base` constructor, no problem at all (`Dad instanceof Granny` is true). The child-specific assignments I would've done in their constructors are done in the `init` method, hence I force the children to declare it using an abstract method. But there, the type-hinting in PHP doesn't lend itself to convariance at all. Hint an interface in the abstract class, and the child can't hint an object that implements that interface... that's what bugs me here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:53:52.633",
"Id": "45520",
"Score": "0",
"body": "Here, read this: http://thedailywtf.com/Articles/The_Complicator_0x27_s_Gloves.aspx then take a step back and think 'Gloves'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:58:38.167",
"Id": "45521",
"Score": "0",
"body": "Nice link, but since the pair of gloves I'm after (ie just defining the method with the signature I need) isn't available, I'll just have to call the setter, as I am doing now, unless someone else trundles along"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T13:09:00.600",
"Id": "28924",
"ParentId": "28921",
"Score": "7"
}
},
{
"body": "<p>As I read it, using this in the super class:</p>\n\n<pre><code>final public function __construct(Granny $init = null)\n</code></pre>\n\n<p>followed by this in the subclass:</p>\n\n<pre><code>final public function __construct(Dad $init = null)\n</code></pre>\n\n<p>where <code>Dad</code> is a subtype of <code>Granny</code> is a violation of the Liskov substitution principle (also from the SOLID principles mentioned in the other answer), since it states that preconditions cannot be strengthened in a subtype (see <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle#Principle\" rel=\"nofollow\">the principle here</a>).</p>\n\n<p>I am not saying that it is obvious in your example, but it seems to be an edge case that can be really hard to get right from the perspective of the PHP developers (and IMHO they have bigger fishes to fry).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T08:20:19.493",
"Id": "45600",
"Score": "0",
"body": "All children of the `Granny` base-class are fully compliant, they only _add_ too the base-class, thus any child will comply with the inherited contract, and no pre-/postconditions will be violated. `Dad` _is_ a `Granny`, their _mitochondrial DNA_ (ie contract) is the same, though `Dad` only knows how to throw a curve-ball"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:27:34.537",
"Id": "45655",
"Score": "0",
"body": "If you change ``__construct`` to accept only ``Dad`` in stead of ``Granny``, you're restricting the the domain that ``$init`` can belong to. Maybe you think ``Dad`` is a great ``Granny`` that throws great curveballs made of DNA and stuff, but that doesn't change anything. (What are you smoking, by the way?)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T07:05:36.527",
"Id": "45722",
"Score": "0",
"body": "I can't change the `__construct`, because it's `final public function __construct(Granny $dep = null)` in the abstract `Base` class. If I pass a `Dad` to that constructor, covariance does apply... what's so hard to understand about that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-04T08:59:12.983",
"Id": "48891",
"Score": "0",
"body": "BTW: I don't know what you were thinking but what you read into my question isn't what I was asking, plus: your two method signatures will result in a fatal error: you can't override a final method in a subclass"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T21:30:25.613",
"Id": "28946",
"ParentId": "28921",
"Score": "0"
}
},
{
"body": "<p>I think @Pinoniq highlight's shoud be warmly welcomed\n, but i think i know why you want it that way, try:</p>\n\n<pre><code>abstract class Base\n{\n protected $foo = null;\n\n protected $_init = null;\n final public function __construct(Granny $init = null)\n {\n $this->_init = $init;\n //The only single possible call of init\n return $this->init();\n }\n abstract protected function init();\n}\n\nclass Ball extends Base {\n protected function init() {\n //so good as 'typeHint'\n if ( !($this->_init instanceof Dad) ) {\n throw new \\Exception();\n }\n return $this;\n }\n}\n</code></pre>\n\n<p>With <code>static</code> </p>\n\n<pre><code>abstract class Base {\n protected $foo = null;\n\n protected $_init = null;\n\n public static final function getOne(Granny $init = null) {\n return new static($init);\n\n }\n protected function __construct(Granny $init = null) {}\n\n}\n\nclass NoBall extends Base {\n\n protected function __construct(Granny $init = null) {\n }\n\n}\n\nclass Ball extends Base {\n\n protected function __construct(Dad $init = null) {\n }\n\n}\n\nclass Granny {}\nclass Dad extends Granny {}\n\n\n$G = new Granny();\n$D = new Dad();\n\n$Ag = NoBall::getOne($G);\necho get_class($Ag);\n$Ad = NoBall::getOne($D);\necho get_class($Ad);\n\n$Bd = Ball::getOne($D);\necho get_class($Bd);\n$Bg = Ball::getOne($G);\necho get_class($Bg);\n</code></pre>\n\n<p>Output</p>\n\n<pre><code>NoBallNoBallBall\nCatchable fatal error: Argument 1 passed to Ball::__construct() must be an instance of Dad, instance of Granny given\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-24T12:29:04.620",
"Id": "158928",
"Score": "0",
"body": "Welcome cske. I hope you enjoy CodeReview."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-24T12:29:43.587",
"Id": "158929",
"Score": "0",
"body": "That's no different to what I have now: `abstract protected function init(Granny $init);` + an implementation that does `if (!$init instanceof Data) throw`... the only difference is your're using a property to pass the argument, which is really quite pointless, IMHO"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-24T12:43:42.267",
"Id": "158931",
"Score": "0",
"body": "What I see `Base` is for an algortithm skeleton, subclasses methods fill the holes, 1. If work can be done when creating new object from it then constructor shoud not be final 2. If not then you shoud save somewhere the reference of constructor args. What you exactly want makes no sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-24T18:26:10.693",
"Id": "158980",
"Score": "0",
"body": "@elias-van-ootegem i've updated my answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T05:11:00.857",
"Id": "159418",
"Score": "0",
"body": "@cske: Your alternative suggestion (overriding the constructor) is a breach of the Liskov principle. PHP allows it, but most languages wouldn't. A constructor, just like any other method, should conform to the inherited contract"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T06:53:21.047",
"Id": "159427",
"Score": "0",
"body": "the contract is the getOne method constructor is protected so not part of the interface"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T07:01:07.377",
"Id": "159430",
"Score": "0",
"body": "anyway OP is all about break Liskov principle wo breaking it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T09:27:28.447",
"Id": "159452",
"Score": "0",
"body": "@cske: `protected function __construct(Granny $init = null) {}` in `Base` is overridden by `protected function __construct(Dad $init = null)`, which breaks the Liskov principle (Child classes cannot strengthen type-requirements, which `Ball` does in your example). PHP allows you to do this, but other languages would not, _because_ it violates the contract"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T09:35:27.133",
"Id": "159453",
"Score": "0",
"body": "@elias-van-ootegem I see no hope even to understand what you are asking , sorry for disturbing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-27T09:55:42.920",
"Id": "159456",
"Score": "0",
"body": "@cske: I haven't gotten around to it yet, but I've asked a similar question to this one [on programmers exchange](http://programmers.stackexchange.com/q/218217), the answer I've added the answer I got there to the OP, but the mods have asked me to post it as an answer instead. There's no way to do what I wanted initially. I appreciate the effort you put into answering this question, don't get me wrong, but I'm sorry to say that your suggestions won't solve the issue I tried to explain in the OP"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-04-24T12:16:32.107",
"Id": "87841",
"ParentId": "28921",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T12:30:32.560",
"Id": "28921",
"Score": "4",
"Tags": [
"php",
"inheritance",
"covariance"
],
"Title": "\"fake\" covariance in PHP type-hinting"
}
|
28921
|
<p>I'm currently working on a project that I had to create basically a running queue of items. My thought was to do this by a list, but surprisingly there weren't any methods to remove the first sequence or last sequence of items in a list that I found. I wrote the following class with extension methods for <code>List<T></code>:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace Extensions
{
public static class ExtensionClass
{
public static bool TrimFirst<T>(this List<T> list, int maxCount)
{
try
{
if (list.Count <= maxCount)
{
throw new InvalidOperationException
("Items in list <= maxCount, unable to trim list.");
}
while (list.Count > maxCount)
{
T first = list.First<T>();
list.Remove(first);
}
return true;
}
catch
{
return false;
}
}
public static bool TrimLast<T>(this List<T> list, int maxCount)
{
try
{
if (list.Count <= maxCount)
{
throw new InvalidOperationException
("Items in list <= maxCount, unable to trim list.");
}
while (list.Count > maxCount)
{
T last = list.Last<T>();
list.Remove(last);
}
return true;
}
catch
{
return false;
}
}
public static bool ItemExists<T>(this List<T> list, T item)
{
foreach (T listItem in list)
{
if (item.ToString() == listItem.ToString())
{
return true;
}
}
return false;
}
}
}
</code></pre>
<p>This seems something that I will likely use in the future, so I would like to optimize it and make it as flexible as possible. Does anyone have any suggestions? For reference, the try/catch/exception are in case I need to modify the code to deal with that in the future, although I was not quite sure about the way that I wrote that part of the code. Anyone that needs this function, feel free to use this code!</p>
<p>I have also added the <code>ItemExists()</code> method since I hate the <code>Any()</code> and <code>Exists()</code> methods' use of a predicate. As far as I know, this method processes the items by enumeration, just at the built-in methods do, except they possibly use a <code>Parallel.ForEach</code> loop. Any suggestions for optimizing this method?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T16:40:17.540",
"Id": "45538",
"Score": "2",
"body": "Did you consider a queue (FIFO) or stack (LIFO) collection?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T17:39:39.290",
"Id": "45543",
"Score": "0",
"body": "I have considered using a queue, but the way I thought of implementing it would require rewriting a large amount of code. I have realized now that I could just enqueue then dequeue with a while loop inside of an if statement, but that is essentially what I am doing here. Would there be any advantages to using that technique?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T17:22:48.717",
"Id": "45640",
"Score": "1",
"body": "@danielu13 - There's also `LinkedList<>` which specifically provides functions for adding to or removing from both ends."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T17:55:41.027",
"Id": "45642",
"Score": "0",
"body": "Great suggestion! I wasn't aware of that, but I looked it up and it offers performance gains for removing at the beginning of a list. I actually changed my code to use this. Thanks!"
}
] |
[
{
"body": "<pre><code>if (list.Count <= maxCount)\n{\n throw new InvalidOperationException(\"Items in list <= maxCount, unable to trim list.\");\n}\n</code></pre>\n\n<p>This doesn't seem like an exceptional case to me. If the idea is to trim the list to a certain size and the list is already smaller than that size -- the job is already done! In that case I would replace this with <code>return true;</code>.</p>\n\n<hr>\n\n<pre><code>while (list.Count > maxCount)\n{\n T last = list.Last<T>();\n list.Remove(last);\n}\n</code></pre>\n\n<p>This is the main guts of your method. Since the preceding <code>if</code> statement has already established that <code>list.Count > maxCount</code>, you know that the loop is always going to run at least one. Therefore you could replace this with a do-while loop. This is a negligible performance improvement.</p>\n\n<pre><code>do\n{\n T last = list.Last<T>();\n list.Remove(last);\n}\nwhile (list.Count > maxCount)\n</code></pre>\n\n<hr>\n\n<pre><code>catch\n{\n return false;\n}\n</code></pre>\n\n<p>Two problems here.</p>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow\">YAGNI</a></li>\n<li>Using boolean values to indicate whether or not the method was successful is a design flaw. This harks back to the old HRESULT days which were universally loathed. Instead, let the exception do the job of alerting the calling code to errors (this is what exceptions are for). In the case that there is no exception, there is no use for the returned <code>true</code> value.</li>\n</ul>\n\n<hr>\n\n<p>You could also consider returning a reference to the list itself from the method, allowing people to use <a href=\"http://en.wikipedia.org/wiki/Method_chaining\" rel=\"nofollow\">method chaining</a> syntax, which is all the rage these days - especially with LINQ..</p>\n\n<pre><code>public static List<T> TrimFirst<T>(this List<T> list, int maxCount)\n{\n if (list.Count <= maxCount)\n return list;\n\n do\n {\n T first = list.First<T>();\n list.Remove(first);\n }\n while (list.Count > maxCount);\n\n return list;\n}\n</code></pre>\n\n<hr>\n\n<p>One final thing. It's usually a good idea to defend against <code>NullReferenceExceptions</code> by asserting that your argument is not null.</p>\n\n<pre><code>if (list == null)\n throw new ArgumentNullException(\"list\");\n</code></pre>\n\n<p><code>ArgumentNullExceptions</code> are always preferable to <code>NullReferenceExceptions</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:46:53.790",
"Id": "45526",
"Score": "0",
"body": "Great suggestions! In addition to removing the exception, I removed the try/catch entirely and will just do it in the code that is using these methods if necessary. I especially liked the suggestion about returning the list for method chaining. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:51:56.233",
"Id": "45528",
"Score": "0",
"body": "@danielu13 No problem. FYI it's a bit of a faux-pas to edit the code in your question to match my suggestion. This invalidates my answer and could be confusing to other people who read this question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:54:16.307",
"Id": "45530",
"Score": "0",
"body": "My fault I've always wondered about that. Anyhow, I changed it back to help limit confusion"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:57:55.137",
"Id": "45531",
"Score": "0",
"body": "No worries! Other people might have far better improvements to your original code anyway - you wouldn't want to limit your options :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T16:58:58.843",
"Id": "45540",
"Score": "1",
"body": "“This is a negligible performance improvement.” And also a small readability decrease, I think it's not worth it ion this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T08:25:49.293",
"Id": "45602",
"Score": "0",
"body": "@svick I would concede that, even if only because do-while loops are bafflingly unidiomatic to C# developers."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:26:56.887",
"Id": "28930",
"ParentId": "28927",
"Score": "2"
}
},
{
"body": "<pre><code>public static bool ItemExists<T>(this List<T> list, T item)\n{\n foreach (T listItem in list)\n {\n if (item.ToString() == listItem.ToString())\n {\n return true;\n }\n }\n\n return false;\n}\n</code></pre>\n\n<p>This method has some problems:</p>\n\n<p>Using <code>ToString()</code> for equality comparison is likely to yield <em>many</em> false positives. The default implementation for <code>ToString</code> is just to return the fully qualified name of the type eg. <code>\"System.SomeClass\"</code>. This will mean that many objects will be considered equal when they are really not!</p>\n\n<p>It would be more semantically correct to use the <code>Object.Equals</code> method, since this method contains sensible defaults for types which have chosen not to override it (reference equality for reference types, value equality for value types).</p>\n\n<pre><code>public static bool ItemExists<T>(this List<T> list, T item)\n{\n foreach (T listItem in list)\n {\n if (item.Equals(listItem))\n return true;\n }\n\n return false;\n}\n</code></pre>\n\n<p>More preferable still is to get an <code>IEqualityComparer</code> instance for the objects. This will take into account special cases such as classes which implement <code>System.IEquatable</code>. The equality comparer can be found with <code>System.Collections.Generic.EqualityComparer<T>.Default</code>.</p>\n\n<pre><code>public static bool ItemExists<T>(this List<T> list, T item)\n{\n var comparer = EqualityComparer<T>.Default;\n\n foreach (T listItem in list)\n {\n if(comparer.Equals(item, listItem))\n return true;\n }\n\n return false;\n}\n</code></pre>\n\n<p>Even better yet, the <code>List</code> class already has a method called <code>Contains</code> which does all of these things :)</p>\n\n<pre><code>list.Contains(item);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T17:36:48.807",
"Id": "45542",
"Score": "0",
"body": "I figured that using `ToString()` would product errors if it were not defined for the object that it was being used on, but the application that I was building it for was using strings exclusively, so I didn't really focus on that. Thanks for the `Contains` suggestion though; I looked over that earlier, but I refactored my code to use that instead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T16:15:49.467",
"Id": "28932",
"ParentId": "28927",
"Score": "2"
}
},
{
"body": "<p>Consider using <a href=\"http://msdn.microsoft.com/en-us/library/y33yd2b5.aspx\" rel=\"nofollow\">RemoveRange</a> method as follows</p>\n\n<pre><code>list.RemoveRange(index, count)\n</code></pre>\n\n<p>Note: It's not defined for IList.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:07:57.303",
"Id": "45633",
"Score": "0",
"body": "I had looked at this before, but I just looked over it again and apparently before I missed the fact that it does indeed reindex the list so it can be reused at index 0. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T09:03:04.307",
"Id": "28962",
"ParentId": "28927",
"Score": "0"
}
},
{
"body": "<p>LINQ has extension methods for any <code>IEnumerable<></code> which will help with this.</p>\n\n<p>There's <a href=\"http://msdn.microsoft.com/en-us/library/bb503062.aspx\" rel=\"nofollow\"><code>.Take(x)</code></a>, which will return the first <code>x</code> elements, and <a href=\"http://msdn.microsoft.com/en-us/library/bb358985.aspx\" rel=\"nofollow\"><code>.Skip(x)</code></a> which will skip <code>x</code> elements, then return the rest. </p>\n\n<p>Of course, these don't actually <em>change</em> the <code>List<></code> they're operating on - they just return a new one. But that's a safer pattern to use - it means you have the option of keeping the untrimmed version around if you need to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:29:58.127",
"Id": "28980",
"ParentId": "28927",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28930",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:17:47.420",
"Id": "28927",
"Score": "1",
"Tags": [
"c#",
".net",
"collections",
"extension-methods"
],
"Title": "Extension Methods for Trimming List"
}
|
28927
|
<p>Can anyone think of a way to DRY up this code or is there a way to make it more efficient or quicker. Its what authenticates a user with my API and i want to make it as fast as possible.</p>
<pre><code>def authenticate!
authenticate_or_request_with_http_basic do |access_key, secret_key|
@current_app = App.find_by_access_key(access_key)
@current_app.secret_key == secret_key ? true : false
end
end
</code></pre>
|
[] |
[
{
"body": "<p>There is not much to say, just two notes:</p>\n\n<ul>\n<li><p>Common mistake of redundant boolean check: <code>some_boolean ? true : false</code> -> <code>some_boolean</code>. </p></li>\n<li><p>You can either use the bang find method or check the returned value, but not just use without a check.</p></li>\n</ul>\n\n<p>So simply:</p>\n\n<pre><code>def authenticate!\n authenticate_or_request_with_http_basic do |access_key, secret_key|\n @current_app = App.find_by_access_key(access_key)\n @current_app && @current_app.secret_key == secret_key\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T15:35:14.813",
"Id": "28931",
"ParentId": "28929",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "28931",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T14:59:27.180",
"Id": "28929",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"active-record"
],
"Title": "DRY Up Rails HTTP Basic Auth"
}
|
28929
|
<blockquote>
<p>If we list all the natural numbers
below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum
of these multiples is 23.</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</p>
</blockquote>
<p>Can someone give me suggestions on how to improve this solution? Also, please tell me whether or not my programming style is good.</p>
<pre><code>#include<stdio.h>
int main()
{
int a,b,c,d,sum3,sum5,sum15,total_sum;
b=999/3;
c=999/5;
d=999/15;
sum3=b*(3+999)/2;
sum5=c*(5+995)/2;
sum15=d*(15+990)/2;
total_sum=sum3+sum5-sum15;
printf("%d",total_sum);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T07:45:05.943",
"Id": "52639",
"Score": "1",
"body": "A [similar question](http://codereview.stackexchange.com/q/31051/9357) has been asked later."
}
] |
[
{
"body": "<ul>\n<li><p>Functions in C with no parameters should have a <code>void</code> parameter:</p>\n\n<pre><code>int main(void)\n</code></pre></li>\n<li><p>Variables should be declared/initialized on separate lines:</p>\n\n<pre><code>int a;\nint b;\nint c;\nint d;\nint sum3;\nint sum5;\nint sum15;\nint total_sum;\n</code></pre></li>\n<li><p>Try to avoid single-character variable names. They're very ambiguous and say nothing about the variable's purpose. The only valid exception to this is loop counter variables.</p></li>\n<li><p>Statements/blocks of different purposes should be separated to increase readability. That would be the divisions, the sums, and the <code>printf()</code>.</p></li>\n<li><p>Your operands should be spread out to make the lines more readable:</p>\n\n<pre><code>sum3 = b * (3+999) / 2;\n</code></pre></li>\n<li><p>Initializations should be done as late as possible to help aid in maintenance:</p>\n\n<pre><code>sum3 = b * (3+999) / 2;\n</code></pre></li>\n<li><p>Remove <code>int a</code> since it's never used.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:01:47.863",
"Id": "28938",
"ParentId": "28936",
"Score": "4"
}
},
{
"body": "<p>I would have implemented it like this:</p>\n\n<pre><code>printf(\"233168\");\n</code></pre>\n\n<p>And solved it on paper. But I guess that's cheating :-)</p>\n\n<p>I would probably write your code as:</p>\n\n<pre><code>#include <stdio.h>\n\nint calculateSumOfMultiples()\n{\n int sum = ((999/3) * (999 + 3))\n + ((999/5) * (995 + 5))\n - ((999/15) * (990 + 15));\n\n return sum / 2;\n}\n\nint main()\n{\n printf(\"%d\\n\", calculateSumOfMultiples());\n return 0;\n}\n</code></pre>\n\n<p>The key different points are:</p>\n\n<ul>\n<li><p>I think it's more readable to put the math into one equation like this. Using variables for temporary results is okay too, but then at least give the variables more meaningful names.</p></li>\n<li><p>I perform the divison only once. It's mathematically equivalent, and gives less clutter.</p></li>\n<li><p>I separate calculation from IO. I have a function that does all the work, and then call that function.</p></li>\n<li><p>I use whitespace and aligning to make the code more readable.</p></li>\n</ul>\n\n<p>To make the code even better, <code>calculateSumOfMultiples</code> could be a generic solution and take the number (<code>1000</code>) and multiples (<code>3</code> and <code>5</code>) as input. This is left as an exercise for the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T07:40:06.313",
"Id": "52637",
"Score": "3",
"body": "+1 for your point about `printf(\"233168\")`. Interestingly, an optimizing compiler will perform that calculation at compile time, such that `calculateSumOfMultiples()` will not even get called — it just compiles to 233168."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T07:42:12.993",
"Id": "52638",
"Score": "0",
"body": "If you're going to be stingy and postpone the division by 2, then rename `sum` to `doubleSum`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T19:22:22.587",
"Id": "28944",
"ParentId": "28936",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T17:41:21.067",
"Id": "28936",
"Score": "3",
"Tags": [
"c",
"project-euler"
],
"Title": "Project Euler #1 - Multiples of 3 and 5"
}
|
28936
|
<p>What do you think about this variant class?</p>
<p>Some hype: no RTTI needed, no heap allocation, supports copying.</p>
<pre><code>#pragma once
#ifndef VARIANT_HPP
# define VARIANT_HPP
#include <cassert>
#include <ostream>
#include <type_traits>
#include <typeinfo>
#include <utility>
namespace detail
{
template <typename A, typename ...B>
struct max_align_type
{
using type = typename ::std::conditional<
(alignof(A) > alignof(typename max_align_type<B...>::type)),
A,
typename max_align_type<B...>::type
>::type;
};
template <typename A, typename B>
struct max_align_type<A, B>
{
using type = typename ::std::conditional<
(alignof(A) > alignof(B)), A, B>::type;
};
template <typename A>
struct max_align_type<A>
{
using type = A;
};
template <typename A, typename ...B>
struct max_size_type
{
using type = typename ::std::conditional<
(sizeof(A) > sizeof(typename max_size_type<B...>::type)),
A,
typename max_size_type<B...>::type
>::type;
};
template <typename A, typename B>
struct max_size_type<A, B>
{
using type = typename ::std::conditional<
(sizeof(A) > sizeof(B)), A, B>::type;
};
template <typename A>
struct max_size_type<A>
{
using type = A;
};
template <typename A, typename B, typename... C>
struct index_of :
::std::integral_constant<int,
::std::is_same<A, B>{} ?
0 :
(-1 == index_of<A, C...>{}) ? -1 : 1 + index_of<A, C...>{}
>
{
};
template <typename A, typename B>
struct index_of<A, B> :
::std::integral_constant<int, ::std::is_same<A, B>{} - 1>
{
};
template <typename A, typename... B>
struct has_duplicates :
::std::integral_constant<bool,
(-1 == index_of<A, B...>{} ? has_duplicates<B...>{} : true)
>
{
};
template <typename A>
struct has_duplicates<A> :
::std::integral_constant<bool, false>
{
};
template <typename A, typename B, typename... C>
struct compatible_index_of :
::std::integral_constant<int,
::std::is_constructible<A, B>{} ?
0 :
(-1 == compatible_index_of<A, C...>{}) ?
-1 :
1 + compatible_index_of<A, C...>{}
>
{
};
template <typename A, typename B>
struct compatible_index_of<A, B> :
::std::integral_constant<int, ::std::is_constructible<A, B>{} - 1>
{
};
template <typename A, typename B, typename... C>
struct compatible_type
{
using type = typename ::std::conditional<
::std::is_constructible<A, B>{},
B,
typename compatible_type<A, C...
>::type
>::type;
};
template <typename A, typename B>
struct compatible_type<A, B>
{
using type = typename ::std::conditional<
::std::is_constructible<A, B>{}, B, void>::type;
};
template <class S, class C, typename = void>
struct is_streamable : ::std::false_type { };
template <class S, class C>
struct is_streamable<S,
C,
decltype(void(sizeof(decltype(::std::declval<S&>()
<< ::std::declval<C const&>()))))
> : ::std::true_type
{
};
template < ::std::size_t I, typename A, typename ...B>
struct type_at : type_at<I - 1, B...>
{
};
template <typename A, typename ...B>
struct type_at<0, A, B...>
{
using type = A;
};
template <bool B>
using bool_constant = ::std::integral_constant<bool, B>;
template <class A, class ...B>
struct all_of : bool_constant<A::value && all_of<B...>::value>
{
};
template <class A>
struct all_of<A> : bool_constant<A::value>
{
};
template <class A, class ...B>
struct any_of : bool_constant<A::value || any_of<B...>::value>
{
};
template <class A>
struct any_of<A> : bool_constant<A::value>
{
};
template <class A>
struct is_move_or_copy_constructible :
bool_constant< ::std::is_copy_constructible<A>{} ||
::std::is_move_constructible<A>{}>
{
};
}
#ifdef __GNUC__
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif // __GNUC__
template <typename... T>
struct variant
{
static_assert(!::detail::any_of< ::std::is_reference<T>...>{},
"reference types are unsupported");
static_assert(!::detail::any_of< ::std::is_void<T>...>{},
"void type is unsupported");
static_assert(::detail::all_of<
::detail::is_move_or_copy_constructible<T>...>{},
"unmovable and uncopyable types are unsupported");
static_assert(!::detail::has_duplicates<T...>{},
"duplicate types are unsupported");
using max_align_type = typename ::detail::max_align_type<T...>::type;
using max_size_type = typename ::detail::max_size_type<T...>::type;
static constexpr auto const max_align = alignof(max_align_type);
variant() = default;
~variant()
{
if (*this)
{
deleter_(store_);
}
// else do nothing
}
variant(variant const& other) { *this = other; }
variant(variant&& other) { *this = ::std::move(other); }
variant& operator=(variant const& rhs)
{
if (!rhs)
{
if (*this)
{
store_type_ = -1;
deleter_(store_);
}
// else do nothing
}
else if (rhs.copier_)
{
rhs.copier_(*this, rhs);
}
else
{
throw ::std::bad_typeid();
}
return *this;
}
variant& operator=(variant&& rhs)
{
if (!rhs)
{
if (*this)
{
store_type_ = -1;
deleter_(store_);
}
// else do nothing
}
else if (rhs.mover_)
{
rhs.mover_(*this, ::std::move(rhs));
}
else
{
throw ::std::bad_typeid();
}
return *this;
}
template <
typename U,
typename = typename ::std::enable_if< ::detail::any_of< ::std::is_same<
typename ::std::remove_reference<U>::type, T>...>{} &&
!::std::is_same<typename ::std::decay<U>::type, variant>{}
>::type
>
variant(U&& f)
{
*this = ::std::forward<U>(f);
}
template <typename S = ::std::ostream, typename U>
typename ::std::enable_if< ::detail::any_of< ::std::is_same<
typename ::std::remove_reference<U>::type, T>...>{} &&
!::std::is_rvalue_reference<U&&>{} &&
::std::is_copy_assignable<typename ::std::remove_reference<U>::type>{} &&
!::std::is_same<typename ::std::decay<U>::type, variant>{},
variant&
>::type
operator=(U&& f)
{
using user_type = typename ::std::remove_reference<U>::type;
if (::detail::index_of<user_type, T...>{} == store_type_)
{
*static_cast<user_type*>(static_cast<void*>(store_)) = f;
}
else
{
if (*this)
{
deleter_(store_);
}
// else do nothing
new (store_) user_type(::std::forward<U>(f));
deleter_ = destructor_stub<user_type>;
copier_ = get_copier<user_type>();
mover_ = get_mover<user_type>();
streamer_ = get_streamer<S, user_type>();
store_type_ = ::detail::index_of<user_type, T...>{};
}
return *this;
}
template <typename S = ::std::ostream, typename U>
typename ::std::enable_if<
::detail::any_of< ::std::is_same<
typename ::std::remove_reference<U>::type, T>...>{} &&
::std::is_rvalue_reference<U&&>{} &&
::std::is_move_assignable<typename ::std::remove_reference<U>::type>{} &&
!::std::is_same<typename ::std::decay<U>::type, variant>{},
variant&
>::type
operator=(U&& f)
{
using user_type = typename ::std::remove_reference<U>::type;
if (::detail::index_of<user_type, T...>{} == store_type_)
{
*static_cast<user_type*>(static_cast<void*>(store_)) = ::std::move(f);
}
else
{
if (*this)
{
deleter_(store_);
}
// else do nothing
new (store_) user_type(::std::forward<U>(f));
deleter_ = destructor_stub<user_type>;
copier_ = get_copier<user_type>();
mover_ = get_mover<user_type>();
streamer_ = get_streamer<S, user_type>();
store_type_ = ::detail::index_of<user_type, T...>{};
}
return *this;
}
template <typename S = ::std::ostream, typename U>
typename ::std::enable_if<
::detail::any_of< ::std::is_same<
typename ::std::remove_reference<U>::type, T>...>{} &&
!::std::is_copy_assignable<
typename ::std::remove_reference<U>::type>{} &&
!::std::is_move_assignable<
typename ::std::remove_reference<U>::type>{} &&
!::std::is_same<typename ::std::decay<U>::type, variant>{},
variant&
>::type
operator=(U&& f)
{
using user_type = typename ::std::remove_reference<U>::type;
if (*this)
{
deleter_(store_);
}
// else do nothing
new (store_) user_type(::std::forward<U>(f));
deleter_ = destructor_stub<user_type>;
copier_ = get_copier<user_type>();
mover_ = get_mover<user_type>();
streamer_ = get_streamer<S, user_type>();
store_type_ = ::detail::index_of<user_type, T...>{};
return *this;
}
explicit operator bool() const noexcept { return -1 != store_type_; }
template <typename S = ::std::ostream, typename U>
variant& assign(U&& f)
{
return operator=<S>(::std::forward<U>(f));
}
template <typename U>
bool contains() const noexcept
{
return ::detail::index_of<U, T...>{} == store_type_;
}
bool empty() const noexcept { return !*this; }
template <typename U>
typename ::std::enable_if<
(-1 != ::detail::index_of<U, T...>{}) &&
(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U
>::type
cget() const
{
if (::detail::index_of<U, T...>{} == store_type_)
{
return *static_cast<U const*>(static_cast<void const*>(store_));
}
else
{
throw ::std::bad_typeid();
}
}
template <typename U>
typename ::std::enable_if<
(-1 != ::detail::index_of<U, T...>{}) &&
!(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U const&
>::type
cget() const
{
if (::detail::index_of<U, T...>{} == store_type_)
{
return *static_cast<U const*>(static_cast<void const*>(store_));
}
else
{
throw ::std::bad_typeid();
}
}
template <typename U>
typename ::std::enable_if<
(-1 != ::detail::index_of<U, T...>{}),
U&
>::type
get()
{
if (::detail::index_of<U, T...>{} == store_type_)
{
return *static_cast<U*>(static_cast<void*>(store_));
}
else
{
throw ::std::bad_typeid();
}
}
template <typename U>
typename ::std::enable_if<
(-1 != ::detail::index_of<U, T...>{}),
U const&
>::type
get() const
{
if (::detail::index_of<U, T...>{} == store_type_)
{
return *static_cast<U const*>(static_cast<void const*>(store_));
}
else
{
throw ::std::bad_typeid();
}
}
template <typename U>
typename ::std::enable_if<
(-1 == ::detail::index_of<U, T...>{}) &&
(-1 != ::detail::compatible_index_of<U, T...>{}) &&
(::std::is_enum<U>{} || ::std::is_fundamental<U>{}),
U
>::type
get() const
{
static_assert(::std::is_same<
typename ::detail::type_at<
::detail::compatible_index_of<U, T...>{}, T...>::type,
typename ::detail::compatible_type<U, T...>::type>{},
"internal error");
if (::detail::compatible_index_of<U, T...>{} == store_type_)
{
return U(*static_cast<
typename ::detail::compatible_type<U, T...>::type const*>(
static_cast<void const*>(store_)));
}
else
{
throw ::std::bad_typeid();
}
}
template <typename U>
static constexpr int type_index() noexcept
{
return ::detail::index_of<U, T...>{};
}
int type_index() const noexcept { return store_type_; }
private:
using copier_type = void (*)(variant&, variant const&);
using mover_type = void (*)(variant&, variant&&);
using streamer_type = void (*)(void*, variant const&);
template <typename charT, typename traits>
friend ::std::basic_ostream<charT, traits>& operator<<(
::std::basic_ostream<charT, traits>& os, variant const& v)
{
v.streamer_(&os, v);
return os;
}
template <class U>
constexpr typename ::std::enable_if<
::std::is_copy_constructible<U>{}, copier_type
>::type
get_copier() const
{
return copier_stub<U>;
}
template <class U>
constexpr typename ::std::enable_if<
!::std::is_copy_constructible<U>{}, copier_type
>::type
get_copier() const
{
return nullptr;
}
template <class U>
constexpr typename ::std::enable_if<
::std::is_move_constructible<U>{}, mover_type
>::type
get_mover() const
{
return mover_stub<U>;
}
template <class U>
constexpr typename ::std::enable_if<
!::std::is_move_constructible<U>{}, mover_type
>::type
get_mover() const
{
return nullptr;
}
template <class S, class U>
constexpr typename ::std::enable_if<
::detail::is_streamable<S, U>{},
streamer_type
>::type
get_streamer() const
{
return streamer_stub<S, U>;
}
template <class S, class U>
constexpr typename ::std::enable_if<
!::detail::is_streamable<S, U>{},
streamer_type
>::type
get_streamer() const
{
return nullptr;
}
template <typename U>
static void destructor_stub(void* const p)
{
static_cast<U*>(p)->~U();
}
template <typename U>
static typename ::std::enable_if<
::std::is_copy_constructible<U>{} &&
::std::is_copy_assignable<U>{}
>::type
copier_stub(variant& dst, variant const& src)
{
if (src.store_type_ == dst.store_type_)
{
*static_cast<U*>(static_cast<void*>(dst.store_)) =
*static_cast<U const*>(static_cast<void const*>(src.store_));
}
else
{
if (dst)
{
dst.deleter_(dst.store_);
}
// else do nothing
new (dst.store_) U(*static_cast<U const*>(
static_cast<void const*>(src.store_)));
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
dst.streamer_ = src.streamer_;
dst.store_type_ = src.store_type_;
}
}
template <typename U>
static typename ::std::enable_if<
::std::is_copy_constructible<U>{} &&
!::std::is_copy_assignable<U>{}
>::type
copier_stub(variant& dst, variant const& src)
{
if (dst)
{
dst.deleter_(dst.store_);
}
// else do nothing
new (dst.store_) U(*static_cast<U const*>(
static_cast<void const*>(src.store_)));
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
dst.streamer_ = src.streamer_;
dst.store_type_ = src.store_type_;
}
template <typename U>
static typename ::std::enable_if<
::std::is_move_constructible<U>{} &&
::std::is_move_assignable<U>{}
>::type
mover_stub(variant& dst, variant&& src)
{
if (src.store_type_ == dst.store_type_)
{
*static_cast<U*>(static_cast<void*>(dst.store_)) =
::std::move(*static_cast<U*>(static_cast<void*>(src.store_)));
}
else
{
if (dst)
{
dst.deleter_(dst.store_);
}
// else do nothing
new (dst.store_) U(::std::move(*static_cast<U*>(
static_cast<void*>(src.store_))));
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
dst.streamer_ = src.streamer_;
dst.store_type_ = src.store_type_;
}
}
template <typename U>
static typename ::std::enable_if<
::std::is_move_constructible<U>{} &&
!::std::is_move_assignable<U>{}
>::type
mover_stub(variant& dst, variant&& src)
{
if (dst)
{
dst.deleter_(dst.store_);
}
// else do nothing
new (dst.store_) U(::std::move(*static_cast<U*>(
static_cast<void*>(src.store_))));
dst.deleter_ = src.deleter_;
dst.copier_ = src.copier_;
dst.mover_ = src.mover_;
dst.streamer_ = src.streamer_;
dst.store_type_ = src.store_type_;
}
template <class S, typename U>
static typename ::std::enable_if<
::detail::is_streamable<S, U>{}
>::type
streamer_stub(void* const os, variant const& v)
{
*static_cast<S*>(os) << v.cget<U>();
}
using deleter_type = void (*)(void*);
deleter_type deleter_;
copier_type copier_;
mover_type mover_;
streamer_type streamer_;
int store_type_{-1};
alignas(max_align_type) char store_[sizeof(max_size_type)];
};
#ifdef __GNUC__
# pragma GCC diagnostic pop
#endif // __GNUC__
#endif // VARIANT_HPP
</code></pre>
<p>Usage:</p>
<pre><code>#include <iostream>
#include "variant.hpp"
int main()
{
variant<std::string, int> v;
v = std::string("A");
std::cout << v.get<std::string>() << std::endl;
auto s(v);
std::cout << s.get<std::string>() << std::endl;
s = 999;
std::cout << s.get<float>() << std::endl;
s = v;
std::cout << s.get<std::string>() << std::endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T04:41:04.670",
"Id": "45588",
"Score": "0",
"body": "Quick comment: In your usage example, you should be able to write `v = std::string(\"AAAAAA\");` (without the `std::move`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T13:08:30.503",
"Id": "46750",
"Score": "0",
"body": "Now works with `g++` yay!"
}
] |
[
{
"body": "<p>I can think of one small improvement you can make.</p>\n\n<p>In the assignment operator (for both <code>variant</code> and <code>U</code> arguments), if the <code>typeid</code> of the argument is the same as <code>store_type_</code>, you can move the argument directly into store instead of deleting and re-newing.</p>\n\n<p>Otherwise, this is a pretty cool class -- always interesting to see what's possible with C++, though I'd have to see a fairly deep series of unit tests to be fully confident this code is correct. Some ideas for test cases:</p>\n\n<ul>\n<li><code>std::unique_ptr</code> with custom deleters moved into a <code>variant</code></li>\n<li>types with different alignments stored in the same <code>variant</code></li>\n<li><code>variant</code>s stored in a <code>variant</code></li>\n<li>trying to store a non-movable type fails to compile</li>\n<li>Simple things, like\n<ul>\n<li><code>get<U></code> fails to compile if <code>U</code> isn't one of the types (e.g. if it's a subtype of one of the types)</li>\n<li><code>get<U></code> throws when <code>U</code> isn't currently stored</li>\n<li><code>contains<U></code> works correctly</li>\n<li><code>variant<Foo, Bar> v(Foo()); Foo foo = std::move(v.get<Foo>());</code> works correctly.</li>\n</ul></li>\n</ul>\n\n<p>Some of these are a bit paranoid, but this is certainly the type of class where I'd like to push into the corner cases to ensure that they work as I expect.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T14:17:48.803",
"Id": "45609",
"Score": "0",
"body": "To move both destination and source objects must exist, so I cannot implement the improvement you propose. I could, however, implement support for `CopyConstructible` types."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T14:35:22.993",
"Id": "45612",
"Score": "0",
"body": "`*static_cast<U*>(static_cast<void*>(store_)) = std::move(f);` doesn't work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T21:05:21.223",
"Id": "45661",
"Score": "0",
"body": "This is the situation in which you're already storing an object of the appropriate type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T22:08:12.000",
"Id": "45670",
"Score": "0",
"body": "Sure, but the stored object needs to be either `MoveAssignable` or `CopyAssignable`, those are additional requirements to `MoveConstructible` and `CopyConstructible`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T00:12:09.193",
"Id": "45680",
"Score": "0",
"body": "Fair enough, but my sense is that most objects that are `MoveConstructible` are also `MoveAssignable`; in any case you can `enable_if` on `is_move_assignable`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T18:16:40.577",
"Id": "45824",
"Score": "0",
"body": "fixed, I think."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T05:06:09.067",
"Id": "28956",
"ParentId": "28939",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "28956",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T18:09:41.843",
"Id": "28939",
"Score": "6",
"Tags": [
"c++",
"c++11"
],
"Title": "Movable and copyable variant"
}
|
28939
|
<p>How can this be improved,to make it easier to maintain? There is so much boilerplate being thrown around, so is it possible to use annotations? I've seen one example from Stack Overflow, but it ended up using reflection in order to call the method.</p>
<p>I was already planning on somehow annotating these "variables" in order to automatically produce the documentation, to prevent the documentation going out of date.</p>
<p><a href="https://github.com/ElgarL/TownyChat/blob/582796e43a0c3b0828c8a5655e8d693bfed94c00/src/com/palmergames/bukkit/TownyChat/TownyChatFormatter.java" rel="nofollow">GitHub</a></p>
<pre><code>public class TownyChatFormatter {
private static StringReplaceManager<LocalTownyChatEvent> replacer = new StringReplaceManager<LocalTownyChatEvent>();
static {
replacer.registerFormatReplacement(Pattern.quote("{worldname}"), new TownyChatReplacerCallable() {
@Override
public String call(String match, LocalTownyChatEvent event) throws Exception {
return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName());
}
});
replacer.registerFormatReplacement(Pattern.quote("{town}"), new TownyChatReplacerCallable() {
@Override
public String call(String match, LocalTownyChatEvent event) throws Exception {
return event.getResident().hasTown() ? event.getResident().getTown().getName() : "";
}
});
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T07:14:10.450",
"Id": "45598",
"Score": "3",
"body": "`event.getEvent().getPlayer().getWorld().getName()` Holy Demeter!:)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-18T10:18:33.860",
"Id": "95323",
"Score": "0",
"body": "Coming back almost a year later I just figured to \"thank\" you for linking to an article or explaining what you even meant by demeter... I tried searching when you first mentioned it finding nothing due to not knowing the context.\n\nhttp://c2.com/cgi/wiki?LawOfDemeter"
}
] |
[
{
"body": "<p>If you don't mind using a String switch, and can't use Java 8 yet (lambda expressions should greatly simplify your existing code), you could use something like the following (which replaces the use of inner classes with a single switch):</p>\n\n<pre><code>static {\n register(\"{worldname}\", \"{town}\");\n}\n\nprivate static void register(final String... patterns) {\n for (final String pattern : patterns) {\n replacer.registerFormatReplacement(Pattern.quote(pattern), new TownyChatReplacerCallable() {\n @Override\n public String call(String match, LocalTownyChatEvent event) throws Exception {\n switch (pattern) {\n case \"{worldname}\": return String.format(ChatSettings.getWorldTag(), event.getEvent().getPlayer().getWorld().getName());\n case \"{town}\": return event.getResident().hasTown() ? event.getResident().getTown().getName() : \"\";\n default: throw new IllegalArgumentException();\n }\n }\n });\n }\n}\n</code></pre>\n\n<p>You would have to profile this to see whether the use of a switch made performance worse or better though (could be better, as the single registered function might be inlined and the switch should be fast). You could also use constants variables instead of strings, but that would increase code size.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T00:22:36.810",
"Id": "45575",
"Score": "0",
"body": "are string switches java 6 or 7, I'm restricted to 6 unfortunately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-23T16:04:03.477",
"Id": "50565",
"Score": "0",
"body": "@RyanTheLeach Unfortunately, String switches are in Java 7."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T23:35:04.677",
"Id": "28950",
"ParentId": "28942",
"Score": "3"
}
},
{
"body": "<p>Reflection is the way to go. The library you depend so transparently on is not \"object oriented\". It uses beans. That means its creators expect it to be used reflectively for some reason.</p>\n\n<p>Create a class to model the recurring concept:</p>\n\n<pre><code>class Replacement {\n String patern;\n String format;\n List<String> props;\n\n // getters, setters, etc...\n}\n</code></pre>\n\n<p>Factor out the repetition to configuration:</p>\n\n<pre><code># JSON-like config example\nreplacements: [{pattern:\"{world}\", format:\"WORLD: %s\", props:[\"event.player.world.name\"]},\n {pattern:\"{town}\", format: ...so and so....}]\n</code></pre>\n\n<p>Load them from config and change the repeating code to a loop:</p>\n\n<pre><code>for (Replacement replacement: replacements) {\n replacer.registerFormatReplacement(\n Pattern.quote(replacement.getPatern()), \n new TownyChatReplacerCallable() {\n @Override\n public String call(String match, LocalTownyChatEvent event) throws Exception {\n Object[] params = getProps(event, replacement.getProps());\n return String.format(replacement.getFormat(), params);\n }\n });\n}\n\nstatic Object[] getProps(Object bean, List<String> properties) {\n // use BeanUtils or some such library to get each property\n // and fill an array\n // use empty string for nulls here\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T02:49:48.627",
"Id": "45837",
"Score": "0",
"body": "I'm sorry I don't follow, I don't know much about beans.\n\nBut its not just the Towny library that I will need to support, there are many libraries that I wish to support, as the plugin I'm working on is designed to run side by side with TownyChat, Towny and other plugins by other authors."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T08:04:40.457",
"Id": "28960",
"ParentId": "28942",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28960",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T19:02:34.750",
"Id": "28942",
"Score": "2",
"Tags": [
"java",
"performance",
"parsing"
],
"Title": "Towny chat formatter"
}
|
28942
|
<p>The following is code I'm running to <code>FIRST</code>, <code>SECOND</code>, <code>THIRD</code> and so on until <code>SEVENTH</code> with a master query and a query of query.</p>
<p>As it's clear that I'm using the master query for each of <code>FIRSTCONN</code>, <code>SECONDCONN</code> etc., I want to have only one master query and the rest subqueries.</p>
<ol>
<li>Is this an efficient way to do so?</li>
<li>How can I make my code efficient?</li>
</ol>
<p></p>
<pre><code><!--- QoQ for FIRSTCONN --->
<!--- Master Query --->
<cfquery datasource = "XX.XX.X.XX" name="master1">
SELECT DATE(Timedetail) as FIRSTCONN, COUNT(Timedetail) as FIRSTOccurances, EVENTS
FROM MyDatabase
WHERE EVENTS = "FIRST"
GROUP BY FIRSTCONN ;
</cfquery>
<!--- Detail Query --->
<!--- <cfdump var = "#master#"> --->
<cfquery dbtype="query" name="detail1">
SELECT *
FROM master1
WHERE FIRSTCONN >= <cfqueryparam value="#form.startdate#" cfsqltype="cf_sql_varchar">
AND FIRSTCONN < <cfqueryparam value="#dateAdd('d', 1,form.enddate)#" cfsqltype="cf_sql_varchar">;
</cfquery>
<!--- QoQ for SECONDCONN --->
<!--- Master Query --->
<cfquery datasource = "XX.XX.X.XX" name="master2">
SELECT DATE(Timedetail) as SECONDCONN, COUNT(Timedetail) as SECONDOccurances, EVENTS
FROM MyDatabase
WHERE EVENTS = "SECOND"
GROUP BY SECONDCONN ;
</cfquery>
<!--- Detail Query --->
<!--- <cfdump var = "#master#"> --->
<cfquery dbtype="query" name="detail2">
SELECT *
FROM master2
WHERE SECONDCONN >= <cfqueryparam value="#form.startdate#" cfsqltype="cf_sql_varchar">
AND SECONDCONN < <cfqueryparam value="#dateAdd('d', 1,form.enddate)#" cfsqltype="cf_sql_varchar">;
</cfquery>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:33:38.597",
"Id": "45621",
"Score": "0",
"body": "@Matt Busche I tested the dump of master query, it's not pulling up any details for SECONDCONN. That is I can only see three columns as of now, namely, timedetail, firstOccurances and events. I belive UNION is not working"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T17:07:10.137",
"Id": "45639",
"Score": "0",
"body": "`union` is perfectly valid SQL. You can try with a `union all` but since the rows are different you shouldn't have different results. Using just `union` eliminates any duplicate rows and `union all` retains all rows"
}
] |
[
{
"body": "<p>You could use a UNION to run one master query</p>\n\n<pre><code><cfquery datasource = \"XX.XX.X.XX\" name=\"master1\">\nSELECT DATE(Timedetail) as FIRSTCONN, COUNT(Timedetail) as FIRSTOccurances, EVENTS \nFROM MyDatabase\nWHERE EVENTS = \"FIRST\" \nGROUP BY FIRSTCONN\nUNION\nSELECT DATE(Timedetail) as SECONDCONN, COUNT(Timedetail) as SECONDOccurances, EVENTS \nFROM MyDatabase\nWHERE EVENTS = \"SECOND\" \nGROUP BY SECONDCONN;\n</cfquery>\n</code></pre>\n\n<p>and then in your QoQ reference the correct column name</p>\n\n<pre><code><cfquery dbtype=\"query\" name=\"detail1\">\nSELECT *\nFROM master1 \nWHERE FIRSTCONN >= <cfqueryparam value=\"#form.startdate#\" cfsqltype=\"cf_sql_varchar\"> \nAND FIRSTCONN < <cfqueryparam value=\"#dateAdd('d', 1,form.enddate)#\" cfsqltype=\"cf_sql_varchar\">\nAND EVENTS = 'FIRST';\n</code></pre>\n\n<p></p>\n\n<pre><code><cfquery dbtype=\"query\" name=\"detail2\">\nSELECT *\nFROM master1\nWHERE SECONDCONN >= <cfqueryparam value=\"#form.startdate#\" cfsqltype=\"cf_sql_varchar\"> \nAND SECONDCONN < <cfqueryparam value=\"#dateAdd('d', 1,form.enddate)#\" cfsqltype=\"cf_sql_varchar\">\nAND EVENTS = 'SECOND';\n</cfquery> \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T04:36:47.950",
"Id": "45587",
"Score": "0",
"body": "Thanks for your answer. I have seven connections, I mean I'll have to UNION till SEVENTHCONN. Do you think that this will take less time as compared to what I have presently?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T12:59:40.723",
"Id": "45607",
"Score": "0",
"body": "you should set it up and time each one. It should be faster."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T03:34:11.253",
"Id": "28954",
"ParentId": "28947",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T22:28:36.487",
"Id": "28947",
"Score": "2",
"Tags": [
"sql",
"mysql",
"coldfusion",
"cfml"
],
"Title": "Running a master query and a query of queries"
}
|
28947
|
<p>This is the first code of this type that I've attempted, so I'm wondering if anybody would be willing to critique it. It's "sort of" (I think) a factory class. I want to keep it as simple as possible (and still work, and be at least as elegant as Phyllis Diller - it doesn't have to be Elizabeth Taylor).</p>
<p>The situation is that we may eventually support any number of printer types (printing labels from a Windows CE device), but want to keep the client code to something as simple as:</p>
<pre><code>var beltPrinter = new BeltPrinter();
beltPrinter.PrintLabel(price, description, barcode);
</code></pre>
<p>Each print job will consist of 0..N preparatory commands sent to the printer ("hey, wake up!") followed by 1..N print commands, followed by 0..N shutdown commands.</p>
<p>Based on that, does the following make sense? If not, what would you advise that I change?</p>
<pre><code>interface IBeltPrinter
{
private List<string> printerSetupCmds;
private List<string> printLabelCmds;
private List<string> printerTeardownCmds;
void PrintLabel();
}
class BeltPrinter : IBeltPrinter
{
if (<ZebraQL220>) // don't know yet how I will determine which printer is in use - perhaps from reading a config file
{
return ZebraQL220Printer;
}
else if (<ONeal>)
{
return ONealPrinter;
}
}
class ZebraQL220Printer : IBeltPrinter
{
public void PrintLabel(string Price, string Desc, string Barcode)
{
var _price = Price;
var _desc = Desc;
var _barcode = Barcode;
printerSetupCmds = new List<string>();
printerSetupCmds.Add(''); // the format and commands, etc. will differ from other printers
. . .
printLabelCmds = new List<string>();
printLabelCmds.Add('');
. . .
printerTeardownCmds = new List<string>();
printerTeardownCmds.Add('');
. . .
foreach (string line in printerSetupCmds) {
//send to ZebraQL220
}
foreach (string line in printLabelCmds) {
//send to ZebraQL220
}
foreach (string line in printerTeardownCmds) {
//send to ZebraQL220
}
}
}
class ONealPrinter : IBeltPrinter
{
public void PrintLabel(string Price, string Desc, string Barcode)
{
var _price = Price;
var _desc = Desc;
var _barcode = Barcode;
printerSetupCmds = new List<string>();
printerSetupCmds.Add(''); // the format and commands, etc. will differ from other printers
. . .
printLabelCmds = new List<string>();
printLabelCmds.Add('');
. . .
printerTeardownCmds = new List<string>();
printerTeardownCmds.Add('');
. . .
foreach (string line in printerSetupCmds) {
//send to ONeal
}
foreach (string line in printLabelCmds) {
//send to ONeal
}
foreach (string line in printerTeardownCmds) {
//send to ONeal
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T12:22:12.367",
"Id": "45603",
"Score": "0",
"body": "Interfaces cannot contain private fields (e.g. `private List<string> printerSetupCmds;`). The line `class IBeltPrinter BeltPrinter()` is also invalid syntax. These errors in your example are significant enough to make it rather difficult to determine the intent of your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:38:33.297",
"Id": "45634",
"Score": "0",
"body": "Okay, so what should it be (rather than \"class IBeltPrinter BeltPrinter()\"? I want it to return an IBeltPrinter (something that implements IBeltPrinter), and \"BeltPrinter\" seems a rational name for the method, so...???"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:52:32.513",
"Id": "45637",
"Score": "0",
"body": "It looks like you want to create a factory class which includes an `IBeltPrinter NewBeltPrinter()` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T01:02:40.533",
"Id": "53104",
"Score": "0",
"body": "This is not a valid C# code. It's important to have working code if you want us to review it."
}
] |
[
{
"body": "<p>First off, I have to say this is a very clean and efficient design.</p>\n\n<p>I'm hoping <code>class IBeltPrinter BeltPrinter()</code> is a typo, because I've never seen C# code like that.</p>\n\n<p>Variable names for local variables (and parameters) should start with a lower case letter.</p>\n\n<p>I would move the setup, labelCommands and tear down into their own methods. It will keep the <code>PrintLabel</code> method much cleaner</p>\n\n<pre><code>public void PrintLabel(string price, string desc, string barcode)\n{\n ExecuteSetup(/*variables*/);\n ExecuteCommands(/*variables*/);\n ExecuteTeardown(/*variables*/);\n}\n</code></pre>\n\n<p>Come to think of it, you could have a base class that has the <code>PrintLabel method, and virtual</code>ExecuteSetup<code>,</code>ExecuteCommands<code>, and</code>ExecuteTeardown` methods, that have generic printer commands. You could then extend that base class as required.</p>\n\n<p>I would also consider putting the Factory definitions in an IDictionary. This will eliminate having a potentially huge switch statement.</p>\n\n<pre><code>private readonly static IDictionary<[whatever], IBeltPrinter> SupportedPrinters = new Dictionary<[whatever], IBeltPrinter>\n {\n {[ZebraQL220], new ZebraQL220Printer()},\n {[ONeal], new ONealPrinter()},\n }\n</code></pre>\n\n<p>Then your factory call would be</p>\n\n<pre><code>public IBeltPrinter CreatePrinter([whatever] printer)\n{\n if (!SupportedPrinters.ContainsKey(printer))\n throw new PrinterNotSupportedException(printer)\n\n return SupportedPrinters[printer];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:39:23.147",
"Id": "45635",
"Score": "0",
"body": "No, \"class IBeltPrinter BeltPrinter()\" was not a typo; apparently, it's a braino. What should it be instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:50:29.503",
"Id": "45636",
"Score": "0",
"body": "@ClayShannon, that depends on what the intent of the line is."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T23:27:49.820",
"Id": "28949",
"ParentId": "28948",
"Score": "1"
}
},
{
"body": "<p>This is a textbook problem for polymorphism. Here's the fully working code:</p>\n\n<pre><code>void Main()\n{\n var oNealPrinter = PrinterFactory.Create(\"ONeal\");\n oNealPrinter.PrintLabel(new LabelDetail() { Price = \"10\", Description = \"Hello\", BarCode = \"ABC\" } );\n\n var zebraPrinter = PrinterFactory.Create(\"Zebra\");\n zebraPrinter.PrintLabel(new LabelDetail() { Price = \"10\", Description = \"Hello\", BarCode = \"ABC\" } ); \n}\n\npublic static class PrinterFactory\n{\n //The following Create method you can put your logic of which printer is available.\n //Adjust the arguments and the code as per your need. \n public static IBeltPrinter Create(string type)\n {\n if(string.IsNullOrWhiteSpace(type))\n throw new ArgumentNullException(\"type\");\n\n if(type == \"ONeal\")\n return new ONealPrinter();\n\n if(type == \"Zebra\")\n return new ZebraQL220Printer();\n\n throw new InvalidOperationException(\"Can not create printer of type \" + type);\n }\n}\n\npublic interface IBeltPrinter\n{\n void PrintLabel(LabelDetail labelDetail);\n}\n\npublic class ONealPrinter : BeltPrinterBase\n{\n protected override IEnumerable<string> SetupCommands \n {\n get\n {\n yield return \"ONeal Setup\";\n }\n }\n\n protected override IEnumerable<string> LabelCommands \n {\n get\n {\n yield return \"ONeal Label\";\n }\n }\n\n protected override IEnumerable<string> TearDownCommands \n {\n get\n {\n yield return \"ONeal Teardown\";\n }\n }\n\n}\n\n\npublic class ZebraQL220Printer : BeltPrinterBase\n{\n protected override IEnumerable<string> SetupCommands \n {\n get\n {\n yield return \"Zebra Setup\";\n }\n }\n\n protected override IEnumerable<string> LabelCommands \n {\n get\n {\n yield return \"Zebra Label\";\n }\n }\n\n protected override IEnumerable<string> TearDownCommands \n {\n get\n {\n yield return \"Zebra Teardown\";\n }\n }\n\n}\n\npublic abstract class BeltPrinterBase : IBeltPrinter\n{\n public LabelDetail LabelDetail { get; private set; }\n\n protected abstract IEnumerable<string> SetupCommands { get; }\n\n protected abstract IEnumerable<string> LabelCommands { get; }\n\n protected abstract IEnumerable<string> TearDownCommands { get; }\n\n IEnumerable<string> AllCommands \n {\n get\n {\n return SetupCommands.Union(LabelCommands).Union(TearDownCommands);\n } \n }\n\n public void PrintLabel(LabelDetail labelDetail)\n {\n if(labelDetail == null)\n throw new ArgumentNullException(\"labelDetail\");\n\n LabelDetail = labelDetail;\n\n foreach (var command in AllCommands)\n {\n Console.WriteLine(command);\n }\n\n Console.WriteLine(\"Printed Label - \" + labelDetail);\n }\n\n}\n\n//Creating a new LabelDetail class will capture the details as semantic\n//unit and make future maintenance easier.\npublic class LabelDetail\n{\n public string Price { get; set; }\n\n public string Description { get; set; }\n\n public string BarCode { get; set; }\n\n public override string ToString()\n {\n return \"Price: \" + Price + \" Description: \" + Description + \" BarCode: \" + BarCode;\n }\n}\n</code></pre>\n\n<p>The output of the program is:</p>\n\n<pre><code>ONeal Setup\nONeal Label\nONeal Teardown\nPrinted Label - Price: 10 Description: Hello BarCode: ABC\nZebra Setup\nZebra Label\nZebra Teardown\nPrinted Label - Price: 10 Description: Hello BarCode: ABC\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T01:20:07.607",
"Id": "33146",
"ParentId": "28948",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T23:12:28.207",
"Id": "28948",
"Score": "3",
"Tags": [
"c#",
".net",
"factory-method"
],
"Title": "RFC on \"Factory\" code"
}
|
28948
|
<p>I am trying to write a function, where given a sorted array, and a number, it returns the FIRST index of that number.</p>
<p>Is this correct? Code is in Ruby, but even if you don't know Ruby, you can pretty much understand the syntax.</p>
<pre><code>def first(array, n)
if(array.size == 0)
return -1
end
l = 0
u = array.size - 1
#LOOP INVARIANT:
# l <= startIndex <= u
while( l != u)
#LOOP TERMINATES when l = u.
#this occurs if we reach the far right or far left without finding the #
#or if we found the start index of the number
m = (l+u)/2
if(array[m] > n)
u = m -1 # l <= startIndex <= u
elsif(array[m] < n)
l = m + 1 # l <= startIndex <= u
elsif(array[m] == n)
u = m # l <= startIndex <= u
end
#LOOP always terminates because we're narrowing the range by changing l or u.
#if there's 1 element, finding the midpoint won't narrow the range,
#but the while condition ends the loop anyway.
end
if(array[u] == n)
return u
else
return -1
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T04:32:27.300",
"Id": "45585",
"Score": "2",
"body": "Could you post an example of input and output?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:10:04.427",
"Id": "46032",
"Score": "0",
"body": "@HenleyChiu: you should give feedback to the people that took their time to answer and comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T02:16:21.433",
"Id": "46191",
"Score": "0",
"body": "The code looks fine to me. (The elsif(array[m] == n) could be 'else' if you wanted). But.. if you are looking for correctness, why not just unit test the method will all the edge cases you can think of?"
}
] |
[
{
"body": "<p>Not exactly a code review, but did you know that ruby 2 introduces binary search for arrays ? </p>\n\n<p>See : <a href=\"http://ruby-doc.org/core-2.0/Array.html#method-i-bsearch\" rel=\"nofollow\">Array#bsearch</a>. </p>\n\n<p>your problem could be solved like this: </p>\n\n<pre><code>myarray.each_with_index.to_a.bsearch{|(x,index)| x == n}\n# => if found, returns an array containing the number and the index \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T14:14:36.780",
"Id": "45608",
"Score": "1",
"body": "The `Array#bsearch` reference is spot on. The problem is that, since we must index the input array, the complexity of the problem is no longer O(log n) but O(n), the same a simple `Array#index` would do (and without creating an intermediate array). I have an answer prepared with a custom `Array#bsearch`, but I am not sure there is something more elegant so I'll wait a bit..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:58:13.913",
"Id": "45638",
"Score": "0",
"body": "But of course it depends on the requirements: if it's going to be 1 initialize, N searches I guess it's ok to do a O(n) pre-processing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T07:48:31.343",
"Id": "45726",
"Score": "0",
"body": "oh right, this did not cross my mind !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T08:06:56.087",
"Id": "45727",
"Score": "0",
"body": "I am a bit puzzled as to why `Array#bsearch` does not return the value *and* the index. Specially in a find-minimum binary search not knowing the index is very limiting."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T13:29:11.750",
"Id": "28970",
"ParentId": "28953",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T02:45:47.257",
"Id": "28953",
"Score": "2",
"Tags": [
"ruby",
"binary-search"
],
"Title": "First Occurrence of Number in Binary Search?"
}
|
28953
|
<p>I am tracking trains and trying to identify individual trains seen multiple times at different points through the IDs of the wagons on them when spotted.</p>
<pre><code>// create a lookup of all tracked trains for each wagon
IEnumerable<Train> trains = GetTrains();
var wagonTrains = new Dictionary<int, List<Train>>();
foreach (Train t in trains)
{
foreach (int w in t.WagonsInTrain)
{
if (!wagonTrains.ContainsKey(w))
{
wagonTrains.Add(w, new List<Train>());
}
wagonTrains[w].Add(t);
}
}
</code></pre>
<p>Is there a better way do to what I am doing in this code segment? Perhaps some chained linq operations? Is there a particular name for the kind of operation I am using here?</p>
|
[] |
[
{
"body": "<blockquote>\n <p>create a lookup of all tracked trains for each wagon</p>\n</blockquote>\n\n<p>That's pretty much what <a href=\"http://msdn.microsoft.com/en-us/library/bb549211.aspx\">the <code>ToLookup()</code> method</a> is for. You just need a bit more LINQ to get a collection of (train, wagon) pairs, so that <code>ToLookup()</code> can work:</p>\n\n<pre><code>var wagonTrains =\n (from train in trains\n from wagon in train.WagonsInTrain\n select new { train, wagon })\n .ToLookup(x => x.wagon, x => x.train);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T11:06:57.517",
"Id": "28966",
"ParentId": "28964",
"Score": "5"
}
},
{
"body": "<p>Here is one that uses <em>chained linq operations</em>:</p>\n\n<pre><code>var trainsByWagon =\n trains\n .SelectMany(train => train.WagonsInTrain, (train, wagon) => new { train, wagon })\n .GroupBy(trainAndWagon => trainAndWagon.wagon, trainAndWagon => trainAndWagon.train);\n .ToDictionary(g => g.Key, g => g.ToList());\n</code></pre>\n\n<p>Small print: Haven't actually tried this, but should work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:37:03.977",
"Id": "45624",
"Score": "0",
"body": "Sorry, I eventually accepted the chronologicaly first answer, but both are super useful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T11:19:33.470",
"Id": "28967",
"ParentId": "28964",
"Score": "2"
}
},
{
"body": "<p>I've actually set this up in my code as a pair of extension methods:</p>\n\n<pre><code>public static class IDictionaryExtensions\n{\n public static void Update<TKEY, TVALUE>(this IDictionary<TKEY, TVALUE> dictionary, TKEY key, TVALUE value)\n {\n if (dictionary.ContainsKey(key))\n {\n dictionary[key] = value;\n }\n else\n {\n dictionary.Add(key, value);\n }\n }\n public static void AddToList<TKEY, TVALUE>(this IDictionary<TKEY, IList<TVALUE>> dictionary, TKEY key, TVALUE value)\n {\n if (dictionary.ContainsKey(key) && dictionary[key] != null)\n {\n dictionary[key].Add(value);\n }\n else\n {\n dictionary.Update(key, new List<TVALUE> {value});\n }\n }\n }\n</code></pre>\n\n<p>The first method is an all-purpose \"Add\"-type method which will either add it or update it depending on whether or not it exists. The second is specifically for dictionaries where the value is a <code>List<></code>. It'll let you add an element to the <code>List<></code>, creating the key if neccesary.</p>\n\n<hr>\n\n<p>For your example, usage would be:</p>\n\n<pre><code>IEnumerable<Train> trains = GetTrains();\nvar wagonTrains = new Dictionary<int, List<Train>>();\nforeach (var train in trains)\n{\n foreach (var wagon in train.WagonsInTrain)\n {\n wagonTrains.AddToList(wagon, train);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T17:49:02.277",
"Id": "45641",
"Score": "0",
"body": "Your code wouldn't compile, `AddToList()` has two parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T13:58:50.923",
"Id": "45742",
"Score": "0",
"body": "@svick - Good catch. That's what I get for freehanding it. Fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:38:31.083",
"Id": "28982",
"ParentId": "28964",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "28966",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T10:18:06.577",
"Id": "28964",
"Score": "3",
"Tags": [
"c#",
"linq"
],
"Title": "Write nested loops as linq query"
}
|
28964
|
<p>G'day
Just before I submit this to CFLib, it'd be great to get feedback:</p>
<pre><code><cfscript>
/**
* @hint CFML implementation of Array.reduce(), similar to Javascript's one ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
* @array Array to reduce
* @callback Callback function to use to reduce. Will receive the following arguments: element (of current iteration of the all), index, array, (optional) result (of preceeding call to callback())
* @initialValue The initial value to use to start the reduction
*/
public any function arrayReduce(required array array, required any callback, any initialValue){
var startIdx = 1;
if (!structKeyExists(arguments, "initialValue")){
if (arrayLen(array) > 0){
var result = callback(array[1], 1, array);
startIdx = 2;
}else{
return;
}
}else{
var result = initialValue;
}
for (var i=startIdx; i <= arrayLen(array); i++){
result = callback(array[i], i, array, result);
}
return result;
}
</cfscript>
</code></pre>
<p>I've created <a href="https://gist.github.com/adamcameroncoldfusion/6082824" rel="nofollow">proper unit tests as a gist</a>.</p>
|
[] |
[
{
"body": "<p>I don't see any flaws in your logic... <strong>but...</strong></p>\n\n<p>I know you've basically just ported the referenced JavaScript example, but I'm not really fond of the implementation of <code>initialValue</code>.</p>\n\n<p>Instead, have a look at <a href=\"https://github.com/russplaysguitar/UnderscoreCF/blob/master/Underscore.cfc#L115\" rel=\"nofollow\">UnderscoreCF's reduce method</a>: (which was itself ported from UnderscoreJS)</p>\n\n<pre><code>/**\n* @header _.reduce(collection, iterator, memo, [context]) : any\n* @hint Also known as inject and foldl, reduce boils down a collection of values into a single value. Memo is the initial state of the reduction, and each successive step of it should be returned by iterator.\n* @example sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);<br />=> 6\n*/\npublic any function reduce(obj = this.obj, iterator = _.identity, memo, this = {}) {\n\n var outer = {};\n if (structKeyExists(arguments, \"memo\")) {\n outer.initial = memo;\n }\n _.each(arguments.obj, function(value, index, collection, this) {\n if (!structKeyExists(outer, \"initial\")) {\n memo = value;\n outer.initial = true;\n }\n else {\n memo = iterator(memo, value, index, this);\n }\n }, arguments.this);\n\n return memo;\n}\n</code></pre>\n\n<p>Granted it does lean on the _.each method, so it can be a little difficult to wrap your head around. The important bit is:</p>\n\n<p>You can omit the <code>initialValue</code> value and it will be correct no matter what data type is being reduced. Since you have a default value of an empty string, if you're working with numerics, you pretty much <em>have</em> to set an initial value.</p>\n\n<p>On the other hand, the way UnderscoreCF's implementation works is that, <em>if you've not specified a value for memo (initialValue)</em> then it uses the first item in the array as the initial value, and skips the first iteration.</p>\n\n<p>So let's look at two (somewhat contrived) examples:</p>\n\n<pre><code>//string concat\narrayReduce(['A','d','a','m'], function(memo, item){\n return memo & item;\n});\n</code></pre>\n\n<p>This (above) will concatenate the characters together into a string. It would work via either implementation of reduce (yours or UnderscoreCF's).</p>\n\n<pre><code>//sum\narrayReduce([1,2,3,4], function(memo, item){\n return memo + item;\n});\n</code></pre>\n\n<p>This one does a sum, similarly to your example, except that your implementation of reduce will (probably? I haven't tested to see what would happen...) choke because the callback is expecting numerics but memo is defaulted to an empty string for the first iteration.</p>\n\n<p>Hopefully this is clear. It's a subtle difference.</p>\n\n<hr>\n\n<p>In writing this answer I've thought of a potential bug in the Underscore implementation: What if you're concatenating a string but you only wanted to include lower-cased characters?</p>\n\n<pre><code>arrayReduce(['A','d','a','m'], function(memo, item){\n var asciiCode = asc(item);\n return memo & ( asciiCode >= 97 && asciiCode <= 122 ? item : '');\n});\n</code></pre>\n\n<p>You would expect the result to be: <code>dam</code> but would probably get back <code>Adam</code> with UnderscoreCF's implementation. It would be easily mitigated by passing <code>''</code> for the initialValue argument to reduce, but it is worth noting.</p>\n\n<p>Food for thought! :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T19:20:03.827",
"Id": "45645",
"Score": "0",
"body": "Cheers Adam, I've modified the code to get rid of the default initialValue, plus added some unit tests. If what you say about Underscore's handling of the initial value is true, that's just the wrong approach (and there's no way it can reasonably be construed to be right, I think). It shouldn't be the VALUE of the first element in the array, it should be the value of the result of the first callback call... and the callback should be dealing with the potentiality of there being no starting value. Examples of this in my unit tests. Thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:14:59.837",
"Id": "45653",
"Score": "0",
"body": "I agree that it would be smarter for the first iteration to use the result of the callback as the memo going into the second (that is the bug I implied), but the fix brings us back to the issue of either requiring an initialValue, or setting a default which may be the wrong type, or requiring a param/default in the closure. None of those solutions is ideal, imo."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T14:02:28.453",
"Id": "28974",
"ParentId": "28968",
"Score": "2"
}
},
{
"body": "<p>Interesting discussion! </p>\n\n<p>@AdamTuttle Regarding the behavior in Underscore that you've highlighted: \nI did some quick tests and found that the same behavior exists in Ruby and native JS (Chrome and FF). This confirmed my suspicions that this seemingly weird behavior is just a product of the reduce algorithm itself. </p>\n\n<p>In the algorithm, \"memo\" represents the current state of the fold operation. If you don't pass in an initial value, you're implying that the first element of the collection represents the initial state of the fold. From that perspective, the behavior you've shown is exactly what I'd expect. </p>\n\n<p>If you want to remove uppercase letters from a collection and convert that to a string in a functional way, it would make more sense to call <code>filter()</code> to and then <code>reduce()</code>. Example: </p>\n\n<pre><code>adamArr = ['A','d','a','m'];\ndamArr = _.filter(adamArr, function (letter) { \n var asciiCode = asc(letter); \n return asciiCode >= 97 && asciiCode <= 122;\n};\ndamString = _.reduce(damArr, function (memo, letter) {\n return memo & letter;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T06:11:23.847",
"Id": "45796",
"Score": "0",
"body": "btw, I wanted to make this a reply to AdamT, but apparently I wrote too much for that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T17:06:40.300",
"Id": "45817",
"Score": "0",
"body": "Hi Russ. Seen in that light, your implementation of Underscore behaves the right way (in that it conforms with the precedent). However I still think THE PRECEDENT uses a poor & illogical approach. It makes no sense to treat the first element of the array in a \"special\" way the way it does. I think my approach here well be to just document the behavioural difference. Thoughts? If you want more discussion space, feel free to comment on my equivalent blog article instead: http://cfmlblog.adamcameron.me/2013/07/cfml-implementation-of-javascripts.html."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T16:08:32.447",
"Id": "45863",
"Score": "0",
"body": "I can see why you might feel that way about the precedent, but I still don't have a conceptual problem with it. It's not that the algorithm is treating the first value in a special way, it is that the algorithm assumes that, wherever you are in the list, the previous value (memo) is the combined result of all previous values. So when you call `reduce` without an initial value, you're actually starting the iteration at the 2nd position in the list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T07:58:00.103",
"Id": "46108",
"Score": "0",
"body": "\"you're actually starting the iteration at the 2nd position in the list\". Which *is* \"treating the first element in the array in a special way\": it's being treated differently from all the other elements in the array. I've had a look @ native JS & underscore & Ruby too, and agree that that is how they behave. It's still daft, and I'm still not having a bar of it ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T06:18:33.920",
"Id": "46194",
"Score": "0",
"body": "Ok, quote from Wikipedia: \"The use of an initial value is necessary when the combining function f is asymmetrical in its types, i.e. when the type of its result is different from the type of list's elements. Then an initial value must be used, with the same type as that of f 's result, for a linear chain of applications to be possible. \" http://en.m.wikipedia.org/wiki/Fold_(higher-order_function)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T06:28:00.633",
"Id": "46195",
"Score": "0",
"body": "I think I explained it slightly incorrectly before. The iterator is a binary operator that is given two values: the result of the previous fold (left operand) and the next value in the list (right operand). So it's not starting at the second value, it is starting between the first and second values."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T06:09:23.090",
"Id": "29049",
"ParentId": "28968",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "29049",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T12:52:35.913",
"Id": "28968",
"Score": "4",
"Tags": [
"coldfusion",
"cfml"
],
"Title": "CFML implementation of Array.reduce()"
}
|
28968
|
<p>I echo a rank of a student whose <code>regd</code> is equal to <code>$regd</code>. In fact, this is working code. However, I was advised by a friend that the MySQL statements <code>Distinct</code> and <code>Group By</code> should not be used together. But as a newbie, I could not figure out how I could implement it without using <code>Distinct</code> because it does not return rows without <code>Distinct</code>.</p>
<p>Can anyone suggest how I can improve this code?</p>
<pre><code><?php
mysql_select_db($database_dbconnect, $dbconnect);
$query_myrank = "SELECT Distinct regd, Name_of_exam,
Name_of_Student, TOTALSCORE, Rank
FROM (SELECT *, IF(@marks = (@marks := TOTALSCORE),
@auto, @auto := @auto + 1) AS Rank
FROM (SELECT Name_of_Student, regd,
Name_of_exam, SUM(Mark_score) AS TOTALSCORE
FROM cixexam, (SELECT @auto := 0,
@marks := 0) AS init
GROUP BY regd
ORDER BY TOTALSCORE DESC) t) AS result
HAVING (Name_of_exam='First Terminal Exam' OR
Name_of_exam='First Term Test')";
$myrank = mysql_query($query_myrank, $dbconnect) or die(mysql_error());
$i = 0;
$j = 0;
$data = array();
while($row_myrank = mysql_fetch_assoc($myrank))
{
$data[$i] = $row_myrank;
if(isset($data[$i - 1])
&& $data[$i - 1]['TOTALSCORE'] == $data[$i]['TOTALSCORE'])
{
$data[$i]['Rank'] = $j;
}else{
$data[$i]['Rank'] = ++$j;
}
$i++;
}
foreach($data as $key => $value)
{
if($value['regd'] == $regd)
{
echo $value['Rank'];
}
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-24T15:26:00.140",
"Id": "47932",
"Score": "0",
"body": "Why are you using `HAVING` instead of `WHERE`? Also, I think you probably intend to filter by `Name_of_exam` within the innermost query, rather than at the outermost query."
}
] |
[
{
"body": "<p>Since you use it in a subquery, I don't see the problem. If you used both in the same query, that would be redundant. But the subquery needs to use it to obtain the required data.</p>\n\n<p>Did the person give a reason as to why he/she thinks this, or was it simply a general statement?</p>\n\n<p>The only thing I can think of is that DISTINCT is rather slow compared to GROUP BY: <a href=\"https://stackoverflow.com/questions/1887953/\">stackoverflow.com/questions/1887953/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T14:24:44.773",
"Id": "45611",
"Score": "0",
"body": "Can you suggest an alternative solution?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:13:42.183",
"Id": "45619",
"Score": "0",
"body": "Sadly not, for I was very surprised when you said you're a \"newbie\", because that's some good code you got there. Intermediate to advanced, I would say. Certainly not \"newbie\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:36:12.373",
"Id": "45623",
"Score": "0",
"body": "Thanks for your encouragement. I have been struggling with this code for a week."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T22:33:38.187",
"Id": "45672",
"Score": "0",
"body": "I find it very confusing that `Name_of_Student`, `regd`, `Name_of_exam` are selected, but the `GROUP BY` clause only contains `regd`. I know that MySQL supports this, but I've never been able to wrap my head around what is going on. What happens if `Name_of_Student` or `Name_of_exam` aren't functionally dependent on `regd`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T22:40:04.317",
"Id": "45673",
"Score": "0",
"body": "Now I found out: http://sqlfiddle.com/#!2/bb1252/1 - the non-FD fields seems to be picked at random. For this reason alone, I suggest including the fields in the `GROUP BY` clause (if they are FD) or specifying an aggregate in stead (`MAX` seems to work on chars)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T04:37:57.527",
"Id": "45710",
"Score": "0",
"body": "I have got an answer to my question in stackoverflow and here is the link: http://stackoverflow.com/questions/17859234/how-to-improve-this-php-mysql-code/17864479?noredirect=1#17864479. Will there be another great solution which is faster and more dependable?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T13:48:42.663",
"Id": "28972",
"ParentId": "28971",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T13:42:20.670",
"Id": "28971",
"Score": "1",
"Tags": [
"php",
"mysql"
],
"Title": "Echoing student ranks"
}
|
28971
|
<p>After posting <a href="https://codereview.stackexchange.com/q/12197/3163">this question</a> I made some updates and changes to my code. My new demo for the game is located <a href="http://jsfiddle.net/maniator/XP9Qv/" rel="nofollow noreferrer">here</a>. Right now it is only one player.</p>
<p>Is there anything I could improve on in the code?</p>
<pre><code>Array.prototype.randomize = function () {
//fisher yates from https://codereview.stackexchange.com/a/12200/3163
var i = this.length;
if (i === 0) return false;
while (--i) {
var j = Math.floor(Math.random() * (i + 1));
var tempi = this[i];
var tempj = this[j];
this[i] = tempj;
this[j] = tempi;
}
};
Array.prototype.toObject = function () {
var o = {};
for (var i = 0; i < this.length; i++) {
o[this[i]] = '';
}
return o;
};
function bindEvent(el, eventName, eventHandler) {
if (el.addEventListener) {
el.addEventListener(eventName, eventHandler, false);
} else if (el.attachEvent) {
el.attachEvent('on' + eventName, eventHandler);
}
}
var Wheel = (function () {
var wheel = document.getElementById('wheel'),
wheelValues = [5000, 600, 500, 300, 500, 800, 550, 400, 300, 900, 500, 300, 900, 0, 600, 400, 300, -2, 800, 350, 450, 700, 300, 600],
spinTimeout = false,
spinModifier = function () {
return Math.random() * 10 + 20;
},
modifier = spinModifier(),
slowdownSpeed = 0.5,
prefix = (function () {
if (document.body.style.MozTransform !== undefined) {
return "MozTransform";
} else if (document.body.style.WebkitTransform !== undefined) {
return "WebkitTransform";
} else if (document.body.style.OTransform !== undefined) {
return "OTransform";
} else {
return "";
}
}()),
degreeToRadian = function (deg) {
return deg / (Math.PI * 180);
};
function Wheel() {}
Wheel.prototype.rotate = function (degrees) {
var val = "rotate(-" + degrees + "deg)";
if (wheel.style[prefix] !== undefined) wheel.style[prefix] = val;
var rad = degreeToRadian(degrees % 360),
filter = "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=" + rad + ", M12=-" + rad + ", M21=" + rad + ", M22=" + rad + ")";
if (wheel.style.filter !== undefined) wheel.style.filter = filter;
wheel.setAttribute("data-rotation", degrees);
};
Wheel.prototype.spin = function (callback, amount) {
var _this = this;
clearTimeout(spinTimeout);
modifier -= slowdownSpeed;
if (amount === undefined) {
amount = parseInt(wheel.getAttribute('data-rotation'), 10);
}
this.rotate(amount);
if (modifier > 0) {
spinTimeout = setTimeout(function () {
_this.spin(callback, amount + modifier);
}, 1000 / 5);
} else {
var dataRotation = parseInt(wheel.getAttribute('data-rotation'), 10);
modifier = spinModifier();
var divider = 360 / wheelValues.length;
var offset = divider / 2; //half division
var wheelValue = wheelValues[Math.floor(Math.ceil((dataRotation + offset) % 360) / divider)];
switch (wheelValue) {
case 0:
return callback(0);
case -1:
return callback("Free Spin");
case -2:
return callback("Lose a turn");
default:
return callback(wheelValue);
}
}
};
return Wheel;
})();
var WheelGame = (function () {
var wheel = new Wheel(),
vowels = ['A', 'E', 'I', 'O', 'U'],
spinWheel = document.getElementById('spin'),
buyVowel = document.getElementById('vowel'),
displayArea = document.getElementById('display'),
newButton = document.getElementById('newpuzzle'),
money = document.getElementById('money'),
solve = document.getElementById('solve');
function WheelGame(puzzles) {
var _this = this;
this.puzzles = puzzles;
this.puzzles.randomize();
this.currentMoney = 0;
this.puzzleSolved = false;
bindEvent(buyVowel, "click", function () {
if (_this.currentMoney > 200) {
if (_this.createGuessPrompt("PLEASE ENTER A VOWEL", true) !== false) {
_this.currentMoney -= 200;
_this.updateMoney();
}
} else {
alert("You need more than $200 to buy a vowel");
}
});
bindEvent(newButton, "click", function () {
_this.newRound();
});
var spinTheWheel = function () {
wheel.spin(function (valueSpun) {
if (isNaN(valueSpun)) {
alert(valueSpun);
} else {
//is a valid number
if (valueSpun === 0) {
alert('Bankrupt!');
_this.currentMoney = 0;
} else {
//spun greater than 0
var amountFound = _this.createGuessPrompt(valueSpun);
_this.currentMoney += (valueSpun * amountFound);
}
_this.updateMoney();
}
});
};
bindEvent(spinWheel, "click", spinTheWheel);
bindEvent(wheel, "click", spinTheWheel);
function arrays_equal(a, b) {
return !(a < b || b < a);
}
bindEvent(solve, "click", function () {
if (!_this.puzzleSolved) {
var solve = prompt("Solve the puzzle?", "");
if (solve) {
guess = solve.toUpperCase().split("");
if (arrays_equal(guess, _this.currentPuzzleArray)) {
for (var i = 0; i < guess.length; ++i) {
_this.guessLetter(guess[i], false, true);
}
}
if (!_this.puzzleSolved) {
alert('PUZZLE NOT SOLVED');
}
}
}
});
this.startRound(0); //start the 1st round
}
WheelGame.prototype.updateMoney = function () {
money.innerHTML = this.currentMoney;
};
WheelGame.prototype.guessLetter = function (guess, isVowel, solvingPuzzle) {
var timesFound = 0;
solvingPuzzle = solvingPuzzle === undefined ? false : true;
//find it:
if (guess.length && !this.puzzleSolved) {
if (!solvingPuzzle && !isVowel && (guess in vowels.toObject())) {
alert("Cannot guess a vowel right now!");
return false;
}
if (!solvingPuzzle && isVowel && !(guess in vowels.toObject())) {
alert("Cannot guess a consanant right now!");
return false;
}
for (var i = 0; i < this.currentPuzzleArray.length; ++i) {
if (guess == this.currentPuzzleArray[i]) {
var span = document.getElementById("letter" + i);
if (span.innerHTML != guess) {
//found it
++timesFound;
}
span.innerHTML = guess;
if (guess in this.lettersInPuzzle.toObject() && !(guess in this.guessedArray.toObject())) {
this.guessedArray.push(guess);
}
}
}
if (this.guessedArray.length == this.lettersInPuzzle.length) {
alert("PUZZLE SOLVED!");
this.puzzleSolved = true;
}
return timesFound;
}
return false;
};
var guessTimes = 0;
WheelGame.prototype.createGuessPrompt = function (valueSpun, isVowel) {
isVowel = isVowel === undefined ? false : true;
if (!this.puzzleSolved) {
var letter;
if (isVowel) {
letter = prompt("PLEASE ENTER A VOWEL", "");
} else {
letter = prompt("YOU SPUN A " + valueSpun + " PLEASE ENTER A CONSONANT", "");
}
if (letter) {
var guess = letter.toUpperCase().charAt(0);
var timesFound = this.guessLetter(guess, isVowel);
if (timesFound === false) {
++guessTimes;
if (guessTimes < 5) {
return this.createGuessPrompt(valueSpun, isVowel);
}
}
guessTimes = 0;
return timesFound;
} else {
++guessTimes;
if (guessTimes < 5) {
return this.createGuessPrompt(valueSpun, isVowel);
}
else {
// reset guessTimes
guessTimes = 0;
}
}
}
return false;
};
WheelGame.prototype.newRound = function () {
var round = ++this.round;
if (round < this.puzzles.length) {
while (displayArea.hasChildNodes()) { //remove old puzzle
displayArea.removeChild(displayArea.firstChild);
}
this.startRound(round);
} else {
alert("No more puzzles!");
}
};
WheelGame.prototype.startRound = function (round) {
this.round = round;
this.lettersInPuzzle = [];
this.guessedArray = [];
this.puzzleSolved = false;
this.currentPuzzle = this.puzzles[this.round].toUpperCase();
this.currentPuzzleArray = this.currentPuzzle.split("");
var currentPuzzleArray = this.currentPuzzleArray;
var lettersInPuzzle = this.lettersInPuzzle;
var word = document.createElement('div');
displayArea.appendChild(word);
word.className = "word";
for (var i = 0; i < currentPuzzleArray.length; ++i) {
var span = document.createElement('div');
span.className = "wordLetter ";
if (currentPuzzleArray[i] != " ") {
span.className += "letter";
if (!(currentPuzzleArray[i] in lettersInPuzzle.toObject())) {
lettersInPuzzle.push(currentPuzzleArray[i]);
}
word.appendChild(span);
} else {
span.className += "space";
word = document.createElement('div');
displayArea.appendChild(word);
word.className = "word";
word.appendChild(span);
word = document.createElement('div');
displayArea.appendChild(word);
word.className = "word";
}
span.id = "letter" + i;
}
var clear = document.createElement('div');
displayArea.appendChild(clear);
clear.className = "clear";
};
return WheelGame;
})();
var Game = new WheelGame([
"doctor who", "the dark knight rises", "wheel of fortune",
"facebook", "twitter", "google plus", "sea world", "pastrami on rye",
"i am sparta", "whose line is it anyway", "google chrome"
]);
</code></pre>
|
[] |
[
{
"body": "<p>This is a lot of code to review so it might be a good idea to break it down into separate parts. This way it'll be easier to give a more detailed and tailored review. But anyways here are a few things you can do that should help your performance:</p>\n\n<p><strong>Minimize Paints and Reflows</strong> - Might seem like an obvious one but it's one of the most important. Especially in your <code>rotate</code> function which from what I can tell does most of the animation grunt work. An easy way to optimize this is if you need to read data from the page, read it all at once, then repaint/edit layout.</p>\n\n<p><strong>Save yourself some code</strong> - There are a few spot where you can bring down the size by joining operations. Something like this:</p>\n\n<pre><code>var word = document.createElement('div');\n displayArea.appendChild(word);\n word.className = \"word\";\n</code></pre>\n\n<p>Could be written in one line:</p>\n\n<pre><code>displayArea.appendChild(document.createElement(\"div\")).className = \"word\";\n</code></pre>\n\n<p>Since <code>.appendChild()</code> returns the appended node, you can chain. I would suggest you go through and try to spot these yourself.</p>\n\n<p><strong>Cache Array Lengths</strong> - The loop is undoubtedly one of the most important parts related to JavaScript performance. Try to optimize the logic inside a loop so that each iteration is done efficiently.</p>\n\n<p>One way to do this is to store the size of the array that will be covered, so it doesn't need to be recalculated every time the loop is iterated.</p>\n\n<p>For example:</p>\n\n<pre><code>for (var i = 0; i < currentPuzzleArray.length; ++i) {\n</code></pre>\n\n<p>Could be done like so:</p>\n\n<pre><code>for (var i = 0, len = currentPuzzleArray.length; i < len ; ++i) {\n</code></pre>\n\n<p><a href=\"http://jsperf.com/browser-diet-cache-array-length/10\" rel=\"nofollow\">This jsPerf</a> can demonstrate what I mean by this. In most of the modern browsers this is less of a problem, but is evident in the older ones.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:34:03.093",
"Id": "45622",
"Score": "1",
"body": "The array length issue is minimal. I am not the best fan of \"chaining\" unless it is really needed -- but it looks cool :-P\n\nAnything else?\n\n(Also I have no idea how to break my code into multiple questions)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:48:48.550",
"Id": "45625",
"Score": "0",
"body": "@Neal you can open different questions and link back to this one. Each question with a smaller snippet that you want to focus on and get reviewed. Another thing is you might want to look into an alternative solution to displaying information and getting input rather than using alerts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:49:44.740",
"Id": "45626",
"Score": "0",
"body": "@Neal it's understandable that some snippets can't be separated from others that's why you should link back here for \"the full code\". You can separate the parts you think need work on and start with those."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:50:27.477",
"Id": "45627",
"Score": "0",
"body": "Multiple questions that all go to the same point are still all the same question -- there is no need for multiple questions asking the same thing -- I am looking for a review on the whole of the code. Aside -- The alerts are annoying, yes, I am trying to replace them, I am just looking for a non-jQuery esque solution (trying to be library lite)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:53:21.957",
"Id": "45630",
"Score": "0",
"body": "In response to your second comment -- I am looking for a review on the full code and not just on bits and pieces of it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:17:51.057",
"Id": "28978",
"ParentId": "28973",
"Score": "0"
}
},
{
"body": "<p>Especially as you develop the programme you will probably want to separate out the game logic from the parts that update different parts of the display or take user input. For instance you can have a separate object controlling the display of the letters:</p>\n\n<pre><code>var WordDisplay = (function () {\n var display = document.getElementById('display'),\n characters;\n\n function WordDisplay(puzzle) {\n while (display.hasChildNodes()) { //remove old puzzle\n display.removeChild(display.firstChild);\n }\n var word = div(display, 'word');\n characters = [];\n for (var i = 0; i < puzzle.length; ++i) {\n if (puzzle[i] == ' ') {\n characters.push(div(display, 'space'));\n word = div(display, 'word');\n } else {\n characters.push(div(word, 'letter'));\n }\n }\n div(display, 'clear');\n }\n WordDisplay.prototype.showLetter = function (i, letter) {\n characters[i].innerHTML = letter;\n };\n return WordDisplay;\n})();\n\nfunction div(parent, className) {\n var r = document.createElement('div');\n r.className = className;\n parent.appendChild(r);\n return r;\n}\n</code></pre>\n\n<p>You then use <code>wordDisplay = new WordDisplay(puzzleArray)</code> to initiate the board and <code>wordDisplay.showLetter(3, 'x')</code> to place the letter x at position 3. This will help to shorten the main <code>WheelGame</code> code and make the whole thing easier to read and debug. (<a href=\"http://jsfiddle.net/9ZXX7/4/\" rel=\"nofollow\">http://jsfiddle.net/9ZXX7/4/</a>)</p>\n\n<p>Note some other changes made there:</p>\n\n<ul>\n<li><p>simplifying the lines that display the puzzle and removing the reliance on element <code>id</code>s</p></li>\n<li><p>using a helper function <code>div</code> to make building html elements less repetitive</p></li>\n<li><p>slightly simplified the method <code>WheelGame.prototype.guessLetter</code></p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T02:13:29.363",
"Id": "30234",
"ParentId": "28973",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T13:59:57.663",
"Id": "28973",
"Score": "1",
"Tags": [
"javascript",
"game"
],
"Title": "Wheel of Fortune game - follow-up"
}
|
28973
|
<p>I have this code that works fine, but I would like to create some unit test for this class. Most of the code is in <code>private</code> or <code>void</code> type methods. Please help me refactor my class to make it more testable.</p>
<pre><code>namespace Insperity.HCRBlackBox.HCRServices.Biz
{
public class OrganizationChartBiz : IOrganizationChartBiz
{
private readonly OrganizationChartRepository _repository;
public OrganizationChartBiz()
{
_repository = new OrganizationChartRepository();
}
public AcknowledgeOrganizationChartType NotifyOrganizationChart(NotifyOrganizationChartType notifyOrganizationChartType)
{
foreach (var organizationChart in notifyOrganizationChartType.DataArea.OrganizationChart)
{
foreach (var unit in organizationChart.OrganizationUnit)
{
var existing = GetExistingOrganization(unit.OrganizationUnitID.Value);
if (existing.Equals(null))
{
TransformToOrganizationAndSave(unit);
}
else
{
TransformToOrganizationAndUpdate(unit, existing);
}
}
}
return new AcknowledgeOrganizationChartType();
}
public AcknowledgeOrganizationChartType SyncOrganizationChart(SyncOrganizationChartType syncOrganizationChartType)
{
foreach (var organizationChart in syncOrganizationChartType.DataArea.OrganizationChart)
{
foreach (var unit in organizationChart.OrganizationUnit)
{
var existing = GetExistingOrganization(unit.OrganizationUnitID.Value);
if (existing!=null)
{
TransformToOrganizationAndUpdate(unit, existing);
}
else
{
TransformToOrganizationAndSave(unit);
}
}
}
return new AcknowledgeOrganizationChartType();
}
private void TransformToOrganizationAndUpdate(OrgChartOrganizationUnitType org, Organization existing)
{
List<RelatedOrganization> relatedOrganizations = new List<RelatedOrganization>();
var now = DateTime.UtcNow;
var organization = existing;
if (org.ParentOrganizationUnit.OrganizationUnitID.Value!=null)
organization.ParentOrganizationId = org.ParentOrganizationUnit.OrganizationUnitID.Value;
organization.OrganizationName = org.OrganizationUnitName.Value;
organization.LastModified = now;
if (org.RelatedOrganizationUnit != null)
{
foreach (var relatedOrganizationUnitType in org.RelatedOrganizationUnit)
{
var controlGroup = new RelatedOrganization
{
ControlGroupId = relatedOrganizationUnitType.OrganizationUnitID.Value,
StartDate =
Convert.ToDateTime(relatedOrganizationUnitType.OrganizationUnitID.validFrom),
Organization = organization,
EndDate =
relatedOrganizationUnitType.OrganizationUnitID.validTo != null
? Convert.ToDateTime(relatedOrganizationUnitType.OrganizationUnitID.validTo)
: new DateTime?(),
LastModified = now
};
relatedOrganizations.Add(controlGroup);
}
}
if (org.UserArea != null)
{
var userArea = org.UserArea as OrganizationChartUserArea;
if (userArea != null)
{
organization.EducationIndicator = userArea.EducationIndicator.Equals(false) ? "F" : "T";
}
}
_repository.UpdateOrganization(organization,relatedOrganizations);
}
private void TransformToOrganizationAndSave(OrgChartOrganizationUnitType org)
{
var now = DateTime.UtcNow;
var organization = new Organization
{
OrganizationId = org.OrganizationUnitID.Value,
ParentOrganizationId = org.ParentOrganizationUnit.OrganizationUnitID.Value,
OrganizationName = org.OrganizationUnitName.Value,
LastModified = now
};
if (org.RelatedOrganizationUnit != null)
{
foreach (var relatedOrganizationUnitType in org.RelatedOrganizationUnit)
{
var controlGroup = new RelatedOrganization
{
ControlGroupId = relatedOrganizationUnitType.OrganizationUnitID.Value,
StartDate =
Convert.ToDateTime(relatedOrganizationUnitType.OrganizationUnitID.validFrom),
OrganizationId = relatedOrganizationUnitType.OrganizationUnitID.Value,
EndDate =
relatedOrganizationUnitType.OrganizationUnitID.validTo != null
? Convert.ToDateTime(relatedOrganizationUnitType.OrganizationUnitID.validTo)
: new DateTime?(),
LastModified = now
};
organization.RelatedOrganizations.Add(controlGroup);
}
}
if (!org.UserArea.Equals(null))
{
var userArea = org.UserArea as OrganizationChartUserArea;
if (userArea != null)
organization.EducationIndicator = userArea.EducationIndicator.Equals(false) ? "F" : "T";
}
_repository.SaveOrganization(organization);
}
private Organization GetExistingOrganization(string organizationUnitId)
{
return _repository.GetExistingOrganization(organizationUnitId);
}
public void Dispose()
{
_repository.Dispose();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:30:25.410",
"Id": "45620",
"Score": "2",
"body": "**1.** I'd change the wording in your question. \"Please help me refactor\" gives the impression that you want other people to do your work for you. **2.** I recommend reading the book *Working Effectively with Legacy Code* by Michael Feathers for tips on how to introduce tests to a codebase."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:50:38.443",
"Id": "45628",
"Score": "0",
"body": "@Lstor I'm not asking anyone to write my unit test just to help make the code more testable. I hope I didn't give you that impression."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:52:17.380",
"Id": "45629",
"Score": "1",
"body": "I know, that's why I suggest the rewording :) Otherwise I would have just downvoted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:56:39.653",
"Id": "45631",
"Score": "0",
"body": "@Lstor Thanks, I took your advice. Hopefully the new title is more accurate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T11:10:04.353",
"Id": "45733",
"Score": "0",
"body": "Names are confusing, collections not having plural etc... Does a `NotifyOrganizationChartType` message *target* a domain entity. You seem to be missing an aggregate. What does the collection of `organizationChart`s that is the `notifyOrganizationChartType.DataArea.OrganizationChart` signify in the domain, to the user for example?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-29T21:27:29.503",
"Id": "90085",
"Score": "0",
"body": "@Malachi Unit tests are always the **first** step in [refactoring](http://en.wikipedia.org/wiki/Code_refactoring): _\"Before applying a refactoring to a section of code, a solid set of automatic unit tests is needed.\"_ That's how you ensure that you didn't break anything during the refactoring."
}
] |
[
{
"body": "<p>I'm not too familiar with C#, so just a few generic notes:</p>\n\n<ol>\n<li><p>If you can, use a dependency injection (DI) framework and inject the <code>OrganizationChartRepository</code> instead of creating it inside the constructor. It would make the classes less coupled and therefore easier to test. If you can't use DI, you can create another constructor:</p>\n\n<pre><code>@VisibleForTesting\npublic OrganizationChartBiz(OrganizationChartRepository repository) {\n _repository = repository;\n}\n</code></pre>\n\n<p>In the tests you can create the <code>OrganizationChartBiz</code> instance with a mocked repository and verify how the <code>OrganizationChartBiz</code> instance uses the mock. (<a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/annotations/VisibleForTesting.html\"><code>@VisibleForTesting</code></a> is from Guava. I guess C# has something similar or you can create your own markup for marking code which is exists only for the sake of testing.)</p></li>\n<li><p>Instead of <code>DateTime</code> use a <code>TimeSource</code> or <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Ticker.html\"><code>Ticker</code></a> interface to wrap the <code>DateTime</code>. See: <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=234\">Use a fake system clock</a>. You can pass this ticker to the constructor and pass a mocked ticker in the tests to make the behaviour repeatable.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T18:12:18.007",
"Id": "28989",
"ParentId": "28979",
"Score": "5"
}
},
{
"body": "<p>In addition to @palacsint's advice, namely you should make the implicit dependencies of system under test explicit, I'll add a few more. </p>\n\n<ul>\n<li><p>In my experience easiest way to make a business method that uses system time testable is to <strong>just pass the current time as a parameter</strong>. \"Time\" is not part of your domain after all. \nThis refactoring is a form of <a href=\"http://www.refactoring.com/catalog/replaceStaticVariableWithParameter.html\" rel=\"nofollow\">Replace Static Variable with Parameter</a> This will also save you the trouble of setting up a mock time provider service for test scenarios. </p></li>\n<li><p>The following means <code>org.RelatedOrganizationUnit</code> is some kind of collection</p>\n\n<pre><code>if (org.RelatedOrganizationUnit != null)\n{\n foreach (... in org.RelatedOrganizationUnit)\n</code></pre>\n\n<p>Make it default to an empty list, and you would not need to check for nulls. Less <code>if</code>s, less test cases needed.</p></li>\n<li><p>Factor out the repeating chunks about related organizations and <code>EducationIndicator</code> out smaller units are easier to test. </p></li>\n<li><p>Duplication is bad in itself. The following two snippets look like they were copy/pasted; then an error was fixed, for just one copy.</p>\n\n<pre><code>// this should throw NullReferenceException if org.UserArea is null\nif (!org.UserArea.Equals(null)) \n\nif (org.UserArea != null)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T13:25:24.603",
"Id": "45740",
"Score": "0",
"body": "Thanks you make great points. The only one I can't do is default RelatedOrganizationUnit to empty. I do not own that class and am not the source of the data, this is a wcf service. Thanks for the advice"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T06:40:20.640",
"Id": "29011",
"ParentId": "28979",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29011",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T15:26:04.450",
"Id": "28979",
"Score": "4",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Does my code need refactoring before adding unit tests?"
}
|
28979
|
<p>I know using a UnitOfWork/Repository pattern in a normal class should work fine without any issues but how about using them in a static class/methods (I mean using a private static IUnitOfWork instance, refer CustomerService class). Will this work fine in multiple user scenario without overlapping with other request (I am using asp.net)?</p>
<p>Can anyone please tell me whether the below code looks fine or I will get any issues (overlapping db issues) going forward because of the static IUnitOfWork instance? Also, please advice me if there is any other better way to do this.</p>
<pre><code>public interface IDataRepository<T> where T : class
{
IQueryable<T> Find(Expression<Func<T, bool>> predicate);
IQueryable<T> GetAll();
T GetById(Guid id);
T GetById(int id);
void Add(T entity);
void Update(T entity);
void Remove(T entity);
}
public class DataRepository<T> : IDataRepository<T> where T : class
{
}
public interface IUnitOfWork
{
IDataRepository<Customer> CustomerRepository { get; }
IDataRepository<Product> ProductRepository { get; }
void SaveChanges();
}
public class UnitOfWork : IUnitOfWork
{
private readonly SomeContext _context;
private IDataRepository<Customer> _customerRepository { get; set; }
private IDataRepository<Product> _productRepository { get; set; }
public UnitOfWork()
{
_context = new SomeContext();
}
public IDataRepository<Customer> CustomerRepository
{
get
{
if (_customerRepository == null)
{
_customerRepository = new DataRepository<Customer>(_context);
}
return _customerRepository;
}
}
public IDataRepository<Product> CustomerRepository
{
get
{
if (_productRepository == null)
{
_productRepository = new DataRepository<Product>(_context);
}
return _productRepository;
}
}
}
public class CustomerService
{
private static IUnitOfWork _unitOfWork = new UnitOfWork();
public static List<Customer> GetCustomers()
{
_unitOfWork.CustomerRepository.Find(t => t.ID == 123).ToList();
}
public static bool IsCustomerExist()
{
return (_unitOfWork.CustomerRepository.Find(t => t.ID == 123).Count() > 0);
}
public static bool UpdateCustomer(Customer customer)
{
.....
_unitOfWork.SaveChanges();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>It entirely depends on your implementation of the unit of works members. If the IDataRepository is using something like NHibernate and keeping open persistent connections (which, being part of a unit of work, I presume it might) you will absolutely run into weird database connectivity issues when using a private static member.</p>\n\n<p>The reason for this, is that the static property is shared between all instances of the CustomerService, in your example, so you'll have one of those, and it'll be constructed with \"whatever it gets at the time\" - for example, the first database connection or session your application opens. If you have some sort of session per request handling that subsequently disposes of that session, the static class will still hold a reference to it, and you'll have a bad time.</p>\n\n<p>To deal with this problem in some things that \"must be\" static, there's a cheap little trick you can use - add a static func to some form of resolver or container that you wire up at bootstrapping time:</p>\n\n<pre><code>public class ContainerRegistrationCode\n{\n public void RegisterTypesInContainer()\n {\n Kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();\n CustomerService.GetCurrentUnitOfWork = () => Kernel.GetService<IUnitOfWork>();\n }\n}\n\npublic class CustomerService\n{\n public static Func<IUnitOfWork> GetCurrentUnitOfWork { get; set; }\n\n public static List<Customer> GetCustomers()\n {\n var currentUnitOfWork = GetCurrentUnitOfWork ();\n currentUnitOfWork.CustomerRepository.Find(t => t.ID == 123).ToList();\n }\n}\n</code></pre>\n\n<p>This way, you delegate out to a container or something that can manage the lifecycle of the unit of work, and every time you use it in a static context, you call the func which gets whatever the current one is.</p>\n\n<p>It's a bit of a hack, don't use statics, use a good container instead that supports scoping (like Ninject) and you just shouldn't have this problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T08:20:40.843",
"Id": "29983",
"ParentId": "28983",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:06:40.110",
"Id": "28983",
"Score": "0",
"Tags": [
"c#",
"design-patterns",
"static"
],
"Title": "Using UnitOfWork/Repository pattern in static class/methods"
}
|
28983
|
<p>In JavaFX, the lifecycle of an <code>Application</code> is quite different than Swing. Your constructor must take no arguments so that the <code>Application</code> class can create an instance of your object. Once the instance has been created, it calls <code>start(Stage)</code>, which gives you a <code>Stage</code> for you to put your user interface on. This may be fine for some people, but I want to access instance variables of my <code>Application</code> class (which happens to be called <code>LJGM</code>), and the only way I thought I could do this was to have a single, static instance of my <code>LJGM</code> object, and have a static <code>instance()</code> method which returns the instance. Whenever the constructor is called, <code>instance</code> is set to <code>this</code>. There has to be a better way to do this.</p>
<pre><code>public class LJGM extends Application {
/** The instance of {@link LJGM}. */
private static LJGM instance;
/**
* Gets the only instance of LJGM.
*
* @return The instance of LJGM.
*/
public static LJGM instance() {
return instance;
}
// (other variables here)
/**
* Instantiates a new LJGM object.
*/
public LJGM() {
LJGM.instance = this;
// (initialize other variables)
}
/*
* (non-Javadoc)
*
* @see javafx.application.Application#start(javafx.stage.Stage)
*/
@Override
public void start(Stage primaryStage) throws Exception {
// (add GUI to the primaryStage here)
}
/**
* Main method.
*
* @param args
* The arguments to pass to the application.
*/
public static void main(String[] args) {
launch(args);
}
}
</code></pre>
<p>Here is the <a href="http://docs.oracle.com/javafx/2/api/javafx/application/Application.html" rel="nofollow">Application Javadoc </a> in case you need it.</p>
|
[] |
[
{
"body": "<p>What you have implemented is the Singleton design pattern.</p>\n\n<p>Normally I would suggest that you make <code>public LJGM()</code> private, and <code>public static LJGM instance()</code> check if <code>instance</code> is null, and if so call the constructor to set it, but it looks like you can't do that since your constructor needs to be able to be called from an inheriting class.</p>\n\n<p>What I would recommend you do however is make your constructor protected, and probably rename your <code>public static LJGM instance()</code> method to something like <code>getInstance</code> just to avoid naming conflicts with the private variable. And it may be prudent to assert that instance is null immediately in your constructor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T21:02:01.463",
"Id": "45780",
"Score": "0",
"body": "Actually, my constructor *has to* be `public`. I may have worded it strangely in the question, but `LJGM`'s *superclass* (`Application`) is calling its constructor, not a subclass."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T21:11:14.393",
"Id": "45782",
"Score": "0",
"body": "Some code from `Application`: `Constructor<? extends Application> c = appClass.getConstructor(); app = c.newInstance();`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T13:27:03.053",
"Id": "29023",
"ParentId": "28984",
"Score": "0"
}
},
{
"body": "<p>One alternative is to use the <a href=\"http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-stinkin-singleton-the-bo/\" rel=\"nofollow\">Borg Pattern</a>. Allow creating multiple instances, all of which, simply share the same state. Most online references will be in Python (where it is real easy to code), but the idea can be transplanted to Java too.</p>\n\n<p>The advantage over the Singleton pattern is that it hides the fact that there is shared state from clients of the class, especially those that are interested in creating instance.</p>\n\n<p>Clients (in casu the JavaFX framework) can simply use the constructor. Your own code can also easily get the Application by creating a separate instance.</p>\n\n<p>so some sample code :</p>\n\n<pre><code>public class LJGM extends Application {\n\n private static SharedState sharedState = new SharedState();\n\n private static class SharedState {\n\n private Object variable;\n\n private Object getVariable() {\n return variable;\n }\n }\n\n public LJGM() {\n }\n\n public Object getVariable() {\n return sharedState.getVariable();\n }\n\n @Override\n public void start(Stage primaryStage) throws Exception {\n // (add GUI to the primaryStage here)\n }\n\n public static void main(String[] args) {\n launch(args);\n }\n}\n</code></pre>\n\n<p>All that being said, I don't see any reason why you could not simply use dependency injection to avoid having global state here. So rather than having low level components query the Application object, let the Application pass them the parameters they will need, by passing itself (preferably implementing an interface) or by passing in the variables themselves.</p>\n\n<pre><code>public class LJGM extends Application implements ApplicationContext {\n\n private Object variable;\n\n public LJGM() {\n }\n\n public Object getVariable() {\n return variable;\n }\n\n @Override\n public void start(Stage primaryStage) throws Exception {\n // (add GUI to the primaryStage here)\n new LowLevelComponent(this);\n new OtherLowLevelComponent(variable);\n }\n\n public static void main(String[] args) {\n launch(args);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T20:58:51.653",
"Id": "45779",
"Score": "0",
"body": "The second idea could work, except for the fact that one of the objects is used for logging, so it doesn't seem like a good idea to have to pass said object into every other object's constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T06:25:10.870",
"Id": "45797",
"Score": "0",
"body": "Ok, but Logging frameworks usually already come with a mechanism to get hold of a Logger without being passed one. So normally you shouldn't need to go through the Application instance for that to begin with."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T14:29:27.720",
"Id": "45809",
"Score": "0",
"body": "In that case, this answer can really help me. Thanks a lot :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T17:06:09.347",
"Id": "29033",
"ParentId": "28984",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:33:24.397",
"Id": "28984",
"Score": "1",
"Tags": [
"java",
"constructor",
"javafx"
],
"Title": "JavaFX design writes to static field from constructor"
}
|
28984
|
<p>I'm looking for a way to make my code more simple. This code takes a list of vectors and returns all subset of that list that sum up to another vector.</p>
<p>For example:</p>
<blockquote>
<p><code>{'a','b','c'}</code> is the subset consisting of: <code>a (1100000)</code>, <code>b (0110000)</code>, and <code>c (0011000)</code>.</p>
</blockquote>
<pre><code>def AddVectors(A, B):
if not A:
return B
if not B:
return A
return [A[i] + B[i] for i in range(len(A))]
def SumVectorList(lst, SuperSet):
result = []
for l in lst:
if not result:
result = SuperSet[l]
else:
for j in range(len(l)):
result = AddVectors(result, SuperSet[l[j]])
return result
def GetPowerSet(lst):
result = [[]]
for x in lst:
result.extend([subset + [x] for subset in result])
return result
S = {'a': [one, one, 0, 0, 0, 0, 0], 'b': [0, one, one, 0, 0, 0, 0],
'c': [0, 0, one, one, 0, 0, 0], 'd': [0, 0, 0, one, one, 0, 0],
'e': [0, 0, 0, 0, one, one, 0], 'f': [0, 0, 0, 0, 0, one, one]}
P = GetPowerSet(S)
u = [0, 0, one, 0, 0, one, 0]
v = [0, one, 0, 0, 0, one, 0]
u_0010010 = {y for x in P for y in x if SumVectorList(x, S) == u}
u_0100010 = {y for x in P for y in x if SumVectorList(x, S) == v}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T19:43:09.140",
"Id": "45648",
"Score": "0",
"body": "What does your code do ? What is it supposed to do ? Does it work ? I've tried replacing `one` by `1` and it is now running fine but it doesn't seem to be doing much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T19:48:30.097",
"Id": "45649",
"Score": "0",
"body": "one should not be replace with 1. The one in this case is 1 in GF2. So one+one=0 where as 1+1 in R = 2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T19:50:10.557",
"Id": "45650",
"Score": "0",
"body": "@Josay As stated about I'm trying to find subset of S that when summed over GF2 you get the value of u or v respectively. I left out the GF2 portion, sorry. The code works just fine. I just was wondering how I could make it cleaner and with less lines maybe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:00:15.253",
"Id": "45652",
"Score": "0",
"body": "Thanks for the clarification. That makes sense now. Can you give the definition of `one` (and any other things we might need for testing purposes) ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:38:32.557",
"Id": "45657",
"Score": "0",
"body": "@Josay you can go to http://resources.codingthematrix.com and Download GF2.py"
}
] |
[
{
"body": "<p>Please have a look at <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP 8</a> giving the Style Guide for Python Code.</p>\n\n<p>Now, in <code>AddVectors</code> (or <code>add_vectors</code>), it seems like you assume that A and B have the same size. You could achieve the same result with <code>zip</code>.</p>\n\n<pre><code>def add_vectors(a, b):\n assert(len(a)==len(b))\n return [sum(i) for i in zip(a,b)]\n</code></pre>\n\n<p>I have to go, I'll some more later :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T17:16:37.603",
"Id": "28987",
"ParentId": "28985",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "28987",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T16:45:53.400",
"Id": "28985",
"Score": "-1",
"Tags": [
"python",
"python-3.x",
"mathematics"
],
"Title": "Find all subsets of a vector that sum up to another vector"
}
|
28985
|
<p>I am using the <a href="http://zserge.bitbucket.org/jsmn.html" rel="nofollow">jsmn JSON parser</a> (<a href="https://raw.github.com/noct/jsmn/master/jsmn.c" rel="nofollow">source code</a>) to get extract data from a JSON string. jsmn stores the data in tokens that just point to the token boundaries in the JSON string instead of copying the data. For example, jsmn will create tokens like:</p>
<ul>
<li><p><code>Object [0..31]</code></p></li>
<li><p><code>String [3..7], String [12..16], String [20..23]</code></p></li>
<li><p><code>Number [27..29]</code></p></li>
</ul>
<p>This method is used to retrieve the actual characters between those values (for String objects):</p>
<pre><code>char* getTextFromJSON(const char *json)
{
json_parser p;
jsontok_t tokens[15];
jsontok_t key;
if (!json) return NULL;
initJsonParser(&p);
parseJson(&p, json, tokens, sizeof(tokens) / sizeof(tokens[0]));
for(unsigned int i = 0; i < sizeof(tokens) / sizeof(tokens[0]); ++i)
{
key = tokens[i];
unsigned int length = key.end - key.start;
char keyString[length + 1];
memcpy(keyString, &json[key.start], length);
keyString[length] = '\0';
if(!strcmp(keyString, "utterance"))
{
key = tokens[i + 1];
length = key.end - key.start;
char* keyString = (char*) malloc(length + 1);
memcpy(keyString, &json[key.start], length);
keyString[length] = '\0';
return keyString;
}
}
return NULL;
}
</code></pre>
<p>Here are some JSON examples that would be thrown into the parser:</p>
<pre><code>{"status":0,"id":"432eac38858968c108899cc6c3a4bade-1","hypotheses" [{"utterance":"test","confidence":0.84134156}]}
</code></pre>
<p></p>
<pre><code>{"status":5,"id":"695118aaa3d01dc2ac4aa8054d1e5bb0-1","hypotheses":[]}
</code></pre>
|
[] |
[
{
"body": "<p>There are a few issues with <code>getTextFromJSON</code> involving use of pointers, code\nduplication and use of an inappropriate function.</p>\n\n<p>Pointers first. In this code:</p>\n\n<pre><code>jsontok_t tokens[15];\njsontok_t key;\n...\nkey = tokens[i];\n</code></pre>\n\n<p>you are copying the token when you could be using a pointer:</p>\n\n<pre><code>jsontok_t *key = &tokens[i];\n</code></pre>\n\n<p>Copying is obviously more costly than pointing. Also note that it is often\nbest to define the variable at its first point of use.</p>\n\n<hr>\n\n<p>There are two points of duplication, one determining the size of the token\narray and one concerned with copying the string. Instead of this:</p>\n\n<pre><code>jsontok_t tokens[15];\n...\nparseJson(&p, json, tokens, sizeof(tokens) / sizeof(tokens[0]));\nfor(unsigned int i = 0; i < sizeof(tokens) / sizeof(tokens[0]); ++i)\n</code></pre>\n\n<p>I would do either:</p>\n\n<pre><code>#define N_TOKENS 15\njsontok_t tokens[N_TOKENS];\n...\nparseJson(&p, json, tokens, N_TOKENS);\nfor(unsigned int i = 0; i < N_TOKENS; ++i)\n</code></pre>\n\n<p>or </p>\n\n<pre><code>jsontok_t tokens[15];\n#define N_TOKENS (sizeof tokens / sizeof tokens[0]) // or const int N_TOKENS inseatd of #define \n...etc \n</code></pre>\n\n<p>The string copying code-duplication is actually unnecessary if you use a\nbetter standard library function...</p>\n\n<hr>\n\n<p>Instead of using <code>strcmp</code> to compare the string (which involves constructing\nthe string because it lacks a \\0):</p>\n\n<pre><code> if(!strcmp(keyString, \"utterance\"))\n</code></pre>\n\n<p>use <code>memcmp</code>. And you can use <code>strndup</code> to create a copy of the key. If you\ndon't have <code>strndup</code> which is non-standard, you can easily write it (in a\nseparate function).</p>\n\n<p>These changes wont speed it up much, but are certainly cleaner:</p>\n\n<pre><code>char* getTextFromJSON(const char *json)\n{\n if (!json) return NULL;\n\n json_parser p;\n #define N_TOKENS 15 // this normally would be at the start of the file\n jsontok_t tokens[N_TOKENS];\n\n initJsonParser(&p);\n int n = parseJson(&p, json, tokens, N_TOKENS);\n for (int i = 0; i < n; ++i) {\n jsontok_t *key = &tokens[i];\n if (!memcmp(\"utterance\", &json[key->start], (size_t) (key->end - key->start))) {\n ++key;\n return strndup(&json[key->start], (size_t)(key->end - key->start));\n }\n }\n return NULL;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:41:22.330",
"Id": "45659",
"Score": "0",
"body": "+1 for all the great suggestions, but the empty JSON gives a \"Segmentation fault\" because no utterance exists in the JSON. How would I go about fixing that? Once it is fixed I will mark it as accepted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T21:15:45.613",
"Id": "45663",
"Score": "0",
"body": "So if the utterance is not found the function returns NULL to the caller (eg in `main`). You need to test for that in `main`, so something like `if ((text = getTextFromJSON(json)) != NULL) { /* do something with text */ }`. Hope that helps :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T21:19:36.897",
"Id": "45664",
"Score": "0",
"body": "Right now I'm doing it with a ternary operator: `printf(\"Text: %s\", text ? text : \"No text recognized.\")`, but it still segfaults."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T21:27:11.287",
"Id": "45665",
"Score": "0",
"body": "Upon changing the last `return NULL` to `return \"No text recognized\"`, it still segfaults, odd."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T21:36:52.540",
"Id": "45666",
"Score": "1",
"body": "Do you know exactly where it segfaults - have you run it in a debugger?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T21:40:41.123",
"Id": "45667",
"Score": "0",
"body": "On the 8th execution of the `for` loop, it fails on the conditional `memcmp()` test."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T23:19:51.777",
"Id": "45675",
"Score": "0",
"body": "Your problem is most likely that you are looping through tokens that don't exist. You should use the number of tokens found, presumably returned by `parseJson`, as the loop limit. I have updated the code above to illustrate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:33:50.380",
"Id": "45699",
"Score": "0",
"body": "No, it returns `JSON_SUCCESS` which is a `jsonerr_t`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:57:02.117",
"Id": "45703",
"Score": "0",
"body": "When I try to print the value of every token in the loop to see what is going on it segfaults. I'm using `printf(\"Token[%d]: %s\", i, strndup(&json[key->start], (size_t)(key->end - key->start)))` right after assigning `key` a value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T17:12:06.733",
"Id": "45756",
"Score": "0",
"body": "There must be a way of finding out how many of your `tokens[]` array contain valid data after the call to `jsonParse`. As you say, it is not the return value, so it must either be in the `json_parser p` parser or in the tokens themselves (initialised to a defined value for example)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-16T22:26:02.797",
"Id": "66003",
"Score": "0",
"body": "It turns out that it was a missed corner case of not checking for an empty token. I've put that and a bit more into my answer, but I'll keep this one as accepted since you got me very close to the final method I have now."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T18:40:54.390",
"Id": "28991",
"ParentId": "28986",
"Score": "8"
}
},
{
"body": "<h2>Improvements</h2>\n\n<p>Check if <code>parseJson()</code> returns an error code.</p>\n\n<pre><code>int err = parseJson(&p, json, tokens, TOKEN_NUMBER);\nif (err)\n{\n fprintf(stderr, \"Error parsing JSON: %d\\n\", err);\n return NULL;\n}\n</code></pre>\n\n<hr>\n\n<p>The code initializes all of the structures, but <code>->start</code> and <code>->end</code> will equal -1, which is why <code>memcmp()</code> will fail sometimes.</p>\n\n<pre><code>for (i = parser->toknext; i < num_tokens; i++) {\n jsmn_fill_token(&tokens[i], JSMN_PRIMITIVE, -1, -1);\n}\n</code></pre>\n\n<p>Checking for a -1 value in <code>->start</code> or <code>->end</code> should be sufficient.</p>\n\n<pre><code>if ((key->end - key->start) < 0) return NULL;\n</code></pre>\n\n<hr>\n\n<p>The <code>tokens[]</code> array is uninitialized before it is passed to <code>parseJson()</code>, so once you iterate beyond the last token, the code is trying to run <code>memcmp()</code> on uninitialized nonsense address values. Initialize <code>tokens[]</code> to something and then check for that initialization value in the start/end fields during in the <code>for()</code> loop.</p>\n\n<pre><code>memset(&tokens, 0, sizeof(tokens));\n</code></pre>\n\n<hr>\n\n<p>During each iteration of the loop check for length zero to see if the token is actually valid before passing it to <code>memcmp()</code>. Bail out of the loop if the token has length zero.</p>\n\n<pre><code>if (!memcmp(\"\", &json[key->start], (size_t) (key->end - key->start))) return NULL;\n</code></pre>\n\n<hr>\n\n<p>Add a test case for a blank token.</p>\n\n<pre><code>if (!memcmp(\"\", &json[key->start], (size_t) (key->end - key->start))) return NULL;\n</code></pre>\n\n<hr>\n\n<h2>Final Code</h2>\n\n<pre><code>#define TOKEN_NUMBER 15\nchar* getTextFromJSON(const char *json)\n{\n if (!json) return NULL;\n\n json_parser p;\n jsontok_t tokens[TOKEN_NUMBER];\n memset(&tokens, 0, sizeof(tokens));\n initJsonParser(&p);\n int err = parseJson(&p, json, tokens, TOKEN_NUMBER);\n if (err)\n {\n fprintf(stderr, \"Error parsing JSON: %d\\n\", err);\n return NULL;\n }\n for(int i = 0; i < TOKEN_NUMBER; ++i)\n {\n jsontok_t *key = &tokens[i];\n if ((key->end - key->start) < 0) return NULL;\n if (!memcmp(\"\", &json[key->start], (size_t) (key->end - key->start))) return NULL;\n if (!memcmp(\"utterance\", &json[key->start], (size_t) (key->end - key->start)))\n {\n ++key;\n return strndup(&json[key->start], (size_t) (key->end - key->start));\n }\n }\n return NULL;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:39:41.533",
"Id": "37636",
"ParentId": "28986",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "28991",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T17:10:00.663",
"Id": "28986",
"Score": "12",
"Tags": [
"performance",
"c",
"parsing",
"json"
],
"Title": "More efficient way to retrieve data from JSON"
}
|
28986
|
<p>The reason I asked about standing the test of time is that I previously used PHP echo to create a string and placed it into a div with .innerHTML, but modern browsers were not passing the value of the select box. (Went back and tested wit IE9 and the innerHTML version worked.)</p>
<p>file:js_selecttest.php</p>
<pre><code><form method="post" action='js_selecttest.php'>
<table>
<tr>
<td><input type="text" name="text_input" onClick="create_sel(document.getElementById('select_holder'),'class_date',op_array)">
<div id="select_holder">Filled by JS</div>
<br><input type="submit"></td>
</tr>
</table>
</form>
<script type="text/javascript">
function create_sel(container,sel_name,op_array)
{
var sel = document.createElement('select');
sel.name=sel_name;
populateList(op_array,sel);
container.innerHTML='';
container.appendChild(sel);
}
function populateList(op_array,sel_obj) // from http://www.webdeveloper.com/forum/showthread.php?206250#4
{
var arLen=op_array.length;
for(var i=0; i<arLen; i++)
{
sel_obj.options[i]=new Option(op_array[i], i);
sel_obj.options[i].value=op_array[i];
}
}
<?php
$op_array=array('Please Select','One','Two','Three','Four','Five','Six',);
?>
var op_array = <?php echo json_encode($op_array) ?>;
</script>
<?php
if($_POST)
{
var_dump($_POST);
}
?>
</code></pre>
<p>Would you have any suggestions or improvements?</p>
|
[] |
[
{
"body": "<p>To answer your question in the title: no\nFor multiple reasons. One being that the things we use today could be out-dated in a few years. who knows</p>\n<p>One question/remark:</p>\n<pre><code>sel_obj.options[i]=new Option(op_array[i], i);\nsel_obj.options[i].value=op_array[i];\n</code></pre>\n<p>is there a reason why you are setting the value twice? (once in the new Option call and once on the next rule)</p>\n<p>My suggestions are:</p>\n<h1>Separation of concerns</h1>\n<p>You have one file with html, javascript and php all interweaved with each other. So debugging won't make it any easier. Alsog reusing a part of that script is nearly impossible since everything is hard coded.</p>\n<h1>Overuse of javascript</h1>\n<p>Is there a reason why you are building the html with javascript? Because this has some drawbacks: Screenreaders will not be able to see the selectlist items since they don't parse javascript. Serach engines will not know about the select-options.\nInstead you should use PHP to create the html for the select items.</p>\n<h1>Hard to read code</h1>\n<p>The code is very hard to read, the function and variable names don't clearly tell what they are or have typehinting in the names. For instance <code>op_array</code> variable. Words as Array, String, int,.. should be banned from variable names. Simply call it <code>options</code>. Now by simply reading it I allready know that is has multiple values and that it are the options. Where as op_array tells me that it is an array of 'op'.</p>\n<p>Also for future enhancements. If for some reason you are going to change the way options are passed in, you will also have to change the name of the variable...</p>\n<p>Also be more consistent in your naming. populateList() needs a select and options. But no list. This is confusing.</p>\n<p>Personally I never use the onClick attributes inhtml. Not because they are bad. But because if you do use them, javascript will be hidden in the html and tightly coupled with it whereas if you EvntListners it is very easy to change the html without having to bother about the javascript. this is also better for <strong>sepperation of concerns</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T14:45:59.083",
"Id": "45811",
"Score": "0",
"body": "The HTML with onClick is just 1 way to implement this & the PHP json is just 1 way to fill the array. It could be ajax as well. I'll test again, but the redundant code was because I think I was getting `value=\"\"` in those elements even though the inner text was filled. The re-naming of vars and funcs make sense and I thank you for pointing those out to me. In the case for which I wrote this, I ended up not using it. I put hidden divs in with various selects and used js to unhide them. Then the handler script has to deal with which ones are filled or empty"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T10:53:11.407",
"Id": "45853",
"Score": "0",
"body": "@TecBrat the PHP json way is a weird way to do what you are doing. You are rendering a part of the html in php on serverside and another part on clientside. This is simply bad practice"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T22:19:49.400",
"Id": "45875",
"Score": "0",
"body": "The use case is where there is a class schedule. The site owner manages the available class dates. The end-user selects between the full class, or just the last day with the exam. The PHP will gather the available dates for the selected class. Then, when the end-user chooses the full class or just the end date, the select box appears with the correct options. A `<noscript>` is used to offer all options. \"bad practice\" is not helpful. Can you finish this sentence? \"That practice will cause a problem when...\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T14:01:06.153",
"Id": "29026",
"ParentId": "28988",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29026",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T17:23:28.303",
"Id": "28988",
"Score": "1",
"Tags": [
"javascript",
"php",
"html"
],
"Title": "Is this code likely to stand the test of time? (Add select box to DOM with JS)"
}
|
28988
|
<p>Based on the post I made here: <a href="https://codereview.stackexchange.com/questions/28948/rfc-on-factory-code">RFC on "Factory" code</a> and its responses, and my (inner) response to those responses, I'm beginning to wonder if it would be just as well to simply switch based on the user's hardware, and forget about this "fancy pants" factory stuff. After all, new code will have to be added for each new printer we support, either the hard way (with all this abstraction) or the easy way ("just do it").</p>
<p>From what I understand, using the factory pattern is more "elegant," but still: new code has to be added; and apparently, because of the "open-closed principle" (open to extension, closed to modification), the elegant way is to continue to add new classes that inherit from prior ones. So we could end up with:</p>
<pre><code>PrintClass, immutable after being written
NewPrintClass, "" (which inherits from PrintClass, but adds another printer type)
NewerPrintClass, "" (which inherits from NewPrintClass, but adds another printer type)
NewestPrintClass, "" ( etc. )
NewestestPrintClass, "" ( etc. )
etc. etc. ad infinitum ad nauseum
</code></pre>
<p>IOW, it might be best just to have this simple client code:</p>
<pre><code>BeltPrinter.PrintLabel(price, description, barcode);
</code></pre>
<p>...and that would be implemented something like this:</p>
<pre><code>namespace BeltPrinter;
string _price = string.Empty;
string _desc = string.Empty;
string _barcode = string.Empty;
List<string> printerSetupCmds = new List<string>();
List<string> printLabelCmds = new List<string>();
List<string> printerTeardownCmds = new List<string>();
public static void PrintLabel(string price, string description, string barcode)
{
_price = price;
_desc = description;
_barcode = barcode;
if (<ZebraQL220>) // don't know yet how I will determine which printer is in use - perhaps from reading a config file...
{
PopulateListsForZebraQL220Printer();
}
else if (<ONeal>)
{
PopulateListsForONealPrinter();
}
// add other calls to PopulateListsForX as needed later
SendPrinterCodes();
}
private void PopulateListsForZebraQL220Printer()
{
printerSetupCmds.Add(<add setup commands specific to Zebra>);
. . .
printLabelCmds .Add(<add print commands specific to Zebra, using _price, _desc, and _barcode>);
. . .
printerTeardownCmds .Add(<add teardown commands specific to Zebra>);
. . .
}
private void PopulateListsForONealPrinter()
{
printerSetupCmds.Add(<add setup commands specific to ONeal>);
. . .
printLabelCmds = new List<string>();
printLabelCmds .Add(<add print commands specific to ONeal, using _price, _desc, and _barcode>);
. . .
printerTeardownCmds = new List<string>();
printerTeardownCmds .Add(<add teardown commands specific to ONeal>);
. . .
}
private void SendPrinterCodes()
{
ExecutePrintCommands(printerSetupCmds);
ExecutePrintCommands(printLabelCmds);
ExecutePrintCommands(printerTeardownCmds);
}
private void ExecutePrintCommands(List<string> printerCmdsList)
{
foreach (string line in printerCmdsList) {
serialPort.Write(line); // There's a lot of OpenNETCF stuff behind this line, this is just 'shorthand' for what happens
}
}
</code></pre>
<p>I wouldn't exactly call that a maintenance nightmare*; it seems quite straightforward to me (of course, I wrote it, and within the last fifteen minutes, so YMMV), whereas the fancy pants "factory" stuff almost seems like a bunch of smoke and mirrors to me. It reminds me of the company attorney who came up with a convoluted legal agreement which the boss could not understand. The boss asked for explanation. Another employer put it plainly. The boss replied, "Would stating it in such a way, plainly and simply, have the same effect"? When the lawyer had to agree that yes, it would, he was soon seeking employment elsewhere.</p>
<ul>
<li>For each new printer type, simply add another "else/if" block to PrintLabel(), and another PopulateListsForX() method to the class. And, of course, the printer-specific code, which is the bulk of the work in any case, and will need to be done whatever the underlying/enveloping programming milieu.</li>
</ul>
<p>I'm not saying all these cats who are so much more clever than I, implementation-wise, are wasting their time or anybody else's. I'm just saying I'm not so sure the straightforward way is not just as good (at times, anyway).</p>
<p>I see it this way: What I will call "fancy pants coding" (using layers of abstraction, patterns, frameworks, the latest buzzword/acronym, etc.) is not in itself, in the long run, any easier or harder than "cowboy coding"; it's just that the hard part and the (relatively) easy part switch places. With fancy pants coding, the hard part comes first, in the architecture and design; with cowboy coding, the hard part is at the end, when you're adding on new and forgotten pieces and dealing with edge cases. So, which one you choose doesn't really matter (pick your poison); anyway, from my experience, you end up dealing with new and forgotten pieces and edge cases that are tough to navigate through no matter which methodology you practice or "philosophy" you espouse.</p>
<p>BUT (there's almost always a "but"): what about the maintenance part of it? In the specific case I'm dealing with, ISTM that adding new "PopulateListsForX()" methods as necessary (along with new "else if" blocks to the PrintLabel() method) would be much easier (read: faster) than extending classes after the canonical (fancy pants) fashion - which M.O. actually seems rather sloppy to me, like adding lean-tos onto the barn once your cow had another calf, or bedrooms off the kitchen after ... (etc.) To be fair, both ways of approaching it are rather like that, so again: it's sort of a tradeoff.</p>
<p>And, what I think is a key question (also based on empirical observation, having been involved in several projects for several companies): Which style of coding is easier for a "new guy" to hit the ground running with: the magnum opus/tour de force of the (<em>possibly</em> still around) boy genius architect, or the straightforward and easy-to-grok "plain vanilla" code?</p>
<p>The bottom line, as I see it, is that creating software is hard, <em>really</em> hard (unless, perhaps, you are a genius, which I obviously am not). As Brooks (not Foster, not Robert: Frederick) said, there are no silver bullets.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T19:39:55.713",
"Id": "45647",
"Score": "6",
"body": "Tip: Reduce the amount of text. The *tl;dr*-factor here is fairly high."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T22:44:59.657",
"Id": "45791",
"Score": "0",
"body": "Yes, it makes everyone dizzy at first, but it quickly becomes second nature, like riding a bike. I would recommend creating a `SettingsReader` business class of some sort which determines which printer to use. The factory could then create one of those and use it to set it's enum field."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T20:13:24.187",
"Id": "45966",
"Score": "0",
"body": "hmmm, I'm not sure how this could work as _printerChoice never seems to be set, or provided to the factory.... Did you have some other \"fancy pants\" way of setting that :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T20:35:09.857",
"Id": "45967",
"Score": "0",
"body": "For the moment, I'm simply setting it to Zebra, as it's the only one we support at present. In the future, will have to read a config file or something to determine which belt printer to target. Besides, the switch statement returns zebra as a fallback/default."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T22:34:03.643",
"Id": "45970",
"Score": "1",
"body": "This doesn't seem to really be a code review question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T22:48:14.340",
"Id": "45971",
"Score": "0",
"body": "Well, it started off that way, at any rate. It has admittedly morphed into a Little Lord Fauntleroy vs. Sam Elliott question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T15:08:04.463",
"Id": "46051",
"Score": "0",
"body": "This kind of goes along with my feelings on the subject, and to wax a little philosopical, I wonder if this extreme abstraction has any connection with the general abstractness of society itself, with virtual \"friends\" seemingly taking the place of real friends, disconnected communication being the norm, etc. Anyway:\n\nhttp://www.codeproject.com/lounge.aspx?msg=4622874#xx4622874xx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:52:08.223",
"Id": "46073",
"Score": "0",
"body": "Related question (about the specific code): http://stackoverflow.com/questions/17955040/how-can-i-return-none-as-a-default-case-from-a-factory"
}
] |
[
{
"body": "<p>Start from the simplest possible way to solve the problem, and add complexity if there is a reason. Reasons could be a specific need from the specifications, or something that your experience tells you will very likely be needed at some point.</p>\n\n<p>In this specific case, there would be a point in isolating the implementation for a printer inside a class by itself. That way you can specify an interface for what the class needs to implement, which would make it clear what needs to be implemented to anyone implementing another class.</p>\n\n<p>The interface would also allow the client code to use any printer implementation without having to know what printer it is, or having separate code for separate printers.</p>\n\n<p>To determine which implementation to use, a row of <code>if</code> statements (or a <code>switch</code>) is the simplest to follow. It needs to be maintained along with the classes, of course, but it's easier for a newcomer to see what's happening, compared to any fancy way of registering classes automagically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:32:38.977",
"Id": "45656",
"Score": "0",
"body": "I think we differ on the \"when there is a reason\" point (that is to say, point in time - for my specific case)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T20:41:02.537",
"Id": "45658",
"Score": "0",
"body": "@ClayShannon: Good point, I changed it to \"if there is a reason\", as I of course meant the complexity added initially."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T22:24:16.280",
"Id": "45671",
"Score": "1",
"body": "Almost exactly what I'd answer. But this is my cue to pull out my favourite pet peeve: that many (most) languages supports interfaces over multiple inheritance, which (used right) is a pragmatic way writing code that is still reusable, without getting caught up in too many layers."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T23:19:02.967",
"Id": "45674",
"Score": "0",
"body": "You must be a C++ cat (not that there's anything wrong with that)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T23:33:46.967",
"Id": "45677",
"Score": "0",
"body": "Well, not really. JavaScript and Perl."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T19:53:59.937",
"Id": "28994",
"ParentId": "28990",
"Score": "7"
}
},
{
"body": "<p>To quote an ancient truth, \"To every thing there is a season, and a time to every purpose.\" There is a time to <em>fancy-pants-code</em>, and there is a time to <em>cowboy-code</em>. Experience is what has to guide you in determining which method is better suited for a given task. There are many things that can impact that decision, for instance:</p>\n\n<ul>\n<li>How long will it take</li>\n<li>How much time do I have until it must be done</li>\n<li>How long will this code be around</li>\n<li>How often is the code going to need modifications in the future</li>\n<li>How many other developers will need to work on this code</li>\n</ul>\n\n<p>Simply put, from an idealistic standpoint, <em>fancy-pants</em> code is always better than <em>cowboy</em> code, but from a practical standpoint, <em>fancy-pants</em> code can sometimes be much worse. So, as a general rule-of-thumb, I would say that <strong>you should always <em>fancy-pants-code</em> unless you have a good reason not to do so, and you should accept that there are some very good reasons not to do so, sometimes.</strong></p>\n\n<p>I have a lot of experience with this, and I can tell you, designing code well up-front, is <em>WELL</em> worth the effort. It's true, as you said, that good design has more up-front cost, and poor design has more back-end cost, but to say that the two are equivalent, because of that, is fallacious. It all depends how much back-end work will need to be done. </p>\n\n<p>As you say, a simple <code>switch</code> statement isn't really that bad, and if adding more <code>case</code> statements to the <code>switch</code> statement is the worst of the back-end cost that you are going to incur, then it's really not worth the time to add a bunch of complication to avoid something as trivial as that. But if the project grows and changes over the years, a little shortcut like that, to save a few hours of development time, could potentially cost months of development time in the long run. It all depends.</p>\n\n<p>Another issue which often muddies the water is that <strong>not all <em>fancy</em> designs are actually good designs</strong>. You could develop the most impressive fancy code in the world, but if it doesn't actually solve any problems, such as making the code more stable, flexible, or maintainable, then you've actually made the problem worse by all your fanciness.</p>\n\n<p>As much as I am a believer of good design, I am also a strong believer in the <a href=\"http://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"noreferrer\">YAGNI</a> principle. If you haven't read the wikipedia page on YAGNI, I'd strongly recommend it. YAGNI simply means \"You aint gonna need it\". Simply put, don't add features and complication that you don't currently need. YAGNI does not preclude good design, but it does preclude unnecessary fanciness. Again, the issue isn't whether or not the design is fancy, it's whether or not the design is good. A good design will follow the YAGNI principle. It is definitely possible to \"over-design\" something.</p>\n\n<p>All that being said, if there is no good reason to <em>cowboy-code</em> on this one, as it sounds like their might not be, allow me to offer my perspective on what a <em>good</em> fancy design might look like. My way is by no means the only right way, but hopefully it will be helpful to you. I'd like to think that my fancy way of doing it does solve a lot of future problems and would therefore be worth the relatively small up-front cost.</p>\n\n<h2>My Way to Do It (Dependency-Injection)</h2>\n\n<p>Your first instinct was to think that the <em>Factory Pattern</em> would be a good solution to this problem. That was a good instinct, but I don't think it quite goes far enough. Dependency-Injection (DI), which relies heavily on factories, is perfectly suited to this type of problem. Personally, I think it is well-suited for almost all problems, but there are certain problems, like this one, which just scream dependency-injection.</p>\n\n<p>In general, the principle of DI is that a class never creates it's own dependencies. So, for instance, if you have a <code>Car</code> class, and it needs an <code>Engine</code> object, you wouldn't have the <code>Car</code> class create its own <code>Engine</code> object. Instead, you would have the <code>Car</code> class request that the <code>Engine</code> (it's <em>dependency</em>) be given to it (<em>injected</em>), usually in its constructor. For example, rather than having something like this:</p>\n\n<pre><code>public class Car\n{\n private Engine _engine = new Engine();\n}\n</code></pre>\n\n<p>With DI, you'd have something like this:</p>\n\n<pre><code>public class Car : ICar\n{\n public Car(IEngine engine)\n {\n _engine = engine;\n }\n\n private IEngine _engine;\n}\n</code></pre>\n\n<p>When you think about it, it makes perfect logical sense. In the real world, you'd never even think of designing a car that creates it's own engine--that would be a nightmare. You of course would build a factory which would create both the car and then engine, and then put the engine into the car (<em>inject</em> it). The equivalent in code, would be to create a factory class, like this:</p>\n\n<pre><code>public class Factory\n{\n public ICar NewCar()\n {\n return new Car(new Engine());\n }\n}\n</code></pre>\n\n<p>The advantage of doing this is that, just as in real life, you have made the situation much less complicated, and much more flexible, by separating the business logic (i.e. how the car actually functions internally, what it does, or, more simply, what makes it a car), from the construction logic (i.e. how to build the individual parts and how to wire them all together).</p>\n\n<p>You'll notice that in the DI example, the car and engine implement interfaces. Interfaces are very important in dependency injection. The point is, that as long as all engines implement the same public interface, the car shouldn't care which engine is actually injected into it. As long as they all serve the same purpose and are called in the same way, their internal workings are irrelevant to the car. In other words, as long as when you press the accelerator, the engine speeds up, it doesn't really matter if it's a jet engine, an internal combustion engine, or a hamster in a hamster wheel. In other words, the car's engine is <em>plug-and-play</em>.</p>\n\n<p>Their are many advantages to this methodology. For instance, DI is used heavily by unit-testing enthusiasts because it makes it very easy to test each class in isolation. For instance, if you want to test the car class, you are in full control of what you give it as an engine. You don't even have to give it a real engine at all. You could give it a fake (<em>mock</em>) engine that just reports back to the unit tester whether or not the car was sending the correct signals to the engine at the right times. </p>\n\n<p>Another major advantage of DI is that it avoids spaghetti code and buggy-ness in the long-run. For instance, lets say, in the future, you keep adding more and more different kinds of engines to your code. With DI, you'll possibly never even have to touch a line of code in your car class to do so. The less you have to modify the code, the less bugs you will create. The alternative is to have, right in the middle of your business logic, a whole bunch of construction logic which keeps growing in complexity with each new engine type that you add.</p>\n\n<h2>Your Project, the DI Way</h2>\n\n<p>So, what does this all mean to you in your situation? Here is a basic idea of how I would implement it with DI principles. First, I would create a simple interface which would be common for all of your printers:</p>\n\n<pre><code>public interface IBeltPrinter\n{\n void PrintLabel(string price, string description, string barcode);\n}\n</code></pre>\n\n<p>Then, I would create a separate concrete implementation for each type of printer, like this:</p>\n\n<pre><code>public class ZebraQL220Printer : IBeltPrinter\n{\n public void PrintLabel(string price, string description, string barcode)\n {\n // Do it the Zebra way\n }\n}\n\npublic class ONealPrinter : IBeltPrinter\n{\n public void PrintLabel(string price, string description, string barcode)\n {\n // Do it the ONeal way\n }\n}\n</code></pre>\n\n<p>The beauty here is, you are free to implement these printer classes however you want. If some of them all work very similarly internally, you could create a base class for them that those classes derive from. But if you need to make a new printer class, sometime in the future, which doesn't work the same way at all, you're free to implement it anyway you want. As long as it implements the <code>IBeltPrinter</code> interface, that's all that matters. It doesn't matter what class it derives from, how it works, what namespace it exists in, or even what library it comes from. So, for instance, if you do have a bunch of printers that all work by sending the same kinds of basic commands, you could create a base class, like this:</p>\n\n<pre><code>public abstract class CommandDrivenBeltPrinter : IBeltPrinter\n{\n public void PrintLabel(string price, string description, string barcode)\n {\n foreach (string i in GetSetupCommands()) ExecuteCommand(i);\n foreach (string i in GetPrintCommands(price, description, barcode)) ExecuteCommand(i);\n foreach (string i in GetTeardownCommands()) ExecuteCommand(i);\n }\n\n private void ExecuteCommand(string command)\n {\n // Do it in the way that is common to all command-driven printers\n }\n\n protected abstract List<string> GetSetupCommands();\n protected abstract List<string> GetPrintCommands(string price, string description, string barcode);\n protected abstract List<string> GetTeardownCommands();\n}\n</code></pre>\n\n<p>Then, you could implement all of your command-driven printers using that same base class, like this:</p>\n\n<pre><code>public class ZebraQL220Printer : CommandDrivenBeltPrinter\n{\n protected override List<string> GetSetupCommands()\n {\n return new List<string>(new string[] {\"Zebra command 1\", \"Zebra command 2\"});\n }\n\n protected override List<string> GetPrintCommands(string price, string description, string barcode)\n {\n return new List<string>(new string[] { \"Zebra command 3\", \"Zebra command 4\" });\n }\n\n protected override List<string> GetTeardownCommands()\n {\n return new List<string>(new string[] { \"Zebra command 5\", \"Zebra command 6\" });\n }\n}\n\npublic class ONealPrinter : CommandDrivenBeltPrinter\n{\n protected override List<string> GetSetupCommands()\n {\n return new List<string>(new string[] { \"ONeal command 1\", \"ONeal command 2\" });\n }\n\n protected override List<string> GetPrintCommands(string price, string description, string barcode)\n {\n return new List<string>(new string[] { \"ONeal command 3\", \"ONeal command 4\" });\n }\n\n protected override List<string> GetTeardownCommands()\n {\n return new List<string>(new string[] { \"ONeal command 5\", \"ONeal command 6\" });\n }\n}\n</code></pre>\n\n<p>But again, the point is, you don't have to use that base class at all. At that point it's totally up to you how you implement each printer class. They may all share the same base class, there may be three different base classes, or you could implement them all separately with no shared inheritance at all. In fact, rather than using inheritance, you may want to create a separate helper class which includes all the common business logic, and then just inject it into each of the printer classes that need it, for instance:</p>\n\n<pre><code>public interface ICommandDrivenPrinterBusiness\n{\n private void ExecuteCommand(string command);\n}\n\npublic class CommandDrivenPrinterBusiness : ICommandDrivenPrinterBusiness\n{\n private void ExecuteCommand(string command)\n {\n // Do it in the way that is common to all command-driven printers\n }\n}\n\npublic class ZebraQL220Printer : IBeltPrinter\n{\n public ZebraQL220Printer(ICommandDrivenPrinterBusiness business)\n {\n _business = business;\n }\n\n private ICommandDrivenPrinterBusiness _business;\n\n public void PrintLabel(string price, string description, string barcode)\n {\n _business.ExecuteCommand(\"Zebra command 1\");\n _business.ExecuteCommand(\"Zebra command 2\");\n }\n}\n</code></pre>\n\n<p>Then, you would need to create a separate factory class which creates all of these objects and wires them together properly:</p>\n\n<pre><code>public interface IBeltPrinterFactory\n{\n IBeltPrinter NewBeltPrinter();\n}\n\npublic enum BeltPrintersEnum\n{\n ZebraQL220,\n ONeal\n}\n\npublic class BeltPrinterFactory : IBeltPrinterFactory\n{\n private BeltPrintersEnum _printerChoice;\n\n public IBeltPrinter NewBeltPrinter()\n {\n switch (_printerChoice)\n {\n case BeltPrintersEnum.ZebraQL220: return new ZebraQL220Printer();\n case BeltPrintersEnum.ONeal: return new ONealPrinter();\n }\n }\n\n private IBeltPrinter NewZebraQL220Printer()\n {\n return new ZebraQL220Printer();\n }\n\n private IBeltPrinter ONealPrinter()\n {\n return new ONealPrinter();\n }\n}\n</code></pre>\n\n<p>Then, when you actually need to print a label, you could just do it like this:</p>\n\n<pre><code>public class OrderBusiness\n{\n public void ProcessOrder(OrderInfo order)\n {\n // ...\n IBeltPrinterFactory factory = new BeltPrinterFactory();\n IBeltPrinter printer = factory.NewBeltPrinter();\n printer.PrintLabel(order.price, order.description, order.barcode);\n // ...\n }\n}\n</code></pre>\n\n<p>Or even better yet, let the DI spread, like a really pleasant virus:</p>\n\n<pre><code>public class OrderBusiness\n{\n public OrderBusiness(IBeltPrinter printer)\n {\n _printer = printer\n }\n\n IBeltPrinter printer;\n\n public void ProcessOrder(OrderInfo order)\n {\n // ...\n _printer.PrintLabel(order.price, order.description, order.barcode);\n // ...\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T17:09:37.263",
"Id": "45755",
"Score": "1",
"body": "\"Another issue which often muddies the water is that not all fancy designs are actually good designs.\" Boy howdy! I've seen (up close) way too many projects where the architect knew just enough to be dangerous and served inadvertently (I assume it was inadvertently!) as agents provacateurs, sabotaging the project or even the company by means of their \"wizardry.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T18:00:46.443",
"Id": "45759",
"Score": "0",
"body": ":) Yes, I've seen my share of that too. Sometimes it can be dangerous when someone who doesn't fully understand the fundamentals starts wanting to use every newfangled methodology or technology. Not because it's better or well suited to the task, but simply because its new."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T18:19:19.243",
"Id": "45760",
"Score": "1",
"body": "This is a great article...I mean response (hint, hint). I had never quite grokked DI until now. In fact, I am preparing to pull on my fancy pants."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T18:24:51.157",
"Id": "45762",
"Score": "0",
"body": "And yes, I am quite familiar with both Ecclesiastes and The Byrds."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T18:41:15.427",
"Id": "45763",
"Score": "0",
"body": "Thanks. One of my favorite books, actually (and not a bad song either)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T18:43:22.200",
"Id": "45764",
"Score": "0",
"body": "If you are interested in learning about DI, do a search for some of Misko Hevery's Google Talk presentations on the subject. I really got a lot out of watching those back when I first started getting into it. For instance, all of these are great: http://www.youtube.com/watch?v=wEhu57pih5w&list=PLD0011D00849E1B79"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:23:09.487",
"Id": "45771",
"Score": "0",
"body": "What would the IBeltPrinterFactory Interface look like?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:44:57.207",
"Id": "45772",
"Score": "0",
"body": "Oops. I somehow missed that when copying and pasting the code. I just added it to the example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T21:33:53.003",
"Id": "45786",
"Score": "0",
"body": "\"factory.NewPrinter();\" should be \"factory.NewBeltPrinter();\" correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T22:39:56.140",
"Id": "45790",
"Score": "0",
"body": "Yes. Fixed it again :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:38:43.800",
"Id": "45941",
"Score": "0",
"body": "Updated my original post with a simplified version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:49:15.627",
"Id": "45942",
"Score": "0",
"body": "@ClayShannon That update looks great to me. Is it just the inheritance part of it that you took out? If so, I think it's better that way anyway. In my opinion, injecting common business objects is usually preferable to inheritance anyway. When you get into lots of inheritance, it often locks you into a certain way of doing things making it less flexible. I often refer to it as frameworks vs. tools. It's usually best to have common tools that are shared rather than some fancy framework that everything has to fit into."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:52:26.983",
"Id": "45943",
"Score": "0",
"body": "Framework-style code design can be very useful when you have a bunch of very similar things and you want to make it as quick and easy to add a new \"thing\" when necessary. But you really paint yourself into a corner when you find that you need to make a new \"thing\" which needs to work slightly differently than the rest of the things. Either you can't use the framework for that one thing, or else you need to modify the framework to handle the one special case. And the more special cases you have, the more convoluted the framework becomes."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T13:58:33.923",
"Id": "29025",
"ParentId": "28990",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T18:24:28.880",
"Id": "28990",
"Score": "4",
"Tags": [
"c#",
"design-patterns",
"factory-method"
],
"Title": "\"Fancy-pants\" vs \"Cowboy\" coding"
}
|
28990
|
<p>This is the code I wrote to find out the time spent by product in process represented by clockin and clock out. Time stamps X and Y (for example, 7/23/2013 7:00 AM and 7/23/2013 8:00 AM) reflect the time period where in I am calculating the time.</p>
<p><code>X</code>, <code>Y</code>, <code>CLOCK_IN</code> and <code>CLOCK_OUT</code> are all timestamps.</p>
<p>I wrote this code, but I am not a programmer. Is there a better way to do it? Please explain step by step.</p>
<p>It runs against a huge set of data. How can I reduce its runtime?</p>
<p>Here is a calculation I'm running in MS Access 2010:</p>
<pre><code>Sum(
IIf([CLOCK_IN]<[X] And [X]<[CLOCK_OUT] And [CLOCK_OUT]<[Y],([CLOCK_OUT]-[X])*24*60,0)+
IIf([CLOCK_IN]<[X] And [Y]=[CLOCK_OUT],60,0)+
IIf([CLOCK_IN]=[X] And [Y]<[CLOCK_OUT],60,0)+
IIf([X]<[CLOCK_IN] And [CLOCK_IN]<[Y] And [Y]<[CLOCK_OUT],([Y]-[CLOCK_IN])*24*60,0)+
IIf([X]<[CLOCK_IN] And [CLOCK_IN]<[CLOCK_OUT] And [CLOCK_OUT]<[Y],([Y]- [CLOCK_IN])*24*60,0)+
IIf([CLOCK_IN]<[X] And [X]<[Y] And [Y]<[CLOCK_OUT],60,0)+
IIf([X]=[CLOCK_IN] And [Y]=[CLOCK_OUT],60,0)+
IIf([X]=[CLOCK_IN] And [CLOCK_OUT]<[Y],24*60*([CLOCK_OUT]-[X]),0)+
IIf([X]<[CLOCK_IN] And [CLOCK_OUT]=[Y],24*60*([CLOCK_OUT]-[X]),0))/60)
)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T04:13:45.813",
"Id": "88702",
"Score": "1",
"body": "This is vague, are you able to provide information about your data set, maybe some context of what this code is part of? Very difficult to suggest improvements without context..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-10T13:50:30.430",
"Id": "93770",
"Score": "0",
"body": "[This](http://allenbrowne.com/casu-13.html) may help you a little bit.."
}
] |
[
{
"body": "<p>I'll attempt to provide something helpful, even though this is old.</p>\n\n<ol>\n<li><p>To start with, just syntax-wise, <code>[brackets]</code> are only required if your column name contains a reserved character, such as a space or apostrophe. It looks less cluttered if you don't use them unless needed, and I don't see any need for it in your columns. </p></li>\n<li><p>Line breaks and tabs make code much easier to read. I know Access is quite limited in the amount of formatting you can do and doesn't allow comments, but every bit helps. </p></li>\n<li><p>I notice a lot of redundancy in your <code>Iif</code> statements. 3 statements result in <code>([CLOCK_OUT]-[X])*24*60</code>. 2 statements result in <code>([Y]-[CLOCK_IN])*24*60</code>. And 4 statements all result in <code>60</code> if true. My thought is to group these together as 3 subqueries and use <code>WHERE</code> instead of <code>Iif</code> to sort out the results. </p></li>\n</ol>\n\n<p>Here is how I would write this. Note I used <code>Your_Table_Name</code> since your code doesn't say, make sure you replace this with the actual table name. </p>\n\n<pre><code>SUM(\n (\n SELECT ((CLOCK_OUT - X) * 24) * 60\n FROM Your_Table_Name\n WHERE CLOCK_IN < X AND X < CLOCK_OUT AND CLOCK_OUT < Y\n OR X < CLOCK_IN AND CLOCK_OUT = Y\n OR X = CLOCK_IN AND CLOCK_OUT < Y\n )\n +\n (\n SELECT ((Y - CLOCK_IN) * 24) * 60\n FROM Your_Table_Name\n WHERE X < CLOCK_IN AND CLOCK_IN < Y AND Y < CLOCK_OUT\n OR X < CLOCK_IN AND CLOCK_IN < CLOCK_OUT AND CLOCK_OUT < Y\n )\n +\n (\n SELECT 60\n FROM Your_Table_Name\n WHERE CLOCK_IN < X AND Y = CLOCK_OUT\n OR CLOCK_IN = X AND Y < CLOCK_OUT\n OR CLOCK_IN < X AND X < Y AND Y < CLOCK_OUT\n OR X = CLOCK_IN AND Y = CLOCK_OUT\n )\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-01T23:08:39.830",
"Id": "52229",
"ParentId": "28993",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T18:50:07.103",
"Id": "28993",
"Score": "4",
"Tags": [
"sql",
"datetime",
"ms-access"
],
"Title": "Time spent by product in process represented by clockin and clock out"
}
|
28993
|
<p>I'm just looking for feedback on correctness of my understanding of async/await. I'm curious about the <code>Task.Run</code> inside of the <code>StartReceive()</code> method. Resharper (or maybe just the compiler) warns against doing this without an await, but I think in this case, it's ok.</p>
<p>After running, one can connect by telnetting to localhost 7776.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace ChatTutorial.ConsoleServer
{
class Program
{
static void Main(string[] args)
{
try
{
var server = new ChatServer();
server.Start();
Console.WriteLine("Listening....");
Console.ReadLine();
}
catch (Exception ex)
{
Logger.PrintException(ex, "Main");
}
}
}
internal class ChatServer
{
private readonly TcpListener _listener = new TcpListener(IPAddress.Parse("0.0.0.0"), 7776);
private readonly Dictionary<string, LocalClient> _clients = new Dictionary<string, LocalClient>();
public async void Start()
{
try
{
_listener.Start();
while (true)
{
try
{
Console.WriteLine("Listening...");
var client = await _listener.AcceptTcpClientAsync();
Console.WriteLine("Client connected");
var id = Guid.NewGuid().ToString();
_clients.Add(id, new LocalClient(client, ReceivedMessage, ClientClosed, id));
}
catch (Exception ex)
{
Console.WriteLine("Start() While() '{0}', '{1}'", ex.Message, ex.StackTrace);
}
}
}
catch (Exception ex)
{
Logger.PrintException(ex, "Start");
}
}
public void ClientClosed(string id)
{
Console.WriteLine("Client {0} disconnected", id);
var client = _clients[id];
_clients.Remove(id);
client.Close();
Console.WriteLine("Client {0} Closed", id);
ReceivedMessage("Client disconnected", id);
}
public void ReceivedMessage(string message, string id)
{
try
{
var clientsToRemove = new List<string>();
foreach (var client in _clients)
{
if (client.Value != null && client.Value.Client.Connected)
{
if (client.Key != id)
client.Value.Send(id + "> " + message);
}
else
clientsToRemove.Add(client.Key);
}
foreach (var client in clientsToRemove)
_clients.Remove(client);
}
catch (Exception ex)
{
Logger.PrintException(ex, "ReceivedMessage");
}
}
internal class LocalClient
{
private readonly TcpClient _client;
public TcpClient Client { get { return _client; } }
private readonly Action<string> _closedCallback;
private readonly Action<string,string> _recvCallback;
private readonly StreamReader _reader;
private readonly StreamWriter _writer;
private readonly string _id;
public string Id { get { return _id; } }
public LocalClient(TcpClient client, Action<string,string> recvCallback, Action<string> closedCallback, string id)
{
_closedCallback = closedCallback;
try
{
_client = client;
_recvCallback = recvCallback;
_id = id;
_reader = new StreamReader(_client.GetStream());
_writer = new StreamWriter(_client.GetStream()) {AutoFlush = true};
StartReceive();
Console.WriteLine("Local client {0} receiving...", id);
}
catch (Exception ex)
{
Logger.PrintException(ex, "LocalClient");
}
}
public async void StartReceive()
{
try
{
while (true)
{
var message = await _reader.ReadLineAsync();
if (String.IsNullOrEmpty(message))
{
Task.Run(() => _closedCallback(_id));
return;
}
_recvCallback(message, _id);
Console.WriteLine("{0} > {1}", _id, message);
}
}
catch (Exception ex)
{
Logger.PrintException(ex, "StartReceive");
}
}
public void Close()
{
if (_reader != null)
_reader.Dispose();
}
public async void Send(string message)
{
try
{
if (String.IsNullOrEmpty(message)) return;
await _writer.WriteLineAsync(message);
}
catch (Exception ex)
{
Logger.PrintException(ex, "Send");
}
}
}
}
public static class Logger
{
public static void PrintException(Exception ex, string methodName)
{
Console.WriteLine("{0}: \n '{1}' \n '{2}'", methodName, ex.Message, ex.StackTrace);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-03T11:00:05.737",
"Id": "54017",
"Score": "0",
"body": "Is v3 is the final version of basic chat server? I would like to use it as my basis of scalable/robust client server application. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-04T18:20:58.973",
"Id": "54145",
"Score": "1",
"body": "It is. If you really want the highest performance for a server, you'll have to use SocketAsyncEventArgs, which use IOCP (I/O Completion Port). [C# SocketAsyncEventArgs](http://www.codeproject.com/Articles/83102/C-SocketAsyncEventArgs-High-Performance-Socket-Cod). I believe Stephen Cleary or Stephen Toub has examples on using async/await in conjunction with SocketAsyncEventArgs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-08T12:01:00.340",
"Id": "86507",
"Score": "0",
"body": "What happens when multiple clients sends messages at the same time, wouldn't there be concurrent calls to Client.Send Method? Can the streamwriter handle that? Because I am having problem with that but i use the SSLstream.WriteAsync directly."
}
] |
[
{
"body": "<pre><code>static void Main(string[] args)\n</code></pre>\n\n<p>If you're not using <code>args</code>, you can just remove them: <code>static void Main()</code>.</p>\n\n<pre><code>server.Start();\nConsole.WriteLine(\"Listening....\");\nConsole.ReadLine();\n</code></pre>\n\n<p>Running a server until Enter is pressed like this might be okay in a testing application, but not in a production-quality one. Probably the biggest problem with this is that you don't give the worker thread any chance to complete the current operation or to perform cleanup.</p>\n\n<p>To fix that, you could change your application into a Windows service. Or you could use a <code>CancellationToken</code> that's somehow triggered by the user's action and then wait for the whole <code>Task</code> to complete.</p>\n\n<pre><code>catch (Exception ex)\n{\n Logger.PrintException(ex, \"Main\");\n}\n</code></pre>\n\n<p>I don't see the point of this in your <code>Main()</code>. I can't think of any situation where this <code>catch</code> would be triggered.</p>\n\n<p>Also, since you're using C# 5.0, you could use <a href=\"http://msdn.microsoft.com/en-us/library/hh534540.aspx\" rel=\"nofollow\">caller information</a> to avoid having to spell out the name of the current method.</p>\n\n<pre><code>new TcpListener(IPAddress.Parse(\"0.0.0.0\"), 7776)\n</code></pre>\n\n<p>According to the documentation, you should use <code>IPAddress.Any</code> if you don't want to specify which IP address to use. That is equivalent to your code (<code>Any</code> returns 0.0.0.0), but I think using <code>Any</code> would make your code clearer.</p>\n\n<pre><code>public async void Start()\n</code></pre>\n\n<p>Normally, you should use <code>async void</code> methods only in event handlers and nowhere else. I guess it could be considered okay here (since you log all exceptions from this method), assuming you don't care about the cleanup problems I mentioned above.</p>\n\n<pre><code>public void ClientClosed(string id)\n</code></pre>\n\n<p>I don't see any reason to use just <code>id</code> here. Instead, the parameter of this method should be the <code>LocalClient</code> directly.</p>\n\n<pre><code>_clients.Remove(id);\n</code></pre>\n\n<p>This line could be run in parallel with other calls to <code>Remove()</code> or with the call to <code>Add()</code> in <code>Start()</code>, which means the code is not thread-safe. You should either use locking or use <code>ConcurrentDictionary</code> instead of normal <code>Dictionary</code>.</p>\n\n<pre><code>foreach (var client in _clients)\n{\n if (client.Value != null && client.Value.Client.Connected)\n</code></pre>\n\n<p>This is very confusing naming. Here, <code>client</code> is not any kind of client, it's a <code>KeyValuePair<LocalClient></code>. And <code>client.Value.Client</code> is a <code>TcpClient</code>, which is not clear from the name at all. I would suggest you to rename <code>LocalClient</code> to something else. If you think that it's the best name you can come up with, use names to make the distinction between <code>LocalClient</code> and <code>TcpClient</code> clear.</p>\n\n<hr>\n\n<p>There are probably other issues with the rest of the code, but this is where I stopped looking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T09:41:24.400",
"Id": "29017",
"ParentId": "29000",
"Score": "4"
}
},
{
"body": "<p>As the latecomer to the party, I'll take it from V3...</p>\n\n<p>First, <code>async void</code> should only be used for event handlers. I'd much rather see <code>Start</code> return a <code>Task</code> representing the listening loop.</p>\n\n<p>For a simple example, you don't need to do any cleanup at all. Once your app exits, the OS will clean up after it. Doing cleanup just before application exit is just a waste of effort.</p>\n\n<p>If you <em>do</em> want to cleanly stop an asynchronous system, you should be using <code>CancellationToken</code> - create a CTS in <code>Main</code> and then pass the token to <code>Start</code>. From there things get tricky, as many operations (such as <code>AcceptTcpClientAsync</code>) do not take a <code>CancellationToken</code>. There's an old trick in Windows programming where you can close the underlying handle (in this case, <code>Stop</code> the <code>TcpListener</code>) which will cause any outstanding asynchronous operations on that handle to complete with an error.</p>\n\n<p>On a side note, it is almost impossible to shut down a socket <em>without</em> seeing exceptions; the general rule of thumb is that once you decide to shut down, just ignore all errors until it's done.</p>\n\n<p>You can find out more about socket programming in my <a href=\"http://blog.stephencleary.com/2009/04/tcpip-net-sockets-faq.html\">TCP/IP .NET Sockets FAQ</a>. However, I highly recommend that you find another sample project to explore <code>async</code> and <code>await</code> (if you like to learn by example, there's a good tutorial built in to LINQPad). There is no such thing as a \"simple\" TCP/IP chat server. I've had many people ask me for sample <code>async</code> socket code, but I haven't given any out for a very simple reason: it's not as hard as it used to be, but it's still <em>really hard</em> to get right!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T03:31:47.070",
"Id": "45793",
"Score": "0",
"body": "Appreciate the response! I fiddled with trying to clean-up cleanly for a while, it's good to know that that's the way it is. Do you seen any issue's with the set it and forget it callback within a Task in StartReceive()?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T01:09:53.910",
"Id": "29045",
"ParentId": "29000",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T23:21:16.837",
"Id": "29000",
"Score": "11",
"Tags": [
"c#",
"task-parallel-library",
"socket",
"async-await",
"tcp"
],
"Title": "Console chat server"
}
|
29000
|
<p>Ramer-Douglas-Peucker is a great algorithm for reducing the number of samples in a given trace, and also for keeping its general shape (as much as he can).</p>
<p>I have a trace with 32.000.000 samples, and I want to compute a reduced version in order to be able to plot it into my winform application.</p>
<p>The first time I used <a href="http://www.codeproject.com/Articles/18936/A-C-Implementation-of-Douglas-Peucker-Line-Approxi" rel="nofollow">this implementation</a>, time execution was about ~3mn on 32M samples, and the reduced version has 450K samples with Tolerance = 12, and the shape was amazingly preserved.</p>
<p>I tried to improve it, and the time execution is now about ~14sec.</p>
<ul>
<li>Getting rid of Math.Pow made me win 121sec...</li>
<li>Using unsafe code + pointers --> -17sec</li>
<li>Splitting the work into different threads --> -28sec (on a Core 2 Duo)</li>
</ul>
<p>Someone could maybe tell me if there is a way to go faster?</p>
<pre><code>public class RDPWorker
{
public int start;
public double Tolerance;
public volatile float[] samples;
public List<int> samplesToKeep;
public void DoWork()
{
int h = samples.Length / 2;
float[] half = new float[h];
unsafe
{
fixed (float* ptr = samples, ptrH = half)
{
float* _half = ptrH;
for (int i = start; i < h; ++i)
*(_half) = *(ptr + i);
}
}
FilterUtils.DouglasPeuckerReduction(half, 0, h - 1, Tolerance, ref samplesToKeep);
}
}
//[...]
//Piece of my FilterUtils class
public static float[] DouglasPeuckerReduction(float[] points, Double Tolerance)
{
if (points == null || points.Length < 3)
return points;
int firstPoint = 0;
int lastPoint = 0;
List<int> pointIndexsToKeep = new List<int>();
pointIndexsToKeep.Add(firstPoint);
pointIndexsToKeep.Add(lastPoint);
int h = points.Length / Environment.ProcessorCount;
List<RDPWorker> workers = new List<RDPWorker>();
List<Thread> threads = new List<Thread>();
int cpu = 0;
while (cpu < Environment.ProcessorCount)
{
RDPWorker _w = new RDPWorker();
_w.samplesToKeep = new List<int>();
_w.Tolerance = Tolerance;
_w.start = h * cpu;
_w.samples = points;
workers.Add(_w);
++cpu;
}
Stopwatch sw = new Stopwatch();
sw.Start();
foreach (RDPWorker worker in workers)
{
Thread t = new Thread(worker.DoWork);
t.IsBackground = true;
threads.Add(t);
t.Start();
}
foreach (Thread thread in threads)
thread.Join();
sw.Stop();
Console.WriteLine("Time = " + sw.ElapsedMilliseconds + " ms");
threads.Clear();
threads = null;
foreach (RDPWorker worker in workers)
pointIndexsToKeep = pointIndexsToKeep.Concat(worker.samplesToKeep).ToList();
workers.Clear();
workers = null;
int l = pointIndexsToKeep.Count;
float[] returnPoints = new float[l];
pointIndexsToKeep.Sort();
unsafe
{
fixed (float* ptr = points, result = returnPoints)
{
float* res = result;
for (int i = 0; i < l; ++i)
*(res + i) = *(ptr + pointIndexsToKeep[i]);
}
}
pointIndexsToKeep.Clear();
pointIndexsToKeep = null;
return returnPoints;
}
internal static void DouglasPeuckerReduction(float[] points, int firstPoint, int lastPoint, Double tolerance, ref List<int> pointIndexsToKeep)
{
float maxDistance = 0, tmp = 0, area = 0, X = 0, Y = 0, bottom = 0, distance = 0;
int indexFarthest = 0;
unsafe
{
fixed (float* samples = points)
{
for (int i = firstPoint; i < lastPoint; ++i)
{
//Perpendicular distance
tmp = 0.5f * ((lastPoint - i) * (firstPoint - i) + (*(samples + lastPoint) - *(samples + i)) * (*(samples + firstPoint) - *(samples + i)));
//Abs
area = tmp < 0 ? -tmp : tmp;
X = (firstPoint - lastPoint);
Y = (*(samples + firstPoint) - *(samples + lastPoint));
bottom = Sqrt((X * X) + (Y * Y));
distance = area / bottom;
if (distance > maxDistance)
{
maxDistance = distance;
indexFarthest = i;
}
}
}
}
if (maxDistance > tolerance && indexFarthest != 0)
{
//Add the largest point that exceeds the tolerance
pointIndexsToKeep.Add(indexFarthest);
DouglasPeuckerReduction(points, firstPoint, indexFarthest, tolerance, ref pointIndexsToKeep);
DouglasPeuckerReduction(points, indexFarthest, lastPoint, tolerance, ref pointIndexsToKeep);
}
}
//http://blog.wouldbetheologian.com/2011/11/fast-approximate-sqrt-method-in-c.html
internal static float Sqrt(float z)
{
if (z == 0) return 0;
FloatIntUnion u;
u.tmp = 0;
u.f = z;
u.tmp -= 1 << 23; /* Subtract 2^m. */
u.tmp >>= 1; /* Divide by 2. */
u.tmp += 1 << 29; /* Add ((b + 1) / 2) * 2^m. */
return u.f;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T00:52:30.423",
"Id": "45681",
"Score": "1",
"body": "wow, I did not even know you could do float* in c#"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T10:16:42.090",
"Id": "45732",
"Score": "0",
"body": "Yep I used unsafe code and pointers http://msdn.microsoft.com/en-us/library/vstudio/t2yzs44b.aspx"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-09-26T21:34:16.783",
"Id": "394193",
"Score": "0",
"body": "I just have a minor comment probably not worth an answer. Instead of creating threads the one liner `Parallel.ForEach(workers, w => w.DoWork());` would be as effective. Though it would not improve performance. Also your `Clear` and null assignments are not needed."
}
] |
[
{
"body": "<p>You could initialize the capacity of the lists (via the constructor) you are generating. The closer you can get to the size the list will be after all points are added the better. </p>\n\n<p>The reason you would do this is that the list implementation is just a wrapper around an array starting at some size. Every time you add an item to the list it first checks to see if the array has enough space and, if not, it will create a new larger array, copy the contents from the array that is full, and add your new item. It is pretty standard for the size of the array to double each time it is resized. The resizing is expensive, so setting the capacity to something close to the total number of items that it will contain can improve performance.</p>\n\n<p>Also, be sure not to set the capacity too high, you can end up wasting a good bit of memory that way (if that is a concern.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:06:23.240",
"Id": "45899",
"Score": "0",
"body": "Hi,\nthanks for your suggestion.\n\nI tried to make the size of Lists fixed but I didn't notice any improvement in the time execution.\n\nRDP is fast with smaller set of data. May be I have to apply another filtering method before, in order to reduce a little bit the number of samples, I don't know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T12:40:03.387",
"Id": "45908",
"Score": "0",
"body": "To do so, I know that with tolerance = 12, RDP reduces my trace from 32.000.000 --> 450.052 samples, which is perfect for me. Thus I try to use array of the same size instead of using List<float>. But it \"just\" made me win ~150ms :)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:39:44.257",
"Id": "29041",
"ParentId": "29002",
"Score": "3"
}
},
{
"body": "<p>The best way I could imagine is, to use loops and stacks to implement the DouglasPeuckerReduction function. A plain recursion, though simple to implement, isn't so efficient in terms of speed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-26T22:09:28.690",
"Id": "79263",
"Score": "0",
"body": "Recursion is quite efficient. Poor implementation of stack can be worse than recursion. In fact this is a matter of time measurement. Although there is also risk of stack overflow when using recursion"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-21T03:27:47.230",
"Id": "39714",
"ParentId": "29002",
"Score": "1"
}
},
{
"body": "<p>There maybe two mistakes in the algorithm. One is line 4 of DouglasPeuckerReduction algorithm, that the lastPoint should be equal to points.length, and another is in line 1 of the \"dowork\" function. although the algorithm is much faster than its previous version, its correctness is quite low especially in spatial data compression.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-17T08:39:34.590",
"Id": "47447",
"ParentId": "29002",
"Score": "1"
}
},
{
"body": "<p>Note that the algorithm only ever <strong>compares</strong> distances never using their actual value.</p>\n\n<p>This means that you can speed up your algorithm significantly by directly comparing the <em>squares</em> of the distances instead. This works because the <code>sqrt</code> function is monotonic and thus <code>sqrt(a) < sqrt(b)</code> if and only if <code>a < b</code>.</p>\n\n<p>This allows to change your <code>DouglasPeuckerReduction()</code> function to this:</p>\n\n<pre><code>internal static void DouglasPeuckerReduction(float[] points, int firstPoint, int lastPoint, Double toleranceSquared, ref List<int> pointIndexsToKeep)\n{\n float maxDistanceSquared = 0, tmp = 0, areaSquared = 0, X = 0, Y = 0, bottomSquared = 0, distanceSquared = 0;\n int indexFarthest = 0;\n\n unsafe\n {\n fixed (float* samples = points)\n {\n for (int i = firstPoint; i < lastPoint; ++i)\n {\n //Perpendicular distance \n tmp = 0.5f * ((lastPoint - i) * (firstPoint - i) + (*(samples + lastPoint) - *(samples + i)) * (*(samples + firstPoint) - *(samples + i)));\n //Abs\n areaSquared = tmp * tmp;\n X = (firstPoint - lastPoint);\n Y = (*(samples + firstPoint) - *(samples + lastPoint));\n bottomSquared = X * X + Y * Y;\n distanceSquared = areaSquared / bottomSquared;\n\n if (distanceSquared > maxDistanceSquared)\n {\n maxDistanceSquared = distanceSquared;\n indexFarthest = i;\n }\n }\n }\n }\n\n if (maxDistanceSquared > toleranceSquared && indexFarthest != 0)\n {\n //Add the largest point that exceeds the tolerance\n DouglasPeuckerReduction(points, firstPoint, indexFarthest, toleranceSquared, ref pointIndexsToKeep);\n pointIndexsToKeep.Add(indexFarthest);\n DouglasPeuckerReduction(points, indexFarthest, lastPoint, toleranceSquared, ref pointIndexsToKeep);\n }\n}\n</code></pre>\n\n<p>and call it with the tolerance squared and you'll get the same result in almost half the time. Note that your special <code>Sqrt</code> function is not used anymore and can now be removed.</p>\n\n<p>Also note that I changed the order in which the <code>pointsToKeep</code> list is populated in the last three lines. This adds the indices in order and allows you to remove the sorting step in line 83 which should also save you some time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-28T08:34:50.380",
"Id": "68155",
"ParentId": "29002",
"Score": "6"
}
},
{
"body": "<p>Use <code>var</code> during local variable declarations when the right-hand side makes the type obvious. This saves you extra typing every time you want to change type. You should also use <code>var</code> when declaring loop index.</p>\n\n<p>Single-letter variables, unless used in loop indices, are needlessly confusing for a maintenance programmer. Use descriptive names. There's a reason one of the first steps an obfuscator makes is to use single-letter variable names.</p>\n\n<p>Lastly, you've misspelled <code>pointIndexsToKeep</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-28T15:09:29.310",
"Id": "68191",
"ParentId": "29002",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-25T23:25:12.770",
"Id": "29002",
"Score": "7",
"Tags": [
"c#",
"performance",
"algorithm",
"multithreading",
"computational-geometry"
],
"Title": "Ramer-Douglas-Peucker algorithm"
}
|
29002
|
<p>I am trying to mimic <code>std::stack</code> in my implementation (just the basic interface - no iterators / allocators). Since I was having trouble handling all the memory allocation/deallocation, I read <a href="https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom">this</a>.</p>
<p>Although my implementation seems to work flawlessly, I'm still not confident about these things: </p>
<ol>
<li>There is no memory-leak</li>
<li>All the routines are fully performance and space-optimized</li>
<li>My usage of Copy-and-Swap idiom is correct</li>
<li>There isn't any better way of displaying the contents of a stack (see the overloaded <code>operator<<</code>).</li>
</ol>
<p>Could you please review it to see if it could be improved? </p>
<pre><code>using namespace std;
template<typename T> struct mystack_node // The data structure for representing the "nodes" of the stack
{
T data;
mystack_node *next;
};
template<typename T> class mystack;
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a);
template<typename T> class mystack
{
unsigned int stack_size; // A variable keeping the record of number of nodes present in the stack
mystack_node<T> *stack_top; // A pointer pointing to the top of the stack
void mystack_swap(mystack &a,mystack &b) // Swap function used in the assignment operator ( Copy-and-Swap Idiom )
{
swap(a.stack_size,b.stack_size);
swap(a.stack_top,b.stack_top);
}
public:
mystack():stack_size(0),stack_top(NULL) {} // Default Constructor
mystack(const mystack& other):stack_size(0),stack_top(NULL) // Copy constructor
{
int i=0;
vector<T> vec(other.stack_size); // A vector for storing a backup of all the nodes in the "other" stack
mystack_node<T> *temp=other.stack_top;
while(temp!=NULL)
{
vec[i++]=temp->data;
temp=temp->next;
}
for(i=(int)vec.size()-1; i>=0; i--)
{
push(vec[i]);
}
}
~mystack() // Destructor
{
mystack_node<T> *temp=stack_top;
while(temp!=NULL)
{
temp=temp->next;
delete stack_top;
stack_top=temp;
}
}
mystack& operator = (mystack other) // Assignment operator
{
mystack_swap(*this,other);
return *this;
}
void push(const T &val) // Add a new node to the stack
{
mystack_node<T> *temp=new mystack_node<T>;
temp->data=val;
temp->next=stack_top;
stack_top=temp;
stack_size++;
}
void pop() // Remove the "top" node from the stack
{
if(stack_top!=NULL) // Don't do anything if the stack is already empty
{
mystack_node<T> *temp=stack_top->next;
delete stack_top;
stack_top=temp;
stack_size--;
}
}
unsigned int size() // Returns the number of nodes in the stack
{
return stack_size;
}
bool empty() // Returns whether if the stack is empty or not
{
return stack_size==0;
}
T top() // Returns the "top" node from the stack
{
return (*stack_top).data; // Deliberately left Out-of-Bound exception checking...
}
friend ostream& operator << <T> (ostream&,const mystack&);
};
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a) // Output operator to show the contents of the stack
{
mystack_node<T> *temp=a.stack_top;
while(temp!=NULL)
{
out<<temp->data<<" ";
temp=temp->next;
}
return out;
}
</code></pre>
<p><strong>EDIT:</strong></p>
<ol>
<li>Made <code>size()</code>, <code>empty()</code> and <code>top()</code> as <code>const</code> functions.</li>
<li>Changed the type of <code>stack_size</code> from <code>unsigned int</code> to <code>size_t</code>.</li>
<li>Defined <code>struct mystack_node</code>in the private section of <code>class mystack</code> so that it is inaccessible to any other part of the code.</li>
</ol>
<p></p>
<pre><code>using namespace std;
template<typename T> class mystack;
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a);
template<typename T> class mystack
{
struct mystack_node // The data structure for representing the "nodes" of the stack
{
T data;
mystack_node *next;
};
size_t stack_size; // A variable keeping the record of number of nodes present in the stack
mystack_node *stack_top; // A pointer pointing to the top of the stack
void mystack_swap(mystack &a,mystack &b) // Swap function used in the assignment operator ( Copy-and-Swap Idiom )
{
swap(a.stack_size,b.stack_size);
swap(a.stack_top,b.stack_top);
}
public:
mystack():stack_size(0),stack_top(NULL) {} // Default Constructor
mystack(const mystack& other):stack_size(0),stack_top(NULL) // Copy constructor
{
int i=0;
vector<T> vec(other.stack_size); // A vector for storing a backup of all the nodes in the "other" stack
mystack_node *temp=other.stack_top;
while(temp!=NULL)
{
vec[i++]=temp->data;
temp=temp->next;
}
for(i=(int)vec.size()-1; i>=0; i--)
{
push(vec[i]);
}
}
~mystack() // Destructor
{
mystack_node *temp=stack_top;
while(temp!=NULL)
{
temp=temp->next;
delete stack_top;
stack_top=temp;
}
}
mystack& operator = (mystack other) // Assignment operator
{
mystack_swap(*this,other);
return *this;
}
void push(const T &val) // Add a new node to the stack
{
mystack_node *temp=new mystack_node;
temp->data=val;
temp->next=stack_top;
stack_top=temp;
stack_size++;
}
void pop() // Remove the "top" node from the stack
{
if(stack_top!=NULL) // Don't do anything if the stack is already empty
{
mystack_node *temp=stack_top->next;
delete stack_top;
stack_top=temp;
stack_size--;
}
}
size_t size() const // Returns the number of nodes in the stack
{
return stack_size;
}
bool empty() const // Returns whether if the stack is empty or not
{
return stack_size==0;
}
T top() const // Returns the "top" node from the stack
{
return (*stack_top).data; // Deliberately left Out-of-Bound exception checking...
}
friend ostream& operator << <T> (ostream&,const mystack&);
};
template<typename T>ostream& operator <<(ostream& out,const mystack<T> &a) // Output operator to show the contents of the stack
{
typename mystack<T>::mystack_node *temp=a.stack_top;
while(temp!=NULL)
{
out<<temp->data<<" ";
temp=temp->next;
}
return out;
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>You may run a high risk of memory leaks when using raw structures, especially with pointers. Memory-management is not one of my strong points, so I won't say too much about that. For learning purposes, you should be okay as long you maintain good habits (accompany each <code>new</code> with <code>delete</code>, etc).</p></li>\n<li><p>Memory-management still plays a big role here, considering your stack is dynamic (as it lacks a <code>full()</code> and uses nodes). Again, watch your memory and pointer usage.</p></li>\n<li><p>Based on <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">this</a>, I think you're using it correctly.</p></li>\n<li><p>With a linked list type structure, that may be as good as you can get it. For a dynamically-allocated array, on the other hand, you would just loop through it. Overall, you won't attain superb data output unless you use iterators. This is okay for a basic implementation, though.</p></li>\n</ol>\n\n<hr>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Do not use <code>using namespace std</code></a>.</p></li>\n<li><p>The <code>class</code> declarations and implementations should be noticeably separate, even if they're in one file. I had to scrounge for that <code>};</code> to see where your declarations ended. Generally, you may still keep your accessors and mutators within the declarations as they'll automatically become <code>inline</code>.</p></li>\n<li><p>The node <code>struct</code> should be kept <code>private</code> within your class since it's a data member and shouldn't be exposed.</p></li>\n<li><p>If you're using C++11, use <code>nullptr</code> instead of <code>NULL</code>.</p></li>\n<li><p>You're not technically putting anything into your output stream. Yours is called <code>out</code>, but you're still using <code>std::cout</code>.</p></li>\n<li><p>Your accessors (<code>size()</code>, <code>empty()</code>, and <code>top()</code>) should be declared with <code>const</code> since they just <code>return</code> data members:</p>\n\n<pre><code>unsigned int size() const\n</code></pre></li>\n<li><p><code>size()</code> should return a <code>std::size_t</code>. This is located in <code><cstddef></code>.</p></li>\n<li><p>If you're keeping careful track of <code>stack_size</code>, <code>pop()</code> could just check if the stack size is zero (using <code>empty()</code>).</p></li>\n</ul>\n\n<p><strong>Follow-up on comments:</strong></p>\n\n<ol>\n<li><p><code>full()</code> was just my name for a common <code>bool</code> function for determining if a static structure has reached its maximum size. With a dynamic structure like yours, this is not needed.</p></li>\n<li><p>Consider this piece of code:</p>\n\n<pre><code>for (auto iter = container.cbegin(); iter != container.cend(); ++iter)\n{\n std::cout << *iter;\n}\n</code></pre>\n\n<p>This is one of a few C++11 ways of iterating through an STL storage container (such as <code>std::vector</code>). Here, let <code>structure</code> be a name of such container and <code>iter</code> an iterator of this container (defined within the implementation). These containers are designed in such a way that, if utilized correctly, you will avoid runtime errors with them. In this case, using iterators <em>instead of indices</em> ensures that you'll not go out-of-bounds when accessing the container.</p></li>\n<li><p>You simply need to move it to the <code>private</code> section of the class. In order for <code>operator<<</code> to recognize your data members, declare it a <code>friend</code> and put it inside the class. This particular operator doesn't belong to any one <code>class</code>, so you also cannot declare it as part of your own <code>class</code> with the <code>::</code> operator (in case you were curious). There's plenty of info on all these <code>operator</code>s, so read up!</p></li>\n<li><p>In and of itself, I don't think so. The reason I've mentioned dynamically-allocated arrays is because stack elements aren't accessed the same way as linked lists. The former deals with popping data from the top, whereas the former can have any node removed anywhere within the structure. However, you're not wrong about using a linked list; it's still another way to implement a stack.</p></li>\n<li><p>Not a huge difference, but I think it's a bit more readable with <code>empty()</code>. With linked lists, <code>NULL</code> is necessary for determining if the list head is pointing to a node (not empty) or the <code>NULL</code> address (empty). Overall, I'd say it's up to you. Again, you should make sure that your element count is maintained, otherwise you'll have problems.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T01:45:01.297",
"Id": "45690",
"Score": "0",
"body": "`op=` taking a parameter by value and then swapping it is the copy-and-swap idiom he is talking about. It should be like he wrote."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T01:46:03.863",
"Id": "45691",
"Score": "0",
"body": "@Lstor: Oh, right. Forgot about that. I'm still working on my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:32:00.897",
"Id": "45698",
"Score": "0",
"body": "@Jamal Thanks for taking the time to review my code!!.. Your answer was very helpful.However,I am not able to understand few things in it -: 1). What is this `full` you are talking about?? 2). How can iterators be used to improve the output process?? 3). Could you please show me a demo on how to make `mystack_node` as a private struct of `mystack`?? [ I tried to shift the structure inside the class (as a normal struct and not as a template ), but then the output operator wasn't able to see `mystack_node *temp`!! ( and i don't know how to fix it )]"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:39:06.147",
"Id": "45700",
"Score": "0",
"body": "@AnmolSinghJaggi: I'll follow-up on this right now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:40:51.847",
"Id": "45701",
"Score": "0",
"body": "Some other things too! -: 4). Will there be any performance gain if i use a dynamic array instead of a \"linked list type structure\"?? ( besides the 3x performance gain in the copy constructor) 5). What difference does it make if I use `empty()` instead of comparison with `NULL`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T04:38:11.963",
"Id": "45711",
"Score": "3",
"body": "@AnmolSinghJaggi `std::stack` is by default implemented on top of a `std::deque`, which uses an array. (C++11 standard section 23.3.3.1.1: *A deque is a sequence container that, like a* `vector` *, supports random access iterators.*) Using an array gives locality of reference, random access (accessing index *n* is `O(1)` instead of `O(n)`), and so on."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T01:41:15.707",
"Id": "29005",
"ParentId": "29003",
"Score": "5"
}
},
{
"body": "<p>The recommended swap function implementation is as a <code>friend</code> named <code>swap</code> (<a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom</a>)</p>\n\n<pre><code>public:\n...\nfriend void swap(mystack &a, mystack &b)\n{\n using std::swap;\n\n swap(a.stack_size, b.stack_size);\n swap(a.stack_top, b.stack_top);\n}\n</code></pre>\n\n<p>And the assignment operator is:</p>\n\n<pre><code>mystack& operator= (mystack other)\n{\n using std::swap;\n\n swap(*this, other);\n return *this;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:15:16.593",
"Id": "45696",
"Score": "0",
"body": "I'd like to emphasize that `::swap(mystack&, mystack&)` is still an external function and *not* a member function, **even though it is defined within the class definition**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:44:09.600",
"Id": "45702",
"Score": "0",
"body": "@William Thanks for reviewing my code. But could you please explain what difference does it make whether i make `swap()` a friend or a private function??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:58:43.453",
"Id": "45704",
"Score": "0",
"body": "@Lstor I am unable to fathom why `swap` isn't a member function. Would you care to explain in a little more depth??"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T04:26:12.950",
"Id": "45709",
"Score": "0",
"body": "Section 11.3.6 of the C++11 standard states: *A function can be defined in a* `friend` *declaration of a class [iff] the class is a non-local class, the function name is unqualified, and the function has namespace scope.* The easiest way to tell is because it has `friend` in front. [See this demonstration](http://codepad.org/BBNKtaE9) (remove line #14 to get it to compile)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T04:53:50.777",
"Id": "45712",
"Score": "0",
"body": "@Lstor I know that a friend function is not a member function! But I haven't declared swap as a friend function!! ( It is declared as `swap(mystack&, mystack&)` and not as `friend swap(mystack&, mystack&)` ). The only function which is declared as friend in my code is the `operator <<`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T07:28:14.343",
"Id": "45723",
"Score": "0",
"body": "@AnmolSinghJaggi I am talking about the `swap` in @WilliamMorris' answer (which is why it was posted as a comment to his answer)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T07:43:14.123",
"Id": "45724",
"Score": "0",
"body": "@Lstor oops! :P Thanks for the help anyways!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T11:51:23.467",
"Id": "45736",
"Score": "1",
"body": "See http://stackoverflow.com/questions/5695548/public-friend-swap-member-function"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T02:41:51.187",
"Id": "29007",
"ParentId": "29003",
"Score": "7"
}
},
{
"body": "<p>Based on <code>Edit 2</code>:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't do this</a>:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>The <code>mystack_node</code> may be a structure. But it can still have members and construcors. If you add a constructor you will make your life simpler in the add or push below.</p>\n\n<pre><code> struct mystack_node // The data structure for representing the \"nodes\" of the stack\n {\n T data;\n mystack_node *next;\n\n // Add\n mystack_node(T const& d, mystack_node* n)\n : data(d)\n , next(n)\n {}\n };\n</code></pre>\n\n<p>As noted elsewhere. Defined a standard swap function: <a href=\"https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom\">https://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom</a></p>\n\n<pre><code> void mystack_swap(mystack &a,mystack &b)\n</code></pre>\n\n<p>The copy constructor is broken.<br>\nYou copy the data into a local vector then don't do anything with it.</p>\n\n<pre><code> mystack(const mystack& other):stack_size(0),stack_top(NULL)\n</code></pre>\n\n<p>You are on the correct line when you try an make it exception safe with a vector. But you don't need to go so far. You just need to make sure if there is an exception during the copy that you free any allocated memory. Note if an exception is thrown from the constructor then the destructor will not be called.</p>\n\n<p>As you only have a singly linked list I would use recursion to track the copy.</p>\n\n<pre><code> mystack(const mystack& other)\n : stack_size(0)\n , stack_top(NULL)\n {\n try\n {\n recursive_copy(other.stack_top);\n stack_size = other.stack_size;\n }\n catch(...)\n {\n // If there is an exception\n // Release all resources then\n // let the exception continue to propagate.\n release_stack();\n throw;\n } \n }\n\n void recursive_copy(mystack_node* head)\n {\n if (head == NULL)\n { return;\n }\n // Recursively go to the end of the list\n recursive_copy(head->next);\n\n // On your way back up.\n // Build each node onto the stack.\n stack_top = new mystack_node(head.data, stack_top);\n }\n</code></pre>\n\n<p>In the destructor I would have used a <code>for(;;)</code> loop. That way you can put all the control in one place. Since the constructor now can potentially relase also use the same function as the constructor.</p>\n\n<pre><code> ~mystack() // Destructor\n {\n release_stack();\n }\n\n release_stack() noexcept /* or C++03 throws() */\n {\n mystack_node* next;\n for(mystack_node* loop=stack_top; loop; loop = next)\n {\n next =loop->next;\n delete loop;\n }\n }\n</code></pre>\n\n<p>By adding the constructor to <code>mystack_node</code> the push becomes much more readable.</p>\n\n<pre><code> void push(const T &val) // Add a new node to the stack\n {\n stack_top = new mystack_node(val, stack_top);\n stack_size++;\n }\n</code></pre>\n\n<p>Since you do not have control of the type T. You must assume that all calls to its methods are not exception safe. This includes the destructor. This means you need to write your code so that your object is fully mutated before calling an exception unsafe method.</p>\n\n<pre><code> void pop() // Remove the \"top\" node from the stack\n {\n if(stack_top!=NULL) // Don't do anything if the stack is already empty\n {\n mystack_node* oldTop = stack_top;\n stack_top=stack_top->next;\n stack_size--;\n\n // Put the delete at the end.\n // Your object has now been fully mutated\n // Thus if the destructor throws it will not harm your object\n // by leaving it in an undefined state.\n delete oldTop;\n\n // In your old version where you called delete before modifying\n // stack_top. An exception would have left your object pointing\n // at an object that had been deleted.\n }\n }\n</code></pre>\n\n<p>Why not return a reference to the top node?</p>\n\n<pre><code> T top() const // Returns the \"top\" node from the stack\n</code></pre>\n\n<p>If you do this you probably need two versions. A const and a non cost version.</p>\n\n<pre><code> T& top(); // See below.\n T const& top() const {return const_cast<mystack>(*this).top();}\n</code></pre>\n\n<p>Rather than dereference the object then use the <code>.</code> operator. It may be best to just use the <code>-></code> operator for readability.</p>\n\n<pre><code> return (*stack_top).data;\n\n // Easier to read as:\n return stack_top->data;\n</code></pre>\n\n<p>One minor thing.</p>\n\n<pre><code> mystack_node *oldTop; // Looks very C like\n\n // In C++ it is more common to put the * on the left with the type.\n // The argument being the `*` is part of the type, and C++ is\n // all about type correctness.\n //\n // Its not a big thing and there is a lot of code your way around\n // but it is in the minority (and it helps C++ developers spot\n // C developers pretending to code in C++ :-) )\n\n mystack_node* oldTop; // More C++ like\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:06:49.497",
"Id": "45766",
"Score": "0",
"body": "Great answer!! I tried to compile my code after making the mentioned changes, but got a compiler warning regarding your `release_stack() throw()` function - `warning: for increment expression has no effect [-Wunused-value]` [my attempt](http://ideone.com/XUI6Yd)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:09:22.250",
"Id": "45767",
"Score": "0",
"body": "@AnmolSinghJaggi: Fixed a bug. Change `loop != next` to `loop = next`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:18:11.600",
"Id": "45770",
"Score": "0",
"body": "Also, in the `pop()` function, you have mentioned `// Thus if the destructor throws it will not harm your object `. I do not understand under what circumstances would a destructor throw an exception?? ( I don't have a good understanding of exception-handling )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T20:56:21.997",
"Id": "45778",
"Score": "0",
"body": "You are not supposed to throw from a destructor but you can. You do not know how `T` is implemented or even who is implementing `T`. So you must assume that they are idiots. If the destructor of T throws an exception (when you call `delete oldTop;`) then it should not affect your class."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T15:14:16.597",
"Id": "29028",
"ParentId": "29003",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29028",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T00:37:38.973",
"Id": "29003",
"Score": "7",
"Tags": [
"c++",
"optimization",
"memory-management",
"reinventing-the-wheel",
"stack"
],
"Title": "Mimicking the basic interface of std::stack"
}
|
29003
|
<p>This is my first time messing with PHP and I tried to put together a simple address book that when the user fills out the form it would update a database table, then display the row data on the page after submission.</p>
<p>It works fine, but I just want to make sure I'm headed in the right direction.</p>
<p><code>index.php</code>:</p>
<pre><code><?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// connect to database
include("inc/dbconnect.php");
// assigns form data to table columns
$assign = "INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')";
// execute query
if (mysqli_query($database,$assign)) {
header("Location:http://localhost/address-book/");
exit;
} else {
echo "Everything blew up!" . mysqli_error($database);
}
// closes database connection
mysqli_close($database);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Address Book</title>
</head>
<body>
<h1>Address Book</h1>
<table cellpadding="5" cellspacing="0">
<thead>
<tr>
<th>Contact name</th>
<th>Email address</th>
<th>Phone</th>
<th>Birth Date</th>
<tr>
</thead>
<tbody>
<?php include("inc/records.php"); ?>
</tbody>
</table>
<h3>Add new contact</h3>
<form method="post" action="index.php">
<input type="text" name="firstName" id="firstName" placeholder="First name">
<input type="text" name="lastName" id="lastName" placeholder="Last Name"><br />
<input type="text" name="email" id="email" placeholder="Email address">
<input type="text" name="phone" id="phone" placeholder="Phone"><br />
<input type="text" name="birthday" id="birthday" placeholder="Birthday">
<input type="submit" value="Save record" placeholder="Save">
</form>
</body>
</html>
</code></pre>
<p><code>dbconnect.php</code>:</p>
<pre><code>// database connect
$database = mysqli_connect(
"localhost",
"user",
"password",
"database"
);
</code></pre>
<p><code>records.php</code>:</p>
<pre><code>// connects to database
include("dbconnect.php");
// targets the database table contacts
$records = mysqli_query($database,"SELECT * FROM contacts");
// pull row data from database
while($record = mysqli_fetch_array($records)) {
echo "<tr>";
echo "<td>" . $record['firstName'] . " " . $record['lastName'] . "</td>";
echo "<td><a href='mailto:" . $record['email'] . "'>" . $record['email'] . "</a></td>";
echo "<td>" . $record['phone'] . "</td>";
echo "<td>" . $record['email'] . "</td>";
echo "</tr>";
}
mysqli_close($database);
</code></pre>
|
[] |
[
{
"body": "<p>I think there are two major issues you should address right in the beginning when you start with PHP.</p>\n\n<h1>Separation of Layout and Logic</h1>\n\n<p>This means in general that you shouldn't mix HTML and PHP code. Later this will lead you to the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\">MVC-Pattern</a>.</p>\n\n<p>index.php</p>\n\n<pre><code><?php\n// connect to database\ninclude(\"inc/dbconnect.php\");\n\nif ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n //...\n}\n\n$result = mysqli_query($database,\"SELECT * FROM contacts\");\n\n$records=array();\nwhile($row = mysqli_fetch_array($result)) {\n $record[]=$row;\n}\n\nmysqli_close($database);\n\ninclude 'template.php';\n</code></pre>\n\n<p>template.php</p>\n\n<pre><code><!DOCTYPE html>\n<html>\n...\n <tbody>\n <?php foreach ($records as $record):?>\n <tr>\n <td><?= $record['firstName']?> <?= $record['lastName']?></td>\n <td><a href=\"mailto:<?= $record['email']?>\"><?= $record['email']?></a></td>\n <td><?= $record['phone']?></td>\n <td><?= $record['email']?></td>\n </tr>\n <?php endforeach;?>\n </tbody>\n...\n</html>\n</code></pre>\n\n<h1>Prevent SQL Injection</h1>\n\n<p>You are passing user input directly to the query you send to the database. <a href=\"http://en.wikipedia.org/wiki/SQL_injection\">Wikipedia</a> will elaborate some examples in detail and shows how queries can be manipulated.</p>\n\n<p>The easies way for you to prevent this, is using <a href=\"http://php.net/manual/en/book.pdo.php\">PHP Data Objects</a> and <strong>Prepared Statements</strong>. I think there is no need for going in detail here if you don't have a specific question, there are many good <a href=\"http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/\">tutorials</a> out there. The important part is, that the user is no longer able to change the query you send to the database.</p>\n\n<h1>Minor issues</h1>\n\n<ul>\n<li>If you only have one database connection PHP will use this connection automatically with the mysqli_ methods so you don't have to pass the <code>$database</code> around.</li>\n<li>It is best practice to leave away the final '?>' in plain php files. This will prevent that you send any whitespace after <code>?></code> to the browser accidentally. (Important if you change the header later.)</li>\n<li><code>echo \"Everything blew up!\" . mysqli_error($database);</code> . May you should use <code>die</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T15:10:03.200",
"Id": "45747",
"Score": "0",
"body": "Thanks for reviewing everything!\n\nI'll definitely make these changes. I added a delete feature last night and plan on trying to add sorting, search and possibility an editing feature."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T05:39:24.587",
"Id": "29009",
"ParentId": "29008",
"Score": "11"
}
},
{
"body": "<p>Before I take a stab at giving some (hopefully) decent feedback here's something to think about..</p>\n\n<pre><code>if ($_SERVER[\"REQUEST_METHOD\"] == \"POST\") {\n</code></pre>\n\n<p>The above I cannot fault but wouldn't the following be better?</p>\n\n<pre><code> if ( isset($_POST['save_btn']) ){\n</code></pre>\n\n<p>I have this nagging need to improve clarity. And I get it, in this instance it's quite subjective but I prefer the latter since you are explicitly checking if the save button was clicked and it gives you a warm feeling of knowing where the POST request came from. If you're thinking 'I Disagree', I won't hold a grudge against you.</p>\n\n<h1>Vulnerability</h1>\n\n<h2>Defending yourself</h2>\n\n<p>As a rule of thumb, never ever trust the data coming from the user. So what you're doing here is without exaggeration disastrous:</p>\n\n<pre><code>// assigns form data to table columns\n$assign = \"INSERT INTO contacts(firstName,lastName,email,phone,birthday) VALUES ('$_POST[firstName]','$_POST[lastName]','$_POST[email]','$_POST[phone]','$_POST[birthday]')\";\n</code></pre>\n\n<p><strong>This is better demonstrated with a simple example:</strong> </p>\n\n<pre><code>//normal input\n//POST value: dave\nquery = \"SELECT username, password FROM users WHERE username='dave'\";\n\n\n//malicious input\n//POST value: 'OR'1\nquery = \"SELECT username, password FROM users WHERE username=''OR'1' \";\n</code></pre>\n\n<p>The nasty thing here is, 1 evaluates to <code>true</code> thus returning all usernames and passwords in the users table!</p>\n\n<h2>mysqli_real_escape_string() to the rescue</h2>\n\n<p>Despite being a mouthful to say, this function provides a safeguard by escaping injection attempts with MySQL-friendly <code>'\\'</code> quote.</p>\n\n<p>So pumping all your post data through this function provides a layer of security.</p>\n\n<pre><code>$username = mysqli_real_escape_string($_POST['username'];\n</code></pre>\n\n<p>Now hopefully that makes sense. Despite rhapsodising <code>mysqli_real_escape_string()</code> I would highly recommend (at some point) looking into using something a bit more sophisticated like <a href=\"http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/\" rel=\"nofollow noreferrer\">PDO</a> instead.</p>\n\n<p>Alrighty, moving on..</p>\n\n<h1>Presentation vs. Logic</h1>\n\n<p>mnhg raises a great point about separation of presentation/layout from logic. Try to get your head around this concept as quickly as you can as it will not only improve the life of your code but it will save you from headaches like <a href=\"https://stackoverflow.com/a/8028987/2180697\">header already sent</a></p>\n\n<p>The idea is quite simple once you catch on to it. Without re-inventing the wheel, taking mnhg's code as an example you'll noticed that the template.php file, also known as the '<strong>view</strong>' is the presentation interface. It's only outputting data. Looping through data and having a conditional statement to check if the data exists is quite acceptable.</p>\n\n<p>On the other hand index.php is known as the '<strong>Controller</strong>'. An analogy would be like a flight control tower where all the 'thinking' or logic happens. And just like a control tower giving instructions to a flight, a Controller, in a similar fashion calls functions. So yes, think about the reusability of your code and function it up! (I emphasize the use of functions because you don't want to clutter your Controllers with redundant tasks when it can be extracted into a function and sometimes its just better represented via a function).</p>\n\n<p>The above and more forms almost a de facto design pattern for web development called <a href=\"http://net.tutsplus.com/tutorials/other/mvc-for-noobs/?search_index=9\" rel=\"nofollow noreferrer\">MVC</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T03:11:32.587",
"Id": "46615",
"Score": "0",
"body": "Thanks. It was an oversight on my part. I did mean to use `mysqli_real_escape_string()`. Updated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-06T12:24:19.180",
"Id": "29442",
"ParentId": "29008",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29009",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T03:02:42.367",
"Id": "29008",
"Score": "7",
"Tags": [
"php",
"beginner",
"mysql"
],
"Title": "Address book with database tables"
}
|
29008
|
<p>I'm doing a BattleShip game in javascript with iio engine.</p>
<p>I'm trying to play against a computer so I have to put a random position for the ships (I hope you know the game :) ).</p>
<p>I have 5 ships that have to be placed in a grid (10x10). The problem is that the function is pretty slow, and sometimes the page don't get load at all.</p>
<p>I want to know if there are some emprovement for the speed of these function, I'm a little bit newbie :D</p>
<pre><code>function posShips(size){
// var size -> size of the ship
var isOk = false; // flag var to check if the ship is in a right position
var isOk2 = true; // flag var, become false if the cell is already fill with another ship
var i;
var j;
var side; // horizontal or vertical
while(!isOk){
i = iio.getRandomInt(1,11);
j = iio.getRandomInt(1,11);
side = iio.getRandomInt(0,2);
if((side ? j : i)+size-1 < 11){ // Not out of the array
for (var k = 0; k < size; k++) { // Size of the ship
if(side){
if(gridHit[i][j+k].stat == "empty"){ //If is empty put the ship
gridHit[i][j+k].stat = "ship";
gridHit[i][j+k].setFillStyle("red")
}else{ // If not empty
isOk2 = false; //Position is not good, do all the thing again.
for (var a = 0; a < size; a++) { // Reset cell
gridHit[i][j+a].stat = "empty";
}
k = 10;
}
}else{
if(gridHit[i+k][j].stat == "empty"){ //If is empty put the ship
gridHit[i+k][j].stat = "ship";
gridHit[i+k][j].setFillStyle("red")
}else{ // If not empty
isOk2 = false; //Position is not good, do all the thing again.
for (var a = 0; a < size; a++) { // Reset cell
gridHit[i+a][j].stat = "empty";
}
k = 10;
}
}
};
if(isOk2)
isOk = true;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T09:43:36.457",
"Id": "45729",
"Score": "0",
"body": "The problem is the algorithm: you need something better than `while (!allPlaced) { do { pos = randPos(); } while (shipAt(pos)); positions.add(pos); }`. 5 ships on a 100 point grid are going to take up quite a bit of the possible placements, meaning lots of wasted guesses. Unfortunately though, I have no idea what algorithm to use here. I suspect it's going to have to be heuristic, but other than that I have no help to offer. I just think your question is very interesting :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T09:45:08.580",
"Id": "45730",
"Score": "0",
"body": "Some pure javascript technicals stuff :\nDeclare your 'a' and 'k' variable (use in `for`) outside of your `while` (you will redeclare your variable each time), and change `if(isOk2) isOk = true` , by `isOk = isOk2;`testing variable is slower that setting it : http://jsperf.com/test-vs-set"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T10:00:09.440",
"Id": "45731",
"Score": "0",
"body": "@julesanchez Because of variable hoisting, `a` and `k` are actually declared outside of the while loop. For that very reason though, he should still declare them at the scope where they're actually declared."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T12:58:26.837",
"Id": "45805",
"Score": "0",
"body": "@Corbin The algorithm is actually fast enough for this scale of problem; there are typically under 10 wasted guesses."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T09:49:48.063",
"Id": "45852",
"Score": "0",
"body": "@Stuart Ah, teaches me to make assumptions :). Had assumed the implementation was fairly quickly done :)."
}
] |
[
{
"body": "<p>This is not really a speed issue; there are a couple of problems with your code that prevent it from working properly.</p>\n\n<p>The most serious problem is that, if the position is not good you set <code>isok2 = false</code>. The <code>while</code> loop then picks another position. But nothing resets <code>isok2</code> to <code>true</code>. So in fact, if the function does not find a good position on the first attempt, it will continue to loop indefinitely, which is why the page does not load.</p>\n\n<p>A second problem is that when the position is not good you set all of the cells to empty. </p>\n\n<pre><code>for (var a = 0; a < size; a++) { // Reset cell\n gridHit[i][j+a].stat = \"empty\";\n}\n</code></pre>\n\n<p>but this overwrites other ships that might have been in that space. A better approach would be to find an appropriate space first, and only once the whole space has been checked, start filling that space with 'ship' cells. Then you don't have to worry about resetting cells you have started filling before realising the space was blocked.</p>\n\n<p>Some other comments:</p>\n\n<p>(1) Instead of using the condition <code>if((side ? j : i)+size-1 < 11)</code> to check if the position is within the grid, it would be better to make sure that the random numbers chosen are within the grid in the first place:</p>\n\n<pre><code>i = iio.getRandomInt(1, side ? 11 : 11 - size);\nj = iio.getRandomInt(1, side ? 11 - size : 11);\n</code></pre>\n\n<p>(2) Instead of setting <code>k = 10</code> to break out of the loop, simply use <code>break</code>.</p>\n\n<p>(3) Debug what is happening in your code by strategically placing <code>console.log</code> commands.</p>\n\n<p>(4) It's often cleaner to use functions and return statements rather than flags. For instance, you could have a function like this within your main function:</p>\n\n<pre><code>function blocked() {\n for (var k = 0; k < size; k++) {\n if (side ? grid[i][j + k] : grid[i + k][j]) {\n return true;\n }\n }\n}\n</code></pre>\n\n<p>Here is a <a href=\"http://jsfiddle.net/bpxVr/4/\" rel=\"nofollow\">jsfiddle</a> demonstrating these points (in the function <code>makeEnemyShip</code>). It uses the same basic algorithm that you do and there is no speed problem.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T12:50:06.503",
"Id": "29059",
"ParentId": "29013",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T08:11:29.317",
"Id": "29013",
"Score": "2",
"Tags": [
"javascript",
"performance"
],
"Title": "Improve performance Javascript function"
}
|
29013
|
<p>I have sample database in <code>GES</code> files and I wrote importer in Ruby.</p>
<p>Sample file: <code>WAR_APO.GES</code>: <a href="https://gist.github.com/regedarek/cd0ce73c5d1e14ff9818" rel="nofollow">https://gist.github.com/regedarek/cd0ce73c5d1e14ff9818</a></p>
<p>I will have several of <code>GES</code> files which I want to move to my <code>data</code> folder in app and I want to process them manually.</p>
<ol>
<li>For most of them logic is the same but the difference are filename, model and attributes hash.</li>
<li>I want to also and new cases like: <code>Update</code> when type is <code>U</code> or <code>Delete</code> if is <code>D</code></li>
</ol>
<p>How should I refactor that:</p>
<pre><code>class PrototypePharmaceuticImporter
ID = '00'
K = "#{ID}K"
F = "#{ID}F"
FB = "#{ID}FB"
D = "#{ID}D"
I = "#{ID}I"
U = "#{ID}U"
E = "#{ID}E"
TYPES = [K, F, FB, D, I, U, E]
ARTICLE_TYPE = 57
BARCODE = 15
GROUP_CODE = 1
GROUP_KEY = 40
GROUP_NAME = 2
FORM_CODE = 1
FORM_KEY = 38
FORM_NAME = 2
FORM_SHORT_NAME = 3
LONGNAME = 28
PACKAGE_TYPE = 46
PHARMACY_ONLY = 3
PRESCRIPTION_ONLY = 47
PRICE = 2
WEIGHT = 14
attr_accessor :file, :k, :f
def initialize
@pharmaceutics_file = File.open 'data/PAC_APO.GES', 'r'
@forms_file = File.open 'data/DAR_APO.GES', 'r'
@groups_file = File.open 'data/WAR_APO.GES', 'r'
@k = []
@f = []
extract_groups_to_database
end
def extract_pharmaceutics_to_database
add = true
tmp = []
type = K
@pharmaceutics_file.each_with_index do |line, i|
break if (i > 96 * 1000 + 760 + 9)
_type = line.strip
_changed = TYPES.include? _type
if _changed && i > 0
case type
when K then @k << tmp
when F then @f << tmp
when FB then @f << tmp
when I, U, D
hash = {
article_type: tmp[ARTICLE_TYPE],
price: tmp[PRICE],
weight: tmp[WEIGHT],
package_type: tmp[PACKAGE_TYPE],
group_code: tmp[GROUP_KEY],
form_code: tmp[FORM_KEY],
name: tmp[LONGNAME],
barcode: tmp[BARCODE],
pharmacy_only: tmp[PHARMACY_ONLY],
prescription_only: tmp[PRESCRIPTION_ONLY]
}
Pharmaceutic.create(hash)
end
tmp = []
type = _type
end
tmp << clean(line)
end
end
def extract_forms_to_database
add = true
tmp = []
type = K
@forms_file.each_with_index do |line, i|
break if (i > 96 * 1000 + 760 + 9)
_type = line.strip
_changed = TYPES.include? _type
if _changed && i > 0
case type
when K then @k << tmp
when F then @f << tmp
when FB then @f << tmp
when I, U, D
hash = {
code: tmp[FORM_CODE],
name: tmp[FORM_NAME],
short_name: tmp[FORM_SHORT_NAME]
}
PharmaceuticForm.create(hash)
end
tmp = []
type = _type
end
tmp << clean(line)
end
end
def extract_groups_to_database
add = true
tmp = []
type = K
@groups_file.each_with_index do |line, i|
break if (i > 96 * 1000 + 760 + 9)
_type = line.strip
_changed = TYPES.include? _type
if _changed && i > 0
case type
when K then @k << tmp
when F then @f << tmp
when FB then @f << tmp
when I, U, D
hash = {
code: tmp[GROUP_CODE],
name: tmp[GROUP_NAME]
}
PharmaceuticGroup.create(hash)
end
tmp = []
type = _type
end
tmp << clean(line)
end
end
private
def clean line
line.strip
.gsub(/^[\d]{2}/, '')
.gsub(/\\[s|S]39/, 'ß')
.gsub(/\\a25/, 'ä')
.gsub(/\\A25/, 'Ä')
.gsub(/\\o25/, 'ö')
.gsub(/\\O25/, 'Ö')
.gsub(/\\u25/, 'ü')
.gsub(/\\U25/, 'Ü')
end
end
</code></pre>
<p>Basically, I want to get rid of duplications in these methods.</p>
|
[] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li><p>As usual, I'd recommend a more functional approach. It's not a theoretical issue, functional code is more concise, more clear. When I see <code>@k = []</code> I get the shakes thinking that this variable can (and will) be modified just everywhere in the class (an instance variable is just a nasty global variable -for the scope a class, granted- with a pretty name).</p></li>\n<li><p>Also related to FP, your code is hard to abstract because it's written with procedures instead of functions: they don't take values (as arguments) and return values, everything works by side-effects through instance variables. No referential transparency, no idempotence...</p></li>\n<li><p>Don't create so many individual constants, group them in hashes.</p></li>\n<li><p><code>File.open 'data/PAC_APO.GES', 'r'</code>. Hardcoded files in classes? mmmm.</p></li>\n<li><p><code>96 * 1000 + 760 + 9</code>. Magic number, define it as a constant so it has a name.</p></li>\n</ul>\n\n<p>Answering your particular question about how to avoid repeating code for those 3 methods: whatever is different put it as arguments. If some value depends on something the caller cannot know yet about (the code under <code>when I, U, D</code>), then use an argument block as callback. So it might be written:</p>\n\n<pre><code>def extract_to_database(collection)\n add = true\n tmp = []\n type = K\n\n collection.each_with_index do |line, i|\n break if (i > 96 * 1000 + 760 + 9)\n\n _type = line.strip\n _changed = TYPES.include? _type\n\n if _changed && i > 0\n case type\n when K then @k << tmp\n when F then @f << tmp\n when FB then @f << tmp\n when I, U, D\n yield(tmp)\n end\n\n tmp = []\n type = _type\n end\n\n tmp << clean(line)\n end\nend\n</code></pre>\n\n<p>Note that I kept your old imperative code (a functional approach would require rewriting the full class), but at least is now DRYed. I'd strongly encourage to try the functional paradigm, it's hard at first but it pays off on the long run. <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">My article on this matter</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T10:21:33.650",
"Id": "46653",
"Score": "0",
"body": "Could you give me simple advice how to get rid of using @k = [] from this method? I read your article and it is great but I have problem with implementing some of your hints. So I changed it to use sql for inserting and it looks like that: https://gist.github.com/regedarek/6172861. Thanks for this article it is great."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T10:30:32.850",
"Id": "46654",
"Score": "1",
"body": "I'll try to write a refactor of the gist later. For now, note that `@f` is defined nowhere. Try to write it without instance variables."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T12:31:22.933",
"Id": "29021",
"ParentId": "29014",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29021",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T09:08:06.120",
"Id": "29014",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"data-importer"
],
"Title": "What are best practices of creating database importer in Rails?"
}
|
29014
|
<p>As a beginner Python programmer, I wrote a simple program that counts how many times each letter appears in a text file. It works fine, but I'd like to know if it's possible to improve it.</p>
<pre><code>def count_letters(filename, case_sensitive=False):
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
with open(filename, 'r') as f:
text = f.read()
if not case_sensitive:
alphabet = alphabet[:26]
text = text.lower()
letter_count = {ltr: 0 for ltr in alphabet}
for char in text:
if char in alphabet:
letter_count[char] += 1
for key in sorted(letter_count):
print(key, letter_count[key])
print("total:", sum(letter_count.values()))
</code></pre>
|
[] |
[
{
"body": "<p>Your coding style is good, especially if you're only starting to program in Python. But to improve your code, you should learn your way around the standard library. In this case, the <a href=\"http://docs.python.org/3/library/string.html\" rel=\"nofollow\"><code>string</code></a> and <a href=\"http://docs.python.org/3/library/collections.html\" rel=\"nofollow\"><code>collections</code></a> modules can make life easier for you.</p>\n\n<pre><code>import collections\nimport string\n\ndef count_letters(filename, case_sensitive=False):\n with open(filename, 'r') as f:\n text = f.read()\n\n if case_sensitive:\n alphabet = string.ascii_letters\n else:\n alphabet = string.ascii_lowercase\n text = text.lower()\n\n letter_count = collections.Counter()\n\n for char in text:\n if char in alphabet:\n letter_count[char] += 1\n\n for letter in alphabet:\n print(letter, letter_count[letter])\n\n print(\"total:\", sum(letter_count.values()))\n</code></pre>\n\n<p><a href=\"http://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a> is, in essence, a dictionary with all values defaulting to <code>0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T12:11:11.783",
"Id": "45804",
"Score": "1",
"body": "Note that `collection.Counter` may take an iterable, so there is no need to add values with a side-effect (`letter_count[char] += 1`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T18:27:12.150",
"Id": "45825",
"Score": "0",
"body": "@tokland Good point."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T16:01:47.133",
"Id": "29031",
"ParentId": "29024",
"Score": "4"
}
},
{
"body": "<p>@flornquake points at the good direction (use <code>string</code> and <code>collections.Counter</code>) but I'd still modify some details:</p>\n\n<ul>\n<li><p><code>alphabet = alphabet[:26]</code> and <code>text = text.lower()</code>: My advice is not to override existing variables with new values, it makes code harder to understand. Use different names.</p></li>\n<li><p><code>if char in alphabet</code>: Make sure you perform inclusion predicates with hashes, sets or similar data structures, not lists/arrays. O(1) vs O(n).</p></li>\n<li><p>Functions should return values (hopefully related with their name). Here it makes sense to return the counter.</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>import collections\nimport string\n\ndef count_letters(filename, case_sensitive=False):\n with open(filename, 'r') as f:\n original_text = f.read()\n if case_sensitive:\n alphabet = string.ascii_letters\n text = original_text\n else:\n alphabet = string.ascii_lowercase\n text = original_text.lower()\n alphabet_set = set(alphabet)\n counts = collections.Counter(c for c in text if c in alphabet_set)\n\n for letter in alphabet:\n print(letter, counts[letter])\n print(\"total:\", sum(counts.values()))\n\n return counts\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T09:03:02.060",
"Id": "45801",
"Score": "0",
"body": "You didn't explicitly mention it, but one of the best improvements is the initialization of the `Counter` from a generator expression. Nice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T12:09:20.523",
"Id": "45803",
"Score": "0",
"body": "@codesparkle: I was to, but I realized that would be reviewing flownquake's answer, not OP :-) I'l add a comment to his question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T16:33:59.233",
"Id": "45944",
"Score": "0",
"body": "Wouldn't using `original_text = original_text.lower()` be better? Avoids unneeded variable. Also what about non-existent files? That would create an unrecognizable error for user as saying that file doesn't exist in error is quite different from the error that `original_text` undeclared."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T16:39:10.743",
"Id": "45945",
"Score": "0",
"body": "@AseemBansal 1) reuse variables: Are you familiar with the functional paradigm? in FP you never ever use the same variable name (or symbol) for two different values (in the same scope, of course), because it's harder to reason about the algorithm. It's like in maths, you don't have x = 1, and just a step later x = 2, that makes no sense; the same when programming. More on this: https://en.wikipedia.org/wiki/Functional_programming 2) \"what about non-existent files\" The OP didn't stated what was to be done, so I did the same he did: nothing. Let the exception blow or be caught by the caller."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T17:00:58.690",
"Id": "45948",
"Score": "0",
"body": "@tokland I just know C so not familiar with functional programming. But here it seems to be just procedural code with function call. Is it bad to reuse variables in Python? Noone pointed that out earlier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:08:33.100",
"Id": "45955",
"Score": "1",
"body": "@AseemBansal: In C is difficult (and usually unrealistic) to apply FP principles, but in Python (like in Ruby, Perl, Lua and other imperative languages), you definitely can (of course an inpure approach to FP, with side-effects). If you give it a try, you'll see that code improves noticiably, it's more much more declarative (describing not *how* but *what* you are doing). Perhaps the starting point would be: http://docs.python.org/3/howto/functional.html. If you happen to know Ruby, I wrote this: https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:12:02.733",
"Id": "45956",
"Score": "0",
"body": "@tokland This will be really helpful. I found that there is a how-to for fetching web resources using urllib also which I am currently trying to do. I wish you had told me earlier. I might not have needed to ask question on SO. Many thanks."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-07-26T20:46:11.370",
"Id": "29043",
"ParentId": "29024",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "29043",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T13:43:09.550",
"Id": "29024",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"file"
],
"Title": "Counting letters in a text file"
}
|
29024
|
<p>I'm working on a project where I need to map XML values to field names. Classic CS problem, I think I've got a pretty good approach but would like feedback.</p>
<p>For example: <code>breachReportType</code> matches to <code>Breach Report Type:</code>. However, there are similar matches like: <code>breachType</code> or <code>breachReportCause</code>.</p>
<p>The inputs are like ...</p>
<ul>
<li>Xml by Field Name: <code><xml><breachReportType></code></li>
<li>Field Name by ID: <code>[ { Key: '1234', Value: 'Breach Report Type' } ]</code></li>
<li><p>Content by Field ID: <code><xml><Field id='1234' Value='Email'></code></p>
<pre><code>// this.MapValues //->
// Fields Example: [{ Key: '12345', Value: 'Breach Report Type' }]
// XML Example: '<breachReportType />'
private Dictionary<string, string> MapValues(Dictionary<string, string> fields, string xml)
{
var map = new Dictionary<string, string>();
var elements = XDocument.Parse(xml).Descendants();
foreach (XElement elm in elements)
{
string name = elm.Name.ToString();
string formattedName = this.SplitCamelCase(name);
int currentMaxCount = 0;
string bestMatchId = null;
foreach (var field in fields)
{
string strippedFieldValue = field.Value.Substring(0, field.Value.Length - 1);
// XML: breach Report Type
// Field Name: Breach Type
int match = this.MatchStrings(strippedFieldValue, formattedName);
// once we find a match, update the index
if (match > currentMaxCount)
{
if (bestMatchId != null)
{
// get the previous one
string prevName;
fields.TryGetValue(bestMatchId, out prevName);
// compare the previous match
int prev = this.MatchStrings(prevName, formattedName);
// if the new match is greater than previous, update best match
// and the string match is closer to the character match
if (match > prev && ((strippedFieldValue.Length - match) < (prevName.Length - prev)))
{
bestMatchId = field.Key;
currentMaxCount = match;
}
}
else
{
bestMatchId = field.Key;
currentMaxCount = match;
}
}
}
if (bestMatchId != null && !map.ContainsKey(bestMatchId))
{
map.Add(bestMatchId, name);
}
}
return map;
}
// MatchStrings //->
// firstString Example: 'breachReportType'
// secondString Example: 'Breach Report Type'
private int MatchStrings(string firstString, string secondString)
{
List<string> firstArr = firstString.Split(new[] { " " },
StringSplitOptions.RemoveEmptyEntries).ToList();
List<string> secondArr = secondString.Split(new[] { " " },
StringSplitOptions.RemoveEmptyEntries).ToList();
int match = 0;
foreach (string string1 in firstArr)
{
foreach (string string2 in secondArr)
{
if (string1.ToLower().IndexOf(string2.ToLower()) > -1)
{
match = match + string2.Length;
}
}
}
return match;
}
// TranslateAndConcert //->
// Record Example: "<xml><Field id="1234" Value="Email">"
// FieldMap Example: [{ Key: '1234', 'breachReportType' }]
private string TranslateAndConvert(string record, Dictionary<string, string> fieldMap)
{
XDocument mappedXml = new XDocument(new XElement("topmostSubform"));
var elements = XDocument.Parse(XDocument.Parse(record).Root.Value)
.Descendants("Field")
.ToList();
foreach (XElement elm in elements)
{
if (elm.Attribute("id") != null && elm.Attribute("value") != null)
{
// get the values from the xml
string id = elm.Attribute("id").Value;
string value = elm.Attribute("value").Value;
// get the mapped name
string name = null;
fieldMap.TryGetValue(id, out name);
// create new element
if (name != null)
{
var node = new XElement(name, value);
mappedXml.Root.Add(node);
}
}
}
return mappedXml.ToString();
}
// SplitCamelCase //->
// input example: 'breachReportType'
private string SplitCamelCase(string input)
{
return System.Text.RegularExpressions.Regex.Replace(input, "([A-Z])",
" $1", System.Text.RegularExpressions.RegexOptions.Compiled).Trim();
}
</code></pre></li>
</ul>
<p>Any better ideas for an approach?</p>
|
[] |
[
{
"body": "<p>You could possibly improve it by using a fuzzy match algorithm such as the <a href=\"http://www.dotnetperls.com/levenshtein\" rel=\"nofollow\">Levenshtein Distance Algorithm</a> for your MatchStrings method. Then you could simply look for the smallest return value of all of the comparisons and use that as the best without having to do the extra length comparisons. This would also work better if there are some spelling variations in the data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:19:42.527",
"Id": "45915",
"Score": "0",
"body": "Ya, I really like that. Thanks for the suggestion!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T02:44:19.450",
"Id": "29048",
"ParentId": "29027",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29048",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T14:13:54.777",
"Id": "29027",
"Score": "3",
"Tags": [
"c#",
"strings",
"regex",
"xml"
],
"Title": "String Interpolation / Word Matching with XML in C#"
}
|
29027
|
<p>I wrote this form object to handle an e-commerce order form. My areas of concern are the verbosity of the <code>populate</code> method, and the repetition of the validations. I omitted some address fields and validations for brevity.</p>
<pre><code>class OrderForm
include ActiveModel::Model
def persisted?
false
end
attr_accessor :params
delegate :email, :bill_to_shipping_address, to: :order
delegate :name, :street, :city, :state, :post_code, to: :shipping_address, prefix: :shipping
delegate :name, :street, :city, :state, :post_code, to: :billing_address, prefix: :billing
validates :email, length: { maximum: 60 }, email_format: true
validates :shipping_name, :shipping_street, :shipping_city, presence: true
validates :shipping_post_code, numericality: { only_integer: true }
validates :billing_name, :billing_street, :shipping_city, presence: true, unless: -> { bill_to_shipping_address }
validates :billing_post_code, numericality: { only_integer: true }, unless: -> { bill_to_shipping_address }
def initialize(item, params = nil, customer = nil)
@item, @params, @customer = item, params, customer
end
def submit
populate
if valid?
order.save!
true
else
false
end
end
def order
@order ||= @item.build_order do |order|
order.customer = @customer if @customer
end
end
private
def shipping_address
@shipping_address ||= order.build_shipping_address
end
def billing_address
@billing_address ||= order.build_billing_address
end
def populate
order.email = params[:email]
order.bill_to_shipping_address = params[:bill_to_shipping_address]
shipping_address.name = params[:shipping_name]
shipping_address.street = params[:shipping_street]
shipping_address.city = params[:shipping_city]
shipping_address.state = params[:shipping_state]
shipping_address.post_code = params[:shipping_post_code]
if order.bill_to_shipping_address?
billing_address.name = params[:shipping_name]
billing_address.street = params[:shipping_street]
billing_address.city = params[:shipping_city]
billing_address.state = params[:shipping_state]
billing_address.post_code = params[:shipping_post_code]
else
billing_address.name = params[:billing_name]
billing_address.street = params[:billing_street]
billing_address.city = params[:billing_city]
billing_address.state = params[:billing_state]
billing_address.post_code = params[:billing_post_code]
end
end
end
</code></pre>
<p>The <code>Order</code> object has <code>billing_address</code> and one <code>shipping_address</code> objects. They both inherit from an <code>Address</code>.</p>
<p>Here's the controller:</p>
<pre><code> def new
@order_form = OrderForm.new(@item)
end
def create
@order_form = OrderForm.new(@item, params[:order], current_user)
if @order_form.submit
# process payment
else
render 'new'
end
end
</code></pre>
|
[] |
[
{
"body": "<p>I was about to propose some changes to your code to reduce the line-count (and get rid of those @cached objects, bad idea IMHO), but I think it's the big picture what it's failing here. Some notes:</p>\n\n<ul>\n<li><p>You are creating an <code>OrderForm</code> abstraction when in fact Rails gives all the infrastructure you need to write this in <code>Order</code> in a simple and very concise way.</p></li>\n<li><p>All those validations belong to each model, validating them from an outside class is not a good practice.</p></li>\n<li><p>Use <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html\" rel=\"nofollow\">accepts_nested_attributes_for</a> (in models) + <a href=\"http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for\" rel=\"nofollow\">fields_for</a> (in views) so the associations are automatically (and transparently) handled by Rails.</p></li>\n</ul>\n\n<p>[EDIT] Regarding the non-cached approach, a glimpse of what I'd write:</p>\n\n<pre><code>order = @item.order || build_order\norder.customer = @customer\nshipping_address = order.shipping_address || order.build_shipping_address\nshipping_address.attributes = params.slice(:shipping_name, :shipping_street,...) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T17:47:47.057",
"Id": "45820",
"Score": "0",
"body": "Interesting comments. My experience tells me otherwise. I found `accepts_nested_attributes_for` lacking here. It presented problems instead of solutions. For example. If `bill_to_shipping_addess` is checked, the user will still see errors for both addresses. You have to hack the error messages and remove them unless the user wants different addresses. You can use `reject_if` to overcome this. But if there is was a validation error on the shipping address, the fields for billing address will disappear. There are other problems too. I spent two days to make it work to no avail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T17:48:32.247",
"Id": "45821",
"Score": "0",
"body": "Can you comment why the cached objects are a bad idea here? And how would you get rid of them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T18:55:26.450",
"Id": "45826",
"Score": "0",
"body": "I see, you've already fought with `accepts_nested_attributes`. Indeed, it may be hard to make it sometimes. About not liking cached objects: I generally don't like cached objects in models at all, too indirect. I prefer more explicit approaches. You want a shipping_address? well, create one, use it and return it or whatever, no need for a method object that creates one or returns the one already existing behind your back. I see no benefits with this indirect, side-effected approach. But I prefer functional programming (and referential transparency) so you can freely say I am biased :-)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T15:18:12.443",
"Id": "29062",
"ParentId": "29030",
"Score": "1"
}
},
{
"body": "<p>It seems to me Address is a value object, your billing and shipping address are just usages of this address. You are receiving either one or two addresses from the request. If you get one, you use the same address for billing as shipping.</p>\n\n<p>I remember fighting nested_attributes a long time ago, but accepts_nested_attributes_for looks much easier.</p>\n\n<p><a href=\"http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/\" rel=\"nofollow\">7 Patterns to Refactor Fat ActiveRecord Models</a> has a bunch of good advice on cleaning up rails code along with guidelines as to when to use each technique.</p>\n\n<p>I haven't used <a href=\"https://github.com/apotonick/reform\" rel=\"nofollow\">Reform</a>, but RailsCasts.com mentioned it when talking on the subject.\nIt provides a DSL for form objects, so you can untie your model from your forms. I'm not sure you I feel about this, I worry it will mean duplicating validation logic. I would use something like this if I was attempting to build a strong domain model and didn't want the presentation logic leaking into the models. Whenever I get the need for a strong domain model (DDD) in Rails, I need to build the logic outside Rails (in a gem) and then integrate that in, so I end up with a Rails app doing what Rails does best, database backed web application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:06:14.007",
"Id": "45910",
"Score": "0",
"body": "There's definitely a duplication of validation logic between the `Address` model and form object. I could not find a way to overcome the issues I mentioned in `accepts_nested_attributes_for`, and in the end it proved much harder to implement in a clean way. While this introduces some duplication in validation, it's far cleaner. The primary issue with `accepts_nested` is the need to create/validate billing address conditionally. That messes it up entirely. I would certainly be interested too see how you would solve this with nested attrs."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T12:04:23.840",
"Id": "29123",
"ParentId": "29030",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T15:35:33.963",
"Id": "29030",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails",
"e-commerce"
],
"Title": "Handling an e-commerce order form"
}
|
29030
|
<p>I have two buttons on an ASP.NET page that have separate <code>OnClick</code> methods in the code behind. In one of the methods, if a certain condition is met, the entire process of the other method should be executed.</p>
<p>Here is a simplified example of my code, which works as I intend in my actual implementation:</p>
<pre><code>// OnClick="ThisButton_OnClick" for ThisButton
protected void ThisButton_OnClick(object sender, EventArgs e)
{
// do stuff
if(condition)
ThatButton_OnClick(null, null);
else
// do stuff
}
// OnClick="ThatButton_OnClick" for ThatButton
protected void ThatButton_OnClick(object sender, EventArgs e)
{
// do stuff
}
</code></pre>
<p>My question is this: is it good practice to do something like this, where you call a method specifically designed for <code>OnClick</code> without clicking that button, or should I be more explicit (perhaps have a separate helper function that is called by <code>ThatButton_OnClick</code> and in the <code>if</code>)?</p>
|
[] |
[
{
"body": "<p>I'd suggest something like the following which is simple enough for even a novice like me to understand. Is there a real need to simulate button click? You're not testing buttons, are you? </p>\n\n<pre><code>// OnClick=\"ThisButton_OnClick\" for ThisButton\nprotected void ThisButton_OnClick(object sender, EventArgs e)\n{\n // do stuff\n if(condition)\n DoStuffThatButtonWouldDo(arg);\n else\n // do stuff\n}\n\n// OnClick=\"ThatButton_OnClick\" for ThatButton\nprotected void ThatButton_OnClick(object sender, EventArgs e)\n{\n DoStuffThatButtonWouldDo(arg);\n}\n\nprivate static DoStuffThatButtonWouldDo(fancy arguments) \n{ \n //TODO: do all the stuff that the that button would do \n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T17:43:23.277",
"Id": "45758",
"Score": "1",
"body": "I'm not testing buttons. Really, it's just chance that `ThatButton_OnClick` did what I might want (depending on `condition`) in `ThisButton_OnClick`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T18:23:39.577",
"Id": "45761",
"Score": "0",
"body": "I think you made the right call in asking yourself if you wanted to make it more explicit. Since the logic does not depend on `ThatButton`, extracting the logic to its own method would reinforce newcomers like me that there is nothing special happening within `ThatButton`. Cheers!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T17:35:50.717",
"Id": "29037",
"ParentId": "29034",
"Score": "8"
}
},
{
"body": "<p>I would probably have a seperate method that takes no parameters. Mainly because by passing null, null you are assuming knowledge of the inner workings of the method. What happens if later on down the track your <code>ThatButton_OnClick</code> suddenly decides to do something with sender. </p>\n\n<p>I think it would be fair enough for the <code>ThatButton_OnClick</code> method to assume the objects will not be <strong>null</strong> and work with them directly. So in that case suddenly your program would fail. You might not even notice that until the program makes production (if the test cases, user doesn't test the ThisButton_onClick functionality).</p>\n\n<p>I would start by making the method private within the code behind. And later move it to the domain or service later later on if required.</p>\n\n<pre><code>protected void ThatButton_OnClick(object sender, EventArgs e)\n{\n // Oh no, this will cause a NullReferenceException but would should it when sender should really never be null......\n\n if(sender.ToString == \"Hello\") \n {\n // do something now\n }\n}\n</code></pre>\n\n<p>As for <strong>Good practice</strong>? I don't think it's either here nor there in this case TBH. However it might help minimize technical debt and possible unintentional future bugs by implementing a seperate method now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:28:18.103",
"Id": "29040",
"ParentId": "29034",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29037",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T17:28:20.403",
"Id": "29034",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "Calling a button's OnClick method elsewhere - Good Practice?"
}
|
29034
|
<p>In my web development company, we have many designers who have the following development knowledge:</p>
<ul>
<li>Client-side web languages (HTML, CSS, JavaScript)</li>
<li>Basic database design (how to create tables, relationships, etc), and</li>
<li>Basic SQL</li>
</ul>
<p>So we thought about giving them a simple platform to create data-oriented web apps.</p>
<ol>
<li>What do you think of the following coding style for ASP.NET MVC?</li>
<li>How can we improve it?</li>
<li>Any ideas for a better SQL injection solution than the params array? Remember that the code should look clean and simple.</li>
</ol>
<p><strong>/apps/pages/index.html</strong></p>
<pre class="lang-html prettyprint-override"><code>@(DB.Select(table: "pages",
where: "id = ? and date > ?",
params: new[] { Request.QueryString["ID"], Request.QueryString["Date"] }))
<html>
<body>
<ul>
@foreach (var row in Model) {
<li><a href="@row.URL">@row.Name</a></li>
}
</ul>
</body>
</html>
</code></pre>
<p><strong>/apps/pages/create.html</strong></p>
<pre class="lang-html prettyprint-override"><code>@(DB.InsertOnPost(table: "pages",
fields: "name, description, date",
values: "?, ?, Now",
params: new[] { Request.Form["Name"], Request.Form["Description"] }))
@RedirectOnPost("/pages")
<form action="/pages/create" method=”post”>
<div>
<label for="name">Name</label>
<input type="text" name="name" />
</div>
<div>
<label for="description">Description</label>
<textarea name="description"></textarea>
</div>
</form>
</code></pre>
<p><strong>/apps/pages/edit.html</strong></p>
<pre class="lang-html prettyprint-override"><code>@(DB.UpdateOnPost(table: "pages",
set: "name = ?, description = ?",
where: "id = ?",
params: new[] { Request.Form["Name"], Request.Form["Description"],
Request.QueryString["ID"] }))
@RedirectOnPost("/pages")
@(DB.Select(table: "pages",
where: "id = ?",
params: new[] { Request.QueryString["ID"] })
<form action="/pages/edit" method="post">
<div>
<label for="name">Name</label>
<input type="text" name="name" value="@Model.Name" />
</div>
<div>
<label for="description">Description</label>
<textarea name="description">@Model.Description</textarea>
</div>
</form>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T19:16:52.450",
"Id": "45769",
"Score": "2",
"body": "What's the reason for not using controllers and repositories for interaction with the database?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T19:28:36.430",
"Id": "45827",
"Score": "2",
"body": "I'm not too sure if I'm keen on mixing the DB specific stuff in with the views themselves. Seems to be crossing boundaries to me"
}
] |
[
{
"body": "<p>That coding style looks more like the WebMatrix <a href=\"http://www.asp.net/web-pages/tutorials/introducing-aspnet-web-pages-2/getting-started\" rel=\"nofollow\">Web Pages</a> pattern rather than ASP.Net MVC. If this coding style is desired then it would be preferable to go ahead and use the data access library that is usually used with Web Pages, the WebMatrix.Data library. That will by default guard against SQL Injection as long as the convention of the parameterized queries is used, e.g. </p>\n\n<pre><code> selectCommand = \"SELECT URL, Name FROM Pages WHERE ID = @0 AND Date = @1\";\n selectedData = db.Query(selectCommand, Request.QueryString[\"Id\"], Request.QueryString[\"Date\"]);\n</code></pre>\n\n<p>This should be OK for simple sites, but for larger or more complex sites you would be better to separate the data access from the presentation layer, using the full MVC pattern. The downside of the pattern shown here is that is difficult to test or debug compared to MVC or WebForms and it tends to introduce duplication in the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T01:47:44.243",
"Id": "29046",
"ParentId": "29035",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T17:32:16.900",
"Id": "29035",
"Score": "1",
"Tags": [
"html",
"sql",
"asp.net",
"mvc"
],
"Title": "Platform for creating data-oriented web apps"
}
|
29035
|
<p>Here is my link to the <a href="http://jsfiddle.net/zq7rq/" rel="nofollow">JSFiddle</a> and the <a href="http://jsfiddle.net/zq7rq/embedded/result/" rel="nofollow">full screen description</a>.</p>
<p><em>Note on the full mode screen</em>: the footer is not sticking, but it actually sticks if I check on my browser.</p>
<p>So that is exactly what I want for my layout. I want someone to see if there's anything in my CSS I don't need, or if I am using improperly without affecting the layout that is displayed. </p>
<p>For example:</p>
<ol>
<li>Under the Header ID I have a element called top:0; what is this used for and do I actually need it?</li>
<li>Under the Main ID I have margin: 0 auto -50px; I found help from someone, but quite don't understand the theory on it.</li>
<li>Under the Footer ID I have bottom:0; what is this used for as well and do I need it?</li>
</ol>
<p><strong>HTML:</strong></p>
<pre><code> <body>
<div id="page">
<div id="header">
</div>
<div id="main">
</div>
<div id="footer">
</div>
</div>
</body>
</html>
</code></pre>
<p><strong>CSS:</strong></p>
<pre><code>/*THIS IS THE CSS CODE FOR WNG WEBSITE*/
html, body
{
padding:0;
margin:0;
height:100%;
font-size:0.8em;
}
#page
{
height:100%;
min-width:960px;
}
#header
{
position:relative;
background-color:#115EA2;
height:100px;
width:100%;
top:0;
}
#main
{
width:1300px;
background-color:#F1F2F3;
margin: 0 auto -50px;
vertical-align:bottom;
padding: 20px 20px 40px 20px;
color:#115EA2;
text-decoration:none;
height:2000px;
}
#footer
{
position:fixed;
width:100%;
bottom:0;
height: 35px;
background-color:#115EA2;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T20:08:30.527",
"Id": "45773",
"Score": "0",
"body": "Fixed width websites are pretty much a thing of the past thanks to a plethora of mobile and tablet resolutions. *Responsive design* is the way things are generally done now, even if mobile devices currently make up a relatively small percentage of your users."
}
] |
[
{
"body": "<p>Unless your element is fixed or absolutely positioned, <code>top: 0</code> is doing nothing for you (<code>#header</code>). Unless your descendant elements are absolutely positioned (or you need to adjust the element's stacking order due to surrounding absolutely positioned elements), you probably don't need <code>position: relative</code> either.</p>\n\n<p>The negative margin on <code>#main</code> is doing nothing for you (<code>margin: 0 auto</code> gives identical results). Generally, you use negative margins to nudge things around similar to relative positioning, but where it effects the position of everything that follows as well (eg. an element with <code>margin-top: -50px</code> will move up 50px and so will everything below it, but an element that's relatively positioned with a <code>top: -50px</code> will only shift <em>that</em> element up and not the following elements).</p>\n\n<p><code>vertical-align: bottom</code> isn't doing anything for you either (<code>#main</code>). The vertical-align property only works on inline or table-cell elements.</p>\n\n<p>It's not really a good idea to set fixed heights on elements that will have an unknown amount of content (<code>#main</code>). Scrollbars give users clues as to how much content there is on the page. It can be confusing to the user when they scroll and scroll, but there's no more content to find. If the content is longer than you've allowed for, it will spill out of the container or get clipped off (depending on the element's overflow setting).</p>\n\n<p>If you want your footer to be at the bottom of the viewport, then yes, you need <code>bottom: 0</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T20:38:05.900",
"Id": "45776",
"Score": "0",
"body": "Thank you tons for all the detailed information!!! I think out of all the help that I have been getting your answer really made it clear. One question I have is about fixed heights. So I want a fixed height for the main content between the header and footer. If I remove height it moves the content div all the way to the header and looks very unprofessional. So what is the best way for me to assign the height to be from the header to the footer and if content needs more room at the bottom it automatically extends with scroll? Any idea how to get that done?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T20:49:09.637",
"Id": "45777",
"Score": "0",
"body": "This question might be better asked on SO, but I usually recommend using an illusion to make you think the element is taller than it really is by setting a background color on an ancestor element. If you need it to work without an illusion, there are ways to do so using `display: table|table-row`: http://cssdeck.com/labs/8ocxwfbk"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T20:08:03.580",
"Id": "29042",
"ParentId": "29038",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29042",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-26T18:27:23.267",
"Id": "29038",
"Score": "0",
"Tags": [
"html",
"css"
],
"Title": "I want to see if there is anything I don't need in my CSS file for my current layout"
}
|
29038
|
<p>I have been working on a Bencoded string parser in order to improve my knowledge
of Haskell. After running the code through hlint, I still have a few questions:</p>
<ol>
<li><p>As I noted in the comments, the key value in the definition of BMapT should
always be a Bstr. Is there any way to enforce a particular data constructor when
pattern matching an algrebraic datatype?</p></li>
<li><p>Since Bencoded dictionaries are generally stored as human readable text, I
made an instance of the Show typeclass so that I could take Bencode structures
and turn them into text. I was wondering if this is the right thing to do, or if
Haskell has another typeclass for storage/serialization a la Python's <code>repr</code>. </p></li>
<li><p>This question is kind of nebulous, but would you consider this code
'idiomatic'? Code without style isn't worth writing :)</p></li>
</ol>
<p><strong>Code:</strong></p>
<pre><code>-- This is an implementation of Bencoding for bittorrent as described at
-- http://www.bittorrent.org/beps/bep_0003.html
module Bencode where
import Text.Parsec.ByteString
import Text.Parsec.Char
import Text.Parsec.Prim
import Text.Parsec.Combinator
import qualified Text.Parsec.Error as PE
import Data.Char
import qualified Data.Map as M
import qualified Control.Monad as Mon
-- Technically this first argument can only be a Bstr, but I don't know
-- how to express that
type BMapT = M.Map Bencode Bencode
-- I have no idea why Bstr is okay as a String when it's a ByteString
data Bencode = Bint Integer
| Bstr String
| Blist [Bencode]
| Bmap BMapT
deriving (Eq, Ord)
instance Show Bencode where
show (Bint i) = "i" ++ show i ++ "e"
show (Bstr s) = (show . length) s ++ ":" ++ s
show (Blist bs) = 'l':concatMap show bs ++ "e"
show (Bmap bm) = M.foldlWithKey (\a k b -> a ++ show k ++ show b) "d" bm ++ "e"
-- Parse a Bencoded Integer
bInt :: Parser Bencode
bInt = do char 'i'
num <- validNum
char 'e'
return $ Bint num
-- This parser parses valid integers in Bencodings
where validNum = do neg <- option ' ' (char '-')
d <- digit
case digitToInt d of
-- Only time the first digit == 0 is "i0e"
0 -> if neg == ' ' then
-- "i0e" allowed but NOT "i-0e" or zero padded integer
lookAhead (char 'e') >> return 0
else
parserFail "Can't have a negative zero"
_ -> many digit >>= \xs -> return $ read (neg:d:xs)
-- Parse a Bencoded String
bString :: Parser Bencode
bString = do ss <- many1 digit
char ':'
let size = read ss
Mon.liftM Bstr $ count size anyChar
bList :: Parser Bencode
bList = do char 'l'
ls <- many (bInt <|> bString <|> bList <|> bMap)
char 'e'
return $ Blist ls
-- A parser which parses bencoded dictionaries
bMap :: Parser Bencode
bMap = do char 'd'
entries <- many dictEntry
char 'e'
return $ Bmap $ M.fromList entries
-- This parser will parse a key-value pair
dictEntry :: Parser (Bencode, Bencode)
dictEntry = do key <- bString
value <- bString <|> bList <|> bInt <|> bMap
return (key, value)
-- This function reads a torrent file. readBencodedFile "filename" reads
-- that filename and returns the parsed bencoded dictionary
readBencodedFile :: String -> IO (Either PE.ParseError Bencode)
readBencodedFile = parseFromFile bMap
</code></pre>
|
[] |
[
{
"body": "<p>Below is your code with some minor tweaks and the comments moved into standard Haddock form.</p>\n\n<pre><code>module Bencode (readBencodedFile, BencodedValue(..), bencode, bencodeBS) where\n\nimport qualified Control.Monad as Mon\nimport Data.ByteString (ByteString)\nimport Data.ByteString.Char8 (pack)\nimport qualified Data.Map as M\nimport Text.Parsec.ByteString as ParseBS\nimport Text.Parsec.Char (anyChar, char, digit)\nimport Text.Parsec.Prim ((<|>), parserFail, runParser)\nimport Text.Parsec.Combinator (count, many1, option)\nimport qualified Text.Parsec.Error as PE\n\n\ntype BMapT = M.Map BencodedValue BencodedValue\n\ndata BencodedValue = Bint Integer\n | Bstr String\n | Blist [BencodedValue]\n | Bmap BMapT\n deriving (Eq, Ord, Show)\n\n\n-- |Transform a 'BencodedValue' back to an encoded string\nbencode :: BencodedValue -> String\nbencode (Bint i) = \"i\" ++ show i ++ \"e\"\nbencode (Bstr s) = (show . length) s ++ \":\" ++ s\nbencode (Blist bs) = 'l':concatMap bencode bs ++ \"e\"\nbencode (Bmap bm) = M.foldlWithKey (\\a k b -> a ++ bencode k ++ bencode b) \"d\" bm ++ \"e\"\n\n\n-- |Return a 'BencodedValue' value to it original encoded 'ByteString' form.\nbencodeBS :: BencodedValue -> ByteString\nbencodeBS = pack . bencode\n\n\n{-|\n 'readBencodedFile' reads data from a torrent file and returns the parsed\n result as a dictionary in a 'BencodedValue'.\n The 'String' is the filename of the torrent to read.\n -}\nreadBencodedFile :: String -> IO (Either PE.ParseError BencodedValue)\nreadBencodedFile = parseFromFile bMap\n\n------------------------\n-- Internal functions --\n------------------------\n\n-- |Parse a Bencoded Integer\nbInt :: ParseBS.Parser BencodedValue\nbInt = do char 'i'\n neg <- option ' ' (char '-')\n nums <- many1 digit\n char 'e'\n mkBint neg nums\n where\n mkBint ' ' ['0'] = return $ Bint 0\n mkBint '-' ('0':ns) = parserFail \"Can't have a negative zero\"\n mkBint _ ('0':ns) = parserFail \"Invalid number with a leading zero\"\n mkBint '-' nums = return $ Bint $ read ('-':nums)\n mkBint _ nums = return $ Bint $ read nums\n\n\n-- |Parse a Bencoded String\nbString :: ParseBS.Parser BencodedValue\nbString = do nums <- many1 digit\n char ':'\n mkBstring (read nums)\n where\n mkBstring size = do cs <- count size anyChar\n return $ Bstr cs\n\n\n-- |Parse a Bencoded List\nbList :: ParseBS.Parser BencodedValue\nbList = do char 'l'\n ls <- many1 (bInt <|> bString <|> bList <|> bMap)\n char 'e'\n mkBlist ls\n where\n mkBlist = return . Blist\n\n\n-- |Parse a Bencoded dictionary\nbMap :: ParseBS.Parser BencodedValue\nbMap = do char 'd'\n entries <- many1 dictEntry\n char 'e'\n mkBmap entries\n where\n mkBmap = return . Bmap . M.fromList\n\n\n-- |Parse a Bencoded dictionary entry.\n-- This is an internal function declared outside of 'bMap' to\n-- facilitate testing.\ndictEntry :: ParseBS.Parser (BencodedValue, BencodedValue)\ndictEntry = do key <- bString\n value <- bString <|> bList <|> bInt <|> bMap\n return (key, value)\n</code></pre>\n\n<p>Answers to your questions.</p>\n\n<ol>\n<li>Without getting REAL fancy there is no good way limit the BMap argument to a Bstr while it is an member of algebraic type.</li>\n<li>Your analogy to <code>repr</code> from Python is a good one. Typically if there is a Haskell <code>Show</code> instance there is also a <code>Read</code> instance so <code>show . read . show</code> is valid. In your case the result of show needs to be parsed again and you do not expose a parse from string/bytestring. I added a <code>bencode</code> and <code>bencodeBS</code> which takes a <code>BencodedValue</code> and outputs a String or ByteString.</li>\n<li>Look at where I simplified or renamed your items to see suggestions on idiomatic usage. On the whole you did pretty well. If I had more time I would have liked to transform your parser functions into Applicative style. By transitioning to the mkFoo functions I started that process for you if you like.</li>\n<li>In the code you ask about why this is a String when the ByteString is the input. It is because the parsers are returning Strings parsed from the ByteString. If the performance really matters you could transition over to Attoparsec.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-01T18:12:38.790",
"Id": "85508",
"Score": "0",
"body": "I apologize for not accepting this earlier! Thank you so much for this review. I like your addition of the mkBInt function, its definitely better than the repeated ifs I was using. You also inspired me to read the typeclassopedia which has made me a more effective Haskeller!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-29T00:40:51.830",
"Id": "45669",
"ParentId": "29050",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "45669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T06:33:06.337",
"Id": "29050",
"Score": "2",
"Tags": [
"haskell",
"functional-programming"
],
"Title": "Haskell Bencoded Dictionary Parser"
}
|
29050
|
<p>I have a web layout that I created and then later wanted to add a dropdown menu to it. I found that my html was not quite optimum for that, so I wrote some jQuery that is now working quite nicely but I need this to be critiqued to see if and where I could have changed some things here.</p>
<p>My dropdown menu is the class "drop" which is an absolutely positioned div nested within the div <code>main_right</code>. I felt this was the best place to put it because I could simply position it right under the <code>li</code> item above it and hopefully avoid too many cross browser display issues. It is set to <code>display:none</code> via CSS.</p>
<p><strong>HTML:</strong></p>
<pre><code> <div id="menu">
<ul>
<li><a href="">1</a></li>
<li><a href="">2</a></li>
<li><a href="">3</a></li>
<li><a href="">4</a></li>
<li><a href="">5</a></li>
</ul>
</div>
<div id="main">
<div class="main_left_index">
<!--some content-->
<ul class="large">
<li>who</li>
<li>what</li>
<li>when</li>
<li>where</li>
</ul>
<img style="float:left;" src="example" alt="some other attributes"/>
<p class="index"></p>
</div>
<div class="main_right">
<div class="drop">
<ul>
<li><a href="">this</a></li>
<li><a href="">that</a></li>
<li><a href="">then</a></li>
<li><a href="">things</a></li>
</ul>
</div>
<img src="example" width="267" height="415" alt="example" />
</div>
</div>
</code></pre>
<p>And now the CSS just for my menu, to kind of justify why I went the route I did:</p>
<pre><code>#menu{
height:50px;
width:100%;
background:url(example);
background-repeat:repeat-x;
color:#FFF;
}
#menu ul{
display:table;
table-layout:fixed;
padding:0;
margin:0 auto;
width:980px;
height:50px;
}
#menu ul li{
border-right:1px solid #CCCCCC;
display:table-cell;
float:none;
list-style:none;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size:14px;
line-height:50px;
text-align:center;
}
#menu ul li a{
display:block;
width:100%;
height:100%;
}
#menu ul li:first-child{
border-left:1px solid #CCCCCC;
}
#menu ul li:hover{
cursor:pointer;
background-image:url(example);
}
#menu ul li:first-child:hover{
text-decoration:underline;
}
#menu ul li:nth-child(2){
width:177px;
}
#menu ul li:nth-child(3){
width:168px;
}
#menu ul li:nth-child(4){
width:180px;
}
#menu ul li:nth-child(5){
width:220px;
}
</code></pre>
<p>And now the jQuery. If my divs were closer I would just have wrapped them in some type of container but I didn't think that was possible. So I essentially made a "buffer" with some <code>mousemove</code> variables and then set flags amongst the movement to control when the drop down should expand or collapse.</p>
<p><strong>jQuery:</strong></p>
<pre><code>var dropDown ={
start: function(){
overDrop = false;
$('#menu').on('mouseenter','ul li:nth-child(5)',function(){
$('div.drop').slideDown('fast');
//currentlyDown = true;
overMenu = true;
});
$('#menu').on('mouseleave','ul li:nth-child(5)',function(){
overMenu = false;
if(overDrop == false && yMenu < 55){
$('div.drop').slideUp('fast');
//currentlyDown = false;
}
});
$('#menu').on('mousemove','ul li:nth-child(5)',function(e){
yMenu = e.pageY - $(this).offset().top + 10
});
$('.main_right').on('mousemove','.drop',function(e){
yDrop = e.pageY - $(this).offset().top + 10
});
$('.main_right').on('mouseenter','.drop',function(){
overDrop = true;
});
$('.main_right').on('mouseleave','.drop',function(){
if(overMenu == false && yDrop >15){
$('div.drop').slideUp('fast');
}
overDrop = false;
});
}
}
$(document).ready(dropDown.start);
</code></pre>
<p>I think I need to add some X mouse coordinate checks to cover the lower corners...it is one inconsistency I am finding during further testing.</p>
|
[] |
[
{
"body": "<h2>HTML</h2>\n\n<p>Your html is <s><em>flawless</em></s> (to me) pretty good. Good job.</p>\n\n<h2>CSS</h2>\n\n<p><em>Also</em> <s>completely flawless</s> pretty good!. Well written, efficient, I wouldn't (personally) change a thing.</p>\n\n<h2>JQuery</h2>\n\n<p>You made a few formatting errors here. I'll refer you to this awesome <a href=\"http://javascript.crockford.com/code.html\" rel=\"nofollow\">JavaScript formatting guide by Douglas Crockford</a>, and walk you through a few <s>mistakes that I noticed</s> ways that you might make your formatting a little more conventional.</p>\n\n<p>The blank line here isn't suggested. Blank lines are, for the most part, best used at the bottom of function declarations (if at all).</p>\n\n<pre><code>var dropDown ={\n\n start: function(){\n</code></pre>\n\n<p>Instead:</p>\n\n<pre><code>var dropDown ={\n start: function(){\n</code></pre>\n\n<hr>\n\n<p>Uh oh... Global variable declarations. As a rule, you should keep variables in the proper scope. </p>\n\n<p>Instead of</p>\n\n<pre><code>overDrop = false;\n</code></pre>\n\n<p>use:</p>\n\n<pre><code>var overDrop = false; \n</code></pre>\n\n<p>or, at the top of the function:</p>\n\n<pre><code>var overDrop;\n</code></pre>\n\n<p>so that when you define <code>overDrop</code> it is defined in its proper scope.</p>\n\n<hr>\n\n<p>You have this commented out, but the variable hasn't been declared, so I assume there's no use for keeping it. </p>\n\n<pre><code>//currentlyDown = true;\n</code></pre>\n\n<hr>\n\n<p>Your indentation here is not conventional. You should keep indentation to a limit of 4 spaces, except for when wrapping a line that is too long, in which case an 8 space indentation is recommended. </p>\n\n<p>Instead of:</p>\n\n<pre><code>$('#menu').on('mousemove','ul li:nth-child(5)',function(e){\n yMenu = e.pageY - $(this).offset().top + 10\n }); \n</code></pre>\n\n<p>use:</p>\n\n<pre><code>$('#menu').on('mousemove', 'ul li:nth-child(5)', function (e) {\n yMenu = e.pageY - $(this).offset().top + 10\n});\n</code></pre>\n\n<hr>\n\n<p>So, finally:</p>\n\n<pre><code>var overMenu, overDrop, yMenue, yDrop;\nvar dropDown = {\n start: function () {\n overDrop = false;\n $('#menu').on('mouseenter', 'ul li:nth-child(5)', function () {\n $('div.drop').slideDown('fast');\n overMenu = true;\n });\n $('#menu').on('mouseleave', 'ul li:nth-child(5)', function () {\n overMenu = false;\n if (overDrop == false && yMenu < 55) {\n $('div.drop').slideUp('fast');\n }\n });\n $('#menu').on('mousemove', 'ul li:nth-child(5)', function (e) {\n yMenu = e.pageY - $(this).offset().top + 10\n });\n $('.main_right').on('mousemove', '.drop', function (e) {\n yDrop = e.pageY - $(this).offset().top + 10\n });\n $('.main_right').on('mouseenter', '.drop', function () {\n overDrop = true;\n });\n $('.main_right').on('mouseleave', '.drop', function () {\n if (overMenu == false && yDrop > 15) {\n $('div.drop').slideUp('fast');\n }\n overDrop = false;\n });\n }\n}\n$(document).ready(dropDown.start);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-26T20:57:46.880",
"Id": "104284",
"Score": "2",
"body": "As long as everyone involved in the maintenance of this code agrees that this is how they want it formatted, then there is no mistake. Nitpick about formatting when its inconsistent or significantly impacts readability, not because its in a style that differs from your own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-26T22:42:52.027",
"Id": "104296",
"Score": "1",
"body": "@cimmanon My answer is 100% based on best practices [as demonstrated by a *pretty reliable* source.](http://javascript.crockford.com/code.html)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-27T00:13:20.927",
"Id": "104305",
"Score": "0",
"body": "http://meta.codereview.stackexchange.com/q/2151/9357"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-26T11:26:33.197",
"Id": "58115",
"ParentId": "29052",
"Score": "4"
}
},
{
"body": "<p>I've made a <a href=\"http://jsbin.com/mipoxeco/1/?output\">JS Bin</a> from your posted code.</p>\n\n<h2>Initialization</h2>\n\n<p>When the pages is loaded, the dropdown menu starts in its expanded state. Is that what you want?</p>\n\n<h2>Usability, Positioning, and Semantic HTML</h2>\n\n<p>It's impossible to move from the \"5\" menu item to click on one of the items in the dropdown menu before it collapses. Perhaps it could work if the dropdown were positioned directly underneath \"5\", but you shouldn't rely on such fragile coincidences. The underlying problem is that semantically, the \"this-that-then-things\" dropdown menu should be a child of item \"5\" in the HTML.</p>\n\n<pre><code><div id=\"menu\">\n <ul>\n <li><a href=\"\">1</a></li>\n <li><a href=\"\">2</a></li>\n <li><a href=\"\">3</a></li>\n <li><a href=\"\">4</a></li>\n <li><a href=\"\">5</a>\n <ul class=\"drop\">\n <li><a href=\"\">this</a></li>\n <li><a href=\"\">that</a></li>\n <li><a href=\"\">then</a></li>\n <li><a href=\"\">things</a></li>\n </ul>\n </li>\n </ul>\n</div>\n</code></pre>\n\n<h2>CSS</h2>\n\n<p>You've hard-coded the width of menu items \"2\", \"3\", \"4\", \"5\" individually. If you need different widths, it would be easier to maintain if you specified the padding, so that each item's width scaled automatically according to the size of its content.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-26T23:58:49.533",
"Id": "58161",
"ParentId": "29052",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T06:56:37.980",
"Id": "29052",
"Score": "5",
"Tags": [
"javascript",
"jquery",
"css"
],
"Title": "Implementation quality of my afterthought jQuery drop-down menu?"
}
|
29052
|
<p>Code is below. I'd like to know if this is a solid/efficient implementation of the in-place quicksort algorithm and if my Python style is good (I know there are no comments for now). Code is also on Github here if you'd like: <a href="https://github.com/michaelrbock/data-structs-and-algos/blob/master/Sorts/quicksort.py">https://github.com/michaelrbock/data-structs-and-algos/blob/master/Sorts/quicksort.py</a> Thanks!</p>
<pre><code>def quicksort(lst):
if len(lst) <= 1:
return lst
lst, store_index = partition(lst)
return quicksort(lst[:store_index-1]) + [lst[store_index-1]] + quicksort(lst[store_index:])
def partition(lst):
if len(lst) % 2 == 0:
middle = (len(lst) / 2) - 1
else:
middle = len(lst) / 2
pivot_choice = get_median( [lst[0], lst[middle], lst[len(lst)-1]] )
if pivot_choice == lst[0]:
PIVOT_INDEX = 0
elif pivot_choice == lst[middle]:
PIVOT_INDEX = middle
elif pivot_choice == lst[len(lst)-1]:
PIVOT_INDEX = len(lst) - 1
pivot = lst[PIVOT_INDEX]
lst[0], lst[PIVOT_INDEX] = lst[PIVOT_INDEX], lst[0]
i = 1
for j in range(1, len(lst)):
if lst[j] < pivot:
lst[j], lst[i] = lst[i], lst[j]
i += 1
lst[0], lst[i-1] = lst[i-1], lst[0]
return lst, i
def get_median(nums):
values = sorted(nums)
if len(values) % 2 == 1:
return values[(len(values)+1)/2-1]
else:
lower = values[len(values)/2-1]
upper = values[len(values)/2]
return (lower+upper)/2
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T14:27:03.650",
"Id": "45808",
"Score": "0",
"body": "Doesn't using `sorted` in a sorting function defeat the purpose of writing your own sorting function?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T02:17:49.547",
"Id": "45879",
"Score": "0",
"body": "yes, yes it would. But in this case, `sorted()` in only used in the choice of pivot, which is really just some preprocessing outside of the quicksort. Though perhaps some more imaginative implementation would have been more in tune with the problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T23:05:28.613",
"Id": "46241",
"Score": "0",
"body": "The in-place sort doesn't work correctly. The returned list is sorted, but the list that you call `quicksort` on isn't neccessarily. `a = [2,99,1,0,3]; print quicksort(a), a` prints `[0, 1, 2, 3, 99] [0, 1, 2, 99, 3]`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-04T23:30:57.503",
"Id": "46423",
"Score": "0",
"body": "@flornquake, good point thanks. Any suggestions on how to improve this?"
}
] |
[
{
"body": "<p>Personally I like the style (especially the nice clear function and variable names). As its quicksort most of the code is straightforward enough that comments would probably only add meaning when it comes to the swapping. You should probably try and use four spaces, rather than tabs, for indenting the code (it's just common practice). The only minor stylistic change I would personally make is to uncapitalise <code>PIVOT_INDEX</code>. I know technically it is constant (in that it doesn't change value after it's assigned), but I just prefer to have one clear assignment for any constant values. However, I'm sure other people would disagree.</p>\n\n<p>As for efficiency, you're always going to be bounded by the algorithm itsef, but there are a couple changes you could make. You calculate <code>len(lst)</code> multiple times in partition. Rather than doing that, you could just assign it like <code>list_length = len(lst)</code> once at the start of the partition function. Not a big deal I know. The only other meaningful change I can think of is in your <code>get_median</code> function. As you know that it's always called with three values you could change it to:</p>\n\n<pre><code>def get_median(nums):\n values = sorted(nums)\n return values[1]\n</code></pre>\n\n<p>If you really want to be fancy you can replace the <code>get_median</code> and the whole if-then-else construct that determines the <code>PIVOT_INDEX</code> with something like:</p>\n\n<pre><code>PIVOT_INDEX = sorted(zip([lst[0], lst[middle], lst[list_length - 1]], [0, middle, list_length]))[1][1]\n</code></pre>\n\n<p>which will give you the index (0, <code>middle</code> or <code>list_length</code>) of the median value in the same way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T14:25:37.393",
"Id": "45807",
"Score": "1",
"body": "`len` [is an O(1) operation](http://wiki.python.org/moin/TimeComplexity) for Python lists, i.e. you don't calculate the length, you just read it. So there's no significant improvement there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T14:53:05.277",
"Id": "45812",
"Score": "0",
"body": "True. I suppose I worded it badly. I just meant that assigning a value to a variable is easier for the reader/writer of the code than explicitly evaluating it each time (although I suppose with len() its not a big deal)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T09:31:03.350",
"Id": "29054",
"ParentId": "29053",
"Score": "1"
}
},
{
"body": "<p>Your style is good.</p>\n\n<p>I had a little improvement for efficiency. Instead of using the condition <code>i % 2 == 0</code> for checking i as an even number you can instead use <code>i % 2</code> as a condition for checking i as an odd number. It reduces the number of comparisons and doesn't effect the functionality at all. It might not have the best readability but it improves time-efficiency. A simple comment can offset the readability lost.</p>\n\n<p>Also this seems like Python 2 so instead of using <code>range</code> which returns a list you should use <code>xrange</code> which returns a generator when you are looping. It costs a little time-performance but is usually compensated by the huge improvement in memory-performance. </p>\n\n<p>Also in the <code>median</code> function you can probably eliminate the <code>lower</code> and <code>upper</code> variable by using something like</p>\n\n<pre><code>return (\n values[len(values)/2-1] +\n values[len(values)/2]\n )/2\n</code></pre>\n\n<p>Hope this helped.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T22:56:25.770",
"Id": "46240",
"Score": "0",
"body": "`xrange` is not only more efficient than `range` memory-wise, it's also quite a bit faster when all you want to do is loop over a range of numbers.\n\nAs for the `lower` and `upper` variables, I think it is perfectly fine to assign them, even if you only use them once. Giving the values a name makes it immediately obvious what the piece of code is doing (imo it is even more readable than an explanatory comment would be)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T09:30:11.993",
"Id": "29258",
"ParentId": "29053",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T07:55:30.270",
"Id": "29053",
"Score": "5",
"Tags": [
"python",
"sorting",
"quick-sort"
],
"Title": "In-Place Quicksort in Python"
}
|
29053
|
<p>I have started to learn Java and I need your critique for my first program. It is an interpreter that can calculate any expression including <code>abs()</code>, <code>sqrt()</code>, <code>min()</code>, <code>max()</code>, <code>round()</code> and <code>pow()</code>.</p>
<p>What can you say about this? Are there any code defects or pointless comments?</p>
<p><code>Main</code> class</p>
<pre><code>import java.io.*;
public class Main {
static boolean Error=false;
public static void main(String args[]) throws Exception{
System.out.println("Type an expression to calculate \n" +
"abs(x) function returns absolute value of x\n" +
"sqrt(x) function returns square root of value x\n" +
"min(x,y,…) function returns a minimum value between x,y,...\n" +
"max(x,y,…) function returns a maximum value between x,y,...\n" +
"round(x) function returns a round value of x\n" +
"pow(x,y) function returns an exponentiation of x,y\n" +
"Type \"exit\" to exit");
while (true){
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
String stringForProcessing =read.readLine(); //Input a string to work with it
String output= Calculating.calculating(stringForProcessing); //Calculating
System.out.println(output);//Output
Error=false;
}
}
}
</code></pre>
<p><code>Calculating</code> class</p>
<pre><code>import java.lang.Math;
import java.util.ArrayList;
public class Calculating {
static String calculating(String workingString){
ArrayList<String> separatedString = new ArrayList<>();
int Position=0;
boolean Negative=false;
if(Main.Error){ //return error report
return(workingString);
}
while(Position<workingString.length()){ //reducing spaces
if(workingString.charAt(Position)==' '){
while (((Position)<workingString.length())
&&(workingString.charAt(Position)==' ')){
Position++;
}
}
else if (workingString.charAt(Position)=='-'&&(Position==0 //checking value for negativity
|| workingString.charAt(Position-1)=='-'
|| workingString.charAt(Position-1)=='+'
|| workingString.charAt(Position-1)=='*'
|| workingString.charAt(Position-1)=='/')){
Negative=true;
Position++;
}
else if ((workingString.charAt(Position)=='-' //checking for repeating operators
|| workingString.charAt(Position)=='+'
|| workingString.charAt(Position)=='*'
|| workingString.charAt(Position)=='/')
&&(Position==0
|| workingString.charAt(Position-1)=='-'
|| workingString.charAt(Position-1)=='+'
|| workingString.charAt(Position-1)=='*'
|| workingString.charAt(Position-1)=='/')){
Main.Error=true;return("Error: two or more operators in a row");
}
separatedString.add(Character.toString(workingString.charAt(Position)));
if (workingString.charAt(Position)=='('){ //Creating bracer stack to parse
int BrcrStack=1;
String Temp="";
while (((Position+1)<workingString.length())){
switch (workingString.charAt(Position+1)){
case '(':BrcrStack++;break;
case ')':BrcrStack--;break;
}
Position++;
if(BrcrStack!=0){
Temp+=workingString.charAt(Position);
}
else {break;}
}
if(BrcrStack!=0){
Main.Error=true;return("Error: missing \")\"");
}
separatedString.set(separatedString.size()-1, calculating(Temp));
}
else if (Character.isDigit(workingString.charAt(Position))){ //Bolting numbers
while (((Position+1)<workingString.length())&&(Character.isDigit(workingString.charAt(Position+1))
|| workingString.charAt(Position+1)=='.') ){
separatedString.set(separatedString.size()-1,
separatedString.get(separatedString.size()-1)+workingString.charAt(Position+1));
Position++;
}
try {
Float.valueOf(separatedString.get(separatedString.size()-1));}
catch(Exception e){
Main.Error=true;return("Error: multiple points");
}
if(Negative){ //Negate parameter
separatedString.set(separatedString.size()-1,Float.toString(-(Float.valueOf(separatedString.get(separatedString.size()-1)))));
Negative=false;
}
}
else if (Character.isAlphabetic(workingString.charAt(Position))){ //Bolting functions
while (((Position+1)<workingString.length())
&&(Character.isAlphabetic(workingString.charAt(Position+1))) ){
separatedString.set(separatedString.size()-1,
separatedString.get(separatedString.size()-1)+workingString.charAt(Position+1));
Position++;
}
switch (separatedString.get(separatedString.size()-1)){ //Checking functions
case "abs":break;
case "sqrt":break;
case "min":break;
case "max":break;
case "round":break;
case "pow":break;
case "exit":System.exit(0);
default: {
Main.Error=true;return("Error: unknown function \""+separatedString.get(separatedString.size()-1)+"\"");
}
}
if ((Position+1)==workingString.length()||workingString.charAt(Position+1)!='(') //Parsing function parameters
{
Main.Error=true;return("Error: missing \"(\" after "+"\""+separatedString.get(separatedString.size()-1)+"\" "+ "function");
}
ArrayList<String> Temp = new ArrayList<>();
int BrcrStack=1;
Temp.add("");
while (((Position+2)<workingString.length())){
switch (workingString.charAt(Position+2)){
case '(':BrcrStack++;break;
case ')':BrcrStack--;break;
case ',': if (BrcrStack==1){Temp.add("");Position++;continue;}break;
}
Position++;
if(BrcrStack!=0){Temp.set(Temp.size()-1,Temp.get(Temp.size()-1)+Character.toString(workingString.charAt(Position+1)));}
else {break;}
}
if(BrcrStack!=0){
Main.Error=true;return("Error: missing \")\"");}
Position++;
float FuncArr[]=new float[Temp.size()];
for (int i=0;i<Temp.size();i++){
Temp.set(i, Calculating.calculating(Temp.get(i)));
if (Temp.get(i).length()==0){
Main.Error=true;return("Error: missing expression");}
FuncArr[i]=Float.valueOf(Temp.get(i));
}
switch (separatedString.get(separatedString.size()-1)){ //Calculating functions
case "abs":if (FuncArr.length==1) {
separatedString.set(separatedString.size()-1,Float.toString(Math.abs(FuncArr[0])));}
else {
Main.Error=true;return("Error: \"abs\" function needs only one argument");}break;
case "sqrt":if (FuncArr.length==1) {
double a=FuncArr[0];
separatedString.set(separatedString.size()-1,Double.toString(Math.sqrt(a)));}
else {
Main.Error=true;return("Error: \"sqrt\" function needs only one argument");}break;
case "min":separatedString.set(separatedString.size()-1,Float.toString(Min(FuncArr))) ;break;
case "max":separatedString.set(separatedString.size()-1,Float.toString(Max(FuncArr))) ;break;
case "round":if (FuncArr.length==1) {
separatedString.set(separatedString.size()-1,Float.toString(Math.round((FuncArr[0]))));}
else {
Main.Error=true;return("Error: \"round\" function needs only one argument");}break;
case "pow":if (FuncArr.length==2) {
separatedString.set(separatedString.size()-1,Double.toString(Math.pow(FuncArr[0],FuncArr[1])));}
else {
Main.Error=true;return("Error: \"pow\" function needs only two arguments");}break;
}
}
Position++;
}
ArrayList<String> ResultArr = new ArrayList<>();
if(Negative){ //Negate parameter
separatedString.set(separatedString.size()-1,Float.toString(-(Float.valueOf(separatedString.get(separatedString.size()-1)))));
}
ArrayList<String> Stack = new ArrayList<>();
int i=0;
while (i<separatedString.size()){ //Converting expression to postfix notation
if (separatedString.get(i).length()==1&&(separatedString.get(i).charAt(0)=='+'||separatedString.get(i).charAt(0)=='-'||separatedString.get(i).charAt(0)=='/'||separatedString.get(i).charAt(0)=='*')){
if(Stack.size()==0){
Stack.add(separatedString.get(i));
}else {
if ((separatedString.get(i).charAt(0) == '+' || separatedString.get(i).charAt(0) == '-') && (Stack.get(Stack.size() - 1).charAt(0) == '*' || Stack.get(Stack.size() - 1).charAt(0) == '/')) {
Stack.add(separatedString.get(i));
} else {
Stack.add(separatedString.get(i));
Stack.add(separatedString.get(i+1));
i++;
while (Stack.size() > 0) {
ResultArr.add(Stack.get(Stack.size()-1));
Stack.remove(Stack.size() - 1);
}
}
}
}
else{
ResultArr.add(separatedString.get(i));
}
i++;
}
while (Stack.size() > 0) {
ResultArr.add(Stack.get(Stack.size()-1));
Stack.remove(Stack.size() - 1);
}
i=0;
while (ResultArr.size()>1){ //Calculating postfix expression
if (ResultArr.get(i).length()==1&&(ResultArr.get(i).charAt(0)=='+'||ResultArr.get(i).charAt(0)=='-'||ResultArr.get(i).charAt(0)=='/'||ResultArr.get(i).charAt(0)=='*')){
switch (ResultArr.get(i).charAt(0)){
case '+':ResultArr.set(i-2,Float.toString(Float.valueOf(ResultArr.get(i-2))+Float.valueOf(ResultArr.get(i-1))));ResultArr.remove(i);ResultArr.remove(i-1);break;
case '-':ResultArr.set(i-2,Float.toString(Float.valueOf(ResultArr.get(i-2))-Float.valueOf(ResultArr.get(i-1))));ResultArr.remove(i);ResultArr.remove(i-1);break;
case '*':ResultArr.set(i-2,Float.toString(Float.valueOf(ResultArr.get(i-2))*Float.valueOf(ResultArr.get(i-1))));ResultArr.remove(i);ResultArr.remove(i-1);break;
case '/':ResultArr.set(i-2,Float.toString(Float.valueOf(ResultArr.get(i-2))/Float.valueOf(ResultArr.get(i-1))));ResultArr.remove(i);ResultArr.remove(i-1);break;
}
i=0;
}
i++;
}
String Result="";
for (String aResultArr : ResultArr) {
Result += aResultArr;
}
if (Float.valueOf(Result)==Math.floor(Float.valueOf(Result))){
Result=Integer.toString(Math.round(Float.valueOf(Result)));
}
return Result;
}
static float Min(float Arr[]){
float Min=Arr[0];
for (int i=1;i<Arr.length;i++){
if (Arr[i]<Min){Min=Arr[i];
}
}
return Min;
}
static float Max(float Arr[]){
float Max=Arr[0];
for (int i=1;i<Arr.length;i++){
if (Arr[i]>Max){Max=Arr[i];
}
}
return Max;
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Formatting</h2>\n\n<ul>\n<li><a href=\"http://en.wikipedia.org/wiki/Naming_convention_%28programming%29#Java\" rel=\"nofollow noreferrer\">Your variable names should start with a lower case letter by convention.</a></li>\n<li>Try to have spaces around operators (<code>+</code>, <code>==</code> etc.)</li>\n<li>Try to have spaces after <code>if</code>, <code>while</code> etc.</li>\n<li>don't have superlong lines. Somebdoy recommends hardlimit on 80 chars, somebody a soft limit on 120 chars, it doesn't matter. Simply try to have shorter lines if it's possible.</li>\n<li><a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\" rel=\"nofollow noreferrer\">generally, these formatting conventions are good to follow</a> (As a baseline, not as a hard rule. They are quite aged, don't contain information about some of the newer Java features (annotations, generics...), enforce the nowadays-controversial spaces instead of tabs and a hard limit of 80 chars-per line.)</li>\n<li>instead of <code>ArrayList<Something> list = new ArrayList<>();</code>, use <code>List<Something> list = new ArrayList<>();</code> See <a href=\"https://stackoverflow.com/questions/9852831/polymorphism-why-use-list-list-new-arraylist-instead-of-arraylist-list-n\">here</a> or <a href=\"http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>anyway, you got the formatting pretty much right</li>\n</ul>\n\n<h2>Code</h2>\n\n<ol>\n<li><p>This:</p>\n\n<pre><code>String result = \"\";\nfor (String aResultArr : resultArr) {\n result += aResultArr;\n}\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/65727/1273080\">is horribly wrong.</a> Strings in Java are immutable, which means that you can't add anything to an existing String. What happens instead is that a new String is allocated and all the characters are copied. This is a killer when used in a loop.</p>\n\n<p>The right way is to use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html\" rel=\"nofollow noreferrer\"><code>StringBuilder</code></a>:</p>\n\n<pre><code>StringBuilder resultBuilder = new StringBuilder();\nfor (String aResultArr : resultArr) {\n resultBuilder.append(aResultArr);\n}\nString result = resultBuilder.toString();\n</code></pre>\n\n<p>By the way, <code>\"some\" + \"thing\"</code> gets internally compiled to <code>new StringBuilder().append(\"some\").append(\"thing\").toString()</code> anyway (because of the String immutability I talked about).</p></li>\n<li><p>You should generally split your code to have fewer loops, less indenting, much more methods. That way, it will be a lot more readable, maintainable (and therefore less error-prone). For example, this code in the main parsing <code>while</code> loop:</p>\n\n<pre><code>// reducing spaces\nif (workingString.charAt(position) == ' ') {\n while ((position < workingString.length())\n && (workingString.charAt(position) == ' ')) {\n position++;\n }\n}\n</code></pre>\n\n<p>This could be a separate method <code>skipSpaces()</code>.</p>\n\n<p>Or, even better, move it out from the main loop. Do you want to strip the user input of all spaces? Do it right away when you read it!</p>\n\n<pre><code>// Input a string to work with it, strip it of all spaces\nString stringForProcessing = read.readLine().replace(\" \", \"\");\n</code></pre>\n\n<p>Or, again, in a method, so it's possible to have a high-level overview over the code:</p>\n\n<pre><code>// Input a string to work with it\nString stringForProcessing = read.readLine();\nstringForProcessing = stripOfSpaces(stringForProcessing);\n</code></pre></li>\n<li><p>Comment your code. Don't explain what it does. For example,</p>\n\n<pre><code>// Calculating\nString output = Calculating.calculating(stringForProcessing);\n</code></pre>\n\n<p>this one is pretty redundant. The code is self-explanatory. Or at least should be (again, split it into multiple methods).</p>\n\n<p>So don't explain what. Explain <em>why</em>.</p>\n\n<pre><code>//checking value for negativity\nif ((workingString.charAt(position) == '-')\n && (position == 0\n || workingString.charAt(position - 1) == '-'\n || workingString.charAt(position - 1) == '+'\n || workingString.charAt(position - 1) == '*'\n || workingString.charAt(position - 1) == '/')) {\n</code></pre>\n\n<p>So this one checks for negativity. Cool. That comment should have been a method name <code>private static boolean checkNegative(String workingString, int pos)</code>. Or something similar.</p>\n\n<p>The comment? Not needed.</p>\n\n<p>What I don't understand (usually until I dive really deep into the code) is why is the condition so long and why is it checking previous characters, too. That should be commented: <code>// checking previous chars, because of ...</code></p></li>\n<li><p>Cache often used values.</p>\n\n<p>If you wrote <code>workingString.charAt(position - 1)</code> four times in a condition, you probably should have used</p>\n\n<pre><code>char previousChar = workingString.charAt(position - 1);\n</code></pre>\n\n<p>And then use this cached value in your condition. Your lines will be shorter, your code will be more clear and faster.</p>\n\n<p>Same problem:</p>\n\n<pre><code>if (Float.valueOf(result) == Math.floor(Float.valueOf(result))) {\n result = Integer.toString(Math.round(Float.valueOf(result)));\n}\nreturn result;\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>float numResult = Float.valueOf(result);\nif (numResult == Math.floor(numResult)) {\n result = Integer.toString(Math.round(numResult));\n}\nreturn result;\n</code></pre>\n\n<p>This issue is all around your code and would help quite a lot when gotten right. However, don't obsess about caching too much - it can hurt readability when used excessively. And readability should be one of your main concerns.</p></li>\n<li><p>If you want to use something as a stack, look for a implemetation of stack, don't use a <code>List</code>. Your code will be much more readable, because you won't have to call <code>stack.get(stack.size() - 1)</code>, but will use <code>stack.getLast()</code> instead.</p>\n\n<p>Also, try to avoid <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Stack.html\" rel=\"nofollow noreferrer\"><code>java.util.Stack</code></a> for reasons you don't yet understand (think \"it's old\"). Use a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html\" rel=\"nofollow noreferrer\"><code>Deque</code></a> interface and a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/ArrayDeque.html\" rel=\"nofollow noreferrer\"><code>ArrayDeque</code></a> (preferred) or <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html\" rel=\"nofollow noreferrer\"><code>LinkedList</code></a> implementation.</p>\n\n<pre><code>Deque<String> stack = new ArrayDeque<>();\n</code></pre></li>\n<li><p>When done with this, instead of your old</p>\n\n<pre><code>while (Stack.size() > 0) {\n ResultArr.add(Stack.get(Stack.size()-1));\n Stack.remove(Stack.size() - 1);\n}\n</code></pre>\n\n<p>you'll end up with code like this:</p>\n\n<pre><code>while (stack.size() > 0) {\n resultArr.add(stack.getLast());\n stack.removeLast();\n}\n</code></pre>\n\n<p>While visibly better, it can still be improved to:</p>\n\n<pre><code>while (!stack.isEmpty()) {\n resultArr.add(stack.removeLast());\n}\n</code></pre></li>\n<li><p>You're parsing strings to numbers, then performing operations on them and then converting them back to strings. Highly inefficient and confusing both for you and for me. Consider storing numbers as ... numbers. I admit that to do this effectively and nicely, you'll probably need to write some classes or enums. That is a step up from your current programming level, so don't bother with it until you're sure what you're doing at the current level. But it's something to consider. <a href=\"https://stackoverflow.com/questions/5926155/calculator-without-if-else-or-switch\">The same applies to operations which can be implemented as enums/classes.</a></p></li>\n</ol>\n\n<p>Wow. I didn't expect this to get so long. It's definitely not all the things that could use some polishing, but it's what caught my eye while going through. I think it's enough for today :).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T13:56:35.977",
"Id": "29060",
"ParentId": "29055",
"Score": "4"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/29060/26200\">Slanec's answer</a> explains it's all. But I would like to add some points.</p>\n\n<ol>\n<li>If you are writing your code in any IDE, try to use some source code analyzer like <a href=\"http://pmd.sourceforge.net/\" rel=\"nofollow noreferrer\">PMD</a>. It will complain about unnecessary code content.</li>\n<li><p>Your <code>boolean</code> field <code>Error</code> doesn't change and always stays as <code>false</code>. So I think you don't need to use that field. So the code snippet </p>\n\n<pre><code>if(Main.Error){ //return error report\n return(workingString);\n}\n</code></pre>\n\n<p>will not execute ever and makes it unnecessary.</p></li>\n<li>Try to <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> your code and remember to <a href=\"https://sites.google.com/site/unclebobconsultingllc/one-thing-extract-till-you-drop\" rel=\"nofollow noreferrer\">Do Only One Thing</a>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T17:06:42.693",
"Id": "29066",
"ParentId": "29055",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29060",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T10:10:44.937",
"Id": "29055",
"Score": "4",
"Tags": [
"java",
"beginner",
"math-expression-eval"
],
"Title": "Evaluating expressions with various mathematical methods"
}
|
29055
|
<p>I'm making this web application that needs some very simple JavaScript/HTML5 related features integrated (hereby an upload feature). However, I'm not sure about whether I've overdone it, as it's the first time I'm writing JavaScript without just throwing it all into the same file, with no namespace.</p>
<p>For example, I'm not sure whether it's worth it to create "alias" for functions, in order to prevent typing mistakes (ex. <code>FileInputs: $("#fileInputs")</code>), or if it's just plain useless.</p>
<p><strong>App.js</strong></p>
<pre><code>var NORTH = {
App: {
Utilities: {},
Tools: {]
},
Views: {}
};
</code></pre>
<p><strong>Uploads.js</strong></p>
<pre><code>NORTH.Views.Uploads = {
Index: {
Progress: {
totalBytes: 0,
percentComplete: 0,
bytesUploaded: 0,
prevBytesUploaded: 0
},
FileInputs: $("#fileInputs"),
FileToUploadInput: $("#fileFake"),
UploadButton: $("#upload"),
FileInfo: $("#fileInfo"),
FileSize: $("#fileSize"),
PasswordInput: $("#password"),
UploadProgress: $("#uploadProgress"),
TransferRate: $("#transferRate"),
TimeRemaining: $("#timeRemaining"),
UploadStatus: $("#uploadStatus"),
DownloadInfo: $("#downloadInfo"),
DownloadLink: $("#downloadLink"),
DdownloadPasswordWrapper: $("#downloadPasswordWrapper"),
DownloadPassword: $("#downloadPassword"),
loadEvents: function () {
var _this = this;
$("#fileFake").bind("click", function () {
$("#file").trigger("click");
});
$("#file").bind("change", function () {
var file = this.files[0];
_this.DownloadInfo.hide();
_this.FileInfo.hide();
_this.FileSize.html(file.size);
_this.PasswordInput.val("");
_this.FileInfo.show();
});
$("#upload").bind("click", function () {
_this.FileInfo.hide();
_this.FileToUploadInput
.attr("disabled", true);
_this.UploadButton
.removeClass("enabled")
.addClass("disabled")
.attr("disabled", true);
_this.UploadProgress.show();
_this.upload(_this.PasswordInput.val());
});
},
init: function() {
this.loadEvents();
},
enableAndResetFileInputs: function () {
var defaultValue = this.FileToUploadInput.data("defaultValue");
this.FileToUploadInput.val(defaultValue);
this.FileToUploadInput.attr("disabled", false);
this.UploadButton
.removeClass("disabled")
.addClass("enabled")
.attr("disabled", false);
},
upload: function (password) {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", window.location.origin + "/?pwd=" + password);
xhr.send(formData);
},
uploadProgress: function (evt) {
if (evt.lengthComputable) {
this.percentComplete = Math.round(evt.loaded * 100 / evt.total);
this.bytesUploaded = evt.loaded;
this.totalBytes = evt.total;
}
},
uploadComplete: function (evt) {
this.UploadProgress.hide();
this.enableAndResetFileInputs();
if (evt.target.status != 200) {
var error = this.UploadButton.data("httpCodeError");
this.UploadStatus(error);
return false;
}
var json = jQuery.parseJSON(evt.target.responseText);
if (json.ErrorCode != null) {
var error = json.ErrorCode == 1 ? "fileTooBigError" : "fileTooBigLimitError";
this.UploadStatus.html(error);
return false;
}
var path = window.location.origin + "/files" + json.Directory;
this.DownloadLink.val(path);
if (json.Password.length != 0) {
this.DownloadPassword.val(json.Password);
this.DownloadPasswordWrapper.show();
}
var success = this.UploadButton.data("success");
this.UploadStatus.html(success);
// TODO: Call GetUsage for refresh
},
uploadFailed: function (evt) {
this.enableAndResetFileInputs();
if (evt.target.responseText != "") {
this.UploadStatus.html(evt.target.responseText);
return false;
}
var error = this.UploadButton.data("failed");
alert(error);
},
uploadCanceled: function (evt) {
this.enableAndResetFileInputs();
var message = this.UploadButton.data("canceled");
alert(message);
},
updateProgress: function () {
var uploaded = this.Progress.bytesUploaded;
var diff = uploaded - this.Progress.prevBytesUploaded;
if (diff == 0)
return;
prevBytesUploaded = uploaded;
diff = diff * 2;
var bytesRemaining = this.Progress.totalBytes - prevBytesUploaded;
var secondsRemaining = bytesRemaining / diff;
var time = NORTH.App.Utilities.secondsToTime(Math.round(secondsRemaining));
var speed = (Math.round(diff * 100 / (1024 * 1024)) / 100).toString() + ' MB/s';
this.TransferRate.html(speed);
this.TimeRemaining.html(timeH + ":" + timeM + ":" + timeS);
},
}
};
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>I think it will be better if all selectors will be in options for <code>init</code> method and all of that fields like <code>FileInputs</code> will be initialized also in <code>init</code>, so I can put <code>Upload.js</code> in header and call <code>init</code> after document ready.</li>\n<li>I prefer prefix <code>$</code> in fields names with jQuery objects like <code>$fileInputs</code>.</li>\n<li>As for me <code>_this</code> not the best choice, better something like <code>uploader</code>.</li>\n<li>Instead of <code>bind</code> method use <code>on</code></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T10:41:09.677",
"Id": "29260",
"ParentId": "29058",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T12:49:14.013",
"Id": "29058",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"ajax",
"network-file-transfer"
],
"Title": "File uploader using XMLHttpRequest"
}
|
29058
|
<p>I would really appreciate a review of my interpretation of MVC <a href="http://jsfiddle.net/zuVkt/" rel="nofollow">here</a>.</p>
<p>It's as bare bones and clear as possible. I've based it on some in-depth reading but I don't know if I have understood everything correctly! </p>
<ol>
<li>For example, how have I wired the model <code>onChange</code> to the controller? </li>
<li>Where/when should the view be initialised, and does it follow to bind DOM events in that init function? </li>
<li>Am I right to pass a path into the controller, thus binding view to one node in the model?</li>
</ol>
<hr>
<p><strong>MVC Objects</strong></p>
<pre><code>(function(window, document, undefined){
//Add namespace to window
window.mvc = {
Model: Model,
View: View,
Controller: Controller
}
/*----------
Objects
---------*/
function Model(tree){
//Constructor
var model = this;
model.tree = tree || {};
model.cbFns = []; //onChange callbacks
}
Model.prototype = {
set: function(props){
//Set a node value
var model = this,
cbFns = model.cbFns;
mixin(model.tree, props);
//Run any registered callbacks
var i = cbFns.length;
while(i--)cbFns[i].call();
},
get: function(p){
//Get a node value
var model = this;
return getNode(model.tree, p);
},
toJSON: function(){
//Render tree as JSON
var model = this;
return JSON.stringify(model.tree);
},
onChange: function(cbFn){
//Register a change callback
var model = this;
model.cbFns.push(cbFn);
}
}
function View(props){ //props must contain 'render' method
//Constructor
var view = this;
mixin(view, props);
}
function Controller(props){ //props must contain 'model', 'view' objects and 'path' string
//Constructor
var controller = this;
mixin(controller, props);
controller.view.controller = controller; //Ref to controller on view
//Add callback to model
controller.model.onChange(function(){
controller.get();
});
}
Controller.prototype = {
set: function(val){
//Write to model
var controller = this,
setArgs = {};
setArgs[controller.path] = val;
controller.model.set(setArgs); //Write to model
},
get: function(){
//Update view from model
var controller = this;
controller.view.render(controller.model.get(controller.path));
}
}
/*--------
Utils
-------*/
var pathSeparator = ".";
function setNode(tree, pathStr, value){
//Set node at path string
var pathArr = pathStr.split(pathSeparator),
prop = pathArr.pop(),
parentPathStr = pathArr.join(pathSeparator),
currNode = parentPathStr && getNode(tree, parentPathStr) || tree;
currNode[prop] = value;
}
function getNode(tree, pathStr){
//Get node from path string
var pathArr = pathStr.split(pathSeparator),
currNode = tree,
i = pathArr.reverse().length;
while(i--)currNode = currNode[pathArr[i]];
return currNode;
}
function mixin(ob1, ob2){
//Add/overwrite all properties right to left
for(var p in ob2){
if(ob2.hasOwnProperty(p)){
setNode(ob1, p, ob2[p]);
}
}
}
})(window, document);
</code></pre>
<p><strong>Application</strong></p>
<pre><code>(function(window, document, undefined){
var mvc = window.mvc,
form = document.getElementById("userForm");
//Create user model
var userModel = new mvc.Model({
profile: {
name: "Prof Farnsworth",
age: "160",
region: "Space"
}
});
function createInputField(model, path){
//Creates MVC input fields
//View is the same for all input fields
var inputView = new mvc.View({
init: function(){
var view = this,
controller = view.controller;
view.domEl = createEl("input", form);
view.domEl.onblur = function(e){
controller.set(this.value);
}
controller.get();
},
render: function(data){
var view = this;
view.domEl.value = data;
}
});
//Create controller
new mvc.Controller({
view: inputView,
model: model,
path: path
});
//Initialise view
inputView.init();
}
//Fields
createInputField(userModel, "profile.name"),
createInputField(userModel, "profile.age");
createInputField(userModel, "profile.region");
//Button to update model
var testBtn = createEl("button", document.body, "Update model");
testBtn.onclick = function(e){
userModel.set({"profile.name":"Zoidberg"});
}
//Button to log model
var logBtn = createEl("button", document.body, "Log model to console");
logBtn.onclick = function(e){
console.log( userModel.toJSON() );
}
/*--------
Utils
-------*/
function createEl(type, parent, innerHTML){
var el = document.createElement(type);
if(parent)parent.appendChild(el);
if(innerHTML)el.innerHTML = innerHTML;
return el;
}
})(window, document);
</code></pre>
|
[] |
[
{
"body": "<p>*\n<code>model.cbFns = []; //onChange callbacks</code></p>\n\n<p>I would rename this to callBacks, <code>cbFns</code> just feels wrong</p>\n\n<pre><code> set: function(props){\n //Set a node value\n var model = this,\n cbFns = model.cbFns;\n mixin(model.tree, props);\n\n //Run any registered callbacks\n var i = cbFns.length;\n while(i--)cbFns[i].call();\n },\n</code></pre>\n\n<p>calling the callbacks seems non-intuitive, how about</p>\n\n<pre><code> set: function(props){\n var model = this;\n mixin(model.tree, props);\n model.cbFns.forEach( function(f){ f(); } ) \n },\n</code></pre>\n\n<p>These 2 lines:</p>\n\n<pre><code>var model = this; \nvar view = this; \n</code></pre>\n\n<p>Not sure this is useful, especially in 2 liner functions</p>\n\n<p>From a design perspective, it seems as if you create a View per input field. Usually there is 1 view with each field being a child of it?\nAlso the logic within createInputField() really should not be part of Application?</p>\n\n<p>A view should be able to generate the entire model, so it should know how to do all the work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:32:37.750",
"Id": "46016",
"Score": "0",
"body": "Thanks for feedback I will try your suggested changes! The logic in createInputField()... I figured that different views will need different render() and init() functions. So say, input fields need an onblur event on the DOM element but other views might have onclick. So I'm supplying them when creating the view, to keep the MVC logic generic. Is there a better way of initialising the view?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:15:57.200",
"Id": "29143",
"ParentId": "29061",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T11:36:37.047",
"Id": "29061",
"Score": "3",
"Tags": [
"javascript",
"design-patterns",
"mvc",
"dom"
],
"Title": "First attempt at MVC JavaScript pattern"
}
|
29061
|
<p>I am creating a dynamic menu whose items appear depending on a set 'mode' (that is passed via AJAX). Off this it creates the menu, disabling and hiding icons that are not associated with that mode.</p>
<p>The problem is, there are a lot of <code>if</code> conditions in my implementation. Can anyone show me a cleaner way of doing what I am trying to achieve?</p>
<pre><code>public function gridMenu()
{
$mode = Validate::sanitize($_POST['mode']);
$modes = array(
'products' => array('edit', 'delete', 'archive')
);
$output = '<div id="hexContainer">';
for($i = 1; $i < 7; $i++) {
$img = '';
$output .= '<div class="hex hex' . $i;
if($i == 1)
{
if(in_array('edit', $modes[$mode]))
{
$output .= ' hex-selectable';
$img = '<img data-option="Edit" src="' . ROOT . 'images/edit.png">';
} else {
$output .= ' hex-disabled';
}
}
if($i == 2)
{
if(in_array('zzz', $modes[$mode]))
{
$output .= ' hex-selectable';
} else {
$output .= ' hex-disabled';
}
}
if($i == 3)
{
if(in_array('delete', $modes[$mode]))
{
$output .= ' hex-selectable';
$img = '<img data-option="Delete" src="' . ROOT . 'images/delete.png">';
} else {
$output .= ' hex-disabled';
}
}
if($i == 4)
{
if(in_array('xxx', $modes[$mode]))
{
$output .= ' hex-selectable';
} else {
$output .= ' hex-disabled';
}
}
if($i == 5)
{
if(in_array('archive', $modes[$mode]))
{
$output .= ' hex-selectable';
$img = '<img data-option="Archive" src="' . ROOT . 'images/archive.png">';
} else {
$output .= ' hex-disabled';
}
}
if($i == 6)
{
if(in_array('zzz', $modes[$mode]))
{
$output .= ' hex-selectable';
} else {
$output .= ' hex-disabled';
}
}
$output .= '">';
$output .= $img;
$output .= '</div>';
}
$output .= '<div class="hex hex-mid"></div>';
$output .= '</div>';
echo $output;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code has multiple bad practices.</p>\n\n<p>There is no speration of concern. Your code is handling display, logic and controlling. All in onde function.</p>\n\n<p>If I look at the function, it tells me it needs nothing (no arguments need to be passed in). So the only thing it should be using are variables that are accessible inside the object scope. BUT it turns out you are using a 'Validate' class and variables from the global scope ($_POST). I only know this because I read the entire code. No really nice towards other developers or the future you demaning that one should read the entire code before knowing how to use it and what is going on. And then ofcourse the biggest problem. al those if's</p>\n\n<p>So, some problems and lets fix those problems.</p>\n\n<p>You sanitize a variable that is handed in by the client ($_POST). You then create an array of possible 'modes' out of the blue. And after that you construct some html with images and a lot of business logic in it. Your function really has to be all knowing!</p>\n\n<p>So, let's sepperate the concerns.</p>\n\n<p>the <code>$mode</code> is clearly something the function needs to do it's magic. So this sould be a paramter that is passed in:</p>\n\n<pre><code>public function gridMenu(String $mode);\n</code></pre>\n\n<p>Note that the $mode needs to be a string. (obviously)</p>\n\n<p>Another thing this function absolutely needs is the <code>$modes</code> variable. But, this variable doesn't change with every call of the <code>gridMenu()</code> function. It is the same, and should be, during runtime. But it could change over time or even change depending on what user is logged in. So we place this in the constructor of the class:</p>\n\n<pre><code>class Grid {\n\n private $modes;\n\n public function __construt($modes) {\n $this->$modes = $modes;\n }\n\n public function gridMenu(String $mode) { }\n}\n</code></pre>\n\n<p>Now, gridMenu doesnt really say much. I would have to guess what it does: save a menu? does it create one? does it return one? So lets change that name to something more understandable:</p>\n\n<pre><code>class Grid {\n\n private $modes;\n\n public function __construt($modes) {\n $this->$modes = $modes;\n }\n\n public function renderMenu(String $mode) { }\n}\n</code></pre>\n\n<p>Other possibilities are echoMenu, printMenu... Note that i left the word grid out because we are allready in the grid class. Obviously we wouldn't print a non-grid menu out here...</p>\n\n<p>Good, so now we can remove that Validate::sanitize to the outside of the code and that declaration of $modes is no longer hard-coded into the class. This gives us a lot more flexibility,...</p>\n\n<p>Now let's look at what our function does. It creates html. wheut? So it doesn't provide functionality but simply prints some html? So it's is actually a template disguised as a function... the sneaky bastard. We really have to keep an eye on those templates mate. They tend to creep into functions all the time all over the code.</p>\n\n<p>This makes them harder to maintain and makes you write tons of Repeat-Yourself code. For instance if we would no want it to return the data in XML, or in a list instead of divs. Or even worse, have the delete button placed somewhere else, or or.... OOh boy, beter start all over again.</p>\n\n<p>Needless to say, we are doing something really wrong here and we have read all this text for nothing :( Well atleast you know about sepration of concern. And I give you an oher link: <a href=\"http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29\" rel=\"nofollow\">SOLID</a> </p>\n\n<p>But what has this todo with you question? Ah it's very easy. What you actually need is a template that handles the display of of those '.hex' divs (what is a hex? and why is action.delete/archive a hex?). You also need some business logic that calculates what 'actions' you can do. and then we need some controller to bring it all together.</p>\n\n<p>Your template would look something like this:</p>\n\n<pre><code><div id=\"hexContainer\">\n\n <div class=\"hex hex1 hex-<?php echo $mode->hasAction('edit') ? 'enabled' : 'disabled' ; ?>\">\n <?php echo $mode->hasAction('edit') ? '<img data-option=\"Edit\" src=\"' . ROOT . 'images/edit.png\">': ''; ?>\n </div>\n\n <div class=\"hex hex2 hex-disabled\">\n //zzz\n </div>\n\n <div class=\"hex hex1 hex-<?php echo $mode->hasAction('delete') ? 'enabled' : 'disabled' ; ?>\">\n <?php echo $mode->hasAction('edit') ? '<img data-option=\"Edit\" src=\"' . ROOT . 'images/delete.png\">': ''; ?>\n </div>\n\n <div class=\"hex hex4 hex-disabled\">\n //xxx\n </div>\n\n <div class=\"hex hex1 hex-<?php echo $mode->hasAction('archive') ? 'enabled' : 'disabled' ; ?>\">\n <?php echo $mode->hasAction('edit') ? '<img data-option=\"Edit\" src=\"' . ROOT . 'images/archive.png\">': ''; ?>\n </div>\n\n <div class=\"hex hex6 hex-disabled\">\n //zzz\n </div>\n\n</div>\n</code></pre>\n\n<p>Your business logic 'Mode' and 'ModeFactory' class would look something like this:</p>\n\n<pre><code>class ModeFactory {\n\n private $modes;\n\n public function __construt(array $modes) {\n $this->$modes = $modes;\n }\n\n public function getMode(string $mode) {\n if ( !isset($this->modes[$mode]) ) {\n throw new ModeNotFoundException();\n }\n return new Mode($this->modes[$mode]);\n }\n}\n\nclass Mode {\n private $actions = $actions;\n public function __construct(array $actions) {\n $this->actions = $actions;\n }\n public function hasAction(string $action) {\n return in_array($this->actions[$action]);\n }\n}\n\nclass ModeNotFoundException extends Exception {}\n</code></pre>\n\n<p>NOTE: I used the Factory pattern here, is this the best? not, but it is a pattern that suited my needs and I feld like using it.</p>\n\n<p>Then to bring it all togeter: the controller:</p>\n\n<pre><code>include 'Validate.php'; #the Validate class\ninclude 'Mode.php'; #Modefactory and Mode\n\n//note that now only the controller needs to know\n// how the client communicates with this program\n$currentMode = Validate::sanitize($_POST['mode']);\n\n//because we pass in the modes+Actions in the factory,\n// we can easily change everything.\n//For instance we could fetch these mode+actions from a database\n$modeFactory = new ModeFactory(array(\n 'products' => array('edit', 'delete', 'archive')\n));\n\n//we need this variable in the template so lets create it\n$mode = $modeFactory->getMode($currentMode);\n\ninclude 'myHexTemplate.php';\n\n//all done\n</code></pre>\n\n<p>To sum up: the massive amount of if's wasn't the real problem. The real problem was the seperation of concern and those sneaky template functions. By solving those issues we now not only have better to read code. It is also very flexible, very easy to test etc etc.</p>\n\n<p>Say we want to test a new Mode, we simply create our Mode:</p>\n\n<pre><code>$mode new Mode(array('myTestAction'));\n</code></pre>\n\n<p>Is this code perfect? no, the names used are horrible. What is a hex? what is a mode? what is an action? These are all generic words and make it very hard actualyl properly reuse this code. But appart from that, I think you get the important lesson here.</p>\n\n<p>Good luck and fire away at the comments. @everyone else: feel free to correct spelling, I honestly don't feel like reading this entire post again for spelling mistakes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-09T19:53:37.710",
"Id": "51900",
"Score": "0",
"body": "Thanks for such a comprehensive and detailed answer! As for templates, are they just stored somewhere as PHP/HTML files? Where would those go in a typical app in terms of directory structure?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T09:20:32.087",
"Id": "51977",
"Score": "0",
"body": "@imperium2335 the most important thing when writing code is to think about your future self. In half a year, this code will stop working or will need some changes. And then you will have to know where to look. For instance templates, I would put them in /templates folder. Controllers in /controller and classes in /lib . there is however no real rule on where to put code. there are however some standards for OO code: http://www.php-fig.org/psr/0/ and yes. you store them as .php files"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-07T08:42:14.553",
"Id": "29487",
"ParentId": "29064",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29487",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T16:37:33.750",
"Id": "29064",
"Score": "7",
"Tags": [
"php"
],
"Title": "Dynamic menu depending on a set mode"
}
|
29064
|
<p>After reading about MVC pattern in <em>Head First Design Patterns</em>, I've decided to write a TicTacToe app.</p>
<p>I will not reveal the source code of the classes <code>Matrix</code>, <code>Dimension</code>, and <code>Size</code> because they do not relate to the topic. All source code can be found <a href="https://github.com/Leonideveloper/TicTacToe/tree/master/TicTacToe/src/main" rel="nofollow">here</a>.</p>
<p>Please criticize my code, along with its MVC pattern usage.</p>
<p><strong>TicTacToeActivity.java</strong></p>
<pre><code>public class TicTacToeActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GameModel model = new GameModelImpl(new Dimension(4, 4));
GameController controller = new GameControllerAndroidImpl(model, this);
}
}
</code></pre>
<p><strong>GameController.java</strong></p>
<pre><code>public interface GameController {
void onViewIsReadyToStartGame();
void onPlayerMove(Matrix.Position movePos);
}
</code></pre>
<p><strong>GameControllerImpl.java</strong></p>
<pre><code>abstract class GameControllerImpl implements GameController {
private final GameModel model;
public GameControllerImpl(GameModel model) {
this.model = model;
}
protected abstract GameView getGameView();
@Override
public void onViewIsReadyToStartGame() {
model.onViewIsReadyToStartGame();
}
@Override
public void onPlayerMove(Matrix.Position movePos) {
getGameView().blockMoves();
model.onPlayerTurn(movePos);
getGameView().unblockMoves();
}
}
</code></pre>
<p><strong>GameControllerAndroidImpl.java</strong></p>
<pre><code>public class GameControllerAndroidImpl extends GameControllerImpl {
private final GameView gameView;
public GameControllerAndroidImpl(GameModel model, Activity activity) {
super(model);
gameView = new GameViewAndroidImpl(this, model, activity);
}
@Override
protected GameView getGameView() {
return gameView;
}
}
</code></pre>
<p><strong>GameView.java</strong></p>
<pre><code>public interface GameView {
void blockMoves();
void unblockMoves();
boolean movesBlocked();
}
</code></pre>
<p><strong>GameViewImpl.java</strong></p>
<pre><code>public abstract class GameViewImpl implements GameView, OnCellClickListener,
OnOpponentMoveListener, OnGameFinishedListener {
private final GameController controller;
private final GameModel model;
private boolean movesBlocked;
private boolean gameFinished;
public GameViewImpl(GameController controller, GameModel model) {
this.controller = controller;
this.model = model;
model.addOnOpponentMoveListener(this);
model.addOnGameFinishedListener(this);
gameFinished = false;
movesBlocked = false;
}
protected abstract GameBoard gameBoard();
protected abstract GameResultDisplay gameResultDisplay();
protected OnCellClickListener getOnCellClickListener() {
return this;
}
@Override
public void blockMoves() {
movesBlocked = true;
}
@Override
public void unblockMoves() {
movesBlocked = false;
}
@Override
public boolean movesBlocked() {
return movesBlocked;
}
@Override
public void onCellClick(Matrix.Position cellPos) {
if (gameFinished) {
gameFinished = false;
gameBoard().clear();
controller.onViewIsReadyToStartGame();
} else if (model.emptyCell(cellPos) && !movesBlocked()) {
gameBoard().showMove(cellPos);
controller.onPlayerMove(cellPos);
}
}
@Override
public void onOpponentMove(Matrix.Position movePos) {
gameBoard().showMove(movePos);
}
@Override
public void onGameFinished(GameInfo gameInfo) {
gameFinished = true;
gameBoard().showFireLine(gameInfo.cellsOnFire());
gameResultDisplay().show(gameInfo.gameResult());
}
}
</code></pre>
<p><strong>OnCellClickListener.java</strong></p>
<pre><code>public interface OnCellClickListener {
void onCellClick(Matrix.Position pos);
}
</code></pre>
<p><strong>GameViewAndroidImpl.java</strong></p>
<pre><code>public class GameViewAndroidImpl extends GameViewImpl {
private final GameBoard gameBoard;
private final GameResultDisplay gameResultDisplay;
public GameViewAndroidImpl(GameController controller, GameModel model, Activity activity) {
super(controller, model);
gameResultDisplay = new GameResultDisplayAndroidToastImpl(activity);
GameBoardCreator gameBoardCreator = new GameBoardCreatorAndroidImpl(activity);
gameBoard = gameBoardCreator.createGameBoard(model.getDimension());
gameBoard.setOnCellClickListener(super.getOnCellClickListener());
}
@Override
protected GameBoard gameBoard() {
return gameBoard;
}
@Override
protected GameResultDisplay gameResultDisplay() {
return gameResultDisplay;
}
}
</code></pre>
<p><strong>GameResultDisplay.java</strong></p>
<pre><code>public interface GameResultDisplay {
void show(GameResult gameResult);
}
</code></pre>
<p><strong>GameResultDisplayAndroidToastImpl.java</strong></p>
<pre><code>public class GameResultDisplayAndroidToastImpl implements GameResultDisplay {
private final Activity activity;
public GameResultDisplayAndroidToastImpl(Activity activity) {
this.activity = activity;
}
@Override
public void show(GameResult gameResult) {
Toast.makeText(activity, gameResult.name(), Toast.LENGTH_LONG).show();
}
}
</code></pre>
<p><strong>GameBoard.java</strong></p>
<pre><code>public interface GameBoard {
void setOnCellClickListener(OnCellClickListener onCellClickListener);
void showMove(Matrix.Position pos);
void showFireLine(List<Matrix.Position> positions);
void clear();
}
</code></pre>
<p><strong>GameBoardAndroidImpl.java</strong></p>
<pre><code>public class GameBoardAndroidImpl implements GameBoard {
private final Matrix<ImageView> cells;
private CellIcon currentIcon;
public GameBoardAndroidImpl(Matrix<ImageView> cells) {
this.cells = cells;
clear();
}
@Override
public void clear() {
cells.forEach(new Matrix.OnEachHandler<ImageView>() {
@Override
public void handle(Matrix<ImageView> matrix, Matrix.Position pos) {
clearCell(pos);
}
});
currentIcon = CellIcon.X;
}
private void clearCell(Matrix.Position cellPos) {
setCellImageResource(cellPos, android.R.color.transparent);
setCellBackgroundResource(cellPos, R.drawable.empty);
}
@Override
public void setOnCellClickListener(final OnCellClickListener onCellClickListener) {
cells.forEach(new Matrix.OnEachHandler<ImageView>() {
@Override
public void handle(Matrix<ImageView> matrix, final Matrix.Position pos) {
ImageView cell = cells.get(pos);
cell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onCellClickListener.onCellClick(pos);
}
});
}
});
}
@Override
public void showMove(Matrix.Position pos) {
int iconId;
if (currentIcon == CellIcon.X) {
iconId = IconRandomizer.randomCrossIconId();
currentIcon = CellIcon.O;
} else {
iconId = IconRandomizer.randomZeroIconId();
currentIcon = CellIcon.X;
}
setCellBackgroundResource(pos, iconId);
}
@Override
public void showFireLine(List<Matrix.Position> positions) {
for (Matrix.Position pos : positions) {
setCellImageResource(pos, IconRandomizer.randomFireIconId());
}
}
private void setCellBackgroundResource(Matrix.Position cellPos, int resId) {
cells.get(cellPos).setBackgroundResource(resId);
}
private void setCellImageResource(Matrix.Position cellPos, int resId) {
cells.get(cellPos).setImageResource(resId);
}
}
</code></pre>
<p><strong>CellIcon.java</strong></p>
<pre><code>public enum CellIcon {
X, O;
}
</code></pre>
<p><strong>IconRandomizer.java</strong></p>
<pre><code>public class IconRandomizer {
private static final int[] CROSS_ICONS_IDS = {
R.drawable.cross_1, R.drawable.cross_2, R.drawable.cross_3
};
private static final int[] ZERO_ICONS_IDS = {
R.drawable.zero_1, R.drawable.zero_2, R.drawable.zero_3
};
private static final int[] FIRE_ICONS_IDS = {
R.drawable.fire_1, R.drawable.fire_2, R.drawable.fire_3,
R.drawable.fire_4, R.drawable.fire_5, R.drawable.fire_6
};
public static int randomCrossIconId() {
return randomElement(CROSS_ICONS_IDS);
}
public static int randomZeroIconId() {
return randomElement(ZERO_ICONS_IDS);
}
public static int randomFireIconId() {
return randomElement(FIRE_ICONS_IDS);
}
private static int randomElement(int[] array) {
int randomIndex = Randomizer.randomPositiveInt() % array.length;
return array[randomIndex];
}
}
</code></pre>
<p><strong>GameBoardCreator.java</strong></p>
<pre><code>public interface GameBoardCreator {
GameBoard createGameBoard(Dimension dim);
}
</code></pre>
<p><strong>GameBoardCreatorAndroidImpl.java</strong></p>
<pre><code>public class GameBoardCreatorAndroidImpl implements GameBoardCreator {
private static final int SPACE_BETWEEN_CELLS = 2;
private final Activity activity;
public GameBoardCreatorAndroidImpl(Activity activity) {
this.activity = activity;
}
@Override
public GameBoard createGameBoard(Dimension dim) {
return new GameBoardAndroidImpl(prepareCells(dim));
}
private Matrix<ImageView> prepareCells(Dimension dim) {
Matrix<ImageView> cells = new Matrix<ImageView>(dim);
LinearLayout verticalLayout = prepareVerticalLinearLayout(dim);
for (int row = 0; row < dim.rows; ++row) {
LinearLayout rowLayout = prepareHorizontalLinearLayout(dim);
for (int column = 0; column < dim.columns; ++column) {
ImageView cell = prepareCell();
setHorizontalMargins(cell, column, dim.columns);
rowLayout.addView(cell);
cells.set(row, column, cell);
}
setVerticalMargins(rowLayout, row, dim.rows);
verticalLayout.addView(rowLayout);
}
activity.setContentView(R.layout.tic_tac_toe_activity);
FrameLayout gameBoardFrameLayout =
(FrameLayout) activity.findViewById(R.id.gameBoardFrameLayout);
gameBoardFrameLayout.addView(verticalLayout);
return cells;
}
private LinearLayout prepareVerticalLinearLayout(Dimension dim) {
return prepareLinearLayout(LinearLayout.VERTICAL, dim.rows);
}
private LinearLayout prepareHorizontalLinearLayout(Dimension dim) {
return prepareLinearLayout(LinearLayout.HORIZONTAL, dim.columns);
}
private LinearLayout prepareLinearLayout(int orientation, int weightSum) {
LinearLayout layout = new LinearLayout(activity);
layout.setWeightSum(weightSum);
layout.setOrientation(orientation);
return layout;
}
private ImageView prepareCell() {
LayoutInflater inflater = activity.getLayoutInflater();
return (ImageView) inflater.inflate(R.layout.cell_image_view, null);
}
private void setHorizontalMargins(ImageView cell, int column, int columns) {
int leftMargin = (column == 0) ? 0 : SPACE_BETWEEN_CELLS;
int rightMargin = (column == columns - 1) ? 0 : SPACE_BETWEEN_CELLS;
setMargins(cell, leftMargin, 0, rightMargin, 0);
}
private void setVerticalMargins(LinearLayout rowLayout, int row, int rows) {
int topMargin = (row == 0) ? 0 : SPACE_BETWEEN_CELLS;
int bottomMargin = (row == rows - 1) ? 0 : SPACE_BETWEEN_CELLS;
setMargins(rowLayout, 0, topMargin, 0, bottomMargin);
}
private void setMargins(View view, int left, int top, int right, int bottom) {
LinearLayout.LayoutParams params = createLinearLayoutParams();
params.setMargins(left, top, right, bottom);
view.setLayoutParams(params);
}
private LinearLayout.LayoutParams createLinearLayoutParams() {
return new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f
);
}
}
</code></pre>
<p><strong>tic_tac_toe_activity.xml</strong></p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".TicTacToeActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="margin"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:textSize="64sp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/gameScoreTextView"
android:textSize="64sp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="margin"
android:id="@+id/adTextView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textSize="74sp"/>
<FrameLayout
android:id="@+id/gameBoardFrameLayout"
android:background="@color/light_green"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/textView"
android:layout_above="@+id/adTextView"
android:layout_alignParentRight="true"
android:layout_alignParentLeft="true">
</FrameLayout>
</RelativeLayout>
</code></pre>
<p><strong>cell_image_view.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:scaleType="fitXY"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
</ImageView>
</code></pre>
<p><strong>GameModel.java</strong></p>
<pre><code>public interface GameModel {
boolean emptyCell(Matrix.Position pos);
Dimension getDimension();
void addOnOpponentMoveListener(OnOpponentMoveListener listener);
void addOnGameFinishedListener(OnGameFinishedListener listener);
void onPlayerTurn(Matrix.Position turnPosition);
void onViewIsReadyToStartGame();
}
</code></pre>
<p><strong>GameModelImpl.java</strong></p>
<pre><code>public class GameModelImpl implements GameModel {
private final Dimension dimension;
private final GameJudge gameJudge;
private final List<OnGameFinishedListener> onGameFinishedListeners;
private final List<OnOpponentMoveListener> onOpponentMoveListeners;
private final Matrix<Cell> gameBoard;
private final Opponent opponent;
private boolean opponentMovesFirst;
public GameModelImpl(Dimension gameBoardDimension) {
dimension = gameBoardDimension;
gameBoard = new Matrix<Cell>(gameBoardDimension);
initGameBoardByEmpty();
gameJudge = new GameJudgeImpl(gameBoard);
onOpponentMoveListeners = new ArrayList<OnOpponentMoveListener>();
onGameFinishedListeners = new ArrayList<OnGameFinishedListener>();
opponent = new StupidAIOpponent(gameBoard);
opponentMovesFirst = false;
}
private void initGameBoardByEmpty() {
gameBoard.forEach(new Matrix.OnEachHandler<Cell>() {
@Override
public void handle(Matrix<Cell> matrix, Matrix.Position pos) {
gameBoard.set(pos, Cell.EMPTY);
}
});
}
@Override
public boolean emptyCell(Matrix.Position pos) {
return gameBoard.get(pos) == Cell.EMPTY;
}
@Override
public Dimension getDimension() {
return dimension;
}
@Override
public void addOnGameFinishedListener(OnGameFinishedListener listener) {
onGameFinishedListeners.add(listener);
}
@Override
public void addOnOpponentMoveListener(OnOpponentMoveListener listener) {
onOpponentMoveListeners.add(listener);
}
@Override
public void onPlayerTurn(Matrix.Position turnPosition) {
gameBoard.set(turnPosition, Cell.PLAYER);
if (gameNotFinished()) {
opponentMove();
}
GameInfo gameInfo = gameJudge.gameResultInfo();
if (gameInfo.resultIsKnown()) {
onGameFinished(gameInfo);
}
}
private boolean gameNotFinished() {
return !gameJudge.gameResultInfo().resultIsKnown();
}
private void opponentMove() {
Matrix.Position opponentMovePos = opponent.positionToMove();
gameBoard.set(opponentMovePos, Cell.OPPONENT);
notifyOnOpponentMoveListeners(opponentMovePos);
}
private void notifyOnOpponentMoveListeners(Matrix.Position opponentMovePos) {
for (OnOpponentMoveListener each : onOpponentMoveListeners) {
each.onOpponentMove(opponentMovePos);
}
}
private void onGameFinished(GameInfo gameInfo) {
opponentMovesFirst = defineOpponentMovesFirst(gameInfo.gameResult());
notifyOnGameFinishedListeners(gameInfo);
initGameBoardByEmpty();
}
private boolean defineOpponentMovesFirst(GameResult gameResult) {
return (gameResult == GameResult.OPPONENT_WINS) ||
(opponentMovesFirst && gameResult == GameResult.DRAW);
}
private void notifyOnGameFinishedListeners(GameInfo gameInfo) {
for (OnGameFinishedListener each : onGameFinishedListeners) {
each.onGameFinished(gameInfo);
}
}
@Override
public void onViewIsReadyToStartGame() {
if (opponentMovesFirst) {
opponentMove();
}
}
}
</code></pre>
<p><strong>Cell.java</strong></p>
<pre><code>public enum Cell {
EMPTY, PLAYER, OPPONENT
}
</code></pre>
<p><strong>OnGameFinishedListener.java</strong></p>
<pre><code>public interface OnGameFinishedListener {
void onGameFinished(GameInfo gameInfo);
}
</code></pre>
<p><strong>OnOpponentMoveListener.java</strong></p>
<pre><code>public interface OnOpponentMoveListener {
void onOpponentMove(Matrix.Position movePos);
}
</code></pre>
<p><strong>GameInfo.java</strong></p>
<pre><code>public class GameInfo {
private final GameResult gameResult;
private final List<Matrix.Position> cellsOnFire;
public static GameInfo unknownResultInfo() {
return new GameInfo(GameResult.UNKNOWN, new ArrayList<Matrix.Position>());
}
public static GameInfo drawResultInfo() {
return new GameInfo(GameResult.DRAW, new ArrayList<Matrix.Position>());
}
public GameInfo(GameResult gameResult, List<Matrix.Position> cellsOnFire) {
this.gameResult = gameResult;
this.cellsOnFire = cellsOnFire;
}
public GameResult gameResult() {
return gameResult;
}
public List<Matrix.Position> cellsOnFire() {
return cellsOnFire;
}
public boolean resultIsKnown() {
return gameResult != GameResult.UNKNOWN;
}
}
</code></pre>
<p><strong>GameResult.java</strong></p>
<pre><code>public enum GameResult {
UNKNOWN, DRAW, PLAYER_WINS, OPPONENT_WINS
}
</code></pre>
<p><strong>GameJudge.java</strong></p>
<pre><code>public interface GameJudge {
public GameInfo gameResultInfo();
}
</code></pre>
<p><strong>GameJudgeImpl.java</strong></p>
<pre><code>public class GameJudgeImpl implements GameJudge {
private final Matrix<Cell> gameBoard;
private final int gameBoardDimension;
public GameJudgeImpl(Matrix<Cell> gameBoard) {
this.gameBoard = gameBoard;
this.gameBoardDimension = gameBoard.rows;
}
@Override
public GameInfo gameResultInfo() {
for (int i = 0; i < gameBoardDimension; ++i) {
GameInfo resultInfo = rowColumnResultInfo(i);
if (resultInfo.resultIsKnown()) {
return resultInfo;
}
}
GameInfo resultInfo = diagonalsResultInfo();
if (resultInfo.resultIsKnown()) {
return resultInfo;
}
return gameBoardContainsEmptyCell()
? GameInfo.unknownResultInfo()
: GameInfo.drawResultInfo();
}
private GameInfo rowColumnResultInfo(int index) {
GameInfo rowResultInfo = rowResultInfo(index);
if (rowResultInfo.resultIsKnown()) {
return rowResultInfo;
} else {
return columnResultInfo(index);
}
}
private GameInfo rowResultInfo(int row) {
List<Matrix.Position> rowCellsPositions = rowCellsPositions(row);
return resultInfoByCellsPositions(rowCellsPositions);
}
private List<Matrix.Position> rowCellsPositions(int row) {
List<Matrix.Position> cells = new ArrayList<Matrix.Position>();
for (int column = 0; column < gameBoardDimension; ++column) {
cells.add(new Matrix.Position(row, column));
}
return cells;
}
private GameInfo resultInfoByCellsPositions(List<Matrix.Position> cellsPositions) {
Matrix.Position firstCellOnLinePosition = cellsPositions.get(0);
Cell firstCellOnLine = gameBoard.get(firstCellOnLinePosition);
if (firstCellOnLine == Cell.EMPTY) {
return GameInfo.unknownResultInfo();
}
for (int i = 1; i < gameBoardDimension; ++i) {
Matrix.Position currentPosition = cellsPositions.get(i);
Cell currentCell = gameBoard.get(currentPosition);
if (firstCellOnLine != currentCell) {
return GameInfo.unknownResultInfo();
}
}
return new GameInfo(cellToResult(firstCellOnLine), cellsPositions);
}
private GameResult cellToResult(Cell cell) {
if (cell == Cell.PLAYER) {
return GameResult.PLAYER_WINS;
} else if (cell == Cell.OPPONENT) {
return GameResult.OPPONENT_WINS;
}
throw new IllegalArgumentException("Input cell must be not empty!");
}
private GameInfo columnResultInfo(int column) {
List<Matrix.Position> columnCellsPositions = columnCellsPositions(column);
return resultInfoByCellsPositions(columnCellsPositions);
}
private List<Matrix.Position> columnCellsPositions(int column) {
List<Matrix.Position> cells = new ArrayList<Matrix.Position>();
for (int row = 0; row < gameBoardDimension; ++row) {
cells.add(new Matrix.Position(row, column));
}
return cells;
}
private GameInfo diagonalsResultInfo() {
GameInfo leftUpperDiagonalResultInfo = leftUpperDiagonalResultInfo();
if (leftUpperDiagonalResultInfo.resultIsKnown()) {
return leftUpperDiagonalResultInfo;
} else {
return rightUpperDiagonalResultInfo();
}
}
private GameInfo leftUpperDiagonalResultInfo() {
return resultInfoByCellsPositions(leftUpperDiagonalPositions());
}
private List<Matrix.Position> leftUpperDiagonalPositions() {
List<Matrix.Position> positions = new ArrayList<Matrix.Position>();
for (int i = 0; i < gameBoardDimension; ++i) {
positions.add(new Matrix.Position(i, i));
}
return positions;
}
private GameInfo rightUpperDiagonalResultInfo() {
return resultInfoByCellsPositions(rightUpperDiagonalPositions());
}
private List<Matrix.Position> rightUpperDiagonalPositions() {
List<Matrix.Position> positions = new ArrayList<Matrix.Position>();
for (int i = 0; i < gameBoardDimension; ++i) {
positions.add(new Matrix.Position(i, gameBoardDimension - i - 1));
}
return positions;
}
private boolean gameBoardContainsEmptyCell() {
for (int row = 0; row < gameBoardDimension; ++row) {
for (int column = 0; column < gameBoardDimension; ++column) {
if (gameBoard.get(row, column) == Cell.EMPTY) {
return true;
}
}
}
return false;
}
}
</code></pre>
<p><strong>Opponent.java</strong></p>
<pre><code>public interface Opponent {
Matrix.Position positionToMove();
}
</code></pre>
<p><strong>StupidAIOpponent.java</strong></p>
<pre><code>public class StupidAIOpponent implements Opponent {
private final Matrix<Cell> gameBoard;
public StupidAIOpponent(Matrix<Cell> gameBoard) {
this.gameBoard = gameBoard;
}
@Override
public Matrix.Position positionToMove() {
for (int row = 0; row < gameBoard.rows; ++row) {
for (int column = 0; column < gameBoard.columns; ++column) {
if (gameBoard.get(row, column) == Cell.EMPTY) {
return new Matrix.Position(row, column);
}
}
}
throw new RuntimeException("There is not empty cells!");
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Note that the following line violates the principle of information hiding:</p>\n\n<pre><code> if (gameBoard.get(row, column) == Cell.EMPTY) {\n</code></pre>\n\n<p>Express this as:</p>\n\n<pre><code> if (gameBoard.isEmpty(row, column)) {\n</code></pre>\n\n<p>In the following:</p>\n\n<pre><code> if (rowResultInfo.resultIsKnown()) {\n return rowResultInfo;\n } else {\n return columnResultInfo(index);\n }\n</code></pre>\n\n<p>The <code>else</code> is superfluous:</p>\n\n<pre><code> if (rowResultInfo.resultIsKnown()) {\n return rowResultInfo;\n }\n\n return columnResultInfo(index);\n</code></pre>\n\n<p>This naturally leads to a single return statement:</p>\n\n<pre><code> return rowResultInfo.resultIsKnown() ? rowResultInfo : columnResultInfo(index);\n</code></pre>\n\n<p>Much of the code breaks encapsulation, and very little of the code is extensible. I'd recommend you read about <a href=\"http://whitemagicsoftware.com/encapsulation.pdf\" rel=\"nofollow\">self-encapsulation</a> to see how to develop code that is extensible (i.e., subscribes to the Open-Closed Principle).</p>\n\n<p>A lot of information is passed between various classes that incurs duplication. For example, all of these are a form of repetition:</p>\n\n<pre><code>gameBoard.get(pos) == Cell.EMPTY\nif (gameBoard.get(row, column) == Cell.EMPTY) {\nif (firstCellOnLine == Cell.EMPTY) {\nif (cell == Cell.PLAYER) {\n} else if (cell == Cell.OPPONENT) {\n</code></pre>\n\n<p>These are all examples of thinking about programming in terms of functions, rather than in terms of objects. Knowledge of an object's state should stay as close to the object as possible. In the cases above, there is no reason to expose the inner workings of the cell. The first step to hiding the cell's state is by eliminating its get accessor method:</p>\n\n<pre><code>if( cell.isTakenBy( Cell.EMPTY ) )\nif( cell.isTakenBy( Cell.OPPONENT ) ) \nif( cell.isTakenBy( Cell.PLAYER ) ) \n</code></pre>\n\n<p>These can also be written as:</p>\n\n<pre><code>if( cell.isEmpty() )\nif( cell.isOpponent() ) \nif( cell.isPlayer() ) \n</code></pre>\n\n<p>I get the feeling that there should be no distinction between an \"opponent\" and a \"player\" -- there should be only players, one being the \"active\" player. This would allow for variations such as 4-player T-T-T. You could then write, for example:</p>\n\n<pre><code>if( cell.isTakenBy( currentPlayerToken ) )\nif( !cell.isTakenBy( currentPlayerToken ) && !cell.isEmpty() )\n</code></pre>\n\n<p>For little effort with this approach, the game can use tokens to occupy board positions, rather than a \"player\" being in a cell. (That is, when playing TTT, the players themselves aren't actually occupying different spaces in the grid, rather their tokens are -- in this case an X or an O. With the model as developed, it strongly implies that a PLAYER or an OPPONENT is in a cell, which, frankly, is nonsensical for TTT, but would make sense for <a href=\"http://en.wikipedia.org/wiki/Twister_%28game%29\" rel=\"nofollow\">other games</a> where the player physically occupies the board space.)</p>\n\n<p>By making the design a little more generic, it can relatively easily apply to more games.</p>\n\n<p>Note that <code>IconRandomizer</code> isn't a \"class\" per se. A class, strictly speaking, must have both <em>attributes</em> and behaviour.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T18:35:26.353",
"Id": "35938",
"ParentId": "29070",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "35938",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T20:16:32.133",
"Id": "29070",
"Score": "3",
"Tags": [
"java",
"design-patterns",
"mvc",
"android"
],
"Title": "TicTacToe - introduction to MVC pattern"
}
|
29070
|
<p><strong>Initial note:</strong> You do not need to have knowledge of LWJGL or OpenGL to review this code. The only parts of the code that require LWJGL knowledge are the <code>Game</code> class, and the rest, although it may contain some LWJGL/OpenGL/Slick-util code, it is rather self explanatory for anybody who's worked in Java before.</p>
<p>So I've built this simple game in Java using LWJGL. It's a relatively simple platformer, and I would like some opinions on my code so that I can correct it. Feel free to leave any constructive criticism or thoughts that you may have. Any and all opinions are appreciated. This is my first game, so it's bound to be a bit rough. This is also still early in development. I'll post all the classes that I've written code for so far. </p>
<p><strong>Game class:</strong></p>
<pre><code>import static org.lwjgl.opengl.GL11.*;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.newdawn.slick.opengl.Texture;
import com.hasherr.platformer.entity.Player;
public class Game { // starts game & manages display/init OpenGL
public Game() {
initDisplay(800, 500, "Komo"); // Temporary game name - KOMO
}
// initiate necessary classes
Player player = new Player(); // user-representation
InputHandler inputHandler = new InputHandler(player);
SpriteHandler spriteHandler = new SpriteHandler();
TextureHandler textureHandler = new TextureHandler();
private void initDisplay(int width, int height, String title) {
try {
Display.setDisplayMode(new DisplayMode(width, height));
Display.setTitle(title);
Display.create();
} catch (LWJGLException e) {
e.printStackTrace();
System.exit(0);
}
grabAllTextures();
while (!Display.isCloseRequested()) {
Display.update();
Display.sync(60); // 60 FPS
inputHandler.handleInput();
initGL(width, height);
spriteHandler.drawSprite(playerTexture, player.xPos, player.yPos);
}
Display.destroy();
}
private void initGL(int width, int height) {
glClear(GL_COLOR_BUFFER_BIT); // clear screen for efficient rendering
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, 0, height, 1, -1); // set orthographic view
glMatrixMode(GL_MODELVIEW);
glEnable(GL_TEXTURE_2D); // enable 2d rendering for textures & sprites
}
// Textures (only one so far)
Texture playerTexture;
private void grabAllTextures() { // basically TextHandler in one method.
playerTexture = textureHandler.grabTexture("Png", "scary_monster"); // on tex so far
}
public static void main(String[] args) { // start yer engines
new Game(); // start the show, ready go
}
}
</code></pre>
<p><strong>InputHandler Class:</strong></p>
<pre><code>import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import com.hasherr.platformer.entity.Player;
public class InputHandler { // handles all input
Player player;
public InputHandler(Player targetToHandle) {
player = targetToHandle;
}
public void handleInput() {
// keyboard input
if (!Keyboard.isKeyDown(Keyboard.KEY_D) && !Keyboard.isKeyDown( // no
Keyboard.KEY_A) && !Keyboard.isKeyDown(Keyboard.KEY_SPACE)) { // input
player.moveSpeed = 10.0f;
}
if (Keyboard.isKeyDown(Keyboard.KEY_D)) {
player.moveRight(); // move right
}
if (Keyboard.isKeyDown(Keyboard.KEY_A)) {
player.moveLeft(); // move left
}
if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) {
// jump
}
// mouse input
if (Mouse.isButtonDown(0)) {
}
}
}
</code></pre>
<p><strong>SpriteHandler class:</strong></p>
<pre><code>import org.newdawn.slick.opengl.Texture;
import static org.lwjgl.opengl.GL11.*;
public class SpriteHandler { // draws all textures onto quads & handles importing of textures
public void drawSprite(Texture texture, float x, float y) {
float width = texture.getImageWidth();
float height = texture.getImageHeight();
texture.bind(); // wrap it before you tap it. (bind it)
glBegin(GL_QUADS);
glTexCoord2f(0, 1);
glVertex2f(x, y);
glTexCoord2f(1, 1);
glVertex2f(x + width, y);
glTexCoord2f(1, 0);
glVertex2f(x + width, y + height);
glTexCoord2f(0, 0);
glVertex2f(x, y + height);
glEnd();
}
}
</code></pre>
<p><strong>TextureHandler class:</strong></p>
<pre><code>import java.io.IOException;
import org.newdawn.slick.opengl.Texture;
import org.newdawn.slick.opengl.TextureLoader;
import org.newdawn.slick.util.ResourceLoader;
public class TextureHandler {
Texture texture;
public Texture grabTexture(String ext, String name) {
try {
texture = TextureLoader.getTexture(
ext.toUpperCase(), ResourceLoader.getResourceAsStream(
"/res/textures/" + name + "." + ext.toLowerCase()));
} catch (IOException e) {
e.printStackTrace();
}
return texture;
}
}
</code></pre>
<p>And last but not least, the <strong>Player class:</strong></p>
<pre><code>public class Player { // controls Player & player physics
// velocity & physics fields
private float angle = 30.0f;
private float acceleration = 3.0f;
private float scaleX = (float) Math.cos(angle);
private float scaleY = (float) Math.sin(angle);
public float moveSpeed = 16.0f; // initial value, obv. set to move
private final static int MAX_MOVE_SPEED = 150;
private float xVelocity = scaleX * moveSpeed;
private float yVelocity = scaleY * moveSpeed;
// position fields
public float xPos = 0; // init
public float yPos = 0; // init
private void printPos() {
System.out.println("Movespeed: " + moveSpeed + ", X-Velocity: "
+ xVelocity);
}
private void handleAcceleration(float force) {
if (moveSpeed < MAX_MOVE_SPEED && moveSpeed > -MAX_MOVE_SPEED) {
moveSpeed += force;
xVelocity = scaleX * moveSpeed;
} else if (moveSpeed >= MAX_MOVE_SPEED) {
moveSpeed = MAX_MOVE_SPEED;
xVelocity = scaleX * moveSpeed;
} else if (moveSpeed <= -MAX_MOVE_SPEED) {
moveSpeed = -MAX_MOVE_SPEED;
xVelocity = scaleX * moveSpeed;
}
xPos += xVelocity;
}
public void moveRight() {
handleAcceleration(acceleration);
printPos();
}
public void moveLeft() {
handleAcceleration(-acceleration);
printPos();
}
public void jump() {
// jump (spacebar)
}
public void shoot() {
// shoot (mouse)
}
}
</code></pre>
<p>Like I said, these are only the classes that I've coded so far. All my code is open-source, so if you want to view the whole repository, you can view it <a href="https://github.com/hasherr/Platformer-Game" rel="nofollow" title="here">here</a>. Let me know if you guys need anything else, as I'll be glad to help anybody who is willing to help me.</p>
|
[] |
[
{
"body": "<p>General:</p>\n\n<p>Dont use <code>} else {</code> or <code>} catch(...) {</code> because it breaks the brace rule and it's not that readable.</p>\n\n<p>Do code a Vector class because it groups your coordinates together so the code gets more easily readable and managable.</p>\n\n<hr>\n\n<p><code>SpriteHandler</code> Class:</p>\n\n<pre><code> glBegin(GL_QUADS);\n glTexCoord2f(0, 1);\n glVertex2f(x, y);\n</code></pre>\n\n<p>Don't format the code this way because you don't open a new brace level.</p>\n\n<hr>\n\n<p><code>TextureHandler</code> Class:</p>\n\n<pre><code> } catch (IOException e) {\n e.printStackTrace();\n }\n</code></pre>\n\n<p>don't eat important error/fault information, propagate it further downwards with a exception or a null result which is checked.</p>\n\n<p>Don't call the class Handler because a Handler handles player input or a fault.</p>\n\n<hr>\n\n<p><code>Player</code> Class:</p>\n\n<pre><code> if (moveSpeed < MAX_MOVE_SPEED && moveSpeed > -MAX_MOVE_SPEED) {\n moveSpeed += force;\n xVelocity = scaleX * moveSpeed;\n } else if (moveSpeed >= MAX_MOVE_SPEED) {\n moveSpeed = MAX_MOVE_SPEED;\n xVelocity = scaleX * moveSpeed;\n } else if (moveSpeed <= -MAX_MOVE_SPEED) {\n moveSpeed = -MAX_MOVE_SPEED;\n xVelocity = scaleX * moveSpeed;\n }\n</code></pre>\n\n<p>one word: <em>redudandency</em></p>\n\n<p>You should try to avoid it as best as possible, and on top of that there is no else part, so a better code is</p>\n\n<pre><code> if (abs(moveSpeed) < MAX_MOVE_SPEED) {\n moveSpeed += force;\n }\n else {\n moveSpeed = clamp(moveSpeed, -MAX_MOVE_SPEED, MAX_MOVE_SPEED);\n }\n\n xVelocity = scaleX * moveSpeed;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T06:04:43.080",
"Id": "45840",
"Score": "0",
"body": "What is 'clamp' method that you used?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T06:09:02.630",
"Id": "45841",
"Score": "0",
"body": "a standard math function, prototype is clamp(value, min, max) see http://msdn.microsoft.com/de-de/library/microsoft.xna.framework.mathhelper.clamp(v=xnagamestudio.40).aspx http://docs.unity3d.com/Documentation/ScriptReference/Mathf.Clamp.html (switch language to c#)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T06:19:35.427",
"Id": "45842",
"Score": "0",
"body": "Your answer seems very Unity based."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T06:40:03.523",
"Id": "45843",
"Score": "3",
"body": "I strongly disagree with the first item and [so does Oracle](http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T06:46:03.130",
"Id": "45844",
"Score": "0",
"body": "@hasherr why... its a standard math function http://www.opengl.org/sdk/docs/manglsl/xhtml/clamp.xml"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T06:47:41.107",
"Id": "45845",
"Score": "0",
"body": "@Lstor this is opinion/programming style based"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T06:50:56.883",
"Id": "45846",
"Score": "0",
"body": "@Quonux I also disagree, as I also do with you critiquing my format on my OpenGl quad rendering. It's an organizational thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T07:51:26.633",
"Id": "45848",
"Score": "1",
"body": "@Quonux It's not opinion- or programming style-based in Java, which has [a standardized coding convention that says to do as OP does](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-142311.html#449) (see section 7.4 and 7.9)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T13:43:01.277",
"Id": "57936",
"Score": "1",
"body": "I agree with everything except the things that Lstor already pointed out, but I still think it's worth to give +1."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T05:30:00.373",
"Id": "29076",
"ParentId": "29073",
"Score": "3"
}
},
{
"body": "<p>You have a <code>Texture texture;</code> field in your <code>TextureHandler</code> class that seems to only be used in one method, and should therefore be a local variable.</p>\n\n<pre><code>public class TextureHandler {\n public Texture grabTexture(String ext, String name) {\n try {\n texture = TextureLoader.getTexture(\n ext.toUpperCase(), ResourceLoader.getResourceAsStream(\n \"/res/textures/\" + name + \".\" + ext.toLowerCase()));\n return texture;\n } catch (IOException e) {\n e.printStackTrace();\n return null;\n }\n }\n}\n</code></pre>\n\n<p>I also think that you should make <strong>better use of the <code>private</code> keyword. There are several fields in your classes that don't need the \"default\" visibility but should rather be marked <code>private</code></strong>.</p>\n\n<p>Besides this, I agree with Quonux's answer (except the first part about <code>} else {</code> or <code>} catch(...) {</code> which you are doing totally fine).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T13:48:27.167",
"Id": "35688",
"ParentId": "29073",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-27T23:26:06.610",
"Id": "29073",
"Score": "3",
"Tags": [
"java",
"game",
"opengl"
],
"Title": "WIP platformer game"
}
|
29073
|
<p>I'm trying to write a simple GTK GUI for the command line program auCDtect. It is supposed to take .flac files, convert them to .wav temporarily, pass the to the auCDtect command line program to check they are lossless and then delete the temporary .wav file and output the results.</p>
<p>For around 10+ files it's rather slow (though admittedly so are the command line tools), so I was hoping somebody could review the code and let me know of any obvious improvements or mistakes I'm making.</p>
<p>All the code can be found <a href="https://github.com/db579/LosslessChecker/tree/master/Audiochecker/src" rel="nofollow">here</a>.</p>
<p>GUI class</p>
<pre><code>//The user interface
import java.io.*;
import java.util.*;
import org.apache.commons.io.*;
import org.gnome.gdk.*;
import org.gnome.glib.*;
import org.gnome.gtk.*;
public class GTK extends Window implements DeleteEvent {
private String directoryPath = null;
private String filePath = null;
private Collection<String> fileList = new ArrayList<String>();
private auCDtect auCDtect;
private TextBuffer resultsBuffer;
private ProgressBar progressBar;
private double progress = 0;
private String output;
private String summary;
boolean outputUpdated = false;
public GTK() {
//Set window title
setTitle("Dan's AudioChecker");
//Initialise user interface
initUI(this);
//Exit GUI cleanly if close pressed
connect(this);
//Set default size, position and make window visible
setDefaultSize(800, 800);
setPosition(WindowPosition.CENTER);
showAll();
}
public void initUI(final GTK gtk) {
setWindowIcon();
//Create container to vertically stack widgets
VBox vBox = new VBox(false, 5);
//Set alignment and size of action buttons container
Alignment halign = new Alignment(0, 0, 1, 0);
//Create hoziontal box for action buttons (homogenous spacing - false, default spacing 10)
HBox actionButtons = new HBox(false, 10);
//Create horizontal box for view panes
HBox viewPanes = new HBox(false, 10);
//Create horizontal box for progress bar
HBox progressBarBox = new HBox(false, 10);
//create scrollable text box for file queue
final TextBuffer queueBuffer = new TextBuffer();
TextTag label = new TextTag();
label.setBackground("#EAE8E3");
queueBuffer.insert(queueBuffer.getIterStart(), "Queue \n", label);
queueBuffer.insert(queueBuffer.getIterEnd(), "\n");
TextView queue = new TextView(queueBuffer);
queue.setEditable(false);
queue.setCursorVisible(false);
ScrolledWindow queueWindow = new ScrolledWindow();
queueWindow.add(queue);
//create scrollable text box for results info
resultsBuffer = new TextBuffer();
resultsBuffer.insert(resultsBuffer.getIterStart(), "Results \n", label);
resultsBuffer.insert(resultsBuffer.getIterEnd(), "\n");
TextView results = new TextView(resultsBuffer);
results.setEditable(false);
results.setCursorVisible(false);
ScrolledWindow resultsWindow = new ScrolledWindow();
resultsWindow.add(results);
//Create buttons to user interface
final FileChooserDialog directoryDialog = new FileChooserDialog("Directory", null, FileChooserAction.SELECT_FOLDER);
Button directory = new Button("Directory");
final FileChooserDialog filesDialog = new FileChooserDialog("Files", null, FileChooserAction.OPEN);
FileFilter allLosslessMusic = new FileFilter("Lossless Music");
allLosslessMusic.addMimeType("audio/flac");allLosslessMusic.addMimeType("audio/wav");
Button files = new Button("File(s)");
filesDialog.addFilter(allLosslessMusic);
Label emptyLabel = new Label("");
Button start = new Button("Start");
//Create progress bar and add to hbox
progressBar = new ProgressBar();
progressBarBox.add(progressBar);
//Make fileChooser dialog come up when directories is clicked
directory.connect(new Button.Clicked(){
@Override
public void onClicked(Button directory) {
directoryDialog.run();
directoryPath = directoryDialog.getFilename();
String[] extensions = {".flac", ".wav"};
if(!(directoryPath == null)){
Iterator<File> files = FileUtils.iterateFiles(new File(directoryPath), new SuffixFileFilter(extensions, IOCase.INSENSITIVE),DirectoryFileFilter.DIRECTORY);
while(files.hasNext()){
File j = files.next();
fileList.add(j.getPath());
queueBuffer.insert(queueBuffer.getIterEnd(), j+"\n");
}
}
directoryDialog.hide();
}
});
//Make fileChooser dialog come up when files is clicked
files.connect(new Button.Clicked(){
@Override
public void onClicked(Button files) {
filesDialog.run();
if (!(filesDialog.getFilename() == null)){
filePath = filesDialog.getFilename();
fileList.add(filePath);
queueBuffer.insert(queueBuffer.getIterEnd(), filePath+"\n");
}
filesDialog.hide();
}
});
//Make start button work
start.connect(new Button.Clicked(){
@Override
public void onClicked(Button start){
auCDtect = new auCDtect(fileList, gtk);
Thread auCDtectThread = new Thread(auCDtect);
auCDtectThread.start();
Glib.idleAdd(new Handler(){
public boolean run(){
progress = auCDtect.getProgress();
output = auCDtect.getOutput();
summary = auCDtect.getSummary();
if(summary == null){
progressBar.setFraction(progress);
if((outputUpdated == true)&&(output != null)){
resultsBuffer.insert(resultsBuffer.getIterEnd(), output+"\n");
setOutputUpdated(false);
}
return true;
}
else{
progressBar.setFraction(progress);
if(summary != null){
resultsBuffer.insert(resultsBuffer.getIterEnd(), "\n"+"Results summary:"+"\n\n"+summary);
}
return false;
}
}
});
}
});
//Position buttons and add to fix
actionButtons.packStart(directory, false, false, 0);
actionButtons.packStart(files, false, false, 0);
actionButtons.packStart(emptyLabel, true, true, 0);
actionButtons.packStart(start, false, false, 0);
//Add
viewPanes.add(queueWindow);
viewPanes.add(resultsWindow);
halign.add(actionButtons);
vBox.packStart(halign, false, false, 10);
vBox.packStart(viewPanes, true, true, 10);
vBox.packStart(progressBarBox, false, false, 10);
add(vBox);
setBorderWidth(15);
}
//Method to exit application
public boolean onDeleteEvent(Widget widget, Event event) {
Gtk.mainQuit();
return false;
}
//Method to set window icon
public void setWindowIcon(){
//Set the audiochecker icon that appears in the start bar
Pixbuf icon = null;
try {
icon = new Pixbuf("audiochecker.png");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
setIcon(icon);
}
public void setOutputUpdated(boolean outputUpdated){
this.outputUpdated = outputUpdated;
}
public static void main(String[] args) {
//Initialise and run GUI
Gtk.init(args);
new GTK();
Gtk.main();
}
}
</code></pre>
<p>The audiochecker Class</p>
<pre><code>//Checks the wav files using auCDtect command line
import java.io.*;
import java.util.*;
public class auCDtect implements Runnable {
private String processingLog;
private String output;
private String summary;
private Collection<String> fileList;
private Collection<String> tempWavList = new ArrayList<String>();
private double progress = 0.0;
private GTK gtk;
auCDtect(Collection<String> fileList, GTK gtk){this.fileList = fileList; this.gtk = gtk;}
public void run () {
List<String> command = new ArrayList<String>();
command.add("./auCDtect");
command.add("-d");
command.add("-m10");
//Add each song passed to this class to the auCDtect command
for(String file:fileList){
if(file.toLowerCase().contains("flac")){
AudioConverter audioConverter = new AudioConverter();
String tempWav = "tempWav.wav"+fileList.iterator();
tempWavList.add(tempWav);
try {
audioConverter.decode(file, tempWav);
} catch (IOException e) {
e.printStackTrace();
}
file = tempWav;
}
command.add(file);
}
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = null;
try {
process = processBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
//Set up error stream thread
StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR", this);
//Set up output stream thread
StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT", this);
// Start error and input stream threads
new Thread(errorGobbler).start();
new Thread(outputGobbler).start();
}
public void update(double progress, String processingLog, String output, String summary){
this.processingLog = processingLog;
this.output = output;
this.summary = summary;
this.progress = progress/(fileList.size());
gtk.setOutputUpdated(true);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(this.progress == 1){
deleteTempTracks();
}
}
public double getProgress(){
return progress;
}
public String getProcessingLog(){
return processingLog;
}
public String getOutput(){
return output;
}
public String getSummary(){
return summary;
}
public void deleteTempTracks(){
for(String tempFileName:tempWavList){
File tempFile = new File(tempFileName);
if(tempFile.exists()){
tempFile.deleteOnExit();
}
}
}
}
</code></pre>
<p>The class to convert flac to WAV</p>
<pre><code>import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.kc7bfi.jflac.PCMProcessor;
import org.kc7bfi.jflac.FLACDecoder;
import org.kc7bfi.jflac.metadata.StreamInfo;
import org.kc7bfi.jflac.util.ByteData;
import org.kc7bfi.jflac.util.WavWriter;
/**
* Decode FLAC file to WAV file application.
* @author kc7bfi
*/
public class AudioConverter implements PCMProcessor {
private WavWriter wav;
/**
* Decode a FLAC file to a WAV file.
* @param inFileName The input FLAC file name
* @param outFileName The output WAV file name
* @throws IOException Thrown if error reading or writing files
*/
public void decode(String flacFile, String tempWav) throws IOException {
FileInputStream inputStream = new FileInputStream(flacFile);
FileOutputStream outputStream = new FileOutputStream(tempWav);
wav = new WavWriter(outputStream);
FLACDecoder decoder = new FLACDecoder(inputStream);
decoder.addPCMProcessor(this);
decoder.decode();
}
/**
* Process the StreamInfo block.
* @param info the StreamInfo block
* @see org.kc7bfi.jflac.PCMProcessor#processStreamInfo(org.kc7bfi.jflac.metadata.StreamInfo)
*/
public void processStreamInfo(StreamInfo info) {
try {
wav.writeHeader(info);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Process the decoded PCM bytes.
* @param pcm The decoded PCM data
* @see org.kc7bfi.jflac.PCMProcessor#processPCM(org.kc7bfi.jflac.util.ByteSpace)
*/
public void processPCM(ByteData pcm) {
try {
wav.writePCM(pcm);
} catch (IOException e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>The streamGobbler class to handle output</p>
<pre><code>//Processes the output of the auCDtect command line program
import java.io.InputStream;
import java.util.Scanner;
public class StreamGobbler implements Runnable {
InputStream inputStream;
String type;
private String processingLog = null;
private String output = null;
private String summary = null;
protected boolean finished = false;
private auCDtect auCDtect;
private int progress = 0;
StreamGobbler(InputStream inputStream, String type, auCDtect auCDtect){this.inputStream = inputStream; this.type = type; this.auCDtect = auCDtect;}
public void run(){
Scanner scanner = new Scanner(inputStream);
while (((scanner.hasNextLine())&&(type == "OUTPUT"))){
String line = scanner.nextLine();
if(line.contains("Processing file:")){
processingLog = line.substring(line.indexOf("P"), (line.indexOf("]")+1));
}
if(line.contains("This track looks like")){
output = line.substring(line.indexOf("This track"), (line.indexOf("%")+1));
progress = progress + 1;
}
if(line.contains("These")){
summary = line.substring(line.indexOf("These tracks"));
}
if((type == "OUTPUT")&&(progress > 0)){
auCDtect.update(progress, processingLog, output, summary);
processingLog = null;
output = null;
summary = null;
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>A few random notes:</p>\n\n<ol>\n<li><p>If I'm right it's not thread safe.</p>\n\n<blockquote>\n<pre><code>progress = auCDtect.getProgress();\noutput = auCDtect.getOutput();\nsummary = auCDtect.getSummary();\n</code></pre>\n</blockquote>\n\n<p>I guess the calls above runs on an event dispatcher thread while the fields of <code>auCDtect</code> are set by <code>StreamGobbler</code> which is run on another thread, started by <code>auCDtect</code>.</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em>.</p></li>\n<li><p>Comments like these should be method names:</p>\n\n<blockquote>\n<pre><code>// create scrollable text box for file queue\n...\n// create scrollable text box for results info\n</code></pre>\n</blockquote>\n\n<p>Eight level of indentation is too much, you should extract out some methods and classes to fulfill the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility principle</a>. Having small classes and methods means that you don't have to understand the whole program during maintenance, modifying just a small part of it is easier and requires less work.</p>\n\n<blockquote>\n <p>The first rule of functions is that they should be small. \n The second rule of functions is that\n they should be smaller than that.</p>\n</blockquote>\n\n<p>Source: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Chapter 3: Functions</em></p></li>\n<li><p>I don't know that <code>WavWriter</code> and <code>FLACDecoder</code> close the <code>FileInputStream</code> and <code>FileOutputStream</code> instances that they get but I guess they aren't. </p>\n\n<blockquote>\n<pre><code>public void decode(String flacFile, String tempWav) throws IOException {\n FileInputStream inputStream = new FileInputStream(flacFile);\n FileOutputStream outputStream = new FileOutputStream(tempWav);\n wav = new WavWriter(outputStream);\n FLACDecoder decoder = new FLACDecoder(inputStream);\n decoder.addPCMProcessor(this);\n decoder.decode();\n}\n</code></pre>\n</blockquote>\n\n<p>Close them in a <code>finally</code> block or use try-with-resources. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow noreferrer\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n<li><blockquote>\n<pre><code>InputStream inputStream;\nString type;\n</code></pre>\n</blockquote>\n\n<p>These fields could be private. (<a href=\"https://stackoverflow.com/q/5484845/843804\">Should I always use the private access modifier for class fields?</a>; <em>Item 13</em> of <em>Effective Java 2nd Edition</em>: <em>Minimize the accessibility of classes and members</em>.)</p></li>\n<li><p>This field is never used, I think you could remove it:</p>\n\n<blockquote>\n<pre><code>protected boolean finished = false;\n</code></pre>\n</blockquote></li>\n<li><blockquote>\n<pre><code>StreamGobbler(InputStream inputStream, String type, auCDtect auCDtect) {\n this.inputStream = inputStream;\n this.type = type;\n this.auCDtect = auCDtect;\n}\n</code></pre>\n</blockquote>\n\n<p>Check input values and throw an exception if they're not valid. If one of the parameters is <code>null</code> the <code>run</code> method will throw a <code>NullPointerException</code> later. When they're <code>null</code>s it's a bug on the side of the caller and there is no point to continue the program with invalid state. Throwing an exception immediately helps debugging a lot since you get a stacktrace with the frames of the erroneous client, not just a <code>NullPointerException</code> on another thread. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><blockquote>\n<pre><code>processingLog = line.substring(line.indexOf(\"P\"), (line.indexOf(\"]\") + 1));\n</code></pre>\n</blockquote>\n\n<p>I guess there is a method for that in <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html\" rel=\"nofollow noreferrer\"><code>StringUtils</code></a> with a readable name which expresses the intent of the statement. <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substringBetween%28java.lang.String,%20java.lang.String,%20java.lang.String%29\" rel=\"nofollow noreferrer\"><code>substringBetween</code></a> looks very promising:</p>\n\n<blockquote>\n<pre><code>StringUtils.substringBetween(\"wx[b]yz\", \"[\", \"]\") = \"b\"\nStringUtils.substringBetween(\"yabczyabcz\", \"y\", \"z\") = \"abc\"\n</code></pre>\n</blockquote>\n\n<p>(<em>Effective Java, 2nd edition</em>, <em>Item 47: Know and use the libraries</em> The author mentions only the JDK's built-in libraries but I think the reasoning could be true for other libraries too.)</p></li>\n<li><blockquote>\n<pre><code>public class auCDtect implements Runnable {\n</code></pre>\n</blockquote>\n\n<p>According to the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367\" rel=\"nofollow noreferrer\">Code Conventions for the Java Programming Language</a> class names should start with uppercase letters. <a href=\"http://docs.oracle.com/javase/specs/\" rel=\"nofollow noreferrer\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a> says the following:</p>\n\n<blockquote>\n <p>Class and Interface Type Names</p>\n \n <p>Names of class types should be descriptive nouns or noun phrases, not overly long, in mixed\n case with the first letter of each word capitalized.</p>\n</blockquote>\n\n<p>Also related: <em>Effective Java, 2nd edition</em>, <em>Item 56: Adhere to generally accepted naming conventions</em></p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-17T11:15:10.293",
"Id": "87969",
"Score": "0",
"body": "Thanks for this very detailed analysis. I've got most of the points adjusted - could you clarify 1 and 3 though? \nFor point 1 why do you say it's not thread safe (1 is reading, 1 is writing and the read doesn't have to return anything) and how could I make it thread safe?For 3 neither class has a close method so how would I do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-25T12:08:47.383",
"Id": "89307",
"Score": "0",
"body": "@db579: The code has a visibility problem there. A thread write it but another threads might not see the change (unless you properly synchronize the reads and writes). The linked book explains it quite well but I guess you can find another resources about it (search for \"visibility\"). http://jcip.net.s3-website-us-east-1.amazonaws.com/ is also a good book. For 3: `FileInputStream` and `FileOutputStream` have `close`, you should call them."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T21:14:09.927",
"Id": "43745",
"ParentId": "29075",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "43745",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T05:14:22.027",
"Id": "29075",
"Score": "3",
"Tags": [
"java",
"gui",
"audio"
],
"Title": "Simple GTK GUI for the command line program auCDtect"
}
|
29075
|
<p>I have written code to print a range of numbers using multi-threaded programming. It takes in the number of threads to spawn as input.</p>
<p>It is working fine and giving the expected results. I just wanted you to check it and see if the code can be written a bit more efficiently.</p>
<pre><code> #include<stdio.h>
#include <windows.h>
void print(LPVOID );
struct range
{
int start;
int end;
int threadnum;
};
void print(LPVOID param)
{
struct range *ptr=(struct range *)(param);
for(int i=ptr->start;i<=ptr->end;i++)
printf("\n Thread %d printed %d",ptr->threadnum,i);
}
int main()
{
int start,end,range,split;
int threadcount=0;
printf("\n Enter the start range :");
scanf_s(" %d",&start);
printf("\n Enter the End Range : ");
scanf_s("%d",&end);
printf("\n Enter the number of threads : ");
scanf_s("%d",&threadcount);
struct range **ptr;
ptr = (struct range **)malloc(threadcount*sizeof(struct range *));
if(ptr==NULL)
{
printf("\n Could not allocate memory for struct range * pointer array ");
free(ptr);
return 1;
}
DWORD *ThreadId;
ThreadId=(DWORD *)malloc(threadcount*sizeof(DWORD));
if(ThreadId==NULL)
{
printf("\n Could not allocate memory for DWORD * pointer array ");
free(ThreadId);
return 1;
}
HANDLE *hThreadArray;
hThreadArray=(HANDLE *)malloc(threadcount*sizeof(HANDLE));
if(hThreadArray==NULL)
{
printf("\n Could not allocate memory for hThreadArray * pointer array ");
free(hThreadArray);
return 1;
}
range=end-start+1;
split=(range/threadcount);
for(int i=0;i<threadcount;i++)
{
ptr[i]=(struct range *)malloc(sizeof(struct range));
if(ptr[i]==NULL)
{
free(ptr[i]);
}
if(split%2==0) // if the split is even then calculated the start and end range for the worker threads as below
{
if(i==0)
{
start=start;
end=start+split-1;
ptr[i]->start=start;
ptr[i]->end=end;
ptr[i]->threadnum=i;
hThreadArray[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)print,ptr[i],0,&ThreadId[i]);
if(hThreadArray[i]==NULL)
{
CloseHandle(hThreadArray[i]);
}
}
else
{
start=end+1;
end=start+split-1;
ptr[i]->start=start;
ptr[i]->end=end;
ptr[i]->threadnum=i;
hThreadArray[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)print,ptr[i],0,&ThreadId[i]);
if(hThreadArray[i]==NULL)
{
CloseHandle(hThreadArray[i]);
}
}
}
else
{
if(i==0)
{
start=start;
end=start+split;
ptr[i]->start=start;
ptr[i]->end=end;
ptr[i]->threadnum=i;
hThreadArray[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)print,ptr[i],0,&ThreadId[i]);
if(hThreadArray[i]==NULL)
{
CloseHandle(hThreadArray[i]);
}
}
else
{
start=end+1;
end=start+split-1;
ptr[i]->start=start;
ptr[i]->end=end;
ptr[i]->threadnum=i;
hThreadArray[i] = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)print,ptr[i],0,&ThreadId[i]);
if(hThreadArray[i]==NULL)
{
CloseHandle(hThreadArray[i]);
}
}
}
}
WaitForMultipleObjects(threadcount, hThreadArray, TRUE, INFINITE);
for(int i=0; i<threadcount; i++)
{
CloseHandle(hThreadArray[i]);
free(ptr[i]);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T16:01:29.790",
"Id": "45861",
"Score": "1",
"body": "Please read [this about casting the result of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)."
}
] |
[
{
"body": "<ul>\n<li>First of all, while reviewing your code the bad code formatting style really hurts my eyes. Good code formatting and indentation makes it easier to review and maintain code.</li>\n<li>Get rid of all unnecessary spaces and tabs.</li>\n<li>Your <code>main</code> function is doing many things at once. Try to break the logic in smaller modules and write function for them.</li>\n<li><p>Define your structure into one type using <code>typedef</code>. The code below</p>\n\n<pre><code>struct range\n{\n int start;\n int end;\n int threadnum;\n};\n</code></pre>\n\n<p>should be like </p>\n\n<pre><code>typedef struct range\n{\n int start;\n int end;\n int threadnum;\n}Range;\n</code></pre>\n\n<p>So you can just use <code>Range</code> instead of <code>struct range</code> everytime.</p>\n\n<p>Then </p>\n\n<pre><code>struct range *ptr=(struct range *)(param);\n</code></pre>\n\n<p>will be something like </p>\n\n<pre><code>Range *ptr = (Range *)(param);\n</code></pre></li>\n<li><p>Keep one space both side of operators (<code>=</code>,<code>==</code>).</p></li>\n<li>Your <code>main</code> function should return <code>EXIT_SUCCESS</code> or <code>return 0</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T16:02:38.120",
"Id": "45862",
"Score": "1",
"body": "Good points. About casting you should also read the link in my comment on the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T10:45:36.787",
"Id": "29082",
"ParentId": "29079",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-24T09:06:37.673",
"Id": "29079",
"Score": "1",
"Tags": [
"c",
"multithreading",
"winapi"
],
"Title": "Printing a range of numbers using configurable worker threads"
}
|
29079
|
<p>Is this the best way of doing this? I wanted to make sure the grammar is correct when the array is output.</p>
<p>1 car, 2 cars.</p>
<p>The output is correct but is there an easier way generally? I just want to make sure I am doing this in a proper way. I don't have the benefit of the experience of the majority of you guys so I am asking for general guidance.
Or is it a case of "if the code works then that's all that matters".</p>
<pre><code><?php
//generates a random number between 1 -10.
function randomnumber(){
$randomnumber = mt_rand(1, 10);
return $randomnumber;
}
//Creates array.
//Checks to see if the random number is greater than 1
//Adds an 's' to the entry if greater than one
for ($i = 0; $i < 10; $i++){
$rannum = randomnumber();
if ($rannum > 1){
$adds = "s";
}else{
$adds = "";
}
$products[$i] = $rannum." car".$adds;
}
//Outputs the final array.
foreach ($products as $current){
echo $current."<br />";
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T11:34:28.120",
"Id": "45904",
"Score": "0",
"body": "I've provided about 4 possible alternatives, but they're all geared towards _\"optimization\"_, sort of. You might get the impression I find your code terrible (which it isn't), but it's kind of hard to know what you mean by _an easier way_. Personally, I'd ditch the second loop and use `implode`, because I find it easier. Some old-school C developers might find my `for`-loop using 2 variables the easier alternative... could you take a look, perhaps ask some follow-ups or expand on what _easyness_ means to you?"
}
] |
[
{
"body": "<p>I also lack a bit of experiance.\nOften it is better to use classes.\nMy probosal would be:</p>\n\n<p>I did not test it.</p>\n\n<pre><code><?php\nclass products {// or wathever name you like\n\n public $products = array();\n\n protected function generate_random_number(){\n return mt_rand(1,10);\n } \n\n public function __construct(){\n for($i=0;$i<10;$i++){\n $ran = $this->generate_random_number();\n $this->products[$i] = $ran.' car'.(($ran>1)?'s':'');\n }\n }\n\n public function render(){\n return implode('<br />',$this->products); \n }\n}\n\n$cars = new products();\necho $cars->render();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:55:42.237",
"Id": "45959",
"Score": "0",
"body": "Many thanks for your response. I'm not quite onto classes yet but I do recognise them from when I learnt a bit of Java. The format seems the same.\nI see what you're getting at though and I can see how it would make sense."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T07:19:05.613",
"Id": "46002",
"Score": "0",
"body": "This code does violate the first of the SOLID principles [Single responsibility principle](http://en.wikipedia.org/wiki/Single_responsibility_principle), aswell as a few conventions (ie class names start with an UpperCase letter). But the main problem is that this class is both populating an array with data, and rendering the output."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T12:40:54.117",
"Id": "46028",
"Score": "0",
"body": "PHP doesn't have naming conventions. A separate class who's only method is render, which is just a wrapper over implode is a bit too over complicating, i think."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:23:26.800",
"Id": "46042",
"Score": "1",
"body": "@AlucardTheRipper: Officially, PHP doesn't have standards, but [there's a proposal in the making](https://github.com/php-fig/fig-standards), and all major parties do pay notice to it, including ZendFW, Zend being the company behind PHP means these conventions aren't going away any time soon. Wrapping the render function is, indeed overkill, but then an object that does all the work in its constructor, and is then waiting for you to call the `render` method isn't quite efficient, either."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T14:25:39.387",
"Id": "46043",
"Score": "0",
"body": "If you go for OO code, then you might as well do it right. OOP is almost certainly going to be less efficient, but it'll almost certainly be easier to maintain and co-author, so you might aswell follow the SOLID principles from the get-go. anyway, If you want to avoid overkill: check the one-liner in my answer. It's horrible, but you find a faster way to do what the OP wanted in PHP"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T15:04:50.180",
"Id": "46050",
"Score": "0",
"body": "Doing OO code right doesn't mean separating ANYTHING. Putting the generating of the membervariable $products in the constructor is right, because every other public methods relies on $products. The class is not very efficient but easy to maintain. And i like your version after \"So, your code ends up looking like:\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T09:03:08.160",
"Id": "46198",
"Score": "0",
"body": "@AlucardTheRipper: It _does_ mean separating things. Objects couple data and functionality (in some cases), but an object should have, and only 1 distinct task (or reason to change). `Products`'s task is to generate a list of 10 random numbers, and provide access to that data. The rendering is another task (presenting data to the outside world), and should be dealt with elsewhere, it might be in the same module, but not the same class... When writing something following MVC, you're not going to call `new Number()` in the view, are you? but in the model/controller layers... that's what I meant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T12:39:15.297",
"Id": "46210",
"Score": "0",
"body": "@Elias Van Ootegem for such a simple task there is no need for MVC, I think. My class doesn't present data to the outer world, it just renders products as string. If you strictly follow MVC, than you would have to separate it."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T01:41:06.040",
"Id": "29101",
"ParentId": "29080",
"Score": "1"
}
},
{
"body": "<p>Just a little detail, to kick off: you're not declaring <code>$products</code> as an array anywhere. PHP will create a new variable, and assign it an empty array for you, true enough, but if you change your ini settings to <code>E_STRICT | E_ALL</code>, you'll notice that it doesn't do this without complaining about it.<Br/>\nIt's always better to declare and initialize your variables beforehand. writing <code>$products = array();</code> isn't hard, nor is it very costly. At any rate it's less costly than producing a notice.</p>\n\n<p>Anyway, about your actual code: There is room to make your code more efficient way, so let's look at it piecce by piece:</p>\n\n<pre><code>function randomnumber(){\n $randomnumber = mt_rand(1, 10);\n return $randomnumber;\n}\n</code></pre>\n\n<p>This function is just calling <code>mt_rand</code>, and returning the result. But only after the return value of <code>mt_rand</code> has been assigned to a local variable. That's just wasteful. Look at it from a machine's standpoint:</p>\n\n<pre><code>randomnumber();//call <name:randomnumber>\n \\\\\n \\==> lookup function in memory, goto, and start\n $randomnumber = mt_rand(1,10);\n \\\\ \\\\\n \\=> allocate memory \\=> lookup function, pass 2 arguments & call\n || /\\ //\n || ||=======then, assign return valueof: =============/\n ||\n \\== return COPY of assigned value\n then flag $randomnumber for GC (Garbage Collection)\n</code></pre>\n\n<p>That's just a hell of a lot of work, for a simple call to <code>mt_rand</code>. You can easily omit the allocation and garbage collection steps by changing the <code>randomnumber</code> function to this:</p>\n\n<pre><code>function randomnumber()\n{\n return mt_rand(1,10);\n}\n</code></pre>\n\n<p>This does exactly the same thing, without the overhead of an assignment. Still, a function call that just calls another function is a bit silly. If anything, it's an alias to an existing function, with default params. But you're still returning a copy of the return value of the core function (<code>mt_rand</code>). Just ditch the function, and in-line <code>mt_rand(1,10);</code><br/>\nIf you insist, keep the alias, but define default arguments:</p>\n\n<pre><code>function randomnumber($from = 1, $to = 10)\n{\n $from = (int) $from;//make sure we're dealing with ints\n $to = (int) $to;\n if ($from > $to)\n {//check order of params\n $tmp = $from;\n $from = $to;\n $to = $tmp;\n }\n return mt_rand($from, $to);\n}\nrandomnumber();//returns mt_rand(1,10)\nrandomnumber(10,20);//returns mt_rand(10,20)\nrandomnumber(200);//returns mt_rand(10, 200)\nrandomnumber(null, 5);//returns mt_rand(0,5)\n</code></pre>\n\n<p>But that's only of any use if you're going to use this alias function throughout, and don't want to bother passing those 2 arguments all the time, or (in case of passign variables) you're not sure what they might contain (<code>null</code>, <code>'a string'</code>, <code>(float) '0.123'</code>,...).<br/>\nBut we're drifting off topic. Next, the array-constructing loop:</p>\n\n<pre><code>//Creates array.\n//Checks to see if the random number is greater than 1\n//Adds an 's' to the entry if greater than one\nfor ($i = 0; $i < 10; $i++){\n $rannum = randomnumber();\n if ($rannum > 1){\n $adds = \"s\";\n }else{\n $adds = \"\";\n }\n $products[$i] = $rannum.\" car\".$adds;\n}\n</code></pre>\n\n<p>This isn't too bad, really, just remove the function-call, and you're good, and perhaps shorten the <code>if-else</code> to a ternary or a single if-statement. you could argue that assigning the random number to a variable isn't really necessairy. You're using <code>$i</code> as an array-key, so you could assign the value to the array directly, and check the value there</p>\n\n<pre><code>for($i=0;$i<10;$i++)\n{\n $products[$i] = mt_rand(1,10);//$i is the key, so we don't need any other vars\n $products[$i] .= 'car '.($products[$i] > 1 ? 's' : '');\n}\n//without ternary:\nfor($i=0;$i<10;$i++)\n{\n $products[$i] = mt_rand(1,10).' car';//just concat car already\n if ($products[$i] > 1)\n {//comparing to int will cast $products[$i] to int\n //since the string starts with an int, it'll compare that int\n //'4 car' > 1 ~~> 4 > 1 ~~> true ==> '4 car' .= s ===> 4 cars\n $products[$i] .= 's';\n }\n}\n</code></pre>\n\n<p>Then, the output loop:</p>\n\n<pre><code>//Outputs the final array.\nforeach ($products as $current){\n echo $current.\"<br />\";\n}\n</code></pre>\n\n<p>Ok, that's perfectly valid code, too, but wouldn't it be a lot shorter just writing this:</p>\n\n<pre><code>echo implode('<br/>', $products);\n</code></pre>\n\n<p>This turns an array into a string, and separates all values with a <code><br/></code>. To add another break at the end (and/or beginning) of this string:</p>\n\n<pre><code>echo '<br/>', implode('<br/>', $products), '<br/>';\n</code></pre>\n\n<p>I use this all the time if I want to dump a quick <code><ul></code> to the screen:</p>\n\n<pre><code>echo '<ul><li>', implode('</li><li>', $array), '</li></ul>';\n</code></pre>\n\n<p>So, your code ends up looking like:</p>\n\n<pre><code>for($i=0;$i<10;$i++)\n{\n $products[$i] = mt_rand(1,10);//$i is the key, so we don't need any other vars\n $products[$i] .= 'car '.($products[$i] > 1 ? 's' : '')\n}\necho implode('<br/>', $products);\n</code></pre>\n\n<p>Or, if regexes don't scare you and you like some unmaintainable code, you could even do this:</p>\n\n<pre><code>$arr = array();\n$i=0;\nwhile($i++<10)\n{\n $arr[] = mt_rand(1,10);\n}\necho preg_replace('/(([2-9]+|10)\\s+car)(?!s)/','$1s',implode(' car<br/>',$arr).' car');\n</code></pre>\n\n<p>But that's just terrible code to maintain... </p>\n\n<p>If the array you're echo-ing isn't of any use to you except for your printing it out, you could just as well drop the array:</p>\n\n<pre><code>for($i=0, $j=mt_rand(1,10);$i<10;$i++, $j=mt_rand(1,10))\n{\n echo $j, ' car', $j > 1 ? 's' : '', '<br/>';\n}\n</code></pre>\n\n<p>Which, if you're a massochist, you can turn into a one-liner quite easily:</p>\n\n<pre><code>for($i=0, $j=mt_rand(1,10);$i<10;$i++, $j=mt_rand(1,10)) echo $j, ' car', $j > 1 ? 's' : '', '<br/>';\n</code></pre>\n\n<p>As you can see, I'm using <code>$i</code> to count the number of iterations, while at the same time <code>$j</code> is (re-)assigned a new random value upon each iteration, too.<Br/>\nUsing multiple variables in a for-loop construct is most commonly done to avoid calling <code>count</code> too much when <code>for</code>-looping a numerically indexed array:</p>\n\n<pre><code>for($i=0, $j = count($array); $i<$j;$i++)\n{\n var_dump($array[$i]);\n}\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>for($i=0;$i<count($array);$i++)\n{\n var_dump($array[$i]);\n}\n</code></pre>\n\n<p>Both of the loops above behave in the same way (provided <code>$array</code> doesn't change inside the loop), but the first one is more performant, because, as you probably know, after each iteration the conditional expression (ie <code>$i<$j</code> or <code>$i<count($array)</code>) is evaluated. In the second case, this means the length of <code>$array</code> will be counted time and time again, whereas in the first case, this is only done once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T19:04:00.090",
"Id": "45961",
"Score": "0",
"body": "Wow. Now that is a response. Many thanks for the big help. I do feel more comfortable declaring variables at the start. \nWould it be good idea to set E_STRICT | E_ALL in the ini anyway? I'm using a localhost environment. If that is unforgiving then it should encourage me to write very clean code.\nThis answered a lot of questions for me and gave me the answers I was looking for.\nMany thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T07:03:51.723",
"Id": "46001",
"Score": "0",
"body": "It's always a good idea to set `E_STRICT | E_ALL` in the ini, especially when writing new code. Notices, warnings and errors are there for a reason: to help you write better code. Ignoring them is like ignoring good advice. In a production environment, though, those same errors and warnings can provide clients with bad intentions with information about your code, which they might exploit compromise your site, that's why you can disable displaying them. On a localhost system, though: never supress them"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T10:11:41.183",
"Id": "29112",
"ParentId": "29080",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "29112",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T09:59:00.330",
"Id": "29080",
"Score": "1",
"Tags": [
"php",
"array",
"random"
],
"Title": "Am I on the right track with this random number array?"
}
|
29080
|
<p>I just wrote some PHP to let a client lock off a their one-page site from the public using a password. No users and no database. Just checking the password the user enters and testing it against the chosen phrase. This should be simple (right?) but I havn't built this sort of thing before. Let me know what you think, and whether it could be done better. Thanks!</p>
<p><code>includes/session.php</code></p>
<pre><code>class Session {
private $logged_in;
function __construct() {
session_start();
$this->check_login();
}
// Return whether they are logged in.
public function is_logged_in() {
return $this->logged_in;
}
// When initialized, check to see if the user is logged in.
private function check_login() {
if (isset($_SESSION['logged_in'])) {
// If logged in, take this action
$this->logged_in = true;
} else {
// If not logged in, take this action
$this->logged_in = false;
}
}
// Set the session. User will remain logged in.
public function login() {
$_SESSION['logged_in'] = 1;
$this->logged_in = true;
}
// Log out. Unset session and destroy it.
public function logout() {
unset($_SESSION['logged_in']);
$this->logged_in = false;
session_destroy();
}
public function check_pass($pass) {
$pass = @strip_tags($pass);
$pass = @stripslashes($pass);
if ($pass !== 'TheChosenPassword') return false;
return true;
}
}
</code></pre>
<p><code>login.php:</code></p>
<pre><code>require_once('includes/session.php');
// If already logged in just send them to index.php
if ($session->is_logged_in()) {
header('Location: index.php');
exit;
}
// Create the var in the global scope.
$msg = 'This page is private.<br> Please enter the password.';
// If the form was submitted ...
if (isset($_POST['submit'])) {
// Make sure they entered a pass
if (!$_POST['pass']) {
$msg = "Please enter a password.";
} else {
// If they entered a pass, grab it and trim it.
$pass = trim($_POST['pass']);
// Now check the pass
if ($session->check_pass($pass)) {
$session->login();
header('Location: index.php');
exit;
} else {
$msg = "Sorry, that password is incorrect.";
} // Endif checkpass
} // endif isset(pass)
} // Endif isset(post)
?> <!-- The form is bellow -->
</code></pre>
<p><code>index.php</code></p>
<pre><code>require_once('includes/session.php');
if (!$session->is_logged_in()) {
header('Location: login.php');
exit;
}
</code></pre>
<p>You can probably guess from the code that the form just has an <code><input></code> with a name of 'pass' and a submit button with a name of 'submit'. Also a <code><small></code> tag in which i echo <code>$msg</code>. So, any thoughts on how this could be improved? Did I make any glaring mistakes? Thanks for the help!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T15:44:07.223",
"Id": "45859",
"Score": "0",
"body": "As far as I can tell it looks pretty good. Don't know why you bother to strip tags etc though?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:15:02.587",
"Id": "45901",
"Score": "0",
"body": "There is always room for improvement. You could make it a little bit more portable by creating a Session class that handles setting, creating,.. of Session values and another class that handles User access. But on the other hand, why bother. this works fine"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:29:27.313",
"Id": "45918",
"Score": "0",
"body": "Thanks guys. I appreciate the feedback. @Bono I stripped tags b/c I didn't want to let users enter some string like \"`?>insert evil code`\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T17:58:39.737",
"Id": "45953",
"Score": "0",
"body": "@Ian: Why is that a concern? You're not executing or displaying the password."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:18:22.290",
"Id": "45957",
"Score": "0",
"body": "@Ian what Brian said ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T01:16:14.863",
"Id": "46095",
"Score": "0",
"body": "Good point guys. I didn't really think about it. Like I said, first time building this sort of simple password protection so I figured I would take a paranoid approach. So thanks guys, next time I'll adjust accordingly :)"
}
] |
[
{
"body": "<p>A few things, mostly around <code>logged_in</code>:</p>\n\n<pre><code>private function check_login() {\n if (isset($_SESSION['logged_in'])) {\n // If logged in, take this action\n $this->logged_in = true;\n } else {\n // If not logged in, take this action\n $this->logged_in = false;\n }\n}\n</code></pre>\n\n<p>Simply:</p>\n\n<pre><code>$this->logged_in = isset( $_SESSION['logged_in'] );\n</code></pre>\n\n<p>Also, the accessor method <code>is_logged_in</code> is being used quite well, yet there is a lack of a corresponding <code>set_logged_in</code>. Add a set accessor, even if private, and use it exclusively.</p>\n\n<p>Directly assigning the value of an instance variable in more than one place violates the DRY principle. That is, the assignment of <code>$this->logged_in = <<value>></code> should exist only once: within the accessor. For example:</p>\n\n<pre><code>private function set_logged_in( $logged_in ) {\n $this->logged_in = $logged_in;\n}\n</code></pre>\n\n<p>Once the accessor is in place, use it:</p>\n\n<pre><code>private function check_login() {\n $this->set_logged_in( isset($_SESSION['logged_in']) );\n}\n</code></pre>\n\n<p>After the logged in status is using accessors exclusively, you can remove the <code>logged_in</code> variable completely and rely only on the <code>$_SESSION['logged_in']</code> value. Think about what this implies for the <code>check_login()</code> method.</p>\n\n<p>Next:</p>\n\n<pre><code>if ($pass !== 'TheChosenPassword') return false;\n\nreturn true;\n</code></pre>\n\n<p>Simply:</p>\n\n<pre><code>return $pass === 'TheChosenPassword';\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T17:37:19.700",
"Id": "29139",
"ParentId": "29081",
"Score": "1"
}
},
{
"body": "<p>I don't see anything in there which forces the use of TLS (HTTPS). It could be that you're certain that the page can only be accessed over TLS, but even so it's good practice to double-check.</p>\n\n<p>The reason for using TLS on login pages is that it prevents the password from being sent in plaintext (e.g. readable by anyone on the same wifi network). If TLS just isn't an option, you can at least use HTTP digest authentication. MD5 isn't considered particularly strong any more, but it's better than nothing.</p>\n\n<p>See Apache's <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_auth_digest.html\" rel=\"nofollow\">mod_auth_digest</a>. As a bonus, you can replace your session include file and login page with a trivial password file and a couple of lines of Apache config.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:59:37.000",
"Id": "29180",
"ParentId": "29081",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29139",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T10:43:43.893",
"Id": "29081",
"Score": "1",
"Tags": [
"php",
"session"
],
"Title": "Password-Lock a Single Page with PHP - How did I do?"
}
|
29081
|
<p>I was attempting to build a program using Ruby that asks the user to input at least three numbers, and it returns the mean, median, and mode of those numbers.</p>
<p>A developer friend of mine glanced over it and said that the program was wrong, but didn't state specifically what was wrong with it. I have looked over it and tested it repeatedly and can't figure out what's wrong with it.</p>
<pre><code>puts "Please input three or more numbers with spaces inbetween them:"
numbers = gets.chomp
numbers = numbers.split(" ").map(&:to_i)
length = numbers.length
y = 0.000
numbers.each do |x|
y = x + y
end
mean = y / length
print "Mean: #{mean}"
print "\n"
a_order = numbers.sort
length1 = (length - 1) / 2
if length%2 == 1
median = a_order[length1]
else
length2 = length1 + 1
median = (a_order[length1] + a_order[length2]) / 2.000
end
print "Median: #{median}"
print "\n"
frequencies = Hash.new(0)
numbers.each do |number|
frequencies[number] = frequencies[number] + 1
end
frequencies = frequencies.sort_by { |a, b| b }
frequencies.reverse!
frequencies = frequencies.to_a
if frequencies[0][1] == frequencies[1][1]
print "Mode: invalid"
else
print "Mode: #{frequencies[0][0]}"
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T11:20:34.907",
"Id": "45854",
"Score": "0",
"body": "Please note that in this case, the mode is a single mode only. If there are multiple numbers that frequent the same number of times, the mode does not exist."
}
] |
[
{
"body": "<p>It looks valid to me. Except you are not enforcing the '3 number minimum'. </p>\n\n<ul>\n<li>You can use x.odd? to check odd or even. </li>\n<li>You can total numbers with [1,2,3].inject(&:+). </li>\n<li>The frequencies.to_a is not needed, as it's already an array after the sort_by. </li>\n<li>You can sort_by -b so you don't have to reverse. </li>\n</ul>\n\n<p>These are all just refactorings. No change in behaviour.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:14:49.787",
"Id": "29111",
"ParentId": "29083",
"Score": "1"
}
},
{
"body": "<p>The program is mostly correct. I don't see any reason why this problem requires at least three numbers, and in any case you don't bother enforcing it.</p>\n\n<p>It's a wall of text, though, and rather hard to read as a result. You should definitely organize the code into three functions.</p>\n\n<p>Try to avoid defining a lot of intermediate variables, which introduce clutter. For example,</p>\n\n<blockquote>\n<pre><code>length = numbers.length\ny = 0.000\nnumbers.each do |x|\n y = x + y\nend\nmean = y / length\n</code></pre>\n</blockquote>\n\n<p>… should be a single expression in a function:</p>\n\n<pre><code>def mean(numbers)\n numbers.inject(:+).to_f / numbers.length\nend\n</code></pre>\n\n<hr>\n\n<p>Similarly,</p>\n\n<blockquote>\n<pre><code>a_order = numbers.sort\nlength1 = (length - 1) / 2\nif length%2 == 1\n median = a_order[length1]\nelse\n length2 = length1 + 1\n median = (a_order[length1] + a_order[length2]) / 2.000\nend\n</code></pre>\n</blockquote>\n\n<p>… should be packed as:</p>\n\n<pre><code>def median(numbers)\n sorted = numbers.sort\n if numbers.length % 2\n sorted[numbers.length / 2]\n else\n 0.5 * (sorted[numbers.length / 2 - 1] + sorted[numbers.length / 2])\n end\nend\n</code></pre>\n\n<hr>\n\n<p>In the mode calculation, the counting operation…</p>\n\n<blockquote>\n<pre><code>frequencies = Hash.new(0)\nnumbers.each do |number|\n frequencies[number] = frequencies[number] + 1\nend\nfrequencies = frequencies.sort_by { |a, b| b }\nfrequencies.reverse!\nfrequencies = frequencies.to_a\n</code></pre>\n</blockquote>\n\n<p>… could be done fluently as a single expression.</p>\n\n<p>You have a bug here: if all of the numbers are the same, then <code>frequencies[1][1]</code> will crash.</p>\n\n<blockquote>\n<pre><code>if frequencies[0][1] == frequencies[1][1]\n print \"Mode: invalid\"\nelse\n print \"Mode: #{frequencies[0][0]}\"\nend\n</code></pre>\n</blockquote>\n\n<pre><code>def mode(numbers)\n frequencies = numbers.inject(Hash.new(0)) { |h, n| h[n] += 1; h }\n .sort_by { |n, count| -count }\n .to_a\n if frequencies.length == 1 || (frequencies[0][1] != frequencies[1][1])\n frequencies[0][0]\n else\n nil\n end\nend\n</code></pre>\n\n<hr>\n\n<p>Once those functions have been defined, the \"main\" program can be very tidy:</p>\n\n<pre><code>puts \"Please input some numbers with spaces in between them:\"\nnumbers = gets.split.map(&:to_i)\nputs \"Mean: #{mean(numbers)}\"\nputs \"Median: #{median(numbers)}\"\nputs \"Mode: #{mode(numbers) || \"invalid\"}\"\n</code></pre>\n\n<p>Note that there is no need to <code>chomp</code> if you're just going to <code>split</code> on whitespace anyway.</p>\n\n<p>Printing a string with a newline at the end is better done using <code>puts</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-18T00:08:12.127",
"Id": "141672",
"ParentId": "29083",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29111",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T11:19:14.993",
"Id": "29083",
"Score": "0",
"Tags": [
"ruby",
"statistics"
],
"Title": "Program to find the mean, median, and mode of numbers"
}
|
29083
|
<p>I've written this code to get input from a file and count the repetition of number of that file and give output to another file. How can I make this code better?</p>
<pre><code>#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
ofstream outputFile("outPutData.txt");
ifstream theFile ("inputData.txt");
int MaxRange= 50;
int myint[100]={0};
int mycompare[90]={0};
int mycount[90] = {0};
int i = 0, j = 0, k = 0, sum = 0;
for(j=0;j <= MaxRange;j++){
mycompare[j] = j;
}
do
{
theFile>>myint[i];
for(j=0;j<=MaxRange;j++)
for(k=0;k<=MaxRange;k++)
{
j = k;
if(myint[i] == mycompare[j])
mycount[k] = mycount[k]+1;
}
i++;
}
while((myint[i-1] >=0) && (myint[i-1] <= MaxRange));
cout<< "The Number\t\t Frequency"<<endl;
cout<<"------\t\t------"<<endl;
for(k=0; k <=MaxRange ;k++)
{
if(mycount[k] != 0)
{
outputFile<<k<<" "<<mycount[k]<<endl;
cout<< k<<"\t\t"<<mycount[k]<<endl;
sum = sum + mycount[k];
}
}
cout<<"Total input from file = "<<sum<<endl;
return 0;
}
</code></pre>
<p>If I have the series of number in my input file like this:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>9
9
9
6
6
5
3
7
9
1
2
</code></pre>
</blockquote>
<p>It gives the output:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>The Number Frequency
--------- --------
1 1
2 1
3 1
5 1
6 2
7 1
9 4
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T15:27:17.767",
"Id": "45858",
"Score": "1",
"body": "The first thing I would suggest to do is to improve the formatting of the code. Unneeded spaces like after the `#include`s you need 1 space so why use 3? It isn't that big a code. No need for the spaces between variable declaration either. \n\nYou aren't consistent in your style. A `for` loop contained another `for` loop but you didn't use braces but in case of `if` you used braces. Also MaxRange doesn't change so why not make that a macro?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T15:48:34.417",
"Id": "45860",
"Score": "0",
"body": "@AseemBansal : I have edited my code & reduced the spaces. If I have the maximum value greater than 50 than it won't run because of the 'while condition' below. That's why I declared it at the beginning in case I need to change the value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T17:20:33.573",
"Id": "45870",
"Score": "0",
"body": "@aries0152: During runtime, you mean? Still doesn't seem right. If you mean _before_ runtime, then it can still be a `const`. Plus, you wouldn't want to accidentally alter that value somewhere else."
}
] |
[
{
"body": "<p>By consistent style I meant something like this. If you use braces when a statement like <code>if</code>, <code>for</code> etc. contains single statement then use braces for <code>if</code>, <code>for</code> etc. containing single statements everywhere. </p>\n\n<pre><code>#include <iostream>\n#include <cmath>\n#include <fstream>\n\nusing namespace std;\n\nint main()\n{\n ofstream outputFile(\"outPutData.txt\");\n ifstream theFile (\"inputData.txt\");\n\n int MaxRange = 50;\n int myint[100] = {0};\n int mycompare[90] = {0};\n int mycount[90] = {0};\n int i = 0, j = 0, k = 0, sum = 0;\n\n for (j = 0; j <= MaxRange; j++){\n mycompare[j] = j;\n }\n\n do\n {\n theFile>>myint[i];\n\n for(j = 0; j <= MaxRange; j++){\n for(k = 0; k <= MaxRange; k++)\n {\n j = k;\n if(myint[i] == mycompare[j]){\n mycount[k]++;\n }\n }\n }\n i++;\n }while((myint[i-1] >=0) && (myint[i-1] <= MaxRange));\n\n cout<< \"The Number\\t\\t Frequency\"<<endl;\n cout<<\"------\\t\\t------\"<<endl;\n\n\n for(k=0; k <=MaxRange ;k++)\n {\n if(mycount[k] != 0)\n {\n outputFile<<k<<\" \"<<mycount[k]<<endl;\n cout<< k<<\"\\t\\t\"<<mycount[k]<<endl;\n\n sum += mycount[k];\n }\n }\n\n cout<<\"Total input from file = \"<<sum<<endl;\n\n return 0;\n}\n</code></pre>\n\n<p>I changed some statement like <code>sum = sum + mycount[k];</code> to <code>sum += mycount[k]</code> for readability. </p>\n\n<p>I just commented on basic things like style. I'll leave the review to someone who knows C++.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T16:01:14.320",
"Id": "29086",
"ParentId": "29085",
"Score": "0"
}
},
{
"body": "<p>Please do not do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>I know every stupid shitty book about C++ does this. But don't. It works fine if your code is 10 lines long but anything larger it becomes a problem. So it is a really bad habit to start and breaking habits is hard so don't start it. Do yourself a favour and get into the habit of <strong>not</strong> using it. See <a href=\"https://stackoverflow.com/q/1452721/14065\">Why is “using namespace std;” considered bad practice?</a> for details.</p>\n\n<p>This looks like it should be a constant:</p>\n\n<pre><code>int MaxRange= 50;\n</code></pre>\n\n<p>You should make it const. Then you can also use it as the size of the arrays below.</p>\n\n<p>Declare one variable per line:</p>\n\n<pre><code>int i = 0, j = 0, k = 0, sum = 0;\n</code></pre>\n\n<p>The is one corner case where it does not do what you expect. But that's not the real reason for not doing this. Readability. And declare the variable as close to the point of use as possible. No point in declaring a variable that is not used until the bottom line of a program. Also loop variables should be declared as part of the loop so there affect does not bleed beyond the loop.</p>\n\n<pre><code>for(int loop = 0; loop < 5; ++loop)\n{\n}\n// loop not valid here.\n</code></pre>\n\n<p>Also use better names. If you have a loop that covers multiple lines. Try and find all uses of the variable <code>i</code>. Your editor is going to hit a bunch of words in comments and other things. Which is a real pain when you are trying to fix code. </p>\n\n<p>Why do you only initialize half of the <code>mycompare</code>. It may be valid but a comment on why would definately be in order.</p>\n\n<pre><code>int MaxRange= 50;\nint mycompare[90]={0};\nfor(j=0;j <= MaxRange;j++){\n mycompare[j] = j;\n}\n</code></pre>\n\n<p>After reading the code it seems that <code>mycompare</code> is not really needed.<br>\nEven in your loop to print out the values you don't use it.</p>\n\n<p>This is an anti pattern for reading from a stream.\nWhat happens if the read (operator>>) fails?</p>\n\n<pre><code>do\n{\n theFile>>myint[i];\n // STUFF\n}\nwhile((myint[i-1] >=0) && (myint[i-1] <= MaxRange));\n</code></pre>\n\n<p>The correct patter for reading from a file is:<br>\nNote: You will find that nearly all programming languages work this way. It is a <strong>VERY</strong> common pattern. Put the read as part of the loop conditional to validate the read worked.</p>\n\n<pre><code>while(theFile>>myint[i])\n{\n // Read worked so do work.\n}\n</code></pre>\n\n<p>You can combine your other conditions:</p>\n\n<pre><code>while((theFile>>myint[i]) && (myint[i] >=0) && (myint[i] <= MaxRange))\n{\n // Read worked and value in the correct range.\n}\n</code></pre>\n\n<p>Try to always use {} around block statements. It will save your butt one day. </p>\n\n<pre><code> for(j=0;j<=MaxRange;j++)\n for(k=0;k<=MaxRange;k++)\n</code></pre>\n\n<p>Prefer</p>\n\n<pre><code> for(j=0;j<=MaxRange;j++)\n {\n for(k=0;k<=MaxRange;k++)\n {\n }\n }\n</code></pre>\n\n<p>Not sure what the outer loop is doing here.</p>\n\n<pre><code> for(j=0;j<=MaxRange;j++) // This line seems redundant.\n for(k=0;k<=MaxRange;k++)\n {\n j = k; // because of this line.\n if(myint[i] == mycompare[j])\n mycount[k] = mycount[k]+1;\n }\n</code></pre>\n\n<p>You may as well remove the outer loop.</p>\n\n<p>Prefer not to use <code>std::endl</code> to mark end of line. Perfer <code>'\\n'</code>. The difference is that <code>std::endl</code> puts the <code>'\\n'</code> character on the stream then flushes the stream. If you don't need the flush do not use it. It makes the stream much more efficient not to use it.</p>\n\n<pre><code>cout<< \"The Number\\t\\t Frequency\"<<endl;\ncout<<\"------\\t\\t------\"<<endl;\n</code></pre>\n\n<p>In C++ the return in main() is optional.<br>\nIf you only return 0 then I would encourage you not put the return in the code. It is an indication that the program can not logically fail. </p>\n\n<pre><code>return 0;\n</code></pre>\n\n<h1>Conclusion:</h1>\n\n<p>You need to learn how to use the built in types. This problem becomes trivial to do by using the std::map.</p>\n\n<pre><code>int main()\n{\n std::map<int,int> data;\n int tmp;\n\n // Read the data\n ifstream theFile (\"inputData.txt\");\n while(theFile >> tmp)\n {\n ++data[tmp];\n }\n\n // Write the data \n for(auto loop = data.begin(); loop != data.end();++loop)\n {\n std::cout << loop->first << \"\\t\\t\" << loop->second << \"\\n\";\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T17:02:47.520",
"Id": "45865",
"Score": "0",
"body": "Thanks for the explanation. Esp. for the conclusion. This code is nice and simple. Is there anyway that it count the total number of input from the file?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T17:08:04.090",
"Id": "45866",
"Score": "0",
"body": "Shouldn't the loop in the conclusion use `.cbegin()` and `.cend()` since you're just printing? Solid answer otherwise. Will vote as soon as I get them all back."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T17:10:10.330",
"Id": "45867",
"Score": "0",
"body": "Bah, I think you posted this answer right after I started mine, which is completely redundant by now. +1 anyway, good answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T17:10:25.550",
"Id": "45868",
"Score": "0",
"body": "@Jamal: Yes. That would be better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T17:13:54.237",
"Id": "45869",
"Score": "0",
"body": "@Lstor: You still made some needed points. :-) I won't even bother to answer now (it'll be all the same stuff), but that's okay."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T16:38:15.723",
"Id": "29087",
"ParentId": "29085",
"Score": "4"
}
},
{
"body": "<h3>Short version:</h3>\n\n<ul>\n<li>Sort your <code>#include</code>s alphabetically.</li>\n<li>Don't use <code>using namespace std</code>.</li>\n<li>Use meaningful variable names. Never prefix a variable with <code>my</code> -- it is never meaningful.</li>\n<li>Use logical code grouping. Having empty lines between variable declarations doesn't make sense.</li>\n<li>Declare variables as late as possible.</li>\n<li>Why is the output file stream called <code>outputFile</code> (which is an okay name), but the input file stream is called <code>theFile</code> (which is not an okay name)? I suggest using simply <code>output</code> and <code>input</code>.</li>\n<li>Some variables start with a capital letter, others do not. Be consistent. It's common to use lower-case for variable names.</li>\n<li>You should almost never use arrays. Normally you want to use <code>std::vector</code> instead.</li>\n<li>When you want to increase a variable by the value of another, prefer <code>+=</code>. For example, <code>sum += mycount[k]</code> is more readable than <code>sum = sum + mycount[k]</code>.</li>\n<li>Don't use <code>std::endl</code> unless you really need to. <code>std::endl</code> flushes the output as well as add a newline. If you just want a newline, do <code><< '\\n'</code> instead.</li>\n<li>You can use <code>std::map</code> to keep track of the numbers.</li>\n<li>I don't really understand what you use <code>mycompare</code> for.</li>\n<li>Use whitespace between operators and other places where it makes sense, to increase readability.</li>\n<li>Either keep block statements on a single line, or use braces.</li>\n</ul>\n\n<hr>\n\n<h3>Explanations:</h3>\n\n<ul>\n<li><strong>Declare variables as late as possible.</strong></li>\n</ul>\n\n<p>Declaring a variable as late as possible keeps the declaration closer to the relevant context. It might also be more efficient in cases where you never need to instantiate the variable at all. <code>for</code> loops should look like this, unless you really need to reuse the index variable later:</p>\n\n<pre><code>for (int i = 0; i < whatever; ++i) {\n // ...\n}\n</code></pre>\n\n<p>Reuse the name <code>i</code> in the next <code>for</code>-loop. You can put the opening brace on a line by itself if you want to.</p>\n\n<ul>\n<li><strong>Prefer</strong> <code>std::vector</code> <strong>over arrays.</strong></li>\n</ul>\n\n<p><code>std::vector</code> can grow, can be range-checked and has a lot of other advantages. Normally when you think \"array\", use <code>std::vector</code>. To access the variable at index <code>i</code>, use <code>numbers.at(i)</code> (where <code>numbers</code> is a <code>vector</code>). Using <code>at(i)</code> instead of <code>[i]</code> will cause an error (exception) if you go out of range -- and you want that.</p>\n\n<ul>\n<li><strong>Using</strong> <code>std::map</code> <strong>instead.</strong></li>\n</ul>\n\n<p>A <code>std::map</code> is an associative array (also known as a dictionary). You associate a <em>key</em> with a certain <em>value</em>. You can later get the <em>value</em> stored at a certain <em>key</em>. Like this:</p>\n\n<pre><code>std::map<int, int> numberCounts;\nwhile (condition) {\n int number;\n input >> number;\n\n numberCounts[number] += 1; // Increase the count of `number` by one.\n}\n</code></pre>\n\n<p>(You can also write <code>++numberCounts[number]</code> if you prefer. Also, you should put the input reading as <em>condition</em>, but that's not the point here.)</p>\n\n<p>Note that key/value pairs will be created when and only when you need it. This means that the snippet above will work for (almost) any number. But, even if <code>number</code> is 1,000,000 (one million), it will <em>not</em> create room for one million key/value pairs. This is in contrast with your solution. Your solution creates room for all numbers up to 90, regardless of whether or not they are read in the file. But if your file reads a number that is too high, your program will not count it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T17:06:39.937",
"Id": "29088",
"ParentId": "29085",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29087",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T15:12:26.327",
"Id": "29085",
"Score": "1",
"Tags": [
"c++",
"file"
],
"Title": "Counting repetitions in a file"
}
|
29085
|
<p>I'm just looking for some feedback on my implementation of a maxheap mostly relating to style. I'm trying to create good habits as I learn to program.</p>
<p>Note: for the sort method I was given the precondition that the passed in array never has empty/null elements and that it must be sorted in place.</p>
<pre><code>public class Heap12<E extends Comparable<? super E>> implements PQueue<E>{
private E[] heap; // Backend data storage array
private int size; // # elements in the heap
</code></pre>
<p>Private constructor that is used by the <code>sort()</code> method to heapify an array of objects type <code>E</code>. <code>Size</code> is initialized to 0 so that the objects in the array can be sorted in place by calling the <code>add(E e)</code> method.</p>
<p><code>@param E[] e</code> - the array to be heapified</p>
<pre><code>@SuppressWarnings("unchecked")
private Heap12(E[] e){
this.heap = e; // Set heap array to passed in array
this.size = 0; // Size HAS to be 0 initially
}
</code></pre>
<p>Public default no-arg constructor that initializes size to 0 and the backing array to a default capacity.</p>
<pre><code>@SuppressWarnings("unchecked")
public Heap12(){
this.size = 0; // Default values
this.heap = (E[]) new Comparable[5];
}
</code></pre>
<p>Public copy constructor that takes in another <code>Heap12<E></code> object. It creates
a new <code>Heap12<E></code> object that is a deep copy of the passed in object. The underlying objects of the backing array are shared, but each <code>Heap12</code> has its own instance variables.</p>
<p><code>@param Heap12<E> o</code> - the <code>Heap12<E></code> object to be copied</p>
<pre><code>@SuppressWarnings("unchecked")
public Heap12(Heap12<E> o){
this.heap = (E[]) new Comparable[o.heap.length];
this.size = o.size; // Copy size
for(int i = 0; i < o.size(); i++){ // Copy each element
this.heap[i] = o.heap[i]; // reference
}
}
</code></pre>
<p>Adds an element to this <code>Heap12</code> object. Does not accept null elements, will throw a <code>NullPointerException</code>. If the <code>Heap12</code> is at maximum capacity, the capacity will be doubled before adding the element.</p>
<p><code>@param E e</code> - the element to be added to the <code>Heap12</code></p>
<pre><code>public void add(E e){
if(e == null) // Check for null element add
throw new NullPointerException();
if(this.size() == heap.length)
expandHeap(); // Double heap capacity if full
heap[this.size()] = e; // Add the element at the rightmost leaflet
bubbleUp(this.size()); // Move it to its proper place
size++;
}
</code></pre>
<p>Returns the largest element contained in the <code>Heap12</code> object (the root). Does not modify the heap.</p>
<p><code>@return E</code> - the largest object (the object at the root)</p>
<pre><code>public E peek(){
return heap[0];
}
</code></pre>
<p>Removes the largest element in this heap (the root). If the heap is empty, null is returned.</p>
<p><code>@return E</code> - the largest element (the root)</p>
<pre><code>public E remove(){
E toReturn;
if(this.isEmpty()) // Empty heap case
return null;
toReturn = heap[0]; // Return greatest element(root)
heap[0] = heap[this.size() - 1]; // Put bottom rightmost at root
heap[this.size() - 1] = null; // Get rid of the copy
size--;
trickleDown(0); // Move the new root to its proper
// place
return toReturn;
}
</code></pre>
<p>Determines if this <code>Heap12</code> is equal to the passed in object. Returns false if the passed in object is not a <code>Heap12</code>, the two <code>Heap12</code>'s have different sizes (# of elements), or if the two <code>Heap12</code> objects do not have the same underlying data, in the same order.</p>
<p><code>@param Object</code> o - the object to compare this <code>Heap12</code> with <code>@return</code> boolean whether the two objects are equal</p>
<pre><code>public boolean equals(Object o){
if( !(o instanceof Heap12) ) // Type check
return false;
Heap12 oQ = (Heap12) o;
if(this.size() != oQ.size()) // Diff # elements means diff heaps
return false;
for(int i = 0; i < this.size(); i++){ // Loop through all the elements
if( !(this.heap[i].equals(oQ.heap[i])) ) // if one is different
return false; // heaps are not equal
}
return true; // If we get here, heaps are equal
}
</code></pre>
<p>Returns a hash code for this <code>Heap12</code> object. The code is the same for objects that contain the same elements in the same order.</p>
<p><code>@return int</code> - the hash code of this <code>Heap12<E></code></p>
<pre><code>public int hashCode(){
int toReturn = 1;
/* Add each elements hashCode to the total and multiples by 31 each time */
for(int i = 0; i < this.size(); i++){
toReturn = 31 * toReturn + heap[i].hashCode();
}
return toReturn;
}
</code></pre>
<p>Checks to see if this <code>Heap12<E></code> is empty (has no elements)</p>
<p><code>@return boolean</code> - true if the <code>Heap12</code> is empty, false if not</p>
<pre><code>public boolean isEmpty(){
return size == 0;
}
</code></pre>
<p>Returns the number of elements in this <code>Heap12<E></code> object as an int. <code>@return</code> - the number of elements in this <code>Heap12</code> object.</p>
<pre><code>public int size(){
return this.size;
}
</code></pre>
<p>Private helper method for <code>remove()</code>. This method reorders the underlying heap array after an element is removed so that the heap retains the max heap property and completeness.</p>
<p><code>@param int parent</code> - the parent node index</p>
<pre><code>private void trickleDown(int parent){
int left = (2 * parent) + 1; // Compute Left/Right child indices
int right = (2 * parent) + 2;
if(left > size - 1 ) // Base case: end of the heap
return;
/* If right child is null or left child >= right child, compare left child
to parent */
if(heap[right] == null || heap[left].compareTo(heap[right]) >= 0){
if(heap[left].compareTo(heap[parent]) > 0){
swap(parent, left); // If the left child is > parent swap
trickleDown(left); // Left index is now the parent index
}
} // If the right child > parent
else if(heap[right].compareTo(heap[parent]) > 0){
swap(parent, right); // Swap the parent and right child
trickleDown(right); // Right index is now the parent index
}
}
</code></pre>
<p>Private helper method for <code>add(E e)</code>. This method reorders the underlying heap array after an element is added so that the heap retains the max heap property and completeness.</p>
<p><code>@param int child</code> - the child node index</p>
<pre><code>private void bubbleUp(int child){
int parent = (child - 1) / 2; // Compute the parent index
if(child == 0) // If we're at the root, stop bubbling
return; // Added simply for clarity (not needed)
if( heap[child].compareTo(heap[parent]) > 0 ){ // If child > parent
swap(parent, child); // Swap them
bubbleUp(parent); // parent is now the old child
}
}
</code></pre>
<p>Private helper method that swaps a parent node element and a child node element using a temp variable.</p>
<p><code>@param int parent</code> - the index of the parent object</p>
<p><code>@param int child</code> - the index of the child object</p>
<pre><code>private void swap(int parent, int child){
E temp = heap[parent]; // Store the parent
heap[parent] = heap[child]; // Replace parent element with child
heap[child] = temp; // Replace child with the parent
}
</code></pre>
<p>Private helper method that doubles the capacity of the underlying array of this <code>Heap12</code> object. Used when trying to add an element to a heap where <code>size == capacity</code>.</p>
<pre><code>@SuppressWarnings("unchecked")
private void expandHeap(){ // Create new array with double capacity
E[] temp = (E[]) new Comparable[heap.length * 2];
for(int i = 0; i < heap.length; i++){
temp[i] = this.heap[i]; // Copy all the references
}
this.heap = temp; // Update instance backing array
}
</code></pre>
<p>Static sort method that sorts the passed in array in place using a heap. The sorted array is in ascending order. The passed in array must be full and not contain any null elements.</p>
<p><code>@param T[] a</code> - the array of objects to be sorted in ascending order</p>
<pre><code>@SuppressWarnings("unchecked")
public static <T extends Comparable<? super T>> void sort(T[] a){
Heap12<T> sorted = new Heap12<T>(a); // Use unsorted array as heap
// backing array in new Heap12
/* Add each array element to the heap, it will sort itself in place */
for(int i = 0; i < sorted.heap.length; i++)
sorted.add(sorted.heap[sorted.size()]); // Size is initially 0
/* Remove each heap element, put it at the end of the underlying array */
while(sorted.size() > 0)
sorted.heap[sorted.size() - 1] = sorted.remove();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-29T13:27:24.723",
"Id": "48390",
"Score": "0",
"body": "@Quonux Nice formatting! Turns out really great! I like the \"javadoc\" format!"
}
] |
[
{
"body": "<pre><code>public class Heap12<E extends Comparable<? super E>> implements PQueue<E>{\n</code></pre>\n\n<p>Don't name your Generic Parameters with a single letter, give them meaningful names wit the end <code>Type</code> so you can differenciate between variables and the Generic Parameters when you read the code.</p>\n\n<p>Do not name your class Heap12, it it a heap for only 12 elements or only for 12 monkeys... nobody knows.</p>\n\n<pre><code>private Heap12(E[] e){\n</code></pre>\n\n<p>Don't name your variables with single letters, give them meaningful names.</p>\n\n<pre><code>if(e == null) // Check for null element add\nthrow new NullPointerException();\n</code></pre>\n\n<p>The comment is not needed, describe why you do something and not what.</p>\n\n<p>Here maybe a assertion is more useful (don't forget to enale assertions with the <code>-ea</code> Parameter, its realy a shame that its not on by default), oh tese poor rockets which exploded because of this... anyways back to topic</p>\n\n<pre><code>if(this.isEmpty()) // Empty heap case\nreturn null;\n</code></pre>\n\n<p>the same as above, don't comment what your code does.</p>\n\n<pre><code>public boolean isEmpty(){\n return size == 0;\n}\n</code></pre>\n\n<p>this is good, but we need also a method for the opposite</p>\n\n<pre><code>public boolean isNotEmpty(){\n return !this.isEmpty();\n}\n</code></pre>\n\n<p>this makes reading of the code which uses this class easier.</p>\n\n<pre><code>swap(parent, child); // Swap them\n</code></pre>\n\n<p>again, the same, don't comment what the code does</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T04:58:27.367",
"Id": "46102",
"Score": "0",
"body": "Thanks. The name of the class was not by choice but I appreciate the feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T19:30:14.977",
"Id": "29148",
"ParentId": "29089",
"Score": "2"
}
},
{
"body": "<p>One thing that I think need to be fixed is:</p>\n\n<pre><code>private Heap12(E[] e){\n this.heap = e; // Set heap array to passed in array\n this.size = 0; // Size HAS to be 0 initially\n}\n</code></pre>\n\n<p>You need to copy it, otherwise the caller has reference to your array to corrupt it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-03T22:47:45.150",
"Id": "376933",
"Score": "0",
"body": "my bad, i did not realize it was private.. too much intervention of comments in the middle"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-03T22:45:19.607",
"Id": "195771",
"ParentId": "29089",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-07-28T17:43:58.313",
"Id": "29089",
"Score": "5",
"Tags": [
"java",
"heap"
],
"Title": "Max heap in Java"
}
|
29089
|
<p>I was making an algorithm for a task I found in a book. It says that there is sorted array, that was swapped so it looks like "4567123", and was proposed to use binary search modification.</p>
<p>Below is my solution in java.</p>
<p>The thing is, I'm a bit cringed that I can't process cases for array size of 2, 3 generically (for case of size 1 it's obvious that it'll require a specific case). Not that I need a solution that'll do that generically for 2, 3 array size cases. But I more like to know, is it a problem. Also I addressed a problem when array wasn't swaped at all. And I'm not sure that I should've done this, if preconditions are clearly specified. Btw binary search doesn't check that it's input is sorted. </p>
<p>So, more what I need is not code review itself, but more of advise, is my hardcoded cases and support for nonswaped array is good or bad. I myself believe that cases are fine, as algorithm compares 2 values, and thus requires at least 2 values to be compared, also it searches for the "peak and drop". But I'll probably try to modify it so it won't cover non-swaped array case and generically work for 2, 3 size array.</p>
<pre><code>//file SwapedArraySearch.java\
public class SwapedArraySearch {
public static int search(int[] arr) {
switch (arr.length){
case 1:
return arr[0];
case 2:
return arr[0] > arr[1]?arr[1]:arr[0];
case 3:
return arr[0] > arr [1] ? (arr[1] > arr[2]?arr[2]: arr[1]):
(arr[0] > arr[2]?arr[2]: arr[0]);
}
int x = arr[0];
int n = arr.length/2;
int prevn = arr[n] > x ? arr.length -1 : 1;
int t;
while(prevn != n) {
if (x < arr[n]) {
if (arr[n] > arr [n + 1] )
return arr[n+1];
t = n;
n = n + (prevn - n)/2;
prevn = t;
} else {
if (arr[n - 1] > arr[n])
return arr[n];
t = n;
n = prevn + (n - prevn)/2;
prevn = t;
}
}
return arr[0] > arr[1] ? arr[arr.length - 1] : arr[0];
}
public static void main(String... args) {
int[] arr = new int[args.length];
for (int i = 0; i < args.length; i++)
arr[i] = Integer.valueOf(args[i]);
System.out.println(search(arr));
}
}
</code></pre>
<p>EDIT: the task is to find the lowest element</p>
<p>EDIT2: after much more thinking I boiled down my search function to this:</p>
<pre><code>x = arr[arr.length - 1]
a = 0
b = arr.length
while b - a > 2
if x > arr[(a+b)/2]
b = (a+b)/2
else
a = (a+b)/2
return arr[(a+b)/2]
</code></pre>
<p>the key point to simplification was to understand that middle element can always be calculated as <code>(a+b)/2</code>. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T17:32:56.020",
"Id": "46815",
"Score": "0",
"body": "What is the purpose of your algorithm? Is it suppose to locate an element in the semi-sorted array? Is it supposed to sort the semi-sorted array? Please improve your problem description so members of the community can intelligently provide suggestions/critiques for your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T10:32:42.510",
"Id": "46873",
"Score": "0",
"body": "The task is to find the lowest element, but I think your comment for finding the highest element is still relevant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-03T15:40:58.907",
"Id": "68721",
"Score": "0",
"body": "FYI, `mid = (a+b)/2` risks integer overflow for large arrays."
}
] |
[
{
"body": "<h2>General Advise</h2>\n\n<ul>\n<li><p>Your methods are difficult to read because you chose to use predominantly single character variable names. Multi-character descriptive variable names are much easier to associate with a value, making the code magnitudes easier to read & maintain. Also, when implementing a binary search it is typical to use <code>hi</code>, <code>lo</code> & <code>mid</code> as variable names.</p></li>\n<li><p>Whenever you nest a ternary statements, this should be an immediate red flag, that you are not writing clear & maintainable code. As soon as you write a nested ternary statement I would advise you to pause, and consider what functionality you are trying to achieve and consider different ways to express that functionality. I'm not going to say that nested ternary statements are always a sign that your doing something wrong, but <em>nested ternary statements is <strong>always</strong> a sign you should stop and think about what your doing.</em></p></li>\n</ul>\n\n<h2>Algorithmic Advise</h2>\n\n<p>I am assuming the algorithm is locating the largest element in a semi-sorted array that has two (and only two) distinctly sorted sequences with a pivot index contains largest value in the array.</p>\n\n<ul>\n<li><p>The three conditions in your switch case are, generally doing the same thing. Each case is returning the largest element in a the array, but can't use the loop because the array is too small. We can cover these conditions in the final return.</p></li>\n<li><p>You should also check for general error cases such as <code>null</code> or the empty set (<code>new int[0]</code>) being passed into the function.</p></li>\n<li><p>Since the logic for checking if the current value of the binary search is the pivot index contains a lot of logic to do correctly, I would create a method <code>isPivotIndex()</code>.</p></li>\n</ul>\n\n<p>Putting all that together, your solution could look something like this.</p>\n\n<p><strong>Java Code:</strong> <em>(<strong><a href=\"http://ideone.com/UZLz20\" rel=\"nofollow\">ideone example link</a></strong>)</em></p>\n\n<pre><code>int findLargestValueInSemiSortedArray(int arr[]) {\n if(arr==null || arr.length==0)\n throw new IllegalArgumentException();\n\n int hi = arr.length; /* exclusive upper bound */\n int low = 0; /* inclusive lower bound */\n int mid;\n while(low < hi) {\n mid = low/2 + hi/2;\n if(isPivotIndex(arr,mid))\n return arr[mid];\n if(arr[hi-1] < arr[mid])\n low = mid + 1;\n else\n hi = mid;\n }\n /* Array was actually sorted, either ascending or descending */\n /* Note that return this covers corner cases of arr.length <= 3 */\n return max(arr[0], arr[arr.length-1]); \n}\n\nint max(final int a, final int b) {\n return (a > b) ? a : b;\n}\n\nboolean isPivotIndex(final int[] arr, final int index) {\n int b = arr[index];\n int a = (index > 0) ? arr[index-1] : Integer.MAX_VALUE;\n int c = (index < arr.length-1) ? arr[index+1] : Integer.MAX_VALUE;\n return a <= b && b > c;\n}\n</code></pre>\n\n<p>The above is much more readable, has fewer lines of code, and is easier to check for correctness. </p>\n\n<ol>\n<li><p>It immediately throws an exception on invalid input. </p></li>\n<li><p>It uses <code>isPivotIndex()</code> method to isolate complex logic & maintain a single level of abstraction.</p></li>\n<li><p>It uses a clever final return to handle corner cases.</p></li>\n</ol>\n\n<hr>\n\n<p>Let's consider how the final return covers the corner cases in your original <code>switch</code> statement.</p>\n\n<p><strong>Case 1:</strong> (<code>arr.length == 1</code>)</p>\n\n<ul>\n<li><code>max(arr[0],arr[arr.length-1])</code> will compare the same values and return <code>arr[0]</code>.</li>\n</ul>\n\n<p><strong>Case 2:</strong> (<code>arr.length == 2</code>)</p>\n\n<ul>\n<li><code>max(arr[0],arr[arr.length-1])</code> will evaluate exactly the same as your ternary statement.</li>\n</ul>\n\n<p><strong>Case 3:</strong> (<code>arr.length == 3</code>)</p>\n\n<ul>\n<li><code>max(arr[0],arr[arr.length-1])</code> will return the larger of <code>arr[0]</code> and <code>arr[2]</code>. If <code>arr[1]</code> happened to be the max value it would have been the pivot index in the binary search loop and the method would have already returned.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-10T18:23:05.930",
"Id": "29594",
"ParentId": "29090",
"Score": "6"
}
},
{
"body": "<p>The midpoint caclulation as you have in your second edit suffers from a subtle bug, which only occurs when handling very large arrays.</p>\n\n<pre><code>int mid = (low + high) / 2;\n</code></pre>\n\n<p>There is a possibility for overflow here; a correct version would be:</p>\n\n<pre><code>int mid = low + ((high - low) / 2);\n</code></pre>\n\n<p>See <a href=\"http://googleresearch.blogspot.be/2006/06/extra-extra-read-all-about-it-nearly.html\" rel=\"noreferrer\">http://googleresearch.blogspot.be/2006/06/extra-extra-read-all-about-it-nearly.html</a> and <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045582\" rel=\"noreferrer\">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5045582</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T12:44:56.507",
"Id": "46882",
"Score": "0",
"body": "This is a great addition as your first post. But as you are referring to a whole well written article a simple comment might be a better way to share your knowledge here. +1 anyway for a good first post."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-12T11:40:07.483",
"Id": "29644",
"ParentId": "29090",
"Score": "6"
}
},
{
"body": "<p>You initialize a certain value as <code>x</code> but you never update it - even though this value is <strong>completely arbitrary</strong>. Which means you are not really using it in the solution. This is a <strong>certain indication</strong> that your solution is <strong>wrong</strong>, and only works on the special case that you tested.</p>\n<p>If the "pivot" point (i.e. the point where the the max value is followed by the min value) is in the left half of the array you will get a max value, and if it's in the right half you will get a min value.</p>\n<p>i.e. if I input this array <code>[10,11,12,1,2,3,4,5,6,7,8,9]</code> it will return 12, but if I input this <code>[5,6,7,8,9,10,11,12,1,2,3,4]</code> it will output 1.</p>\n<h1>Problem Context</h1>\n<p>Searching a value in an array can be up to <code>O(n)</code> in time complexity - you have to iterate through the array and check for each element if it's equal the search value. But - if the array is sorted, this is reduced to <code>O(log(n))</code> due to a strategy called <strong>Binary Search</strong>. Binary search allows us at each time cut half of the options to consider. You check the middle element in the array, if the search value is bigger you can discard the lower half, if it's lower you can discard the upper half, and now you do the same for the remaining array - until you either find the value or end up with an empty/1-element array - in that case the element is not in the array.</p>\n<p>Here there is a problem that the array is swapped - the question is can we still reduce the time complexity to <code>O(log(n))</code> ?</p>\n<p>The key insight here is that <strong>even though the array itself is not perfectly sorted, at least half of it IS</strong> - and so we can always tell something about that half, and reduce our scope. This is true for every sub-division we make of the array - at least half of it will be sorted (and in some cases, both halves).</p>\n<p>If we are looking for the min/max value, we basically don't care about the part that is sorted, because the pivot value will be in the other half (though the mid value should be included, as it can be the min/max value) - so we can discard the sorted part.</p>\n<p>If we are looking for a specific value - we can automatically check if our value is in the range of the sorted half, if it is we discard the non-sorted half, and focus on the sorted. If it's not we focus on the non-sorted - and do the same.</p>\n<h1>Find Min value</h1>\n<p>Here is a solution in python - here we check if the right half is sorted. If it is, we reduce our scope to the left half. If not, we reduce our scope to the right half (note that in that case we can safely discard the mid point and move beyond it).</p>\n<pre><code>def findMin(arr):\n start = 0\n end = len(arr) - 1\n while(start < end):\n mid = (start + end) // 2\n rightSorted = arr[mid] < arr[end]\n if rightSorted:\n end = mid\n else:\n start = mid + 1\n return arr[start]\n</code></pre>\n<p>The decision to check the right is not arbitrary - it is necessary in case we search for a min value. If we instead search the left, and find out it is sorted - we could not confidently discard that half, as the array might be perfectly sorted - in that case the 0th element is the minimum. So we choose the right in order to be completely sure we still have the min value in the sub array.</p>\n<h1>Find Max value</h1>\n<p>In python this is actually very easy - you just need to go one element before the minimum - and even if the min is in 0 position, python interprets -1 as the last element of the array. So you could just use the same code as above, but with <code>return arr[start-1]</code>.</p>\n<p>Alternatively, we could reverse the min function above:</p>\n<pre><code>def findMax(arr):\n start = 0\n end = len(arr) - 1\n while(start < end):\n mid = (start + end) // 2\n leftSorted = arr[mid] > arr[start]\n if leftSorted:\n start = mid\n else:\n end = mid - 1\n return arr[start]\n</code></pre>\n<h1>Finding a specific value</h1>\n<p>If we want to check if a specific value exists in the array - the same key insight hold.</p>\n<pre><code>def findVal(arr, val): \n start = 0\n end = len(arr) - 1 \n while(start < end):\n mid = (start + end) // 2\n rightSorted = arr[mid] < arr[end] and arr[start] > arr[mid]\n if rightSorted:\n if val >= arr[mid] and val <= arr[end]:\n start = mid\n else:\n end = mid - 1\n else:\n if val >= arr[start] and val <= arr[mid]:\n end = mid\n else:\n start = mid + 1\n return val == arr[start]\n</code></pre>\n<p>A few differences: (1) we have to check if our value is in the sorted half, and if not discard it. (2) in order to avoid getting stuck with a sorted array of 2 elements - we have to define that the right half is sorted only if also the left half is not sorted (or vice versa). (otherwise we'll be stuck in an endless loop, as mid value won't advance)</p>\n<p>[We could also create a less elegant implementation that simply goes until 2 elements and then just check if one of them is the value; or we could also always check the mid value and if it is the correct value return true, and if not we always discard it - I chose this implementation because I think it's more elegant and it is close to the other 2 min/max functions above]</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-22T14:08:25.387",
"Id": "234487",
"ParentId": "29090",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29594",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T18:24:10.483",
"Id": "29090",
"Score": "5",
"Tags": [
"java",
"algorithm"
],
"Title": "Binary search modification for \"swaped\" array"
}
|
29090
|
<p>I am looking for feedback on a solution to the following problem posed from a book that I'm working through (<em>Java: How To Program 9th Edition</em>):</p>
<blockquote>
<p>Write an application that reads a line of text and prints a table indicating the number of occurrences of each different word in the text. The application should include the words in the table in the same order in which they appear in the text. For example, the lines</p>
<p>To be, or not to be: that is the question:
Whether 'tis nobler in the mind to suffer</p>
<p>contain the word “to” three times, the word “be” two times, the word “or” once, etc.</p>
</blockquote>
<pre><code>import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class TextAnalysisC {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner( System.in );
System.out.println( "Please enter a line of text" );
String userInput = sc.nextLine();
userInput = userInput.toLowerCase();
userInput = userInput.replaceAll( "\\W", " " ); // strip out any non words.
userInput = userInput.replaceAll( " ", " " ); // strip out any double spaces
// created from stripping out non words
// in the first place!
String[] tokens = userInput.split( " " );
System.out.println( userInput );
ArrayList< String > items = new ArrayList< String >();
items.addAll( Arrays.asList( tokens ) );
int count = 0;
for( int i = 0; i < items.size(); i++ )
{
System.out.printf( "%s: ", items.get( i ) );
for( int j = 0; j < items.size(); j++ )
{
if( items.get( i ).equals( items.get( j ) ) )
count++;
if( items.get( i ).equals( items.get( j ) ) && count > 1 )
items.remove( j ); // after having counted at least
} // one, remove duplicates from List
System.out.printf( "%d\n", count );
count = 0;
}
}
}
</code></pre>
<p>Can this be simplified? Is this easy to understand? What should I improve?</p>
<p>I regret to report that I have been remiss on the current scope of my knowledge as I work through my textbook (<em>Java: 9th Edition</em>). Solutions should be within the limits of what I have covered so far, that being:</p>
<ol>
<li>Introduction to Computers and Java </li>
<li>Introduction to Java Applications</li>
<li>Introduction to Classes, Objects, Methods and Strings</li>
<li>Control Statements: Part 1</li>
<li>Control Statements: Part 2</li>
<li>Methods: A Deeper Look</li>
<li>Arrays and ArrayLists</li>
<li>Classes and Objects: A Deeper Look</li>
<li>Object-Oriented Programming: Inheritance</li>
<li>Object-Oriented Programming: Polymorphism</li>
<li>Exception Handling: A Deeper Look</li>
<li>GUI Components: Part 1 (Swing)</li>
<li>Strings, Characters and Regular Expressions</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T18:52:46.143",
"Id": "45871",
"Score": "0",
"body": "your code has a bug. Try to give `a b b b c` as input and see the result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T19:39:28.597",
"Id": "45873",
"Score": "0",
"body": "oh hell yes, well spotted @tintinmj, I think it has something to do with the line `items.remove( j )` reordering the sequence of letters in the ArrayList. I think it could be confusing things, I'll try and fix it in the morning. A better algorithm might be in order."
}
] |
[
{
"body": "<p>Both calls to replaceAll and the call to split could be replaced by 1 call to split. Remember that split accepts a regex and that regex patterns can endlessly combine matches for \"one or more occurrences\" of another pattern with matches for \"one pattern or another\", etc.</p>\n\n<p>In any case, your regex usage would have to be a little more complicated if you wanted to support words like \"don't\".</p>\n\n<p>Your counting algorithm does not scale up well for large inputs -- it's \"O(n-squared)\",\nand it uses a lot of custom code to make an ArrayList do the work of a more functional collection class.\nWhat you want is one scan over your tokens to build up a smarter collection of tokens with their running counts.\nFor that, you want a collection that lets you efficiently find the running count for an \"old\" token without serially scanning for the token among all the tokens so far.\nAfter that, you can make one pass over the collection to print your output.\nThat means that you want the collection to preserve the order in which you added each token. </p>\n\n<p>There's a collection class for that. It's name currently escapes me. It'd probably be instructive for you to research it, anyway, since this is an educational project.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T18:07:38.347",
"Id": "46064",
"Score": "0",
"body": "hey user1542234, the book I'm using doesn't seem to show how to do this with split(), I tried split.(\" \\\\s*\") to no avail. Searching for more info. I've not fully covered Collections yet, still a few chapters away, sorry for the lack of clarity (see edit above)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T20:10:41.293",
"Id": "29095",
"ParentId": "29091",
"Score": "0"
}
},
{
"body": "<p>The easiest way would be to use a <code>LinkedHashMap</code><code><String,</code><a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html\" rel=\"nofollow\"><code>AtomicInteger</code></a><code>></code>, adding the words in order.</p>\n\n<p><code>LinkedHashMap</code> is a <code>Map</code>, so duplicate keys can easily be detected. <code>AtomicInteger</code> will allow incrementing the value without having to replace the value in the <code>Map</code>. Yet AtomicInteger isn't exactly intended to be used as a dumb counter, making your own <code>Counter</code> class is also a good option, as long as it has an <code>increment()</code> and a <code>get()</code> method, it'll make your interaction with the Map a lot smoother.</p>\n\n<p>You can use <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29\" rel=\"nofollow\">String.split()</a> to break up the input String in words.</p>\n\n<p>Quick pseudo code:</p>\n\n<pre><code>split input String into words\nloop the words\n if word not in map\n add word as key, with new counter\n get counter for word and increment\nloop map entries\n print word and number of occurrences\n</code></pre>\n\n<p><em><strong>Edit</em></strong></p>\n\n<p>Given the scope of your knowledge, I'll make a suggestion that only uses what you should know already. The idea is to replace the Map by an ArrayList of words and a matching array of int to hold the counts.</p>\n\n<pre><code>split input String into words\ninitialize an int[] array with the size equal to the number of words // max needed capacity\ninitialize an ArrayList of Strings\nloop the words\n determine index of the word in ArrayList.\n if word not in ArrayList\n add word to ArrayList\n increment int in array at matching index as the word in the ArrayList\nloop ArrayList\n print word and number of occurrences (from same index in array)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T17:57:56.863",
"Id": "46062",
"Score": "0",
"body": "as a beginner I haven't covered these topics yet, (see edit above) my apologies for the lack of clarity. However I shall revisit your contribution when I come to the appropriate chapter and absorb your solution at that time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:05:52.727",
"Id": "46074",
"Score": "0",
"body": "That's ok, but the scope of this site is however larger."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T17:28:36.820",
"Id": "29138",
"ParentId": "29091",
"Score": "2"
}
},
{
"body": "<p>There are a couple of ways of doing this problem: </p>\n\n<ol>\n<li><p>Using a <code>HashMap<String, Integer></code>, read each line and split the words and test to see if the <code>HashMap</code> contains a particular word. If not, then insert it, else, increment the value. This will require us to compute the HashCode which can be done in \\$O(N)\\$ and the search for a HashMap in \\$O(1)\\$.</p></li>\n<li><p>Use a dictionary/symbol table BST with a key and value inside all nodes. Search and insert is done in a \\$log(N)\\$ time. For a given word we can search the BST and insert if the key is not found. If found, update the counter in the node. The space taken will be proportional to number of words in the book.</p></li>\n<li><p>Perhaps the most efficient and scalable answer is to simply use a database table with two columns (name, value). Consider millions or billion of words. There is no easy or elegant way to keeping that much data in memory inside a <code>HashMap</code> or a BST. For every word, do a see if it exists in the table. If not, insert it, else, update the counter.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-30T03:00:51.133",
"Id": "180620",
"Score": "0",
"body": "thanks @Jamal i was just about to correct the HashSet to HashMap"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-07-30T02:38:56.163",
"Id": "98543",
"ParentId": "29091",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29138",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T18:25:55.477",
"Id": "29091",
"Score": "4",
"Tags": [
"java",
"beginner"
],
"Title": "Number of occurrences of each different word in a line of text"
}
|
29091
|
<p>I am working on creating a Makefile for my ProjectEuler solutions. I need to compile each solution into a separate binary for personal timing purposes. Is it possible to pass the name of the rule to the -o option to remove some repeated code?</p>
<pre><code>CXX = g++
CXXFLAGS = -std=c++0x
INC = -Iinclude/ -I../tools/
binaries=01sum35\
02evenfibs\
03largestprimefactor\
04largestpallyproduct\
05smallestmultiple\
06sumsquaredifference\
07tenthousandfirstprime\
08largestproductinseries\
09specialpythagtriplet
all: $(binaries)
01sum35:
$(CXX) $(CXXFLAGS) 01sum35.cc $(INC) -o 01sum35
02evenfibs:
$(CXX) $(CXXFLAGS) 02evenfibs.cc $(INC) -o 02evenfibs
03largestprimefactor:
$(CXX) $(CXXFLAGS) 03largestprimefactor.cc $(INC) -o 03largestprimefactor
04largestpallyproduct:
$(CXX) $(CXXFLAGS) 04largestpallyproduct.cc ../tools/tools.cc $(INC) -o 04largestpallyproduct
05smallestmultiple:
$(CXX) $(CXXFLAGS) 05smallestmultiple.cc $(INC) -o 05smallestmultiple
06sumsquaredifference:
$(CXX) $(CXXFLAGS) 06sumsquaredifference.cc $(INC) -o 06sumsquaredifference
07tenthousandfirstprime:
$(CXX) $(CXXFLAGS) 07tenthousandfirstprime.cc ../tools/tools.cc $(INC) -o 07tenthousandfirstprime
08largestproductinseries:
$(CXX) $(CXXFLAGS) 08largestproductinseries.cc ../tools/tools.cc $(INC) -o 08largestproductinseries
09specialpythagtriplet:
$(CXX) $(CXXFLAGS) 09specialpythagtriplet.cc $(INC) -o 09specialpythagtriplet
clean:
rm -f $(binaries)
</code></pre>
|
[] |
[
{
"body": "<p>You could use suffix rules (the .c.o part below) to tell make how to compile a c file. Then you can just tell the dependencies for each target.</p>\n\n<pre><code>CXX = g++\nCXXFLAGS = -std=c++0x\nINC = -Iinclude/ -I../tools/\n\nbinaries=01sum35\\\n 02evenfibs\\\n 03largestprimefactor\\\n 04largestpallyproduct\\\n 05smallestmultiple\\\n 06sumsquaredifference\\\n 07tenthousandfirstprime\\\n 08largestproductinseries\\\n 09specialpythagtriplet\n\nall: $(binaries)\n\n01sum35: 01sum35.cc\n\n02evenfibs: 02evenfibs.cc\n\n03largestprimefactor: 03largestprimefactor.cc \n\n04largestpallyproduct: 04largestpallyproduct.cc ../tools/tools.cc\n\n05smallestmultiple: 05smallestmultiple.cc\n\n06sumsquaredifference: 06sumsquaredifference.cc\n\n07tenthousandfirstprime: 07tenthousandfirstprime.cc ../tools/tools.cc\n\n08largestproductinseries: 08largestproductinseries.cc ../tools/tools.cc\n\n09specialpythagtriplet: 09specialpythagtriplet.cc \n\n.cc.o:\n $(CXX) $(CXXFLAGS) $< $(INC) -o $@\n\nclean:\n rm -f $(binaries)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T20:40:54.423",
"Id": "29096",
"ParentId": "29093",
"Score": "0"
}
},
{
"body": "<p>Yes:</p>\n\n<pre><code>CXX = g++\n#\n# Notice the +=. Use CPPFLAGS rather than INC for pre-processor rules.\n#\nCPPFLAGS += -Iinclude/ -I../tools/\nCXXFLAGS += -std=c++0x\n\n#\n# Move the backslash\n# This will stop it looking like a directory at first glance.\nbinaries=01sum35 \\\n 02evenfibs \\\n 03largestprimefactor \\\n 04largestpallyproduct \\\n 05smallestmultiple \\\n 06sumsquaredifference \\\n 07tenthousandfirstprime \\\n 08largestproductinseries \\\n 09specialpythagtriplet\n\nall: $(binaries)\n\nclean:\n rm -f $(binaries)\n\n# Default rules and dependencies works for all the targets\n# except the following which need one more file (dependency)\n\n04largestpallyproduct: 04largestpallyproduct.cc ../tools/tools.cc\n07tenthousandfirstprime: 07tenthousandfirstprime.cc ../tools/tools.cc\n08largestproductinseries: 08largestproductinseries.cc ../tools/tools.cc\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T20:45:54.053",
"Id": "29097",
"ParentId": "29093",
"Score": "4"
}
},
{
"body": "<p>A few extra things that add to the post from @LokiAstari<br>\nIn the listing below:</p>\n\n<ol>\n<li>Add some warnings, -Wall as a minimum</li>\n<li>Use VPATH to find the source files for the tools</li>\n<li>Mark targets that are not created as 'phony'. This stops <code>make</code> from doing some searches and prevents the makefile failing if a file called <code>all</code> or <code>clean</code> ever exists.</li>\n<li>Added some cleanup files</li>\n<li>By making the binaries that depend on the tools depend on the <code>tools.o</code> object file not the source file, you avoid recompiling tools.cc for every binary. Because we have a VPATH defined, the path to <code>tools.cc</code> need not be specified.</li>\n</ol>\n\n<p>Here's the simplified file:</p>\n\n<pre><code>CXX = g++\nCPPFLAGS += -Iinclude/ -I../tools/\nCXXFLAGS += -std=c++0x -Wall (1)\nVPATH = ../tools (2)\n\nbinaries = a b c\n\n.PHONY : all (3)\nall: $(binaries)\n\n.PHONY : clean (3)\nclean:\n rm -f $(binaries) *.o *~ (4)\n\nb: b.c tools.o (5)\nc: c.c tools.o (5)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T05:04:21.080",
"Id": "45997",
"Score": "1",
"body": "The new thing I learned today is VPATH. I have used make a lot and its the first time I have heard this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T19:35:14.827",
"Id": "46077",
"Score": "0",
"body": "@LokiAstari I've learnt many things from your answers to the many C++ questions, so I am glad it is now not an entirely one-way street :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T00:12:49.583",
"Id": "29099",
"ParentId": "29093",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "29097",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T19:27:29.830",
"Id": "29093",
"Score": "2",
"Tags": [
"c++",
"makefile"
],
"Title": "How can I improve this Makefile?"
}
|
29093
|
<p>I am learning <code>PowerShell</code>, and created the following script <code>cmdlet</code>. </p>
<p>It reads one or more specified script files, to discover special functions (UnitTests, or functions with the Verb 'UnitTest' or 'DataTest'.</p>
<p>I designed the parameters to work like <code>Get-Content</code>, as it reads content from files.</p>
<p>I would like general feedback on this cmdlet (design, workings), but i am also intrested in correctness.</p>
<pre><code><#
.SYNOPSIS
Gets UnitTests from a UnitTestFile.
.DESCRIPTION
UnitTests are PowerShell script functions, which are identified with the verb 'UnitTest' or 'DataTest'.
#>
function Get-UnitTest {
[CmdletBinding(DefaultParameterSetName = "Path")]
[OutputType([System.Management.Automation.FunctionInfo])]
Param(
<# Specifies a path to one or more UnitTestFiles. Wildcards are permitted. #>
[Parameter(Position = 0, ParameterSetName = "Path", Mandatory = $true)]
[string[]] $Path,
<# Specifies a LiteralPath to one or more UnitTestFiles. Wildcards are permitted. #>
[Parameter(ParameterSetName = "LiteralPath", Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[Alias("FullName")]
[string[]] $LiteralPath,
<# Specifies the Verb to use to identify UnitTests. The default verbs are 'UnitTest' and 'DataTest'. This means that functions with a name like 'UnitTest-Get-ChildItem' or 'DataTest-Invoke-WebRequest' are found. #>
[String[]] $Verb = @( "UnitTest", "DataTest" )
)
Process {
foreach($curPath in ($LiteralPath + $Path | Where {$_} | Resolve-Path)) {
if(Test-Path $curPath -PathType Leaf) {
Write-Trace "Getting UnitTests from '$curPath'."
. $curPath
# find and return all unit tests (from the requested file)
Get-Command -Verb $Verb `
| Where { $_.CommandType -eq "Function" } `
| Where { ( $_.ScriptBlock.File ) -eq $curPath }
}
}
}
}
</code></pre>
<p>This cmdlet can be called as follows:</p>
<pre><code>Get-UnitTest -Path .\somefile.ps1
Get-UnitTest -Path .\somefile.ps1 -Verb 'OtherTest'
Get-ChildItem -Recurse *.ps1 | Get-UnitTest
</code></pre>
|
[] |
[
{
"body": "<p>Looks good.\nPersonally, I would take:</p>\n\n<pre><code>foreach($curPath in ($LiteralPath + $Path | Where {$_} | Resolve-Path)) {\n</code></pre>\n\n<p>and break out the collection generation code.\nSpecifically into something like:</p>\n\n<pre><code>$PathList = Join-Path $literalPath $Path | Resolve-Path \n</code></pre>\n\n<p>You shouldn't need to worry about a Where-Object to validate that it isn't $null. If there is no result it won't go up the pipeline.</p>\n\n<p>If you Dot Include all of your Scripts you can wait until all are included then check your commands. This will run anything else you have in the script though.</p>\n\n<p>It may be safer to use the parser like this sample below. In this code I looked for catch blocks to insert a breakpoint , but you could have it filter for your test prefixes too.</p>\n\n<pre><code>$ParseError = $null\n$Tokens = $null\n$AST = [System.Management.Automation.Language.Parser]::ParseInput($psISE.CurrentFile.Editor.Text, [ref]$Tokens, [ref]$ParseError)\nif($ParseError) { \n foreach($er in $ParseError) { Write-Error $er }\n throw \"There was an error parsing script (See above). We cannot expand aliases until the script parses without errors.\"\n}\n$a = $ast.FindAll({($args[0] -is [System.Management.Automation.Language.CatchClauseAst])},$true)\n</code></pre>\n\n<ul>\n<li>Josh</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T17:58:25.053",
"Id": "29238",
"ParentId": "29094",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29238",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T20:10:39.530",
"Id": "29094",
"Score": "1",
"Tags": [
"powershell"
],
"Title": "Test finder PowerShell cmdlet"
}
|
29094
|
<p>I typed this up quickly as an intuitive solution for determining if a given number is a perfect square.</p>
<p>How could I improve this? I already know that it doesn't handle the case where the number is 1. I'm wondering if I could generalize the calculation so it rounds up. What can I look into to develop a mindset for tackling these sorts of problems?</p>
<pre><code>int number = 1000000;
int half = (number + 2 - 1)/2;
int square = 0;
boolean isSquare = false;
for( int i = half; i > 0 ; i-- ){
square = i*i;
if( square > number )
continue;
if( square == number ){
System.out.println( "This number is a perfect square" );
isSquare = true;
break;
}
}
if( !isSquare ){
System.out.println( "This number is not a perfect square" );
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T02:49:03.213",
"Id": "45880",
"Score": "1",
"body": "try FIPS 186-3 Appendix C section 4 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T18:58:27.620",
"Id": "526471",
"Score": "0",
"body": "here's a method that can check if an integer is a perfect square using only elementary math. https://math.stackexchange.com/questions/4226869/how-well-does-this-method-of-checking-if-an-integer-n-is-a-square-perform?noredirect=1#comment8784477_4226869"
}
] |
[
{
"body": "<p>You can narrow down your search range. If a number requires <code>n</code> bits to represent, its square root is between <code>1 << ((n-1) / 2)</code> and <code>1 << ((n+1) / 2)</code>. You can determine number of bits with something like:</p>\n\n<pre><code>int numBits(long l) {\n for (int i = 62; i >= 0; i--) {\n if (l & (1 << i)) return i + 1;\n }\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T06:29:36.663",
"Id": "45892",
"Score": "0",
"body": "I had an error in the shift statements, which I've now fixed."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T03:49:47.717",
"Id": "29105",
"ParentId": "29100",
"Score": "4"
}
},
{
"body": "<p>You could make use of the fact that <em>n</em>² = the sum of the first <em>n</em> odd numbers (for integral <em>n</em> ≥ 0), rather than having to compute <code>i * i</code> every time through the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T04:17:49.247",
"Id": "45884",
"Score": "1",
"body": "Interesting number set property. Didn't know about that one. Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T16:47:37.087",
"Id": "45947",
"Score": "0",
"body": "Is two additions cheaper than a multiplication?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-09T00:24:15.163",
"Id": "46734",
"Score": "1",
"body": "Did the experiment, was twice as fast..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-16T12:26:27.783",
"Id": "197806",
"Score": "0",
"body": "The property derives from (n+1)² - n² = 2n + 1, the next greater odd number."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T04:06:11.980",
"Id": "29106",
"ParentId": "29100",
"Score": "7"
}
},
{
"body": "<p>There are significant improvements that can be made by choosing a more optimal algorithm.</p>\n\n<p>Better algorithms for finding the root of <em>x² - n = 0</em> are :</p>\n\n<ul>\n<li><p>Halving intervals to search for the root. This is called the <a href=\"https://en.wikipedia.org/wiki/Bisection_method\" rel=\"nofollow\">bisection method</a>.</p></li>\n<li><p>Even faster would be <a href=\"https://en.wikipedia.org/wiki/Newton%27s_method\" rel=\"nofollow\">Newton's method</a> : follow the tangent line on your current approximated root, to find a closer approximation.</p></li>\n</ul>\n\n<p>Note the pseudo code on the linked wiki pages.</p>\n\n<p>Both are defined to use reals, but can easily be adapted to accept only integer results : once improvements stop or are less than the distance to the nearest integer, you either have found an exact integer result, or the root isn't an integer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T07:54:40.923",
"Id": "29108",
"ParentId": "29100",
"Score": "2"
}
},
{
"body": "<p>What you need is to use integer square root algorithm and verify that the root's square value is the original number (e.g. x == isqrt(x)^2).</p>\n\n<p>You can find integer square root algorithm code here:\n<a href=\"http://medialab.freaknet.org/martin/src/sqrt/\" rel=\"nofollow\">http://medialab.freaknet.org/martin/src/sqrt/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-08T10:52:41.663",
"Id": "29518",
"ParentId": "29100",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29106",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T00:25:31.550",
"Id": "29100",
"Score": "5",
"Tags": [
"java",
"algorithm"
],
"Title": "Checking if a number is a perfect square (without Math)"
}
|
29100
|
<blockquote>
<p><strong>Function: Trim</strong></p>
<p>Returns a new string after removing any white-space characters from
the beginning and end of the argument.</p>
</blockquote>
<pre><code>string trim(string word) {
if(startsWith(word, " ")) return removeSpaces(word, "Front");
if(endsWith(word, " ")) return removeSpaces(word , "Back");
return word;
}
string removeSpaces(string word , string position){
if(position == "Front"){
for(int i =0; i <word.length();i++){
if(word[i] != ' '){
return word;
}else{
word.erase(i);
}
}
return word;
}else if(position == "Back"){
for(int i =word.length() - 1 ; i >=0 ; i--){
if(word[i] != ' '){
return word;
}else{
word.erase(i);
}
}
return word;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-27T05:16:48.843",
"Id": "136224",
"Score": "0",
"body": "Any particular reason why there isn't a `trim()` method available as part of the string library? [C#](http://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28string_functions%29#trim) has it."
}
] |
[
{
"body": "<ul>\n<li><p>Your absence of <code>std::</code> before your <code>string</code>s lead me to believe that you're using <code>using namespace std;</code>. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't do that</a>.</p></li>\n<li><p>If-statements don't look too clear as just one line. Try this instead:</p>\n\n<pre><code>if (startsWith(word, \" \"))\n{\n return removeSpaces(word, \"Front\");\n}\n</code></pre></li>\n<li><p>With <code>std::string</code>, it's best to use its iterators instead of indices in a for-loop:</p>\n\n<pre><code>for (auto iter = str.begin(); iter != str.end(); ++iter)\n{\n // do something with string\n}\n</code></pre>\n\n<p>However, this won't work well in this particular function since you're reducing the size. For that, I would prefer a while-loop.</p></li>\n<li><p>In case you ever want to remove <em>all</em> whitespace from an <code>std::string</code>:</p>\n\n<pre><code>str.erase(remove_if(str.begin(), str.end(), isspace), str.end());\n</code></pre>\n\n<p>It's quite clear and safe since it uses the STL. Include <code><algorithm></code> to use <code>remove_if()</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T04:05:40.823",
"Id": "45882",
"Score": "0",
"body": "Your erase-remove will work to remove all the spaces from a string, but doesn't fulfill the stated contract of the function (remove whitespace from the beginning and end of the string). So for example, it will do the wrong thing for \" hi there \"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T04:12:21.883",
"Id": "45883",
"Score": "0",
"body": "@ruds: I see. I somehow thought it said _starting from_ (and the function name isn't specific enough). I'll keep it here for generality."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T09:35:22.833",
"Id": "46004",
"Score": "0",
"body": "I disagree with one-line `if`s. They are common, concise and often more readable than their multiline counterparts. (Also, Bjarne uses them.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:57:36.547",
"Id": "46018",
"Score": "0",
"body": "@Lstor: He does? That's good enough for me, then."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T03:19:19.713",
"Id": "29103",
"ParentId": "29102",
"Score": "3"
}
},
{
"body": "<p>The second argument to <code>removeSpaces</code> should by no means be a <code>string</code>. I suggest an <code>enum</code>:</p>\n\n<pre><code>enum StringPostion {\n BEGINNING_OF_STRING,\n END_OF_STRING,\n};\n</code></pre>\n\n<hr>\n\n<p>You appear to have a <code>using namespace std;</code> statement in your program. You shouldn't do this. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">This StackOverflow question</a> explains why.</p>\n\n<hr>\n\n<p>Your implementation of <code>trim</code> removes spaces from the front or back of <code>word</code>, not both.</p>\n\n<hr>\n\n<p>You've chosen an O(kn) algorithm (which is in any case incorrect), where k is the number of spaces at the beginning of the string and n is the number of characters in the string. Each call to <code>s.erase(i)</code> causes all of the characters after <code>i</code> to be shifted to the left. It also causes the string to be shortened by one character. Your function will only erase half of the leading or trailing spaces since you shorten the string <em>and</em> increment <code>i</code>.</p>\n\n<p>Try this:</p>\n\n<pre><code>std::string trim(std::string word) {\n removeSpaces(word, BEGINNING_OF_STRING);\n removeSpaces(word, END_OF_STRING);\n return word;\n}\nvoid removeSpaces(std::string& word, StringPosition position) {\n switch (position) {\n case BEGINNING_OF_STRING: {\n const auto first_nonspace = word.find_first_not_of(' ');\n word.erase(0, first_nonspace);\n return;\n }\n case END_OF_STRING: {\n const auto last_nonspace = word.find_last_not_of(' ');\n if (last_nonspace != std:string::npos) word.erase(last_nonspace + 1);\n return;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T05:34:00.687",
"Id": "45885",
"Score": "0",
"body": "Dude!!!! Eye Opening explanation :) still more insights are needed.. when i was writing this code i thought that it will work fine., but how can we get to know about the hidden fail cases of our code.? and i have not seen this \"O(kn) algorithm\" where can i get to know similar kind of algo .. ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T05:56:58.653",
"Id": "45886",
"Score": "1",
"body": "Unit testing is very important. I think that Google's C++ unit testing library is pretty good: https://code.google.com/p/googletest/ . A simple unit test where you passed \" foo \" and didn't get \"foo\" in return would have pointed out your errors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T06:01:47.533",
"Id": "45887",
"Score": "1",
"body": "\"O(kn) algorithm\" is shorthand for something like \"As the size of your input increases, the number of instructions executed by your algorithm will increase linearly in k and n.\" This is big-O notation https://en.wikipedia.org/wiki/Big_O_notation, which is widely used by computer scientists to describe the performance of an algorithm. The main point here is that your algorithm performs poorly compared with mine because you remove one character, copy all the other characters one slot to the left, and then repeat. Mine copies all the non-space characters once, instead of once for each space."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:40:59.233",
"Id": "45921",
"Score": "1",
"body": "@AravinthChandran In your edit comment, you asked what precisely `const auto first_nonspace = word.find_first_not_of(' ');` means. `auto` gives `first_nonspace` the same type as the expression on the right side of the assignment operator (in this case, `std::string::size_type`, which is the same as `std::size_t` in most implementations but not required to be). `const auto` means that you add a `const` qualifier to the type, making `first_nonspace` a `const std::string::size_type`. `auto` is a new feature in the 2011 C++ standard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:55:49.443",
"Id": "45923",
"Score": "0",
"body": "@AravinthChandran: To add onto that: using `std::string::size_type`, `auto`, or `std::size_t` also guarantees that you can store the string size, no matter how large it is. Related discussion [here](http://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:45:18.843",
"Id": "45958",
"Score": "0",
"body": "@Murph I've clarified my comment. My point was that the implementation of `trim` in the question only trims from one side, despite the comment that it should trim from both."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T11:20:34.853",
"Id": "46015",
"Score": "0",
"body": "@ruds I *completely* missed that! Yes, the code is broken."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T03:32:26.543",
"Id": "29104",
"ParentId": "29102",
"Score": "2"
}
},
{
"body": "<p>Since there is no common code between the two code paths within removeSpaces you should have two separate functions:</p>\n\n<pre><code>string removeSpacesFromFront(string word) \nstring removeSpacesFromBack(string word)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T18:00:30.577",
"Id": "45954",
"Score": "0",
"body": "Same idea I had earlier (also the main cause for the confusion in my answer), but I never thought about separate functions. Good find."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T17:55:03.017",
"Id": "29140",
"ParentId": "29102",
"Score": "3"
}
},
{
"body": "<p>We can simplify this:</p>\n\n<pre><code>std::string trim(std::string const& input)\n{\n std::string::size_type start = input.find_first_not_of(\" \");\n std::string::size_type end = input.find_last_not_of(\" \");\n\n start = (start == std::string::npos ? 0 : start);\n end = (end == std::string::npos ? 0 : end );\n\n return input.substr(start, end-start);\n}\n</code></pre>\n\n<p>Notice a couple of things:</p>\n\n<p>We don't copy the string. Pass it in by const reference.</p>\n\n<p>We work out where in the input string the start and end are. Then we use the string <code>substr()</code> method to just hack out the part we need once.</p>\n\n<p>There are a whole bunch of string manipulation functions in string that make this easy.</p>\n\n<p>OK. So I cheated and it does not do white space just space. So think of this is draft one. A tiny bit of extra effort and we can do the same thing but check for white space by using <code>std::isspace()</code>.</p>\n\n<p>I would also think about a version that modifies the input string:</p>\n\n<pre><code>void trim_in_place(std::string& input) // Pass by reference.\n{\n std::string::size_type start = input.find_first_not_of(\" \");\n std::string::size_type end = input.find_last_not_of(\" \");\n\n start = (start == std::string::npos ? 0 : start);\n end = (end == std::string::npos ? 0 : end );\n\n // Create the result\n std::string result = input.substr(start, end-start);\n\n // Swap it into the input variable (once we know everything has worked).\n swap(result, input)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T05:20:11.350",
"Id": "29161",
"ParentId": "29102",
"Score": "4"
}
},
{
"body": "<p>I think if I were doing this, I'd treat the <code>string</code> like a normal collection, and use standard algorithms to do the searching. Instead of comparing directly with <code>' '</code>, I'd also rather see <code>std::isspace</code> (or something similar) used to determine whether something is a space or not.</p>\n\n<p>Since the standard algorithms all use iterators, we can pretty easily make one piece of code work for trimming either the beginning or end of a string by passing normal or reverse iterators.</p>\n\n<p>With that idea in place, things fall together pretty simply:</p>\n\n<pre><code>template <class Iter>\nIter ltrim(Iter b, Iter e) {\n return std::find_if_not(b, e, isspace);\n}\n\nstd::string ltrim(std::string const &in) {\n return std::string(ltrim(in.begin(), in.end()), in.end());\n}\n\nstd::string rtrim(std::string const &in) {\n return std::string(in.begin(), ltrim(in.rbegin(), in.rend()).base());\n}\n\nstd::string trim(std::string const &in) {\n return ltrim(rtrim(in));\n}\n</code></pre>\n\n<p>For the full trim, you might prefer to avoid the intermediate result, and instead search for the positions, and create one new string from both positions:</p>\n\n<pre><code>std::string trim(std::string const &in) {\n auto b = std::find_if_not(in.begin(), in.end(), isspace);\n auto e = std::find_if_not(in.rbegin(), in.rend(), isspace).base();\n return std::string(b, e);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T08:14:53.310",
"Id": "29209",
"ParentId": "29102",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "29104",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T02:49:07.920",
"Id": "29102",
"Score": "2",
"Tags": [
"c++",
"strings"
],
"Title": "Trimming a string"
}
|
29102
|
<p>Considering the code that you can find at the bottom of this post, it's safe to say that this is a good example of how I can use different representations in different basefields correctly in C++ ?</p>
<p>I'm referring to the use of:</p>
<ul>
<li><code>std::hex</code> in the <code>std::istringstream</code> case</li>
<li>the use of <code>std::cout.setf()</code> and <code>std::cout.unsetf()</code> in the "output section"</li>
</ul>
<p>In short is this correct for both input and output ?</p>
<p>This could possibly lead to some bug of some kind on some platforms ?</p>
<p>I also have a doubt about the use of an unsigned int to input a char, the basefield always cares about that ? I mean if I input <code>f</code> I would like to store <code>15</code> in decimals and <a href="http://www.asciitable.com/">not <code>102</code> from the ascii table</a>.
(because a <code>char</code> is often implemented as an <code>unsigned int</code>)</p>
<p>Thanks.</p>
<pre><code>// trying to determine what is the header available for unsigned ints
#if __cplusplus < 201103L
#include <stdint.h>
#else
#include <cstdint>
#endif
#include <cstdlib>
#include <string>
#include <map>
#include <bitset>
#include <iostream>
#include <iomanip>
#include <sstream>
const static uint32_t fieldWidth = 2;
int main(int argc, char **argv) {
std::map<std::string, uint32_t> bucket;
bucket["EAX"] = 0x0; // initializing bucket with default values
bucket["EBX"] = 0x0;
bucket["ECX"] = 0x0;
bucket["EDX"] = 0x0;
if (argc >= 2) {
switch (argc) {
case 2:
std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
break;
case 3:
std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
break;
case 4:
std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
break;
case 5:
std::istringstream(argv[1]) >> std::hex >> bucket["EAX"];
std::istringstream(argv[2]) >> std::hex >> bucket["EBX"];
std::istringstream(argv[3]) >> std::hex >> bucket["ECX"];
std::istringstream(argv[4]) >> std::hex >> bucket["EDX"];
break;
default:
std::cout << "Too many arguments, exiting now\n";
exit(EXIT_FAILURE);
}
} else {
std::cout << "Not enough arguments, exiting now\n";
exit(EXIT_FAILURE);
}
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout.setf(std::ios::showbase);
std::cout << "\nExecuting with this HEX values :\n\n";
std::cout << "EAX = " << std::hex << bucket["EAX"] << "\n"
<< "EBX = " << std::hex << bucket["EBX"] << "\n"
<< "ECX = " << std::hex << bucket["ECX"] << "\n"
<< "EDX = " << std::hex << bucket["EDX"] << "\n";
std::cout.unsetf(std::ios::showbase);
std::cout.unsetf(std::ios::hex);
asm volatile("cpuid"
: "=a"(bucket["EAX"]), "=b"(bucket["EBX"]), "=c"(bucket["ECX"]),
"=d"(bucket["EDX"])
: "a"(bucket["EAX"]), "b"(bucket["EBX"]), "c"(bucket["ECX"]),
"d"(bucket["EDX"]));
std::cout << "\nThe results:\n";
for (std::map<std::string, uint32_t>::const_iterator k = bucket.begin();
k != bucket.end(); ++k) {
std::cout << "\n";
std::cout << k->first << "\n";
for (int c = 31; c >= 0; c--) {
std::cout << std::setfill(' ') << std::setw(fieldWidth) << c;
}
std::cout << "\n";
std::string s(std::bitset<32>(k->second).to_string());
for (std::string::const_iterator j = s.begin(); j != s.end(); ++j) {
std::cout << std::setfill(' ') << std::setw(fieldWidth) << *j;
}
std::cout << "\n";
}
std::cout << "\n";
return (0);
}
</code></pre>
<p><a href="https://github.com/emanuelecestari/cpuidplayer">original repository</a></p>
|
[] |
[
{
"body": "<blockquote>\n <p>it's safe to say that this is a good example of how I can use different representations in different basefields correctly in C++ ?</p>\n</blockquote>\n\n<p>I presume you <code>stream manipulators</code>.</p>\n\n<blockquote>\n <p>I'm referring to the use of:</p>\n</blockquote>\n\n<pre><code>std::hex in the std::istringstream case\nthe use of std::cout.setf() and std::cout.unsetf() in the \"output section\"\n</code></pre>\n\n<p>These are examples of stream manipulators:</p>\n\n<p>I would not do this:</p>\n\n<pre><code>#if __cplusplus < 201103L\n#include <stdint.h>\n#else\n#include <cstdint>\n#endif\n</code></pre>\n\n<p>In one version you are putting the functions in the global namespace (stdint.h) the other you are putting the functions in the std namespace. This will cause problems and may give you different results on different compilers.</p>\n\n<p>This seems like you are doing it the hard way:</p>\n\n<pre><code> if (argc >= 2) {\n switch (argc) {\n case 2:\n std::istringstream(argv[1]) >> std::hex >> bucket[\"EAX\"];\n break;\n case 3:\n std::istringstream(argv[1]) >> std::hex >> bucket[\"EAX\"];\n std::istringstream(argv[2]) >> std::hex >> bucket[\"EBX\"];\n break;\n case 4:\n std::istringstream(argv[1]) >> std::hex >> bucket[\"EAX\"];\n std::istringstream(argv[2]) >> std::hex >> bucket[\"EBX\"];\n std::istringstream(argv[3]) >> std::hex >> bucket[\"ECX\"];\n break;\n case 5:\n std::istringstream(argv[1]) >> std::hex >> bucket[\"EAX\"];\n std::istringstream(argv[2]) >> std::hex >> bucket[\"EBX\"];\n std::istringstream(argv[3]) >> std::hex >> bucket[\"ECX\"];\n std::istringstream(argv[4]) >> std::hex >> bucket[\"EDX\"];\n break;\n default:\n std::cout << \"Too many arguments, exiting now\\n\";\n exit(EXIT_FAILURE);\n }\n</code></pre>\n\n<p>Why not a loop?</p>\n\n<pre><code> if (argc < 2 || argc > 4) {/*ERROR MSG AND EXIT*/}\n\n std::vector<std::string> mapIndex = { \"EAX\", \"EBX\", \"ECX\", \"EDX\" };\n for(int loop = 1; loop < argc; ++loop)\n {\n // PS: just using mapIndex to keep it as close to your original\n // code as possbile. If I had done this from scratch I would\n // have just put the values into a four element array.\n\n std::istringstream(argv[loop]) >> std::hex >> bucket[mapIndex[loop-1]];\n }\n</code></pre>\n\n<p>The use of std::hex in this situation is correct.<br>\nIt marks the input stream and the next value (if an hex integer) is correctly read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T05:07:31.730",
"Id": "46192",
"Score": "0",
"body": "I assume that the use of `std::cout.setf()` and `std::cout.unsetf()` is ok too, I know that `stdint.h` is a dirty solution, but on non-c++11 compiler how do you provide a safe `uint32_t` type ? I should remove the include and add a `typedef` ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T17:46:52.467",
"Id": "46220",
"Score": "0",
"body": "Looks fine to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T17:58:16.907",
"Id": "46221",
"Score": "0",
"body": "ok, but what about the uint32_t ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T18:31:03.700",
"Id": "46226",
"Score": "0",
"body": "If you have to support multiple compilers I would just include <stdint.h> so that it is in the global namespace. Or you can do as above. But manually export the types you want into the global namespace with `using std::uint32_t;` assuming my statement above is correct and cstdint puts things in the std namespace."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-03T04:08:50.883",
"Id": "46309",
"Score": "1",
"body": "You may also want to see: http://stackoverflow.com/a/4217811/14065"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-31T23:08:23.277",
"Id": "29249",
"ParentId": "29107",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "29249",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T06:17:28.887",
"Id": "29107",
"Score": "6",
"Tags": [
"c++"
],
"Title": "Is this a correct use of the std::cout and std::cin basefields/conversions?"
}
|
29107
|
<p>Can my <code>rand_int</code> function be improved?</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int rand_int(int a,int b)
{
//The basic function here is like (rand() % range)+ Lower_bound
srand(time(0));
if (a > b)
return((rand() % (a-b+1)) + b);
else if (b > a)
return((rand() % (b-a+1)) + a);
else
return a;
}
int main()
{
int a,b;
printf("\nEnter the range in which the a random no. is required: ");
scanf("%d %d", &a, &b);
printf("%d\n", rand_int(a,b));
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T08:52:45.237",
"Id": "45893",
"Score": "0",
"body": "I think that your main problem is in the concept, `rand()` is probably the most unreliable prng, but this is not the real downside, the real problem is that `rand()` in just defined as a generic pseudo-random number generator that returns a value between 0 and RAND_MAX, no words about the real algorithm that `rand()` uses, so you can work on `rand()` as much as you want but you will never get a consistent behaviour or even a predictable one. You also should describe what kind of PRNG you are looking for in a question like this one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T08:56:47.910",
"Id": "45894",
"Score": "0",
"body": "@user2485710 In a real-life problem when I want randomness the pnrg used in `rand()` would matter but here I was just looking for how to use `rand()` properly. Mainly for timing codes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:04:15.620",
"Id": "45896",
"Score": "0",
"body": "yes, infact I just avoided to comment on the \"unreliable\" side of `rand()`, my point is since `rand()` is not defined by standard and is implementation-dependant, you are basically taking an educated guess no matter what you are doing with `rand()`, no matter what your goals or requirements are."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:06:13.547",
"Id": "45898",
"Score": "0",
"body": "@user2485710 So is it always better to write my own prng?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:09:32.800",
"Id": "45900",
"Score": "0",
"body": "Considering that your language of choice is C, yes, C doesn't really offer a good PRNG out of the box, but there are also a lot of PRNGs that are extremely easy to implement ( especially if you don't set the bar really high and you can live without a super-complex PRNG for a banking system ) http://en.wikipedia.org/wiki/Xorshift"
}
] |
[
{
"body": "<p>First of all. Move <code>srand()</code> out of the function call. For now, it is not random at all if you manage to execute function twice in the same second. You will reset the random seed to the same value with <code>time(0)</code> as it normally has a <code>1s</code> resolution.</p>\n\n<p>Then I would suggest to do a conditional swap, and then perform \"generate random\" thing. This way you will split it into \"preparation of arguments\" and the \"actual work parts\".</p>\n\n<p>You will have one exit point, which is a bit more readable and AFAIK tend to be a bit more optimizer friendly. Also, modern processors don't like too many <code>if</code>s, especially unpredictable. So I would further suggest refactoring the \"job\" part into a separate function <code>int rand_hi_lo(int upper, int lower)</code> maybe even <code>inline</code>d. You could skip the branch at all then in certain cases.</p>\n\n<pre><code>#include<stdio.h>\n#include<stdlib.h>\n#include<time.h>\n\nvoid swap_int(int* a, int* b){ int tmp = *a; *a=*b; *b=tmp; }\n\ninline int rand_int_hi_lo(int upper, int lower){\n return((rand() % (upper-lower+1)) + lower);\n}\n\nint rand_int(int a,int b)\n{\n if (b > a) swap_int(&a,&b);\n return rand_int_hi_lo(a,b);\n}\n\nint main()\n{\n int a,b;\n srand(time(0));\n printf(\"\\nEnter the range in which the a random no. is required: \");\n scanf(\"%d %d\", &a, &b);\n printf(\"%d\\n\", rand_int(a,b));\n}\n</code></pre>\n\n<p>It might be even possible to skip the conditional at all. But I am not sure about the negative modulo arithmetics. I think it is possible. Also my <code>c</code> is rusty, so I hope I wrote <code>swap</code> correctly.</p>\n\n<p>EDIT:\nI also skipped the <code>a==b</code>. I don't think it is worth to put there at all unless you are sure it happens more than rarely. If necessary I would put <code>if (a==b) return a;</code> it before the <code>swap_int</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:04:26.477",
"Id": "45897",
"Score": "0",
"body": "Your `swap` is correct but can you elaborate the part about `inline`? I have heard that it is good but I haven't used it before. Also didn't get how avoiding many `if`s leads to a separate function"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T09:17:39.977",
"Id": "45903",
"Score": "0",
"body": "It used to indicate that the function body might be embedded into the caller's body, when generating assembler, to avoid unnecessary jumps. It used to be a performance option. Now it has mostly semantical meaning, as the compilers are smart enough to figure out what to inline. They were also free to ignore it. Regarding `if`s. It is the opposite. Refactoring helps to provide an additional function that avoids conditional, which might be important perfomnace-wise; related to \"branch predictions\" and \"code path execution\" stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:13:08.903",
"Id": "45912",
"Score": "0",
"body": "In this example how does using `rand_int_hi_lo` function avoid the `if`? You can simply put that into the `rand_int` function and it would be the same"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:15:27.537",
"Id": "45913",
"Score": "0",
"body": "It allows you to skip it, when you know the order of operands is right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:18:53.740",
"Id": "45914",
"Score": "0",
"body": "So you are saying that in the function `rand_int` the `if` wouldn't be executed because of the use of the function call to `rand_int_hi_lo`? How is that possible? The `if` is before that function call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:38:27.487",
"Id": "45920",
"Score": "0",
"body": "No, I never said that. Let me rephrase ... It allows the programmer to choose the better (optimization-wise) version, if he is certain of the operands order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:47:01.197",
"Id": "45922",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/9869/discussion-between-aseem-bansal-and-luk32)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T08:53:48.117",
"Id": "29110",
"ParentId": "29109",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "29110",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T08:26:24.727",
"Id": "29109",
"Score": "2",
"Tags": [
"c",
"random"
],
"Title": "Random integer generation in given range"
}
|
29109
|
<p>I'm looking for an lib which can search an array of strings with multible search-strings (array). I want to get an int-array of all indexes/matches.</p>
<pre><code>private int[] getIndexArray(String[] pArray, String[] pSearchStrings) {
int[] indexes = new int[0];
for (String str : pArray) {
if (ArrayUtils.contains(pSearchStrings, str))
indexes = ArrayUtils.add(indexes, ArrayUtils.indexOf(pArray, str));
}
return indexes;
}
</code></pre>
<p>Is there a better way of doing it?</p>
|
[] |
[
{
"body": "<p>If you use <code>pSearchStrings[]</code> for all <code>pArray[]</code>, you can transform <code>pSearchStrings</code> in a <em>Pattern</em> and use <em>matcher</em> method to avoid to load each time <em>ArrayUtils.contains(..)</em></p>\n\n<p><strong>EDIT</strong><br></p>\n\n<pre><code>private static int[] getIndexArray(String[] pArray, String[] pSearchStrings) {\n StringBuilder sb = new StringBuilder((int) estimateSizeOfSearchStrings +16);\n for (String searh : pSearchStrings) {\n sb.append(\".*\");\n sb.append(search)\n sb.append(\".*|\");\n }\n Pattern patt = Pattern.compile(sb.toString().subString(0,sb.length() -1);\n // If pSearchStrings are always the same, you can put static 'patt' outside this method\n // Or pass pre-compiled 'patt' as a parameter.\n int [] indexes = new int [pSearchStrings.length];\n int i = 0;\n for (String str : pArray) {\n if (patt.matcher(str).find())\n indexes[i++] = ArrayUtils.indexOf(pArray, str);\n }\n return indexes;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T08:41:03.657",
"Id": "46197",
"Score": "0",
"body": "Interesting point of view. But is it really a better way of checking to create a pattern and check the pattern instead of calling `ArrayUtils.contains(..)`. Both methods will run in O(n), but the creation of the pattern will cost performance and memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T10:15:31.967",
"Id": "46202",
"Score": "0",
"body": "@d.poellath As I wrote in comment, if you can put `patt`in a static field outside the method, or have determined Pattern to pass as parameter, it certainly will give more maintanble code. I'm not certain that a `foreach` with `ArrayUtils.indexOf()` will be needed if you use a fr(int i = 0, n = `pArray.length; ...)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T11:37:47.553",
"Id": "46204",
"Score": "0",
"body": "I have to correct my comment before. The methods both will need O(n*m), because of the two arrays. In your method the search-array of size m will be transformed to an string of sitze m*(size(searchStr)). there is no really time saving. especially because the you need to create a pattern for every different search array (and store for reuse). or do i miss something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-01T12:04:44.880",
"Id": "46205",
"Score": "0",
"body": "@d.poellath Usign pattern(s) is useful only if you can built it(them) at the begining, and know all matching cases ; then pass it(them) as a parameter. If `getIndexArray` is uses three or more times on big `[]pArray`, it may be worst to test the two methods . But I guess the gain is less than 1%, compile tools are too powerful."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T11:34:55.300",
"Id": "29118",
"ParentId": "29113",
"Score": "1"
}
},
{
"body": "<p>Try this:</p>\n\n<pre><code>private static int[] getIndexArray(String[] pArray, String[] pSearchStrings) {\n //There can only be as many indices as there are search terms, right? So:\n int [] indexes = new int [pSearchStrings.length];\n int i = 0;\n for (String str : pArray) {\n if (ArrayUtils.contains(pSearchStrings, str))\n indexes[i++] = ArrayUtils.indexOf(pArray, str);\n }\n return indexes;\n}\n</code></pre>\n\n<p>I haven't tested it, so I dunno if it works, but your code makes a new array every time through the loop (which isn't that big of a deal, but still).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:18:06.390",
"Id": "29126",
"ParentId": "29113",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T10:14:08.773",
"Id": "29113",
"Score": "2",
"Tags": [
"java"
],
"Title": "Search Array of Strings in Array of String, receive Int-Array of indexes"
}
|
29113
|
<p>This script takes the list of provided URLs and scrapes the present links in each URL. For each scraped link, Facebook share, tweet, Google Plus is found out.</p>
<p>For example, if the provided URL is www.example.com, the URL is scraped and, let us say, 2 links are found:</p>
<blockquote>
<p>www.example.com/1.php<br>
www.example.com/2.php</p>
</blockquote>
<p>Then Facebook likes and others are found for both the links and average (i.e. total Facebook likes / 2 (two links scraped)) is calculated. The problem is that the script takes too much time. Is there any method to optimize it?</p>
<pre><code><?php
/* Enable Error Reporting in php */
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
function get_tweets($url) {
$url =trim(rtrim($url,"\n"));
$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url='.$url);
$json = json_decode($json_string, true);
return @intval( $json['count'] );
}
function get_likes($url) {
$url =trim(rtrim($url,"\n"));
$json_string = file_get_contents('http://graph.facebook.com/?ids='.$url);
$json = json_decode($json_string, true);
return @intval( $json[$url]['shares'] );
}
function get_plusones($url) {
$url =trim(rtrim($url,"\n"));
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"' . $url . '","source":"widget","userId":"@viewer","groupId":"@self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
return @intval( $json[0]['result']['metadata']['globalCounts']['count'] );
}
function scrapper($Url){
$resultant = array();
$details="URL,Likes,Tweets,Plus ones\n";
$fb_sum = 0;
$tweets = 0;
$g_plus = 0;
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; //Change it to some other
$master_curl = curl_multi_init();
$curl_arr = array();
for($i=0;$i<count($Url);$i++)
{
$url = $Url[$i];
$curl_arr[$i] = curl_init($url);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_arr[$i], CURLOPT_USERAGENT, $userAgent);
curl_setopt($curl_arr[$i], CURLOPT_FAILONERROR, true);
curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER,true);
curl_multi_add_handle($master_curl, $curl_arr[$i]);
}
$running = 0;
do {
curl_multi_exec($master_curl, $running);
} while ($running > 0);
for($j=0; $j<count($Url); $j++)
{
$html = curl_multi_getcontent($curl_arr[$j]);
$dom = new DOMDocument();
@$dom->loadHTML($html);
//Grab the entire Page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url2 = $href->getAttribute('href');
// Url's are obtained
//Obtain Tweets, fb likes and google plus ones of the url
$fb_sum += get_likes($url2);
$tweets += get_tweets($url2);
$g_plus += get_plusones($url2);
}
array_push($resultant,array($Url[$j],$fb_sum,$tweets,$g_plus));
}
return $resultant;
}
if(isset($_POST['submit']) && (trim($_POST['urls'])!=""))
{
$getUrls = explode("\n",rtrim($_POST['urls'],"\n"));
$time_start = microtime(true);
$final_display = scrapper($getUrls);
print_r($final_display);
$time_end = microtime(true);
$execution_time = ($time_end - $time_start)/60;
echo '<br><b>Total Execution Time:</b> '.$execution_time.' Mins';
}
else
{
echo "<center><h3>Now Go <a href='index.php'>Back</a> and Type something. </h3></center>";
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>I can't comment on performance, as I'm not very familiar with the cURL library and web scraping techniques.</p>\n\n<p>However, I'd be happy to comment on other points! I'll point things out in the order the script is ran.</p>\n\n<ul>\n<li><code>&& (trim($_POST['urls'])!=\"\"))</code> is redundant, consider just using <code>&& !empty($_POST['urls']))</code>.</li>\n<li><p>Thorughout the code, I see <code>rtrim($_POST['urls'],\"\\n\")</code> a lot. Factor this into a single function:</p>\n\n<pre><code>function remove_last_newline($input) {\n return rtrim($input, \"\\n\");\n}\n</code></pre></li>\n<li><p><code>scrapper</code> is a poor function name. It has no meaning and confuses the reader. Also, the parameter <code>$Url</code> should be <code>array $urls</code>. We type hint an array, and make it plural.</p></li>\n<li>Avoid variables with numbers concatenated: <code>$url2</code>.</li>\n<li>I notice you check every single link on the page for likes and such. This is my guess as to why it's so slow. Only query the links you think would have likes.</li>\n<li><code>array_push</code> is actually slower than <code>$resultant[] = array($Url[$j],$fb_sum,$tweets,$g_plus);</code>. If you can, use the brackets for single pushes.</li>\n<li><code>$resultant</code> isn't a word... Just use <code>$results</code>.</li>\n<li><p>This part is repeated a lot, consider using a function and passing the URL as a parameter:</p>\n\n<pre><code>$url =trim(rtrim($url,\"\\n\"));\n$json_string = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url='.$url);\n$json = json_decode($json_string, true);\n</code></pre></li>\n<li><p>Why are you suppressing <code>@intval</code>?</p></li>\n<li>You spacing is very inconsistent, give unity to the spaces around operators and assignments.</li>\n</ul>\n\n<p>My advice to making this faster:</p>\n\n<ul>\n<li>use as little code as possible. The more clutter, the less likely it is to be fast (unless it's for a good reason).</li>\n<li>Use any APIs you can. <strong>Much</strong> faster than scraping.</li>\n<li>Use <code>microtime</code> to figure out where</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-20T22:43:20.013",
"Id": "57541",
"ParentId": "29115",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T11:11:28.150",
"Id": "29115",
"Score": "1",
"Tags": [
"php",
"performance",
"php5",
"url",
"web-scraping"
],
"Title": "Scraping links from provided URLs"
}
|
29115
|
<p>I have a method that checks whether an <code>addressCriteria</code> contains only certain fields or more. If it contains more fields, it should return false, otherwise true.</p>
<p>I'm uncertain what the best way to write my if statement is. As far as I can tell, I see 2 options:</p>
<ul>
<li>Write them in 1 if statement</li>
<li>Write each check in a different if statement</li>
</ul>
<p><strong>Single if statement:</strong></p>
<pre><code>private boolean isShortAddress(AddressCriteria addressCriteria) {
if((null != addressCriteria.getCity() && !addressCriteria.getCity().isEmpty()) ||
(null != addressCriteria.getNumber() && !addressCriteria.getNumber().isEmpty()) ||
(null != addressCriteria.getState() && !addressCriteria.getState().isEmpty()) ||
(null != addressCriteria.getZipCode() && !addressCriteria.getZipCode().isEmpty())) {
return false;
}
return true;
}
</code></pre>
<p><strong>Multiple if statements:</strong></p>
<pre><code>private boolean isShortAddress(AddressCriteria addressCriteria) {
if(null != addressCriteria.getCity() && !addressCriteria.getCity().isEmpty()) {
return false;
}
if(null != addressCriteria.getNumber() && !addressCriteria.getNumber().isEmpty()) {
return false;
}
if(null != addressCriteria.getState() && !addressCriteria.getState().isEmpty()) {
return false;
}
if(null != addressCriteria.getZipCode() && !addressCriteria.getZipCode().isEmpty()) {
return false;
}
return true;
}
</code></pre>
<p>Maybe there's a 3rd or 4th option that I am unaware of?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T07:57:12.150",
"Id": "47628",
"Score": "0",
"body": "Wow, so many responses have got the boolean logic inverted. Are Code Review users copying each others' mistakes? Or is `isShortAddress()` poorly named, such that it gives programmers the wrong impression about what it's supposed to do?"
}
] |
[
{
"body": "<p>I think the second approach with <strong>multiple if statements</strong> is better because it is <strong>more readable</strong>. </p>\n\n<p>Having multiple exit points allows to faster read source code as Martin Fowler explains in his book <em>Refactoring: Improving the Design of Existing Code</em>:</p>\n\n<blockquote>\n <p>Nested conditional code often is written by programmers who are taught to have one exit point from a method. I've found that is a too simplistic rule. When I have no further interest in a method,\n I signal my lack of interest by getting out. Directing the reader to look at an empty else block only gets in the way of comprehension.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:28:40.873",
"Id": "29128",
"ParentId": "29127",
"Score": "5"
}
},
{
"body": "<p>I would be compelled to write a helper that accepts a variable number of address fields and and returns true if all of the address fields are not null and not empty.</p>\n\n<pre><code>private boolean isShortAddress(AddressCriteria addressCriteria) {\n\n return hasFields( addressCriteria.getCity(), \n addressCriteria.getNumber(),\n addressCriteria.getState(),\n addressCriteria.getZipCode() );\n}\n\nprivate boolean hasFields( addressField... args )\n{\n for( addressField arg:args)\n {\n if( null == arg || arg.isEmpty() )\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>I did not test this code, but you should catch the drift.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T15:01:34.693",
"Id": "45936",
"Score": "2",
"body": "+1. This seems like a good approach because the null and isEmpty() checks are being carried out on all fields."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T19:49:57.210",
"Id": "45964",
"Score": "1",
"body": "And use a name shorter than `addressCriteria` if all you're going to do is use it four times in a row!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T17:44:32.010",
"Id": "47594",
"Score": "0",
"body": "Good idea, but the boolean logic is backwards. See my answer for an explanation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:34:14.160",
"Id": "29129",
"ParentId": "29127",
"Score": "35"
}
},
{
"body": "<p>A reasonable alternative to @tomdemuyt's answer would be to also change the class so that those getters will never return null, but instead return empty string. I personally hate using <code>null</code> when a NullObject will suffice (like empty string).</p>\n\n<p>I would move this method on to the <code>AddressCriteria</code> class, because it is a little better to ask an object about it's nature than to ask it a lot of details to decide it's nature with.</p>\n\n<p>Finally, you could make the AddressCriteria class immutable, so that those properties can't change. Then they get set in the constructor, and you could make this check once and keep a <code>boolean</code> field for <code>isShortFormAddress</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:17:30.417",
"Id": "45924",
"Score": "0",
"body": "`AddressCriteria` is from an existing API, I can't change it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T15:41:14.613",
"Id": "47589",
"Score": "0",
"body": "This code : `String s; s.isEmpty();` throw an Exception"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T15:31:06.557",
"Id": "47658",
"Score": "0",
"body": "Sure, the variable s is not initialized. You would need `String s = \"\";`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:00:05.743",
"Id": "29131",
"ParentId": "29127",
"Score": "2"
}
},
{
"body": "<p>An AddressCriteria should know when its address is short so move this behavior into AddressCriteria is a good idea. Using @tomdemuyt code:</p>\n\n<pre><code>public class AddressCriteria {\n\n public boolean isShortAddress() {\n return hasFields(getCity(), getNumber(), getState(), getZipCode());\n }\n\n private boolean hasFields(final String... fields) {\n for (String field : fields) {\n if (Strings.isNullOrEmpty(field)) { // from google guava\n return false;\n }\n }\n return true;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:18:56.930",
"Id": "45926",
"Score": "1",
"body": "I can't change `AddressCriteria` because it's from an existing API."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:59:06.650",
"Id": "45935",
"Score": "8",
"body": "It could be wrapped in another class though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:01:11.310",
"Id": "29132",
"ParentId": "29127",
"Score": "14"
}
},
{
"body": "<pre><code>. . .\nif( //\n Strings.isNullOrEmpty(addressCriteria.getCity()) && //\n Strings.isNullOrEmpty(addressCriteria.getNumber())&& // \n Strings.isNullOrEmpty(addressCriteria.getState()) && // \n Strings.isNullOrEmpty(addressCriteria.getZipCode())) {\n return true ;\n }\nreturn false;\n....\n</code></pre>\n\n<p>It seems difficult to have more readable presentation.</p>\n\n<p><strong>EDIT</strong> <em>after comment</em></p>\n\n<pre><code> public static final boolean isNullOrEmpty(final String s1) {\n if (null == s1 || s1.isEmpty()) {\n return true;\n }\n return false ;\n }\n</code></pre>\n\n<p>or more simple as Zack wrote :</p>\n\n<pre><code> public static final boolean isNullOrEmpty(final String s1) {\n return null == s1 || s1.isEmpty();\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T17:57:00.540",
"Id": "45951",
"Score": "0",
"body": "What about reversing the logic (pseudocoding the functions for brevity): `return !(nullOrEmpty(City) && nullOrEmpty(Number) && nullOrEmpty(State) && nullOrEmpty(ZipCode));`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T06:22:50.933",
"Id": "46000",
"Score": "0",
"body": "Not certain it is a good idea : in my mind, at the first `null` found withe the '`||`' the method return `false` BUT it have to test all (or at least two) '&&' between the `()` to verify the logic of the test"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T14:51:42.050",
"Id": "47584",
"Score": "0",
"body": "I think `Strings.isNullOrEmpty()` is from Guava or an external library, you didn't mention it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T15:12:41.537",
"Id": "47588",
"Score": "1",
"body": "@Marc-Andre Thanks, I've fogotten that is a home made tool."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T17:11:31.197",
"Id": "47591",
"Score": "0",
"body": "You got your boolean logic backwards — your solution is not equivalent to the code in the question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-21T06:38:32.397",
"Id": "47625",
"Score": "0",
"body": "@200_success Exact, corrected"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T14:40:30.493",
"Id": "29135",
"ParentId": "29127",
"Score": "1"
}
},
{
"body": "<p>First, <del><code>if (null != thing)</code> can and should always be simplified to <code>if (thing)</code>.<br>\n(Similarly, <code>if (null == thing)</code> can and should always be simplified to <code>if (!thing)</code>.)</del> <strong>EDIT:</strong> Apparently you can't do that in Java, OK (bleah). You should still know that this is preferred style in several closely-related languages where you <em>can</em> do that.</p>\n\n<p>Second, as several other people have pointed out, you have a repeated condition that should be factored into an <code>isNullOrEmpty</code> helper function.</p>\n\n<p>Third, the construction</p>\n\n<pre><code>if (condition)\n return true;\nreturn false;\n</code></pre>\n\n<p>is usually better written</p>\n\n<pre><code>return condition;\n</code></pre>\n\n<p>Putting it all together, we get</p>\n\n<pre><code>boolean isNullOrEmpty(String s)\n{\n return s == null || s.isEmpty();\n}\n\n// ...\n\nreturn (isNullOrEmpty(addressCriteria.getCity()) ||\n isNullOrEmpty(addressCriteria.getNumber()) || \n isNullOrEmpty(addressCriteria.getState()) || \n isNullOrEmpty(addressCriteria.getZipCode()));\n</code></pre>\n\n<p>Editorial aside: It is a bad code smell that the <code>addressCriteria</code> getters can return either <code>null</code> or an empty string. They should consistently pick one or the other to represent the absence of that field. However, you say that class can't be modified, so file that under \"technical debt\" and move on.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T02:51:21.580",
"Id": "45979",
"Score": "0",
"body": "Java doesn't have an equivalent for most uses of `const`, including `const*`. However, `final` in Java means that a pointer can't be reseated, i.e. the same as `x* const`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T04:35:41.870",
"Id": "45993",
"Score": "1",
"body": "Java only allows boolean expressions in conditionals. You can't replace `if (null != thing)` with `if (thing)`; the latter is a compile error."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:35:29.710",
"Id": "46034",
"Score": "0",
"body": "@Lstor Is Java default pass-by-reference? In C++ `foo(String s)` would *copy* `s`, and in particular it would be impossible for `s` to be `NULL`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:35:54.570",
"Id": "46035",
"Score": "0",
"body": "@IsmailBadawi Corrected, thanks. You can tell I'm not really a Java programmer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-30T13:48:48.170",
"Id": "46036",
"Score": "0",
"body": "Yes, Java uses reference semantics for everything but basic types (`int`, `char` and so on)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T20:09:39.753",
"Id": "29149",
"ParentId": "29127",
"Score": "-1"
}
},
{
"body": "<p>I think @tomdemuyt in on the right track, but unfortunately confused himself due to ambiguous method naming. Reading the logic in his <code>hasFields(...)</code> method, you'll see that it would be clearer to name it <code>hasAllOfFields(...)</code>. That's not what was wanted in the original question.</p>\n\n<p>Here is a corrected version of his solution:</p>\n\n<pre><code>private boolean isShortAddress(AddressCriteria addressCriteria) {\n return !hasAnyOfFields( addressCriteria.getCity(), \n addressCriteria.getNumber(),\n addressCriteria.getState(),\n addressCriteria.getZipCode() );\n}\n\nprivate boolean hasAnyOfFields(addressField... args) {\n for (addressField arg:args) {\n if (!(null == arg || arg.isEmpty()))\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>An alternative way to express that would be:</p>\n\n<pre><code>private boolean isShortAddress(AddressCriteria addressCriteria) {\n return hasNoneOfFields( addressCriteria.getCity(), \n addressCriteria.getNumber(),\n addressCriteria.getState(),\n addressCriteria.getZipCode() );\n}\n\nprivate boolean hasNoneOfFields(addressField... args) {\n for (addressField arg:args) {\n if (!(null == arg || arg.isEmpty()))\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>The second version reads better as English, but incorporating a negative sense into the helper method hurts its reusability, in my opinion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T17:43:19.850",
"Id": "47593",
"Score": "0",
"body": "@tomdemuyt should get most of the credit for the idea, and I considered just editing his post. However, I thought it would be important to leave the bug there for comparison as a cautionary tale to illustrate the danger of the ambiguous naming of `hasFields(...)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T19:12:01.723",
"Id": "47601",
"Score": "0",
"body": "I am fairly certain you are mistaken. A short address must have both city, number, state and zip. Your code returns true if any 1 of these fields is filled in."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T20:05:55.327",
"Id": "47604",
"Score": "0",
"body": "@tomdemuyt Read the original question again. If any of the fields is non-empty, it's *supposed* to return false. A short address must have *none* of those fields present. (I suppose that the presence of any one of those fields would make it a long address.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-20T17:40:23.493",
"Id": "30001",
"ParentId": "29127",
"Score": "2"
}
},
{
"body": "<p>You might want to be a little bit more defensive and check not just empty strings but blank ones too.\n<code>String.isEmpty()</code> returns <code>false</code> for string with only whitespace characters.</p>\n\n<p>Apache Commons Lang has a <a href=\"http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#isBlank%28java.lang.CharSequence%29\" rel=\"nofollow\"><code>StringUtils.isBlank</code></a> method for that.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:19:13.073",
"Id": "47103",
"ParentId": "29127",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "29129",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T13:18:39.580",
"Id": "29127",
"Score": "11",
"Tags": [
"java",
"validation"
],
"Title": "Check whether address criteria contain only certain fields or more"
}
|
29127
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.