body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have to reverse the string "He is the one" to "one the is He". I have written some programs in Java but am looking for other best solutions. Suggest any possible ways to minimize the current program.</p>
<p>First approach:</p>
<pre><code>class StringRev{
public static void main(String args[]){
String str = "He is the one";
String temp = "";
String finalString = "";
for(int i =str.length()-1;i>=0;i--){
temp +=i!=0?str.charAt(i):str.charAt(i)+" ";
if(str.charAt(i) == ' '||i==0){
for(int j=temp.length()-1;j>=0;j--){
finalString += temp.charAt(j);
}
temp = "";
}
}
System.out.println(finalString);
}
}
</code></pre>
<p>Second approach:</p>
<pre><code>class StringRev2{
public static void main(String args[]){
String str[] = "He is the one".split(" ");
String finalStr="";
for(int i = str.length-1; i>= 0 ;i--){
finalStr += str[i]+" ";
}
System.out.println(finalStr);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:30:03.720",
"Id": "61785",
"Score": "0",
"body": "If you are attempting to write as few characters as possible, you should instead go to [Code Golf](http://codegolf.stackexchange.com)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-26T17:11:53.677",
"Id": "63430",
"Score": "0",
"body": "related: [Efficiently reverse the order of the words (not characters) in an array of characters](http://stackoverflow.com/q/47402/4279)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-30T06:37:03.557",
"Id": "200980",
"Score": "0",
"body": "Could anyone explain why the second approach with double spaces in the split function gives us the desired result and using single space doesn't ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-31T17:34:03.867",
"Id": "201328",
"Score": "0",
"body": "basically with split function needs parameter how to break a string . Each word in string is separated by a single space , so I have used single space within double quotes ."
}
] |
[
{
"body": "<p>Here is a clean approach to reverse a string by its parts:</p>\n\n<pre><code>public class Main {\n\n // ReverseParts: reverses a string by words as opposed to characters.\n public static String ReverseParts(String input, String splitBy, String joinBy) {\n StringBuilder built = new StringBuilder();\n\n // Note: String.split uses regex. See its definition\n String[] list = input.split(splitBy);\n\n // Rejoin all the characters into a StringBuilder.\n for ( String part: list ) {\n built.insert(0, part);\n built.insert(0, joinBy);\n }\n\n // Remove the unnecessary 'joinBy bit'.\n built.delete(0, 1);\n\n // Get back the final string.\n return built.toString();\n }\n public static void main(String[] args) {\n final String input = \"Hello Johnny's World!\";\n\n System.out.println(\"Result: '\" + ReverseParts(input, \" +\", \" \")+\"'\");\n // Output:\n // Result: 'World! Johnny's Hello'\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T12:15:55.420",
"Id": "61888",
"Score": "0",
"body": "Dino's version is much better. Don't reinvent the wheel."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-14T11:04:58.900",
"Id": "217006",
"Score": "0",
"body": "Also don't capitalize the first character in method names. Java is not C# :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:00:49.193",
"Id": "37367",
"ParentId": "37364",
"Score": "1"
}
},
{
"body": "<p>\"Minimize\" is a really bad word to use when trying to consider the quality of your code. It's vague, and it can lead to undesirable outcomes, such as broken or unusable code.</p>\n\n<p>For example, is your goal to minimize the number of bytes used storing the source code on a hard drive? That might have been important when paper tape was a popular storage medium, but it's irrelevant today. It's so irrelevant that the difference between these two files is less than the size of a sector, so both actually occupy the same amount of storage space.</p>\n\n<p>Is your goal to reduce the number of CPU cycles spent? Given that cell phones have 100MHz processors these days, you need to do more work to figure out if the effort you expend thinking about the problem will ever be made up for in efficiency experienced by your users. If this is run once or twice, efficiency simply is not important. On the other hand, if it could ever become part of a networking protocol, efficiency is extremely important. Quite honestly, English word reversal seems to be too specialized to fit the test of practicality for efficiency.</p>\n\n<p>In general, what most people should be striving for in their code is \"correctness\" and \"clarity\". You want to know that it works correctly in all situations. The answer to that is to write unit tests. For clarity, you want the code to be readable, understandable, and usable. Make sure you have chosen good names. Modularize the functions. For example, you should consider extracting the dependency on System.out.println, as outputting the string has nothing to do with reversing the string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:05:14.283",
"Id": "37368",
"ParentId": "37364",
"Score": "11"
}
},
{
"body": "<p>In your first approach you have the right idea of starting at the end of the String and working backwards. The issues you have are:</p>\n\n<ul>\n<li>you should use StringBuilder instead of String concatenation....</li>\n<li>using a <code>temp</code> string which you add-to in reverse order, then reverse again in to the result is a slow approach .... but effective.</li>\n<li>you should be doing it more than 1 character at a time.</li>\n</ul>\n\n<p>In your second approach, I don't like:</p>\n\n<ul>\n<li>you have string concatenation again <strong>use</strong> a <code>StringBuilder()</code></li>\n<li>you assume all spaces are 'equal'... what about multi-space breaks <code>\"Hello There\"</code> with this code will become <code>\"There Hello\"</code></li>\n</ul>\n\n<p>So, with a small adjustment to your regular expression (perhaps <code>\"\\\\b\"</code> ...) and conversion to StringBuilder, I think the second option is good.</p>\n\n<p>The first option, if written right, will be faster than the split one (although the code is longer)....</p>\n\n<p>Here's an attempt at doing it by first principles:</p>\n\n<pre><code>private static String reverse(String string) {\n if (string.isEmpty()) {\n return string;\n }\n int last = string.length();\n StringBuilder sb = new StringBuilder(string.length());\n boolean contextspace = ' ' == string.charAt(string.length() - 1);\n for (int i = string.length() - 1; i >= 0; i--) {\n if (contextspace != (string.charAt(i) == ' ')) {\n sb.append(string.substring(i + 1, last));\n last = i + 1;\n contextspace = !contextspace;\n }\n }\n sb.append(string.substring(0, last));\n return sb.toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-08-13T18:33:32.547",
"Id": "327801",
"Score": "0",
"body": "this is a brilliant solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T18:32:17.387",
"Id": "37371",
"ParentId": "37364",
"Score": "6"
}
},
{
"body": "<p>There are many ways to do this, depending on what you're going for.</p>\n\n<p>If you're stuck with Java, then probably look to Apache commons:</p>\n\n<pre><code>StringUtils.reverseDelimited(st, ' ');\n</code></pre>\n\n<p>Try using Scala if you can, which is nicer in so many ways:</p>\n\n<pre><code>st.split(\" \").reverse.mkString(\" \")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T00:20:23.163",
"Id": "61848",
"Score": "0",
"body": "http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverseDelimited(java.lang.String, char)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T00:19:42.693",
"Id": "37388",
"ParentId": "37364",
"Score": "2"
}
},
{
"body": "<p><strong>Approach 1:</strong></p>\n\n<p>JDK provides <code>java.util.StringTokenizer</code> to do the split or tokenizing a given text. This API helps avoid going character by character. No external jar/libraries required. Tokenizing gives you each separated word as an array element that you could print in reverse. </p>\n\n<pre><code>import java.util.ArrayList;\nimport java.util.StringTokenizer;\n\n\npublic class reverseString {\n public static void main(String args[])\n {\n StringTokenizer st = new StringTokenizer(\"this is a string\");\n ArrayList<String> arrLstStrings = new ArrayList<>();\n while (st.hasMoreTokens()) {\n arrLstStrings.add(st.nextToken());\n }\n\n for(int loop=arrLstStrings.size()-1;loop>=0;loop--)\n System.out.println(arrLstStrings.get(loop));\n }\n}\n</code></pre>\n\n<p><strong>Approach 2:</strong></p>\n\n<pre><code>import java.util.regex.*;\n\npublic class reverseString {\n public static void main(String args[])\n{\n String strSource = \"This is a string\";\n // give a max int as limit in next stmt.\n String[] tokens = Pattern.compile(\" \").split(strSource,15) ;\n for (int loop=tokens.length-1;loop>=0;loop--)\n System.out.println(tokens[loop]);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:29:14.993",
"Id": "61878",
"Score": "0",
"body": "Are you sure what are you doing? This will not reverse the string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T13:15:18.153",
"Id": "61889",
"Score": "0",
"body": "additionally, you suggest StringTokenizer, but use Regex/split"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T09:41:17.187",
"Id": "37405",
"ParentId": "37364",
"Score": "-3"
}
},
{
"body": "<p>Stuffing all your code into <code>main()</code> is bad practice. This functionality belongs in a function of its own.</p>\n\n<p>When doing multiple string concatenations, you really want to use a <code>StringBuilder</code>. If you don't, the compiler will make one for you anyway, <em>every time you concatenate two strings using +</em>. It's better to do it explicitly, then, and control how many of those temporary objects are created.</p>\n\n<hr>\n\n<p>Your first approach works a character at a time. I suggest the following character-at-a-time approach, which allocates just one large temporary buffer.</p>\n\n<pre><code>private static void reverse(char[] buf, int start, int end) {\n for (int i = start, j = end - 1; i < j; i++, j--) {\n char swap = buf[i];\n buf[i] = buf[j];\n buf[j] = swap;\n }\n}\n\npublic static String reverseWords1(String sentence) {\n char[] buf = sentence.toCharArray();\n\n // Reverse the string, character-wise\n reverse(buf, 0, buf.length);\n\n // Within each word, reverse the characters again\n int wordEnd = 0;\n for (int wordStart = 0; wordStart < buf.length; wordStart = wordEnd + 1) {\n for (wordEnd = wordStart; wordEnd < buf.length && buf[wordEnd] != ' '; wordEnd++) {}\n\n // wordStart is at the start of a word.\n // wordEnd is just past the end of the word.\n reverse(buf, wordStart, wordEnd);\n }\n return new String(buf);\n}\n</code></pre>\n\n<hr>\n\n<p>I prefer your second approach, which is more succinct. Here it is, cleaned up by using a <code>StringBuilder</code>.</p>\n\n<pre><code>public static String reverseWords2(String sentence) {\n StringBuilder sb = new StringBuilder(sentence.length() + 1);\n String[] words = sentence.split(\" \");\n for (int i = words.length - 1; i >= 0; i--) {\n sb.append(words[i]).append(' ');\n }\n sb.setLength(sb.length() - 1); // Strip trailing space\n return sb.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T11:48:00.157",
"Id": "37407",
"ParentId": "37364",
"Score": "9"
}
},
{
"body": "<h2>Re-use existing code.</h2>\n\n<p>Libraries allow for maximum re-use. Use them!</p>\n\n<p>If you don't like libraries, try to re-use as much as Java offers. Look up documentation, examples, etc.</p>\n\n<ul>\n<li>Splitting strings is java default <code>split()</code></li>\n<li>Reversing can be done with the excellent <code>Collections</code> class</li>\n<li>Java8 has some nice String join stuff. </li>\n</ul>\n\n<p>I also try to make the code as readable as possible by having short statements and avoiding loops (for, while, etc) when you don't need them.</p>\n\n<p>My approach:</p>\n\n<pre><code>public static String reverseWords (String s) \n{\n String delimiter = \" \";\n List<String> words = Arrays.asList(s.split(delimiter));\n Collections.reverse(words);\n return String.join(delimiter, words);\n}\n\npublic static void main(String[] args) \n{\n System.out.println(reverseWords(\"He is the one\"));\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-14T09:36:37.060",
"Id": "116763",
"ParentId": "37364",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37407",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:21:13.557",
"Id": "37364",
"Score": "11",
"Tags": [
"java",
"algorithm",
"strings"
],
"Title": "Reversing words in a string"
}
|
37364
|
<p>I have an image loader, now only for bitmaps. I'm a little confused because I want to split my code to different classes, one for writing a BMP data to a file (<em>WRITER</em>), one for loading BMP data from file, or from pre-generated dataset <em>(1)</em> and storing it in its private members.<em>( (1) like a noise function saved to an array)</em>.</p>
<p>Currently I have the 2 class for this. The header:</p>
<pre><code>namespace PND
{
inline void out(const ::std::string); //standard output log
inline void err(const ::std::string); //error log
bool file_exists(::std::string m_filename) //this could be used in both classes
{
::std::ifstream infile(m_filename+".bmp");
return infile.good();
}
class BMP
{
public:
BMP();
BMP(const BMP&);//copy csrt
~BMP();
BMP& operator= (BMP other); //ass. operator
bool loadData(::std::string filename);//from file, filename is the file's filename
bool loadData(::std::string filename,const int width, const int height, const unsigned char* data, const unsigned int length);//from array, filename is user defined
//they are simple pixel data accessors with out of bounds handling
unsigned char getData_B(const unsigned int x, const unsigned int y);
unsigned char getData_G(const unsigned int x, const unsigned int y);
unsigned char getData_R(const unsigned int x, const unsigned int y);
unsigned int* getSize() { return m_size; }; //some getter
::std::string getName() { return m_filename; };
private:
void swap(BMP& other);
void freeData();
//the bitmap data:
BITMAPINFOHEADER m_infoheader;
BITMAPFILEHEADER m_fileheader;
::std::string m_filename;
unsigned char* m_data;
unsigned int m_size[2];
long __m_size; //it is the length of the m_data array (num of pixels * 3)
};
class WRITER
{
public:
bool writeData(::std::string filename, const int width, const int height, const unsigned char* data, const unsigned int length);
bool writeData(::std::string filename, const BMP& bmp);//now this is the problem, more info below the code
private:
::std::ofstream outstream;
bool openFile(::std::string filename);
bool writeHeader(const int width,const int height);
bool writeFile(const unsigned char* data, const unsigned int length);
bool closeStream();
};
}
</code></pre>
<p>I'm in trouble because <strong>I would like to access (read only) the bitmap data (headers, pixel data) from the image - that was saved to a <code>BMP</code> object - in the <code>WRITER</code> class.</strong> But because they are private members I can not access them in the <code>writeheader()</code> and <code>writefile()</code> functions. It would be nice to access them without making them public members, and I also try to avoid using inheritance in this case since a <strong><code>WRITER</code> is not really a <code>BMP</code></strong>. Lots of <code>getters</code>are also not the best way for accessing arrays I think.</p>
<p>So the <code>BMP</code> could only load and save the image data. And with a <code>WRITER</code> I can write this data to a .bmp file. I want to make a pretty clean interface with public functions, and do not mix classes if not neccessary.</p>
|
[] |
[
{
"body": "<p>The only standard ways to access private data from another class are:</p>\n\n<ol>\n<li>Getters </li>\n<li>Friend class</li>\n</ol>\n\n<p>If you want to make a friend class, just do something like this:</p>\n\n<pre><code>class Writer ;\n\nclass BMP\n{\n //...\nprivate:\nfriend class Writer ;\n}\n</code></pre>\n\n<p>Now the <code>Writer</code> class can access all of <code>BMP</code>'s data fields. </p>\n\n<p>I would personally suggest using getters though. You could have getters for the header information and use <code>operator []</code> for accessing any arrays.</p>\n\n<pre><code>unsigned char& BMP::operator [] (const size_t i) {\n return m_data [i] ;\n}\n\nconst unsigned char& BMP::operator [] (const size_t i) const {\n return m_data [i] ;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:51:30.047",
"Id": "61883",
"Score": "0",
"body": "+1 I've never used overloaded []. That's seems much better for accessing arrays thanks! Also, friend functions are the way to go, I think so(never really used them)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:11:37.593",
"Id": "37382",
"ParentId": "37365",
"Score": "3"
}
},
{
"body": "<p>Is there a reason the <code>WRITER</code> class can't be static (i.e. just have all static methods) and then put a <code>write()</code> function in the <code>BMP</code> class that would just call the static writer methods? You would have to create an overload to take all the private members you would want to pass in (i.e. a write method to take in file name and a <code>const BITMAPINFOHEADER&</code> or whatever you might need). Otherwise a friend function (as red_eight mentioned) would be the way to go in your case.</p>\n\n<p>Alternatively if you are trying to separate your classes into a sort of hierarchical reader/writer structure, a possibility would be to have a base <code>BMP</code> class that has all the necessary info (like headers, size, filename etc) then having 2 separate classes derived from it, for example using your code:</p>\n\n<pre><code>namespace PND\n{\n inline void out(const ::std::string); //standard output log\n inline void err(const ::std::string); //error log\n\n bool file_exists(::std::string m_filename) //this could be used in both classes\n {\n ::std::ifstream infile(m_filename+\".bmp\");\n return infile.good();\n }\n\n class BMP\n {\n public:\n BMP();\n BMP(const BMP&);//copy csrt\n virtual ~BMP();\n BMP& operator= (BMP other); //ass. operator\n\n //they are simple pixel data accessors with out of bounds handling\n unsigned char getData_B(const unsigned int x, const unsigned int y);\n unsigned char getData_G(const unsigned int x, const unsigned int y);\n unsigned char getData_R(const unsigned int x, const unsigned int y);\n\n unsigned int* getSize() { return m_size; }; //some getter\n ::std::string getName() { return m_filename; };\n\n protected:\n //the bitmap data:\n BITMAPINFOHEADER m_infoheader;\n BITMAPFILEHEADER m_fileheader;\n ::std::string m_filename;\n unsigned char* m_data;\n unsigned int m_size[2];\n long __m_size; //it is the length of the m_data array (num of pixels * 3)\n private: // NOTE: not sure if these would be private or in BMP_READER\n void swap(BMP& other);\n void freeData();\n };\n\n class BMP_READER : virtual public BMP\n {\n public:\n bool loadData(::std::string filename);//from file, filename is the file's filename\n bool loadData(::std::string filename, const int width, const int height, const unsigned char* data, const unsigned int length);//from array, filename is user defined\n }\n\n class BMP_WRITER : virtual public BMP\n {\n public:\n static bool writeData(::std::string filename, const int width, const int height, const unsigned char* data, const unsigned int length);\n bool writeData(); // already have 'm_filename' and access to base BMP\n\n private:\n ::std::ofstream outstream;\n\n bool openFile(::std::string filename);\n bool writeHeader(const int width,const int height);\n bool writeFile(const unsigned char* data, const unsigned int length);\n bool closeStream();\n };\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:49:40.087",
"Id": "61882",
"Score": "0",
"body": "Thanks for the answer, I'm gonna use friend functions/classes for this. I've not really used them, but I think its the best solution. +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:53:42.527",
"Id": "61885",
"Score": "1",
"body": "Sounds good, sometimes they really are the best answer to a solution; check out [this link](http://www.cprogramming.com/tutorial/friends.html) for a good example on friend functions if you might need it :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T06:25:01.393",
"Id": "37397",
"ParentId": "37365",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37382",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:25:50.110",
"Id": "37365",
"Score": "3",
"Tags": [
"c++",
"design-patterns",
"classes",
"image"
],
"Title": "Image loader/writer design (no API, pure C++ on Windows)"
}
|
37365
|
<p>I am writing a flask app that I will deploy it on Heroku to test it. There is a page that will generate daily photos and information based on a JSON file. The view is valid for 24 hours beginning from 00:00 to 23:59 of everyday.</p>
<p>I am thinking about using a cache, otherwise the app will consume unnecessary resources.</p>
<pre><code>import ..
TODAY = date.today()
app = Flask(__name__)
app.jinja_env.auto_reload = False
cache = Cache(config={'CACHE_TYPE': 'simple', 'CACHE_ARGS' : TODAY})
#This function reads a json file, filter the daily data to process and render a html template with photos and text .
# 3600 * 24 = 86400
@cache.cached(timeout=86400)
@app.route('/inf')
def inf():
input_file = open(os.path.join(__location__, 'json/output.json'));
j = json.loads(input_file.read().decode("utf-8-sig"))
etc ..
return render_template('inf.html',
title = title,
config={'environment_args':{'autoescape':False}},
zipped =zipped)
if __name__ == '__main__':
if TODAY != cache.config['CACHE_ARGS'] :
with app.app_context():
cache.clear()
port = int(os.environ.get('PORT', 33507))
app.run(debug = True, host='0.0.0.0', port=port)
</code></pre>
<p>I am not sure if this is the best solution to cache the view for a day. That's why I am asking here for more suggestions.</p>
|
[] |
[
{
"body": "<p>Why not take advantage of the RESTful architecture of the internet? I suggest you have the code generate a static page and set the expires header on that resource (or set of resources) to the end of that day (considering your audience's time zones, I guess). <a href=\"https://devcenter.heroku.com/articles/increasing-application-performance-with-http-cache-headers\" rel=\"nofollow\">This</a> might help.</p>\n\n<p>Sorry, if I had experience with heroku or flask I would provide code or more details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T01:03:53.650",
"Id": "74515",
"Score": "0",
"body": "A lot of activity out of you recently, feel free to come join us on our [chat room](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) sometime! :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T00:52:17.590",
"Id": "43188",
"ParentId": "37366",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T17:57:36.097",
"Id": "37366",
"Score": "4",
"Tags": [
"python",
"cache",
"flask"
],
"Title": "Caching a function view for a day"
}
|
37366
|
<p>I'm trying to make a scala interface to the spotify API. I'm using it to learn Scala. I come from mostly a python background.</p>
<pre><code>import dispatch._, Defaults._
trait Request {
val name: String
val endpoint: String
}
case class Track(name: String) extends Request {
override val endpoint = "track.json"
}
case class Album(name: String) extends Request {
override val endpoint = "album.json"
}
case class Artist(name: String) extends Request {
override val endpoint = "artist.json"
}
object Spotify {
def getResponse(req: Request) = {
val params = Map("q" -> req.name)
val spotifyUrl = host("ws.spotify.com")
spotifyUrl / "search"/ "1" / req.endpoint <<? params
}
val foo = Album("foo")
val songs = Http(getResponse(foo) OK as.String)
}
</code></pre>
<p>I feel like <code>getResponse</code> should be in the Request trait, or something since it's generic enough to only need the overridden <code>endpoint</code> - but not sure.
Any general recommendations on structuring this sort of thing would be helpful.</p>
|
[] |
[
{
"body": "<p>Decouple everything.</p>\n\n<p>I am certain that Scala veterans will have more to say than I do and possibly comment over my comments.</p>\n\n<p>Here are some changes and respective comments to your code.</p>\n\n<pre><code>import dispatch._, Defaults._\n\n// decouple from any \"master\" class.\ncase class Track(name: String)\n\ncase class Album(name: String)\n\ncase class Artist(name: String)\n\n// This is called a structural type. We are using a def\n// because a val restricts extensibility.\ntype Named = {def name: String}\n\n// Separate out the endpoints into their own category\nobject endpointResolver {\n\n // Use a partial function which you can re-use in order parts\n // of your program. You may use this in your testing as well.\n val endPoints: PartialFunction[Named, String] = {\n case _: Track => \"track.json\"\n case _: Album => \"album.json\"\n case _: Artist => \"artist.json\"\n }\n\n // use an implicit class. This allows you to add methods\n // to existing classes seamlessly.\n implicit class nrEndpoint(namedRequest: Named) {\n def endpoint: String =\n endPoints apply namedRequest\n }\n\n}\n\nobject Spotify {\n\n // Specify the return type. I was not sure what it was initially.\n def getResponse(req: Named): Req = {\n\n val params = Map(\"q\" -> req.name)\n\n val spotifyUrl = host(\"ws.spotify.com\")\n\n // import and utilise this implicit class\n import endpointResolver.nrEndpoint\n\n spotifyUrl / \"search\"/ \"1\" / req.endpoint <<? params\n\n }\n\n val foo = Album(\"foo\")\n\n // OK is another example of an implicit being used. Use an IDE\n // such as IntelliJ IDEA to navigate through the vast depths\n // of Scala source.\n val songs = Http(getResponse(foo) OK as.String)\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T22:35:04.473",
"Id": "61833",
"Score": "0",
"body": "Very interesting, thanks for the code (and more for the comments). Lots of stuff to play with here.\n\nI'm not going to accept for a bit uncase like you say a veteran comes in, but will if that doesn't happen."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T21:58:14.910",
"Id": "37377",
"ParentId": "37375",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37377",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T21:21:41.233",
"Id": "37375",
"Score": "2",
"Tags": [
"scala"
],
"Title": "Interface for Spotify API"
}
|
37375
|
<p>How would one optimize this code? </p>
<pre><code>import java.util.*;
public class VendingMachineAssignement {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double item1 = 1.25;
double item2 = .75;
double item3 = .90;
double item4 = .75;
double item5 = 1.50;
double item6 = .75;
System.out.print("Enter an item number: ");
int item = keyboard.nextInt();
System.out.print("Enter the amount paid: ");
double paid = keyboard.nextDouble();
if (item == 2 || item == 4 || item == 6)
{
if (paid >= item2)
{
System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item2) + ". Please come again!");
}
if (paid < item2)
{
System.out.println("Please insert another " + "$" + (item2-paid));
}
}
else if (item == 1)
{
if (paid >= item1)
{
System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item1) + ". Please come again!");
}
if (paid < item1)
{
System.out.println("Please insert another " + "$" + (item1-paid));
}
}
else if (item == 3)
{
if (paid >= item3)
{
System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item3) + ". Please come again!");
}
if (paid < item3)
{
System.out.println("Please insert another " + "$" + (item3-paid));
}
}
else if (item == 5)
{
if (paid >= item5)
{
System.out.println("Thank you for buying item " + item + ", your change is $" + (paid-item5) + ". Please come again!");
}
if (paid < item5)
{
System.out.println("Please insert another " + "$" + (item5-paid));
}
}
}
}
</code></pre>
<p>And also, for example, if I enter <code>5</code> for <code>item</code> and <code>.10</code> for <code>paid</code>, then why does it say <code>Please insert another $1.4</code> instead of 1.40? Even though 1.50 - 1.4 and 1.50 - 1.40 would be the same, how come it does not display <code>1.40</code>?</p>
|
[] |
[
{
"body": "<h2>Things I would fix:</h2>\n\n<p>All of your condition test statements do exactly the same thing. </p>\n\n<blockquote>\n<pre><code>else if (item == 1)\n{\n if (paid >= item1) \n {\n System.out.println(\"Thank you for buying item \" + item + \", your change is $\" + (paid-item1) + \". Please come again!\");\n }\n if (paid < item1)\n {\n System.out.println(\"Please insert another \" + \"$\" + (item1-paid));\n }\n}\nelse if (item == 3)\n{\n if (paid >= item3) \n {\n System.out.println(\"Thank you for buying item \" + item + \", your change is $\" + (paid-item3) + \". Please come again!\");\n }\n if (paid < item3)\n {\n System.out.println(\"Please insert another \" + \"$\" + (item3-paid));\n }\n}\n...\n</code></pre>\n</blockquote>\n\n<p>You can use arrays to help solve this issue.</p>\n\n<pre><code>double[] prices = new double[] { 1.25, 0.75, 0.9, 0.75, 1.5, 0.75 };\n</code></pre>\n\n<p>Then you can access those specific values with <code>prices[item - 1]</code>. Remember that arrays start with the index <code>0</code>, so without subtracting 1 you will end up with an <a href=\"https://en.wikipedia.org/wiki/Off-by-one_error\" rel=\"nofollow noreferrer\">off-by-one error</a>. The comparison is now simplified.</p>\n\n<pre><code>if (paid >= (prices[item - 1]))\n{\n System.out.println(\"Thank you for buying item \" + item + \", your change is \" + (paid - prices[item - 1]) + \". Please come again!\");\n}\n</code></pre>\n\n<hr>\n\n<p>You ask the user to insert more money, but never actually allow him to.</p>\n\n<blockquote>\n<pre><code>if (paid < item2)\n{\n System.out.println(\"Please insert another \" + \"$\" + (item2-paid));\n}\n</code></pre>\n</blockquote>\n\n<p>This can easily be solved with a <code>while</code> loop and another pair of input request statements.</p>\n\n<hr>\n\n<p>You never close your <code>Scanner</code> when you are finished with it (a memory issue).</p>\n\n<pre><code>keyboard.close();\n</code></pre>\n\n<hr>\n\n<p>You never check if the item you buy is actually within the bounds of the array length.</p>\n\n<pre><code>if (!(item <= prices.length))\n{\n System.out.println(\"Sorry, we don't have that item in stock.\");\n keyboard.close();\n return;\n}\n</code></pre>\n\n<hr>\n\n<p>When working with money, it is hard to work with <code>doubles</code>, they are too imprecise. An example of this is that <code>0.42 - .21</code> is likely something like <code>0.209999999999999997</code> rather than <code>0.21</code> exactly. </p>\n\n<p>We are going to use the <a href=\"http://docs.oracle.com/javase/7/docs/api/java/text/NumberFormat.html\" rel=\"nofollow noreferrer\"><code>NumberFormat</code></a> class to make sure that the our <code>double</code> values will stay accurate.</p>\n\n<pre><code>NumberFormat.getCurrencyInstance().format(number)\n</code></pre>\n\n<hr>\n\n<h2>Recommendations that are optional:</h2>\n\n<p>Don't do this:</p>\n\n<blockquote>\n<pre><code>import java.util.*;\n</code></pre>\n</blockquote>\n\n<p>It could be problematic for the compiler to import a bunch of packages at once. If two packages provide the same type, both are imported, and the type is used in the class, a compile-time error occurs. This is described in <a href=\"http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#32799\" rel=\"nofollow noreferrer\">JLS 6.5.5.1</a>:</p>\n\n<blockquote>\n <p>Otherwise, if a type of that name is declared by more than one type-import-on-demand declaration of the compilation unit, then the name is ambiguous as a type name; a compile-time error occurs.</p>\n</blockquote>\n\n<p>In addition, it also saves a bit of memory. And your IDE (if you use one), should have the ability to do this automatically.</p>\n\n<hr>\n\n<p>You might note that this:</p>\n\n<pre><code>public static void main(String... args)\n</code></pre>\n\n<p>Is a bit different than your usual:</p>\n\n<blockquote>\n<pre><code>public static void main(String[] args)\n</code></pre>\n</blockquote>\n\n<p>They both do the same thing, but one uses <a href=\"https://stackoverflow.com/questions/2925153/can-i-pass-an-array-as-arguments-to-a-method-with-variable-arguments-in-java/2926653#2926653\">variable arity parameters</a>.</p>\n\n<hr>\n\n<p>The <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29\" rel=\"nofollow noreferrer\"><code>Scanner.nextInt()</code></a> method does not read the <em>last newline</em> character of your input, and thus a <em>newline</em> could be consumed if you call <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29\" rel=\"nofollow noreferrer\"><code>Scanner.nextLine</code></a>. I prefer to use <code>Scanner.nextLine</code> since you can input any valid <code>String</code>, and then just parse it into the type you need (as long as it's a valid type to parse it to).</p>\n\n<hr>\n\n<h2>Final code:</h2>\n\n<pre><code>import java.text.NumberFormat;\nimport java.util.Scanner;\n\npublic class Test\n{\n public static void main(String... args)\n {\n Scanner keyboard = new Scanner(System.in);\n double[] prices = new double[] { 1.25, 0.75, 0.9, 0.75, 1.5, 0.75 };\n int item = 0;\n\n System.out.print(\"Enter an item number: \");\n item = Integer.parseInt(keyboard.nextLine());\n if (!(item <= prices.length))\n {\n System.out.println(\"Sorry, we don't have that item in stock.\");\n keyboard.close();\n return;\n }\n\n System.out.print(\"Enter the amount paid: \");\n double paid = Double.parseDouble(keyboard.nextLine());\n\n while (paid < (prices[item - 1]))\n {\n System.out.print(\"You need \" + NumberFormat.getCurrencyInstance().format(Math.abs((paid - prices[item - 1]))) + \" more for item \" + item);\n paid += Double.parseDouble(keyboard.nextLine());\n }\n System.out.println(\"Thank you for buying item \" + item + \", your change is \" + NumberFormat.getCurrencyInstance().format((paid - prices[item - 1])) + \". Please come again!\");\n\n keyboard.close();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T00:45:02.850",
"Id": "61849",
"Score": "1",
"body": "`keyboard.close();` - why? It'll just get collected when the function ends, which is the very next thing that happens."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T00:50:27.517",
"Id": "61850",
"Score": "1",
"body": "You say that it's hard to work with doubles, but you don't really fix the problem; you just change how they're displayed. If the user puts in 30 cents 3 times, this program will think the user still needs to input a tiny fraction of a nanocent to pay for item 3."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T01:38:23.203",
"Id": "61852",
"Score": "2",
"body": "@user2357112 - `keyboard` *goes out of scope* when the method terminates, but the GC choose when to clean it up. In a tiny program like this, that will occur immediately when the program itself terminates, but you never know in a longer-running program. Better to pick up good habits early."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T02:19:28.963",
"Id": "61854",
"Score": "0",
"body": "@DavidHarkness: Yeah, that was a mistake; I should have said it becomes collectable when the function ends. Even if you close it, the GC *still* decides when to collect the resources, so closing it won't help with memory. The only effect it has is closing `System.in`, and I don't know whether or not that counts as a positive."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T02:30:24.463",
"Id": "61855",
"Score": "0",
"body": "@user2357112 - True, but if the scanner were backed by a file rather than `System.in`, the file's input stream is closed immediately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T03:05:45.437",
"Id": "61858",
"Score": "2",
"body": "`Then you can access those specific values with prices[item - 1]. Remember that arrays start with the index 0, so without subtracting 1 you will end up with an off-by-one error.` - Or you can put a dummy value at `price[0]`, so item matches index. It's what I tend to do in anything more complex than this, so you don't have to mix'n'match for comparisons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T11:58:13.060",
"Id": "61887",
"Score": "0",
"body": "I don't see much of a problem with `import java.util.*`. The classes in that package are very well known; name clashes are highly unlikely (`java.sql.Date` aside), and I'd argue that `java.util` deserves priority naming rights anyway. Also, the `import` makes no difference to the program's runtime performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T19:05:05.570",
"Id": "61925",
"Score": "0",
"body": "@syb0rg: You should probably add something to check against the hilariously easy to hit array overflow condition."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T03:56:52.657",
"Id": "61996",
"Score": "0",
"body": "@syb0rg: Enter an item number of 15."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T22:07:56.443",
"Id": "37379",
"ParentId": "37376",
"Score": "21"
}
},
{
"body": "<p>To start of, if using amount of variables of the same data-type, the appropriate way of doing such a thing is an Array; specific case, double [] prices;</p>\n\n<p>An array will allow you to keep a reference to all your values and allowing you to make a single if-else instead of each for every item.\nDemo:<BR></p>\n\n<pre><code>double [] prices = {1.25, 0.75, 0.90, 0.75, 1.50, 0.75};\nSystem.out.print(\"Enter an item number: \");\nint item = keyboard.nextInt();\nSystem.out.print(\"Enter the amount paid: \");\ndouble paid = keyboard.nextDouble();\nif (paid >= prices[item-1])\n System.out.println(\"Thank you for buying item \" + item + \", your change is $\" + (paid-prices[item-1]) + \". Please come again!\");\nelse\n System.out.println(\"Please insert another \" + \"$\" + (prices[item-1]-paid));\n</code></pre>\n\n<p>you could make a helper function to add another zero to a string if you want to, like you wanted in 1.4 to become 1.40, another way is to use String.format(\"%.2f\",(paid-prices[item-1])); to get the string.</p>\n\n<p>Hope that helps.\nPlease ask if anything isn't clear.</p>\n\n<p>EDIT: changed to output to decremented value of item since an Array starts with 0, and user's requested first item to be 1.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T22:21:10.407",
"Id": "61830",
"Score": "2",
"body": "initializing the array can be done like this: `double[] prices = new double[]{ 1.25, 0.75, 0.9, 0.75, 1.5, 0.75 };`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T22:22:25.213",
"Id": "61831",
"Score": "0",
"body": "Changed due to suggestion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T22:23:03.637",
"Id": "61832",
"Score": "0",
"body": "Sorry, damn Firefox submitted the comment when I fixed spelling. See the edit of the comment :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T22:17:12.313",
"Id": "37380",
"ParentId": "37376",
"Score": "8"
}
},
{
"body": "<p>Here is a block of code with comments below.</p>\n\n<p>Always consider exceptional cases. That is a crucial part of programming.</p>\n\n<pre><code>// Only import what you need.\nimport java.util.InputMismatchException;\nimport java.util.Scanner;\n\npublic class Main {\n\n public static void main(String[] args) {\n\n Scanner keyboard = new Scanner(System.in);\n\n // Use an array if you have a list.\n double[] itemPrices = {1.25, .75, .90, .75, 1.50, .75};\n\n // This array starts from 0 end ends at 5.\n // Corresponding to item #1 to #6.\n int maxItem = itemPrices.length;\n\n // Have we been given an item that is Ok yet?\n boolean itemFound = false;\n\n // We have not been provided an item # yet. This will have to be non-null\n // once we exit the do-while statement below.\n Integer item = null;\n\n // read an item number until an existing item is found.\n do {\n System.out.print(\"Enter an item number: \");\n try {\n item = keyboard.nextInt();\n if ( item >= 1 && item <= maxItem ) {\n itemFound = true;\n } else {\n // Inform the user of the problem. Give them another chance.\n // String.format is very neat stuff. Use it.\n String message = String.format(\"Unfortunately, item #%d does not exist.\", item);\n System.out.println(message);\n }\n\n // note how an exception is raised when we get an invalid input.\n // you must consider what happens when the input is invalid.\n } catch (InputMismatchException e) {\n System.out.println(\"Bad input. Try again.\");\n keyboard.next();\n }\n } while (!itemFound);\n\n\n Double paid = null;\n do {\n System.out.print(\"Enter the amount paid: \");\n try {\n paid = keyboard.nextDouble();\n } catch (InputMismatchException e) {\n System.out.println(\"Bad input. Try again.\");\n keyboard.next();\n }\n } while (paid == null);\n\n double itemValue = itemPrices[item-1];\n\n double change = paid - itemValue;\n\n double moneyNeeded = 0 - change;\n\n if ( moneyNeeded > 0 ) {\n // We can inform the user what the problem was. And again the String.format magic.\n String message = String.format(\"Please insert another $%.2f.%n\", moneyNeeded);\n System.out.println(message);\n\n // But this time, we will gracefully exit.\n System.exit(0);\n }\n\n String message = String.format(\"Thank you for buying item #%d, your change is $%.2f. Please come again!\", item, change);\n\n System.out.println(message);\n\n }\n\n}\n</code></pre>\n\n<p>Would be much prettier if done using the Scala programming language.\nThose loops could be replaced with tail recursion, absolutely no mutability (mutability is not pretty, but immutability is harder to do in Java).</p>\n\n<p><strong>Edit:</strong> Exercise for the reader: fix the <code>moneyNeeded</code> <code>if</code>-statement to have the correct \"business\"-logic. At the moment it quits having eaten all your money.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T22:29:00.160",
"Id": "37381",
"ParentId": "37376",
"Score": "7"
}
},
{
"body": "<p>Using floating-point data types to represent money is <a href=\"https://stackoverflow.com/q/3730019/1157100\">bad practice</a>, due to the inability to represent some rational numbers in binary. Either use <code>java.math.BigDecimal</code> or work in cents instead of dollars.</p>\n\n<p>Parsing a string representation of dollars and cents directly into an integer number of cents, is slightly tricky. One approach is to use <a href=\"https://stackoverflow.com/a/2408469/1157100\"><code>BigDecimal</code></a> to help with the parsing and conversion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T12:25:37.330",
"Id": "37409",
"ParentId": "37376",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "37379",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T21:48:30.483",
"Id": "37376",
"Score": "14",
"Tags": [
"java",
"console"
],
"Title": "Vending machine implementation"
}
|
37376
|
<p>I'm building an http handler at work which has about 6 methods and I'm trying to figure out what design pattern will work the best for my needs:</p>
<p>What's done already (Only an example to make this more clear, methods are not real, but the main concept is there):</p>
<pre><code>#region interfaces
public interface IDateRange
{
DateTime StartDate { get; set; }
DateTime EndDate { get; set; }
}
public interface ISomeMoreParams
{
int Param1 { get; set; }
int Param2 { get; set; }
}
public interface IBaseParams
{
string UserName { get; set; }
string CompanyName { get; set; }
}
public interface IClassMethod : IBaseParams
{
void ExecuteLogic(HttpContext context);
}
#endregion
#region FactoryClass
public static class ClassMethodFactory
{
public static IClassMethod GetInstance(string methodName)
{
switch(methodName)
{
case "MethodA":
return new MethodA();
case "MethodB":
return new MethodB();
case "MethodC":
return new MethodC();
}
throw new NotImplementedException(string.Format("{0} is not implemented", methodName));
}
}
#endregion
#region Class methods
public class MethodA : IClassMethod, IDateRange
{
string UserName { get; set; }
string CompanyName { get; set; }
DateTime StartDate { get; set; }
DateTime EndDate { get; set; }
public void ExecuteLogic(HttpContext context)
{
// Do MethodA
}
}
public class MethodB : IClassMethod, ISomeMoreParams
{
string UserName { get; set; }
string CompanyName { get; set; }
int Param1 { get; set; }
int Param2 { get; set; }
public void ExecuteLogic(HttpContext context)
{
// Do MethodB
}
}
public class MethodC : IClassMethod, IDateRange, ISomeMoreParams
{
string UserName { get; set; }
string CompanyName { get; set; }
DateTime StartDate { get; set; }
DateTime EndDate { get; set; }
int Param1 { get; set; }
int Param2 { get; set; }
public void ExecuteLogic(HttpContext context)
{
// Do MethodC
}
}
#endregion
#region HttpHandler
public IClassMethod method;
public void ProcessRequest(HttpContext context)
{
ProcessParams();
ExecuteLogic();
}
public ProcessParams()
{
var qs = HttpContext.Current.Request.QueryString;
method = ClassMethodFactory.GetInstance(qs["action"]);
if(method is IDateRange)
{
(method as IDateRange).StartDate = DateTime.Parse(qs["startDate"]);
(method as IDateRange).EndDate = DateTime.Parse(qs["endDate"]);
}
if(method is ISomeMoreParams
{
(method as ISomeMoreParams).Param1 = int.Parse(qs["param1"]);
(method as ISomeMoreParams).Param2 = int.Parse(qs["param2"]);
}
if(method is IBaseParams)
{
(method as IBaseParams).UserName = qs["UserName"];
(method as IBaseParams).CompanyName = qs["CompanyName"];
}
}
public ExecuteLogic()
{
method.ExecuteLogic();
}
#endregion
</code></pre>
<p>Now, the only part the I have a problem with, is the casting each time I want to see if the class method implements some parameter logic. I wish it would be more organized.</p>
<p>My thoughts:
1. Create for each parameter interface a parameter resolver class which would look like this:</p>
<pre><code>#region Resolvers
public class DateRangeResolver
{
public void Resolve(IDateRange dateRangeClass)
{
var qs = HttpContext.Current.Request.QueryString;
dateRangeClass.StartDate = DateTime.Parse(qs["startDate"]);
dateRangeClass.EndDate = DateTime.Parse(qs["endDate"]);
}
}
public class SomeMoreParamsResolver
{
public void Resolve(ISomeMoreParams someMoreParamsClass)
{
var qs = HttpContext.Current.Request.QueryString;
someMoreParamsClass.Param1 = int.Parse(qs["param1"]);
someMoreParamsClass.Param2 = int.Parse(qs["param2"]);
}
}
public class BaseParamsResolver
{
public void Resolve(IBaseParams baseParamsResolver)
{
// Do resolve
}
}
#endregion
</code></pre>
<p>Then I change the code to fit the new approach:</p>
<pre><code>#region interfaces
// ...
public interface IClassMethod : IBaseParams
{
void ProcessParams();
void ExecuteLogic();
}
// ...
#endregion
#region Class methods
// ...
public class MethodA : IClassMethod, IDateRange
{
// params
public void ProcessParams()
{
new BaseParamsResolver().Resolve(this);
new DateRangeResolver().Resolve(this);
}
public void ExecuteLogic()
{
// Do MethodA
}
}
public class MethodB : IClassMethod, ISomeMoreParams
{
// params
public void ProcessParams()
{
new BaseParamsResolver().Resolve(this);
new SomeMoreParams().Resolve(this);
}
public void ExecuteLogic()
{
// Do MethodB
}
}
public class MethodC : IClassMethod, IDateRange, ISomeMoreParams
{
// params
public void ProcessParams()
{
new BaseParamsResolver().Resolve(this);
new DateRangeResolver().Resolve(this);
new SomeMoreParams().Resolve(this);
}
public void ExecuteLogic(HttpContext context)
{
// Do MethodC
}
}
// ...
#endregion
#region HttpHandler
// ...
public void ProcessParams()
{
method.ProcessParams();
}
//...
#endregion
</code></pre>
<p>Now, my problem is that if I don't call the right resolvers on the ProcessParams of each class method, I would get an exception at runtime and not on debug, which means, I need to consider a new approach or change the existing approach to do so.</p>
<p>I had another idea, the idea is to add to each parameter interface its own resolver so when a class method implements the param interface it would also need to define the resolver for the interface.</p>
<p>This idea, although sounds better, still doesn't enforce the programmer to actually call these resolvers when executing the ProcessParams() function.</p>
<p>Now, after this long long explanation... is there a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:26:23.473",
"Id": "61835",
"Score": "0",
"body": "“is there a better way?” Not reinventing the wheel and using something like ASP.NET Web API?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:35:38.440",
"Id": "61837",
"Score": "0",
"body": "And could you explain why wouldn't you get an exception on debug?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:03:39.450",
"Id": "61905",
"Score": "0",
"body": "svick, what do you mean? How will it let you do this different?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:05:18.860",
"Id": "61907",
"Score": "0",
"body": "svick, the exception would be only on run time since when debugging, the debugger doesn't know if those parameters have values and in the ExecuteLogic function on each class method, it would try to use these parameters but they would be null or default."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:29:27.023",
"Id": "61912",
"Score": "0",
"body": "When you say “debugger”, do you mean “compiler”? Because when you're debugging, the debugger does know what values do the parameters have right now."
}
] |
[
{
"body": "<p>Let me admit up front I don't know a lot about implementing web handlers and the various frameworks, so this answer ignores a probably very legitimate point about reusing the wheels that are already out there. Instead this answer addresses how the code is factored.</p>\n\n<p>Your third block of code is definitely an improvement on the first, but I would still say you are using way too many abstraction layers, resulting in way too much code for a simple task. You should let each class drive reading the querystring params. If you find there's a lot of shared work, factor out helper methods. I would probably avoid the extra classes for the level of complexity in your sample, opting instead for methods that call helpers. After all, if they're not related, why are they on the same <code>HttpHandler</code>?</p>\n\n<pre><code>public void ProcessRequest(HttpContext context)\n{\n var qs = context.Request.QueryString;\n switch(qs[\"action\"])\n {\n case \"MethodA\": return MethodA(context);\n case \"MethodB\": return MethodB(context);\n case \"MethodC\": return MethodC(context);\n }\n throw new NotImplementedException(string.Format(\"{0} is not implemented\", qs[\"action\"]));\n}\n\nvoid MethodA(HttpContext context)\n{\n var qs = context.Request.QueryString;\n ResolveIdentity(qs, out UserName, out CompanyName); // straightforward helper method\n ResolveDates(qs, out StartDate, out EndDate); // ditto; you can write them\n\n // do Method A logic\n}\n</code></pre>\n\n<p>As for the true fact that you can't enforce that a new method will call the resolvers, don't worry about it. This isn't some corner case; it's a core need. It's not like it'll work right most of the time and then fail spectacularly when the moon is full; it will always fail. Rather than worrying about if it's possible to do the wrong thing, focus on making it easy to do the right thing.</p>\n\n<p>As a side note, <code>if (obj is interface) { (obj as interface) ...; }</code> is an antipattern because it can pay casting costs multiple times. You should typically either check <code>is</code> then cast directly (<code>(interface)obj</code>), or store the results of <code>as</code> once and check it for <code>null</code>; don't mix the two.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:55:25.897",
"Id": "37387",
"ParentId": "37378",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T21:59:37.707",
"Id": "37378",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"design-patterns"
],
"Title": "Best design pattern to approach http handler with multiple methods"
}
|
37378
|
<p>Does my PHP look secure enough for a sign up form?</p>
<pre><code><?php
$con=mysqli_connect("host","user","password","db_name");
$sql="INSERT INTO users values (?, ?, ?)";
if ($stmt = mysqli_prepare($con,$sql)) {
mysqli_stmt_bind_param($stmt, "sss",
$_POST["username"], $_POST["pwd"], $_POST["email"]);
if (mysqli_stmt_execute($stmt)) {
echo "User added!";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:37:55.273",
"Id": "61839",
"Score": "3",
"body": "From PHP side of view: you might want to check if connection is successful first. It's important to check if all variables are valid (not empty, matching something). Also someone might spoof form and pass an array instead a string. From security point of view: missing salting and hashing of the password. You might also want to make sure that mail and username are unique (but you can do that using sql unique keys)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:45:03.000",
"Id": "61841",
"Score": "0",
"body": "It depends on your php version and available plugins. PHP 5.5 - http://www.php.net/manual/en/function.password-hash.php . Earlier versions http://php.net/manual/en/function.crypt.php - I recommend blowfish algorithm. Take a look on second comment, it shows a quite secure way to generate salt."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:57:46.030",
"Id": "61844",
"Score": "0",
"body": "@Misiur 2nd to top or 2nd to bottom?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:59:44.677",
"Id": "61845",
"Score": "0",
"body": "On crypt function page, comment by \"steve at tobtu dot com\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T00:03:41.913",
"Id": "61846",
"Score": "0",
"body": "@Misiur Just that one line of code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T08:03:14.737",
"Id": "61871",
"Score": "3",
"body": "@Misiur: Why don't you turn your comments into an answer? There is enough there to be a code review."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T15:44:45.657",
"Id": "65249",
"Score": "0",
"body": "it looks ok, but I would like to see how you are handeling the input. Are you sanatizing all inputs and salt/hashing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T21:37:50.783",
"Id": "65288",
"Score": "1",
"body": "@SaggingRufus Yeah, I'm salting and hashing."
}
] |
[
{
"body": "<p>It looks like you have a good and solid <code>Insert</code>, probably pretty safe, but this still allows a user to enter data into the database that could be run at a later time, you should still check the input coming in before inserting it into the Database even though it has been \"prepared\".</p>\n\n<p>The prepare just means that the insert will not break anything, but if you run a SQL Query on the information in that column where someone has entered SQL injection Characters it could still crash the database. </p>\n\n<p>Please make sure the input is safe all the way around. Alert the user that they cannot enter certain characters but be aware you are asking for an e-mail address there too. The Password should be encrypted, not sure whether you should do that here or in the Database itself, probably in the PHP, but that is another review altogether.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-10T15:00:26.517",
"Id": "39006",
"ParentId": "37383",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "39006",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T23:17:13.590",
"Id": "37383",
"Score": "3",
"Tags": [
"php",
"sql",
"security",
"mysqli"
],
"Title": "Increase security of sign up form code"
}
|
37383
|
<p>Is there a more optimal way of retrieving the character for the letter? I would assume that I would just replace my Entry set loop with another map, but I do not want to bloat the code, because it will reduce scalability.</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class AciiLetters {
private enum Letter {
_A("010101111101101"), _B("110101110101110"), _C("011100100100011"),
_D("110101101101110"), _E("111100110100111"), _F("111100110100100"),
_G("011100101101011"), _H("101101111101101"), _I("111010010010111"),
_J("011001001101010"), _K("101101110101101"), _L("100100100100111"),
_M("101111111101101"), _N("111101101101101"), _O("010101101101010"),
_P("110101110100100"), _Q("010101101011001"), _R("110101110101101"),
_S("011100010001110"), _T("111010010010010"), _U("101101101101111"),
_V("101101101101010"), _W("101101111111101"), _X("101101010101101"),
_Y("101101010010010"), _Z("111001010100111"), _0("111101101101111"),
_1("010110010010111"), _2("111001111100111"), _3("111001011001111"),
_4("101101111001001"), _5("111100111001111"), _6("111100111101111"),
_7("111001001001001"), _8("111101111101111"), _9("111101111001111"),
SPACE("000000000000000"), UNKNOWN("010101001010010");
private static final Map<Character, Letter> cache;
static {
cache = new HashMap<Character, Letter>();
cache.put('A', _A); cache.put('B', _B); cache.put('C', _C);
cache.put('D', _D); cache.put('E', _E); cache.put('F', _F);
cache.put('G', _G); cache.put('H', _H); cache.put('I', _I);
cache.put('J', _J); cache.put('K', _K); cache.put('L', _L);
cache.put('M', _M); cache.put('N', _N); cache.put('O', _O);
cache.put('P', _P); cache.put('Q', _Q); cache.put('R', _R);
cache.put('S', _S); cache.put('T', _T); cache.put('U', _U);
cache.put('V', _V); cache.put('W', _W); cache.put('X', _X);
cache.put('Y', _Y); cache.put('Z', _Z); cache.put('0', _0);
cache.put('1', _1); cache.put('2', _2); cache.put('3', _3);
cache.put('4', _4); cache.put('5', _5); cache.put('6', _6);
cache.put('7', _7); cache.put('8', _8); cache.put('9', _9);
cache.put(' ', SPACE); cache.put('?', UNKNOWN);
}
public static final int WIDTH = 3, HEIGHT = 5;
private String bitSequence;
Letter(String bitSequence) {
this.bitSequence = bitSequence;
}
public static Letter getEnum(Character value) {
Letter letter = cache.get(value);
if (letter != null)
return letter;
return UNKNOWN;
}
public char getChar() {
for (Entry<Character, Letter> entry : cache.entrySet()) {
if (entry.getValue() == this)
return entry.getKey();
}
return '?';
}
}
public AciiLetters() {
printText("ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 ?", " ");
}
public void printText(String text, String spacing) {
Letter letter;
int offset;
String seq;
Character val;
for (int row = 0; row < Letter.HEIGHT; row++) {
for (Character tCh : text.toCharArray()) {
letter = Letter.getEnum(tCh);
offset = row * Letter.WIDTH;
seq = letter.bitSequence.substring(offset, offset + Letter.WIDTH);
val = letter.getChar();
for (Character ch : seq.toCharArray()) {
System.out.printf("%c", ch == '0' ? ' ' : val);
}
System.out.print(spacing);
}
System.out.println();
}
}
public static void main(String[] args) {
new AciiLetters();
}
}
</code></pre>
<p>Output:</p>
<pre><code> A BB CC DD EEE FFF GG H H III JJ K K L M M NNN O PP Q RR SS TTT U U V V W W X X Y Y ZZZ 000 1 222 333 4 4 555 666 777 888 999 ?
A A B B C D D E F G H H I J K K L MMM N N O O P P Q Q R R S T U U V V W W X X Y Y Z 0 0 11 2 3 4 4 5 6 7 8 8 9 9 ? ?
AAA BB C D D EE FF G G HHH I J KK L MMM N N O O PP Q Q RR S T U U V V WWW X Y Z 0 0 1 222 33 444 555 666 7 888 999 ?
A A B B C D D E F G G H H I J J K K L M M N N O O P QQ R R S T U U V V WWW X X Y Z 0 0 1 2 3 4 5 6 6 7 8 8 9 ?
A A BB CC DD EEE F GG H H III J K K LLL M M N N O P Q R R SS T UUU V W W X X Y ZZZ 000 111 222 333 4 555 666 7 888 999 ?
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T04:06:24.637",
"Id": "61862",
"Score": "0",
"body": "BTW: I see nothing that is [ASCII](http://en.wikipedia.org/wiki/Ascii) specific here. Your solution appears to be character set agnostic - which is good."
}
] |
[
{
"body": "<p>This is one of those occasions where a 'sparse' dataset may be very helpful.</p>\n\n<p>But, first some nit-picks:</p>\n\n<ul>\n<li>You should probably call the class <code>AsciiLetters</code> instead of <code>AciiLetters</code></li>\n<li><p>Declaring multiple constants on one line is unconventinal, and makes things hard to read... fix:</p>\n\n<pre><code>public static final int WIDTH = 3, HEIGHT = 5;\n</code></pre></li>\n<li><p>In the printText you over-cook the lookups to the Enum:</p>\n\n<pre><code>for (int row = 0; row < Letter.HEIGHT; row++) {\n for (Character tCh : text.toCharArray()) {\n letter = Letter.getEnum(tCh);\n</code></pre>\n\n<p>this can become:</p>\n\n<pre><code>char[] textchars = text.toCharArray();\nLetter[] letters = new Letter[textchars.length];\nfor (int i = 0; i < textchars.length; i++) {\n letters[i] = Letter.getEnum(textchars[i]);\n}\nfor (int row = 0; row < Letter.HEIGHT; row++) {\n for (letter letter : letters) {\n</code></pre></li>\n<li><p>also in the printText(), there is no need to do all the work with <code>Character</code>. Using <code>char</code> is better.</p></li>\n<li>also, declaring all your variables outside the loop is not useful for anything, and can even make performance worse. Languages like <code>C</code> need that, but Java is better if you declare your variables when you need them, not before.</li>\n<li>If you wanted to, you could store the <code>0</code> and <code>1</code> values as actual bits. This would actually be faster (slightly) but would also be more complicated. In this case, I don't think it is significantly different.</li>\n</ul>\n\n<p>OK, now for the real issue, the storage of the Enums in a convenient-to-access system...</p>\n\n<p>First, I recommend that you change your Enum to have two parameters in the constructor:</p>\n\n<pre><code> private String bitSequence;\n Letter(String bitSequence) {\n this.bitSequence = bitSequence;\n }\n</code></pre>\n\n<p>This should become (note, I have also made them final!):</p>\n\n<pre><code> private final String bitSequence;\n private final char mychar;\n Letter(char c, String bitSequence) {\n this.mychar = c;\n this.bitSequence = bitSequence;\n }\n</code></pre>\n\n<p>Then change each of your Enum values to also send the char it represents.</p>\n\n<p>If you do that, then your getChar() method becomes simply:</p>\n\n<pre><code> public char getChar() {\n return mychar;\n }\n</code></pre>\n\n<p><strong>BUT</strong>, I was lazy, and I pulled your code in to my eclipse environment, and I could not be bothered to change all the Enum values... so I cheated... and used:</p>\n\n<pre><code> public char getChar() {\n return name().charAt(1);\n }\n</code></pre>\n\n<p>That takes the second letter from the Enum name (e.g. it will pull <code>L</code> from <code>_L</code>). Since all your Enum names have a systematic name scheme, this will work, but, it's not the best system...</p>\n\n<p>But still, once I have the <code>getChar()</code> working off the internal values of the enum (instead of the <code>Map<...></code>), you can do the following:</p>\n\n<p>replace the line:</p>\n\n<pre><code>private static final Map<Character, Letter> cache;\n</code></pre>\n\n<p>and instead have:</p>\n\n<pre><code>// store enough values for ASCII characters. If we wanted to, even 32768 is not large\n// and with that we could store **all** Letters,\nprivate static final Letter[] cache = new Letter[128];\n</code></pre>\n\n<p>Then, in your static block, fill the cache with 'Unknown', and then 'fix' the ones you know:</p>\n\n<pre><code> static {\n // assume things are UNKNOWN.\n Arrays.fill(cache, UNKNOWN);\n // 'fix' the things we actually know...\n for (Letter letter : values()) {\n // use the actual char (cast implicitly to an int...)\n // as the index to the array.\n // if you have chars >= 128 you will need to make the array bigger.\n cache[letter.getChar()] = letter;\n }\n }\n</code></pre>\n\n<p>Finally, using this array is really simple:</p>\n\n<pre><code> public static Letter getEnum(char value) {\n return value < cache.length ? cache[value] : UNKNOWN;\n }\n</code></pre>\n\n<p>Note, I have changed the parameter to simple <code>char</code> instead of <code>Character</code>.</p>\n\n<p>Putting it all together, I have your code running as (without the additional char as a constructor to the Enum...):</p>\n\n<pre><code>import java.util.Arrays;\n\npublic class AsciiLetters {\n private enum Letter {\n _A(\"010101111101101\"), _B(\"110101110101110\"), _C(\"011100100100011\"),\n _D(\"110101101101110\"), _E(\"111100110100111\"), _F(\"111100110100100\"),\n _G(\"011100101101011\"), _H(\"101101111101101\"), _I(\"111010010010111\"),\n _J(\"011001001101010\"), _K(\"101101110101101\"), _L(\"100100100100111\"),\n _M(\"101111111101101\"), _N(\"111101101101101\"), _O(\"010101101101010\"),\n _P(\"110101110100100\"), _Q(\"010101101011001\"), _R(\"110101110101101\"),\n _S(\"011100010001110\"), _T(\"111010010010010\"), _U(\"101101101101111\"),\n _V(\"101101101101010\"), _W(\"101101111111101\"), _X(\"101101010101101\"),\n _Y(\"101101010010010\"), _Z(\"111001010100111\"), _0(\"111101101101111\"),\n _1(\"010110010010111\"), _2(\"111001111100111\"), _3(\"111001011001111\"),\n _4(\"101101111001001\"), _5(\"111100111001111\"), _6(\"111100111101111\"),\n _7(\"111001001001001\"), _8(\"111101111101111\"), _9(\"111101111001111\"),\n SPACE(\"000000000000000\"), UNKNOWN(\"010101001010010\");\n\n public static final int WIDTH = 3;\n public static final int HEIGHT = 5;\n\n private static final Letter[] cache = new Letter[128];\n\n static {\n Arrays.fill(cache, UNKNOWN);\n for (Letter letter : values()) {\n cache[letter.getChar()] = letter;\n }\n }\n\n private String bitSequence;\n\n Letter(String bitSequence) {\n this.bitSequence = bitSequence;\n }\n\n public static Letter getEnum(char value) {\n return value < cache.length ? cache[value] : UNKNOWN;\n }\n\n public char getChar() {\n return name().charAt(1);\n }\n }\n\n public AciiLetters() {\n printText(\"ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 ?\", \" \");\n }\n\n public void printText(String text, String spacing) {\n\n char[] textchars = text.toCharArray();\n Letter[] letters = new Letter[textchars.length];\n for (int i = 0; i < textchars.length; i++) {\n letters[i] = Letter.getEnum(textchars[i]);\n }\n for (int row = 0; row < Letter.HEIGHT; row++) {\n for (Letter letter : letters) {\n int offset = row * Letter.WIDTH;\n String seq = letter.bitSequence.substring(offset, offset + Letter.WIDTH);\n char val = letter.getChar();\n for (Character ch : seq.toCharArray()) {\n System.out.printf(\"%c\", ch == '0' ? ' ' : val);\n }\n System.out.print(spacing);\n }\n System.out.println();\n }\n }\n\n public static void main(String[] args) {\n new AciiLetters();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T06:37:31.163",
"Id": "61867",
"Score": "0",
"body": "Thanks, very thorough. I will have to check this in the morning. Note: I didn't realize I spelled ASCII wrong... That was dumb on my part. I may not even have to store the char for each sequence, because I could just get the current letter that was read in from the inputText..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T10:34:00.437",
"Id": "61879",
"Score": "1",
"body": "`return name().charAt(1);` now this is lazy wait for it genius."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T06:04:08.710",
"Id": "37396",
"ParentId": "37392",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T03:38:53.147",
"Id": "37392",
"Score": "5",
"Tags": [
"java",
"optimization",
"cache",
"hash-map",
"lookup"
],
"Title": "Optimize text to ascii lookup map and scalability"
}
|
37392
|
<p>I'm creating a program to retrieve web content in order to learn how these things work. I would like it to be as correct as possible, ideally fully compliant.</p>
<p>But I'm not sure this is the right approach to the problem. Is the following structure an appropriate way to hold server response header data after parsing it?</p>
<pre><code>typedef enum {
OPTIONS = 1, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, PATCH
} HTTP_Methods;
typedef enum {
KEEP_ALIVE = 1, CLOSE
} HTTP_Connection_Field;
typedef enum {
CHUNKED = 1, COMPRESS, DEFLATE, GZIP, IDENTITY
} HTTP_Transfer_Encoding;
typedef struct {
uint8_t http_version; //e.g. HTTP/1.1 = 11, HTTP/1.0 = 10, HTTP/0.9 = 9
uint16_t response_code; //e.g. 200, 404, 500, ...
char *accept_ranges;
uint32_t age; //Non-negative, time in seconds, at least 31 bits of range
HTTP_Methods allow;
char *cache_control;
HTTP_Connection_Field connection;
char *content_encoding;
char *content_language;
uint32_t content_length;
char *content_location;
char *content_MD5;
char *content_disposition;
char *content_range;
char *content_type;
time_t date;
char *etag;
time_t expires;
time_t last_modified;
char *link;
char *location;
char *p3p;
char *pragma;
char *proxy_authenticate;
char *refresh;
time_t retry_after;
char *server;
char *set_cookie;
char *strict_transport_security;
char *trailer;
HTTP_Transfer_Encoding transfer_encoding;
char *vary;
char *via;
char *warning;
char *www_authenticate;
} HTTP_Response_Header;
</code></pre>
<p>Maybe grouping the members that are not very commonly used into a different struct that is only allocated when they are in use would be a better idea?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T05:50:51.797",
"Id": "61864",
"Score": "3",
"body": "Adding all of these headers explicitly into a struct doesn't work very well because it's entirely possible to send/receive non-standard headers. You really just need a map of strings to strings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T06:19:41.913",
"Id": "61866",
"Score": "0",
"body": "Because this is C, you might want to permit a NULL value for every byte of the struct, (especially the HTTP_Methods and other enums,) so you can use a simple `memset(&hrh, 0, sizeof(HTTP_Response_Header));` to initialize it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T07:41:02.853",
"Id": "61869",
"Score": "1",
"body": "@ChrisHayes Your comment should be submitted as an answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T08:14:50.777",
"Id": "61872",
"Score": "0",
"body": "@200_success Probably, but I was feeling lazy earlier. :) Expanded and posted as an answer now though."
}
] |
[
{
"body": "<p>The way I would do it is by simply representing the headers as map of <code>char*</code> to <code>char*</code>. That'll be the most flexible and extensible situation, since HTTP headers are added over time, and custom headers are completely acceptable and allowed for by the standard. Any solution involving struct fields will require updating as the standard expands, and can't handle custom headers easily. (You could handle custom headers the same way as standard ones, but then you'd have the problem that their meaning is not standard, and different clients could use them to represent different things.)</p>\n\n<p>The downside of making the map values be <code>char*</code> is that you'll have to translate into the proper data type wherever you retrieve them from the map, rather than only performing this translation when you read the request headers. This is an acceptable trade-off for the flexibility you gain, and you can find a way to encapsulate it if desired.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T08:14:24.273",
"Id": "37400",
"ParentId": "37395",
"Score": "8"
}
},
{
"body": "<p>Good artists copy; great artists steal. Except you can't really steal Apache, since it's free software. ☺</p>\n\n<p>Take a look at how they define <a href=\"http://ci.apache.org/projects/httpd/trunk/doxygen/structrequest__rec.html\" rel=\"nofollow\"><code>struct request_rec</code></a>. (Their task is to parse an HTTP request into a data structure, rather than an HTTP server response, but the idea is similar.) As you can see, they take a hybrid approach: the most relevant information, such as the URI in their case, or the content length in your case, is stored directly in the struct. However, the struct also has pointers to tables that store each header verbatim, since it's impossible for your struct to cover all of the possible headers.</p>\n\n<p>Normally, I would recommend grouping your struct members by data type (putting all <code>time_t</code> members together, for example) to avoid wasting padding space due to alignment. However, most of the members are pointers and <code>time_t</code>, which should be the same size anyway, so there shouldn't be much of a difference. Try it both ways and compare <code>sizeof HTTP_Response_Header</code> in each case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T09:00:03.153",
"Id": "37403",
"ParentId": "37395",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37400",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T05:38:34.980",
"Id": "37395",
"Score": "6",
"Tags": [
"c",
"http"
],
"Title": "Holding server response header data after parsing it"
}
|
37395
|
<p><a href="http://projecteuler.net/problem=9" rel="nofollow">Project Euler problem 9</a> says:</p>
<blockquote>
<p>A Pythagorean triplet is a set of three natural numbers, <em>a</em> < <em>b</em> < <em>c</em>,
for which,</p>
<p><em>a</em><sup>2</sup> + <em>b</em><sup>2</sup> = <em>c</em><sup>2</sup></p>
<p>For example, 3<sup>2</sup> + 4<sup>2</sup> = 9 + 16 = 25 = 5<sup>2</sup>.</p>
<p>There exists exactly one Pythagorean triplet for which <em>a</em> + <em>b</em> + <em>c</em> =
1000. Find the product <em>abc</em>.</p>
</blockquote>
<p>I am a beginner in programming, especially Python. I got the answer for the problem, but how can I optimize it?</p>
<pre><code>a=0
b=a+1
exit=False
#a loop
for x in xrange(1000):
a+=1
b=a+1
c=b+1
#b loop
for y in xrange(1000):
b+=1
if(1000-b-a < 0):
break
c = 1000-a-b
if(a**2 + b**2 == c**2):
print "The number is ", a*b*c
x=1000
exit = True
else:
print "A is ", a ,".\n B is ", b, ".\n C is ",c,"."
if exit:
break
if exit:
break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T07:58:43.927",
"Id": "61870",
"Score": "3",
"body": "This is [Project Euler Problem 9](http://projecteuler.net/problem=9)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T07:01:05.563",
"Id": "61955",
"Score": "0",
"body": "Any optimizations that you could make would likely be in removing the O(n^2) complexity."
}
] |
[
{
"body": "<p>Here are some changes I would do in your code:</p>\n\n<ol>\n<li><p>Since you already have two variables <code>x</code> and <code>y</code> from the loop, you don't need <code>a</code> and <code>b</code>. Get the 3 numbers as - <code>x</code>, <code>y</code>, and <code>1000 - x - y</code>, and use them.</p></li>\n<li><p>You might well possibly be checking the values same pythagorean triplets twice. Once with <code>x</code>, <code>y</code>, and <code>1000 - x - y</code>, and then with <code>y</code>, <code>x</code>, <code>1000 - y - x</code>. For example, when <code>x</code> takes <code>2</code> and <code>y</code> takes <code>3</code>, then you don't want to check this again for <code>x = 3</code> and <code>y = 2</code>. This might happen, as your inner loop is running from the beginning every time. You can avoid this by iterating from <code>x</code> to <code>1000</code>.</p></li>\n<li><p>No need of <code>exit</code> <code>boolean</code> variable. Put those loops inside some function, and return as soon as the result is found.</p></li>\n</ol>\n\n<p><em>Modified Code:</em></p>\n\n<pre><code>def specialPythagoreanTriplet(s):\n\n for a in xrange(s):\n for b in xrange(a, s):\n c = s - a - b;\n if a**2 + b**2 = c**2:\n return (a, b, c)\n</code></pre>\n\n<p>In addition to all that, you don't really need to iterate till <code>1000</code> for values of <code>a</code> and <code>b</code>. The maximum value that <code>a</code> could take should be much less than <code>1000</code>. Let's find out.</p>\n\n<p>You have:</p>\n\n<blockquote>\n <p>a + b + c = 1000, and<br>\n a < b < c</p>\n</blockquote>\n\n<p>Replace <code>b</code> and <code>c</code> with <code>a</code>, we get:</p>\n\n<blockquote>\n <p>a + a + a < 1000<br>\n 3a < 1000<br>\n a < 333</p>\n</blockquote>\n\n<p>Similarly, you can find out the threshold for <code>b</code>, I'm leaving it for you:</p>\n\n<pre><code>for a in xrange(s / 3):\n for b in xrange(a + 1, s): # Change `s` to someother value\n # Same as previous code.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T08:09:48.127",
"Id": "37399",
"ParentId": "37398",
"Score": "5"
}
},
{
"body": "<p>Well, you got the answer, but your code could be tidier. The main weaknesses I see are:</p>\n\n<ul>\n<li><p><strong>Too many variables:</strong> The problem calls for numbers <em>a</em>, <em>b</em>, and <em>c</em>. Introducing variables <code>x</code> and <code>y</code> needlessly complicates the code. It's always the case that <code>a = x + 1</code>, so <code>x</code> is redundant. Then, with <code>y</code> (but not really using <code>y</code>), you loop up to 1000 times with <code>b</code> starting from <code>a + 1</code>.</p>\n\n<p>Your loop structure can be distilled down to…</p>\n\n<pre><code>for a in xrange(1, 1001):\n for b in xrange(a + 1, a + 1001):\n if a + b > 1000:\n break\n c = 1000 - a - b\n # etc.\n</code></pre>\n\n<p>However, the if-break could still be improved upon — see below.</p></li>\n<li><strong>Using variables for flow control:</strong> It's cumbersome to set an <code>exit</code> flag, then have code elsewhere inspect the flag. There are more assertive techniques to go where you want to go immediately. You want to break out from a nested loop, so search Stack Overflow and read <a href=\"https://stackoverflow.com/q/189645/1157100\">this advice</a>.</li>\n</ul>\n\n<p>As previously mentioned, there is an even better way to enumerate possibilities for <code>a</code>, <code>b</code>, and <code>c</code> such that their sum is always 1000. That way, you don't need the if-break in your code.</p>\n\n<pre><code>def euler9():\n # Ensure a < c\n for c in xrange(2, 1000):\n for a in xrange(1, c):\n # Ensure a + b + c == 1000. Since a is counting up, the first\n # answer we find should have a <= b.\n b = 1000 - c - a\n\n # Ensure Pythagorean triple\n if a**2 + b**2 == c**2:\n print(\"a = %d, b = %d, c = %d. abc = %d\" % (a, b, c, a * b * c))\n return\n\neuler9()\n</code></pre>\n\n<p>Alternatively:</p>\n\n<pre><code>def euler9():\n for a in xrange(1, 1000):\n for b in xrange(a + 1, 1000 - a):\n # Ensure a + b + c == 1000. Since b is counting up, the first\n # answer we find should have b <= c.\n c = 1000 - a - b\n # etc.\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T08:23:24.983",
"Id": "37401",
"ParentId": "37398",
"Score": "5"
}
},
{
"body": "<p>I think I have the fastest solution:</p>\n\n<pre><code>print \"The number is 31875000\"\n</code></pre>\n\n<p>In all seriousness, you have several constraints you can throw in. WLOG, a <= b. We also know a,b < c. We know that a + b + c = 1000. So a < 334. If a = 100, then b < 450.</p>\n\n<p>I will also say that since this is a Project Euler question you can probably find some very clever solutions on the Project Euler thread. I imagine this problem can be done pretty quickly by hand with the right maths.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T06:49:41.763",
"Id": "61956",
"Score": "0",
"body": "lol, I know the answer and my code works. I just want an optimized version. Your suggestion will also be taken. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T06:46:35.140",
"Id": "37450",
"ParentId": "37398",
"Score": "2"
}
},
{
"body": "<p>I used information here and it seems to solve fairly quickly:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Pythagorean_triple\" rel=\"nofollow\">Euclid's Formula</a></p>\n\n<pre><code>a = m^2 - n^2 , b = 2mn , c = m^2 + n^2 \n</code></pre>\n\n<p>For math related questions, using the correct formula can save quite a lot of computation.</p>\n\n<p>In regard to your current code, you can probably avoid setting the a, b, c in the outer loop, and b in the inner loop if you change your 'for x in xrange' to 'for a in xrange' and your 'for y in xrange' to 'for b in xrange'. This is a pretty common way to advance those values and saves quite a bit of moving the numbers in python. Less work done is faster. :)</p>\n\n<p>Using the Euler formula above is likely much faster though. You may want to consider how you would cycle through values m and n and calculate a,b,c.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:23:13.257",
"Id": "62047",
"Score": "0",
"body": "True, but it's only faster if you disregard the time to write and debug your program. A computer can easily iterate 1000 x 1000 times in less than one second."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T07:26:15.737",
"Id": "37451",
"ParentId": "37398",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37401",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T07:03:27.883",
"Id": "37398",
"Score": "7",
"Tags": [
"python",
"optimization",
"beginner",
"project-euler",
"mathematics"
],
"Title": "Finding the Pythagorean triplet that sums to 1000"
}
|
37398
|
<p>I am still new to C++ and don't have a great insight on my coding yet, so I would be very grateful to anyone and everyone that gives advice.</p>
<p><strong>Also, this code is meant to:</strong> keep all of my objects in an ordered fashion based on depth. I have a couple functions that allow for easy management and I made <code>object</code> friends with the <code>depth manager</code> because I only want the <code>depthManager</code> to have control over each objects <code>idDepth</code> and <code>depth</code> which are two different things. </p>
<p>The reason I need a depth system is because I need to have objects execute there code in an orderly fashion, and I also need to have control of what objects are drawn first to last.</p>
<p><strong>This class has been tested and works as expected.</strong></p>
<ul>
<li><a href="https://github.com/Lemony-Andrew/SFML-Game-Engine" rel="nofollow"><strong>Stay up to date with this project on GitHub.com</strong></a>
<br><br></li>
</ul>
<hr>
<p><strong>Abstract <code>object</code> class:</strong></p>
<pre><code>class object{
// Placement Data
unsigned int depth, idDepth, idObject, idMain;
// Friends
friend class depthManager;
friend class objectManager;
protected:
unsigned int getDepthId(){ return idDepth; }
public:
virtual void update() = 0;
virtual void draw() = 0;
unsigned int getDepth() { return this->depth; }
};
</code></pre>
<p><em>note: I have each object handle its own update and draw events for easier design. I'm mainly asking on approval for the depth system.</em>
<br><br><br></p>
<hr>
<p><strong><code>depthManager</code> class</strong></p>
<pre><code>class depthManager{
private:
std::map<unsigned, std::vector<object*>* > objectMap;
void changeListPlacement( unsigned int depth, unsigned int position, int change);
public:
void objectAdd( unsigned int depth, object* obj);
void objectRemove( object* obj );
void objectMove( unsigned int depth, object* obj );
};
</code></pre>
<p><br><br>
<strong><code>depthManager</code>s Functions:</strong></p>
<pre><code>void depthManager::objectAdd(unsigned int depth, object *obj)
{
obj->depth = depth;
// Check if depth key existant
if ( objectMap.find( depth ) != objectMap.end() )
{
std::vector< object* >* &refVec = objectMap[ depth ];
refVec->push_back( obj );
obj->idDepth = (unsigned)(int)refVec->size() - 1;
}
else // Add new Key
{
objectMap[ depth ] = new std::vector< object* >;
std::vector< object* >* &refVec = objectMap[ depth ];
refVec->push_back( obj );
obj->idDepth = (unsigned)(int)refVec->size() - 1;
}
}
void depthManager::changeListPlacement(unsigned int depth, unsigned int position, int change = -1)
{
if ( objectMap.find( depth ) == objectMap.end() )
{
return;
}
std::vector<object*>* &refVec = objectMap[ depth ];
for( unsigned int i = refVec->size() - 1; i > position; i -- )
{
object* &pObj = refVec->at( i );
pObj->idDepth += change;
}
}
void depthManager::objectRemove(object *obj)
{
if ( objectMap.find( obj->depth ) == objectMap.end() )
{
std::cout << "ERROR DEPTH NOT FOUND \n" << std::flush ;
return;
}
std::vector<object*>* &refVec = objectMap[ obj->depth ];
changeListPlacement( obj->depth, obj->idDepth);
refVec->erase( refVec->begin() + obj->idDepth );
}
void depthManager::objectMove(unsigned int depth, object *obj)
{
this->objectRemove( obj );
this->objectAdd( depth, obj );
}
</code></pre>
<p><strong>previous verions</strong></p>
<p><a href="https://drive.google.com/file/d/0B3OyWP9-u8E1V3NnVXQ5elFEUUE/edit?usp=sharing" rel="nofollow">Depth Manager Source Code 1</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:24:33.220",
"Id": "61910",
"Score": "0",
"body": "Can you elaborate more on the purpose? Why is this better than a single flat vector of `object`s ordered by `depth`? What are the use cases, besides iterating though all objects in all depths in either order?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:43:15.507",
"Id": "61916",
"Score": "0",
"body": "@KarolisJuodele It is easier to manage. Instead of keeping track of how large each depth section is in one vector, it's split in to more easily manageable sections based on depth. This way the number of iterations is reduced to a fraction of the amount. Notice how if you were to remove an object in a single vector in the middle of one large vector it would effect the position of objects not even in the same depth resulting in unnecessary processing time. This engines main purpose is depth, and keeping track of it, so there is little scope outside of that reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T18:35:30.650",
"Id": "61921",
"Score": "0",
"body": "What is `object`? It sounds like an image, but why does it not have `double x, y`? If it will, is it okay for `depth` to be integer? How often will objects be moved between the depths?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T18:38:01.660",
"Id": "61922",
"Score": "0",
"body": "Also, I think you should be able to simplify your code, as it is, by using `std::map<unsigned, std::vector<object*>>` instead of a pair of vectors."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T18:58:27.497",
"Id": "61924",
"Score": "0",
"body": "@KarolisJuodelė `object` is the basic abstract class I will be using for all in game entities to be derived from. It does not have a position because that will be up to the derived classes. Also, Depth must be positive at all times and I believe depth should be a short as well because it will only be able to go to 100. Thanks for the reference to `std::map` it will be very useful in the future."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T20:46:31.463",
"Id": "61936",
"Score": "0",
"body": "@KarolisJuodelė Uploaded new version using maps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:29:57.520",
"Id": "62094",
"Score": "0",
"body": "My only concern with your use of maps is that maps only allow 1 value per key. So with this implementation you are forcing that every object has a unique depth and no two objects can ever be at the same depth. This may certainly be desired (perhaps to prevent fighting over z-orders), but you should at least be aware of it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:28:07.663",
"Id": "62121",
"Score": "1",
"body": "@YoungJohn Yes, I was aware of this when writing the code. That's why the map holds vectors that contain a list of objects there for more than one object can be located in the same depth. -- `std::map<unsigned, std::vector<object*>* > objectMap;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:40:32.437",
"Id": "62125",
"Score": "1",
"body": "@Lemony-Andrew while a map of vectors will achieve what you are looking for you could also look into using std::multimap which exists for this purpose. Also, if you are using C++11 you could look into using unordered_map or unordered_multimap, but those may all be overkill for your project depending on your performance concerns."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T18:57:44.550",
"Id": "62133",
"Score": "0",
"body": "@YoungJohn I had no Idea multi maps exist, I'm going to have to study the standard c++ library a bit more. I'll take a look at this later today and see if I can implement its functionality without flaw. Thanks YoungJohn! +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T13:20:43.393",
"Id": "62273",
"Score": "0",
"body": "@YoungJohn Well, multi maps were definitely not in my favor if one of my prime goals was to reduce the amount of iterations need to locate data. But at least I got some good practice with iterators and maps haha."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:16:46.240",
"Id": "62292",
"Score": "1",
"body": "@Lemony-Andrew Yeah, there's always more than one way to solve a problem and you just have to go with what works best for you, but I'm glad you at least took the time to look at your alternatives."
}
] |
[
{
"body": "<p>Some remarks to your current <code>map</code>-based implementation:</p>\n\n<ol>\n<li><p>The idiomatic way of accessing an item in a map and adding it if not present usually goes like this:</p>\n\n<pre><code>if not map.contains(key)\n map[key] = new value\n\nvalue = map[key]\n... modify value\n</code></pre>\n\n<p>So <code>objectAdd</code> could be shortened:</p>\n\n<pre><code>obj->depth = depth;\n// make sure we have an object vector for the given depth\nif ( objectMap.find( depth ) == objectMap.end() )\n{\n objectMap[ depth ] = new std::vector< object* >;\n}\n\nstd::vector< object* >* &refVec = objectMap[ depth ];\nrefVec->push_back( obj );\nobj->idDepth = (unsigned)(int)refVec->size() - 1;\n</code></pre></li>\n<li><p>In <code>objectRemove</code> it is apparently illegal to pass an object with a non-existent depth. Printing an error message to stdout is not the best way to handle an error like that. You should throw an appropriate exception (fail early is a valuable debugging tool) or allow it by ignoring invalid depths.</p></li>\n<li><p>It is not imminently clear what <code>objectMove</code> exactly does based on its name and the names of its parameters. It looks like it moves an object to a different depth. So a better name and signature might be:</p>\n\n<pre><code>void depthManager::changeDepth(unsigned int newDepth, object *obj)\n</code></pre></li>\n<li><p>In <code>class object</code> the methods <code>getIdDepth()</code> and <code>getDepth</code> do not modify the object state so you should consider making them <code>const</code> (i.e. <code>unsigned int getDepth() const { return this->depth; }</code>).</p></li>\n<li><p>I'm not 100% convinced of the <code>idDepth</code> property. It basically just reflects the current position of the object in the depth-list and you are writing a fair amount of boiler plate code to keep it that way. This increases the complexity of the class somewhat. I'd revisit the concept and check if I can't get by without it.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:58:37.730",
"Id": "62042",
"Score": "0",
"body": "Great catch on point #1! It definitely should be simplified. On #2 I have been semi rushing this code, I haven't sat down to learn error handling yet; but I do intend to add that functionality. #3 when I made that function I was uncertain on the naming convention, changeDepth does sound more reasonable. #4 This functionality was replace with const getDepth() earlier today, and yes it should be read only. #5 All the Id's are merely positions in a corresponding vector, this way looping is cut to a minimum. --- I greatly Appreciate the insight!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:55:07.940",
"Id": "62051",
"Score": "0",
"body": "@Lemony-Andrew On #1: `map::operator[]` default constructs and inserts an element for the provided key if none exists. So if default construction of values is okay, the idiomatic form is just `auto& value = map[key]`. In the OP's case, where the value type is a raw pointer, you can just add `if (!value) value = new Value` to create the new value object, but that's ignoring the questionable usage of raw pointers with ownership semantics. Anyway, this method only involves 1 tree search, instead of the 3 required for a `contains()` and 2 `operator[]` calls."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:07:29.993",
"Id": "62077",
"Score": "0",
"body": "@bcrist Alright I'll have a look at the code later today. Also were you using auto for shortening purposes to explain the code? Else I see no benefits in using it in my case. The IDE wouldn't like to work with it haha ( doesn't know the type so no friendly auto-completion )"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T14:56:01.400",
"Id": "62284",
"Score": "0",
"body": "@Lemony-Andrew Yes, the `auto&` was just for ease of reading the comment. Personally I have no problem using `auto` in a program that's already using other C++11 features, and Visual Studio intellisense has no problem determining the actual type of an `auto`, but I try to only use it where the entire type would be much harder to read; eg. `auto` is much easier to read than `std::unordered_map<Identifier<SomeType>, SomeType, SomeTypeHasher<Identifier<SomeType>>, std::equal_to<Identifier<SomeType>>, SomeAllocatorTypedef>::const_iterator`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:43:34.273",
"Id": "37483",
"ParentId": "37402",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37483",
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T08:31:48.660",
"Id": "37402",
"Score": "5",
"Tags": [
"c++",
"performance",
"object-oriented",
"beginner",
"memory-management"
],
"Title": "Could this depth system for a game be improved?"
}
|
37402
|
<p>Im creating an single page application with not reload or redirects so I display all my contents with partial view(since im using <strong>MVC4</strong> and <strong>angularjs</strong> ) and modals.</p>
<p>But I came with a situation, and that is that in some cases when i request a view with ajax to the server I need to perform some action(javascript loads) on the view when load but as you know i have to way for the response(the view) to execute this since still not present in the DOM. So I came with this solution. I just develop a method that allows me to wait for a piece HTML with timeouts and recursions and then execute the code when the HTML is render in the view.</p>
<pre><code>//this is actually a service in angular, im just giving an example
function $WaitFor(selector,callback,timeout)
{
var execute = function()
{
if(document.Selector(selector) != null)
callback();
else
startTimeout()
}
var startTimeout = function()
{
setTimeout(execute, 200 || timeout)
}
startTimeout();
}
</code></pre>
<p>And indeed the code works, it waits and execute the code successfully when the response(the view) is display. But, is that code ok? is there any another alternative that? And what about performance? Any sugestions/help you can give me??</p>
|
[] |
[
{
"body": "<h2>Read your framework's documentation</h2>\n\n<p>Before you actually do some voodoo magic on your code, I suggest you read your framework's documentation. It's quite impossible that a web framework has not taken into account JS's asynchronous nature. There should be a proper way to do this.</p>\n\n<p>For instance, in Meteor we have the <code>.rendered</code> handler which runs when the template has rendered or rerendered. This is usually where we hook stuff or modify the DOM to the newly rendered template.</p>\n\n<h2>Mutation observers</h2>\n\n<p>This is one of the new, shiny toys of JS and should be the proper way to do this operation in plain JS. <a href=\"https://developer.mozilla.org/en/docs/Web/API/MutationObserver\" rel=\"nofollow\">Mutation Observers</a> listen for changes on the DOM and fire assigned callbacks. You can configure them to listen for specific changes on the DOM, like attribute modifications, subtree modifications (adding or removing DOM). As of this writing, <a href=\"http://caniuse.com/mutationobserver\" rel=\"nofollow\">current browsers support them already</a>.</p>\n\n<h2>Using AJAX? The callbacks!</h2>\n\n<p>When there is AJAX, there should be some mechanism to attach handlers to know when the data arrived. Use that instead.</p>\n\n<p>For example, in jQuery you can do this:</p>\n\n<pre><code>$.get('some_resource_url')\n .done(function(data){\n //Do something with the data when it arrives\n });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:05:01.270",
"Id": "61906",
"Score": "0",
"body": "I tried with observer but if you look, ie 10 down not supported. Thanks for your first advice, ill search if angular has a such a method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T14:32:14.320",
"Id": "37416",
"ParentId": "37408",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37416",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T12:06:04.483",
"Id": "37408",
"Score": "2",
"Tags": [
"javascript",
"performance"
],
"Title": "Create an alternative wait in javascript"
}
|
37408
|
<p>I would be glad if someone could take a look at my code and maybe improve it. It's an animation effect to gradually reveal text as if it were being decoded. I wouldn't mind if it could run with jQuery (if it's shorter or better). I uploaded it on <a href="http://jsbin.com/OtUZaGOy/1/edit?html,js,output" rel="nofollow">jsbin.com</a>. It's all about the effect and not about encryption or decryption.</p>
<p>I've written the following JS Code:</p>
<pre><code>var got,
chars,
decrypted = document.getElementById("decoded"),
encrypted = document.getElementById("encoded");
function change() {
var randstring = "",
rslength = chars.length - got.length,
i;
for (var x=0;x<rslength;x++) {
i = Math.floor(Math.random() * chars.length);
randstring += chars[i];
}
if (randstring[0] === chars[got.length]) {
got += randstring[0];
decrypted.textContent = got;
} else {
encrypted.textContent = randstring;
}
if (chars.length > got.length) {
setTimeout(change, 10);
} else {
encrypted.textContent = "";
}
}
function startdecrypt() {
chars = decrypted.textContent;
decrypted.textContent = "";
got = "";
setTimeout(change, 10);
}
if (window.addEventListener) {
window.addEventListener('load', startdecrypt, false); //W3C
} else {
window.attachEvent('onload', startdecrypt); //IE
}
</code></pre>
<p>And this short HTML part:</p>
<pre><code><span id="decoded">Enjoy this effect!</span>
<span id="encoded"></span>
</code></pre>
|
[] |
[
{
"body": "<pre><code>var decrypted = document.getElementById(\"decoded\");\nvar encrypted = document.getElementById(\"encoded\");\n\nfunction startdecrypt() {\n // Original text, split into an array and reversed (for faster pop())\n var originalText = decrypted.textContent.split('').reverse();\n var decryptedText = \"\";\n var i = 0;\n\n decrypted.textContent = \"\";\n\n var shuffleInterval = setInterval(function(){\n\n // Generate random strings. You can modify the generator function range\n // (Math.random()*(to-from+1)+from);\n var shuffledText = '';\n var j = originalText.length;\n while(j--) shuffledText += String.fromCharCode((Math.random()*94+33) | 0);\n // You can also use this generator to use only the remaining letters\n // while(j--) shuffledText += originalText[(Math.random()*j) | 0];\n\n // On every 10 cycles, remove a character from the original text to the decoded text\n if(i++ % 10 === 0) decryptedText += originalText.pop();\n\n // Display\n decrypted.textContent = decryptedText;\n encrypted.textContent = shuffledText;\n\n // Stop when done\n if(!shuffledText.length) clearInterval(shuffleInterval);\n\n // 50ms looks more dramatic\n },50);\n}\n\nif (window.addEventListener) {\n window.addEventListener('load', startdecrypt, false); //W3C\n} else {\n window.attachEvent('onload', startdecrypt); //IE\n}\n</code></pre>\n\n<h2><a href=\"http://jsbin.com/OtUZaGOy/4/edit\">Changes</a></h2>\n\n<ul>\n<li><p>Everything in one function</p></li>\n<li><p>Simplified the code</p></li>\n<li><p>Using <code>setInterval</code> rather than <code>setTimeout</code>. This is more efficient since you don't create timers everytime</p></li>\n<li><p>More drama by adding random string generator, instead of just your original set of letters. This adds more mystery to the next letters.</p></li>\n<li><p>In addition to the code, a monospace font would be more dramatic. It avoids the to-fro movement of the decoding text.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:40:17.037",
"Id": "37420",
"ParentId": "37411",
"Score": "6"
}
},
{
"body": "<p>Joseph gave a fine answer, so this is just for fun. You said you might want a jQuery alternative, so here's a plugin. More code, but a lot more flexible.</p>\n\n<p>Notable stuff: Options. You can control the number of time each letter should change before being \"decoded\", which letters should be used for the code, how long (roughly) the animation should run, and a class name for the span that holds the code.<br>\nThe span that holds the code is created when the effect starts, and removed afterwards, so you only need the \"real\" text in the HTML.</p>\n\n<p><a href=\"http://jsfiddle.net/y58hP/\" rel=\"nofollow\">Here's a demo</a> and here's the plugin code</p>\n\n<pre><code>jQuery.fn.decodeEffect = (function ($) {\n var defaultOptions = {\n duration: 3000,\n stepsPerGlyph: 10,\n codeGlyphs: \"ABCDEFGHIJKLMNOPQRSTUWVXYZ1234567890\",\n className: \"code\"\n };\n\n // get a random string from the given set,\n // or from the 33 - 125 ASCII range\n function randomString(set, length) {\n var string = \"\", i, glyph;\n for(i = 0 ; i < length ; i++) {\n glyph = Math.random() * set.length;\n string += set[glyph | 0];\n }\n return string;\n }\n\n // this function starts the animation. Basically a closure\n // over the relevant vars. It creates a new separate span\n // for the code text, and a stepper function that performs\n // the animation itself\n function animate(element, options) {\n var text = element.text(),\n span = $(\"<span/>\").addClass(options.className).insertAfter(element),\n interval = options.duration / (text.length * options.stepsPerGlyph),\n step = 0,\n length = 0,\n stepper = function () {\n if(++step % options.stepsPerGlyph === 0) {\n length++;\n element.text(text.slice(0, length));\n }\n if(length <= text.length) {\n span.text(randomString(options.codeGlyphs, text.length - length));\n setTimeout(stepper, interval);\n } else {\n span.remove();\n }\n };\n element.text(\"\");\n stepper();\n }\n\n // Basic jQuery plugin pattern\n return function (options) {\n options = $.extend({}, defaultOptions, (options || {}));\n return this.each(function () {\n animate($(this), options);\n });\n };\n}(jQuery));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T23:52:40.880",
"Id": "62982",
"Score": "0",
"body": "This is also great Flambino‼ :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:30:43.757",
"Id": "37426",
"ParentId": "37411",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37420",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T13:33:05.713",
"Id": "37411",
"Score": "3",
"Tags": [
"javascript",
"performance",
"jquery",
"html",
"animation"
],
"Title": "Text revelation effect"
}
|
37411
|
<p>This code works great, but I think it can be reduced.</p>
<pre><code>@if (Session["Success"] != null)
{
<text>
<div class="alert alert-success">@Session["Success"]</div>
</text>
Session.Remove("Success");
}
else if (Session["Error"] != null)
{
<text>
<div class="alert alert-danger">@Session["Error"]</div>
</text>
Session.Remove("Error");
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:05:52.863",
"Id": "61893",
"Score": "1",
"body": "What should happen when `Session` contains both `\"Success\"` and `\"Error\"`? Should that behave exactly the same as your code (i.e. print the success case)? Or is that situation impossible?"
}
] |
[
{
"body": "<p>It's a bad idea to modify the session state from inside a view or a partial view. Instead, I would create an alert view model</p>\n\n<pre><code>public class AlertViewModel\n{\n public AlertType AlertType { get; set; }\n public string Message { get; set; }\n}\n\npublic enum AlertType\n{\n None,\n Success,\n Error\n}\n</code></pre>\n\n<p>and use that from inside the view/partial view, for example:</p>\n\n<pre><code>@if (Model.AlertType != AlertType.None)\n{\n string alertClass = Model.AlertType.ToString().ToLowerInvariant();\n\n <text>\n <div class=\"alert alert-@alertClass\">@Model.Message</div>\n </text>\n}\n</code></pre>\n\n<p>This way, you avoid modifying the session where someone else may not expect it, and you have a cleaner view.</p>\n\n<p>About populating the view: I do not know why you are using the session, but if the value is only needed for one request, you should consider using <code>TempData</code> instead. In any way, just populate the view model in the controller and remove the session value if you need to.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:45:50.440",
"Id": "37429",
"ParentId": "37414",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37429",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T13:58:24.003",
"Id": "37414",
"Score": "5",
"Tags": [
"c#",
".net",
"asp.net-mvc",
"razor"
],
"Title": "Displaying alert from an action"
}
|
37414
|
<h3>1. Introduction</h3>
<p>This is a solution to <a href="https://codereview.meta.stackexchange.com/a/1248/11728">Weekend Challenge #3</a>: a Sudoku solver in Python. It works by translating a Sudoku puzzle into an <a href="https://en.wikipedia.org/wiki/Exact_cover" rel="noreferrer">exact cover</a> problem, and then solving the exact cover problem using Donald Knuth's "<a href="http://lanl.arxiv.org/pdf/cs/0011047.pdf" rel="noreferrer">Algorithm X</a>". The code should be self-explanatory (assuming you've read and understood the Knuth paper), so I won't say more than that.</p>
<p>All comments welcome.</p>
<h3>2. exactcover.py</h3>
<pre><code>from collections import Iterator, defaultdict
from random import shuffle
class ExactCover(Iterator):
"""An iterator that yields solutions to an EXACT COVER problem.
An EXACT COVER problem consists of a set of "choices". Each choice
satisfies one or more "constraints". Choices and constraints may
be represented by any hashable Python objects, with the proviso
that all choices must be distinct, as must all constraints.
A solution is a list of choices such that each constraint is
satisfied by exactly one of the choices in the solution.
The constructor takes three arguments:
constraints A map from each choice to an iterable of constraints
satisfied by that choice.
initial An iterable of choices that must appear in every
solution. (Default: no choices.)
random Generate solutions in random order? (Default: False.)
For example:
>>> next(ExactCover(dict(A = [1, 4, 7],
... B = [1, 4],
... C = [4, 5, 7],
... D = [3, 5, 6],
... E = [2, 3, 6, 7],
... F = [2, 7])))
['B', 'D', 'F']
"""
# This implements Donald Knuth's "Algorithm X"
# http://lanl.arxiv.org/pdf/cs/0011047.pdf
def __init__(self, constraints, initial=(), random=False):
self.random = random
self.constraints = constraints
# A map from constraint to the set of choices that satisfy
# that constraint.
self.choices = defaultdict(set)
for i in self.constraints:
for j in self.constraints[i]:
self.choices[j].add(i)
# The set of constraints which are currently unsatisfied.
self.unsatisfied = set(self.choices)
# The partial solution currently under consideration,
# implemented as a stack of choices.
self.solution = []
# Make all the initial choices.
try:
for i in initial:
self._choose(i)
self.it = self._solve()
except KeyError:
# Initial choices were contradictory, so there are no solutions.
self.it = iter(())
def __next__(self):
return next(self.it)
next = __next__ # for compatibility with Python 2
def _solve(self):
if not self.unsatisfied:
# No remaining unsatisfied constraints.
yield list(self.solution)
return
# Find the constraint with the fewest remaining choices.
best = min(self.unsatisfied, key=lambda j:len(self.choices[j]))
choices = list(self.choices[best])
if self.random:
shuffle(choices)
# Try each choice in turn and recurse.
for i in choices:
self._choose(i)
for solution in self._solve():
yield solution
self._unchoose(i)
def _choose(self, i):
"""Make choice i; mark constraints satisfied; and remove any
choices that clash with it.
"""
self.solution.append(i)
for j in self.constraints[i]:
self.unsatisfied.remove(j)
for k in self.choices[j]:
for l in self.constraints[k]:
if l != j:
self.choices[l].remove(k)
def _unchoose(self, i):
"""Unmake choice i; restore constraints and choices."""
self.solution.pop()
for j in self.constraints[i]:
self.unsatisfied.add(j)
for k in self.choices[j]:
for l in self.constraints[k]:
if l != j:
self.choices[l].add(k)
</code></pre>
<h3>3. sudoku.py</h3>
<pre><code>from collections import Iterator
from copy import deepcopy
from exactcover import ExactCover
from itertools import islice, product
from math import ceil, sqrt
from random import shuffle
from string import ascii_lowercase, ascii_uppercase
DIGITS = '123456789' + ascii_uppercase + ascii_lowercase
def make_grid(n):
"""Return a Sudoku grid of size n x n."""
return [[-1] * n for _ in range(n)]
def puzzle_to_grid(puzzle):
"""Convert printed representation of a Sudoku puzzle into grid
representation (a list of lists of numbers, or -1 if unknown).
"""
puzzle = puzzle.split()
grid = make_grid(len(puzzle))
for y, row in enumerate(puzzle):
for x, d in enumerate(row):
grid[y][x] = DIGITS.find(d)
return grid
def grid_to_puzzle(grid):
"""Convert grid representation of a Sudoku puzzle (a list of lists of
numbers, or -1 if unknown) into printed representation.
"""
return '\n'.join(''.join('.' if d == -1 else DIGITS[d] for d in row)
for row in grid)
class Sudoku(Iterator):
"""An iterator that yields the solutions to a Sudoku problem.
The constructor takes three arguments:
puzzle The puzzle to solve, in the form of a string of n
words, each word consisting of n characters, either a
digit or a dot indicating a blank square.
(Default: the blank puzzle.)
n The size of the puzzle. (Default: 9.)
m The width of the blocks. (Default: the square root of n,
rounded up.)
random Generate solutions in random order? (Default: False.)
For example:
>>> print(next(Sudoku('''...84...9
... ..1.....5
... 8...2146.
... 7.8....9.
... .........
... .5....3.1
... .2491...7
... 9.....5..
... 3...84...''')))
632845179
471369285
895721463
748153692
163492758
259678341
524916837
986237514
317584926
"""
def __init__(self, puzzle=None, n=9, m=None, random=False):
if puzzle:
puzzle = puzzle.split()
self.n = n = len(puzzle)
initial = self._encode_puzzle(puzzle)
else:
self.n = n
initial = ()
if m is None:
m = int(ceil(sqrt(n)))
assert(0 < n <= len(DIGITS))
assert(n % m == 0)
def constraints(choice):
d, x, y = self._decode_choice(choice)
block = m * (x // m) + y // (n // m)
return [a + 4 * (b + n * c) for a, b, c in [
(0, x, y), # Any digit at x, y.
(1, d, y), # Digit d in row y.
(2, d, x), # Digit d in column x.
(3, d, block), # Digit d in block.
]]
self.solver = ExactCover({i: constraints(i) for i in range(n ** 3)},
initial, random)
def __next__(self):
return self._decode_solution(next(self.solver))
next = __next__ # for compatibility with Python 2
def _encode_choice(self, d, x, y):
"""Encode the placement of d at (x, y) as a choice."""
n = self.n
assert(0 <= d < n and 0 <= x < n and 0 <= y < n)
return d + n * (x + n * y)
def _decode_choice(self, choice):
"""Decode a choice into a (digit, x, y) tuple."""
choice, digit = divmod(choice, self.n)
y, x = divmod(choice, self.n)
return digit, x, y
def _encode_puzzle(self, puzzle):
"""Encode a Sudoku puzzle and yield initial choices."""
for y, row in enumerate(puzzle):
for x, d in enumerate(row):
digit = DIGITS.find(d)
if digit != -1:
yield self._encode_choice(digit, x, y)
def _decode_solution(self, solution):
"""Decode a Sudoku solution and return it as a string."""
grid = make_grid(self.n)
for d, x, y in map(self._decode_choice, solution):
grid[y][x] = d
return grid_to_puzzle(grid)
class ImpossiblePuzzle(Exception): pass
class AmbiguousPuzzle(Exception): pass
def solve(puzzle, m=None):
"""Solve the Sudoku puzzle and return its unique solution. If the
puzzle is impossible, raise ImpossiblePuzzle. If the puzzle has
multiple solutions, raise AmbiguousPuzzle.
Optional argument m is the width of the blocks (default: the
square root of n, rounded up).
For example:
>>> print(solve('''.6.5..9..
... ..4.....6
... .29..3..8
... ....32..4
... ..61.75..
... 1..95....
... 6..4..27.
... 2.....4..
... ..7..6.8.'''))
768514923
314829756
529763148
975632814
836147592
142958637
693481275
281375469
457296381
>>> print(solve('''...8.....
... ..1.....5
... 8....1...
... 7.8....9.
... ...1.....
... .5....3.1
... ....1...7
... 9.....5..
... 3........'''))
... # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ImpossiblePuzzle: no solutions
"""
solutions = list(islice(Sudoku(puzzle, m=m), 2))
if len(solutions) == 1:
return solutions[0]
elif len(solutions) == 0:
raise ImpossiblePuzzle('no solutions')
else:
raise AmbiguousPuzzle('two or more solutions')
def make_puzzle(n=9, m=None):
"""Return a random nxn Sudoku puzzle with 180-degree rotational
symmetry. The puzzle returned is minimal in the sense that no
symmetric pair of givens can be removed without making the puzzle
ambiguous.
The optional arguments are n, the size of the puzzle (default: 9)
and m, the width of the blocks (default: the square root of n,
rounded up).
"""
grid = puzzle_to_grid(next(Sudoku(n=n, m=m, random=True)))
coords = list(divmod(i, n) for i in range((n ** 2 + 1) // 2))
shuffle(coords)
for i, j in coords:
g = deepcopy(grid)
g[i][j] = g[n - i - 1][n - j - 1] = -1
try:
solve(grid_to_puzzle(g))
grid = g
except AmbiguousPuzzle:
pass
return grid_to_puzzle(grid)
</code></pre>
<h3>4. Examples</h3>
<pre class="lang-none prettyprint-override"><code>>>> for puzzle in map(make_puzzle, (4, 6, 9, 12, 16)):
... print('\n'.join('{} {}'.format(*a) for a in zip(puzzle.split(), solve(puzzle).split())), '\n')
...3 1243
.4.. 3412
..2. 4321
2... 2134
..2..4 632514
.1.2.. 415236
3.4... 354162
...3.5 126345
..1.5. 241653
5..4.. 563421
...3...4. 678325149
1.94..... 139476528
...98.3.7 452981367
.87....34 587612934
..4...7.. 214893756
39....81. 396754812
7.5.69... 725169483
.....72.1 863547291
.4...8... 941238675
6A....7.8... 6ABC42758391
.952C.A...4. 3952C8A17B46
4..1....5... 47819B635C2A
83...1..96.. 832471BA96C5
7......921.4 7B658C3921A4
.....6.4.7.. 91CA2654B783
..A.3.2..... B5A7342C1869
C.196......B C4196A87325B
..38..1...7C 2638591BA47C
...3....6..2 1C73A54869B2
.8...3.2451. A896B3C24517
...B.7....38 524B1796CA38
.F3D..A.......87 1F3D95AEC46BG287
.9B.63....5.F... E9BC63D87G52FA14
.62.....91.AD... 862GB74F91EADC35
457..G.1....9... 457ACG21FD8396BE
.8..5..G..AC.... F8D25E6G13AC497B
..6E.48.D..7.1.G CB6E3489D5F7A12G
5.14D...G...68.. 5314D27AGEB968FC
.A.7.FC.8.4..... 9AG71FCB82465ED3
.....D.5.82.3.C. GE4FAD95B82137C6
..91...4...G25.F BD918CE4367G25AF
7.A.G..3.CD.EB.. 72A6G1F35CD4EB98
....76..A..E..G. 3C8576B2AF9E14GD
...8....E.3..G62 D4C8F917EA35BG62
...92.3C.....FE. 67592A3C4BGD8FE1
...B.8....CF.35. 21EB48GD69CF735A
AG.......7..CD4. AGF3EB562718CD49
</code></pre>
|
[] |
[
{
"body": "<p>I have only a minor comment:</p>\n\n<p>In <code>ExactCover.__init__</code>, I would use <code>iteritems</code> rather than iterating over the keys of <code>constraints</code>:</p>\n\n<pre><code>for choice, constraintsList in self.constraints.iteritems():\n for constraint in constraintsList:\n self.choices[choice].add(constraint)\n</code></pre>\n\n<p>You have written good code, factored into nice, small functions with clear purpose. Well done!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T02:32:30.150",
"Id": "37457",
"ParentId": "37415",
"Score": "5"
}
},
{
"body": "<p>This is not quite right:</p>\n\n<pre><code>def _unchoose(self, i):\n \"\"\"Unmake choice i; restore constraints and choices.\"\"\"\n self.solution.pop()\n</code></pre>\n\n<p>It promises to undo an arbitrary choice <code>i</code> but actually pops the latest one from <code>self.solution</code>. As you only use if for undoing the latest choice, I suggest to drop the parameter:</p>\n\n<pre><code>def _unchoose(self):\n \"\"\"Unmake latest choice; restore constraints and choices.\"\"\"\n i = self.solution.pop()\n</code></pre>\n\n<p>Actually the choose-unchoose pattern feels a bit awkward to me. I'd prefer functional programming instead. Another idea that would make me feel more comfortable would be to create a context manager:</p>\n\n<pre><code>@contextlib.contextmanager\ndef _tentative_choice(self, i):\n self._choose(i)\n yield\n self._unchoose(i)\n</code></pre>\n\n<p>use: </p>\n\n<pre><code> for i in choices:\n with self._tentative_choice(i):\n for solution in self._solve():\n yield solution\n</code></pre>\n\n<p>Another small concern is that you use a local variable <code>choices</code> in methods of a class that has an instance variable <code>self.choices</code>. This may lead to confusion; I'd use a different name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:22:48.330",
"Id": "62080",
"Score": "1",
"body": "Good review! But can you explain the use of `try: ... finally:` in the context manager? If `_solve` raises an exception then something must have gone so badly wrong that I can't expect to be able to continue searching, so surely there's no need to worry about restoring the context in that case?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T18:51:32.487",
"Id": "62132",
"Score": "1",
"body": "@GarethRees You are right. I was reaching for a more defensive style, but I can't see an actual benefit now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:58:31.423",
"Id": "37492",
"ParentId": "37415",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37492",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T14:31:55.517",
"Id": "37415",
"Score": "27",
"Tags": [
"python",
"algorithm",
"recursion",
"sudoku",
"community-challenge"
],
"Title": "Sudoku using 'exact cover' solver"
}
|
37415
|
<p>I am building a cypher program which uses a matrix of numbers and letters. A message is encoded according to the row and column each letter of the message is found in the matrix.</p>
<p>I am trying to find a nice way of iterating over the 2D matrix (6*6).</p>
<pre><code> for char in range (0, len(message), 1):
for i in range(0, len(rows), 1):
for y in range(0, len(cols), 1):
if matrix[i][y] == message[char]:
cyphermessage.append(i)
cyphermessage.append(y)
cyphermessage.append(" ")
</code></pre>
<p>But this method uses a 3-tier <code>for</code> loop which makes it \$\mathcal{O}((N)*3)\$, plus the the cypher append messages are quite ugly.</p>
|
[] |
[
{
"body": "<p>Don't search – find. Specifically, don't iterate through all matrix entries for each character. Instead, build a dictionary that maps the characters in the matrix to a pair of indices.</p>\n\n<p>Also, don't loop over indices (in <code>message</code>) unless you have to. Now we have:</p>\n\n<pre><code>position_lookup = dict()\nfor x in range(len(matrix)):\n for y in range(len(matrix[x])):\n position_lookup[matrix[x][y]] = (x, y)\n\nfor char in message:\n if char in position_lookup:\n x, y = position_lookup[char]\n cyphermessage.extend([x, y, \" \"])\n</code></pre>\n\n<p>Technically, this behaves different from the code you wrote: consider what happens when one character occurs multiple times in the <code>matrix</code> – I only use the last occurrence, while you append all possibilities.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:02:09.347",
"Id": "61892",
"Score": "0",
"body": "let me read about dictionaries, an ill get back to you with relevant points."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:30:16.173",
"Id": "61900",
"Score": "0",
"body": "could i add a third field to the dictionary to use as a key; for instance, i am using the row/collum lable as the cypher, rather than haveing 01 i would have AB"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:35:48.390",
"Id": "61901",
"Score": "0",
"body": "am sorry i misunderstood the code, the problem is i need to change position_lookup[matrix[x][y]] = (x, y) so that the values store will be A,A for position 0,0.\nso instaed of using a number as the key i would store a char letter (A-F)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T15:54:58.110",
"Id": "61903",
"Score": "0",
"body": "@Babbleshack I don't quite understand what you are trying to do – I just showed a way to improve your code. If you need to change what your code does, stackoverflow might be of more help. Anyway, what would be wrong with translating the indices along the lines of `letters = \"ABCDEFG\"; letter = letters[i]`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:16:05.747",
"Id": "61909",
"Score": "0",
"body": "haha excellent idea! thanks for that, and i realize that i asked a seperate questions, sorry about that!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:22:21.783",
"Id": "62464",
"Score": "0",
"body": "By the way i dont think that extends() takes multiple args"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:39:14.077",
"Id": "62468",
"Score": "0",
"body": "@Babbleshack it doesn't and I aren't using it as such: `[x, y, \" \"]` is a single list which we pass to `extend`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T14:55:50.767",
"Id": "37419",
"ParentId": "37417",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37419",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T14:34:48.413",
"Id": "37417",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"matrix"
],
"Title": "Reading Multidimensional arrays"
}
|
37417
|
<p>I have made an application to display images in the form of gallery, from terminal if you are standing at the same location then it will open those images in the gallery if it does not have it will prompt to select the directory.</p>
<p>below is the module: <strong>gallery.py</strong></p>
<pre><code>import sys
import os
import utils
from PyQt4 import QtGui, QtCore
class MyListModel(QtCore.QAbstractTableModel):
def __init__(self, window, datain, col, thumbRes, parent=None):
""" Methods in this class sets up data/images to be
visible in the table.
Args:
datain(list): 2D list where each item is a row
col(int): number of columns to show in table
thumbRes(tuple): resolution of the thumbnail
"""
QtCore.QAbstractListModel.__init__(self, parent)
self._slideShowWin = window
self._thumbRes = thumbRes
self._listdata = datain
self.pixmap_cache = {}
self._col = col
def colData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
return None
def headerData(self, section, orientation, role):
if role == QtCore.Qt.DisplayRole:
if orientation in [QtCore.Qt.Vertical, QtCore.Qt.Horizontal]:
return None
def rowCount(self, parent=QtCore.QModelIndex()):
return len(self._listdata)
def columnCount(self, parent):
return self._col
def data(self, index, role):
""" method sets the data/images to visible in table
"""
if index.isValid() and role == QtCore.Qt.SizeHintRole:
return QtCore.QSize(*self._thumbRes)
if index.isValid() and role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
if index.isValid() and role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
try:
fileName = os.path.split(self._listdata[row][column])[-1]
except IndexError:
return
return fileName
if index.isValid() and role == QtCore.Qt.ToolTipRole:
row = index.row()
column = index.column()
try:
fileName = os.path.split(self._listdata[row][column])[-1]
except IndexError:
return
exifData = "\n".join(list(utils.getExifData((self._listdata[row][column]))))
return QtCore.QString(exifData if exifData else fileName)
if index.isValid() and role == QtCore.Qt.DecorationRole:
row = index.row()
column = index.column()
try:
value = self._listdata[row][column]
except IndexError:
return
pixmap = None
# value is image path as key
if self.pixmap_cache.has_key(value) == False:
pixmap=utils.generatePixmap(value)
self.pixmap_cache[value] = pixmap
else:
pixmap = self.pixmap_cache[value]
return QtGui.QImage(pixmap).scaled(self._thumbRes[0],self._thumbRes[1],
QtCore.Qt.KeepAspectRatio)
def flags(self, index):
return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def setData(self, index, value, role=QtCore.Qt.EditRole):
if role == QtCore.Qt.EditRole:
row = index.row()
column = index.column()
try:
newName = os.path.join(str(os.path.split(self._listdata[row][column])[0]), str(value.toString()))
except IndexError:
return
utils._renameFile(self._listdata[row][column], newName)
self._listdata[row][column] = newName
self.dataChanged.emit(index, index)
return True
return False
class GalleryUi(QtGui.QTableView):
""" Class contains the methods that forms the
UI of Image galery
"""
def __init__(self, window, imgagesPathLst=None):
super(GalleryUi, self).__init__()
self._slideShowWin = window
self.__sw = QtGui.QDesktopWidget().screenGeometry(self).width()
self.__sh = QtGui.QDesktopWidget().screenGeometry(self).height()
self.__animRate = 1200
self.setUpWindow(imgagesPathLst)
def setUpWindow(self, images=None):
""" method to setup window frameless and fullscreen,
setting up thumbnaul size and animation rate
"""
if not images:
path = utils._browseDir("Select the directory that contains images")
images = slideShowBase.ingestData(path)
thumbWidth = 200
thumbheight = thumbWidth + 20
self.setWindowFlags(
QtCore.Qt.Widget |
QtCore.Qt.FramelessWindowHint |
QtCore.Qt.X11BypassWindowManagerHint
)
col = self.__sw/thumbWidth
self._twoDLst = utils.convertToTwoDList(images, col)
self.setGeometry(0, 0, self.__sw, self.__sh)
self.showFullScreen()
self.setColumnWidth(thumbWidth, thumbheight)
self._lm = MyListModel(self._slideShowWin, self._twoDLst, col, (thumbWidth, thumbheight), self)
self.setShowGrid(False)
self.setWordWrap(True)
self.setModel(self._lm)
self.resizeColumnsToContents()
self.resizeRowsToContents()
self.selectionModel().selectionChanged.connect(self.selChanged)
def selChanged(self):
if self._slideShowWin:
row = self.selectionModel().currentIndex().row()
column = self.selectionModel().currentIndex().column()
# if specific image is selected the slideshow opens paused.
self._slideShowWin.playPause()
self._slideShowWin.showImageByPath(self._twoDLst[row][column])
def animateUpSlideShow(self):
""" animate the slideshow window back up
to view mode and starts the slideShowBase
where it was paused.
"""
self.animateUpGallery()
self.animation = QtCore.QPropertyAnimation(self._slideShowWin, "geometry")
self.animation.setDuration(self.__animRate);
self.animation.setStartValue(QtCore.QRect(0, self.__sh, self.__sw, self.__sh))
self.animation.setEndValue(QtCore.QRect(0, 0, self.__sw, self.__sh))
self.animation.start()
self._slideShowWin.activateWindow()
self._slideShowWin.raise_()
self._slideShowWin.playPause()
def animateUpGallery(self):
""" animate the gallery window up to make slideshow visible
"""
self.animGallery = QtCore.QPropertyAnimation(self, "geometry")
self.animGallery.setDuration(self.__animRate);
self.animGallery.setStartValue(QtCore.QRect(0, 0, self.__sw, self.__sh))
self.animGallery.setEndValue(QtCore.QRect(0, -(self.__sh), self.__sw, self.__sh))
self.animGallery.start()
def keyPressEvent(self, keyevent):
""" Capture key to exit, next image, previous image,
on Escape , Key Right and key left respectively.
"""
event = keyevent.key()
if event == QtCore.Qt.Key_Escape:
if self._slideShowWin:
self._slideShowWin.close()
self.close()
if event == QtCore.Qt.Key_Up:
if self._slideShowWin:
self.animateUpSlideShow()
def main(imgLst=None):
""" method to start gallery standalone
"""
app = QtGui.QApplication(sys.argv)
window = GalleryUi(None, imgLst)
window.raise_()
sys.exit(app.exec_())
if __name__ == '__main__':
curntPath = os.getcwd()
if len(sys.argv) > 1:
curntPath = sys.argv[1:]
main(utils.ingestData(curntPath))
</code></pre>
<p>and dependent module <strong>utils.py</strong>
some of the methods in the below are used by module slideshow which can also launch the image gallery from which a 2D list containing image paths.</p>
<pre><code>import os
import sys
import exifread
from PyQt4 import QtGui
def isExtensionSupported(filename):
""" Supported extensions viewable in SlideShow
"""
reader = QtGui.QImageReader()
ALLOWABLE = [str(each) for each in reader.supportedImageFormats()]
return filename.lower()[-3:] in ALLOWABLE
def imageFilePaths(paths):
imagesWithPath = []
for _path in paths:
dirContent = getDirContent(_path)
for each in dirContent:
selFile = os.path.join(_path, each)
if ifFilePathExists(selFile) and isExtensionSupported(selFile):
imagesWithPath.append(selFile)
return list(set(imagesWithPath))
def ifFilePathExists(selFile):
return os.path.isfile(selFile)
def getDirContent(path):
try:
return os.listdir(path)
except OSError:
raise OSError("Provided path '%s' doesn't exists." % path)
def getExifData(filePath):
""" Gets exif data from image
"""
try:
f = open(filePath, 'rb')
except OSError:
return
tags = exifread.process_file(f)
exifData = {}
if tags:
for tag, data in tags.iteritems():
if tag != 'EXIF Tag 0x9009':
yield "%s: %s" % (tag, data)
def convertToTwoDList(l, n):
""" Method to convert a list to two
dimensional list for QTableView
"""
return [l[i:i+n] for i in range(0, len(l), n)]
def _renameFile(fileToRename, newName):
""" method to rename a image name when double click
"""
try:
os.rename(str(fileToRename), newName)
except Exception, err:
print err
def _browseDir(label):
""" method to browse path you want to
view in gallery
"""
selectedDir = str(QtGui.QFileDialog.getExistingDirectory(None,
label,
os.getcwd()))
if selectedDir:
return selectedDir
else:
sys.exit()
def generatePixmap(value):
""" generates a pixmap if already not incache
"""
pixmap=QtGui.QPixmap()
pixmap.load(value)
return pixmap
def ingestData(paths):
""" This method is used to create a list containing
images path to slideshow.
"""
if isinstance(paths, list):
imgLst = imageFilePaths(paths)
elif isinstance(paths, str):
imgLst = imageFilePaths([paths])
else:
print "You can either enter a list of paths or single path"
return imgLst
</code></pre>
<p>I need a code review for the implementation, any Suggestions/hints is welcome that I can use to improve the code and more testable? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T05:17:30.260",
"Id": "62214",
"Score": "0",
"body": "MyListModel.colData() and MyListData.headerData() don't do anything. They always return None."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:22:39.617",
"Id": "62295",
"Score": "0",
"body": "if i don't set it to return none the header will show numbers in for rows and columns"
}
] |
[
{
"body": "<p><strong>Disclaimer:</strong> this is not a design pattern review, but rather a Pythonization one.</p>\n\n<ol>\n<li><p>Not always returning a value: <code>MyListModel.colData()</code> <code>MyListModel.headerData()</code>. Even though Python implicitly returns <code>None</code> if you don't specify a return value or return statement at all, it is better to return explicitly in all the code branches, or have a catch-all return:</p>\n\n<pre><code>def colData(self, section, orientation, role):\n if role == QtCore.Qt.DisplayRole:\n return None\n return None\n</code></pre></li>\n<li><p>Inconsistent return statements: in <code>MyListModel.data()</code>, <code>MyListModel.setData()</code> and others you mix return statements with value and the ones without value. Consider returning <code>None</code> explicitly.</p></li>\n<li><p>In <code>MyListModel.data()</code> the check <code>index.isValid()</code> is repeated over and over again, a single check would be sufficient:</p>\n\n<pre><code>if not index.isValid():\n return None\n\nif role == QtCore.Qt.SizeHintRole:\n return QtCore.QSize(*self._thumbRes)\n</code></pre></li>\n<li><p>Always use a file as a context manager, this way you wouldn't leak open files (e.g. in <code>getExifData</code>), even if your code with throw during file processing:</p>\n\n<pre><code>try:\n with open(filePath, 'rb') as f:\n # Work with file\nexcept OSError:\n return\n</code></pre></li>\n<li><p>Use <a href=\"https://www.youtube.com/watch?v=MvXxpU3wcLc\" rel=\"nofollow\">list comprehensions</a> and <a href=\"https://www.youtube.com/watch?v=qZVWbkE-Fg0\" rel=\"nofollow\">generator expressions</a>, they rock! Here's how I would rewrite <code>getExifData</code>:</p>\n\n<pre><code>def get_exif_data(file_path):\n \"\"\" Gets exif data from image\n \"\"\"\n try:\n with open(file_path, 'rb') as f:\n return (\"%s: %s\" % (tag, data)\n for tag, data in exifread.process_file(f).iteritems()\n if tag != 'EXIF Tag 0x9009')\n except OSError:\n return\n</code></pre>\n\n<p>Here's the <code>imageFilePaths</code>:</p>\n\n<pre><code>def image_file_paths(paths):\n images = {\n joined_path\n for path in paths\n for each in get_dir_content(path)\n for joined_path in [os.path.join(path, each)]\n if if_file_path_exists(joined_path)\n if is_extension_supported(joined_path)\n }\n\n return list(images)\n</code></pre></li>\n<li><p>You should really follow <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">pep8</a>, name your methods <code>with_underscore_separators</code>, but do <code>notCamelCase</code> them.</p></li>\n<li><p>Methods/functions should not have unexpected side-effects like printing error messages on their own (see <code>_renameFile</code>, <code>ingestData</code>) or even worse - perform exit (see <code>_browseDir</code>). Consider raising appropriate exceptions, e.g. <code>ValueError</code> would be a perfect fit for parameter type-checking.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:07:53.353",
"Id": "62097",
"Score": "0",
"body": "great thanks @Ihor Kaharlichenko. I have habit of coding from my workplace where we do not use underscore within the method names, however camelCase sticking the rest with PEP8\n\nI agree using context manager, intact earlier i was going use it, it just slipped my mind but i was returning generator object in that method.\n\nlastly for imageFilePaths method i wanted to keep the code more readable, for someone else the way you have accomplished a list being return could be slightly less readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:13:16.893",
"Id": "62100",
"Score": "0",
"body": "expected comments on `animateUpGallery` and `animateUpSlideShow` in gallery.py module."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T08:29:31.530",
"Id": "37485",
"ParentId": "37418",
"Score": "1"
}
},
{
"body": "<p>I would change</p>\n\n<pre><code> def ifFilePathExists(selFile):\n</code></pre>\n\n<p>to</p>\n\n<pre><code> def file_path_exists(sel_file):\n</code></pre>\n\n<p>Saying \"if if\" feels wrong:</p>\n\n<pre><code> if ifFilePathExists(filename):\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:09:00.893",
"Id": "37544",
"ParentId": "37418",
"Score": "4"
}
},
{
"body": "<p>I'm not sure this function adds any value.</p>\n\n<pre><code>def ifFilePathExists(selFile):\n return os.path.isfile(selFile)\n</code></pre>\n\n<p>Why not call os.path.isfile() directly?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T01:55:22.507",
"Id": "62179",
"Score": "0",
"body": "then I need to know how to mock built-in `os.path.isfile` !!! since I am testing `imageFilePaths` method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:02:10.293",
"Id": "62182",
"Score": "0",
"body": "here is the [test][1] \n\n\n\n[1]: https://github.com/sanfx/slideShow/blob/master/tests/test_utils.py"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:26:53.013",
"Id": "62191",
"Score": "0",
"body": "I think I would create a test directory with some test files in it. No need to mock the isfile() function."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T01:52:38.953",
"Id": "37558",
"ParentId": "37418",
"Score": "2"
}
},
{
"body": "<pre><code> def ingestData(paths):\n \"\"\" This method is used to create a list containing\n images path to slideshow.\n \"\"\"\n if isinstance(paths, list):\n imgLst = imageFilePaths(paths)\n\n elif isinstance(paths, str):\n imgLst = imageFilePaths([paths])\n else:\n print \"You can either enter a list of paths or single path\"\n return imgLst\n</code></pre>\n\n<p>The imgLst variable is not set in all cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T01:57:09.017",
"Id": "62180",
"Score": "0",
"body": "do you mean I have ti first initialize it as None or empty list ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:08:54.077",
"Id": "62185",
"Score": "0",
"body": "how is imgLst not set?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:25:29.570",
"Id": "62190",
"Score": "1",
"body": "When the \"else\" is executed, imgLst is not set. The statement \"return imgLst\" will fail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T04:31:26.410",
"Id": "62204",
"Score": "0",
"body": "that is true. I will fix that , I am thinking to use an Exception instead of printing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T05:10:46.040",
"Id": "62207",
"Score": "0",
"body": "I think this whole function can go away. Calling imageFilePaths([\"filename\"]) and making the user type the [ ] isn't really a burden in my opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:52:34.983",
"Id": "62300",
"Score": "0",
"body": "if while passing arguments from command line list contains space that can cause problem"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T01:55:53.140",
"Id": "37559",
"ParentId": "37418",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "37485",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T14:50:01.367",
"Id": "37418",
"Score": "0",
"Tags": [
"python",
"design-patterns"
],
"Title": "Feedback on logic implementation of PyQt4 based Image gallery using QTableView"
}
|
37418
|
<p><a href="http://www.spoj.com/problems/SHPATH/" rel="nofollow">This is the problem</a> and my solution to this is:</p>
<pre><code>#include "iostream"
#include "stdio.h"
#include "algorithm"
#include "math.h"
#include "string.h"
#include "time.h"
#include "stdlib.h"
#include <list>
#include <vector>
#include <string>
#include <queue>
#define MALLOC(name,type,n) (name=(type*)malloc(sizeof(type)*(n)))
using namespace std;
typedef unsigned long long int ll;
#include <cstdio>
#define gc getchar_unlocked
const ll INF=~0;
</code></pre>
<p>Fast input and output:</p>
<pre><code>void scanint(int &x)
{
register int c = gc();
x = 0;
int m=0;
if(c=='-')
m=1;
for(;(c<48 || c>57);c = gc());
for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
if(m==1)
x*=-1;
}
void scanstring(string& str)
{
str.clear();
str.reserve(20);
char x;
while((x=getchar_unlocked())!=EOF&&x!='\n'&&x!=' ')
str.push_back(x);
}
</code></pre>
<p>I'm hashing the names for that specific vertex.</p>
<p>The simple hash function:</p>
<pre><code>int hash(const string &x)
{
int y=0;
for (int i = 0; i < x.size(); ++i){
y+=x[i]*137;
}
return y%1000;
}
</code></pre>
<p><code>V</code> - total number of vertices</p>
<p><code>u</code>, <code>v</code>, <code>c</code> -source, destination, cost</p>
<pre><code>int V,u,v,c,e;
string name;
typedef pair<int ,int> ii;
typedef std::vector<int> vi;
typedef std::vector<ii> vii;
std::vector<vii> graph;
typedef pair<string,int> si;
vector<vector<si> > h_table;
vi sourced;
vector< vector<ll> > dijkstra_data;
</code></pre>
<p>Gets vertex position from name:</p>
<pre><code>int get_index(const string &s)
{
int h=hash(s);
for (int i = 0; i < h_table[h].size(); ++i){
if(h_table[h][i].first==s)
{
return h_table[h][i].second;
}
}
}
void dijkstra(int,int);
int main()
{
//freopen("input","r",stdin);
int tc;
cin>>tc;
while(tc--)
{
scanint(V);
h_table.clear();
h_table.assign(1000,vector<si>());
graph.clear();
graph.assign(V+1,vii());
sourced.clear();
sourced.assign(V+1,0);
dijkstra_data.clear();
dijkstra_data.assign(V+1,std::vector<ll> ());
// dijkstra_data stores all shortest paths from a source that have been calculated till now
for (int i = 1; i < V+1; ++i){
scanstring(name);
si x(name,i);
h_table[hash(name)].push_back(x);
scanint(e);
while(e--)
{
scanint(v);scanint(c);
graph[i].push_back(ii(v,c));
}
}
int cases;
scanint(cases);
string src,dest;
while(cases--)
{
scanstring(src);
scanstring(dest);
int isrc=get_index(src),idest=get_index(dest);
if(sourced[isrc])
printf("%llu\n", dijkstra_data[isrc][idest]);
else
dijkstra(isrc,idest);
}
}
return 0;
}
void dijkstra(int src,int dest)
{
vi visited(V+1,0);
std::vector<ll> dist(V+1,INF);
dist[src]=0;
typedef pair<int,ll> il;
typedef std::vector<il> vil;
std::priority_queue<il,vil,greater<il> > pq;
pq.push(il(src,0));
int n=1;
while(n<V&&!pq.empty())
{
il x=pq.top();
pq.pop();
int sv=x.first; ll sd=x.second;
if(visited[sv])
continue;
visited[sv]=1;n++;dist[sv]=sd;
for (int i = 0; i < graph[sv].size(); ++i){
ll d1=sd+graph[sv][i].second;
ll d2=dist[graph[sv][i].first];
if(d1<d2)
{
dist[graph[sv][i].first]=d1;
pq.push(il(graph[sv][i].first,d1));
}
}
}
dijkstra_data[src].assign(dist.begin(),dist.end());
sourced[src]=1;
printf("%llu\n", dist[dest]);
}
</code></pre>
<p>and TLE is my result.</p>
<p>I know I could use my own heap instead of STL <code>std::priority_queue</code>. I'm new to the STL so I want to know if there is anything associated with STL where I have caused more overhead.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:35:18.500",
"Id": "61913",
"Score": "2",
"body": "Note: `for(;(c<48 || c>57);c = gc());` is an endless loop should `c` equal EOF."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:38:13.387",
"Id": "61914",
"Score": "1",
"body": "All those STL `#include`s should use `<>`, not `\"\"`. You also use `<stdio.h>`, `printf`, and `malloc`, which indicate C code instead of C++ code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:40:30.137",
"Id": "61915",
"Score": "0",
"body": "Note: `int hash(const string &x)` returns values -999 to 999. I suspect this is a problem for `h_table[h]`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T19:58:19.670",
"Id": "61931",
"Score": "0",
"body": "@chux NO,int hash(const string &x) will only return betwen 0-999 as x[i] is always positive and since only maximum 10 chars of x are there so,it fits in integer range"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T20:00:20.443",
"Id": "61932",
"Score": "0",
"body": "@chux 'for(;(c<48 || c>57);c = gc());' that is fast integer so anything within integral values will be taken"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T20:02:49.457",
"Id": "61933",
"Score": "0",
"body": "@Jamal c++ codes can use all c libraries and functions of C language by including those libraries. I have submitted lots of codes like this and everything went right"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T20:14:26.293",
"Id": "61934",
"Score": "1",
"body": "Yes, it won't cause immediate problems, but `\"string.h\"` would only be needed if that happens to be your own defined header in the same directory. If you're just using `std::string`, then only `<string>` is needed. More information [here](http://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename?rq=1). Unless you have a necessary reason for these extra headers, your code will just look less like C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:39:54.597",
"Id": "61938",
"Score": "0",
"body": "@user2058841 (x[0] + x[1] ... x[9])*137 can well exceed 32767. `int` is not guaranteed to have a range greater than -32767 to 32767. Thus the comment about values -999 to 999."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:45:52.050",
"Id": "61939",
"Score": "1",
"body": "@user2058841 if `gc()` returns EOF, in `for(;(c<48 || c>57);c = gc());`, the `for` loop does not exit. Instead the loop repeats. `c` on the next call will get set to EOF again and again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:51:08.623",
"Id": "61940",
"Score": "0",
"body": "@chux thnx I'm wrong there"
}
] |
[
{
"body": "<p>In your hash function, you're doing <code>x.size()</code> in a loop, which will slow the function down quite a lot for a long string. Instead, store the size in a variable and compare to that</p>\n\n<pre><code>int hash(const string &x)\n{\n int y=0;\n int xLength = x.size();\n for (int i = 0; i < xLength; ++i){\n y+=x[i]*137;\n }\n return y%1000;\n}\n</code></pre>\n\n<p>Also, you're <code>using namespace::std</code>. <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't do that, for good reasons</a>. As well as this, if you're having to explain your variable names that last for a while and actually require explanation (I'm looking at <code>V</code>, <code>u</code>, <code>v</code>, <code>c</code>), maybe name them something else? Or at least include comments if they're the convention that people would expect that would give someone who doesn't know the convention a chance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-30T15:02:18.840",
"Id": "124769",
"Score": "0",
"body": "Calling `std::string::size()` is constant time, see here: [std::basic_string::size()](http://en.cppreference.com/w/cpp/string/basic_string/size). To be constant size it's either implemented as an internal `size` member in the string or as a pointer arithmetic with start and end pointers. Both should be inlined by the compiler. This has a negligible effect on the run-time."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-30T14:40:23.187",
"Id": "68407",
"ParentId": "37422",
"Score": "3"
}
},
{
"body": "<p>You're putting too much effort into your input reading. Just use <code>cin</code> it'll be fast enough. The problem is in your algorithm, not the input parsing. The note about input size on the site is meant for languages where naive handling of input can be slow, e.g. Java. C++ is not affected by this.</p>\n\n<p>Instead of implementing your own hash function you can use <a href=\"http://en.cppreference.com/w/cpp/utility/hash\" rel=\"nofollow noreferrer\"><code>std::hash</code></a> (since C++11). Or simply use <a href=\"http://en.cppreference.com/w/cpp/container/unordered_map\" rel=\"nofollow noreferrer\"><code>std::unordered_map</code></a> which is basically a hash map, and save yourself a lot of trouble.</p>\n\n<p>Your naming of types and variables is absolutely horrific. Use descriptive names, a type called <code>ii</code> is not descriptive. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/14041453/why-are-preprocessor-macros-evil-and-what-are-the-alternatives\">Macros are evil</a> don't use them like that.</p>\n\n<p>Now to the core of your problem. You're applying Dijkstra's algorithm for each of the queries in the test case. This is where your slow down is. </p>\n\n<p>You need to use the <a href=\"http://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm\" rel=\"nofollow noreferrer\">Floyd-Warshall Algorithm</a>. This will bring down your run-time and make you get past the TLE with flying colours.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-30T15:16:08.413",
"Id": "68410",
"ParentId": "37422",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:03:10.057",
"Id": "37422",
"Score": "4",
"Tags": [
"c++",
"graph",
"stl",
"time-limit-exceeded"
],
"Title": "STL and Dijkstra's algorithm optimization"
}
|
37422
|
<p>I have a UIImage Category for iOS Objective-C which tints an image based on a given UIColor value. You can take a look at the method below:</p>
<pre><code>- (UIImage *)tintImageWithTint:(UIColor *)color withIntensity:(float)alpha {
CGSize size = self.size;
UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); // MEMORY SPIKE
CGContextRef context = UIGraphicsGetCurrentContext();
[self drawAtPoint:CGPointZero blendMode:kCGBlendModeNormal alpha:1.0]; // MEMORY SPIKE
CGContextSetFillColorWithColor(context, color.CGColor);
CGContextSetBlendMode(context, kCGBlendModeOverlay);
CGContextSetAlpha(context, alpha);
CGContextFillRect(UIGraphicsGetCurrentContext(), CGRectMake(CGPointZero.x, CGPointZero.y, self.size.width, self.size.height));
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context); // MEMORY SPIKE
UIImage *tintedImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return tintedImage;
}
</code></pre>
<p>I've been testing this method with Xcode's Instruments app and found that it takes up more than 96.0 % of all bytes used during the life cycle of the app. That's crazy! It allocates more than 5 MB very quickly, which causes a level one memory warning and begins to terminate other running processes. </p>
<p><img src="https://i.stack.imgur.com/V8zQH.png" alt="Instruments Allocation Analysis"></p>
<p>The image that I'm tinting is <strong>only</strong> a 111 KB, so I can't see how this code could possibly allocate more than 5 MB so quickly.</p>
<p><strong>How can I improve the performance of this code and reduce its memory impact?</strong> I'm not very familiar with CoreGraphics, so any help would be appreciated.</p>
|
[] |
[
{
"body": "<p>your image might have 111 KB compressed as an jpg or a png. But for image processing it needs to be decompressed. It will be loaded into memory with 8 or 16 bit for each color channel. With RGB it would be up to 48 bit per pixel and 8 bit for the alpha cannel in case of png. So 5MB would represent roughly 1.25 million pixel, or something like 1000*1250 pixel. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T05:43:40.673",
"Id": "37898",
"ParentId": "37423",
"Score": "2"
}
},
{
"body": "<p>You could use this approach on iOS 7 devices. I can't see which images you're using, so I don't know if this will be an actual improvement for you, but the new UIView methods are supposedly ultra-performant:</p>\n\n<pre><code>- (UIImage *)tintImageWithTint:(UIColor *)color withIntensity:(float)alpha {\n CGRect frame = CGRectMake(0, 0, self.size.width, self.size.height);\n UIView *view = [[UIView alloc] initWithFrame:frame];\n\n UIImageView *imageView = [[UIImageView alloc] initWithImage:self];\n\n UIView *tintView = [[UIView alloc] initWithFrame:frame];\n tintView.backgroundColor = color;\n tintView.alpha = alpha;\n\n [view addSubview:imageView];\n [view addSubview:tintView];\n\n UIGraphicsBeginImageContextWithOptions(self.size, NO, [UIScreen mainScreen].scale);\n\n [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];\n\n UIImage *image = UIGraphicsGetImageFromCurrentImageContext();\n UIGraphicsEndImageContext();\n return image;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T01:20:48.673",
"Id": "64515",
"Score": "0",
"body": "could you explain your review a little more please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T01:26:23.307",
"Id": "64516",
"Score": "0",
"body": "@Malachi I'd be happy to. Are there specific questions I should answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T01:27:53.000",
"Id": "64517",
"Score": "0",
"body": "you could explain why these are more performant, or how it works, etc. I don't code in Objective C or do anything for Apple Devices, but I know that we like our reviews to have a little more information in them."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T21:14:39.730",
"Id": "38656",
"ParentId": "37423",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:30:08.100",
"Id": "37423",
"Score": "3",
"Tags": [
"objective-c",
"memory-management",
"ios"
],
"Title": "UIGraphicsImageContext Memory Spike - Reducing Footprint"
}
|
37423
|
<p>I've seen usage of <code>switch(true)</code> multiple times and have used it myself today instead of multiple <code>else</code>if`s. Here is the case I used it for:</p>
<pre><code>var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') != -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') != -1;
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') != -1;
var browser = null;
switch (true) {
case isChrome:
{
browser = "chrome";
break;
}
case isSafari:
{
browser = "safari";
break;
}
case isFirefox:
{
browser = "firefox";
break;
}
}
</code></pre>
<p>My view is that much more explicit than multiple <code>else if</code>s. Do you think it's a good approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:30:14.880",
"Id": "61918",
"Score": "0",
"body": "The else-if alternative is shorter and more explicit."
}
] |
[
{
"body": "<p>Assuming that you bad a bunch of boolean variables already defined, I think a chained ternary conditional expression would be even better, because it's more compact, and also emphasizes that the goal is to assigning <em>something</em> to <code>browser</code>.</p>\n\n<pre><code>var browser = isChrome ? \"chrome\" :\n isSafari ? \"safari\" :\n isFirefox ? \"firefox\" :\n null;\n</code></pre>\n\n<p>Also consider defining a <code>userAgentContains(…)</code> function to reduce redundancy.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:39:29.010",
"Id": "37427",
"ParentId": "37424",
"Score": "10"
}
},
{
"body": "<p>It kinda looks explicit, but it also looks... weird. Too much going on.</p>\n\n<p><code>if ... else if</code> (or 200_success's neat ternaries) is shorter and much more conventional, which is a good thing. And with a <code>switch</code> you've got to beware of fall-throughs.</p>\n\n<p>In your example, though, I might simply do:</p>\n\n<pre><code>var browser = (navigator.userAgent.toLowerCase().match(/(chrome|safari|firefox)/) || [null])[0];\n</code></pre>\n\n<p>Which accomplishes the same thing, really.</p>\n\n<p>Or, if you need to do other stuff, after getting the browser name, <em>then</em> you can use a switch if you want:</p>\n\n<pre><code>var match = navigator.userAgent.toLowerCase().match(/(chrome|safari|firefox)/) || [];\nswitch( match[0] ) {\n case \"chrome\":\n ...\n break;\n case \"safari\":\n ...\n break;\n case \"firefox\":\n ...\n break;\n default:\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:45:13.483",
"Id": "37428",
"ParentId": "37424",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37427",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:45:16.290",
"Id": "37424",
"Score": "6",
"Tags": [
"javascript",
"cross-browser"
],
"Title": "User agent classification using switch (true)"
}
|
37424
|
<p>This is part of my attempt at the <a href="https://codereview.meta.stackexchange.com/questions/1245/weekend-challenge-3">Week-End Challenge #3</a>. The overall problem is larger than will fit in one question. This is a well-contained subset of my larger program.</p>
<p>The goal of this part is to brute-force all possible (if any) solutions to a puzzle. The input to this algorithm is a 2-dimensional array representing the Sudoku grid. This array is processed so that, at each point in the array, there is a 'set' of 'possible' digits. For example, at a position (r,c) in the grid, if there is the set of values <code>[ 1, 2, 3 ]</code> it would mean that, at position (r,c) the puzzle could possibly be a 2, 3, or 4. (The solution assumes a zero-based counting system, whereas traditional Sudoku's use a 1-based counting system).</p>
<p>If the set of digits at (r,c) contains just a single value then the assumption is that the cell at that position is 'solved'.</p>
<p>It is assumed that the input grid is 'consistent' with the rules of Sudoku.... that a solved value occurs only once in any row/column/block combination, and that no solved value appears anywhere in the 'potential' set of values for any other cell in the same row/column/block.</p>
<p>I have tried numerous algorithms for forcing a solution, and this is the fastest I tried (by a long shot), but the algorithm is complicated....</p>
<p>I have a tendency to reduce problems down to primitive-value manipulation, and that tends to make solutions harder to read (even though they may be faster).</p>
<p>What I would like is suggestions for how to improve this code by expressing the algorithm more clearly (make the code look more like the algorithm) while not horribly impacting the performance. In other words, I do not believe there are significantly faster algorithms, but performance is not everything!</p>
<p>I have tried to describe the algorithm in the code. Additionally, I have a 'main method' which supplies a pre-constructed Sudoku puzzle in the required input format. The actual example puzzle is the same as the one in this week's challenge.</p>
<p>The algorithm:</p>
<pre><code>import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A class that is able to brute-force a solution for a Sudoku-like puzzle.
* <br>
* Due to the internal use of bit-shifting the largest sudoku puzzle this can solve is 25x25
* which should be more than enough. Sudoku-like puzzles are always square-number sized. 1x1, 4x4, 9x9, 16x16, 25x25, etc.
*
* @author rolfl
*
*/
public class RecursiveBruteSolver {
// dimension - the width of the grid
private final int dimension;
// a simple bit-mask with 1 bit set for each possible value in each square.
// for a 4-size sudoku it will look like:
// 0b0001 0b0010 0b0100 0b1000
// for a 9-size sudoku like:
// 0b000000001 0b000000010 0b000000100 .....
private final int[] bitmask;
// if we flatten the grid, this is how big it is in 1 dimension
private final int flatsize;
// the array of flattened cell available digits
private final int[][] available;
// a complicated concept - the index into the flattened array of all
// squares that are in the same row/column/block, but also have a larger
// index in the flattened array.
private final int[][] followings;
// Some squares will have just one possible value, they do not need to be
// solved.
// this unknown array is the indices of the unsolved squares in the
// flattened array
private final int[] unknown;
// keep track of all recursive call counts
private long statistics = 0L;
/**
* Create a Brute-force solver that will determine all the solutions (if
* any) for a Sudoku grid (when you call the solve() method).
*
* @param dimension
* the side-size of the sudoku grid. The digits 2D array is
* expected to match the same dimensions.
* @param digits
* a 3D array containing the digits that are allowed at that
* position in the array. The actual digits available are
* expected to be 0-based. i.e. a regular 9-size Sudoku has the
* digits 1-9, this solver expects them to be represented as 0-8.
*/
public RecursiveBruteSolver(int dimension, int[][][] digits) {
this.dimension = dimension;
// if we flatten the array....
this.flatsize = dimension * dimension;
available = new int[flatsize][];
followings = new int[flatsize][];
// how many digits are there...and what will the bit-mask be for each digit.
bitmask = new int[dimension];
for (int i = 0; i < dimension; i++) {
bitmask[i] = 1 << i;
}
// keep track of the unknown cells.
// make a generous-size array, we will trim it later.
int[] tmpunknown = new int[flatsize];
int tmpunknowncnt = 0;
// flatten out the grid.
for (int r = 0; r < dimension; r++) {
for (int c = 0; c < dimension; c++) {
int flatid = r * dimension + c;
// gets an array of digits that can be put in each square.
// for example, if a Sudoku square can have 3,5 or 6 this will return
// [2,4,5]
available[flatid] = Arrays.copyOf(digits[r][c], digits[r][c].length);
if (available[flatid].length > 1) {
tmpunknown[tmpunknowncnt++] = flatid;
}
}
}
// System.out.println("There are " + tmpunknowncnt + " unknown cells");
// Special note about `followings`
// A square in a Sudoku puzzle affects all other squares in the same row, column, and block.
// Only one square in the same row/block/column can have particular value.
// For this recursion we 'flatten' the grid, and process the grid in order.
// For each unsolved cell, we set the cell value, and then move on to the next unsolved cell
// but, we need to 'remove' our value from the possible values of other cells in the same row/column/block.
// Because of the way this solver progresses along the flattened array, we only need to remove it
// from cells that come **after** us in the flattened array (values before us already have a fixed value).
// So, buildFollowing() builds an array of indexes in the flattened array that are in the same row/column/block
// but also have a higher index in the flattened array.
for (int flat = 0; flat < available.length; flat++) {
if (available[flat] != null) {
followings[flat] = buildFollowing(flat / dimension, flat
% dimension);
}
}
// create the final copy of the unknown cells (cells which need to be solved).
unknown = Arrays.copyOf(tmpunknown, tmpunknowncnt);
}
public int[][][] solve() {
// following points to unknown subsequent values.....
final int[] combination = new int[flatsize];
// where to store the possible solutions we find
final List<int[][]> solutions = new ArrayList<>();
// this freedoms is an integer for each value.
// bits in the integer are set for each of the values the
// position can be. This is essentially a record of the state
// inside the recursive routine. For example, if setting some other
// cell in the same row/column/block to 5, and our 5-bit is set,
// then we will unset it here because we no longer have the freedom
// to be 5.
final int[] freedoms = new int[flatsize]; //Arrays.copyOf(resetmask, resetmask.length);
for (int flatid = 0; flatid < flatsize; flatid++) {
for (int b : available[flatid]) {
// set the degrees-of-freedom mask of this...
// what values can this cell take?
freedoms[flatid] |= bitmask[b];
}
}
// Do the actual recursion.
// combination contains pointers to which actual values are being used.
// freedom contans the possible states for all subsequent cells.
recurse(solutions, 0, combination, freedoms);
System.out.println("There were " + statistics + " recursive calls...");
// convert the list of Solutions back to an array
return solutions.toArray(new int[solutions.size()][][]);
}
/**
* Recursively solve the Sudoku puzzle.
* @param solutions where to store any found solutions.
* @param index The index in the 'unknown' array that points to the flat-based cell we need to solve.
* @param combination What the current combination of cell values is.
* @param freedoms The state of what potential values all cells can have.
*/
private void recurse(final List<int[][]> solutions, final int index,
final int[] combination, final int[] freedoms) {
statistics++;
if (index >= unknown.length) {
// solution!
solutions.add(buildSolution(combination));
return;
}
// The basic algorithm here is: for our unsolved square, we set it to each of it's possible values in turn.
// then, for each of the values we can be:
// 1. we also find all 'related' squares, and remove our value
// from the degrees-of-freedom for the related squares
// (If I am 'x' then they cannot be). See special not about 'followings'
// 3. we keep track of which other squares we actually change the freedoms for.
// 4. we recurse to the next unsolved square.
// 5. when the recursion returns, we restore the freedoms we previously 'revoked'
// 6. we move on to the next value we can be (back to 1).
// 7. when we have run out of possible values, we return.
final int flat = unknown[index];
for (int a = available[flat].length - 1; a >= 0; a--) {
final int attempt = available[flat][a];
if ((freedoms[flat] & bitmask[attempt]) == 0) {
// this option excluded by previous restrictions....
// the original unsolved puzzle says we can be 'attempt', but
// higher levels of recursion have removed 'attempt' from our
// degrees-of-freedom.
continue;
}
// ok, is used to track whether we are still creating a valid Sudoku.
boolean ok = true;
// progress is used to forward, and then backtrack which following cells
// have been impacted.
// start at -1 because we pre-increment the progress.
int progress = -1;
// act has 1 bit representing each follower we act on.
long act = 0;
while (++progress < followings[flat].length) {
if (freedoms[followings[flat][progress]] == bitmask[attempt]) {
// we intend to remove the attempt from this follower's freedom's
// but that will leave it with nothing, so this is not possible to do.
// ok is false, so we will start a back-up
ok = false;
break;
}
// we **can** remove the value from this follower's freedoms.
// indicate that this follower is being 'touched'.
// act will have 1 bit available for each follower we touch.
act <<= 1;
// record the pre-state of the follower's freedoms.
final int pre = freedoms[followings[flat][progress]];
// if the follower's freedoms contained the value we are revoking, then set the bit.
act |= (freedoms[followings[flat][progress]] &= ~bitmask[attempt]) == pre ? 0 : 1;
}
if (ok) {
// we have removed our digit from all followers, and the puzzle is still valid.
// indicate our combination digit....
combination[flat] = a;
// find the next unsolved.
recurse(solutions, index + 1, combination, freedoms);
}
while (--progress >= 0) {
// restore all previously revoked freedoms.
if ((act & 0x1) == 1) {
freedoms[followings[flat][progress]] |= bitmask[attempt]; // & resetmask[flat]);
}
act >>= 1;
}
}
}
/**
* buildFollowing creates an array of references to other cells in the same
* row/column/block that also have an index **after** us in the flattened array system.
*
* @param row our row index
* @param col our column index
* @return an array of flattened indices that are in the same row/column/block as us.
*/
private int[] buildFollowing(int row, int col) {
int[] folls = new int[dimension * 3]; // possible rows/columns/blocks - 3 sets of values.
final int innerbound = (int)Math.sqrt(dimension); // 3 for size 9, 2 for size 4, 4 for size 16, etc.
// cnt is used to count the valid following indices.
int cnt = 0;
// column-bound - last column in the same block as us.
int cb = ((1 + col / innerbound) * innerbound);
// row-bound - last row in the same block as us.
int rb = ((1 + row / innerbound) * innerbound);
// get all (unsolved) indices that follow us in the same row
for (int c = col + 1; c < dimension; c++) {
// rest of row.
if (available[row * dimension + c].length > 1) {
// only need to worry about unsolved followers.
folls[cnt++] = row * dimension + c;
}
}
// get all (unsolved) indices that follow us in the same column
for (int r = row + 1; r < dimension; r++) {
if (available[r * dimension + col].length > 1) {
// only need to worry about unsolved followers.
folls[cnt++] = r * dimension + col;
}
if (r < rb) {
// if we have not 'escaped' our block, we also find other cells in
// the same block, but not our row/column.
for (int c = col + 1; c < cb; c++) {
if (available[r * dimension + c].length > 1) {
// only need to worry about unsolved followers.
folls[cnt++] = r * dimension + c;
}
}
}
}
// return just the values that were needed as followers.
return Arrays.copyOf(folls, cnt);
}
/**
* Convert the valid combination of values back to a simple int[] grid.
* @param combination the combination of unsolved values that is a valid puzzle.
* @return A Solution object representing the solution.
*/
private int[][] buildSolution(int[] combination) {
int[][] grid = new int[dimension][dimension];
for (int f = 0; f < combination.length; f++) {
grid[f / dimension][f % dimension] = available[f][combination[f]];
}
// double-check the validity of this solution (all sudoku basic rules are followed.
// throws exception if not.
// SudokuRules.isValid(grid);
// mechanism for printing out a grid.
// System.out.println("BruteForceRecursive found Solution:\n"
// + GridToText.displayAsString(grid));
return grid;
}
}
</code></pre>
<p>It has been suggested that the following code is not 'in the spirit' of the week-end challenge because it works off a pre-processed Sudoku puzzle. This is true... I have the data pre-processed in this BruteMain class, but that is only because I wanted to make it easy to run the above algorithm in a self-contained way. The remainder of the code I wrote (i.e. not the code above) is all about solving the Sudoku puzzle as much as I can, (including parsing input, and creating the 'pre-processed' puzzle). That code is more than can fit i a single CodeReview question, so I have broken out just this brute-force code, and a simple way for others (you) to run it.</p>
<p>The 'main' class which can be used for testing (not much commented in here...):</p>
<pre><code>public class BruteMain {
public static void main(String[] args) {
int[][][] puzzle = new int[][][] {
{ { 1, 4, 5, },{ 2, 5, 6, },{ 1, 2, 4, 5, 6, },{ 7, },{ 3, },{ 2, 4, 5, 6, },{ 0, 1, 6, },{ 0, 1, 6, },{ 8, }, },
{ { 1, 3, 5, },{ 2, 3, 5, 6, 8, },{ 0, },{ 2, 5, 6, },{ 2, 5, 6, 8, },{ 2, 5, 6, 8, },{ 1, 6, 7, },{ 1, 6, 7, },{ 4, }, },
{ { 7, },{ 6, 8, },{ 4, 6, 8, },{ 4, 6, },{ 1, },{ 0, },{ 3, },{ 5, },{ 2, }, },
{ { 6, },{ 0, 2, 3, 5, },{ 7, },{ 0, 1, 2, 3, 4, 5, },{ 2, 4, 5, },{ 1, 2, 4, 5, },{ 1, 5, },{ 8, },{ 1, 3, 5, }, },
{ { 0, 1, 3, 5, },{ 0, 2, 3, 5, 8, },{ 1, 2, 5, 8, },{ 0, 1, 2, 3, 4, 5, 6, },{ 2, 4, 5, 6, 8, },{ 1, 2, 4, 5, 6, 7, 8, },{ 1, 5, 6, 7, },{ 1, 3, 4, 6, 7, },{ 1, 3, 5, 7, }, },
{ { 1, 3, 5, },{ 4, },{ 1, 5, 8, },{ 1, 3, 5, 6, },{ 5, 6, 8, },{ 1, 5, 6, 7, 8, },{ 2, },{ 1, 3, 6, 7, },{ 0, }, },
{ { 4, 5, },{ 1, },{ 3, },{ 8, },{ 0, },{ 2, 4, 5, },{ 5, 7, },{ 2, 7, },{ 6, }, },
{ { 8, },{ 0, 5, 6, 7, },{ 5, 6, },{ 1, 2, 5, 6, },{ 2, 5, 6, },{ 1, 2, 5, 6, },{ 4, },{ 0, 1, 2, 3, 7, },{ 1, 3, 5, 7, }, },
{ { 2, },{ 0, 5, 6, },{ 4, 5, 6, },{ 1, 4, 5, 6, },{ 7, },{ 3, },{ 0, 1, 5, 8, },{ 0, 1, },{ 1, 5, }, },
};
RecursiveBruteSolver solver = new RecursiveBruteSolver(9, puzzle);
for (int[][] sol : solver.solve()) {
System.out.println("Solution:");
System.out.println(displayAsString(sol));
}
}
private static final char[][] symbols = {
"╔═╤╦╗".toCharArray(),
"║ │║║".toCharArray(),
"╟─┼╫╢".toCharArray(),
"╠═╪╬╣".toCharArray(),
"╚═╧╩╝".toCharArray(),
};
private static final char[] DIGITCHARS = "123456789ABCFEDGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
public static final char getSudokuDigit(final int value) {
if (value < 0) {
return ' ';
}
return DIGITCHARS[value];
}
public static final String displayAsString(int[][]data) {
return buildStringForGrid(data.length, (int)Math.sqrt(data.length), data);
}
private static final String buildStringForGrid(final int dimension, final int blocksize, final int[][]rows) {
final StringBuilder sb = new StringBuilder();
for (int r = 0; r < dimension; r++) {
if (r == 0) {
sb.append(printSymbolLine(dimension, blocksize, null, symbols[0]));
} else if (r % blocksize == 0) {
sb.append(printSymbolLine(dimension, blocksize, null, symbols[3]));
} else {
sb.append(printSymbolLine(dimension, blocksize, null, symbols[2]));
}
sb.append(printSymbolLine(dimension, blocksize, rows[r], symbols[1]));
}
sb.append(printSymbolLine(dimension, blocksize, null, symbols[4]));
return sb.toString();
}
private static String printSymbolLine(int dimension, int blocksize, int[] values, char[] symbols) {
StringBuilder sb = new StringBuilder();
sb.append(symbols[0]);
int vc = 0;
for (int b = 0; b < blocksize; b++) {
for (int c = 0; c < blocksize; c++) {
if (values == null) {
sb.append(symbols[1]).append(symbols[1]).append(symbols[1]).append(symbols[2]);
} else {
final int val = values[vc++];
char ch = getSudokuDigit(val);
sb.append(symbols[1]).append(ch).append(symbols[1]).append(symbols[2]);
}
}
sb.setCharAt(sb.length() - 1, symbols[3]);
}
sb.setCharAt(sb.length() - 1, symbols[4]);
sb.append("\n");
return sb.toString();
}
}
</code></pre>
<p>I have added in an <a href="http://ideone.com/GUSwn2" rel="nofollow noreferrer">Ideone implementation of this solution</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:18:54.860",
"Id": "61917",
"Score": "1",
"body": "For the record, I've seen 6 x 6 puzzles, where each box is 2 x 3. As long as you handle 9 x 9, though, that's OK."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:58:47.163",
"Id": "61941",
"Score": "0",
"body": "Encapsulation would help you out a lot here. You're using an object oriented language, but you're barely using any object oriented features. IMHO, at the very least you should have a `Cell` and `Puzzle` class, in addition to `Solver`, and probably a `Group` class which keeps track of all the cells in a particular row, column or 3x3 square. Otherwise you might as well be writing this in C."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T22:03:11.657",
"Id": "61942",
"Score": "0",
"body": "Also, I find that if you need tons of inline comments inside functions to make it clear what's happening, it's a pretty good sign that a function is trying to do too much, and some refactoring might be in order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T23:42:30.497",
"Id": "61957",
"Score": "0",
"body": "@bcrist In my defense, this code is a small part of an OO system... and the OO part of the system was very much slower than the code above. I plan on posting more code... (been out for a few hours....) . Another question is on it's way...."
}
] |
[
{
"body": "<h2><code>buildFollowing</code></h2>\n\n<p>The logic of this this function is difficult to follow. Part of it is because of your insistence on very short names (<code>rb</code>, <code>cb</code>, etc.) with comments breaking up the flow of the code; as a rule of thumb, if you need a comment to describe what a variable does, you should probably make the name longer. Internal comments should almost always describe why, not what.</p>\n\n<p>I'd consider something like this:</p>\n\n<pre><code>/**\n * Compute a list of all indices **after** the one corresponding to\n * row and col that are not already solved.\n *\n * Requires that available has already been initialized.\n */\nprivate int[] buildFollowing(int row, int col) {\n int[] following = new int[dimension * 3];\n int numFollowers = 0;\n // Get all followers in this row.\n for (int c = col + 1; c < dimension; c++) {\n int candidate = row * dimension + c;\n if (available[candidate].length > 1) {\n following[numFollowers++] = candidate;\n }\n }\n // Get all followers in this column.\n for (int r = row + 1; r < dimension; r++) {\n int candidate = r * dimension + col;\n if (available[candidate].length > 1) {\n following[numFollowers++] = candidate;\n }\n }\n // Get followers in the same block.\n int blockDimension = (int) Math.sqrt(dimension);\n int lastColInBlock = ((col % blockDimension) + 1) * blockDimension - 1;\n int lastRowInBlock = ((row % blockDimension) + 1) * blockDimension - 1;\n for (int r = row + 1; r < lastRowInBlock; r++) {\n for (int c = col + 1; c < lastColInBlock; c++) {\n int candidate = r * dimension + c;\n if (available[candidate].length > 1) {\n following[numFollowers++] = candidate;\n }\n }\n }\n return Arrays.copyOf(following, numFollowers);\n}\n</code></pre>\n\n<p>This function is divided into \"paragraphs,\" where the purpose of each block is clear. <code>rb</code> and <code>cb</code> are renamed to <code>lastRowInBlock</code> and <code>lastColInBlock</code>, and they're not declared until they're used.</p>\n\n<h2><code>recurse</code></h2>\n\n<p>Why is the <code>for</code> loop counting down instead of up? When I see that pattern, I expect that there's a reason for it, but there doesn't seem to be here. As with <code>buildFollowing</code>, this function suffers a bit from superfluous comments and oddly named variables. Let me take a crack:</p>\n\n<pre><code>/**\n * Recursively solve the Sudoku puzzle.\n *\n * @param solutions All solutions found so far.\n * @param unknownIndex The current element of unknown we're solving on.\n * @param partialSolution This array contains the partial solution selected\n * so far for all cells prior to unknowns[unknownIndex]; the solution\n * for cell (i / dimension, i % dimension) is\n * available[partialSolution[i]].\n * @param stillAvailable (stillAvailable[i] & (1 << v)) is 1 iff\n * v has not been eliminated for cell (i / dimension, i % dimension)\n * by any part of partialSolution.\n */\nprivate void recurse(List<int[][]> solutions, int unknownIndex,\n int[] partialSolution, int[] stillAvailable) {\n if (unknownIndex >= unknowns.length) {\n solutions.add(buildSolution(partialSolution));\n return;\n }\n int index = unknowns[unknownIndex];\n for (int a = 0; a < available[index.length]; a++) {\n int candidate = available[a];\n long appliedConstraints = applyConstraints(\n index, candidate, stillAvailable);\n if (appliedConstraints < 0) {\n // No solution is possible with this cell set to candidate.\n continue;\n }\n partialSolution[index] = a;\n recurse(solutions, index + 1, partialSolution, stillAvailable);\n removeConstraints(\n index, candidate, stillAvailable, appliedConstraints);\n }\n}\n</code></pre>\n\n<p>I'll leave the implementation of <code>applyConstraints</code> and <code>removeConstraints</code> as an exercise to the reader, but the contract of <code>applyConstraints</code> is that it returns a negative number iff any following cell is left with no possible value; otherwise it returns a long that encodes which elements of stillAvailable were modified.</p>\n\n<p>Notice how the comment describing the workings of the algorithm is made unnecessary by using well-named helper functions; the code makes the algorithm clear.</p>\n\n<h2>Minor Issues</h2>\n\n<ul>\n<li>The comment describing <code>followings</code> should include an example to make it easier to understand. On that note, you should put the description of <code>followings</code> in one place; right now it's split between the declaration and the initialization.</li>\n<li><code>tmpunknowns</code> complicates the logic in your constructor to save a few tens of bytes. I'm reasonably sure that it doesn't even help with cacheline pressure, as I doubt that the entire array is pulled into the L1 cache when accessing a signle elements. If you decide to keep it, you should move the copy from <code>tmpunknowns</code> to <code>unknowns</code> up to immediately after the initialization of <code>tmpunknowns</code>; as it is, you're separating related pieces of code, which makes it more difficult to understand.</li>\n<li>It's bad practice to check in commented-out code (I refer here to your <code>// System.out.println(...</code>, <code>//Arrays.copyOf(resetmask...</code>, etc.</li>\n<li>In my experience, local variables are only declared <code>final</code> if they are to be used in inner classes. So, e.g., in <code>solve</code> when you declare <code>combination</code> or <code>freedoms</code> to be <code>final</code>, I look for the inner class where they're used. Idiomatic Java doesn't have the same sense of <code>const</code>-correctness that C++ has.</li>\n<li>I suspect that making <code>bitmasks</code> a method instead of an array will make your optimized code faster; the compiler can inline the function for a single arithmetic operation instead of reading from memory (which requires a single arithmetic operation to get the offset anyway, along with requiring a cacheline, etc.).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:15:51.143",
"Id": "61959",
"Score": "0",
"body": "Addressing the initial comment - about the strict format of the input. Truth is, I am cheating. I have already parsed the input, and, typically, I have run it through multiple 'Sudoku Strategy' clases before I discover I need to 'brute-force' the puzzle. I have not (yet) posted the full solution to the Week-end challenge, but, rest assured, I **do** process raw (example-specified) input, and I have just posted this question here as a self-contained solution... which the 'short-cut' input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:33:41.940",
"Id": "61961",
"Score": "0",
"body": "That makes sense. I've removed the initial comment in response to your edit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:00:24.733",
"Id": "37439",
"ParentId": "37425",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "37439",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T16:46:45.107",
"Id": "37425",
"Score": "14",
"Tags": [
"java",
"algorithm",
"recursion",
"weekend-challenge",
"sudoku"
],
"Title": "Sudoku Week-End Challenge - Brute-Force Recursive solver"
}
|
37425
|
<p>I had this code lying around, so I figured I would submit this as my first attempt at a <a href="/questions/tagged/weekend-challenge" class="post-tag" title="show questions tagged 'weekend-challenge'" rel="tag">weekend-challenge</a>. I would prefer if reviews contained suggestions on how to improve the algorithm, but all suggestions are acceptable.</p>
<pre><code>#include <stdio.h>
int isAvailable(int puzzle[][9], int row, int col, int num)
{
int rowStart = (row/3) * 3;
int colStart = (col/3) * 3;
int i, j;
for(i=0; i<9; ++i)
{
if (puzzle[row][i] == num) return 0;
if (puzzle[i][col] == num) return 0;
if (puzzle[rowStart + (i%3)][colStart + (i/3)] == num) return 0;
}
return 1;
}
int fillSudoku(int puzzle[][9], int row, int col)
{
int i;
if(row<9 && col<9)
{
if(puzzle[row][col] != 0)
{
if((col+1)<9) return fillSudoku(puzzle, row, col+1);
else if((row+1)<9) return fillSudoku(puzzle, row+1, 0);
else return 1;
}
else
{
for(i=0; i<9; ++i)
{
if(isAvailable(puzzle, row, col, i+1))
{
puzzle[row][col] = i+1;
if((col+1)<9)
{
if(fillSudoku(puzzle, row, col +1)) return 1;
else puzzle[row][col] = 0;
}
else if((row+1)<9)
{
if(fillSudoku(puzzle, row+1, 0)) return 1;
else puzzle[row][col] = 0;
}
else return 1;
}
}
}
return 0;
}
else return 1;
}
int main()
{
int i, j;
int puzzle[9][9]={{0, 0, 0, 0, 0, 0, 0, 9, 0},
{1, 9, 0, 4, 7, 0, 6, 0, 8},
{0, 5, 2, 8, 1, 9, 4, 0, 7},
{2, 0, 0, 0, 4, 8, 0, 0, 0},
{0, 0, 9, 0, 0, 0, 5, 0, 0},
{0, 0, 0, 7, 5, 0, 0, 0, 9},
{9, 0, 7, 3, 6, 4, 1, 8, 0},
{5, 0, 6, 0, 8, 1, 0, 7, 4},
{0, 8, 0, 0, 0, 0, 0, 0, 0}};
if(fillSudoku(puzzle, 0, 0))
{
printf("\n+-----+-----+-----+\n");
for(i=1; i<10; ++i)
{
for(j=1; j<10; ++j) printf("|%d", puzzle[i-1][j-1]);
printf("|\n");
if (i%3 == 0) printf("+-----+-----+-----+\n");
}
}
else printf("\n\nNO SOLUTION\n\n");
return 0;
}
</code></pre>
<p>Test run:</p>
<pre><code>$ ./SudokuSolver
+-----+-----+-----+
|7|4|8|6|3|5|2|9|1|
|1|9|3|4|7|2|6|5|8|
|6|5|2|8|1|9|4|3|7|
+-----+-----+-----+
|2|6|5|9|4|8|7|1|3|
|8|7|9|1|2|3|5|4|6|
|3|1|4|7|5|6|8|2|9|
+-----+-----+-----+
|9|2|7|3|6|4|1|8|5|
|5|3|6|2|8|1|9|7|4|
|4|8|1|5|9|7|3|6|2|
+-----+-----+-----+
</code></pre>
|
[] |
[
{
"body": "<p>I would love to go through and find all sorts of things that this code does badly... but, it's short, sweet, and works, and that in itself speaks to a measure of sophistication.</p>\n\n<p>This solution is very lightweight on all resources other than CPU cycles, and it does not carry much through on the stack, either. All in all, it's neat, and well structured.</p>\n\n<p>A few minor criticisms:</p>\n\n<ul>\n<li>in your <code>isAvailable()</code> method you declare <code>j</code>, but do not use it.</li>\n<li>the fancy modulo/divide mechanism (<code>puzzle[rowStart + (i%3)][colStart + (i/3)] == num</code>) for checking the block is just that, fancy... and probably needs some sort of comment. I have worked through the math, and I can see it is right, but some help there would have been useful.</li>\n<li>I don't like that you check values multiple times in <code>isAvailable()</code>, but I must admit that I cannot see a nice way to avoid the duplication without adding even more expensive complexity. By my calculation, you double-check 4 values, and triple-check 1. That is 5/27 checks are redundant... As I say, though, I think avoiding those checks will be more costly than the redundancy.</li>\n<li>in your <code>fillSudoku</code> method, you declare <code>i</code> and use it as <code>for(i=0; i<9; ++i)</code>. Since, in this case, <code>i</code> is not actually an index to some array, or a simple loop limiter, but it is actually a puzzle digit, you should do two things:\n<ol>\n<li>rename it to be something like <code>digit</code></li>\n<li>change the loop to be: <code>for(digit=1; digit<=9; ++digit)</code>, and then you can remove all the redundant <code>+1</code> operations you do inside the loop (e.g. <code>isAvailable(puzzle, row, col, i+1)</code>)</li>\n</ol></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T18:32:41.223",
"Id": "37432",
"ParentId": "37430",
"Score": "17"
}
},
{
"body": "<p>Your solution is short and sweet. Hopefully my answer will be too since rolfl covered most of what I saw. :)</p>\n\n<ol>\n<li><p>Perhaps <code>solveSudoku</code> will better convey the fact that it's <em>solving</em> the puzzle. <code>fillSudoku</code> sounds like a function that fills in the initial positions from a file or string or something.</p></li>\n<li><p>You could shorten the \"is the cell is filled\" check by dropping the <code>!= 0</code> for maximum C-ness:</p>\n\n<pre><code>if(puzzle[row][col])\n</code></pre></li>\n<li><p>You are duplicating the code that advances the cell indices in <code>fillSudoku</code>: once if the cell comes in already filled and again when you place the next guess. You can drop the latter and simply pass in the same cell indices since you're setting the cell's value first.</p>\n\n<pre><code>if(isAvailable(puzzle, row, col, i+1))\n{\n puzzle[row][col] = i+1;\n\n if(fillSudoku(puzzle, row, col) return 1;\n else puzzle[row][col] = 0;\n}\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T19:15:23.413",
"Id": "37433",
"ParentId": "37430",
"Score": "19"
}
}
] |
{
"AcceptedAnswerId": "37433",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T17:47:41.137",
"Id": "37430",
"Score": "38",
"Tags": [
"c",
"weekend-challenge",
"sudoku"
],
"Title": "Sudoku Solver in C"
}
|
37430
|
<p>This is my first, very-very first attempt at <a href="/questions/tagged/java" class="post-tag" title="show questions tagged 'java'" rel="tag">java</a>. I haven't started tackling the actual resolution of the <a href="/questions/tagged/sudoku" class="post-tag" title="show questions tagged 'sudoku'" rel="tag">sudoku</a> puzzle (not even sure where to start, haven't looked at other <a href="/questions/tagged/weekend-challenge" class="post-tag" title="show questions tagged 'weekend-challenge'" rel="tag">weekend-challenge</a> entries yet). I don't have much to go over here, but I'm sure it's filled with <a href="/questions/tagged/beginner" class="post-tag" title="show questions tagged 'beginner'" rel="tag">beginner</a> mistakes already, so before I make things any worse I'd like to get a review of what I have.</p>
<p>The puzzle being parsed is the one provided as an example in <a href="https://codereview.meta.stackexchange.com/a/1248/23788">the winning weekend-challenge suggestion</a>.</p>
<pre><code>public class SudokuGame {
private final static String newLine = System.lineSeparator();
private final static String puzzle =
"...84...9" + newLine +
"..1.....5" + newLine +
"8...2146." + newLine +
"7.8....9." + newLine +
"........." + newLine +
".5....3.1" + newLine +
".2491...7" + newLine +
"9.....5.." + newLine +
"3...84...";
public static void main(String[] args){
SudokuGrid grid = new SudokuGrid(puzzle);
System.out.print(grid);
}
}
</code></pre>
<p>The program takes the string and outputs this:</p>
<blockquote>
<pre><code>+===========+===========+===========+
| | | | 8 | 4 | | | | 9 |
-------------------------------------
| | | 1 | | | | | | 5 |
-------------------------------------
| 8 | | | | 2 | 1 | 4 | 6 | |
+===========+===========+===========+
| 7 | | 8 | | | | | 9 | |
-------------------------------------
| | | | | | | | | |
-------------------------------------
| | 5 | | | | | 3 | | 1 |
+===========+===========+===========+
| | 2 | 4 | 9 | 1 | | | | 7 |
-------------------------------------
| 9 | | | | | | 5 | | |
-------------------------------------
| 3 | | | | 8 | 4 | | | |
+===========+===========+===========+
</code></pre>
</blockquote>
<p>Here's the <code>SudokuGrid</code> class:</p>
<pre><code>/** A 9x9 Sudoku grid */
public class SudokuGrid {
private SudokuDigit[][] digits;
/** Creates a new SudokuGrid. Specified array must be 9x9. */
public SudokuGrid(SudokuDigit[][] digits){
this.digits = digits;
}
/** Creates a new SudokuGrid from specified string, assumed to be 9 lines of 9 characters. */
public SudokuGrid(String contents) {
this(contents.split("\\r?\\n"));
}
/** Creates a new SudokuGrid from specified string array, assumed to be 9 strings of 9 characters. */
public SudokuGrid(String[] contents) {
this(parseStringContent(contents));
}
private static SudokuDigit[][] parseStringContent(String[] contents) {
SudokuDigit[][] result = new SudokuDigit[9][9];
for (int i = 0; i < 9; i++) {
String row = contents[i];
for (int j = 0; j < 9; j++) {
result[i][j] = new SudokuDigit(row.charAt(j));
}
}
return result;
}
/** Sets the value of specified grid coordinates. */
public void setDigit(Point coordinates, Integer value) {
setDigit(coordinates, new SudokuDigit(value));
}
/** Sets the value of specified grid coordinates. */
public void setDigit(Point coordinates, SudokuDigit value) {
this.digits[coordinates.x][coordinates.y] = value;
}
/** Gets the SudokuDigit at specified grid coordinates. */
public SudokuDigit getDigit(Point coordinates) {
return this.digits[coordinates.x][coordinates.y];
}
/** Gets all SudokuDigits in specified row (0-8). */
public SudokuDigit[] getRow(int row) {
return this.digits[row];
}
/** Gets all SudokuDigits in specified column (0-8). */
public SudokuDigit[] getColumn(int column) {
SudokuDigit[] result = new SudokuDigit[9];
for (int row = 0; row < 9; row++) {
result[row] = this.digits[row][column];
}
return result;
}
/** Gets all SudokuDigits in specified 3x3 region (x: 0-2, y: 0-2). */
public SudokuDigit[][] getRegion(Point coordinates) {
SudokuDigit[][] result = new SudokuDigit[3][3];
int startRow = coordinates.x * 3;
int startCol = coordinates.y * 3;
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
result[row][col] = this.digits[startRow + row][startCol + col];
}
}
return result;
}
public String toString() {
final String newLine = System.lineSeparator();
String result = "+===========+===========+===========+" + newLine;
for (int row = 0; row < this.digits.length; row++) {
result = result.concat("|");
for (int col = 0; col < this.digits[row].length; col++) {
result = result.concat(" " + this.digits[row][col].toString() + " |");
}
if ((row + 1) % 3 == 0) {
result = result.concat(newLine + "+===========+===========+===========+" + newLine);
}
else {
result = result.concat(newLine + "-------------------------------------" + newLine);
}
}
return result;
}
}
</code></pre>
<p>And this is my <code>SudokuDigit</code> class:</p>
<pre><code>/** An object that represents a single digit in a SudokuGrid, with or without a value. */
public class SudokuDigit {
private Integer digit;
/** Creates a new, empty value */
public SudokuDigit() {
this((Integer)null);
}
/** Creates a new digit from specified character. */
public SudokuDigit(char value) {
Integer numericValue;
if (value == '.') {
numericValue = null;
}
else {
numericValue = Integer.parseInt(String.valueOf(value));
}
this.digit = numericValue;
}
/** Creates a new digit with specified value */
public SudokuDigit(Integer value) {
this.digit = value;
}
/** Gets the current value of the digit. Null if no value is specified. */
public Integer getDigit() {
return this.digit;
}
/** Sets the current value of the digit.
* Specify null for no value.
* Throws UnsupportedOperationException if value is not valid.*/
public void setDigit(Integer value) {
if (!validateDigitValue(value)) throw new UnsupportedOperationException();
this.digit = value;
}
private boolean validateDigitValue(Integer value) {
return value == null || (value >= 1 && value <= 9);
}
public String toString() {
return this.digit != null ? this.digit.toString() : " ";
}
}
</code></pre>
<p>This is really a "Hello World!" thing, but I want this code to be the grounds for an actual Sudoku resolver (which I'll post later, when/if I manage to put it together!). Any blatant mistakes that will drive me into a brick wall?</p>
|
[] |
[
{
"body": "<ul>\n<li><p>Instead of your <code>String puzzle</code> you could use an <code>String[]</code> like below (not saying you have to, but you should know that the alternative exists). You are currently converting it to a <code>String</code> array later anyway, so why not have it as a String array right from the start?</p>\n\n<pre><code>private final static String[] puzzle = new String[]{ \"...84...9\", \"..1.....5\", ... };\n</code></pre></li>\n<li><p>This can be marked with <strong>final</strong>: <code>private SudokuDigit[][] digits;</code> to prevent any malicious programmer from even trying to use <code>this.digits = null</code> after it has once been initialized, or initialize a new 2-dimensional array</p></li>\n<li><p><code>3</code> is a magic number. Yes it is, it's a magic number. In the past in the present and the future, I say three, is a magic number.</p></li>\n<li><p><code>9</code> is also magic number. This means that you should use it as a constant:</p>\n\n<pre><code>public static final int MAGIC_NUMBER = 9;\n</code></pre></li>\n<li><p>A double for-loop with variables <code>i</code> and <code>j</code> can be called <code>x</code> and <code>y</code> instead, to avoid any possible confusion about which one is which.</p></li>\n<li><p><code>UnsupportedOperationException</code> might not be the best exception to throw in your <code>setDigit</code> method. <code>IllegalArgumentException</code> would be better, since the argument to the method is incorrect.</p></li>\n<li><p>Simplification possible in your <code>SudokuDigit</code> char constructor:</p>\n\n<pre><code>numericValue = value == '.' ? null : Integer.parseInt(String.valueOf(value));\n</code></pre></li>\n<li><p>When writing JavaDoc, I believe it's convention to use it on multiple lines. Or at least that's more common than using only one line (Also, did you know that you could write <code>/**</code> before a method in Eclipse and then press enter to make Eclipse write the basic \"layout\" of it for you?)</p>\n\n<pre><code>/**\n * Creates a new digit from specified character.\n */\npublic SudokuDigit(char value) {\n</code></pre></li>\n<li><p>You can use <code>@throws</code> in Javadoc to specify What exception can be thrown, and why.</p>\n\n<pre><code>/** \n * Sets the current value of the digit.\n * Specify null for no value. \n * @throws UnsupportedOperationException if value is not valid.\n */ \npublic void setDigit(Integer value) {\n</code></pre></li>\n<li><p>You can use <code>Character.digit(char c, int radix)</code> instead of <code>Integer.parseInt</code> to convert your <code>char</code>s to <code>int</code>. Such as <code>Character.digit(value, 10)</code></p></li>\n</ul>\n\n<p>If I wouldn't have known it, I wouldn't be able to tell that you are a Java beginner. You seem to be following nearly all of the common conventions and seem to be doing things well overall. Not much to complain about, really.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T19:58:19.323",
"Id": "61930",
"Score": "2",
"body": "+1 for the magic numbers. I realized that was going to bite me when I saw you resolve a `{{1,0},{0,1}}` \"Sudoku puzzle\"..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:24:52.687",
"Id": "62171",
"Score": "1",
"body": "@retailcoder Thanks to reviewing your code, I remembered to constantify my magic numbers before submitting my code. Otherwise I would very likely also have been told the same thing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T19:53:07.603",
"Id": "37438",
"ParentId": "37435",
"Score": "4"
}
},
{
"body": "<p><code>SudokuDigit</code> should be a Value Object. Apart from arguments from domain some syntactical clues are also in your code. <code>SudokuDigit.setValue</code> is not called anywhere. When the <em>value</em> of a <code>Digit</code> withing a <code>Grid</code> needs to change you set it to another <code>Digit</code> and do not mutate the <code>Digit</code> instead.\nOnce you are content that <code>Digit</code> is a value object, you do the following:</p>\n\n<ul>\n<li>Mark all fields as <code>final</code>.</li>\n<li>remove setters and other mutators. They give compile errors, so easy enough.</li>\n</ul>\n\n<p><code>SudokuDigit(Integer)</code> is the basic constructor and <code>SudokuDigit()</code> is a specialized one that depends on it. Putting the basic constructor above and specialized one below makes it easier to read top-down.</p>\n\n<p><code>SudokuDigit(char)</code> does too much for a constructor, that is more than assignment to the fiels. And also knows too much: It really needn't concern itself with whether '.' corresponds to and empty digit. It belongs with other parsing code. The code should just work whether I use a ' ' or '.' to represent some value. It can be turned to static factory method. And moved to wherever it is actually needed.</p>\n\n<p>Same goes for <code>validateDigitValue(Integer)</code>. That it can be made static is a tell. Marking anything static that can be marked static is a good rule of thumb. A static method can be moved easily around and awkward calling syntax is a reminder that that piece of code is not at its natural home. Dependence of the method on magic constant <code>9</code> is a sign that it probably belongs to a class with a field whose value would be <code>9</code>. <code>SudokuGrid.size</code> maybe? A \nSudoku game can be trivially generalized to 1X1, 4X4, 16X16 grids with same rules. But this method would cause reuse and testing trouble if we attempted that.</p>\n\n<p>The same arguments go for separating parsing concern from other concerns, ie single responsibility principle, goes for <code>SudokuGrid</code>. That is convert the constructors that do parsing to factory methods, e.g. convert <code>SudokuGrid(String contents)</code> to <code>static SudokuGrid parseGrid(String contents)</code>. Then Move it to a <code>SudokuParser</code> class, for example.</p>\n\n<p>A side note: making <code>SudokuDigit</code> immutable prevents misuse of <code>SudokuGrid</code>'s API:</p>\n\n<pre><code>grid.get(coords).setDigit(-12345); // ???\n</code></pre>\n\n<p>You shouldn't leak references to internal state, as done in <code>SudokuGrid.getRow</code>. It violates encapsulation:</p>\n\n<pre><code>grid.getRow(0)[0] = new SudokuDigit(-12345);\n</code></pre>\n\n<p>You can return an <code>Iterable<SudokuDigit></code> from each of <code>getRow</code>, <code>getColumn</code> and <code>getRegion</code> that are backed by unmodifiable collections; also making their return types more uniform, more abstract and more composable, all at the same time.</p>\n\n<p>I assume the <code>Point</code> type is not <code>java.awt.Point</code>. If so; just define a new <code>class SudokuCoordinate {int row, col;}</code> in 10 secs, and deny ever having used <code>java.awt.Point</code> vehemently.</p>\n\n<p>Lastly; </p>\n\n<ul>\n<li>Remove <code>Sudoku-</code> prefix from your classes. </li>\n<li>Put each type in a separate source file. </li>\n<li>Use \"open resource\" (in Eclipse: ctrl+shift+r) instead of \"open type\" to find your types easily.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T11:43:05.200",
"Id": "37498",
"ParentId": "37435",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37438",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T19:37:58.777",
"Id": "37435",
"Score": "8",
"Tags": [
"java",
"beginner",
"parsing",
"weekend-challenge",
"sudoku"
],
"Title": "Hello Java World ~> Parsing a Sudoku Grid"
}
|
37435
|
<p>This is a Python script that generates a grid of random HTML colors. It works by reading random data from <code>/dev/urandom</code> and then encoding it as a hexadecimal string. This string is spit into individual values that will be represented as a color.</p>
<p>I am wanting to know if this is the best way to generate random values for this task. Would it be better to use the <code>random</code> module? Or is my method more beneficial for this task?</p>
<pre><code>WIDTH = 64
HIGHT = 5
def chunks(l, n):
return [l[i:i+n] for i in range(0, len(l), n)]
data = file("/dev/urandom").read(HIGHT*WIDTH*3).encode("hex")
colors = ""
count = 0
for byte in chunks(data, 6):
if count == WIDTH:
colors+="<br>"
count=0
count+=1
colors+="""<p style="color:%s; display:inline;">&#x25a0;</p>""" % (byte)
file("colors.html", "w").write(colors)
</code></pre>
<p>This is the output:</p>
<p><img src="https://i.stack.imgur.com/wUEsP.png" alt="Screenshot"></p>
|
[] |
[
{
"body": "<p>An implementation that uses the <code>random</code> module has the benefit of being platform independent. This code isn't going to run so well if you try it on Windows.</p>\n\n<p>There is also another alternative. <a href=\"http://docs.python.org/2/library/os.html#os.urandom\" rel=\"nofollow noreferrer\"><code>os.urandom()</code></a> will use the underlying os to provide the random values.</p>\n\n<blockquote>\n <p>On a UNIX-like system this will query <code>/dev/urandom</code>, and on Windows it\n will use <code>CryptGenRandom()</code>.</p>\n</blockquote>\n\n<p>You can also use <a href=\"http://docs.python.org/2/library/random.html#random.SystemRandom\" rel=\"nofollow noreferrer\"><code>random.SystemRandom()</code></a> if you still want the OS source, but want to use the interface provided by <code>random</code>.</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/a/434411/210526\">This answer</a> provides an implementation of <code>chunks()</code> that iterates instead of constructing a list of all the chunks.</p>\n\n<hr>\n\n<p>I would also lean towards an implementation that opens the output file first, then writes to it as it iterates over the chunks. This way, you won't need to build a huge string in memory before writing it to disk. Similarly, I would generate the random values as needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:53:30.297",
"Id": "37445",
"ParentId": "37440",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>By using <code>/dev/urandom</code> you make it hard for someone to run your code on Windows. Instead, use the built-in function <a href=\"http://docs.python.org/3/library/os.html#os.urandom\" rel=\"nofollow\"><code>os.urandom</code></a>.</p></li>\n<li><p>But what are these colours going to be used for? Do you really care whether they are generated using cryptographically secure random numbers? It looks like an application for which ordinary pseudo-random numbers from the <a href=\"http://docs.python.org/3/library/random.html\" rel=\"nofollow\"><code>random</code></a> module will be perfectly adequate.</p></li>\n<li><p>The word \"height\" has an \"e\" in it.</p></li>\n<li><p><code>str.encode('hex')</code> isn't portable to Python 3. Instead, you should use <a href=\"http://docs.python.org/3/library/binascii.html#binascii.hexlify\" rel=\"nofollow\"><code>binascii.hexlify</code></a>.</p></li>\n<li><p>The name <code>byte</code> seems like a bad name for a variable that contains a 6-character-long string.</p></li>\n<li><p>You read a big block of random data and then use the <code>chunks</code> function to split it up. But it would be simpler to read one chunk of random data at a time—then you wouldn't need the <code>chunks</code> function.</p></li>\n<li><p>Similarly, you build a big string and then write it to the output all in one go. But it would be simpler to open the output file and then write one small string at a time to it.</p></li>\n<li><p>The entity reference <code>&#x25a0;</code> is unclear. I would use the <a href=\"http://docs.python.org/3/library/unicodedata.html\" rel=\"nofollow\"><code>unicodedata</code></a> module and write <code>unicodedata.lookup('BLACK SQUARE')</code> so that the meaning is clear</p></li>\n<li><p>Why do you use <code><p></code> if you are going to specify <code>display:inline</code>? Why not use <code><span></code> instead?</p></li>\n</ol>\n\n<p>Putting all this together, I'd write:</p>\n\n<pre><code>from random import randrange\nfrom unicodedata import lookup\n\nWIDTH = 64\nHEIGHT = 5\nSQUARE = ord(lookup('BLACK SQUARE'))\nFORMAT = '<span style=\"color:{{:06x}}\">&#x{:x};</span>'.format(SQUARE)\n\nwith open('colors.html', 'w') as f:\n for _ in range(HEIGHT):\n for _ in range(WIDTH):\n f.write(FORMAT.format(randrange(0x1000000)))\n f.write('<br>')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T22:11:47.263",
"Id": "37447",
"ParentId": "37440",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:05:05.680",
"Id": "37440",
"Score": "6",
"Tags": [
"python",
"html",
"random"
],
"Title": "Generating random HTML color grid"
}
|
37440
|
<p>I have written <code>ExtendedConfigParser</code> class that adds ability to dot access config values like ExtendedConfigParser().section_name.option_name:</p>
<pre><code>from ConfigParser import SafeConfigParser
class ExtendedConfigParser(SafeConfigParser):
def __init__(self, config_file=None, type_conversion={}, *args, **kwargs):
self.config_file = config_file
self.type_conversion = type_conversion
SafeConfigParser.__init__(self, *args, **kwargs)
self.chain = []
self.cmap = {}
if config_file:
self.read(config_file)
def section2dict(self, secname):
opts = self.options(secname)
def opt_conv_type(optname, value):
if optname in self.cmap:
return self.cmap[optname](value)
return value
return {o:opt_conv_type(o, self.get(secname, o)) for o in opts}
def add_type_conversion_map(self, cmap):
self.cmap.update(cmap)
def __getattr__(self, attrname):
if attrname in self.sections():
self.chain.append(attrname)
return self
if len(self.chain) == 1 and attrname in self.section2dict(self.chain[0]):
return self.section2dict(self.chain[0])[attrname]
self.chain = []
return getattr(SafeConfigParser, attrname)(self)
</code></pre>
<p>Let's have config file like this:</p>
<pre><code>[globals]
webui_port = 8888
redis_host = 127.0.0.1
redis_port = 5600
</code></pre>
<p>Then it works like this:</p>
<pre><code>cmap = {'redis_port':int, 'webui_port':int}
cfg = ExtendedConfigParser(config_file=confile, type_conversion=cmap)
print cfg.globals.webui_port
</code></pre>
<p>What I do not like about the code above is that I'm doing sort of manual attribute resolution in <code>__getattr__</code>. Is there a better (cleaner, more general) solution?</p>
<p>And also what will happen if a section name happens to be called like <code>SafeConfigParser</code> attribute? It would override it, correct? How can I avoid that?</p>
|
[] |
[
{
"body": "<p>I'd start with the caveat that you're buying some syntax sugar at the cost of possible bugs - the need to do the attribute resolution, and as you point out the possibility of name clashes, makes it seem like it may not be worth the effort unless you need to access these class properties in lots of places in your code. </p>\n\n<p>That said you can simplify this by converting your sections - which are dictionaries -- to namedtuples:</p>\n\n<p>from collections import namedtuple</p>\n\n<pre><code>def section2dict(self, secname):\n if secname in self.__dict__:\n raise KeyError, \"%s is cannot be used as a property name\" % secname \n opts = self.options(secname)\n #nb: I didn't bother recreating the type code, but you would do it here...\n nt = namedtuple(secname, opts.keys())(**opts)\n self.__dict__[secname] = nt\n</code></pre>\n\n<p>By sticking the result into <strong>dict</strong> you don't have to override <strong>getattr</strong> yourself, which limits the intervention to a single place although it does deprive you of the option to do guard checks for bad values, etc. This example would except on name collisions and get you off the hook for manually redirecting double-dotted attribute queries. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:41:51.260",
"Id": "37539",
"ParentId": "37441",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37539",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T21:27:43.163",
"Id": "37441",
"Score": "1",
"Tags": [
"python"
],
"Title": "Risks related to overriding attribute access"
}
|
37441
|
<p>Even though it's the first time I'm writing something this "big", it feels like I know C# quite well (it is very similar to Java after all). It's been nice to learn LINQ also and I am very impressed by the features (which is just like Steams in Java 8), and perhaps I have overused it here (if it's possible to do that).</p>
<h3>Class summary</h3>
<ul>
<li>SudokuFactory: Contains static methods to create some Sudoku variations</li>
<li>SudokuBoard: Contains collection of <code>SudokuRule</code> and of <code>SudokuTile</code></li>
<li>SudokuRule: Whether it's a box, a line, a row, or something entirely different doesn't matter. Contains a collection of <code>SudokuTile</code> that must be unique.</li>
<li>SudokuTile: Each tile in the puzzle. Can be "blocked" (like a hole in the puzzle), remembers it's <code>possibleValues</code>, and also contains a value (0 is used for tiles without a value)</li>
<li>SudokuProgress: Used to know what the progress of a solving step was.</li>
<li>Program: Main starting point. Contains tests for seven different Sudokus. All have been verified to be solved correctly.</li>
</ul>
<p>Since this is the first time I'm using C# and LINQ, please tell me anything. All suggestions welcome. Except for the fact that the method <code>box</code> should be called <code>Box</code>. I'd be especially interested in cases where I could simplify some of the LINQ usage (trust me, there is a lot). I hope you are able to follow all the LINQ queries. I have tried to put some short comments where needed to explain what is happening. If you want an explanation for some part, post a comment and I will explain.</p>
<p>As usual, I have a tendency to make the challenge into something super-flexible with support for a whole lot of more or less unnecessary things. Some of the possible puzzles that this code can solve is:</p>
<ul>
<li>A hard classic <a href="https://codereview.meta.stackexchange.com/questions/1245/weekend-challenge-3/1248#1248">9x9 Sudoku with 3x3 boxes</a> that requires more advanced techniques (or in my case, more or less "brute force" by trial and error)</li>
<li><a href="http://en.wikipedia.org/wiki/File:A_nonomino_sudoku.svg" rel="noreferrer">Nonomino</a></li>
<li><a href="http://en.wikipedia.org/wiki/File:Oceans_Hypersudoku18_Puzzle.svg" rel="noreferrer">HyperSudoku</a></li>
<li><a href="http://www.freesamuraisudoku.com/1001HardSamuraiSudokus.aspx?puzzle=42" rel="noreferrer">Samurai Sudoku</a></li>
<li>A classic Sudoku of any size with any number of boxes and size of boxes (only completely tested on 9x9 with 3x3 boxes and 4x4 with 2x2 boxes but any sizes should be possible)</li>
</ul>
<p>These images are puzzles that are tested and solved in the below code:</p>
<p><img src="https://i.stack.imgur.com/EQVTA.png" alt="The Weekend Challenge Sudoku">
<img src="https://i.stack.imgur.com/rjZiQ.png" alt="Sudoku with "weird" boxes">
<img src="https://i.stack.imgur.com/KvsEr.png" alt="Sudoku with additional boxes">
<img src="https://i.stack.imgur.com/1DIp9.png" alt="Samurai Sudoku"></p>
<p>One known issue with the implementation is if you would input an empty puzzle, then it would work for years to find all the possible combinations for it.</p>
<p>SudokuProgress</p>
<pre><code>public enum SudokuProgress { FAILED, NO_PROGRESS, PROGRESS }
</code></pre>
<p>SudokuTile</p>
<pre><code>public class SudokuTile
{
internal static SudokuProgress CombineSolvedState(SudokuProgress a, SudokuProgress b)
{
if (a == SudokuProgress.FAILED)
return a;
if (a == SudokuProgress.NO_PROGRESS)
return b;
if (a == SudokuProgress.PROGRESS)
return b == SudokuProgress.FAILED ? b : a;
throw new InvalidOperationException("Invalid value for a");
}
public const int CLEARED = 0;
private int _maxValue;
private int _value;
private int _x;
private int _y;
private ISet<int> possibleValues;
private bool _blocked;
public SudokuTile(int x, int y, int maxValue)
{
_x = x;
_y = y;
_blocked = false;
_maxValue = maxValue;
possibleValues = new HashSet<int>();
_value = 0;
}
public int Value
{
get { return _value; }
set
{
if (value > _maxValue)
throw new ArgumentOutOfRangeException("SudokuTile Value cannot be greater than " + _maxValue.ToString() + ". Was " + value);
if (value < CLEARED)
throw new ArgumentOutOfRangeException("SudokuTile Value cannot be zero or smaller. Was " + value);
_value = value;
}
}
public bool HasValue
{
get { return Value != CLEARED; }
}
public string ToStringSimple()
{
return Value.ToString();
}
public override string ToString()
{
return String.Format("Value {0} at pos {1}, {2}. ", Value, _x, _y, possibleValues.Count);
}
internal void ResetPossibles()
{
possibleValues.Clear();
foreach (int i in Enumerable.Range(1, _maxValue))
{
if (!HasValue || Value == i)
possibleValues.Add(i);
}
}
public void Block()
{
_blocked = true;
}
internal void Fix(int value, string reason)
{
Console.WriteLine("Fixing {0} on pos {1}, {2}: {3}", value, _x, _y, reason);
Value = value;
ResetPossibles();
}
internal SudokuProgress RemovePossibles(IEnumerable<int> existingNumbers)
{
if (_blocked)
return SudokuProgress.NO_PROGRESS;
// Takes the current possible values and removes the ones existing in `existingNumbers`
possibleValues = new HashSet<int>(possibleValues.Where(x => !existingNumbers.Contains(x)));
SudokuProgress result = SudokuProgress.NO_PROGRESS;
if (possibleValues.Count == 1)
{
Fix(possibleValues.First(), "Only one possibility");
result = SudokuProgress.PROGRESS;
}
if (possibleValues.Count == 0)
return SudokuProgress.FAILED;
return result;
}
public bool IsValuePossible(int i)
{
return possibleValues.Contains(i);
}
public int X { get { return _x; } }
public int Y { get { return _y; } }
public bool IsBlocked { get { return _blocked; } } // A blocked field can not contain a value -- used for creating 'holes' in the map
public int PossibleCount
{
get {
return IsBlocked ? 1 : possibleValues.Count;
}
}
}
</code></pre>
<p>SudokuRule</p>
<pre><code>public class SudokuRule : IEnumerable<SudokuTile>
{
internal SudokuRule(IEnumerable<SudokuTile> tiles, string description)
{
_tiles = new HashSet<SudokuTile>(tiles);
_description = description;
}
private ISet<SudokuTile> _tiles;
private string _description;
public bool CheckValid()
{
var filtered = _tiles.Where(tile => tile.HasValue);
var groupedByValue = filtered.GroupBy(tile => tile.Value);
return groupedByValue.All(group => group.Count() == 1);
}
public bool CheckComplete()
{
return _tiles.All(tile => tile.HasValue) && CheckValid();
}
internal SudokuProgress RemovePossibles()
{
// Tiles that has a number already
IEnumerable<SudokuTile> withNumber = _tiles.Where(tile => tile.HasValue);
// Tiles without a number
IEnumerable<SudokuTile> withoutNumber = _tiles.Where(tile => !tile.HasValue);
// The existing numbers in this rule
IEnumerable<int> existingNumbers = new HashSet<int>(withNumber.Select(tile => tile.Value).Distinct().ToList());
SudokuProgress result = SudokuProgress.NO_PROGRESS;
foreach (SudokuTile tile in withoutNumber)
result = SudokuTile.CombineSolvedState(result, tile.RemovePossibles(existingNumbers));
return result;
}
internal SudokuProgress CheckForOnlyOnePossibility()
{
// Check if there is only one number within this rule that can have a specific value
IList<int> existingNumbers = _tiles.Select(tile => tile.Value).Distinct().ToList();
SudokuProgress result = SudokuProgress.NO_PROGRESS;
foreach (int value in Enumerable.Range(1, _tiles.Count))
{
if (existingNumbers.Contains(value)) // this rule already has the value, skip checking for it
continue;
var possibles = _tiles.Where(tile => !tile.HasValue && tile.IsValuePossible(value)).ToList();
if (possibles.Count == 0)
return SudokuProgress.FAILED;
if (possibles.Count == 1)
{
possibles.First().Fix(value, "Only possible in rule " + ToString());
result = SudokuProgress.PROGRESS;
}
}
return result;
}
internal SudokuProgress Solve()
{
// If both are null, return null (indicating no change). If one is null, return the other. Else return result1 && result2
SudokuProgress result1 = RemovePossibles();
SudokuProgress result2 = CheckForOnlyOnePossibility();
return SudokuTile.CombineSolvedState(result1, result2);
}
public override string ToString()
{
return _description;
}
public IEnumerator<SudokuTile> GetEnumerator()
{
return _tiles.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public string Description { get { return _description; } }
}
</code></pre>
<p>SudokuBoard:</p>
<pre><code>public class SudokuBoard
{
public SudokuBoard(SudokuBoard copy)
{
_maxValue = copy._maxValue;
tiles = new SudokuTile[copy.Width, copy.Height];
CreateTiles();
// Copy the tile values
foreach (var pos in SudokuFactory.box(Width, Height))
{
tiles[pos.Item1, pos.Item2] = new SudokuTile(pos.Item1, pos.Item2, _maxValue);
tiles[pos.Item1, pos.Item2].Value = copy.tiles[pos.Item1, pos.Item2].Value;
}
// Copy the rules
foreach (SudokuRule rule in copy.rules)
{
var ruleTiles = new HashSet<SudokuTile>();
foreach (SudokuTile tile in rule)
{
ruleTiles.Add(tiles[tile.X, tile.Y]);
}
rules.Add(new SudokuRule(ruleTiles, rule.Description));
}
}
public SudokuBoard(int width, int height, int maxValue)
{
_maxValue = maxValue;
tiles = new SudokuTile[width, height];
CreateTiles();
if (_maxValue == width || _maxValue == height) // If maxValue is not width or height, then adding line rules would be stupid
SetupLineRules();
}
public SudokuBoard(int width, int height) : this(width, height, Math.Max(width, height)) {}
private int _maxValue;
private void CreateTiles()
{
foreach (var pos in SudokuFactory.box(tiles.GetLength(0), tiles.GetLength(1)))
{
tiles[pos.Item1, pos.Item2] = new SudokuTile(pos.Item1, pos.Item2, _maxValue);
}
}
private void SetupLineRules()
{
// Create rules for rows and columns
for (int x = 0; x < Width; x++)
{
IEnumerable<SudokuTile> row = GetCol(x);
rules.Add(new SudokuRule(row, "Row " + x.ToString()));
}
for (int y = 0; y < Height; y++)
{
IEnumerable<SudokuTile> col = GetRow(y);
rules.Add(new SudokuRule(col, "Col " + y.ToString()));
}
}
internal IEnumerable<SudokuTile> TileBox(int startX, int startY, int sizeX, int sizeY)
{
return from pos in SudokuFactory.box(sizeX, sizeY) select tiles[startX + pos.Item1, startY + pos.Item2];
}
private IEnumerable<SudokuTile> GetRow(int row)
{
for (int i = 0; i < tiles.GetLength(0); i++)
{
yield return tiles[i, row];
}
}
private IEnumerable<SudokuTile> GetCol(int col)
{
for (int i = 0; i < tiles.GetLength(1); i++)
{
yield return tiles[col, i];
}
}
private ISet<SudokuRule> rules = new HashSet<SudokuRule>();
private SudokuTile[,] tiles;
public int Width
{
get { return tiles.GetLength(0); }
}
public int Height {
get { return tiles.GetLength(1); }
}
public void CreateRule(string description, params SudokuTile[] tiles)
{
rules.Add(new SudokuRule(tiles, description));
}
public void CreateRule(string description, IEnumerable<SudokuTile> tiles)
{
rules.Add(new SudokuRule(tiles, description));
}
public bool CheckValid()
{
return rules.All(rule => rule.CheckValid());
}
public IEnumerable<SudokuBoard> Solve()
{
ResetSolutions();
SudokuProgress simplify = SudokuProgress.PROGRESS;
while (simplify == SudokuProgress.PROGRESS) simplify = Simplify();
if (simplify == SudokuProgress.FAILED)
yield break;
// Find one of the values with the least number of alternatives, but that still has at least 2 alternatives
var query = from rule in rules
from tile in rule
where tile.PossibleCount > 1
orderby tile.PossibleCount ascending
select tile;
SudokuTile chosen = query.FirstOrDefault();
if (chosen == null)
{
// The board has been completed, we're done!
yield return this;
yield break;
}
Console.WriteLine("SudokuTile: " + chosen.ToString());
foreach (var value in Enumerable.Range(1, _maxValue))
{
// Iterate through all the valid possibles on the chosen square and pick a number for it
if (!chosen.IsValuePossible(value))
continue;
var copy = new SudokuBoard(this);
copy.Tile(chosen.X, chosen.Y).Fix(value, "Trial and error");
foreach (var innerSolution in copy.Solve())
yield return innerSolution;
}
yield break;
}
public void Output()
{
for (int y = 0; y < tiles.GetLength(1); y++)
{
for (int x = 0; x < tiles.GetLength(0); x++)
{
Console.Write(tiles[x, y].ToStringSimple());
}
Console.WriteLine();
}
}
public SudokuTile Tile(int x, int y)
{
return tiles[x, y];
}
private int _rowAddIndex;
public void AddRow(string s)
{
// Method for initializing a board from string
for (int i = 0; i < s.Length; i++)
{
var tile = tiles[i, _rowAddIndex];
if (s[i] == '/')
{
tile.Block();
continue;
}
int value = s[i] == '.' ? 0 : (int)Char.GetNumericValue(s[i]);
tile.Value = value;
}
_rowAddIndex++;
}
internal void ResetSolutions()
{
foreach (SudokuTile tile in tiles)
tile.ResetPossibles();
}
internal SudokuProgress Simplify()
{
SudokuProgress result = SudokuProgress.NO_PROGRESS;
bool valid = CheckValid();
if (!valid)
return SudokuProgress.FAILED;
foreach (SudokuRule rule in rules)
result = SudokuTile.CombineSolvedState(result, rule.Solve());
return result;
}
internal void AddBoxesCount(int boxesX, int boxesY)
{
int sizeX = Width / boxesX;
int sizeY = Height / boxesY;
var boxes = SudokuFactory.box(sizeX, sizeY);
foreach (var pos in boxes)
{
IEnumerable<SudokuTile> boxTiles = TileBox(pos.Item1 * sizeX, pos.Item2 * sizeY, sizeX, sizeY);
CreateRule("Box at (" + pos.Item1.ToString() + ", " + pos.Item2.ToString() + ")", boxTiles);
}
}
internal void OutputRules()
{
foreach (var rule in rules)
{
Console.WriteLine(String.Join(",", rule) + " - " + rule.ToString());
}
}
}
</code></pre>
<p>SudokuFactory:</p>
<pre><code>public class SudokuFactory
{
private const int DefaultSize = 9;
private const int SamuraiAreas = 7;
private const int BoxSize = 3;
private const int HyperMargin = 1;
public static IEnumerable<Tuple<int, int>> box(int sizeX, int sizeY)
{
foreach (int x in Enumerable.Range(0, sizeX))
{
foreach (int y in Enumerable.Range(0, sizeY))
{
yield return new Tuple<int, int>(x, y);
}
}
}
public static SudokuBoard Samurai()
{
SudokuBoard board = new SudokuBoard(SamuraiAreas*BoxSize, SamuraiAreas*BoxSize, DefaultSize);
// Removed the empty areas where there are no tiles
var queriesForBlocked = new List<IEnumerable<SudokuTile>>();
queriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 ));
queriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 + DefaultSize * 2 - BoxSize));
queriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 , pos.Item2 + DefaultSize));
queriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 + DefaultSize * 2 - BoxSize, pos.Item2 + DefaultSize));
foreach (var query in queriesForBlocked)
{
foreach (var tile in query) tile.Block();
}
// Select the tiles in the 3 x 3 area (area.X, area.Y) and create rules for them
foreach (var area in box(SamuraiAreas, SamuraiAreas))
{
var tilesInArea = from pos in box(BoxSize, BoxSize) select board.Tile(area.Item1 * BoxSize + pos.Item1, area.Item2 * BoxSize + pos.Item2);
if (tilesInArea.First().IsBlocked)
continue;
board.CreateRule("Area " + area.Item1.ToString() + ", " + area.Item2.ToString(), tilesInArea);
}
// Select all rows and create columns for them
var cols = from pos in box(board.Width, 1) select new { X = pos.Item1, Y = pos.Item2 };
var rows = from pos in box(1, board.Height) select new { X = pos.Item1, Y = pos.Item2 };
foreach (var posSet in Enumerable.Range(0, board.Width))
{
board.CreateRule("Column Upper " + posSet, from pos in box(1, DefaultSize) select board.Tile(posSet, pos.Item2));
board.CreateRule("Column Lower " + posSet, from pos in box(1, DefaultSize) select board.Tile(posSet, pos.Item2 + DefaultSize + BoxSize));
board.CreateRule("Row Left " + posSet, from pos in box(DefaultSize, 1) select board.Tile(pos.Item1, posSet));
board.CreateRule("Row Right " + posSet, from pos in box(DefaultSize, 1) select board.Tile(pos.Item1 + DefaultSize + BoxSize, posSet));
if (posSet >= BoxSize*2 && posSet < BoxSize*2 + DefaultSize)
{
// Create rules for the middle sudoku
board.CreateRule("Column Middle " + posSet, from pos in box(1, 9) select board.Tile(posSet, pos.Item2 + BoxSize*2));
board.CreateRule("Row Middle " + posSet, from pos in box(9, 1) select board.Tile(pos.Item1 + BoxSize*2, posSet));
}
}
return board;
}
public static SudokuBoard SizeAndBoxes(int width, int height, int boxCountX, int boxCountY)
{
SudokuBoard board = new SudokuBoard(width, height);
board.AddBoxesCount(boxCountX, boxCountY);
return board;
}
public static SudokuBoard ClassicWith3x3Boxes()
{
return SizeAndBoxes(DefaultSize, DefaultSize, DefaultSize / BoxSize, DefaultSize / BoxSize);
}
public static SudokuBoard ClassicWith3x3BoxesAndHyperRegions()
{
SudokuBoard board = ClassicWith3x3Boxes();
const int HyperSecond = HyperMargin + BoxSize + HyperMargin;
// Create the four extra hyper regions
board.CreateRule("HyperA", from pos in box(3, 3) select board.Tile(pos.Item1 + HyperMargin, pos.Item2 + HyperMargin));
board.CreateRule("HyperB", from pos in box(3, 3) select board.Tile(pos.Item1 + HyperSecond, pos.Item2 + HyperMargin));
board.CreateRule("HyperC", from pos in box(3, 3) select board.Tile(pos.Item1 + HyperMargin, pos.Item2 + HyperSecond));
board.CreateRule("HyperD", from pos in box(3, 3) select board.Tile(pos.Item1 + HyperSecond, pos.Item2 + HyperSecond));
return board;
}
public static SudokuBoard ClassicWithSpecialBoxes(string[] areas)
{
int sizeX = areas[0].Length;
int sizeY = areas.Length;
SudokuBoard board = new SudokuBoard(sizeX, sizeY);
var joinedString = String.Join("", areas);
var grouped = joinedString.Distinct();
// Loop through all the unique characters
foreach (var ch in grouped)
{
// Select the rule tiles based on the index of the character
var ruleTiles = from i in Enumerable.Range(0, joinedString.Length)
where joinedString[i] == ch // filter out any non-matching characters
select board.Tile(i % sizeX, i / sizeY);
board.CreateRule("Area " + ch.ToString(), ruleTiles);
}
return board;
}
}
</code></pre>
<p>Program:</p>
<pre><code>static class Program
{
[STAThread]
static void Main()
{
SolveFail();
SolveClassic();
SolveSmall();
SolveExtraZones();
SolveHyper();
SolveSamurai();
SolveIncompleteClassic();
}
private static void SolveFail()
{
SudokuBoard board = SudokuFactory.SizeAndBoxes(4, 4, 2, 2);
board.AddRow("0003");
board.AddRow("0204"); // the 2 must be a 1 on this row to be solvable
board.AddRow("1000");
board.AddRow("4000");
CompleteSolve(board);
}
private static void SolveExtraZones()
{
// http://en.wikipedia.org/wiki/File:Oceans_Hypersudoku18_Puzzle.svg
SudokuBoard board = SudokuFactory.ClassicWith3x3BoxesAndHyperRegions();
board.AddRow(".......1.");
board.AddRow("..2....34");
board.AddRow("....51...");
board.AddRow(".....65..");
board.AddRow(".7.3...8.");
board.AddRow("..3......");
board.AddRow("....8....");
board.AddRow("58....9..");
board.AddRow("69.......");
CompleteSolve(board);
}
private static void SolveSmall()
{
SudokuBoard board = SudokuFactory.SizeAndBoxes(4, 4, 2, 2);
board.AddRow("0003");
board.AddRow("0004");
board.AddRow("1000");
board.AddRow("4000");
CompleteSolve(board);
}
private static void SolveHyper()
{
// http://en.wikipedia.org/wiki/File:A_nonomino_sudoku.svg
string[] areas = new string[]{
"111233333",
"111222333",
"144442223",
"114555522",
"444456666",
"775555688",
"977766668",
"999777888",
"999997888"
};
SudokuBoard board = SudokuFactory.ClassicWithSpecialBoxes(areas);
board.AddRow("3.......4");
board.AddRow("..2.6.1..");
board.AddRow(".1.9.8.2.");
board.AddRow("..5...6..");
board.AddRow(".2.....1.");
board.AddRow("..9...8..");
board.AddRow(".8.3.4.6.");
board.AddRow("..4.1.9..");
board.AddRow("5.......7");
CompleteSolve(board);
}
private static void SolveSamurai()
{
// http://www.freesamuraisudoku.com/1001HardSamuraiSudokus.aspx?puzzle=42
SudokuBoard board = SudokuFactory.Samurai();
board.AddRow("6..8..9..///.....38..");
board.AddRow("...79....///89..2.3..");
board.AddRow("..2..64.5///...1...7.");
board.AddRow(".57.1.2..///..5....3.");
board.AddRow(".....731.///.1.3..2..");
board.AddRow("...3...9.///.7..429.5");
board.AddRow("4..5..1...5....5.....");
board.AddRow("8.1...7...8.2..768...");
board.AddRow(".......8.23...4...6..");
board.AddRow("//////.12.4..9.//////");
board.AddRow("//////......82.//////");
board.AddRow("//////.6.....1.//////");
board.AddRow(".4...1....76...36..9.");
board.AddRow("2.....9..8..5.34...81");
board.AddRow(".5.873......9.8..23..");
board.AddRow("...2....9///.25.4....");
board.AddRow("..3.64...///31.8.....");
board.AddRow("..75.8.12///...6.14..");
board.AddRow(".......2.///.31...9..");
board.AddRow("..17.....///..7......");
board.AddRow(".7.6...84///8...7..5.");
CompleteSolve(board);
}
private static void SolveClassic()
{
var board = SudokuFactory.ClassicWith3x3Boxes();
board.AddRow("...84...9");
board.AddRow("..1.....5");
board.AddRow("8...2146.");
board.AddRow("7.8....9.");
board.AddRow(".........");
board.AddRow(".5....3.1");
board.AddRow(".2491...7");
board.AddRow("9.....5..");
board.AddRow("3...84...");
CompleteSolve(board);
}
private static void SolveIncompleteClassic()
{
var board = SudokuFactory.ClassicWith3x3Boxes();
board.AddRow("...84...9");
board.AddRow("..1.....5");
board.AddRow("8...2.46."); // Removed a "1" on this line
board.AddRow("7.8....9.");
board.AddRow(".........");
board.AddRow(".5....3.1");
board.AddRow(".2491...7");
board.AddRow("9.....5..");
board.AddRow("3...84...");
CompleteSolve(board);
}
private static void CompleteSolve(SudokuBoard board)
{
Console.WriteLine("Rules:");
board.OutputRules();
Console.WriteLine("Board:");
board.Output();
var solutions = board.Solve().ToList();
Console.WriteLine("Base Board Progress:");
board.Output();
Console.WriteLine("--");
Console.WriteLine("--");
Console.WriteLine("All " + solutions.Count + " solutions:");
var i = 1;
foreach (var solution in solutions)
{
Console.WriteLine("----------------");
Console.WriteLine("Solution " + i++.ToString() + " / " + solutions.Count + ":");
solution.Output();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T22:25:57.517",
"Id": "61948",
"Score": "14",
"body": "Simon-André \"Extra Mile\" Forsberg is the name!"
}
] |
[
{
"body": "<p>Impressive. I mean it.</p>\n\n<p>Couple observations:</p>\n\n<p>Your enums...</p>\n\n<pre><code>public enum SudokuProgress { FAILED, NO_PROGRESS, PROGRESS }\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>public enum SudokuProgress { Failed, NoProgress, Progress }\n</code></pre>\n\n<hr>\n\n<p>When the first thing you see is this:</p>\n\n<pre><code>public class SudokuBoard\n{\n public SudokuBoard(SudokuBoard copy)\n {\n _maxValue = copy._maxValue;\n tiles = new SudokuTile[copy.Width, copy.Height];\n CreateTiles();\n</code></pre>\n\n<p>you wonder where <code>_maxValue</code> and <code>tiles</code> come from, and why <code>_maxValue</code> (whose naming convention is that of a private field) can be accessed like that - I would expose it as a get-only property. Accessing private fields from another object doesn't seem instinctively right to me.</p>\n\n<p>Speaking of the devil:</p>\n\n<pre><code>private int _maxValue;\n</code></pre>\n\n<p>This line belongs just above the constructor that's using it (it's 30-some lines below its first usage).</p>\n\n<p>This <code>box</code> method <s>which should be named <code>Box</code></s> (actually <code>box</code> is a bad name because it's the name of a <a href=\"http://en.wikipedia.org/wiki/List_of_CIL_instructions\" rel=\"noreferrer\">CIL instruction</a> that your C# compiles to), is returning a not-so-pretty <code>Tuple<T1,T2></code> - The framework has a type called <code>Point</code> which has <code>X</code> and <code>Y</code> properties; if that's not appropriate, I don't know what is. Side note, <code>Point</code> is a <em>value type</em>, so there's no <em>boxing</em> actually going on if you use it over a <code>Tuple</code>, which is a <em>reference type</em> (incurs boxing). Bottom line, use a <code>Point</code> and call that method something else:</p>\n\n<pre><code>public static IEnumerable<Point> Box(int sizeX, int sizeY)\n{\n foreach (int x in Enumerable.Range(0, sizeX))\n {\n foreach (int y in Enumerable.Range(0, sizeY))\n {\n yield return new Point(x, y);\n }\n }\n}\n</code></pre>\n\n<p>You want to abuse LINQ? How about taking this:</p>\n\n<pre><code>private SudokuTile[,] tiles;\nprivate void CreateTiles()\n{\n foreach (var pos in SudokuFactory.box(tiles.GetLength(0), tiles.GetLength(1)))\n {\n tiles[pos.Item1, pos.Item2] = new SudokuTile(pos.Item1, pos.Item2, _maxValue);\n }\n}\n</code></pre>\n\n<p>And turning it into that:</p>\n\n<pre><code>private Dictionary<Point, SudokuTile> tiles;\nprivate void CreateTiles()\n{\n tiles = SudokuFactory\n .Box(tiles.GetLength(0), tiles.GetLength(1))\n .Select(p => new KeyValuePair<Point, SudokuTile>{ Key = p, Value = new SudokuTile(p.X, p.Y, _maxValue)})\n .ToDictionary(kvp => pkv.Key, kvp => kvp.Value);\n}\n</code></pre>\n\n<p>It takes the <code>IEnumerable<Point></code> returned by the modified <code>Box</code> method, selects each point into the <code>Key</code> of a <code>KeyValuePair</code> and a new <code>SudokuTile</code> as the vale, and then <code>ToDictionary</code> selects the Enumerable into a dictionary, which gets assigned to <code>tiles</code>. (<s>C#: 1, Java: 0</s>) Lines of code: 1.</p>\n\n<hr>\n\n<p>In <code>SudokuRule</code>, your private fields can be marked as <code>readonly</code>.</p>\n\n<p>This is only a partial review, I'll write more after I've implemented my own solution - I purposely haven't looked at your puzzle-resolution code :)</p>\n\n<p>Overall looks quite good (except for all that <code>static</code> stuff that doesn't <em>need</em> to be, but that's <a href=\"/questions/tagged/dependency-injection\" class=\"post-tag\" title=\"show questions tagged 'dependency-injection'\" rel=\"tag\">dependency-injection</a> me talking, doesn't make it any worse <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged 'c#'\" rel=\"tag\">c#</a>, but testing might be more enjoyable with non-static dependencies), It's great that you gave C# a bit of lovin' this week. I know Visual Studio isn't Eclipse, but I can assure you that VS with ReSharper would have made it a similar experience (and could have shown you some LINQ tricks!), at least in terms of code inspections (R# makes VS actually better than Eclipse... but I'm biased, and drifting, so I'll keep it at that!)...</p>\n\n<hr>\n\n<p>I like how your <code>Solve()</code> method <code>yield</code> returns all found solutions.</p>\n\n<p>That said, if your entire project is compiled into 1 single assembly (.exe/.dll), your usage of the <code>internal</code> access modifier is equivalent to <code>public</code> - <code>internal</code> basically means \"assembly scope\", so an <code>internal</code> type or method cannot be accessed <em>from another assembly</em>; if there's no other assembly, everything in the project can \"see\" it, so I don't see a point for <code>internal</code> here.</p>\n\n<p>Not much left to say, except perhaps method <code>IsValuePossible</code> might be better off as <code>IsPossibleValue</code>, but that's mere nitpicking. Very neat, I'm jealous.</p>\n\n<p>One last thing - this piece of list-initialization code:</p>\n\n<blockquote>\n<pre><code>var queriesForBlocked = new List<IEnumerable<SudokuTile>>();\nqueriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 ));\nqueriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 + DefaultSize * 2 - BoxSize));\nqueriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 , pos.Item2 + DefaultSize));\nqueriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 + DefaultSize * 2 - BoxSize, pos.Item2 + DefaultSize));\n</code></pre>\n</blockquote>\n\n<p>Could use a <em>collection initializer</em> and be written like this:</p>\n\n<pre><code>var queriesForBlocked = new List<IEnumerable<SudokuTile>>\n {\n { box(BoxSize, BoxSize*2).Select(pos => board.Tile(pos.Item1 + DefaultSize, pos.Item2)) },\n { box(BoxSize, BoxSize*2).Select(pos => board.Tile(pos.Item1 + DefaultSize, pos.Item2 + DefaultSize * 2 - BoxSize)) },\n { box(BoxSize*2, BoxSize).Select(pos => board.Tile(pos.Item1, pos.Item2 + DefaultSize)) },\n { box(BoxSize*2, BoxSize).Select(pos => board.Tile(pos.Item1 + DefaultSize * 2 - BoxSize, pos.Item2 + DefaultSize)) }\n };\n</code></pre>\n\n<p>Each item in the <em>collection initializer</em> actually calls the <code>.Add</code> method anyway, so it's completely equivalent. Except it's 1 single instruction now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T05:59:30.573",
"Id": "37479",
"ParentId": "37448",
"Score": "48"
}
},
{
"body": "<p>Can't read all this code on my phone even though it looks pretty well structured to me! Good job!</p>\n\n<p>I saw this. Isn't the exception message contradicting the <code>if</code> clause?</p>\n\n<pre><code>if (value < CLEARED)\n throw new ArgumentOutOfRangeException(\"SudokuTile Value cannot be zero or smaller. Was \" + value);\n</code></pre>\n\n<p><code>CLEARED</code> is set to 0, and the if checks for 'less than 0' so the value could be set to 0.</p>\n\n<p>Also, not having run the code, why does the <code>toString()</code> have four parameters on <code>String.Format</code>, only using three?</p>\n\n<p>I'll have a closer look when I'm at a computer, but nice work! </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:16:13.947",
"Id": "62087",
"Score": "0",
"body": "You're right, I used to have a `ClearValue` method to handle clearing separately, but I realized that was useless as I was just doing `if-else` to check if I should set the value or call the ClearValue method. Forgot to change the exception description. Also forgot to remove that extra parameter from `String.Format`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:35:27.927",
"Id": "37482",
"ParentId": "37448",
"Score": "23"
}
},
{
"body": "<p>I know next to zilch about C# so I won't be much help with this review, but I can say that it looks well thought out and implements some cool features. And like retailcoder I'm still working on my version (hoping to minimize the brute-force portion) using Ruby.</p>\n\n<p>If C# allows enums to implement methods, I would move <code>CombineSolvedState</code> into <code>SudokuProgress</code>. Forgive my Java syntax, but if this is allowed I expect it will be easy to translate.</p>\n\n<pre><code>public enum SudokuProgress {\n public SudokuProgress CombineSolvedState(SudokuProgress solved) {\n if (this == SudokuProgress.FAILED)\n return this;\n if (this == SudokuProgress.NO_PROGRESS)\n return solved;\n if (this == SudokuProgress.PROGRESS)\n return solved == SudokuProgress.FAILED ? solved : this;\n throw new InvalidOperationException(\"Invalid value for \" + this);\n }\n\n FAILED, NO_PROGRESS, PROGRESS\n}\n</code></pre>\n\n<p>I think <a href=\"https://stackoverflow.com/questions/7443126/enum-with-methods-for-functionality-combine-class-enum\">this SO question</a> addresses the issue, and one answer says it's not directly possible without using a class instead of an enum while another implies that it can be done using extensions.</p>\n\n<p>Also, can't you use enums in a <code>switch</code> statement instead of a series of <code>if</code>s?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:12:24.407",
"Id": "62056",
"Score": "5",
"body": "Enums in C# cannot have methods, but indeed it would be nice to have that.\nAnd Yes, you can type sw[itch], Tab (auto-expand) and then the name of a variable/parameter of the type of the enum and VS will provide case statements for all the members."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:08:57.763",
"Id": "62085",
"Score": "0",
"body": "Yeah, I wanted to use enum methods but unlike Java, C# doesn't have them. You're right about the switch-statement though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:30:55.883",
"Id": "62744",
"Score": "1",
"body": "Enums in C# can have extension methods, which would let you achieve the same syntax."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T21:24:59.210",
"Id": "62749",
"Score": "0",
"body": "@breischl - The [second answer](http://stackoverflow.com/a/7445807/285873) to the question I linked above mentioned extension methods as well, but I couldn't figure out the syntax from its example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T21:34:16.277",
"Id": "62750",
"Score": "0",
"body": "Ah, right. Sorry, I skimmed the tail end of the answer and missed that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T22:15:58.577",
"Id": "62753",
"Score": "0",
"body": "@breischl - No worries! Does that answer describe fully how to use extension methods for an enum? I couldn't see how they were connected together short of the name of the class ending in `Extensions`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T23:03:29.607",
"Id": "62756",
"Score": "0",
"body": "Yep. The only this that connects them together is the \"this\" in the method argument list. Extension methods are just a tiny bit of syntactic sugar on top of a static method, so there's not much to it."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:48:54.023",
"Id": "37484",
"ParentId": "37448",
"Score": "19"
}
},
{
"body": "<p>You can write your <code>Box</code> method without <code>foreach</code> loops or <code>yield return</code>:</p>\n\n<pre><code>public static IEnumerable<Tuple<int, int>> Box(int sizeX, int sizeY)\n{\n return \n from x in Enumerable.Range(0, sizeX)\n from y in Enumerable.Range(0, sizeY)\n select Tuple.Create(x,y);\n}\n</code></pre>\n\n<p>or equivalently:</p>\n\n<pre><code>public static IEnumerable<Tuple<int, int>> Box2(int sizeX, int sizeY)\n{\n return \n Enumerable.Range(0,sizeX).SelectMany(x => \n Enumerable.Range(0,sizeY).Select(y => \n Tuple.Create(x,y)));\n}\n</code></pre>\n\n<p>Standard, and less verbose, method of creating <code>Tuple</code>s is <code>Tuple.Create</code>.</p>\n\n<p>If you had made your <code>Tile</code>, <code>Rule</code>, and <code>Board</code> immutable, as they are; sharing state between them would not have been a problem. For example two <strong>Samurai Sudoku</strong> puzzles <em>do share</em> rules.</p>\n\n<p>Your model does not differentiate between an empty board and a partial assignment;\nA position of a board and an assignment to that position you call both <code>Tile</code>. You call <code>Tuple<int,int></code> <code>position</code> in places. </p>\n\n<ul>\n<li><p><code>_rowAddIndex</code> looks like an orphan. It clearly do not belong to that class.</p></li>\n<li><p><code>AddRow</code> should be called some exact number of times.</p></li>\n<li><p>Before calling anything else. Seems like a constructor to me.</p></li>\n</ul>\n\n<p>Also there is not differentiation between a puzzle and its solving method. A puzzle is an immutable structure. Every one trying to solve some puzzle on the newspaper is trying to solve <strong>the same puzzle</strong>. They use different methods and use different temporary data structures.</p>\n\n<pre><code>Board board = samuraiSudokuBoard.create();\nPartialAssignment puzzle = new PartialAssignment(board, parse(puzzleStr));\nSolutionStrategy strategy = new RecursiveStrategy(maxDepth);\nvar solutions = strategy.Solve(puzzle);\nvar solutions2 = new IterativeStrategy(maxStackSize).Solve(puzzle);\nvar solutions2 = new ConcurrentStrategy(maxThreads).Solve(puzzle);\nvar comparison = CompareSolutionTimes(puzzle, strategies);\n</code></pre>\n\n<p>You are aggregating here.</p>\n\n<pre><code>SudokuProgress result = SudokuProgress.NO_PROGRESS;\nforeach (SudokuTile tile in withoutNumber)\n result = SudokuTile.CombineSolvedState(result, \n tile.RemovePossibles(existingNumbers));\nreturn result;\n</code></pre>\n\n<p>can be rewritten more clearly as:</p>\n\n<pre><code>return withoutNumber.Aggregate(\n SudokuProgress.NO_PROGRESS,\n (result, tile) => SudokuTile.CombineSolvedState(\n result, \n tile.RemovePossibles(existingNumbers)));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:19:59.263",
"Id": "62089",
"Score": "0",
"body": "I'm not sure how you mean to share state between boards... If they would have been immutable, then I would have needed to make a whole lot of extra code to solve the map, as all the basic solving (the non-brute-force part) would need to create a whole new map.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:29:48.230",
"Id": "62123",
"Score": "0",
"body": "@SimonAndréForsberg The separation would be between the classes that model 1) the layout and rules of the board, 2) the initial known cells of that particular puzzle, and 3) the mutable model used to solve that puzzle. While very cool, it would be a lot more code for something designed to run in a single-user console app."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:52:48.620",
"Id": "62127",
"Score": "0",
"body": "You have some very good points, which will be good to think about for further projects, but for this weekly challenge it would have been even more overkill I think :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:58:10.813",
"Id": "37506",
"ParentId": "37448",
"Score": "17"
}
},
{
"body": "<p>This is amazing. Especially for person who is not using C# every day for years.</p>\n\n<hr>\n\n<p>My main concerns are </p>\n\n<ul>\n<li>too many thing that are <code>public</code> that should be <code>internal</code>, sometimes <code>internal</code> members can be turned to <code>private</code>. Use the most restrictive access level that makes sense for a particular member.</li>\n<li>error-prone method <code>AddRow</code> of <code>SudokuBoard</code>. I'd prefer single string array passing to <code>SudokuFactory</code> constructor instead of multiple <code>AddRow</code> calls. It's easy to call this method too many or too few times to get a runtime exception.</li>\n<li>absence of some string representation of solution result that could be used in unit tests.</li>\n<li>console output method like <code>Output</code> and <code>OutputRules</code> in core classes. They should reside in <code>Program</code> because they are just used for console output, nothing more.</li>\n<li>absence of unit tests. I've moved your logic to separate library and added unit test project. This is the first thing I did when I started to refactor your code to be sure that my refactoring won't break anything.<br />\nAlso I'd use .NET Standard library type. This will allow to reuse the same logic for website, mobile (Xamarin) and desktop applications.</li>\n</ul>\n\n<hr>\n\n<h2>Unit tests</h2>\n\n<p>To add unit tests I've added <code>string[] tileDefinitions</code> parameter to <code>SudokuBoard</code> constructors (also they should be <code>internal</code>):</p>\n\n<pre><code>internal SudokuBoard(int width, int height, int maxValue, string[] tileDefinitions)\n{\n _maxValue = maxValue;\n tiles = new SudokuTile[width, height];\n CreateTiles();\n if (_maxValue == width || _maxValue == height) // If maxValue is not width or height, then adding line rules would be stupid\n SetupLineRules();\n\n Populate(tileDefinitions);\n}\n\ninternal SudokuBoard(int width, int height, string[] tileDefinitions) : this(width, height, Math.Max(width, height), tileDefinitions)\n{\n}\n</code></pre>\n\n<p>Also I've removed <code>_rowAddIndex</code> field and replaced <code>AddRow</code> method with <code>PopulateTiles</code>:</p>\n\n<pre><code>private void PopulateTiles(string[] tileDefinitions)\n{\n for (int row = 0; row < tileDefinitions.Length; row++)\n {\n string tileDefinition = tileDefinitions[row];\n\n for (int column = 0; column < tileDefinition.Length; column++)\n {\n SudokuTile tile = _tiles[column, row];\n if (tileDefinition[column] == '/')\n {\n tile.Block();\n continue;\n }\n tile.Value = tileDefinition[column] == '.' ? SudokuTile.CLEARED : (int)char.GetNumericValue(tileDefinition[column]);\n }\n }\n}\n</code></pre>\n\n<p>Now I've added <code>string[] tileDefinitions</code> to all <code>SudokuFactory</code> methods.</p>\n\n<p>To get simple string representation of sudoku solution that could be easily used in unit tests and maybe in other projects I've added <code>string[] TileDefinitions</code> public property to <code>SudokuBoard</code>:</p>\n\n<pre><code>public string[] TileDefinitions => tiles\n .Cast<SudokuTile>()\n .OrderBy(t => t.X)\n .ThenBy(t => t.Y)\n .GroupBy(t => t.Y)\n .Select(g => string.Join(string.Empty, g.Select(t => t.Value)))\n .ToArray();\n</code></pre>\n\n<p>Now code of our unit tests (I've reused your code from console output for test cases). I'm using XUnit here:</p>\n\n<pre><code>public class SudokuSolverTests\n{\n [Fact]\n public void SudokuBoard_Solve_NoSolutionFound()\n {\n // Arrange\n SudokuBoard board = SudokuFactory.SizeAndBoxes(4, 4, 2, 2, new[]\n {\n \"0003\",\n \"0204\", // the 2 must be a 1 on this row to be solvable\n \"1000\",\n \"4000\"\n });\n\n // Act\n IEnumerable<SudokuBoard> solutions = board.Solve();\n\n // Assert\n Assert.False(solutions.Any());\n }\n\n [Fact]\n public void SudokuBoard_Solve_ClassicWithSolution()\n {\n // Arrange\n SudokuBoard board = SudokuFactory.ClassicWith3x3Boxes(new[]\n {\n \"...84...9\",\n \"..1.....5\",\n \"8...2146.\",\n \"7.8....9.\",\n \".........\",\n \".5....3.1\",\n \".2491...7\",\n \"9.....5..\",\n \"3...84...\"\n });\n\n string[] tileDefinitions = new[]\n {\n \"632845179\",\n \"471369285\",\n \"895721463\",\n \"748153692\",\n \"163492758\",\n \"259678341\",\n \"524916837\",\n \"986237514\",\n \"317584926\",\n };\n\n // Act\n IEnumerable<SudokuBoard> solutions = board.Solve();\n\n // Assert\n Assert.Single(solutions);\n Assert.Equal(tileDefinitions, solutions.First().TileDefinitions);\n }\n\n [Fact]\n public void SudokoBoard_Solve_ClassicWithMultipleSolutions()\n {\n // Arrange\n SudokuBoard board = SudokuFactory.ClassicWith3x3Boxes(new[]\n {\n \"...84...9\",\n \"..1.....5\",\n \"8...2.46.\", // Removed a \"1\" on this line\n \"7.8....9.\",\n \".........\",\n \".5....3.1\",\n \".2491...7\",\n \"9.....5..\",\n \"3...84...\"\n });\n\n // Act\n IEnumerable<SudokuBoard> solutions = board.Solve();\n\n // Assert\n Assert.Equal(20, solutions.Count());\n }\n\n [Fact]\n public void SudukoBoard_Solve_SmallWithSolution()\n {\n // Arrange\n SudokuBoard board = SudokuFactory.SizeAndBoxes(4, 4, 2, 2, new[]\n {\n \"0003\",\n \"0004\",\n \"1000\",\n \"4000\"\n });\n\n string[] tileDefinitions = new[]\n {\n \"2413\",\n \"3124\",\n \"1342\",\n \"4231\"\n };\n\n // Act\n IEnumerable<SudokuBoard> solutions = board.Solve();\n\n // Assert\n Assert.Single(solutions);\n Assert.Equal(tileDefinitions, solutions.Single().TileDefinitions);\n }\n\n [Fact]\n public void SudokoBoard_Solve_ExtraZonesWithSolution()\n {\n // Arrange\n // http://en.wikipedia.org/wiki/File:Oceans_Hypersudoku18_Puzzle.svg\n SudokuBoard board = SudokuFactory.ClassicWith3x3BoxesAndHyperRegions(new[]\n {\n \".......1.\",\n \"..2....34\",\n \"....51...\",\n \".....65..\",\n \".7.3...8.\",\n \"..3......\",\n \"....8....\",\n \"58....9..\",\n \"69.......\"\n });\n\n string[] tileDefinitions = new[]\n {\n \"946832715\",\n \"152697834\",\n \"738451296\",\n \"819726543\",\n \"475319682\",\n \"263548179\",\n \"327985461\",\n \"584163927\",\n \"691274358\"\n };\n\n // Act\n IEnumerable<SudokuBoard> solutions = board.Solve();\n\n // Assert\n Assert.Single(solutions);\n Assert.Equal(tileDefinitions, solutions.First().TileDefinitions);\n }\n\n [Fact]\n public void SudokoBoard_Solve_HyperWithSolution()\n {\n // Arrange\n // http://en.wikipedia.org/wiki/File:A_nonomino_sudoku.svg\n string[] areas = new string[]\n {\n \"111233333\",\n \"111222333\",\n \"144442223\",\n \"114555522\",\n \"444456666\",\n \"775555688\",\n \"977766668\",\n \"999777888\",\n \"999997888\"\n };\n SudokuBoard board = SudokuFactory.ClassicWithSpecialBoxes(areas, new[]\n {\n \"3.......4\",\n \"..2.6.1..\",\n \".1.9.8.2.\",\n \"..5...6..\",\n \".2.....1.\",\n \"..9...8..\",\n \".8.3.4.6.\",\n \"..4.1.9..\",\n \"5.......7\"\n });\n\n string[] tileDefinitions = new[]\n {\n \"358196274\",\n \"492567138\",\n \"613978425\",\n \"175842693\",\n \"826453719\",\n \"249731856\",\n \"987324561\",\n \"734615982\",\n \"561289347\"\n };\n\n // Act\n IEnumerable<SudokuBoard> solutions = board.Solve();\n\n // Assert\n Assert.Single(solutions);\n Assert.Equal(tileDefinitions, solutions.First().TileDefinitions);\n }\n\n [Fact]\n public void SudokoBoard_Solve_SamuraiWithSolution()\n {\n // Arrange\n // http://www.freesamuraisudoku.com/1001HardSamuraiSudokus.aspx?puzzle=42\n SudokuBoard board = SudokuFactory.Samurai(new[]\n {\n \"6..8..9..///.....38..\",\n \"...79....///89..2.3..\",\n \"..2..64.5///...1...7.\",\n \".57.1.2..///..5....3.\",\n \".....731.///.1.3..2..\",\n \"...3...9.///.7..429.5\",\n \"4..5..1...5....5.....\",\n \"8.1...7...8.2..768...\",\n \".......8.23...4...6..\",\n \"//////.12.4..9.//////\",\n \"//////......82.//////\",\n \"//////.6.....1.//////\",\n \".4...1....76...36..9.\",\n \"2.....9..8..5.34...81\",\n \".5.873......9.8..23..\",\n \"...2....9///.25.4....\",\n \"..3.64...///31.8.....\",\n \"..75.8.12///...6.14..\",\n \".......2.///.31...9..\",\n \"..17.....///..7......\",\n \".7.6...84///8...7..5.\"\n });\n\n string[] tileDefinitions = new[]\n {\n \"674825931000142673859\",\n \"513794862000897425361\",\n \"982136475000563189472\",\n \"357619248000425916738\",\n \"298457316000918357246\",\n \"146382597000376842915\",\n \"469578123457689534127\",\n \"821963754689231768594\",\n \"735241689231754291683\",\n \"000000512748396000000\",\n \"000000497163825000000\",\n \"000000368592417000000\",\n \"746921835976142368597\",\n \"238456971824563497281\",\n \"159873246315978152346\",\n \"815237469000625749813\",\n \"923164758000314825769\",\n \"467598312000789631425\",\n \"694385127000431586972\",\n \"581742693000257914638\",\n \"372619584000896273154\"\n };\n\n // Act\n IEnumerable<SudokuBoard> solutions = board.Solve();\n\n // Assert\n Assert.Single(solutions);\n Assert.Equal(tileDefinitions, solutions.First().TileDefinitions);\n }\n}\n</code></pre>\n\n<h2>Refactoring</h2>\n\n<p>I've applied already mentioned refactoring ideas from other answers so I won't mention them separately.</p>\n\n<p>Also I'm using expression-bodied members, string interpolations and local functions from newer versions of C# which weren't available when you wrote your post.</p>\n\n<h3>SudokuTile</h3>\n\n<p>Properties can be grouped by <code>readonly</code>/<code>const</code> and mutable:</p>\n\n<pre><code>internal const int CLEARED = 0;\nprivate readonly int _maxValue;\nprivate readonly int _x;\nprivate readonly int _y;\n\nprivate IEnumerable<int> _possibleValues = Enumerable.Empty<int>();\nprivate int _value = 0;\nprivate bool _blocked = false;\n</code></pre>\n\n<p><code>_possibleValues</code> should begin with underscore to be consistent with your naming convention. Type of <code>_possibleValues</code> can be safely replaced from <code>ISet<int></code> to more primitive <code>IEnumerable<int></code>. <code>ResetPossibles</code> method should be simplified:</p>\n\n<pre><code>internal void ResetPossibles()\n{\n if (HasValue)\n _possibleValues = Enumerable.Repeat(Value, 1);\n else\n _possibleValues = Enumerable.Range(1, _maxValue);\n}\n</code></pre>\n\n<hr>\n\n<p>Line </p>\n\n<pre><code>possibleValues = new HashSet<int>(possibleValues.Where(x => !existingNumbers.Contains(x)));\n</code></pre>\n\n<p>in <code>RemovePossibles</code> method can be easily replaced using <code>Except</code> LINQ method</p>\n\n<pre><code>_possibleValues = _possibleValues.Except(existingNumbers);\n</code></pre>\n\n<p>Also you can replace double <code>if</code> with <code>switch</code> statement in <code>RemovePossibles</code> method. Result:</p>\n\n<pre><code>internal SudokuProgress RemovePossibles(IEnumerable<int> existingNumbers)\n{\n if (_blocked)\n return SudokuProgress.NO_PROGRESS;\n\n // Takes the current possible values and removes the ones existing in `existingNumbers`\n _possibleValues = _possibleValues.Except(existingNumbers);\n\n switch (_possibleValues.Count())\n {\n case 0:\n return SudokuProgress.FAILED;\n case 1:\n Fix(_possibleValues.First(), \"Only one possibility\");\n return SudokuProgress.PROGRESS;\n default:\n return SudokuProgress.NO_PROGRESS;\n }\n}\n</code></pre>\n\n<h3>SudokuRule</h3>\n\n<p>Here we should change <code>_tiles</code> field type from <code>ISet<SudokuTile></code> to <code>IEnumerable<SudokuTile></code> because you won't use any collection modification methods like <code>Add</code>, <code>Remove</code> or <code>Clear</code>. Collection is used only for reading. But you can preserve the line</p>\n\n<pre><code>_tiles = new HashSet<SudokuTile>(tiles);\n</code></pre>\n\n<p>in constructor because LINQ methods have deferred execution and here collection should be calculated immediately. But I've replaced this with</p>\n\n<pre><code>_tiles = tiles.ToArray();\n</code></pre>\n\n<p>just because this is shorter.</p>\n\n<p>Also your fields should be <code>readonly</code></p>\n\n<pre><code>private readonly IEnumerable<SudokuTile> _tiles;\nprivate readonly string _description;\n</code></pre>\n\n<hr>\n\n<p>Line in <code>RemovePossibles</code> method</p>\n\n<pre><code>IEnumerable<int> existingNumbers = new HashSet<int>(withNumber.Select(tile => tile.Value).Distinct().ToList());\n</code></pre>\n\n<p>has a lot of redundancies:</p>\n\n<ul>\n<li><code>HashSet<int></code> constructor call doesn't make sense here, because you've get materialized collection using <code>ToList</code> method call</li>\n<li>but even <code>ToList</code> method call is redundant here because this number collection are passed to <code>SudokuTile.RemovePossibles</code> which immediately modifies <code>_possibleValues</code> collection.</li>\n<li><p><code>Distinct</code> call is also redundant here because you've checked all your rules before using <code>SudokuBoard.Simplify</code> method using line</p>\n\n<pre><code>bool valid = _rules.All(rule => rule.CheckValid());\n</code></pre>\n\n<p>so all your tile values are already distinct here.</p></li>\n</ul>\n\n<p>So this line can be shorten to</p>\n\n<pre><code>IEnumerable<int> existingNumbers = withNumber.Select(tile => tile.Value);\n</code></pre>\n\n<hr>\n\n<p>Also line in <code>CheckForOnlyOnePossibility</code> method</p>\n\n<pre><code>IList<int> existingNumbers = _tiles.Select(tile => tile.Value).Distinct().ToList();\n</code></pre>\n\n<p>has issues</p>\n\n<ul>\n<li><p>You're using <code>existingNumbers</code> as collection only for reading using <code>Contains</code> method, so <code>IList<int></code> can be safely replaced with <code>IEnumerable<int></code>.</p></li>\n<li><p><code>ToList</code> call is redundant here because <code>Contains</code> method is not using deferred execution.</p></li>\n<li><p><code>Distinct</code> call is also redundant here because you've checked all your rules before using <code>SudokuBoard.Simplify</code> method using line</p>\n\n<pre><code>bool valid = _rules.All(rule => rule.CheckValid());\n</code></pre>\n\n<p>so all your tile values are already distinct here.</p></li>\n</ul>\n\n<p>So this line can be shorten to</p>\n\n<pre><code>IEnumerable<int> existingNumbers = _tiles.Select(tile => tile.Value);\n</code></pre>\n\n<h3>SudokuBoard</h3>\n\n<p>I think it'll better to move all field definitions to top of the class with <code>readonly</code> modifier. Also I've add underscore to field names to enforce your naming convention consistency.</p>\n\n<pre><code>private readonly List<SudokuRule> _rules = new List<SudokuRule>();\nprivate readonly SudokuTile[,] _tiles;\nprivate readonly int _maxValue;\n</code></pre>\n\n<p>Also I've change <code>_rules</code> type to <code>List<SudokuRule></code> because it's more friendly with LINQ (because LINQ has <code>ToList</code> method but not <code>ToSet</code>).</p>\n\n<hr>\n\n<p>Double loop in <code>SudokuBoard</code> copy constructor can be simplified with single LINQ statement (by the way I've changed <code>SudokuFactory.Box</code> return type from faceless <code>Tuple</code> to more meaningful <code>Point</code>):</p>\n\n<pre><code>internal SudokuBoard(SudokuBoard copy)\n{\n _maxValue = copy._maxValue;\n _tiles = new SudokuTile[copy.Width, copy.Height];\n CreateTiles();\n // Copy the tile values\n foreach (Point pos in SudokuFactory.Box(Width, Height))\n {\n _tiles[pos.X, pos.Y] = new SudokuTile(pos.X, pos.Y, _maxValue)\n {\n Value = copy[pos.X, pos.Y].Value\n };\n }\n\n // Copy the rules\n _rules = copy._rules\n .Select(rule => new SudokuRule(rule.Select(tile => _tiles[tile.X, tile.Y]), rule.Description))\n .ToList();\n}\n</code></pre>\n\n<hr>\n\n<p>This big piece of code</p>\n\n<pre><code>private void SetupLineRules()\n{\n // Create rules for rows and columns\n for (int x = 0; x < Width; x++)\n {\n IEnumerable<SudokuTile> row = GetCol(x);\n rules.Add(new SudokuRule(row, \"Row \" + x.ToString()));\n }\n for (int y = 0; y < Height; y++)\n {\n IEnumerable<SudokuTile> col = GetRow(y);\n rules.Add(new SudokuRule(col, \"Col \" + y.ToString()));\n }\n}\n\nprivate IEnumerable<SudokuTile> GetRow(int row)\n{\n for (int i = 0; i < tiles.GetLength(0); i++)\n {\n yield return tiles[i, row];\n }\n}\nprivate IEnumerable<SudokuTile> GetCol(int col)\n{\n for (int i = 0; i < tiles.GetLength(1); i++)\n {\n yield return tiles[col, i];\n }\n}\n</code></pre>\n\n<p>can be replaced with couple of lines:</p>\n\n<pre><code>private void SetupLineRules()\n{\n // Create rules for rows and columns\n for (int x = 0; x < Width; x++)\n _rules.Add(new SudokuRule(Enumerable.Range(0, _tiles.GetLength(1)).Select(i => _tiles[x, i]), $\"Row {x}\"));\n\n for (int y = 0; y < Height; y++)\n _rules.Add(new SudokuRule(Enumerable.Range(0, _tiles.GetLength(0)).Select(i => _tiles[i, y]), $\"Col {y}\"));\n}\n</code></pre>\n\n<hr>\n\n<p><code>Tile</code> method can be replaced with indexer to access tiles of board via array syntax:</p>\n\n<pre><code>public SudokuTile this[int x, int y] => _tiles[x, y];\n</code></pre>\n\n<hr>\n\n<p><code>Simplify</code> method can be simplified using <code>Aggregate</code> LINQ method and variable inlining:</p>\n\n<pre><code>private SudokuProgress Simplify()\n{\n bool valid = _rules.All(rule => rule.CheckValid());\n if (!valid)\n return SudokuProgress.FAILED;\n\n return _rules.Aggregate(SudokuProgress.NO_PROGRESS,\n (progress, rule) => SudokuTile.CombineSolvedState(progress, rule.Solve()));\n}\n</code></pre>\n\n<hr>\n\n<p>All short and simple one-time used stuff like <code>CheckValid</code>, <code>TileBox</code>, <code>ResetSolutions</code>, <code>Simplify</code>, <code>SetupLineRules</code> should be inlined or used as local function. Result file will be listed below.</p>\n\n<h3>SudokuFactory</h3>\n\n<p>Refactored <code>Box</code> method using advices from several other answers:</p>\n\n<pre><code>internal static IEnumerable<Point> Box(int sizeX, int sizeY)\n{\n return\n from x in Enumerable.Range(0, sizeX)\n from y in Enumerable.Range(0, sizeY)\n select new Point(x, y);\n}\n</code></pre>\n\n<hr>\n\n<p>Replaced this code from <code>Samurai</code> method</p>\n\n<pre><code>SudokuBoard board = new SudokuBoard(SamuraiAreas*BoxSize, SamuraiAreas*BoxSize, DefaultSize);\n// Removed the empty areas where there are no tiles\nvar queriesForBlocked = new List<IEnumerable<SudokuTile>>();\nqueriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 ));\nqueriesForBlocked.Add(from pos in box(BoxSize, BoxSize*2) select board.Tile(pos.Item1 + DefaultSize, pos.Item2 + DefaultSize * 2 - BoxSize));\nqueriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 , pos.Item2 + DefaultSize));\nqueriesForBlocked.Add(from pos in box(BoxSize*2, BoxSize) select board.Tile(pos.Item1 + DefaultSize * 2 - BoxSize, pos.Item2 + DefaultSize));\nforeach (var query in queriesForBlocked) \n{\n foreach (var tile in query) tile.Block();\n}\n</code></pre>\n\n<p>with collection initializer and <code>SelectMany</code> LINQ method:</p>\n\n<pre><code>SudokuBoard board = new SudokuBoard(SamuraiAreas * BoxSize, SamuraiAreas * BoxSize, DefaultSize, tileDefinitions);\n// Removed the empty areas where there are no tiles\nIEnumerable<SudokuTile> tiles = new[]\n{\n Box(BoxSize, BoxSize * 2).Select(pos => board[pos.X + DefaultSize, pos.Y]),\n Box(BoxSize, BoxSize * 2).Select(pos => board[pos.X + DefaultSize, pos.Y + DefaultSize * 2 - BoxSize]),\n Box(BoxSize * 2, BoxSize).Select(pos => board[pos.X, pos.Y + DefaultSize]),\n Box(BoxSize * 2, BoxSize).Select(pos => board[pos.X + DefaultSize * 2 - BoxSize, pos.Y + DefaultSize])\n}.SelectMany(t => t);\n\nforeach (SudokuTile tile in tiles) tile.Block();\n</code></pre>\n\n<hr>\n\n<p>Also there are multiple places in this file where LINQ method syntax is shorter and much readable then query syntax.</p>\n\n<h2>Result files</h2>\n\n<h3>SudokuProgress</h3>\n\n<pre><code>internal enum SudokuProgress { FAILED, NO_PROGRESS, PROGRESS }\n</code></pre>\n\n<h3>SudokuTile</h3>\n\n<pre><code>public class SudokuTile\n{\n internal const int CLEARED = 0;\n private readonly int _maxValue;\n private readonly int _x;\n private readonly int _y;\n\n private IEnumerable<int> _possibleValues = Enumerable.Empty<int>();\n private int _value = 0;\n private bool _blocked = false;\n\n internal static SudokuProgress CombineSolvedState(SudokuProgress a, SudokuProgress b)\n {\n switch (a)\n {\n case SudokuProgress.FAILED:\n return a;\n\n case SudokuProgress.NO_PROGRESS:\n return b;\n\n case SudokuProgress.PROGRESS:\n return b == SudokuProgress.FAILED ? b : a;\n }\n throw new InvalidOperationException($\"Invalid value for {nameof(a)}\");\n }\n\n public SudokuTile(int x, int y, int maxValue)\n {\n _x = x;\n _y = y;\n _maxValue = maxValue;\n }\n\n public int Value\n {\n get => _value;\n internal set\n {\n if (value > _maxValue)\n throw new ArgumentOutOfRangeException($\"SudokuTile Value cannot be greater than {_maxValue}. Was {value}\");\n if (value < CLEARED)\n throw new ArgumentOutOfRangeException($\"SudokuTile Value cannot be smaller than zero. Was {value}\");\n _value = value;\n }\n }\n\n public bool HasValue => Value != CLEARED;\n\n public string ToStringSimple() => Value.ToString();\n\n public override string ToString() => $\"Value {Value} at pos {_x}, {_y}. \";\n\n internal void ResetPossibles()\n {\n if (HasValue)\n _possibleValues = Enumerable.Repeat(Value, 1);\n else\n _possibleValues = Enumerable.Range(1, _maxValue);\n }\n\n internal void Block() => _blocked = true;\n\n internal void Fix(int value, string reason)\n {\n Value = value;\n ResetPossibles();\n }\n\n internal SudokuProgress RemovePossibles(IEnumerable<int> existingNumbers)\n {\n if (_blocked)\n return SudokuProgress.NO_PROGRESS;\n\n // Takes the current possible values and removes the ones existing in `existingNumbers`\n _possibleValues = _possibleValues.Except(existingNumbers);\n\n switch (_possibleValues.Count())\n {\n case 0:\n return SudokuProgress.FAILED;\n case 1:\n Fix(_possibleValues.First(), \"Only one possibility\");\n return SudokuProgress.PROGRESS;\n default:\n return SudokuProgress.NO_PROGRESS;\n }\n }\n\n internal bool IsValuePossible(int i) => _possibleValues.Contains(i);\n\n public int X => _x;\n public int Y => _y;\n public bool IsBlocked => _blocked; // A blocked field can not contain a value — used for creating 'holes' in the map\n\n internal int PossibleCount => IsBlocked ? 1 : _possibleValues.Count();\n}\n</code></pre>\n\n<h3>SudokuRule</h3>\n\n<pre><code>public class SudokuRule : IEnumerable<SudokuTile>\n{\n private readonly IEnumerable<SudokuTile> _tiles;\n private readonly string _description;\n\n internal SudokuRule(IEnumerable<SudokuTile> tiles, string description)\n {\n _tiles = tiles.ToArray();\n _description = description;\n }\n\n internal bool CheckValid()\n {\n IEnumerable<SudokuTile> filtered = _tiles.Where(tile => tile.HasValue);\n IEnumerable<IGrouping<int, SudokuTile>> groupedByValue = filtered.GroupBy(tile => tile.Value);\n return groupedByValue.All(group => group.Count() == 1);\n }\n\n internal SudokuProgress RemovePossibles()\n {\n // Tiles that has a number already\n IEnumerable<SudokuTile> withNumber = _tiles.Where(tile => tile.HasValue);\n\n // Tiles without a number\n IEnumerable<SudokuTile> withoutNumber = _tiles.Where(tile => !tile.HasValue);\n\n // The existing numbers in this rule\n IEnumerable<int> existingNumbers = withNumber.Select(tile => tile.Value);\n\n return withoutNumber.Aggregate(\n SudokuProgress.NO_PROGRESS,\n (result, tile) => SudokuTile.CombineSolvedState(result, tile.RemovePossibles(existingNumbers)));\n }\n\n internal SudokuProgress CheckForOnlyOnePossibility()\n {\n // Check if there is only one number within this rule that can have a specific value\n IEnumerable<int> existingNumbers = _tiles.Select(tile => tile.Value);\n SudokuProgress result = SudokuProgress.NO_PROGRESS;\n\n foreach (int value in Enumerable.Range(1, _tiles.Count()))\n {\n if (existingNumbers.Contains(value)) // this rule already has the value, skip checking for it\n continue;\n List<SudokuTile> possibles = _tiles.Where(tile => !tile.HasValue && tile.IsValuePossible(value)).ToList();\n if (possibles.Count == 0)\n return SudokuProgress.FAILED;\n if (possibles.Count == 1)\n {\n possibles.First().Fix(value, $\"Only possible in rule {ToString()}\");\n result = SudokuProgress.PROGRESS;\n }\n }\n return result;\n }\n\n internal SudokuProgress Solve()\n {\n // If both are null, return null (indicating no change). If one is null, return the other. Else return result1 && result2\n SudokuProgress result1 = RemovePossibles();\n SudokuProgress result2 = CheckForOnlyOnePossibility();\n return SudokuTile.CombineSolvedState(result1, result2);\n }\n\n public override string ToString() => _description;\n\n public IEnumerator<SudokuTile> GetEnumerator() => _tiles.GetEnumerator();\n\n IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();\n\n public string Description => _description;\n}\n</code></pre>\n\n<h3>SudokuBoard</h3>\n\n<pre><code>public class SudokuBoard\n{\n private readonly List<SudokuRule> _rules = new List<SudokuRule>();\n private readonly SudokuTile[,] _tiles;\n private readonly int _maxValue;\n\n internal SudokuBoard(SudokuBoard copy)\n {\n _maxValue = copy._maxValue;\n _tiles = new SudokuTile[copy.Width, copy.Height];\n CreateTiles();\n // Copy the tile values\n foreach (Point pos in SudokuFactory.Box(Width, Height))\n {\n _tiles[pos.X, pos.Y] = new SudokuTile(pos.X, pos.Y, _maxValue)\n {\n Value = copy[pos.X, pos.Y].Value\n };\n }\n\n // Copy the rules\n _rules = copy._rules\n .Select(rule => new SudokuRule(rule.Select(tile => _tiles[tile.X, tile.Y]), rule.Description))\n .ToList();\n }\n\n internal SudokuBoard(int width, int height, int maxValue, string[] tileDefinitions)\n {\n _maxValue = maxValue;\n _tiles = new SudokuTile[width, height];\n CreateTiles();\n if (_maxValue == width || _maxValue == height) // If maxValue is not width or height, then adding line rules would be stupid\n {\n // Create rules for rows and columns\n for (int x = 0; x < Width; x++)\n _rules.Add(new SudokuRule(Enumerable.Range(0, _tiles.GetLength(1)).Select(i => _tiles[x, i]), $\"Row {x}\"));\n\n for (int y = 0; y < Height; y++)\n _rules.Add(new SudokuRule(Enumerable.Range(0, _tiles.GetLength(0)).Select(i => _tiles[i, y]), $\"Col {y}\"));\n }\n\n PopulateTiles(tileDefinitions);\n }\n\n internal SudokuBoard(int width, int height, string[] tileDefinitions) : this(width, height, Math.Max(width, height), tileDefinitions)\n {\n }\n\n private void PopulateTiles(string[] tileDefinitions)\n {\n for (int row = 0; row < tileDefinitions.Length; row++)\n {\n string tileDefinition = tileDefinitions[row];\n\n for (int column = 0; column < tileDefinition.Length; column++)\n {\n SudokuTile tile = _tiles[column, row];\n if (tileDefinition[column] == '/')\n {\n tile.Block();\n continue;\n }\n tile.Value = tileDefinition[column] == '.' ? SudokuTile.CLEARED : (int)char.GetNumericValue(tileDefinition[column]);\n }\n }\n }\n\n private void CreateTiles()\n {\n foreach (Point pos in SudokuFactory.Box(_tiles.GetLength(0), _tiles.GetLength(1)))\n {\n _tiles[pos.X, pos.Y] = new SudokuTile(pos.X, pos.Y, _maxValue);\n }\n }\n\n public SudokuTile this[int x, int y] => _tiles[x, y];\n\n public int Width => _tiles.GetLength(0);\n\n public int Height => _tiles.GetLength(1);\n\n internal void CreateRule(string description, IEnumerable<SudokuTile> tiles) => _rules.Add(new SudokuRule(tiles, description));\n\n public string[] TileDefinitions => _tiles\n .Cast<SudokuTile>()\n .OrderBy(t => t.X)\n .ThenBy(t => t.Y)\n .GroupBy(t => t.Y)\n .Select(g => string.Join(string.Empty, g.Select(t => t.Value)))\n .ToArray();\n\n public IEnumerable<SudokuBoard> Solve()\n {\n SudokuProgress Simplify()\n {\n bool valid = _rules.All(rule => rule.CheckValid());\n if (!valid)\n return SudokuProgress.FAILED;\n\n return _rules.Aggregate(SudokuProgress.NO_PROGRESS,\n (progress, rule) => SudokuTile.CombineSolvedState(progress, rule.Solve()));\n }\n\n // reset solution\n foreach (SudokuTile tile in _tiles)\n tile.ResetPossibles();\n\n SudokuProgress simplify = SudokuProgress.PROGRESS;\n while (simplify == SudokuProgress.PROGRESS) simplify = Simplify();\n\n if (simplify == SudokuProgress.FAILED)\n yield break;\n\n // Find one of the values with the least number of alternatives, but that still has at least 2 alternatives\n IEnumerable<SudokuTile> query = from rule in _rules\n from tile in rule\n where tile.PossibleCount > 1\n orderby tile.PossibleCount ascending\n select tile;\n\n SudokuTile chosen = query.FirstOrDefault();\n if (chosen == null)\n {\n // The board has been completed, we're done!\n yield return this;\n yield break;\n }\n\n foreach (int value in Enumerable.Range(1, _maxValue))\n {\n // Iterate through all the valid possibles on the chosen square and pick a number for it\n if (!chosen.IsValuePossible(value))\n continue;\n SudokuBoard copy = new SudokuBoard(this);\n copy[chosen.X, chosen.Y].Fix(value, \"Trial and error\");\n foreach (SudokuBoard innerSolution in copy.Solve())\n yield return innerSolution;\n }\n yield break;\n }\n\n internal void AddBoxesCount(int boxesX, int boxesY)\n {\n int sizeX = Width / boxesX;\n int sizeY = Height / boxesY;\n\n IEnumerable<SudokuTile> TileBox(int startX, int startY) =>\n SudokuFactory.Box(sizeX, sizeY).Select(pos => _tiles[startX + pos.X, startY + pos.Y]);\n\n IEnumerable<Point> boxes = SudokuFactory.Box(sizeX, sizeY);\n foreach (Point pos in boxes)\n CreateRule($\"Box at ({pos.X}, {pos.Y})\", TileBox(pos.X * sizeX, pos.Y * sizeY));\n }\n}\n</code></pre>\n\n<h3>SudokuFactory</h3>\n\n<pre><code>public class SudokuFactory\n{\n private const int DefaultSize = 9;\n private const int SamuraiAreas = 7;\n private const int BoxSize = 3;\n private const int HyperMargin = 1;\n\n internal static IEnumerable<Point> Box(int sizeX, int sizeY)\n {\n return\n from x in Enumerable.Range(0, sizeX)\n from y in Enumerable.Range(0, sizeY)\n select new Point(x, y);\n }\n\n public static SudokuBoard Samurai(string[] tileDefinitions)\n {\n SudokuBoard board = new SudokuBoard(SamuraiAreas * BoxSize, SamuraiAreas * BoxSize, DefaultSize, tileDefinitions);\n // Removed the empty areas where there are no tiles\n IEnumerable<SudokuTile> tiles = new[]\n {\n Box(BoxSize, BoxSize * 2).Select(pos => board[pos.X + DefaultSize, pos.Y]),\n Box(BoxSize, BoxSize * 2).Select(pos => board[pos.X + DefaultSize, pos.Y + DefaultSize * 2 - BoxSize]),\n Box(BoxSize * 2, BoxSize).Select(pos => board[pos.X, pos.Y + DefaultSize]),\n Box(BoxSize * 2, BoxSize).Select(pos => board[pos.X + DefaultSize * 2 - BoxSize, pos.Y + DefaultSize])\n }.SelectMany(t => t);\n\n foreach (SudokuTile tile in tiles) tile.Block();\n\n // Select the tiles in the 3 x 3 area (area.X, area.Y) and create rules for them\n foreach (Point area in Box(SamuraiAreas, SamuraiAreas))\n {\n IEnumerable<SudokuTile> tilesInArea = Box(BoxSize, BoxSize)\n .Select(pos => board[area.X * BoxSize + pos.X, area.Y * BoxSize + pos.Y]);\n if (tilesInArea.First().IsBlocked)\n continue;\n board.CreateRule($\"Area {area.X}, {area.Y}\", tilesInArea);\n }\n\n // Select all rows and create columns for them\n foreach (int posSet in Enumerable.Range(0, board.Width))\n {\n board.CreateRule($\"Column Upper {posSet}\", Box(1, DefaultSize).Select(pos => board[posSet, pos.Y]));\n board.CreateRule($\"Column Lower {posSet}\", Box(1, DefaultSize).Select(pos => board[posSet, pos.Y + DefaultSize + BoxSize]));\n\n board.CreateRule($\"Row Left {posSet}\", Box(DefaultSize, 1).Select(pos => board[pos.X, posSet]));\n board.CreateRule($\"Row Right {posSet}\", Box(DefaultSize, 1).Select(pos => board[pos.X + DefaultSize + BoxSize, posSet]));\n\n if (posSet >= BoxSize * 2 && posSet < BoxSize * 2 + DefaultSize)\n {\n // Create rules for the middle sudoku\n board.CreateRule($\"Column Middle {posSet}\", Box(1, 9).Select(pos => board[posSet, pos.Y + BoxSize * 2]));\n board.CreateRule($\"Row Middle {posSet}\", Box(9, 1).Select(pos => board[pos.X + BoxSize * 2, posSet]));\n }\n }\n return board;\n }\n\n public static SudokuBoard SizeAndBoxes(int width, int height, int boxCountX, int boxCountY, string[] tileDefinitions)\n {\n SudokuBoard board = new SudokuBoard(width, height, tileDefinitions);\n board.AddBoxesCount(boxCountX, boxCountY);\n return board;\n }\n\n public static SudokuBoard ClassicWith3x3Boxes(string[] tileDefinitions) => SizeAndBoxes(DefaultSize, DefaultSize, DefaultSize / BoxSize, DefaultSize / BoxSize, tileDefinitions);\n\n public static SudokuBoard ClassicWith3x3BoxesAndHyperRegions(string[] tileDefinitions)\n {\n SudokuBoard board = ClassicWith3x3Boxes(tileDefinitions);\n const int HyperSecond = HyperMargin + BoxSize + HyperMargin;\n // Create the four extra hyper regions\n board.CreateRule(\"HyperA\", Box(3, 3).Select(pos => board[pos.X + HyperMargin, pos.Y + HyperMargin]));\n board.CreateRule(\"HyperB\", Box(3, 3).Select(pos => board[pos.X + HyperSecond, pos.Y + HyperMargin]));\n board.CreateRule(\"HyperC\", Box(3, 3).Select(pos => board[pos.X + HyperMargin, pos.Y + HyperSecond]));\n board.CreateRule(\"HyperD\", Box(3, 3).Select(pos => board[pos.X + HyperSecond, pos.Y + HyperSecond]));\n return board;\n }\n\n public static SudokuBoard ClassicWithSpecialBoxes(string[] areas, string[] tileDefinitions)\n {\n int sizeX = areas[0].Length;\n int sizeY = areas.Length;\n SudokuBoard board = new SudokuBoard(sizeX, sizeY, tileDefinitions);\n string joinedString = string.Join(string.Empty, areas);\n\n // Loop through all the unique characters\n foreach (char ch in joinedString.Distinct())\n {\n // Select the rule tiles based on the index of the character\n IEnumerable<SudokuTile> ruleTiles = from i in Enumerable.Range(0, joinedString.Length)\n where joinedString[i] == ch // filter out any non-matching characters\n select board[i % sizeX, i / sizeY];\n board.CreateRule($\"Area {ch}\", ruleTiles);\n }\n\n return board;\n }\n}\n</code></pre>\n\n<h2>Source code</h2>\n\n<p>All source code is available on <a href=\"https://github.com/VadimOvchinnikov/SudokuSolver\" rel=\"noreferrer\">Github</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-03-23T20:54:15.027",
"Id": "190333",
"ParentId": "37448",
"Score": "20"
}
}
] |
{
"AcceptedAnswerId": "190333",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T22:22:52.040",
"Id": "37448",
"Score": "81",
"Tags": [
"c#",
"linq",
"community-challenge",
"sudoku"
],
"Title": "SudokuSharp Solver with advanced features"
}
|
37448
|
<p>I'm trying to figure out a way to have cleaner, efficient code for a web audio project i've been working on. the code I have right now is this:</p>
<pre><code>//OSCILLATOR INFO//
// Oscillator Pitch is in Hz.
// Oscillator Detune is in Cents & can be positive or negative values.
// 1 Octave = double/half the note frequency in Hz. (A3 = 220Hz; A4 = 440Hz; A5 = 880Hz)
// 1 Octave = 1200 Cents. 100 Cents per Semitone. (A3 - A4 = 1200 Cents; A4 - A5 = 1200 Cents)
// 12 Semitones per Octave.
// (A-440Hz detuned by 100 cents = A#; detuned by -100 cents = Ab)
//JQUERY SET UP//
//WEB AUDIO SET UP//
//used start web audio
var ctx = new webkitAudioContext();
speakers = ctx.destination;
var osc1 = ctx.createOscillator();
var osc2 = ctx.createOscillator();
var osc3 = ctx.createOscillator();
$(document).ready(function () {
//WAVEFORM OBJECTS - used to set the value of "cur_wave_osc" under Waveform sliders.//
var wF = {
0: "Sine",
1: "Square",
2: "Sawtooth",
3: "Triangle"
};
//PLAY_PAUSE BUTTONS - used to play & pause the oscillators.//
//OSC1 PLAY_PAUSE//
$('#play_pause_osc1').click(function () {
if ($(this).val() == "Play Osc1") {
$(this).val("Pause");
oscillator1Start();
} else {
$(this).val("Play Osc1");
osc1.disconnect();
}
});
//OSC2 PLAY_PAUSE//
$('#play_pause_osc2').click(function () {
if ($(this).val() == "Play Osc2") {
$(this).val("Pause");
oscillator2Start();
} else {
$(this).val("Play Osc2");
osc2.disconnect();
}
});
//OSC3 PLAY_PAUSE//
$('#play_pause_osc3').click(function () {
if ($(this).val() == "Play Osc3") {
$(this).val("Pause");
oscillator3Start();
} else {
$(this).val("Play Osc3");
osc3.disconnect();
}
});
//GAIN SLIDERS - used for controlling osc volume.//
//OSC1_GAIN//
$(function () {
$("#osc1_vol").slider({
min: 0,
max: 1,
value: 0.5,
step: 0.01,
slide: function (event, ui) {
$("#cur_vol_osc1").val(ui.value);
gainNode1.gain.value = $("#cur_vol_osc1").val();
}
});
$("#cur_vol_osc1").val($("#osc1_vol").slider("value"));
});
//OSC2_GAIN//
$(function () {
$("#osc2_vol").slider({
min: 0,
max: 1,
value: 0.5,
step: 0.01,
slide: function (event, ui) {
$("#cur_vol_osc2").val(ui.value);
gainNode2.gain.value = $("#cur_vol_osc2").val();
}
});
$("#cur_vol_osc2").val($("#osc2_vol").slider("value"));
});
//OSC3_GAIN//
$(function () {
$("#osc3_vol").slider({
min: 0,
max: 1,
value: 0.5,
step: 0.01,
slide: function (event, ui) {
$("#cur_vol_osc3").val(ui.value);
gainNode3.gain.value = $("#cur_vol_osc3").val();
}
});
$("#cur_vol_osc3").val($("#osc3_vol").slider("value"));
});
//PITCH SLIDERS - used for controlling osc pitch.//
//OSC1_PITCH//
$(function () {
$("#osc1_pitch").slider({
min: 0,
max: 25000,
value: 440,
step: 1,
slide: function (event, ui) {
$("#cur_pitch_osc1").val(ui.value);
osc1.frequency.value = $("#cur_pitch_osc1").val();
}
});
$("#cur_pitch_osc1").val($("#osc1_pitch").slider("value"));
});
//OSC2_PITCH//
$(function () {
$("#osc2_pitch").slider({
min: 0,
max: 25000,
value: 440,
step: 1,
slide: function (event, ui) {
$("#cur_pitch_osc2").val(ui.value);
osc2.frequency.value = $("#cur_pitch_osc2").val();
}
});
$("#cur_pitch_osc2").val($("#osc2_pitch").slider("value"));
});
//OSC3_PITCH//
$(function () {
$("#osc3_pitch").slider({
min: 0,
max: 25000,
value: 440,
step: 1,
slide: function (event, ui) {
$("#cur_pitch_osc3").val(ui.value);
osc3.frequency.value = $("#cur_pitch_osc3").val();
}
});
$("#cur_pitch_osc3").val($("#osc3_pitch").slider("value"));
});
//DETUNE SLIDER - used for controlling osc detune.//
//OSC1_DETUNE//
$(function () {
$("#osc1_detune").slider({
min: -4800,
max: 4800,
value: 0,
step: 1,
slide: function (event, ui) {
$("#cur_detune_osc1").val(ui.value);
osc1.detune.value = $("#cur_detune_osc1").val();
}
});
$("#cur_detune_osc1").val($("#osc1_detune").slider("value"));
});
//OSC2_DETUNE//
$(function () {
$("#osc2_detune").slider({
min: -4800,
max: 4800,
value: 0,
step: 1,
slide: function (event, ui) {
$("#cur_detune_osc2").val(ui.value);
osc2.detune.value = $("#cur_detune_osc2").val();
}
});
$("#cur_detune_osc2").val($("#osc2_detune").slider("value"));
});
//OSC3_DETUNE//
$(function () {
$("#osc3_detune").slider({
min: -4800,
max: 4800,
value: 0,
step: 1,
slide: function (event, ui) {
$("#cur_detune_osc3").val(ui.value);
osc3.detune.value = $("#cur_detune_osc3").val();
}
});
$("#cur_detune_osc3").val($("#osc3_detune").slider("value"));
});
//WAVEFORM SLIDERS - used for selecting osc waveform.//
//OSC1_WAVEFORM//
$(function () {
$("#osc1_wave").slider({
min: 0,
max: 3,
value: 0,
step: 1,
slide: function (event, ui) {
$("#cur_wave_osc1").val(wF[ui.value]);
}
});
$("#cur_wave_osc1").val("Sine");
osc1.type = $("#osc1_wave").slider("value");
});
//OSC2_WAVEFORM//
$(function () {
$("#osc2_wave").slider({
min: 0,
max: 3,
value: 0,
step: 1,
slide: function (event, ui) {
$("#cur_wave_osc2").val(wF[ui.value]);
}
});
$("#cur_wave_osc2").val("Sine");
osc2.type = $("#osc2_wave").slider("value");
});
//OSC3_WAVEFORM//
$(function () {
$("#osc3_wave").slider({
min: 0,
max: 3,
value: 0,
step: 1,
slide: function (event, ui) {
$("#cur_wave_osc3").val(wF[ui.value]);
}
});
$("#cur_wave_osc3").val("Sine");
osc3.type = $("#osc3_wave").slider("value");
});
});
//CREATE OSCILLATORS//
//OSC1//
function oscillator1Start() {
//creates the osc
osc1 = ctx.createOscillator();
//sets waveform
osc1.type = $("#osc1_wave").slider("value"); //0 = sine, 1 = square, 2 = saw, 3 = triangle, 4 = custom
//sets frequency
osc1.frequency.value;
//sets detune
osc1.detune.value;
//creates a gain node
gainNode1 = ctx.createGainNode();
//connects osc to gain node
osc1.connect(gainNode1);
//connects gain node to speakers
gainNode1.connect(speakers);
//sets gain value
gainNode1.gain.value;
//plays the osc
osc1.start(0);
}
//OSC2//
function oscillator2Start() {
//creates the osc
osc2 = ctx.createOscillator();
//sets waveform
osc2.type; //0 = sine, 1 = square, 2 = saw, 3 = triangle, 4 = custom
//sets frequency
osc2.frequency.value;
//sets detune
osc2.detune.value;
//creates a gain node
gainNode2 = ctx.createGainNode();
//connects osc to gain node
osc2.connect(gainNode2);
//connects gain node to speakers
gainNode2.connect(speakers);
//sets gain value
gainNode2.gain.value;
//plays the osc
osc2.start(0);
}
//OSC3//
function oscillator3Start() {
//creates the osc
osc3 = ctx.createOscillator();
//sets waveform
osc3.type; //0 = sine, 1 = square, 2 = saw, 3 = triangle, 4 = custom
//sets frequency
osc3.frequency.value;
//sets detune
osc3.detune.value;
//creates a gain node
gainNode3 = ctx.createGainNode();
//connects osc to gain node
osc3.connect(gainNode3);
//connects gain node to speakers
gainNode3.connect(speakers);
//sets gain value
gainNode3.gain.value;
//plays the osc
osc3.start(0);
}
</code></pre>
<p>it seems like I have a lot of repetitive code so I was considering making some constructors for things like creating a a new osc or play/pause button. The problem I'm running into though, is since my oscillator controls are controlled via jquery how would i still use my jQuery sliders, buttons in the constructors?</p>
<p>This is as far as I've gotten:</p>
<pre><code>var ctx = new webkitAudioContext();
//object constructor
function Osc(type,freq,detune,gain)
{
this.create = new ctx.createOscillator();
this.type = type; //0 = sine, 1 = square, 2 = saw, 3 = triangle, 4 = custom
this.freq = freq;
this.detune = detune;
this.gain = gain;
this.changeType = changeType;
function changeType(type)
{
this.type = type;
};
this.changeFreq = changeFreq;
function changeFreq(freq)
{
this.freq = freq;
};
}
</code></pre>
<p>Any help is appreciated!</p>
|
[] |
[
{
"body": "<p>I just picked one part of the code that could use some polishing. Consider the following :</p>\n\n<pre><code>$('#play_pause_osc1').click(function () {\n if ($(this).val() == \"Play Osc1\") {\n $(this).val(\"Pause\");\n oscillator1Start();\n } else {\n $(this).val(\"Play Osc1\");\n osc1.disconnect();\n }\n});\n</code></pre>\n\n<p>You are switching here from one label back to another in a cycle, and then also do something. You do this for a ton of click listeners. You could do something like</p>\n\n<pre><code>function switchButton( $button, label1, label2, function1, function2 )\n{\n if( $button.val() == label1 )\n {\n $(this).val( label2 );\n function1(); \n }\n else\n {\n $(this).val( label1 );\n function2(); \n }\n}\n\n$('#play_pause_osc1').click( function() \n{ \n switchButton( \"Play Osc1\" , \"Pause\" , oscillator1Start , osc1.disconnect );\n});\n$('#play_pause_osc2').click( function() \n{\n switchButton( \"Play Osc2\" , \"Pause\" , oscillator2Start , osc2.disconnect );\n});\n$('#play_pause_osc3').click( function() \n{\n switchButton( \"Play Osc3\" , \"Pause\" , oscillator3Start , osc3.disconnect );\n});\n</code></pre>\n\n<p>This is much less code, but it is obvious that you still have copy pasted code. It is also obvious that your oscillators should be in an array.</p>\n\n<p>On a final note, are you sure your code is working ? The following statements do completely nothing, and they are part of your <code>oscillatornStart</code>:</p>\n\n<pre><code> //sets frequency\n osc1.frequency.value;\n //sets detune\n osc1.detune.value;\n //sets gain value\n gainNode1.gain.value;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-15T21:43:29.377",
"Id": "39335",
"ParentId": "37454",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:41:47.523",
"Id": "37454",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"jquery-ui",
"audio"
],
"Title": "Web Audio Constructors and jQuery"
}
|
37454
|
<p>I am building an array of strings to form the "empty" representation of a puzzle onto which I will overwrite single characters as necessary <em>for debugging purposes</em>. However, building the array using scalar multiplication results in shared string instances among the rows which breaks when I modify them.</p>
<pre><code>> grid = [["... " * 3] * 3, ""].flatten * 3
</code></pre>
<p>This produces the desired output</p>
<blockquote>
<pre><code>> puts grid * "\n"
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
... ... ...
</code></pre>
</blockquote>
<p>But the array contains only two string instances: nine of <code>"... ... ..."</code> and two of <code>""</code>. To solve this I use <code>map</code> to clone each string:</p>
<pre><code>grid = ([["... " * 3] * 3, ""].flatten * 3).map(&:clone)
</code></pre>
<p>Is there a better way?</p>
<p>The main question here is how best to make sure each array element is a <em>separate</em> string instance.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T01:44:14.680",
"Id": "61967",
"Score": "1",
"body": "Do I smell the beginning of a [tag:weekend-challenge] submission?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T16:33:54.567",
"Id": "62502",
"Score": "1",
"body": "I generally use \"ruby-like\" since it's very easy to write perl, C, or even python in ruby. \"The Ruby Way\" is a great book and also used in this context."
}
] |
[
{
"body": "<p>I might do this:</p>\n\n<pre><code>grid = 9.times.map { \"... \" * 3 }\n</code></pre>\n\n<p>Or, better yet, as Naklion proposes in the comments:</p>\n\n<pre><code>grid = Array.new(9) { \"... \" * 3 }\n</code></pre>\n\n<p>to get the rows (as separate string instances), and this</p>\n\n<pre><code>grid.each_slice(3) { |rows| puts rows, \"\\n\" }\n</code></pre>\n\n<p>to print it similar to yours. But I wouldn't call either approach \"idiomatic\", just variations on a theme. I don't know if anything really idiomatic can be said to exist for this</p>\n\n<p>However, it might be easier to approach this from a higher level, rather than rely on a string representation. I.e. parse the input grid into <code>Cell</code>, <code>Row</code> etc. objects (I'm obviously assuming this is sudoku we're talking about).<br>\nOf course, if you have a clever idea that relies on string manipulation, then go for it!</p>\n\n<p>My point is more that I know you can get far with, say, bitwise representations of sudoku, but implementing that in Ruby (while totally possible) seems \"crude\". Ruby's not geared toward twiddling bits, but toward more high-level OOP abstractions. It'd be right at home in C/C++, though.</p>\n\n<p>*) I'd go with \"rubyesque\" or just \"ruby\" as in \"the ruby way of doing things\" :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:46:07.910",
"Id": "62095",
"Score": "2",
"body": "`grid = Array.new(9){ \"... \" * 3 }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:14:43.863",
"Id": "62108",
"Score": "0",
"body": "@Naklion Better! I'll update the answer. I always forget about the block initializers on Array and Hash. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:16:21.190",
"Id": "62109",
"Score": "0",
"body": "I like the `9.times.map` bit because it seems more explicit, but I'm returning the built string from this method rather than displaying it immediately, so I can't do the `each_slice` trick. This is just for debugging, but it should still probably be moved into a model class. Each 3x3 block is a representation of the possible numbers a `Cell` may still take; this isn't the actual storage mechanism."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:17:59.730",
"Id": "62111",
"Score": "0",
"body": "@Nakilon Hah! I'm using that all over the place for building the internal data structures, yet I didn't think of it here. It is indeed a nifty trick."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:18:01.133",
"Id": "37502",
"ParentId": "37455",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37502",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T00:58:22.870",
"Id": "37455",
"Score": "3",
"Tags": [
"ruby",
"array"
],
"Title": "Clone array elements when multiplying by a scalar"
}
|
37455
|
<p>I'm writing a function in Python that compares the modification time of a file in Linux (using os.stat) with a specific time and compare the dates. If the modification date is older than the date I specified, an event should happen. </p>
<pre><code>import os
import time
import datetime
# File Modification time in seconds since epoch
file_mod_time = round(os.stat(file).st_mtime)
# Time in seconds since epoch for time, in which logfile can be unmodified.
t = datetime.datetime.today() - datetime.timedelta(minutes=30)
should_time = round(time.mktime(t.timetuple()))
# Time in minutes since last modification of file
last_time = round((int(time.time()) - file_mod_time) / 60, 2)
if (file_mod_time - should_time) < args.time:
print "CRITICAL:", file, "last modified", last_time, "minutes. Threshold set to 30 minutes"
else:
print "OK. Command completed successfully", last_time, "minutes ago."
</code></pre>
<p>It is working but I have the feeling that this could be largely improved, because there are so many time conversions. Can you give me a hint on how I can make it better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T20:52:55.320",
"Id": "61992",
"Score": "3",
"body": "Side note: it is better to never call a variable `file`: this shadows the built-in `file` class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-28T01:24:21.683",
"Id": "510221",
"Score": "0",
"body": "@EOL: True, but virtually no one uses the built-in explicitly, so it's extremely likely to not really matter — I see if all the time."
}
] |
[
{
"body": "<p>Mainly, you are working with timestamps, so instead of calling <em>both</em> <code>datetime.datetime.today()</code> and <code>time.time()</code> (which introduces a slight discrepancy), you could do your computations based on <code>time.time()</code> alone:</p>\n\n<p>You could replace</p>\n\n<pre><code>t = datetime.datetime.today() - datetime.timedelta(minutes=30)\nshould_time = round(time.mktime(t.timetuple())) \nlast_time = round((int(time.time()) - file_mod_time) / 60, 2)\n</code></pre>\n\n<p>with </p>\n\n<pre><code>t = time.time()\nshould_time = round(t - 30*60) \nlast_time = round((int(t) - file_mod_time) / 60, 2)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T19:02:41.050",
"Id": "37466",
"ParentId": "37465",
"Score": "1"
}
},
{
"body": "<p>For floating-point time values, go straight to <code>time.time()</code> and not use <code>datetime</code>:</p>\n\n<pre><code>file_mod_time = os.stat(file).st_mtime\n\n# Time in seconds since epoch for time, in which logfile can be unmodified.\nshould_time = time.time() - (30 * 60)\n\n# Time in minutes since last modification of file\nlast_time = (time.time() - file_mod_time) / 60\n\nif (file_mod_time - should_time) < args.time:\n print \"CRITICAL: {} last modified {:.2f} minutes. Threshold set to 30 minutes\".format(last_time, file, last_time)\nelse:\n print \"OK. Command completed successfully {:.2f} minutes ago.\".format(last_time)\n</code></pre>\n\n<p>I used string formatting to handle the rounding for you; just work with the float values in the calculations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T19:06:56.803",
"Id": "37467",
"ParentId": "37465",
"Score": "5"
}
},
{
"body": "<p>I think you were actually on the right path. <strong>I really do not concur with the \"represent dates with floats\" approaches</strong>: they <strong>force you to add many comments</strong> that (1) describe in what units your variables are (seconds, microseconds, whatever) and (2) indicate the reference time (epoch time, etc.). Instead, I recommend to <strong>manipulate dates directly</strong>: (1) the code is readily understandable, and (2) this allows one to do simple prints of the variables and get obviously meaningful results (useful for debugging and maintaining the code, etc.).</p>\n\n<p>Here is a simple implementation:</p>\n\n<pre><code>import os\nfrom datetime import datetime, timedelta\n\nfile_mod_time = datetime.fromtimestamp(os.stat(file_name).st_mtime) # This is a datetime.datetime object!\nnow = datetime.today()\nmax_delay = timedelta(minutes=args.time)\n\nif now-file_mod_time > max_delay:\n print \"CRITICAL: {} last modified on {}. Threshold set to {} minutes.\".format(file_name, file_mod_time, max_delay.seconds/60)\nelse:\n print \"OK. Command completed successfully {} minutes ago.\".format((now-file_mod_time).seconds/60)\n</code></pre>\n\n<p>(This is not exactly what your original code does, but I'm not sure whether you really intended to use both a delay of 30 minutes and <code>args.time</code>, from the text of the question: I merged them. The code can be easily adapted to your case, were it slightly different.)</p>\n\n<p><strong>This is much more legible</strong>. There is also really no need to add many comments about what is being done, as everything is explicit (<code>today()</code>, <code>timedelta()</code>, <code>.seconds</code>,…). No need to do much calculations either, or to round things (<code>int()</code>, <code>round()</code>). You also get a neat date+time printing for free (the printed <code>file_mod_time</code>).</p>\n\n<p>More generally, I would advise to <em>always have variables be of the type of object that they represent</em>. In your case, Python offers a nice date+time class, so I would not never suggest to downgrade dates and time intervals to pure numbers, as their meaning is not obvious (units? time corresponding to number 0?).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-14T12:50:56.873",
"Id": "61994",
"Score": "1",
"body": "It's not so clear that dates should *always* be handled by datetime objects. If you need to store the dates in a database, you would need to use timestamps. If your work begins and ends with timestamps and the calculations are easy -- as they are in this case -- it seems overly dogmatic to insist a solution is wrong if it does not use Python datetime objects. Also, there can be performance reasons for avoiding datetime objects. Pandas was able to improve performance by a factor of around 150x by [using 64-bit timestamps instead of datetime.datetime objects](http://wesmckinney.com/blog/?p=506)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-15T20:13:10.657",
"Id": "61995",
"Score": "1",
"body": "@unutbu: I agree with most of these interesting points. The question does not seem to fall at all in these use cases, though. Furthermore, the other answers show that calculations with timestamps are not nearly as simple as they are with the `datetime` objects of this answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T21:22:36.663",
"Id": "37469",
"ParentId": "37465",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37467",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-09T18:59:34.820",
"Id": "37465",
"Score": "7",
"Tags": [
"python",
"datetime",
"file-system"
],
"Title": "Compare last modification time with specfied time"
}
|
37465
|
<p><strong>Original</strong> </p>
<p>quicksort.h </p>
<pre><code>#include <algorithm>
namespace quicksort {
template <typename iterator, typename value_type>
struct traits
{
static iterator choose_pivot (iterator first, iterator last) {
return first + (last - first) / 2 ;
}
static iterator partition (iterator first, iterator last, iterator pivot) {
--last ;
traits::swap (*pivot, *last) ;
pivot = last ;
while (true) {
while (*first < *pivot) {
++first ;
}
--last ;
while (*pivot < *last) {
--last ;
}
if (first >= last) {
traits::swap (*pivot, *first) ;
return first ;
}
traits::swap (*first, *last) ;
++first ;
}
}
static void swap (value_type &lhs, value_type &rhs) {
std::swap (lhs, rhs) ;
}
};
template <typename iterator, typename value_type>
void sort (iterator first, iterator last)
{
if (first >= last) {
return ;
}
auto pivot = traits<iterator, value_type>::choose_pivot (first, last) ;
auto next_pivot = traits<iterator, value_type>::partition (first, last, pivot) ;
sort <iterator, value_type> (first, next_pivot) ;
sort <iterator, value_type> (next_pivot + 1, last) ;
}
} // end of namespace quicksort
</code></pre>
<p>Driver.cpp </p>
<pre><code>#include "quicksort.h"
#include <vector>
#include <string>
#include <iostream>
template <typename DataType, template <typename ...> class Container>
void print_container (const Container <DataType> &container)
{
for (const DataType &d : container) {
std::cout << d << " " ;
}
std::cout << std::endl ;
}
template <typename DataType, template <typename ...> class Container>
void run_test (const std::string &name, Container <DataType> &&container)
{
std::cout << name << ":\n" ;
print_container <DataType, Container> (container) ;
quicksort::sort <typename Container<DataType>::iterator, DataType> (std::begin (container), std::end (container)) ;
std::cout << name << " quicksorted:\n" ;
print_container <DataType, Container> (container) ;
}
int main (void)
{
run_test <int, std::vector> ("vec1", std::vector <int> {5, 4, 3, 1, 2}) ;
run_test <int, std::vector> ("vec2", std::vector <int> {5, 4, 10, 7, 6, 11, 14, 17, 12, 3, 1, 2}) ;
return 0 ;
}
</code></pre>
<p><br>
<strong>Updated</strong> </p>
<p>quicksort.h </p>
<pre><code>#include <algorithm>
#include <iterator>
namespace quicksort {
namespace detail {
struct first_pivot_selector
{
template <typename Iterator>
static Iterator choose_pivot (Iterator first, Iterator last) {
return first ;
}
};
struct middle_pivot_selector
{
template <typename Iterator>
static Iterator choose_pivot (Iterator first, Iterator last) {
auto distance = std::distance (first, last) / 2 ;
std::advance (first, distance) ;
return first ;
}
};
struct last_pivot_selector
{
template <typename Iterator>
static Iterator choose_pivot (Iterator first, Iterator last) {
return last ;
}
};
// Kept for debugging
struct my_pivot_selector
{
template <typename Iterator>
static Iterator choose_pivot (Iterator first, Iterator last) {
return first + (last - first) / 2 ;
}
};
struct std_partition {
template <typename Iterator>
static Iterator partition (Iterator first, Iterator last, Iterator pivot)
{
using value_type = typename std::iterator_traits<Iterator>::value_type ;
return std::stable_partition (first, last, [=] (const value_type &v) {
return v < *pivot ;
}) ;
}
};
// Kept for debugging
struct my_partition
{
template <typename Iterator>
static Iterator partition (Iterator first, Iterator last, Iterator pivot)
{
--last ;
std::swap (*pivot, *last) ;
pivot = last ;
while (true) {
while (*first < *pivot) {
++first ;
}
--last ;
while (*pivot < *last) {
--last ;
}
if (first >= last) {
std::swap (*pivot, *first) ;
return first ;
}
std::swap (*first, *last) ;
++first ;
}
}
};
} // end of namespace detail
template <typename Iterator, typename Pivot = detail::middle_pivot_selector, typename Partition = detail::my_partition>
void sort (Iterator first, Iterator last)
{
if (first >= last) {
return ;
}
auto pivot = Pivot::choose_pivot (first, last) ;
auto next_pivot = Partition::partition (first, last, pivot) ;
sort <Iterator, Pivot, Partition> (first, next_pivot) ;
sort <Iterator, Pivot, Partition> (next_pivot + 1, last) ;
}
} // end of namespace quicksort
</code></pre>
<p>Driver.cpp </p>
<pre><code>#include "quicksort.h"
#include <vector>
#include <string>
#include <iostream>
template <typename Container>
void print_container (const Container &container)
{
for (const typename Container::value_type &v : container) {
std::cout << v << " " ;
}
std::cout << std::endl ;
}
template <typename Container>
void run_test (const std::string &name, Container container)
{
std::cout << name << ":\n" ;
print_container (container) ;
quicksort::sort (std::begin (container), std::end (container)) ;
std::cout << name << " quicksorted:\n" ;
print_container (container) ;
}
int main (void)
{
run_test ("vec1", std::vector <int> {5, 4, 3, 1, 2}) ;
run_test ("vec2", std::vector <int> {5, 4, 10, 7, 6, 11, 14, 17, 12, 3, 1, 2}) ;
return 0 ;
}
</code></pre>
<p><br>
<strong>Problem</strong><br>
Based on these changes, <code>std_partition::partition</code> produces incorrect results. I found some code that follows a similar strategy on <a href="http://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Quicksort#C.2B.2B" rel="nofollow">wikibooks</a>. </p>
<pre><code>T middle = partition (begin, end, bind2nd(
less<typename iterator_traits<T>::value_type>(), *begin));
sort (begin, middle);
T new_middle = begin;
sort (++new_middle, end);
</code></pre>
<p>The problem is that this would break my current algorithm. I guess I could do a partial-specialization.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-22T16:18:54.657",
"Id": "88822",
"Score": "0",
"body": "I'm sorry that I asking this. But you trying to implement quicksort algoritm, or it is somehow different from std::sort? There is no offense, I just not really good understand quicksort algoritm, and can't figure out, is it better than std's one?"
}
] |
[
{
"body": "<p>Let's start with things that can be cleaned up in your <code>traits</code> struct:</p>\n\n<p>Firstly, by convention, all template parameters should be <code>UpperCaseFirstLetter</code>. Secondly, you don't need to pass in a <code>value_type</code>, because you can get this directly from the iterator using <code>std::iterator_traits</code>. Finally, using a <code>struct</code> with all static functions smells a bit: this should simply be an inner namespace. Usually, when it's details that you don't want to expose to people, the chosen name for the namespace would be <code>detail</code>. Let's apply that to the <code>choose_pivot</code> function:</p>\n\n<pre><code>#include <iterator>\n\nnamespace quicksort\n{\nnamespace detail\n{\n\ntemplate <typename Iterator>\nIterator choose_pivot(Iterator first, Iterator last)\n{\n auto distance = std::distance(first, last) / 2;\n std::advance(first, distance);\n return first;\n}\n\n} // end namespace detail\n\n...\n</code></pre>\n\n<p>It's now using <code>std::distance</code> and <code>std::advance</code>. This will work with any iterator type, but performance will obviously be degraded. If you want to enforce that the iterator is random access, you can always throw in a <code>static_assert</code>:</p>\n\n<pre><code> static_assert(std::is_same<std::iterator_traits<Iterator>::iterator_category,\n std::random_access_iterator_tag>::value,\n \"Iterator must be random access\");\n</code></pre>\n\n<p>The <code>partition</code> function you've got currently could be very easily replaced with <code>std::partition</code>:</p>\n\n<pre><code>template <typename Iterator>\nIterator partition(Iterator first, Iterator last, Iterator pivot)\n{\n using value_type = typename std::iterator_traits<Iterator>::value_type;\n return std::partition(first, last, [=](const value_type& v) { return v < *pivot; });\n}\n</code></pre>\n\n<p>If you want to make it really customisable, then I'd suggest doing that as template parameters on the <code>sort</code> function. Also, it's always a good idea to provide defaults, because otherwise your users are going to have to specify masses of template parameters, which is annoying. This will require modifying the <code>choose_pivot</code> function above into a <code>struct\\class</code>:</p>\n\n<pre><code>namespace detail\n{\nstruct pivot\n{\n template <typename Iterator>\n Iterator choose_pivot(Iterator first, Iterator last)\n {\n auto distance = std::distance(first, last) / 2;\n std::advance(first, distance);\n return first;\n }\n};\n} // end namespace detail\n</code></pre>\n\n<p>Then your sort function would look something like:</p>\n\n<pre><code>template <typename Iterator, typename Pivot = detail::pivot>\nvoid sort(Iterator first, Iterator last)\n{\n if (first >= last) {\n return;\n }\n\n auto pivot = Pivot().choose_pivot(first, last);\n auto next_pivot = detail::partition(first, last, pivot);\n sort<Iterator, Pivot>(first, next_pivot);\n sort<Iterator, Pivot>(next_pivot + 1, last);\n}\n</code></pre>\n\n<p>A similar pattern can be used for anything else you want to specify.</p>\n\n<p>Note that we've gotten rid of having to specify template parameters (almost) everywhere. In fact, the same can be done in your <code>run_test</code> function:</p>\n\n<pre><code>...\nquicksort::sort(std::begin(container), std::end(container));\n...\n</code></pre>\n\n<p>The compiler is smart enough to deduce parameters, so let it do the hard work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:27:33.683",
"Id": "62192",
"Score": "0",
"body": "Is naming the pivot struct `pivot` a good idea if I want to have multiple pivot choosing algorithms? Would it be better to call that struct something like `middle_pivot_selector`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:34:02.597",
"Id": "62194",
"Score": "0",
"body": "@red_eight Sure, `middle_pivot_selector` would probably be a better name for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T05:13:29.610",
"Id": "62208",
"Score": "0",
"body": "I have updated my code base on your and @MichaelUrman 's suggestions. The `std::partition` algorithm does not work correctly for some reason. I'm using `std::stable_partition` instead, but I'm getting the same incorrect results. When I use my partition method, everything still works fine."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T06:42:16.320",
"Id": "62435",
"Score": "0",
"body": "@red_eight My apologies with that. When I tested that what I'd written was working, I forgot to specify template parameters for `sort` (even though I included them above), and it must have switched to using `std::sort`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-01T18:02:19.310",
"Id": "411449",
"Score": "0",
"body": "@Yuushi: I don't think your `partition` function works, because `pivot` points into the range [`first`, `last`) and therefore the value of `*pivot` will change as the elements are swapped around inside `std::partition`, which means the lambda you've given to `std::partition` is not a predicate (it can give two different results for the same inputs)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T06:14:37.193",
"Id": "37480",
"ParentId": "37474",
"Score": "8"
}
},
{
"body": "<p>Regarding Driver.cpp's rvalue reference in <code>void run_test (const std::string &name, Container <DataType> &&container)</code>, since <code>Container</code> is being deduced, this isn't necessarily an rvalue reference; this could be either an rvalue or lvalue reference. Scott Meyers calls this construct a <a href=\"http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers\">universal reference</a> and offers advice on how to use them, as well as their pitfalls.</p>\n\n<p>Typically the only place you need to care rvalue references are for implementing move constructors and forwarding functions (the \"universal reference\" is great for forwarding functions). Outside of those, the rules haven't changed much: take a reference if you want to change things, take a const reference if you don't want to change things, and take it by value if you need to change things internally. The last of these is automatically move-constructed if the type supports it.</p>\n\n<p>And no, while your construct currently looks like one for a forwarding function, your function doesn't really forward anything. So you probably shouldn't be using std::forward (the conditional move) or even std::move (the unconditional rvalue cast) in <code>run_test</code>. This is because the only time you can afford for <code>run_test</code> to move the container is the last line where it calls <code>print_container</code> and <code>print_container</code> only accepts a const reference. Given that, I would probably remove the references entirely - semantically <code>run_test</code> accepts a container and then modifies it internally - it should just accept raw <code>Container<DataType></code>, and not care whether it was moved or copied to get there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T03:08:47.400",
"Id": "62201",
"Score": "0",
"body": "+1 For the article. That was a great read, but a tad complicated. Man, passing non-trivial objects by value is going to take time to get used to."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:15:14.740",
"Id": "37507",
"ParentId": "37474",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37480",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T04:37:10.290",
"Id": "37474",
"Score": "10",
"Tags": [
"c++",
"c++11",
"template",
"quick-sort"
],
"Title": "Templated Quicksort"
}
|
37474
|
<p>I have some concerns:</p>
<ol>
<li><p>Is it normal for the class to have at least one node? In other words, this implementation cannot have an empty linked list; the length is always 1.</p></li>
<li><p>Would this be a proper way to implement a linked list in, say, a professional environment? Or perhaps there is a better way to do it? I am not a professional in any way, mind you, just a college freshman.</p></li>
</ol>
<p>Implementation file:</p>
<pre><code>#include "ListNode.h"
#include <iostream>
#include <climits>
using namespace std;
ListNode::ListNode()
{
}
ListNode::ListNode(int value, ListNode* node){
this->value = value;
this->next = node;
}
void ListNode::setNext(ListNode* node){
this->next = node;
}
void ListNode::setValue(int value){
this->value = value;
}
ListNode* ListNode::getNext(){
return this->next;
}
int ListNode::getValue(){
return this->value;
}
int ListNode::getLength(){
if (this != NULL){//if this is not NULL
if ((*this).getNext() == 0)
return 1;
else{
ListNode* temp = this;
int count = 0;
while (temp != 0){
count++;
temp = (*temp).getNext();
}//end while
temp = NULL;
return count;
}//end else
}//end if
return 0;
}
void ListNode::replace(int position, int value){
ListNode* temp = this;
if (position > -1 && position < getLength()){
for (int i = 0; i < position; i++){
temp = (*temp).getNext();
}//end for
(*temp).setValue(value);
}//end if
else
cout << "Desired index is out of bounds by " << getLength() - position + 1 << " units" << endl;
temp = NULL;
}
void ListNode::remove(int position){
ListNode* temp = this;
if (position > -1 && position < getLength()){
for (int i = 0; i < position - 1; i++){
temp = (*temp).getNext();
}//end for
(*temp).setNext((*(*temp).getNext()).getNext());
}//end if
else
cout << "Desired index is out of bounds by " << getLength() - position+1 << " units" << endl;
temp = NULL;
}
void ListNode::addAt(int position, int value){
ListNode* temp = this;
ListNode* temp2;
if (position > -1 && position < getLength() + 1){
if (position == 0){
addInfront(value);
}//end if
else
if (position == getLength()){
addAppend(value);
}//end else if
else{
for (int i = 0; i < position - 1; i++){
temp = (*temp).getNext();
}//end for
temp2 = (*temp).getNext();
(*temp).setNext(new ListNode(value, temp2));
}//end else
}//end if
else
cout << "Desired index is out of bounds by " << getLength() - position << " units" << endl;
temp = NULL;
temp2 = NULL;
}
void ListNode::addAppend(int value){
ListNode* temp = this;
while ((*temp).getNext() != 0){
temp = (*temp).getNext();
}
(*temp).setNext(new ListNode(value, NULL));
temp = NULL;
}
void ListNode::addInfront(int value){
ListNode* temp = (*this).getNext();
int num = (*this).getValue();
(*this).setValue(value);
(*this).setNext(new ListNode(num, temp));
temp = NULL;
}
int ListNode::elementAt(int position){
if (this == 0 || (*this).getLength() <= position)
return INT_MIN;
ListNode* temp = this;
for (int i = 0; i < position; i++){
temp = (*temp).getNext();
}
int num = (*temp).getValue();
temp = NULL;
return num;
}
int ListNode::indexOfElement(int value){
ListNode* temp = this;
for (int i = 0; i < (*this).getLength(); i++){
if ((*temp).getValue() == value)
return i;
temp = (*temp).getNext();
}
temp = NULL;
return -1;
}
int ListNode::lastIndexOfElement(int value){
ListNode* temp = this;
int count = -1;
for (int i = 0; i < (*this).getLength(); i++){
if ((*temp).getValue() == value)
count = i;
temp = (*temp).getNext();
}
temp = NULL;
return count;
}
void ListNode::deleteFirstElement(){
ListNode* temp = this;
if ((*(*this).getNext()).getNext() == 0){//if there are only two nodes
temp = (*temp).getNext();
(*this) = *temp;
(*this).setNext(0);
delete temp;
}
else{//if there are more than two nodes
temp = (*temp).getNext();
(*this) = *temp;
temp = (*temp).getNext();
(*this).setNext(temp);
temp = NULL;
}
}
void ListNode::deleteLastElement(){
ListNode* temp = this;
while ((*(*temp).getNext()).getNext() != 0){
temp = (*temp).getNext();
}
(*temp).setNext(0);
temp = NULL;
}
void ListNode::printList(){
ListNode* temp = this;
while (temp != NULL){
cout << (*temp).getValue() << " ";
temp = (*temp).getNext();
}//end while
cout << endl;
}
ListNode::~ListNode()
{
}
</code></pre>
<p>Header file:</p>
<pre><code>#pragma once
class ListNode
{
public:
ListNode();
ListNode(int, ListNode*);
void setValue(int);
void setNext(ListNode*);
int getValue();
void deleteFirstElement();
void deleteLastElement();
int getLength();
int indexOfElement(int);
int lastIndexOfElement(int);
int elementAt(int);
void addAppend(int);//adds new node with corresponding value to end of LinkedList
void addInfront(int);//add new node with corresponding value at the begining of the LinkedList
void addAt(int, int);//adds new node with specified value to the specified index...other elements are then shifted(index, value)
void remove(int);//removes first instance of node at specified index
void replace(int, int);//replaces value at specified index with new value, respectively(index, value);
void deleteElement(int, int);
void printList();
ListNode* getNext();
~ListNode();
private:
ListNode* next = 0;
int value;
};//end class
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T10:54:00.333",
"Id": "63146",
"Score": "2",
"body": "Don't worry; you're not alone. C++ takes just a few lifetimes to master."
}
] |
[
{
"body": "<blockquote>\n <p>For example, is it normal for the class to have at least one node? In\n other words, this implementation cannot have an empty linked list. The\n length is always 1.</p>\n</blockquote>\n\n<p>No, a linked list can be empty (i.e. size 0).</p>\n\n<p>But there are designs that intentionally always have at least one member in the list. This special member is referred to as a sentinel and should not hold any data or be counted as a member of the list in terms of size. So if the only member of the list is a sentinel, the size is zero.</p>\n\n<p>There are design advantages to using a sentinel as the list never has any <code>NULL</code> pointers. This actually makes implementing the list easier (as you don't have to check for the <code>NULL</code> special case).</p>\n\n<blockquote>\n <p>Lastly, would this be a proper way to implement a linkedList in, say,\n a professional environment?</p>\n</blockquote>\n\n<p>Even without looking at it, I would still have to say that <a href=\"http://en.cppreference.com/w/cpp/container/list\" rel=\"nofollow noreferrer\"><code>std::list</code></a> would be preferred in a professional environment as it comes from the <a href=\"http://en.wikipedia.org/wiki/Standard_Template_Library\" rel=\"nofollow noreferrer\">Standard Template Library (STL)</a>. That said, I'd recommend closely following the STL while studying best practices in the language from any trusted reference material at your disposal. <em>Practicing</em> writing your own list, however, would be helpful for learning how the linked list implementation works under the hood.</p>\n\n<p>After looking at it further, it already looks like an uncommon implementation. There's only one class which, based off the name, seems to resembles a node. However, the implementation seems more like a list itself with the basic aspects of a node, primarily as the <code>private</code> data members. They're two separate entities and should have their own properties, which I will explain below.</p>\n\n<p>You should have two main entities - the linked list itself (as a <code>class</code>) and a node (as a <code>class</code> or as a <code>struct</code>). The node structure should be a <code>private</code> member of the linked list class. The node just has two data members - a value (of some type or a templated type) and a pointer to the next node (and the previous node if it's a doubly-linked list). The linked list class handles the list operations and maintains a pointer to the head node, which should also be <code>private</code>. The head node points to <code>NULL</code> (or a sentinel) if the list is empty, or the first node if it's not. It should also maintain a <code>private</code> size, based on the number of nodes (excluding a sentinel). The size should also be accessible to the client via a <code>public</code> accessor (\"getter\") function.</p>\n\n<hr>\n\n<p>Moreover, I'll point out some general flaws and other points in your code with no regard to the above:</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1282295/what-exactly-is-nullptr\">Prefer <code>nullptr</code> to <code>NULL</code> if you're using C++11</a>.</p></li>\n<li><p>Your accessors (or \"getters\") should be <code>const</code>. This prevents data members from possibly being modified in the function. This is important because you want to make sure the accessors return the unchanged data member in order to avoid bugs. This also helps ensure <a href=\"http://www.cprogramming.com/tutorial/const_correctness.html\" rel=\"nofollow noreferrer\">const correctness</a>.</p></li>\n<li><p>Linked lists add nodes by allocating new memory. In C++, that's done with <code>new</code>. You also need to <em>deallocate</em> the memory with <code>delete</code> when you're finished with it. If you do not, you'll experience <em>memory leaks</em>. This deallocation should be done in the destructor, specifically with a loop that destroys each node with <code>delete</code>.</p></li>\n<li><p>You're interchanging <code>pointer->member</code> and <code>(*pointer).member</code>. Prefer the <code>-></code> operator as it is more readable and \"less-awkward\" than the other.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:00:45.270",
"Id": "62037",
"Score": "3",
"body": "`NULL` is just integer 0; using it or not is more a matter of style than a strict flaw. I'd definitely prefer `nullptr` in a C++11 environment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:35:19.820",
"Id": "62039",
"Score": "0",
"body": "There is no need to set the `head` pointer back to `nullptr` in a destructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:20:57.453",
"Id": "62090",
"Score": "0",
"body": "@user2357112: Yes, I was going after style there, but I didn't quite mention it since I'm very used to seeing `NULL` with linked lists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:21:58.337",
"Id": "62091",
"Score": "0",
"body": "@AntonGolov: True. I thought I remember once having to do that, but it must've been with a separate function other than the destructor. I'll keep that in mind."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T05:23:30.803",
"Id": "37476",
"ParentId": "37475",
"Score": "27"
}
},
{
"body": "<p>I haven't looked at all of you code, but here are a few things that jumped out to me: </p>\n\n<p>Typically, a linked list is composed of two classes. One class represents the list and the other class represents a node in the list.</p>\n\n<pre><code>class ListNode\n{\npublic:\n ListNode () ;\n ListNode (const int data, const ListNode *next) ;\n ~ListNode () ;\n\n // Other functions, maybe a getNext, getData, etc...\n\nprivate:\n int data ;\n ListNode *next ;\n ListNode *previous ; // Optional\n};\n\nclass LinkedList\n{\npublic:\n // Constructors, destructors..\n // Functions such as insert, remove, getSize, etc...\n\nprivate:\n ListNode *head ;\n ListNode *tail ; // Optional \n};\n</code></pre>\n\n<p><br>\nYou constructor does not initialize your variables. You should use a <a href=\"http://www.learncpp.com/cpp-tutorial/101-constructor-initialization-lists/\" rel=\"nofollow\">constructor initialization list</a>. </p>\n\n<pre><code>ListNode::ListNode() : value (0), next (NULL) // or nullptr for C++11\n{\n}\n</code></pre>\n\n<p><br>\nThis is a bug: </p>\n\n<pre><code>if (this != NULL){//if this is not NULL\n</code></pre>\n\n<p>There is no scenario where <code>this</code> could be <code>NULL</code>. If <code>this</code> was <code>NULL</code> and you tried to call a member function, then you would get undefined behavior. For example: </p>\n\n<pre><code>ListNode node (5, NULL) ; // create on stack\nListNode *node2 = node.getNext () ; // gets a NULL pointer\nnode2->getLength () ; // oops, we dereferenced a NULL pointer, undefined behavior!\n</code></pre>\n\n<p><br>\nDon't use this notation: <code>(*temp).getNext();</code>.<br>\nUse <code>temp->getNext()</code> instead. </p>\n\n<p><br>\nAn important topic that @Jamal touched up on is <strong>Dynamic Memory Ownership</strong>.<br>\nLet's say you do something like this: </p>\n\n<pre><code>void someFunction (ListNode *list)\n{\n ListNode node (5, NULL) ;\n list->setNext (&node) ;\n}\n\n// Somewhere else in the code\nListNode list (0, NULL) ;\nsomeFunction (&list) ;\nint n = list.elementAt (1) ; // Why is it crashing here?\n</code></pre>\n\n<p>What's happening here is that <code>node</code> was allocated on the stack.<br>\nOnce <code>someFunction</code> exits, <code>node</code> is popped off the stack and is garbage data.<br>\nIt may not cause your program to crash everytime, but it is undefined behavior.<br>\nA container typically wants to take ownership of whatever data is being inserted into it. This is done by calling <code>new</code> when inserting the object into the container and calling <code>delete</code> inside a destructor. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T07:35:58.420",
"Id": "62040",
"Score": "1",
"body": "In your last bit of code, there is no dynamically allocated memory and so cannot be a memory leak; however, there probably is undefined behaviour."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:07:57.440",
"Id": "62045",
"Score": "1",
"body": "dereferencing a NULL is not necessarily a segfault but undefined behavior, or in other words all bets are off on what it will actually do"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T05:35:12.820",
"Id": "37477",
"ParentId": "37475",
"Score": "11"
}
},
{
"body": "<ul>\n<li>Don't print error messages to <code>cout</code>, as that hurts reusability. I suggest changing the methods to return <code>true</code> on success and <code>false</code> on failure. The reason for the failure should be obvious enough to the caller. (If you must print error messages, direct them to <code>cerr</code> instead of <code>cout</code>.)</li>\n<li><p>Avoid calling <code>.getLength()</code>, as that requires you to traverse the entire list. For example, <code>.elementAt()</code> could be</p>\n\n<pre><code>int ListNode::elementAt(int position) {\n // You can't call a method on nullptr, so you don't need to check if\n // this == 0. Instead of .getLength(), check for the end of the list\n // in the loop below.\n //\n // if (this == 0 || (*this).getLength() <= position)\n // return INT_MIN;\n ListNode* temp = this;\n for (int i = 0; i < position; i++) {\n if (!temp) {\n return INT_MIN;\n }\n temp = temp->getNext();\n } \n return temp->getValue();\n // Since temp is a local variable, we don't care what its value is\n // after the function returns.\n // temp = NULL;\n}\n</code></pre></li>\n<li><p>In <code>.addAt()</code>, you shouldn't need the special case</p>\n\n<pre><code>if (position == getLength()) {\n addAppend(value);\n}\n</code></pre></li>\n<li>The name <code>.addAppend()</code> is awkward; <code>.append()</code> should suffice.</li>\n<li><p>Using similar principles, you could simplify <code>.getLength()</code> by eliminating all the special cases:</p>\n\n<pre><code>int ListNode::getLength() {\n int count = 0;\n for (ListNode *temp = this; temp; temp = temp->getNext()) {\n count++;\n }\n return count;\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T16:36:58.647",
"Id": "63165",
"Score": "1",
"body": "An alternative to error codes would be to throw exceptions. Also, a private variable could be used to keep track of the size of the list. This would make the `getLength ()` method an `O(1)` operation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T17:24:05.310",
"Id": "63166",
"Score": "1",
"body": "@jliv902 Keeping track of the length is only practical if you do it in a `LinkedList` object. If you do it in the `ListNode` class, some operations become expensive. For example, when you insert an element at the head of the list, you would have to increment the length field of every single node."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T03:31:27.447",
"Id": "70081",
"Score": "0",
"body": "`elementAt` will segfault if `position` equals the list length."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T03:44:58.557",
"Id": "70085",
"Score": "0",
"body": "@DavidHarkness In C/C++, the usual attitude is that if you make an \"illegal\" request like accessing an element beyond the end of a list, you deserve to crash."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T04:04:18.863",
"Id": "70087",
"Score": "0",
"body": "@200_success In that case, it should crash whether you're 1 beyond or 500, but here it returns `INT_MIN` if more than 1 beyond the end. Consistency is key."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T11:28:26.543",
"Id": "37952",
"ParentId": "37475",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T04:48:19.547",
"Id": "37475",
"Score": "14",
"Tags": [
"c++",
"c++11",
"linked-list"
],
"Title": "Implementing a proper linked list for a professional environment"
}
|
37475
|
<p>Let me start by saying that the code works as is but I think it has a lot of redundancy. It is written this way as I kept getting nullpointerexceptions if I try to put the fileCounter > gameDiff if/else inside one for loop.</p>
<p>The program allows a user to create directories and add images to them. It will also display a certain number of images based on the users selection. If the user's chosen directory doesn't have enough images, it drops back to the default directory to add more.</p>
<pre><code>String userDir = cboImages.getSelectedItem().toString();
File filePath = new File(baseDir + "/" + userDir + "/");
comboFile = filePath.listFiles();
int fileCounter = 0;
for (int ctr = 0; ctr < comboFile.length; ctr++) {
if (comboFile[ctr].isFile()) {
fileCounter++;
}
}
filePath = new File(baseDir + "/default/");
defaultFile = filePath.listFiles();
List<File> listShuffle = Arrays.asList(comboFile);
List<File> defaultShuffle = Arrays.asList(defaultFile);
Collections.shuffle(listShuffle);
Collections.shuffle(defaultShuffle);
if(fileCounter > gameDiff){
for (int ctr = 0; ctr < gameDiff; ctr++) {
Card card = new Card();
card.setbackImage(new ImageIcon(cardBackImage));
Image img = null;
if (listShuffle.get(ctr).isFile()) {
img = new ImageIcon(listShuffle.get(ctr).getPath()).getImage();
}
Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);
card.setfrontImage(new ImageIcon(dimg));
// Populate card with db results
cardsList.add(card);
}
}
else{
for (int ctr = 0; ctr < gameDiff; ctr++) {
Card card = new Card();
card.setbackImage(new ImageIcon(cardBackImage));
Image img = null;
if (ctr < listShuffle.size()) {
if (listShuffle.get(ctr).isFile()) {
if (fileCounter <= gameDiff) {
img = new ImageIcon(listShuffle.get(ctr).getPath()).getImage();
}
}
} else if (ctr < gameDiff) {
if (defaultShuffle.get(ctr).isFile()) {
img = new ImageIcon(defaultShuffle.get(ctr).getPath()).getImage();
}
}
Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);
card.setfrontImage(new ImageIcon(dimg));
// Populate card with db results
cardsList.add(card);
}
}
</code></pre>
<p>Using two separate groups insures that the chosen directory images get added.</p>
|
[] |
[
{
"body": "<p>First of all, Java code doesn't really make sense outside of the context of a class and a method. Sometimes you can get away without the class, but the method signature is definitely important. In this case, you've included references to variables without a type: are these arguments to a method? Members of a class?</p>\n\n<p>Second, your description of what this code does has too many ands in it. Code should be organized in terms of abstractions. For instance, if you describe something this way, it's a bit confusing as to what it actually does: \"It lets you write arrays of bytes to a magnetic medium and causes the read heads to seek to a particular place on the disk and also it lets you refer to a group of bytes by a name, etc, etc.\" Instead you might start from the bottom: \"Files are sequences of bytes intended for long-term storage; they support the following operations: append, truncate, etc. Files are organized into a directory structure by a filesystem, which is built on top of a storage device, etc.\" This description divides the details into various levels of abstraction.</p>\n\n<p>I'll give a new listing and afterward describe why I made the changes I did.</p>\n\n<pre><code>class Card {\n private final ImageIcon frontImage;\n private final ImageIcon backImage;\n\n public Card(ImageIcon frontImage, ImageIcon backImage) {\n this.frontImage = frontImage;\n this.backImage = backImage;\n }\n // Probably more goes on here\n}\n\nclass Deck {\n private static final String DEFAULT_SUBDIRECTORY = \"default\";\n private final String baseDir;\n private final ImageIcon cardBackImage;\n\n private List<File> loadSubdirectory(String subdir) {\n List<File> files = new ArrayList<File>();\n File[] listing = new File(baseDir, subdir).listFiles();\n for (int i = 0; i < listing.length; i++) {\n if (listing[i].isFile()) {\n files.add(listing[i]);\n }\n }\n return files;\n }\n\n public List<Card> selectCardsFromDirectory(int numCards, ComboBox cboImages) {\n return selectCardsFromDirectory(numCards, cboImages.getSelectedItem().toString());\n }\n\n /** Selects numCards at random from the user's directory,\n filling in from the default directory if the user has\n too few */\n public List<Card> selectCardsFromDirectory(int numCards, String userDirectory) {\n List<File> userFiles = loadSubdirectory(userDirectory);\n List<File> defaultFiles = loadSubdirectory(DEFAULT_SUBDIRECTORY);\n\n Collections.shuffle(userFiles);\n Collections.shuffle(defaultFiles);\n\n List<Card> cards = new ArrayList<Card>();\n for (int i = 0; i < numCards; i++) {\n ImageIcon frontImage;\n if (i < userFiles.size()) {\n frontImage = loadScaledImage(userFiles.get(i));\n } else {\n frontImage = loadScaledImage(defaultFiles.get(i - userFiles.size()));\n }\n cards.add(new Card(frontImage, cardBackImage));\n }\n return cards;\n }\n\n private ImageIcon loadScaledImage(File file) {\n Image image = new ImageIcon(file.getPath()).getImage();\n return new ImageIcon(\n image.getScaledInstance(IMAGE_WIDTH, IMAGE_HEIGHT, Image.SCALE_SMOOTH));\n }\n}\n</code></pre>\n\n<p>This is a quick and dirty refactoring and I haven't compiled it to check that it all builds, but it should give you the idea. In particular, the code is not presented in any reasonable order.</p>\n\n<p>It appears that you had a bug in the code; you use <code>fileCounter</code> to determine how many normal files are in a directory, and only take <code>fileCounter</code> files from the user directory, but you don't skip past directories, etc. I've modified the logic.</p>\n\n<p>This <code>Deck</code> class knows about too many things. Why does it know about the disk layout? Why does it know about elements of the GUI (ie <code>cboImages</code>)? Try reading up on <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\">MVP</a> or <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\">MVC</a> design for ideas of how to restructure your code to have better encapsulation. Some thoughts:</p>\n\n<ul>\n<li>Separate the shuffling logic out of the class that deals with the file system; that should be as simple as moving <code>loadSubdirectory</code> into a new class.</li>\n<li>Remove the overload of <code>selectFilesFromDirectory</code> that takes a <code>ComboBox</code>; the GUI should extract the <code>String</code> before calling into this class.</li>\n</ul>\n\n<p>I've pulled out some helper functions. These do two things: reduce code duplication, and improve abstraction. As a good rule of thumb, most methods shouldn't exceed 25 lines. By pulling out the file-loading logic, I've made it so you don't need to think about how exactly the files are loaded when you're reading <code>selectFilesFromDirectory</code>.</p>\n\n<p><code>Card</code> has some problems as a class. It is odd that you are default-constructing it, and then constructing it more afterward. I've redesigned part of it.</p>\n\n<p><code>ctr</code> is not a very good name for a generic loop counter. Most programmers use <code>i</code>, <code>j</code>, and other one-letter names for short loops, or actually descriptive names. For this reason, when reading the code, my brain tries to figure out what <code>ctr</code> means. I'm lucky; English is my first language -- for some people who don't have English as their first language, unusual abbreviations of English words are difficult to decipher.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T13:55:01.617",
"Id": "62075",
"Score": "0",
"body": "Thank you, I thought the Game Screen was doing to much but was overruled by the rest of the team. I didn't create all of the code in this class. What I posted is my code. Next time I post I'll make sure to include the variable types if they are not declared in the posted code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T06:48:50.257",
"Id": "37481",
"ParentId": "37478",
"Score": "8"
}
},
{
"body": "<p>I'll give you some general comments about your code and style.</p>\n\n<hr>\n\n<pre><code>File filePath = new File(baseDir + \"/\" + userDir + \"/\");\n</code></pre>\n\n<p>That's bad. The <code>File</code> class has a constructor especially designed to create joined paths:</p>\n\n<pre><code>File filePath = new File(baseDir, userDir);\n</code></pre>\n\n<p>No more dealing with path separators.</p>\n\n<hr>\n\n<pre><code>comboFile = filePath.listFiles();\nint fileCounter = 0;\nfor (int ctr = 0; ctr < comboFile.length; ctr++) {\n if (comboFile[ctr].isFile()) {\n fileCounter++;\n }\n}\n</code></pre>\n\n<p>This loop is unnecessary complicated. Use a <code>for</code> loop whenever you need to know the index of what you iterate over <em>or</em> if it is not something compatible with the <code>foreach</code> loop. You should always use a <code>foreach</code> loop by default.</p>\n\n<pre><code>int fileCounter = 0;\nfor (File file : filePath.listFiles()) {\n if (file.isFile()) {\n fielCounter++;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>There is no check that the directories you us actually exist, does it not matter or are they guarantied to exist?</p>\n\n<hr>\n\n<pre><code>File filePath = new File(baseDir + \"/\" + userDir + \"/\");\n...\nfilePath = new File(baseDir + \"/default/\");\n</code></pre>\n\n<p>First, do not reuse variables if they will be holding two distinct values or have been used in between. Second, your naming of variables could be better.</p>\n\n<pre><code>File absoluteUserDir = new File(baseDir, userDir);\n</code></pre>\n\n<p>Actually, this doesn't make much sense, it would be better if <code>userDir</code> would hold this path directly:</p>\n\n<pre><code>File userDir = new File(baseDir, cboImages.getSelectedItem().toString());\n</code></pre>\n\n<p>And the last one:</p>\n\n<pre><code>File defaultDir = new File(baseDir, \"default\");\n</code></pre>\n\n<hr>\n\n<pre><code>card.setbackImage(new ImageIcon(cardBackImage));\ncard.setfrontImage(new ImageIcon(dimg));\n</code></pre>\n\n<p>There's a typo here, the b and f should be uppercase.</p>\n\n<hr>\n\n<pre><code>Image dimg = img.getScaledInstance(144, 216, Image.SCALE_SMOOTH);\n</code></pre>\n\n<p>Again, this is not the best name this variable could have:</p>\n\n<pre><code>Image scaledImage = ...\n</code></pre>\n\n<hr>\n\n<pre><code>cardsList.add(card);\n</code></pre>\n\n<p>There's no need to pre- or postfix variables with their type. <code>cards</code> alone does already tell the reader that it is a collection or list of some sort.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:19:50.603",
"Id": "62078",
"Score": "0",
"body": "Thank you for the comments. I will start using the file constructor to create the paths. I am still struggling with Java's foreach loop while I can do a for loop off the top of my head. I will start using it more. The directory check is not done here as it has been done during the init method when the combobox was populated with directory listings. The method calls for setbackImage and setfrontImage weren't created by me, they are in another class. In your last comment are you saying to drop the \"List\" part? I was attempting to do code name commenting to reduce comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:23:59.243",
"Id": "62081",
"Score": "0",
"body": "Yes, I meant to drop the list parts, it's unnecessary. `cards` tells you that it is a collection, array or list or something similar. If someone is only reading through it it is easier to parse. If someone wants to change something, they need to check the declaration anyway."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T08:37:12.163",
"Id": "37486",
"ParentId": "37478",
"Score": "6"
}
},
{
"body": "<p>This is a suggested improvement on @ruds refactoring. I liked his refactoring, particularly his <code>i - userFiles.size()</code> trick. But conditional in a loop still looks ugly. Uninitialized declarations and multiple assignments to a local variables are not good either. It can be improved easily though, once the above trick is noted.</p>\n\n<pre><code>public List<Card> selectCardsFromDirectory(int numCards, String userDirectory) {\n List<File> userFiles = loadSubdirectory(userDirectory);\n List<File> defaultFiles = loadSubdirectory(DEFAULT_SUBDIRECTORY);\n\n Collections.shuffle(userFiles);\n Collections.shuffle(defaultFiles);\n\n ArrayList<File> allFiles = new ArrayList<File>();\n allFiles.addAll(userFiles);\n allFiles.addAll(defaultFiles);\n\n List<Card> cards = new ArrayList<Card>();\n for (int i = 0; i < numCards; i++) {\n ImageIcon frontImage = loadScaledImage(allFiles.get(i));\n cards.add(new Card(frontImage, cardBackImage));\n }\n return cards;\n}\n</code></pre>\n\n<p>With guava <code>selectCardsFromDirectory</code> can be further condensed, <em>at the expense of some usual Java clutter</em>, like this:</p>\n\n<pre><code>public List<Card> selectCardsFromDirectory(int numCards, String userDirectory) {\n List<File> userFiles = loadSubdirectory(userDirectory);\n List<File> defaultFiles = loadSubdirectory(DEFAULT_SUBDIRECTORY);\n\n Collections.shuffle(userFiles);\n Collections.shuffle(defaultFiles);\n\n return FluentIterable\n .from(Iterables.concat(userFiles, defaultFiles))\n .transform(FILE_TO_CARD)\n .limit(numCards)\n .toList();\n}\n\n// just some glue\nprivate static final Function<File, ImageIcon> FILE_TO_CARD \n = new Function<File, ImageIcon>() {\n public ImageIcon apply(File file) {\n return fileToCard(file);\n }\n };\n\nprivate static final fileToCard(File file) {\n ImageIcon frontImage = loadScaledImage(file);\n return new Card(frontImage, cardBackImage);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T08:55:56.960",
"Id": "37489",
"ParentId": "37478",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37481",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T05:37:38.657",
"Id": "37478",
"Score": "5",
"Tags": [
"java",
"file-system",
"image"
],
"Title": "Improve this image file browser (remove redundancy)?"
}
|
37478
|
<p>I have been changing this code and I don't get to make it much better. I changed a little bit the structure, reimplemeted a new function for splitting Strings which is more efficient, etc. I have been tested with MR-Unit (it's part of map-reduce code).</p>
<p>I'm testing the code with 1.5 millions calls. It takes about 35 seconds on my computer, but in the real environment, it could be called with much more data, so, any optimization could be great. I'm worry about a little part of the code which I call around 7 times each iteration.</p>
<p>The parameters of my function are a map with the values what I want to replace, and another string which is a expression. It could be something like hard-code (I won't have to do any processing) or a expression like <code>${0}</code> or something more complex like <code>${0}_${3}</code>. </p>
<p>My idea now, since it's map-reduce code, is to do some of this code out of the mapper, and it should execute just once. The code could be more complex but I would only have once for the matchers and the split. I don't know if that could improve the performance.</p>
<pre><code>private static final Pattern PATTERN = Pattern
.compile("\\$\\{.+?\\}");
private static final Pattern PATTERN_DOLLAR = Pattern
.compile("^.*\\$.*$");
public static String replaceVariables(final String expression,
final Map<String, String> vars) {
String tmpExp = expression;
Matcher matcher = PATTERN.matcher(tmpExp);
while (matcher.find()) {
final String group = matcher.group();
//${4} --> 4, ${2,8} --> 2,8
final String prop = group.substring(2, group.length() - 1);
// If the property has a comma, special case.
final String[] props = split(prop, ',');
//I get the value from the Map
String sValue = vars.get(props[0]);
if (sValue != null) {
//Special case, I could write ${0,3}, field 0, only the first 3 characters.
if (props.length > 1) {
final int cut = Integer.parseInt(props[1]);
if (sValue.length() > cut) {
sValue = sValue.substring(0, cut);
}
}
Matcher matcherDollar = PATTERN_DOLLAR.matcher(sValue);
if (matcherDollar.matches()) {
tmpExp =
matcher.replaceFirst(sValue.replace("$", "\\$"));
} else {
tmpExp = matcher.replaceFirst(sValue);
}
} else {
tmpExp = matcher.replaceFirst("");
}
matcher = VAR_PATTERN.matcher(tmpExp);
}
return tmpExp;
}
</code></pre>
<p>The split function:</p>
<pre><code>public static String[] split(final String s, final char delimeter) {
int count = 1;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == delimeter)
count++;
String[] array = new String[count];
int a = -1;
int b = 0;
for (int i = 0; i < count; i++) {
while (b < s.length() && s.charAt(b) != delimeter)
b++;
array[i] = s.substring(a + 1, b);
a = b;
b++;
}
return array;
}
</code></pre>
<p>The possible input it could be:</p>
<p>Expression:</p>
<blockquote>
<p>Hi {0,2}</p>
</blockquote>
<p>Map:</p>
<blockquote>
<p>0=test, 1=test1, 2=test2, ...</p>
</blockquote>
<p>Usually, the expressions are pretty simple; just a hardcode of one or two variable expressions (e.g. <code>{0,1}_{2}</code> or even simpler). Although it's possible to find more complex expressions, it's not so common.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T09:48:58.433",
"Id": "62049",
"Score": "0",
"body": "What is your split implementation?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:09:50.413",
"Id": "62055",
"Score": "0",
"body": "And what about `VAR_PATTERN`? I'm guessing, it's `PATTERN`, right? And add some example values for the parameters of `replaceVariables`. It will be easier to understand!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T12:02:05.910",
"Id": "62066",
"Score": "0",
"body": "Thanks a lot, I'm going to put the split implementation and some input examples."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T12:19:41.810",
"Id": "62069",
"Score": "0",
"body": "So, does my code improvement help you? With your example values it works perfectly. Try it with real values of your system and look, if it improves the performance heavily."
}
] |
[
{
"body": "<p>What about the following code. I've improved it by not using regular expressions (except one call of <code>String.split</code>, perhaps you already improved this by your own function <code>split</code>).</p>\n\n<pre><code>private final static char EXPR_VAR = '$';\nprivate final static char EXPR_START = '{';\nprivate final static char EXPR_END = '}';\nprivate final static char EXPR_SPLIT = ',';\n\npublic static String replaceVariables(final String expression, final Map<String, String> vars) {\n if (expression == null) {\n throw new IllegalArgumentException(\"The expression may not be null!\");\n }\n\n if (vars == null) {\n throw new IllegalArgumentException(\"The vars map may not be null!\");\n }\n\n int firstIndex = expression.indexOf(EXPR_VAR);\n\n if (firstIndex == -1) {\n // nothing to replace, just return the expression\n return expression;\n }\n\n final StringBuffer sb = new StringBuffer();\n String tmpExp = expression;\n int lastIndex;\n String group;\n String parts[];\n\n while (firstIndex != -1) {\n // check if char after '$' is '{'\n if (tmpExp.charAt(firstIndex + 1) != EXPR_START) {\n continue;\n }\n\n // find ending sign '}'\n lastIndex = tmpExp.indexOf(EXPR_END, firstIndex);\n\n if (lastIndex > -1) {\n // complete pattern \"${...}\" found, append previous chars\n sb.append(tmpExp.substring(0, firstIndex));\n\n // get value inside pattern\n group = tmpExp.substring(firstIndex + 2, lastIndex);\n\n if (group.indexOf(EXPR_SPLIT) > -1) {\n // we have a pattern like \"${xxxxx,xxxxxx}\"\n parts = split(group, EXPR_SPLIT);\n\n if (vars.containsKey(parts[0])) {\n sb.append(vars.get(parts[0]).substring(0, Integer.valueOf(parts[1])));\n } else {\n throw new IllegalArgumentException(\"Key [\" + parts[0] + \"] not found in variable map!\");\n }\n } else {\n // we have a pattern like \"${xxxxx}\"\n if (vars.containsKey(group)) {\n sb.append(vars.get(group));\n } else {\n throw new IllegalArgumentException(\"Key [\" + group + \"] not found in variable map!\");\n }\n }\n\n // cut off previous chars from expression\n tmpExp = tmpExp.substring(lastIndex + 1);\n } else {\n // assuming, that if no right parenthesis is found, there is nothing\n // more to replace in this expression. So just get out of here!\n return sb.append(tmpExp).toString();\n }\n\n // find next pattern\n firstIndex = tmpExp.indexOf(EXPR_VAR);\n }\n\n // append rest of expression and return it as String\n return sb.append(tmpExp).toString();\n}\n</code></pre>\n\n<p>With the following example values:</p>\n\n<pre><code>final String expression = \"Hello! This is a ${1} ${0,2} of foo bla.\";\nfinal Map<String, String> vars = new HashMap<>();\nvars.put(\"0\", \"Foo\");\nvars.put(\"1\", \"funny\");\n</code></pre>\n\n<p>I have a benchmark of (1 million replaces):</p>\n\n<pre><code>// Original (yours): 1872 ms\n// Improved (mine): 500 ms\n</code></pre>\n\n<p>So it's a bit more than three times faster than your implementation.\nAnd the more values like <code>{1,3}</code> are in the input expression, the faster it is in relation:</p>\n\n<p>Input:</p>\n\n<pre><code>final String expression = \"${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} ${1} ${0,2} \";\n</code></pre>\n\n<p>Benchmark:</p>\n\n<pre><code>// Original: 17455 ms\n// Improved: 2855 ms\n</code></pre>\n\n<p>So, here it is more than six times faster!</p>\n\n<p>Probably, it can be much more improved. But I just wanted to show you a possible direction so far!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T13:10:07.940",
"Id": "62071",
"Score": "0",
"body": "It works great!. I changed a little bit the code because I realize that it could be ${param1} or ${a.b}, so the key in the Map could be \"a.b\", etc. But it's awesome the improve!."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T13:15:17.713",
"Id": "62072",
"Score": "0",
"body": "With `${param1}` or `${a.b}` it should also work! And with your own split function, it's even faster!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:13:20.063",
"Id": "62086",
"Score": "0",
"body": "Did you checked the last function? it works a little slower to me than your last version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:26:13.303",
"Id": "62093",
"Score": "0",
"body": "Yes, I changed some more code in my function. But if you think, the last version is faster, look at this at: http://codereview.stackexchange.com/revisions/37495/3 :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:49:35.303",
"Id": "37495",
"ParentId": "37487",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37495",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T08:50:56.100",
"Id": "37487",
"Score": "8",
"Tags": [
"java",
"performance",
"strings",
"regex",
"mapreduce"
],
"Title": "Map-reduce implementation for splitting strings"
}
|
37487
|
<p>I have created a small HomeScreen Widget which displays random numbers.
Attached is the code. Please let me know if the approach is good.</p>
<p><a href="https://github.com/gottp/HomeWidgetTest/tree/b8a9a2fee0b76dd5eb70da1e6cf24ffe2977aebe">https://github.com/gottp/HomeWidgetTest</a></p>
<p>MainAppClass.java</p>
<pre><code>package com.example.homewidgettest;
import java.util.HashMap;
import android.app.Application;
public class MainAppClass extends Application{
private static MainAppClass singleton;
/* Maps to hold widget ids */
public HashMap<Integer, Boolean> widgetsMap = null;
public static MainAppClass getInstance() {
return singleton;
}
@Override
public void onCreate() {
super.onCreate();
singleton = this;
widgetsMap = new HashMap<Integer, Boolean>();
}
}
</code></pre>
<p>MyWidgetUpdateService.java</p>
<pre><code>package com.example.homewidgettest;
import java.util.Random;
import java.util.Set;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.RemoteViews;
public class MyWidgetUpdateService extends Service {
Handler h = null;
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (h == null) {
h = new Handler();
h.postDelayed(widgetRunnable, 500);
}
return START_STICKY;
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
}
private Runnable widgetRunnable = new Runnable() {
public void run() {
updateWidgets();
h.postDelayed(widgetRunnable, 2000);
}
};
void updateWidgets() {
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
.getApplicationContext());
Set<Integer> s = MainAppClass.getInstance().widgetsMap.
keySet();
Integer []wids = s.toArray(new Integer[s.size()]);
for (int widgetId : wids) {
// create some random data
int number = (new Random().nextInt(100));
RemoteViews remoteViews = new RemoteViews(this
.getApplicationContext().getPackageName(),
R.layout.widget_layout);
// Set the text
remoteViews.setTextViewText(R.id.update,
"Random: " + String.valueOf(number));
appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
}
}
</code></pre>
<p>MyWidgetProvider.java</p>
<pre><code>package com.example.homewidgettest;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
try {
MainAppClass myapp = MainAppClass.getInstance();
for (int wid : appWidgetIds) {
Integer i = wid;
Log.e("AAA", String.valueOf(i) + "" + myapp.toString() + " " +
myapp.widgetsMap.toString());
myapp.widgetsMap.put(wid, true);
}
if (appWidgetIds.length > 0) {
/* Start a service */
Intent intent = new Intent(context.getApplicationContext(),
MyWidgetUpdateService.class);
context.startService(intent);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
try {
MainAppClass myapp = MainAppClass.getInstance();
for (int wid : appWidgetIds) {
Integer i = wid;
if (myapp.widgetsMap.containsKey(i)) {
myapp.widgetsMap.put(i, false);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
</code></pre>
<p>My questions are:</p>
<ol>
<li>Do you find the implementation ok?</li>
<li>I have used post Delayed instead of AlarmManager. Is this fine?</li>
</ol>
|
[] |
[
{
"body": "<p>Looks like some nice Java! I just have a few comments. (Better late than never? Haha)</p>\n\n<h1>TL;DR</h1>\n\n<ol>\n<li><strong>Better variable names.</strong> Things like <code>h</code>, <code>s</code>, and <code>i</code> don't make for good variable names. Try to be descriptive and to name them for what they actually <em>represent</em>, like <code>widgetMapKeys</code> for your <code>Set</code>. This will make your code much easier to read, and thus more maintainable. (I promise, even if it's just you revisiting your own code six months later, you'll be grateful to yourself.)</li>\n<li><strong>Better and consistent line breaks.</strong> The way you break up long lines into multiple is kind of awkward and muddies up your code. When dealing with this issue, try to perform line breaks where you can keep logical units together rather than arbitrarily throwing them in. Again, this has to do with code readability and maintainability.</li>\n<li><strong>Always encapsulate fields.</strong> If you want to be object-oriented, class fields should be <code>private</code> and accessed through getters and setters. (An exception might be made when using inheritance, but this is a separate concept that has nothing to do with your project.)</li>\n</ol>\n\n<h1>Specific Issues</h1>\n\n<pre><code>@Override\npublic void onCreate() {\n super.onCreate();\n singleton = this;\n widgetsMap = new HashMap<Integer, Boolean>();\n}\n</code></pre>\n\n<p>If you run FindBugs on this, it will generate a warning about assigning a value to a static variable from an instance method. This is a good warning, and it's even more appropriate for a class which is supposed to be a singleton. Using this technique of assigning the <code>instance</code> variable, you must be absolutely sure that <code>onCreate()</code> will be called once and only once. Otherwise, your class isn't really a singleton, and any logic you've created which relies on it being one is subject to bugs.</p>\n\n<pre><code>/* Maps to hold widget ids */\npublic HashMap<Integer, Boolean> widgetsMap = null;\n</code></pre>\n\n<p>You say this is to hold IDs, but what does the Boolean represent? I'm confused why you can't just use a <code>List<Integer></code>.</p>\n\n<pre><code>public class MyWidgetUpdateService extends Service {\n</code></pre>\n\n<p>This is a bit nitpick-y, but I really dislike classes which are named \"MyWhatever\". Try to be more descriptive. In this case <code>WidgetUpdateService</code> might even be sufficient.</p>\n\n<pre><code>Handler h = null;\n</code></pre>\n\n<p>Same thing here. Try to be more descriptive with your variable names.</p>\n\n<pre><code>void updateWidgets() {\n</code></pre>\n\n<p>You should always explicitly declare an access modifier (<code>public</code>, <code>private</code>, or <code>protected</code>) for your methods. (As @Marc-Andre points out in the comments below, there actually is a specific difference between <code>protected</code> and default access. You can read an explanation of the difference on <a href=\"https://stackoverflow.com/a/215505/1435657\">this StackOverflow question</a>. I'm not convinced there's a really good use-case for this, but there you go.)</p>\n\n<pre><code>AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this\n .getApplicationContext());\nSet<Integer> s = MainAppClass.getInstance().widgetsMap.\n keySet();\n</code></pre>\n\n<p>This bit of code is kind of muddy. I get that you're trying to not have the lines stretch out to the right, but there are some better formatting techniques you can use. Also, you should be consistent; on the first line, you break before the <code>.</code> and the method call, but on the second line you break <em>after</em> the <code>.</code>. Whatever you choose to do, at least do it the same way every time.</p>\n\n<p>I'd probably rewrite it like this:</p>\n\n<pre><code>AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(\n this.getApplicationContext()\n);\n\nSet<Integer> s = MainAppClass.getInstance().widgetsMap.keySet();\n</code></pre>\n\n<p>(You actually don't even need to call <code>getApplicationContext()</code> via <code>this</code>, but I kept it to remain consistent with your code.)</p>\n\n<p>There's no need to even wrap the second line of code, since it's approximately the same length as the first (before the line break). Again, I'd also rename your <code>s</code> variable to something more meaningful, like <code>widgetsMapKeys</code> or something. It's also just my particular style to put the closing bracket and semicolon on a separate line when I do this (to me it just looks much cleaner and groups things nicely), but if you hate that you can just end the last indented line with it and still be okay stylistically.</p>\n\n<p>These lines also have one other issue. The <code>widgetsMap</code> variable is accessed directly rather than through a getter and setter. If you're trying to be strictly object-oriented, you should always keep your class's fields <code>private</code> and encapsulate them (e.g., <code>getWidgetsMap()</code>).</p>\n\n<pre><code>Integer []wids = s.toArray(new Integer[s.size()]);\n</code></pre>\n\n<p>This line is a bit awkward, mostly because of the placement of <code>[]</code>. You should really either have <code>Integer[] wids</code> or <code>Integer wids[]</code>. I strongly prefer the first one, but arguments can be made either way.</p>\n\n<pre><code>for (int widgetId : wids) {\n // create some random data\n int number = (new Random().nextInt(100));\n</code></pre>\n\n<p>Why are you creating a <code>new Random()</code> every time you pass through this loop? The only conceivable reason is if you think getting a new seed every time will increase your randomness, but that's not really true. All seeds have an approximately uniform distribution of random numbers. You should really have your <code>Random</code> as a constant, i.e., <code>private static final Random RNG = new Random()</code>.</p>\n\n<pre><code>RemoteViews remoteViews = new RemoteViews(this\n .getApplicationContext().getPackageName(),\n R.layout.widget_layout);\n</code></pre>\n\n<p>Again, this has odd line breaks. I might rewrite it as something like the following:</p>\n\n<pre><code>RemoteViews remoteViews = new RemoteViews(\n this.getApplicationContext().getPackageName(),\n R.layout.widget_layout\n);\n</code></pre>\n\n<p>Also, in this bit of code, what's up with <code>R.layout.widget_layout</code>? I'm not intimately familiar with Android API, but if this is something you coded, you should maintain consistent variable names (<code>widgetLayout</code> versus <code>widget_layout</code>) and encapsulation <code>R.getLayout().getWidgetLayout()</code>).</p>\n\n<pre><code>public class MyWidgetProvider extends AppWidgetProvider {\n @Override\n public void onUpdate(Context context, AppWidgetManager appWidgetManager,\n int[] appWidgetIds) {\n try {\n MainAppClass myapp = MainAppClass.getInstance();\n</code></pre>\n\n<p>Same comments here as above about using <code>MyWhatever</code> for class and variable names. Also, keep variables in camel case (<code>myApp</code>).</p>\n\n<pre><code>catch (Exception e) {\n e.printStackTrace();\n}\n</code></pre>\n\n<p>Can you perform some actual logging here rather than just printing the stack trace to standard out? Also be aware that you're catching <em>all</em> exceptions with this, including runtime exceptions like <code>NullPointerException</code>s, which, in general, should not be caught. It might make sense for a UI to do so, however.</p>\n\n<pre><code>@Override\npublic void onDeleted(Context context, int[] appWidgetIds) {\n try {\n MainAppClass myapp = MainAppClass.getInstance();\n for (int wid : appWidgetIds) {\n Integer i = wid;\n if (myapp.widgetsMap.containsKey(i)) {\n myapp.widgetsMap.put(i, false);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n}\n</code></pre>\n\n<p>I'm still a little confused as to why you're using a <code>Map<Integer, Boolean></code> to store IDs rather than a simple <code>List<Integer></code>. Is there some reason you want to hold on to IDs after they've been deleted? You could simply remove the ID from the <code>List</code> on delete, if not. Just trying to understand, because the simpler you can make your code, the better.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:14:36.217",
"Id": "81533",
"Score": "0",
"body": "`You should always explicitly declare an access modifier (public, private, or protected) for your methods.` not excatly true, sometime package is visibility could be good, but I agree those are rare exceptions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:16:12.030",
"Id": "81534",
"Score": "0",
"body": "@Marc-Andre Do you really mean visibility only to the class's package? If so, `protected` serves that purpose, no? (Obviously this would also expose it to any classes which `extend` it as well.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:19:12.663",
"Id": "81536",
"Score": "0",
"body": "@Marc-Andre Ah, I guess that *is* the difference. Makes sense. I'll edit it into the post. Though I'm not sure of any good use-case for it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:20:48.867",
"Id": "81537",
"Score": "0",
"body": "No I'm talking about the default one, package visibility, where the method is private to everything except all classes in the same package. A good use-case has been for tests(not sure anymore that this is still the case with all the mock framework)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-08T15:03:20.353",
"Id": "46646",
"ParentId": "37488",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T08:51:41.057",
"Id": "37488",
"Score": "8",
"Tags": [
"java",
"android"
],
"Title": "Home screen widget to display random numbers"
}
|
37488
|
<p>I'm new to C# and OO programing.
I have an aspx page with 3 lists of checkboxes and I would like to generate them from the DB.
how should I structure my code?</p>
<p>Here is an example of what I did so far:</p>
<ol>
<li><p>ASPX page</p>
<pre><code><asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
<asp:CheckBoxList ID="CheckBoxList2" runat="server"></asp:CheckBoxList>
<asp:CheckBoxList ID="CheckBoxList3" runat="server"></asp:CheckBoxList>
</code></pre></li>
<li><p>ASPX Code behind:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GenerateCheckBoxList1();
GenerateCheckBoxList2();
}
}
private void GenerateCheckBoxList1()
{
CBLists cbl = new CBLists();
CheckBoxList1.DataSource = cbl.GetCheckBoxList1();
CheckBoxList1.DataTextField = "name";
CheckBoxList1.DataValueField = "id";
CheckBoxList1.DataBind();
}
private void GenerateCheckBoxList2()
{
CBLists cbl = new CBLists();
CheckBoxList2.DataSource = cbl.GetCheckBoxList2();
CheckBoxList2.DataTextField = "country";
CheckBoxList2.DataValueField = "country_id";
CheckBoxList2.DataBind();
}
</code></pre></li>
<li><p>a class file to handle the connection to the db and return the DataSet:</p>
<pre><code>public class CBLists
{
private SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["CONN"].ConnectionString);
public DataSet GetCheckBoxList1()
{
try
{
DataSet ds = new DataSet();
string cmdstr = "select * from table1 where id<>999 order by id";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
adp.Fill(ds);
return ds;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
public DataSet GetCheckBoxList2()
{
try
{
DataSet ds = new DataSet();
string cmdstr = "select * from table2";
SqlDataAdapter adp = new SqlDataAdapter(cmdstr, conn);
adp.Fill(ds);
return ds;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
</code></pre></li>
</ol>
<p>Is this the "correct" way to do it? multiple methods in a separate file?</p>
|
[] |
[
{
"body": "<p>In general for OO programming you separate out code into objects and each object focuses on doing one thing and doing it well.</p>\n\n<p>Each object should then generally have it's own source file in your code tree.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T11:57:34.667",
"Id": "62064",
"Score": "2",
"body": "That's general advice, but you should be reviewing this specific code. Does the posted code follow that advice? If not, how would you improve it?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:50:02.137",
"Id": "37496",
"ParentId": "37493",
"Score": "-1"
}
},
{
"body": "<p>In 3-Layer design, we have below three layers</p>\n\n<p><strong>Presentation Layer:</strong> In this case your aspx and code behind files.</p>\n\n<p><strong>Business Layer:</strong> It seems this is missing in your project. You may include this for various purposes e.g., filtering items based on different scenarios, logged in user, etc.</p>\n\n<p><strong>Data Layer:</strong> This layer interacts with data store, external services, etc. CBLists class in this case.</p>\n\n<p>Also, in OO programming class names are singular so CBLists should be changed to CBList.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:17:59.523",
"Id": "62088",
"Score": "0",
"body": "thank you for your explanation. what about the use of multiple methods for retrieving the dataset? is this the correct way or should I use one generic method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:36:14.017",
"Id": "62124",
"Score": "0",
"body": "I think it depends on requirements, if there are multiple methods required that is okay but if same functionality can be provided using some generic method, it is better. Also, have you looked into Entity Framework, which allows to access data from database in OO form."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:24:56.197",
"Id": "37503",
"ParentId": "37493",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T10:30:06.990",
"Id": "37493",
"Score": "3",
"Tags": [
"c#",
"asp.net"
],
"Title": "3 layer design and multiple dataset"
}
|
37493
|
<p>I am learning <code>getopt</code> in Python to parse and validate command line inputs:</p>
<pre><code>#!/usr/bin/python
'''\nMailing Script
Usage: python script.py -y <year> -c <type_user>"
Arguments:
-y, --year any value from 2008 to 2013
-c, --campaign any value in:
'80c', '80d', 'allowances', 'late_filing',
'exempt_income', 'other_sources'
Flags:
-h help
'''
import sys, getopt
first_yr, last_yr = (2008, 2013)
campaign_type = (
'80c', '80d', 'allowances', 'late_filing',
'exempt_income', 'other_sources',
)
def usage():
print sys.exit(__doc__)
def parse_arguments(argv):
try:
opts, args = getopt.getopt(argv[1:], "y:c:", ["year=", "campaign="])
except getopt.GetoptError:
usage()
for opt, arg in opts:
if opt == '-h':
usage()
elif opt in ("-y", "--year"):
target_year = arg
# customized exception
try:
if not target_year in map(str, range(first_yr, last_yr+1)):
raise Exception()
except:
sys.exit("Argument Error: Invalid year passed. \n"
"One valid year is within (%s, %s)" % (first_yr, last_yr)
)
elif opt in ("-c", "--campaign"):
campaign = arg.lower()
try:
if not campaign in campaign_type:
raise Exception()
except Exception, e:
sys.exit("Argument Error: Invalid 'Campaign type' passed. \n"
"A valid value can be any of %s" % str(campaign_type)
)
# to avoid 'UnboundLocalError' Exception when one argument not passed
try:
target_year, campaign
except UnboundLocalError, u:
usage()
print 'Year : ', target_year
print 'campaign: ', campaign
# return argument values
return (target_year, campaign)
if __name__ == "__main__":
target_year, campaign = parse_arguments(sys.argv)
</code></pre>
<p><sub> Presently I didn't learn <a href="http://docs.python.org/dev/library/argparse.html" rel="nofollow">16.4. argparse</a>. I will learn it in the next step.</sub></p>
<p>I want to improve my script as follows:</p>
<ol>
<li><p>All arguments are mandatory. Presently if the user misses some argument then the script raises an <code>UnboundLocalError</code> exception. I then catch it and call <code>usage()</code>. Is it a correct way? Should I use <code>len(argv)</code> in some ways to handle this? </p></li>
<li><p>I check for correct values of arguments. If any argument value is wrong then I explicitly raise an exception and print an error message in the <code>except</code> clause. I am again not sure whether it's a preferable way to write this kind of code. I feel it adds one more level of nested blocks.</p></li>
</ol>
<p>Some runs of this script:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>$ python opt.py -y 2012 -c 80c
Year : 2012
campaign: 80c
</code></pre>
</blockquote>
<p>Correct as I want:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>$ python opt.py -year=2012
Argument Error: Invalid year passed.
One valid year is within (2008, 2013)
</code></pre>
</blockquote>
<p>I think I should print message something like "insufficient arguments passed" or "use --year=2012 or -y 2012".</p>
|
[] |
[
{
"body": "<p>I think you have too many try/excepts. More than one of them raise and catch their own exceptions. I've made some changes that improves readability.</p>\n\n<p>For clarity the new code created a new exception class and raises it when appropriate. </p>\n\n<p>Also using getopt's own handler for bogus input. The <code>else</code> in the main loop is redundant but it can also serve as a fallback in case you make a mistake by allowing an arg but forget to process it. </p>\n\n<p>Pay attention to the wording:\n<code>if target_year not in map( ...</code></p>\n\n<p>reads better than:\n<code>if not target_year in map( ...</code></p>\n\n<pre><code>#!/usr/bin/python\n'''\\nMailing Script\nUsage: python script.py -y <year> -c <type_user>\"\nArguments:\n -y, --year any value from 2008 to 2013\n -c, --campaign any value in:\n '80c', '80d', 'allowances', 'late_filing', \n 'exempt_income', 'other_sources' \nFlags:\n -h help\n''' \nimport sys\nimport getopt\nfirst_yr, last_yr = (2008, 2013)\ncampaign_type = (\n '80c', '80d', 'allowances', 'late_filing',\n 'exempt_income', 'other_sources',\n)\n\n\nclass ArgumentError(Exception):\n pass\n\n\ndef usage():\n print sys.exit(__doc__)\n\n\ndef parse_arguments(argv):\n target_year = None\n campaign = None\n\n try:\n opts, args = getopt.getopt(argv[1:], \"y:c:\", [\"year=\", \"campaign=\"])\n except getopt.GetoptError as err:\n # print help information and exit:\n print str(err) # will print something like \"option -a not recognized\"\n usage()\n\n for opt, arg in opts:\n if opt == '-h':\n usage()\n\n elif opt in (\"-y\", \"--year\"):\n target_year = arg\n if target_year not in map(str, range(first_yr, last_yr + 1)):\n raise ArgumentError(\"Argument Error: Invalid year passed. \\n \"\n \"One valid year is within (%s, %s)\" % (first_yr, last_yr))\n\n elif opt in (\"-c\", \"--campaign\"):\n campaign = arg.lower()\n if campaign not in campaign_type:\n raise ArgumentError(\"Argument Error: Invalid 'Campaign type' passed. \"\n \"A valid value can be any of %s\" % str(campaign_type))\n else:\n raise ArgumentError(\"Bad argument: I don't know what %s is\" % arg)\n\n if target_year is None or campaign is None:\n raise ArgumentError(\"You need to supply both -y and -c\")\n\n print 'Year : ', target_year \n print 'campaign: ', campaign \n\n # return argument values\n return target_year, campaign\n\n\n\nif __name__ == \"__main__\":\n target_year, campaign = parse_arguments(sys.argv)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:55:45.733",
"Id": "37510",
"ParentId": "37499",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T11:52:47.643",
"Id": "37499",
"Score": "6",
"Tags": [
"python",
"parsing"
],
"Title": "Using getopt parse and validate command line arguments"
}
|
37499
|
<p>In my project i work with COM object via <code>System.Reflection</code>. COM object returns pointer on structure <code>VARIANT</code>, that i cast as <code>object</code> and then i cast one as <code>byte array</code>. There are many structures that i get from COM object. Since i know about how organize these structure i write static class to deserialize them byte-by-byte according to their structure. Because i have many structures with different fields i have many methods: one method for deserialize one structure. Then i write generics method when i call these method depend on some number of structure. Is this correct code organization?</p>
<p>Class:</p>
<pre><code>using SpRReaderSocketServerLib.SpRRecordLib;
using System;
using System.IO;
namespace SpRReaderSocketServerLib.SpRTools
{
/// <summary>
/// Static class for deserialize structures from unmanaged code via BinaryReader and MemoryStream.
/// 1. SPR_MSG_RECORD_START => MSGRecordStart - ok
/// 2. SPR_MSG_RECORD_STOP => MSGRecordStop - ok
/// 3. SPR_MSG_ANI_DETECT => MSGPhoneNumber - ok
/// 4. SPR_MSG_DIALLED_PHONE => MSGPhoneNumber
/// 5. SPR_MSG_RING => MSGRing - ok
/// 6. SPR_MSG_MISSED_PHONE => MSGMissedPhone - ok - for tests
/// </summary>
public static class Deserializer
{
/// <summary>
/// Generic method for deserialize messages.
/// </summary>
/// <typeparam name="T">Struct</typeparam>
/// <param name="msgId">Message Id</param>
/// <param name="msgObject">Message as object</param>
/// <returns>T Struct</returns>
public static T DeserializeMsg<T>(int msgId, object msgObject) where T : struct
{
byte[] bytes = (byte[])msgObject;
switch (msgId)
{
case SpRecordLibTypesW.SPR_MSG_HEADER:
return (T)Convert.ChangeType(DeserializeHeader(bytes), typeof(T));
case SpRecordLibTypesW.SPR_MSG_RING:
return (T)Convert.ChangeType(DeserializeRing(bytes), typeof(T));
case SpRecordLibTypesW.SPR_MSG_RECORD_START:
return (T)Convert.ChangeType(DeserializeRecordStart(bytes), typeof(T));
case SpRecordLibTypesW.SPR_MSG_RECORD_STOP:
return (T)Convert.ChangeType(DeserializeRecordStop(bytes), typeof(T));
case SpRecordLibTypesW.SPR_MSG_ANI_DETECT:
case SpRecordLibTypesW.SPR_MSG_DIALLED_PHONE:
return (T)Convert.ChangeType(DeserializePhoneNumber(bytes), typeof(T));
case SpRecordLibTypesW.SPR_MSG_MISSED_PHONE:
return (T)Convert.ChangeType(DeserializeMissedPhone(bytes), typeof(T));
default:
return default(T);
}
}
/// <summary>
/// Deserialize object with MSGHeader structure.
/// </summary>
/// <param name="message">Message from SpRecord system</param>
/// <returns>MSGHeader</returns>
private static MSGHeader DeserializeHeader(byte[] message)
{
Stream s = new MemoryStream(message);
MSGHeader msgHeader = new MSGHeader();
using (BinaryReader br = new BinaryReader(s))
{
msgHeader.dwMsgSize = br.ReadInt32(); // 4
msgHeader.dwMsg = br.ReadInt32(); // + 4
msgHeader.MsgTime = DateTime.FromOADate(br.ReadDouble()); // + 8
}
return msgHeader; // = 16
}
/// <summary>
/// Deserialize object with MSGRing structure.
/// </summary>
/// <param name="message">Message from SpRecord system</param>
/// <returns>MSGRing</returns>
private static MSGRing DeserializeRing(byte[] message)
{
Stream s = new MemoryStream(message);
MSGRing msgRing = new MSGRing();
using (BinaryReader br = new BinaryReader(s))
{
msgRing.mh.dwMsgSize = br.ReadInt32(); // 4
msgRing.mh.dwMsg = br.ReadInt32(); // + 4
msgRing.mh.MsgTime = DateTime.FromOADate(br.ReadDouble()); // + 8
msgRing.cbChannelName = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_CHANNEL_NAME_CHARS * 2)); // + 48*2
msgRing.dwRingCount = br.ReadInt32(); // + 4
}
return msgRing; // 116
}
/// <summary>
/// Deserialize object with MSGMissedPhone structure.
/// </summary>
/// <param name="message">Message from SpRecord system</param>
/// <returns>MSGMissedPhone</returns>
private static MSGMissedPhone DeserializeMissedPhone(byte[] message)
{
Stream s = new MemoryStream(message);
MSGMissedPhone msgMissedPhone = new MSGMissedPhone();
using (BinaryReader br = new BinaryReader(s))
{
msgMissedPhone.mh.dwMsgSize = br.ReadInt32(); // 4
msgMissedPhone.mh.dwMsg = br.ReadInt32(); // + 4
msgMissedPhone.mh.MsgTime = DateTime.FromOADate(br.ReadDouble()); // + 8
msgMissedPhone.cbChannelName = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_CHANNEL_NAME_CHARS * 2)); // + 48*2
msgMissedPhone.cbPhoneFrom = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_PHONE_NUMBER_CHARS * 2)); // + 48*2
msgMissedPhone.cbSubPhoneFrom = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_SUBPHONE_NUMBER_CHARS * 2)); // + 24*2
msgMissedPhone.cbPhoneTo = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_PHONE_NUMBER_CHARS * 2)); // + 48*2
msgMissedPhone.cbSubPhoneTo = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_SUBPHONE_NUMBER_CHARS * 2)); // + 24*2
}
return msgMissedPhone; // = 400
}
/// <summary>
/// Deserialize object with MSGRecordStart structure.
/// </summary>
/// <param name="message">Message from SpRecord system</param>
/// <returns>MSGRecordStart</returns>
private static MSGRecordStart DeserializeRecordStart(byte[] message)
{
Stream s = new MemoryStream(message);
MSGRecordStart msgRecordStart = new MSGRecordStart();
using (BinaryReader br = new BinaryReader(s))
{
msgRecordStart.mh.dwMsgSize = br.ReadInt32(); // 4
msgRecordStart.mh.dwMsg = br.ReadInt32(); // + 4
msgRecordStart.mh.MsgTime = DateTime.FromOADate(br.ReadDouble()); // + 8
msgRecordStart.cbChannelName = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_CHANNEL_NAME_CHARS * 2)); // + 48*2
msgRecordStart.dwRecordType = br.ReadInt32(); // + 4
msgRecordStart.cbPhoneFrom = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_PHONE_NUMBER_CHARS * 2)); // + 48*2
msgRecordStart.cbSubPhoneFrom = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_SUBPHONE_NUMBER_CHARS * 2)); // + 24*2
msgRecordStart.cbPhoneTo = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_PHONE_NUMBER_CHARS * 2)); // + 48*2
msgRecordStart.cbSubPhoneTo = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_SUBPHONE_NUMBER_CHARS * 2)); // + 24*2
msgRecordStart.cbFileName = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRecordLibTypesW.MAX_PATH * 2)); // + 260*2
}
return msgRecordStart; // = 924
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:15:50.897",
"Id": "62101",
"Score": "0",
"body": "I think that if possible, you shouldn't do this manually. Can you use .Net 4.5.1? It seems to have a [new method](http://msdn.microsoft.com/en-us/library/dn261460) that could help with this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:21:06.860",
"Id": "62102",
"Score": "0",
"body": "I use .NET 4. As to marshalling i have some problem with one, for example all structures are nested and before parse any outer structure i must parse inner structure in order to get type of outer structure. Deserializing via `BinaryReader` good option for me. Everything work fine. I would like to ask about my code."
}
] |
[
{
"body": "<pre><code>int msgId\n</code></pre>\n\n<p>I think it would be better if this was an <code>enum</code>. That way, it's clear what values are acceptable for this parameter.</p>\n\n<pre><code>object msgObject\n</code></pre>\n\n<p>Since this method only accepts <code>byte[]</code>, I think that should be the parameter. It will then be a responsibility of the caller to do the casting.</p>\n\n<pre><code>(T)Convert.ChangeType(DeserializeHeader(bytes), typeof(T))\n</code></pre>\n\n<p>Unless you actually need to perform some conversions here, what you can do is to write just <code>(T)(object)DeserializeHeader(bytes)</code>. This works around the fact that the compiler doesn't know what code to generate for <code>(T)DeserializeHeader(bytes)</code>, because it could be a custom conversion.</p>\n\n<pre><code>default:\n return default(T);\n</code></pre>\n\n<p>I think that this means that the <code>msgId</code> parameter is invalid, so this should be an error and you should throw an exception here.</p>\n\n<pre><code>Stream s = new MemoryStream(message);\n</code></pre>\n\n<p>This variable is very simple and used only in one place, you could inline it: <code>new BinaryReader(new MemoryStream(message))</code>.</p>\n\n<pre><code>msgRing.cbChannelName = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_CHANNEL_NAME_CHARS * 2));\n</code></pre>\n\n<p>Why is this a <code>char[]</code>? Using <code>string</code> would be more natural. To do that, just use <code>GetString()</code> instead of <code>GetChars()</code>. Though that seems to result in <code>string</code> that contains lots of null chars at the end. To fix that, you could use <code>.TrimEnd('\\0')</code>.</p>\n\n<pre><code>msgRing.mh.dwMsgSize = br.ReadInt32(); // 4\nmsgRing.mh.dwMsg = br.ReadInt32(); // + 4\nmsgRing.mh.MsgTime = DateTime.FromOADate(br.ReadDouble()); // + 8\n\nmsgRing.cbChannelName = System.Text.Encoding.Unicode.GetChars(br.ReadBytes(SpRRecordLib.SpRecordLibTypesW.MAX_CHANNEL_NAME_CHARS * 2)); // + 48*2\nmsgRing.dwRingCount = br.ReadInt32(); // + 4\n</code></pre>\n\n<p>You could use object initializer here, something like:</p>\n\n<pre><code>return new MSGRing\n{\n mh =\n {\n dwMsgSize = br.ReadInt32(), // 4\n dwMsg = br.ReadInt32(), // +4\n MsgTime = DateTime.FromOADate(br.ReadDouble()) // +8\n },\n cbChannelName =\n Encoding.Unicode.GetString(\n br.ReadBytes(\n SpRRecordLib.SpRecordLibTypesW.MAX_CHANNEL_NAME_CHARS * 2)), // + 48*2\n dwRingCount = br.ReadInt32() // + 4\n}; // 116\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:16:37.370",
"Id": "62110",
"Score": "0",
"body": "Thank you, svick. I will take into account all of your arguments and fix your code!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:04:07.473",
"Id": "37518",
"ParentId": "37501",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37518",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T13:31:11.650",
"Id": "37501",
"Score": "2",
"Tags": [
"c#",
"generics",
"com"
],
"Title": "VARIANT structure deserialization code organization"
}
|
37501
|
<p>I am working on a (HTML/CSS) website to improve my skills but I am not sure if I am doing it the right way, because I have a lot of floats and sizes. I also need help with some CSS things:</p>
<p>What I have:</p>
<p><img src="https://i.stack.imgur.com/pOMUy.jpg" alt="i.imgur.com/r3VGbWy.png"></p>
<p>What I am Shooting for
<img src="https://i.stack.imgur.com/q11Ca.jpg" alt="WishList Picture"></p>
<p>The red dimensions in the image are the dimensions I've tried to give the objects and which I am not sure if it is the correct way of doing it.
The black words are the things I would like to change in the future, but I need this code reviewed first.</p>
<p>All my code:
INDEX.HTML</p>
<pre><code><div id="wrapper">
<div id="mainContent">
<div id="newsHolder">
<div id="item1">
<img src="img/item1.jpg">
</div>
<div id="item2">
<img src="img/item2.jpg">
</div>
<div id="item5">
<img src="img/item3.jpg">
</div>
<div id="item3">
<img src="img/item4.jpg">
</div>
<div id="item4">
<img src="img/item5.jpg">
</div>
</div>
</div>
<div id="sidebar-right">
<p>sidebar</p>
</div>
<div id="newsList">
<p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>
</div>
</div>
<!--<div id="footer"></div>-->
</code></pre>
<p>STYLE.CSS</p>
<pre><code>@import url(reset.css);
body {
background:#f1f1f1;
}
#fullHeader {
float:left;
min-width:100%;
height:90px;
}
#header {
min-width:100%;
height:60px;
background:#B52B42;
}
#inner-header {
width:1180px;
height:60px;
margin:0 auto;
}
#home {
float: left;
width: 140px;
}
#menubar{
float: left;
width: 1180px;
}
#wrapper {
width:1180px;
margin:0 auto;
-moz-box-shadow:0 0 5px #888;
-webkit-box-shadow:0 0 5px #888;
box-shadow:0 0 5px #888;
}
#mainContent {
width:100%;
float:left;
background-color:#FFF;
}
#newsHolder {
float:left;
width:840px;
height:493px;
}
#item1 {
float:left;
width:477px;
height:320px;
margin-bottom:5px;
}
#item2 {
float:right;
width:358px;
height:244px;
margin-bottom:5px;
}
#item3 {
float:left;
width:236px;
height:167px;
margin-right:5px;
}
#item4 {
float:left;
width:236px;
height:167px;
}
#item5 {
float:right;
width:358px;
height:244px;
}
#item1 img,#item2 img,#item3 img,#item4 img,#item5 img {
width:100%;
height:100%;
}
#sidebar-right {
float:right;
width:340px;
background:#FFF;
}
#newsList {
float:left;
width: 840px;
background:#FFF;
}
#footer {
float:left;
min-width:100%;
height:70px;
background:#006;
}
</code></pre>
<p>I did not post the CSS code of the navigation menu because it is already working correctly.</p>
<p>I would be very happy if anyone can help me make my HTML/CSS cleaner</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:22:53.043",
"Id": "62092",
"Score": "0",
"body": "Code review is not for \"fixing HTML/CSS layout to look correctly\". Code Review is essentially about having working and correct code, then rewriting parts of that code so that you still get the same result but in a better way. Your question is therefore off-topic because it's about *fixing a problem*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:08:06.337",
"Id": "62098",
"Score": "0",
"body": "Keep your CSS as DRY as Possible. you are repeating your width several times. item 3 & 4 differ only by a `margin-right` 2 & 5 by a `margin-bottom` you could add a class to 2 & 5 and then add another class for the margin, I hope that makes sense. then if you want another row you can just repeat. you shouldn't use ID's for those items, because then you can't use that style again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:09:58.067",
"Id": "62099",
"Score": "0",
"body": "you should provide all the html, I don't know what is going on with your Headers, but the CSS for them looks wrong. you should apply the width to the outermost element and then `100%` the elements inside that you want to be the same width."
}
] |
[
{
"body": "<p>instead of using ID's you should be using classes. like this</p>\n\n<pre><code><div id=\"wrapper\">\n <div id=\"mainContent\">\n <div id=\"newsHolder\">\n <div class=\"item1\">\n <img src=\"img/item1.jpg\">\n </div>\n <div class=\"item2\">\n <img src=\"img/item2.jpg\">\n </div>\n <div class=\"item5\">\n <img src=\"img/item3.jpg\">\n </div>\n <div class=\"item3\">\n <img src=\"img/item4.jpg\">\n </div>\n <div class=\"item4\">\n <img src=\"img/item5.jpg\">\n </div>\n </div>\n </div>\n <div id=\"sidebar-right\">\n <p>sidebar</p>\n </div>\n <div id=\"newsList\">\n <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</p>\n </div>\n</div>\n<!--<div id=\"footer\"></div>-->\n</code></pre>\n\n<p>then you could change it a little bit more because you have the same exact CSS for 3 & 4 so I would change those to something like this.</p>\n\n\n\n<pre><code> <div class=\"smallLeft rtMargin\"> <!-- Generic Class Names -->\n <img src=\"img/item4.jpg\">\n </div>\n <div class=\"smallLeft\">\n <img src=\"img/item5.jpg\">\n </div>\n</code></pre>\n\n<pre><code>#smallLeft {\n float:left;\n width:236px;\n height:167px;\n}\n\n #rtMargin {\n margin-right:5px;\n}\n</code></pre>\n\n<p>same concept for items 2 & 5, and remember that CSS executes top to bottom and will overwrite itself if you change an element with two different selectors in different CSS documents or even on the same document it will overwrite the style, the last one will prevail (in that instance)</p>\n\n<hr>\n\n<h2>Something from my Comment</h2>\n\n<p>you should provide all the html, I don't know what is going on with your Headers, but the CSS for them looks wrong. you should apply the width to the outermost element and then 100% the elements inside that you want to be the same width. – Malachi 1 hour ago </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T18:04:36.783",
"Id": "37531",
"ParentId": "37504",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "37531",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:53:03.167",
"Id": "37504",
"Score": "6",
"Tags": [
"html",
"css"
],
"Title": "How to optimize my CSS/HTML webpage?"
}
|
37504
|
<p>I'm using this method from my <code>Downloads()</code> class in a back-end admin system, where these can upload some files, which must be .rar or .zip I'm not to concern about filesize, yet. Eventually, these compressed files, will be holding only .mp3 files.</p>
<p>Well, here's the code. As you can see, I'm checking <code>mimetype</code> against an array of the ones allowed, which I got them from Stack Overflow, but I'm still not sure if I'm not missing any.</p>
<p>Then, I'm checking against the file extension in case <code>mimetype</code> is faked (not sure how accurate this check is).</p>
<p>Are those conditionals OK? I mean, I wouldn't want the file to be uploaded, but the query not to be done, or vice-versa.</p>
<pre><code>//Handle file upload process
public function uploadFile($titulo,$file) {
$accepted_types = array(
'application/zip',
'application/x-zip-compressed',
'multipart/x-zip',
'application/x-compressed',
'application/x-rar-compressed',
);
if (isset($file['name'])) {
$filename = str_replace(' ', '_',$file["name"]);
$tmp_name = $file["tmp_name"];
$type = $file["type"];
$name = explode(".", $filename);
foreach($accepted_types as $mime_type) {
if($mime_type == $type) {
$okay = true;
break;
}
}
//Check mimeType
$continue = (strtolower($name[1]) == 'zip') || (strtolower($name[1]) == 'rar') ? true : false;
if(!$continue) {
return false;
}
$finalPath = DOWNLOAD_PATH.$filename;
if (file_exists($finalPath)) {
$newname= Utility::file_newname(DWONLOAD_PATH,$filename);
$finalPath= DWONLOAD_PATH.$newname;
}
if (move_uploaded_file($tmp_name, $finalPath)) {
$fileSize = filesize($finalPath);
$query = "INSERT INTO descargas (titulo,size,src,filename) VALUES
('$titulo','$fileSize','$finalPath','$filename')";
if ($this->mysqli->query($query)) {
return true;
} else {//The file's been moved, but theere was an error in the query
unlink($finalPath);
return false;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:23:33.287",
"Id": "62104",
"Score": "0",
"body": "Check the second half [of my answer to this question](http://codereview.stackexchange.com/questions/36411/secure-image-upload-class/36457#36457) it deals with various ways to check a file's mime-type"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:21:14.723",
"Id": "62119",
"Score": "0",
"body": "Thank you very much, @EliasVanOotegem I think i'm gonna go with checking the n bytes of the file. Seems to be the most accurate. By the way, what do you think about the last conditional in the method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T07:40:43.067",
"Id": "62220",
"Score": "0",
"body": "There's a couple of issues with that bit of your code: you're using `mysqli`, but you're not using prepared statements. I'd play it safe, and use a prep. stmt. I'd also _not_ use a `die`: you're using `mysqli::query() or die`, so the `else` will never get executed. Besides, `or die` shouldn't be used, except when debugging..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:05:27.937",
"Id": "62307",
"Score": "0",
"body": "@EliasVanOotegem Thank you very much for your answer, I'm using prep stmt(in other methods of same project), but just when the user sends that from an input, is that OK? by the way, I stopped using `or die()` since you told me not to in another question. But, i haven't removed them from the res of my code. Thank you very much again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T07:32:29.353",
"Id": "62439",
"Score": "0",
"body": "Well, I've taken the time to put together a more general review of the code you posted, with some tips and tricks I hadn't discussed in these comments"
}
] |
[
{
"body": "<p>Right, seeing as I could go on and review your code in comments, I'd thought I'd post my comments + extra review in one go instead (after all, that's what this site is for).</p>\n\n<p>Starting from the top:</p>\n\n<pre><code>public function uploadFile($titulo,$file) {\n</code></pre>\n\n<p>A couple of niggles and suggestions</p>\n\n<ul>\n<li>Please try to adhere to the <a href=\"http://www.php-fig.org/\" rel=\"nofollow noreferrer\">PHP-FIG coding standards</a>. They're not official, but there <em>are</em> no official standards. PHP-FIG is subscribed to by all the main players, so it's best you do, too</li>\n<li>The <code>$file</code> argument is central to the entire method. Why isn't it the first argument? Suppose you want <code>$titulo</code> (I'm assuming it means title or something) <em>optional</em>, and default to a string?</li>\n<li>What is <code>$file</code> meant to be? What do you expect it to be? If I am to use your class, I'd like to be able to know what I have to pass to your methods just by looking at their signature.</li>\n</ul>\n\n<p>So, basically, I'd recommend changing your method signature to:</p>\n\n<pre><code>public function uploadFile(array $file, $titulo = 'optional default argument')\n{//brace goes on new line\n}\n</code></pre>\n\n<p>Even that wouldn't be to my liking, though. I should know I'm expected to pass a file, so why not write:</p>\n\n<pre><code>public function uploadFile(\\SplFileInfo $file, $titulo = null)\n{\n}\n</code></pre>\n\n<p>In this case, you can get rid of that <code>if (isset($file['name']))</code> bit, and focus on the stuff that matters.</p>\n\n<p>Next:</p>\n\n<pre><code>$accepted_types = array(\n 'application/zip',\n 'application/x-zip-compressed',\n 'multipart/x-zip',\n 'application/x-compressed',\n 'application/x-rar-compressed',\n);\n</code></pre>\n\n<p>Now every time this method gets called, the array above will be constructed. After the function returns, its ref-count will (or should) be zero, and it'll get GC. If you want to call this method more than once, or if you want to re-use this class for other file manipulations, you should turn this into a property:</p>\n\n<pre><code>class Downloads\n{\n private $accepted_mimes = array(\n 'application/zip',\n 'application/x-zip-compressed',\n 'multipart/x-zip',\n 'application/x-compressed',\n 'application/x-rar-compressed',\n );\n public function uploadFile(\\SplFileInfo $file, $titulo)\n {\n //code here\n }\n}\n</code></pre>\n\n<p>Better yet: define an associative array (this can be a <code>private static</code>, for once) that groups the mime-types into <em>\"modes\"</em>, which you can then use per constant:</p>\n\n<pre><code>class Downloads\n{\n const MIME_MODE_FILE = 1;\n const MIME_MODE_TEXT = 2;\n const MIME_MODE_FOO = 4;//powers of 2, for easy bitwise operations\n\n private static $mime_modes = array(\n self::MIME_MODE_FILE => array(\n 'application/zip',\n 'application/x-zip-compressed',\n 'multipart/x-zip',\n 'application/x-compressed',\n 'application/x-rar-compressed',\n ),\n self::MIME_MODE_TEXT => array(\n //mime-types for text content\n )\n );\n private $mime_mode = null;\n private $accepted = null;\n\n public function __construct($mode = self::MIME_MODE_FILE)\n {\n if (!isset(static::$mime_modes[$mode])) throw new InvalidArgumentException('Invalid mime-mode for '.__CLASS__);\n $this->mime_mode = $mode;\n $this->accepted = static::$mime_modes[$mode];\n }\n}\n</code></pre>\n\n<p>And take it from there. The reason why bitwise operators can come in handy here is that, if I wanted to use your <code>Download</code> class to process text files, but then call a method that was intended for use on non-text files, like archive decompression, you could check the <code>$this->mime_mode</code> property.<br/>\nHowever MS Office documents are, in effect zip files. So a mime-type to accept those would have to accept zip files, too. Thus, the mime-mode to set might have to be <code>Downloads::MIME_MODE_FILE | Downloads::MIME_MODE_TEXT</code><br/>\nOf course, you'll have to work on the constructor in that case, but that's something you can do yourself. It's not that hard.</p>\n\n<p>As for the actual checking of the mime-type: <a href=\"https://codereview.stackexchange.com/questions/36411/secure-image-upload-class/36457#36457\">I've previously linked this answer</a> and discussed various ways to do so. You've decided to play it safe and go for the checking of the first <em>n</em> bytes. That's fine, but never trust the result of a single check, though: always check both the given mime-type, and the bytes, always go <em>\"Double Dutch\"</em>.</p>\n\n<p>Lastly: <code>mysqli_*</code> usage where prepared statements shine in absence.<Br/>\nSure, you say this code will only be called deep in the bowels of your back-end system, and no user input will be used. Call me stupid, but <strong><em>an uploaded file is user input in my book</em></strong>. I haven't got the faintest idea as to what <code>$titulo</code> is, nor do I know what the filenames might look like. Personally, I'd still play it safe and use a prepared statement.<br/>\nIf you feel as if prepared statements will only cause overhead then don't, because <em>prepared statements can be used more than once</em>. You could lazy-load a statement:</p>\n\n<pre><code>class Downloads\n{\n //all of the consts, methods and properties I've previously listed +:\n private $mysqli = null;\n private $stmts = array();\n //then add:\n private function getStatement($queryString)\n {\n if (!isset($stmts[$queryString]))\n {\n $this->stmts[$queryString] = $this->mysqli->prepare($queryString);\n }\n return $this->stmts[$queryString];\n }\n}\n</code></pre>\n\n<p>The prepared statement won't exist until, from the <code>uploadFile</code> method you call:</p>\n\n<pre><code>$stmt = $this->getStatement(\n 'INSERT INTO descargas (titulo,size,src,filename) VALUES\n (?,?,?,?)'\n);\n</code></pre>\n\n<p>The first time this call is executed, you'll create a prepared statement, the following times, you'll just get the same prepared statement returned to you, ready to be used again. So the overhead isn't as big as you might expect it to be.<br/>\nSecurity-wise, however, you'll be better of. And in a way, in terms of traffic between PHP and MySQL, you'll bode well, too: the query string from which the statement is prepared is sent once, for all subsequent <code>execute</code> calls, only the parameters are sent over to the server, via a different protocol, so if you execute this query 20 times or more, you'll possibly end up sending <em>less</em> data to the DB.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T07:31:26.490",
"Id": "37658",
"ParentId": "37505",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37658",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:54:38.830",
"Id": "37505",
"Score": "1",
"Tags": [
"php"
],
"Title": "Checking mimetype and uploading a file"
}
|
37505
|
<p>I have created a list of files using <code>find</code>, <code>foundlist.lst</code>.</p>
<p>The find command is simply <code>find . -type f -name "<search_pattern>" > foundlist.lst</code></p>
<p>I would now like to use this list to find copies of these files in other directories.</p>
<p>The 'twist' in my requirements is that I want to search only for the 'base' of the file name. I don't want to include the extension in the search.</p>
<p>Example:</p>
<p><code>./sort.cc</code> is a member of the list. I want to look for all files of the pattern <code>sort.*</code></p>
<p>Here is what I wrote. It works. It seems to me that there is a more efficient way to do this.</p>
<pre><code>./findfiles.sh foundfiles.lst /usr/bin/temp
#!/bin/bash
# findfiles.sh
if [ $# -ne 2 ]; then
echo "Need two arguments"
echo "usage: findfiles <filelist> <dir_to_search>"
else
filename=$1
echo "$filename"
while read -r line; do
name=$line
# change './file.ext' to 'file.*'
search_base=$( echo ${name} | sed "s%\.\/%%" | sed "s/\..*/\.\*/" )
find $2 -type f -name $search_base
done < $filename
fi
</code></pre>
|
[] |
[
{
"body": "<p>Instead of calling sed twice, you can use Parameter expansion in bash:</p>\n\n<pre><code>search_base=${name%.*}'.*' # Remove everything after the last dot (included).\nsearch_base=${search_base#./} # Remove the leading dot and slash.\n</code></pre>\n\n<p>Keep in mind, though, that some files can have no extension.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:27:50.677",
"Id": "62120",
"Score": "1",
"body": "The two sed scripts perform the following, remove the leading ./, then remove the trailing extension and replace with .*. So I can use the second line of your answer, but not the first. Correct?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:29:09.447",
"Id": "62122",
"Score": "0",
"body": "@KeithSmith: Sorry, my mistake. Fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:11:28.000",
"Id": "37519",
"ParentId": "37511",
"Score": "2"
}
},
{
"body": "<p>In think you can do three things to improve your script(s):</p>\n\n<ul>\n<li>Try to avoid complexity O(N^2)</li>\n<li>Try to reuse intermediate results</li>\n<li>Try to reduce extra process calls</li>\n</ul>\n\n<p>The first aspects comes about because you compare the <em>ALL</em> files in the first directory to <em>ALL</em> files in the second directory. If both directories scale more or less by N you will have a rather slow algorithm for really large directories.</p>\n\n<p>The second aspect relates to calling <code>find</code> again and again instead of calling it once and then using the output of the call for comparison.</p>\n\n<p>The third aspect relates to e.g. calling <code>sed</code> twice in a pipe for something that can be done by the <code>bash</code> itself.</p>\n\n<p>I have prepared a slightly different approach which is far from elegant and/or perfect but which may give you some ideas. The key features are:</p>\n\n<ul>\n<li>It only calls <code>find</code> once for each directory and stores the result in files.</li>\n<li>Instead of a nested loop (with <code>find</code> being the inner loop) it uses <code>sort</code> with complexity O(NlogN) to find the matches.</li>\n<li>It focuses on the basenames of the filenames for comparison. Only for the result the \"long\" names are looked up again.</li>\n</ul>\n\n<p>This is the script:</p>\n\n<pre><code>#!/bin/bash\ndir1=$1\ndir2=$2\n\n# list all files in dir a using format \"filename filepath\"\nfind $dir1 -type f -printf \"%f %p\\n\" > dir1.lst\n\n# sort filename portion alphabetically and append \" 1\" as source\ncat dir1.lst | while read filename filepath\ndo\n echo ${filename%.*}\ndone | sort -u | while read filename \ndo\n echo \"$filename 1\"\ndone > dir1base.lst\n\n# list all files in dir b using format \"filename filepath\"\nfind $dir2 -type f -printf \"%f %p\\n\" > dir2.lst\n\n# sort filename portion alphabetically and append \" 2\" as source\ncat dir2.lst | while read filename filepath\ndo\n echo ${filename%.*}\ndone | sort -u | while read filename \ndo\n echo \"$filename 2\"\ndone > dir2base.lst\n\n# now merge the two lists together; sort them by filename first and by source second\nlast=\"\"\nsort -k 1 -k 2 -u dir1base.lst dir2base.lst | while read filename dir\ndo\n # if we find an entry from source 2 that had the same filename from source 1 just before we have a match\n if [[ $dir -eq 2 && $last == $filename ]] ; then\n # output match\n echo $filename\n fi\n last=$filename\ndone | while read match \ndo\n # now grep for matches in both original files\n echo \"*** File(s)\"\n grep $match dir1.lst\n echo \"*** match file(s)\"\n grep $match dir2.lst\n echo \"---\"\ndone \n</code></pre>\n\n<p>Note that the output loop still has complexity O(M^2) with the inner loop being in the <code>grep</code> call. However, in this case M scales with the number of matches and not the original input size. The former should be considerably smaller.</p>\n\n<p>Also note the first <code>find</code> command will have to be adapted to be more selective than it is now.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T18:05:03.033",
"Id": "37532",
"ParentId": "37511",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37532",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:11:24.697",
"Id": "37511",
"Score": "4",
"Tags": [
"bash",
"file-system"
],
"Title": "Is there a 'better' way to find files from a list in a directory tree"
}
|
37511
|
<p>I am looking for some guidance and optimization pointers for my custom JavaScript function which counts the bytes in a string rather than just chars. The website uses UTF-8 and I am looking to maintain IE8 compatibility.</p>
<pre><code>/**
* Count bytes in string
*
* Count and return the number of bytes in a given string
*
* @access public
* @param string
* @return int
*/
function getByteLen(normal_val)
{
// Force string type
normal_val = String(normal_val);
// Split original string into array
var normal_pieces = normal_val.split('');
// Get length of original array
var normal_length = normal_pieces.length;
// Declare array for encoded normal array
var encoded_pieces = new Array();
// Declare array for individual byte pieces
var byte_pieces = new Array();
// Loop through normal pieces and convert to URL friendly format
for(var i = 0; i <= normal_length; i++)
{
if(normal_pieces[i] && normal_pieces[i] != '')
{
encoded_pieces[i] = encodeURI(normal_pieces[i]);
}
}
// Get length of encoded array
var encoded_length = encoded_pieces.length;
// Loop through encoded array
// Scan individual items for a %
// Split on % and add to byte array
// If no % exists then add to byte array
for(var i = 0; i <= encoded_length; i++)
{
if(encoded_pieces[i] && encoded_pieces[i] != '')
{
// % exists
if(encoded_pieces[i].indexOf('%') != -1)
{
// Split on %
var split_code = encoded_pieces[i].split('%');
// Get length
var split_length = split_code.length;
// Loop through pieces
for(var j = 0; j <= split_length; j++)
{
if(split_code[j] && split_code[j] != '')
{
// Push to byte array
byte_pieces.push(split_code[j]);
}
}
}
else
{
// No percent
// Push to byte array
byte_pieces.push(encoded_pieces[i]);
}
}
}
// Array length is the number of bytes in string
var byte_length = byte_pieces.length;
return byte_length;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-21T10:14:13.340",
"Id": "218513",
"Score": "0",
"body": "[Here](http://stackoverflow.com/questions/5515869/string-length-in-bytes-in-javascript#answer-34920444) is an independent and efficient method to count UTF-8 bytes of a string. Note that the method may throw error if an input string is UCS-2 malformed."
}
] |
[
{
"body": "<p>My 2 cents</p>\n\n<ul>\n<li>Please do not abbreviate words, choose short words or acronyms ( Len -> Length )</li>\n<li>Please lower camel case ( normal_val -> normalValue )</li>\n<li>Consider using spartan conventions ( s -> generic string )</li>\n<li><code>new Array()</code> is considered old skool, consider <code>var byte_pieces = []</code></li>\n<li>You are using <code>byte_pieces</code> to track the bytes just to get the length, you could have just kept track of the length, this would be more efficient</li>\n<li>I am not sure what <code>abnormal pieces</code> would be here: </li>\n</ul>\n\n<p><code>if(normal_pieces[i] && normal_pieces[i] != '')</code></p>\n\n<ul>\n<li>You check again for these here, probably not needed:</li>\n</ul>\n\n<p><code>if(encoded_pieces[i] && encoded_pieces[i] != '')</code></p>\n\n<ul>\n<li>You could just do <code>return byte_pieces.length</code> instead of</li>\n</ul>\n\n<blockquote>\n<pre><code>// Array length is the number of bytes in string\nvar byte_length = byte_pieces.length;\n\nreturn byte_length;\n</code></pre>\n</blockquote>\n\n<p>All that together, I would counter propose something like this:</p>\n\n<pre><code>function getByteCount( s )\n{\n var count = 0, stringLength = s.length, i;\n s = String( s || \"\" );\n for( i = 0 ; i < stringLength ; i++ )\n {\n var partCount = encodeURI( s[i] ).split(\"%\").length;\n count += partCount==1?1:partCount-1;\n }\n return count;\n}\ngetByteCount(\"i ♥ js\");\ngetByteCount(\"abc def\");\n</code></pre>\n\n<p>You could get the sum by using <code>.reduce()</code>, I leave that as an exercise to the reader.</p>\n\n<p>Finally, if you are truly concerned about performance, there are some very fancy performant js libraries <a href=\"http://mothereff.in/byte-counter#i%20%E2%99%A5%20js\">out there</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T18:51:14.147",
"Id": "62131",
"Score": "1",
"body": "Thank you so much, looks like a lot of good stuff in your post. I will give them a go and see if I can get better performance numbers. I am not overly concerned about performance but my original code took ~6 seconds for 1200 iterations of 2400 Euro signs deduced by one char per iteration until I hit 1200 for my enforceMaxByteLength script and this code took ~3.8 so hopefully I can shave off a bit more"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T19:14:13.100",
"Id": "62137",
"Score": "1",
"body": "Your counter proposition is genius, it shaved another .6 seconds off my benchmark, thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T18:35:51.070",
"Id": "37533",
"ParentId": "37512",
"Score": "8"
}
},
{
"body": "<p>It would be a lot simpler to <a href=\"http://en.wikipedia.org/wiki/UTF-8#Description\" rel=\"nofollow noreferrer\">work out the length</a> yourself rather than to interpret the results of <code>encodeURI()</code>.</p>\n<pre><code>/**\n * Count bytes in a string's UTF-8 representation.\n *\n * @param string\n * @return int\n */\nfunction getByteLen(normal_val) {\n // Force string type\n normal_val = String(normal_val);\n\n var byteLen = 0;\n for (var i = 0; i < normal_val.length; i++) {\n var c = normal_val.charCodeAt(i);\n byteLen += (c & 0xf800) == 0xd800 ? 2 : // Code point is half of a surrogate pair\n c < (1 << 7) ? 1 :\n c < (1 << 11) ? 2 : 3;\n }\n return byteLen;\n}\n</code></pre>\n<p>JavaScript implementations may use either UCS-2 or UTF-16 to represent strings.</p>\n<p>UCS-2 only supports Unicode code points up to U+FFFF, and such Unicode characters occupy 1, 2, or 3 bytes in their UTF-8 representation. This is not too tricky to handle.</p>\n<p>However, as @Mac points out, UTF-16 surrogate pairs are a tricky special case. UTF-16 extends UCS-2 by adding support for code points U+10000 to U+10FFFF, which UTF-16 encodes using a pair of code points. The first code point of such a pair (called the "high surrogate") is in the range D800 to DBFF; it should always be followed by another code point (called the "low surrogate") is in the range DC00 to DFFF. Observe that the UTF-8 representation of any character in the range U+10000 to U+10FFFF would take 4 bytes. Therefore, any surrogate pair in UTF-16 would translate to a 4-byte UTF-8 representation. Or, we could say that whenever we encounter half of a surrogate pair (i.e., a code point is in the range from D800 to DFFF), just add two bytes to the UTF-8 length.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T13:23:25.447",
"Id": "62274",
"Score": "0",
"body": "Nice, I saw similar but less clean code on the site I linked to, +1"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T14:24:58.557",
"Id": "62281",
"Score": "0",
"body": "I will give your suggestion a try as well but are the comments on [this site](http://forrst.com/posts/JavaScript_Get_the_exact_size_in_bytes_of_a_st-BZ5) relevant to the use of `charCodeAt()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:44:08.137",
"Id": "62385",
"Score": "2",
"body": "Good question! The code at [forrst.com](http://forrst.com/posts/JavaScript_Get_the_exact_size_in_bytes_of_a_st-BZ5) is bogus. Although `ceil(log_256(charCode))` tells you the number of bytes it would take to represent `charCode`, there's nothing about UTF-8 in their `byteLength()` function. UTF-8 is a variable-length encoding scheme, and the few most-significant bits of every byte are necessary to indicate how many bytes form each character. Since any variable-length encoding scheme will have such padding, their `byteLength()` function gives a wrong answer for any encoding, including UTF-8."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:22:32.437",
"Id": "62465",
"Score": "0",
"body": "Great answer, thank you! My test scenario was chopped down to .1 seconds with your code by the way, compared to ~3.2 respectively for @tomdemuyt , so it is definitely extremely efficient. I just have to wrap my head around these bitwise operators (I've never used them before) and then I can have rock-solid confidence in the script. According to Wikipedia, UTF-8 was ultimately restricted to a max of 4 bytes per char so is checking for 5 and 6 bytes fruitless or do you think UTF-8 will eventually extend to 5 and 6 bytes? I see your shorthand `if` statements will essentially never get to 5 and 6."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:21:30.800",
"Id": "62522",
"Score": "0",
"body": "`1 << n` is simply a way to write 2^n. I think it's easier to understand `1 << n` than the magic numbers 128, 2048, 16384, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:22:08.583",
"Id": "62523",
"Score": "1",
"body": "The 4-byte limit for UTF-8 derives from the decision to [cap Unicode code points to U+10FFFF](http://www.unicode.org/faq/blocks_ranges.html#2). However, it takes no additional effort to add two more cases, so I would code defensively."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-15T16:21:30.190",
"Id": "310689",
"Score": "2",
"body": "getByteLength( '' ) returns 6, but should be 4."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T11:48:11.687",
"Id": "496069",
"Score": "2",
"body": "@Mac Addressed your bug report in Rev 2!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T15:47:16.130",
"Id": "496099",
"Score": "0",
"body": "@200_success - Nice fix! "
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-12-16T23:05:20.857",
"Id": "37552",
"ParentId": "37512",
"Score": "15"
}
},
{
"body": "<p>You can try this:</p>\n\n<pre><code>var b = str.match(/[^\\x00-\\xff]/g);\nreturn (str.length + (!b ? 0: b.length));\n</code></pre>\n\n<p>It worked for me.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-10T11:54:25.247",
"Id": "496070",
"Score": "0",
"body": "This only works for strings that consist solely of code points up to U+03FF. It fails to account for any Unicode characters whose UTF-8 representation requires 3 or more bytes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-11T02:54:16.463",
"Id": "53948",
"ParentId": "37512",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "37552",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:22:08.733",
"Id": "37512",
"Score": "16",
"Tags": [
"javascript",
"performance",
"strings",
"utf-8"
],
"Title": "Count byte length of string"
}
|
37512
|
<p>I am having problem with a simple Hanoi tower program. I need to do something to reduce its time.</p>
<pre><code>#include <stdio.h>
#include <fstream>
using namespace std;
int hanojus(int n, char a, char b, char c) {
ofstream fr("hanoj.out",ios::app);
if (n == 1)
fr<<a<< " -> " <<c<<endl;
else {
hanojus(n-1, a, c, b);
fr<<a<< " -> " <<c<<endl;
hanojus(n-1, b, a, c);
}
}
int main()
{
ifstream fd("hanoj.in");
int sk;
fd>>sk;
hanojus(sk, 'A', 'B', 'C');
}
</code></pre>
|
[] |
[
{
"body": "<p>Try moving the ofstream outside of the method so that you're not creating it every time you make a recursive call.</p>\n\n<p>Like this:</p>\n\n<pre><code>#include <stdio.h>\n#include <fstream>\n\nusing namespace std;\n\nint hanojus(int n, char a, char b, char c, ofstream& fr)\n{\n if (n == 1)\n fr<<a<< \" -> \" <<c<<endl;\n else\n {\n hanojus(n-1, a, c, b, fr);\n fr<<a<< \" -> \" <<c<<endl;\n hanojus(n-1, b, a, c, fr);\n }\n}\n\nint main()\n{\n ifstream fd(\"hanoj.in\");\n ofstream fr(\"hanoj.out\",ios::app);\n int sk;\n fd>>sk;\n hanojus(sk, 'A', 'B', 'C', fr);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T15:02:11.367",
"Id": "37515",
"ParentId": "37514",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>The most efficient is to use non-recursive algorithm.\nYou can read about it in <a href=\"http://en.wikipedia.org/wiki/Tower_of_Hanoi#Non-recursive_solution\" rel=\"nofollow noreferrer\">wikipedia</a>. </p>\n\n<p>Time: <img src=\"https://latex.codecogs.com/gif.latex?%5CTheta%282%5En%29\" alt=\"\"> Same as recursive algorithm</p>\n\n<p>Memory: <img src=\"https://latex.codecogs.com/gif.latex?O%28n%29\" alt=\"\"> Unlike the recursive version, the configuration of the \nrings must be explicitly represented; it suffices to use 3 stacks, each \nholding a maximum of n rings.</p>\n\n<p>Note: to store stack it is better to use <code>std::vector</code> or static array instead of <code>std::stack</code>. </p></li>\n<li><p>You can use C-style io. It often works faster. Do not create output stream each time (if you use recursive algorithm).</p></li>\n<li><p>If you compile your code, use <code>-O2</code> or <code>-O3</code> to create more optimized program.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:33:52.270",
"Id": "62369",
"Score": "0",
"body": "I would be pretty surprised if well used streams are significantly slower than the C family of IO. Potentially relevant: http://stackoverflow.com/a/17468320/567864"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:16:26.070",
"Id": "37627",
"ParentId": "37514",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "37515",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T14:59:14.563",
"Id": "37514",
"Score": "3",
"Tags": [
"c++",
"performance",
"recursion"
],
"Title": "Hanoi towers time exeeded"
}
|
37514
|
<p>Considering the code sample below, which approach of service method design would be considered best-practice and why? The one used in <code>SaveOrder1</code> or the one in <code>SaveOrder2</code>?</p>
<p><strong>UPDATE:</strong> To be clear, I'm <em>not talking about web service here</em>, but application-type-agnostic service class from my business logic layer. I marked parts of code to focus on for this discussion, but included whole example for people to be able to actually try it.</p>
<p><strong>UPDATE 2:</strong> As everyone is obsessed with exceptions, I just want to clarify that Alerts are not only errors. I need to return multiple messages of different importance/type from business logic in my service method, and handling exceptions is not what solves that problem.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Patterns
{
class Program
{
static void Main(string[] args)
{
SaveOrder1();
SaveOrder2();
}
static void SaveOrder1()
{
var order = new Order();
var service = new MyService();
//////////////////////////////////////////////////
// Usage of service method marked as OPTION 1
//////////////////////////////////////////////////
var result = service.SaveOrder(order);
ShowAlerts(result.Alerts);
if (result.Alerts.HasErrors)
return;
Console.WriteLine(result.ReturnedValue);
//////////////////////////////////////////////////
}
static void SaveOrder2()
{
var order = new Order();
var service = new MyService();
//////////////////////////////////////////////////
// Usage of service method marked as OPTION 2
//////////////////////////////////////////////////
AlertCollection alerts;
var orderID = service.SaveOrder(order, out alerts);
ShowAlerts(alerts);
if (alerts.HasErrors)
return;
Console.WriteLine(orderID);
//////////////////////////////////////////////////
}
static void ShowAlerts(IEnumerable<Alert> alerts)
{
foreach (var alert in alerts)
{
Console.WriteLine("{0}: {1}", alert.AlertType, alert.Message);
}
}
}
class MyService
{
// OPTION 1
public ServiceMethodResult<Guid> SaveOrder(Order order)
{
var result = new ServiceMethodResult<Guid>();
if (order.CustomerID == Guid.Empty)
{
result.Alerts.Add(AlertType.Error, "CustomerID missing.");
return result;
}
order.OrderID = Guid.NewGuid(); // Order will get ID when saved...
result.Alerts.Add(AlertType.Success, "Order saved.");
result.ReturnedValue = order.OrderID;
return result;
}
// OPTION 2
public Guid? SaveOrder(Order order, out AlertCollection alerts)
{
alerts = new AlertCollection();
if (order.CustomerID == Guid.Empty)
{
alerts.Add(AlertType.Error, "CustomerID missing.");
return null;
}
order.OrderID = Guid.NewGuid(); // Order will get ID when saved...
alerts.Add(AlertType.Success, "Order saved.");
return order.OrderID;
}
}
class Order
{
public Guid OrderID { get; set; }
public Guid CustomerID { get; set; }
}
class ServiceMethodResult<TResult>
{
public ServiceMethodResult()
{
this.Alerts = new AlertCollection();
}
public TResult ReturnedValue { get; set; }
public AlertCollection Alerts { get; private set; }
}
class AlertCollection : Collection<Alert>
{
public void Add(AlertType alertType, string message)
{
this.Add(new Alert { AlertType = alertType, Message = message });
}
public bool HasErrors
{
get { return this.Count(a => a.AlertType == AlertType.Error) > 0; }
}
}
class Alert
{
public AlertType AlertType { get; set; }
public string Message { get; set; }
}
enum AlertType
{
Error,
Warning,
Success,
Notice
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Honestly I'd rather see a validation routine called first and an exception thrown with validation errors in a custom exception type.</p>\n\n<p>That said, I'm also not a fan of out parameters. So #1 over #2.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:10:52.783",
"Id": "62225",
"Score": "0",
"body": "Hmm... not sure about that. Why? Two reasons: 1. I don't like to use exceptions to control the flow of my business logic. Exceptions are for something exceptional (e.g. couldn't access the database) 2. How would you return an information about success of the operation, or about a warning that didn't prevent the execution, or simply some notification, like \"Order will be shipped in 5 days\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:45:17.097",
"Id": "62227",
"Score": "0",
"body": "I believe has errors is an exceptional case and isn't really flow control. Assuming previous client validations. I would expect the order or Id to be returned on success. Since \"will be shipped in 5 days\" is not really a concern of saving, I would expect another operation to determine this from the state of the returned order."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:25:28.013",
"Id": "62253",
"Score": "0",
"body": "Agreed, shipping info is not something SaveOrder should do, but that is not an important detail now... Imagine a ProcessOrder method which would return a success alert \"order is processed\" and also some additional notice (info about shipping) and maybe even some warning which says \"You are approaching the limit of... something, please consider doing this and that\". Anyway I have an impression that we are loosing focus here. As already said, I need to return multiple messages of different importance/type from my service method and handling exceptions is not what solves my problem here."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T07:58:16.023",
"Id": "37574",
"ParentId": "37516",
"Score": "1"
}
},
{
"body": "<p>I also find the example unclear. But I get a general sense of what you're doing so I can at least speak to the alternatives.</p>\n\n<p>Regarding patterns the for returning application states to the client from a web service, there are really only three approaches from a black box perspective.</p>\n\n<ol>\n<li><p>Use a status enumeration (your approach) on the return object or an 'errors' collection.</p></li>\n<li><p>Use an implicit value: eg, return null for nullable types</p></li>\n<li><p>Use HTTP Status codes and status descriptions</p></li>\n</ol>\n\n<p>I've tried all three, but I'm a proponent of #3 because I typically work with JavaScript / AJAX on the client side and the implication of sending back an HTTP status code is that in the JavaScript you simply implement the error callback or status code conditional code. Since it also removes the status states from the return object, it ends up being cleaner code in the web service as well.</p>\n\n<p>Note: I'm assuming since your question is C# you probably have access to the <code>System.Web</code> and <code>System.Net</code> namespaces - which is where <code>HttpContext</code> and <code>HttpStatusCode</code> reside.</p>\n\n<pre><code>public class MyServiceImplementation : IMyServiceContract\n{\n public BusinessObject DoWork(object parameter)\n {\n BusinessObject returnItem = null;\n\n try\n {\n returnItem = PrimaryBusinessClass.DoWork(parameter);\n }\n catch (ArgumentException ex)\n {\n LogException(ex);\n HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.BadRequest;\n HttpContext.Current.Response.StatusDescription = \"Invalid arguments - [descriptive message]\";\n }\n catch (MyProjectException ex)\n {\n LogException(ex);\n HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.InternalServerError;\n HttpContext.Current.Response.StatusDescription = \"An error occurred in the application code - [message]\";\n }\n catch (Exception ex)\n {\n LogException(ex);\n HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.InternalServerError;\n HttpContext.Current.Response.StatusDescription = \"An unexpected error occurred - [message]\";\n }\n\n return returnItem;\n }\n}\n</code></pre>\n\n<p>What it buys you:</p>\n\n<ol>\n<li>Lighter / Pure return object - Should be exactly what you asked for,\nor empty</li>\n<li>Easier client side debugging - Web debuggers in modern browsers know\nto distinguish between HTTP status codes such as <code>200 (OK)</code>, <code>404</code>, <code>500</code> etc and will surface the message / colorize the response.</li>\n<li>Cleaner service code - Separates your business logic from your web\nresponse messaging and error log messaging.</li>\n<li>Better Exception Handling - Using specific top-level exceptions to\ntrap expected (and unexpected) error states encourages the use of\nproper classifiable exceptions that are thrown from the internal\ncode. This is also significant in that you can use known and custom\nHTTP codes for known application error states.</li>\n</ol>\n\n<p>Just my two cents.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:47:45.920",
"Id": "62228",
"Score": "0",
"body": "Not sure why such focus on exceptions? I'll repeat the comment to a poster above: 1. I don't like to use exceptions to control the flow of my business logic. Exceptions are for something exceptional (e.g. couldn't access the database) 2. How would you return an information about success of the operation, or about a warning that didn't prevent the execution, or simply some notification, like \"Order will be shipped in 5 days\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:52:20.037",
"Id": "62229",
"Score": "0",
"body": "Also the problem with your approach is that you can only get one response. But I want to be able to return multiple alerts to caller of the service method (I'm not implying web service here, but a service class in my application. Notice that the example isn't even a web application)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:16:19.917",
"Id": "62240",
"Score": "0",
"body": "@Anil - Exceptions should *NEVER* be used for flow control. Agreed! But I'm not so sure that's what Michael Smith is doing. He's just handling different kind of exceptional cases."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:29:16.657",
"Id": "62254",
"Score": "0",
"body": "@Max Imagine a ProcessOrder method which would return a success alert \"order is processed\" and also some additional notice (info about shipping) and maybe even some warning which says \"You are approaching the limit of... something, please consider doing this and that\". Why? Because there are a lot of things being checked during order processing and user should be notified. As already said, I need to return multiple messages of different importance/type from business logic in my service method and handling exceptions is not what solves the problem here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:39:15.330",
"Id": "62257",
"Score": "0",
"body": "@Anil - I disagree, if (as in Michael Smith's example) `PrimaryBusinessClass.DoWork(parameter)` would throw an exception as in your usecase of processing an order you would want to deploy a graceful rollback. If, on the other hand, an order process returns with insufficient products in the warehouse for the shipment or if the order process returns with a invalid delivery address - then that's not exceptions and should be returned as they are, which Michael's example adheres to. It's also rarely needed to return multiples failure messages to the user as you want - just return the first one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:44:30.477",
"Id": "62259",
"Score": "0",
"body": "@Max You're not reading what I'm writing here. Alerts are not only failures and errors!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:58:56.820",
"Id": "62263",
"Score": "0",
"body": "@Anil - Read my answer, all of it, and comment under it what you think. If I understood you correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:23:19.307",
"Id": "62296",
"Score": "0",
"body": "Max is correct this isn't an example of flow control using exceptions. \n\nAt the top level of a web service you've already experienced a failed call if an exception has escalated all the way to return point. You don't want the exception message to be thrown all the way back to the client, but you do want to differentiate between categories of failure if it makes sense.\n\nRegardless it sounds like I was barking up the wrong tree."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:13:41.087",
"Id": "37577",
"ParentId": "37516",
"Score": "2"
}
},
{
"body": "<p>Your 1st Option looks better to me, however need some modifictions:</p>\n\n<ul>\n<li>Validate data before sending to service.</li>\n<li><p>Change SaveOrder1 method</p>\n\n<pre><code>if (result.Alerts.HasErrors) {\n ShowAlerts(result.Alerts); \n return;\n}\n</code></pre></li>\n<li><p>move HasErrors to result, rather than Alerts</p></li>\n<li>put business validation on service, like if minimum total should be greater than xxx etc</li>\n<li><p>Change HasErrors to (if you move HasErrors to result, the code will be this.Alerts.Any()</p>\n\n<pre><code>public bool HasErrors\n{\n get { return this.Any(); }\n}\n</code></pre></li>\n<li>wrap your service code in try catch and set \"Unhandled Exception\" with generic message in Alerts</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:38:08.353",
"Id": "62255",
"Score": "1",
"body": "Everyone seems to be obsessed with freaking exceptions :) Alerts.Any() does not mean there are errors in alert collection! Imagine a ProcessOrder method which would return a success alert \"order is processed\" and also some additional notice (info about shipping) and maybe even some warning which says \"You are approaching the limit of... something, please consider doing this and that\". Why? Because there are a lot of things being checked during order processing and user should be notified, not only about failure but also about success and other stuff."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:39:01.637",
"Id": "62256",
"Score": "0",
"body": "If not clear, I need to return multiple messages of different importance/type from business logic in my service method and handling exceptions is not what solves the problem here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:43:25.550",
"Id": "62258",
"Score": "1",
"body": "@Anil you can also post your own answer that says everything you want to hear."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:17:41.357",
"Id": "37581",
"ParentId": "37516",
"Score": "4"
}
},
{
"body": "<p>I find it a bit odd that a method like <code>SaveOrder(..)</code> would return an <code>ServiceMethodResult</code> which has a heavy focus on your Alerts (I know, I know! They are not exceptions...!), as in your first example. I also dislike the <code>out parameter</code> approach. If I were to go with the <code>out parameter</code> approach I would rename it from <code>AlertCollection alerts</code> to something like <code>OrderSuccess</code>.</p>\n\n<p>But both of your examples are not optimal. You shouldn't do all of this in your <code>SaveOrder()</code> method but when placing your order, or even before. </p>\n\n<p>For example; </p>\n\n<ol>\n<li><p>Would you want to know that the item your put in your shopping cart is actually out of stock <em>when you are placing the order</em>? Or would you want to know it before putting it in the shopping cart? This is a check I would do before even allowing the user to put it in the shopping cart (i.e. <code>if(item.Stock == 0) { return OutOfStock; }</code></p></li>\n<li><p>Would you want to know at checkout that the delivery company is unable to deliver to your destination? Or would you want to know before checkout? This is also a check I would do before even allowing the user to checkout.</p></li>\n</ol>\n\n<p>So all of this would be taken care of <em>before</em> invoking <code>SaveOrder()</code>.</p>\n\n<blockquote>\n <p>@Max You're not reading what I'm writing here. Alerts are not only failures and errors! </p>\n</blockquote>\n\n<p>Yes I am. Because if you take care of all the things I mentioned above the only thing you need to take care of in the final step of placing the order is exceptions or returning a message to the user that the order has been placed. In the former its a simple matter of wrapping try/catch around the <code>SaveOrder()</code> function and in the latter it's a simple matter of, well, returning a success message.</p>\n\n<p>There is also hardly any idea to return additional info such as \"stock is running low\" (well, this do depend on what kind of service you are offering), and even if you do find additional info to be valuable to the user you could and should include it in the same message and not divide it into several messages. By dividing it into several messages you are just hassling the user with poor UX and a user is more inclined to read a single message, than several messages.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T12:11:58.617",
"Id": "62265",
"Score": "0",
"body": "Your points about validation before invoking final method are valid. That is something I do for more complex validations, but that doesn't solve the problem still. I want to be able to return multiple alerts (messages) from service method and I have valid reasons for that. Example: First message I add to alerts is message about successfully placed order \"Order Processed\", but then I check and see that customer has placed his 5th order and I move him to higher discount group, so I add second message \"You have placed your 5th order and we moved you to next discount group! Enjoy!\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T12:22:48.023",
"Id": "62267",
"Score": "0",
"body": "What I described is something we do a lot in our application and it works really well. All nested domain service calls, inside one application service method, return their messages (if any) and application service method returns them all together. I didn't want to disclose following for the sake of not pushing comments into one direction, but we are currently using the approach with \"out\" parameter, which I don't like. So I came up with the solution of having a generic ServiceMethodResult class, but wanted to check opinions here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:56:41.137",
"Id": "37586",
"ParentId": "37516",
"Score": "2"
}
},
{
"body": "<p>I can't think of a more appropriate place to have a discussion like this. Here are my thoughts. I prefer Option #2 with a subtle change in the calling convention, like so.</p>\n\n<pre><code> static void SaveOrder2() {\n var order = new Order();\n var service = new MyService();\n AlertCollection alerts;\n Guid? orderID;\n\n ...\n\n if ((orderID = service.SaveOrder(order, out alerts)) == null) {\n ShowAlerts(alerts);\n return;\n }\n\n Console.WriteLine(orderID);\n }\n</code></pre>\n\n<p>The reason I like option #2 is because it is more concise. It lets you get rid of the <code>ServiceMethodResult</code> class all together and keeps your success or failure logic based on whether an OrderID has successfully been assigned, period. It doesn't rely on a LINQ statement that checks for the existence of a message type flag in a collection. I think that the code behind saving an order should be as atomic and clear as possible. I'm not sure I agree with the Guid thing, but that isn't really the question.</p>\n\n<p>Come to think of it, if your alerts are really being used as progress indicators and not just errors, I would think about using <code>ref</code> instead of <code>out</code> to pass it throught the rest of your processes. But again, that doesn't really change the design pattern. In C++ returning a <code>bool</code> or a numeric value while also passing in pointer(s) to class instance(s) as function arguments is an EXTREMELY common pattern. My guess is, that is why they put out and ref parameters into the .NET framework. It certainly wasn't for speed.</p>\n\n<p>I hope this is the kind of critiquing you were looking for. Take care!</p>\n\n<p><strong>Update from discussion</strong></p>\n\n<p>This is an example pattern that you could use if you implement <code>ref</code>. I created a fictitious scenario for a complex ordering process. This was written straight into the text window without any real functional analysis. So, please think of it as a rough pseudo-code design with lots of room for changes. But, it does accommodate atomicity and heavily exploits the encapsulation features provided by the language.</p>\n\n<p><strong>Update #2</strong> - notice that now you can create as many different types of models as you want without ever having to create new AlertCollection instances by hand. They are already there.</p>\n\n<ul>\n<li>Added <code>ModelBase</code> class</li>\n<li>Added <code>SomeOtherModel</code> class that derives from <code>ModelBase</code></li>\n<li>Changed <code>Order</code> class to also derive from <code>ModelBase</code></li>\n<li>Added <code>SomeOtherModel</code> instance in the <code>Main</code> method</li>\n</ul>\n\n\n\n<pre><code>static void Main(string[] args){\n var order = new Order();\n var model = new SomeOtherModel();\n order.GetOrderDetails(); // Fill the order with all the order info. shirt sizes etc...\n\n //----------------------------------------------\n // This abstracts the whole order save process \n // from the caller. It either worked or it didn't.\n //----------------------------------------------\n if(!order.Save()) {\n // react to failed order process\n // you can access order.Alerts\n }\n else {\n // do whatever is next\n // you can also access order.Alerts\n }\n\n // View seperate Alerts collections\n Console.WriteLine(order.Alerts.Count);\n Console.WriteLine(model.Alerts.Count);\n}\n\n//----------------------------------------------\n// Use as base class for all Models\n//----------------------------------------------\ninternal class ModelBase{\n public AlertCollection Alerts = new AlertCollection();\n ...\n // Add abstract or virtual methods and properties for anything \n // that ALL models should do or have to prevent duplicating code.\n}\n\npublic class SomeOtherModel : ModelBase {\n public SomeOtherModel(){\n Alerts.Add(AlertType.Notice, \"SomeOtherModel instance created successfully.\");\n }\n\n ...\n}\n\n//----------------------------------------------\n// By making the Alerts collection part of \n// the ModelBase, it will automatically be \n// created for any class that inherits from it.\n// Notice that the Alerts collection is no longer \n// declared in the Order class.\n//----------------------------------------------\npublic class Order : ModelBase {\n public Guid OrderID { get; set; }\n public Guid CustomerID { get; set; }\n\n ...\n ...\n\n //----------------------------------------------\n // The Save() function clearly outlines the steps \n // carried out in the complex save procedure\n //----------------------------------------------\n public bool Save(){\n if (!PreValidate())\n return false;\n if (!ProcessPayment())\n return false;\n if (!SaveToDatabase())\n return false;\n if (!ReserveInventory())\n return false;\n if (!SendConfirmEmail())\n return false;\n\n return true;\n }\n\n //----------------------------------------------\n // These functions call the OrderSave() method of each \n // IOrderServiceProvider. Obviously, 'ref this' can't \n // pass a null value.\n //----------------------------------------------\n private bool PreValidate() {\n return new ValidationService().OrderSave(ref this)\n }\n\n private bool ProcessPayment() {\n return new PaymentService().OrderSave(ref this)\n }\n\n private bool SaveToDatabase() {\n return new DataService().OrderSave(ref this)\n }\n\n private bool ReserveInventory() {\n return new InventoryService().OrderSave(ref this)\n }\n\n private bool SendConfirmEmail() {\n return new MessagingService().OrderSave(ref this)\n }\n\n ...\n}\n\n//----------------------------------------------\n// Simple interface for complex processes involved with \n// processing orders. All implementations have access \n// to the order that they work on, including the order.Alerts \n// collection\n//----------------------------------------------\npublic interface IOrderServiceProvider{\n bool OrderSave(ref Order order);\n // bool OrderPutOnBackOrder(ref Order order);\n // bool OrderUpdateFulfillmentStatus(ref Order order);\n // etc...\n}\n\n//----------------------------------------------\n// Encapsulates business rules for validating \n// the quality of order information.\n//----------------------------------------------\npublic class ValidationService : IOrderServiceProvider {\n private Order m_order = null;\n\n public bool OrderSave(ref Order order){\n m_order = order;\n return this.ValidateOrderContents(); \n }\n\n ...\n}\n\n//----------------------------------------------\n// Encapsulates all functions related to inventory \n// management.\n//----------------------------------------------\npublic class InventoryService : IOrderServiceProvider {\n private Order m_order = null;\n\n public bool OrderSave(ref Order order){\n m_order = order;\n return this.ReserveInvetory(); \n }\n\n ...\n}\n\n//----------------------------------------------\n// Encapsulates all functions related to processing\n// payments\n//----------------------------------------------\npublic class PaymentService : IOrderServiceProvider {\n private Order m_order = null;\n\n public bool OrderSave(ref Order order){\n m_order = order;\n return this.ProcessOrderPayment(); \n }\n\n ...\n}\n\n//----------------------------------------------\n// Encapsulates all functions that modify the \n// Orders database during order-level processes\n//----------------------------------------------\npublic class DataService : IOrderServiceProvider {\n private Order m_order = null;\n\n public bool OrderSave(ref Order order){\n m_order = order;\n\n if(!this.SaveToDataBase()){\n order.Alerts.Add(AlertType.Error, \"Unable to save order\");\n return false;\n }\n\n return true;\n }\n\n private bool SaveToDataBase(){\n // SQL Stuff pseudo-code\n BeginTransaction();\n //----------------------------------------------\n // Assign db info to order.\n //----------------------------------------------\n if(ExecuteSaveCommand(m_order.Fields)){\n CommitTransaction();\n order.OrderID = result[\"OrderID\"];\n order.CustomerID = result[\"CustomerID\"];\n return true;\n }\n else{\n RollbackTransaction();\n return false;\n }\n }\n\n ...\n}\n\n//----------------------------------------------\n// Encapsulates all functions related to process\n// messaging.\n//----------------------------------------------\npublic class MessagingService : IOrderServiceProvider {\n private Order m_order = null; \n\n public bool OrderSave(ref Order order){ \n m_order = order; \n return this.SendOrderConfirmationEmail();\n }\n\n ...\n}\n</code></pre>\n\n<p>\nNow, you have an Order class that <strong>is</strong> a Model and also consumes IOrderServiceProvider classes that <strong>do</strong> order-specific functions.</p>\n\n<p><strong>Encapsulation, Inheritance, Polymorphism</strong> ... that's all I'm sayin' here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:11:19.530",
"Id": "62453",
"Score": "0",
"body": "Now that's a constructive answer :) Thanks! Regarding `ref`, I did use it in the beginning, but decided to use `out` exclusively to avoid checking for `null` in every method and instantiating alerts collection conditionally. Also I might accidentally replace it with new collection and loose previously collected alerts. By using `out` compiler forces me to instantiate new collection, and method doesn't have to care about outside world."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:20:14.600",
"Id": "62456",
"Score": "0",
"body": "That being said, I somehow felt it is a bit cumbersome to explicitly declare variable with type and then pass it to the method. Also, inside the application service methods, when I call domain services, I have to declare multiple alerts variables and deal with their names. That's why I came up with this \"almighty result\" thing. It somehow feels more fluent. But there are pros and cons on every side :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:35:34.653",
"Id": "62458",
"Score": "0",
"body": "One more thing, I'm passing the alerts back to caller regardless of success of called method. If it didn't succeed then alerts will show the reasons in form of error messages (as much as possible at once to avoid frustration of submitting 5 times just to find out that 5 fields were not ok). On the other side, if it was successful, alerts will contain confirmation message and any possible additional notice or warning (by warning I assume a condition which did not prevent the execution, but user should be warned about the state of affairs)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:59:12.783",
"Id": "62545",
"Score": "0",
"body": "Those are all valid points. In the end it's totally up to you. But, it does sort of seem that your last comment argues for implementing the `ref` parameter. The beauty of a pattern is that it repeats itself. You only have to create the `AlertCollection` once. You don't have to check for null because your can't pass `ref null`. I'll update my answer with what I mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:46:30.437",
"Id": "62577",
"Score": "0",
"body": "What I should have said in my last comment was... You don't have to check for null because your design doesn't facilitate it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T10:25:13.597",
"Id": "62622",
"Score": "0",
"body": "You're right, with `ref` I can enjoy a comfort of having only one collection and avoid instantiating new one in each method. Also, checking for null can be avoided by having the collection newed-up as a property. However, since I'm trying to have the pattern usable for many other scenarios, I'd have to add alerts collection to many (if not all) model classes, which, I'm afraid, would pollute the model."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T10:27:05.120",
"Id": "62624",
"Score": "0",
"body": "Anyway, thanks a lot for constructive feedback! In essence, I admit I'm leaning towards the solution with generic result class containing both the method result and any alerts, but wanted to ask for opinion here to make sure I'm not overseeing some major flaw in that design ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T22:23:40.320",
"Id": "62754",
"Score": "0",
"body": "No problem @Anil. My goal isn't to be right or wrong. I'm just trying to get you to favor OOP principles when solving problems related to **does** or **is** issues. Generally, when you want **unrelated** classes to implement a common behavior, an interface will solve the problem. Whenever you want **related** classes to implement a common behavior, inheritance is the solution. Look at my updated answer to see an example that solves the problem you just described."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T09:48:23.333",
"Id": "62875",
"Score": "0",
"body": "I'll have to test this approach in practice to see how it \"feels\" and if it fits into picture better than my generic result class. For now I'll mark this as answer, as you were the only one who really understood the question and provided a good discussion concerning pros/cons of different approaches. Cheers!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T15:39:23.560",
"Id": "62897",
"Score": "0",
"body": "@drankin2112: As you seem to have only made so many edits to help the OP (eventually leading to an accept), not to excessively bump the question for attention, I'll lift the wiki status. Please do try make your edits as substantial as possible to help keep them to a minimum."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:33:41.583",
"Id": "37607",
"ParentId": "37516",
"Score": "1"
}
},
{
"body": "<p><strong>SaveOrder2 is better in this case.</strong></p>\n\n<p>We use out parameter when we try to do something and return value indicates whether the method succeeded or not, so we don't have to make null checks, etc. on the variables returned/set by the method.</p>\n\n<p>Also, the code is relatively clean and more readable.</p>\n\n<pre><code>var orderID = service.SaveOrder(order, out alerts);\n\nif(orderID.HasValue)\n{\n Console.WriteLine(orderID);\n}\nelse\n{\n ShowAlerts(alerts);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:25:48.330",
"Id": "62457",
"Score": "0",
"body": "Thanks for the answer. One issue with this approach is that alerts are not passed to caller/user if everything is fine, and alerts in that case contain one or more messages for the user (e.g. one success message, and one notice about moving customer to new discount group due to his Xth order). So basically by alerts I don't assume just errors, but also success statuses and different notices and warnings that did not prevent successful execution of the method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:30:06.703",
"Id": "62466",
"Score": "0",
"body": "It is just about the structure of the code. We can execute `ShowAlerts(alerts)` in both `if` and `else` block. Also, if there is some specific code that we have to execute either in case of success or failure, we can write that in the corresponding block."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:05:56.990",
"Id": "37625",
"ParentId": "37516",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37607",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T16:59:00.513",
"Id": "37516",
"Score": "4",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Which pattern to choose for passing alerts from service method back to user?"
}
|
37516
|
<p>Here is my attempt at <a href="https://codereview.meta.stackexchange.com/q/1245/9357">Weekend Challenge #3</a>.</p>
<p>Out of scope:</p>
<ul>
<li>It only will do 9*9</li>
<li>It will stop at the first solution</li>
<li>Could have been smarter at re-using the cache when recursively calling <code>solveGrid</code></li>
<li>I ignored OO as this is not an app, but a simple script</li>
</ul>
<p>In scope:</p>
<ul>
<li><code>Bitflags</code> & cache for pencil marks</li>
</ul>
<p></p>
<pre><code>var grid = "...84...9\n" +
"..1.....5\n" +
"8...2146.\n" +
"7.8....9.\n" +
".........\n" +
".5....3.1\n" +
".2491...7\n" +
"9.....5..\n" +
"3...84...";
var N = 3, //Changing N wont do much, solvedValues would have to be updated as well
impossible = 511, //parseInt("111111111",2)
solvedValues =
{
510 : 1, //parseInt("111111110",2)
509 : 2, //parseInt("111111101",2)
507 : 3, //parseInt("111111011",2)
503 : 4, //parseInt("111110111",2)
495 : 5, //parseInt("111101111",2)
479 : 6, //parseInt("111011111",2)
447 : 7, //parseInt("110111111",2)
383 : 8, //parseInt("101111111",2)
255 : 9 //parseInt("011111111",2)
};
/* Create a grid array from a string */
function createGrid( s )
{
return s.split("\n").map( function(v)
{
return v.split("").map( function(v)
{ //Each cell is an array [value, pencilmarks as binary bitflag ]
return [v=="."?0:v*1,0]; //Dots or 0 are accepted as blanks
});
});
}
/* Create a string from a grid array */
function createString( grid )
{
return grid.map( function(row){ return row.map( function(v){ return v[0]; } ).join(""); } ).join("\n");
}
/* Determine which 3*3 zone a given location belongs to */
function deriveZone( x , y )
{
return Math.floor( x / N ) * N + Math.floor( y / N );
}
/* Create a cache, to make addToCache cleaner, I preset the values to 0 */
function Cache()
{
this.rows = []; /* What numbers are already used in a given row */
this.cols = []; /* What numbers are already used in a given column */
this.zones = []; /* What numbers are already used in a given zone */
for( var i = 0 ; i < N*N ; i++ )
{
this.rows.push(0);
this.cols.push(0);
this.zones.push(0);
}
}
/* Add a data point to the cache */
function addToCache( cache , x , y , value )
{
value--; // Value 1 would be shifting 0 times to the right etc.
cache.rows[x] |= 1 << value;
cache.cols[y] |= 1 << value;
cache.zones[deriveZone( x , y )] |= 1 << value;
}
/* Collect a cache of all numbers, assign them to their respective rows and columns */
function buildGridCache( grid )
{
var cache = new Cache(), x, y ,value;
for( x = 0 ; x < N*N ; x++ )
for( y = 0 ; y < N*N ; y++ )
if( value = grid[x][y][0] )
addToCache( cache, x , y , value );
return cache;
}
/* Cache what we know, analyze each cell in the grid, see if anything comes up */
function solveObvious( grid , cache)
{
var redo, x, y;
if( !cache )
cache = buildGridCache( grid );
for( x = 0 ; x < N*N ; x++ )
for( y = 0 ; y < N*N ; y++ )
if( !grid[x][y][0] )
{
grid[x][y][1] |= cache.rows[x] | cache.cols[y] | cache.zones[ deriveZone(x,y) ];
grid[x][y][0] = solvedValues[ grid[x][y][1] ] || 0;
if( grid[x][y][0] )
{
addToCache( cache , x , y , grid[x][y][0] );
redo = true;
}
else if( grid[x][y][1] == impossible )
return false;
}
if(redo)
solveObvious( grid , cache );
return true;
}
/* Is there a cell that still has value 0 ? */
function findUnsolved( grid )
{
var x, y ;
for( x = 0 ; x < N*N ; x++ )
for( y = 0 ; y < N*N ; y++ )
if(!grid[x][y][0] )
return grid[x][y];
}
/* Solve the grid, if solving all obvious cells is not enough, try recursive guessing */
function solveGrid( grid )
{
var possible = solveObvious( grid ),
unsolved = findUnsolved( grid ),
newGrid, i;
if( possible && !unsolved )
return grid;
if( unsolved )
for( i = 0 ; i < N*N ; i++ )
if( unsolved[1] != ( unsolved[1] |= 1<<i ) && ( unsolved[0] = i+1 ) )
if( newGrid = solveGrid( JSON.parse( JSON.stringify( grid ) ) ) )
return newGrid;
return false;
}
/* Parse a grid string, return a grid string if the grid is solved */
function solve( s )
{
var grid = solveGrid( createGrid( s ) );
return grid?createString( grid ):"The puzzle is unsolvable: it has no solution";
}
/* Test case */
console.log( solve( grid ) );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:35:34.093",
"Id": "62172",
"Score": "0",
"body": "Heh, tried to make it report \"unsolvable\", but it actually solves a completely blank grid without complaining :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:42:39.057",
"Id": "62173",
"Score": "0",
"body": "+1 for a nice script by the way. I would've preferred an object literal like `{value: ..., bitmask: ...}` for the individual cells, just for readability"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T01:25:52.760",
"Id": "62176",
"Score": "0",
"body": "I +1'd just for the creative title :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:52:29.813",
"Id": "62299",
"Score": "1",
"body": "I tried an unsolveable grid which was empty except for the first value in the first to rows were both 1. It hung my browser. >.>"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:27:47.563",
"Id": "62962",
"Score": "0",
"body": "I almost feel like starting a bounty on that one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T13:23:38.033",
"Id": "63153",
"Score": "0",
"body": "@retailcoder Too late."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T13:44:44.230",
"Id": "63154",
"Score": "0",
"body": "@SimonAndréForsberg good!"
}
] |
[
{
"body": "<p>All in all, an interesting approach to the problem, and seeing JavaScript used in such an efficient way is a pleasure (stick it to all those people who think JavaScript is ... ).</p>\n\n<p>I have the following small criticisims of the code (nothing can be perfect, right?)...</p>\n\n<h2>Variables</h2>\n\n<ul>\n<li>You declare <code>var N = 3</code> but:\n<ul>\n<li>N is a poor variable name choice. In this case, it represents a 'zone dimension'. A name something like <code>ZONESIZE</code> would be better</li>\n<li>all references to <code>N</code> (except 1 line) perform the square of <code>N*N</code>. <code>N</code> and <code>N*N</code> are effectively constants... you should have a second global variable <code>GRIDSIZE = ZONESIZE * ZONESIZE</code>, and then replacing all the <code>N*N</code> with <code>GRIDSIZE</code> would be better.</li>\n</ul></li>\n<li>your Cache class consists of rows, columns, and zones, but, when you access the multi-dimensional arrays containing the Cache (and other data), you use variables called <code>x</code> and <code>y</code>. I personally like short variable names like this, but I would choose <code>r</code> and <code>c</code> instead. many lines would be affected by this, for example, <code>if( value = grid[x][y][0] ) ...</code> would become <code>if( value = grid[r][c][0] ) ...</code>. Similarly, <code>cache.rows[x] |= 1 << value;</code> becomes <code>cache.rows[r] |= 1 << value;</code></li>\n</ul>\n\n<h2>Details</h2>\n\n<ul>\n<li>in your <code>createGrid</code> function, you nested-map the string input to the multi-dimensional grid output. This method is 'elegant', but I would prefer the more explicit numeric conversion of the String to a Number. You do <code>n*1</code> for the conversion, but <code>Number(n)</code> would be more structured. Also, putting a space after the array-member comma (and other places) would make it more readable, the line <code>return [v==\".\"?0:v*1,0];</code> becomes <code>return [v == \".\" ? 0 : Number(v), 0];</code> (P.S. re-reading this comment, I count 11 characters of 'punctuation' in that line - <code>[==\"\"?:*,];</code> , and just 6 characters of 'value' - <code>v.0v10</code>)</li>\n<li>in your <code>createString</code> method, which converts the solution back to a String, you should use the same form of indenting that you use in the <code>createGrid</code> method. Writing it all as a 1-liner is not helpful.</li>\n<li>in <code>deriveZone</code> ... see my comment about <code>N</code>, which should be <code>ZONESIZE</code> or some better-named variable. As an aside, it may be a nice option to pre-compute the zones for a row/column combination in a separate 2D array, and then your method can become a simple <code>return zone[x][y];</code></li>\n<li>in <code>buildGridCache</code> you have the line <code>if( value = grid[x][y][0] )</code>. I <strong>know</strong> this is logically correct, but, the multiple levels of logic here, the assignment, as well as the logical condition of the assignment are more complicated than should be present on a 1-liner. Visibly it looks like a 'classic' bug pattern. Even though it is redundant, I would prefer to make the different 'stages' of execution more visible, say <code>if( (value = grid[x][y][0]) != 0 )</code>, or <code>value = grid[x][y][0];</code> and <code>if (value) ...</code></li>\n<li>in <code>solveObvious</code> you 'fake' a data structure in the grid by having a 2-member array in the last dimension. The first member of the array is the 'solution value', and the second member is the 'pencil marks'. You repeatedly reference these two members as <code>grid[x][y][0]</code> and <code>grid[x][y][1]</code> respectively. These 0 and 1 constants (magic numbers) should be decalred as 'globals' with a meaningful name, like <code>grid[r][c][SOLUTION]</code> and <code>grid[r][c][PENCIL]</code></li>\n</ul>\n\n<p>All in all, the only things i can find to criticize are some naming conventions, formatting, and some pedanticness that is really minor. It's a great solution to the problem. Thanks</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T15:44:23.060",
"Id": "63273",
"Score": "0",
"body": "Some very good stuff there, most appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T00:02:16.647",
"Id": "63588",
"Score": "0",
"body": "@tomdemuyt I think this deserves a checkmark :p"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-24T15:36:49.020",
"Id": "38034",
"ParentId": "37517",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "38034",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:02:03.753",
"Id": "37517",
"Score": "10",
"Tags": [
"javascript",
"recursion",
"sudoku",
"community-challenge"
],
"Title": "Sudoku solver: pencil marks & recursive patience"
}
|
37517
|
<p>Project contains 3 classes:</p>
<pre><code>/*************************************************************************************
The purpose of this project is to create 3 classes. Pile contains the number of marbles
in a randomly generated pile, and also a remove method to determine how many marbles are
to be removed. The player class determines the behavior of each type of player. There are
three types of players. Simple computer, Smart computer, and Human. These are all of enum
type. The program will use a randomly generated number to determine who goes first and
which level of skill the computer player is set at. Each player will draw a number of marbles
from the pile until the pile reaches 1. Whoever pulls the last marble will lose.
A player must choose between 1 and half the remaining pile.
***************************************************************************************/
</code></pre>
<p><strong>Game</strong></p>
<pre><code>import java.util.*;
public class Game {
private static void printHeading(int projectNum, String projectName){ //creates an identifier method.
System.out.println("Chris Olson");
System.out.println("CMSC 255-002, Spring 2013");
System.out.println("Project " + projectNum);
System.out.println(projectName);
System.out.println();
}
public static void main(String[] args) {
printHeading(8,"Nim");
Scanner in = new Scanner(System.in);
Pile marbles = new Pile(); //creates initial Pile object
//Sets variables and objects to enum type
int marblesToRemove = 0;
Player humanPlayer = new Player(Player.Type.HUMAN);
Player compPlayer = new Player(Player.Type.SMART_COMPUTER);
Player secondPlayer = new Player(Player.Type.HUMAN);
Player firstPlayer = new Player(Player.Type.HUMAN);
Random randomNum = new Random(); //creates new random object to generate random numbers
int selection = 0;
//Interface
System.out.println("**************WELCOME TO THE GAME OF NIM******************");
System.out.println();
System.out.println();
System.out.println("******************RULES OF THE GAME***********************");
System.out.println("--The number of marbles in the initial pile will be random amount between 10 and 100.");
System.out.println("---Each player must choose between 1 and half of the remaining pile of marbles to remove.");
System.out.println("----The player stuck with the last marble loses the game.");
System.out.println("---The computer will randomly be placed into simple or smart mode randomly.");
System.out.println("--The player who goes first will also be chosen at random.");
System.out.println();
System.out.println("Enter 1 to play against another human or 2 to play against a computer.");
System.out.println("Enter 3 if you would like 2 computers to play against each other.");
selection = in.nextInt();
//Generates a random number between 1-2 to determine whether computer is set to smart of simple mode
if(randomNum.nextInt(2) == 1){
compPlayer.setType(Player.Type.SMART_COMPUTER);
System.out.println("Computer is set to Smart mode.");
}
else{
compPlayer.setType(Player.Type.SIMPLE_COMPUTER);
System.out.println("Computer is set to Simple mode.");
}
if(selection == 1){
compPlayer = humanPlayer;
}
else if(selection == 2) compPlayer = compPlayer;
else if(selection == 3) humanPlayer = compPlayer;
//Generates a random number between 1-2 to determine who goes first
if(randomNum.nextInt(2) == 1){
System.out.println("The user may go first.");
firstPlayer = humanPlayer; //sets player order
secondPlayer = compPlayer;
}
else{
System.out.println("The computer will go first.");
firstPlayer = compPlayer; //sets player order
secondPlayer = humanPlayer;
}
System.out.println();
System.out.println("Initial pile contains " + marbles.getMarbles() + " marbles.");
System.out.println();
while(marbles.getMarbles() > 0){ //while loop runs until getMarbles is greater than 0
System.out.println("Number of marbles currently in pile: " + marbles.getMarbles());
System.out.println();
marblesToRemove = firstPlayer.playTurn(marbles.getMarbles()); //calls playTurn and getMarbles methods to determine how many marbles have been removed and strategy
for(int i = 0;i<10;i++){
System.out.println("*");
}
System.out.println("--Player 1 removed " + marblesToRemove + " marbles.");
marbles.removeMarbles(marblesToRemove); //calls removeMarbles method with argument marblesToRemove
System.out.println();
if(marbles.getMarbles() == 1){ //If player 2 ends up with 1 marble left, player 1 wins
System.out.println("**********Player 1 wins.**********");
break;
}
System.out.println("Number of marbles currently in pile: " + marbles.getMarbles());
System.out.println();
marblesToRemove = secondPlayer.playTurn(marbles.getMarbles()); //calls playTurn and getMarbles methods to determine how many marbles have been removed and strategy
System.out.println("--Player 2 removed " + marblesToRemove + " marbles.");
marbles.removeMarbles(marblesToRemove); //calls removeMarbles method with argument marblesToRemove
System.out.println();
if(marbles.getMarbles() == 1){ //If player 1 ends up with 1 marble left, player 2 wins
System.out.println("**********Player 2 wins.**********");
break;
}
}
}
}
</code></pre>
<p><strong>Player</strong></p>
<pre><code>import java.util.*;
/**
*
* @param player class sets the player type to enum and then dictates behavior based on selection in Game class.
*/
public class Player {
Scanner input = new Scanner(System.in);
Random marbles = new Random(); //creates random object of random class
public enum Type{HUMAN,SMART_COMPUTER,SIMPLE_COMPUTER} //declare enum objects
private Type type;
/**
* Constructor
* @param t indicates which of the three allowable Types this Player object will be
*/
public Player(Type t){
this.type = t;
}
/**
*
* @param t allows for enum type to be re-assigned
*/
public void setType(Type t){
this.type = t;
}
/**
*
* @param playTurn determines the computer and human behavior that dictates the course of the game
*/
public int playTurn(int pileSize){
int marblesRemoved = 0; //sets variable to 0
if(type == Type.SIMPLE_COMPUTER){ //SIMPLE_COMPUTER makes any random move, with no strategy.
marblesRemoved = marbles.nextInt((pileSize)/2)+1; //removes a random number between 1 and half the size of the remaining pile
}
else if(type == Type.SMART_COMPUTER){ //SMART_COMPUTER plays with a strategy. the computer takes off enough marbles to make the size of the pile a power of two minus 1—that is, 3, 7, 15, 31, or 63
if(pileSize > 63)
marblesRemoved = pileSize - 63;
else if(pileSize > 31)
marblesRemoved = pileSize - 31;
else if(pileSize > 15)
marblesRemoved = pileSize - 15;
else if (pileSize > 7)
marblesRemoved = pileSize - 7;
else if(pileSize == 2)
marblesRemoved = pileSize - 1;
else
marblesRemoved = marbles.nextInt((pileSize)/2)+1; //if the size of the pile is between 3-7, SMART_COMPUTER makes random legal move
}
else if (type == Type.HUMAN){ //HUMAN chooses the amount of marbles to remove
System.out.println("Please choose a number of marbles to remove between 1 and " + (pileSize/2));
marblesRemoved = input.nextInt();
while(marblesRemoved <=0 || marblesRemoved > pileSize/2){ //user input check to make sure number is between the correct values
System.out.println("You must choose a number between 1 and " + (pileSize/2) + ". Please choose another number.");
marblesRemoved = input.nextInt();
}
}
return marblesRemoved; //return marbles removed based on player enum type
}
public String toString(){ //can be implicitly called and relevant information about the internal state of the object. shows which enum player type is being played.
return this.type + "Player type selected.";
}
}
</code></pre>
<p><strong>Pile</strong></p>
<pre><code>import java.util.*;
/**
*
* @param pile class generates a random pile of marbles to be used in game class. Ths number of marbles is between 10-100 inclusive.
* It also calculates the number of marbles removed
*/
public class Pile {
private int marbles = 0;
Random rand = new Random(); //create new random object to generate random number
/**
*
* @param pile constructer sets marble pile to random number between 1-100
*/
public Pile(){
this.marbles = rand.nextInt(89)+11;
}
/**
*
* @param getMarbles returns the current number of marbles in the game
*/
public int getMarbles(){
return this.marbles;
}
/**
*
* @param removeMarbles accepts an int vaiarble to remove from the stack of marbles
*/
public void removeMarbles(int takeMarb){
this.marbles -= takeMarb;
}
public String toString(){ //can be implicitly called and relevant information about the internal state of the object. Shows the current amount of marbles in stack.
return this.marbles + "marbles left in pile.";
}
}
</code></pre>
|
[] |
[
{
"body": "<p>There is a lot of code in <code>main()</code>. It would be better to break this up into smaller pieces.</p>\n\n<hr>\n\n<p>There is a lot of extra white space. There generally is no need for multiple consecutive empty lines.</p>\n\n<p>Within <code>playTurn()</code>, you separate a sequence of if-else if blocks with an empty line. A better solution would be to use curly brackets. This will clearly mark the sections to both humans and computers. Without the curly brackets, adding a second indented statement after the first will always execute (or be a syntax error if it is followed by an else.</p>\n\n<hr>\n\n<p>Enums are a bad way to implement different strategies. It requires a lot of boilerplate code to be written in many different places. In addition, it makes it very easy to miss a case when adding a new strategy. A better solution would be to define an interface that has a method for each decision or action point. Then, the <code>Player</code> would accept some implementation of this interfaces. This makes adding a new strategy simple and requires no changes to <code>Player</code>.</p>\n\n<hr>\n\n<p>If you do need to make a decision based on the value of a enum, a switch statement is better than a number of if else statements. It is easier for the compiler to optimize the makes it clearer to someone readying the code that each enum value has a distinct action. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T19:06:14.670",
"Id": "37535",
"ParentId": "37521",
"Score": "6"
}
},
{
"body": "<p>Hard coding a series of \"println\" statements for printing out the rules is problematical as it blurs the line between things that are code and things that are data. My preference would be to have the rules in a separate file, read it into a single string and print that string at the appropriate time. However, just moving it to a single constant string would be an improvement. Something like this:</p>\n\n<pre><code>private final String GAME_RULES = \n \"**************WELCOME TO THE GAME OF NIM******************\\n\" +\n \"\\n\" +\n \"\\n\" +\n \"******************RULES OF THE GAME***********************\\n\" +\n \"--The number of marbles in the initial pile will be random amount between 10 and 100.\\n\" +\n \"---Each player must choose between 1 and half of the remaining pile of marbles to remove.\\n\" +\n \"----The player stuck with the last marble loses the game.\\n\" +\n \"---The computer will randomly be placed into simple or smart mode randomly.\\n\" +\n \"--The player who goes first will also be chosen at random.\\n\" +\n \"\\n\" +\n \"Enter 1 to play against another human or 2 to play against a computer.\\n\" +\n \"Enter 3 if you would like 2 computers to play against each other.\"\n</code></pre>\n\n<p>Then the section that is marked \"Interface\" becomes:</p>\n\n<pre><code> //Interface\n System.out.println(GAME_RULES);\n selection = in.nextInt();\n</code></pre>\n\n<p>Which is much easier to understand because we have cleared away all the clutter.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:06:07.380",
"Id": "37537",
"ParentId": "37521",
"Score": "6"
}
},
{
"body": "<p>You are using a lot of different variables to store the <code>Player</code> objects in and declaring them for your whole main method. If you really needed four it would be better to have an array of <code>Players[]</code> but in this case you are better just having 2 (maybe still in an array) but only create them when you actually need them and set them to the right type then.</p>\n\n<p>By using the array that then lets you change the player 1 and player 2 while loop into one for loop to run over the array[] and you can remove all that duplicated code. It also lets you support any number of players virtually for free.</p>\n\n<p>For the loop you can use a do-while loop as you know you always have to run through the loop at least once.</p>\n\n<p>It would be more efficient to use one Random object created in Main and then passed into anywhere else that needs it. Other than that your Pile object looks fine.</p>\n\n<p>Your Player object is a classic case where inheritance should be used.</p>\n\n<p>Create an abstract base class Player and then create subclasses HumanPlayer, ComputerPlayer and SmartComputerPlayer (the computer players may or may not also have a common ancestor). Then you just have a Player object reference in your main class and it calls the relevant method in that - which gets sent to the right subclass automatically.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:23:44.870",
"Id": "37545",
"ParentId": "37521",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T17:16:13.437",
"Id": "37521",
"Score": "7",
"Tags": [
"java",
"game"
],
"Title": "Marbles game with classes"
}
|
37521
|
<pre><code>def current_time():
'''Returns a tuple containing (hour, minute) for current local time.'''
import time
local_time = time.localtime(time.time())
return (local_time.tm_hour, local_time.tm_min)
(hour,minute) = current_time()
def ishtime(hour, minute):
import random
Starting_str = ['it is','its',"it's","Current time is"]
h_str = ['one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve']
mid_str = ['almost','nearly','roughly','maybe']
Ex = ['Exactly' , 'Perpectly' ,'']
m_str = ['ten','twenty','thirty','fourty','fifty']
End_str = ['in the morning','in the afternoon','in the evening','at night']
## - define random strings
Head = Starting_str[int(random.random()*4)]
Mid = mid_str[int(random.random()*4)]
Hour = h_str[(int(hour)-1)%12]
if round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
Rand_m_str = ''
else:
Rand_m_str = m_str[int((round(int(minute),-1)/10))-1]
## -define for final ex)its , it's , almost, one two three..
if int(hour)>=6 and int(hour)<13:
Ending = End_str[0]
elif int(hour)>=13 and int(hour)<19:
Ending = End_str[1]
elif int(hour)>=19 and int(hour)<=23:
Ending = End_str[2]
elif int(hour)>=0 and int(hour)<6:
Ending = End_str[3]
## - define 'ending str' ex) in the morning
if minute == 0 or minute == 00:
Result = "%s %s 'o clock %s" %(Head,Hour,Ending)
elif minute%10 == 0:
Result = "%s %s %s after %s %s" %(Head,Ex[int(random.random()*4)],Rand_m_str,Hour,Ending)
elif round(int(minute),-1) == 0 or round(int(minute),-1) == 60:
Result = "%s %s %s%s %s" %(Head,Mid,Rand_m_str,Hour,Ending)
else:
Result = "%s %s %s minute after %s %s" %(Head,Mid,Rand_m_str,Hour,Ending)
return Result
print ishtime(hour,minute)
</code></pre>
<p>I did this job.. how could i make it simpler?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T09:07:26.743",
"Id": "62112",
"Score": "1",
"body": "You could start by removing \"its\" and fixing \"Perpectly\" and capitalization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T10:37:33.940",
"Id": "63009",
"Score": "0",
"body": "Why not the builtin `datetime.datetime.strftime`?"
}
] |
[
{
"body": "<p>Python supports double-ended inequalities:</p>\n\n<pre><code>End_str = ['at night', 'in the morning','in the afternoon','in the evening']\n\nif 0 <= hour < 6:\n Ending = End_str[0]\nelif 6 <= hour < 13:\n Ending = End_str[1]\nelif 13 <= hour < 19:\n Ending = End_str[2]\nelif 19 <= hour < 24:\n Ending = End_str[3]\n</code></pre>\n\n<p>I've changed 23 to 24 for consistency and rearranged the members of <code>End_str</code>. I don't see how <code>hour</code> should be anything other than an integer, so I've removed the casts.</p>\n\n<p><code>if minute == 0 or minute == 00</code> is redundant, since 00 is exactly the same as 0.</p>\n\n<p>I would expect noon and midnight to be handled as special cases.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T00:01:25.723",
"Id": "37556",
"ParentId": "37522",
"Score": "3"
}
},
{
"body": "<p>Avoid constructs like <code>Ex[int(random.random()*4)]</code> which are brittle at several levels:</p>\n\n<ul>\n<li>What if <code>Ex</code> is changed to no longer contain 4 elements?</li>\n<li>Hey, it already only has 3 elements.</li>\n<li>Fixing that by using <code>len(Ex)</code> is still quite verbose.</li>\n</ul>\n\n<p>Prefer <a href=\"http://docs.python.org/dev/library/random.html?highlight=random#random.choice\" rel=\"nofollow\"><code>random.choice</code></a>, using it like this: <code>random.choice(Ex)</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:22:58.833",
"Id": "37563",
"ParentId": "37522",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T07:59:14.927",
"Id": "37522",
"Score": "3",
"Tags": [
"python",
"datetime"
],
"Title": "Expressing current time with natural language"
}
|
37522
|
<p>See, I have a file which consists of a bunch of lines like</p>
<pre><code>NAME:0001;some text
ANOTHERNAME:000103;some more text
NEWNAME:42; blah blah
</code></pre>
<p>So what I need to do is to have a list of those names, list of numbers (IDs actually, so the order matters) and list of further comments. I wrote a code, which actually does work, but I'm afraid it's horrible and not pythonic at all.</p>
<pre><code>reactions_file = open("reactions.txt","r")
lines = reactions_file.readlines()
reaction_names = []
reaction_other = []
reaction_IDs = []
reaction_notes = []
for line in lines:
r_name = line.partition(":")[0]
r_other = line.partition(":")[2]
reaction_names.append(r_name)
reaction_other.append(r_other)
for item in reaction_other:
r_ID = item.partition(";")[0]
r_note = item.partition(";")[2]
reaction_IDs.append(r_ID)
reaction_notes.append(r_note)
print(reaction_names)
print(reaction_IDs)
print(reaction_notes)
reactions_file.close()
</code></pre>
<p>How can it be changed to look less like written by newbie? :)</p>
|
[] |
[
{
"body": "<p>You can say:</p>\n\n<pre><code>>>> import re\n>>> re.split('[:;]', 'NAME:0001;some text')\n['NAME', '0001', 'some text']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:31:38.637",
"Id": "62113",
"Score": "0",
"body": "Seems like you could improve that by checking only for upper case, then colon then digits then semi colon, otherwise any time the last group has either of those two characters, you're going to be dealing with all kinds of craziness. Outside the scope of the question, I guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:32:00.800",
"Id": "62154",
"Score": "0",
"body": "I'd suggest maybe storing the result for each line as a namedtuple (http://docs.python.org/2/library/collections.html) or dictionary for easier access in the rest of the code"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:13:01.207",
"Id": "37524",
"ParentId": "37523",
"Score": "3"
}
},
{
"body": "<p>Here's a solution that works without importing Regex (though it's worth noting that Regex is extremely powerful and worth learning)!</p>\n\n<p>This solution:</p>\n\n<ul>\n<li>Has one <code>for</code> loop</li>\n<li>Looks at each line, replaces all <code>;</code> with <code>:</code>, and then splits each line into 3 parts.</li>\n<li>Adds each part to their respective lists.</li>\n<li>Prints each list afterwards.</li>\n</ul>\n\n<p>Here is the code:</p>\n\n<pre><code>reactions_file = open(\"reactions.txt\",\"r\")\nlines = reactions_file.readlines()\nnames = []\nids = []\nnotes = []\n\nfor line in lines:\n names.append(line.replace(';',':').split(':')[0])\n ids.append(line.replace(';',':').split(':')[1])\n notes.append(line.replace(';',':').split(':')[2])\n\nprint(names)\nprint(ids)\nprint(notes)\n\nreactions_file.close()\n</code></pre>\n\n<p>A note: One weakness is that if your \"notes\" section has a <code>:</code> anywhere in it, the note will be cut off at that <code>:</code>. There are fixes for this obviously, namely the <code>regex</code> method. But, this method is logically simple and you may follow it more easily.</p>\n\n<h2>Breakdown of the solution</h2>\n\n<pre><code>#You know what these do\nreactions_file = open(\"reactions.txt\",\"r\")\nlines = reactions_file.readlines()\nnames = []\nids = []\nnotes = []\n</code></pre>\n\n<p>Let's look at each of the <code>split</code> lines, using placeholder names for a general case.</p>\n\n<pre><code>placeholderlist.append(line.replace(';',':').split(':')[i])\n</code></pre>\n\n<p>In this operation, things are processed from left to right inside the first set of parentheses.</p>\n\n<p>For this case, say the <code>line</code> in question is <code>james:0001;Hello world</code></p>\n\n<p>The first operation is <code>line.replace(';',':')</code> which turns <code>line</code> into:</p>\n\n<pre><code>`james:0001:Hello world`\n</code></pre>\n\n<p>Then comes <code>.split(':')</code>, which splits a string into any number of parts, each one separated by <code>:</code>.</p>\n\n<p>Then comes indexing-- have you ever touched upon indexes?</p>\n\n<p>When Python splits something, or there is a list, or even in strings, there exists indexes. It starts from the left to the right, at position <code>0</code> and progressing to position <code>n</code>, the end of the list/string/etc.</p>\n\n<p>Example:</p>\n\n<pre><code>string = \"Hello world\"\nprint(string[0])\nprint(string[3])\nprint(string[4])\n</code></pre>\n\n<p>Produces:</p>\n\n<pre><code>>>H\n>>l\n>>o\n</code></pre>\n\n<p>Similarly, a list will give you element <code>n</code> in its list. So when we run <code>split(':')[i]</code> on <code>line</code>:</p>\n\n<pre><code>print(line.replace(';',':').split(':')[0])\nprint(line.replace(';',':').split(':')[1])\nprint(line.replace(';',':').split(':')[2])\n</code></pre>\n\n<p>We get</p>\n\n<pre><code>>>james\n>>0001\n>>Hello world\n</code></pre>\n\n<p>But that's not enough! We want to put them into your lists, <code>names</code>, <code>ids</code>, and <code>notes</code>.</p>\n\n<p>For this we use <code>.append()</code>, which simply adds <code>element</code> to <code>list</code>.</p>\n\n<p>As such, for each loop we add the <code>name</code>, the <code>id</code>, and the <code>notes</code> to their respective lists. At the end, we print each list to verify.</p>\n\n<p>You should find each list will be exactly what you want <em>provided no <code>:</code> is in your <code>notes</code></em></p>\n\n<p>Any questions? Feel free to comment (tag my name with @jwarner112) and I'll show back up to help.</p>\n\n<p>Happy Coding!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:40:17.900",
"Id": "37527",
"ParentId": "37523",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37524",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T15:10:19.387",
"Id": "37523",
"Score": "1",
"Tags": [
"python",
"parsing"
],
"Title": "How parse nicely a string into three (or more) pieces?"
}
|
37523
|
<p>I need to display a list of category links, like so:</p>
<p>Category 1, Category 2, Category 3</p>
<p>I've got it working already but the code seems pretty repetitive and a bit of a mess, I was wondering if there was a better way of doing it.</p>
<p>This is what I've got so far:</p>
<pre><code>for (var i = 0; i < data['categories'].length; i++) {
var comma = document.createTextNode(', ');
var link = document.createElement('a');
link.setAttribute('href', '#journal__category--' + data['categories'][i]['url_title'] );
link.setAttribute('class', 'js--page__link');
link.innerHTML = data['categories'][i]['category_name'];
document.getElementById('js--journal__categories').appendChild(link);
if( (i + 1) != data['categories'].length ) {
document.getElementById('js--journal__categories').appendChild(comma);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This doesn´t look all too repetitive to me, I see no obvious duplication.\nYou could extract a local variable or two to make the naming more explicit and to not query for the same element twice.\nThat would however be a tradeoff between function size and readability. Also you see a few references to the <code>link</code> variable in one place, this indicates that this could be pulled into its own function.</p>\n\n<pre><code>/**\n * Build a link for a category\n * @param category\n * @return DomNode\n */\nfunction linkForCategory(category) {\n var link = document.createElement('a');\n link.setAttribute('href', '#journal__category--' + category['url_title']);\n link.setAttribute('class', 'js--page__link');\n link.innerHTML = category['category_name'];\n\n return link;\n}\n\nfor (var i = 0; i < data['categories'].length; i++) {\n var comma = document.createTextNode(', '),\n journal_categories = document.getElementById('js--journal__categories');\n\n var link = linkForCategory(data['categories'][i]);\n journal_categories.appendChild(link);\n\n if ( (i + 1) != data['categories'].length ) {\n journal_categories.appendChild(comma);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:53:35.560",
"Id": "37541",
"ParentId": "37536",
"Score": "0"
}
},
{
"body": "<p>Here's how I might try to clean things up:</p>\n\n<ul>\n<li><p>refer to object properties without bracket notation where possible\ne.g. <code>data.categories.length</code></p></li>\n<li><p>create a loop variable for the current category, which allows you to reference it nicely without <code>data.categories[i]</code></p>\n\n<pre><code>for (var i = 0; i < data.categories.length; i++) {\n var category = data.categories[i];\n}\n</code></pre></li>\n<li><p>don't look up the container on every iteration, move that outside the loop:</p>\n\n<pre><code>var container = document.getElementById('js--journal__categories');\nfor (...loop...) {\n ...create your node...\n container.appendChild(link);\n}\n</code></pre></li>\n<li><p>same for creating the comma node, create it outside the loop.</p></li>\n<li><p>you don't need to wrap <code>i + 1</code> in parenthesis, and this is just my preference, but you should be consistent with spaces. You could also use <code><</code> instead of <code>!=</code> which is more consistent with the for loop. (These are fairly minor nits)</p>\n\n<pre><code>if (i + 1 < data.categories.length)\n</code></pre></li>\n<li><p>Why are you using double dashes and underscores in your element IDs? </p></li>\n<li><p>Comments are helpful to explain what your for loop and if statement is doing, since it's probably easier/quicker to understand the comment than figure out the for loop.</p></li>\n<li><p>Maybe I'm getting overkill at this point, but a way to write really descriptive, easy to read code is to break it into functions whose name makes sense:</p>\n\n<pre><code>function createCategoryElement(name, url_title) {\n ...create your anchor element here...\n ...set its attributes and content, etc...\n return element;\n}\n</code></pre></li>\n</ul>\n\n<p>I ended up with something like this:</p>\n\n<pre><code>var data = {\n categories: [\n {name: 'one', url_title: 'oneUrl'},\n {name: 'two', url_title: 'twoUrl'}\n ],\n};\n\nvar container = document.getElementById('container');\nvar comma = document.createTextNode(', ');\n\nfunction createCategoryElement(name, url) {\n var urlBase = '#journal-category-';\n var cssClass = 'js-page-link';\n\n var el = document.createElement('a');\n el.setAttribute('href', urlBase + url);\n el.setAttribute('class', cssClass);\n el.innerHTML = name;\n return el;\n}\n\n// Create HTML elements for each category and append them to the DOM.\n\nfor (var i = 0; i < data.categories.length; i++) {\n var category = data.categories[i];\n var categoryElement = createCategoryElement(category.name, category.url_title);\n container.appendChild(categoryElement);\n\n // Join categories with a comma\n if (i + 1 < data.categories.length) {\n container.appendChild(comma);\n }\n}\n\n for (...loop over categories...) {\n ...\n var categoryElement = createCategoryElement(category.name, category.url_title);\n container.appendChild(categoryElement);\n\n if (i + 1 < data.categories.length) {\n containenr.appendChild(commaElement);\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:50:12.170",
"Id": "62157",
"Score": "0",
"body": "Thanks, your way definitely seems a lot cleaner. The reason I'm using double -- & __ is because it's a one page site with content pulled in with Ajax so it's kind of a naming structure. `journal` Tells me it's the blog, `__category` Tells me it's a blog category and they `--categoryURL` Tells me the actual category. This also makes everything bookmarkable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T22:02:03.223",
"Id": "62161",
"Score": "0",
"body": "Cool, if that naming scheme works well for you, then use it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:58:35.183",
"Id": "37543",
"ParentId": "37536",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37543",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:03:06.163",
"Id": "37536",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Better way to display list of categories"
}
|
37536
|
<p>Is it possible to combine all the functions into a single function? I'm providing <a href="http://jsfiddle.net/hB2T8/" rel="nofollow">my fiddle</a> as well.</p>
<p><strong>I am trying to test it for different scenarios..
but I am not sure how to combine all the scenarios into one..</strong></p>
<pre><code>var myNumbersToSort = [null, -1, 2, 0.001, -3, 4, 0.3,1,-0.0001];
function getClosestToZero(set) {
if(0 === set.length) return null;
var closest = set[0], result = 0;
for(var i in set) {
var next = set[i];
if(Math.abs(closest) > Math.abs(next)) {
result = i;
closest = next;
}
}
return closest;
}
function getClosestToZeroWithNaN(set) {
var closest;
if(set instanceof Array) {
for(var i = 0; i < set.length; i++) {
var val = set[i];
if(!isNaN(val)){
val = Number(val);
var absVal = Math.abs(val);
if(typeof closest == 'undefined' || Math.abs(closest) > absVal) {
closest = val;
}
}
}
}
return closest;
}
function getClosestToZeroOnlyNumbers(set) {
var closest;
if(set instanceof Array) {
for(var i = 0; i < set.length; i++) {
var val = set[i];
if(typeof val == "number"){
var absVal = Math.abs(val);
if(typeof closest == 'undefined' || Math.abs(closest) > absVal) {
closest = val;
}
}
}
}
return closest;
}
document.getElementById('output').innerHTML = (getClosestToZeroOnlyNumbers(myNumbersToSort));
</code></pre>
|
[] |
[
{
"body": "<p>I think your code would be cleanest if you wrote the program as a composition of a minimum-absolute-value-of-array function and a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow\">filter</a>.</p>\n\n<p>Assuming that performance in the face of large data sets is not a concern, you could have, for example:</p>\n\n<pre><code>function isNumber(val) {\n return typeof val == \"number\";\n}\n\ngetClosestToZero(myNumbersToSort.filter(isNumber));\n</code></pre>\n\n<p>Alternatively, <code>getClosestToZero()</code> could directly support an optional second argument that servers as a filtering callback if it is provided.</p>\n\n<p>Please pay attention to the consistency of the indentation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:46:45.073",
"Id": "62150",
"Score": "0",
"body": "thanks for your reply...can you update in the fiddle http://jsfiddle.net/hB2T8/ its confusing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T21:50:22.973",
"Id": "62158",
"Score": "0",
"body": "According to our [help/on-topic] rules, asking for code to be written is off-topic for Code Review. The original question was marginal; your request would definitely violate our community's standards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:43:20.130",
"Id": "37540",
"ParentId": "37538",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:11:17.783",
"Id": "37538",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"performance"
],
"Title": "Convert three functions into a single function"
}
|
37538
|
<p>There is a pattern that keeps coming up in my ruby code and I'm somewhat ambivalent about it. It's somewhere between a Hash and a Struct. Basically
I used method_missing to return/set values in the Hash unless I want to
override a specific value with some logic or flatten out the complex underlying structure in the JSON. It's very flexible and quickly
allows code changes, but it also hides much of the structure of the object.</p>
<p>In effect, the structure is in the data ( JSON file ) and not in the code.
Is this an effective Pattern or just asking for trouble down the road? </p>
<pre><code>class AttributeKeeper
def initialize
@attributes = Hash.new
end
def import
// Special import methods usually from JSON
end
def export
// Export to JSON with maybe some data verification along the way.
end
def special_value= (value )
// Perform data check on special value
@attributes[special_value] = value
end
def checked_value
// Return value if passes checks.
end
def method_missing(meth, *args, &block)
smeth = meth.to_s
trim = smeth.chomp('=') #Handle setter methods.
unless ( smeth == trim )
@attributes[trim] = args[0]
else
@attributes[smeth]
end
end
def responds_to?(meth)
smeth = meth.to_s
if( @attributes[smeth] or smeth[-1,1] == '=')
true
else
super
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>I have the feeling that your patterns is very similar to the idea behind <a href=\"http://www.ruby-doc.org/stdlib-2.0/libdoc/ostruct/rdoc/OpenStruct.html\" rel=\"nofollow\"><code>OpenStruct</code></a> and similar libraries, such as <a href=\"https://github.com/intridea/hashie#mash\" rel=\"nofollow\"><code>Hashie::Mash</code></a>.</p>\n\n<p>So I would say, it's definitely not an anti-pattern in some cases. Such structures are very helpful when parsing and converting structured inputs, for example an API call.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:10:31.103",
"Id": "37553",
"ParentId": "37542",
"Score": "3"
}
},
{
"body": "<p>Useful to create mock, small scripts, remote api mapping... the github ruby api Octokit.rb is using this kind of pattern.</p>\n\n<p>Don't use this for <strong>huge (1000+) collection of objects</strong> with intensive call on them. </p>\n\n<ul>\n<li>The method_missing, symbol conversion will compromise your performance, generating a memory bloat and a lot of garbage collection,</li>\n<li>the Hashie isn't optimized as ActiveRecord::Base (method_missing triggering a define_method) so method call resolution has a always higher cost.</li>\n</ul>\n\n<p>Another aspect is that you tend <strong>to put your code at the wrong place</strong> (<code>UtilityClass#full_name</code>) instead of the actual class (<code>user.full_name</code>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T16:29:38.487",
"Id": "62501",
"Score": "0",
"body": "In practice my \"real\" objects tend to be subclasses of this object. The whole point is to make user.full_name \"easy\" rather than user.validate(JSON['subhash']['full_name'])"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:42:39.487",
"Id": "62645",
"Score": "0",
"body": "I'm fine with this I often use Hashie to mock some value object. The ancestor is a real good trick but then you can define the method and relying on the method missing only at the first call."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:11:50.150",
"Id": "37675",
"ParentId": "37542",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37675",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T20:54:05.330",
"Id": "37542",
"Score": "4",
"Tags": [
"ruby",
"design-patterns"
],
"Title": "Ruby Dynamic Struct - Pattern or AntiPattern?"
}
|
37542
|
<p><a href="http://projecteuler.net/problem=10" rel="nofollow">Project Euler Problem 10</a> asks: "What is the sum of all prime numbers below 2 million?"</p>
<p>How do I speed up my code? It's taking forever and I have never gotten the answer. However, I am sure that my code is right; I cheated the answer from online as I couldn't wait for an hour.</p>
<pre><code>def isPrime(number):
for n in xrange (2,number):
if number%n == 0:
return False
return True
result = 2
for k in xrange (3,2000000,2):
if isPrime(k):
result += k
print result," ",k
print "The total is %d" % result
</code></pre>
<p>The result is 142913828922.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:17:52.783",
"Id": "62169",
"Score": "0",
"body": "Srry, Edited and improved a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:41:51.873",
"Id": "62391",
"Score": "1",
"body": "One tip: Replace your implementation of `isPrime(number)` with the [Miller Rabin primality test](http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test). It will be much faster."
}
] |
[
{
"body": "<p>Unfortunately, I don't speak python so I can't provide any code but there's a couple of things I see that can be improved algorithmically:</p>\n<ol>\n<li>In <code>isPrime</code> start checking if it's divisible by two, then start check 3 and increase by two on each step. So instead of checking 2,3,4,5,6... you check 2,3,5,7,9,11,13,15...</li>\n<li>You only need to check numbers up to sqrt(number) in your <code>isPrimes</code> method</li>\n</ol>\n<p>Point 1 here can also be applied to your main loop (that goes from 2 to 20000000). Initialize k to 2 and check if that's prime. Then set k to 3, check if it's prime and then increase k by 2 each time. So that the numbers you check for primeness also becomes 2,3,5,7,9,11...</p>\n<h3>Theory on another approach (Untested in all languages, might not work)</h3>\n<p>I'm not sure if this will be faster or not, but here's a thought that you might be able to gain speed with:</p>\n<p>Since you loop through numbers to check for primes, add the already found primes to a list and when checking a new number then you only need to check if it's divisible by one of the previously known primes. That way you won't have to check with 9 and 15 for example.</p>\n<p>Pseudo-code:</p>\n<ol>\n<li>Create an empty list, here called <code>primeList</code></li>\n<li>Loop from 2 to 2000000, call this number <code>k</code> (as in your existing code)</li>\n<li>Check if the number is divisible by any item in the <code>primeList</code>, if it is then <code>k</code> is not prime so go to the next iteration.</li>\n<li>If a number was not found in step 3, then add <code>k</code> to the <code>primeList</code></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:19:12.560",
"Id": "62170",
"Score": "4",
"body": "Your other approach is basically an inefficient implementation of the [sieve of Erathostenes](http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes). So while it can be done better, your idea will replace having to do `n` checks to test `n` for primality, to only do [about `n / log(n)`](http://en.wikipedia.org/wiki/Prime-counting_function), so it is definitely going to be (much) faster."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:01:51.900",
"Id": "37551",
"ParentId": "37550",
"Score": "6"
}
},
{
"body": "<p>When the performance of your program in the face of large inputs is not even in the right ballpark, it's time to look for a new algorithm, even if your code is correct. Factoring numbers is considered a \"hard\" problem — most public-key cryptography relies on the fact that factoring numbers takes a long time.</p>\n\n<p>The <a href=\"http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\">Sieve of Eratosthenes</a> would be perfect for this problem. It should be possible in about 10 lines of code, and run in about one second.</p>\n\n<p>Implementation hint:</p>\n\n<pre><code># Build a big list\nprime_list = range(limit + 1)\n\n# Strike non-prime numbers 0 and 1 from the list\nprime_list[0] = prime_list[1] = None\n\n# TODO: Strike all multiples of prime numbers from the list\nfor k in xrange(len(prime_list)):\n ...\n\n# Sum the numbers that have not been stricken out\nreturn sum(filter(None, prime_list))\n</code></pre>\n\n<p>Alternatively, strike out numbers by setting them to 0 instead of <code>None</code>. That removes the need to call <code>filter()</code>, but I think the clarity would suffer a tiny bit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:33:30.080",
"Id": "37555",
"ParentId": "37550",
"Score": "10"
}
},
{
"body": "<p>Here's a simple function that should give the answer pretty quickly:</p>\n\n<pre><code>def sum_primes(limit):\n primes = []\n for n in xrange(2, limit+1):\n # try dividing n with all primes less than sqrt(n):\n for p in primes:\n if n % p == 0: break # if p divides n, stop the search\n if n < p*p:\n primes.append(n) # if p > sqrt(n), mark n as prime and stop search\n break\n else: primes.append(n) # fallback: we actually only get here for n == 2\n return sum(primes)\n</code></pre>\n\n<p>It relies on the fact that every composite number <em>n</em> must be divisible by a prime <em>p</em> less than or equal to its square root. (<em>Proof</em>: By definition, every composite number is divisible by some prime. If <em>n</em> is divisible by a prime <em>p</em> > sqrt(<em>n</em>), then <em>n</em> is also divisible by <em>m</em> = <em>n</em> / <em>p</em> < sqrt(<em>n</em>), and thus <em>n</em> must be divisible by some prime divisor <em>q</em> ≤ <em>m</em> < sqrt(<em>n</em>) of <em>m</em>.)</p>\n\n<p>The only tricky part, performance-wise, is ensuring that we don't iterate through the list of primes any further than necessary to confirm or deny the primality of <em>n</em>. For this, both of the breaking conditions are important.</p>\n\n<p>The code above is actually somewhat inefficient in its memory use, since it builds up the entire list of primes up to the limit before summing them. If we instead maintained a running sum in a separate variable, we wouldn't need to store any of the primes above the square root of the limit in the list. Implementing that optimization is left as an exercise.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> As <a href=\"https://codereview.stackexchange.com/a/37555/\">200_success suggests</a>, a well-written <a href=\"http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a> can indeed be faster than the trial division method described above, at the cost of using more memory. Here's an example of such a solution:</p>\n\n<pre><code>from math import sqrt\ndef sum_primes(limit):\n sieve = range(limit+1); sieve[1] = 0\n for n in xrange(2, int(sqrt(limit))+1):\n if sieve[n] > 0:\n for i in xrange(n*n, limit+1, n): sieve[i] = 0\n return sum(sieve)\n</code></pre>\n\n<p>On my computer, this runs nice and fast for a limit of 2 million or 20 million, but throws a MemoryError for 200 million.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T03:06:36.140",
"Id": "62200",
"Score": "0",
"body": "This is amazingly fast too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T07:53:55.387",
"Id": "62224",
"Score": "2",
"body": "This is the first time I've seen an \"else\" block to a \"for\" loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:36:47.353",
"Id": "62226",
"Score": "1",
"body": "Me too, but it makes sense. http://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:53:30.867",
"Id": "62230",
"Score": "0",
"body": "I see what you mean now by iterating up to `sqrt(limit) + 1)` in the Sieve of Eratosthenes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:26:09.017",
"Id": "62233",
"Score": "1",
"body": "A common improvement is to skip even numbers. `primes=[2]; for n in xrange(3, limit+1, 2): ...`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:17:33.427",
"Id": "37562",
"ParentId": "37550",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37562",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T22:47:09.557",
"Id": "37550",
"Score": "5",
"Tags": [
"python",
"performance",
"primes",
"project-euler"
],
"Title": "Summation of primes takes forever"
}
|
37550
|
<p>I have created a generic repository for my MVC 3 page. I am using interfaces and a UnitOfWork. But before I set out to do this? Is this the right way to separate my databaseaccess from my viewmodels and views?</p>
<p><strong>WHY I DID IT:</strong></p>
<p>I want to seperate my databaseaccess from my viewmodels and my views, I also want the option to have specific methods for inserting some of my data hence the UserRepository. I also want a controlled environment using the UnitOfWork.</p>
<p><strong>FEARS:</strong></p>
<p>Am I over-complicating everything using these interfaces? Should I ditch the generic repository, I will use it for "basic" inserts so it's not useless by any means. I do understand that I might save some time having the generic repository, only to be creating specific repositories for some of my inserts/update/deletes.</p>
<p><strong>Summary:</strong></p>
<p>It consists of 6 files at the moment of which 2 are:</p>
<ul>
<li><code>IRepository</code></li>
<li><code>GenericRepository</code></li>
<li><code>IUnitOfWork</code></li>
<li><code>UnitOfWork</code></li>
<li><code>IUserRepository</code></li>
<li><code>UserRepository</code></li>
</ul>
<hr>
<h2>Code</h2>
<p><strong>IRepository:</strong></p>
<pre><code>public interface IRepository<T> where T : class
{
IEnumerable<T> BaseFetchAll();
void BaseAdd(T entity);
void BaseDelete(T Entity);
}
</code></pre>
<p><strong>Repository:</strong></p>
<pre><code>public abstract class GenericRepository<T> : IRepository<T> where T : class
{
private IObjectSet<T> _dbContext;
private Entities _context;
protected DbSet<T> dbSet;
internal GenericRepository(Entities context)
{
this._context = context;
dbSet = context.Set<T>();
}
public void BaseDelete(T entity)
{
dbSet.Remove(entity);
}
public IEnumerable<T> BaseFetchAll()
{
return (IEnumerable<T>)(from x in dbSet select x).ToList<T>();
}
public void BaseAdd(T entity)
{
dbSet.Add(entity);
}
}
</code></pre>
<p><strong>IUnitOfWork:</strong>
Before you kick my butt, I am to implement the save,rollback etc. methods this is just to show you what I'm doing.</p>
<pre><code>public interface IUnitOfWork
{
IUserRepository UserRepository { get; }
IUserFileRepository UserFileRepository { get; }
}
</code></pre>
<p><strong>UnitOfWork:</strong></p>
<pre><code>public class UnitOfWork : IUnitOfWork
{
private IUserRepository _userRepository;
private Entities context = new Entities();
public IUserRepository UserRepository
{
get
{
if(this._userRepository == null)
this._userRepository = new UserRepository(context);
return this._userRepository;
}
}
}
</code></pre>
<p><strong>IUserRepository:</strong></p>
<pre><code>public interface IUserRepository: IRepository<t_users>
{
IEnumerable<t_users> FetchAllUsers();
void InsertToUserTableWithSpecs();
}
</code></pre>
<p><strong>UserRepository:</strong></p>
<pre><code>public class UserRepository : GenericRepository<t_users>, IUserRepository
{
private Entities dbContext;
public UserRepository(Entities context) : base(context)
{
this.dbContext = context;
}
public IEnumerable<t_users> FetchAllUsers()
{
return (IEnumerable<t_users>)(from x in dbContext.t_users select x);
}
public void InsertToUserTableWithSpecs()
{
}
}
</code></pre>
<p>Not a lot of code but hopefully something to give you an idea in which direction I'm going.</p>
|
[] |
[
{
"body": "<p>I think if you are going to have only one Repository, then yeah this is over complicated! But if you will have many Repositories and you will be adding more and more, then you are on the right track. But couple of points: </p>\n\n<p>I am not sure how your are using your UoW. From my point of view UoW should look like something like: </p>\n\n<pre><code>interface IUnitOfWork\n{\n Begin();\n End();\n Rollback();\n}\n</code></pre>\n\n<p>And UoW should be passed to Repositories. So basically you have a UoW that couple of Repositories may use to get their job done (get/insert records for instance). From where I look at this a UoW is not specific to a single Repository and can span multiple Repositories. </p>\n\n<p>Imagine for instance that your UoW involves creating an Order entity and updating the Customer entity together. </p>\n\n<p>Also I would suggest to tighten <code>IRepository</code> definition to:</p>\n\n<pre><code>public interface IRepository<T> where T : IDomainObject\n</code></pre>\n\n<p>This basically is saying that repositories are not supposed to be created for any sort of class. Your Domain classes can then implement IDomainObject to satisfy this condition. IDomainObject can be empty or depending on your Domain it can have some Domain related properties. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:07:19.027",
"Id": "37626",
"ParentId": "37554",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37626",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-16T23:17:56.867",
"Id": "37554",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Generic Repository: Am I over-complicating?"
}
|
37554
|
<p>I have made this search filter and it works fine, but I think the code looks a little messy and I have no idea how to clean it up.</p>
<p>I hope the following makes sense, otherwise please tell me which information you need, and I will provide it ASAP.</p>
<pre><code>// GET THE POST VALUE FROM FORM FIELDS
$field_value_service = $_POST['service_filter'];
$field_value_region = $_POST['service_region'];
$field_value_postal = $_POST['postal_code'];
$field_value_gender = $_POST['gender_filter'];
// GET USER INFO FROM USERS WHERE USERS VALUES IS EQUAL TO FORM FIELD VALUES
$valuesService = get_cimyFieldValue(false, 'service', $field_value_service);
$valuesRegion = get_cimyFieldValue(false, 'region', $field_value_region);
$valuesPostal = get_cimyFieldValue(false, 'postnummer', $field_value_postal);
$valuesGender = get_cimyFieldValue(false, 'gender', $field_value_gender);
// CREATE EMPTY ARRAYS
$userArray = array();
$userArrayTwo = array();
$userArrayThree = array();
$userArrayFour = array();
$userArrayFive = array();
foreach ($valuesService as $value) {
$userArray[] = $value['user_id'];
}
foreach ($valuesRegion as $value) {
$userArrayTwo[] = $value['user_id'];
}
foreach ($valuesPostal as $value) {
$userArrayThree[] = $value['user_id'];
}
foreach ($valuesGender as $value) {
$userArrayFour[] = $value['user_id'];
}
$firstResult = array_merge($userArray, $userArrayTwo);
$duplicates = array_unique(array_diff_assoc($firstResult, array_unique($firstResult)));
$secondResult = array_merge($duplicates, $userArrayThree);
$secondDuplicates = array_unique(array_diff_assoc($secondResult, array_unique($secondResult)));
$thirdResult = array_merge($secondDuplicates, $userArrayFour);
$thirdDuplicates = array_unique(array_diff_assoc($thirdResult, array_unique($thirdResult)));
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>comments should explain what the code does, at least the complicated blocks, such as the array merging, and/or a comment to describe the whole thing</p></li>\n<li><p>Be consistent with naming things: you use camelCase sometimes (e.g. <code>userArray</code>) and underscores other times (e.g. <code>field_value_gender</code>). IIRC, underscores is the PHP style, so you could go with that, but the important thing is to be consistent.</p></li>\n<li><p>Same goes for your filter parameter names: service_filter, region_filter, postal_code_filter, gender_filter</p></li>\n<li><p>When you have places where you repeat code, use a function:</p>\n\n<pre><code>function build_array(post_field, user_field) {\n $post_value = $_POST[post_field];\n $user_value = get_cimyFieldValue(false, user_field, $post_value);\n $arr = array();\n\n foreach ($user_value as $value) {\n $arr[] = $val['user_id'];\n }\n return $arr;\n}\n\nbuild_array('service_filter', 'service');\n</code></pre></li>\n<li><p>But really, you probably don't need that. Are you trying to get a unique list of user IDs? Can you use one array and call array_unique on that? Or, are you trying to get duplicates? Or both? Either way, I really doubt you need all that merge/diff/unique'ing. For example, you could keep an array of <code>user_id => times_seen</code> and then loop through that to get entries with <code>times_seen</code> > 1 or whatever.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T03:04:48.703",
"Id": "37565",
"ParentId": "37561",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T02:11:19.083",
"Id": "37561",
"Score": "1",
"Tags": [
"php",
"array"
],
"Title": "Copying a lot of code to filter four PHP arrays"
}
|
37561
|
<p>I have a program written in PyQt that has a lot of content. The basic way I've been doing it is using a stacked widget with all the content on pages and buttons to navigate through the pages.</p>
<p>However, a lot of the pages are just the same stuff with maybe a couple of different things. What I've been doing is:</p>
<ol>
<li>Initializing all the variables for the widgets</li>
<li>Creating a dictionary using the index as a string version of the variable name</li>
<li>Using the key as a list containing all the widgets settings</li>
<li>Using a <code>for</code> loop to recursively pass the values to a function that configures the widget</li>
</ol>
<p>I'm wondering if anyone has any recommendations to shorten or simplify this code. Coding suggestions are welcome as well.</p>
<pre><code>def widgetConfigurer(widgetType, xPos, yPos, xSize, ySize, name, image=None, styleSheet=None):
widgetType.setGeometry(QtCore.QRect(xPos, yPos, xSize, ySize))
widgetType.setObjectName(_fromUtf8(name))
if image != None:
widgetType.setPixmap(QtGui.QPixmap(_fromUtf8(image)))
if styleSheet != None:
widgetType.setStyleSheet(_fromUtf8(styleSheet))
...
self.someLabel = QtGui.QLabel(self.firstPage)
self.someButton = QtGui.QPushButton(self.firstPage)
self.someCheckBox = QtGui.QCheckBox(self.firstPage)
...
Bunch more widgets here
...
firstPageDict = {
"someLabel": [self.someLabel, -20, 70, 891, 551, None, "background-color: rgb(0, 0, 0);"]
"someButton": [self.someButton, 140, 90, 91, 41, None, None]
"someCheckBox": [self.someCheckBox, 260, 390, 71, 21, None, None]
}
for widgetName, widgetSettings in firstPageDict.items():
widgetConfigurer(widgetSettings[0], widgetSettings[1], widgetSettings[2], widgetSettings[3], widgetSettings[4], widgetName, widgetSettings[6], widgetSettings[7])
...
</code></pre>
|
[] |
[
{
"body": "<p>I quite that you've chosen to use a dictionary here as it is a readable way to group your widgets with their initialisation arguments, but I see two problems:</p>\n\n<ol>\n<li>You are labelling each widget twice: once in <code>self</code> and once in the dictionary. </li>\n<li>Your arguments are begging to be unpacked with <code>*</code></li>\n</ol>\n\n<p>I would tackle both of these by grouping the name, the initialisation and the arguments into one structure, and modifying the definition of widgetConfigurer so that you can unpack the arguments into it:</p>\n\n<pre><code>self.widgets = {\n # name : (widget, xpos, ypos, ... )\n 'someLabel': (QtGui.QLabel(self.firstPage), -20, 70, ... ),\n ... }\n\ndef widgetConfigurer(name, widget, xPos, yPos, ... ):\n ...\n\nfor name, args in self.widgets.iteritems():\n widgetConfigurer(name, *args)\n</code></pre>\n\n<p>The issue with this is that it's a bit ugly referencing a particular widget <code>someLabel = self.widgets['someLabel'][0]</code>. The most important thing is that you're unpacking those lists of arguments, everything else is just renaming for readability. </p>\n\n<p>One other thing: You should use <code>is</code> when comparing objects to <code>None</code> rather than <code>==</code> or <code>!=</code>. </p>\n\n<pre><code>if image is not None:\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T08:43:54.777",
"Id": "62999",
"Score": "0",
"body": "Genius! I was looking for a way to initialize the variables inline, but couldn't figure out how to access them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T17:33:33.413",
"Id": "37818",
"ParentId": "37571",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37818",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T05:37:53.460",
"Id": "37571",
"Score": "0",
"Tags": [
"python",
"pyqt"
],
"Title": "Widget configurer"
}
|
37571
|
<p>I want my code to be reviewed and I'd like to hear your opinions.</p>
<p>Sun's code to compute hash of string:</p>
<blockquote>
<pre><code>public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
</code></pre>
</blockquote>
<p>My code:</p>
<pre><code>public int hashCode2() {
if (hash == 0) {
for (int i = 0; i < value.length; i++) {
hash = 31 * hash + value[i];
}
}
return hash;
}
</code></pre>
<p>Why I consider my code an improved version:</p>
<ol>
<li>There is no need to create variables <code>h</code> and <code>val</code> as done in Sun's method.</li>
<li>The premature check of <code>value.length > 0</code> is not good enough to add this complexity.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T06:51:52.427",
"Id": "62217",
"Score": "3",
"body": "That code, which you claim is from sun, is broken, (some places you have `val` and other places you have `value`. Is this not a copy/paste?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:06:20.543",
"Id": "62237",
"Score": "2",
"body": "Not sure with what you mean. This code is a copy paste, it was intended to be a copy paste. I apologize but i dint see whats broken and where?"
}
] |
[
{
"body": "<p>I do not understand why <code>val</code> was introduced in addition to <code>value</code> – it isn't even a copy of the contents.</p>\n\n<p>On the other hand <code>h</code> does make sense once you consider thread safety. Assume we have two threads which calculate the hash of the string at nearly the same time – to trigger this, have both threads sleep for a moment when they enter the <code>if</code> branch. At the beginning, both threads will have <code>hash == 0</code>, so they will calculate the hash anew. With the original implementation, only a local variable is mutated, and then atomicaly committed to the <code>hash</code> variable. With your code, both threads mutate the same <code>hash</code> directly and will thus compute an invalid result. Your solution would be OK iff all accesses to the <code>hash</code> were synchronized (by locking the whole string object for each such method which is silly when using immutable strings).</p>\n\n<p>As this is Code Review, I will also suggest to return early in both implementations, instead of putting the whole calculation into an <code>if</code> branch. It is also nicer to use a foreach loop than to use indices. </p>\n\n<pre><code>public int hashCode() {\n int h = hash; // copy for thread safety\n if (h != 0 || value.length == 0) return h;\n\n for (char c : value) {\n h = 31 * h + c;\n }\n\n hash = h; // commit the change\n return h;\n}\n</code></pre>\n\n<p>On the other hand, a foreach-loop might not be as optimized as looping over the indices, and an early return could also impact what code is generated.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> The <code>value.length > 0</code> test in the original avoids committing the old value when no change of the hash is required (for the empty string). This can be relevant in cache-sensitive applications (remember that writing to shared memory can invalidate caches for other processors as well – we want to avoid this if possible. The condition also provides the guarantee that the loop will execute at least once if that branch is taken. Code ought to be generated in a way that this prior check does not reduce performance – on the contrary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:44:16.800",
"Id": "62235",
"Score": "0",
"body": "`val` was likely introduced as a micro-optimization to take out querying the `value` field in the loop. I've seen that pattern a few times in Sun's code elsewhere. They likely relied on constant extraction for the `value.length` test (easily provable because both value and it's length field are `final`)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:11:57.257",
"Id": "62238",
"Score": "0",
"body": "@amon great answer, but whats your take on second criteria ? `The premature check of value.length > 0 is not good enough to add this complexity.` Do u suggest it be a included in clause for early return ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:22:24.847",
"Id": "62241",
"Score": "1",
"body": "@JavaDeveloper This is very professional-looking and highly optimized code. My guess is (as I explained in my edit) that this avoids cache invalidation – but it isn't there just to look ugly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:25:13.223",
"Id": "62242",
"Score": "0",
"body": "@amon i understood your point. Very useful feedback."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:25:21.873",
"Id": "37578",
"ParentId": "37572",
"Score": "8"
}
},
{
"body": "<p>Something to remember about the Java libraries (especially older ones) is that they were written when Java was a new language. Some of the techniques and patterns we use as standard now were not available and the compilers, optimizers etc were a lot less smart.</p>\n\n<p>A lot of things we can just ignore now and let hotspot handle had to be considered in the code, and since these are core libraries that must run well on every possible Java device they cannot assume anything about the environment they run in so have to do as many optimizations as possible by hand.</p>\n\n<p>Sun's code to compute hash of string:</p>\n\n<pre><code>public int hashCode() {\n int h = hash;\n if (h == 0 && value.length > 0) {\n char val[] = value;\n for (int i = 0; i < value.length; i++) {\n h = 31 * h + val[i];\n }\n hash = h;\n }\n return h;\n}\n</code></pre>\n\n<p>My code:</p>\n\n<pre><code>public int hashCode2() {\n if (hash == 0) {\n for (int i = 0; i < value.length; i++) {\n hash = 31 * hash + value[i];\n }\n }\n return hash;\n}\n</code></pre>\n\n<p>The separate variable h is needed for thread safety. Otherwise you could potentially have a second thread see a partially computed h (or as already mentioned have two threads calculating a hash at the same time and interfering). Both will break things badly (for example inserting a string into a HashMap with the hash wrongly calculated and you will never find that String again).</p>\n\n<p>Copying value to val[] looks like a now-obsolete micro optimization.</p>\n\n<p>Again the immediate check for the array being empty is a micro optimization to handle the empty string case without entering the loop.</p>\n\n<pre><code>public int hashCode() {\n int h = hash; // copy for thread safety\n if (h != 0 || value.length == 0) return h;\n\n for (char c : value) {\n h = 31 * h + c;\n }\n\n hash = h; // commit the change\n return h;\n}\n</code></pre>\n\n<p>This is a very nice implementation, and in fact will be just as fast as the sun one since <code>foreach</code> over an Array internally uses a <code>for (i=0;..)</code> style approach.</p>\n\n<p>The problem with it is that it is not compatible with earlier versions of Java since the <code>foreach</code> loop is a recent addition to the language.</p>\n\n<p><strong>Micro optimisations</strong></p>\n\n<p>You will see this term a fair amount in this sort of discussion and in general it can be read to mean \"something that makes such a small performance increase that it is not worth the increased code complexity\". In the usual development scenario keeping code simple will reduce bugs and increase <em>developer</em> performance in terms of functionality provided for time spent far more than the micro optimisations can increase <em>application</em> performance.</p>\n\n<p>In fact in some cases micro optimisations actually degrade performance as they confuse the compiler which otherwise would make the same or better optimisations behind the scene.</p>\n\n<p>\"Premature optimisation is the root of all evil\" - Donald Knuth</p>\n\n<p>This is a well known quote in this field, although actually if you go hunt down the full quote there is far more to it than the catchy tagline.</p>\n\n<p>As a developer you should focus on writing clean and well structured code and on the big optimisations such as choosing the right algorithms, data structures, etc. Once that is done if you still need to increase performance then assuming you have the right algorithms and data structures (which will save far more than any amount of micro optimisation) that is when you look at progressively finer optimisations.</p>\n\n<p>But keeping the code clean and readable will gain you far more in the long run...quite apart from anything else it makes it easier to get the algorithm right!</p>\n\n<p>The core Java libraries are a special case as every single Java program is written on top of them, so slow performance there slows down everyone...and they have to run on every single JVM so they cannot rely on clever compilers or virtual machines.</p>\n\n<p>In many cases the core Java libraries are a bad source of coding examples. Partly for that reason and partly because they were written when Java was new and people were still learning the best ways to do things. In fact the book \"Effective Java\" by Joshua Bloch uses examples from the core Java libraries as things NOT to do.</p>\n\n<p>That's an excellent book by the way, you need some Java experience to appreciate it but I recommend it to all developers with a year or two of Java behind them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T05:11:08.580",
"Id": "62417",
"Score": "0",
"body": "Very useful explanation, but \"Again the immediate check for the array being empty is a micro optimization to handle the empty string case without entering the loop.\" - is it recommended to take effort to make a check or reduce code complexity by removing such micro optimizations - assuming cache invalidation is not a concern in some code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T06:29:18.240",
"Id": "62427",
"Score": "0",
"body": "See the small Essay I just added"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T14:02:56.657",
"Id": "37590",
"ParentId": "37572",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37578",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T06:45:57.540",
"Id": "37572",
"Score": "2",
"Tags": [
"java",
"strings",
"hashcode"
],
"Title": "Computing hash of string"
}
|
37572
|
<p>The title could probably be better, but in any case here goes.</p>
<p>I am having a bit of a problem understanding how to move methods/functions to other classes to organize things.</p>
<p>So, I have moved a method of sorts, but as I am skeptical of it, I would like to get it reviewed and hear opinions on what can be improved.</p>
<p>Here is the method ran from the default class:</p>
<pre><code>private void GetAudioDevices()
{
foreach (MMDevice device in Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))
{
comboBox1.Items.Add(device.FriendlyName);
Console.WriteLine("{0}, {1}", device.FriendlyName, device.State);
}
PlayBackDevices = Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
for (waveInDevice = 0; waveInDevice < NAudio.Wave.WaveIn.DeviceCount; waveInDevice++)
{
DeviceInfo = WaveIn.GetCapabilities(waveInDevice);
AudioDevices.Items.Add(DeviceInfo.ProductName);
}
if (AudioDevices.Items.Count > 0)
AudioDevices.SelectedIndex = 0;
AudioDevices.Items.Add("Wasapi Loopback");
ListenAudioAgain = false;
AudioDevice = AudioDevices.SelectedItem.ToString();
comboBox1.SelectedItem = VoiceChatClass.Enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).ToString();
}
</code></pre>
<p>Here it is when ran from a separate class:</p>
<pre><code>public static void GetAudioDevices(ComboBox comboBox1, ComboBox AudioDevices)
{
foreach (MMDevice device in VoiceChatClass.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))
{
comboBox1.Items.Add(device.FriendlyName);
Console.WriteLine("{0}, {1}", device.FriendlyName, device.State);
}
VoiceChatClass.PlayBackDevices = VoiceChatClass.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);
for (VoiceChatClass.waveInDevice = 0; VoiceChatClass.waveInDevice < NAudio.Wave.WaveIn.DeviceCount; VoiceChatClass.waveInDevice++)
{
VoiceChatClass.DeviceInfo = NAudio.Wave.WaveIn.GetCapabilities(VoiceChatClass.waveInDevice);
AudioDevices.Items.Add(VoiceChatClass.DeviceInfo.ProductName);
}
if (AudioDevices.Items.Count > 0)
AudioDevices.SelectedIndex = 0;
AudioDevices.Items.Add("Wasapi Loopback");
VoiceChatClass.ListenAudioAgain = false;
VoiceChatClass.AudioDevice = AudioDevices.SelectedItem.ToString();
comboBox1.SelectedItem = VoiceChatClass.Enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).ToString();
Console.WriteLine(VoiceChatClass.Enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia));
}
</code></pre>
<p>I am having difficulties understanding how to use static and non-static variables.</p>
<p>I just want to move it to a separate class for organization reasons. I know you can do it with partial classes, but sadly they are a bit "bugged" when used with a form in Visual Studio, as the design form will go away and stuff. It just gets unnecessarily complicated so to speak.</p>
<p>So anyway, what are your opinions upon viewing this? Is there a way to make it simpler? Are there any issues that have come up?</p>
|
[] |
[
{
"body": "<p>It seems to me like you are really asking about <code>static</code> vs <code>non-static</code></p>\n\n<ul>\n<li><code>static</code></li>\n</ul>\n\n<p>This means that your instance or instance variable is class-bound. No matter how many objects you make, they will all share the same <code>static</code> variable. Take this class with a <code>static</code> variable called <code>InstanceID</code>. What it will do is increment the <code>static</code> variable by one for each object you create</p>\n\n<pre><code>public class StaticVSNonStatic\n{\n private static int InstanceID = 0;\n\n public StaticVSNonStatic()\n {\n InstanceID++;\n }\n\n public int GetInstanceID() { return InstanceID; }\n}\n</code></pre>\n\n<p>so say that you later create N number of StaticVSNonStatic objects it won't matter which one you call because they will all share the same variable and will output the same value.</p>\n\n<pre><code>StaticVSNonStatic s1 = new StaticVSNonStatic();\nStaticVSNonStatic s2 = new StaticVSNonStatic();\nStaticVSNonStatic s3 = new StaticVSNonStatic();\n\nvar value = s1.GetInstanceID(); // this will be 3\n</code></pre>\n\n<p>And if we create any more object of <code>StaticVSNonStatic</code> the <code>InstanceID</code> value will just keep on incrementing. </p>\n\n<ul>\n<li><code>non-static</code></li>\n</ul>\n\n<p>Simply means a variable or an object that is not declared as static. A variable that is not static is instance-bound, and for each instance you create they will have their own variable. So if we go back to the class above and remove the <code>static</code> keyword the value will always be 1 regardless of which object you are accessing and regardless of how many objects you have.</p>\n\n<blockquote>\n <p>So anyway, what are your opinions upon viewing this? Is there a way to make it simpler? Are there any issues that have come up?</p>\n</blockquote>\n\n<p>It seems like you do not quite understand how and when to create a class to represent an object and you don't fully understand <code>static</code>. But it's ok, OOP is a hard design pattern to grasp. Let's take a look of what you can improve and what makes me say that you don't understand it...</p>\n\n<p>In a few places in your <em>\"seperate class\"</em> example you write</p>\n\n<pre><code>VoiceChatClass.ListenAudioAgain = false;\nVoiceChatClass.AudioDevice = AudioDevices.SelectedItem.ToString();\nVoiceChatClass.DeviceInfo = Audio.Wave.WaveIn.GetCapabilities(VoiceChatClass.waveInDevice);\nVoiceChatClass.PlayBackDevices = VoiceChatClass.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);\n</code></pre>\n\n<p>Which are all <code>static</code> variables which you are invoking, but to me it looks like this should be <code>non-static</code> because to me it looks like you should be able to have multiple \"unique\" VoiceChat objects. </p>\n\n<p>e.g., you should be able to have one VoiceChat object which has <code>ListenAudioAgain</code> set to false and another VoiceChat object which has it set to true. Or you could have two different VoiceChats with different PlayBackDevices. This is the way it should be but is impossible in your case because of the <code>static</code>.</p>\n\n<p>. The first step in making sure we can have multiple \"unique\" VoiceChat objects is by removing the <code>static</code> keyword from the class, which should give you a class that looks something like this (remember that this is a guess since I can't actually know what the class looks like):</p>\n\n<pre><code>public class VoiceChat\n{\n public bool ListenToAudioAgain { get; set; }\n public string AudioDevice { get; set; }\n public DeviceInfo DeviceInfo { get; set; }\n public PlayBackDevices[] PlayBackDevices { get; set; }\n}\n</code></pre>\n\n<p>And you would use this (in your second example) by first creating (or passing it in by your parameters) an instance of the <code>VoiceChat</code> class. In this case we named the instance to <code>voiceChat</code>, and then we access its instance members.</p>\n\n<pre><code>public static void GetAudioDevices(ComboBox comboBox1, ComboBox AudioDevices)\n{\n VoiceChat voiceChat = new VoiceChat()\n\n foreach (MMDevice device in voiceChat.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active))\n {\n comboBox1.Items.Add(device.FriendlyName);\n Console.WriteLine(\"{0}, {1}\", device.FriendlyName, device.State);\n }\n\n voiceChat.PlayBackDevices = voiceChat.Enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.Active);\n\n for (voiceChat.waveInDevice = 0; voiceChat.waveInDevice < NAudio.Wave.WaveIn.DeviceCount; VoiceChatClass.waveInDevice++)\n {\n voiceChat.DeviceInfo = NAudio.Wave.WaveIn.GetCapabilities(VoiceChatClass.waveInDevice);\n AudioDevices.Items.Add(voiceChat.DeviceInfo.ProductName);\n }\n\n if (AudioDevices.Items.Count > 0) {\n AudioDevices.SelectedIndex = 0;\n }\n\n AudioDevices.Items.Add(\"Wasapi Loopback\");\n\n voiceChat.ListenAudioAgain = false;\n voiceChat.AudioDevice = AudioDevices.SelectedItem.ToString();\n\n comboBox1.SelectedItem = voiceChat.Enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia).ToString();\n\n Console.WriteLine(voiceChat.Enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Multimedia));\n}\n</code></pre>\n\n<p>This is a quick introduction so if there's something unclear just let me know and I'll try to clarify.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T07:32:27.073",
"Id": "62438",
"Score": "0",
"body": "Okay after reading this i clearly see that i build my code completely different.\n\nI don´t even have Classes overall. I just have one huge class where i have Everything, which is why i want to separate it, but only because it´s so frustrating looking through the code as it´s so long.\n\nWhich is why i asked about Static, as Static is very easy to make in other Classes, like a simple calculation and such, but i can´t use the Forms etc.\n\nIsn´t there a way to just \"divide\" the Class into separate classes, but everthing it sunder the same \"Class\"? (I know partial class works, but it´s a bit bugged."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T07:46:13.490",
"Id": "62440",
"Score": "0",
"body": "Oaky think i will go will Partial Classes anyway, it works as intended if you ignore the \"bug\".\n\nWill accept this answer, much can be learned from this thorough explanation, Much Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T07:51:13.540",
"Id": "62441",
"Score": "0",
"body": "@Zerowalker - Partial is also the wrong approach for your code :P You should spend a couple of hours trying to learn about OOP and classes. What \"bug\" is there when using partial classes with a form?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T11:36:04.510",
"Id": "62447",
"Score": "0",
"body": "Probably, but i think it´s much easier to have everything in 1 class, i think of it like 1 program or something. Luckily at my skills, it works good enough, but i guess a limit will be hit sooner or later.\n\nThe \"bug\" is that if i make several Partial Classes of 1 class. And that main class is a form class, All will appear as Forms in Visual Studio, but all are New forms (empty window) and completely unnecessary, they don´t even show when starting the program as they aren´t even there.\n\nThere is a why to bypass it by disabling the \"form\" to show, but that disabled the main form as well."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:07:44.813",
"Id": "37575",
"ParentId": "37573",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T07:18:12.260",
"Id": "37573",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Improving function when used from another class"
}
|
37573
|
<p>I am using Dr.Racket, <em>Intermediate Student with Lambda</em>. I was wondering if there was any way I can simplify this code using any sort of method like lambda, abstraction, map, filter, etc.</p>
<pre><code> ; alien-at-edge?: alien --> boolean
(define (alien-at-edge? an-alien)
(or (alien-at-right-edge? an-alien)
(alien-at-left-edge? an-alien)))
; any-alien-at-edge?: loa --> boolean
(define (any-alien-at-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-edge? (first a-loa))
(any-alien-at-edge? (rest a-loa)))]))
;alien-at-left-edge?: alien --> boolean
(define (alien-at-left-edge? an-alien)
(<= (- (posn-x an-alien) ALIEN-DELTA-X) alien-half))
;alien-at-right-edge?: alien --> boolean
(define (alien-at-right-edge? an-alien)
(>= (+ (posn-x an-alien) ALIEN-DELTA-X) (- WIDTH alien-half)))
;any-alien-at-right-edge?: loa --> boolean
(define (any-alien-at-right-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-right-edge? (first a-loa))
(any-alien-at-right-edge? (rest a-loa)))]))
;any-alien-at-left-edge?: loa --> boolean
(define (any-alien-at-left-edge? a-loa)
(cond [(empty? a-loa) false]
[else (or (alien-at-left-edge? (first a-loa))
(any-alien-at-left-edge? (rest a-loa)))]))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:47:35.463",
"Id": "62336",
"Score": "0",
"body": "In what sort of ways do you think lambda, filter, map, and abstraction might be applied to simplify the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T18:27:12.647",
"Id": "62338",
"Score": "0",
"body": "Can you reindent the code? Also, have you read chapter 16 on \"Similarities\"? http://www.ccs.neu.edu/home/matthias/HtDP2e/part_three.html"
}
] |
[
{
"body": "<pre><code> ; alien-at-edge?: alien --> boolean\n(define (alien-at-edge? an-alien)\n(or (alien-at-right-edge? an-alien)\n(alien-at-left-edge? an-alien)))\n</code></pre>\n\n<p>Not much to do here but don't forget about indentation to make your code readable.</p>\n\n<pre><code>; any-alien-at-edge?: loa --> boolean \n(define (any-alien-at-edge? a-loa) \n(cond [(empty? a-loa) false] \n[else (or (alien-at-edge? (first a-loa)) \n (any-alien-at-edge? (rest a-loa)))]))\n</code></pre>\n\n<p>This pattern occurs a lot in functional programming: produce a value (a boolean here) by applying a function (<code>or</code> here) to your list. You can rewrite your function as:</p>\n\n<pre><code>; any-alien-at-edge?: loa --> boolean \n(define (any-alien-at-edge? a-loa) \n (foldl or false a-loa)\n</code></pre>\n\n<p>You can also use <code>ormap</code> if <code>foldl</code> is hard to understand.</p>\n\n<pre><code>;alien-at-left-edge?: alien --> boolean\n(define (alien-at-left-edge? an-alien)\n (<= (- (posn-x an-alien) ALIEN-DELTA-X) alien-half)) \n\n;alien-at-right-edge?: alien --> boolean\n(define (alien-at-right-edge? an-alien)\n(>= (+ (posn-x an-alien) ALIEN-DELTA-X) (- WIDTH alien-half))) \n</code></pre>\n\n<p>Watch out for indentation and trailing spaces.</p>\n\n<pre><code>;any-alien-at-right-edge?: loa --> boolean \n(define (any-alien-at-right-edge? a-loa) \n(cond [(empty? a-loa) false] \n[else (or (alien-at-right-edge? (first a-loa)) \n (any-alien-at-right-edge? (rest a-loa)))])) \n\n;any-alien-at-left-edge?: loa --> boolean \n(define (any-alien-at-left-edge? a-loa) \n(cond [(empty? a-loa) false] \n[else (or (alien-at-left-edge? (first a-loa)) \n (any-alien-at-left-edge? (rest a-loa)))]))\n</code></pre>\n\n<p>Those ones can also be implemented using foldl. Try it out!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:08:34.953",
"Id": "37580",
"ParentId": "37576",
"Score": "2"
}
},
{
"body": "<p>You can rewrite all your any- functions in one definition like this</p>\n\n<pre><code>(define (any predicate? a-loa) \n (cond [(empty? a-loa) false] \n [else (or (predicate? (first a-loa)) \n (any predicate? (rest a-loa)))]))\n</code></pre>\n\n<p>There is also a <a href=\"http://docs.racket-lang.org/reference/pairs.html#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._findf%29%29\" rel=\"nofollow\">findf</a> function in standard library</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-14T09:57:50.230",
"Id": "59992",
"ParentId": "37576",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:12:02.917",
"Id": "37576",
"Score": "3",
"Tags": [
"racket"
],
"Title": "Simplifying Dr.Racket alien code"
}
|
37576
|
<p>I am using Dr.Racket, <em>Intermediate Student with Lambda</em>. I was wondering if there was any way I can simplify this code using any sort of method like lambda, abstraction, map, filter, etc.</p>
<pre><code> ; DRAWING FUNCTIONS
; draw-rocket: rocket scene --> scene
; Purpose: To draw the given rocket in the given scene
(define (draw-rocket a-rocket a-scene)
(place-image rocket-img a-rocket ROCKET-Y a-scene))
; draw-alien: alien scene --> scene
; Purpose: To draw the given alien in the given scene
(define (draw-alien an-alien a-scene)
(place-image alien-img
(posn-x an-alien)
(posn-y an-alien)
a-scene))
; draw-aliens: loa scn --> scene
; Purpose: To draw the aliens in the given scene
(define (draw-aliens a-loa scn)
(cond [(empty? a-loa) scn]
[else (draw-alien (first a-loa) (draw-aliens (rest a-loa) scn)
)]))
;
; draw-shot: shot scene --> scene
; Purpose: To draw the given shot in the given scene
(define (draw-shot a-shot scn)
(place-image SHOT-IMG (posn-x a-shot) (posn-y a-shot) scn))
; draw-aliens: loa scn --> scene
; Purpose: To draw the aliens in the given scene
(define (draw-shots a-los scn)
(cond [(empty? a-los) scn]
[else (draw-shot (first a-los) (draw-shots (rest a-los) scn)
)]))
; draw-world: world --> scene
; Purpose: Draw the world in the empty scene
(define (draw-world a-world)
(draw-rocket (world-rocket a-world)
(draw-aliens (world-aliens a-world)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:33:34.533",
"Id": "62234",
"Score": "0",
"body": "Your `draw-world` has mismatched parentheses."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T13:14:33.107",
"Id": "62272",
"Score": "0",
"body": "In the future, please use better descriptive titles than \"Is there anyway of simplifying this code?\". I've edited both of the titles in your latest questions."
}
] |
[
{
"body": "<p>There are significant issues here:</p>\n\n<pre><code>; draw-rocket: rocket scene --> scene\n; Purpose: To draw the given rocket in the given scene\n(define (draw-rocket a-rocket a-scene) \n(place-image rocket-img a-rocket ROCKET-Y a-scene))\n</code></pre>\n\n<p>Why break the pattern from drawing code for the others? Use (pos-x a-rocket), (pos-y a-rocket) instead of a-rocket ROCKET-Y. That will help you abstract the code later on.</p>\n\n<pre><code>; draw-aliens: loa scn --> scene \n; Purpose: To draw the aliens in the given scene \n(define (draw-shots a-los scn) \n(cond [(empty? a-los) scn] \n[else (draw-shot (first a-los) (draw-shots (rest a-los) scn) \n )])) \n</code></pre>\n\n<p>This method has the wrong purpose and signature. This should be:</p>\n\n<pre><code>; draw_shots: los scn --> scn\n; Purpose: To draw the shots in the given scene\n</code></pre>\n\n<hr>\n\n<p>This code seems to have multiple issues:</p>\n\n<pre><code>; draw-world: world --> scene\n; Purpose: Draw the world in the empty scene\n(define (draw-world a-world)\n(draw-rocket (world-rocket a-world) \n(draw-aliens (world-aliens a-world)\n</code></pre>\n\n<ol>\n<li>The parentheses are mismatched, as mentioned in the comments.</li>\n<li>Why are the draw-shots methods not called here?</li>\n</ol>\n\n<p>I also think that you want to nest the calls so that the results are cumulative.\nThis is done like so:</p>\n\n<pre><code>; draw-world: world --> scene\n; Purpose: Draw the world in the scene (why would does it have to be empty?)\n(define (draw-world a-world)\n(draw-shots (world-shots \n(draw-rocket (world-rocket \n(draw-aliens (world-aliens a-world)))))))\n</code></pre>\n\n<hr>\n\n<p>As for using higher-order functions:</p>\n\n<p>Try using foldr like so:</p>\n\n<pre><code>(define (draw-shots a-los scn)\n(foldr draw-shot (first a-los) (rest a-los)))\n</code></pre>\n\n<p>Similarly, you can apply this to all the functions on lists.</p>\n\n<hr>\n\n<p>Finally, using abstraction is very easy here. Create a new type, called Sprite or Actor or something similar, and have Aliens, Shots and Rocket all extend it. That way you only need 2 functions: 1 for singular, 1 for plural. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-18T18:02:39.413",
"Id": "57404",
"ParentId": "37579",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T08:41:36.627",
"Id": "37579",
"Score": "2",
"Tags": [
"image",
"racket"
],
"Title": "Simplifying Dr.Racket drawing code"
}
|
37579
|
<p>Is there any other way to optimize the below code? I feel the below code is huge for the operations it performs.</p>
<pre><code>{
if ((currentElement == null ||
(firstGridRow["Low"].ToString() == string.Empty ||
firstGridRow["High"].ToString() == string.Empty ||
firstGridRow["Mean"].ToString() == string.Empty ||
firstGridRow["StdDev"].ToString() == string.Empty)))
{
continue;
}
double currentLow = Convert.ToDouble(firstGridRow["Low"]);
double currentHigh = Convert.ToDouble(firstGridRow["High"]);
double currentMean = Convert.ToDouble(firstGridRow["Mean"]);
double currentStdDev = Convert.ToDouble(firstGridRow["StdDev"]);
if (newRow.Length != 0)
{
AddColorList(currentElement, opid, currentLow, "Low", newRow, listCollectionLow);
AddColorList(currentElement, opid, currentHigh, "High", newRow, listCollectionHigh);
AddColorList(currentElement, opid, currentMean, "Mean", newRow, listCollectionMean);
AddColorList(currentElement, opid, currentStdDev, "StdDev", newRow, listCollectionStdDev);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:48:10.583",
"Id": "62243",
"Score": "0",
"body": "Is the double if() at the start a typo/copy paste issue?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:49:38.093",
"Id": "62245",
"Score": "0",
"body": "can you check the updated code now @Kyle? There is no copy paste or typo issues in the updated code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:56:54.813",
"Id": "62247",
"Score": "0",
"body": "Just wondering about the first two if statements (of three), they are identical. There is also one too many close brace (})."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:01:26.300",
"Id": "62249",
"Score": "0",
"body": "Thanks for your comments @Kyle. I have now removed the condition."
}
] |
[
{
"body": "<p>So I'll preface this with it's a little difficult without the actual context of the code, and that all suggestions need to be checked to ensure they don't break the existing flow of control.</p>\n\n<p>A few options:</p>\n\n<ul>\n<li>Breaking out repetitive operations into reusable methods</li>\n<li>Wrapper methods (within reason) to apply some common operations and call some other method</li>\n</ul>\n\n<p>With the assumption that these are inside of a loop, and you're not relying on an exception from the Convert.ToDouble() call to break out then you might consider some approaches like follows.</p>\n\n<p>Simplified from provided example. Assuming additional trailing '}' is not significant.</p>\n\n<pre><code>if (currentElement != null\n && !RowHasEmptyCells(firstGridRow, \"Low\", \"High\", \"Mean\", \"StdDev\")\n && newRow.Lenth != 0)\n\n{\n AddColourListWithSourceValue(firstGridRow, newRow, \"Low\", currentElement, opid, listCollectionLow);\n AddColourListWithSourceValue(firstGridRow, newRow, \"High\", currentElement, opid, listCollectionHigh);\n AddColourListWithSourceValue(firstGridRow, newRow, \"Mean\", currentElement, opid, listCollectionMean);\n AddColourListWithSourceValue(firstGridRow, newRow, \"StdDev\", currentElement, opid, listCollectionStdDev);\n}\n\n</code></pre>\n\n<p>Functions attempting to contain some of the previously duplicated logic:</p>\n\n<pre><code>//return true if any of the named cells in the row are 'empty'\nbool RowHasEmptyCells(RowType row, params string[] cellNames)\n{\n return cellNames.Any(cellName => row[cellName].ToString() == string.Empty);\n}\n\n//RowType is the type of your row object (DataGridRow?)\nvoid AddColourListWithSourceValue(RowType sourceRow, RowType newRow, string cellName, object currentElement, object opid, object listCollection)\n{\n double currentValue = Convert.ToDouble(sourceRow[cellName]);\n AddColourList(currentElement, opid, currentValue, cellName, newRow, listCollection);\n}\n</code></pre>\n\n<p>For the above <a href=\"http://msdn.microsoft.com/en-us/library/system.double.parse%28v=vs.110%29.aspx\" rel=\"nofollow\">double.Parse</a> or <a href=\"http://msdn.microsoft.com/en-us/library/system.double.tryparse%28v=vs.110%29.aspx\" rel=\"nofollow\">.TryParse</a> might be the way to go for a string > double conversion. If using Parse you could remove the empty cells check and just catch a FormatException/ArgumentNullException</p>\n\n<p>This can likely be improved upon, but I've tried to make the flow of the main part a bit easier to follow whilst keeping roughly the same logic.</p>\n\n<p><b>Edit 1:</b> Sorry - fixed typo. Also AddColourListWithSourceValue() is just a guess at what's going on :)</p>\n\n<p><b>Edit 2: </b> Quick edit with @svick's correction on logic and suggestion for LINQ to check for empty. Inverted to allow for the positive method prefix 'Has' instead of a 'CellsNotEmpty'. Would welcome thoughts on !IsSomething() vs IsNotSomething()...</p>\n\n<p><b>Edit 3:</b> <code>!=</code> to <code>==</code> in <code>RowHasEmptyCells()</code> as pointed out by @svick</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:28:10.490",
"Id": "62310",
"Score": "3",
"body": "I think that `AnyCellsEmpty()` would be much simpler if you used LINQ `Any()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:47:53.590",
"Id": "62357",
"Score": "0",
"body": "@svick thanks, Can you comment on how you might achieve this assuming something like a DataGridViewCellCollection? I'm assuming you referring to something like `return row.Any(c => c.Value.ToString() == string.Empty || c.Value == null);` (if row was a `IDictionary<string, string>` for example)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T23:59:20.447",
"Id": "62392",
"Score": "2",
"body": "Actually, now I think you got the logic wrong. The main part of the code should execute if all columns are nonempty, which means your `AnyCellsEmpty` should be renamed and it should contain `if (row[cellName].ToString() == string.Empty) return false`. Or using LINQ: `return cellNames.All(cellName => row[cellName].ToString() != string.Empty)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T00:25:14.723",
"Id": "62395",
"Score": "0",
"body": "Thanks again @svick. Quick edit, hopefully that captures the original intent. Would be interested to hear any thoughts on the negations in method names? Just reword to use a different adjective, ie: NamedCellsPopulated()?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T01:02:29.230",
"Id": "62403",
"Score": "2",
"body": "Yeah, I think it's better this way, methods shouldn't be negated by themselves, because you should never have `!IsNotSomething()`. And the best way to avoid that is to have all names positive. But you didn't apply de Morgan's laws correctly, it should be `cellNames.Any(cellName => row[cellName].ToString() == string.Empty)`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T01:15:01.383",
"Id": "62404",
"Score": "0",
"body": "The double negation is a good way to put it. Thanks also, RowHasEmptyCells() should actually work now :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:46:28.757",
"Id": "37585",
"ParentId": "37582",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "37585",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:43:23.850",
"Id": "37582",
"Score": "11",
"Tags": [
"c#"
],
"Title": "Multiple values against same condition"
}
|
37582
|
<p>I've created unit test for the "student" CRUD operations that looks like this:</p>
<pre><code>[Test]
public void Can_Exec_CrudOps()
{
#region Prepare
var account = Processor.Execute(new CreateAccount
{
Email = "email@example.com",
Username = "username",
Password = "password",
}).Result;
#endregion
var student = Processor.Execute(new CreateStudent
{
AccountId = account.EntityID
}).Result;
Assert.NotNull(student);
student.AreEqual(Processor.Execute(new GetStudent
{
EntityId = student.EntityID
}).Result);
student.AreEqual(Processor.Execute(new GetStudentByAccount
{
AccountId = account.EntityID
}).Result);
var upd_student = Processor.Execute(new UpdateStudent
{
EntityId = student.EntityID,
Flags = StudentFlags.Active
}).Result;
Assert.NotNull(upd_student);
upd_student.AreEqual(student);
upd_student.Flags.AreEqual(StudentFlags.Active);
Processor.Execute(new DeleteStudent
{
EntityId = student.EntityID
});
}
</code></pre>
<p>As you can see, the region #prepare contains code that will insert required data to the database for the current test to be possible. </p>
<p>Is it good practice to create a single test for each CRUD operation and then call that test inside the tests that require them?</p>
<p>What I'm thinking about would look like this:</p>
<pre><code> [TestFixture]
public class StudentTest : OperationTest
{
protected override IEnumerable<Type> ModelMappings
{
get
{
return NHMappings.EDUCATION;
}
}
[Test]
public void Can_Exec_CrudOps()
{
#region Prepare
// here is what changed //
var acc = new AccountTests();
var acc_id= acc.create_account();
#endregion
var student = Processor.Execute(new CreateStudent
{
//here too//
AccountId = acc_id
}).Result;
Assert.NotNull(student);
student.AreEqual(Processor.Execute(new GetStudent
{
EntityId = student.EntityID
}).Result);
student.AreEqual(Processor.Execute(new GetStudentByAccount
{
// and here//
AccountId = acc_id
}).Result);
var upd_student = Processor.Execute(new UpdateStudent
{
EntityId = student.EntityID,
Flags = StudentFlags.Active
}).Result;
Assert.NotNull(upd_student);
upd_student.AreEqual(student);
upd_student.Flags.AreEqual(StudentFlags.Active);
Processor.Execute(new DeleteStudent
{
EntityId = student.EntityID
});
// and here //
acc.deleteaccount(acc_id);
}
}
</code></pre>
<p>So the point is not to write the same code over and over again.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T13:28:31.657",
"Id": "62277",
"Score": "2",
"body": "Please include a language tag next time, since this looks like C#, I added that tag."
}
] |
[
{
"body": "<p>No, I would say, and the reason for that is that you have too many asserts in your test (it does to many thinks). There should only be one reason for a test to fail. So:</p>\n\n<p>Split your test into smaller ones with a more descriptive name and stick to one assert per test. By doing so it's also easier to track down why a test is failing, both in the case is the bug is in the test or in the production code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:48:19.983",
"Id": "62358",
"Score": "1",
"body": "I would also call these integration tests because they are hitting the database. Unit tests are written to test a very specific section of the logic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:27:06.870",
"Id": "37623",
"ParentId": "37584",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:44:14.803",
"Id": "37584",
"Score": "1",
"Tags": [
"c#",
"unit-testing"
],
"Title": "Is this good practice with unit-testing?"
}
|
37584
|
<p>This is more like a share and a request than a question. I converted Eric Lengyel's code, which calculates tangents of a mesh for the purpose of texturing and normal mapping, to support SIMD. For this I used DirectXMath library from windows SDK. I don't know if this is actually faster than regular floating point version (didn't test it yet). So, my request is: please let me know if you have any suggestions as to optimize the code even further.</p>
<pre><code>void CalculateTangentsAndNormals( vector<Vertex>& verts, vector <U32>& idx )
{
// Computing Tangent Space Basis Vectors for an Arbitrary Mesh
// http://www.terathon.com/code/tangent.html
//
const XMVECTOR NullVector = XMLoadFloat4A(&XMFLOAT4A(0.f, 0.f, 0.f, 0.f));
const XMVECTOR W_Null = XMLoadFloat4A(&XMFLOAT4A(1.f, 1.f, 1.f, 0.f));
const XMVECTOR signature = XMLoadFloat4A(&XMFLOAT4A(1.f,-1.f,-1.f,1.f));
XMMATRIX st(NullVector, NullVector, NullVector, NullVector);
vector <XMVECTOR> vTangents, vBitangents;
const U32 NumberOfVertices = (U32)verts.size();
vTangents.resize( NumberOfVertices , NullVector);
vBitangents.resize( NumberOfVertices, NullVector);
const U32 NumberOfIndices = (U32)idx.size();
for ( U32 i = 0; i < NumberOfIndices; ++i )
{
const U32 i0 = idx[i];
const U32 i1 = idx[++i];
const U32 i2 = idx[++i];
const XMVECTOR v0 = XMLoadFloat3A(&verts[i0].pos);
const XMVECTOR v1 = XMLoadFloat3A(&verts[i1].pos);
const XMVECTOR v2 = XMLoadFloat3A(&verts[i2].pos);
const XMVECTOR e0 = XMVectorMultiply( v1 - v0, W_Null);
const XMVECTOR e1 = XMVectorMultiply( v2 - v0, W_Null);
const XMMATRIX e01( e0, e1, NullVector, NullVector);
/* | e0.x e0.y e0.z 0 |
| e1.x e1.y e1.z 0 |
e01 = | 0 0 0 0 |
| 0 0 0 0 |
*/
const XMVECTOR t0 = XMLoadFloat2A(&verts[i0].tex);
const XMVECTOR t1 = XMLoadFloat2A(&verts[i1].tex);
const XMVECTOR t2 = XMLoadFloat2A(&verts[i2].tex);
XMVECTOR s = XMVectorMergeXY(t1 - t0, t2 - t0); // s = (t1x - t0x, t2x - t0x, t1y - t0y, t2y - t0y)
XMFLOAT4A d;
XMStoreFloat4A(&d, s);
const float DetInv = 1.0f/( d.x * d.w - d.z * d.y );
s *= DetInv;
s = XMVectorMultiply(s, signature); // s = (sx, -sy, -sz, sw)
const U32 *const pSrc = reinterpret_cast<const U32 *const>(&s);
U32* pDst = reinterpret_cast<U32*>(&st.r[0]);
pDst[0] = pSrc[3]; // _00 = sw
pDst[1] = pSrc[2]; // _01 = -sz
pDst = reinterpret_cast<U32*>(&st.r[1]);
pDst[0] = pSrc[1]; // _10 = -sy
pDst[1] = pSrc[0]; // _11 = sz
/* | sw -sz 0 0 |
| -sy sx 0 0 |
st = | 0 0 0 0 |*DetInv
| 0 0 0 0 |
*/
const XMMATRIX uv( XMMatrixMultiply(st, e01) );
vTangents[i0] += uv.r[0];
vTangents[i1] += uv.r[0];
vTangents[i2] += uv.r[0];
vBitangents[i0] += uv.r[1];
vBitangents[i1] += uv.r[1];
vBitangents[i2] += uv.r[1];
}
// orthogonalize normals and tangents
for ( U32 i = 0; i < NumberOfVertices; ++i )
{
const XMVECTOR normal = XMVector3Normalize(XMLoadFloat3A(&verts[i].normal));
// normalize tangents and orthogonalize TBN
XMVECTOR n0 = XMVector3Normalize( vTangents[i] - XMVector3Dot( normal, vTangents[i] ) * normal );
//calculate handedness
const XMVECTOR n1 = XMVector3Cross( normal, vTangents[i] );
const float w = (XMVector3Less(XMVector3Dot(n1, vBitangents[i] ), NullVector)) ? -1.f : 1.f;
n0 = XMVectorSetW(n0, w);
XMStoreFloat4A(&verts[i].tangent, n0);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Here's my pass at it; without the rest of your source I can't verify it's integrity so I don't know if this will compile correctly with the rest of your code, so hopefully it can help:</p>\n\n<pre><code>// outside function since they're consts, decreases run time as no more construction each function call\nconst XMVECTOR NullVector = XMLoadFloat4A(&XMFLOAT4A(0.f, 0.f, 0.f, 0.f));\nconst XMVECTOR W_Null = XMLoadFloat4A(&XMFLOAT4A(1.f, 1.f, 1.f, 0.f));\nconst XMVECTOR signature = XMLoadFloat4A(&XMFLOAT4A(1.f,-1.f,-1.f,1.f));\n\nvoid CalculateTangentsAndNormals( vector<Vertex>& verts, vector <U32>& idx )\n{\n // Computing Tangent Space Basis Vectors for an Arbitrary Mesh \n // http://www.terathon.com/code/tangent.html\n\n const U32 NumberOfVertices = (U32)verts.size();\n const U32 NumberOfIndices = (U32)idx.size();\n U32 i = 0;\n\n XMMATRIX st(NullVector, NullVector, NullVector, NullVector);\n\n // explicit construction\n vector <XMVECTOR> vTangents( NumberOfVertices , NullVector);\n vector <XMVECTOR> vBitangents( NumberOfVertices, NullVector);\n\n {\n U32 i0, i1, i2;\n XMVECTOR v0, v1, v2;\n XMVECTOR t0;\n XMFLOAT4A d;\n const U32* pSrc = 0;\n U32* pDst = 0;\n while (i < NumberOfIndices) {\n i0 = idx[i];\n i1 = idx[++i];\n i2 = idx[++i];\n\n v0 = XMLoadFloat3A(&verts[i0].pos);\n v1 = XMLoadFloat3A(&verts[i1].pos);\n v2 = XMLoadFloat3A(&verts[i2].pos);\n\n // e0, e1, NullVector, NullVector\n const XMMATRIX e01( XMVectorMultiply( v1 - v0, W_Null),\n XMVectorMultiply( v2 - v0, W_Null),\n NullVector,\n NullVector);\n /* | e0.x e0.y e0.z 0 |\n | e1.x e1.y e1.z 0 |\n e01 = | 0 0 0 0 |\n | 0 0 0 0 |\n */\n t0 = XMLoadFloat2A(&verts[i0].tex);\n\n // s = (t1x - t0x, t2x - t0x, t1y - t0y, t2y - t0y)\n XMVECTOR s = XMVectorMergeXY((XMLoadFloat2A(&verts[i1].tex) - t0),\n (XMLoadFloat2A(&verts[i2].tex) - t0));\n XMStoreFloat4A(&d, s);\n s *= (1.0f/( d.x * d.w - d.z * d.y )); //DetInv;\n s = XMVectorMultiply(s, signature); // s = (sx, -sy, -sz, sw)\n\n pSrc = reinterpret_cast<const U32*>(&s);\n pDst = reinterpret_cast<U32*>(&st.r[0]);\n pDst[0] = pSrc[3]; // _00 = sw\n pDst[1] = pSrc[2]; // _01 = -sz\n pDst = reinterpret_cast<U32*>(&st.r[1]);\n pDst[0] = pSrc[1]; // _10 = -sy\n pDst[1] = pSrc[0]; // _11 = sz\n\n /* | sw -sz 0 0 |\n | -sy sx 0 0 |\n st = | 0 0 0 0 |*DetInv\n | 0 0 0 0 |\n */\n\n const XMMATRIX uv( XMMatrixMultiply(st, e01) );\n\n vTangents[i0] += uv.r[0];\n vTangents[i1] += uv.r[0];\n vTangents[i2] += uv.r[0];\n\n vBitangents[i0] += uv.r[1];\n vBitangents[i1] += uv.r[1];\n vBitangents[i2] += uv.r[1];\n\n ++i;\n }\n } // end scope for temp vars\n i = 0;\n XMVECTOR normal, n0, n1;\n float w;\n while (i < NumberOfVertices) {\n normal = XMVector3Normalize(XMLoadFloat3A(&verts[i].normal));\n // normalize tangents and orthogonalize TBN\n n0 = XMVector3Normalize( vTangents[i] - XMVector3Dot( normal, vTangents[i] ) * normal );\n //calculate handedness\n n1 = XMVector3Cross( normal, vTangents[i] );\n w = (XMVector3Less(XMVector3Dot(n1, vBitangents[i] ), NullVector)) ? -1.f : 1.f;\n n0 = XMVectorSetW(n0, w);\n XMStoreFloat4A(&verts[i].tangent, n0);\n ++i;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:32:37.207",
"Id": "37635",
"ParentId": "37592",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T14:34:46.907",
"Id": "37592",
"Score": "1",
"Tags": [
"c++",
"optimization",
"computational-geometry",
"matrix",
"simd"
],
"Title": "Computing tangent space basis vectors for an arbitrary mesh"
}
|
37592
|
<p>I've played with F# for over a year, but I've only recently begun tentatively using it for professional work. I'm concerned that my c-style OOP principles are blinding me to the advantages of a functional language. I wrote the following code and it works just fine, but I feel like I'm just not quite using the language to its full potential. It still feels too C#-ish to me.</p>
<pre><code>open System
open System.Configuration
open System.DirectoryServices
open System.DirectoryServices.ActiveDirectory
type adEntry =
static member prop (name:string) (entry:SearchResult) =
( entry.Properties.Item( name ).Item( 0 ).ToString() )
static member formatUserName (format:string) (entry:SearchResult) =
let displayName = adEntry.prop "displayName" entry
let first = displayName.Substring ( 2 + displayName.IndexOf ", " )
let last = displayName.Substring ( 0, displayName.IndexOf ", " )
let ntid = adEntry.prop "cn" entry
format.Replace( "%f", first )
.Replace( "%l", last )
.Replace( "%i", ntid )
type ad =
static member query (filter:string) =
use searcher = new DirectorySearcher( filter )
Seq.cast<SearchResult> ( searcher.FindAll() )
[<EntryPoint>]
let main argv =
let groupQuery = "memberof=CN=" + ( ConfigurationManager.AppSettings.Item "ADGroup" ) + ",OU=XYZ Groups,DC=xyz,DC=com"
let results =
Seq.map
( adEntry.formatUserName "%f %l-%i" )
( ad.query groupQuery )
Seq.iter
( printf "%s\n" )
results
ignore ( Console.ReadKey true )
0
</code></pre>
<p>Am I missing out on F#'s power or maintainability by using types in the code above?</p>
|
[] |
[
{
"body": "<p>I think that functional programming shows itself most when you're manipulating data. You almost don't have that in your code, so there isn't much to change.</p>\n\n<p>Though there are some small things that you could change:</p>\n\n<ol>\n<li>You could create a type for user name. This would make sense if you wanted to do other things that formatting with them, otherwise, it would probably just complicate the code for no good reason.</li>\n<li>You have just three methods, I don't see much reason to put them into classes, you don't have to do that in F#. If you still think that it's worth it, you should use the F# equivalent of static classes, which are <a href=\"http://msdn.microsoft.com/en-us/library/dd233221.aspx\" rel=\"nofollow\">modules</a>, since all your functions are static.</li>\n<li>Similarly, you don't need <code>main</code>, you could just put all that code at the top level.</li>\n<li>To create <code>groupQuery</code>, I would use <code>sptrintf</code>, I think it makes the code more readable.</li>\n<li>Instead of <code>Seq.iter</code>, you could use <code>for..in</code>.</li>\n<li><code>ignore</code> is usually written using <code>|></code>, e.g. <code>Console.ReadKey true |> ignore</code>.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:46:22.267",
"Id": "62331",
"Score": "0",
"body": "I originally had my methods as \"global\" functions, but organized them into \"static classes\" in anticipation of this code growing in size as I add new features. How are functional programs typically organized?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:41:50.417",
"Id": "37608",
"ParentId": "37594",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37608",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:01:40.970",
"Id": "37594",
"Score": "2",
"Tags": [
"object-oriented",
"functional-programming",
"f#"
],
"Title": "Using types in F#"
}
|
37594
|
<p>I have the following class designs, and I'm looking for the best practices, aligned to the OOP design principles/patterns.</p>
<p>The <code>ParameterParser</code> will be used inside a foreach block through 10 items approximately.</p>
<p>Any comments regarding the method body will also be appreciated, though the focus of the question is on the class design/usage.</p>
<ol>
<li><p>Use the constructor to take the parameter and parse (one instance per parse)</p>
<pre><code>public class ParameterParser
{
private readonly Type _propertyType;
private readonly string _parameter;
public ParameterParser(Type propertyType, string parameter)
{
_propertyType = propertyType;
_parameter = parameter;
}
public object Parse()
{
if (typeof(IEnumerable).IsAssignableFrom(_propertyType)
|| typeof(IEnumerable<>).IsAssignableFrom(_propertyType))
return _parameter.Split(new[] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries);
if (_propertyType.IsEnum)
return Enum.Parse(_propertyType, _parameter);
return Convert.ChangeType(_parameter, _propertyType);
}
}
</code></pre></li>
<li><p>Parameterless constructor, multiple parsing per instance</p>
<pre><code>public class ParameterParser2
{
public object Parse(Type propertyType, string parameter)
{
//same code
}
}
</code></pre></li>
<li><p>A helper class, static method</p>
<pre><code>public class ParameterHelper
{
public static object Parse(Type propertyType, string parameter)
{
//same code
}
}
</code></pre></li>
</ol>
<p>I think the first one is more likely to be the best, but I can't explain which exactly are the advantages over the others. <strong>The question is "Considering design principles, which one is the best and why? Is there any pattern which would fit the scenario?"</strong>.</p>
|
[] |
[
{
"body": "<p>The important thing is to ask yourself: <strong>How would you use it?</strong></p>\n\n<p>If you are only going to parse with the same parameters multiple times, then the first method would be preferable since you only have to send it the parameters once. However, if you're doing the same thing over and over again then you should ask yourself if you really <em>need</em> to do it over and over again or if just once would be enough?</p>\n\n<p>Since the class are only using the <code>_propertyType</code> and <code>_parameter</code> in one method, I see no need to keep them stored in the instance of the class, and therefore I like method 2. The way I see it, this is the option that best fits <a href=\"http://en.wikipedia.org/wiki/Open/closed_principle\" rel=\"nofollow\">Open/Closed Principle</a>.</p>\n\n<p>Option 3 has a slight negative side that static methods can't be overridden (at least not in Java), and so it's harder to provide different implementations for it. However, if you are sure that you need one and only one implementation and that there's no need to override the method anywhere, then option 3 is fine from my perspective. Be aware that this option defies <a href=\"http://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow\">Dependency Inversion principle</a>, since you would always need to know the actual implementing class of the method (unless you write another class for determining which static method to call, but then why have the method static in the first place?)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:11:03.153",
"Id": "62309",
"Score": "1",
"body": "I'd upvote but I'm out of ammo :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:51:42.447",
"Id": "62332",
"Score": "0",
"body": "Not sure why you mention Java, the question is about C#. But overriding static methods doesn't make much sense anyway."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:52:58.567",
"Id": "62333",
"Score": "0",
"body": "@svick It's simply because I know Java a lot better than C#, and I know that even though the languages are similar there are differences too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:49:56.383",
"Id": "37599",
"ParentId": "37597",
"Score": "4"
}
},
{
"body": "<h3>Option 1 is surprising.</h3>\n<p>I find it funny that you have <code>return Enum.Parse(_propertyType, _parameter);</code> in a parameterless <code>Parse()</code> method. <code>Enum.Parse</code> is just an example (<code>int.Parse</code> would be another); these methods are commonly used by C# programmers and your single-use parser seems to break POLS in my opinion.</p>\n<h3>Option 2 is [more] consistent with the framework.</h3>\n<p>I don't mean to repeat what I just said, but it feels natural for a <code>Parse</code> method to take in all the parameters it needs. Now there is another problem here: your API is exposing <code>object</code>, which means the parsed value will need to be cast from the calling code, into the correct type. This is bad. Very bad. Nothing should ever be returning an <code>object</code>. If you're parsing a value type, you're boxing it right there. Is that not likely?</p>\n<p>How about keeping it type-safe and taking a generic type argument instead of a <code>Type</code> parameter?</p>\n<pre><code>public T Parse<out T>(string value)\n{\n ...\n return Convert.ChangeType(value, typeof(T));\n}\n</code></pre>\n<p>This way if <code>T</code> is a value type, you're not boxing it. And you're not returning an <code>object</code>, and it's still the calling code that decides what type to parse the string with.</p>\n<h3>Option 3 feels wrong.</h3>\n<p>Whenever I feel the need for a class to be called <code>xxxxxHelper</code>, something itches. The class should be <code>static</code> as well, if it's only going to expose <code>static</code> methods. That said, as @Simon has noted (oh, well, <em>Simon says...</em>) this brings DI to its knees. Best stay clear from that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:49:20.413",
"Id": "62316",
"Score": "4",
"body": "Simon says: Upvote this answer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:53:00.697",
"Id": "62321",
"Score": "0",
"body": "Haha thanks for your answer, but I'll have to ask over it: 1) I couldn't get the funny part (do you mean that it is useless, since `Convert.ChangeType` should work aswell?), Also, I didn't know that POLS principle, although it's very subtle and implicit, it's very nice to know that it has a name and is documented!\n2) the type is known only at runtime, so generics are not likely to be the best option, unless you tell me that reflection performs better over unboxing ;-)\n3) Certainly, something itches. I fell the same. I'm close to believe that helpers are i-dont-know-where-to-put-this-yet class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:02:15.067",
"Id": "62326",
"Score": "0",
"body": "@natenho Principle Of Least Surprise (/Astonishment) :) what I meant was that you're using a *parameterized* `Parse` method inside a *parameterless* `Parse` method, being parameterless should feel wrong when all `Parse` methods in the framework take in their parameters. 2) bah, generics was just an attempt at something :) - maybe `dynamic` can come to the rescue then? 3) 100% agree!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:06:36.587",
"Id": "62328",
"Score": "0",
"body": "@natenho wait a minute, *the type is known only at runtime* - then what do you pass for a `propertyType` argument? Say you've got `Parse(typeof(int), \"123\")`, would turn to `Parse<int>(\"123\")`... that wouldn't work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:37:05.397",
"Id": "62330",
"Score": "1",
"body": "ok, I don't want to increase the scope of the question here, but basically the context is that the parser is used to read a dictionary and pass its values to a instance of *any given* class (object properties are mapped to keys and are get/set via reflection). So the parser will always be called with a propetyInfo.PropertyType parameter."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:27:51.880",
"Id": "37602",
"ParentId": "37597",
"Score": "10"
}
},
{
"body": "<pre><code>if (_propertyType.IsAssignableFrom(typeof(IEnumerable))\n || _propertyType.IsAssignableFrom(typeof(IEnumerable<>)))\n</code></pre>\n\n<p>This is wrong.</p>\n\n<ol>\n<li><code>IsAssignableFrom()</code> is kind of confusing method, it works the other way around, it should be <code>typeof(IEnumerable).IsAssignableFrom(_propertyType)</code>. If you leave it the way it is, it will match <code>object</code>, but not for example <code>List<int></code>.</li>\n<li><code>IEnumerable<T></code> inherits from <code>IEnumerable</code>, so the second condition is not necessary.</li>\n<li>The second condition wouldn't work correctly anyway. Neither <code>List<int></code> nor <code>List<></code> match that (after the reverse from #1).</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T18:16:50.857",
"Id": "62335",
"Score": "0",
"body": "Wow! Thank you very much! I hadn't noticed it. It's very confusing indeed."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T18:21:59.380",
"Id": "62337",
"Score": "0",
"body": "I've just checked and the original code had already been fixed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T17:56:26.140",
"Id": "37609",
"ParentId": "37597",
"Score": "4"
}
},
{
"body": "<p>It seems using a generic class might be a good choice for this. See if this code fits what you're doing. Off the top of my head, I can't see where using <code>Convert.ChangeType</code> against a <code>string</code> is going to work except for the built-in primitive types or types that implicitly implement a string cast. But I guess if you're just parsing generic data though, that should be good enough.</p>\n\n<p>The first method just shows implementations for a primitive, an enum, an array, and a generic IEnumerable. </p>\n\n<p>I'm not clear about what you mean regarding it being used in a for loop. If your only using the function to recast your input, then a static method works fine here. Meaning that you don't have any other reason to store the property string for later use. If you do need to store it, then the static methods in the code below would need to be changed back to instance methods.</p>\n\n<p>BTW. For the life of me I couldn't get the </p>\n\n<p><code>if (typeof(IEnumerable).IsAssignableFrom(_propertyType) || typeof(IEnumerable<>).IsAssignableFrom(_propertyType))</code></p>\n\n<p>line to work against arrays or generic lists so I changed that in my example as well.</p>\n\n<p>Anyhow, I hope this helps. Good luck.</p>\n\n<pre><code>private void Test() {\n Console.WriteLine(ParameterParser<int>.Parse(\"2\"));\n Console.WriteLine(ParameterParser<ButtonBorderStyle>.Parse(\"2\"));\n Console.WriteLine(((string[])ParameterParser<int[]>.Parse(\"2, 3, 4, 5\")).Length);\n Console.WriteLine(((string[])ParameterParser<int[]>.Parse(\"2|3|4|5\")).Length);\n Console.WriteLine(((string[])ParameterParser<List<int>>.Parse(\"2, 3, 4, 5\")).Length);\n}\n\npublic class ParameterParser <T>{\n\n public static object Parse(string param) {\n\n try {\n if (typeof(T).IsArray || IsGenericList())\n return param.Split(new[] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries);\n\n if (typeof(T).IsEnum)\n return Enum.Parse(typeof(T), param);\n\n return Convert.ChangeType(param, typeof(T));\n\n } catch {\n return param;\n // throw new ArgumentException(param + \"cannot be converted to \" + typeof(T).ToString());\n }\n }\n private static bool IsGenericList(){\n foreach (Type type in typeof(T).GetInterfaces()) { \n if (type.IsGenericType) {\n if (type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) {\n return true;\n }\n }\n }\n\n return false;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:29:14.817",
"Id": "62345",
"Score": "0",
"body": "Thanks for your answer, my actual code is currently very close to yours, but I can't use generics because T is only known during run-time, i.e. T is known via reflection."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:35:46.217",
"Id": "62348",
"Score": "0",
"body": "if you're already using reflection you could use `Activator.CreateInstance` dynamically at run-time. But either way, the `IsGenericList` should be useful. Again, good luck."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:20:28.367",
"Id": "37615",
"ParentId": "37597",
"Score": "2"
}
},
{
"body": "<p>Although I'd like to know more about where it's being called from and where it's likely to be used in the future, my vote goes to #3.</p>\n\n<ul>\n<li><p>#1 is over-complicating a simple task. The only reason it would make sense to take that approach is if you anticipate needing other parameter-related functions that also operate on <code>propertyType</code> and <code>parameter</code>, in which case the class would be <code>Parameter</code>, with <code>Parse()</code> as a function. In general if a class exists solely to hold one function, then there's either a better place for that function, or a more generic class that should be made instead.</p></li>\n<li><p>#2 Likely better than #1 because it allows for a wider range of parameter-related functions that act on something other than <code>propertyType</code> and <code>parameter</code>, but the same criticism applies. Either name the class <code>Parameter</code> with an eye toward expanding it in the future, or go with #3.</p></li>\n<li><p>#3 Completely acceptable and appropriate in this case. If this is your only parameter related helper function and you don't see a need for others in the future, then there is no reason to instantiate an object. This is a perfect case for a <code>static</code> function: takes a couple of parameters, returns the result, is completely ephemeral and stores no state information.</p></li>\n</ul>\n\n<p>Overall, I generally favor the solution that does the minimum necessary and requires the least to use. Even if there are other parameter-related functions in the future, I would keep the class and functions <code>static</code> unless a need arose to save state information or take advantage of another instantiated-object feature.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:13:45.170",
"Id": "62375",
"Score": "0",
"body": "code is only most simple when you cannot take anything from it. someone else said that before me but it fits."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T01:26:16.650",
"Id": "62405",
"Score": "0",
"body": "I understand your point of view, and I confess that is very tempting to write static functions in several scenarios when you came from structural programming. As I told before, generally this kind of function is placed in a helper because they don't seem to fit in an object, and its behavior could be so simple that it may be considered a freeloader code smell.\nI still accept the #2 as the best, not just because its more elegant, but because it seems safer to consider that an object is more likely to survive a future refactoring / new implementation..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:54:13.560",
"Id": "37629",
"ParentId": "37597",
"Score": "2"
}
},
{
"body": "<p>I agree with the other posters in that it depends on how the class is to be used.</p>\n\n<p>In addition, for completeness, I'd like to propose a fourth pattern.</p>\n\n<p>This pattern is intended for a specific sort of use-- dealing with parameters as stateful objects that need to be worked with in a variety of ways. To do this well, the new design will have to address a couple issues:</p>\n\n<ol>\n<li><p>Stateful classes that have a name ending with \"er\" should set off a warning. If a class is stateful, it represents a thing, not an action; \"parser\" \"controller\" \"helper\" are all suspicious in this case. The class IS a thing, it doesn't DO a thing (the methods do). (Another warning sign is that the class has only one method. It indicates procedural rather than object-oriented thinking.)</p></li>\n<li><p>Type conversion, by convention in the CLR, is performed using methods that begin with \"To\" e.g. \"ToString()\" or \"Convert.ToInt32\"</p></li>\n<li><p>It would be nice if we could repeatedly call \"Parse\" without incurring overhead every time. In this example the overhead is very small but we're talking about general patterns here. </p></li>\n<li><p>The class ought to be extensible. For example, what if you need to compare parameters? It'd be nice to be able to implement IComparable. What if you want to be able to print it to logs? You'd want to override ToString. Etc.</p></li>\n</ol>\n\n<p>So here's my solution:</p>\n\n<pre><code>public class Parameter : IComparable\n{\n private readonly Type _type;\n private readonly string _value;\n private object _objectResult = null;\n\n public Parameter(Type type, string val)\n {\n _type = type;\n _value = val;\n\n //The following line is optional, depending if you want lazy evaluation vs. control over when the logic is executed\n //_objectResult = ParseAsObject();\n }\n\n private object ParseAsObject()\n {\n if (typeof(IEnumerable).IsAssignableFrom(_type)\n || typeof(IEnumerable<>).IsAssignableFrom(_type))\n return _value.Split(new[] { ',', ';', '|' }, StringSplitOptions.RemoveEmptyEntries);\n\n if (_type.IsEnum)\n return Enum.Parse(_type, _value);\n\n return Convert.ChangeType(_value, _type);\n }\n\n public object ToObject()\n {\n if (_resultObject == null) _resultObject = ParseAsObject(); //Not needed if you chose to uncomment the optional line above\n return _resultObject;\n }\n\n public override void ToString()\n {\n return ToObject().ToString();\n }\n\n public int CompareTo(object compareTo)\n {\n Parameter p = compareTo as Parameter;\n if (p == null) throw new ArgumentException(\"Can't compare to that!\");\n return this.ToString().CompareTo(p.ToString());\n }\n}\n</code></pre>\n\n<p>In general I tend to prefer the lazy evaluation approach (the values are only parsed when the parsed value is needed and not before) but again we are talking general patterns here. In some cases you will want to the caller to know exactly when the heavy lifting takes place, e.g. if the parsing operation requires a DB call or something expensive. I've given you the option with the commented-out lines above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T11:51:17.250",
"Id": "62449",
"Score": "0",
"body": "Very good approach, I really appreciated your issues list, specially the first item. But in this case, it's a class which needs to perform operations over another kind of object (every string value in a dictionary<string, string>, for instance). I don't think it should be stateful, but I'm thinking about the generality of your statement whether a class have to \"DO a thing\" or \"BE a thing\". Btw, although the class is extensible, YAGNI principle is a worth thinking, so I don't need to implement IComparable neither override ToString at *this* moment, then the class ends up with only one method."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T09:15:58.040",
"Id": "37659",
"ParentId": "37597",
"Score": "3"
}
},
{
"body": "<p>Well first decide <strong>what type of object you are going to design</strong> whether its <strong>statefull or stateless</strong>. What I understood from your class purpose is to parse a parameter. The way you have designed is state full which is absolutely unnecessary and might be not thread safe (depends on usage). </p>\n\n<p>Parsing is generic thing and it has no necessity to hold any state. Fine how would you use your class?</p>\n\n<pre><code>//Parsing first parameter \nParameterParser parser1 = new ParameterParser(“xx”,”yy”);\nObject parameter1 = Parser1.parse();\n</code></pre>\n\n<p>If I want to parse another parameter , I should create new instance which is unnecessary since its not statefull object .</p>\n\n<pre><code>ParameterParser parser2 = new ParameterParser(“AA”,”BB”);\nObject parameter2 = Parser2.parse();\n</code></pre>\n\n<p>Instead of this you could make it as stateless object and its thread safe.</p>\n\n<pre><code>//You can also think of make it singleton or static since its stateless \nParameterParser parser1 = new ParameterParser();\nObject1 parameter1 =Parser1.parse(“xx”,”yy”);\nObject1 parameter2 =Parser1.parse(“AA”,”BB”);\n\n// You can also think of accessors method based implementation to change the behaviour at run-time. If you feel some other operations/methods are depends on your variables passed in then consider this one... This is not thread safe by nature but you can make it as thread safe. \nParameterParser parser1 = new ParameterParser();\nparser1.setXXX(\"xxx\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:09:31.443",
"Id": "62639",
"Score": "0",
"body": "It's almost the essence of the other answers: Statefull vs. Stateless and Static vs. Non-static implementation.\n+1 for raising the threading concern. I'm learning a lot with this question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:12:20.393",
"Id": "37744",
"ParentId": "37597",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37602",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:28:22.217",
"Id": "37597",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"classes"
],
"Title": "One instance per method call or multiple method call per instance"
}
|
37597
|
<p>I recently started learning and programming Java based on a series of beginner videos created by a Youtuber (TheNewBoston), who had a tutorial on a calculator. So based on everything else I've previously learned, I have tried to mix it in to create a bit more advanced one. If you are able to minimize and clean up the code, please give a brief explanation. I'd like some tips as well.</p>
<pre><code>import java.util.Scanner;
class apples{
public static void main(String args[]){
Scanner checker = new Scanner(System.in);
int selection = 0;
double fnum, snum, answer;
System.out.println("Calculator Program Initialized");
System.out.println("Please select your math operator");
System.out.println("Enter 1 for Addition");
System.out.println("Enter 2 for Subraction");
selection = checker.nextInt();
if (selection == 1){
System.out.println("Enter your first number here");
fnum = checker.nextDouble();
System.out.println("Enter your second number here");
snum = checker.nextDouble();
answer = fnum+snum;
System.out.println("Answer: " + answer);
System.out.println("Thank you for using my calculator");
}else{
System.out.println("Enter your first number here");
fnum = checker.nextDouble();
System.out.println("Enter your second number here");
snum = checker.nextDouble();
answer = fnum-snum;
System.out.println("Answer: " + answer);
System.out.println("Thank you for using my calculator");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:00:34.947",
"Id": "62302",
"Score": "0",
"body": "Oh, and by the way would I be able to apply a Switch Statement in this, since i tested the variable selection for the operator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:34:04.233",
"Id": "62312",
"Score": "0",
"body": "What if I enter a 0? You should handle that case, too!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:53:59.660",
"Id": "62322",
"Score": "0",
"body": "Right, that's what i was thinking =3"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T18:53:44.563",
"Id": "64068",
"Score": "0",
"body": "There are simple Swing calculator and Awt calculator using java [Swing Calculator](https://github.com/ThilinaM/Basic-swing-calculator-Using-NetBeans.git) and\n[Awt calculator](https://github.com/ThilinaM/Basic-awt-calculator.git)"
}
] |
[
{
"body": "<p>In this case we'd eliminate the repeated code and have left only the different code from your original:</p>\n\n<pre><code>import java.util.Scanner;\n\nclass apples{\n public static void main(String args[]){\n Scanner checker = new Scanner(System.in);\n int selection = 1;\n double fnum, snum, answer;\n\n while(selection != 0){\n\n System.out.println(\"Calculator Program Initialized\");\n System.out.println(\"Please select your math operator\");\n System.out.println(\"Enter 1 for Addition\");\n System.out.println(\"Enter 2 for Subraction\");\n System.out.println(\"Enter 0 to exit\");\n\n selection = checker.nextInt();\n if(selection==0) break;\n\n System.out.println(\"Enter your first number here\");\n fnum = checker.nextDouble();\n System.out.println(\"Enter your second number here\");\n snum = checker.nextDouble();\n\n switch(selection){\n case 1: \n answer = fnum+snum;\n case 2:\n answer = fnum-snum;\n System.out.println(\"Answer: \" + answer);\n break;\n default:\n System.out.println(\"Invalid option, try again \");\n }\n\n }\n System.out.println(\"Thank you for using my calculator\");\n\n }\n}\n</code></pre>\n\n<p>The enter first and second number are repeated, and the print the answer, so we take that out of the condition and differentiate only the operation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:34:34.953",
"Id": "62313",
"Score": "0",
"body": "Even though this simplifies the code, please add a description outside the code block about what you are doing and why you are doing it and why it is better. We don't like \"code only\" answers here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:38:26.103",
"Id": "62315",
"Score": "0",
"body": "Thank you very much sir, I'll look into this. And technically if I used a switch statement such as while(selection <= 2) that would work too right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:49:41.637",
"Id": "62317",
"Score": "0",
"body": "edited it with a loop"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:51:56.570",
"Id": "62320",
"Score": "0",
"body": "Yep, that makes more sense now. Thank your fernando"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:31:23.890",
"Id": "37603",
"ParentId": "37598",
"Score": "1"
}
},
{
"body": "<pre><code>class apples{\n</code></pre>\n\n<p>Naming your class something like <code>apples</code> is always wrong. Java class names start with a Capital letter and are written in CamelCase. Thus, regardless of whether the name itself is good, it should be spelled <code>Apples</code>, not <code>apples</code>.</p>\n\n<p>Also, you need to add a javadoc comment to the class that explains exactly what it does, when to or not use it, and all that.</p>\n\n<p>About the name itself, now. Is <code>Apples</code> really a good summary of what this class is? Looking at your dialogue, probably not; maybe <code>BasicInteractiveCommandlineCalculator</code> would be a better fit? In any case, change the name to something that actually has to do with the class's purpose.</p>\n\n<hr>\n\n<pre><code>public static void main(String args[]){\n</code></pre>\n\n<p>Again, no javadoc. Javadoc for a main method should include information about what arguments it takes or how to invoke it. Pretend you were calling it from the command line, exactly what arguments are you passing it? If it doesn't take any arguments, say no args, but at least say something.</p>\n\n<hr>\n\n<pre><code>Scanner checker = new Scanner(System.in);\n</code></pre>\n\n<p>Here, <code>checker</code> isn't exactly a great name for this. Call it something shorter, like <code>in</code>.</p>\n\n<p>While your initialization of the scanner is fine, it really ought to be created in a try-with-resources, so you can easily change to use a different input stream as needed, like a file. Instead write:</p>\n\n<pre><code>try(Scanner in = new Scanner(System.in)){\n</code></pre>\n\n<hr>\n\n<pre><code>System.out.println(\"Calculator Program Initialized\");\nSystem.out.println(\"Please select your math operator\");\nSystem.out.println(\"Enter 1 for Addition\");\nSystem.out.println(\"Enter 2 for Subraction\");\n</code></pre>\n\n<p>Doesn't this seem a little wordy for a simple calculator app? You should try talking less, and just say what you mean.</p>\n\n<p>Also, you shouldn't use <code>System.out</code> for permanent output statements. Instead, add another declaration to your try statement. That way, you can easily change the desired stream later, with only minimal modification:</p>\n\n<pre><code>try(Scanner in = new Scanner(System.in); PrintStream out = System.out){\n</code></pre>\n\n<p>Now, replace the dialog with a much shorter one:</p>\n\n<pre><code>out.println(\"Enter operation (+ or -):\");\n</code></pre>\n\n<p>Match the input then with <code>in.next(String regex)</code>, so it will just wait until there is a valid input.</p>\n\n<p>Handling the input should be way easier, too. Using java 7, we can <code>switch</code> on a string value:</p>\n\n<pre><code>String op = in.next(\"[+-]\");\n\n// ...\n\nswitch(op){\ncase \"+\": // ...\ncase \"-\": // ...\n}\n</code></pre>\n\n<p>If you don't have java 7, then you should still allow the user to input this way, you just need to use <code>if</code> statements instead.</p>\n\n<hr>\n\n<p>Now, the main problem, though, is in the way it handles the following dialog. Not only is some of the dialog itself duplicated, confusing data with logic, but in the way it computes the answer.</p>\n\n<p>Refactoring the dialog out, and simplifying it, we get much, much neater code:</p>\n\n<pre><code>out.println(\"x=\");\nfnum = in.nextDouble();\nout.println(\"y=\");\nsnum = in.nextDouble();\n\nswitch(op){\ncase \"+\": answer = fnum + snum; break;\ncase \"-\": answer = fnum - snum; break;\ndefault: answer = Double.NaN;\n}\n\nout.println(\"x\" + op + \"y=\" + result);\n</code></pre>\n\n<hr>\n\n<p>This here is only the most basic level of revisions that ought to be made to the code. An application or command that attempts to do this would be expected to support all standard mathematical operations, and to be able to parse a <em>complete</em> expression passed to it as a string.</p>\n\n<p>I once wrote a program like that, that supported all java operators and every function from <code>java.util.Math</code>. My approach was to use a runtime compiler <a href=\"http://docs.codehaus.org/display/JANINO/Home\" rel=\"nofollow\">janino</a> to <em>compile as java source code</em> an expression given to it. (It probably would have been simpler to just use syntax trees though; configuring everything was a nightmare.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:56:34.893",
"Id": "62324",
"Score": "1",
"body": "Thank you very much AJ, I appreciate all your advice and corrections. But once again, I'm new to Java so I'll need some time :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T16:53:22.853",
"Id": "37605",
"ParentId": "37598",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "37605",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:43:38.457",
"Id": "37598",
"Score": "6",
"Tags": [
"java",
"beginner",
"calculator"
],
"Title": "Cleaning up calculator program"
}
|
37598
|
<p>I have a Django form with a lot of fields, including some FileFields. I want to validate the form based on the contents of the files: they must be valid gdal datasets, and if both are present (one of them is optional) then the optional dataset's extent must entirely cover the required file's extent.</p>
<p>To do this, I have to save the files to a temporary place and process them there, which is different from how I'd usually treat uploaded files in Django (only process them after form validation). The view needs to know that the files are already saved and how to get at them, and it has to make sure to clean up the files afterwards.</p>
<p>I've omitted parts of the code, the relevant parts of the Form look like this:</p>
<pre><code>class FormStep1(forms.Form):
waterlevel = forms.FileField(required=True)
customlanduse = forms.FileField(required=False)
def add_field_error(self, field, message):
"""Assumes this field has no errors yet"""
self._errors[field] = self.error_class([message])
def clean(self):
"""Check that optional custom datasets cover the right area."""
cleaned_data = super(FormStep1, self).clean()
if 'customlanduse' and 'waterlevel' in cleaned_data:
# Save files to a temporary directory to check them
self.temp_directory = tempfile.mkdtemp()
for field in ('customlanduse', 'waterlevel'):
filename = os.path.join(
self.temp_directory, cleaned_data[field].name)
with open(filename, 'wb') as f:
for chunk in cleaned_data[field].chunks():
f.write(chunk)
cleaned_data[field + '_filename'] = filename
# Open datasets
customlanduse = gdal.Open(cleaned_data['customlanduse_filename'])
waterlevel = gdal.Open(cleaned_data['waterlevel_filename'])
if customlanduse is None:
self.add_field_error("customlanduse", "Can't open dataset")
if waterlevel is None:
self.add_field_error("waterlevel", "Can't open dataset")
if customlanduse is not None and waterlevel is not None:
water_extent = extent_from_dataset(waterlevel)
landuse_extent = extent_from_dataset(customlanduse)
if not extent_within_extent(
inner_extent=water_extent, outer_extent=landuse_extent):
self.add_field_error('customlanduse', "Not within extent")
return cleaned_data
def cleanup_files(self):
"""This must be called after processing the saved files."""
shutil.rmtree(self.temp_directory)
</code></pre>
<p>In short: don't really like handling downloaded files in a Form, but it works. Is there a better way?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T15:58:35.270",
"Id": "37600",
"Score": "4",
"Tags": [
"python",
"form",
"django"
],
"Title": "Django form validation based on the contents of uploaded files"
}
|
37600
|
<p>I created a plug-in powered by jQuery that simplifies the developer's life to create responsive applications. It's flexible and I want to give to users a good syntax to write.</p>
<p>How can I improve this?</p>
<p><a href="https://github.com/chiefGui/sensitivejs" rel="nofollow">GitHub</a></p>
<pre><code>; (function ($) {
var debug = {
ranges: [],
refreshRanges: function(ranges) {
this.ranges = ranges;
},
invoke: function(reference) {
console.log(this.warnings[reference].apply());
},
clean: function() {
this.ranges = undefined;
},
warnings: {
inRange: function () {
return 'You\'re in range between ' + debug.ranges[0] + 'px and ' + debug.ranges[1] + 'px.';
},
outOfRange: function() {
return 'You\'re out of range between ' + debug.ranges[0] + 'px and ' + debug.ranges[1] + 'px.';
}
}
};
var screen = {
inRange: undefined,
outOfRange: undefined,
firstTimeResponsive: true,
sensibilize: function(ranges, action, callback, debugging) {
if (this.isInRange(ranges) === true) {
this.outOfRange = false;
if (this.inRange === false || (typeof this.inRange === 'undefined' && this.firstTimeResponsive === true)) {
action(device);
this.inRange = true;
this.firstTimeResponsive = false;
if (debugging === true) {
debug.refreshRanges(ranges);
debug.invoke('inRange');
debug.clean();
}
};
} else {
this.inRange = false;
if (this.outOfRange === false || (typeof this.outOfRange === 'undefined' && this.firstTimeResponsive === true)) {
if (this.firstTimeResponsive === false) {
callback(device);
}
this.outOfRange = true;
this.firstTimeResponsive = false;
if (debugging === true) {
debug.refreshRanges(ranges);
debug.invoke('outOfRange');
debug.clean();
}
};
}
},
isInRange: function(ranges) {
if (this.reached(ranges)) {
return true;
};
},
reached: function(range) {
var windowWidth = $(window).width();
if (windowWidth >= range[0] && windowWidth <= range[1]) {
return true;
}
}
};
var device = {
identification: navigator.userAgent,
isMobile: function() {
return /mobi/i.test(navigator.userAgent);
},
Android: function() {
return navigator.userAgent.match(/Android/i);
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i);
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i);
},
Opera: function() {
return navigator.userAgent.match(/Opera Mini/i);
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i);
},
any: function() {
return (device.Android() || device.BlackBerry() ||
device.iOS() || device.Opera() || device.Windows());
}
};
$.sensitive = function(ranges, action, callback, options) {
var defaults = {
debugging: false,
handheldDevicesOnly: false,
ultimateScreenWidth: 15360
};
var plugin = this;
plugin.settings = $.extend({}, defaults, options);
if (typeof ranges[1] === 'undefined') {
ranges[1] = plugin.settings.ultimateScreenWidth;
};
if (plugin.settings.handheldDevicesOnly === true && device.isMobile() === false) {
return null;
};
$(window).on('resize', function() {
screen.sensibilize(ranges, action, callback, plugin.settings.debugging);
}).trigger('resize');
};
}(jQuery));
</code></pre>
|
[] |
[
{
"body": "<p>My 2 cents : </p>\n\n<ul>\n<li>Why jQuery, libraries targetting mobile should not require jQuery, #perfmatters</li>\n<li>Your github project should have a production version where debug is excluded, your code is 4215 bytes with debug feature, 3014 without debugging ( removing all debugging related code )</li>\n<li>Your code maintains both the value of <code>inRange</code> and <code>outOfRange</code>, you should only need 1 ?</li>\n<li><code>this.firstTimeResponsive === true</code> can be replaced with <code>this.firstTimeResponsive</code></li>\n<li><code>this.inRange === false || (typeof this.inRange === 'undefined')</code> can be <code>!this.inRange</code></li>\n<li><code>isInRange</code> seems pointless, it's a wrapper around <code>reached</code> without added value ?</li>\n<li><code>ranges</code> is an unfortunate parameter name, since you only pass 1 range ( from/to pair )</li>\n<li><code>action</code> and <code>callback</code> are misleading as parameter names, how about <code>inRangeCallback</code> and <code>outOfRangeCallback</code> ?</li>\n</ul>\n\n<p>From a design perspective, why do you track <code>firstTimeResponse</code> and also track resizing of the browser, it seems pointless. I think you need to test resizing.</p>\n\n<p>Whereas this review seems harsh, I think the library can be put to good use, but it needs some serious clean up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T10:29:20.557",
"Id": "62444",
"Score": "0",
"body": "Do you think that `debugging` parameter is necessary? I mean, isn't an argument, it's just an option. `sensibilize: function(range, inRangeCallback, outOfRangeCallback, debugging) { ... }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:00:35.183",
"Id": "62451",
"Score": "0",
"body": "It's 25% less code without debugging code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T11:52:35.480",
"Id": "62629",
"Score": "0",
"body": "I followed your hint — I removed debugging. If you want to see the new version, [jump in](https://github.com/chiefGui/sensitivejs/blob/v0.4.0/dist/sensitive-0.4.0.js)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T19:48:55.963",
"Id": "37619",
"ParentId": "37612",
"Score": "7"
}
},
{
"body": "<p>I know names aren't hugely important but my 2 cents in addition to having already written some of what @tomdemuyt said (which I editted out):</p>\n\n<ul>\n<li><p><code>clean</code> isn't very descriptive. It's also inconsistent. Based upon other names, a better fit would be <code>clearRanges</code></p></li>\n<li><p>You don't always have to do <code>=== false</code> or <code>=== true</code> Please use truthy/falsiness. You're already doing this by not returning a value from your functions that either return true, or undefined. Undefined being falsy.</p></li>\n<li><p>As tomdemuyt said, you can simplify some of your functions. Instead of </p>\n\n<pre><code>if (windowWidth >= range[0] && windowWidth <= range[1]) {\n return true;\n }\n</code></pre>\n\n<p>You could use:</p>\n\n<pre><code>return windowWidth >= range[0] && windowWidth <= range[1];\n</code></pre></li>\n</ul>\n\n<p>I agree with tomdemuyt that requiring this to be used with jQuery seems to contradict your description of it being \"lightweight\". Most of the code doesn't reference jQuery, I'd look into factoring out the jQuery dependence.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:13:05.723",
"Id": "37621",
"ParentId": "37612",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37619",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T18:29:14.880",
"Id": "37612",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Responsive jQuery plug-in"
}
|
37612
|
<p>I'm working on my pet project with MVC 5 and EF, and everytime I'm adding a parent with it children (I have the children ID's) I have to go to the database, because if I just create a new child with this ID it just inserts a child object. Is there anyway to avoid this? </p>
<p>This is part of my code:
My classes: </p>
<pre><code>public class FeatureType
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<ItemType> ItemTypes { set; get; }
}
public class ItemType
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<FeatureType> FeatureTypes { get; set; }
}
</code></pre>
<p>What I have to do to insert FeatureTypes, for a Array of ItemTypesID (of my view Model) I go to the database and populate a List of ItemTypes.</p>
<pre><code> private IEnumerable<ItemType> GetItemTypes()
{
return ItemTypes.Select(id => unitOfWork.ItemTypeRepository.GetById(id));
}
</code></pre>
<p>Then I just assign this list to my Model property and insert. Can I avoid this trip to the database? </p>
<p>If you need anything else from my code ask for it and I can post it or you can check it all at <a href="https://github.com/tellez12/Classifieds/" rel="nofollow">https://github.com/tellez12/Classifieds/</a></p>
<p>UPDATE: </p>
<p>This is my ViewModel where I get the itemTypes and call my repository to do the insert : </p>
<pre><code>public class FeatureTypeViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool Required { get; set; }
public string RequiredText { get; set; }
public int ControlType { get; set; }
public int Order { get; set; }
public int SectionId { get; set; }
public int[] ItemTypes { set; get; }
public SelectList SectionSelect { get; set; }
public SelectList ControllerTypeSelect { get; set; }
public SelectList ItemTypeSelect { get; set; }
private IUnitOfWork unitOfWork;
public FeatureTypeViewModel()
{
}
public FeatureTypeViewModel(FeatureType ft,IUnitOfWork myUnitOfWork)
{
SetRepositories( myUnitOfWork);
Id = ft.Id;
Name = ft.Name;
Required = ft.Required;
RequiredText = ft.RequiredText;
ControlType = (int)ft.ControlType;
Order = ft.Order;
SectionId = ft.Section.Id;
ItemTypes = getItemTypesId(ft.ItemTypes).ToArray();
FillSelectList();
}
public void SetRepositories(IUnitOfWork myUnitOfWork)
{
unitOfWork = myUnitOfWork;
}
public FeatureTypeViewModel(IUnitOfWork myUnitOfWork)
{
SetRepositories( myUnitOfWork);
FillSelectList();
}
private void FillSelectList()
{
SectionSelect = new SelectList(unitOfWork.SectionRepository.Get().ToList(), "Id", "Name", SectionId);
ItemTypeSelect = new SelectList(unitOfWork.ItemTypeRepository.Get().ToList(), "Id", "Name", ItemTypes);
var typeEnumSelect = from ControlType s in Enum.GetValues(typeof(ControlType))
select new { ID = (int)s, Name = s.ToString() };
ControllerTypeSelect = new SelectList(typeEnumSelect, "ID", "Name", ControlType);
}
private IEnumerable<int> getItemTypesId(IEnumerable<ItemType> list)
{
return list.Select(item => item.Id);
}
public FeatureType ToModel()
{
var ft = new FeatureType
{
Name = Name,
ControlType = (ControlType)ControlType,
Order = Order,
Required = Required,
RequiredText = RequiredText,
ItemTypes = GetItemTypes().ToList(),
Section = GetSection(),
};
return ft;
}
private Section GetSection()
{
var section = unitOfWork.SectionRepository.GetById(SectionId);
return section;
}
private IEnumerable<ItemType> GetItemTypes()
{
return ItemTypes.Select(id => unitOfWork.ItemTypeRepository.GetById(id));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T18:48:40.283",
"Id": "62343",
"Score": "0",
"body": "I like my navigation properties to be `ICollection` - `List<T>` is an implementation of that interface."
}
] |
[
{
"body": "<p>Since <code>FeatureType</code> - <code>ItemTupe</code> is a many-to-many association you can only handle it as an <a href=\"https://stackoverflow.com/q/5281974/861716\"><em>independent association</em></a>, because there is no junction class in the class model that exposes the primitive foreign key fields.</p>\n\n<p>So, no, you can't prevent database roundtrips to fetch the objects that you need to populate the many-to-many association. A (micro) optimization could be to cache the objects in case you're going to create multiple <code>FeatureType</code>s.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T11:10:52.510",
"Id": "37666",
"ParentId": "37613",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37666",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T18:29:37.347",
"Id": "37613",
"Score": "1",
"Tags": [
"c#",
"entity-framework"
],
"Title": "EF adding Item with children"
}
|
37613
|
<p>I'm new to Java and have just started making <code>JFrame</code>s. I wrote a program for a game project I'm working on and would like help on where I can improve. I'm not new to programming, I also know HTML and Python well.</p>
<p>I believe one of the goals for all programmers is to make a useful/fun program as simple and short as possible.</p>
<p>I would like pointers/ideas/improvements for my Java program on how I can make it shorter, where I should aim for and how I can make it simpler.</p>
<pre><code>package main;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class Game {
//Set Variables to make it easier for myself
public static double VER = 1.0;
public static String STATE = "ALPHA";
public static int WIDTH = 400;
public static int HEIGHT = 400;
public static int SCALE = 1;
public static void main(String [ ] args) {
//Create JFrame
JFrame launcher = new JFrame("Infinite Doom " + STATE + " " + VER);
launcher.pack();
//Settings for JFrame
launcher.setVisible(true);
launcher.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
launcher.setResizable(false);
launcher.setIconImage(new ImageIcon("Logo.png").getImage());
launcher.setSize(WIDTH, HEIGHT);
//Check Screen Res and centre window
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
launcher.setLocation(dim.width/2-launcher.getSize().width/2, dim.height/2-launcher.getSize().height/2);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:24:57.800",
"Id": "62382",
"Score": "3",
"body": "\"as simple and short as possible\", pffft... you apparently don't know me..."
}
] |
[
{
"body": "<p>Just about the only thing I could comment on is your indentation the last two brackets</p>\n\n<pre><code> launcher.setLocation(dim.width/2-launcher.getSize().width/2, dim.height/2-launcher.getSize().height/2);\n }\n }\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code> launcher.setLocation(dim.width/2-launcher.getSize().width/2, dim.height/2launcher.getSize().height/2);\n }\n}\n</code></pre>\n\n<p>Your variables:\n<code>VER</code>, <code>STATE</code>, <code>WIDTH</code>, <code>HEIGHT</code> and <code>SCALE</code> could be set to final.</p>\n\n<p>And last but maybe irrelevant. <code>SCALE</code> is not used, but maybe you're going to use it later. What do it know. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:34:37.883",
"Id": "62541",
"Score": "0",
"body": "Yeah am planning to implement scale later in the project and i will fix the brackets and set the variables to final, thanks for the help!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T16:28:23.600",
"Id": "62686",
"Score": "0",
"body": "So I looked again at the project and the brackets where fine. Must have been a copy and paste thing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:05:26.473",
"Id": "37624",
"ParentId": "37622",
"Score": "4"
}
},
{
"body": "<p>One way to improve your game is to actually have a game. =)</p>\n\n<p>You should probably think about the design of your game a little more. </p>\n\n<ol>\n<li>What type of game are you actually going to make? </li>\n<li>What user interface elements does your game require?</li>\n</ol>\n\n<p>Putting the <code>JFrame</code> logic into your <code>main</code> method seems like a bad idea no matter what you're planning on. You should either create a class that has a <code>JFrame</code> as a member data field or a class that extends from <code>JFrame</code>. This would make your code more modular.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:47:06.590",
"Id": "62530",
"Score": "0",
"body": "Yeah am working on that XD"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T21:19:25.477",
"Id": "37628",
"ParentId": "37622",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37628",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T20:20:19.473",
"Id": "37622",
"Score": "1",
"Tags": [
"java",
"beginner",
"swing"
],
"Title": "Shortening code to create a JFrame"
}
|
37622
|
<p>The following code sorts an HTML table with JavaScript (without using any external libraries like jQuery). Are there any shortcomings or possible improvements I could make?</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<meta http-equiv="content-type" content="text/html;charset=Windows-1252">
<script type="text/javascript">
var people, asc1 = 1,
asc2 = 1,
asc3 = 1;
window.onload = function () {
people = document.getElementById("people");
}
function sort_table(tbody, col, asc) {
var rows = tbody.rows,
rlen = rows.length,
arr = new Array(),
i, j, cells, clen;
// fill the array with values from the table
for (i = 0; i < rlen; i++) {
cells = rows[i].cells;
clen = cells.length;
arr[i] = new Array();
for (j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
// sort the array by the specified column number (col) and order (asc)
arr.sort(function (a, b) {
return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1 * asc);
});
// replace existing rows with new rows created from the sorted array
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
</script>
<style type="text/css">
table {
border-collapse: collapse;
border: none;
}
th,
td {
border: 1px solid black;
padding: 4px 16px;
font-family: Times New Roman;
font-size: 24px;
text-align: left;
}
th {
background-color: #C8C8C8;
cursor: pointer;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th onclick="sort_table(people, 0, asc1); asc1 *= -1; asc2 = 1; asc3 = 1;">Name</th>
<th onclick="sort_table(people, 1, asc2); asc2 *= -1; asc3 = 1; asc1 = 1;">Surname</th>
<th onclick="sort_table(people, 2, asc3); asc3 *= -1; asc1 = 1; asc2 = 1;">Age</th>
</tr>
</thead>
<tbody id="people">
<tr>
<td>Raja</td>
<td>Dey</td>
<td>18</td>
</tr>
<tr>
<td>Mamata</td>
<td>Sharma</td>
<td>20</td>
</tr>
<tr>
<td>Avijit</td>
<td>Sharma</td>
<td>21</td>
</tr>
<tr>
<td>Sharanya</td>
<td>Dutta</td>
<td>26</td>
</tr>
<tr>
<td>Nabin</td>
<td>Roy</td>
<td>27</td>
</tr>
</tbody>
</table>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:37:37.393",
"Id": "62377",
"Score": "5",
"body": "Is the code otherwise working? If you're looking for just feedback, you should post to [codereview.se] instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:14:58.157",
"Id": "62378",
"Score": "0",
"body": "Why not use Jquery. You can use tablesorter plugin. http://tablesorter.com/docs/example-pager.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:20:37.977",
"Id": "62379",
"Score": "1",
"body": "His code is working (it only had a misconfiguration on jsfiddle: [jsfiddle](http://jsfiddle.net/qGf45/1/) ) and he is asking for performance tips. @Anup : `(without any external library like JQuery)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-08T18:56:58.353",
"Id": "275235",
"Score": "0",
"body": "Instead of `-1 * asc`, use just `-asc`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-22T10:53:41.017",
"Id": "277745",
"Score": "0",
"body": "Why not using UTF-8 instead of this weird charset?"
}
] |
[
{
"body": "<p>To speed up the sorting you first have to find what is consuming time. In your case the slower part of your code is:</p>\n\n<pre><code>for(i = 0; i < rlen; i++){\n rows[i].innerHTML = \"<td>\"+arr[i].join(\"</td><td>\")+\"</td>\";\n}\n</code></pre>\n\n<p>The reason is that the DOM elaboration is time consuming for the browser.</p>\n\n<p>Here's an updated version that minimizes the access to the DOM:</p>\n\n<pre><code>function sort_table(tbody, col, asc){\n var rows = tbody.rows, rlen = rows.length, arr = new Array(), i, j, cells, clen;\n // fill the array with values from the table\n for(i = 0; i < rlen; i++){\n cells = rows[i].cells;\n clen = cells.length;\n arr[i] = new Array();\n for(j = 0; j < clen; j++){\n arr[i][j] = cells[j].innerHTML;\n }\n }\n // sort the array by the specified column number (col) and order (asc)\n arr.sort(function(a, b){\n return (a[col] == b[col]) ? 0 : ((a[col] > b[col]) ? asc : -1*asc);\n });\n for(i = 0; i < rlen; i++){\n arr[i] = \"<td>\"+arr[i].join(\"</td><td>\")+\"</td>\";\n }\n tbody.innerHTML = \"<tr>\"+arr.join(\"</tr><tr>\")+\"</tr>\";\n}\n</code></pre>\n\n<p>Proof: <a href=\"http://jsperf.com/table-sorting-stack-overflow\">http://jsperf.com/table-sorting-stack-overflow</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-07-10T14:38:53.257",
"Id": "382234",
"Score": "0",
"body": "why is your method slower than op s method on firefox 61 osx 10.14 lol"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T10:58:47.557",
"Id": "37633",
"ParentId": "37632",
"Score": "11"
}
},
{
"body": "<p>Here is the pure JS for sorting table data. I used first column which holds numbers. You have to modify <strong>column index and condition statement</strong> as per your requirements. I hope that solves your problem...</p>\n\n<pre><code> // Table data sorting starts....\n function sortData() {\n // Read table body node.\n var tableData = document.getElementById('data_table').getElementsByTagName('tbody').item(0);\n\n // Read table row nodes.\n var rowData = tableData.getElementsByTagName('tr'); \n\n for(var i = 0; i < rowData.length - 1; i++) {\n for(var j = 0; j < rowData.length - (i + 1); j++) {\n\n //Swap row nodes if short condition matches\n if(parseInt(rowData.item(j).getElementsByTagName('td').item(0).innerHTML) > parseInt(rowData.item(j+1).getElementsByTagName('td').item(0).innerHTML)) {\n tableData.insertBefore(rowData.item(j+1),rowData.item(j));\n }\n }\n }\n }\n // Table data sorting ends....\n</code></pre>\n\n<p>HTML Table:</p>\n\n<pre><code><table id=\"data_table\" width=\"200\" border=\"1\">\n <tbody>\n <tr>\n <td width=\"100\">01</td>\n <td>aaa</td>\n </tr>\n <tr>\n <td>04</td>\n <td>ddd</td>\n </tr>\n <tr>\n <td>05</td>\n <td>eee</td>\n </tr>\n <tr>\n <td>03</td>\n <td>ccc</td>\n </tr>\n <tr>\n <td>02</td>\n <td>bbb</td>\n </tr>\n <tr>\n <td>06</td>\n <td>fff</td>\n </tr>\n </tbody>\n</table>\n</code></pre>\n\n<p>HTML Table: Sorted</p>\n\n<pre><code><table id=\"data_table\" width=\"200\" border=\"1\">\n <tbody>\n <tr>\n <td width=\"100\">01</td>\n <td>aaa</td>\n </tr>\n <tr>\n <td>02</td>\n <td>bbb</td>\n </tr>\n <tr>\n <td>03</td>\n <td>ccc</td>\n </tr>\n <tr>\n <td>04</td>\n <td>ddd</td>\n </tr>\n <tr>\n <td>05</td>\n <td>eee</td>\n </tr>\n <tr>\n <td>06</td>\n <td>fff</td>\n </tr>\n </tbody>\n</table>\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/QZ3t4/2/\" rel=\"nofollow\">Here is demo</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T05:33:49.513",
"Id": "62988",
"Score": "0",
"body": "This whole answer is all jquery. Although I think it's great you answered, the OP was asking specifically for non jquery solutions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T11:18:32.877",
"Id": "63066",
"Score": "0",
"body": "Here you go. Pure JS code for sorting HTML nodes. You can see the demo on given link."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T11:29:12.310",
"Id": "37634",
"ParentId": "37632",
"Score": "4"
}
},
{
"body": "<p>I ran into some trouble with <strong>ProGM</strong>'s solution. </p>\n\n<ol>\n<li>It didn't take numerical sorting into account. </li>\n<li>IE did NOT like setting this line: <code>tbody.innerHTML = \"<tr>\"+arr.join(\"</tr><tr>\")+\"</tr>\";</code></li>\n<li>It would destroy any attributes assigned to any part of the table (css class names and etc)</li>\n</ol>\n\n<p>I have made adjustments:</p>\n\n<pre><code>function sort_table(tbody, col, asc)\n{\n var rows = tbody.rows;\n var rlen = rows.length;\n var arr = new Array();\n var i, j, cells, clen;\n // fill the array with values from the table\n for(i = 0; i < rlen; i++)\n {\n cells = rows[i].cells;\n clen = cells.length;\n arr[i] = new Array();\n for(j = 0; j < clen; j++) { arr[i][j] = cells[j].innerHTML; }\n }\n // sort the array by the specified column number (col) and order (asc)\n arr.sort(function(a, b)\n {\n var retval=0;\n var fA=parseFloat(a[col]);\n var fB=parseFloat(b[col]);\n if(a[col] != b[col])\n {\n if((fA==a[col]) && (fB==b[col]) ){ retval=( fA > fB ) ? asc : -1*asc; } //numerical\n else { retval=(a[col] > b[col]) ? asc : -1*asc;}\n }\n return retval; \n });\n for(var rowidx=0;rowidx<rlen;rowidx++)\n {\n for(var colidx=0;colidx<arr[rowidx].length;colidx++){ tbody.rows[rowidx].cells[colidx].innerHTML=arr[rowidx][colidx]; }\n }\n}\n</code></pre>\n\n<p>To address point #1, I added in the calls to <code>parseFloat()</code> and then compared the result the original value (You change to checking if it produces <code>NaN</code> instead). If both values are numeric, they compared via numerical preference and not by their string versions.</p>\n\n<p>For points #2 and #3, I solved it via the same set of code. Instead of destroying the whole table body by setting the <code>innerHTML</code>, I change the individual cell contents to the new sorted values: </p>\n\n<pre><code>for(var rowidx=0;rowidx<rlen;rowidx++)\n{\n for(var colidx=0;colidx<arr[rowidx].length;colidx++)\n { \n tbody.rows[rowidx].cells[colidx].innerHTML=arr[rowidx][colidx]; \n }\n}\n</code></pre>\n\n<p>That only works if yours all have the same number of columns, but if you do not, sorting is much more complex anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-10T17:12:29.737",
"Id": "126706",
"Score": "0",
"body": "will you explain the adjustments please and how they overcome the issues that you found?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-11T13:51:59.100",
"Id": "126903",
"Score": "1",
"body": "Can do, I also found a mistake in mine."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-10T16:19:41.833",
"Id": "69395",
"ParentId": "37632",
"Score": "6"
}
},
{
"body": "<p>Here is an improved version based on Plater's anwser. Just in case there is DOM elements inside of <code>td</code> tags, the code gets the last child of the cell and get the value, and apply a customized filter to it. </p>\n\n<p><strong>Note:</strong> The customized filter here is just an example, and also you don't need to get the last child of the <code>td</code> tags, and it can be any child of your use case.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function sortTable(tbody, col, asc) {\n var rows = tbody.rows;\n var rlen = rows.length;\n var arr = new Array();\n var i, j, cells, clen;\n /* fill the array with values from the table */\n for (i = 0; i < rlen; i++) {\n cells = rows[i].cells;\n clen = cells.length;\n arr[i] = new Array();\n for (j = 0; j < clen; j++) {\n arr[i][j] = cells[j].innerHTML;\n }\n }\n /* sort the array by the specified column number (col) and order (asc) */\n arr.sort(function(a, b) {\n var retval = 0;\n var aVal = getDomValue(a[col]);\n var bVal = getDomValue(b[col]);\n var fA = parseFloat(aVal);\n var fB = parseFloat(bVal);\n if (aVal != bVal) {\n\n if ((fA == aVal) && (fB == bVal)) {\n retval = (fA > fB) ? asc : -1 * asc;\n } // Numerical\n else {\n retval = (aVal > bVal) ? asc : -1 * asc;\n } // String\n }\n return retval;\n });\n /* fill the table with sorted values */\n for (var rowidx = 0; rowidx < rlen; rowidx++) {\n for (var colidx = 0; colidx < arr[rowidx].length; colidx++) {\n tbody.rows[rowidx].cells[colidx].innerHTML = arr[rowidx][colidx];\n }\n }\n\n}\n\nfunction getDomValue(domString) {\n var value;\n var parser = new DOMParser();\n var element = parser.parseFromString(domString, 'text/xml');\n var content = element.lastChild.innerHTML;\n\n // Custom filter just in case if there is elements inside of the td.\n // I made two filters to standardize numbers like '$20,000', also I\n // treat whereas ' ' space as '0'\n if (content === ' ') content = content.replace(' ', '0');\n if (content.indexOf('$') !== -1) {\n content = content.replace('$', '');\n content = content.replace(',', '');\n }\n value = isNaN(parseFloat(content)) ? content : parseFloat(content);\n return value;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-11-06T20:14:50.910",
"Id": "110052",
"ParentId": "37632",
"Score": "1"
}
},
{
"body": "<p>I was working on a table sorting script in ES6 today, researching the various methods to determine the most efficient. I dismissed working with the <code>innerHTML</code> property out of hand, from <a href=\"https://jsperf.com/innerhtml-vs-removechild/400\" rel=\"nofollow noreferrer\">previous research</a>, instead trying a series of options using:</p>\n\n<ol>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow\" rel=\"nofollow noreferrer\"><code>insertRow()</code></a> & <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/deleteRow\" rel=\"nofollow noreferrer\"><code>deleteRow()</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en/docs/Web/API/Node/appendChild\" rel=\"nofollow noreferrer\"><code>appendChild()</code></a> & <a href=\"https://developer.mozilla.org/en/docs/Web/API/Node/removeChild\" rel=\"nofollow noreferrer\"><code>removeChild()</code></a></li>\n<li><a href=\"https://developer.mozilla.org/en/docs/Web/API/ParentNode/append\" rel=\"nofollow noreferrer\"><code>append()</code></a> / <a href=\"https://developer.mozilla.org/en/docs/Web/API/ParentNode/prepend\" rel=\"nofollow noreferrer\"><code>prepend()</code></a> & <a href=\"https://developer.mozilla.org/en/docs/Web/API/ChildNode/remove\" rel=\"nofollow noreferrer\"><code>remove()</code></a></li>\n</ol>\n\n<p>with the latter coming out as the fastest in my tests on tables with a large number (>5000) of rows.</p>\n\n<p>Given that, here is the code I came up with, integrated into your use case.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>(()=>{\n let people=document.getElementById(\"people\"),\n thead=people.previousElementSibling,\n rows=[...people.rows],\n orders=[1,1,-1],\n sort=(col)=>{\n let x=rows.length;\n rows.sort((a,b)=>{\n let i=a.children[col].firstChild.nodeValue,\n j=b.children[col].firstChild.nodeValue;\n return i===j?0:i>j?orders[col]:-orders[col];\n });\n orders[col]*=-1;\n while(people.lastChild)\n people.lastChild.remove();\n while(x--)\n people.prepend(rows[x]);\n };\n thead.addEventListener(\"click\",event=>{\n let target=event.target;\n if(target.nodeName.toLowerCase()===\"th\")\n sort(target.cellIndex);\n },0);\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>table{\n border-collapse:collapse;\n border:none;\n}\nth,td{\n border:1px solid black;\n padding:4px 16px;\n font-family:Times New Roman;\n font-size:24px;\n text-align:left;\n}\nth{\n background-color:#C8C8C8;\n cursor:pointer;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><table>\n <thead>\n <tr>\n <th>Name</th>\n <th>Surname</th>\n <th>Age</th>\n </tr>\n </thead>\n <tbody id=\"people\">\n <tr>\n <td>Raja</td>\n <td>Dey</td>\n <td>18</td>\n </tr>\n <tr>\n <td>Mamata</td>\n <td>Sharma</td>\n <td>20</td>\n </tr>\n <tr>\n <td>Avijit</td>\n <td>Sharma</td>\n <td>21</td>\n </tr>\n <tr>\n <td>Sharanya</td>\n <td>Dutta</td>\n <td>26</td>\n </tr>\n <tr>\n <td>Nabin</td>\n <td>Roy</td>\n <td>27</td>\n </tr>\n </tbody>\n</table></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-17T16:33:26.727",
"Id": "276856",
"Score": "0",
"body": "Thank you. I just converted your script into Javascript of \"nowadays\", I used \".tHead\" on the table object instead of previousElementSibling and I added a null check because a.children[col].firstChild.nodeValue can be null when a cell is empty. I'm going to compute the content of \"orders\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-22T10:55:04.030",
"Id": "277746",
"Score": "0",
"body": "prepend is an experimental feature not supported by Microsoft Edge. Array.from() isn't supported by Microsoft Internet Explorer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-22T14:06:14.283",
"Id": "277806",
"Score": "0",
"body": "I modified the loop in order to use appendChild() instead of prepend(), I used removeChild() instead of remove() and I replaced Array.from by a simple creation of an array and a loop to copy the elements one by one. Now, it works in Mozilla Firefox, Google Chrome & Chromium, Microsoft Edge and Microsoft Internet Explorer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-11-15T17:36:24.453",
"Id": "147127",
"ParentId": "37632",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37633",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T09:35:37.360",
"Id": "37632",
"Score": "17",
"Tags": [
"javascript",
"html",
"sorting"
],
"Title": "Sorting an HTML table with JavaScript"
}
|
37632
|
<p>I have created a MySQL query that works, but I feel there must be a better way. The query will be used by a PHP script whose purpose is to assign conditions & subconditions to new participants in an online experiment based on how many times each combination of condition & subcondition was already assigned to previous participants. (There are 2556 conditions and 8 subconditions, all combinations are allowed.) The purpose of the query is to calculate the number of "filtered completes" for each condition, defined as follows:</p>
<ol>
<li>for a given condition C, the number of completes in each subcondition S is the number of unique data rows with condition==C and subcondition==S</li>
<li>for a given condition C, the "target" is 1 + the smallest number of completes for any subcondition S in C</li>
<li>for a given condition C and subcondition S, the "filtered completes" for S in C is the minimum of the "target" for C and the actual number of completes for S in C</li>
<li>the total "filtered completes" for the condition C is the sum of filtered completes for all subconditions S in C</li>
</ol>
<p>Intuitively, at a given moment, I want to act as though my goal is to assign the "target" number of participants to each subcondition in a given condition. The "target" can increase only once ALL subconditions in the condition have met the target. At a given moment, I want to ignore completes in any subcondition that exceed the target. OK, here now is the query which works:</p>
<pre><code>select `condition`, (
LEAST( `Target`, `subcond_0` ) +
LEAST( `Target`, `subcond_1` ) +
LEAST( `Target`, `subcond_2` ) +
LEAST( `Target`, `subcond_3` ) +
LEAST( `Target`, `subcond_4` ) +
LEAST( `Target`, `subcond_5` ) +
LEAST( `Target`, `subcond_6` ) +
LEAST( `Target`, `subcond_7` ) ) as `filtered_completes`
from (
select `condition`,
(1+LEAST( `subcond_0`, `subcond_1`, `subcond_2`, `subcond_3`, `subcond_4`, `subcond_5`, `subcond_6`, `subcond_7` )) as `Target`,
`subcond_0`, `subcond_1`, `subcond_2`, `subcond_3`, `subcond_4`, `subcond_5`, `subcond_6`, `subcond_7`
from (
select `condition`,
SUM( CASE `subcondition` WHEN 0 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_0`,
SUM( CASE `subcondition` WHEN 1 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_1`,
SUM( CASE `subcondition` WHEN 2 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_2`,
SUM( CASE `subcondition` WHEN 3 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_3`,
SUM( CASE `subcondition` WHEN 4 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_4`,
SUM( CASE `subcondition` WHEN 5 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_5`,
SUM( CASE `subcondition` WHEN 6 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_6`,
SUM( CASE `subcondition` WHEN 7 THEN `count( distinct id )` ELSE 0 END ) AS `subcond_7`
from
(
select `condition`, `subcondition`, count( distinct id ) from test_table_3
where approve=1 group by `condition`, `subcondition`
) as T1 group by `condition`
) as T2
) as T3;
</code></pre>
<p>Reasons I don't think it's good are </p>
<ol>
<li>it requires me to hand-code the subconditions, so it would not be easy to change to a different number of subconditions </li>
<li>the nested selects look ugly to me</li>
<li>it seems to run a bit slow. Any suggestions for how to improve it? </li>
</ol>
<p><strong>Should I be doing this in PHP instead?</strong></p>
<p>Here is some sample data as requested, eliminating columns that I don't think are relevant to the question:</p>
<pre><code>id subjid condition subcondition approve
51 A3GM1SF5FUOS8L 1175 3 1
52 A3GM1SF5FUOS8L 456 0 1
53 A3GM1SF5FUOS8L 1301 0 1
54 A3GM1SF5FUOS8L 499 5 1
55 A3GM1SF5FUOS8L 886 5 1
56 A3GM1SF5FUOS8L 2257 7 1
57 A3GM1SF5FUOS8L 1955 4 1
58 A3GM1SF5FUOS8L 890 2 1
59 A3GM1SF5FUOS8L 1667 0 1
60 A3GM1SF5FUOS8L 1546 2 1
61 A3GM1SF5FUOS8L 1315 5 1
62 A3GM1SF5FUOS8L 139 1 1
63 A3GM1SF5FUOS8L 374 3 1
64 A3GM1SF5FUOS8L 1249 4 1
65 A3GM1SF5FUOS8L 1658 7 1
66 A3GM1SF5FUOS8L 2241 3 1
67 A3GM1SF5FUOS8L 167 6 1
68 A3GM1SF5FUOS8L 1370 0 1
69 A3GM1SF5FUOS8L 26 3 1
70 A3GM1SF5FUOS8L 2499 6 1
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T23:13:23.217",
"Id": "62388",
"Score": "1",
"body": "I'd suggest pasting an ERD, or sample data for this. Odds are the SQL statement is just the symptom of a bigger problem: badly designed tables and relationships."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T03:31:46.420",
"Id": "62414",
"Score": "0",
"body": "Added sample data as requested."
}
] |
[
{
"body": "<p>The generic solution that won't require changing when adding new subconditions involves several subqueries and will probably be very slow. There isn't too much data here, but it can be sped up (see below).</p>\n\n<p><strong>1. Completes</strong></p>\n\n<p>You have this one already in your query.</p>\n\n<pre><code>select\n condition,\n subcondition,\n count(distinct id) as completes\nfrom\n test_table_3\nwhere\n approve = 1\ngroup by\n condition,\n subcondition\n</code></pre>\n\n<p><strong>2. Minimum Completes</strong></p>\n\n<pre><code>select\n condition,\n min(completes) as min_completes\nfrom\n <query-1>\ngroup by\n condition\n</code></pre>\n\n<p><strong>3. Filtered Completes</strong></p>\n\n<p>Join 1 and 2</p>\n\n<pre><code>select\n condition,\n subcondition,\n min(min_completes, count(distinct id)) as filtered_completes\nfrom\n test_table_3\njoin\n <query-2> using condition\nwhere\n approve = 1\ngroup by\n condition,\n subcondition\n</code></pre>\n\n<p><strong>4. Total Filtered Completes</strong></p>\n\n<pre><code>select\n condition,\n sum(filtered_completes) as total_filtered_completes\nfrom\n <query-3>\ngroup by\n condition\n</code></pre>\n\n<p><strong>Going Faster</strong></p>\n\n<p>First, creating a temporary table out of <code><query-1></code> would be huge. Technically, MySQL should be smart enough to do this on its own, and being only three short columns should allow it to fit easily in RAM. However, I've found that the simplest of derived tables can often cause it to go off the rails. I will confess that I don't have a lot of MySQL tuning experience.</p>\n\n<p>Second, this would be pretty easy in PHP. Load the results of <code><query-1></code> into an array and use two passes to calculate the minimum, filtered, and total completes. The latter two values can be calculated together during the second pass. Since you probably need these values in PHP in the end, the only real cost is slurping in all that data which again isn't very much here.</p>\n\n<p>If you got tricky, you could even probably do it with a single pass while streaming the results from MySQL so you wouldn't have to store the entire derived table in RAM at once. For each condition, you only need to know a) the minimum subcondition completes, b) how many subconditions have that minimum value, and c) how many subconditions are over that minimum. The total filtered completes for that condition equals</p>\n\n<pre><code>a * b + (a + 1) * c\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:20:16.280",
"Id": "62553",
"Score": "0",
"body": "I don't think step 2 does what I need. I need to set the target for each condition equal to the minimum number of completes for subconditions *within that condition*, not overall."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:32:10.740",
"Id": "62567",
"Score": "0",
"body": "@baixiwei Grouping by condition on the outer query while grouping on both fields on the inner one gives you the minimum subcondition completes per condition."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T06:47:24.700",
"Id": "37657",
"ParentId": "37637",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37657",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T22:46:37.937",
"Id": "37637",
"Score": "4",
"Tags": [
"php",
"mysql",
"sql"
],
"Title": "Make this MySQL query more elegant &/or efficient"
}
|
37637
|
<p>Below is my typical WindowController module for presenting a modal dialog (could be settings, asking username/password, etc) loaded from a XIB. It seems a bit too complex for something like this. Any ideas how this can be done better/with less code?</p>
<p>Never mind that it's asking for a password, it could be anything. What frustrates me most is that I repeat the same pattern in each and every of my XIB-based modal window modules. Which of course means I could define a custom window controller class, but before doing that I need to make sure this is really the best way of doing things.</p>
<pre><code>#import "MyPasswordWindowController.h"
static MyPasswordWindowController* windowController;
@interface MyPasswordWindowController ()
@property (weak) IBOutlet NSSecureTextField *passwordField;
@end
@implementation MyPasswordWindowController
{
NSInteger _dialogCode;
}
- (id)init
{
return [super initWithWindowNibName:@"MyPassword"];
}
- (void)awakeFromNib
{
[super awakeFromNib];
[self.window center];
}
- (void)windowWillClose:(NSNotification*)notification
{
[NSApp stopModalWithCode:_dialogCode];
_dialogCode = 0;
}
- (IBAction)okButtonAction:(NSButton *)sender
{
_dialogCode = 1;
[self.window close];
}
- (IBAction)cancelButtonAction:(NSButton *)sender
{
[self.window close];
}
+ (NSString*)run
{
if (!windowController)
windowController = [MyPasswordWindowController new];
[windowController loadWindow];
windowController.passwordField.stringValue = @"";
if ([NSApp runModalForWindow:windowController.window])
return windowController.passwordField.stringValue;
return nil;
}
</code></pre>
<p>The application calls [MyPasswordWindowController run], so from the point of view of the user of this module it looks simple, but not so much when you look inside.</p>
|
[] |
[
{
"body": "<p>Based on Ken Thomases answer given <a href=\"https://stackoverflow.com/questions/20477717/presenting-modal-dialogs-from-xib-in-cocoa-best-shortest-pattern/20647814#20647814\">on SO here</a>, here is my revised modal window module. Note that the window should have the system close button disabled, or otherwise you will have to handle windowWillClose, which will lead to having _dialogCode like in my original code above. If, however, OK and Cancel are the only buttons that end the modal dialog, then:</p>\n\n<pre><code>#import \"MyPasswordWindowController.h\"\n\n@interface MyPasswordWindowController ()\n@property (weak) IBOutlet NSSecureTextField *passwordField;\n@end\n\n@implementation MyPasswordWindowController\n\n- (IBAction)okCancelAction:(NSButton *)sender\n{\n [NSApp stopModalWithCode:sender.tag]; // the OK button's tag should be 1\n [self.window close];\n}\n\n+ (NSString*)run\n{\n MyPasswordWindowController* windowController =\n [[MyPasswordWindowController alloc] initWithWindowNibName:@\"MyPassword\"];\n if ([NSApp runModalForWindow:windowController.window])\n return windowController.passwordField.stringValue;\n return nil;\n}\n\n@end\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T03:45:31.780",
"Id": "37649",
"ParentId": "37640",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-17T23:32:38.893",
"Id": "37640",
"Score": "5",
"Tags": [
"objective-c",
"cocoa",
"osx"
],
"Title": "Presenting modal dialogs from XIB in Cocoa: best/shortest pattern?"
}
|
37640
|
<p>Here is a implementation of the cryptographic hash function SHA1 written in Python. It does not use any external libraries, only built-in functions. I know that it would be faster to use an external library, but my code is for learning purposes.</p>
<p>I want to know if I am properly implementing the algorithm. Am I taking any unnecessary steps? What changes can I make to speed up the code?</p>
<p>The code properly works. I've compared the result to a trusted implementation.</p>
<pre><code>def sha1(data):
bytes = ""
h0 = 0x67452301
h1 = 0xEFCDAB89
h2 = 0x98BADCFE
h3 = 0x10325476
h4 = 0xC3D2E1F0
for n in range(len(data)):
bytes+='{0:08b}'.format(ord(data[n]))
bits = bytes+"1"
pBits = bits
#pad until length equals 448 mod 512
while len(pBits)%512 != 448:
pBits+="0"
#append the original length
pBits+='{0:064b}'.format(len(bits)-1)
def chunks(l, n):
return [l[i:i+n] for i in range(0, len(l), n)]
def rol(n, b):
return ((n << b) | (n >> (32 - b))) & 0xffffffff
for c in chunks(pBits, 512):
words = chunks(c, 32)
w = [0]*80
for n in range(0, 16):
w[n] = int(words[n], 2)
for i in range(16, 80):
w[i] = rol((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)
a = h0
b = h1
c = h2
d = h3
e = h4
#Main loop
for i in range(0, 80):
if 0 <= i <= 19:
f = (b & c) | ((~b) & d)
k = 0x5A827999
elif 20 <= i <= 39:
f = b ^ c ^ d
k = 0x6ED9EBA1
elif 40 <= i <= 59:
f = (b & c) | (b & d) | (c & d)
k = 0x8F1BBCDC
elif 60 <= i <= 79:
f = b ^ c ^ d
k = 0xCA62C1D6
temp = rol(a, 5) + f + e + k + w[i] & 0xffffffff
e = d
d = c
c = rol(b, 30)
b = a
a = temp
h0 = h0 + a & 0xffffffff
h1 = h1 + b & 0xffffffff
h2 = h2 + c & 0xffffffff
h3 = h3 + d & 0xffffffff
h4 = h4 + e & 0xffffffff
return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4)
print sha1("hello world")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T02:47:05.580",
"Id": "62412",
"Score": "2",
"body": "http://docs.python.org/2/library/hashlib.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T05:09:38.407",
"Id": "62415",
"Score": "1",
"body": "@AlexBuchanan I said that my code was not for practical use."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T09:51:22.687",
"Id": "62443",
"Score": "1",
"body": "That's what the [tag:reinventing-the-wheel] tag is for. I've added it for you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:26:00.257",
"Id": "62526",
"Score": "0",
"body": "Ah, my bad, I must have skimmed over that line."
}
] |
[
{
"body": "<p>I'm no expert on SHA1, and I see mostly small things, but one big thing that gave me pause. As an overall observation, you seem to value readability over memory usage. Since hashes are often used for large files, this seems to be a risky tradeoff, and python does provide good ways to handle this as well. More of this in the third observation below. On to the observations:</p>\n\n<ul>\n<li><code>pBits</code> being represented as a series of characters for each bit seems unusual for such low level work. I would typically expect to see this as a hexadecimal string, or even a number. Yet except for possible difficulties comparing it to other implementations that favor less space usage, this seems to make things easy to read.</li>\n<li>Filling out <code>pBits</code> to lengths congruent to 448 mod 512 could be done in a single step by figuring out how many bits of padding are necessary and doing a single <code>pBits += \"0\" * padding</code>; there's no need for a while loop.</li>\n<li><p>This one's important: <code>chunks()</code> should probably be a generator so that you don't have three copies of your data around (one original, one expanded a bit to a byte, and one in chunked strings); correspondingly this could serve out the trailing zero and length bits. Let's examine what this would look like, as 3 copies of large data is really large. Let's remove the sliced copies, creating only one chunk at a time:</p>\n\n<pre><code>def iterchunks(bits, chunkbits=512):\n for i in range(0, len(bits), chunkbits):\n yield bits[i:i + chunkbits]\n</code></pre>\n\n<p>Note that if the pBits generation was here, checking <code>i + chunkbits</code> against <code>len(bits)</code> and the bytes to bits conversion, you could process a file-like stream instead of a string, taking you further down, from the original 3 copies (with two of them 8 times larger than usual) to not even a full copy of your data in memory at one time.</p></li>\n<li>Back to small ideas. Your bit string could be more literally a bit string, storing <code>\\0</code> and <code>\\1</code> characters. This would let you simplify setting up <code>w</code> into <code>w = map(ord, words)</code>. (Of course with the appropriate helper, you could do that with the <code>0</code> and <code>1</code> characters of your current string.)</li>\n<li><p>I'm not a big fan of the <code>for i in range(0, 80): if 0 <= i <= 19: ...</code> section. It feels like it might read better with a series of for loops that do their different thing then call a helper:</p>\n\n<pre><code>for i in range(0, 19):\n f = (b & c) | ((~b) & d)\n k = 0x5A827999\n a, b, c, d, e = update(a, b, c, d, e, f, k, w[i])\nfor i in range(20, 39):\n f = b ^ c ^ d\n k = 0x6ED9EBA1\n a, b, c, d, e = update(a, b, c, d, e, f, k, w[i])\n...\n</code></pre>\n\n<p>but that seems pretty ridiculous, and would probably hurt performance to boot. After looking more closely at the obvious alternative, I'm going to withdraw this complaint.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T04:07:29.550",
"Id": "37650",
"ParentId": "37648",
"Score": "11"
}
},
{
"body": "<ol>\n<li><p>There's no documentation. What does this code do and how am I supposed to use it?</p></li>\n<li><p>There are no test cases. Since the <a href=\"http://docs.python.org/3/library/hashlib.html\" rel=\"nofollow\"><code>hashlib</code></a> module has a <code>sha1</code> function, it would be easy to write a test case that generates some random data and hashes it with both algorithms. For example:</p>\n\n<pre><code>import hashlib\nfrom random import randrange\nfrom unittest import TestCase\n\nclass TestSha1(TestCase):\n def test_sha1(self):\n for l in range(129):\n data = bytearray(randrange(256) for _ in range(l))\n self.assertEqual(hashlib.sha1(data).hexdigest(), sha1(data))\n</code></pre></li>\n<li><p>You start by converting the message to a string containing its representation in binary. But then later on you convert it back to integers again. It would be simpler and faster to work with bytes throughout. Python provides the <a href=\"http://docs.python.org/3/library/functions.html#bytearray\" rel=\"nofollow\"><code>bytearray</code></a> type for manipulating sequences of bytes and the <a href=\"http://docs.python.org/3/library/struct.html\" rel=\"nofollow\"><code>struct</code></a> module for interpreting sequences of bytes as binary data. So you could initialize and pad the message like this:</p>\n\n<pre><code>message = bytearray(data)\n# Append a 1-bit.\nmessage.append(0x80)\n# Pad with zeroes until message length in bytes is 56 (mod 64).\nmessage.extend([0] * (63 - (len(message) + 7) % 64))\n# Append the original length (big-endian, 64 bits).\nmessage.extend(struct.pack('>Q', len(data) * 8))\n</code></pre>\n\n<p>and then convert the chunks to 32-bit integers using <a href=\"http://docs.python.org/3/library/struct.html#struct.unpack\" rel=\"nofollow\"><code>struct.unpack</code></a> like this:</p>\n\n<pre><code>for chunk in range(0, len(message), 64):\n w = list(struct.unpack('>16L', message[chunk: chunk+64]))\n for i in range(16, 80):\n w.append(rol((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1))\n</code></pre>\n\n<p>This runs substantially faster than your code.</p></li>\n<li><p>I would write the conditions in the main loop as <code>0 <= i < 20</code>, <code>20 <= i < 40</code> and so on, to match the half-open intervals that Python uses elsewhere (in list slices, <code>range</code> and so on).</p></li>\n<li><p>I would replace:</p>\n\n<pre><code>elif 60 <= i <= 79:\n</code></pre>\n\n<p>by</p>\n\n<pre><code>else:\n assert 60 <= i < 80\n</code></pre>\n\n<p>to make it clear that this case must match.</p></li>\n<li><p>You can avoid the need for <code>temp</code> by using a tuple assignment:</p>\n\n<pre><code>a, b, c, d, e = ((rol(a, 5) + f + e + k + w[i]) & 0xffffffff, a, rol(b, 30), c, d)\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T11:51:20.343",
"Id": "37668",
"ParentId": "37648",
"Score": "6"
}
},
{
"body": "<p>Serializing the data into a string of <code>'1'</code> and <code>'0'</code> characters, then parsing the string back into numbers, seems incredibly wasteful. You should aim to do the whole thing without stringifying the numbers. I've done it using <code>struct.pack()</code> and <code>struct.unpack()</code>, though you could also use basic functions like <code>ord()</code> with more bit manipulation.</p>\n\n<p>I've kept everything starting from the main loop about the same. The minor changes I've made are to use parallel assignments and inclusive-exclusive ranges, both of which are in the spirit of Python.</p>\n\n<pre><code>from struct import pack, unpack\n\ndef sha1(data):\n \"\"\" Returns the SHA1 sum as a 40-character hex string \"\"\"\n h0 = 0x67452301\n h1 = 0xEFCDAB89\n h2 = 0x98BADCFE\n h3 = 0x10325476\n h4 = 0xC3D2E1F0\n\n def rol(n, b):\n return ((n << b) | (n >> (32 - b))) & 0xffffffff\n\n # After the data, append a '1' bit, then pad data to a multiple of 64 bytes\n # (512 bits). The last 64 bits must contain the length of the original\n # string in bits, so leave room for that (adding a whole padding block if\n # necessary).\n padding = chr(128) + chr(0) * (55 - len(data) % 64)\n if len(data) % 64 > 55:\n padding += chr(0) * (64 + 55 - len(data) % 64)\n padded_data = data + padding + pack('>Q', 8 * len(data))\n\n thunks = [padded_data[i:i+64] for i in range(0, len(padded_data), 64)]\n for thunk in thunks:\n w = list(unpack('>16L', thunk)) + [0] * 64\n for i in range(16, 80):\n w[i] = rol((w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16]), 1)\n\n a, b, c, d, e = h0, h1, h2, h3, h4\n\n # Main loop\n for i in range(0, 80):\n if 0 <= i < 20:\n f = (b & c) | ((~b) & d)\n k = 0x5A827999\n elif 20 <= i < 40:\n f = b ^ c ^ d\n k = 0x6ED9EBA1\n elif 40 <= i < 60:\n f = (b & c) | (b & d) | (c & d) \n k = 0x8F1BBCDC\n elif 60 <= i < 80:\n f = b ^ c ^ d\n k = 0xCA62C1D6\n\n a, b, c, d, e = rol(a, 5) + f + e + k + w[i] & 0xffffffff, \\\n a, rol(b, 30), c, d\n\n h0 = h0 + a & 0xffffffff\n h1 = h1 + b & 0xffffffff\n h2 = h2 + c & 0xffffffff\n h3 = h3 + d & 0xffffffff\n h4 = h4 + e & 0xffffffff\n\n return '%08x%08x%08x%08x%08x' % (h0, h1, h2, h3, h4)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:14:28.440",
"Id": "62454",
"Score": "3",
"body": "You could avoid the `if` in the calculation of the padding if you wrote `63 - (len(data) + 8) % 64`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-31T20:06:37.783",
"Id": "451903",
"Score": "0",
"body": "FYI same algorithm using the hashlib.sha1 streaming interface (.update and .digest methods): https://github.com/pts/tinyveracrypt/blob/bbd1c26960e4b2e3d2905000fd694d540b6ac35f/tinyveracrypt.py#L563"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T11:58:32.713",
"Id": "37669",
"ParentId": "37648",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T02:32:41.667",
"Id": "37648",
"Score": "13",
"Tags": [
"python",
"cryptography",
"reinventing-the-wheel"
],
"Title": "Python implementation of SHA1"
}
|
37648
|
<p>I am currently storing form data in an XML format:</p>
<pre><code><cfsavecontent variable="myFormData">
<cfoutput>
<ul class="xoxo">
<cfloop list="#form.fieldnames#" index="item">
<cfloop list="#form[item]#" index="eachItem">
<li><b>#xmlformat(item)#</b> <var>#xmlformat(eachItem)#</var>
</cfloop>
</cfloop>
</ul>
<cfoutput>
</cfsavecontent>
</code></pre>
<p>Then do a single insert:</p>
<pre><code><cfquery>
INSERT INTO table (formData)
VALUES (<cfqueryparam value="#myFormData#" cfsqltype="cf_sql_varchar">)
</cfquery>
</code></pre>
<p>When I pull the data out, I can:</p>
<pre><code><cfquery name="qryData">
SELECT formData
FROM table
WHERE ID = <cfqueryparam value="#ID#" cfsqltype="cf_sql_integer">
</cfquery>
<cfoutput query="qryData">#formData#</cfoutput>
</code></pre>
<p><strong>OR</strong></p>
<pre><code><cfquery name="qryData">
SELECT li.value('(b/text())[1]', 'varchar(50)') AS Item,
li.value('(var/text())[1]', 'varchar(50)') AS Value
FROM table
CROSS APPLY XmlData.nodes('/ul/li') AS ul(li)
WHERE ID = <cfqueryparam value="#ID#" cfsqltype="cf_sql_integer">
</cfquery>
<cfoutput query="qryData">#Item# #Value#</cfoutput>
</code></pre>
<p>Some developers have concerns about storing the data in this format. Is this the best way to store arbitrary form data?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T06:58:23.317",
"Id": "62437",
"Score": "0",
"body": "How is the data used? It seems very odd to render it as an HTML list, then store it thus."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:47:12.323",
"Id": "62469",
"Score": "0",
"body": "Is there a reason that you would not store the data in JSON format? It might be simpler and easier to work with the data with SerializeJSON and DeserializeJSON and the resultant structures than with XML parsing functions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:34:43.620",
"Id": "62557",
"Score": "0",
"body": "@Brian: I don't use JSON because a) There is no JSON format in SQL Server b) It can be displayed in a clean format without additional processing"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:36:26.987",
"Id": "62559",
"Score": "0",
"body": "@Adam I am able to tap into the data having three natures at the same time:a) It is HTML so it can be displayed as is, b) It is XML so it can be treated nearly the same way as being on a more formal table structure and c) It is a string, which can easily be pushed around as a string"
}
] |
[
{
"body": "<p>Well, it depends what you want to do with this data. If you ever want to query individual field names or debug an issue with a field you will have a hard time extracting this kind of information out of an XML blob.</p>\n\n<p>Potential pitfall: According to the <a href=\"http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=Tags_p-q_18.html\" rel=\"nofollow\">coldfusion docs</a>, <code>CF_SQL_VARCHAR</code> maps to <code>varchar</code> columns on MSSQL. You need to make sure that the column is <code>varchar(max)</code> as XML can get pretty verbose and any character limit might get hit.</p>\n\n<p>On how to better store the data this is hard to say. From your example it looks like a form has fields and each field could have multiple values. This looks like a classic 1:n relationship to me:</p>\n\n<p>Form table:</p>\n\n<pre><code>FormID | Name | Description | ...\n</code></pre>\n\n<p>Field Name table:</p>\n\n<pre><code>FieldID | FormID | Name\n</code></pre>\n\n<p>Field Value table:</p>\n\n<pre><code>ValueID | FieldID | Value\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:38:13.417",
"Id": "62492",
"Score": "0",
"body": "You touch on a lot off good points, let me address the `1:n` relationship. It is a `1:n` relationship, just so happens that the `n` part is stored on the original table. The `CROSS APPLY` is basically a `LEFT JOIN` after shredding the data."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T09:36:07.350",
"Id": "37661",
"ParentId": "37653",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37661",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T05:17:58.407",
"Id": "37653",
"Score": "2",
"Tags": [
"sql-server",
"xml",
"coldfusion",
"cfml"
],
"Title": "Storing arbitrary form data in SQL as an XML blob"
}
|
37653
|
<p>I have used multiple lines of code in one <code>if</code> condition without using curly braces, which is executing properly. So what is the main necessity of using curly braces in <code>if</code> statements for multiple lines?</p>
<pre><code> if (ggcCompareGrid.TopLevelTable != null)
foreach (GridRow row in ggcCompareGrid.TopLevelTable.Rows)
{
if (row.DisplayElement.ParentGroup != null)
if (row.DisplayElement.ParentGroup.Category != null)
if ((int)row.DisplayElement.ParentGroup.Category == key && row.Record == null)
{
row.DisplayElement.ParentGroup.IsExpanded = false;
break;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:15:15.690",
"Id": "62455",
"Score": "5",
"body": "Have you researched this all through SE? This question (and fairly large list of related cousins) is old enough to have whiskers on it.\n\nhttp://programmers.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no.\n- http://stackoverflow.com/questions/2125066/is-it-bad-practice-to-use-an-if-statement-without-brackets\n\nIn your case, somebody not clear about the indents/structure (which can happen if function too long to read on a single screen) can easily mess up by adding a line after the foreach at the same indent-level.\n\nAlso, with 4-5 indent levels,consider refactoring."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:51:17.653",
"Id": "62479",
"Score": "6",
"body": "This question appears to be off-topic because it is about a basic coding practice. The question could essentially be reworded as, \"Why should I indicate the beginning and end of code blocks when it isn't required?\" Which would be language agnostic, still answer the OPs question, and isn't really Code Review."
}
] |
[
{
"body": "<p>You're not using multiple lines of code in one <code>if</code> without curly braces, only one. For example, your <code>foreach</code> loop is considered as one statement, even if the code inside your loop is on multiple lines. That's why you don't need curly braces for your first <code>if</code>. </p>\n\n<p>Same thing for <code>if (row.DisplayElement.ParentGroup != null)</code>, which has only one statement : <code>if (row.DisplayElement.ParentGroup.Category != null)</code>. It doesn't care about what is inside your second <code>if</code>.</p>\n\n<p>Also, i suggest you to avoid nesting loops and <code>if</code> statements like that because it can become hard to read when your statements get bigger.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T12:12:33.830",
"Id": "37670",
"ParentId": "37665",
"Score": "10"
}
},
{
"body": "<p>The problem with massively nested if statements without the { } is that it is a fragile structure. It is easy to come in and add a new statement and not realize whether it is or is not in one of the ifs or not. It also makes else statements harder to follow as not everyone is completely familiar with the precedence rules for else statements.</p>\n\n<p>It works, it's entirely valid code - but it is bad style.</p>\n\n<p>In this particular case you don't even need the nested ifs:</p>\n\n<pre><code>if (ggcCompareGrid.TopLevelTable != null)\n{\n foreach (GridRow row in ggcCompareGrid.TopLevelTable.Rows)\n {\n if (row.DisplayElement.ParentGroup != null && \n row.DisplayElement.ParentGroup.Category != null && \n (int)row.DisplayElement.ParentGroup.Category == key && \n row.Record == null)\n {\n row.DisplayElement.ParentGroup.IsExpanded = false;\n break;\n }\n }\n }\n</code></pre>\n\n<p>You could also consider in this case having a private boolean function that does the comparison:</p>\n\n<pre><code> private boolean checkParentGroup(ParentGroup group, int key, Record record) {\n return ((group != null) && (group.Category != null) && \n ((int)group.Category == key) && \n (record == null))\n }\n\nif (ggcCompareGrid.TopLevelTable != null)\n{\n foreach (GridRow row in ggcCompareGrid.TopLevelTable.Rows)\n {\n if (checkParentGroup(row.DisplayElement.ParentGroup, key, row.Record)\n {\n row.DisplayElement.ParentGroup.IsExpanded = false;\n break;\n }\n }\n }\n</code></pre>\n\n<p>This makes every part of the code simpler and clearer.</p>\n\n<p>Obviously the checkParentGroup method should have a better name though, describing what it is actually checking.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:16:29.250",
"Id": "37671",
"ParentId": "37665",
"Score": "12"
}
},
{
"body": "<p>In addition to other comments about the multi-line blocks, I think some of the more obvious issues are being ignored.... Why do you need these nested <code>if</code> blocks at all? You are just daisy-chaining logic that can easily be short-circuited in a single if condition.</p>\n\n<p>You code should/could be easily rewritten as (even if you use multiple-line structures):</p>\n\n<pre><code> if (ggcCompareGrid.TopLevelTable != null)\n foreach (GridRow row in ggcCompareGrid.TopLevelTable.Rows)\n if ( row.DisplayElement.ParentGroup != null\n && row.DisplayElement.ParentGroup.Category != null\n && (int)row.DisplayElement.ParentGroup.Category == key\n && row.Record == null)\n {\n row.DisplayElement.ParentGroup.IsExpanded = false;\n break;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:36:53.037",
"Id": "62490",
"Score": "0",
"body": "you have an extra parenthesis in there, and this is almost the same answer that TimB gave"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:39:32.660",
"Id": "62494",
"Score": "0",
"body": "I see the difference in the code now."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:32:25.330",
"Id": "37676",
"ParentId": "37665",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37670",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T10:59:46.143",
"Id": "37665",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Multiple lines of code in if statement without curly braces"
}
|
37665
|
<p>I'm making a text-based RPG in JavaScript. It works but I'd like to know how to improve it, like code-wise. Also, I want to know how to make it run on anything other than Internet Explorer.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.createElement("canvas");
canvas.id = "canvas";
var ctx = canvas.getContext("2d");
canvas.width = 1280;
canvas.height = 720;
document.body.appendChild(canvas);
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
bgReady = true;
};
bgImage.src = "images/background.bmp";
var inventory = new Array();
var map = new Array();
var T = 404;
var events = ["nothing","enemy","shop"];
var gamestate = "";
var lines = new Array();
var text = "";
var textposx =32;
var textposy = 33;
var playerx = 50;
var playery = 0;
var dead = false;
var weapon = new Array();
var armor = new Array();
var shield = new Array();
var mapsizex = 100;
var mapsizey = 100;
var finished = false;
var enemytypes = new Array();
player = new Object()
player.health = 300;
player.gold = 0;
player.xp = 0;
player.level = 0;
// weapon object
function item(I,wname,acc,dmg,cat,b1,b2) {
I = I || {};
I.type = cat; // type 1 = weapon, 2 = armor, 3 = healing item, 4 = stat enchancements
I.name = wname;
I.catergory = cat;
I.rating = acc;
I.damage = dmg;
I.bonus = new Array(b1,b2); //defence bonus,armor bonus
return I;
}
weapon.push(item(0,"short sword",100,60,"weapon",0,0));
armor.push(item(0,"leather armor",0,0,"armor",30,3));
//after adding a new stat, dont forget to edit the spawnMonster() function!
function enemy(I,ename,hp,acc,dmg,def,arm,exp,lvl){
I = I || {};
I.name = ename;
I.health = hp;
I.rating = acc;
I.damage = dmg;
I.defence = def;
I.armor = arm;
I.level = lvl;
I.xp = exp;
I.type = 1;
return I;
}
//enemy database
//level 1
enemytypes.push(enemy(0,"Thief",200,65,15,8,0,250,1));
enemytypes.push(enemy(0,"Zombie",250,60,10,15,0,300,1));
enemytypes.push(enemy(0,"Fallen",180,80,15,20,3,350,1));
enemytypes.push(enemy(0,"Yeti",325,70,10,10,0,450,1));
enemytypes.push(enemy(0,"Skeleton",150,60,10,10,0,200,1));
enemytypes.push(enemy(0,"Lion",125,120,25,10,0,300,1));
function randString()
{
var rtext = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
rtext += possible.charAt(Math.floor(Math.random() * possible.length));
return rtext;
}
function spawnMonster(place)
{
map[place]=new Array();
var x = Math.round(place/100);
var y = place%mapsizey;
var numgenmons = 1+Math.round(Math.random()*5);
for (var i = 0; i<numgenmons; i++){
var num = Math.round(Math.random()*5);
map[place].push(enemy(0,enemytypes[num].name,enemytypes[num].health,enemytypes[num].rating,enemytypes[num].damage,enemytypes[num].defence,enemytypes[num].armor,enemytypes[num].xp,enemytypes[num].level));
}
//name,hp,acc,dmg,def,arm,lvl
}
generate = function(){
for (var i = 0; i < (mapsizex*mapsizey); i++){
var r = Math.random();
if(r<0.5){
spawnMonster(i);
//50 % chance of encountering a monster/enemy
}
}
finished = true;
}
generate();
function eventCheck(){
var tempname = map[playerx*mapsizex+playery][0].name;
if(tempname!=undefined){
text = "you encountered a "+tempname+" !";
write();
gamestate = "enemy";
}
}
doShit = function(){
if(gamestate=="enemy"&&dead==false){
fight();
}
}
function targetCheck(){
T = 404;
for (var i=0;i<10;i++){
if(map[playerx*mapsizex+playery][i]!=undefined){
T = i;
return;
}
}
}
function fight(){
targetCheck();
if(T==404||map[playerx*mapsizex+playery][T].health<0){
alert("Target not found/dead!");
}
// player attacks enemy
var c = Math.random()*weapon[0].rating;
var d = map[playerx*mapsizex+playery][T].defence;
//comparing your attack rating to enemies' defence rating
if(c>d){
map[playerx*mapsizex+playery][T].health-=(weapon[0].damage-map[playerx*mapsizex+playery][T].armor);
text = "You succesfully attacked the enemy with "+(weapon[0].damage-map[playerx*mapsizex+playery][T].armor)+".";
write();
}else{
text = "You tried to attack the enemy, but failed to inflict any damage.";
write();
//alert(c+" : "+d);
}
if(map[playerx*mapsizex+playery][T].health <= 0){
text = "You killed the "+map[playerx*mapsizex+playery][T].name+" !";
write();
player.xp+=map[playerx*mapsizex+playery][T].xp;
if(player.xp>Math.pow((player.level+1)*10,2)){
player.level++;
}
//50% chance of loot drop
if(Math.random()<0.5){
dropLoot(map[playerx*mapsizex+playery][T].level);
}
delete map[playerx*mapsizex+playery][T];
targetCheck();
if(T==404){
text = "There are no enemies left. You won the battle!";
write();
gamestate="";
}else{
text = "You encountered a "+map[playerx*mapsizex+playery][T].name+".";
write();
}
return;
}
//enemy attacks player
var c2 = Math.random()*map[playerx*mapsizex+playery][T].rating;
var d2 = armor[0].bonus[0];
//comparing your defence rating to enemies' attack rating
if(c2>d2){
player.health-=(map[playerx*mapsizex+playery][T].damage-armor[0].bonus[1]);
text = "The enemy succesfully attacked you with "+(map[playerx*mapsizex+playery][T].damage-armor[0].bonus[1])+" damage.";
write();
if(player.health <= 1){dead = true,text="You died!",write()};
}else{
text = "The enemy failed to attack you.";
write();
//alert(c+" : "+d);
}
}
function dropLoot(level)
{
var kaas = Math.round(Math.pow((Math.random()*level*30),1.2));
player.gold+=kaas;
text = "You found "+kaas+" gold!";
write();
}
move = function(n){
if(gamestate==""&&dead==false){
if(n==3){
if(playerx<mapsizex){
playerx++;
text = "You moved east!";
}
}
if(n==2){
if(playerx>0){
playerx--;
text = "You moved west!";
}
}
if(n==1){
if(playery<mapsizey){
playery++;
text = "You moved north!";
}
}
write();
eventCheck();
}
}
function switchWeapon(){
}
write = function(){
//error was ~= instead of !=
if(textposy<650&text!=""){
lines.push(text);
}
}
function updateText()
{
ctx.fillText("\n \n",textposx, textposy);
ctx.fillStyle = "rgb(0, 0, 0)";
ctx.font = "24px Helvetica";
ctx.textAlign = "left";
ctx.textBaseline = "top"; //top
textposy = 10;
textposx = 33;
if(lines.length<30){var scroll = 0}else{var scroll = lines.length-30};
for (var i=scroll; i<lines.length; i++)
{
textposy += 20;
ctx.fillText(lines[i],textposx,textposy);
}
ctx.fillText("Your health: "+player.health,850,20);
ctx.fillText("Your gold: "+player.gold,850,50);
ctx.fillText("Your experience: "+player.xp + " / "+Math.pow((player.level+1)*10,2),850,80);
ctx.fillText("Your level: "+player.level,850,110);
}
setup = function() {
ctx.clearRect(300,0,1000,1000);
if (bgReady&&finished) {
ctx.drawImage(bgImage,0,0); //draw background first
}
updateText(); // after that, draw text
//alert(map[400][0].name);
}
//setInterval(setup,250);
//setTimeout(setup,1500);
setInterval(setup,250);</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.button {
position: fixed;
bottom: 245px;
right: 1200px;
}
.switch{
position: fixed;
bottom: 780px;
right: 710px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" href="css/style.css" type="text/css">
<head>
<meta charset="utf-8">
<title>rpg game</title>
</head>
<body>
<script src="javascript/diablo2.js"></script>
<div class="button">
<button onclick="move(3)">Go east</button>
<button onclick="move(2)">Go west</button>
<button onclick="move(1)">Go north</button>
<button onclick="doShit()">Action</button>
</div>
<div class = "switch">
<button onclick="switchWeapon()">Switch weapon</button>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:57:25.880",
"Id": "62470",
"Score": "0",
"body": "I read your post but i'm not sure what your question is. Please clarify if you want to be able to run this on any other browser, i.e., Chrome, Firefox, or if you want to be able to run it elsewhere such as a desktop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:04:37.377",
"Id": "62471",
"Score": "0",
"body": "OH, I ment run it locally, not on a webserver."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:05:30.147",
"Id": "62472",
"Score": "0",
"body": "Im asking for code-wise advice, how the same can be done better. If there are any other ways to achieve the same , that are simpler or better suited."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:14:05.853",
"Id": "62473",
"Score": "0",
"body": "I can't help you with how to make it work for other browsers and IE, but I am working on several suggestions for you on how to clean up some code mess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:14:49.150",
"Id": "62474",
"Score": "0",
"body": "The site is called code review, where else should I let my code be reviewed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:18:35.643",
"Id": "62475",
"Score": "1",
"body": "@none, you are in the right place ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T16:00:51.537",
"Id": "62498",
"Score": "0",
"body": "How do I approve suggestions? I cant seem to find a button..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T16:05:15.817",
"Id": "62500",
"Score": "0",
"body": "oh nevermind..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T18:32:29.583",
"Id": "63098",
"Score": "0",
"body": "Just curious - if it's text based, why use a <canvas>? It will be simpler and more portable, and also perform better if there's a lot of animated text, if you use jQuery and HTML elements that are text-oriented. Example: canvas context 2D always takes measurements in pixels, but you have to do a bunch of math all the time if you need to center or (wince) wrap text for a smaller screen, like a smart phone. It's more standards-oriented that way, too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-02T04:48:13.540",
"Id": "63975",
"Score": "0",
"body": "Note to the original author of this question - if you have additional concerns, please [contact us directly](http://codereview.stackexchange.com/contact) and let us know."
}
] |
[
{
"body": "<ul>\n<li><p>You have a lot of inconsistent indentation. (See link at the bottom for an easy way to fix this)</p></li>\n<li><p>Inconsistent positioning of <code>{</code>, are you going to place it on it's own line (common C# style) or on the previous line (common Java style)? The JavaScript conventions is to use the same conventions like Java for this.</p></li>\n<li><p>Put your global variables (playerx, playery, weapon, armor, shield, mapsizex, finished...) into an object, such as <code>game</code>. Perhaps <code>weapon</code>, <code>armor</code> and <code>shield</code> should be a part of the <code>player</code> object?</p></li>\n<li><p>Unclear variable names: <code>I</code>, <code>acc</code>, <code>arm</code> (there's also nothing wrong in using <code>damage</code> instead of <code>dmg</code>) Use variable names that are not too long (<code>theDamageOfTheEnemy</code> would be too long) but still long enough to be descriptive. (<code>damage</code> is fine, or sometimes <code>enemyDamage</code>)</p></li>\n<li><p>This comment indicates a code smell:</p>\n\n<blockquote>\n <p>//after adding a new stat, dont forget to edit the spawnMonster() function!</p>\n</blockquote>\n\n<p>When you have code that needs to be edited on multiple places in order to work, something is wrong. Instead consider using a <code>enemy(enemytype)</code> method that creates an enemy from an object. Instead of using nine <strong>(!!)</strong> parameters you can use <strong>one</strong> object that contains nine properties. Then you won't have to keep track of the <strong>order of the parameters</strong>. <code>enemy({ hp: 20, damage: 40, experience: 23, level: 15 })</code></p></li>\n<li><p>Perhaps my JavaScript knowledge is a bit rusty, but <code>I = I || {};</code> looks strange to me. Instead, consider using if-else to handle that logic to make it more clear what you are doing. <em>(Disregard this one, apparently it is very common and actually seems very useful. However, see <a href=\"https://codereview.stackexchange.com/questions/37672/javascript-rpg-advice/37695#37695\">tomdemuyt's answer</a> for a better solution)</em></p></li>\n<li><p>This method:</p>\n\n<pre><code>generate = function(){\nfor (var i = 0; i < (mapsizex*mapsizey); i++){\nvar r = Math.random();\nif(r<0.5){\nspawnMonster(i);\n//50 % chance of encountering a monster/enemy\n}\n\n}\nfinished = true;\n\n\n}\n</code></pre>\n\n<p>The readability is almost zero, use proper indentation and spacing and get rid of some empty lines:</p>\n\n<pre><code>generate = function() {\n for (var i = 0; i < (mapsizex * mapsizey); i++) {\n var r = Math.random();\n if (r < 0.5) {\n spawnMonster(i);\n //50 % chance of encountering a monster/enemy\n }\n }\n finished = true;\n}\n</code></pre>\n\n<p>And it suddenly becomes so much more readable! This should be applied to all your code.</p></li>\n<li><p><code>1+Math.round(Math.random()*5);</code> that's not the proper way to generate a number. You've used the correct way at one place, <code>Math.floor(Math.random() * ...)</code>. Why is this? Because the first number (0) and the last number(5) will have slightly lower probability than the others. Math.random() is guaranteed to return a number from 0 (inclusive) to 1 (exclusive). Therefore, to generate one of the numbers <code>1 2 3 4 5 6</code>, you should use: <code>Math.floor(Math.random() * 6) + 1</code>. This will give equal probabilities to all of the numbers.</p></li>\n</ul>\n\n<p>Honestly, there are more things that needs to be cleaned up in your code, this is just a start. @tomdemuyt provided more very important things.</p>\n\n<p>Consider using an <a href=\"http://jsbeautifier.org/\" rel=\"nofollow noreferrer\">Online JavaScript beautifier</a> for your code every now and then. This tool doesn't take care of refactoring your code though, such as renaming variables and organizing variables into objects, and rewriting methods to use one parameters instead of nine, but it is a handy tool to clean up some things at least.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:31:15.400",
"Id": "62477",
"Score": "5",
"body": "`variable ||= default` is a common idiom in javascript, the question is just using a less common form of that idiom."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:32:37.913",
"Id": "62478",
"Score": "0",
"body": "@amon OK, thanks. Then I guess the OP can disregard that part."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:54:52.497",
"Id": "62480",
"Score": "0",
"body": "@amon Just curious: What do you mean by \"less common form\"? `x = x || default` is pretty common. Or are you referring to `x || (x = default)` as the more common one?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:04:07.200",
"Id": "62483",
"Score": "0",
"body": "@Flambino I am referring to the equivalence of `x ||= y` and `x = x || y`, with the latter mostly being used by new programmers or readability fanatics."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:12:34.763",
"Id": "62485",
"Score": "3",
"body": "@amon `||=` isn't valid javascript syntax though, so I assume you mean `x || (x = y)`, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:17:50.997",
"Id": "62486",
"Score": "0",
"body": "@Flambino Thanks, I didn't know that and was inferring syntax from other languages in the C family – this is almost as bad as Python!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:15:20.910",
"Id": "62563",
"Score": "1",
"body": "With regards to the variable defaulting: in all JavaScript I've ever seen, `var x = value || default;` is the only form I've ever come across. It does indeed look a bit odd at first, but it tends to be extremely common. The long form with an if/else would be extremely noisy for any more than one or two few variables."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:26:41.270",
"Id": "37673",
"ParentId": "37672",
"Score": "11"
}
},
{
"body": "<p>As for running this code locally, your browser will be able to run it locally so long as all the resources are present and all links to those resources are relative. Yours links are already relative. It runs (for me) locally in firefox using this directory structure: </p>\n\n<pre><code>cr37672/\n├── 37672.html\n├── css\n│ └── style.css\n├── images\n│ └── background.bmp\n└── javascript\n └── diablo2.js\n</code></pre>\n\n<p>If I open the file <code>37672.html</code> in my browser of choice game renders and appears to function. </p>\n\n<p>This can be a useful setup especially if you have an <a href=\"http://www.jetbrains.com/pycharm/\" rel=\"nofollow\">IDE</a> that provides you a 'live view' function where changes made in the editor cause the browser to automatically refresh.</p>\n\n<p>Make life easier and structure your code. </p>\n\n<p>Make your life easier and write <a href=\"http://www.agiledata.org/essays/tdd.html\" rel=\"nofollow\">tests</a> -- it'll inform your design. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:58:04.420",
"Id": "62481",
"Score": "0",
"body": "As the entire game is JavaScript-based, which runs on the client side, I don't see how latency issues could ever occur where-ever it was running?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:01:05.437",
"Id": "62482",
"Score": "0",
"body": "@SimonAndréForsberg I was thinking that if images or other resources were pulled in then there could be a delay. On review, this is not the case here so i'll edit that out."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T16:04:28.283",
"Id": "62499",
"Score": "0",
"body": "Oh, I forgot there is no mouse/click function in the game, some people say getting the x and y mouse position may cause lag/performance issues in javascript.."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:45:56.257",
"Id": "37674",
"ParentId": "37672",
"Score": "4"
}
},
{
"body": "<h2>General</h2>\n\n<p>One of the best ways to learn a language is to write an RPG in it, because you can write working code with just basic knowledge, and then you keep polishing for a really long time.</p>\n\n<p>Since your game has a respectable 300 lines which is definitely going to grow, I would advise you to organize your code into objects.</p>\n\n<h2>Approach</h2>\n\n<p>I gave your code a read through and comment on things as I see them.</p>\n\n<h2>UI</h2>\n\n<p>You should have a <code>UI</code> object with an <code>init</code> function which will build the UI.</p>\n\n<pre><code>var UI =\n{\n init : function()\n {\n var canvas = document.createElement(\"canvas\");\n canvas.id = \"canvas\";\n this.ctx = canvas.getContext(\"2d\");\n\n canvas.width = 1280;\n canvas.height = 720;\n\n document.body.appendChild(canvas);\n\n var bgReady = false;\n var bgImage = new Image();\n\n bgImage.onload = function () {\n bgReady = true;\n };\n bgImage.src = \"images/background.bmp\";\n },\n write : function\n {\n ....\n },\n update: function\n {\n ....\n }\n}\n</code></pre>\n\n<p>On a side note, you probably want those magical constants <code>1280</code> and <code>720</code> placed on top of your code in constants. Furthermore, you are loading a <code>bmp</code>, this might be the reason that this only works in IE, considering using a <code>png</code> or <code>jpg</code> file instead.</p>\n\n<h2>Rogue Variables</h2>\n\n<p>Your code then has a number of variables that you should try to place inside an object.</p>\n\n<p>These could belong to a <code>game</code> object:</p>\n\n<pre><code>var events = [\"nothing\",\"enemy\",\"shop\"];\nvar gamestate = \"\";\nvar finished = false;\n</code></pre>\n\n<p>Note that you should try to stick to 1 naming convention, ideally lowerCamelCase, so you would use gameState instead of gamestate or game_state.</p>\n\n<p>These could belong to the <code>UI</code> object:</p>\n\n<pre><code>var lines = new Array();\nvar text = \"\";\nvar textposx =32;\nvar textposy = 33;\n</code></pre>\n\n<p>These could be long to the <code>player</code> object that you have already</p>\n\n<pre><code>var playerx = 50;\nvar playery = 0;\nvar dead = false;\nvar enemytypes = [];\nvar weapon = [];\nvar armor = [];\nvar shield = [];\n</code></pre>\n\n<p>Notice how I replaced with <code>new Array();</code> with <code>[]</code>, which is considered more appropriate.</p>\n\n<p>These could belong to a <code>dungeonMap</code> object:</p>\n\n<pre><code>var map = new Array();\nvar mapsizex = 100;\nvar mapsizey = 100;\n</code></pre>\n\n<p>you could even call the property <code>size</code> and assign <code>{ x : 100 , y : 100 }</code> to it.\nA map, in essence, is a 2d array, you should really consider using that instead of \na single array, it will make things much easier.</p>\n\n<p>Also, I would advise you to use a different way to init the player object:</p>\n\n<pre><code>player = \n{\n health : 300,\n gold : 0,\n xp : 0,\n level : 0,\n x : 50,\n y : 0,\n dead :false,\n inventory : [] \n}\n</code></pre>\n\n<p>instead of generating the object and assign properties to it (DRY).</p>\n\n<h2>Items</h2>\n\n<p>On to item/weapon/armor/shield : </p>\n\n<pre><code>// weapon object\nfunction item(I,wname,acc,dmg,cat,b1,b2)\n{\n I = I || {};\n I.type = cat; // type 1 = weapon, 2 = armor, 3 = healing item, 4 = stat enchancements\n I.name = wname;\n I.catergory = cat;\n I.rating = acc;\n I.damage = dmg;\n I.bonus = new Array(b1,b2); //defence bonus,armor bonus\n return I;\n}\n</code></pre>\n\n<p>You have realized that armor/weapon/shield is close enough that you can use the \nsame object, plus this will give you the option to create weapons with defense \nbonuses and armor with attack bonuses etc. I would change this function to be a\nconstructor though and hence drop the I argument.</p>\n\n<pre><code>function Item( name, rating, damage, type, db, ab )\n{\n this.name = name;\n this.rating = rating;\n this.damage = damage;\n this.type = type; \n this.bonus = { defense : db , armor : ab };\n}\n</code></pre>\n\n<p>I dropped catergory(sic) since you store that in type.</p>\n\n<p>You should have constants to represent the type, you could store them in item</p>\n\n<pre><code>Item.prototype.types = \n{\n WEAPON = 1,\n ARMOR = 2,\n HEALING = 3,\n STATBONUS = 4,\n}\n\nweapon.push(item(0,\"short sword\",100,60,\"weapon\",0,0));\narmor.push(item(0,\"leather armor\",0,0,\"armor\",30,3));\n</code></pre>\n\n<p>could then become</p>\n\n<pre><code>weapons.push(new Item(\"short sword\",100,60,Item.types.WEAPON,0,0));\narmors.push(new Item(\"leather armor\",0,0,Item.types.ARMOR,30,3));\n</code></pre>\n\n<h2>Enemies</h2>\n\n<p>See Items</p>\n\n<h2>Functions</h2>\n\n<p><strong>randString</strong></p>\n\n<ul>\n<li><code>randString</code> is interesting, I am not sure what you would do with this,\nsince you do not seem to use it anywhere, you might as well drop it.</li>\n</ul>\n\n<p><strong>spawnMonster</strong></p>\n\n<ul>\n<li>This function should be part of the dungeonMap object.</li>\n<li>It could really use some indenting</li>\n<li><code>var x = Math.round(place/100);</code> -> you dont use x</li>\n<li><code>var y = place%mapsizey</code> -> you dont use y</li>\n<li><code>numgenmons</code> could be called <code>monsterCount</code></li>\n<li><code>1+Math.round(Math.random()*5);</code> -> You should scour your code and put all\n<code>Math.random</code> related code into an <code>RNG</code> object. ( Random Number Generator, all\npraise him, for he giveth and taketh away ).</li>\n<li>To push a new monster, I would use the built in JSON to clone the monster\n<code>map[place].push( JSON.parse( JSON.stringify( enemytypes[num] ) ) );</code></li>\n</ul>\n\n<p><strong>generate</strong></p>\n\n<ul>\n<li>Not sure why you chose <code>generate = function(){</code> instead of <code>function generate(){</code></li>\n<li>So much more could be done there, think walls, treasures, traps, quests, NPC's etc.</li>\n</ul>\n\n<p><strong>eventCheck</strong></p>\n\n<ul>\n<li>You should replace direct map access with a call to the dungeonMap object</li>\n<li>The code does not seem to check what happens if you come back to a cell where all monsters were defeated, bug ?</li>\n<li>Indenting!</li>\n<li><code>gamestate = \"enemy\";</code> -> \"enemy\" should be a constant, declared at the top or as part of the game class</li>\n</ul>\n\n<p><strong>targetCheck</strong></p>\n\n<ul>\n<li><code>404</code> is cute</li>\n<li>since the monster are added randomly to the array, just pick the first instead of a random one, then you can just check .length() of the cell and maybe you wont even need this function anymore, since it would be a one liner</li>\n</ul>\n\n<p><strong>fight</strong></p>\n\n<p>Combat, the crux of RPG!</p>\n\n<ul>\n<li>Whenever you write alert(something), consider console.log( something ) or write( something), this way only developers will see those messages</li>\n<li><code>text</code> should be a parameter of <code>write</code>, globals are evil in general, but especially here</li>\n<li>'c' and 'd' , could be better named</li>\n<li>From a design perspective, 'd' should have a random factor as well I feel</li>\n<li><code>[playerx*mapsizex+playery][T]</code> & <code>weapon[0]</code>\n<ul>\n<li>You could just <code>var monster = [playerx*mapsizex+playery][T]</code></li>\n<li>You could just <code>var weapon = player.weapon[0]</code></li>\n<li>Then you can write </li>\n</ul></li>\n</ul>\n\n<blockquote>\n<pre><code>if( attackScore > defenseScore ){\n var damage = weapon.damage - monster.armor\n monster.health-= damage;\n write( 'You succesfully attacked the enemy for ' + damage + '.' );\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li>Indent your code!</li>\n<li>The code where player attacks monster, and the code where monster counter attacks should really be in 2 different functions</li>\n<li>Consider to give the monster a bonus if there are several monsters in the same place ?</li>\n<li>Finally, player/monster level should probably increase the attackScore ?</li>\n</ul>\n\n<p><strong>dropLoot</strong></p>\n\n<ul>\n<li>Just had to say I love kaas as well</li>\n</ul>\n\n<p><strong>move</strong></p>\n\n<ul>\n<li>INDENT!</li>\n<li>consider putting the directions into an object</li>\n</ul>\n\n<blockquote>\n<pre><code>directions = \n{\n 1 : { x : +0 , y : +1 , s : 'north' },\n 2 : { x : -1 , y : +0 , s : 'west' },\n 3 : { x : +1 , y : +0 , s : 'east' },\n 4 : { x : +0 , y : -1 , s : 'south' } /* Did you omit south on purpose ? */\n};\n</code></pre>\n</blockquote>\n\n<ul>\n<li>with that object you could check directions[ n ] to check for a valid direction\nand modify player.x and player.y and build a string to show where the player is going</li>\n</ul>\n\n<p><strong>updateText</strong></p>\n\n<ul>\n<li>This should be part of a UI object</li>\n<li>indent..</li>\n<li>There are a ton of magical constants that you should tidy up</li>\n<li>Use newlines, dont be tempted to do this : <code>if(lines.length<30){var scroll = 0}else{var scroll = lines.length-30};</code></li>\n<li><code>fillStyle</code>, <code>font</code>, <code>textAlign</code>, and <code>textBaseline</code> should be part of initialization, they dont change</li>\n</ul>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Much work to be done, please come back after you have implemented some/all of the code review answers, it was fun to read.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:12:16.010",
"Id": "62550",
"Score": "2",
"body": "Remember that JavaScript uses \"automatic semicolon insertion\", `player =` and `{` should be on the same line, otherwise it will be buggy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:38:28.980",
"Id": "62560",
"Score": "1",
"body": "Correction: When initializing variables, there does **not** seem to be any automatic semicolon insertion. So there's nothing wrong with this answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T09:04:45.793",
"Id": "63002",
"Score": "0",
"body": "I haven't tried map[place].push( JSON.parse( JSON.stringify( enemytypes[num] ) ) ); yet, but regular map[place].push(enemytypes[num]) doesn't work for some reason, the health variable will behave strange, i.e. if you kill the enemy, ALL enemies of that type are dead in the whole game.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T11:46:49.673",
"Id": "63069",
"Score": "0",
"body": "I tried JSON.parse( JSON.stringify( and It works! Amazing! Although I don't understand how it works, it encrypts the text or something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T15:52:45.600",
"Id": "63083",
"Score": "0",
"body": "It is the easiest way to clone an object, it changes it to text format (JSON) and then creates a new object from it. All your monsters died because every monster pointed to the same object. Objects are pointers."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:58:07.057",
"Id": "37695",
"ParentId": "37672",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T13:39:34.920",
"Id": "37672",
"Score": "6",
"Tags": [
"javascript",
"game",
"role-playing-game"
],
"Title": "JavaScript text-based RPG"
}
|
37672
|
<p>I've been working on a small "frame" for a text adventure in Python.</p>
<p>So it's less of a real adventure and more of a small testing location for all the commands.</p>
<p>I pretty much just started learning Python after completing the Codecademy tutorial and don't want to pick up any bad habits.</p>
<pre><code>#Text Adventure
import shlex
def map():
print ' _____________________________ '
print '| | | |'
print '| | | |'
print '| Room B = Room D = Room E |'
print '| Jack | Sword | Bear |'
print '| | | |'
print '|____||___|____||___|____\____|'
print '| | | |'
print '| | | |'
print '| Steve | Jesse | Room F |'
print '| Room A = Room C = Chest |'
print '| | | |'
print '|_________|_________|_________|'
#The Room class
class Room(object):
def __init__(self, location,objectsinRoom, containersinRooom, wallsinRoom,peopleinRoom,hasDoor,\
description,descriptionpeople,descriptiondirections):
self.location = location
self.objectsinRoom = objectsinRoom
self.containersinRooom = containersinRooom
self.wallsinRoom = wallsinRoom
self.peopleinRoom = peopleinRoom
self.hasDoor = hasDoor
self.description = description
self.descriptionpeople = descriptionpeople
self.descriptiondirections = descriptiondirections
#Returns what will be printed about the Room you're in right meow
def display_Room(self):
stri = (' ')
itemprint = []
contprint = []
peopprint = []
for item in self.objectsinRoom:
if item.islocked == True:
pass
else:
if item.incontainer == True:
itemprint.append('A ' + item.name + ' is in the ' + item.containername + '. ')
else:
itemprint.append('A ' + item.name + ' is here.')
stritem = stri.join(itemprint)
for cont in self.containersinRooom:
contprint.append(cont.text)
strcont = stri.join(contprint)
for people in self.peopleinRoom:
if people.state == 'alive':
peopprint.append(' ' + people.name + ' is here. ')
elif people.state != 'alive':
peopprint.append(' ' + people.name + "'s dead body is here. ")
strpeop = stri.join(peopprint)
return self.description + strpeop + strcont + stritem
#The class for NPCs
class People(object):
def __init__(self,location,name,text,description,state):
self.location = location
self.name = name
self.text = text
self.description = description
self.state = state
#Pretty much useless
def printText(self):
print self.text
#Moves the player to another room
def go(self,location,Decision):
newlocation = list(self.location)
if Decision == 'go north' or Decision == 'go n' or Decision == 'n':
newlocation[1] += 1
test = world.get(tuple(newlocation))
if test == None:
print 'You cannot go there'
else:
if test.wallsinRoom[2] == False and (test.hasDoor == None or test.hasDoor.islocked == False\
or test.hasDoor.dir1 != 'n'):
Ply.location = tuple(newlocation)
elif test.wallsinRoom[2] == True:
print 'There is a wall here. '
elif test.hasDoor.islocked == True:
print 'There is a door in the way. '
elif Decision == 'go south' or Decision == 'go s' or Decision == 's':
newlocation[1] -= 1
test = world.get(tuple(newlocation))
if test == None:
print 'You cannot go there'
else:
if test.wallsinRoom[0] == False and (test.hasDoor == None or test.hasDoor.islocked == False\
or test.hasDoor.dir1 != 's'):
Ply.location = tuple(newlocation)
elif test.wallsinRoom[0] == True:
print 'There is a wall here. '
elif test.hasDoor.islocked == True:
print 'There is a door in the way. '
elif Decision == 'go east' or Decision == 'go e' or Decision == 'e':
newlocation[0] += 1
test = world.get(tuple(newlocation))
if test == None:
print 'You cannot go there'
else:
if test.wallsinRoom[3] == False and (test.hasDoor == None or test.hasDoor.islocked == False\
or test.hasDoor.dir1 != 'e'):
Ply.location = tuple(newlocation)
elif test.wallsinRoom[3] == True:
print 'There is a wall here. '
elif test.hasDoor.islocked == True:
print 'There is a door in the way. '
elif Decision == 'go west' or Decision == 'go w' or Decision == 'w':
newlocation[0] -= 1
test = world.get(tuple(newlocation))
if test == None:
print 'You cannot go there'
else:
if test.wallsinRoom[1] == False and (test.hasDoor == None or test.hasDoor.islocked == False\
or test.hasDoor.dir1 != 'w'):
Ply.location = tuple(newlocation)
elif test.wallsinRoom[1] == True:
print 'There is a wall here. '
elif test.hasDoor.islocked == True:
print 'There is a door in the way. '
#The Player class!
class Player(People):
def __init__(self,location,name,text,state):
self.location = location
self.name = name
self.text = text
self.state = state
#Actually prints the description of your location
def printlocation(self,location):
return world.get(self.location).display_Room()
#Adds to inventory n shit
def take(self,location,Decision):
tokens = shlex.split(Decision)
if len(tokens) != 2 or tokens[1] not in objects:
print "This doesn't exist."
else:
if Ply.location == objects[tokens[1]].location:
if objects[tokens[1]].ininv == 'no':
if objects[tokens[1]].islocked == False:
Inventory.append(objects[tokens[1]].name)
print 'Taken'
objects[tokens[1]].ininv = 'yes'
objects[tokens[1]].incontainer = 'yes'
objects[tokens[1]].containername = None
world.get(self.location).objectsinRoom.remove(objects[tokens[1]])
else:
print "You don't see that"
elif objects[tokens[1]].ininv == 'no':
print "You already have that"
else:
print "You don't see that"
#Removes from inventory n shit
def drop(self,location,Decision):
tokens = shlex.split(Decision)
if len(tokens) != 2 or tokens[1] not in Inventory:
print "You don't have that"
else:
objects[tokens[1]].ininv = 'no'
Inventory.remove(objects[tokens[1]].name)
objects[tokens[1]].location = self.location
world.get(self.location).objectsinRoom.append(objects[tokens[1]])
print 'Dropped'
#Puts something in a container.
def put(self,location,Decision):
tokens = shlex.split(Decision)
if len(tokens) != (4) or tokens[1] not in Inventory:
print "You don't have that"
elif tokens[2] != 'in' and tokens[2] != 'on':
print 'What?'
elif tokens[2] == 'in':
if tokens[3] not in containers:
print "The thing you want that in doesn't exist"
else:
objects[tokens[1]].ininv = 'no'
Inventory.remove(objects[tokens[1]].name)
objects[tokens[1]].location = self.location
world.get(self.location).objectsinRoom.append(objects[tokens[1]])
objects[tokens[1]].incontainer = True
objects[tokens[1]].containername = tokens[3]
print 'Put.'
elif tokens[2] == 'on' and tokens[3] == 'floor':
if tokens[1] not in Inventory:
print "You don't have that"
else:
objects[tokens[1]].ininv = 'no'
Inventory.remove(objects[tokens[1]].name)
objects[tokens[1]].location = self.location
world.get(self.location).objectsinRoom.append(objects[tokens[1]])
print 'Dropped'
#Opens a door or container
def open(self,location,Decision):
tokens = shlex.split(Decision)
if len(tokens) != 2 or tokens[1] not in containers:
if tokens[1] == 'door':
unlock(Decision)
else:
print "This doesn't exist."
else:
containers[tokens[1]].isopen = True
print 'Opened'
containers[tokens[1]].text = "An open " + containers[tokens[1]].name +" is here. "
for item in itemsincontainers[containers[tokens[1]]]:
item.islocked = False
#Closes a container
def close(self,location,Decision):
tokens = shlex.split(Decision)
if len(tokens) != 2 or tokens[1] not in containers:
print "This doesn't exist."
else:
containers[tokens[1]].isopen = False
print 'Closed'
containers[tokens[1]].text = "A " + containers[tokens[1]].name +" is here. "
for item in itemsincontainers[containers[tokens[1]]]:
item.islocked = True
#Talks to a NPC
def talk(self,location,Decision):
if Decision == 'talk steve' or Decision == 'talk to steve' or Decision == 'talk with steve':
if self.location == Steve.location:
if Jack.state == 'dead':
if gold.ininv == 'no':
print 'You killed Jack! Take this is a reward.'
print 'Gold added to Inventory'
Inventory.append(gold.name)
elif gold.ininv == 'yes':
print 'Thanks again, man.'
elif Steve.state == 'dead':
print 'This person is dead.'\
else:
Steve.printText()
else:
print "This person is not here."
elif Decision == 'talk jack' or Decision == 'talk to jack' or Decision == 'talk with jack':
if self.location == Jack.location:
if Jack.state == 'dead':
print 'This person is dead.'
else:
Jack.printText()
else:
print 'This person is not here'
elif Decision == 'talk jesse' or Decision == 'talk to jesse' or Decision == 'talk with jesse':
if self.location == Jesse.location:
if Jesse.state == 'dead':
print 'this person is dead'
elif 'gold' in Inventory:
Drug = raw_input('You wanna buy some drugs?')
if Drug == 'no':
print 'THEN FUCK OFF'
elif Drug == 'yes':
Inventory.remove('gold')
Inventory.append(meth.name)
print 'Gold removed from Inventory'
print 'Meth added to Inventory'
else:
Jesse.printText()
else:
print 'This person is not here'
elif Decision == 'talk bear' or Decision == 'talk to bear' or Decision == 'talk with bear':
if self.location == Bear.location:
if Bear.state == 'dead':
print 'this monster is dead'
else:
Bear.printText()
print 'The bear killed you'
print 'Game over'
Ply.state = 'dead'
else:
print 'This thing is not here'
#Kills a NPC
def kill(self,location,Decision):
tokens = shlex.split(Decision)
if len(tokens) == 2:
if tokens[1] in people:
if self.location == people[tokens[1]].location:
killhelp(tokens[1])
else:
print 'This person is not here.'
else:
print 'This person does not exist'
elif len(tokens) == 4:
if tokens[2] == 'with':
if tokens[1] in people:
if self.location == people[tokens[1]].location:
killhelpwithitem(tokens[3],tokens[1])
else:
print 'This person is not here.'
else:
print 'This person does not exist'
else:
print "This won't work"
else:
print "This doesn't work"
#The item class
class Item(object):
def __init__(self,name,text,location,cankill,ininv,incontainer,islocked,containername):
self.name = name
self.text = text
self.location = location
self.cankill = cankill
self.ininv = ininv
self.incontainer = incontainer
self.islocked = islocked
self.containername = containername
#Container Class
class Container(object):
def __init__(self,name,text,location,isopen,contains):
self.name = name
self.text = text
self.location = location
self.isopen = isopen
self.contains = contains
#Door class
class Door(object):
def __init__(self,name,text,location1,location2,dir1,dir2,islocked,needskey,key):
self.name = name
self.text = text
self.location1 = location1
self.location2 = location2
self.dir1 = dir1
self.dir2 = dir2
self.islocked = islocked
self.needskey = needskey
self.key = key
#helps the killmethod find out, if kill works
def killhelp(victim):
Dec = raw_input('With what?')
Dec2 = Dec.lower()
if Dec2 in objects:
if Dec2 in Inventory:
if objects[Dec2].cankill == 'yes':
killcons(victim)
else:
print "You can't kill with that!"
else:
print "You don't have that."
else:
print "This doesn't exist."
#helps the killmethod find out, if kill works
def killhelpwithitem(Item,victim):
if Item in objects:
if Item in Inventory:
if objects[Item].cankill == 'yes':
killcons(victim)
else:
print "You can't kill with that!"
else:
print "You don't have that."
else:
print "This doesn't exist."
#The consequences of a kill
def killcons(victim):
genericvictims = ['steve','jack','jesse']
if victim in genericvictims:
people[victim].state = 'dead'
print victim + ' died. '
else:
if victim == 'myself':
print 'You killed yourself. Good job, Really. Congratulations.'
print 'Game over'
Ply.state = 'dead'
elif victim == 'bear':
print 'YOU CANNOT KILL A BEAR GODDAMNIT'
#Prints your inventory
def inv():
stri = ', '
print 'You have ' + stri.join(Inventory)
#also opens stuff
#why is this not in the player class?
def unlock(Decision):
tokens = shlex.split(Decision)
otherlocation = list(Ply.location)
if len(tokens) != 2 or tokens[1] != 'door' or Ply.location not in Doorslocations:
if tokens[1] in containers:
Ply.open(Ply.location,Decision)
else:
"This not exist, brother. "
else:
if Doorsdirection[Ply.location] == 'n':
otherlocation[1] += 1
Doorslocations.get(Ply.location).islocked = False
print 'unlocked'
elif Doorsdirection[Ply.location] == 'e':
otherlocation[0] += 1
Doorslocations.get(Ply.location).islocked = False
print 'unlocked'
elif Doorsdirection[Ply.location] == 's':
otherlocation[1] -= 1
Doorslocations.get(Ply.location).islocked = False
print 'unlocked'
elif Doorsdirection[Ply.location] == 'w':
otherlocation[0] -= 1
Doorslocations.get(Ply.location).islocked = False
print 'unlocked'
#Examines an item.
def exam(Decision):
tokens = shlex.split(Decision)
if len(tokens) != 2 or tokens[0] != 'exam' or tokens[1] not in objects:
print "This doesn't exist"
else:
if Ply.location == objects[tokens[1]].location or tokens[1] in Inventory:
print objects[tokens[1]].text
else:
print "You don't see this"
#This doesn't work for some reason
def dodrugs():
if 'meth' in Inventory:
print 'YOU ARE HIGH'
Inventory.remove('meth')
meth.ininv = 'no'
else:
print "You don't have that"
#This is supposed to check at the end of turn, if something is supposed to happen
def script():
pass
#prints the help thingy
def helpp():
print "You can use the following commands:"
print "go (north,south,west,east)"
print "talk (person)"
print "kill (person) with (item)"
print "take (item)"
print "drop (item)"
print "open (door or container)"
print "inventory"
print "examine (item)"
print "quit"
Inventory = []
sword = Item('sword','This is a sword',(2,2,1),'yes','no',False,False,None)
pistol = Item('pistol','This is a pistol',(3,1,1),'yes','no',True,True,'chest')
gold = Item('gold','This is gold',(1,1,1),'no','no',False,False,None)
meth = Item('meth','THIS IS SOME REALLY NICE BLUE METH',(1,2,1),'no','no',False,False,None)
objects = {
'sword': sword,
'gold': gold,
'meth': meth,
'pistol': pistol
}
objectsinroomA = []
objectsinroomB = []
objectsinroomC = [sword]
objectsinroomD = []
objectsinroomE = []
objectsinroomF = [pistol]
chest = Container('Chest','A chest is here. ',(3,1,1),False,None)
containers = {
'chest': chest
}
itemsinchest = [pistol]
itemsincontainers = {
chest: itemsinchest
}
containersinRoomA = []
containersinRoomB = []
containersinRoomC = []
containersinRoomD = []
containersinRoomE = []
containersinRoomF = [chest]
Door1 = Door('Door','This is a door. ',(3,1,1),(3,2,1),'n','s',True,False,None)
Doorslocations = {
(3,1,1): Door1,
(3,2,1): Door1
}
Doorsdirection = {
(3,1,1): Door1.dir1,
(3,2,1): Door1.dir2
}
Ply = Player((1,1,1),'Player','','alive')
Steve = People((1,1,1),'Steve',"Hi, I'm Steve. Dude, can you do me favor? Kill Jack.",'This is Steve','alive')
Jack = People((1,2,1),'Jack',"Don't kill me! ",'This is Jack','alive')
Jesse = People((2,1,1),'Jesse','Piss off, bitch.','This is Jesse','alive')
Bear = People((3,2,1),'Bearbro','RAWWWRRR','THIS IS A FUCKING BEAR','alive')
people = {
'steve': Steve,
'jack': Jack,
'jesse': Jesse,
'bear' : Bear,
'myself': Ply,
}
peopleinRoomA = [Steve]
peopleinRoomB = [Jack]
peopleinRoomC = []
peopleinRoomD = [Jesse]
peopleinRoomE = [Bear]
peopleinRoomF = []
# North,East,South,West, Northlo,Eastlo,Southlo,Westlo
wallsinRoomA = [False,False,False,False, False,False,False,False]
wallsinRoomB = [False,False,False,False, False,False,False,False]
wallsinRoomC = [False,False,False,False, False,False,False,False]
wallsinRoomD = [False,False,False,False, False,False,False,False]
wallsinRoomE = [False,False,False,False, False,False,Door1.islocked,False]
wallsinRoomF = [False,False,False,False, Door1.islocked,False,False,False]
RoomA = Room((1,1,1),objectsinroomA,containersinRoomA,wallsinRoomA,peopleinRoomA,None,\
'You are in Room A.','',' You see a hallway to the north and to the east.')
RoomB = Room((1,2,1),objectsinroomB,containersinRoomB,wallsinRoomB,peopleinRoomB,None,\
'You are in Room B.','',' You see a hallway to the south and to the east.')
RoomC = Room((2,2,1),objectsinroomC,containersinRoomC,wallsinRoomC,peopleinRoomC,None,\
'You are in Room C.','',' You see a hallway to the west, to the east and to the south.')
RoomD = Room((2,1,1),objectsinroomD,containersinRoomD,wallsinRoomD,peopleinRoomD,None,\
'You are in Room D.','',' You see a hallway to the north and to the west.')
RoomE = Room((3,2,1),objectsinroomE,containersinRoomE,wallsinRoomE,peopleinRoomE,Door1,\
'You are in Room E. A door leading north is here. ',' ',' You see a hallway to the west and south.')
RoomF = Room((3,1,1),objectsinroomF,containersinRoomF,wallsinRoomF,peopleinRoomF,Door1,\
'You are in Room F. A door leading south is here.','',' You see a hallway to the west and north.')
world = {
(1,1,1):RoomA,
(1,2,1):RoomB,
(2,2,1):RoomC,
(2,1,1):RoomD,
(3,2,1):RoomE,
(3,1,1):RoomF
}
emptyline = '\n'
#The turn
def main():
print "Welcome to my Text Adventure!"
print "Use the 'help' command for help!"
while Ply.state == 'alive':
print Ply.printlocation(Ply.location)
Decisionst = raw_input('>')
Decisionstr = Decisionst.lower()
lst = shlex.split(Decisionstr)
if lst[0] == 'go' or lst[0] in 'nwse':
Ply.go(Ply.location,Decisionstr)
elif lst[0] == 'take' or lst[0] == 'get':
Ply.take(Ply.location, Decisionstr)
elif lst[0] == 'drop':
Ply.drop(Ply.location,Decisionstr)
elif lst[0] == 'quit':
break
elif lst[0] == 'talk':
Ply.talk(Ply.location, Decisionstr)
elif lst[0] == 'kill':
Ply.kill(Ply.location,Decisionstr)
elif lst[0] == 'die':
killcons('myself')
elif lst[0] == 'inventory' or lst[0] == 'inv' or lst[0] == 'i':
inv()
elif lst[0] == 'help':
helpp()
elif lst[0] == 'look':
Ply.printlocation(Ply.location)
elif lst[0] == 'open':
Ply.open(Ply.location,Decisionstr)
elif lst[0] == 'close':
Ply.close(Ply.location,Decisionstr)
elif lst[0] == 'put':
Ply.put(Ply.location,Decisionstr)
elif lst[0] == 'unlock':
unlock(Decisionstr)
elif lst[0] == 'examine' or 'exam':
exam(Decisionstr)
elif Decisionstr == 'do drugs' or 'do meth':
dodrugs()
script()
map()
main()
</code></pre>
<p><a href="http://pastebin.com/R9rfd5kZ">Code from Pastebin</a></p>
|
[] |
[
{
"body": "<p>There's a lot of code here, so it's hard to make a cohesive review. Instead I'll point out a few things related to your comment about avoiding picking up bad habits. The most common problems I see in your code are repeated work, and misplacement of responsibilities.</p>\n\n<p>This isn't comprehensive. I'm not going to even touch on the question of whether the rooms and players should be code or external data files. But here goes:</p>\n\n<h3><code>Room.__init__</code></h3>\n\n<ul>\n<li>I don't like having 9 parameters used by position. This makes things hard to read when invoking it; how do you know what's what in your <code>RoomA = Room(...)</code> lines? In your case, having named things like <code>wallsInRoomA</code> does clear this up, but that's not always the right answer.</li>\n<li>Good job wrapping the line. However note that inside matched braces, parentheses, or brackets, you don't need the trailing backslash.</li>\n</ul>\n\n<h3><code>Room.display_Room</code></h3>\n\n<ul>\n<li>Calling it display_<em>Room</em> limits duck typing from the outside. Instead of being able to write one helper function which eventually delegates to a method called <code>display</code>, it has to know the type of the thing it's displaying, and call the appropriate method. Granted today that's only Rooms, and there is no helper.</li>\n<li>The comparisons like <code>if item.islocked == True</code> could be merely <code>if item.islocked</code>; the <code>== True</code> is redundant and distracting.</li>\n<li><p>The way an item is displayed seems to put the logic in <code>Room</code> instead of where I think it would belong: on <code>Item</code>. If the code that combines the item name and location was put on <code>Item</code> (and similarly for containers and people), this function would look more like this:</p>\n\n<pre><code>def display():\n stri = ' '\n stritem = stri.join(item.display() for item in self.objectsinRoom if not item.islocked)\n strcont = stri.join(cont.display() for cont in self.containersinRooom)\n strpeop = stri.join(person.display() for person in self.peopleinRoom)\n return self.description + strpeop + strcont + stritem\n</code></pre></li>\n</ul>\n\n<h3><code>People.go</code></h3>\n\n<ul>\n<li>Should <code>go</code> be on <code>People</code> or <code>Player</code>? If you'll have wandering NPCs, it's fine on <code>People</code>, but if you won't, that seems somewhat odd to place this on the base class.</li>\n<li>The conversion of <code>self.location</code> from a tuple to a list and back is cute; it implicitly copies things, allows you to make your change, and so forth. But it also inherently limits how your world is laid out. You can't skip rooms. You can't make infinite loops. You can't make rooms by the North or South poles that don't follow the usual \"square\" terms. I would probably instead make the next room part of the doors.</li>\n<li>There's a lot of repeated code here. It would be good to refactor this, say by checking <code>Decision</code> and setting variables for the parts that differ (perhaps <code>index</code>, <code>move</code>, and <code>direction</code>), and then combining the remaining code. Or if you put this on a <code>Door</code>, you just have to look up your door, then process the door.</li>\n<li>Rather than using <code>world.get</code> and checking for None, I would probably just index <code>world[tuple(newlocation)]</code> and handle the potential <code>KeyError</code> in one spot. This change from get to indexing is more important in <code>Player.printlocation</code>, where using <code>world.get(self.location)</code> might return <code>None</code>, and you'd get a hard to read exception about <code>NoneType</code> not having attribute <code>display_Room</code>. If this was just <code>world[self.location].display_Room()</code>, you'd get a <code>KeyError</code> about <code>self.location</code> not being in the dictionary. Note as well that <code>printlocation</code> is not using the passed <code>location</code> parameter.</li>\n</ul>\n\n<h3><code>Player.open</code> and <code>Player.close</code></h3>\n\n<ul>\n<li>There's a lot of reuse of <code>tokens[1]</code>. This should probably be given a name, at least in the else clauses, to make things more readable.</li>\n</ul>\n\n<h3><code>Player.talk</code></h3>\n\n<ul>\n<li>The logic here should probably be refactored to the various NPCs. As is, all the talking logic of your entire set of NPCs is in the <code>Player</code> class. The trick is finding the balance between code like you have now, giving them each a different subclass, and trying to abstract just the bits you need somewhere inbetween.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:17:13.317",
"Id": "37697",
"ParentId": "37677",
"Score": "6"
}
},
{
"body": "<p>I'd second @michaelUrman's point about the room constructor- the long list of params makes it hard to follow what's going on. Since you don't do much with the constructor - you're not processing or otherwise mutating the incoming data - you could just create empty lists/dictionaries as needed and then have separate methods such as 'add_wall' and 'add_person' which would make the code read more legibly.</p>\n\n<p>I'd be more aggressive about pushing the logic down into the different pieces. For example, you have a lot of logic in Room.display_Room() which depends on knowledge of what the state of different items in the room is. If the room simply called a standard \"display\" method that gave back the description of things in the room based on their own code the whole setup would be much cleaner. This is the much-discussed '<a href=\"http://www.oodesign.com/single-responsibility-principle.html\" rel=\"nofollow\">single-responsibility principle</a>' </p>\n\n<p>You could combine that with generalizing the various types of room contents into a common base class so you don't need to manage so many types of pieces in different variables. This would make it easy to inventory and search through room contents and also make future expansion easier. Here's a very simplified example.</p>\n\n<pre><code>class SimplifiedExampleRoom(object):\n def __init__(self, name, *walls, contents = [])\n self.Name = name\n self.Walls = (w for w in walls)\n self.Contents = contents\n\n def add_items (self, *items):\n self.Contents += list(items)\n\n def displayl(self):\n return \"\\n\".join([item.display() for item in self.Contents])\n\n class RoomItem(object):\n\n def __init__(self, name, description, **options):\n self.Name = name\n\n self.Description = description\n self.Options = options # this is a dictionary so you can add optional \n # keyword arguments without changing constructors \n # in derived classes\n\n def display(self):\n return \"you see a %s\" % self.Description\n\n class ContainerItem(RoomItem):\n OPEN = 'open'\n CLOSED = 'closed' \n\n def__init__(self, name, descripton, **opts):\n super(self, ContainerItem).__init__(name, description, **opts)\n self.Contents = []\n self.State = self.CLOSED\n\n def add_item(self, item):\n self.Contents.add\n\n def remove_item(self, item):\n if item in self.Contents:\n self.Contents.remove(item)\n\n def display(self):\n if self.State == self.CLOSED:\n return \"you see a closed %s\" % self.Description\n else:\n contents = \"\\n * \".join([item.Name for item in self.Contents])\n header = \"you see an open %s. Inside you see:\" % self.Description\n return header + contents\n\n class Person(RoomItem):\n\n def__init__(self, name, descripton, **opts):\n super(self, Person).__init__(name, description, **opts)\n self.Alive = True\n\n def kill(self):\n self.Alive = False\n return \"%s falls lifeless to the floor\" % self.Name \n\n def display(self):\n if self.Alive:\n return self.description\n else:\n return \"You see the lifeless body of %s sprawled on the floor\" % self.Name\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T04:03:25.133",
"Id": "37719",
"ParentId": "37677",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T16:00:05.563",
"Id": "37677",
"Score": "10",
"Tags": [
"python",
"game",
"python-2.x"
],
"Title": "A small Python text adventure \"frame\""
}
|
37677
|
<p>Suppose I have data coming from different sources that tells me information about a large group of stores that has the following (just an example):</p>
<p><strong>Necessary to define what store we're dealing with:</strong></p>
<ul>
<li>Store_Name (String)</li>
<li>Location (String)</li>
</ul>
<p><strong>Store characteristics:</strong></p>
<ul>
<li>Square_Feet (Double)</li>
<li>No_Employees (Double)</li>
<li>Years_Open (Double)</li>
<li>... (Whatever else)</li>
</ul>
<p>And the structure of the program I'm working with is such that we will always get the first 2 (defining) characteristics and one or more of the store-specific characteristics. My goal is to conglomerate all the characteristics for each of the specific stores together.</p>
<p>To do this, I have created the following class:</p>
<pre class="lang-vb prettyprint-override"><code>Public Class StoreChars
Public Property Square_Feet as Double = 0
Public Property No_Employees as Double = 0
Public Property Years_Open as Double = 0
...
End Class
</code></pre>
<p>And then, in my program, I have created the following:</p>
<pre class="lang-vb prettyprint-override"><code>Dim StoreData As New Dictionary(Of Tuple(Of String, String), StoreChars)
</code></pre>
<p>The key being the <code>Store_Name</code> and <code>Location</code> as the defining tuple.</p>
<p>So, now, in my code, supposing I just got some data together with the defining characteristics for a set of stores (might be some, might be all... we don't know if we've seen these before or not even), my loop to put in that data looks as follows:</p>
<pre class="lang-vb prettyprint-override"><code>For Each PieceOfInfo in ReturnedData
Dim TupleKey As New Tuple(Of String, String)(PieceOfInfo.Store_Name,
PieceOfInfo.Location)
If Not StoreData.ContainsKey(TupleKey) Then
StoreData.Add(TupleKey, New StoreChars With
{
.Square_Feet = PieceOfInfo.Square_Feet
... (whatever else we got) ...
})
Else
StoreData(TupleKey).Square_Feet = PieceOfInfo.Square_Feet
... (whatever else we got) ...
End If
Next
</code></pre>
<p>But this seems to be very slow and I'm wondering if it isn't overly-processor-intensive to create a tuple in each loop, check the existence as a key, etc, but I can't think of a better way to do this.</p>
<p>The other solution I was thinking of was to create a <code>Dictionary(Of String, Dictionary(Of String, StoreChars))</code>. That would eliminate having to create a Tuple with each loop, but it would mean having to check existence of the keys in 2 separate dictionaries.</p>
<p>If there is a better way to do this, I would <strong>LOVE</strong> to hear what it is because I find myself having to program solutions like this fairly often! </p>
<p>Also, even though I wrote this code in VB, I'm just as comfortable with a C# solution - I'm just currently working in a VB environment.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:40:06.317",
"Id": "62503",
"Score": "1",
"body": "One suggestion I can make is rather than calling `StoreData.ContainsKey` you could call `StoreData.TryGetValue`. This way you don't have to do a 2nd lookup in your `Else` block."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:46:39.340",
"Id": "62504",
"Score": "0",
"body": "Tuple is not a good candidate for a key as it can yield a lot of hash collisions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:47:15.393",
"Id": "62505",
"Score": "1",
"body": "You should use a smaller unique identifier for each store instead of the combination of the store name and location. Besides, is it not possible to have two stores in one location? I know of a place with a Dunkin Donuts, \"Subway\", and a convenience store/gas station/car wash. Single address."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:54:25.550",
"Id": "62506",
"Score": "0",
"body": "@JohnSaunders, like I said, this is just an example I came up with to illustrate my scenario... In my case, it really is unique. As for using a smaller identifier. Like I said, the challenge is that the data is coming from various sources and the 2 characteristics ARE the unique identifiers... Any thoughts?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:55:06.887",
"Id": "62507",
"Score": "1",
"body": "I would include Name and Location in StoreChars, override GetHashCode and Equals, and use a HashSet for the collection. Or use a KeyedCollection with an indexer for the composite key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:02:16.173",
"Id": "62508",
"Score": "0",
"body": "@Blam, that sounds really interesting, but possibly out of my (current) depth... Do you have any resources / examples you could point me to... I'd love to learn better ways to do such things!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:09:40.340",
"Id": "62509",
"Score": "0",
"body": "I hope you have first measured the performance and decided that your code is working but isn't working fast enough. \"If it isn't working, then it doesn't matter how fast it isn't working\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:10:26.377",
"Id": "62510",
"Score": "0",
"body": "@JohnSaunders - It works, it's just substantially slower than I would like"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:12:03.273",
"Id": "62511",
"Score": "0",
"body": "OK, and so you've run a performance profiler and have narrowed it down to your dictionary. Good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:21:49.107",
"Id": "62512",
"Score": "1",
"body": "This link is really close (see my answer) but the key is composite Int rather than string. I use this in production and it is fast. But it does use a bit of memory as under the covers a KeyCollection seems to use two indexes. http://stackoverflow.com/questions/9328852/dictionary-with-multiple-keys-and-multiple-values-for-each-key/12682835#12682835"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:38:05.717",
"Id": "62513",
"Score": "0",
"body": "@Blam... WOW!!... That is really above my head, but I'll keep looking into it... <gulp> :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:37:57.140",
"Id": "62527",
"Score": "1",
"body": "Why would you ever declare number of employees a double?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T18:56:13.927",
"Id": "62533",
"Score": "0",
"body": "@svick, as I stated in the question, I created a dummy example to illustrate what I was trying to do here - This is not my production code"
}
] |
[
{
"body": "<p>If you're stuck with <code>Tuple<T1,T2></code> as a key, you want to provide an <code>IEqualityComparer<Tuple<T1,T2>></code> implementation in <a href=\"http://msdn.microsoft.com/fr-fr/library/ms132072%28v=vs.110%29.aspx\" rel=\"nofollow\">the constructor</a> of your dictionary.</p>\n\n<p>If you can change the <code>TKey</code> type, you might want to provide a custom class that implements <code>IEquatable<T></code>.</p>\n\n<p>The problem with the current code is that comparison between keys of type <code>Tuple<string, string></code> is not efficient.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:59:16.303",
"Id": "62514",
"Score": "0",
"body": "Thanks, Ken, I'm not in any way stuck with the `Tuple`, though. It's just what I thought would be the best solution. As for your suggestions, could you maybe help point me in the right direction for what you would consider being the best / most efficient solution (I'm guessing that would be the custom class implementing `IEquatable` - That is BRAND NEW to me... I'm not even sure how I'd use that)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:44:43.297",
"Id": "62529",
"Score": "1",
"body": "Why do you say that comparing `Tuple`s with the default comparer is not efficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-19T13:13:14.550",
"Id": "88238",
"Score": "0",
"body": "@svick see http://stackoverflow.com/questions/21084412/net-tuple-and-equals-performance"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:43:54.520",
"Id": "37680",
"ParentId": "37679",
"Score": "4"
}
},
{
"body": "<p>I take it you are mostly concerned with efficiency in this question (because your code already works).</p>\n\n<p>Instead of using the built-in <code>Tuple</code> (which is a reference type), create a custom <code>struct</code> or <code>struct</code>-based <code>Tuple</code> so that you save on heap allocations. Allocating and GC'ing a new heap object per lookup is indeed expensive.</p>\n\n<p>Be sure to override the equality members.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:00:32.167",
"Id": "62515",
"Score": "0",
"body": "Thank you so much for the reply, usr. Unfortunately, this is BRAND NEW territory for me... Do you know of any suggestions / resources that could help point me in the right direction to do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:11:27.497",
"Id": "62516",
"Score": "1",
"body": "@JohnBustos maybe you should start by looking at the difference between class and struct (https://www.google.com/webhp?complete=1&hl=en#complete=1&hl=en&q=c%23+class+struct). They are conceptually similar. It is not that hard to create a custom tuple. It is even easier to create a specialized struct: `struct Key { string Store_Name; string Location; }` (this is a sketch). If you've got any specific problems just post another comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:42:49.597",
"Id": "62517",
"Score": "0",
"body": "Thanks SO MUCH, creating the custom key `struct` does makes sense - And you're saying that creating a struct the same way I am now creating a tuple will save on memory allocation... That makes sense too!! - The part that kind of still catches me is \"overriding the equality members\"... How / where would I do that? Also, if you were programming a solution to a situation such as mine, would you do it this way or would you do something completely different (like maybe one of the other solutions posted)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:44:41.780",
"Id": "62518",
"Score": "2",
"body": "I would do it this way and I have done it this way. Override GetHashCode and make the struct implement IEquatable<MyStruct>. That way the dictionary will call your code to determine equality."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:48:17.973",
"Id": "37681",
"ParentId": "37679",
"Score": "4"
}
},
{
"body": "<p>Turns out I had a String, String KeyedCollection in my archive </p>\n\n<pre><code>using System.Collections.ObjectModel;\n\nnamespace KeyCollStringString\n{\n class Program\n {\n static void Main(string[] args)\n {\n StringStringO ss1 = new StringStringO(\"Sall\",\"John\");\n StringStringO ss2 = new StringStringO(\"Sall\", \"John\");\n if (ss1 == ss2) Console.WriteLine(\"same\");\n if (ss1.Equals(ss2)) Console.WriteLine(\"equals\");\n // that are equal but not the same I don't override = so I have both features\n\n StringStringCollection stringStringCollection = new StringStringCollection();\n // dont't have to repeat the key like Dictionary\n stringStringCollection.Add(new StringStringO(\"Ringo\", \"Paul\"));\n stringStringCollection.Add(new StringStringO(\"Mary\", \"Paul\"));\n stringStringCollection.Add(ss1);\n //this would thow a duplicate key error\n //stringStringCollection.Add(ss2);\n //this would thow a duplicate key error\n //stringStringCollection.Add(new StringStringO(\"Ringo\", \"Paul\"));\n Console.WriteLine(\"count\");\n Console.WriteLine(stringStringCollection.Count.ToString());\n // reference by ordinal postion (note the is not the long key)\n Console.WriteLine(\"oridinal\");\n Console.WriteLine(stringStringCollection[0].GetHashCode().ToString());\n // reference by index\n Console.WriteLine(\"index\");\n Console.WriteLine(stringStringCollection[\"Mary\", \"Paul\"].GetHashCode().ToString());\n Console.WriteLine(\"foreach\");\n foreach (StringStringO ssO in stringStringCollection)\n {\n Console.WriteLine(string.Format(\"HashCode {0} String1 {1} String2 {2} \", ssO.GetHashCode(), ssO.String1, ssO.String2));\n }\n Console.WriteLine(\"sorted by date\");\n foreach (StringStringO ssO in stringStringCollection.OrderBy(x => x.String1).ThenBy(x => x.String2))\n {\n Console.WriteLine(string.Format(\"HashCode {0} String1 {1} String2 {2} \", ssO.GetHashCode(), ssO.String1, ssO.String2));\n }\n Console.ReadLine();\n }\n public class StringStringCollection : KeyedCollection<StringStringS, StringStringO>\n {\n // This parameterless constructor calls the base class constructor \n // that specifies a dictionary threshold of 0, so that the internal \n // dictionary is created as soon as an item is added to the \n // collection. \n // \n public StringStringCollection() : base(null, 0) { }\n\n // This is the only method that absolutely must be overridden, \n // because without it the KeyedCollection cannot extract the \n // keys from the items. \n // \n protected override StringStringS GetKeyForItem(StringStringO item)\n {\n // In this example, the key is the part number. \n return item.StringStringS;\n }\n\n // indexer \n public StringStringO this[string String1, string String2]\n {\n get { return this[new StringStringS(String1, String2)]; }\n }\n }\n\n public struct StringStringS\n { // required as KeyCollection Key must be a single item\n // but you don't reaaly need to interact with Int32Int32s\n public readonly String String1, String2;\n public StringStringS(string string1, string string2) { this.String1 = string1.Trim(); this.String2 = string2.Trim(); }\n }\n public class StringStringO : Object\n {\n // implement you properties\n public StringStringS StringStringS { get; private set; }\n public String String1 { get { return StringStringS.String1; } }\n public String String2 { get { return StringStringS.String2; } }\n public override bool Equals(Object obj)\n {\n //Check for null and compare run-time types.\n if (obj == null || !(obj is StringStringO)) return false;\n StringStringO item = (StringStringO)obj;\n return (this.String1 == item.String1 && this.String2 == item.String2);\n }\n public override int GetHashCode() \n {\n int hash = 17;\n // Suitable nullity checks etc, of course :)\n hash = hash * 23 + String1.GetHashCode();\n hash = hash * 31 + String2.GetHashCode();\n return hash;\n }\n public StringStringO(string string1, string string2)\n {\n StringStringS stringStringS = new StringStringS(string1, string2);\n this.StringStringS = stringStringS;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:20:06.813",
"Id": "62540",
"Score": "0",
"body": "Blam, I truly loved your solution, but I have to admit it was just above my head... I'm going through the code now and still trying to wrap my head around it... I ended up going with tinstaafl's solution since it seemed to be the easiest solution that actually made sense to me... I am intent to learn your method, though, because it seems to be great programming practice. THANK YOU FOR YOUR HELP AND GUIDANCE!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:56:58.860",
"Id": "62661",
"Score": "0",
"body": "Given @svick's comment to Blam's solution, your answer seems to be the best, most concise... Albeit slightly over my head... But that I shall remedy!! THANK YOU!!!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-25T20:00:47.903",
"Id": "225561",
"Score": "2",
"body": "Could you provide an explanation of your solution, and not just the code?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T15:38:53.513",
"Id": "37682",
"ParentId": "37679",
"Score": "2"
}
},
{
"body": "<p>Another way to do this, is to add the store name and location to the <code>StoreChars</code> class and override the gethashcode function. You can combine the store name and location and create a hashcode to use as the key and the storechars object as the value:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Public Class StoreChars\n Public Property Store_Name As String = \"\"\n Public Property Location As String = \"\"\n Public Property Square_Feet As Double = 0\n Public Property No_Employees As Double = 0\n Public Property Years_Open As Double = 0\n Public Overrides Function GetHashCode() As Integer\n Return (Store_Name & Location).GetHashCode\n End Function\nEnd Class\n</code></pre>\n\n<p>Use it something like this:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Dim StoreData As Dictionary(Of Integer, StoreChars)\nFor Each PieceOfInfo In ReturnedData\n Dim TempChars As New StoreChars With\n {\n .Store_Name = PieceOfInfo.Store_Name,\n .Location = PieceOfInfo.Location,\n .Square_Feet = PieceOfInfo.Square_Feet,\n .No_Employees = PieceOfInfo.No_Employees,\n .Years_Open = PieceOfInfo.Years_Open\n }\n 'If using the hashcode is bothersome you could use \n 'Dim tempkey As String = PieceOfInfo.Store_Name & PieceOfInfo.Location\n Dim tempkey As Integer = TempChars.GetHashCode\n If StoreData.ContainsKey(tempkey) Then\n StoreData(tempkey) = TempChars\n Else\n StoreData.Add(tempkey, TempChars)\n End If\nNext\n</code></pre>\n\n<p>This assumes the properties in pieceofinfo will have have at least a default value and not be nothing.</p>\n\n<p>Creating a new storechars is mainly for readability and maintenance, You could optimize it by creating the hashcode separately from the store name and location strings then adding the other data separately. Since the hashcode is an integer it would probably be more efficient to store it than a tuple.</p>\n\n<p>Here's a revision without the extra object:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>For Each PieceOfInfo In ReturnedData\n 'If using the hashcode is bothersome you could use \n 'Dim tempkey As String = PieceOfInfo.Store_Name & PieceOfInfo.Location\n Dim tempkey As Integer = (PieceOfInfo.Store_Name & PieceOfInfo.Location).GetHashCode\n If StoreData.ContainsKey(tempkey) Then\n Using StoreData(tempkey)\n\n .Store_Name = PieceOfInfo.Store_Name\n .Location = PieceOfInfo.Location\n .Square_Feet = PieceOfInfo.Square_eet\n .No_Employees = PieceOfInfo.No_Employees\n .Years_Open = PieceOfInfo.Years_Open\n End Using\n Else\n StoreData.Add(tempkey, New StoreChars With\n {\n .Store_Name = PieceOfInfo.Store_Name,\n .Location = PieceOfInfo.Location,\n .Square_Feet = PieceOfInfo.Square_Feet,\n .No_Employees = PieceOfInfo.No_Employees,\n .Years_Open = PieceOfInfo.Years_Open\n })\n End If\nNext\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:01:01.927",
"Id": "62534",
"Score": "0",
"body": "Would this be more efficient? Because, in effect, you're creating a new `StoreChars` with each loop (even if one already exists) then running the `GetHashCode` on it to see if it already exists whereas with the original code, you're only creating a tuple..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:14:08.323",
"Id": "62536",
"Score": "0",
"body": "I think I'm catching on and this seems to be making the most amount of sense to me... So, if I understand correctly, you would, in your loop, do something like `tempkey = (PieceOfInfo.Store_Name & PieceOfInfo.Location).GetHashCode` then there wouldn't be a need to create the new object unless needed? ... that really does sound pretty genius to me if it works that way in real life - No tuples, no implementing IEquatable, none of that scary stuff!! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:18:05.737",
"Id": "62642",
"Score": "1",
"body": "Doing it like this is a very bad idea, because GetHashCode is not guaranteed to be unique."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:55:12.463",
"Id": "62659",
"Score": "0",
"body": "Darn it, @svick... I just read more into it and that makes sense too... Sorry, tinstaafl... I thought this was the best solution, but it turns out not...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T15:12:09.660",
"Id": "62673",
"Score": "0",
"body": "Seems to me that the hashcode of the two strings combined would be just as unique as comparing the two strings separately, which is what you were originally doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T16:04:49.277",
"Id": "62683",
"Score": "1",
"body": "@tinstaafl No, it won't. There are only 2^32 ints, but there are infintely many strings. So, there is a chance (though probably quite small) that two different strings will have the same hash code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T16:46:14.193",
"Id": "62692",
"Score": "0",
"body": "So then the basic code is still good compare the concatenated strings instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-04T15:55:02.157",
"Id": "149591",
"Score": "0",
"body": "You can't combine hashcodes like you are, this is flatly wrong. You need to use prime multiplication, then it likely becomes more costly anyway. If you calculate the HashCode one time in the constructor this might be viable method"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T18:53:13.267",
"Id": "37689",
"ParentId": "37679",
"Score": "0"
}
},
{
"body": "<p>You may like to create a Store class that holds all the properties of the store as </p>\n\n<ul>\n<li>We are not using the key components individually.</li>\n<li>Also, every class needs to have one purpose. </li>\n</ul>\n\n<p>Then, we can create the dictionary as below</p>\n\n<ul>\n<li>Dictionary(Of String, Store)</li>\n<li>Key = StoreName & Location</li>\n</ul>\n\n<p>Also, you may simply use Pascal case in variables, using underscore to seperate words is an old convention.</p>\n\n<p>Using concatenated string (StoreName & Location) as the key doesn't seem to be very elegant but it is a simple solution and we don't need to override the GetHashCode method in our class as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:20:42.327",
"Id": "62564",
"Score": "0",
"body": "Are you saying that the dictionary key should be a concatenation of the two strings? I think that's a bad advice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:04:50.880",
"Id": "62634",
"Score": "0",
"body": "Can you please explain why? I understand that solution doesn't seem to be very elegant but it results in less code and is also very simple to implement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:37:40.553",
"Id": "62635",
"Score": "0",
"body": "The main problem I have with that is that if everything is a string, then you have almost no type checking, so it's very easy to make a mistake by using the wrong string. Using Tuple would be somewhat better and a custom type would be best."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T15:01:48.567",
"Id": "62667",
"Score": "0",
"body": "I think this is not relevant at all. Yes, generally speaking we should not use strings in code as typo may result in bugs that are hard to find but neither are we embedding any strings here nor are we changing any string values here. Whether you use two string variables or single variable, it doesn't make is more error prone."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T15:03:40.120",
"Id": "62671",
"Score": "0",
"body": "Also, if you don't have any proper answer that explains why solution is bad, please undo the negative voting that you have done."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:28:08.480",
"Id": "37692",
"ParentId": "37679",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "37682",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T14:32:36.323",
"Id": "37679",
"Score": "3",
"Tags": [
"c#",
".net",
"vb.net",
"hash-map"
],
"Title": "Is there a better, more efficient way than Dictionary(Of Tuple(), MyClass)?"
}
|
37679
|
<p>I am learning the Strategy pattern but hate the idea of passing a new object to the Context each time I need to change the desired algorithm. Instead I think it would be best to create an enum that holds all of the Concrete Strategy objects, and simply update them with a setter on the context. Below is my implementation. Please let me know if this is a good approach for Strategy?</p>
<p><strong>Client</strong></p>
<pre><code>public class Client {
public static void main(String args[]){
IntroductionContext introductionContext = new IntroductionContext();
introductionContext.setStrategy(ConcreteStrategies.HELLO);
introductionContext.executeStrategy();
introductionContext.setStrategy(ConcreteStrategies.GOODBYE);
introductionContext.executeStrategy();
}
}
</code></pre>
<p><strong>Context</strong></p>
<pre><code>public class IntroductionContext {
private IInteractionStrategy iInteractionStrategy;
public void executeStrategy() {
if(iInteractionStrategy == null){
throw new RuntimeException("Context must set its strategy before invoking executeStrategy()");
}
this.iInteractionStrategy.interact();
}
public void setStrategy(ConcreteStrategies concreteStrategy){
this.iInteractionStrategy = (IInteractionStrategy) concreteStrategy.getConcreteStrategy();
}
}
</code></pre>
<p><strong>Enum to hold all strategy objects</strong></p>
<pre><code>public enum ConcreteStrategies {
HELLO(new HelloStrategy()), GOODBYE(new GoodByeStrategy());
private Object concreteStrategy;
private ConcreteStrategies(Object concreteStrategy){
this.concreteStrategy = concreteStrategy;
}
public Object getConcreteStrategy(){
return this.concreteStrategy;
}
}
</code></pre>
<p><strong>Strategy (Interface)</strong></p>
<pre><code>public interface IInteractionStrategy {
public void interact();
}
</code></pre>
<p><strong>Concrete Strategy</strong></p>
<pre><code>public class HelloStrategy implements IInteractionStrategy {
@Override
public void interact() {
System.out.println("Hello!");
}
}
</code></pre>
<p><strong>Concrete Strategy</strong></p>
<pre><code>public class GoodByeStrategy implements IInteractionStrategy {
@Override
public void interact() {
System.out.println("Goodbye!");
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:19:17.207",
"Id": "62521",
"Score": "0",
"body": "Is ConcreteStrategies an enum or a class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:25:23.597",
"Id": "62525",
"Score": "1",
"body": "@shivsky It's an enum. In Java, enums can contain methods."
}
] |
[
{
"body": "<p>The overall quality of your code is very good. It is, at least in my opinion, perfectly fine to have an enum containing the strategy implementations.</p>\n\n<p>A few comments and suggestions though:</p>\n\n<ul>\n<li><code>private Object concreteStrategy;</code> in your enum can and should be <code>private IInteractionStrategy concreteStrategy;</code> instead. No need to use <code>Object</code> references at all in your enum when you can use <code>IInteractionStrategy</code> instead. By doing this, you won't have to typecast in your <code>setStrategy</code> method.</li>\n<li>After implementing the above, <code>private IInteractionStrategy concreteStrategy</code> can and should be marked <strong>final</strong>.</li>\n<li>Even though it's fine to store all your strategies in your enum, you shouldn't enforce it. By having the method <code>public void setStrategy(ConcreteStrategies concreteStrategy)</code> you deny any strategies that are not part of your enum. Either change this method, or add a new one, to be <code>public void setStrategy(IInteractionStrategy concreteStrategy)</code></li>\n<li><code>IntroductionContext</code> <em>could</em> include a <code>executeStrategy(IInteractionStrategy)</code> method to execute a specific strategy. Then you don't <strong>need</strong> to first call <code>setStrategy</code> and then call <code>executeStrategy</code> (This is only a suggestion, use it if you like)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:42:09.673",
"Id": "62528",
"Score": "0",
"body": "Very nice analysis! Thanks for your detailed review. I was actually thinking that Object in the enum was a bad choice after I posted the code, I will definitely update that. On your point 3, I do want to enforce the context setter to only take enums. The reason for this is, from the client perspective, it will eliminate needing to know ALL of the possible concrete strategies available, as they will all be easily accessible through the ConcreteStrategies enum. Although I guess a better name for that enum might be needed. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:10:53.427",
"Id": "37685",
"ParentId": "37683",
"Score": "7"
}
},
{
"body": "<p>I'll add a little Java naming advice to complement Simon's thorough answer.</p>\n\n<ul>\n<li><p>Enum names are typically singular since you are always referencing a single value: <code>ConcreteStrategy.HELLO</code> instead of <code>ConcreteStrategies.HELLO</code>.</p></li>\n<li><p>I'm sure some people still prefix their interface names with <code>I</code>, but I cannot remember the last project I've worked on or open source tool I've used that does. That smells like leaking an implementation detail into the API.</p>\n\n<p>While it seems contradictory, it's still common to include <code>Abstract</code> in the names of abstract methods. I do this too because a) you have to have a different name from the interface and b) the abstract class is for implementers and doesn't go into the public API (normally).</p></li>\n<li><p>If you keep the <code>I</code> prefix, I would still remove the <code>i</code> prefix on the instance field: <code>interactionStrategy</code> instead of <code>iInteractionStrategy</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:36:46.820",
"Id": "62543",
"Score": "0",
"body": "\"That smells like leaking an implementation detail into the API\", whether a type is a class or an interface **is** a part of the public API. I also haven't seen many interfaces that gets prefixed like that though. Overall, I totally agree. +1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:26:50.817",
"Id": "62565",
"Score": "0",
"body": "@Simon - In a way yes, but I think that matters mostly when the client is required to extend it. If you're returning instances of the class/interface only for consumption, the client doesn't need to know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:31:45.957",
"Id": "62576",
"Score": "0",
"body": "That's true, David. But there's no way to protect the client from being able to know if something is a class or an interface."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:01:06.763",
"Id": "37690",
"ParentId": "37683",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37685",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T16:52:17.657",
"Id": "37683",
"Score": "7",
"Tags": [
"java"
],
"Title": "Implementation of the Strategy pattern"
}
|
37683
|
<p>I want to extract some values in i-commas(") from lines like this: </p>
<pre><code><P k="9,0,1" vt="191" v="100.99936" z="" />
</code></pre>
<p>Example:</p>
<pre><code>getCharVal ( cp, char "k=\"", 9)
</code></pre>
<p>where cp is a pointer the line above should return "9,0,1"</p>
<p>The function:</p>
<pre><code>#define ENDTAG "/>"
#define ICOMMAS '"'
char * getCharVal ( char *cp, char *att, size_t s)
{
char * val;
char * endTagP;
if (cp == NULL)return NULL;
cp = strstr(cp, att)+strlen(att);
if (cp == NULL) return NULL;
char * endP = strchr(cp, ICOMMAS);
if (endP == NULL) return NULL;
endTagP = strstr(cp, ENDTAG);
if (endTagP == NULL) return NULL;
if (endP > endTagP) return NULL;
size_t valsize = endP - cp ;
if (valsize > s) return NULL;
val = malloc(valsize + 1);
memcpy (val, cp, valsize);
val[valsize]='\0';
cp = endTagP;
return val;
}
</code></pre>
<p>This code is ugly. Could anyone give me hints on how to write it better? </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T03:04:17.527",
"Id": "62594",
"Score": "0",
"body": "[Use a regular expression](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)! (seriously, **don't!**)"
}
] |
[
{
"body": "<p>The easiest code to maintain is code that doesn't exist. For parsing XML, use an XML-parsing library, preferably with XPath support. Sometimes it <em>might</em> be justified to whip up your own code to extract values from XML, but it clearly does not make sense in this case. Not only is the code ugly by your own admission, low-level string- and memory-manipulation also distracts you from thinking about the big picture. Furthermore, your code will be less robust than a proper XML parser, and it will fail if the text is encoded in a semantically equivalent variant (for example, if a value is escaped).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:11:03.687",
"Id": "62584",
"Score": "0",
"body": "Definitely use a tried and true library, but as a exercise or for fun, try to write these yourself. You'll become a better programmer for the effort."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:36:59.807",
"Id": "37686",
"ParentId": "37684",
"Score": "5"
}
},
{
"body": "<p>Work on the algorithm first before you think about error checking. You know you'll input information correctly. The basic algorithm follows:</p>\n\n<pre><code>char *getCharVal(char *cp, char *att, size_t s)\n{\n char *val, *pChStart, *pChEnd;\n size_t valLen;\n\n pChStart = strstr(cp, att); // Find value substring in source string\n pChStart += strlen(att); // Go to beginning of value substring\n pChEnd = strstr(pChStart, \"\\\"\"); // Find end of value substring\n valLen = pChEnd - pChStart; // Calculate length of value substring\n\n val = malloc(valLen * sizeof(char) + 1); // Allocate memory for value substring\n strncpy(val, pChStart, valLen); // Copy value in source string to value substring copy\n val[valLen] = '\\0'; // NULL terminate value substring copy\n\n return val;\n}\n</code></pre>\n\n<p>Once you get the algorithm down, you can add error checking. You know you'll be checking for <code>NULL</code> a lot, so instead of using a lot of <code>if</code> statements in the source code, which adds clutter and makes things less readable, add a macro to \"hide\" it:</p>\n\n<pre><code>#define CHECK_NULL(string) (if((string) == NULL) return NULL)\n</code></pre>\n\n<p>With this, you can check for <code>NULL</code>s in a less obtrusive way:</p>\n\n<pre><code> CHECK_NULL(pChStart == strstr(cp, att));\n</code></pre>\n\n<p>Your code with the <code>CHECK_NULL</code> macro is much more readable:</p>\n\n<pre><code>char * getCharVal ( char *cp, char *att, size_t s)\n{\n char * val;\n char * endTagP;\n char * endP;\n\n CHECK_NULL(cp);\n CHECK_NULL(strstr(cp, att)+strlen(att));\n CHECK_NULL(endP = strchr(cp, ICOMMAS));\n CHECK_NULL(strstr(cp, ENDTAG));\n\n size_t valsize = endP - cp ;\n if (valsize > s) return NULL;\n\n CHECK_NULL(val = malloc(valsize + 1));\n memcpy (val, cp, valsize);\n val[valsize]='\\0';\n cp = endTagP;\n\n return val;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:34:04.040",
"Id": "62587",
"Score": "1",
"body": "Note that `sizeof(char)` is 1 by definition, `malloc` should not be cast, the OP is correct in using `memcpy` instead of your `strncpy` (he knows the length) and that multiple vars are usually best not declared on the same line but are often better defined at the point of first use. Encouraging the use of macros is also not something I would do and encouraging their use to hide error handling is arguably wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:41:41.030",
"Id": "62588",
"Score": "1",
"body": "@WilliamMorris OP tagged this C, so variables at top is convention. Using old compiler... I forgot to take the cast that it requires out. Chars are not always one byte. The macro is simple and it's obvious what it does."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T02:21:46.220",
"Id": "62589",
"Score": "1",
"body": "sizeof(char) is 1. By definition. The macro call is only \"obvious\" here because the definition is right above it. In normal use it will not be, and so without looking up the definition there is no way to know what happens if its \"check\" turns out false. And what happens when you have another use case where the return needs to be -1 instead of NULL? Another macro with a similar name? Use of macros is discouraged for good reasons."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:54:35.350",
"Id": "62658",
"Score": "1",
"body": "@WilliamMorris http://stackoverflow.com/questions/20684056/is-using-sizeofchar-when-dynamically-allocating-a-char-redundant You are correct sir. My apologies."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T10:14:43.270",
"Id": "62876",
"Score": "1",
"body": "@Fiddling Bits i really like your solution. I really didn't know to whom I should give \"accepted\". I decided for Morris because of his further explanation. Anyhow big thanks and I'll use some of you ideas too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T10:42:54.150",
"Id": "62877",
"Score": "1",
"body": "@MaMu Morris has more experience than I, so you made a good choice. Keep up the great work!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T11:00:11.560",
"Id": "62878",
"Score": "1",
"body": "@FiddlingBits Your solution seems more elegant to me. But I'm very beginner to c and have much less experience comparing to both of you."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:18:41.513",
"Id": "37701",
"ParentId": "37684",
"Score": "3"
}
},
{
"body": "<p>I've modified your code to make it more normal C99, including adding <code>const</code>\nto parameters that your function does not change, improving (to my taste) the\nvariable names, moving variable definition to the point of their first use and\nusing <code>strndup</code> to duplicate the tag (not universally available but easily\nwritten).</p>\n\n<pre><code>char *getCharVal(const char *ch, const char *att, size_t size)\n{\n if (!ch) {\n return NULL;\n }\n ch = strstr(ch, att);\n if (!ch) {\n return NULL;\n }\n ch += strlen(att);\n\n char *end = strchr(ch, '\"');\n if (!end) {\n return NULL;\n }\n char *endTag = strstr(ch, ENDTAG);\n if (!endTag) {\n return NULL;\n }\n if (end > endTag) {\n return NULL;\n }\n size_t valSize = end - ch;\n if (valSize > size) {\n return NULL;\n }\n return strndup(ch, valSize);\n}\n</code></pre>\n\n<p>Note also that your</p>\n\n<pre><code>cp = strstr(cp, att)+strlen(att);\nif (cp == NULL) return NULL;\n</code></pre>\n\n<p>will never fail because even if <code>att</code> is not found you have added its length\nto the NULL pointer that <code>strstr</code> would return.</p>\n\n<p>A beneficial change would be to omit the check for size (although perhaps your\napplication is such that this check is more necessary than it appears).</p>\n\n<p>Finally, I think your interface is ugly. It would be much cleaner to pass the\nthe pure attribute \"k\". However, I can see that passing \"k=\\\"\" is an\noptimisation that makes the function much simpler to implement. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T04:07:05.243",
"Id": "62600",
"Score": "0",
"body": "Didn't notice: `cp = strstr(cp, att)+strlen(att);`. Goo eye."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:16:31.390",
"Id": "62612",
"Score": "0",
"body": "Do you also recommend the change it and use standard xml libraries?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:25:44.897",
"Id": "62613",
"Score": "0",
"body": "Size is checked because it is stream and sometimes comes something wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T11:52:06.837",
"Id": "62628",
"Score": "1",
"body": "Depends. If if you only ever want to extract \"k\" from your stream then using your own function might be sensible. But if you need to extract more and/or your XML can be badly formed a library is likely to make the job much easier."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T02:07:04.140",
"Id": "37712",
"ParentId": "37684",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37712",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:02:32.920",
"Id": "37684",
"Score": "3",
"Tags": [
"c",
"strings",
"parsing",
"xml"
],
"Title": "Small function for getting character value"
}
|
37684
|
<p>I am writing a simple web application where I have a User entity and set of pre-defined questions to be answered by the User. The answers provided by the users for these questions would need to be stored against the userId and questionId. After a bit of googling and with the help of stackoverflow, I have designed the tables in the following way.</p>
<pre><code>UserDetails(userId, userName)
QuestionMaster(questionId, question)
QuestionAnswer(userId, questionId, answer, date) PK(userId, questionId)
</code></pre>
<p>The Hibernate Entity classes:</p>
<p><strong>UserDetails.class</strong></p>
<pre><code>@Entity
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "user")
public class UserDetails {
private int userId;
private String userName;
private Collection<QuestionAnswer> listOfAnswers = new HashSet<QuestionAnswer>();
@XmlElement (name = "answer", type=QuestionAnswer.class)
@OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.userDetails", cascade=CascadeType.ALL)
public Collection<QuestionAnswer> getListOfAnswers() {
return listOfAnswers;
}
public void setListOfAnswers(Collection<QuestionAnswer> listOfAnswers) {
this.listOfAnswers = listOfAnswers;
}
@XmlElement (name = "userId")
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
@XmlElement (name = "userName")
@Column(nullable=false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
</code></pre>
<p><strong>QuestionMaster.class</strong></p>
<pre><code>@Entity
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name="question")
public class QuestionMaster {
private int questionId;
private String question;
private Collection<QuestionAnswer> listOfAnswers = new HashSet<QuestionAnswer>();
@OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.questionMaster", cascade=CascadeType.ALL)
public Collection<QuestionAnswer> getListOfAnswers() {
return listOfAnswers;
}
public void setListOfAnswers(Collection<QuestionAnswer> listOfAnswers) {
this.listOfAnswers = listOfAnswers;
}
@XmlElement(name="quesId")
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
@XmlElement(name="ques")
@Column(unique=true, nullable=false)
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
</code></pre>
<p><strong>QuestionAnswer.class</strong> (fixed the typo)</p>
<pre><code>@Entity
@AssociationOverrides({
@AssociationOverride(name = "pk.questionMaster",
joinColumns = @JoinColumn(name = "QUESTIONID", nullable = false)),
@AssociationOverride(name = "pk.userDetails",
joinColumns = @JoinColumn(name = "USERID", nullable = false)) })
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "answer")
public class QuestionAnswer {
private String answer;
private Date date;
private QuestionAnswerId pk = new QuestionAnswerId();
@EmbeddedId
public QuestionAnswerId getPk() {
return pk;
}
@XmlElement (name = "question", type=QuestionMaster.class)
@Transient
public QuestionMaster getQuestionMaster(){
return getPk().getQuestionMaster();
}
public void setQuestionMaster(QuestionMaster questionMaster){
getPk().setQuestionMaster(questionMaster);
}
@Transient
public UserDetails getUserDetails(){
return getPk().getUserDetails();
}
public void setUserDetails(UserDetails userDetails){
getPk().setUserDetails(userDetails);
}
public void setPk(QuestionAnswerId pk) {
this.pk = pk;
}
@XmlElement(name="ans")
@Column(nullable=false)
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
@XmlElement(name="date")
@Temporal(TemporalType.DATE)
@Column(name = "DATE", nullable = false, length = 10)
public Date getDate() {
return date;
}
public void setDate(Date date){
this.date = date;
}
}
</code></pre>
<p><strong>QuestionAnswerId.class</strong></p>
<pre><code>@Embeddable
public class QuestionAnswerId implements Serializable {
private QuestionMaster questionMaster;
private UserDetails userDetails;
@ManyToOne (cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public QuestionMaster getQuestionMaster() {
return questionMaster;
}
public void setQuestionMaster(QuestionMaster questionMaster) {
this.questionMaster = questionMaster;
}
@ManyToOne (cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public UserDetails getUserDetails() {
return userDetails;
}
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
}
</code></pre>
<p>Sample REST API output for: /rest/users/5</p>
<pre><code><user>
<userName>xyz</userName>
<userId>5</userId>
<answer>
<ans>xyz</ans>
<date>2013-12-18T00:00:00+05:30</date>
<question>
<ques>What is your name</quesId>
<quesId>5</quesId>
</question>
</answer>
<answer>
<ans>25</ans>
<date>2013-12-18T00:00:00+05:30</date>
<question>
<ques>What is your age</ques>
<quesId>6</quesId>
</question>
</answer>
</user>
</code></pre>
<p>You comments/suggestions on this database design will be highly appreciated. I am new to Hibernate and in the process the learning it. Please suggest whether there is a better way to design the user-question-answer relationship, so that the response XML looks more elegant.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:15:45.807",
"Id": "62551",
"Score": "1",
"body": "XML is a data-interchange format. It is not something that is supposed to be pretty, or 'looks elegant'. It is supposed to be easily computer-readable, and sophisticated developer readable. If you need it to look elegant then you should not be using XML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T08:24:30.550",
"Id": "62609",
"Score": "0",
"body": "I do not quite agree. XML is meant to be human readable while also being processable by machines. This allows for example easy debugging. This is one of the main advantages of XML over for example JSON."
}
] |
[
{
"body": "<p>Rename QuestionAnser to QuestionAnswer but I think this is obvious..</p>\n\n<p>IMHO your Entitynames are to complicated and contain duplicate answers. I would rename QuestionMaster to Question and QuestionAnswer to QuestionAnswer. </p>\n\n<p>Why do you have an embedded ID?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:49:13.453",
"Id": "62653",
"Score": "0",
"body": "Thanks for your comment...\n1. QuestionAnser is s typo :) Thanks for pointing that out.\n2. I can work on simplifying the entity names.\n3. embedded ID... The composite id (UserDetails and QuestionMaster table) would be unique and hence went ahead with the embedded ID option. What would be you suggestion? A generated Id for QuestionAnswer table, and creating a unique index(userId, questionId)? Can you please help me understand the pros/cons of these approaches..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T17:10:22.873",
"Id": "62697",
"Score": "0",
"body": "It is personally preference. Your solution needs less space but I like to use an additional id."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T12:55:34.673",
"Id": "37742",
"ParentId": "37687",
"Score": "1"
}
},
{
"body": "<p>Whether a mapping is <em>correct</em> cannot be answered without knowing more about the Domain/UseCase.\nMapping above applies to both ORM and serialization mappings. ORM is a form of serialization/deserialization after all.</p>\n\n<p>Due to different reasons, chief among them being that ORM and other <em>mappings</em> are still a sore point, \ndevelopers try to make mappings reusable. Trying to make code more reusable, they try to make one set of mappings to rule them all. \nIn most cases this is a false trade-off between <strong>reuse</strong> and <strong>separation of concerns</strong>.\nInstead it usually is just another case of <a href=\"http://c2.com/cgi/wiki?PrematureGeneralization\" rel=\"nofollow\">Premature Generalization</a>. </p>\n\n<p>Analyzing your code in this light.</p>\n\n<p>Assuming a use case of \"View what answers a user gave to each question\" or \"view-user-answers\" for short.</p>\n\n<p>Starting with XML schema, since it is used for information interchange it is a given, we move from out side in. </p>\n\n<p>But in the initial design we can make improvements.\n<code>user/userName</code>, <code>user/userId</code> repetition in element name.\nI find wrapping collections in a collection root element more readable.\nIf there is a small number of questions client can cache them however it wants.\nWe wouldn't need to pass question text and id at the same time.\nThis is an engineering question. \nAlso made element names more readable. If bandwith were a concern you might as well think other options than raw xml before making element names cryptic.</p>\n\n<pre><code><user>\n <name>xyz</name>\n <id>5</id>\n <answers>\n <answer>\n <questionId>5</questionId>\n <text>xyz</text>\n <date>2013-12-18T00:00:00+05:30</date>\n </answer>\n <answer>\n <questionId>6</questionId>\n <text>25</text>\n <date>2013-12-18T00:00:00+05:30</date>\n </answer>\n </answers>\n</user>\n</code></pre>\n\n<p>Above is an immutable data structure. These usually map to a Data Transfer Object. DTOs also are immutable. You can pretty much map your xml schema one-to-one to a Java class. In fact there are tools which do that automatically for you.</p>\n\n<pre><code>// packaging convention: company-url/project-name/use-case/sub-use-cases-or-mvc-layers\npackage com.example.questapp.questionaire.view_user_answers.more_packages_only_if_necessary;\n\n// constructor getters equals etc usual suspects omitted for readability.\n// this class is NOT mapped to database. \n// because database and xml schemas should be able to changed independently \n// XML mapping annotations goes here\nclass UserDTO {\n String name;\n int id;\n List<Answer> answers;\n\n static class Answer {\n int questionId;\n String text;\n Date date; \n }\n}\n</code></pre>\n\n<p>Note <code>...Details</code> etc useless suffix. In fact I only added <code>..DTO</code> suffix because java namespacing is crap and I plan to have two User classes in the same source file.\n<code>Answer</code> does not have the suffix becaus it can be referred to unambiguously as <code>UserDTO.Answer</code>.</p>\n\n<p>We can call this just <code>Service</code> because services and use-cases map one-to-one.</p>\n\n<pre><code>package com.example.questapp.questionaire.view_user_answers;\n// note no updater method\n// note no class mapped do DB is present in this interface\ninterface Service {\n // would be called from /rest/users/id\n UserDTO getUser(int id);\n // would be called from /rest/users\n List<UserDTO> getUsers();\n}\n</code></pre>\n\n<p>Another service for another use case can be.</p>\n\n<pre><code>package com.example.questapp.questionaire.record_answer;\n// note no getter method\n// note no class mapped do DB is present in this interface either\ninterface Service {\n void recordAnswer(userId, questionId, text, date);\n}\n</code></pre>\n\n<p>Both use cases will work on the same <strong>Entities</strong>, though they do not need to.</p>\n\n<p>In this use case there are two top level entities: <strong>User</strong> and <strong>Question</strong>. For this case an <strong>Answer</strong> given by a User to a Question belong to User.</p>\n\n<p>We name our classes the SAME as above. We do not name our class <code>UserDetails</code> while we talk about <strong>Users</strong>. Similarly just <code>Question</code> instead of <code>QuestionMaster</code> and just <code>Answer</code> instead of <code>QuestionAnswer</code>. We <strong>do not</strong> name our classes not after tables.</p>\n\n<p><code>private Collection<QuestionAnswer> listOfAnswers</code> We do not repeat type in identifiers. Just <code>answers</code> is enough. Remember we assumed the use case was: \"View what answers a user gave to each question\". This suggest there is a one-to-one mapping between a Question and the Answer the User gave to it. So we use a <code>Map</code>. There probably is a natural ordering by <code>questionId</code> or <code>question number</code> whatever, and you using <code>listOfAnswers</code> hints at that so a <code>SortedMap</code> then.</p>\n\n<pre><code>// This is shared by both sub-use-cases \n// therefore it is in the upper level\npackage com.example.questapp.questionaire;\n\n// ORM mapping is here\nclass User {\n int userId;\n String userName;\n SortedMap<Question, Answer> answers;\n\n // this is private since no one except hibernate should set it \n private void setAnswers(Map<Question, Answer> answers);\n\n // this is the SAME name with service method\n // which is the SAME name with the use-case\n // which is the SAME name with what users call what they do. \n public recordAnswer(Question question, text, date);\n}\n</code></pre>\n\n<p>After renaming <code>QuestionMaster</code> to <code>Question</code> I renamed <code>Question.question</code> to <code>Question.text</code> because it is \"the text of the Question\", no? I also removed <code>Question.answers</code> as it is irrelevant in this use case. And we do not write code \"just in case\". Because <strong>You Ain't Gonna Need It</strong>.</p>\n\n<pre><code>// Simpler, no?\nclass Question {\n int id;\n // By naming this text\n String text;\n}\n</code></pre>\n\n<p>Similarly:</p>\n\n<pre><code>class Answer {\n Id id;\n String answer;\n Date date;\n\n static class Id {\n // Now that we decided root entity for answer is User\n // We put it first.\n User user;\n Question question;\n }\n}\n</code></pre>\n\n<p>This already is a long answer and is enough to digest. But I can make edits if questions are asked in comments.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:36:00.323",
"Id": "37812",
"ParentId": "37687",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T17:57:12.887",
"Id": "37687",
"Score": "1",
"Tags": [
"java",
"xml",
"hibernate"
],
"Title": "A query on Hibernate database design"
}
|
37687
|
<p>I'm trying to make a few webpages that will allow us in the tech support team at the factory I work at to provide support faster by adding a simple interface to actions we perform everyday directly on the database. </p>
<p>The following is for a simple page where we will enter a list of serial numbers and select from a few choices of actions to perform on them (actions are mostly executing a stored procedure or query in order to change something in the database). It consists of a texbox where we will enter a list of serials, a dropdown list and a checkbox. These basically move the serials to a diferent location and remove its flag as a finished product in the database. It also has two gridviews to show the serial data before and after the change. All this is inside panels to make each visible/invisible easily depending on where we are in the execution. The actuall calls to the database are in a different class which i'm not including here but are very straightforward parametrized queries and stored procedures.</p>
<p>I'm by no means an expert programmer but very interested in moving my career in that direction. I would like to know how a more experienced professional would have done this. </p>
<p>This is the code behind the webpage. Any comments are welcome, thank you very much.</p>
<pre><code>namespace UnpackTool
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region ViewStates
private List<string> CRIDS {
get
{
if (ViewState["CRIDS"] != null )
{
return (List<string>)ViewState["CRIDS"];
}
return null;
}
set
{
ViewState["CRIDS"] = value;
}
}
private List<string> SerialNumbers
{
get
{
if (ViewState["SerialNumbers"] != null)
{
return (List<string>)ViewState["SerialNumbers"];
}
return null;
}
set
{
ViewState["SerialNumbers"] = value;
}
}
private DataTable SerialData
{
get
{
if (ViewState["SerialData"] != null)
{
return (DataTable)ViewState["SerialData"];
}
return null;
}
set
{
ViewState["SerialData"] = value;
}
}
#endregion
#region Helpers
//Clear viewstate values and grids to start over
private void ClearSerials()
{
CRIDS = null;
SerialNumbers = null;
SerialData = null;
CRIDS = null;
SearchGrid.DataSource = null;
ResultsGrid.DataSource = null;
SearchGrid.DataBind();
ResultsGrid.DataBind();
}
// Switch view between panels according to current state
public void SwitchView(string sender)
{
if (sender == "Search")
{
Panel1.Visible = false;
Panel2.Visible = true;
Panel3.Visible = false;
SerialBox.Enabled = false;
}
if (sender == "Cancel")
{
Panel1.Visible = true;
Panel2.Visible = false;
Panel3.Visible = false;
SerialBox.Enabled = true;
UnpackCheck.Checked = false;
ProcessList.SelectedValue = "NO CHANGE";
HideErrorMessage();
}
if (sender == "Accept")
{
Panel1.Visible = false;
Panel2.Visible = false;
Panel3.Visible = true;
SerialBox.Enabled = false;
}
if (sender == "Return")
{
Panel1.Visible = true;
Panel2.Visible = false;
Panel3.Visible = false;
SerialBox.Enabled = true;
SerialBox.Text = "";
UnpackCheck.Checked = false;
ProcessList.SelectedValue = "NO CHANGE";
HideErrorMessage();
}
}
private void ShowErrorMessage(string Error)
{
ErrorLabel.Text = Error;
ErrorLabel.ForeColor = System.Drawing.Color.Red;
ErrorLabel.Visible = true;
}
private void HideErrorMessage()
{
ErrorLabel.Text = "";
ErrorLabel.ForeColor = System.Drawing.Color.Black;
ErrorLabel.Visible = false;
}
#endregion
#region Events
//Read from textbbox and get serial info from db
protected void SearchBtn_Click(object sender, EventArgs e)
{
GetSerials();
SwitchView("Search");
//Only get serial info from db if actual data is entered in textbox
if (SerialNumbers.Count > 0)
{
GetSerialData();
GetModelProcess();
}
}
//Check if serials should be moved and/or unpacked, and perform actions
protected void AcceptBtn_Click(object sender, EventArgs e)
{
//only do something if valid data is entered
if (SerialNumbers.Count > 0)
{
try
{
//If Unpack is checked, serials are unpacked
if (UnpackCheck.Checked)
{
UnpackSerials();
}
//When value is NO CHANGE, serials arent moved
if (ProcessList.SelectedValue.ToString() != "NO CHANGE")
{
MoveSerials();
}
//Get serial info again to see results
GetSerialData();
SwitchView("Accept");
HideErrorMessage();
}
catch (Exception ex)
{
ShowErrorMessage(ex.Message);
}
}
}
//Reset view
protected void CancelBtn_Click(object sender, EventArgs e)
{
SwitchView("Cancel");
ClearSerials();
}
//Reset view
protected void ReturnBtn_Click(object sender, EventArgs e)
{
SwitchView("Return");
ClearSerials();
}
#endregion
#region DataAccess
//Get serial info from db
private void GetSerials()
{
//If CrateID is selected search by CRID
if (InputType.SelectedValue.ToString() == "CrateID")
{
//Read from textbox into CRID viewstate list
CRIDS = new List<string>(SerialBox.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
//Method received list of CRID and returns list of serials
SerialNumbers = Dal.ExecuteCRIDSerialQuery(CRIDS).AsEnumerable().Select(x => x[0].ToString()).ToList();
}
else
{
//Read from textbox into SerialNumber viewstate list
SerialNumbers = new List<string>(SerialBox.Text.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries));
}
}
private void UnpackSerials()
{
//Unpack method receives list, returns nothing
Dal.ExecuteUnpackQuery(SerialNumbers);
}
private void MoveSerials()
{
//Move serials, executes stored procedure, receives single serialnumber, iterate through list executing for each
if (SerialData.Rows.Count > 0)
{
foreach (DataRow row in SerialData.Rows)
{
Dal.ExecuteMoveQuery(row["TSN"].ToString(), row["Model"].ToString(), ProcessList.SelectedValue.ToString());
}
}
}
private void GetSerialData()
{
DataTable serialdata = new DataTable();
//Get serial data from db, method receives list of serials, returns data table
SerialData = Dal.ExecuteResultsQuery(SerialNumbers);
//Fill datagrids
SearchGrid.DataSource = SerialData;
ResultsGrid.DataSource = SerialData;
SearchGrid.DataBind();
ResultsGrid.DataBind();
}
//Gets processed used by the models listed in the serial data, can receive different models, binds to dropdownlist
private void GetModelProcess()
{
if (SerialNumbers != null)
{
DataTable Processes = Dal.ExecuteProcessByModelQuery(SerialData.AsEnumerable().Select(x => x["Model"].ToString()).ToList());
ProcessList.DataSource = Processes;
ProcessList.DataTextField = "Process_Name";
ProcessList.DataValueField = "Process_Name";
ProcessList.DataBind();
//When value is NO CHANGE, serials arent moved
ProcessList.SelectedValue = "NO CHANGE";
}
}
#endregion
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T08:10:18.347",
"Id": "62757",
"Score": "0",
"body": "No, please don't advise to add a switch statement. It's clear that you should replace these conditions with polymorphism (sub classes). You create a Interface or Abstract base class that you use in your class, then each sub class defines its own behavior. This will make your code easier to read and maintain."
}
] |
[
{
"body": "<p>Simplify your properties with the <code>as</code> operator:</p>\n\n<pre><code>private List<string> CRIDS\n{\n get\n {\n return ViewState[\"CRIDS\"] as List<string>;\n }\n\n set\n {\n ViewState[\"CRIDS\"] = value;\n }\n}\n\nprivate List<string> SerialNumbers\n{\n get\n {\n return ViewState[\"SerialNumbers\"] as List<string>;\n }\n\n set\n {\n ViewState[\"SerialNumbers\"] = value;\n }\n}\n\nprivate DataTable SerialData\n{\n get\n {\n return ViewState[\"SerialData\"] as DataTable;\n }\n\n set\n {\n ViewState[\"SerialData\"] = value;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:33:52.520",
"Id": "62586",
"Score": "0",
"body": "+1, also not returning a null value indicating 'no values', better to return an empty list. Might need to initialise `ViewState[\"xyz\"] == null` elsewhere though, or check and return the empty list in the getter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T10:16:51.230",
"Id": "62621",
"Score": "1",
"body": "This subtly changes the behaviour. Before if the wrong type was placed in a field you would get a cast exception, in this case it will silently return null, potentially hiding a bug. Personally I'd just drop the null check and do a straight cast, e.g. `return (List<string>)ViewState[\"CRIDS\"];`. I don't believe you need to set to null first either, but then I haven't used ViewState in years - the MSDN docs should be able to tell you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:44:25.773",
"Id": "37704",
"ParentId": "37688",
"Score": "5"
}
},
{
"body": "<p>A few examples of opportunities to:</p>\n\n<ul>\n<li>Be more concise with the flow of control to improve readability and reduce the likelyhood of introducing bugs later on</li>\n<li>Breaking out/abstracting some operations to prevent duplication</li>\n</ul>\n\n<p><b>Conditionals</b></p>\n\n<p>The <code>SwitchView()</code> method will pass though each if statement even though it will match either none or one. In some cases avoiding unnecessary conditionals might be a performance consideration, but here it's just to be concise and improve readability:</p>\n\n<p>You could use either a series of <code>if() {} else if() {}</code>'s:</p>\n\n<pre><code>if (condition1)\n{\n //stuff\n}\nelse if (condition2)\n{\n //stuff\n}\nelse if (condition3)\n{\n //stuff\n}\nelse\n{\n //nothing matched\n}\n</code></pre>\n\n<p>Or in this case as you're checking only for string equality a <code>switch</code> as follows (generally worth thinking about case sensitivity here as well):</p>\n\n<pre><code>public void SwitchView(string sender)\n{\n switch (sender)\n {\n case \"Search\":\n Panel1.Visible = false;\n Panel2.Visible = true;\n Panel3.Visible = false;\n SerialBox.Enabled = false;\n break;\n case \"Cancel\":\n Panel1.Visible = true;\n Panel2.Visible = false;\n Panel3.Visible = false;\n SerialBox.Enabled = true;\n UnpackCheck.Checked = false;\n ProcessList.SelectedValue = \"NO CHANGE\";\n HideErrorMessage();\n break;\n case \"Accept\":\n Panel1.Visible = false;\n Panel2.Visible = false;\n Panel3.Visible = true;\n SerialBox.Enabled = false;\n break;\n case \"Return\":\n Panel1.Visible = true;\n Panel2.Visible = false;\n Panel3.Visible = false;\n SerialBox.Enabled = true;\n SerialBox.Text = \"\";\n UnpackCheck.Checked = false;\n ProcessList.SelectedValue = \"NO CHANGE\";\n HideErrorMessage();\n break;\n //optionally you could handle a situation of an unexpected sender as follows\n //default:\n // throw new Exception(\"Unexpected sender '\" + sender + \"' in SwitchView()\");\n }\n}\n</code></pre>\n\n<p>To remove some of those strings you might also define an <code>enum</code> like this giving you a strongly typed method of indicating what kind of action is triggering the view change:</p>\n\n<pre><code>public enum ActionViewStyle { Search, Cancel, Accept, Return };\n\npublic void SwitchView(ActionViewStyle sender)\n{\n switch (sender)\n {\n case ActionViewStyle.Search:\n Panel1.Visible = false;\n //etc...\n }\n}\n</code></pre>\n\n<p><b>Magic strings/numbers</b></p>\n\n<p>It's often considered good practice to avoid the use of <a href=\"https://softwareengineering.stackexchange.com/questions/187126/why-does-the-net-world-seem-to-embrace-magic-strings-instead-of-staticly-typed\">magic strings and numbers</a> <i>where practical</i>. For example, the following is easier to read, you can find all references, and prevents bugs introduced by a typo in some instance of the string:</p>\n\n<pre><code>private const string VS_KEY_CRIDS = \"CRIDS\";\nprivate const string VS_KEY_SERIAL_NUMBERS = \"SerialNumbers\";\nprivate const string VS_KEY_SERIAL_DATA = \"SerialData\";\nprivate const string MSG_PROCS_NO_CHANGE = \"NO CHANGE\";\nprivate const string COL_NAME_TSN = \"TSN\";\nprivate const string COL_NAME_MODEL = \"Model\";\n//etc...\n\nprivate List<string> CRIDS\n{\n get\n {\n if (ViewState[VS_KEY_CRIDS] != null)\n {\n return (List<string>)ViewState[VS_KEY_CRIDS];\n }\n\n return null;\n }\n set\n {\n ViewState[VS_KEY_CRIDS] = value;\n }\n}\n</code></pre>\n\n<p>You might also consider the approach for other strings reused throughout the class.</p>\n\n<p>There are a few approaches to storing strings/numbers, probably try to make a decision balancing the benefits abstracting the configuration, vs the complexity it introduces to what might otherwise be a trivial operation. Some options are:</p>\n\n<ul>\n<li>Local constants (above). Easy, simple, not so flexible</li>\n<li>Static class which can be referenced elsewhere</li>\n<li>External/independent configuration (file, database, etc)</li>\n</ul>\n\n<p><b>Splitting Strings</b></p>\n\n<p>I notice you're splitting up the user input like this in a few places:</p>\n\n<pre><code>new List<string>(SerialBox.Text.Split(new string[] { \"\\r\\n\" }, StringSplitOptions.RemoveEmptyEntries));\n</code></pre>\n\n<p>Nothing wrong with this, but you might consider breaking out the delimiter definition to a single location you can refer to, and the operation of getting a list of values from a delimited string into it's own method if it's something you'll be doing a lot:</p>\n\n<pre><code>//static string[] valueDelimiters = new string[] { Environment.NewLine };\nstatic string[] valueDelimiters = new string[] { \"\\r\\n\", \"\\n\" }; //if you want to handle LF and CRLF\n\nprivate IEnumerable<string> GetValuesAsList(string values, string [] delimiters)\n{\n return values.Split(valueDelimiters, StringSplitOptions.RemoveEmptyEntries).ToList();\n}\n\nprivate void GetSerials()\n{\n //If CrateID is selected search by CRID\n if (InputType.SelectedValue.ToString() == \"CrateID\")\n {\n //Read from textbox into CRID viewstate list\n CRIDS = GetValuesAsList(SerialBox.Text, valueDelimiters);\n\n //Method received list of CRID and returns list of serials\n SerialNumbers = Dal.ExecuteCRIDSerialQuery(CRIDS).AsEnumerable().Select(x => x[0].ToString()).ToList();\n }\n else\n {\n //Read from textbox into SerialNumber viewstate list\n SerialNumbers = GetValuesAsList(SerialBox.Text, valueDelimiters);\n }\n}\n</code></pre>\n\n<p><b>Input Sanitising</b></p>\n\n<p>As you're taking user input from <code>SerialBox</code> and passing it into a data access layer which may be executing some sql query, it's worth checking to make sure that you're guarding against injection with something like <a href=\"https://stackoverflow.com/questions/7505808/using-parameters-in-sql-statements\">parameterised queries</a></p>\n\n<p><b>Error Handling</b></p>\n\n<p>Looking at the calls into the data access layer, I'm just wondering if they might ever throw an exception (data repository unreachable, malformed query, bad data, etc). If so it would be a worthwhile investment in handling them and logging/display an appropriate message.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:56:22.863",
"Id": "62725",
"Score": "0",
"body": "Thank you for taking your time with this answer, it brings up some good points I hadn't considered. I'm already using paremeterised queries, but I did add error handling which had passed me by in some cases, changed the SwitchView method to a switch and removed the magic strings."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T00:06:26.887",
"Id": "37707",
"ParentId": "37688",
"Score": "6"
}
},
{
"body": "<p>For your <code>SwitchView()</code> function, i'd change the <code>if</code> statement to a <code>switch</code>, and simplify it for better readability.</p>\n\n<pre><code>public void SwitchView(string sender)\n{\n Panel1.Visible = false;\n Panel2.Visible = false;\n Panel3.Visible = false;\n SerialBox.Enabled = false;\n UnpackCheck.Checked = false;\n\n switch (sender)\n {\n case \"Search\":\n Panel2.Visible = true;\n UnpackCheck.Checked = true;\n break;\n case \"Cancel\":\n Panel1.Visible = true;\n SerialBox.Enabled = true;\n ProcessList.SelectedValue = \"NO CHANGE\";\n HideErrorMessage();\n break;\n case \"Accept\":\n Panel3.Visible = true;\n break;\n case \"Return\":\n Panel1.Visible = true;\n SerialBox.Enabled = true;\n SerialBox.Text = \"\";\n ProcessList.SelectedValue = \"NO CHANGE\";\n HideErrorMessage();\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T03:49:36.473",
"Id": "62598",
"Score": "1",
"body": "This was already mentioned in Kyle's answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T03:56:23.930",
"Id": "62599",
"Score": "2",
"body": "It was, but i expanded on it by resetting the panel visibility up the top so it's much clearer to see what's happening in each case. Simply changing it from `if` to `switch` seems pointless, ie a change for the sake of change."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T04:10:38.657",
"Id": "62601",
"Score": "1",
"body": "I think the change from if/else to switch is made useful even if just for the readability, and implicit understanding that 'we're dealing with cases that match sender and nothing else' as soon as you see the `switch` keyword, rather than needing to look at each x == y conditional. I agree with your simplification by removing the common components to improve readability, definitely good, though this could be done in exactly the same fashion with an if/elseif/etc block if you're that way inclined."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T04:44:07.287",
"Id": "62603",
"Score": "2",
"body": "Don't get me wrong, I agree with you. Yes you could simply change it from `if` to `switch`, or keep the `if` and do what I did and both are fine, but if you combine them, you end up in a much better place. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:17:27.850",
"Id": "37709",
"ParentId": "37688",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "37707",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T18:02:19.280",
"Id": "37688",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Advice to improve code in simple webpage"
}
|
37688
|
<p>I want to establish a hierarchy, where at each level of the hierarchy, each type can contain a <code>list<its own type></code>. So <code>Node</code> (root of object class hierarchy) contains a <code>list<Node*></code>, <code>SpecialNode : Node</code> contains a list of <code>SpecialNode</code>. <code>SpecialNode</code> should not "accidentally" put new <code>SpecialNode</code> children into the <code>list<Node*></code> in the base class, so the <code>list<></code> are private.</p>
<p>I personally <strong>hate</strong> the concept of namehiding, because it is extremely prone to mistakes, uninitialized values, etc. So here I have made it impossible (via <code>private</code>) for <code>SpecialNode</code> to "accidentally" insert into the <code>list<Node*></code> instead of its own <code>list<SpecialNode*></code>.</p>
<pre><code>struct Node
{
private:
list<Node*> children ;
protected:
int v ;
public:
Node( int iv ) : v(iv) { }
virtual void print( const char* msg )
{
printf( "REGULAR CHILD %d in %s\n", v, msg ) ;
for( Node *sn : Node::children )
sn->print( "regular" ) ;
}
} ;
struct SpecialNode : public Node
{
private:
list<SpecialNode*> children ;
public:
SpecialNode( int iv ) : Node(iv) { }
void add( SpecialNode* child ) {
children.push_back( child ) ;
}
void print( const char* msg )
{
printf( "SPECIAL CHILD %d in %s\n", v, msg ) ;
for( SpecialNode *sn : children )
sn->print( "special" ) ;
//for( Node *sn : Node::children )
// sn->print( "regular" ) ;
}
} ;
int main(int argc, const char * argv[])
{
SpecialNode *sn = new SpecialNode( 1 ) ;
// SpecialNodes must contain SpecialNode children.
sn->add( new SpecialNode( 2 ) ) ;
//sn->children.push_back( new Node( 3 ) ) ; // fails b/c Node is too basic to fit in SpecialNode container.
sn->print( "root" ) ;
}
</code></pre>
<p>Is this a good way to do this, or is there a better way?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:48:43.493",
"Id": "62544",
"Score": "0",
"body": "What are you trying to achieve with this? From your code it looks like you're only inheriting from `Node` so that you can have a 'level' to each node, is there a specific need to have a child with a parent each with a list of references to its own type (keep in mind that `std::list<SpecialNode>` will contain a `std::list<Node>` as well adding numerous levels of complexity)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:29:17.380",
"Id": "62554",
"Score": "0",
"body": "I'm trying to 1) Concrete each class' `list<self>` as its own type. 2) _Avoid name hiding errors and mistakes_"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:32:08.070",
"Id": "62566",
"Score": "0",
"body": "That's the mechanism you're trying to find, but why do you need it? Since a `SpecialNode*` can be stored in any `Node*`, such as the private `list<Node*>` if `Node` had an `add()`, but then unlike a `Node` it can't hold other `Node`s, this sounds like a violation of [LSP](http://en.wikipedia.org/wiki/Liskov_substitution_principle)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T23:17:02.513",
"Id": "62581",
"Score": "0",
"body": "your Node class has no add method in it at all, so you can never add any nodes to the base class. And you can only add SpecialNodes to the derived class. Perhaps what you would rather have are 2 separate classes with no relation or dependence on each other since you can't actually use these 2 together at all."
}
] |
[
{
"body": "<p>You might prefer to not use polymorphism at all if you want to make sure that your types remain unique. Consider something more like:</p>\n\n<pre><code>class Node\n{\nprivate:\n list<Node*> children ;\n int v ;\n\npublic:\n Node( int iv ) : v(iv) { }\n\n void add( Node* child )\n {\n children.push_back( child );\n }\n\n void print( const char* msg )\n {\n printf( \"REGULAR CHILD %d in %s\\n\", v, msg );\n for( Node *sn : Node::children )\n {\n sn->print( \"regular\" );\n }\n }\n};\n\nclass SpecialNode // no inheritance\n{\nprivate:\n list<SpecialNode*> children;\n int v;\n\npublic:\n SpecialNode( int iv ) : v(iv) {}\n void add( SpecialNode* child )\n {\n children.push_back( child ) ;\n }\n\n void print( const char* msg )\n {\n printf( \"SPECIAL CHILD %d in %s\\n\", v, msg ) ;\n for( SpecialNode *sn : children )\n sn->print( \"special\" ) ;\n }\n};\n\nclass Composite // no inheritance\n{\nprivate:\n Node nodes;\n SpecialNode specialNodes;\n\npublic:\n Composite( int iv ) : nodes(iv), specialNodes(iv)\n void addSpecial( SpecialNode* child )\n {\n specialNodes.add( child ) ;\n }\n void add( Node * child)\n {\n nodes.add(child);\n }\n\n void print( const char* msg )\n {\n nodes.print(msg);\n specialNodes.print(msg);\n }\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T23:31:52.977",
"Id": "37705",
"ParentId": "37691",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T19:07:27.677",
"Id": "37691",
"Score": "3",
"Tags": [
"c++",
"collections"
],
"Title": "Hierarchy with `list<self>` type"
}
|
37691
|
<p>I'm iterating through a number of text files, trying to locate all carriage-returns, and individually save the text between carriage-returns. I get the index numbers of all carriage-returns, but I haven't got the slightest about saving the text.</p>
<p>Basically I want to save every string between two carriage-returns into an individual variable. The next step is to save all the words within a string as an individual hash.</p>
<p>Here is my code so far (edited based on the help by Tin Man and Screenmutt) to get every single paragraph of a file into an array:</p>
<pre><code># script start
# outputfile
output_text = File.open("output.txt", 'w')
# directory with files
Dir.chdir("nkamp")
#count lines
lines = File.readlines("first.txt")
line_count = lines.size
text = lines.join
paragraph_count = text.split("\.\r").length
puts "#{paragraph_count} paragraphs."
#array of paragraphs
paragraphs = Array.new
contents = []
File.foreach("first.txt", "\.\r") do |paragraph|
puts paragraph.chomp
puts '-' * 40
contents << paragraph.chomp
paragraphs << paragraph.chomp
end
puts paragraphs[10]
</code></pre>
<p>This code gives me an array with all the paragraphs. I am using ".\r" instead of "\n\n" because the texts are copied from PDF files, and have lost the normal page layout structures.</p>
<p>The next step is to save an array of the words in a paragraph into the array instead of simply a string of text:</p>
<pre><code>words_in_each_paragraph = Array.new
File.foreach("Ann Reg Sci (2).txt", "\.\r") do |paragraph|
word_hash = {}
paragraph.split(/\W+/).each_with_object(word_hash) { |w, h|
h[w] = []
}
words_in_each_paragraph << word_hash
end
puts words_in_each_paragraph[8]
</code></pre>
<p>Which gives the following output:</p>
<pre><code>{""=>[], "The"=>[], "above"=>[], "contributions"=>[], "highlight"=>[], "the"=>[], "importance"=>[], "of"=>[], "sophisticated"=>[], "modeling"=>[], "work"=>[], "for"=>[], "a"=>[], "better"=>[], "understanding"=>[], "complexity"=>[], "entrepreneurial"=>[], "space"=>[], "economy"=>[]}
</code></pre>
<p>Now the next step is loop through every file, and create a dynamic hash that gives me</p>
<p>a. a number for the article. b. a number for the paragraph. c. the list of words as seen above.</p>
<p>For this I need to learn how to dynamically create hashes. This is where it goes wrong:</p>
<pre><code>lines = File.readlines("test.txt")
line_count = lines.size
text = lines.join
paragraph_count = text.split("\.\r").length
puts "#{paragraph_count} paragraphs."
testArray = Array.new(paragraph_count.to_i, Hash.new)
for i in 0...paragraph_count.to_i do
testArray[i] = Hash.new
puts "testArray #{i} has been made"
end
words_in_each_paragraph = Array.new
File.foreach("test.txt", "\.\r") do |paragraph|
word_hash = {}
paragraph.split(/\W+/).each_with_object(word_hash) { |w, h|
h[w] = []
}
words_in_each_paragraph << word_hash
testArray[i][:value] = word_hash
puts testArray[i] # IT WORKS HERE #
end
puts testArray[1] # AND IT DOESN'T WORK HERE #
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T04:14:08.137",
"Id": "63132",
"Score": "0",
"body": "Seeb, do you want it to work with this paragraph? :-)"
}
] |
[
{
"body": "<pre><code>text = File.read \"test.txt\"\nputs \"#{text.split(\"\\n\").size} lines.\"\nparagraphs = text.split \".\\n\"\nputs \"#{paragraphs.length} paragraphs.\"\n\nwords_in_each_paragraph = paragraphs.map.with_index do |paragraph, i|\n puts \"working on paragraph ##{i}\"\n paragraph.split(\"\\n\").map.with_index do |line, j|\n puts \"working on line ##{j}\"\n line.scan(/\\w+/).tap &method(:p)\n end\nend\n\np words_in_each_paragraph[1]\n</code></pre>\n\n<ol>\n<li><code>i</code> isn't inside <code>File.foreach</code> loop. It was used in previous looping, but not here.</li>\n<li>The best practice to create a new array with the same length as another one is to use <code>.map</code>. Anyway try to avoid usage of <code>i</code> in Ruby. You shouldn't bother with indexes.</li>\n<li>I assume you wanted to get a three-dimensional array, not the array and some hashes.</li>\n<li>Method <code>.tap</code> can be handy for debug printing while processing/converting data. It allows do some post-processing while returning the object itself to keep your <code>.map</code> blocks safe.</li>\n<li>Note, I used <code>\\n</code> -- you may want to change it back to <code>\\r</code>, but usually you don't need to think about line-endings -- <code>\\n</code> should be ok everywhere since OS should take care about it. </li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T11:55:22.493",
"Id": "37735",
"ParentId": "37696",
"Score": "4"
}
},
{
"body": "<p>So there's a lot going on here - a <em>lot</em> more than there needs to be. You're working way too hard for what is actually very simple.</p>\n\n<p>A few notes: I can't review code that hasn't been written. You're saying you want the \"article number\", but I don't see code for anything like that, so I'll ignore that bit for now. Similarly, you talk about \"a number of files\" but all your current code has hard-coded file names (that are different from code block to code block), so I'll leave that alone too. That leaves finding paragraphs and the words in those paragraphs.</p>\n\n<p>First, though, here are some of the things I noticed in your code:</p>\n\n<ul>\n<li>Your code keeps doing the same things over and over. You open, read, and split the target file into paragraphs again and again. And in different ways.</li>\n<li>A lot of code is never used for anything, or made entirely redundant by later code. E.g. you read all the lines in the file... and then don't use that for anything before joining all the lines into a single string again. And then you split it again, only differently. And <em>then</em> you read everything <em>again</em> a moment later...</li>\n<li>You open the \"output.txt\" file for writing, but you never use it for anything. Nor do you close it again. I'd suggest just printing to stdout (i.e. <code>puts</code>) and then you can use I/O redirection in the shell to dump that into a file.</li>\n</ul>\n\n<p>In all, there are problems, a lot of which, quite frankly, seem to suggest you don't understand your current code.</p>\n\n<p>Here's a detailed look at your last code block</p>\n\n<pre><code># Why use readlines when you don't need the actual lines?\nlines = File.readlines(\"test.txt\")\n\n# Never used for anything\nline_count = lines.size\n\n# File.readlines + join is the same as just using File.read\ntext = lines.join\n\n# Now you're re-splitting the text you just joined\nparagraph_count = text.split(\"\\.\\r\").length\n\n# ... just so you can print this, which the next bit\n# of code can do too, since it also splits the text\n# into paragraphs\nputs \"#{paragraph_count} paragraphs.\"\n\n# So all of the code above can safely be replaced with:\n# Nothing (just delete it)\n\n# When you use Array.new with a length and an object,\n# that object is *repeated* - not cloned - across the\n# array. So each index in the array points to the\n# exact same object.\n# This would likely lead to a bug (except that your\n# next bit of code makes all of this redundant)\n# Also, Ruby convention is to use underscores, so\n# \"test_array\", not \"testArray\". Of course, that name\n# is bad to begin with because it doesn't give you any\n# hints about what it contains. \ntestArray = Array.new(paragraph_count.to_i, Hash.new)\n\n# You never need to use a basic for loop in Ruby, ever.\n# Want you want is Enumerable#map, or - better yet -\n# use a block initializer in the first place to populate\n# the array\nfor i in 0...paragraph_count.to_i do\n # So here, you overwrite each index, making the\n # the above array initialization pointless\n testArray[i] = Hash.new\nend\n\n# Elsewhere in your post, you just used `[]` to create\n# a new, empty array. Why not do that here? It's the\n# most common way of doing it.\nwords_in_each_paragraph = Array.new\n\n# And now you open the file yet again, and split it\n# into paragraphs. Didn't we just do all this?\nFile.foreach(\"test.txt\", \"\\.\\r\") do |paragraph|\n\n # So you make a hash, and make each word a key in\n # that hash. Presumably because you only want unique\n # words. But that's what Array#uniq is for\n word_hash = {}\n paragraph.split(/\\W+/).each_with_object(word_hash) { |w, h|\n h[w] = []\n }\n\n # Why do this? You can transform the structure for\n # testArray into words_in_each_paragraph, and back\n # again, as needed, rather than build two pretty\n # similar arrays.\n words_in_each_paragraph << word_hash\n testArray[i][:value] = word_hash\nend\n</code></pre>\n\n<p>So yeah, there are issues.</p>\n\n<p>Here's my take on practically <em>all</em> of your code: How to get an array, where each item is itself an array of unique words in the paragraph</p>\n\n<pre><code># read file, split into paragraphs, and map each paragraph\n# into its unique, constituent words\nparagraphs = File.read(\"test.txt\").split(/\\s*?\\r\\s*/).map do |paragraph|\n paragraph.scan(/[[:alnum:]]+/).uniq\nend\n</code></pre>\n\n<p>Done. That's <em>all</em> of it in 3 lines.</p>\n\n<p>And it's more careful with its regexp patterns: It doesn't split at <em>anything</em> plus <code>\\r</code>, and it'll include non-\"word\" characters in words, so it won't split non-English names for instance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:06:03.027",
"Id": "37743",
"ParentId": "37696",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37743",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T20:08:21.013",
"Id": "37696",
"Score": "5",
"Tags": [
"ruby",
"array",
"hash-map"
],
"Title": "Splitting a text file into paragraphs and words"
}
|
37696
|
<pre><code>def truthy(v):
if issubclass(v.__class__, numbers.Number):
return bool(int(v))
if isinstance(v, basestring):
vl = v.lower()[0]
if vl == 'y' or vl == 't':
return True
return False
</code></pre>
<ol>
<li><p>Is there some type/class I missed that can be evaluated by Python as True/False that I missed here?</p></li>
<li><p>Drawbacks? Better ways?</p></li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:41:18.807",
"Id": "62568",
"Score": "2",
"body": "What do you plan to use this for?"
}
] |
[
{
"body": "<p>How about:</p>\n\n<pre><code>accepted_truthy_characters = {'y', 't'}\n\ndef truthy(value):\n if isinstance(value, basestring):\n return value and value[0].lower() in accepted_truthy_characters\n return bool(value)\n</code></pre>\n\n<p>In Python 3.x, basestring won't work and you'll need <code>isinstance(value, str)</code> instead.</p>\n\n<p>One thing you missed is that <code>value</code> might be a string, but it might be empty, which would leave you with an IndexError.</p>\n\n<p>Python's <code>bool()</code> will check an <code>int</code> for you, so I don't think you need to check if it's a Number, convert it with <code>int()</code>, and then <code>bool()</code>, unless I'm missing something about your use case.</p>\n\n<p>Out of curiosity, why do you need this? Are you checking user input? Won't that always be a string anyway? And in that case, wouldn't it be better to just check a few allowed \"positive\" strings?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:05:48.443",
"Id": "62570",
"Score": "0",
"body": "this is for parsing (INI) config file settings. Sysadmins are used to entire menagerie of truthy/falsy values across different sw, like: unset value (falsy), 'True', 'true', 't', 'y', 'yes', 1, 0..., so they can make errors. e.g. PHP rubbish is notorious for using all kinds of inconsistent truthy/falsy settings."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:08:18.490",
"Id": "62571",
"Score": "0",
"body": "`len(value)` → `value`. `&&` → `and`. `value.lower()[0]` → `value[0].lower()`. `bool(value)` → `value`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:10:03.147",
"Id": "62572",
"Score": "0",
"body": "argh and I forgot one more thing: `''[0]` -> `IndexError`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:16:12.890",
"Id": "62574",
"Score": "0",
"body": "`'no'` is a string, so it will be handled by the other return statement."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:16:17.653",
"Id": "62575",
"Score": "0",
"body": "@Gareth: if I'm writing \"truthy/falsy\" filter for a range of input types, I'd prefer to return clean boolean types only rather than truthy/falsy values again.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T23:11:18.683",
"Id": "62579",
"Score": "0",
"body": "Ack, I got '&&' in my python code, ew. Been writing too much javascript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T23:13:55.170",
"Id": "62580",
"Score": "0",
"body": "@GarethRees I used `bool(value)` to ensure that this function would always return a boolean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T23:20:01.997",
"Id": "62582",
"Score": "0",
"body": "Yes, I understand that. But if `value` is ever used in a context that requires a Boolean, Python will automatically convert it. So (unless the OP gives us more details about how this is going to be used) it doesn't seem necessary to do the conversion here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T23:31:28.757",
"Id": "62583",
"Score": "0",
"body": "I would want the signature of this function to be \"returns Boolean\" not \"returns True or else the original value\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:18:51.723",
"Id": "62585",
"Score": "0",
"body": "Is there any point in also checking __nonzero__ for objects and __len__ for sequences, if only to be 'generous in what you accept'?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:43:50.157",
"Id": "62616",
"Score": "0",
"body": "@Gareth: long story short: side effects. Sysadmin A puts \"yes\" in config file. Programmer A thinks \"neat I can put 'y' on the admin summary webpage directly\". Sysadmin B on another machine puts 1 in the setting or leaves it unset. People *may* use those values in ways other than boolean-type evaluation. Had the use been limited to boolean-type evaluation, you'd be 100% correct. Unfortunately, there's no guarantee other things will not be done on the truthy() output depending on the output type. If only booleans are guaranteed to be output, it eliminates many schroedinger-type classes of bugs."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:45:48.633",
"Id": "62617",
"Score": "0",
"body": "@theodox: my goal is to be \"strict in what you send out\" rather than be \"liberal in what you accept\". :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:53:48.170",
"Id": "62620",
"Score": "0",
"body": "@GarethRees: I do realize this sort of goes against spirit of duck typing. However, in this particular context, there's little to be gained by multiple output types and their methods and much to be lost. There's a lot to be gained by objects of different types having `.sum()` or `.append()` methods, and probably not much to be lost. But if output is expected to mean true or false, most of what different types and methods do here I think is introducing potential for bugs that are hard to find."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:54:15.963",
"Id": "62908",
"Score": "0",
"body": "No need for 2 returns `if isinstance(v, basestring): v = v and v[0].lower() in 'yt'` (v is either `''`, `True` or `False`) then `return bool(v)`"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:49:36.003",
"Id": "37699",
"ParentId": "37698",
"Score": "2"
}
},
{
"body": "<p>I can't test this right now, but the <code>isinstance</code> seems very unpythonic to me. Assuming that your original logic is correct, why not:</p>\n\n<pre><code>def truthy(v):\n try:\n return bool(int(v))\n except ValueError:\n pass\n try:\n first = v.lower()[0]\n return (first == 'y') or (first == 't')\n except AttributeError:\n pass\n return False\n</code></pre>\n\n<p>That way, you don't need to worry about missing any types -- if it's convertible to an <code>int</code> or if it implements a <code>lower()</code> method you'll catch it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T10:27:29.387",
"Id": "37875",
"ParentId": "37698",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37875",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T21:33:22.940",
"Id": "37698",
"Score": "2",
"Tags": [
"python"
],
"Title": "Truthy/falsy in Python"
}
|
37698
|
<p>I am sorry for the simple request, but I'm trying to figure out the best way to optimizing the following bit of code. I hate using 20 lines of code when 12-15 will suffice. I also don't like having to use intermediate variables if I don't need to.</p>
<pre><code>$total_query_raw = "SELECT SUM( total ) AS total
FROM `tblinvoices`
WHERE `datepaid`
BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'";
$total_query = mysqli_query($link, $total_query_raw);
if (!$total_query) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysqli_error();
exit;
}
$total_result = mysqli_fetch_array($total_query);
$grand_total = $total_result['total'];
echo "Grand Total: $" . number_format($grand_total,2) . "<br>";
mysqli_free_result($total_query);
</code></pre>
|
[] |
[
{
"body": "<p>you might want to write it like this</p>\n\n<pre><code>$total_query_raw = \"SELECT SUM( total ) AS total\n FROM `tblinvoices` \n WHERE `datepaid` \n BETWEEN '$start_date 00:00:00' AND '$end_date 23:59:59'\";\n\n$total_query = mysqli_query($link, $total_query_raw);\n\nif (!$total_query) {\n echo \"DB Error, could not query the database\\n\";\n echo 'MySQL Error: ' . mysqli_error();\n exit;\n} else {\n $total_result = mysqli_fetch_array($total_query);\n $grand_total = $total_result['total'];\n echo \"Grand Total: $\" . number_format($grand_total,2) . \"<br>\";\n mysqli_free_result($total_query);\n}\n</code></pre>\n\n<p>otherwise you are going to try and perform action on something that you know will give you an error, that is the whole reason for the if statement, so put the rest of that stuff in the else statement.</p>\n\n<p>and I am not sure but I think you can write the last part of it like this</p>\n\n<p>I think that it will do the assignment inside the if statement and return a <code>1</code> or <code>0</code> (<em>which relates to <code>true</code> or <code>false</code></em>)<br>\n<strong>but I may be thinking of another language that allows you to do this</strong></p>\n\n<pre><code>if ($total_query = mysqli_query($link, $total_query_raw))\n{\n $total_result = mysqli_fetch_array($total_query);\n $grand_total = $total_result['total'];\n echo \"Grand Total: $\" . number_format($grand_total,2) . \"<br>\";\n mysqli_free_result($total_query);\n} \nelse \n{\n echo \"DB Error, could not query the database\\n\";\n echo 'MySQL Error: ' . mysqli_error();\n exit;\n}\n</code></pre>\n\n<h1>UPDATE</h1>\n\n<p>ok so I did a little research on the Declaration & Assignment inside the condition, and based of <strong><a href=\"https://stackoverflow.com/a/6741415/1214743\">THIS ANSWER</a></strong> you can perform the assignment inside the If Condition.</p>\n\n<p>it does sound like you have to assign a \"<em>truthy</em>\" value? not sure exactly what that means. I assume that if the assignment is good, it will return True but if the assignment is bad it will return False.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:18:00.203",
"Id": "62641",
"Score": "0",
"body": "I am curious, did the Declaration in the If Condition work?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:58:53.737",
"Id": "62665",
"Score": "1",
"body": "Technically, PHP variables aren't *declared*, they just magically appear out of nowhere. Your way of initializing the variable inside the if-statement should work fine and is very common in PHP."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T15:20:02.640",
"Id": "62675",
"Score": "0",
"body": "@SimonAndréForsberg thank you for that little bit of info, I forgot about PHP being so nice (like Javascript) and giving you whatever you want on the fly like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T15:31:33.017",
"Id": "62678",
"Score": "1",
"body": "I'm not so sure I would call it \"nice\" but that's an entirely different subject..."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T23:47:08.697",
"Id": "37706",
"ParentId": "37703",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37706",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-18T22:42:14.753",
"Id": "37703",
"Score": "3",
"Tags": [
"php",
"optimization",
"mysql"
],
"Title": "Need help optimizing PHP/MySQL code snippet"
}
|
37703
|
<h2>Task</h2>
<p>Create a matrix of checkboxes. The user must be able to select only 1 checkbox in a row or unselect all of them.</p>
<p><img src="https://i.stack.imgur.com/i91DZ.png" alt="enter image description here" /></p>
<h2>Solution</h2>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<script type="text/javascript">
function switch_checkbox(id_selected, id_pair)
{
//if the current checkbox is checked - uncheck the 2-nd checkbox in this row
if(document.getElementById(id_selected).checked == true)
{
document.getElementById(id_pair).checked = false;
}
}
</script>
</head>
<body>
<form method="post" id="" action="send.php">
<input type="checkbox" name="group1[]" id="1-1" value="1-1" onChange="switch_checkbox('1-1', '1-2');"/>
<input type="checkbox" name="group2[]" id="1-2" value="1-2" onChange="switch_checkbox('1-2', '1-1');"/>
<br />
<input type="checkbox" name="group1[]" id="2-1" value="2-1" onChange="switch_checkbox('2-1', '2-2');"/>
<input type="checkbox" name="group2[]" id="2-2" value="2-2" onChange="switch_checkbox('2-2', '2-1');"/>
</form>
</body>
</html>
</code></pre>
<p>As you see, the solution is very primitive. Is it possible to make it even simpler?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:37:26.533",
"Id": "62615",
"Score": "0",
"body": "why not change to radio buttons?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:51:18.730",
"Id": "62618",
"Score": "0",
"body": "@ratchetfreak Because when you select one radio button, you can't unselect all of them."
}
] |
[
{
"body": "<p>Assuming an unchecked starting condition you can eliminate a parameter and thus drop the conditional:</p>\n\n<pre><code>function switch_checkbox(id_pair)\n{\n document.getElementById(id_pair).checked = false;\n}\n</code></pre>\n\n<p>...</p>\n\n<pre><code><input type=\"checkbox\" name=\"group1[]\" id=\"1-1\" value=\"1-1\" onChange=\"switch_checkbox('1-2');\"/>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T03:06:38.097",
"Id": "37715",
"ParentId": "37708",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "37715",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T00:47:04.777",
"Id": "37708",
"Score": "2",
"Tags": [
"javascript",
"html",
"matrix"
],
"Title": "Matrix of checkboxes - only 1 allowed in a row"
}
|
37708
|
<p>I've made the following and have a few questions:</p>
<ol>
<li><p>Do I have some (big) mistakes in this approach? (bad practices, 'this code is trash'...)</p>
<p>1.1 If I do, can you suggest what to fix?</p></li>
<li>Are appended element created in good way?</li>
<li>Code in success function seems to be a little long. Any way to refactor?</li>
</ol>
<p></p>
<p><img src="https://i.stack.imgur.com/Bt7Lr.jpg" alt="enter image description here"></p>
<p><strong>CSS code</strong></p>
<pre><code>.no-display-table {
display: none;
}
</code></pre>
<p><strong>HTML code</strong></p>
<pre><code><div class="row">
...
<!-- empty div will hold <select> which will be crated on ajax success -->
<div class="append-select col-md-3"></div>
...
</div>
...
<!-- onLoad => 'display: none', <tr> will be dynamically crated on Ajax Success -->
<div class="row">
<div class="col-md-4 col-md-offset-2">
<table id="options-table" class="table table-striped">
<thead> <tr><th> Selected options </th></tr> </thead>
<tbody></tbody>
</table>
</div>
</div>
</code></pre>
<p><strong>JavaScript code</strong><br></p>
<pre><code>$(function() {
$('#options-table').addClass('no-display-table');
$('#product-option-select').change(function() {
if($('.append-select select').length > 0)
$('.append-select select').remove();
var selectedOptionId = $(this).val();
$.ajax({
type: 'get',
url: '../option_types/' + selectedOptionId,
success: function(data) {
var element = '<select id="value-select" class="form-control">';
element += '<option selected disabled>Select value...</option>';
for(var i=0; i<data.length; i++) {
element += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
}
element += '</select>';
$('.append-select').append(element);
$('.append-select').on('change', '#value-select', function() {
$('#options-table').removeClass('no-display-table');
var selectedValue = $('#value-select option:selected').text();
var element = '<tr><td>' + selectedValue + '</td>';
element += '<td><a class="remove"> x </a></tr>';
$('#options-table tbody').append(element);
$('#options-table').on('mouseover', '.remove', function() {
$('.remove').css('cursor', 'pointer');
});
$('#options-table').on('click', '.remove', function() {
$(this).parent().parent().remove();
if($('#options-table tbody tr').length == 0)
$('#options-table').addClass('no-display-table');
});
});
}
});
});
});
</code></pre>
|
[] |
[
{
"body": "<h1>My 2 cents:</h1>\n\n<ul>\n<li><p>You could use <code>$().hide()</code> instead of assigning your custom hiding css class</p></li>\n<li><p>Similarly you could use <code>$().show()</code> instead of removing your custom hiding css class</p></li>\n<li><p>You do not have to check the length of a jQuery query, just call <code>remove()</code>, it will work.</p></li>\n<li><p>Your building of html inside the success callback is ugly, have a helper function to construct it and consider using DOM functions instead of HTML building. I personally tend to show/hide the select element and then rebuild the list with this helper function:</p></li>\n</ul>\n\n<blockquote>\n<pre><code>function setOptions( id , array )\n{\n //Get the element\n var select = document.getElementById( id ) , i \n //Remove potentially existing children, somewhat heartless\n while (select.firstChild)\n select.removeChild(select.firstChild);\n //Add the new children\n for( i = 0 ; i < array.length ; i++ )\n {\n var element = new Option( array[i].id , array[i].name );\n select.appendChild(element); \n } \n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li><p>Assiging the listener in the success callback is also too much, consider building a listener that takes into account new elements on document instead <code>$(document').on('change',</code> etc.</p></li>\n<li><p>Same for the mouseover / click event listeners</p></li>\n</ul>\n\n<p>Simply having the document element ( or any other parent element that stays in the DOM ) and the selector inside the on call should activate the listeners for new elements.</p>\n\n<blockquote>\n<pre><code>function initializeListeners()\n{\n $(document).on('change', '#value-select', function() {\n $('#options-table').removeClass('no-display-table');\n\n var selectedValue = $('#value-select option:selected').text();\n var element = '<tr><td>' + selectedValue + '</td>';\n element += '<td><a class=\"remove\"> x </a></tr>';\n\n $('#options-table tbody').append(element);\n\n $('#options-table').on('mouseover', '.remove', function() {\n $('.remove').css('cursor', 'pointer');\n });\n\n $('#options-table').on('click', '.remove', function() {\n $(this).parent().parent().remove();\n\n if($('#options-table tbody tr').length == 0)\n $('#options-table').addClass('no-display-table');\n });\n });\n}\n</code></pre>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:02:05.983",
"Id": "62942",
"Score": "0",
"body": "Assiging the listener in the success callback is also too much....Same for the mouseover / click event listeners\n\nCan you please provide code for that?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T16:03:48.020",
"Id": "37808",
"ParentId": "37711",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37808",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T01:37:14.927",
"Id": "37711",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"html",
"ajax",
"html5"
],
"Title": "Creating <select> element and append data to it"
}
|
37711
|
<p>This is my first real program in python (and my first real program) and I would like to have input by some more advanced programmers on the code, on the writing style and on the amount of comments (is it clear enough?).</p>
<p><code>new_name(scheme)</code> does seems a bit bloated to me, but I can't figure out how to write it in a simpler way.</p>
<p>The program is made to run on Debian GNU/Linux exclusively (if I get a good feedback I'll port it to other distros)</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
rename-flac takes the information from FLAC metadata to batch rename
the files according to a filenaming scheme.
Usage:
rename-flac.py <scheme> <directory>
rename-flac.py -o
rename-flac.py (-h | --help)
rename-flac.py --version
Arguments:
<scheme> The filenaming scheme. Has to be between quotation marks
<directory> The path to the directory containing the album
Options:
-o Displays filenaming scheme options
-h --help Shows the help screen
--version Outputs version information
"""
from docopt import docopt # Creating command-line interface
import sys
import subprocess
from py.path import local
#TODO: write to work with Python 3
# Dependency check
programlist = ["flac", "python-py", "python-docopt"]
for program in programlist:
pipe = subprocess.Popen(
["dpkg", "-l", program], stdout=subprocess.PIPE)
dependency, error = pipe.communicate()
if pipe.returncode:
print """
%s is not installed: this program won't run correctly.
To instal %s, run: aptitude install %s
""" % (program, program, program)
sys.exit()
else:
pass
# Defining the function that fetches metadata and formats it
def metadata(filename):
filename = str(filename).decode("utf-8") # Since filename is a LocalPath
# Tracknumber
pipe = subprocess.Popen(
["metaflac", "--show-tag=tracknumber", filename],
stdout=subprocess.PIPE)
tracknumber, error = pipe.communicate()
tracknumber = tracknumber.replace("tracknumber=", "")
tracknumber = tracknumber.replace("TRACKNUMBER=", "")
tracknumber = tracknumber.replace("TrackNumber=", "")
tracknumber = tracknumber.rstrip() # Remove whitespaces
if int(tracknumber) < 10: # To achieve 01 instead of 1
if "0" in tracknumber:
pass
else:
tracknumber = "0" + tracknumber
else:
pass
# Title
pipe = subprocess.Popen(
["metaflac", "--show-tag=title", filename],
stdout=subprocess.PIPE)
title, error = pipe.communicate()
title = title.replace("TITLE=", "")
title = title.replace("title=", "")
title = title.rstrip()
# Artist
pipe = subprocess.Popen(
["metaflac", "--show-tag=artist", filename],
stdout=subprocess.PIPE)
artist, error = pipe.communicate()
artist = artist.replace("ARTIST=", "")
artist = artist.replace("artist=", "")
artist = artist.rstrip()
# Date
pipe = subprocess.Popen(
["metaflac", "--show-tag=date", filename],
stdout=subprocess.PIPE)
date, error = pipe.communicate()
date = date.replace("DATE=", "")
date = date.replace("date=", "")
date = date.rstrip()
# Album
pipe = subprocess.Popen(
["metaflac", "--show-tag=album", filename],
stdout=subprocess.PIPE)
album, error = pipe.communicate()
album = album.replace("ALBUM=", "")
album = album.replace("album=", "")
album = album.rstrip()
# Genre
pipe = subprocess.Popen(
["metaflac", "--show-tag=genre", filename],
stdout=subprocess.PIPE)
genre, error = pipe.communicate()
genre = genre.replace("GENRE=", "")
genre = genre.replace("genre=", "")
genre = genre.rstrip()
return tracknumber, title, artist, date, album, genre
# Defining the function that puts together the new name
def new_name(scheme):
scheme_list = permanent_scheme.rsplit("%")
formatter = {}
for option in scheme_list:
if "a" in option:
scheme = scheme.replace("%a", "%(artist)s")
formatter["artist"] = artist
elif "b" in option:
scheme = scheme.replace("%b", "%(album)s")
formatter["album"] = album
elif "d" in option:
scheme = scheme.replace("%d", "%(date)s")
formatter["date"] = date
elif "g" in option:
scheme = scheme.replace("%g", "%(genre)s")
formatter["genre"] = genre
elif "n" in option:
scheme = scheme.replace("%n", "%(tracknumber)s")
formatter["tracknumber"] = tracknumber
elif "t" in option:
scheme = scheme.replace("%t", "%(title)s")
formatter["title"] = title
else:
pass
return scheme, formatter
# Defining function that renames the files
def rename(root):
if "t" not in permanent_scheme: # To have different file names
print " %t has to be present in <scheme>"
sys.exit()
new_filename = scheme % formatter
if new_filename == filename.purebasename:
print "%s is already named correctly\n" % (title)
else:
filename.rename(filename.new(purebasename=new_filename))
# Importing command line arguments
args = docopt(__doc__, version="rename-flac 1.0")
if args["<directory>"] != "None":
root = local(args["<directory>"])
scheme = args["<scheme>"]
permanent_scheme = args["<scheme>"]
else:
pass
# Filenaming scheme options
if args["-o"] == True:
print"""
Theses are the options you can use to define the filenaming scheme:
%a = Artist | %b = Album | %d = Date
%g = Genre | %n = Tracknumber | %t = Title
"""
sys.exit()
# Renaming files
if args["<scheme>"] != "None":
for filename in root.visit(fil="*.flac", rec=True):
tracknumber, title, artist, date, album, genre = metadata(filename)
scheme, formatter = new_name(permanent_scheme)
rename(root)
print "Files renamed"
else:
pass
</code></pre>
<p>After a few days trying to understand the awesome reviews I got, here is the revised code. Even though it might look a bit like <a href="https://codereview.stackexchange.com/users/11728/gareth-rees">Gareth Rees'</a> reviewed code, I rewrote everything (no cheats!).</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
rename-flac takes the information from FLAC metadata to batch rename
the files according to a filenaming scheme.
Usage:
rename-flac.py [--verbose] <scheme> <directory>
rename-flac.py (-h | --help)
rename-flac.py --version
Arguments:
<scheme> The filenaming scheme. Has to be between quotation marks
<directory> The path to the directory containing the album
Options:
-h --help Shows the help screen
--version Outputs version information
--verbose Runs the program as verbose mode
These are the options you can use to define the filenaming scheme:
%a = Artist | %b = Album | %d = Date
%g = Genre | %n = Tracknumber | %t = Title
"""
try:
from docopt import docopt # Creating command-line interface
except ImportError:
sys.stderr.write("""
%s is not installed: this program won't run correctly.
To install %s, run: aptitude install %s
""" % ("python-docopt", "python-docopt", "python-docopt"))
import sys
import subprocess
import re
import os
#TODO: write to work with Python 3
TAGS = dict(a='artist', b='album', d='date',
g='genre', n='tracknumber', t='title')
# Defining the function that fetches metadata and formats it
def metadata(filepath):
args = ["--show-tag=%s" % tag for tag in TAGS.values()]
tags = ["%s=" % tag for tag in TAGS.values()]
formatter = dict()
pipe = subprocess.Popen(["metaflac"] + args + [filepath],
stdout=subprocess.PIPE)
output, error = pipe.communicate()
if pipe.returncode:
raise IOError("metaflac failed: %s" % error)
for tag in tags:
x = re.compile(re.escape(tag), re.IGNORECASE)
output = x.sub("", output)
output = output.splitlines()
formatter["artist"] = output[0]
formatter["album"] = output[1]
formatter["date"] = output[2]
formatter["genre"] = output[3]
formatter["title"] = output[4]
formatter["tracknumber"] = output[5].zfill(2)
return formatter
# Defining function that renames the files
def rename(scheme, dirname, filename, args):
filepath = os.path.join(dirname, filename)
new_filename = scheme % metadata(filepath) + ".flac"
if new_filename == filename:
print("%s is already named correctly") % (filename)
else:
new_filepath = os.path.join(dirname, new_filename)
os.rename(filepath, new_filepath)
if args["--verbose"] == True:
print("%s >> %s") % (filename, new_filename)
# Defining main function
def main():
args = docopt(__doc__, version="rename-flac 1.0")
scheme = args["<scheme>"]
if not re.search("%[tn]", scheme): # To have a unique filename
sys.stderr.write("%t or %n has to be present in <scheme>\n")
return
scheme = re.sub('%%([%s])' % ''.join(TAGS.keys()),
lambda m: '%%(%s)s' % TAGS[m.group(1)],
scheme)
for dirname, _, filenames in os.walk(
args["<directory>"],
topdown=False):
for filename in filenames:
if os.path.splitext(filename)[1] == ".flac":
try:
rename(scheme, dirname, filename, args)
except KeyboardInterrupt:
raise
print("Files renamed")
# Calling main function
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-06-07T07:42:37.877",
"Id": "244847",
"Score": "0",
"body": "Looks like quite a lot of people are looking at this code to use it, so here's a shameless plug for the actual git repository for rename-flac: https://gitlab.com/baldurmen/rename-flac"
}
] |
[
{
"body": "<ol>\n<li><p>This does not seem really useful:</p>\n\n<pre><code>else:\n pass\n</code></pre></li>\n<li><p>On the Internet, you'll find various ways to perform the string replacement in a case-insensitive way (<a href=\"https://stackoverflow.com/questions/919056/python-case-insensitive-replace\">for example here</a>).</p></li>\n<li><p>You'll also find ways to pad numbers in order to have it on 2 digits (<a href=\"https://stackoverflow.com/questions/134934/display-number-with-leading-zeros\">for example here</a>).</p></li>\n<li><p>Instead of doing</p>\n\n<pre><code>my_variable = value\nmy_variable = my_variable.method1(parameters1)\nmy_variable = my_variable.method2(parameters2)\nmy_variable = my_variable.method3(parameters3)\nmy_variable = my_variable.method4(parameters4)\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>my_variable = value.method1(parameters1).method2(parameters2).method3(parameters3).method4(parameters4)\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T11:21:31.133",
"Id": "37733",
"ParentId": "37721",
"Score": "6"
}
},
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>I like the way you've used <a href=\"https://github.com/docopt/docopt\"><code>docopt</code></a>. But why do you require the user to run <code>rename-flac.py -o</code> in order to read the documentation for the schemes? Surely it would be clearer and simplier if the documentation for the schemes were included in the usage documentation?</p></li>\n<li><p>Your program would be easier to test if you put the top-level code into a function and then guarded the function call with <a href=\"http://docs.python.org/3/library/__main__.html\"><code>if __name__ == '__main__'</code></a>. At the moment if you try to import the script from the interactive interpreter, the script runs.</p></li>\n<li><p>Your program would be easier to test if it didn't call <code>sys.exit()</code>, but instead just finished running. At the moment, when testing it from the interactive interpreter, whenever something goes wrong then it quits the interpreter, which is annoying.</p></li>\n<li><p>You use <a href=\"http://py.readthedocs.org/en/latest/path.html\"><code>py.path</code></a> but this seems like overkill to me given that you don't use it for anything complicated. Instead you could use the built-in <a href=\"http://docs.python.org/3/library/os.html\"><code>os</code></a> module and avoid the extra dependency on <code>py.path</code>. (Use <code>os.walk</code> instead of <code>LocalPath.visit</code> and <code>os.rename</code> instead of <code>LocalPath.rename</code>.)</p></li>\n<li><p>Your function <code>rename</code> takes an argument <code>root</code> but this is not used. The function happens to work, but that's just by luck, because <code>filename</code> is a global variable: but if you move the top-level code to a function, then it will break.</p>\n\n<p>In fact, you make a lot of use of global variables. It's better to pass all the variables you need as function parameters: that way, you can be sure that you've got the right variable, and not some other variable that happens to have the same name.</p></li>\n<li><p>You write:</p>\n\n<pre><code>#TODO: write to work with Python 3\n</code></pre>\n\n<p>but it's not too hard to make your code portable between Python 2 and Python 3. You have to change your <code>print</code> statements:</p>\n\n<pre><code>print \"Files renamed\"\n</code></pre>\n\n<p>so that they have parentheses:</p>\n\n<pre><code>print(\"Files renamed\")\n</code></pre>\n\n<p>and you have to decode the output from <code>metaflac</code>.</p></li>\n<li><p>Your \"dependency check\" runs <code>dpkg</code> to see if certain packages are installed. But that's not very portable. How do you know that the user used <code>dpkg</code> to install the Python packages? Maybe they used <code>pip</code> or <code>easy-install</code> instead? How do you know that they are on an operating system that uses <code>dpkg</code> at all?</p>\n\n<p>I would avoid this dependency check altogether. For the <code>docopt</code> package it's too late to check since you've already executed <code>from docopt import ...</code> at this point. Someone who hasn't installed <code>docopt</code> will get:</p>\n\n<pre><code>ImportError: No module named 'docopt'\n</code></pre>\n\n<p>And if <code>metaflac</code> is not installed, then when you try to run it you'll get:</p>\n\n<pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'metaflac'\n</code></pre></li>\n<li><p>You write:</p>\n\n<pre><code>pipe = subprocess.Popen(\n [\"dpkg\", \"-l\", program], stdout=subprocess.PIPE)\ndependency, error = pipe.communicate()\nif pipe.returncode:\n</code></pre>\n\n<p>but you do not use <code>dependency</code> or <code>error</code>. If you just want to throw away the output, you can replace the above with:</p>\n\n<pre><code>if subprocess.call([\"dpkg\", \"-l\", program], stdout=subprocess.DEVNULL):\n</code></pre></li>\n<li><p>Your function <code>rename</code> starts by checking:</p>\n\n<pre><code>if \"t\" not in permanent_scheme: # To have different file names\n print(\" %t has to be present in <scheme>\")\n sys.exit()\n</code></pre>\n\n<p>but wouldn't it be better to do this check just once, rather than for each file? Also, shouldn't the test be <code>\"%t\" not in permanent_scheme</code>?</p></li>\n<li><p>Error messages from a command-line program ought to go to standard error, not standard output, so this:</p>\n\n<pre><code>print \"%t has to be present in <scheme>\"\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>sys.stderr.write(\"%t has to be present in <scheme>\\n\")\n</code></pre></li>\n<li><p>It's not actually clear to me why <code>%t</code> has to be present in the scheme. Obviously something has to be there to ensure that the filenames are different, but surely <code>%n</code> would do just as well?</p></li>\n<li><p>You write:</p>\n\n<pre><code>scheme = args[\"<scheme>\"]\n</code></pre>\n\n<p>but this variable never gets used: it always gets overwritten by:</p>\n\n<pre><code>scheme, formatter = new_name(permanent_scheme)\n</code></pre></li>\n<li><p>The function <code>new_name</code> does two things. First, it rewrites the <code>scheme</code> replacing <code>%t</code> with <code>%(title)s</code> and so on. This is always the same. Second, it creates a dictionary <code>formatter</code> with keys <code>title</code>, <code>artist</code> and so on. This is different for each file. It would be better if you split up these functions: have one function that rewrites the scheme (which you could call just once), and another that creates the dictionary (which you would call for each file).</p>\n\n<p>In fact, why not change the function <code>metadata</code> so that it creates and returns the dictionary?</p></li>\n<li><p>The output on success is just:</p>\n\n<pre><code>Files renamed\n</code></pre>\n\n<p>but I think it would be more useful to output a description of the renames that took place.</p></li>\n<li><p>In <code>metadata</code> it would be better to write a loop than to copy out the code for running <code>metaflac</code> six times. This loop should be driven by a data structure that lists the tags you are going to look up.</p></li>\n<li><p>Similarly, in <code>new_name</code> it would be better to write a loop than to copy out the code for replacing a string six times. Or, by using <a href=\"http://docs.python.org/3/library/re.html#re.sub\"><code>re.sub</code></a>, you could do in one function call. Again, this operation should be driven by a data structure that lists the tags and their abbreviations. (This could be the same data structure as in the point above.)</p></li>\n<li><p>You run <code>metaflac</code> six times, once for each tag. But I believe that you can actually just run it once, passing multiple <code>--show-tag</code> options, one for each tag you want to look up.</p></li>\n<li><p>Typos: \"Theses\", \"instal\".</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>This is totally untested (I'm not running on Linux and so it's inconvenient for me to install <code>metaflac</code>), but it should give you some ideas.</p>\n\n<pre><code>#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nrename-flac takes the information from FLAC metadata to batch rename\nthe files according to a filenaming scheme.\n\nUsage:\n rename-flac.py <scheme> <directory>\n rename-flac.py (-h | --help)\n rename-flac.py --version\n\nArguments:\n <scheme> The filenaming scheme (see below)\n <directory> The path to the directory containing the album\n\nOptions:\n -h --help Shows the help screen\n --version Outputs version information\n\nThese are the options you can use to define the filenaming scheme:\n %a = Artist | %b = Album | %d = Date\n %g = Genre | %n = Tracknumber | %t = Title\n\n\"\"\"\nfrom docopt import docopt\nimport os\nimport re\nimport subprocess\nimport sys\n\nTAGS = dict(a='artist', b='album', d='date',\n g='genre', n='tracknumber', t='title')\n\ndef metadata(filename):\n \"\"\"Return the metadata associated with FLAC file filename.\"\"\"\n result = dict()\n args = [\"--show-tag=%s\" % tag for tag in TAGS.values()]\n pipe = subprocess.Popen([\"metaflac\"] + args + [filename],\n stdout=subprocess.PIPE)\n output, error = pipe.communicate()\n if pipe.returncode:\n raise IOError(\"metaflac failed: %s\" % error)\n for line in output.decode().splitlines():\n m = re.match('(\\w+)=(.*)', line)\n if m:\n result[m.group(0).lower()] = m.group(1)\n result['tracknumber'] = '%02d' % int(result['tracknumber'])\n return result\n\ndef rename(dirname, filename, scheme):\n \"\"\"Rename dirname/filename according to scheme.\"\"\"\n filepath = os.path.join(dirname, filename)\n new_filename = scheme % metadata(filepath) + '.flac'\n if new_filename == filename:\n print(\"%s unchanged\" % filename)\n else:\n new_filepath = os.path.join(dirname, new_filename)\n os.rename(filepath, new_filepath)\n print(\"%s renamed %s\" % (filename, new_filename))\n\ndef main(argv):\n args = docopt(__doc__, argv=argv, version=\"rename-flac 1.0\")\n scheme = args[\"<scheme>\"]\n if not re.search('%[tn]', scheme):\n sys.stderr.write(\"%t or %n has to be present in <scheme>\\n\")\n return\n scheme = re.sub('%%([%s])' % ''.join(TAGS.keys()),\n lambda m: '%%(%s)s' % TAGS[m.group(1)],\n scheme)\n for dirname, _, filenames in os.walk(args[\"<directory>\"]):\n for filename in filenames:\n if os.path.splitext(filename)[1] == '.flac':\n rename(dirname, filename, scheme)\n\nif __name__ == '__main__':\n main(sys.argv)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T20:58:34.183",
"Id": "62965",
"Score": "0",
"body": "Wow, that's a comprehensive review, very interesting for readers, thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T05:19:29.637",
"Id": "63606",
"Score": "0",
"body": "Thanks! I just wanted to point out how nice is the use of `re.sub` and `lambda` to build `scheme`. Still looks a bit lit magic to me!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:52:48.377",
"Id": "37748",
"ParentId": "37721",
"Score": "12"
}
}
] |
{
"AcceptedAnswerId": "37748",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T04:14:57.423",
"Id": "37721",
"Score": "6",
"Tags": [
"python",
"beginner",
"linux",
"file-system"
],
"Title": "Batch rename flac files"
}
|
37721
|
<p>This week's <a href="https://codereview.meta.stackexchange.com/q/1245/9357">weekend challenge #3</a> seemed like a great opportunity to learn Ruby! Unfortunately, my workload and looming vacation did not cooperate. :( The puzzle will make forced moves automatically, but I was hoping to implement rules such as Naked Pairs before resorting to brute force.</p>
<p>But there's plenty of code to make a review worthwhile, and I'm hoping some experienced Ruby coders will give it a shot. I have included a few test puzzles (easy and medium solve to completion), and it's easy to add more. See the bottom for a sample test run.</p>
<p>The real meat of the algorithm is the interaction between the <code>Cell</code> and <code>Group</code> instances. <code>Board</code> merely instantiates everything and applies the initial puzzle state.</p>
<p>I'm looking for feedback on Ruby style (e.g. "avoid <code>and</code> and <code>or</code> as they are confusing"), correct use of idioms and the standard library, code organization, etc. This is a Ruby learning exercise, so I want to avoid picking up bad habits early. Since I haven't implemented any brute-force or complex solving yet, performance isn't an issue.</p>
<p><strong>Board.rb</strong></p>
<pre><code>require 'Cell'
require 'Group'
require 'Inspector'
module Sudoku
# Builds the cells and groups and provides an API for setting up and interacting with the puzzle.
#
# Several debugging methods are provided that are being extracted to the inspector.
class Board
# Builds the board structure and initializes an empty puzzle.
#
# @param start [String] optional initial values passed to #setup
def initialize(start = nil)
@cells = Array.new(9) { |r| Array.new(9) { |c| Cell.new r, c } }
@rows = Array.new(9) { |i| Group.new :row, i }
@cols = Array.new(9) { |i| Group.new :col, i }
@boxes = Array.new(9) { |i| Group.new :box, i }
(0..8).each do |i|
connect @rows[i], row_cells(i)
connect @cols[i], col_cells(i)
connect @boxes[i], box_cells(i)
end
setup start if start
end
# Sets the initial values of the puzzle.
#
# Place each row on a separate line and nine cell values on each row.
# Whitespace is ignored around the row on each line. Each cell value
# may be a digit [1-9] or a period (.) if empty.
#
# @param start [String] optional initial values passed to #setup
#
# @example Nine queens
# .....9...
# ...9.....
# ......9..
# 9........
# .......9.
# .9.......
# ....9....
# ..9......
# ........9
def setup(puzzle)
r = 1
puzzle.split.each do |line|
c = 1
line.each_char do |n|
set(r, c, n.to_i, :start) if n =~ /[1-9]/
c += 1
end
r += 1
end
end
# Returns true if the cell can be set to the value.
#
# @param r [Fixnum] one-based row
# @param c [Fixnum] one-based column
# @param n [Fixnum] one-based cell value
# @return [Boolean]
def possible?(r, c, n)
cell(r, c).possible? n
end
# Returns true if the cell has been set to a value.
#
# @param r [Fixnum] one-based row
# @param c [Fixnum] one-based column
# @return [Boolean]
def known?(r, c)
cell(r, c).known?
end
# Sets the cell to the value for the given reason (omit when playing).
#
# @param r [Fixnum] one-based row
# @param c [Fixnum] one-based column
# @param n [Fixnum] one-based cell value
# @param reason [Symbol] one of :start, :choose, or :force
# @return [void]
#
# @raise [RuntimeError] if the cell is already set
# @raise [RuntimeError] if the value is not possible for the cell
def set(r, c, n, reason = :choose)
cell(r, c).set(n, reason)
end
# Iterates over each cell on the board from left-to-right and top-to-bottom.
#
# Used by the inspector.
#
# @yieldparam cell [Cell]
# @return [void]
def each_cell
@cells.each { |row| row.each { |cell| yield cell } }
end
def to_s
@cells.map { |row| row * "" } * "\n"
end
# Creates an inspector for this board.
#
# @return [Inspector] doesn't yet fully implement the output available in this class
def inspector
Inspector.new self
end
private
def cell(r, c)
@cells[r - 1][c - 1]
end
def row_cells(r)
Array.new(9) { |c| @cells[r][c] }
end
def col_cells(c)
Array.new(9) { |r| @cells[r][c] }
end
def box_cells(b)
box_r = b % 3 * 3
box_c = b / 3 * 3
Array.new(9) { |i| @cells[box_r + i % 3][box_c + i / 3] }
end
def connect(group, cells)
cells.each { |cell| cell.join group }
end
### Debugging
public
def inspect
"Board State\n#{to_s}"
end
def debug
debug_cells
debug_rows
debug_cols
debug_boxes
end
def debug_cells
puts "Cell Possibilities"
puts @cells.map { |row| row.map { |cell| cell.debug } * " " } * "\n"
end
def debug_rows
puts "Row Possibilities"
debug_group(@rows)
end
def debug_cols
puts "Column Possibilities"
debug_group(@cols)
end
def debug_boxes
puts "Box Possibilities"
debug_group(@boxes)
end
private
def debug_group(groups)
puts groups.map { |group| group.debug } * "\n"
end
end
end
</code></pre>
<p><strong>Group.rb</strong></p>
<pre><code>require 'set'
module Sudoku
# Tracks the cells that make up a single row, column, or 3x3 box, which are still available
# to be set to which values, and the values still left to be set somewhere in the group.
class Group
# Creates an empty group of the given type.
#
# @param type [Symbol] either :row, :col, or :box
# @param index [Fixnum] zero-based index
def initialize(type, index)
@type, @index = type, index
@id = "#{type}-#{index + 1}"
@knowns = {}
@possibles = Hash[(1..9).map { |n| [n, Set.new] }]
end
attr_reader :id, :type, :index
# Makes the cell available for the given value or all values.
#
# @param cell [Cell] the cell that can be set to the value
# @param n [Fixnum or nil] omit to make the cell available for every value
# @return [void]
def available(cell, n = nil)
if n
@possibles[n] << cell
else
@possibles.each_value { |cells| cells << cell }
end
end
# Makes the cell unavailable to receive the value.
#
# If the value has only one cell possibility left, it is set to the value.
#
# @param cell [Cell] the cell that can no longer be set to the value
# @param n [Fixnum] one-based cell value
# @return [void]
def unavailable(cell, n)
# puts "%s - unavail: %s -> %d: %s" % [id, cell.id, n, debug]
cells = @possibles[n]
cells.delete cell
if cells.size == 1 and !known? n
cells.take(1).first.set n, :force
end
end
# Returns true if a cell in this group has been set to the value.
#
# @param n [Fixnum] one-based cell value
# @return [Boolean] true if set; false if still available for this group
def known?(n)
!!@knowns[n]
end
# Returns true if no cell in this group has been set to the value.
#
# @param n [Fixnum] one-based cell value
# @return [Boolean] false if none set; true if still available for this group
def possible?(n)
!@knowns[n]
end
# Returns the number of cells that can still be set to the value.
#
# @param n [Fixnum] one-based cell value
# @return [Fixnum]
def num_possible(n)
@possibles[n].size
end
# Stores that the cell has been set to the value and removes the value as a possible from other cells.
#
# @param cell [Cell] the cell that was just set
# @param n [Fixnum] one-based cell value
# @return [void]
def known(cell, n)
# puts "%s - known : %s -> %d: %s" % [id, cell.id, n, debug]
raise "#{@knowns[n]} in #{@id} already known for #{n}" if known? n
raise "#{cell} in #{@id} not possible for #{n}" unless @possibles[n].delete? cell
@knowns[n] = cell
@possibles[n].each { |possible| possible.unavailable self, n }
end
# Returns a string denoting which values are still possible and in how many cells.
#
# @return [String] first group: possible values are as-is; not possible values are dots;
# second group: number of available cells per cell value
def debug
((1..9).map { |n| possible?(n) ? n : "." } * "") + " " + ((1..9).map { |n| num_possible n } * "")
end
end
end
</code></pre>
<p><strong>Cell.rb</strong></p>
<pre><code>require 'set'
module Sudoku
# Models a single cell that tracks the possible values to which it may be set
# and the current value if already set.
class Cell
# Creates an empty cell at the given row and column.
#
# @param r [Fixnum] zero-based row number
# @param c [Fixnum] zero-based column number
def initialize(r, c)
@r, @c = r, c
@id = "(#{r + 1},#{c + 1})"
@initial = @current = nil
@possibles = (1..9).to_set
@groups = []
end
# Joins the given group and makes this cell available for all numbers.
#
# @param group [Group] contains this cell
# @return [void]
def join(group)
@groups << group
group.available self
end
attr_reader :id, :r, :c, :initial, :current
# Returns true if this cell can be set to the value.
#
# @param n [Fixnum] one-based cell value
# @return [Boolean]
def possible?(n)
!known? and @possibles.include? n
end
# Iterates over each value this cell can be set to.
#
# @yieldparam n [Fixnum] one-based cell value
# @return [void]
def each_possible
@possibles.each { |n| yield n } if !known?
end
# Returns true if this cell has been set to a value.
#
# @return [Boolean]
def known?
!!@current
end
# Removes a value from this cell's set of possibilities.
#
# If this leaves the cell with but one possibility, the cell is set to it.
#
# @param n [Fixnum] one-based cell value
# @return [void]
#
# @raise [RuntimeError] if n is the only possibility left
def known(n)
if possible? n
raise "No possibilities left for cell #{@id}" if @possibles.size == 1
@possibles.delete n
set(@possibles.take(1).first, :force) if @possibles.size == 1
end
end
# Notifies this cell's groups that the value is no longer possible for this cell.
#
# @param n [Fixnum] one-based cell value
# @return [void]
#
# @todo Merge with #known.
def unavailable(group, n)
# puts " - unavail: %s -> %d: %s from %s" % [id, n, debug, group.id]
@groups.each { |possible| possible.unavailable self, n }
known n
end
# Sets this cell to the value and notifies each group.
#
# @param n [Fixnum] one-based cell value
# @param reason [Symbol] either :setup, :choose, or :force
# @return [void]
#
# @raise [RuntimeError] if this cell is already set
# @raise [RuntimeError] if the value is not possible for this cell
def set(n, reason)
puts " - %-7s: %s -> %d: %s" % [reason, id, n, debug]
@initial = n if reason == :initial
return if @current == n
raise "cannot change #{@id} from #{@current} to #{n}" if @current
raise "Cannot set #{@id} to #{n}" if !possible? n
@possibles.delete n
@current = n
@groups.each do |group|
group.known self, n
@possibles.each { |n| group.unavailable self, n }
end
@possibles.clear
end
# Returns the current value of this cell if set or a dot if not.
#
# @return [String] single digit or a dot
def to_s
(@current || ".").to_s
end
# Returns a string denoting which values are still possible.
#
# @return [String] possible values are as-is; not possible values are dots
def debug
(1..9).map { |n| possible?(n) ? n : "." } * ""
end
end
end
</code></pre>
<p><strong>Test.rb</strong></p>
<pre><code>require 'Board'
module Sudoku
# Creates several test puzzles from easy to evil.
#
# @see http://www.websudoku.com/
module Test
def self.easy
self.test <<-PUZZLE
..38.4.5.
84......7
6....29..
.18.5..9.
2.6.7.4.5
.3..4.86.
..51....8
1......79
.6.5.7.2.
PUZZLE
end
def self.medium
self.test <<-PUZZLE
.5.....7.
9428.....
....6...5
48..765..
.93...78.
..598..14
7...4....
.....8193
.1.....4.
PUZZLE
end
def self.hard
self.test <<-PUZZLE
.....5.8.
.8....5.1
..5.12.69
......17.
.2.....3.
.19......
15.34.7..
8.7....1.
.6.9.....
PUZZLE
end
def self.evil # http://www.websudoku.com/?level=4&set_id=6247568390
self.test <<-PUZZLE
.4.2.....
.....13.7
..5...91.
.8..13...
..3.6.5..
...72..4.
.12...4..
8.69.....
.....2.3.
PUZZLE
end
def self.test(puzzle)
puts "Initial Puzzle"
puts puzzle
b = Board.new puzzle
b.debug
b.inspector.cells
b
end
end
end
</code></pre>
<p><strong>Inspector.rb</strong></p>
<pre><code>module Sudoku
# Assists debugging the internal state of the board.
class Inspector
# Stores the board for inspection
#
# @param board [Board]
def initialize(board)
@board = board
end
# Displays the current cell values.
def current
rows = []
row = nil
@board.each_cell do |cell|
if cell.c == 0
row = ""
rows << "" if cell.r != 0 && cell.r % 3 == 0
end
row += " " if cell.c != 0 && cell.c % 3 == 0
row += cell.to_s
rows << row if cell.c == 8
end
puts "Current Puzzle"
puts
puts rows * "\n"
end
# Displays the available values for each cell.
def cells
grid = ([["... " * 9] * 3, ""].flatten * 9).map(&:clone)
@board.each_cell do |cell|
r, c = 4 * cell.r, 4 * cell.c
cell.each_possible do |n|
grid[r + (n - 1) / 3][c + (n - 1) % 3] = n.to_s
end
end
puts "Cell Possibilities"
puts
puts grid * "\n"
end
def inspect
"Inspector"
end
end
end
</code></pre>
<p><strong>Sample Test Run</strong></p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>-> require 'Test'
-> Sudoku::Test::easy
Initial Puzzle
..38.4.5.
84......7
6....29..
.18.5..9.
2.6.7.4.5
.3..4.86.
..51....8
1......79
.6.5.7.2.
start : (1,3) -> 3: 123456789
start : (1,4) -> 8: 12.456789
start : (1,6) -> 4: 12.4567.9
start : (1,8) -> 5: 12..567.9
start : (2,1) -> 8: 12.456789
start : (2,2) -> 4: 12.4567.9
start : (2,9) -> 7: 123..67.9
start : (3,1) -> 6: 12..567.9
start : (3,6) -> 2: 123.5.7.9
start : (3,7) -> 9: 1.34...89
start : (4,2) -> 1: 123.56789
start : (4,3) -> 8: .2.456789
start : (4,5) -> 5: .234567.9
start : (4,8) -> 9: .234.67.9
start : (5,1) -> 2: .2345.7.9
start : (5,3) -> 6: ...4567.9
start : (5,5) -> 7: 1.34..789
force : (3,4) -> 7: 1.3.5.7..
force : (3,2) -> 5: ....5....
force : (3,3) -> 1: 1........
force : (3,5) -> 3: ..3......
start : (5,7) -> 4: 1.345..8.
force : (5,9) -> 5: 1.3.5..8.
start : (5,9) -> 5: .........
start : (6,2) -> 3: ..3...7.9
force : (5,2) -> 9: ........9
start : (6,5) -> 4: 12.4.6.89
force : (4,1) -> 4: ...4..7..
force : (4,7) -> 7: .23..67..
force : (6,5) -> 4: .........
start : (6,7) -> 8: 12...6.8.
force : (5,6) -> 8: 1.3....8.
force : (6,7) -> 8: .........
start : (6,8) -> 6: 12...6...
start : (7,3) -> 5: .2.45.7.9
force : (6,1) -> 5: ....5.7..
force : (6,3) -> 7: ....5.7..
force : (6,1) -> 5: .........
force : (7,3) -> 5: .........
start : (7,4) -> 1: 1234.6..9
force : (5,8) -> 1: 1.3......
force : (5,4) -> 3: 1.3......
force : (4,9) -> 3: .23......
force : (4,4) -> 2: .2...6...
force : (4,6) -> 6: ..3..6...
force : (4,4) -> 2: .........
force : (6,9) -> 2: 12.......
force : (5,8) -> 1: .........
force : (6,6) -> 1: 1.......9
force : (6,4) -> 9: 1.......9
force : (6,6) -> 1: .........
start : (7,9) -> 8: ...4.6.89
force : (7,8) -> 4: .234..7..
force : (3,9) -> 4: ...4...8.
force : (3,8) -> 8: ...4...8.
force : (3,9) -> 4: .........
force : (7,8) -> 4: .........
force : (7,9) -> 8: .........
start : (8,1) -> 1: 1.3...7.9
force : (8,1) -> 1: .........
start : (8,8) -> 7: .23...7..
force : (8,8) -> 7: .........
start : (8,9) -> 9: .....6..9
force : (8,9) -> 9: .........
start : (9,2) -> 6: .2...678.
force : (9,2) -> 6: .........
force : (8,2) -> 8: .2.....8.
force : (9,5) -> 8: .2...6.89
force : (9,5) -> 8: .........
force : (8,2) -> 8: .........
force : (1,9) -> 6: 1....6...
force : (9,9) -> 1: 1....6...
force : (9,9) -> 1: .........
start : (9,4) -> 5: ...45....
force : (2,6) -> 5: ....5...9
force : (2,4) -> 6: .....6...
force : (2,4) -> 6: .........
force : (8,6) -> 3: ..3......
force : (8,6) -> 3: .........
force : (9,4) -> 5: .........
force : (8,7) -> 5: .2..56...
force : (9,4) -> 5: .........
force : (8,7) -> 5: .........
force : (7,7) -> 6: .23..6...
force : (8,5) -> 6: .2...6...
force : (7,5) -> 2: .2...6..9
force : (8,5) -> 6: .........
force : (1,2) -> 2: .2....7..
force : (1,7) -> 1: 1........
force : (2,5) -> 1: 1.......9
force : (1,7) -> 1: .........
force : (1,7) -> 1: .........
force : (2,3) -> 9: .2......9
force : (1,5) -> 9: 1.......9
force : (2,3) -> 9: .........
force : (1,5) -> 9: .........
force : (2,5) -> 1: .........
force : (2,5) -> 1: .........
force : (1,1) -> 7: ......7..
force : (1,1) -> 7: .........
force : (7,2) -> 7: .2....7..
force : (1,2) -> 2: .........
force : (1,1) -> 7: .........
force : (9,6) -> 7: ......7.9
force : (9,6) -> 7: .........
force : (7,2) -> 7: .........
force : (7,6) -> 9: ........9
force : (7,6) -> 9: .........
force : (9,1) -> 9: ..3...7.9
force : (7,1) -> 3: ..3.....9
force : (1,1) -> 7: .........
force : (2,3) -> 9: .........
force : (9,1) -> 9: .........
force : (9,6) -> 7: .........
force : (1,2) -> 2: .........
force : (7,7) -> 6: .........
force : (7,7) -> 6: .........
force : (8,3) -> 2: .2.4.....
force : (8,3) -> 2: .........
force : (9,3) -> 4: ...4.....
force : (9,3) -> 4: .........
force : (8,4) -> 4: ...45....
force : (8,4) -> 4: .........
force : (9,3) -> 4: .........
force : (9,4) -> 5: .........
start : (9,6) -> 7: .........
start : (9,8) -> 2: .23......
force : (2,7) -> 2: .23......
force : (2,8) -> 3: .23......
force : (9,7) -> 3: .23......
force : (2,7) -> 2: .........
force : (2,8) -> 3: .........
force : (9,7) -> 3: .........
force : (9,8) -> 2: .........
force : (9,8) -> 2: .........
force : (2,7) -> 2: .........
Board State
723894156
849615237
651732984
418256793
296378415
537941862
375129648
182463579
964587321
</code></pre>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T16:17:24.297",
"Id": "62685",
"Score": "0",
"body": "What kind of feedback are you looking for? For example, are you looking for feedback on readability, performance, etc.?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:16:29.353",
"Id": "62710",
"Score": "0",
"body": "@KenrickChien - Please see the update near the top of my question."
}
] |
[
{
"body": "<p>It's definitely a nice start. But it's funny; I can tell you're coming to Ruby from Java :)<br>\nI don't mean anything negative by that, by the way. It's just interesting how some subtle clues here and there give it away.</p>\n\n<p>Anyway, if you want to develop good habits early, unit testing and TDD/BDD would be my first recommendations. Personally, I neglected it for too long, and it's hard to make a habit of it later.</p>\n\n<p>I'm sure you know all the reasons to test, but it's doubly great if you're still learning and want to try different solutions out. It's also just nice to learn it in a situation where you already have a spec (as opposed to developing something brand new where you're figuring it out feature spec by feature spec, then figuring out what tests to apply, then the code, etc.).</p>\n\n<p>I'm a fan of <a href=\"http://rspec.info/\">rspec</a> myself, but there are plenty of testing solutions out there, like <a href=\"http://ruby-doc.org/stdlib-2.0.0/libdoc/test/unit/rdoc/index.html\">test/unit</a> which is included in Ruby's standard library.</p>\n\n<p>But let's move on to the code itself, starting with the <code>Board</code> class:</p>\n\n<p>I'd suggest more (private or otherwise) accessor methods rather than accessing instance variables directly. To begin with, you can just do <code>attr_reader :cells</code> (for instance), and leave it at that. But accessor methods make everything easier later on. This is probably not something you'll have to maintain over a long time, but you asked for good habits, and the idea is that you couple your code to a method, which is more flexible than coupling it directly to a variable.</p>\n\n<p>Speaking of, I might move the cells/rows/cols/boxes initialization out of the <code>initialize</code> method, favoring reader methods (getters) that use to the <code>||=</code> operator to initialize them, if they haven't been defined. E.g.</p>\n\n<pre><code> def rows\n @rows ||= Array.new(9) { |i| Group.new :row, i }\n end\n</code></pre>\n\n<p>That way, you're guaranteed to always have <code>rows</code> available, and the code to create them has been moved, slimming down the initializer method (try to be zealous about keeping method line counts low; like aim for, like, 5 lines max. Won't always work, but try it as an exercise).</p>\n\n<p>I might actually go further to DRY (Don't Repeat Yourself) the code, by making a helper method just to return a new array of groups</p>\n\n<pre><code> def rows\n @rows ||= create_groups(:row)\n end\n\n # ...\n\n def create_groups(type)\n Array.new(9) { |i| Group.new type, i }\n end\n</code></pre>\n\n<p>I know, it seems sort of pointless, but what if, for instance, you want different board sizes later? You could add a size argument to <code>create_types</code>, or (better) have it access an instance variable (again, directly or through a reader method) to get the size. Of course the actual solving would need to take the different size into account, but the basics of building the board would \"just work\".</p>\n\n<p>Another general note would be to use longer variable names. It doesn't cost you anything to replace <code>r</code>, <code>c</code> and <code>n</code> with <code>row</code>, <code>column</code> and <code>number</code> (or better yet <code>value</code> for the last one, as you can conceivably use any symbol set for a sudoku puzzle). It just makes everything way more explicit.</p>\n\n<p>Basically, in most Ruby code, you'll typically only see a few <code>@</code>s (confined to accessor methods) and virtually no single-letter variables.</p>\n\n<p>Which leads me to <code>Board#setup</code>. Again there are some one-letter variables going on here, but moreover you're doing some un-Rubyesque looping. You should go read though the docs for <a href=\"http://ruby-doc.org/core-2.0.0/Array.html\"><code>Array</code></a> and the <a href=\"http://ruby-doc.org/core-2.0.0/Enumerable.html\"><code>Enumerable</code></a> module, as that's one of the most handy parts of Ruby, in my opinion. I know a lot of my own early Ruby code could have benefitted a lot if I'd had the patience to just go through those APIs.</p>\n\n<p>Here's one, more Ruby-like, way to achieve the same thing:</p>\n\n<pre><code>def setup(puzzle)\n puzzle.split.each_with_index do |line, row|\n line.scan(/./).each_with_index do |char, column|\n set(row, column, char.to_i, :start) if char =~ /\\d/\n end\n end\nend\n</code></pre>\n\n<p>Basically, you practically never need to track and manually increment indices when looping, and only very rarely does a block need to have side-effects (like pushing items into an array); Ruby can get very functional.<br>\nFor instance, you could consider <code>map</code>'ing the lines and chars directly to the <code>@cells</code>, as it follows the same 2D-structure as the puzzle text.</p>\n\n<p>Your <code>Board#set</code> method is also a bit un-Rubyesque. For one, it's got a lot of arguments, which couples it rather tightly to the rest of the code. There's also the symbol you pass according to the state of the puzzle (a state you must explicitly supply). I'd recommend separate methods for setting/force setting the cells. That's a plain refactoring concern, and as I said I won't delve too deep into that, but here are some ideas:</p>\n\n<ul>\n<li>changing the order of things to a cell isn't initialized until you've got a value to feed its constructor</li>\n<li><code>set</code> and <code>set!</code> and <code>choose</code> methods for the various ways of setting the value; more explicit and expressive that way.</li>\n</ul>\n\n<p>Speaking of method names, you could consider using <code>[]</code> in your cell-specific methods, to make <code>Board</code> appear more like a 2D array. E.g.</p>\n\n<pre><code>def cell[](row, column)\n cells[row - 1][column - 1]\nend\n</code></pre>\n\n<p>which'll let you call, say, <code>board.cell[row, column].known?</code>.</p>\n\n<p>Accessing a cell directly like that is of course a departure from your current practice of proxying a lot of the <code>Cell</code> class's methods directly in <code>Board</code> (e.g. <code>Board#known?(r, c)</code>).<br>\nThe reasons for proxying are much the same as for accessors: Add some implementation flexibility and provide a flat API. However, here it smells like repetition to me. So I'd probably prefer just getting a cell, and chaining off of that like in the example above. It just seems cleaner and more expressive to me, than replicating all its methods on <code>Board</code>. But arguments can be made either way.</p>\n\n<p>(More worrisome are perhaps the circular references and side-effects you create between a cell and the groups it belongs to, but again, I'll leave the specifics of the solver's structure alone)</p>\n\n<p>Oh, man. I've only been looking at <code>Board</code> but you've got lots of other classes :)<br>\nI'm out of time, though, so here are what I found while skimming through stuff:</p>\n\n<ul>\n<li>More methods, just in general, to break up the long'ish ones you have here and there.</li>\n<li>I'd remove references to the <code>Inspector</code> class from <code>Board</code>; the board doesn't need to know how it's being presented.</li>\n<li><p>Or, I'd roll the functionality into board itself; it can be shortened considerably, so it won't seem like a burden. For instance, the <code>Inspector#current</code> method could be:</p>\n\n<pre><code>def current\n puts \"Current Puzzle\"\n puts cells.map { |row|\n row.map(&:to_s).each_slice(3).to_a.map(&:join).join(\" \")\n }.each_slice(3).map { |slice| slice.join(\"\\n\") }.join(\"\\n\\n\")\nend\n</code></pre>\n\n<p>Ok, that's maybe a bit crazy, but still: gotta love Array/Enumerable stuff :)</p></li>\n<li><p>Lastly: Ruby files are always named in lowercase. Completely irrelevant to the code of course (apart from the <code>require</code> statements), but you don't want to stand out as the \"Java guy\", right? :)</p></li>\n</ul>\n\n<p>Hope I gave you some worthwhile ideas.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T16:48:59.953",
"Id": "63086",
"Score": "0",
"body": "Lots of excellent advice here. Every language I learn leaves a trace in how I code elsewhere; I take no offense. I avoid using other libraries like testing frameworks while starting so I'm forced to use I/O for debugging and other low-evel techniques. Many of your refactoring suggestions are spot on and would apply in other languages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T16:56:53.320",
"Id": "63087",
"Score": "0",
"body": "The facade methods in `Board` are there to hide the internal structure. However, if I expose `Cell` directly, without package-private methods, how can I hide its \"internal\" methods that `Group` needs to call?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T16:59:57.897",
"Id": "63088",
"Score": "0",
"body": "BTW, very nice use of `scan` there. I gave up looking for a way to get automatic loop counters when there was no `each_char_with_index`. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:05:41.140",
"Id": "63089",
"Score": "0",
"body": "@DavidHarkness I'm glad you found it helpful! And please don't think I took any offense! :) Good point about basic I/O vs. tests. There's a lot of tooling for Ruby, so it's kinda daunting at first, and probably not where you should jump in. But do jump in at some point :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:15:19.480",
"Id": "63090",
"Score": "0",
"body": "@DavidHarkness re your 2nd comment: Ruby's a lot more relaxed regarding access to stuff. For instance, you can call private methods from anywhere if you want, and you can monkeypatch anything, redeclare classes, whatever. It's very flexible and powerful, but also totally different from other languages. Here, there's also a design choice: Do you want `Board` to be the only API, or do you want to expose the building blocks (`Cell`, `Group`) too? Ruby leans toward the latter, since you can always get at the internals anyway, so there's little point in worrying too much"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:21:07.727",
"Id": "63091",
"Score": "0",
"body": "@DavidHarkness Of course, you should still provide a nice and clean API, but you can't really properly \"hide\" the internals, merely obfuscate them a bit. As for the loop you mention, you can chain enumerators, so you could to `string.each_char.each_with_index { |char, i| ... }` (but it's kinda clunky-looking compared to `scan`) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T17:33:04.260",
"Id": "63094",
"Score": "0",
"body": "I'll start with rspec since I've used plenty of xUnit frameworks already. Interesting take on the visibility modifiers. I'll have to play around with those. I intended `Board` as the sole API to simulate working with the puzzle as a whole, but that's arbitrary and not really enforceable as you say. Relaxing that and exposing `Cell` would certainly shrink the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T18:52:36.160",
"Id": "63099",
"Score": "0",
"body": "@DavidHarkness Well, setting visibility to, say, `private` does require outside code to jump through some hoops (like [`Object#send`](http://ruby-doc.org/core-2.0.0/Object.html#method-i-send)) so it's not ignored; it's just not strict either. \"There's always a way\" could be a motto (which is why Ruby people are so big on convention and idioms). As for API design, you can keep `Board` as the _primary_ API for the reasons you mention, but it doesn't have to be the _sole_ API. Best of both worlds, I think: Easy to use, easy to tinker with"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-21T00:31:10.483",
"Id": "37856",
"ParentId": "37723",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "37856",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T06:41:47.017",
"Id": "37723",
"Score": "13",
"Tags": [
"ruby",
"community-challenge",
"sudoku"
],
"Title": "Ruby Sudoku solver"
}
|
37723
|
<p>I've inherited a class in a project which is purposed to execute a function that exists in POST data from a specified class. I've tried to clean this up as much as possible as well as secure it against SQL injection but I'm wondering if I could have done a better job or written this better. Any assistance would be much appreciated!</p>
<pre><code>class RegistrationProceduresController
{
public function __construct($username, $password, $host, $port, $dbname)
{
$SP = new RegistrationProceduresModel($username, $password, $host, $port, $dbname);
// Sanitize all the incoming POST data and move into an array of its own
$sanitized = array_map(array($this, 'sanitize'), $_POST);
// Check whether the method passed via our POST data is a public function within the model, or even exists
// at all. If not then skip to logging.
if(method_exists($SP, $sanitized['function']))
{
try
{
// Execute the function we passed via our post data against the model class post-sanitization.
$SP->$sanitized['function']();
}
catch(exception $ex)
{
json_encode("Exception when trying to execute a sanitized function in registration controller: " . $ex->getMessage());
}
}
else
{
try
{
$val = isset($sanitized['function']) ? $sanitized['function'] . " does not exist in model." : "was not specified";
json_encode("Function " . $val);
}
catch(exception $ex)
{
json_encode("Threw an error after failing to evaluate whether a $_POST method exists. Review registration controller. " . $ex->getMessage());
}
}
}
/// <summary>
/// Takes an input and returns it with all HTML characters stripped.
/// Protects against SQL injection.
/// </summary>
/// <param name="$input">Any string based input</param>
public function sanitize($input)
{
try
{
return htmlspecialchars(trim($input));
}
catch(exception $ex)
{
json_encode("Failed to sanitize POST data array in registration controller: " . $ex->getMessage());
}
return null;
}
}
</code></pre>
<p>This project is using POST data to call a function since it's being initialized by JavaScript. If there's a better way to call a PHP function from within JavaScript I would definitely, definitely value feedback on it!</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:03:47.977",
"Id": "62610",
"Score": "0",
"body": "Whatever you are trying to do, there _has_ to be a better way than to use `$_POST` data to call a function! besides, your syntax is ambiguous: should PHP evaluate `$SP->$sanitized['function']();` as `$SP->{$sanitized}['function']();` where `$sanitized` is a string, containing the name of a property, that has been assigned an array with a `function` key that has been assigned a lambda, or is it `$SP->{$sanitized['function']()};`: a lambda returning a string, that is a property of `$SP` _or_ is it `$SP->{$sanitized['function']}();`? use the latter to disambiguate"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:05:07.063",
"Id": "62611",
"Score": "0",
"body": "Also `json_encode` a string: not a good idea. `json_encode(array('error' => 'your custom string', 'msg' => $ex->getMessage(), 'code' => $ex->getCode()));` is what you want"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:29:24.653",
"Id": "62614",
"Score": "0",
"body": "@EliasVanOotegem See edit for justification - I'd love to know a better way!"
}
] |
[
{
"body": "<p>Well, I'm going to post it as an answer, simply because comments aren't the right place for this:</p>\n\n<blockquote>\n <p>See edit for justification</p>\n</blockquote>\n\n<p>You <em>can't</em> justify using <code>$_POST</code> data to call functions or methods in a script. <strong><em>never trust the network</em></strong>, POST data is coming from the network, never trust it. Full stop.<br/>\nIt's a piece of cake to send something like <code>__toString</code>, <code>__invoke</code>, <code>__sleep</code> and other magic-methods. They might exist, so they might pass the <code>method_exist</code> check you do. However, <em>what</em> they do is something different entirely.</p>\n\n<p>You're basically calling a method on an object. That implies <em>a finite list</em> of methods that exist <em>and are callable</em> (there's <a href=\"http://php.net/is_callable\" rel=\"nofollow\">a function called <code>is_callable</code></a> to chekc just that, BTW).<br/>\nA safer way might be to have a property (array) containing a white-list of methods that can be invoked through JS requests:</p>\n\n<pre><code>$psMethods = array(\n 'ajaxMethod1',\n 'ajaxMethod2'\n);\n</code></pre>\n\n<p>As an added bonus, you could use the method names as keys, and assign those keys a couple of arguments that the method might require.<br/>\nThe downside of this (a static array) is that you'll have to add and remove items from this array as you write your code. Don't worry however, help is at hand thanks to <code>get_class_methods</code>:</p>\n\n<pre><code>private $SP = null;\nprivate $spMethods = array();//empty\n//in constructor, or wherever you assign $this->SP\npublic function __construct(SPClass $sp)\n{\n $this->SP = $sp;\n $methods = get_class_methods($sp);\n foreach($methods as $method)\n {\n if (substr($method, 0, 5) === 'ajax_')\n {\n $this->spMethods[] = substr($method,5);\n }\n }\n}\n</code></pre>\n\n<p>Here, any method that has to be callable through an ajax request has to be given an arbitrary prefix (<code>ajax_</code> in this case). That's how you can determine what methods are valid.<Br/>\nThen, when you receive your data:</p>\n\n<pre><code>if (in_array($_POST['function'], $this->spMethods)) //valid post data\n return $this->SP->{'ajax_'.$_POST['function']}();\nelse\n</code></pre>\n\n<p>What to do in the <code>else</code> cases? the choice is yours, really: either provide a default, fallback method in <code>$this->SP</code>:</p>\n\n<pre><code>public function ajax_fallback(array $post = null)\n{\n return array('invalid/unknown request action', $post);\n}\n</code></pre>\n\n<p>throw an exception or return a <em>valid</em> json encoded string (<code>json_encode</code> should be passed at least an array, strings needn't be encoded)</p>\n\n<p>Resist the temptation to <em>guess</em> what <code>$_POST['function']</code> should've been. If its contents is invalid, that can only mean one of the following things:</p>\n\n<ul>\n<li>there's an error in either your PHP or JS code, in which case: fix it</li>\n<li>clients trying to exploit your ajax call, in which case, don't try to help them by guessing, throw an exception. Amateur hackers aren't worth the code that'll only end up making it easier for them to actually achieve something</li>\n<li>connection problems (unlikely), trying to work your way around those is pointless, so don't</li>\n</ul>\n\n<p><em>Other considerations:</em><br/>\nIf you are going to post (part of) a function name to your server, don't call that parameter <em>function</em>. Everybody knows what a function is, so it doesn't take long for some spotty teen to realize which post param is worth trying to exploit!<br/>\nSending data over ajax isn't secure anyway, I'd <em>not</em> send a function name, but given the info you've provided, I can't tell which is the better way to go. It might be worth while to hash the function names, and compare the hash value to an array of hashes. The chances someone <em>guesses</em> a hash of (part of) a function name, especially when you add salt are very low indeed:</p>\n\n<pre><code> $this->SP = $sp;\n $methods = get_class_methods($sp);\n foreach($methods as $method)\n {\n if (substr($method, 0, 5) === 'ajax_')\n {\n $this->spMethods[] = sha1(\n 'YOUR_sup3rh3r03-0F=çH01ce'.substr($method,5);\n );\n }\n }\n</code></pre>\n\n<p>and just hard-code, or send these hashes over through a predefined ajax request.<Br/>\nThose teen-would-be-hackers are easily discouraged when they realize they have to use strings like <em>\"ff45204b9bbf938f7c10a734ed4e05434203790d\"</em>, without knowing what they are :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T11:03:53.083",
"Id": "62626",
"Score": "0",
"body": "Will review this in the morning and bubble it up to the project manager - thank-you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T10:56:50.617",
"Id": "37732",
"ParentId": "37724",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37732",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T07:16:27.987",
"Id": "37724",
"Score": "4",
"Tags": [
"php",
"optimization",
"classes",
"security",
"sql-injection"
],
"Title": "Using POST data to call a function from a specified class"
}
|
37724
|
<p>I wrote these classes and I would like to know if this is a correct way. I created a new Project with Blank activity and "Scrollable Tabs + Swipe" as Navigation type.</p>
<p>My main activity:</p>
<pre><code>public class MyMainActvity extends FragmentActivity {
private static String url = "http://www.myurl.it";
static JSONObject jObj = null;
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity);
new JSONParse().execute();
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_activity, menu);
return true;
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch (position) {
case 0:
{
HomeSection homeFrag= new HomeSection();
homeFrag.newInstance(jObj);
return homeFrag;
}
case 1:
{
ServiceSection servFrag= new ServiceSection();
servFrag.newInstance(jObj);
return servFrag;
}
case 2:
{
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
case 3:
{
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
}
return null;
}
@Override
public int getCount() {
// Show 4 total pages.
return 4;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
private class JSONParse extends AsyncTask<String, String, JSONArray> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MyMainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONArray doInBackground(String... args) {
JSONParser jParser= new JSONParser();
JSONArray json =jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONArray json) {
pDialog.dismiss();
Log.d("JSONARRAY:", json.toString());
try {
JSONObject json_data = json.getJSONObject(0);
jObj= json_data;
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
catch(JSONException exception) {
Log.e("ERROR", exception.getMessage());
}
}
}
}
</code></pre>
<p>And this is one of my subclassed Fragments:</p>
<pre><code>public class HomeSection extends Fragment {
JSONObject _jObj;
public HomeSection(){}
public void newInstance(JSONObject jObj) {
Bundle args = new Bundle();
_jObj= jObj;
try{
String content= _jObj.getString("descrizione");
args.putString("description", content);
}
catch(JSONException exception){
Log.e("ERROR JSON HOME", exception.getMessage());
}
// Put any other arguments
this.setArguments(args);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(
R.layout.fragment_dummy, container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
try {
dummyTextView.setText(_jObj.getString("descrizione"));
}
catch(JSONException exception){
Log.e("ERROR JSON HOME", exception.getMessage());
}
return rootView;
}
}
</code></pre>
<p>It works, but I would like if it is a correct way to populate the views in my app. Then I didn't know if in the <code>HomeSection</code> class, the Bundle that I created in the <code>newIstance</code> method is effectively necessary because I set my text in the view within the method <code>onCreateView</code>.</p>
|
[] |
[
{
"body": "<p>I'm not too familiar with Android, so just some generic notes about the Java code:</p>\n\n<ol>\n<li><p>Instead of using magic numbers in the switch-case use named constants. It would help maintenance a lot. There is more than one switch-case with the same 0-3 case branches. A reader might wonder: are they the same? Help them!</p>\n\n<p>Might be useful here too:</p>\n\n<ul>\n<li><em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>: <em>Replacing the Conditional Logic on Price Code with Polymorphism</em></li>\n<li><a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\" rel=\"nofollow\">Replace Conditional with Polymorphism</a></li>\n</ul></li>\n<li><pre><code>@Override\npublic CharSequence getPageTitle(int position) {\n Locale l = Locale.getDefault();\n switch (position) {\n case 0:\n return getString(R.string.title_section1).toUpperCase(l);\n case 1:\n return getString(R.string.title_section2).toUpperCase(l);\n case 2:\n return getString(R.string.title_section3).toUpperCase(l);\n case 3:\n return getString(R.string.title_section4).toUpperCase(l);\n }\n return null;\n}\n</code></pre>\n\n<p>Is it considered to be an error in the program if position is not between <code>0</code> and <code>3</code>? If it is there might be no reason to continue processing with wrong state. Consider throwing an exception or logging the error. (<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><p>Some duplication could be eliminated from the switch-case above with a helper method:</p>\n\n<pre><code>@Override\npublic CharSequence getPageTitle(int position) {\n switch (position) {\n case 0:\n return getUpperCaseString(R.string.title_section1);\n case 1:\n return getUpperCaseString(R.string.title_section2);\n case 2:\n return getUpperCaseString(R.string.title_section3);\n case 3:\n return getUpperCaseString(R.string.title_section4);\n }\n return null;\n}\n\nprivate CharSequence getUpperCaseString(final String input) {\n final Locale locale = Locale.getDefault();\n return getString(input).toUpperCase(locale);\n}\n</code></pre></li>\n<li><p><code>jObj</code> should have have a more descriptive name. What's the purpose of this field? Name it accordingly.</p></li>\n<li><p>A name constant instead of <code>4</code> (<code>TOTAL_PAGES_COUNT</code>, for example) could eliminate the comment here:</p>\n\n<pre><code>@Override\npublic int getCount() {\n // Show 4 total pages.\n return 4;\n}\n</code></pre></li>\n<li><p>Field and variable naming is not consistent:</p>\n\n<pre><code>ViewPager mViewPager;\n...\nJSONObject _jObj;\n...\nJSONObject json_data = json.getJSONObject(0);\n</code></pre>\n\n<p>The <code>m</code> prefixes to access fields are not really necessary and it's just noise. Modern IDEs use highlighting to separate local variables from fields.</p>\n\n<p>Field names should not start with underscore. See <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em> and <a href=\"http://docs.oracle.com/javase/specs/\" rel=\"nofollow\">The Java Language Specification, Java SE 7 Edition, 6.1 Declarations</a>:</p>\n\n<blockquote>\n <p>Names of fields that are not final should be in mixed \n case with a lowercase first letter and the first letters of \n subsequent words capitalized.</p>\n</blockquote></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-02T20:35:26.250",
"Id": "43248",
"ParentId": "37726",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T09:54:36.237",
"Id": "37726",
"Score": "6",
"Tags": [
"java",
"android",
"json"
],
"Title": "Populate views in Android application"
}
|
37726
|
<p>I made a simple Universal-File-Duplicator (Example: make 125 duplicates of one file).
Very useful if you want to fill a whole USB flash drive or an old harddisk with an important file (Example: Bitcoin wallet.dat or privatekey) and you don't want to hit <kbd>Ctrl</kbd>+<kbd>V</kbd> all the time...</p>
<p>Suggestions? Improvements?</p>
<pre><code>#include "stdafx.h"
#include "stdio.h"
#include <stdlib.h>
#include <strstream>
#include <string>
#include <iostream>
#include <fstream>
#include <conio.h>
using namespace std;
int main(int argc, char* argv[])
{
char nummer[1000000], sourcefile[255], targetfile[255], targetfileneu[255], endung[255];
int i = 0;
int anzahl = 0;
ifstream Quelldatei;
printf("Welcome! You are using UNIVERSAL-DATEI-DUPLIKATOR v1.0\n");
printf("Filename? (Example: test.txt)\n");
gets(sourcefile);
printf("New Filename without ending? (Example: filename)\n");
gets(targetfile);
printf("Ending? (Example: .txt)\n");
gets(endung);
printf("How many times do you want to create the file?\n");
scanf("%d", &anzahl);
for (i = 0; i < anzahl; i++)
{
sprintf(nummer, "%ld", i);
strcpy(targetfileneu, targetfile);
strcat(targetfileneu, nummer);
strcat(targetfileneu, endung);
printf("Targetfilename: %s\n", targetfileneu);
Quelldatei.open(sourcefile, ios::binary);
if (!Quelldatei)
{
cerr << "ERROR!\n";
return 0;
}
ofstream Zieldatei(targetfileneu, ios::binary);
if (!Zieldatei)
{
cerr << "ERROR!\n";
return 0;
}
else
{
int c;
while ((c = Quelldatei.get()) >= 0) { Zieldatei.put(c); }
}
memset(&targetfileneu[0], 0, sizeof(targetfileneu));
Quelldatei.close();
Zieldatei.close();
}
printf("SUCCESS!\n");
system("pause");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T17:21:35.243",
"Id": "62699",
"Score": "0",
"body": "Why would you want to fill a whole harddisk with one file? If the drive crashes, it crashes. Even though this could be useful for when only some sectors of a drive goes down, making copies across multiple drives would be more reasonable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:38:20.297",
"Id": "62715",
"Score": "0",
"body": "I'm no expert but I think it's better to have the file on all platters for longterm storage (10+ years). If the one platter gets damaged (due to a magnetic field for example) the chances are higher that you can restore the file from another platter.\nI think it is even possible to restore the file if there is only a fragment of a platter intact."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T17:43:45.843",
"Id": "62912",
"Score": "0",
"body": "@Thomas: That is why RAID was invented. Reformat your drive with RAID 10 http://www.thegeekstuff.com/2010/08/raid-levels-tutorial/"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:19:16.917",
"Id": "62950",
"Score": "0",
"body": "I know, but RAID is not possible with very old and different IDE harddisks :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T19:28:44.930",
"Id": "63104",
"Score": "0",
"body": "Why write a (extremely buggy and inefficient) C++ program for something you could do with a single, short shell one-liner?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T00:49:11.467",
"Id": "63117",
"Score": "0",
"body": "Do you mean a batch-program? I don't know how to make this..\nMaybe you can post the batch-code as an alternative here?"
}
] |
[
{
"body": "<p>You've got a <code>using namespace std;</code> in your code. <a href=\"https://stackoverflow.com/questions/1265039/using-std-namespace\">Don't do that</a>. (<a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">No, really</a>).</p>\n\n<hr>\n\n<p><a href=\"https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used\"><code>gets</code> is dangerous</a>; don't use it. Streams are so much more convenient anyway! For instance, you could write:</p>\n\n<pre><code>std::string sourcefile, targetfile, endung;\nstd::cout << \"Welcome! You are using UNIVERSAL-DATEI-DUPLIKATOR v1.0\\n\"\n << \"Filename? (Example: test.txt)\\n\";\nstd::cin >> sourcefile;\nstd::cout << \"New Filename without ending? (Example: filename)\\n\";\nstd::cin >> targetfile;\nstd::cout << \"Ending? (Example: .txt)\\n\";\nstd::cin >> endung;\n\nint anzahl;\nstd::cout << \"How many times do you want to create the file?\\n\";\nstd::cin >> anzahl;\n</code></pre>\n\n<hr>\n\n<p>Opening the input file only once and resetting the stream to the beginning for each copy may allow the stream to make better use of buffering, reducing the number of seeks required.</p>\n\n<p>Also, streams can be copied directly to <code>streambuf</code>s using <code>operator>></code>.</p>\n\n<pre><code>std::ifstream Quelldatei(sourcefile, std::ios::binary);\nfor (int i = 0; i < anzahl; ++i) {\n Quelldatei.seekg(0);\n std::ostringstream output_filename(targetfile);\n output_filename << i << endung;\n std::ofstream Zieldatei(output_filename, std::ios::binary);\n Quelldatei >> Zieldatei.rdbuf();\n Zieldatei.close();\n}\nstd::cout << \"SUCCESS!\" << std::endl;\nsystem(\"pause\");\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:49:25.860",
"Id": "37773",
"ParentId": "37728",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T10:24:35.413",
"Id": "37728",
"Score": "4",
"Tags": [
"c++",
"file",
"console"
],
"Title": "Universal File Duplicator"
}
|
37728
|
<p>The task is fairly simple. I want to create a collection of intervals and implement an <code>Add</code> method which would insert new intervals to the collection and merge overlapping ones. I would also like this method to somehow tell me which parts of the added interval were not in the collection before adding.</p>
<p>Here is an interval implementation, which is pretty straightforward:</p>
<pre><code>public class Interval
{
public Interval(int start, int end)
{
Start = start;
End = end;
}
public Interval ()
{
}
public int Start { get; set; }
public int End { get; set; }
public bool Contains(int value)
{
return value <= End && value >= Start;
}
public bool Contains(Interval other)
{
return Contains(other.Start) && Contains(other.End);
}
public override string ToString()
{
return String.Format("[{0}, {1}]", Start, End);
}
public Interval Clone()
{
return new Interval(Start, End);
}
}
</code></pre>
<p>Implementing the collection proved to be a much trickier task.</p>
<pre><code>public class IntervalCollection
{
private readonly List<Interval> _intervals = new List<Interval>();
public IEnumerable<Interval> Intervals { get { return _intervals; } }
public bool TryAdd(Interval interval, out List<Interval> addedSections)
{
addedSections = null;
int indexToDelete = -1;
int countToDelete = 0;
Interval mergedInterval = null;
var i = 0;
//in this loop i am trying to locate intersections with existing intervals
for (; i < _intervals.Count; i++)
{
var current = _intervals[i];
if (current.End < interval.Start)
{
//no need to inspect this one
continue;
}
if (mergedInterval == null)
{
//start of intersection is not yet detected
if (current.Contains(interval))
{
//there is nothing to add
return false;
}
if (current.Start > interval.Start)
{
//start of added interval does not intersects with anything
mergedInterval = new Interval(interval.Start, -1);
addedSections = new List<Interval> { mergedInterval.Clone() };
indexToDelete = i;
}
else if (current.Contains(interval.Start))
{
//start of added interval intersects with one of the existing intervals
mergedInterval = new Interval(current.Start, -1);
addedSections = new List<Interval> {new Interval(current.End, -1) };
indexToDelete = i;
}
}
if (mergedInterval != null)
{
//start of intersection is detected
if (interval.Contains(current))
{
//added interval contains current interval
addedSections.Last().End = current.Start;
addedSections.Add(new Interval(current.End, -1));
continue;
}
if (current.Contains(interval.End))
{
//end of added interval intersects with one of the existing intervals
countToDelete = i - indexToDelete + 1;
addedSections.Last().End = current.Start;
mergedInterval.End = current.End;
break;
}
if (current.Start > interval.End)
{
//no need to search further
countToDelete = i - indexToDelete;
addedSections.Last().End = mergedInterval.End = interval.End;
break;
}
}
}
if (mergedInterval == null)
{
//nothing to merge and no insert is needed, adding interval to the end
_intervals.Add(interval);
addedSections = new List<Interval> { interval };
return true;
}
if (i == _intervals.Count)
{
//end of collection reached, closing open intervals
countToDelete = i - indexToDelete;
addedSections.Last().End = mergedInterval.End = interval.End;
}
//finally i am removing intervals which were merged and adding the new one instead
_intervals.RemoveRange(indexToDelete, countToDelete);
_intervals.Insert(indexToDelete, mergedInterval);
return true;
}
}
</code></pre>
<p>Now if this code was not mine, I would have a really hard time figuring out what is going on in <code>TryAdd</code>. However, it seems that I fail to come up with a more readable solution. The only one I came up with involved recreating inner collection on each add, and that I do not want to do. Can someone suggest a refactoring which will improve readability of this method? General code review is also welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:00:04.827",
"Id": "62632",
"Score": "0",
"body": "Does performance matter? In other words, is going through all intervals for each insert okay, or do you need something better than that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:53:04.660",
"Id": "62638",
"Score": "0",
"body": "@svick, Performance does matter to some extent, but i think, that iterating through collection is unavoidable either way. The only optimization i can think of is using binary search to find the range of intervals for merge straight away instead of iterating, but i think such optimization is premature. At the moment my main concern is readability."
}
] |
[
{
"body": "<p>Unless necessary you should consider making your <code>Interval</code> immutable by making the <code>set</code>s private. It's easier to deal with such \"value containers\" if they're immutable (see <code>Point</code>, <code>DateTime</code>, etc.).</p>\n\n<p>Also at the moment you can break your collection by doing the following (also it's non obvious what happens, to be honest):</p>\n\n<pre><code>List<Interval> intervals = new List<Interval>();\nIntervalCollection intervalsCollection = new IntervalCollection();\nintervalsCollection.TryAdd(new Interval(1, 5), out intervals);\nintervalsCollection.TryAdd(new Interval(20, 25), out intervals);\nintervalsCollection.TryAdd(new Interval(7, 10), out intervals);\n\nInterval intervalA = new Interval(100, 120);\nintervalsCollection.TryAdd(intervalA, out intervals)\nintervalA.Start = 7;\nintervalA.End = 50;\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code>[1, 5]\n[7, 10]\n[20, 25]\n[7, 50]\n</code></pre>\n\n<hr>\n\n<p>This class would benefit <em>a lot</em> from documentation. F.e. it is not obvious if the start or end is inclusive or exclusive. Make sure to cover this in the docs.</p>\n\n<hr>\n\n<p>Adding an <code>Intersects</code> function would also help in the long run, especially when checking in the list.</p>\n\n<pre><code>foreach (Interval interval : theIntervalsYouHave)\n{\n if (interval.Intersects(intervalToInsert))\n {\n // ...\n</code></pre>\n\n<p>An <code>Extend</code> function might also be interesting for later use, something like this:</p>\n\n<pre><code>function Interval Extend(Interval extendWith)\n{\n return new Interval(\n Math.Min(Start, extendWith.Start),\n Math.Max(End, extendWith.End));\n}\n</code></pre>\n\n<hr>\n\n<p>There's no checking if <code>Start</code> is greater then <code>End</code>, is this a valid <code>Interval</code>?</p>\n\n<pre><code>new Interval(10, 5);\n</code></pre>\n\n<hr>\n\n<pre><code>var i = 0;\n//in this loop i am trying to locate intersections with existing intervals\nfor (; i < _intervals.Count; i++)\n{\n</code></pre>\n\n<p>You did not reuse <code>i</code> for something different then the loop counter, did you? That's bad, either rename it accordingly or use a different variable for whatever you need to do outside of the loop.</p>\n\n<hr>\n\n<p>The name <code>IntervalsCollection</code> suggests that it implements <code>ICollection</code> or <code>Icollection<Interval></code> (or inherits from one of the implementing classes), yet this is not the case. Either rename the class or actually implement <code>ICollection</code>...or clearly document why this is not the case.</p>\n\n<hr>\n\n<p>If I see this correct, <code>IntervalsCollection.TryAdd()</code> does not really try to add an interval, it will add it, merge it with another or not add it.</p>\n\n<p>Without knowing your exact usage, maybe a better approach would be to provide a immutable collection which needs to be recreated every time.</p>\n\n<ol>\n<li>You make <code>Interval</code> immutable.</li>\n<li>You write an implementation of <code>ICollection<Interval></code> (called <code>Intervals</code>, there might be a better name) which is readonly.</li>\n<li>You create a static constructor/factory function <code>Merge</code> which accepts the original collection and a new value to add to it and returns a new collection. You can add overloads as you see fit (f.e. one that only accepts <code>Interval</code>s without a prior collection).</li>\n</ol>\n\n<p>That twill leave you with a very slick interface (and much less glue), which looks like this:</p>\n\n<pre><code>Intervals intervals = Intervals.Merge(intervalA, intervalB, intervalC);\nIntervals extended = Intervals.Merge(intervals, intervalD);\n</code></pre>\n\n<p>And no way to break the list.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T16:13:27.357",
"Id": "62684",
"Score": "0",
"body": "He actually does use `i` later on, but great advice to rename it. Possibly something like `intervalsChecked` based on its usage. Anyway, great answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T15:25:43.603",
"Id": "37756",
"ParentId": "37729",
"Score": "5"
}
},
{
"body": "<p>I wish I had a suggestion on how to improve your loop, but as you said, it's much trickier than you might think, and I'm probably not smart enough. ;-) </p>\n\n<p>Only suggestions I can think of here:</p>\n\n<ul>\n<li><p>Your code like <code>new Interval(current.Start, -1)</code> really bothers me. I'd suggest adding another constructor like the following since the 2nd parameter doesn't matter in each of those calls:</p>\n\n<pre><code>public Interval(int point)\n{\n Start = point;\n End = point;\n}\n</code></pre>\n\n<p>you could now call <code>new Interval(current.Start);</code> which feels cleaner to me.</p></li>\n<li><p>If you add that constructor, you can also update your other one to accept the start and end values swapped. Personally, when I think of an interval the order of the start and end doesn't matter to me. I.E. 2,4 and 4,2 are the same. Your code can't handle the latter properly. An example to correct that follows:</p>\n\n<pre><code>public Interval(int start, int end)\n{\n if (start > end) // parameters swapped\n {\n Start = end;\n End = start;\n }\n else\n {\n Start = start;\n End = end;\n }\n}\n</code></pre></li>\n<li><p>Consider changing <code>return value <= End && value >= Start;</code> to </p>\n\n<p><code>return Start <= value && value <= End;</code> for slightly improved readability. I find the 2nd format easier to quickly understand.</p></li>\n<li><p>Possibly add some sort of comment to explain that the <code>List<Interval></code> remains ordered by <code>Start</code> and <code>End</code> throughout the process. That's the one thing I figured out while reviewing it that made it much easier to understand why you did what you did, and how it worked.</p></li>\n</ul>\n\n<p>For reference, here's the code I used to find that your program doesn't handle intervals the way I would expect. Add a break point at the commented lines and inspect your locals to see what I mean:</p>\n\n<pre><code>IntervalCollection ic = new IntervalCollection();\nList<Interval> addedIntervals = null;\nic.TryAdd(new Interval(-2, -5), out addedIntervals);\nic.TryAdd(new Interval(10, 0), out addedIntervals);\nic.TryAdd(new Interval(-4, 0), out addedIntervals);\nic.TryAdd(new Interval(-10, -5), out addedIntervals); // uh oh\nic.TryAdd(new Interval(2, 2), out addedIntervals);\nic.TryAdd(new Interval(0, -10), out addedIntervals); // uh oh\nic.TryAdd(new Interval(-3, -4), out addedIntervals);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T15:43:29.287",
"Id": "37757",
"ParentId": "37729",
"Score": "4"
}
},
{
"body": "<p>Often times readability and optimization go hand in hand. Personally I like to enhance readability after I get reasonable optimization so that any further changes don't require re-enhancing the readability again. Here's some code to look at. </p>\n\n<p>When there are a lot of conditions to check I find that returning from the inner condition rather that nesting everything makes your code more stream line and in many case more readable.</p>\n\n<p>One thing to consider using the FindIndex method the list to find the insertion point of the new interval simplifies the code quite a bit.</p>\n\n<p>I added some private methods that also enhance readability by putting a logical name to blocks of code.</p>\n\n<p>I implemented an IEnumerable with indexing, not sure how proper that is but it seems to work well. Because the inner collection is a List implementing any of the List methods and/or properties should be pretty straight forward, for instance I added a Remove method.</p>\n\n<pre><code>public class Interval\n{\n public Interval(int _start, int _end)\n {\n if(!Verify(_start, _end))\n throw new ArgumentException(\"Start must be less than End\");\n start = _start;\n end = _end;\n }\n public Interval()\n {\n start = int.MinValue;\n end = int.MinValue + 2;\n }\n public Interval(Interval input)\n {\n start = input.start;\n end = input.end;\n }\n private bool Verify(int _start, int _end)\n {\n return (_start <= _end);\n }\n public int start\n {\n get;\n set;\n }\n public int end\n {\n get;\n set;\n }\n\n public void NewValues(Interval input)\n {\n start = input.start;\n end = input.end;\n }\n public override string ToString()\n {\n return String.Format(\"[{0} - {1}]\", start, end);\n }\n}\npublic class IntervalCollection : IEnumerable<Interval>\n{\n private readonly List<Interval> items = new List<Interval>();\n\n public Interval this[int index]\n {\n get\n {\n if(index < 0 || index >= items.Count())\n throw new IndexOutOfRangeException(\"Index is out of range\");\n return items[index];\n }\n set\n {\n items[index] = value;\n }\n }\n public void Remove(Interval input)\n {\n if(items.Contains(input))\n items.Remove(input);\n }\n public void AddInterval(Interval input)\n {\n //if there is an existing interval that equal the new one do nothing\n if(items.Contains(input))\n return;\n //empty collection add the new one\n if(items.Count() == 0)\n {\n items.Add(input);\n return;\n }\n //if input.Start is greater than the last interval's end, we just add it.\n if(input.start > items.Last().end)\n {\n items.Add(input);\n return;\n }\n //input.End is less than the first start insert the new interval\n if(input.end < items.First().start)\n {\n items.Insert(0, input);\n return;\n }\n //find where the new interval belongs.\n Interval lesserinterval = new Interval();\n int insertionindex = items.FindIndex(ival => input.start <= ival.start);\n //All the conditions are based on the new interval(input) and the existing interval right before where the new interval belongs in the list(lesserinterval)\n if(insertionindex == 0)\n {\n //Swap the 2 so that the interval being inserted/merged is between 2 existing intervals.\n SwapIntervals(items[0], input);\n lesserinterval = items[0];\n insertionindex++;\n }\n else\n //if FindIndex doesn't find a suitable insertion point then lesserinterval is the last one\n //otherwise lesserinterval is the one at insertionindex -1\n if(insertionindex == -1)\n {\n lesserinterval = items.Last();\n }\n else\n lesserinterval = items[insertionindex - 1];\n //At this point input.Start > lesserinterval.Start\n //If it's less than or equal to lesserinterval.End, we have overlap and we merge it to lesserinterval then see if any of the rest of the intervals need to be merged.\n if(input.start <= lesserinterval.end)\n {\n if(input.end > lesserinterval.end)\n {\n lesserinterval.end = input.end;\n MergeIntervals(lesserinterval, insertionindex);\n return ;\n }\n }\n //At this point input.Start is greater than lesserinterval.End so we insert it and check the rest of the intervals to see if any need to merge into it.\n if(insertionindex != -1)\n {\n items.Insert(insertionindex, input);\n MergeIntervals(items[insertionindex], insertionindex + 1);\n return ;\n }\n if(input.end > items.Last().end)\n {\n items.Last().end = input.end;\n return ;\n } \n }\n private void SwapIntervals(Interval a, Interval b)\n {\n Interval temp = new Interval(a);\n a.NewValues(b);\n b.NewValues(temp);\n }\n private void MergeIntervals(Interval lesser, int insertionindex)\n {\n while(lesser != items.Last())\n {\n if(lesser.end >= items[insertionindex].end)\n {\n items.RemoveAt(insertionindex);\n }\n else\n if(lesser.end >= items[insertionindex].start)\n {\n lesser.end = items[insertionindex].end;\n items.RemoveAt(insertionindex);\n return;\n }\n else\n return;\n }\n }\n public IEnumerator<Interval> GetEnumerator()\n {\n return new MyEnumerator(this);\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n // Declare the enumerator and implement the IEnumerator interface:\n public class MyEnumerator : IEnumerator<Interval>\n {\n int nIndex;\n IntervalCollection collection;\n public void Dispose()\n {\n collection = null;\n }\n public MyEnumerator(IntervalCollection coll)\n {\n collection = coll;\n nIndex = -1;\n }\n\n public void Reset()\n {\n nIndex = -1;\n }\n\n public bool MoveNext()\n {\n nIndex++;\n return (nIndex < collection.items.Count());\n }\n\n public Interval Current\n {\n get\n {\n return (collection.items[nIndex]);\n }\n }\n\n // The current property on the IEnumerator interface:\n object System.Collections.IEnumerator.Current\n {\n get\n {\n return (Current);\n }\n }\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-23T06:28:27.393",
"Id": "37938",
"ParentId": "37729",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37938",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T10:26:04.753",
"Id": "37729",
"Score": "5",
"Tags": [
"c#",
"collections",
"interval"
],
"Title": "Inserting interval into a collection"
}
|
37729
|
<p>I'm building an API wrapper for a bookkeeping SOAP API. </p>
<p>I have some questions regarding bast practice for structure of the wrapper and for error handling.</p>
<p>For now i've structured it like this:</p>
<p><em>EconClient.php</em></p>
<pre><code>class EconClient {
public function __construct()
{
$wsdlUrl = 'https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL';
$this->client = new SoapClient($wsdlUrl, array("trace" => 1, "exceptions" => 1));
}
public function connectWithToken($token, $appToken)
{
$this->client->ConnectWithToken(array('token' => $token, 'appToken' => $appToken));
}
public function debtor()
{
$this->debtor = new Debtor($this->client);
return $this->debtor;
}
public function debtorGroup()
{
$this->debtorGroup = new DebtorGroup($this->client);
return $this->debtorGroup;
}
}
</code></pre>
<p><em>Debtor.php</em></p>
<pre><code>class Debtor {
public function __construct($client)
{
$this->client = $client;
}
public function get($param, $value)
{
return $this->client->Debtor_GetData(array('entityHandle' => $this->getHandle($param, $value)))->Debtor_GetDataResult;
}
public function getHandle($param, $value)
{
switch ($param) {
case 'number':
return $this->client->Debtor_FindByNumber(array('number' => $value))->Debtor_FindByNumberResult;
break;
case 'email':
return $this->client->Debtor_FindByEmail(array('number' => $value))->Debtor_FindByEmailResult;
}
}
</code></pre>
<p>Is there any way i could structure this so i would'nt have to pass in the $client into the resource classes?</p>
<p>The only response i can get from the SOAP client except from data in case of success is exceptions. If i'm trying to fetch an ID that doesn't exist i will get an exception too. Should i try and catch these exceptions in for example Debtor.php? Or how could i structure error handling?</p>
|
[] |
[
{
"body": "<p>As for passing in <code>$client</code> in your resource class I don't see a real problem there, are there any specific reason for why you do not want to do it?</p>\n\n<p>...</p>\n\n<p>When it comes to error handling in API's there's a few things you can do that are usually API-specific.</p>\n\n<p>1) First you need to determine how the API should be used, and with that you need to determine what kind of exceptions are useful for the API consumer. There are two general guidelines that can be built upon.</p>\n\n<ul>\n<li>If there is an internal exception in the API due to it being poorly written (not saying that's the case here) then you most likely want to try/catch them and let them fail silently, or fairly silently (i.e., write the exception to <code>stderr</code>). e.g., an <code>IndexOutOfBoundsException</code> or maybe a <code>NullPointerReferenceException</code> is thrown...</li>\n<li>If an error is thrown because the API consumer are using it wrongly, or a service that the API depends on doesn't work (maybe <code>https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL</code> is down), then let them bubble up to the API consumer and let him handle the exceptions.</li>\n</ul>\n\n<p>2) Then of course there are cases which fall inbetween these two points and cases that are derivative or in the outskirts of the cases - in that case it's best if you as the API developer take stand on what to do. </p>\n\n<p>If you can't decide what to do it's often best to let the API consumer handle the exceptions instead of just failing silently.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T12:45:19.123",
"Id": "37738",
"ParentId": "37731",
"Score": "1"
}
},
{
"body": "<p>First off:</p>\n\n<blockquote>\n <p>The only response i can get from the SOAP client except from data in case of success is exceptions.</p>\n</blockquote>\n\n<p>Of course, if your call wasn't successful, there's something wrong, and an exception <em>should be thrown</em>. If you query for an ID that doesn't exist, don't catch the exception. That means the user has provided your client with invalid data, and its that user who must deal with the problem. Not You.<br/>\nAn API doesn't really deal with that many exceptions. In fact, I'm one of those people who think that a well written, bug free API-wrapper doesn't need exception handling. If the wrapper/client's code is properly put together, exceptions are the result of either bad usage or exceptions being returned by the webservice. Both types of errors should be dealt with by the user.</p>\n\n<p>If you don't want to pass the client to all those classes, the answer is simple: <strong><em>inheritance</em></strong>:</p>\n\n<pre><code>class BaseClient\n{\n protected $client = null;//declare your properties!!!\n protected $config = null;\n //use type hints, default = null means you don't HAVE to pass the argument\n public function __construct(\\SoapClient $client = null)\n {\n $this->client = $client;\n }\n //lazy-loading getter\n protected function getClient()\n {\n if ($this->client === null)\n {//set client only when it's required\n $this->setClient(\n new \\SoapClient($this->config['wsdl'], $config['options']\n );\n }\n return $this->client;\n }\n //public to allow injection\n protected function setClient(\\SoapClient $client)\n {\n $this->client = $client;\n return $this;//makes your api chainable\n }\n}\n</code></pre>\n\n<p>Then define all the classes you'll actually be using along these lines:</p>\n\n<pre><code>class DebptorClient extends BaseClient\n{\n protected $config = array(//optional\n 'wsdl' => 'the specific wsdl',\n 'options'=> array()//defaults\n );\n\n public function get($param, $value)\n {\n $client = $this->getClient();//loads if not yet loaded\n return $client->Debtor_GetData(\n array(\n 'entityHandle' => $this->getHandle($param, $value)\n )\n )->Debtor_GetDataResult;\n }\n}\n</code></pre>\n\n<p>And so on.</p>\n\n<p>Now, some actual code-review:</p>\n\n<h1>Declare your properties</h1>\n\n<p>From the <em>wrapper</em> tag wiki:</p>\n\n<blockquote>\n <p>A wrapper is an OOP technique where an object encapsulates (wraps) another object, hiding/protecting the object and controlling all access to it.</p>\n</blockquote>\n\n<p>By not declaring <code>$this->client</code>, <code>client</code> is effectively added later on in your objects life, which means <a href=\"https://stackoverflow.com/a/17696356/1230836\">property lookups will be slower</a>, but more importantly: <code>$this->client</code> will be a <strong><em>public</em></strong> property. If <code>$this->client</code> is public, then you don't have a wrapper because:</p>\n\n<blockquote>\n <p>A wrapper [...] encapsulates another object, hiding/protecting the object and controlling all access to it.</p>\n</blockquote>\n\n<p>Thus, <code>$this->client</code> <em>has</em> to be protected or private.<br/>\nNext.</p>\n\n<p>Seeing this code worries me:</p>\n\n<pre><code>public function getHandle($param, $value)\n{\n switch ($param) {\n case 'number':\n return $this->client->Debtor_FindByNumber(array('number' => $value))->Debtor_FindByNumberResult;\n break;//unreachable statement, btw\n case 'email':\n return $this->client->Debtor_FindByEmail(array('number' => $value))->Debtor_FindByEmailResult;\n}\n</code></pre>\n\n<p>You're expecting the people who are to use your api to <em>know</em> that <code>$param</code> and <code>$value</code> are expected to be. <code>$param</code> has only 2 valid options: number or email. anything else is invalid, yet at no point to you bother to <em>validate</em> the data you're being passed.<br/>\nWhen developing an API wrapper, it's not a bad idea to create <code>Argument</code> models:</p>\n\n<pre><code>namespace Soap\\Data;\nclass Argument\n{\n private $type = null;\n private $value = null;\n public function __construct($type, $value)\n {\n $setter = 'set'.ucfirst(trim($type));//email becomes setEmail\n if (!method_exists($setter, $this))\n {\n throw new \\InvalidArgumentException($type.' is not a valid type for '.__CLASS__);\n }\n $this->{$setter}($value);\n }\n public function setEmail($email)\n {\n if (!filter_var($email, \\FILTER_VALIDATE_EMAIL))\n {\n throw new \\InvalidArgumentException($email.' is not a valid email address');\n }\n $this->value = $email;\n return $this;\n }\n}\n</code></pre>\n\n<p>This allows you to define methods like this:</p>\n\n<pre><code>public function getByType(Argument $value)\n</code></pre>\n\n<p>and the <code>Argument</code> class ensures that the data you'll receive is validated properly.</p>\n\n<p>Now, error handling.<br/>\nThat very much depends on how you see your code being used. Is it supposed to be a sort of <em>\"module\"</em> to be included into various projects, in which case, I'd just throw my exceptions out for the caller to deal with them. Code that is used as a dependency shouldn't have to anticipate all sorts of errors that might occur, that's the users job.</p>\n\n<p>If you want this code to work sort of in the background, You could write your own exceptions (extending from either the base <code>Exception</code> class, or <code>SoapFault</code>) if you wanted to.<br/>\nYou could then register your own exception/error handler and unset/restore the old at lib, and quietly log the exceptions. The user, who will then be left clueless as to what actually went wrong will hate you for this. Having to check the logs constantly is a pain when developing, so add some manual overrides, too</p>\n\n<pre><code>class BaseClient\n{\n protected static $exceptions = false;\n public function __construct()\n {\n if (static::$exceptions === false)\n {//static to avoid setting handler more than once\n static::$exceptions = true;\n set_exception_handler(array($this, 'exceptionHandler'));\n }\n public function exceptionHandler(\\Exception $e)\n {\n //handle\n }\n public function freeExceptions()\n {\n if (static::$exceptions)\n {\n restore_exception_handler();\n static::$exceptions = false;\n }\n }\n public function __destruct()\n {\n $this->freeExceptions();\n }\n}\n</code></pre>\n\n<p>That's one way of going about your business. Generally, though, I use the occasional try-catch block, if I've created a method that strings together a series of Soap calls, for example, but most of the time I consider Exceptions best handled by the code that <em>invoked</em> the method where the exception is thrown, not by the code that throws the exception.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T12:49:09.517",
"Id": "63076",
"Score": "0",
"body": "Thank you for such an awesome answer! I've got a couple of things to read up on now :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T12:54:43.153",
"Id": "37741",
"ParentId": "37731",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37741",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T10:51:20.230",
"Id": "37731",
"Score": "3",
"Tags": [
"php",
"object-oriented",
"api",
"wrapper"
],
"Title": "Structure of API wrapper"
}
|
37731
|
<p>Some time ago I <a href="https://bitbucket.org/BigYellowCactus/mdclj">created a markdown parser in clojure</a> and I would like to get some feedback, since I'm a clojure noob in the first place (is the code understandable?/is it idiomatic?/can some things be improved?). </p>
<p>So I'm looking for feedback on best practices and design pattern usage (performance isn't my main concern).</p>
<p>The most relevant parts are:</p>
<p><strong><a href="https://bitbucket.org/BigYellowCactus/mdclj/src/c89b27c80e1e843aa1fd11f9daa3e91807b5548d/src/mdclj/blocks.clj?at=master">blocks.clj</a></strong></p>
<pre><code>(ns mdclj.blocks
(:use [clojure.string :only [blank? split]]
[mdclj.spans :only [parse-spans]]
[mdclj.misc]))
(defn- collect-prefixed-lines [lines prefix]
(when-let [[prefixed remaining] (partition-while #(startswith % prefix) lines)]
[(map #(to-string (drop (count prefix) %)) prefixed) remaining]))
(defn- line-seperated [lines]
(when-let [[par [r & rrest :as remaining]] (partition-while (complement blank?) lines)]
(list par rrest)))
(declare parse-blocks)
(defn- create-block-map [type content & extra]
(into {:type type :content content} extra))
(defn- clean-heading-string [line]
(-> line (to-string)
(clojure.string/trim)
(clojure.string/replace #" #*$" "") ;; match space followed by any number of #s
(clojure.string/trim)))
(defn match-heading [[head & remaining :as text]]
(let [headings (map vector (range 1 6) (iterate #(str \# %) "#")) ;; ([1 "#"] [2 "##"] [3 "###"] ...)
[size rest] (some (fn [[index pattern]]
(let [rest (startswith head pattern)]
(when (seq rest)
[index rest]))) headings)]
(when (not (nil? rest))
[(create-block-map ::heading (parse-spans (clean-heading-string rest)) {:size size}) remaining])))
(defn- match-underline-heading [[caption underline & remaining :as text]]
(let [current (set underline)
marker [\- \=]
markers (mapcat #(list #{\space %} #{%}) marker)]
(when (and (some #(= % current) markers)
(some #(startswith underline [%]) marker)
(< (count (partition-by identity underline)) 3))
[(create-block-map ::heading (parse-spans caption) remaining {:size 1}) remaining])))
(defn- match-horizontal-rule [[rule & remaining :as text]]
(let [s (set rule)
marker [\- \*]
markers (mapcat #(list #{\space %} #{%}) marker)]
(when (and (some #(= % s) markers)
(> (some #(get (frequencies rule) %) marker) 2))
[{:type ::hrule} remaining])))
(defn- match-codeblock [text]
(when-let [[code remaining] (collect-prefixed-lines text " ")]
[(create-block-map ::codeblock code) remaining]))
(defn- match-blockquote [text]
(when-let [[quote remaining] (collect-prefixed-lines text "> ")]
[(create-block-map ::blockquote (parse-blocks quote)) remaining]))
(defn- match-paragraph [text]
(when-let [[lines remaining] (line-seperated text)]
[(create-block-map ::paragraph (parse-spans (clojure.string/join "\n" lines))) remaining]))
(defn- match-empty [[head & remaining :as text]]
(when (and (blank? head) (seq remaining))
(parse-blocks remaining)))
(def ^:private block-matcher
[match-heading
match-underline-heading
match-horizontal-rule
match-codeblock
match-blockquote
match-paragraph
match-empty])
(defn- parse-blocks [lines]
(lazy-seq
(when-let [[result remaining] (some #(% lines) block-matcher)]
(cons result (parse-blocks remaining)))))
(defn parse-text [text]
(parse-blocks (seq (clojure.string/split-lines text))))
</code></pre>
<hr>
<p><strong><a href="https://bitbucket.org/BigYellowCactus/mdclj/src/c89b27c80e1e843aa1fd11f9daa3e91807b5548d/src/mdclj/spans.clj?at=master">spans.clj</a></strong></p>
<pre><code>(ns mdclj.spans
(:use [mdclj.misc]))
(def ^:private formatter
[["`" ::inlinecode]
["**" ::strong]
["__" ::strong]
["*" ::emphasis]
["_" ::emphasis]])
(defn- apply-formatter [text [pattern spantype]]
"Checks if text starts with the given pattern. If so, return the spantype, the text
enclosed in the pattern, and the remaining text"
(when-let [[body remaining] (delimited text pattern)]
[spantype body remaining]))
(defn- get-spantype [text]
(let [[spantype body remaining :as match] (some #(apply-formatter text %) formatter)]
(if (some-every-pred startswith [body remaining] ["*" "_"])
[spantype (-> body (vec) (conj (first remaining))) (rest remaining)]
match)))
(defn- make-literal [acc]
"Creates a literal span from the acc"
{:type ::literal :content (to-string (reverse acc))})
(declare parse-spans)
(defn- span-emit [literal-text span]
"Creates a vector containing a literal span created from literal-text and 'span' if literal-text, else 'span'"
(if (seq literal-text)
[(make-literal literal-text) span] ;; if non-empty literal before next span
[span]))
(defn- concat-spans [acc span remaining]
(concat (span-emit acc span) (parse-spans [] remaining)))
(defn- parse-span-body
([body]
(parse-span-body nil body))
([spantype body]
(if (in? [::inlinecode ::image] spantype)
(to-string body)
(parse-spans [] body)))) ;; all spans except inlinecode and image can be nested
(defn- match-span [acc text] ;; matches ::inlinecode ::strong ::emphasis
(when-let [[spantype body remaining :as match] (get-spantype text)] ;; get the first matching span
(let [span {:type spantype :content (parse-span-body spantype body)}]
(concat-spans acc span remaining))))
(defn- extract-link-title [text]
(reduce #(clojure.string/replace % %2 "") (to-string text) [#"\"$" #"'$" #"^\"" #"^'"]))
(defn- parse-link-text [linktext]
(let [[link title] (clojure.string/split (to-string linktext) #" " 2)]
(if (seq title)
{:url link :title (extract-link-title title)}
{:url link})))
(defn- match-link-impl [acc text type]
(when-let [[linkbody remaining :as body] (bracketed text "[" "]")]
(when-let [[linktext remaining :as link] (bracketed remaining "(" ")")]
(concat-spans acc (into {:type type :content (parse-span-body type linkbody)} (parse-link-text linktext)) remaining))))
(defn- match-link [acc text]
(match-link-impl acc text ::link))
(defn- match-inline-image [acc [exmark & remaining :as text]]
(when (= exmark \!)
(match-link-impl acc remaining ::image)))
(defn- match-break [acc text]
(when-let [remaining (some #(startswith text %) [" \n\r" " \n" " \r"])] ;; match hard-breaks
(concat-spans acc {:type ::hard-break} remaining)))
(defn- match-literal [acc [t & trest :as text]]
(cond
(seq trest)
(parse-spans (cons t acc) trest) ;; accumulate literal body (unparsed text left)
(seq text)
(list (make-literal (cons t acc))))) ;; emit literal (at end of text: no trest left)
(def ^:private span-matcher
[match-span
match-link
match-inline-image
match-break
match-literal])
(defn parse-spans
([text]
(parse-spans [] text))
([acc text]
(some #(% acc text) span-matcher)))
</code></pre>
<hr>
<p><strong><a href="https://bitbucket.org/BigYellowCactus/mdclj/src/c89b27c80e1e843aa1fd11f9daa3e91807b5548d/src/mdclj/misc.clj?at=master">misc.clj</a></strong></p>
<pre><code>(ns mdclj.misc)
(defn in?
"true if seq contains elm"
[seq elm]
(some #(= elm %) seq))
(defn startswith [coll prefix]
"Checks if coll starts with prefix.
If so, returns the rest of coll, otherwise nil"
(let [[t & trest] coll
[p & prest] prefix]
(cond
(and (= p t) ((some-fn seq) trest prest)) (recur trest prest)
(= p t) '()
(nil? prefix) coll)))
(defn partition-while
([f coll]
(partition-while f [] coll))
([f acc [head & tail :as coll]]
(cond
(f head)
(recur f (cons head acc) tail)
(seq acc)
(list (reverse acc) coll))))
(defn- bracketed-body [closing acc text]
"Searches for the sequence 'closing' in text and returns a
list containing the elements before and after it"
(let [[t & trest] text
r (startswith text closing)]
(cond
(not (nil? r)) (list (reverse acc) r)
(seq text) (recur closing (cons t acc) trest))))
(defn bracketed [coll opening closing]
"Checks if coll starts with opening and ends with closing.
If so, returns a list of the elements between 'opening' and 'closing', and the
remaining elements"
(when-let [remaining (startswith coll opening)]
(bracketed-body closing '() remaining)))
(defn delimited [coll pattern]
"Checks if coll starts with pattern and also contains pattern.
If so, returns a list of the elements between the pattern and the remaining elements"
(bracketed coll pattern pattern))
(defn to-string [coll]
"Takes a coll of chars and returns a string"
(apply str coll))
(defn some-every-pred [f ands ors]
"Builds a list of partial function predicates with function f and
all values in ands and returns if any argument in ors fullfills
all those predicates"
(let [preds (map #(partial f %) ands)]
(some true? (map #((apply every-pred preds) %) ors))))
</code></pre>
<hr>
<p>Some "highlights":</p>
<pre><code>(def ^:private block-matcher
[match-heading
match-underline-heading
match-horizontal-rule
match-codeblock
match-blockquote
match-paragraph
match-empty])
(defn- parse-blocks [lines]
(lazy-seq
(when-let [[result remaining] (some #(% lines) block-matcher)]
(cons result (parse-blocks remaining)))))
</code></pre>
<p>This piece always seemed somewhat strange to me. Is using a list of function and <code>when-let</code> idiomatic here? Are there alternatives?</p>
<pre><code>(defn- create-block-map [type content & extra]
(into {:type type :content content} extra))
</code></pre>
<p>I'm using this function to create hashmaps in a certain "format". Is this an idiomatic approach? </p>
<hr>
<p>P.S.: While looking at the code myself, I spot two minor things: I can use <code>when-not</code> instead of <code>when(not (...</code> and <code>clojure.string/join coll</code> instead of <code>(apply str coll)</code></p>
|
[] |
[
{
"body": "<p>This is overall very impressive! Here are my thoughts:</p>\n\n<p>It looks like you've pretty much written your parser \"from scratch\" -- you have it set up so that it takes text as an input and dissects it line by line, looking for blocks and spans, and labeling and converting them appropriately. This is great, but a much easier way to go about this would be to use a parsing library like <a href=\"https://github.com/Engelberg/instaparse\" rel=\"nofollow\">instaparse</a>. Using this approach, you define a simple grammar as either a string or a separate text file, and then use instaparse to turn it into a custom parser, then you just use the parser as a function on the text, returning a parse tree that contains all of the information you need, in either hiccup or enlive format. There's a little bit of a learning curve if you've never defined a grammar before, but I found it pretty easy to learn, and instaparse is one of the most intuitive parsing libraries out of the handful that I tried. I would recommend this method -- it lets you worry more about defining your grammar and leave the implementation details to instaparse. At this point you've already done most (all?) of the work manually, so you might want to stick with the structure you have in place, but you should at least consider re-doing it with a parsing library -- it would at least make it easier to add new Markdown features.</p>\n\n<p>I think your <code>block-matcher</code>/<code>parse-blocks</code> section is elegant and idiomatic as far as I'm concerned. It's a nice demonstration of first-class functions in Clojure. The only thing is, I'm not sure that you need to wrap it in a <code>lazy-seq</code>, since don't you need to realize the entire sequence? I haven't looked super thoroughly at your code, but I'm assuming you would use this function to parse <em>all</em> the lines of text from the input, so this sequence might not necessarily need to be lazy. It all depends on how you're using that function, though.</p>\n\n<p>I think your <code>create-block-map</code> function is nice and idiomatic, too. It's such a simple function that you could potentially do without it, and just have all of your <code>match-*</code> functions return something like this:</p>\n\n<pre><code>[{:type ::heading\n :content (parse-spans (clean-heading-string rest))\n :size size}\n remaining]\n</code></pre>\n\n<p>But you have so many different <code>match-*</code> functions, it would get tedious having that show up under every single one of them, so I think you did the right thing by pulling it out into a separate function, thereby enabling you to express the above as just, e.g., <code>(create-block-map ::heading (parse-spans (clean-heading-string rest)) {:size size}</code>. My only suggestion would be to consider renaming it to just <code>block-map</code> for the sake of simplicity -- that's just a minor aesthetic preference, though.</p>\n\n<p>Lastly, I saw this bit in your <code>match-heading</code> function:</p>\n\n<pre><code>(when (not (nil? rest))\n [(create-block-map ...\n</code></pre>\n\n<p>You could simplify this to just:</p>\n\n<pre><code>(when rest\n [(create-block-map ...\n</code></pre>\n\n<p>Since you're only using <code>rest</code> in a boolean context (it's either nil or it's a non-nil value) within a <code>when</code> expression, you can just use the value of <code>rest</code> itself. If it's not <code>nil</code> or <code>false</code>, the rest of the expression will be returned, otherwise <code>nil</code> will be returned. The only reason you might not want to do it this way is if you still want the rest of the <code>when</code> expression to be returned if the value of <code>rest</code> is <code>false</code> -- i.e., literally anything but <code>nil</code>. If that's not a concern, though, <code>(when rest ...</code> is more concise and idiomatic.</p>\n\n<p>Hope that helps. You're off to a great start!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T09:58:47.710",
"Id": "78713",
"Score": "0",
"body": "Thank you very much for your answer. I've written the parser from scratch just to write a parser from scratch and to write some non-trivial clojure code for learning clojure :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-21T17:36:53.820",
"Id": "44992",
"ParentId": "37736",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "44992",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T12:26:42.223",
"Id": "37736",
"Score": "10",
"Tags": [
"parsing",
"clojure",
"markdown"
],
"Title": "Idiomatic clojure code in a markdown parser"
}
|
37736
|
<p><strong>What should the code do:</strong> Process client HTML requests, query database and return the answer in XML. Working with a high load.
I need to know how can it be optimized.
Is something terribly wrong with this code?</p>
<p><strong>Input data:</strong> HTML-session, MAC-address (in form of GET argument).</p>
<p><strong>Output data:</strong> XML (<code>session_id</code>, <code>session_sign</code>).</p>
<p><strong>Servlet:</strong> </p>
<pre><code>package com.packageexample.servlet;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.apache.tomcat.jdbc.pool.PoolProperties;
/**
* Servlet implementation class TestServlet
*/
@WebServlet("/Servlet")
public class Servlet extends HttpServlet {
private static final long serialVersionUID = -3954448641206344959L;
private static final long SESSION_TIMEOUT = 360000;
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String JDBC_MYSQL_SERVER = "jdbc:mysql://192.168.0.100:3306/test?useUnicode=true&amp;characterEncoding=UTF-8";
private static final String JDBC_MYSQL_USER = "test";
private static final String JDBC_MYSQL_PASSWORD = "test";
private static DataSource datasource;
private static enum RESPONSE_STATUS {SESSION_NEW, SESSION_RESTORED, SESSION_OK, MAC_UNDEFINED, UNAUTHORIZED_ACCESS, HACK_ATTEMPT};
/**
* @see HttpServlet#HttpServlet()
*/
public Servlet() {
super();
PoolProperties p = new PoolProperties();
p.setUrl(JDBC_MYSQL_SERVER);
p.setDriverClassName(JDBC_DRIVER);
p.setUsername(JDBC_MYSQL_USER);
p.setPassword(JDBC_MYSQL_PASSWORD);
p.setJmxEnabled(true);
p.setTestWhileIdle(false);
p.setTestOnBorrow(true);
p.setValidationQuery("SELECT 1");
p.setTestOnReturn(false);
p.setValidationInterval(30000);
p.setTimeBetweenEvictionRunsMillis(30000);
p.setMaxActive(100);
p.setInitialSize(10);
p.setMaxWait(10000);
p.setRemoveAbandonedTimeout(60);
p.setMinEvictableIdleTimeMillis(30000);
p.setMinIdle(10);
p.setLogAbandoned(true);
p.setRemoveAbandoned(true);
p.setJdbcInterceptors(
"org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"
+ "org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
/*Using apache tomcat7 datasource for connection pooling
/We choose to use DBCP, because we have a high load on our project*/
datasource = new DataSource();
datasource.setPoolProperties(p);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Need to check if we've got session already
HttpSession session = request.getSession(false);
String session_id = null;
//Parse GET parameter mac from client request
String mac = request.getParameter("mac");
if (session!=null) {session_id = session.getId();}
//Firstly, we need to check whether we got some MAC-address provided at all
if (mac == null) {
makeXml (request,response,session_id, RESPONSE_STATUS.MAC_UNDEFINED);
return;
}
//Now that we need to deal with db,
ManageDatabase dbDo = new ManageDatabase();
/*Check that there's a record for this MAC in database
/If yes, return this device*/
Device device = dbDo.getDeviceByMAC (mac, datasource);
if (device==null) {
makeXml (request,response,session_id, RESPONSE_STATUS.UNAUTHORIZED_ACCESS);
return;
}
/*Now that we know for sure that we've got some valid mac-address provided,
/we need to check, if client has got some SESSION_ID*/
if (session_id == null) {
session = request.getSession();
device.setSessionId(session.getId());
dbDo.setSessionId(device, datasource);
makeXml (request,response,device.getSessionId(), RESPONSE_STATUS.SESSION_NEW);
return;
}
else {
//If session_id is not null, we need to check if it is valid for mac provided
if (!(device.getSessionId().equals(session.getId()))) {
makeXml (request,response,session_id, RESPONSE_STATUS.HACK_ATTEMPT);
return;
}
//If session_id not null and it's a valid session, then check it for timeout. Restore if needed
long sessionActiveTime = System.currentTimeMillis() - session.getLastAccessedTime();
if (sessionActiveTime > SESSION_TIMEOUT) {
makeXml (request,response,session_id, RESPONSE_STATUS.SESSION_RESTORED);
}
else{
makeXml (request,response,session_id, RESPONSE_STATUS.SESSION_OK);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void makeXml (HttpServletRequest request, HttpServletResponse response, String sid, Enum<?> res) throws ServletException, IOException {
request.setAttribute("session_id", sid);
request.setAttribute("session_sign", res);
RequestDispatcher view = request.getRequestDispatcher("Result.jsp");
view.forward(request, response);
}
}
</code></pre>
<p><strong>ManageDatabase:</strong></p>
<pre><code>package com.packageexample.servlet;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.tomcat.jdbc.pool.DataSource;
class ManageDatabase {
private static final String MYSQL_QUERY_CHECK_MAC = "SELECT * FROM device WHERE mac=?;";
private static final String MYSQL_QUERY_UPDATE_SESSION_ID = "UPDATE device set session_id=? WHERE mac=?;";
Device getDeviceByMAC(String mac, DataSource datasource) {
ResultSet rs = null;
Device device = null;
try (Connection connection = datasource.getConnection();
PreparedStatement statement = connection.prepareStatement(MYSQL_QUERY_CHECK_MAC, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);){
statement.setString(1, mac);
rs = statement.executeQuery();
while (rs.next()) {
device = new Device();
device.setMac(rs.getString("mac"));
device.setSessionId(rs.getString("session_id"));
}
}
catch (SQLException e){System.out.println(e);}
finally {
if (rs!=null)
try {rs.close();}
catch (SQLException e) {System.out.println(e);}
}
return device;
}
void setSessionId(Device device, DataSource datasource) {
try (Connection connection = datasource.getConnection();
PreparedStatement statement = connection.prepareStatement(MYSQL_QUERY_UPDATE_SESSION_ID, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);) {
statement.setString(1, device.getSessionId());
statement.setString(2, device.getMac());
statement.executeUpdate();
}
catch (SQLException e){System.out.println(e);}
}
}
</code></pre>
<p><strong>Device:</strong></p>
<pre><code>package com.packageexample.servlet;
class Device {
private String mac;
private String sessionId;
public String getMac() {
return mac;
}
public void setMac(String mac_address) {
this.mac = mac_address;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String session_id) {
this.sessionId = session_id;
}
public String toString () {
return "Device mac:" + this.mac +" ; session_id:" + this.sessionId;
}
}
</code></pre>
<p><strong>Result.jsp</strong></p>
<pre><code><%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<result>
<session_id>
<%
out.println(request.getAttribute("session_id"));
%>
</session_id>
<session_sign>
<%
out.println(request.getAttribute("session_sign"));
%>
</session_sign>
</result>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T19:25:36.103",
"Id": "67564",
"Score": "1",
"body": "Ensure that you have indexes defined on the `device` table for the `session_id` and `mac` columns."
}
] |
[
{
"body": "<p>Some minor random notes:</p>\n\n<ol>\n<li><p>Instead of commenting, like this:</p>\n\n<pre><code> //If session_id is not null, we need to check if it is valid for mac provided\n if (!(device.getSessionId().equals(session.getId()))) {\n makeXml (request,response,session_id, RESPONSE_STATUS.HACK_ATTEMPT);\n return;\n }\n</code></pre>\n\n<p>I'd use an explaining variable:</p>\n\n<pre><code>final boolean isValidMac = device.getSessionId().equals(session.getId());\nif (!isValidMac) {\n makeXml (request, response, session_id, RESPONSE_STATUS.HACK_ATTEMPT);\n return;\n}\n</code></pre>\n\n<p>This would make the comment unnecessary. References:</p>\n\n<p><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>I'd rename <code>SESSION_TIMEOUT</code> to <code>SESSION_TIMEOUT_MILLIS</code>. It would help readers, maintainers.</p></li>\n<li><p>JDBC connection details often change. A configuration file be better for them.</p></li>\n<li><p><code>session_id</code> and <code>mac_address</code> do not follow the <code>camelCase</code> convention which the other parts of the code use.</p></li>\n<li><p>Comments like this are unnecessary:</p>\n\n<pre><code> /**\n * Servlet implementation class TestServlet\n */ \n</code></pre>\n\n<p>It says nothing more than the code already does, it's rather noise. (<em>Clean Code</em> by <em>Robert C. Martin</em>: <em>Chapter 4: Comments, Noise Comments</em>)</p></li>\n<li><p>Instead of raw strings I'd consider using this:</p>\n\n<pre><code>ConnectionState.class.getCanonicalName() + \";\" + \n StatementFinalizer.class.getCanonicalName()\n</code></pre>\n\n<p>It's not a big difference but a little bit less error-prone.</p></li>\n<li><p>The <code>else</code> keyword is unnecessary here:</p>\n\n<pre><code>/*Now that we know for sure that we've got some valid mac-address provided, \n/we need to check, if client has got some SESSION_ID*/\nif (session_id == null) { \n ...\n return;\n}\nelse {\n ... // content of the else block\n} \n</code></pre>\n\n<p>It could be simply the following:</p>\n\n<pre><code>if (session_id == null) { \n ...\n return;\n}\n... // content of the (former) else block\n</code></pre></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T18:59:48.900",
"Id": "40191",
"ParentId": "37740",
"Score": "5"
}
},
{
"body": "<p>It doesn't make much sense to have a connection pool to be used by just one servlet. Usually, the connection pool is shared by the entire webapp. Furthermore, much of the setup can be accomplished by <a href=\"http://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html\" rel=\"noreferrer\">configuration</a> rather than with code. It is certainly bad practice to hard-code connection strings, especially passwords, in your code. You wouldn't want to have to recompile the application to point to a testing database or change the password. You also wouldn't want to store the code with the password in a source code control system.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T20:10:00.773",
"Id": "67574",
"Score": "1",
"body": "Agreed on hard-coded connection strings, we ought to know better since last century."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-27T19:12:40.247",
"Id": "40192",
"ParentId": "37740",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T12:51:08.037",
"Id": "37740",
"Score": "10",
"Tags": [
"java",
"mysql",
"servlets"
],
"Title": "Servlet for querying database on some high-loaded system"
}
|
37740
|
<pre><code>public class ConsoleQuery {
public static void main(String[] args) throws SQLException {
if (args.length == 0) {
System.out.println("You must specify name");
return;
}
String name = args[0];
Map < String, Object > device = getDeviceByName(name);
if (device != null) {
System.out.printf("Found device by name %s: %s",
name, device);
} else {
System.out.printf("There is no device by name %s", name);
}
}
private static Map < String, Object > getDeviceByName(String name) throws SQLException {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "test", "test");
PreparedStatement statement = connection.prepareStatement("SELECT id, mac, name FROM device");
ResultSet rs = statement.executeQuery();
List < Map < String, Object >> deviceList = new LinkedList < Map < String, Object >> ();
try {
ResultSetMetaData rsmd = rs.getMetaData();
Integer columnCount = rsmd.getColumnCount();
while (rs.next()) {
Map < String, Object > row = new LinkedHashMap < String, Object > ();
for (int i = 1; i <= columnCount; i++) {
row.put(rsmd.getColumnName(i), rs.getObject(i));
}
deviceList.add(row);
}
} finally {
rs.close();
}
for (Map < String, Object > device: deviceList) {
if (name.equals(String.valueOf(device.get("name")))) {
return device;
}
}
return null;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, the most important optimization you can make to this code is to improve your SQL query. You are currently pulling down the entire db but only care about one row; you're doing half your query on the client side. Use SQL, not Java, for selecting data from the db! Consider the following version of <code>getDeviceByName</code>:</p>\n\n<pre><code>private static Map<String, Object> getDeviceByName(String name) throws SQLException {\n DriverManager.registerDriver(new com.mysql.jbdc.Driver());\n Connection connection = DriverManager.getConnection(\n \"jdbc:mysql://127.0.0.1:3306/test\", \"test\", \"test\");\n PreparedStatement statement = connection.prepareStatement(\n \"SELECT id, mac, name FROM device WHERE name = ? LIMIT 1\");\n statement.setString(1, name);\n ResultSet rs = statement.executeQuery();\n try {\n if (!rs.next()) {\n return null;\n }\n return readRowIntoMap(rs);\n } finally {\n rs.close();\n }\n}\n\nprivate Map<String, Object> readRowIntoMap(ResultSet rs) throws SQLException {\n ResultSetMetaData metadata = rs.getMetaData();\n Map<String, Object> row = new LinkedHashMap<>();\n for (int i = 1; i <= metadata.getColumnCount(); i++) {\n row.put(metadata.getColumnName(i), rs.getObject(i));\n }\n return row;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:34:13.020",
"Id": "37752",
"ParentId": "37745",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T13:26:41.873",
"Id": "37745",
"Score": "0",
"Tags": [
"java",
"optimization"
],
"Title": "Simple command line tool to query database. Need code optimized"
}
|
37745
|
<p>I have a method which returns an Array. This array can contain values or can be empty. Here is the code:</p>
<pre><code>function getCustomerIds() {
//this declaration is at the top to inform about returning value of the method; I don't declare variables at the top
var customerIds = [];
var linkedContact = getLinkedContacts(this);
if (linkedContact === null) {
return [];
}
var linkedResource = getLinkedResources(linkedContact);
if (linkedResource === null) {
return [];
}
var linkedCustomersIds = getLinkedCustomers(linkedResource);
return customerIds.concat(linkedCustomersIds);
}
</code></pre>
<p>I'm not sure if it should be <code>return []</code> or <code>return customerIds</code>. The first one seems more explicit that the empty array is returned, while the second option seems more logical. What would be the best practice here? Do you have some other suggestions re method structure?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:43:33.070",
"Id": "62648",
"Score": "2",
"body": "Why does the `customerIds` variable exists at all?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:45:48.050",
"Id": "62649",
"Score": "0",
"body": "It's purpose is to inform about returning value of the method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:50:10.607",
"Id": "62655",
"Score": "0",
"body": "What does `getLinkedResources` and `getLinkedContacts` do? Also, I believe the last line is supposted to be `concat`, I've never heard of a `contat` function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:52:15.150",
"Id": "62657",
"Score": "0",
"body": "They return IDs of objects. At the current case assume they return only one ID. You're right about `concat` function, it's a typo"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T17:33:57.197",
"Id": "62702",
"Score": "1",
"body": "@SimonAndréForsberg There is a subtle difference between returning the result of `getLinkedCustomers()` directly and returning a copy of it. This code does the latter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-10T01:18:32.080",
"Id": "75956",
"Score": "0",
"body": "In JS, you never need to check if a value is null or undefined see my [this](http://codereview.stackexchange.com/a/43772/38328) answer"
}
] |
[
{
"body": "<p>It's debatable. Or perhaps I'd say: it's very dependent on context.</p>\n\n<p>If you return early (as you do here), I think it's probably good to return <code>[]</code>. When you read the code, you see the conditional and its effect: an empty array is returned, period. To me early returns feel a bit like throwing exceptions - not in the sense that there's an error, but just \"this is a special case; do something special and return control to the caller (i.e. exit the function)\"</p>\n\n<p>The other way to go about it is, of course, to return at the end of the function, and treat the steps before that as optional (or \"conditional\" to be exact). They <em>may</em> do something to the <code>customerIds</code> array, or they may not. Regardless, we return the array at the end, whether it's empty or not.</p>\n\n<p>(note: I'm using all these words, like \"normal\" or \"special\", <em>very</em> lightly. Don't read too much into them)</p>\n\n<p>Either way is perfectly acceptable, so it's pretty much up to you. You've got two dependent conditionals, so returning early is a good way to avoid a ton of indentation and nesting.</p>\n\n<p>However, if the return value \"changes\" when the function returns early, and you don't otherwise declare variables at the top, I'd skip declaring <code>customerIds</code> there too. If the idea is to declare the thing you'll return, but then you don't return that specific object anyway, it's misdirection. Though again, this is really on the margins of \"does it matter?\" because you're always returning an array, so it's not like the var declaration is totally false.</p>\n\n<p>But, but, in your case, the simplest solution might be to not have that declaration at all. If you expect the code to be read, and people to see the <code>return [];</code>, you can also expect them to read to the end of the function anyway, and see what it would otherwise return. No need for the return-type pseudo-declaration at all. <strike>Especially as it's not needed at all (the <code>concat</code> call is pointless).</strike> (see update below the code)</p>\n\n<pre><code>function getCustomerIds() {\n var linkedContact = getLinkedContacts(this);\n if (linkedContact === null) {\n return [];\n }\n var linkedResource = getLinkedResources(linkedContact);\n if (linkedResource === null) {\n return [];\n }\n return getLinkedCustomers(linkedResource);\n}\n</code></pre>\n\n<p><em>Update:</em> As 200_success points out in the comments, the semantics <em>do</em> change when returning without using <code>concat</code>. However, I'd probably still prefer a more direct route than declaring an empty array (that I might not use for anything), and using <code>concat</code>. I'd probably do this </p>\n\n<pre><code>return getLinkedCustomers(linkedResource).slice(0);\n</code></pre>\n\n<p>to get a copy of the array returned by <code>getLinkedCustomers()</code>. <em>End of update</em></p>\n\n<p>No declaration necessary. Your function's name (which is plural) should already be a strong enough hint that an array will get returned. Or, you know, add a comment... that's a pretty good way to deal with this too, now that I think about it.</p>\n\n<p>So basically, I think it's your custom of \"kinda' sorta'\" declaring the return type that's interfering here. Since such a declaration is not exactly binding or enforced by JS (at all), the early returns muddy the picture. </p>\n\n<p>Or (for fun) if you just want to confuse people for a moment :)</p>\n\n<pre><code>function getCustomerIds() {\n var linkedContact = getLinkedContacts(this),\n linkedResource = !linkedContact || getLinkedResources(linkedContact);\n return linkedResource ? getLinkedCustomers(linkedResource) : [];\n}\n</code></pre>\n\n<hr>\n\n<p>Update: If I'm correct in assuming that <em>all</em> the <code>getLinked...()</code> functions return similar types, then we can deduce that they all return either an array or <code>null</code>.</p>\n\n<p>If that's the case, then both my suggestion (not the joking one above, but the actual one higher up), and your code may give some unexpected results.</p>\n\n<p>The original <code>customerIds.concat(linkedCustomersIds)</code> will result in <code>[null]</code> - <em>not</em> an empty array.</p>\n\n<p>My code will either return the <code>null</code> directly, or - if you use the <code>slice</code> call - it'll just fail, as <code>null</code> doesn't have a <code>slice</code> function.</p>\n\n<p>So there should perhaps be a 3rd conditional for <code>null</code>-checking the return of <code>getLinkedCustomers(linkedResource)</code> and deciding what to return.</p>\n\n<p>But again, this is me making some straight-up guesses at how the rest of the code works. No idea if it's actually an issue.</p>\n\n<p>However, it's confusing that your variables are <em>singular</em>, but hold the return values of functions that are <em>plural</em>. Given the plural function names, I'd assume the return values are (nominally) arrays, but given the singular variables, I'd assume something else (anything else, really).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T17:35:48.640",
"Id": "62704",
"Score": "2",
"body": "Be aware, though, that returning the result of `getLinkedCustomers()` directly instead of returning a copy is semantically different from the original code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T17:44:42.453",
"Id": "62707",
"Score": "2",
"body": "@200_success True. It's an assumption on my part (I'll make that clear - thanks for pointing it out). But I'd probably go for duplicating the array from `getLinkedCustomers` rather than using `concat`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T17:29:25.320",
"Id": "37761",
"ParentId": "37750",
"Score": "13"
}
},
{
"body": "<p>While I'm fine with multiple returns for longer methods or throwing exceptions from guard clauses, I would probably rewrite the code as below. I find it easier to think of the method as \"get the customer IDs if there are any, otherwise return an empty array.\"</p>\n\n<pre><code>function getCustomerIds() {\n var contact, resource;\n return (contact = getLinkedContacts(this)) && (resource = getLinkedResources(contact))\n ? getLinkedCustomers(resource) : [];\n}\n</code></pre>\n\n<p>And I would definitely have <code>getLinkedCustomers</code> return a copy of the array of IDs rather than have callers copy it themselves.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T21:52:13.493",
"Id": "62751",
"Score": "1",
"body": "I would rather maintain the original code than this. If it wasn't for the excellent observation that `getLinkedCustomers` should provide a copy, I would -1 this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:42:39.090",
"Id": "37772",
"ParentId": "37750",
"Score": "4"
}
},
{
"body": "<h2>Re @Flambino's second suggestion</h2>\n\n<p><code>0</code> is falsy. But it is usually a valid key/index. Therefore using expressions like <code>!linkedContact</code> and <code>linkedResource ? ... : ...</code> which depend on <code>null</code> being falsy in <strong>chain lookups</strong> gets you in trouble.\nAlso note two expressions are not consistent in style. Another readability problem is multiple declarations in single statement.</p>\n\n<p>But these could be fixed as below, to yield a valid alternative:</p>\n\n<pre><code>var linkedContact = getLinkedContacts(this);\nvar linkedResource = linkedContact === null ? null : getLinkedResources(linkedContact);\nvar linkedCustomersIds = linkedResource === null ? null : getLinkedCustomers(linkedResource);\nreturn linkedCustomersId === null ? [] : linkedCustomersIds;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:15:54.780",
"Id": "62743",
"Score": "0",
"body": "I thought I made it fairly clear that that code was a joke. But your points are of course valid, just kinda meta since you're basically reviewing _my_ code and not OP's :P"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T23:43:15.857",
"Id": "62760",
"Score": "0",
"body": "@Flambino I've seen David's answer, which made the same mistake, after I posted mine and now believe more firmly that this is a useful answer. About your suggestion being a joke: humans remember patterns, and they reproduce them. You shouldn't *show* them what **not** to do. (Editing your joke would be too presumptuous.)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:53:58.683",
"Id": "37774",
"ParentId": "37750",
"Score": "2"
}
},
{
"body": "<p>You should <code>return</code> when you're ready to <code>return</code> and no later (or sooner).</p>\n\n<p>When I see a <code>return</code> statement I know immediately that the processing has finished for that logical branch. If you wait to return until the bottom of the function, then I need to do more (unnecessary) reasoning about (what will ultimately be) the return value. Does it get modified later? Does its present value trigger some other function or side-effect below? I don't know.</p>\n\n<p>Also, I agree that <code>return []</code> is more explicit and therefore preferable. Again, why make me reason unnecessarily about what's being returned there? If it can only ever be an empty array, then <em>make that obvious</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:29:14.760",
"Id": "37778",
"ParentId": "37750",
"Score": "6"
}
},
{
"body": "<p>And now for something completely different. You could completely bypass the question and simplify the API by employing two <a href=\"https://en.wikipedia.org/wiki/Null_Object_pattern\" rel=\"nofollow\">Null Objects</a>: one each for an empty set of contacts and resources.</p>\n\n<pre><code>SomeObject.prototype.getCustomerIds = function () {\n return this.getLinkedContacts().getLinkedResources().getLinkedCustomers();\n};\n\nSomeObject.prototype.getLinkedContacts = function () {\n if (this.linkedContacts.length === 0) {\n return new NoContacts();\n }\n else { ... }\n};\n\nNoContacts.prototype.getLinkedResources = function () {\n return new NoResources();\n};\n\nNoResources.prototype.getLinkedCustomers = function () {\n return [];\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-24T17:40:13.433",
"Id": "42683",
"ParentId": "37750",
"Score": "3"
}
},
{
"body": "<p>I believe that multiple returns (accompanied by proper comments, which is optional) will help you to have code with a fewer number of opening and closing brackets used. </p>\n\n<p>It happens especially when there are many condition checks or complex requirements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-04T13:08:34.660",
"Id": "56105",
"ParentId": "37750",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "37761",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T14:26:16.360",
"Id": "37750",
"Score": "16",
"Tags": [
"javascript"
],
"Title": "Multiple returns in a method or one return"
}
|
37750
|
<p>We are given a string which is compressed and we have to decompress it.</p>
<blockquote>
<p>(a(bc2)d2)$</p>
</blockquote>
<p>"$" indicates end of string.</p>
<blockquote>
<p>(abcbcd2)$</p>
<p>abcbcdabcbcd (This is the final uncompressed string.)</p>
</blockquote>
<p>My code:</p>
<pre><code>import java.util.*;
class decompress
{
public static void main(String[] ar)
{
int end = 0, st = 0;
Scanner sc = new Scanner(System.in);
System.out.print(">> ");
String s = sc.next();
while(s.indexOf('(') != -1)
{
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == '(')
st = i;
else if(c == ')')
{
end = i;
String t = s.substring(st+1,end);
int n = t.charAt(t.length()-1) - '0';
t = t.substring(0,t.length() - 1);
String q = "";
for(int j = 0; j < n; j++)
q += t;
String m = "";
if(st != 0)
m = s.substring(0,st);
s = m + q + s.substring(i+1);
break;
}
}
}
System.out.println(s);
}
}
</code></pre>
<p>Is there a more elegant way to make this program ?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:37:43.613",
"Id": "62714",
"Score": "0",
"body": "Can you explain a bit about what your code does, how it works?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:40:25.790",
"Id": "62716",
"Score": "0",
"body": "@SimonAndréForsberg My code first searches for a string between '()'. Then it replaces that string with the number of times it needs to be. Again the whole process is repeated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-20T19:09:43.343",
"Id": "62946",
"Score": "0",
"body": "http://codereview.stackexchange.com/questions/37769/compressing-a-string?noredirect=1#comment62934_37769"
}
] |
[
{
"body": "<p>Did you start out code golfing?</p>\n\n<p>Use variable names that mean something. The only variable you used that has any meaning to the reader is <code>end</code>. This means that unless you remember, every time you hit a variable you have to scroll up to find out what it is.</p>\n\n<p>This almost looks obfuscated. (It's not, but it is painful to read.) I'm not even reviewing the logic itself. You need to use meaningful variable names or no one else will ever want to touch your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:26:59.043",
"Id": "37764",
"ParentId": "37763",
"Score": "6"
}
},
{
"body": "<ol>\n<li><p>Indentation. If you are using Eclipse, please select all your code and press Ctrl + I. Your entire for-loop should be indented one step further.</p></li>\n<li><p>Use methods. One method for inputting a String, one method for making one iteration of the \"decompression\".</p></li>\n<li><p>Did you forget about how to properly use <code>indexOf</code> suddenly? You use <code>indexOf</code> as a condition for your while loop, that makes sense. But then you're using a for-loop to determine the location of the <code>(</code> and <code>)</code> characters you are going to work with. This makes no sense to me.</p></li>\n<li><p>Better variable names. Thanks to your comments on your question, I managed to figure out parts of what you are doing and write a review about that. However, Daniel still has a point that your code is not readable.</p></li>\n<li><p>Close the scanner. Your scanner is a resource that needs to be closed, call <code>sc.close();</code> as soon as you are done with the scanner (that is, after you have received all the required inputs from it)</p></li>\n<li><p>Potential problems. What if I want to encrypt the string <code>(thisWillMessWithYourCode2)</code>, how should that string be encrypted in order to be decrypted correctly? Or what would happen if I gave your program the input <code>42)invalid(data</code>? I believe your code would have a hard time with that.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:20:15.513",
"Id": "62732",
"Score": "5",
"body": "+1 for actually reviewing the code. The variables bothered me so powerfully that I felt like it warranted being an answer instead of just a comment. =)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:53:36.423",
"Id": "37768",
"ParentId": "37763",
"Score": "10"
}
},
{
"body": "<p>I have taken a while to answer this question (I started, then work got in the way...). Now that I am back to it, I see that Simon has posted a good review...</p>\n\n<p>So, part 1, a review (and then later, a suggestion):</p>\n\n<ul>\n<li>reiterating what Simon and Daniel suggest: the variable names are overly concise, and that is simply unnecessary. <code>sc</code> -> <code>scanner</code>, <code>s</code> -> <code>input</code>, <code>st</code> -> <code>start</code> ... is that too difficult? I can't even guess as to why you chose <code>q</code> though...</li>\n<li><p>Your code uses a lot of String concatenation (<code>stringval + someotherstring</code>). This is inefficient. You should have a <code>StringBuilder</code> instance declared at the beginning, and then just copy the data in to the <code>StringBuilder</code>. For example the code:</p>\n\n<pre><code>for(int j = 0; j < n; j++)\n q += t;\n</code></pre>\n\n<p>could become:</p>\n\n<pre><code>StringBuilder decompressed = new StringBuilder(); // declared somewhere at the top\n....\nfor(int j = 0; j < n; j++)\n decompressed.append(t);\n</code></pre>\n\n<p>if you use <code>decompressed.append(...)</code> then you don't need to keep 'substringing' as well.... i.e. this does not need to be in the loop at all: <code>m = s.substring(0,st);</code></p></li>\n</ul>\n\n<p>So, two major issues, variable names, and string concatenation. (in addition to what others have suggested).</p>\n\n<p>Now, for an interesting diversion, consider two alternative methods:</p>\n\n<ol>\n<li>recursion - this problem looks like recursion will be nice.</li>\n<li>consider regex - regex to find your 'tokens' will (assuming you understand the regex) make the code short (although exection may be slightly impeded).</li>\n</ol>\n\n<p>Here's a regex method (which is more concise than yours, but probably runs longer):</p>\n\n<pre><code>private static final Pattern TOKEN = Pattern.compile(\"\\\\(([^()]+?)(\\\\d)\\\\)\");\n\nprivate static String decompress(String input) {\n // check that the last character is '$'.\n if (input.isEmpty() || input.charAt(input.length() - 1) != '$') {\n return input;\n }\n input = input.substring(0, input.length() - 1);\n\n boolean matched = false;\n do {\n Matcher matcher = TOKEN.matcher(input);\n StringBuffer buffer = new StringBuffer();\n matched = false;\n while (matcher.find()) {\n matched = true;\n matcher.appendReplacement(buffer, \"\");\n for (int i = (matcher.group(2).charAt(0) - '0') - 1; i >= 0; i--) {\n buffer.append(matcher.group(1));\n }\n }\n matcher.appendTail(buffer);\n input = buffer.toString();\n } while (matched);\n return input;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:35:43.043",
"Id": "62736",
"Score": "0",
"body": "how will we implement recursion ?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:30:30.097",
"Id": "37771",
"ParentId": "37763",
"Score": "6"
}
},
{
"body": "<p>Your question says that <code>$</code> is some kind of end-of-string marker, yet you treat it just like any other character. I'm not sure why you mentioned <code>$</code> as a special case.</p>\n\n<p>When doing any non-trivial string manipulation, use a <code>StringBuilder</code> for better performance.</p>\n\n<p>Stuffing all your code into <code>main()</code> is poor programming practice. This code can easily be decomposed into a string-rewriting function and a prompt-and-display driver.</p>\n\n<p>There are several directions you could take to improve the code.</p>\n\n<ul>\n<li><p>Use <code>.lastIndexOf()</code> and <code>.indexOf()</code> to avoid iterating a character at a time.</p>\n\n<pre><code>public static String shorterDecompress(String s) {\n int openParen;\n StringBuilder sb = new StringBuilder(s);\n while ((openParen = sb.lastIndexOf(\"(\")) >= 0) {\n int closeParen = sb.indexOf(\")\", openParen);\n int n = sb.charAt(closeParen - 1) - '0';\n String inner = sb.substring(openParen + 1, closeParen - 1);\n\n StringBuilder repeated = new StringBuilder();\n while (n-- > 0) {\n repeated.append(inner);\n }\n sb.replace(openParen, closeParen + 1, repeated.toString());\n }\n return sb.toString();\n}\n</code></pre></li>\n<li><p>Use a stack to store the positions of the open parentheses so that you only have to make one pass through the string.</p>\n\n<pre><code>public static String stackDecompress(String s) {\n int[] openParens = new int[s.length() / 2];\n int nParens = -1;\n\n StringBuilder sb = new StringBuilder(s);\n for (int i = 0; i < sb.length(); i++) {\n switch (sb.charAt(i)) {\n case '(':\n openParens[++nParens] = i;\n break;\n case ')':\n int n = sb.charAt(i - 1) - '0';\n\n String inner = sb.substring(openParens[nParens] + 1, i - 1);\n StringBuilder repeated = new StringBuilder();\n while (n-- > 0) {\n repeated.append(inner);\n }\n sb.replace(openParens[nParens--], i + 1, repeated.toString());\n\n // We added repeated.length() characters, but removed (, inner, a digit, and )\n i += repeated.length() - inner.length() - 3;\n }\n }\n return sb.toString();\n}\n</code></pre></li>\n<li><p>Use a regular expression to avoid all tedious drudgery. Unlike the two ideas above and your original code, this should be more resilient to malformed input. Regular expressions also make it easy to support more than one digit for the repeat count. Besides those advantages, the code is very short.</p>\n\n<pre><code>private static final Pattern PAREN_PATTERN = Pattern.compile(\"\\\\(([^(]*?)(\\\\d*)\\\\)\");\n\npublic static String regexDecompress(String s) {\n Matcher m;\n while ((m = PAREN_PATTERN.matcher(s)).find()) {\n String inner = m.group(1);\n try {\n int n = Integer.parseInt(m.group(2));\n inner = new String(new char[n]).replace(\"\\0\", inner);\n } catch (NumberFormatException justUseOneOccurrenceThen) {\n }\n s = s.substring(0, m.start()) + inner + s.substring(m.end());\n }\n return s;\n}\n</code></pre></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T23:46:05.753",
"Id": "37788",
"ParentId": "37763",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "37768",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:20:16.197",
"Id": "37763",
"Score": "5",
"Tags": [
"java",
"strings"
],
"Title": "Decompressing a string"
}
|
37763
|
<p><a href="http://projecteuler.net/problem=11">Project Euler problem 11</a> says:</p>
<blockquote>
<p>In the 20×20 grid below, four numbers along a diagonal line have been marked in bold. [<em>red in the original</em>]</p>
<p><code>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08</code><br>
<code>49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00</code><br>
<code>81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65</code><br>
<code>52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91</code><br>
<code>22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80</code><br>
<code>24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50</code><br>
<code>32 98 81 28 64 23 67 10</code><b><code>26</code></b><code>38 40 67 59 54 70 66 18 38 64 70</code><br>
<code>67 26 20 68 02 62 12 20 95</code><b><code>63</code></b><code>94 39 63 08 40 91 66 49 94 21</code><br>
<code>24 55 58 05 66 73 99 26 97 17</code><b><code>78</code></b><code>78 96 83 14 88 34 89 63 72</code><br>
<code>21 36 23 09 75 00 76 44 20 45 35</code><b><code>14</code></b><code>00 61 33 97 34 31 33 95</code><br>
<code>78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92</code><br>
<code>16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57</code><br>
<code>86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58</code><br>
<code>19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40</code><br>
<code>04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66</code><br>
<code>88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69</code><br>
<code>04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36</code><br>
<code>20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16</code><br>
<code>20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54</code><br>
<code>01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48</code><br></p>
<p>The product of these numbers is 26 × 63 × 78 × 14 = 1788696. </p>
<p>What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?</p>
</blockquote>
<p>So, I coded this:</p>
<pre><code>grid=[8,2,22,97,38,15,0,40,0,75,4,5,7,78,52,12,50,77,91,8,
49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,4,56,62,0,
81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,3,49,13,36,65,
52,70,95,23,4,60,11,42,69,24,68,56,1,32,56,71,37,2,36,91,
22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80,
24,47,32,60,99,3,45,2,44,75,33,53,78,36,84,20,35,17,12,50,
32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70,
67,26,20,68,2,62,12,20,95,63,94,39,63,8,40,91,66,49,94,21,
24,55,58,5,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72,
21,36,23,9,75,0,76,44,20,45,35,14,0,61,33,97,34,31,33,95,
78,17,53,28,22,75,31,67,15,94,3,80,4,62,16,14,9,53,56,92,
16,39,5,42,96,35,31,47,55,58,88,24,0,17,54,24,36,29,85,57,
86,56,0,48,35,71,89,7,5,44,44,37,44,60,21,58,51,54,17,58,
19,80,81,68,5,94,47,69,28,73,92,13,86,52,17,77,4,89,55,40,
4,52,8,83,97,35,99,16,7,97,57,32,16,26,26,79,33,27,98,66,
88,36,68,87,57,62,20,72,3,46,33,67,46,55,12,32,63,93,53,69,
4,42,16,73,38,25,39,11,24,94,72,18,8,46,29,32,40,62,76,36,
20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,4,36,16,
20,73,35,29,78,31,90,1,74,31,49,71,48,86,81,16,23,57,5,54,
1,70,54,71,83,51,54,69,16,92,33,48,61,43,52,1,89,19,67,48]
largest=[0,0,0,0]
#horizontal and verticle
for h in xrange(0,20):
for hsub in xrange(0,17):
if grid[h*10+hsub]*grid[h*10+hsub+1]*grid[h*10+hsub+2]*grid[h*10+hsub+3] > largest[0]:
largest[0] = grid[h*10+hsub]*grid[h*10+hsub+1]*grid[h*10+hsub+2]*grid[h*10+hsub+3]
if grid[(hsub*20)+h]* grid[((hsub+1)*20)+h]* grid[((hsub+2)*20)+h]* grid[((hsub+3)*20)+h] > largest[1]:
largest[1] = grid[(hsub*20)+h]* grid[((hsub+1)*20)+h]* grid[((hsub+2)*20)+h]* grid[((hsub+3)*20)+h]
#diagonal right and left
for r in xrange(0,17):
for rsub in xrange (0,17):
if grid[(rsub*20)+r]* grid[((rsub+1)*20)+1+r]* grid[((rsub+2)*20)+2+r]* grid[((rsub+3)*20)+3+r] > largest[2]:
largest[2] = grid[(rsub*20)+r]* grid[((rsub+1)*20)+1+r]* grid[((rsub+2)*20)+2+r]* grid[((rsub+3)*20)+3+r]
if grid[(rsub*20)+3+r]* grid[((rsub+1)*20)+2+r]* grid[((rsub+2)*20)+1+r]* grid[((rsub+3)*20)+r] > largest[3]:
largest[3] = grid[(rsub*20)+3+r]* grid[((rsub+1)*20)+2+r]* grid[((rsub+2)*20)+1+r]* grid[((rsub+3)*20)+r]
print max(largest)
</code></pre>
<p>Even though I got the answer right, I am quite unsatisfied with my current code. I feel as though it's very very messy. I have always thought that in order to become a good programmer, one has to code in a neat and elegant manner.</p>
<p>I am a complete beginner. What should I do differently?</p>
|
[] |
[
{
"body": "<ul>\n<li><code>xrange(0, N)</code> to <code>xrange(N)</code></li>\n<li>name your loop variables something meaningful, like <code>row</code> and <code>col</code></li>\n<li>create some variables for the indices you need, e.g. <code>one_cell_up = grid[h*whatever]</code></li>\n<li>do you need a list of largest numbers, or just one largest number?</li>\n<li>what is 17 and what is 20? If you created <code>GRID_SIZE = 20</code> it'd be more obvious</li>\n<li>Might a list (rows) of lists (cols) be a more intuitive data structure?</li>\n<li>Better comments would help people understand your code, which is important. It'd take me 15, 20, who knows how many minutes to walk through this algorithm (which I'm not going to do) or 30 seconds to read some comments.</li>\n<li>anytime you repeat the same big chunk of code, <code>grid[h*10...hsub+3]</code>, just store it in a variable</li>\n<li>you might check out the <code>step</code> argument to xrange, so you can get steps of 10 instead of <code>h * 10</code> everywhere</li>\n<li>check out <a href=\"http://www.python.org/dev/peps/pep-0008/\">pep8</a></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T19:56:05.557",
"Id": "37775",
"ParentId": "37767",
"Score": "5"
}
},
{
"body": "<p>Your code would be much simpler if you'd use a list of lists for the matrix:</p>\n\n<pre><code>grid = [\n [...],\n [...],\n ...\n]\n</code></pre>\n\n<p>each row is a list itself, so to get the element at <code>(x, y)</code> we can now say <code>grid[y][x]</code>. This is massively more readable than your previous <code>grid[y*20+x]</code>.</p>\n\n<p>Your code now looks like:</p>\n\n<pre><code>#horizontal and vertical\nfor h in xrange(0,20):\n for hsub in xrange(0,17):\n if grid[h][hsub]*grid[h][hsub+1]*grid[h][hsub+2]*grid[h][hsub+3] > largest[0]:\n largest[0] = grid[h][hsub]*grid[h][hsub+1]*grid[h][hsub+2]*grid[h][hsub+3]\n if grid[hsub][h]* grid[hsub+1][h]* grid[hsub+2][h]* grid[hsub+3][h] > largest[1]:\n largest[1] = grid[hsub][h]* grid[hsub+1][h]* grid[hsub+2][h]* grid[hsub+3][h]\n\n#diagonal right and left\nfor r in xrange(0,17):\n for rsub in xrange (0,17):\n if grid[rsub][r]* grid[rsub+1][1+r]* grid[rsub+2][2+r]* grid[rsub+3][3+r] > largest[2]:\n largest[2] = grid[rsub][r]* grid[rsub+1][1+r]* grid[rsub+2][2+r]* grid[rsub+3][3+r] \n if grid[rsub][3+r]* grid[rsub+1][2+r]* grid[rsub+2][1+r]* grid[rsub+3][r] > largest[3]:\n largest[3] = grid[rsub][3+r]* grid[rsub+1][2+r]* grid[rsub+2][1+r]* grid[rsub+3][r]\n</code></pre>\n\n<p>At this step I also removed uneccessary empty lines from your code.</p>\n\n<p>We see that each expression for summing adjacent cells in a certain direction is repeated two times. We can avoid this by using a variable each time:</p>\n\n<pre><code>#horizontal and vertical\nfor h in xrange(0,20):\n for hsub in xrange(0,17):\n horizontal = grid[h][hsub] * grid[h][hsub+1] * grid[h][hsub+2] * grid[h][hsub+3]\n vertical = grid[hsub][h] * grid[hsub+1][h] * grid[hsub+2][h] * grid[hsub+3][h]\n if horizontal > largest[0]:\n largest[0] = horizontal\n if vertical > largest[1]:\n largest[1] = vertical\n\n#diagonal right and left\nfor r in xrange(0,17):\n for rsub in xrange (0,17):\n right_diagonal = grid[rsub][0+r] * grid[rsub+1][1+r] * grid[rsub+2][2+r] * grid[rsub+3][3+r]\n left_diagonal = grid[rsub][3+r] * grid[rsub+1][2+r] * grid[rsub+2][1+r] * grid[rsub+3][r]\n if right_diagonal > largest[2]:\n largest[2] = right_diagonal\n if left_diagonal > largest[3]:\n largest[3] = left_diagonal\n</code></pre>\n\n<p>This format makes it much easier to spot errors – just as I'm writing this, I see that we forgot a <code>+1</code> in the left diagonal (corrected in the previous code as well).</p>\n\n<p>All of these products look similar: We have some starting point and a direction. We then take three steps in that direction, and multiply all numbers. We could abstract this:</p>\n\n<pre><code>def product_in_direction(grid, start, direction, steps):\n x0, y0 = start\n dx, dy = direction\n product = 1\n for n in range(steps):\n product *= grid[y0 + n*dy][x0 + n*dx]\n return product\n</code></pre>\n\n<p>Now the rest of the code simplifies to:</p>\n\n<pre><code>#horizontal and vertical\nfor h in xrange(0,20):\n for hsub in xrange(0,17):\n horizontal = product_in_direction(grid, (hsub, h), (1, 0), 4)\n vertical = product_in_direction(grid, (h, hsub), (0, 1), 4)\n if horizontal > largest[0]:\n largest[0] = horizontal\n if vertical > largest[1]:\n largest[1] = vertical\n\n#diagonal right and left\nfor r in xrange(0,17):\n for rsub in xrange (0,17):\n right_diagonal = product_in_direction(grid, (rsub, r ), (1, 1), 4)\n left_diagonal = product_in_direction(grid, (rsub, r+3), (1, -1), 4)\n if right_diagonal > largest[2]:\n largest[2] = right_diagonal\n if left_diagonal > largest[3]:\n largest[3] = left_diagonal\n</code></pre>\n\n<p>As a next step, we will remove the unnecesary <code>largest</code> array: Why do we need to remember four different values when we only want the largest?</p>\n\n<pre><code>largest = 0\n\n#horizontal and vertical\nfor h in xrange(0,20):\n for hsub in xrange(0,17):\n largest = max(\n product_in_direction(grid, (hsub, h), (1, 0), 4), # horizontal\n product_in_direction(grid, (h, hsub), (0, 1), 4), # vertical\n largest,\n )\n\n#diagonal right and left\nfor r in xrange(0,17):\n for rsub in xrange (0,17):\n largest = max(\n product_in_direction(grid, (rsub, r ), (1, 1), 4), # right diagonal\n product_in_direction(grid, (rsub, r+3), (1, -1), 4), # left diagonal\n largest,\n )\n</code></pre>\n\n<p>It is annoying that we iterate over two different ranges. If we update our <code>product_in_direction</code> function to employ a range check, then we can avoid the need for that:</p>\n\n<pre><code>def product_in_direction(grid, start, direction, steps):\n x0, y0 = start\n dx, dy = direction\n\n if not(0 <= y0 < len(grid) and\n 0 <= y0 + (steps - 1)*dy < len(grid) and\n 0 <= x0 < len(grid[y0]) and\n 0 <= x0 + (steps - 1)*dx < len(grid[y0])):\n return 0\n\n product = 1\n for n in range(steps):\n product *= grid[y0 + n*dy][x0 + n*dx]\n return product\n</code></pre>\n\n<p>Now we just iterate over all indices:</p>\n\n<pre><code>#horizontal and vertical\nfor y in range(len(grid)):\n for x in range(len(grid[y])):\n largest = max(\n product_in_direction(grid, (x, y), (1, 0), 4), # horizontal\n product_in_direction(grid, (x, y), (0, 1), 4), # vertical\n product_in_direction(grid, (x, y ), (1, 1), 4), # right diagonal\n product_in_direction(grid, (x, y+3), (1, -1), 4), # left diagonal\n largest,\n )\n</code></pre>\n\n<p>Note how the variable names <code>x</code> and <code>y</code> more clearly express what they actually mean than <code>h</code> or <code>rsub</code>.</p>\n\n<p>To sum up what I did:</p>\n\n<ol>\n<li>picked appropriate data structures</li>\n<li>factored out common code, using functions if appropriate</li>\n<li>abstract details like bounds checking away</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:13:37.520",
"Id": "62742",
"Score": "0",
"body": "I was about to write all that, but I thought it would be easier to wait for you, then upvote yours instead...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T09:39:14.447",
"Id": "63059",
"Score": "1",
"body": "Nice answer. Have you thought about using numpy? It could offer some more efficient constructs/abstractions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-22T22:49:14.753",
"Id": "63110",
"Score": "0",
"body": "@Nobody good point: using numpy would hide most of the loops. OTOH I think that using explicit loops is easier to understand and to explain: OP seems fairly new to Python, so maybe it wouldn't be wise to introduce a library that changes how the language behaves."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T20:11:29.260",
"Id": "37777",
"ParentId": "37767",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "37777",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-19T18:46:37.143",
"Id": "37767",
"Score": "9",
"Tags": [
"python",
"beginner",
"project-euler"
],
"Title": "Largest product in a grid"
}
|
37767
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.